Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Remove print statement for DD currents
#include "sn_sweeper_dd.hpp" namespace mocc { namespace sn { void SnSweeper_DD::sweep( int group ) { // Store the transport cross section somewhere useful for( auto &xsr: *xs_mesh_ ) { real_t xstr = xsr.xsmactr()[group]; for( auto &ireg: xsr.reg() ) { xstr_[ireg] = xstr; } } flux_1g_ = flux_[ std::slice(n_reg_*group, n_reg_, 1) ]; // Perform inner iterations for( size_t inner=0; inner<n_inner_; inner++ ) { // Set the source (add upscatter and divide by 4PI) source_->self_scatter( group, flux_1g_, q_ ); if( inner == n_inner_-1 && coarse_data_ ) { // Wipe out the existing currents coarse_data_->current.col( group ) = 0.0; this->sweep_1g<sn::Current, CellWorker_DD>( group, cell_worker_ ); std::cout << coarse_data_->current.col( group ) << std::endl << std::endl; } else { this->sweep_1g<sn::NoCurrent, CellWorker_DD>( group, cell_worker_ ); } } flux_[ std::slice(n_reg_*group, n_reg_, 1) ] = flux_1g_; return; } } }
#include "sn_sweeper_dd.hpp" namespace mocc { namespace sn { void SnSweeper_DD::sweep( int group ) { // Store the transport cross section somewhere useful for( auto &xsr: *xs_mesh_ ) { real_t xstr = xsr.xsmactr()[group]; for( auto &ireg: xsr.reg() ) { xstr_[ireg] = xstr; } } flux_1g_ = flux_[ std::slice(n_reg_*group, n_reg_, 1) ]; // Perform inner iterations for( size_t inner=0; inner<n_inner_; inner++ ) { // Set the source (add upscatter and divide by 4PI) source_->self_scatter( group, flux_1g_, q_ ); if( inner == n_inner_-1 && coarse_data_ ) { // Wipe out the existing currents coarse_data_->current.col( group ) = 0.0; this->sweep_1g<sn::Current, CellWorker_DD>( group, cell_worker_ ); } else { this->sweep_1g<sn::NoCurrent, CellWorker_DD>( group, cell_worker_ ); } } flux_[ std::slice(n_reg_*group, n_reg_, 1) ] = flux_1g_; return; } } }
Use C.UTF-8 instead of en_US.UTF-8
// Licensed under the Apache License, Version 2.0. #include "support.h" #include <clocale> #include <cstdio> #include <cwchar> #include <sys/ioctl.h> #include <unistd.h> void setup() { setlocale(LC_ALL, "en_US.UTF-8"); } void clear_screen() { fputws(L"\033[2J\033[1;1H", stdout); } std::pair<size_t, size_t> screen_size() { winsize size; ioctl(STDOUT_FILENO, TIOCGWINSZ, &size); return {size.ws_row, size.ws_col}; }
// Licensed under the Apache License, Version 2.0. #include "support.h" #include <clocale> #include <cstdio> #include <cwchar> #include <sys/ioctl.h> #include <unistd.h> void setup() { setlocale(LC_ALL, "C.UTF-8"); } void clear_screen() { fputws(L"\033[2J\033[1;1H", stdout); } std::pair<size_t, size_t> screen_size() { winsize size; ioctl(STDOUT_FILENO, TIOCGWINSZ, &size); return {size.ws_row, size.ws_col}; }
Put the iterator construction inside the for loop
#include "partition.hpp" namespace SorterThreadedHelper { Partition::Partition(const std::set<double>::iterator pivotsBegin, const std::set<double>::iterator pivotsEnd, const std::vector<double>::iterator chunkBegin, const std::vector<double>::iterator chunkEnd) : chunkBegin_(chunkBegin), chunkEnd_(chunkEnd) { for (std::set<double>::iterator it = pivotsBegin; it != pivotsEnd; ++it) { partition_.insert(new PartitionWall(*it, false)); } partition_.insert(new PartitionWall(*pivotsBegin, true)); } Partition::~Partition() { for (std::set<PartitionWall*>::iterator it = partition_.begin(); it != partition_.end(); ++it) { delete *it; } } }
#include "partition.hpp" namespace SorterThreadedHelper { Partition::Partition(const std::set<double>::iterator pivotsBegin, const std::set<double>::iterator pivotsEnd, const std::vector<double>::iterator chunkBegin, const std::vector<double>::iterator chunkEnd) : chunkBegin_(chunkBegin), chunkEnd_(chunkEnd) { for (std::set<double>::iterator it = pivotsBegin; it != pivotsEnd; ++it) { partition_.insert(new PartitionWall(*it, false)); } partition_.insert(new PartitionWall(*pivotsBegin, true)); } Partition::~Partition() { for (std::set<PartitionWall*>::iterator it = partition_.begin(); it != partition_.end(); ++it) { delete *it; } } }
Handle -> Local for node 12 compat
#include <node.h> #include <v8.h> #ifdef _WIN32 #include "notificationstate-query.h" #endif using namespace v8; void Method(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); int returnValue = -1; #ifdef _WIN32 returnValue = queryUserNotificationState(); #endif args.GetReturnValue().Set(Int32::New(isolate, returnValue)); } void Init(Handle<Object> exports) { Isolate* isolate = Isolate::GetCurrent(); exports->Set(String::NewFromUtf8(isolate, "getNotificationState"), FunctionTemplate::New(isolate, Method)->GetFunction()); } NODE_MODULE(quiethours, Init)
#include <node.h> #include <v8.h> #ifdef _WIN32 #include "notificationstate-query.h" #endif using namespace v8; void Method(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); int returnValue = -1; #ifdef _WIN32 returnValue = queryUserNotificationState(); #endif args.GetReturnValue().Set(Int32::New(isolate, returnValue)); } void Init(Local<Object> exports) { Isolate* isolate = Isolate::GetCurrent(); exports->Set(String::NewFromUtf8(isolate, "getNotificationState"), FunctionTemplate::New(isolate, Method)->GetFunction()); } NODE_MODULE(quiethours, Init)
Fix incorrect display of note C in octaves 1-3
// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information. #include "Note.h" QString noteName(Note note) { switch (note) { case Note::C: return "do"; case Note::Cis: return "di"; case Note::D: return "re"; case Note::Ees: return "me"; case Note::E: return "mi"; case Note::F: return "fa"; case Note::Fis: return "fi"; case Note::G: return "so"; case Note::Aes: return "lu"; case Note::A: return "la"; case Note::Bes: return "se"; case Note::B: return "si"; default: break; } return "?"; } bool isFilled(Note note) { switch (note) { case Note::C: case Note::D: case Note::E: case Note::Fis: case Note::Aes: case Note::Bes: return true; default: break; } return false; } Note noteFromKey(int key) { int c4key = 60; int deltaKey = key - c4key; int note = 0; if (deltaKey >= 0) { note = deltaKey % 12; } else { note = 12 + deltaKey % 12; } //int octave = 4 + deltaKey / 12; return (Note)note; }
// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information. #include "Note.h" #include "Utils/Utils.h" QString noteName(Note note) { switch (note) { case Note::C: return "do"; case Note::Cis: return "di"; case Note::D: return "re"; case Note::Ees: return "me"; case Note::E: return "mi"; case Note::F: return "fa"; case Note::Fis: return "fi"; case Note::G: return "so"; case Note::Aes: return "lu"; case Note::A: return "la"; case Note::Bes: return "se"; case Note::B: return "si"; default: break; } return "?"; } bool isFilled(Note note) { switch (note) { case Note::C: case Note::D: case Note::E: case Note::Fis: case Note::Aes: case Note::Bes: return true; default: break; } return false; } Note noteFromKey(int key) { int c4key = 60; int deltaKey = key - c4key; int note = 0; if (deltaKey >= 0) { note = deltaKey % 12; } else { note = 12 + deltaKey % 12; note %= 12; } //int octave = 4 + deltaKey / 12; return (Note)note; }
Update identifiers to reflect consistent casing
// This is the starting point // #include <iostream> #include <fstream> #include <sstream> int main() { std::string firstInputString; std::string secondInputString; std::cout << "Enter the first string" << std::endl; std::cin >> firstInputString; std::cout << "Enter the second string" << std::endl; std::cin >> secondInputString; if (firstInputString == secondInputString) { std::cout << "Match!" << std::endl; } std::string fileName; std::cout << "Enter a filename in which to look for the string" << std::endl; std::cin >> fileName; std::ifstream fileInputStream(fileName); std::string line; if (fileInputStream.is_open()) { std::cout << "Successfully opened " << fileName << std::endl; while(true) { if (fileInputStream.fail()) { std::cout << "The file input stream went into an error state" << std::endl; break; } getline(fileInputStream, line); std::cout << line << std::endl; if (firstInputString == line) { std::cout << "Match!" << std::endl; } } } else { std::cout << "Could not open file for reading" << std::endl; } return 0; }
// This is the starting point // #include <iostream> #include <fstream> #include <sstream> int main() { std::string first_input; std::string second_input; std::cout << "Enter the first string" << std::endl; std::cin >> first_input; std::cout << "Enter the second string" << std::endl; std::cin >> second_input; if (first_input == second_input) { std::cout << "Match!" << std::endl; } std::string fileName; std::cout << "Enter a filename in which to look for the string" << std::endl; std::cin >> fileName; std::ifstream file_input_stream(fileName); std::string line; if (file_input_stream.is_open()) { std::cout << "Successfully opened " << fileName << std::endl; while(true) { if (file_input_stream.fail()) { std::cout << "The file input stream went into an error state" << std::endl; break; } getline(file_input_stream, line); std::cout << line << std::endl; if (first_input == line) { std::cout << "Match!" << std::endl; } } } else { std::cout << "Could not open file for reading" << std::endl; } return 0; }
Use recommended c++11 benchmark loop
#include <string> #include <benchmark/benchmark.h> #include "farmhash.h" static void BM_Farmhash(benchmark::State& state) { auto payload = std::string(state.range(0), '.'); while (state.KeepRunning()) util::Hash64(payload); state.SetBytesProcessed(int64_t(state.iterations()) * int64_t(state.range(0))); } // Register the function as a benchmark BENCHMARK(BM_Farmhash)->Arg(4)->Arg(11)->Arg(25)->Arg(100)->Arg(1000)->Arg(10000); BENCHMARK_MAIN();
#include <string> #include <benchmark/benchmark.h> #include "farmhash.h" static void BM_Farmhash(benchmark::State& state) { auto payload = std::string(state.range(0), '.'); for (auto _ : state) util::Hash64(payload); state.SetBytesProcessed(int64_t(state.iterations()) * int64_t(state.range(0))); } // Register the function as a benchmark BENCHMARK(BM_Farmhash)->Arg(4)->Arg(11)->Arg(25)->Arg(100)->Arg(1000)->Arg(10000); BENCHMARK_MAIN();
Make sure the app closes on error
#include "htmlsnap.h" #include <QPainter> #include <QDebug> #include <QWebFrame> #include <QTimer> #include <iostream> #include <QBuffer> HtmlSnap::HtmlSnap() { connect(&page, SIGNAL(loadFinished(bool)), this, SLOT(render())); } void HtmlSnap::loadHtml(char* html) { page.mainFrame()->setHtml(QString(html), QUrl()); } void HtmlSnap::render() { page.setViewportSize(page.mainFrame()->contentsSize()); QImage image(page.viewportSize(), QImage::Format_ARGB32); QPainter painter(&image); page.mainFrame()->render(&painter); painter.end(); QByteArray data; QBuffer buffer(&data); buffer.open(QBuffer::WriteOnly); if(!image.save(&buffer, "PNG")) { std::cerr << "could not save data to buffer"; return; } std::cout << data.toBase64().data(); QTimer::singleShot(0, this, SIGNAL(finished())); }
#include "htmlsnap.h" #include <QPainter> #include <QDebug> #include <QWebFrame> #include <QTimer> #include <iostream> #include <QBuffer> HtmlSnap::HtmlSnap() { connect(&page, SIGNAL(loadFinished(bool)), this, SLOT(render())); } void HtmlSnap::loadHtml(char* html) { page.mainFrame()->setHtml(QString(html), QUrl()); } void HtmlSnap::render() { page.setViewportSize(page.mainFrame()->contentsSize()); QImage image(page.viewportSize(), QImage::Format_ARGB32); QPainter painter(&image); page.mainFrame()->render(&painter); painter.end(); QByteArray data; QBuffer buffer(&data); buffer.open(QBuffer::WriteOnly); if(!image.save(&buffer, "PNG")) std::cerr << "could not save data to buffer"; else std::cout << data.toBase64().data(); QTimer::singleShot(0, this, SIGNAL(finished())); }
Check if tasks pool is set
#include "executor.h" #include <chrono> const std::time_t Executor::waitOnNullTask; const std::time_t Executor::waitOnEndTask; Executor::Executor(int id) : Thread(id), cLog("Executor #" + std::to_string(id)) { } Executor::~Executor() { } void Executor::SetTasksPool(TasksPool& p) { tasksPool = &p; } void Executor::Run() { Thread::Run(); D_LOG("Run"); while (!interrupted){ auto task = tasksPool->GetTask(); if (task){ // cppcheck-suppress constStatement log(logxx::notice) << "Starting task #" << task->id << logxx::endl; bool res = RunTask(task); auto &s = log(logxx::notice) << "Task #" << task->id << " "; if (res) s << "successfully done"; else s << "failed"; s << logxx::endl; std::this_thread::sleep_for(std::chrono::seconds(waitOnEndTask)); } else std::this_thread::sleep_for(std::chrono::seconds(waitOnNullTask)); } }
#include "executor.h" #include <chrono> const std::time_t Executor::waitOnNullTask; const std::time_t Executor::waitOnEndTask; Executor::Executor(int id) : Thread(id), cLog("Executor #" + std::to_string(id)) { } Executor::~Executor() { } void Executor::SetTasksPool(TasksPool& p) { tasksPool = &p; } void Executor::Run() { Thread::Run(); D_LOG("Run"); if (tasksPool){ while (!interrupted){ auto task = tasksPool->GetTask(); if (task){ // cppcheck-suppress constStatement log(logxx::notice) << "Starting task #" << task->id << logxx::endl; bool res = RunTask(task); auto &s = log(logxx::notice) << "Task #" << task->id << " "; if (res) s << "successfully done"; else s << "failed"; s << logxx::endl; std::this_thread::sleep_for(std::chrono::seconds(waitOnEndTask)); } else std::this_thread::sleep_for(std::chrono::seconds(waitOnNullTask)); } } else log(logxx::error) << "No tasks pool provided" << logxx::endl; }
Correct transaction count when reading a first line
#include "Data.hpp" #include <stdexcept> #include <string> namespace Tools { Data::BitsType getBitsFromString(const std::string& buf) { Data::BitsType bits(buf.size()); for (size_t i = 0; i < buf.size(); ++i) { if (buf[i] == '0') bits[i] = 0; else if (buf[i] == '1') bits[i] = 1; else throw std::logic_error("Wrong data"); } return bits; } } Data Data::parseUniqueDataFromStream(std::istream& stream) { std::string buf; Data data; // I. get first line if (not (stream >> buf)) throw std::logic_error("Error reading stream"); data.sizeOfDimension = buf.size(); data.numOfTransactions = 0; // increment occurrence of transaction`s elements data.data[Tools::getBitsFromString(buf)]++; // II. process rest of the file content: while (stream >> buf) { if (data.sizeOfDimension != buf.size()) throw std::logic_error("Data inconsistent"); data.data[Tools::getBitsFromString(buf)]++; data.numOfTransactions++; } return data; }
#include "Data.hpp" #include <stdexcept> #include <string> namespace Tools { Data::BitsType getBitsFromString(const std::string& buf) { Data::BitsType bits(buf.size()); for (size_t i = 0; i < buf.size(); ++i) { if (buf[i] == '0') bits[i] = 0; else if (buf[i] == '1') bits[i] = 1; else throw std::logic_error("Wrong data"); } return bits; } } Data Data::parseUniqueDataFromStream(std::istream& stream) { std::string buf; Data data; // I. get first line if (not (stream >> buf)) throw std::logic_error("Error reading stream"); data.sizeOfDimension = buf.size(); data.numOfTransactions = 0; // increment occurrence of transaction`s elements data.data[Tools::getBitsFromString(buf)]++; data.numOfTransactions++; // II. process rest of the file content: while (stream >> buf) { if (data.sizeOfDimension != buf.size()) throw std::logic_error("Data inconsistent"); data.data[Tools::getBitsFromString(buf)]++; data.numOfTransactions++; } return data; }
Mark a test as flaky on ChromeOS.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) // Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms. // See http://crbug.com/39916 for details. #define MAYBE_Infobars Infobars #else #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) #if defined (OS_WIN) #define MAYBE_Infobars Infobars #else // Flaky on ChromeOS, see http://crbug.com/40141. #define MAYBE_Infobars FLAKY_Infobars #endif #else // Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms. // See http://crbug.com/39916 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
Fix build error on Android
// Copyright 2015-2017 Directive Games Limited - All Rights Reserved #include "DriftPrivatePCH.h" #include "AndroidSecureStorage.h" #include "FileHelper.h" #if PLATFORM_ANDROID AndroidSecureStorage::AndroidSecureStorage(const FString& productName, const FString& serviceName) : productName_{ productName } , serviceName_{ serviceName } { } bool AndroidSecureStorage::SaveValue(const FString& key, const FString& value, bool overwrite) { auto fullPath = key + TEXT(".dat"); uint32 flags = overwrite ? 0 : FILEWRITE_NoReplaceExisting; return FFileHelper::SaveStringToFile(value, *fullPath, EEncodingOptions::AutoDetect, &IFileManager::Get(), flags); } bool AndroidSecureStorage::GetValue(const FString& key, FString& value) { auto fullPath = key + TEXT(".dat"); FString fileContent; if (FFileHelper::LoadFileToString(fileContent, *fullPath)) { value = fileContent; return true; } return false; } #endif // PLATFORM_ANDROID
// Copyright 2015-2017 Directive Games Limited - All Rights Reserved #include "DriftPrivatePCH.h" #include "AndroidSecureStorage.h" #include "FileHelper.h" #if PLATFORM_ANDROID AndroidSecureStorage::AndroidSecureStorage(const FString& productName, const FString& serviceName) : productName_{ productName } , serviceName_{ serviceName } { } bool AndroidSecureStorage::SaveValue(const FString& key, const FString& value, bool overwrite) { auto fullPath = key + TEXT(".dat"); uint32 flags = overwrite ? 0 : FILEWRITE_NoReplaceExisting; return FFileHelper::SaveStringToFile(value, *fullPath, FFileHelper::EEncodingOptions::AutoDetect, &IFileManager::Get(), flags); } bool AndroidSecureStorage::GetValue(const FString& key, FString& value) { auto fullPath = key + TEXT(".dat"); FString fileContent; if (FFileHelper::LoadFileToString(fileContent, *fullPath)) { value = fileContent; return true; } return false; } #endif // PLATFORM_ANDROID
Test serialization of zero too
#include <cassert> #include <cmath> #include <limits> #include <serializer.h> void test(const double in) { Serializer s; writer<decltype(+in)>::write(s, in); const auto buf = s.data(); Deserializer d(s.buffer, s.buffer.size() - buf.second); const auto out = reader<decltype(+in)>::read(d); assert(in == out || (std::isnan(in) && std::isnan(out))); } int main() { test(std::numeric_limits<double>::infinity()); test(-std::numeric_limits<double>::infinity()); test(std::numeric_limits<double>::quiet_NaN()); test(1.0); test(-1.0); test(2.0); test(-2.0); test(M_PI); test(-M_PI); test(std::numeric_limits<double>::epsilon()); test(std::numeric_limits<double>::min()); test(std::numeric_limits<double>::max()); test(std::numeric_limits<double>::denorm_min()); }
#include <cassert> #include <cmath> #include <limits> #include <serializer.h> void test(const double in) { Serializer s; writer<decltype(+in)>::write(s, in); const auto buf = s.data(); Deserializer d(s.buffer, s.buffer.size() - buf.second); const auto out = reader<decltype(+in)>::read(d); assert(in == out || (std::isnan(in) && std::isnan(out))); } int main() { test(std::numeric_limits<double>::infinity()); test(-std::numeric_limits<double>::infinity()); test(std::numeric_limits<double>::quiet_NaN()); test(0.0); test(-0.0); test(1.0); test(-1.0); test(2.0); test(-2.0); test(M_PI); test(-M_PI); test(std::numeric_limits<double>::epsilon()); test(std::numeric_limits<double>::min()); test(std::numeric_limits<double>::max()); test(std::numeric_limits<double>::denorm_min()); }
Change default config to use one thread less that CPUS available for the thread pool. Since there is a thread which calles next() it makes sense to not use all CPUs for the thread pool.
#include "queryconfig.h" #include <thread> annis::QueryConfig::QueryConfig() : optimize(true), forceFallback(false), avoidNestedBySwitch(true), numOfParallelTasks(std::thread::hardware_concurrency()) { }
#include "queryconfig.h" #include <thread> annis::QueryConfig::QueryConfig() : optimize(true), forceFallback(false), avoidNestedBySwitch(true), numOfParallelTasks(std::thread::hardware_concurrency()-1) { }
Use QML booster only when compiling to Harmattan target.
#include <QApplication> #include <QDeclarativeView> #include <QUrl> #include <MDeclarativeCache> Q_DECL_EXPORT int main(int argc, char** argv) { QApplication* app = MDeclarativeCache::qApplication(argc, argv); QDeclarativeView viewer; viewer.setSource(QUrl("qrc:/qml/main.qml")); viewer.showFullScreen(); return app->exec(); }
#include <QApplication> #include <QDeclarativeView> #include <QUrl> #include <qplatformdefs.h> #if defined(MEEGO_EDITION_HARMATTAN) #include <MDeclarativeCache> #define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y)) Q_DECL_EXPORT #else #define NEW_QAPPLICATION(x, y) new QApplication((x), (y)) #endif int main(int argc, char** argv) { QApplication* app = NEW_QAPPLICATION(argc, argv); QDeclarativeView viewer; viewer.setSource(QUrl("qrc:/qml/main.qml")); viewer.showFullScreen(); return app->exec(); }
Remove redundant inclusions from newt_test.cc
#include "gtest/gtest.h" //#include <nr.h> //#include <nrutil.h> #include "packages/transformation/src/newt2.cc" #include <irtkTransformation.h> const double EPSILON = 0.001; TEST(Packages_Transformation_newt2, irtkMultiLevelFreeFormTransformation_Inverse) { irtkCifstream iStream; iStream.Open("/vol/medic02/users/sp2010/PhD/Tumor/dofs/gradientnreg2-NGP-HG01.dof.gz"); irtkMultiLevelFreeFormTransformation transformation; transformation.Read(iStream); double x = 10, y = 10, z = 10; transformation.Inverse(x, y, z); ASSERT_NEAR(1.16573, x, EPSILON); ASSERT_NEAR(23.9054, y, EPSILON); ASSERT_NEAR(-17.255, z, EPSILON); }
#include "gtest/gtest.h" #include <irtkTransformation.h> const double EPSILON = 0.001; TEST(Packages_Transformation_newt2, irtkMultiLevelFreeFormTransformation_Inverse) { irtkCifstream iStream; iStream.Open("/vol/medic02/users/sp2010/PhD/Tumor/dofs/gradientnreg2-NGP-HG01.dof.gz"); irtkMultiLevelFreeFormTransformation transformation; transformation.Read(iStream); double x = 10, y = 10, z = 10; transformation.Inverse(x, y, z); ASSERT_NEAR(1.16573, x, EPSILON); ASSERT_NEAR(23.9054, y, EPSILON); ASSERT_NEAR(-17.255, z, EPSILON); }
Add screen_witdh, height. Change window_height, width base function.
#include "rubybasic/BindApplication.hpp" #include "mruby.h" #include "mrubybind.h" #include "ofAppRunner.h" namespace { static float get_frame_rate() { return ofGetFrameRate(); } static void set_window_pos(int x, int y) { ofSetWindowPosition(x, y); } static void set_window_size(int width, int height) { ofSetWindowShape(width, height); } static int window_pos_x() { return ofGetWindowPositionX(); } static int window_pos_y() { return ofGetWindowPositionY(); } static int window_width() { return ofGetWidth(); } static int window_height() { return ofGetHeight(); } } //-------------------------------------------------------------------------------- void BindApplication::Bind(mrb_state* mrb) { mrubybind::MrubyBind b(mrb); b.bind("get_frame_rate", get_frame_rate); b.bind("set_window_pos", set_window_pos); b.bind("set_window_size", set_window_size); b.bind("window_pos_x", window_pos_x); b.bind("window_pos_y", window_pos_y); b.bind("window_width", window_width); b.bind("window_height", window_height); } //EOF
#include "rubybasic/BindApplication.hpp" #include "mruby.h" #include "mrubybind.h" #include "ofAppRunner.h" namespace { static float get_frame_rate() { return ofGetFrameRate(); } static void set_window_pos(int x, int y) { ofSetWindowPosition(x, y); } static void set_window_size(int width, int height) { ofSetWindowShape(width, height); } static int window_pos_x() { return ofGetWindowPositionX(); } static int window_pos_y() { return ofGetWindowPositionY(); } // static int window_width() { return ofGetWidth(); } // static int window_height() { return ofGetHeight(); } static int window_width() { return ofGetWindowWidth(); } static int window_height() { return ofGetWindowHeight(); } static int screen_width() { return ofGetScreenWidth(); } static int screen_height() { return ofGetScreenHeight(); } } //-------------------------------------------------------------------------------- void BindApplication::Bind(mrb_state* mrb) { mrubybind::MrubyBind b(mrb); b.bind("get_frame_rate", get_frame_rate); b.bind("set_window_pos", set_window_pos); b.bind("set_window_size", set_window_size); b.bind("window_pos_x", window_pos_x); b.bind("window_pos_y", window_pos_y); b.bind("window_width", window_width); b.bind("window_height", window_height); b.bind("screen_width", screen_width); b.bind("screen_height", screen_height); } //EOF
Add some explicit anchoring tests.
MATCH_TEST("x", UNANCHORED, "x"); MATCH_TEST("x", UNANCHORED, "xyz"); MATCH_TEST("x", UNANCHORED, "uvwx"); MATCH_TEST("x", UNANCHORED, "uvwxyz"); MATCH_TEST("x", ANCHOR_START, "x"); MATCH_TEST("x", ANCHOR_START, "xyz"); MATCH_TEST("x", ANCHOR_START, "uvwx"); MATCH_TEST("x", ANCHOR_START, "uvwxyz"); MATCH_TEST("x", ANCHOR_BOTH, "x"); MATCH_TEST("x", ANCHOR_BOTH, "xyz"); MATCH_TEST("x", ANCHOR_BOTH, "uvwx"); MATCH_TEST("x", ANCHOR_BOTH, "uvwxyz");
MATCH_TEST("x", UNANCHORED, "x"); MATCH_TEST("x", UNANCHORED, "xyz"); MATCH_TEST("x", UNANCHORED, "uvwx"); MATCH_TEST("x", UNANCHORED, "uvwxyz"); MATCH_TEST("x", ANCHOR_START, "x"); MATCH_TEST("x", ANCHOR_START, "xyz"); MATCH_TEST("x", ANCHOR_START, "uvwx"); MATCH_TEST("x", ANCHOR_START, "uvwxyz"); MATCH_TEST("x", ANCHOR_BOTH, "x"); MATCH_TEST("x", ANCHOR_BOTH, "xyz"); MATCH_TEST("x", ANCHOR_BOTH, "uvwx"); MATCH_TEST("x", ANCHOR_BOTH, "uvwxyz"); MATCH_TEST("^x", UNANCHORED, "x"); MATCH_TEST("^x", UNANCHORED, "xyz"); MATCH_TEST("^x", UNANCHORED, "uvwx"); MATCH_TEST("^x", UNANCHORED, "uvwxyz"); MATCH_TEST("x$", UNANCHORED, "x"); MATCH_TEST("x$", UNANCHORED, "xyz"); MATCH_TEST("x$", UNANCHORED, "uvwx"); MATCH_TEST("x$", UNANCHORED, "uvwxyz"); MATCH_TEST("^x$", UNANCHORED, "x"); MATCH_TEST("^x$", UNANCHORED, "xyz"); MATCH_TEST("^x$", UNANCHORED, "uvwx"); MATCH_TEST("^x$", UNANCHORED, "uvwxyz");
Fix unit test in NDEBUG build
//===- llvm/unittest/Support/DebugTest.cpp --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <string> using namespace llvm; TEST(DebugTest, Basic) { std::string s1, s2; raw_string_ostream os1(s1), os2(s2); static const char *DT[] = {"A", "B"}; llvm::DebugFlag = true; setCurrentDebugTypes(DT, 2); DEBUG_WITH_TYPE("A", os1 << "A"); DEBUG_WITH_TYPE("B", os1 << "B"); EXPECT_EQ("AB", os1.str()); setCurrentDebugType("A"); DEBUG_WITH_TYPE("A", os2 << "A"); DEBUG_WITH_TYPE("B", os2 << "B"); EXPECT_EQ("A", os2.str()); }
//===- llvm/unittest/Support/DebugTest.cpp --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <string> using namespace llvm; #ifndef NDEBUG TEST(DebugTest, Basic) { std::string s1, s2; raw_string_ostream os1(s1), os2(s2); static const char *DT[] = {"A", "B"}; llvm::DebugFlag = true; setCurrentDebugTypes(DT, 2); DEBUG_WITH_TYPE("A", os1 << "A"); DEBUG_WITH_TYPE("B", os1 << "B"); EXPECT_EQ("AB", os1.str()); setCurrentDebugType("A"); DEBUG_WITH_TYPE("A", os2 << "A"); DEBUG_WITH_TYPE("B", os2 << "B"); EXPECT_EQ("A", os2.str()); } #endif
Revert r341387. (Calling abort() from lldb_assert()).
//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Utility/LLDBAssert.h" #include "llvm/Support/Format.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace lldb_private; void lldb_private::lldb_assert(bool expression, const char *expr_text, const char *func, const char *file, unsigned int line) { if (LLVM_LIKELY(expression)) return; errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n", expr_text, func, file, line); errs() << "backtrace leading to the failure:\n"; llvm::sys::PrintStackTrace(errs()); errs() << "please file a bug report against lldb reporting this failure " "log, and as many details as possible\n"; abort(); }
//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Utility/LLDBAssert.h" #include "llvm/Support/Format.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace lldb_private; void lldb_private::lldb_assert(bool expression, const char *expr_text, const char *func, const char *file, unsigned int line) { if (LLVM_LIKELY(expression)) return; errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n", expr_text, func, file, line); errs() << "backtrace leading to the failure:\n"; llvm::sys::PrintStackTrace(errs()); errs() << "please file a bug report against lldb reporting this failure " "log, and as many details as possible\n"; }
Comment out testing procedure for now because it doesn't work (yet).
/** * @file nmf_test.cpp * @author Mohan Rajendran * * Test file for NMF class. */ #include <mlpack/core.hpp> #include <mlpack/methods/nmf/nmf.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" BOOST_AUTO_TEST_SUITE(NMFTest); using namespace std; using namespace arma; using namespace mlpack; using namespace mlpack::nmf; /** * Check the if the product of the calculated factorization is close to the * input matrix. */ BOOST_AUTO_TEST_CASE(NMFTest) { mat v = randu<mat>(5, 5); size_t r = 4; mat w, h; NMF<> nmf(0); nmf.Apply(v, w, h, r); mat wh = w * h; v.print("v"); wh.print("wh"); for (size_t row = 0; row < 5; row++) for (size_t col = 0; col < 5; col++) BOOST_REQUIRE_CLOSE(v(row, col), wh(row, col), 5.0); } BOOST_AUTO_TEST_SUITE_END();
/** * @file nmf_test.cpp * @author Mohan Rajendran * * Test file for NMF class. */ #include <mlpack/core.hpp> #include <mlpack/methods/nmf/nmf.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" BOOST_AUTO_TEST_SUITE(NMFTest); using namespace std; using namespace arma; using namespace mlpack; using namespace mlpack::nmf; /** * Check the if the product of the calculated factorization is close to the * input matrix. */ BOOST_AUTO_TEST_CASE(NMFTest) { mat v = randu<mat>(5, 5); size_t r = 4; mat w, h; NMF<> nmf(0); nmf.Apply(v, w, h, r); mat wh = w * h; v.print("v"); wh.print("wh"); // for (size_t row = 0; row < 5; row++) // for (size_t col = 0; col < 5; col++) // BOOST_REQUIRE_CLOSE(v(row, col), wh(row, col), 5.0); } BOOST_AUTO_TEST_SUITE_END();
Fix undefined set_stacktrace symbol by adding missing header in source
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <common/err_common.hpp> #include <af/device.h> #include <af/exception.h> #include <algorithm> #include <string> void af_get_last_error(char **str, dim_t *len) { std::string &global_error_string = get_global_error_string(); dim_t slen = std::min(MAX_ERR_SIZE, static_cast<int>(global_error_string.size())); if (len && slen == 0) { *len = 0; *str = NULL; return; } af_alloc_host(reinterpret_cast<void **>(str), sizeof(char) * (slen + 1)); global_error_string.copy(*str, slen); (*str)[slen] = '\0'; global_error_string = std::string(""); if (len) { *len = slen; } } af_err af_set_enable_stacktrace(int is_enabled) { common::is_stacktrace_enabled() = is_enabled; return AF_SUCCESS; }
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <common/err_common.hpp> #include <af/device.h> #include <af/exception.h> #include <af/util.h> #include <algorithm> #include <string> void af_get_last_error(char **str, dim_t *len) { std::string &global_error_string = get_global_error_string(); dim_t slen = std::min(MAX_ERR_SIZE, static_cast<int>(global_error_string.size())); if (len && slen == 0) { *len = 0; *str = NULL; return; } af_alloc_host(reinterpret_cast<void **>(str), sizeof(char) * (slen + 1)); global_error_string.copy(*str, slen); (*str)[slen] = '\0'; global_error_string = std::string(""); if (len) { *len = slen; } } af_err af_set_enable_stacktrace(int is_enabled) { common::is_stacktrace_enabled() = is_enabled; return AF_SUCCESS; }
Resolve C standard library functions in std::
#include <iostream> #include <cstdlib> #include <Eigen/Dense> #include "problem.hpp" using namespace integrator_chains; int main() { Eigen::Vector2i numdim_output_bounds( 2, 2 ); Eigen::Vector2i num_integrators_bounds( 2, 2 ); Eigen::Vector4d Y_box; Y_box << -1, 10, -2, 10; Eigen::Vector4d U_box; U_box << -1, 1, -1, 1; Eigen::Vector2d period_bounds( 0.05, 0.1 ); Eigen::Vector2i number_goals_bounds( 1, 2 ); Eigen::Vector2i number_obstacles_bounds( 0, 1 ); srand(time(0)); Problem *prob = Problem::random( numdim_output_bounds, num_integrators_bounds, Y_box, U_box, number_goals_bounds, number_obstacles_bounds, period_bounds ); std::cout << *prob << std::endl; prob->to_formula( std::cerr ); std::cerr << std::endl; delete prob; return 0; }
#include <iostream> #include <cstdlib> #include <ctime> #include <Eigen/Dense> #include "problem.hpp" using namespace integrator_chains; int main() { Eigen::Vector2i numdim_output_bounds( 2, 2 ); Eigen::Vector2i num_integrators_bounds( 2, 2 ); Eigen::Vector4d Y_box; Y_box << -1, 10, -2, 10; Eigen::Vector4d U_box; U_box << -1, 1, -1, 1; Eigen::Vector2d period_bounds( 0.05, 0.1 ); Eigen::Vector2i number_goals_bounds( 1, 2 ); Eigen::Vector2i number_obstacles_bounds( 0, 1 ); std::srand( std::time( 0 ) ); Problem *prob = Problem::random( numdim_output_bounds, num_integrators_bounds, Y_box, U_box, number_goals_bounds, number_obstacles_bounds, period_bounds ); std::cout << *prob << std::endl; prob->to_formula( std::cerr ); std::cerr << std::endl; delete prob; return 0; }
Add conversion method for ArticleCollection
#include "ToJsonWriter.h" #include <json/json.h> std::string ToJsonWriter::convertToJson(const Article* a) { Json::Value val; Json::Value array(Json::ValueType::arrayValue); for(auto ali = a->linkBegin(); ali != a->linkEnd(); ali++) { std::string tit = (*ali)->getTitle(); array.append(Json::Value(tit)); } val[a->getTitle()] = array; Json::FastWriter jsw; jsw.omitEndingLineFeed(); return jsw.write(val); } std::string ToJsonWriter::convertToJson(const ArticleCollection&) { return ""; } void ToJsonWriter::output(const Article* article, std::ostream& outstream) { outstream << convertToJson(article); } void ToJsonWriter::output(const ArticleCollection& collection, std::ostream& outstream) { outstream << convertToJson(collection); }
#include "ToJsonWriter.h" #include <json/json.h> Json::Value getArticleLinks(const Article* a) { Json::Value array(Json::ValueType::arrayValue); for(auto ali = a->linkBegin(); ali != a->linkEnd(); ali++) { std::string tit = (*ali)->getTitle(); array.append(Json::Value(tit)); } return array; } std::string ToJsonWriter::convertToJson(const Article* a) { Json::Value val; val[a->getTitle()] = getArticleLinks(a); Json::FastWriter jsw; jsw.omitEndingLineFeed(); return jsw.write(val); } std::string ToJsonWriter::convertToJson(const ArticleCollection& ac) { Json::Value val(Json::ValueType::objectValue); for(auto ar : ac) { val[ar.first] = getArticleLinks(ar.second); } Json::FastWriter jsw; jsw.omitEndingLineFeed(); return jsw.write(val); } void ToJsonWriter::output(const Article* article, std::ostream& outstream) { outstream << convertToJson(article); } void ToJsonWriter::output(const ArticleCollection& collection, std::ostream& outstream) { outstream << convertToJson(collection); }
Add simple help to the CLI client.
// Copyright (C) 2012, All Rights Reserved. // Author: Cory Maccarrone <darkstar6262@gmail.com> #include "client/ui/cli/cli_client.h" #include "gflags/gflags.h" #include "glog/logging.h" using backup::CliMain; int main(int argc, char* argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); CHECK_LT(1, argc) << "Must specify a command"; // Construct the command handler. CliMain cli(argc, argv); if (!cli.Init()) { LOG(FATAL) << "Error initializing backend"; } return cli.RunCommand(); }
// Copyright (C) 2012, All Rights Reserved. // Author: Cory Maccarrone <darkstar6262@gmail.com> #include "client/ui/cli/cli_client.h" #include "gflags/gflags.h" #include "glog/logging.h" using backup::CliMain; int main(int argc, char* argv[]) { google::SetUsageMessage( "Usage: cli_client <options> <command>\n\n" "Commands:\n" " list_backup_sets\n" " List the available backup sets.\n\n" " create_backup_set <backup set name>\n" " Create a backup set with the given name.\n\n" " create_incremental_backup <backup set> <backup name> <size_in_mb>\n" " Create an incremental backup in the given backup set with at most\n" " <size_in_mb> megabytes."); google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); CHECK_LT(1, argc) << "Must specify a command"; // Construct the command handler. CliMain cli(argc, argv); if (!cli.Init()) { LOG(FATAL) << "Error initializing backend"; } return cli.RunCommand(); }
Remove debug and unused headers
#include <fstream> #include <iostream> #include <utility> #include <map> #include <set> #include <queue> #include <bitset> using namespace std; int main() { ifstream fin("highcard.in"); ofstream fout("highcard.out"); int num_sing_cards; fin >> num_sing_cards; bitset<100000> cards; for (int i = 0; i < num_sing_cards; i++) { int card; fin >> card; cards[card - 1] = true; cout << "? " << card << endl; } int elsie = 0, score = 0; for (int i = 0; i < 2 * num_sing_cards; i++) { cout << "C " << i << ' ' << cards[i] << endl; if (cards[i]) { elsie++; } else if (elsie) { elsie--; score++; } } fout << score << endl; }
#include <fstream> #include <bitset> using namespace std; int main() { ifstream fin("highcard.in"); ofstream fout("highcard.out"); int num_sing_cards; fin >> num_sing_cards; bitset<100000> cards; for (int i = 0; i < num_sing_cards; i++) { int card; fin >> card; cards[card - 1] = true; } int elsie = 0, score = 0; for (int i = 0; i < 2 * num_sing_cards; i++) { if (cards[i]) { elsie++; } else if (elsie) { elsie--; score++; } } fout << score << endl; }
Check type similarity at runtim instead
#include <gtest/gtest.h> #include "distance.h" using namespace testing; using namespace std::literals::distance_literals; namespace TestDistanceUnits { class DistanceTest : public Test { protected: std::units::si::distance<long int> distance{0}; }; TEST_F(DistanceTest, Constructor_WhenInvoked_WillInitialise) { EXPECT_EQ(0, distance.count()); } class LiteralsTest : public Test { }; TEST_F(LiteralsTest, MetresLiteral_WhenUsed_WillReturnMetresType) { static_assert(std::is_same<std::units::si::metres, decltype(1_m)>::value, "Incompatible types"); EXPECT_TRUE(true); } }
#include <gtest/gtest.h> #include "distance.h" using namespace testing; using namespace std::literals::distance_literals; namespace TestDistanceUnits { class DistanceTest : public Test { protected: std::units::si::distance<long int> distance{0}; }; TEST_F(DistanceTest, Constructor_WhenInvoked_WillInitialise) { EXPECT_EQ(0, distance.count()); } class LiteralsTest : public Test { }; TEST_F(LiteralsTest, MetresLiteral_WhenUsed_WillReturnMetresType) { constexpr auto is_same = std::is_same<std::units::si::metres, decltype(1_m)>::value; EXPECT_TRUE(is_same) << "Incompatible types"; } }
Remove context test, context is to be reimpleemnted.
#include <iostream> #include <string> #include <proxc/config.hpp> #include <proxc/context.hpp> #include <proxc/scheduler.hpp> #include "setup.hpp" using Context = proxc::Context; void printer(int x, int y) { SafeCout::print(x, ", ", y); } void test_context() { auto main_ctx = Context::running(); auto scheduler = main_ctx->get_scheduler(); auto func1_ctx = Context::make_work_context( printer, 42, 1337 ); auto func2_ctx = Context::make_work_context( [](){ SafeCout::print("no arguments!"); } ); scheduler->attach_work_context(func1_ctx); scheduler->attach_work_context(func2_ctx); scheduler->schedule(func1_ctx); func2_ctx->resume(); std::cout << "done" << std::endl; } int main() { test_context(); return 0; }
#include <iostream> #include <string> #include <proxc/config.hpp> #include <proxc/context.hpp> #include <proxc/scheduler.hpp> #include "setup.hpp" using Context = proxc::Context; void printer(int x, int y) { SafeCout::print(x, ", ", y); } void test_context() { // TODO } int main() { test_context(); return 0; }
Fix missing std::memset for DLPack utils
// Copyright (c) 2020 Sony Corporation. 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 <nbla/array/cpu_array.hpp> #include <nbla/array/cpu_dlpack_array.hpp> namespace nbla { CpuDlpackArray::CpuDlpackArray(const Size_t size, dtypes dtype, const Context &ctx) : DlpackArray(size, dtype, ctx) {} CpuDlpackArray::~CpuDlpackArray() {} Context CpuDlpackArray::filter_context(const Context &ctx) { return Context({}, "CpuDlpackArray", ""); } void CpuDlpackArray::zero() { std::memset(this->pointer<void>(), 0, this->size() * sizeof_dtype(this->dtype_)); } NBLA_DEFINE_FUNC_COPY_FROM(CpuDlpackArray, cpu_array_copy, cpu); NBLA_DEFINE_FUNC_FILL(CpuDlpackArray, cpu_fill, cpu); }
// Copyright (c) 2020 Sony Corporation. 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 <nbla/array/cpu_array.hpp> #include <nbla/array/cpu_dlpack_array.hpp> #include <cstring> namespace nbla { CpuDlpackArray::CpuDlpackArray(const Size_t size, dtypes dtype, const Context &ctx) : DlpackArray(size, dtype, ctx) {} CpuDlpackArray::~CpuDlpackArray() {} Context CpuDlpackArray::filter_context(const Context &ctx) { return Context({}, "CpuDlpackArray", ""); } void CpuDlpackArray::zero() { std::memset(this->pointer<void>(), 0, this->size() * sizeof_dtype(this->dtype_)); } NBLA_DEFINE_FUNC_COPY_FROM(CpuDlpackArray, cpu_array_copy, cpu); NBLA_DEFINE_FUNC_FILL(CpuDlpackArray, cpu_fill, cpu); }
Use stderr to be consistent
#include "main.h" #include <boost/program_options.hpp> #include <iostream> #include "application.h" namespace po = boost::program_options; using namespace simplicity; using namespace std; void print_version(void); int main(int argc, char **argv) { po::options_description program_desc("Simplicity window manager"); program_desc.add_options() ("help", "Display usage") ("version", "Print simplicity version") ; po::variables_map args; po::store(po::parse_command_line(argc, argv, program_desc), args); po::notify(args); if (args.count("help")) { cerr << program_desc << endl; return 1; } if (args.count("version")) { print_version(); return 1; } SimplicityApplication::get_instance().run(); return 0; } void print_version(void) { cout << PACKAGE_STRING << endl; cout << "Copyright (C) 2014 James Durand\n" "This is free software; see the source for copying conditions.\n" "There is NO warranty." << endl; }
#include "main.h" #include <boost/program_options.hpp> #include <iostream> #include "application.h" namespace po = boost::program_options; using namespace simplicity; using namespace std; void print_version(void); int main(int argc, char **argv) { po::options_description program_desc("Simplicity window manager"); program_desc.add_options() ("help", "Display usage") ("version", "Print simplicity version") ; po::variables_map args; po::store(po::parse_command_line(argc, argv, program_desc), args); po::notify(args); if (args.count("help")) { cerr << program_desc << endl; return 1; } if (args.count("version")) { print_version(); return 1; } SimplicityApplication::get_instance().run(); return 0; } void print_version(void) { cerr << PACKAGE_STRING << endl; cerr << "Copyright (C) 2014 James Durand\n" "This is free software; see the source for copying conditions.\n" "There is NO warranty." << endl; }
Print a message at the end of the test run so it's easier to determine if any of the tests failed.
/* * ***************************************************************************** * Copyright 2014 Spectra Logic Corporation. 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. A copy of the License * is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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 <QTest> #include "test.h" int main(int /*argc*/, char** /*argv[]*/) { int failed = 0; for (int i = 0; i < Test::s_tests.size(); i++) { int result = QTest::qExec(Test::s_tests.at(i)); if (result != 0) { failed++; } } return failed; }
/* * ***************************************************************************** * Copyright 2014 Spectra Logic Corporation. 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. A copy of the License * is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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 <qDebug> #include <QTest> #include "test.h" int main(int /*argc*/, char** /*argv[]*/) { int failed = 0; for (int i = 0; i < Test::s_tests.size(); i++) { int result = QTest::qExec(Test::s_tests.at(i)); if (result != 0) { failed++; } } qDebug(); if (failed == 0) { qDebug() << "All Tests Passed"; } else { qDebug() << failed << "Test Suite(s) Contained Failures"; } return failed; }
Use make_shared instead of raw smart pointer constructor.
#include "RegExp.h" namespace tinygrep { namespace resyntax { RegExp::RegExp() : RegExp::RegExp(RegExpEnum::kEmpty) {} RegExp::RegExp(RegExpEnum type) : type_(type), r1_(nullptr), r2_(nullptr), literal_('\0') {} RegExp::RegExp(RegExpEnum type, literalType literal) : RegExp::RegExp(type) { literal_ = literal; } RegExp::RegExp(RegExpEnum type, const RegExp& r1) : RegExp::RegExp(type) { r1_ = SPtr(new RegExp(r1)); } RegExp::RegExp(RegExpEnum type, const RegExp& r1, const RegExp& r2) : RegExp::RegExp(type, r1) { r2_ = SPtr(new RegExp(r2)); } RegExpEnum RegExp::getType() const { return type_; } const RegExp& RegExp::getR1() const { return *r1_; } const RegExp& RegExp::getR2() const { return *r2_; } RegExp::literalType RegExp::getLiteral() const { return literal_; } } // namespace resyntax } // namespace tinygrep
#include "RegExp.h" namespace tinygrep { namespace resyntax { RegExp::RegExp() : RegExp::RegExp(RegExpEnum::kEmpty) {} RegExp::RegExp(RegExpEnum type) : type_(type), r1_(nullptr), r2_(nullptr), literal_('\0') {} RegExp::RegExp(RegExpEnum type, literalType literal) : RegExp::RegExp(type) { literal_ = literal; } RegExp::RegExp(RegExpEnum type, const RegExp& r1) : RegExp::RegExp(type) { r1_ = std::make_shared<RegExp>(r1); } RegExp::RegExp(RegExpEnum type, const RegExp& r1, const RegExp& r2) : RegExp::RegExp(type, r1) { r2_ = std::make_shared<RegExp>(r2); } RegExpEnum RegExp::getType() const { return type_; } const RegExp& RegExp::getR1() const { return *r1_; } const RegExp& RegExp::getR2() const { return *r2_; } RegExp::literalType RegExp::getLiteral() const { return literal_; } } // namespace resyntax } // namespace tinygrep
Set the toolbar to be static in its location. It looks ugly otherwise.
/* * Qumulus UML editor * Author: Randy Thiemann * */ #include "ToolBar.h" #include <Gui/Widgets/MainWindow.h> QUML_BEGIN_NAMESPACE_GW #ifdef Q_OS_MAC_disabled ToolBar::ToolBar(QObject* parent) : QObject(parent), mToolBar(new QMacNativeToolBar()) { } #else ToolBar::ToolBar(QObject* parent) : QObject(parent), mToolBar(new QToolBar()) { } #endif void ToolBar::showInWindow(MainWindow* w) { mWindow = w; #ifdef Q_OS_MAC_disabled mToolBar->showInWindowForWidget(w); mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); #else w->addToolBar(mToolBar.get()); mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); #endif } QuGW::MainWindow* ToolBar::window() { return mWindow; } // #ifndef Q_OS_MAC void ToolBar::addWidget(ToolBarItem* item) { mToolBar->addWidget(item); } // #endif void ToolBar::addSeparator() { mToolBar->addSeparator(); } #ifdef Q_OS_MAC_disabled void ToolBar::addFlexibleSpace() { mToolBar->addStandardItem(QMacToolButton::FlexibleSpace); } #endif QUML_END_NAMESPACE_GW
/* * Qumulus UML editor * Author: Randy Thiemann * */ #include "ToolBar.h" #include <Gui/Widgets/MainWindow.h> QUML_BEGIN_NAMESPACE_GW #ifdef Q_OS_MAC_disabled ToolBar::ToolBar(QObject* parent) : QObject(parent), mToolBar(new QMacNativeToolBar()) { } #else ToolBar::ToolBar(QObject* parent) : QObject(parent), mToolBar(new QToolBar()) { mToolBar->setFloatable(false); mToolBar->setMovable(false); } #endif void ToolBar::showInWindow(MainWindow* w) { mWindow = w; #ifdef Q_OS_MAC_disabled mToolBar->showInWindowForWidget(w); mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); #else w->addToolBar(mToolBar.get()); mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); #endif } QuGW::MainWindow* ToolBar::window() { return mWindow; } // #ifndef Q_OS_MAC void ToolBar::addWidget(ToolBarItem* item) { mToolBar->addWidget(item); } // #endif void ToolBar::addSeparator() { mToolBar->addSeparator(); } #ifdef Q_OS_MAC_disabled void ToolBar::addFlexibleSpace() { mToolBar->addStandardItem(QMacToolButton::FlexibleSpace); } #endif QUML_END_NAMESPACE_GW
Change wording on thread synchronization
#include "counter_application.hpp" #include <lib-tmsp/server.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/log/trivial.hpp> int main(int argc, char const* argv[]) { if(argc < 3) { BOOST_LOG_TRIVIAL(info) << "Provide TMSP listening endpoint on command line. Example: 0.0.0.0 46658"; return 1; } try { boost::asio::io_service io_service; tmsp::server_type const server( io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(argv[1]), std::atoi(argv[2])), std::make_shared<counter::application_type>() ); // In this simple application, all work is scheduled on the main thread using boost asio (just below). // Since the application is thus protected from being re-entered, there is no need for a mutex // inside the application. However it was left in in as a kind reminder that application // state must be synchronized if the thread count ever increased. io_service.run(); } catch(...) { BOOST_LOG_TRIVIAL(error) << boost::current_exception_diagnostic_information(); return 2; } return 0; }
#include "counter_application.hpp" #include <lib-tmsp/server.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/log/trivial.hpp> int main(int argc, char const* argv[]) { if(argc < 3) { BOOST_LOG_TRIVIAL(info) << "Provide TMSP listening endpoint on command line. Example: 0.0.0.0 46658"; return 1; } try { boost::asio::io_service io_service; tmsp::server_type const server( io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(argv[1]), std::atoi(argv[2])), std::make_shared<counter::application_type>() ); // In this simple application, all work is scheduled on the main thread using boost asio (just below). // Since the application is thus protected from being re-entered, there is no need for a mutex to synchronize access. // It was left there as a kind reminder that synchronization must be used if the thread count ever increases. io_service.run(); } catch(...) { BOOST_LOG_TRIVIAL(error) << boost::current_exception_diagnostic_information(); return 2; } return 0; }
Extend STM32L4's lowLevelInitialization() with flash initialization
/** * \file * \brief chip::lowLevelInitialization() implementation for STM32L4 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { } } // namespace chip } // namespace distortos
/** * \file * \brief chip::lowLevelInitialization() implementation for STM32L4 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" #include "distortos/chip/STM32L4-FLASH.hpp" #include "distortos/distortosConfiguration.h" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { #ifdef CONFIG_CHIP_STM32L4_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(true); #else // !def CONFIG_CHIP_STM32L4_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(false); #endif // !def CONFIG_CHIP_STM32L4_FLASH_PREFETCH_ENABLE #ifdef CONFIG_CHIP_STM32L4_FLASH_DATA_CACHE_ENABLE enableDataCache(); #else // !def CONFIG_CHIP_STM32L4_FLASH_DATA_CACHE_ENABLE disableDataCache(); #endif // !def CONFIG_CHIP_STM32L4_FLASH_DATA_CACHE_ENABLE #ifdef CONFIG_CHIP_STM32L4_FLASH_INSTRUCTION_CACHE_ENABLE enableInstructionCache(); #else // !def CONFIG_CHIP_STM32L4_FLASH_INSTRUCTION_CACHE_ENABLE disableInstructionCache(); #endif // !def CONFIG_CHIP_STM32L4_FLASH_INSTRUCTION_CACHE_ENABLE } } // namespace chip } // namespace distortos
Fix type warning (and success value)
#include <windows.h> #include "system/thread.hh" using System::Thread; DWORD WINAPI startThread(LPVOID args); class Implementation : public Thread::ThreadImplementation { public: Implementation(Thread::Callable function) : _function(function) { } void start() { _threadHandle = CreateThread(NULL, 0, ::startThread, this, 0, NULL); } void join() { WaitForSingleObject(_threadHandle, INFINITE); } void run() { _function(); } private: Thread::Callable _function; HANDLE _threadHandle; }; DWORD WINAPI startThread(LPVOID args) { Implementation *self = (Implementation *)args; self->run(); return NULL; } Thread::ThreadImplementation *Thread::createImplementation(Thread::Callable function) { return new Implementation(function); } Thread::Thread(Callable function) { _implementation = createImplementation(function); _implementation->start(); } void Thread::join() { _implementation->join(); }
#include <windows.h> #include "system/thread.hh" using System::Thread; DWORD WINAPI startThread(LPVOID args); class Implementation : public Thread::ThreadImplementation { public: Implementation(Thread::Callable function) : _function(function) { } void start() { _threadHandle = CreateThread(NULL, 0, ::startThread, this, 0, NULL); } void join() { WaitForSingleObject(_threadHandle, INFINITE); } void run() { _function(); } private: Thread::Callable _function; HANDLE _threadHandle; }; DWORD WINAPI startThread(LPVOID args) { Implementation *self = (Implementation *)args; self->run(); return 1; } Thread::ThreadImplementation *Thread::createImplementation(Thread::Callable function) { return new Implementation(function); } Thread::Thread(Callable function) { _implementation = createImplementation(function); _implementation->start(); } void Thread::join() { _implementation->join(); }
Revert r110936; this fails on clang-i686-darwin10 too.
// RUN: %clang -march=x86_64-apple-darwin10 -emit-llvm -g -S %s -o - | FileCheck %s struct X { X(int v); int value; }; X::X(int v) { // CHECK: call void @_ZN1XC2Ei(%struct.X* %this1, i32 %tmp), !dbg value = v; }
// RUN: %clang -emit-llvm -g -S %s -o - | FileCheck %s struct X { X(int v); int value; }; X::X(int v) { // CHECK_TEMPORARILY_DISABLED: call void @_ZN1XC2Ei(%struct.X* %this1, i32 %tmp), !dbg // TEMPORARY CHECK: X value = v; }
Fix broken compilation on Linux/OS X
#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
#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
Add NOLINT to C++17 structured binding code
#include "mips_memory.h" #include "mips_instr.h" #include <infra/instrcache/instr_cache.h> FuncInstr MIPSMemory::fetch_instr( Addr PC) { const auto [found, value] = instr_cache.find( PC); FuncInstr instr = found ? value : FuncInstr( fetch( PC), PC); instr_cache.update( PC, instr); return instr; }
#include "mips_memory.h" #include "mips_instr.h" #include <infra/instrcache/instr_cache.h> FuncInstr MIPSMemory::fetch_instr( Addr PC) { const auto [found, value] = instr_cache.find( PC); // NOLINT https://bugs.llvm.org/show_bug.cgi?id=36283 FuncInstr instr = found ? value : FuncInstr( fetch( PC), PC); instr_cache.update( PC, instr); return instr; }
Load values in MatcherCreationDialog from settings
#include "include/matchercreationdialog.h" #include "ui_matchercreationdialog.h" MatcherCreationDialog::MatcherCreationDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MatcherCreationDialog) { ui->setupUi(this); } MatcherCreationDialog::~MatcherCreationDialog() { delete ui; } int MatcherCreationDialog::xblocks() { return ui->xblocks->value(); } int MatcherCreationDialog::yblocks() { return ui->yblocks->value(); } int MatcherCreationDialog::windowSize() { return ui->window_size->value(); } CharacterSets MatcherCreationDialog::set() { switch(ui->set->currentIndex()) { case 1: return CharacterSets::CHINESE; case 2: return CharacterSets::LATIN; case 0: default: return CharacterSets::CHINESE_REDUCED; } }
#include "include/matchercreationdialog.h" #include "ui_matchercreationdialog.h" #include <QSettings> MatcherCreationDialog::MatcherCreationDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MatcherCreationDialog) { ui->setupUi(this); QSettings settings; ui->xblocks->setValue(settings.value("xblocks").toInt()); ui->yblocks->setValue(settings.value("yblocks").toInt()); ui->window_size->setValue(settings.value("windowSize").toInt()); switch(settings.value("characterSet").value<CharacterSets>()) { case CharacterSets::CHINESE: ui->set->setCurrentIndex(1); break; case CharacterSets::LATIN: ui->set->setCurrentIndex(2); break; case CharacterSets::CHINESE_REDUCED: default: ui->set->setCurrentIndex(0); break; } } MatcherCreationDialog::~MatcherCreationDialog() { delete ui; } int MatcherCreationDialog::xblocks() { return ui->xblocks->value(); } int MatcherCreationDialog::yblocks() { return ui->yblocks->value(); } int MatcherCreationDialog::windowSize() { return ui->window_size->value(); } CharacterSets MatcherCreationDialog::set() { switch(ui->set->currentIndex()) { case 1: return CharacterSets::CHINESE; case 2: return CharacterSets::LATIN; case 0: default: return CharacterSets::CHINESE_REDUCED; } }
Fix error in setting both HVX_64 and HVX_128 at same time
#include <Halide.h> #include "vzero.h" #include <stdio.h> using namespace Halide; // RUN: rm -f vzero.stdout; ./vzero.out; llvm-dis -o vzero.stdout vzero.bc; FileCheck %s < vzero.stdout int main(int argc, char **argv) { Target target; setupHexagonTarget(target); target.set_feature(Target::HVX_64); //CHECK: call{{.*}}@llvm.hexagon.V6.vd0 testBzero<uint32_t>(target); printf ("Done\n"); return 0; }
#include <Halide.h> #include "vzero.h" #include <stdio.h> using namespace Halide; // RUN: rm -f vzero.stdout; ./vzero.out; llvm-dis -o vzero.stdout vzero.bc; FileCheck %s < vzero.stdout int main(int argc, char **argv) { Target target; setupHexagonTarget(target, Target::HVX_64); //CHECK: call{{.*}}@llvm.hexagon.V6.vd0 testBzero<uint32_t>(target); printf ("Done\n"); return 0; }
Remove static initializer to register destructor.
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFontConfigInterface.h" #include "SkFontMgr.h" #include "SkMutex.h" #include "SkRefCnt.h" SK_DECLARE_STATIC_MUTEX(gFontConfigInterfaceMutex); static sk_sp<SkFontConfigInterface> gFontConfigInterface(nullptr); sk_sp<SkFontConfigInterface> SkFontConfigInterface::RefGlobal() { SkAutoMutexAcquire ac(gFontConfigInterfaceMutex); if (gFontConfigInterface) { return gFontConfigInterface; } return sk_ref_sp(SkFontConfigInterface::GetSingletonDirectInterface()); } void SkFontConfigInterface::SetGlobal(sk_sp<SkFontConfigInterface> fc) { SkAutoMutexAcquire ac(gFontConfigInterfaceMutex); gFontConfigInterface = std::move(fc); }
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFontConfigInterface.h" #include "SkFontMgr.h" #include "SkMutex.h" #include "SkRefCnt.h" SK_DECLARE_STATIC_MUTEX(gFontConfigInterfaceMutex); static SkFontConfigInterface* gFontConfigInterface; sk_sp<SkFontConfigInterface> SkFontConfigInterface::RefGlobal() { SkAutoMutexAcquire ac(gFontConfigInterfaceMutex); if (gFontConfigInterface) { return sk_ref_sp(gFontConfigInterface); } return sk_ref_sp(SkFontConfigInterface::GetSingletonDirectInterface()); } void SkFontConfigInterface::SetGlobal(sk_sp<SkFontConfigInterface> fc) { SkAutoMutexAcquire ac(gFontConfigInterfaceMutex); SkSafeUnref(gFontConfigInterface); gFontConfigInterface = fc.release(); }
Fix unintended behavior in KontsevichGraphSum's reduce() method: now all signs of graphs are properly set to 1.
#include <kontsevich_graph_sum.hpp> template <class T> void KontsevichGraphSum<T>::reduce() { auto current_term = this->begin(); current_term->first *= current_term->second.sign(); current_term->second.sign(1); while (current_term < this->end()) { auto subsequent_term = current_term + 1; while (subsequent_term < this->end()) { if (subsequent_term->second.abs() == current_term->second.abs()) { current_term->first += subsequent_term->first * subsequent_term->second.sign(); subsequent_term = this->erase(subsequent_term); } else subsequent_term++; } current_term++; } } template <class T> std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<T>& gs) { if (gs.size() == 0) return os << "0"; for (auto &term : gs) { os << term.first << "*(" << term.second << ")"; if (&term != &gs.back()) os << " + "; } return os; } template class KontsevichGraphSum<int>; template std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<int>& gs);
#include "kontsevich_graph_sum.hpp" template <class T> void KontsevichGraphSum<T>::reduce() { auto current_term = this->begin(); while (current_term < this->end()) { current_term->first *= current_term->second.sign(); current_term->second.sign(1); auto subsequent_term = current_term + 1; while (subsequent_term < this->end()) { if (subsequent_term->second.abs() == current_term->second.abs()) { current_term->first += subsequent_term->first * subsequent_term->second.sign(); subsequent_term = this->erase(subsequent_term); } else subsequent_term++; } current_term++; } } template <class T> std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<T>& gs) { if (gs.size() == 0) return os << "0"; for (auto &term : gs) { os << term.first << "*(" << term.second << ")"; if (&term != &gs.back()) os << " + "; } return os; } template class KontsevichGraphSum<int>; template std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<int>& gs);
Use FileCheck variable matchers for better test support
// RUN: %clangxx -target x86_64-unknown-unknown -g %s -emit-llvm -S -o - | FileCheck %s // RUN: %clangxx -target x86_64-unknown-unknown -g -fno-elide-constructors %s -emit-llvm -S -o - | FileCheck %s -check-prefix=NOELIDE struct Foo { Foo() = default; Foo(Foo &&other) { x = other.x; } int x; }; void some_function(int); Foo getFoo() { Foo foo; foo.x = 41; some_function(foo.x); return foo; } int main() { Foo bar = getFoo(); return bar.x; } // Check that NRVO variables are stored as a pointer with deref if they are // stored in the return register. // CHECK: %result.ptr = alloca i8*, align 8 // CHECK: call void @llvm.dbg.declare(metadata i8** %result.ptr, // CHECK-SAME: metadata !DIExpression(DW_OP_deref) // NOELIDE: call void @llvm.dbg.declare(metadata %struct.Foo* %foo, // NOELIDE-SAME: metadata !DIExpression()
// RUN: %clangxx -target x86_64-unknown-unknown -g \ // RUN: %s -emit-llvm -S -o - | FileCheck %s // RUN: %clangxx -target x86_64-unknown-unknown -g \ // RUN: -fno-elide-constructors %s -emit-llvm -S -o - | \ // RUN: FileCheck %s -check-prefix=NOELIDE struct Foo { Foo() = default; Foo(Foo &&other) { x = other.x; } int x; }; void some_function(int); Foo getFoo() { Foo foo; foo.x = 41; some_function(foo.x); return foo; } int main() { Foo bar = getFoo(); return bar.x; } // Check that NRVO variables are stored as a pointer with deref if they are // stored in the return register. // CHECK: %[[RESULT:.*]] = alloca i8*, align 8 // CHECK: call void @llvm.dbg.declare(metadata i8** %[[RESULT]], // CHECK-SAME: metadata !DIExpression(DW_OP_deref) // NOELIDE: %[[FOO:.*]] = alloca %struct.Foo, align 4 // NOELIDE: call void @llvm.dbg.declare(metadata %struct.Foo* %[[FOO]], // NOELIDE-SAME: metadata !DIExpression()
Fix warning on unused parameter
#include "singlerole.h" #include <QVariant> namespace qqsfpm { /*! \qmltype SingleRole \inherits ProxyRole \inqmlmodule SortFilterProxyModel \brief Base type for the \l SortFilterProxyModel proxy roles defining a single role SingleRole is a convenience base class for proxy roles who define a single role. It cannot be used directly in a QML file. It exists to provide a set of common properties and methods, available across all the other proxy role types that inherit from it. Attempting to use the SingleRole type directly will result in an error. */ /*! \qmlproperty string SingleRole::name This property holds the role name of the proxy role. */ QString SingleRole::name() const { return m_name; } void SingleRole::setName(const QString& name) { if (m_name == name) return; Q_EMIT namesAboutToBeChanged(); m_name = name; Q_EMIT nameChanged(); Q_EMIT namesChanged(); } QStringList SingleRole::names() { return QStringList { m_name }; } QVariant SingleRole::data(const QModelIndex &sourceIndex, const QQmlSortFilterProxyModel &proxyModel, const QString &name) { return data(sourceIndex, proxyModel); } }
#include "singlerole.h" #include <QVariant> namespace qqsfpm { /*! \qmltype SingleRole \inherits ProxyRole \inqmlmodule SortFilterProxyModel \brief Base type for the \l SortFilterProxyModel proxy roles defining a single role SingleRole is a convenience base class for proxy roles who define a single role. It cannot be used directly in a QML file. It exists to provide a set of common properties and methods, available across all the other proxy role types that inherit from it. Attempting to use the SingleRole type directly will result in an error. */ /*! \qmlproperty string SingleRole::name This property holds the role name of the proxy role. */ QString SingleRole::name() const { return m_name; } void SingleRole::setName(const QString& name) { if (m_name == name) return; Q_EMIT namesAboutToBeChanged(); m_name = name; Q_EMIT nameChanged(); Q_EMIT namesChanged(); } QStringList SingleRole::names() { return QStringList { m_name }; } QVariant SingleRole::data(const QModelIndex &sourceIndex, const QQmlSortFilterProxyModel &proxyModel, const QString &name) { Q_UNUSED(name); return data(sourceIndex, proxyModel); } }
Allow placement new array test to consume extra bytes as specified by the standard.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // test placement new array #include <new> #include <cassert> int A_constructed = 0; struct A { A() {++A_constructed;} ~A() {--A_constructed;} }; int main() { char buf[3*sizeof(A)]; A* ap = new(buf) A[3]; assert((char*)ap == buf); assert(A_constructed == 3); }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // test placement new array #include <new> #include <cassert> int A_constructed = 0; struct A { A() {++A_constructed;} ~A() {--A_constructed;} }; int main() { const std::size_t Size = 3; // placement new might require additional space. const std::size_t ExtraSize = 64; char buf[Size*sizeof(A) + ExtraSize]; A* ap = new(buf) A[Size]; assert((char*)ap >= buf); assert((char*)ap < (buf + ExtraSize)); assert(A_constructed == Size); }
Extend a bit the thread test output
#include <evenk/synch.h> #include <evenk/thread.h> #include <iostream> evenk::default_synch::lock_type lock; evenk::default_synch::cond_var_type cond; void thread_routine() { evenk::default_synch::lock_owner_type guard(lock); cond.notify_one(); // notify that the thread started cond.wait(guard); // wait for test finish } void print_affinity(const evenk::thread::cpuset_type &affinity) { for (std::size_t cpu = 0; cpu < affinity.size(); cpu++) std::cout << cpu << " "; std::cout << "\n"; } int main() { evenk::default_synch::lock_owner_type guard(lock); evenk::thread thread(thread_routine); cond.wait(guard); // wait until the thread starts guard.unlock(); { auto affinity = thread.affinity(); print_affinity(affinity); for (std::size_t i = 0; i < affinity.size(); i++) affinity[i] = false; thread.affinity(affinity); } { auto affinity = thread.affinity(); print_affinity(affinity); } guard.lock(); cond.notify_one(); // notify about test finish guard.unlock(); thread.join(); return 0; }
#include <evenk/synch.h> #include <evenk/thread.h> #include <iostream> evenk::default_synch::lock_type lock; evenk::default_synch::cond_var_type cond; void thread_routine() { evenk::default_synch::lock_owner_type guard(lock); cond.notify_one(); // notify that the thread started cond.wait(guard); // wait for test finish } void print_affinity(const evenk::thread::cpuset_type &affinity) { std::cout << affinity.size() << ":"; for (std::size_t cpu = 0; cpu < affinity.size(); cpu++) std::cout << " " << cpu; std::cout << "\n"; } int main() { evenk::default_synch::lock_owner_type guard(lock); evenk::thread thread(thread_routine); cond.wait(guard); // wait until the thread starts guard.unlock(); { auto affinity = thread.affinity(); print_affinity(affinity); for (std::size_t i = 0; i < affinity.size(); i++) affinity[i] = false; thread.affinity(affinity); } { auto affinity = thread.affinity(); print_affinity(affinity); } guard.lock(); cond.notify_one(); // notify about test finish guard.unlock(); thread.join(); return 0; }
Use fopen instead of iostream
// // Created by monty on 08/12/16. // #include <string> #include <iostream> #include <fstream> #include <vector> #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" namespace Knights { CPlainFileLoader::CPlainFileLoader() { } CPlainFileLoader::CPlainFileLoader(std::string prefix) : mPrefix(prefix) { } std::vector<char> CPlainFileLoader::loadBinaryFileFromPath(const std::string &path) { std::ifstream fontFile(path, std::ios::binary); std::vector<char> buffer(( std::istreambuf_iterator<char>(fontFile)), (std::istreambuf_iterator<char>())); return buffer; } std::string CPlainFileLoader::loadFileFromPath(const std::string &path) { std::string entry; std::ifstream fileToLoad(path); char buffer; while (!fileToLoad.eof()) { fileToLoad >> std::noskipws >> buffer; entry.push_back(buffer); } return entry; } std::string CPlainFileLoader::getFilePathPrefix() { return mPrefix; } }
// // Created by monty on 08/12/16. // #include <string> #include <iostream> #include <fstream> #include <vector> #include <Common.h> #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" namespace Knights { CPlainFileLoader::CPlainFileLoader() { } CPlainFileLoader::CPlainFileLoader(std::string prefix) : mPrefix(prefix) { } std::vector<char> CPlainFileLoader::loadBinaryFileFromPath(const std::string &path) { FILE *fd; fd = fopen(( getFilePathPrefix() + path).c_str(), "rb"); std::vector<char> toReturn = readToBuffer(fd); fclose(fd); return toReturn; } std::string CPlainFileLoader::loadFileFromPath(const std::string &path) { FILE *fd; fd = fopen(( getFilePathPrefix() + path).c_str(), "r"); auto toReturn = readToString(fd); fclose(fd); return toReturn; } std::string CPlainFileLoader::getFilePathPrefix() { return mPrefix; } }
Add fuzzing for 32-bit PE/COFF files
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <inttypes.h> #include <cstddef> #include <unwindstack/Memory.h> #include <unwindstack/PeCoffInterface.h> // The most basic fuzzer for PE/COFF parsing. Generates really poor coverage as // it is not PE/COFF file structure aware. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::shared_ptr<unwindstack::Memory> memory = unwindstack::Memory::CreateOfflineMemory(data, 0, size); unwindstack::PeCoffInterface<uint64_t> pe_coff_interface(memory.get()); pe_coff_interface.Init(); return 0; }
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <inttypes.h> #include <cstddef> #include <unwindstack/Memory.h> #include <unwindstack/PeCoffInterface.h> namespace { template <typename AddressType> void FuzzPeCoffInterface(const uint8_t* data, size_t size) { std::shared_ptr<unwindstack::Memory> memory = unwindstack::Memory::CreateOfflineMemory(data, 0, size); unwindstack::PeCoffInterface<AddressType> pe_coff_interface(memory.get()); pe_coff_interface.Init(); } } // namespace // The most basic fuzzer for PE/COFF parsing, not PE/COFF structure aware. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { FuzzPeCoffInterface<uint32_t>(data, size); FuzzPeCoffInterface<uint64_t>(data, size); return 0; }
Update empty scene to draw code
#include "emptyScene.h" void emptyScene::setup(){ // parameters.add(param); loadCode("emptyScene/exampleCode.cpp"); } void emptyScene::update(){ } void emptyScene::draw(){ } void emptyScene::drawCode(){ string codeReplaced = getCodeWithParamsReplaced(); ofDrawBitmapString(codeReplaced, 40,40); }
#include "emptyScene.h" void emptyScene::setup(){ // parameters.add(param); loadCode("emptyScene/exampleCode.cpp"); } void emptyScene::update(){ } void emptyScene::draw(){ drawCode(); } void emptyScene::drawCode(){ string codeReplaced = getCodeWithParamsReplaced(); ofDrawBitmapString(codeReplaced, 40,40); }
Remove superfluous headers from main file
#include <climits> #include <cstdlib> #include <cstring> #include <unistd.h> #include <iostream> #include <algorithm> #include <list> #include <deque> #include <vector> #include <X11/keysym.h> #include <xcb/xcb.h> #include <xcb/xcb_atom.h> #include <xcb/xcb_keysyms.h> #include <xcb/damage.h> #include <xcb/xinerama.h> #include <xcb/composite.h> #include "data_types.hpp" #include "x_event_handler.hpp" #include "x_connection.hpp" #include "x_client.hpp" #include "x_event_source.hpp" #include "x_client_container.hpp" #include "x_clients_preview.hpp" #include "layout_t.hpp" #include "grid.hpp" int main(int argc, char ** argv) { x_connection c; c.grab_key(XCB_MOD_MASK_4, XK_Tab); x_event_source es(c); x_client_container cc(c, es); grid_t grid; x_clients_preview cp(c, &grid, cc); es.register_handler(&c); es.register_handler(&cp); es.run_event_loop(); return 0; }
#include <xcb/xcb.h> #include <X11/keysym.h> #include "data_types.hpp" #include "x_event_handler.hpp" #include "x_connection.hpp" #include "x_client.hpp" #include "x_event_source.hpp" #include "x_client_container.hpp" #include "x_clients_preview.hpp" #include "layout_t.hpp" #include "grid.hpp" int main(int argc, char ** argv) { x_connection c; c.grab_key(XCB_MOD_MASK_4, XK_Tab); x_event_source es(c); x_client_container cc(c, es); grid_t grid; x_clients_preview cp(c, &grid, cc); es.register_handler(&c); es.register_handler(&cp); es.run_event_loop(); return 0; }
Fix erroneous test; was failing on darwin-ppc32. Fixes PR18469.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // type_traits // alignment_of #include <type_traits> #include <cstdint> template <class T, unsigned A> void test_alignment_of() { static_assert( std::alignment_of<T>::value == A, ""); static_assert( std::alignment_of<const T>::value == A, ""); static_assert( std::alignment_of<volatile T>::value == A, ""); static_assert( std::alignment_of<const volatile T>::value == A, ""); } class Class { public: ~Class(); }; int main() { test_alignment_of<int&, 4>(); test_alignment_of<Class, 1>(); test_alignment_of<int*, sizeof(intptr_t)>(); test_alignment_of<const int*, sizeof(intptr_t)>(); test_alignment_of<char[3], 1>(); test_alignment_of<int, 4>(); test_alignment_of<double, 8>(); test_alignment_of<bool, 1>(); test_alignment_of<unsigned, 4>(); }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // type_traits // alignment_of #include <type_traits> #include <cstdint> template <class T, unsigned A> void test_alignment_of() { static_assert( std::alignment_of<T>::value == A, ""); static_assert( std::alignment_of<const T>::value == A, ""); static_assert( std::alignment_of<volatile T>::value == A, ""); static_assert( std::alignment_of<const volatile T>::value == A, ""); } class Class { public: ~Class(); }; int main() { test_alignment_of<int&, 4>(); test_alignment_of<Class, 1>(); test_alignment_of<int*, sizeof(intptr_t)>(); test_alignment_of<const int*, sizeof(intptr_t)>(); test_alignment_of<char[3], 1>(); test_alignment_of<int, 4>(); test_alignment_of<double, 8>(); #if (defined(__ppc__) && !defined(__ppc64__)) test_alignment_of<bool, 4>(); // 32-bit PPC has four byte bool #else test_alignment_of<bool, 1>(); #endif test_alignment_of<unsigned, 4>(); }
Fix 'clang-cc -analyzer-display-progress' by flushing standard error after printing the name of the analyzed function.
//== AnalysisManager.cpp - Path sensitive analysis data manager ----*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the AnalysisManager class. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/AnalysisManager.h" #include "clang/Basic/SourceManager.h" using namespace clang; void AnalysisManager::DisplayFunction(Decl *D) { if (DisplayedFunction) return; DisplayedFunction = true; // FIXME: Is getCodeDecl() always a named decl? if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { const NamedDecl *ND = cast<NamedDecl>(D); SourceManager &SM = getASTContext().getSourceManager(); llvm::errs() << "ANALYZE: " << SM.getPresumedLoc(ND->getLocation()).getFilename() << ' ' << ND->getNameAsString() << '\n'; } }
//== AnalysisManager.cpp - Path sensitive analysis data manager ----*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the AnalysisManager class. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/AnalysisManager.h" #include "clang/Basic/SourceManager.h" using namespace clang; void AnalysisManager::DisplayFunction(Decl *D) { if (DisplayedFunction) return; DisplayedFunction = true; // FIXME: Is getCodeDecl() always a named decl? if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { const NamedDecl *ND = cast<NamedDecl>(D); SourceManager &SM = getASTContext().getSourceManager(); (llvm::errs() << "ANALYZE: " << SM.getPresumedLoc(ND->getLocation()).getFilename() << ' ' << ND->getNameAsString() << '\n').flush(); } }
Move request header to a separate structure
#include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <string> #include <sys/time.h> #include <thread> #include <rclcpp/rclcpp.hpp> #include <simple_msgs/AllBuiltinTypes.h> #include <simple_msgs/AllDynamicArrayTypes.h> #include <simple_msgs/AllPrimitiveTypes.h> #include <simple_msgs/AllStaticArrayTypes.h> #include <simple_msgs/Nested.h> #include <simple_msgs/String.h> #include <simple_msgs/Uint32.h> #include <userland_msgs/AddTwoInts.h> void add(const std::shared_ptr<userland_msgs::AddTwoIntsRequest> req, std::shared_ptr<userland_msgs::AddTwoIntsResponse> res) { std::cout << "Incoming request" << std::endl; res->sum = req->a + req->b; } int main(int argc, char** argv) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("add_two_ints_server"); node->create_service<userland_msgs::AddTwoInts>("add_two_ints", add); rclcpp::spin(node); return 0; }
#include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <string> #include <sys/time.h> #include <thread> #include <rclcpp/rclcpp.hpp> #include <simple_msgs/AllBuiltinTypes.h> #include <simple_msgs/AllDynamicArrayTypes.h> #include <simple_msgs/AllPrimitiveTypes.h> #include <simple_msgs/AllStaticArrayTypes.h> #include <simple_msgs/Nested.h> #include <simple_msgs/String.h> #include <simple_msgs/Uint32.h> #include <userland_msgs/AddTwoInts.h> void add(const std::shared_ptr<userland_msgs::AddTwoIntsRequestWithHeader> req, std::shared_ptr<userland_msgs::AddTwoIntsResponse> res) { std::cout << "Incoming request" << std::endl; std::cout << "a: " << req->request.a << " b: " << req->request.b << std::endl; res->sum = req->request.a + req->request.b; } int main(int argc, char** argv) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("add_two_ints_server"); node->create_service<userland_msgs::AddTwoInts>("add_two_ints", add); rclcpp::spin(node); return 0; }
Add tests to ensure that reference_wrapper<T> is trivially copyable. This was added to C++1z with the adoption of N4277, but libc++ already implemented it as a conforming extension. No code changes were needed, just more tests.
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <functional> // reference_wrapper // Test that reference wrapper meets the requirements of TriviallyCopyable, // CopyConstructible and CopyAssignable. #include <functional> #include <type_traits> int main() { typedef std::reference_wrapper<int> T; static_assert(std::is_copy_constructible<T>::value, ""); static_assert(std::is_copy_assignable<T>::value, ""); // Extension up for standardization: See N4151. static_assert(std::is_trivially_copyable<T>::value, ""); }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <functional> // reference_wrapper // Test that reference wrapper meets the requirements of TriviallyCopyable, // CopyConstructible and CopyAssignable. #include <functional> #include <type_traits> #include <string> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES class MoveOnly { MoveOnly(const MoveOnly&); MoveOnly& operator=(const MoveOnly&); int data_; public: MoveOnly(int data = 1) : data_(data) {} MoveOnly(MoveOnly&& x) : data_(x.data_) {x.data_ = 0;} MoveOnly& operator=(MoveOnly&& x) {data_ = x.data_; x.data_ = 0; return *this;} int get() const {return data_;} }; #endif template <class T> void test() { typedef std::reference_wrapper<T> Wrap; static_assert(std::is_copy_constructible<Wrap>::value, ""); static_assert(std::is_copy_assignable<Wrap>::value, ""); // Extension up for standardization: See N4151. static_assert(std::is_trivially_copyable<Wrap>::value, ""); } int main() { test<int>(); test<double>(); test<std::string>(); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES test<MoveOnly>(); #endif }
Add exception handling to threads
// // ODCManager.cpp // opendatacon_suite // // Created by Alan Murray on 6/06/2017. // // #include <opendatacon/ODCManager.h> namespace odc { ODCManager::ODCManager( uint32_t concurrencyHint, openpal::ICryptoProvider* crypto, std::function<void()> onThreadStart, std::function<void()> onThreadExit ) : ios_working(new asio::io_service::work(IOS)), scheduler(IOS) { for (size_t i = 0; i < concurrencyHint; ++i) std::thread([&](){ IOS.run(); }).detach(); } }
// // ODCManager.cpp // opendatacon_suite // // Created by Alan Murray on 6/06/2017. // // #include <opendatacon/ODCManager.h> #include <iostream> namespace odc { ODCManager::ODCManager( uint32_t concurrencyHint, openpal::ICryptoProvider* crypto, std::function<void()> onThreadStart, std::function<void()> onThreadExit ) : ios_working(new asio::io_service::work(IOS)), scheduler(IOS) { for (size_t i = 0; i < concurrencyHint; ++i) std::thread([&](){ for (;;) { try { IOS.run(); break; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; // TODO: work out what best to do // log exception // shutdown port, restart application? } } }).detach(); } }
Set dense feature count to 0
#include <iostream> #include "SparseReorderingFeature.h" using namespace std; namespace Moses { SparseReorderingFeature::SparseReorderingFeature(const std::string &line) :StatefulFeatureFunction("StatefulFeatureFunction", line) { cerr << "Constructing a Sparse Reordering feature" << endl; } FFState* SparseReorderingFeature::EvaluateChart( const ChartHypothesis& /* cur_hypo */, int /* featureID - used to index the state in the previous hypotheses */, ScoreComponentCollection* accumulator) const { return new SparseReorderingState(); } }
#include <iostream> #include "moses/ChartHypothesis.h" #include "SparseReorderingFeature.h" using namespace std; namespace Moses { SparseReorderingFeature::SparseReorderingFeature(const std::string &line) :StatefulFeatureFunction("StatefulFeatureFunction",0, line) { cerr << "Constructing a Sparse Reordering feature" << endl; } FFState* SparseReorderingFeature::EvaluateChart( const ChartHypothesis& cur_hypo , int featureID /*- used to index the state in the previous hypotheses */, ScoreComponentCollection* accumulator) const { // get index map for underlying hypotheses const AlignmentInfo::NonTermIndexMap &nonTermIndexMap = cur_hypo.GetCurrTargetPhrase().GetAlignNonTerm().GetNonTermIndexMap(); return new SparseReorderingState(); } }
Use the short/full as fallback when the full/short is not set
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright (C) 2012 Illya Kovalevskyy <illya.kovalevskyy@gmail.com> // #include "GeoSceneLicense.h" namespace Marble { GeoSceneLicense::GeoSceneLicense() : m_attribution( OptOut ) { // nothing to do } QString GeoSceneLicense::license() const { return m_fullLicense; } QString GeoSceneLicense::shortLicense() const { return m_shortLicense; } GeoSceneLicense::Attribution GeoSceneLicense::attribution() const { return m_attribution; } void GeoSceneLicense::setLicense(const QString &license ) { m_fullLicense = license; } void GeoSceneLicense::setShortLicense( const QString &license ) { m_shortLicense = license; } void GeoSceneLicense::setAttribution(Attribution attr ) { m_attribution = attr; } }
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright (C) 2012 Illya Kovalevskyy <illya.kovalevskyy@gmail.com> // #include "GeoSceneLicense.h" namespace Marble { GeoSceneLicense::GeoSceneLicense() : m_attribution( OptOut ) { // nothing to do } QString GeoSceneLicense::license() const { return m_fullLicense.isEmpty() ? m_shortLicense : m_fullLicense; } QString GeoSceneLicense::shortLicense() const { return m_shortLicense.isEmpty() ? m_fullLicense : m_shortLicense; } GeoSceneLicense::Attribution GeoSceneLicense::attribution() const { return m_attribution; } void GeoSceneLicense::setLicense(const QString &license ) { m_fullLicense = license; } void GeoSceneLicense::setShortLicense( const QString &license ) { m_shortLicense = license; } void GeoSceneLicense::setAttribution(Attribution attr ) { m_attribution = attr; } }
Refactor program options and make them "temp" and "location"
#include <iostream> #include "boost/program_options.hpp" using namespace std; namespace po = boost::program_options; int main(int argc, char **argv) { // Declare the supported options. po::options_description desc("Accepted options"); desc.add_options() ("help", "produce help message") ("temperature", "sort by temperature") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } if (vm.count("temperature")) { cout << "All righty, we'll sort by temperature.\n"; } else { cout << "We'll sort randomly. Like a bawse.\n"; } return 0; }
#include <iostream> #include "boost/program_options.hpp" using namespace std; namespace po = boost::program_options; po::variables_map parse_args(int argc, char **argv) { po::options_description desc("Accepted options"); desc.add_options() ("help", "produce help message") ("temp", "sort by temperature instead of location") ("location", po::value<vector<string> >(), "location(s)") ; po::positional_options_description p; p.add("location", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; } return vm; } int main(int argc, char **argv) { po::variables_map vm = parse_args(argc, argv); if (vm.count("help")) { return 1; } if (vm.count("location") == 0) { cerr << "No locations given" << endl; return 2; } if (vm.count("temp")) { cout << "All righty, we'll sort by temperature instead of location" << endl; } return 0; }
Check / and /boot for uuids, not only /.
#include "deviceinfo.h" #include "log/logger.h" #include <QCryptographicHash> #include <QDir> #include <fstab.h> LOGGER(DeviceInfo); DeviceInfo::DeviceInfo() : d(NULL) { } DeviceInfo::~DeviceInfo() { } QString DeviceInfo::deviceId() const { if (int ret = setfsent() != 1) { LOG_ERROR(QString("Error opening fstab: setfsent returned %1").arg(ret)); return QString(); } fstab* tab = getfsfile("/"); if (!tab) { LOG_ERROR("Mount point / not found!"); endfsent(); return QString(); } QByteArray uuid = QByteArray::fromRawData(tab->fs_spec, strlen(tab->fs_spec)); if (uuid.indexOf("UUID=") == 0) { uuid.remove(0, 5); } else { LOG_ERROR(QString("fs_spec does not contain an UUID: %1").arg(QString::fromLatin1(uuid))); } endfsent(); LOG_INFO(QString("HDD UUID: %1").arg(QString::fromLatin1(uuid))); QCryptographicHash hash(QCryptographicHash::Sha224); hash.addData(uuid); return QString::fromLatin1(hash.result().toHex()); }
#include "deviceinfo.h" #include "log/logger.h" #include <QCryptographicHash> #include <QDir> #include <fstab.h> LOGGER(DeviceInfo); namespace { static const char* FSEntries[] = { "/", "/boot", NULL }; } DeviceInfo::DeviceInfo() : d(NULL) { } DeviceInfo::~DeviceInfo() { } QString DeviceInfo::deviceId() const { if (int ret = setfsent() != 1) { LOG_ERROR(QString("Error opening fstab: setfsent returned %1").arg(ret)); return QString(); } QByteArray uuid; for(const char** fsentry=FSEntries; *fsentry != NULL; ++fsentry) { fstab* tab = getfsfile(*fsentry); if (!tab) { continue; } uuid = QByteArray::fromRawData(tab->fs_spec, strlen(tab->fs_spec)); if (uuid.indexOf("UUID=") == 0) { uuid.remove(0, 5); break; } else { uuid.clear(); } } endfsent(); if (uuid.isEmpty()) { LOG_ERROR("No HDD UID found!"); return QString(); } LOG_INFO(QString("HDD UUID: %1").arg(QString::fromLatin1(uuid))); QCryptographicHash hash(QCryptographicHash::Sha224); hash.addData(uuid); return QString::fromLatin1(hash.result().toHex()); }
Add more testcases with longer sentences
#include <iostream> #include "../../Parser/Tagger/converter.h" void testConverter(string sentence); using namespace std; int main() { testConverter("This is a Bear"); testConverter("That is not a building"); /// Bug , comma in dictionary testConverter("Who told you that?"); // testConverter("That's what she said."); return 0; } /** * Test case for Converter class * @param none */ void testConverter(string sentence) { std::cout << "--- Testing Converter -----\n"; try { NLP::Converter converted(sentence); // Passed list<NLP::Word> myParsedWords = converted.getWords(); for(NLP::Word wd: myParsedWords) cout << wd << " : " << wd.getRawtypes() << endl; } catch (const char* e) { cout << "something went wrong : " << "Converter" << endl; } cout << "-------- End of Converter test case -----\n\n"; } /** BUG * STokenize may not map all characters, if new character is found, just add * it to the token.h (UNKNOWN Token feature not working) */
#include <iostream> #include "../../Parser/Tagger/converter.h" void testConverter(string sentence); using namespace std; int main() { testConverter("This is a Bear"); testConverter("That is not a building"); /// Bug , comma in dictionary testConverter("Who told you that?"); testConverter("That's what she said."); testConverter("In general, the dative marks the indirect object of a verb, although in some instances, the dative is used for the direct object of a verb pertaining directly to an act of giving something"); testConverter("These pronouns are not proper datives anymore in modern English, because they are also used for functions of the accusative."); return 0; } /** * Test case for Converter class * @param none */ void testConverter(string sentence) { std::cout << "--- Testing Converter -----\n"; try { NLP::Converter converted(sentence); // Passed list<NLP::Word> myParsedWords = converted.getWords(); for(NLP::Word wd: myParsedWords) cout << wd << " : " << wd.getRawtypes() << endl; } catch (const char* e) { cout << "something went wrong : " << "Converter" << endl; } cout << "-------- End of Converter test case -----\n\n"; } /** BUG * STokenize may not map all characters, if new character is found, just add * it to the token.h (UNKNOWN Token feature not working) */
Create and destroy two windows
#include "demo/system/precompiled.h" #if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS) #include <windows.h> #endif int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow) { /* Just the get this to compile for now */ (void*)hInstance; (void*)hPrevInstance; (void*)pScmdline; --iCmdshow; return 0; }
#include "demo/system/precompiled.h" #include "engine/system/system.h" DEA_START() #if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS) #include <windows.h> int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show) { /* Just the get this to compile for now */ (void*)hinstance; (void*)prev_instance; (void*)cmd_line; --cmd_show; const bool fullscreen = false; window windows[2]; create_window(1280, 720, 0.5f, 0.5f, L"Engine", fullscreen, windows[0]); create_window(600, 400, 0.0f, 0.0f, L"Editor", fullscreen, windows[1]); focus_window(windows[0]); run(); destroy_window(windows[0], fullscreen); destroy_window(windows[1], fullscreen); return 0; } #else #error No Main for current platform #endif DEA_END()
Read initial commands from file
#include <iostream> #include <memory> #include <boost/interprocess/ipc/message_queue.hpp> #include "messageQueue.h" using namespace boost::interprocess; int main() { std::unique_ptr<message_queue> mq = nullptr; try { mq = std::make_unique<message_queue>(open_only, mqName); } catch (std::exception const&){ std::cout << "Couldn't connect to the game. Make sure the game is running and try again." << std::endl; std::cout << "Press any key..." << std::endl; std::getchar(); return 0; } std::string msg; for (;;) { std::getline(std::cin, msg); if (msg == "quit") { return 0; } mq->send(msg.data(), msg.size(), 0); } }
#include <iostream> #include <memory> #include <fstream> #include <boost/interprocess/ipc/message_queue.hpp> #include "messageQueue.h" using namespace boost::interprocess; int main() { std::unique_ptr<message_queue> mq = nullptr; try { mq = std::make_unique<message_queue>(open_only, mqName); } catch (std::exception const&){ std::cout << "Couldn't connect to the game. Make sure the game is running and try again." << std::endl; std::cout << "Press any key..." << std::endl; std::getchar(); return 0; } { std::ifstream initFile("vttainit.ini"); if (initFile.good()) { std::string msg; while (std::getline(initFile, msg)) { std::cout << msg << std::endl; if (msg == "quit") { return 0; } mq->send(msg.data(), msg.size(), 0); } } } std::string msg; for (;;) { std::getline(std::cin, msg); if (msg == "quit") { return 0; } mq->send(msg.data(), msg.size(), 0); } }
Use strtoll like strtoimax on Interix.
#include <inttypes.h> #include <stdlib.h> #include <config/config_type_int.h> ConfigTypeInt config_type_int; bool ConfigTypeInt::set(ConfigValue *cv, const std::string& vstr) { if (ints_.find(cv) != ints_.end()) return (false); const char *str = vstr.c_str(); char *endp; intmax_t imax; imax = strtoimax(str, &endp, 0); if (*endp != '\0') return (false); ints_[cv] = imax; return (true); }
#if !defined(__OPENNT) #include <inttypes.h> #endif #include <stdlib.h> #include <config/config_type_int.h> ConfigTypeInt config_type_int; bool ConfigTypeInt::set(ConfigValue *cv, const std::string& vstr) { if (ints_.find(cv) != ints_.end()) return (false); const char *str = vstr.c_str(); char *endp; intmax_t imax; #if !defined(__OPENNT) imax = strtoimax(str, &endp, 0); #else imax = strtoll(str, &endp, 0); #endif if (*endp != '\0') return (false); ints_[cv] = imax; return (true); }
Add testcase for PR16134, which no longer crashes with ToT.
// RUN: %clang_cc1 -fsyntax-only -verify %s // Clang used to crash trying to recover while adding 'this->' before Work(x); template <typename> struct A { static void Work(int); // expected-note{{must qualify identifier}} }; template <typename T> struct B : public A<T> { template <typename T2> B(T2 x) { Work(x); // expected-error{{use of undeclared identifier}} } }; void Test() { B<int> b(0); // expected-note{{in instantiation of function template}} }
// RUN: %clang_cc1 -fsyntax-only -verify %s // Clang used to crash trying to recover while adding 'this->' before Work(x); template <typename> struct A { static void Work(int); // expected-note{{must qualify identifier}} }; template <typename T> struct B : public A<T> { template <typename T2> B(T2 x) { Work(x); // expected-error{{use of undeclared identifier}} } }; void Test() { B<int> b(0); // expected-note{{in instantiation of function template}} } // Don't crash here. namespace PR16134 { template <class P> struct S // expected-error {{expected ';'}} template <> static S<Q>::f() // expected-error +{{}} }
Make it compile on newer Annwvyn version
#include "stdafx.h" #include "myLevel.hpp" MyLevel::MyLevel() : AnnAbstractLevel() { } void MyLevel::load() { //For having a lighter syntax : auto engine(AnnEngine::Instance()); //Load Sinbad: auto Sinbad (engine->createGameObject("Sinbad.mesh")); Sinbad->setUpPhysics(100, phyShapeType::boxShape); //Add it to the level list levelContent.push_back(Sinbad); //Load Ground: auto Ground (engine->createGameObject("Ground.mesh")); Ground->setPos(0,-2,0); Ground->setUpPhysics(); //Add it to the level list levelContent.push_back(Ground); //Create a light source auto light(engine->addLight()); light->setPosition(0,1,3); //Add it to the level lst levelLighting.push_back(light); engine->setAmbiantLight(Ogre::ColourValue::White/2); } void MyLevel::runLogic() { }
#include "stdafx.h" #include "myLevel.hpp" MyLevel::MyLevel() : AnnAbstractLevel() { } void MyLevel::load() { //For having a lighter syntax : auto engine(AnnEngine::Instance()); //Load Sinbad: auto Sinbad (engine->createGameObject("Sinbad.mesh")); Sinbad->setUpPhysics(100, phyShapeType::boxShape); //Add it to the level list levelContent.push_back(Sinbad); //Load Ground: auto Ground (engine->createGameObject("Ground.mesh")); Ground->setPos(0,-2,0); Ground->setUpPhysics(); //Add it to the level list levelContent.push_back(Ground); //Create a light source auto light(engine->addLight()); light->setPosition(AnnVect3(0,1,3)); //Add it to the level lst levelLighting.push_back(light); engine->setAmbiantLight(Ogre::ColourValue::White/2); } void MyLevel::runLogic() { }
Add an optional device_id command line argument.
#include <cuda_runtime_api.h> #include <stdio.h> int main(void) { int num_devices = 0; cudaGetDeviceCount(&num_devices); if(num_devices > 0) { cudaDeviceProp properties; cudaGetDeviceProperties(&properties, 0); printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor); return 0; } // end if return -1; }
#include <cuda_runtime_api.h> #include <stdio.h> #include <stdlib.h> void usage(const char *name) { printf("usage: %s [device_id]\n", name); } int main(int argc, char **argv) { int num_devices = 0; int device_id = 0; if(argc == 2) { device_id = atoi(argv[1]); } else if(argc > 2) { usage(argv[0]); exit(-1); } cudaGetDeviceCount(&num_devices); if(num_devices > device_id) { cudaDeviceProp properties; cudaGetDeviceProperties(&properties, device_id); printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor); return 0; } // end if else { printf("No available device with id %d\n", device_id); } return -1; }
Remove using since it is unnecessary.
#include <iostream> #include "demo/demo.h" int main() { using namespace demo; // create demo Demo demo; // run demo demo.startup(); demo.run(); demo.shutdown(); return 0; }
#include <iostream> #include "demo/demo.h" int main() { // create demo demo::Demo demo; // run demo demo.startup(); demo.run(); demo.shutdown(); return 0; }
Add a header check to the sensord configure test.
#include <sensormanagerinterface.h> int main() { SensorManagerInterface* m_remoteSensorManager; m_remoteSensorManager = &SensorManagerInterface::instance(); return 0; }
#include <sensormanagerinterface.h> #include <datatypes/magneticfield.h> int main() { SensorManagerInterface* m_remoteSensorManager; m_remoteSensorManager = &SensorManagerInterface::instance(); return 0; }
Remove a ; from after a pre-processor directive
/* -*- mode:linux -*- */ /** * \file completion_counter.cc * * * * \author Ethan Burns * \date 2008-10-24 */ #include <pthread.h> #include "completion_counter.h" #include <iostream>; CompletionCounter::CompletionCounter(unsigned int max) : counter(0), max(max) { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); } void CompletionCounter::complete(void) { pthread_mutex_lock(&mutex); counter += 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } /** * Wait for all the completions. (counter == max) */ void CompletionCounter::wait(void) { pthread_mutex_lock(&mutex); while (counter < max) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); }
/* -*- mode:linux -*- */ /** * \file completion_counter.cc * * * * \author Ethan Burns * \date 2008-10-24 */ #include <pthread.h> #include "completion_counter.h" #include <iostream> CompletionCounter::CompletionCounter(unsigned int max) : counter(0), max(max) { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); } void CompletionCounter::complete(void) { pthread_mutex_lock(&mutex); counter += 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } /** * Wait for all the completions. (counter == max) */ void CompletionCounter::wait(void) { pthread_mutex_lock(&mutex); while (counter < max) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); }
Introduce the structure of the optimizer
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "tac/Optimizer.hpp" using namespace eddic; void tac::Optimizer::optimize(tac::Program& program) const { //TODO }
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <boost/variant.hpp> #include "tac/Optimizer.hpp" #include "tac/Program.hpp" using namespace eddic; namespace { struct ArithmeticIdentities : public boost::static_visitor<tac::Statement> { template<typename T> tac::Statement operator()(T& statement) const { return statement; } }; } template<typename Visitor> void apply_to_all(Visitor visitor, tac::Program& program){ for(auto& function : program.functions){ for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ statement = boost::apply_visitor(visitor, statement); } } } } void tac::Optimizer::optimize(tac::Program& program) const { ArithmeticIdentities identities; apply_to_all(identities, program); }
Clean up test a bit
#include <iostream> #include <gtest/gtest.h> #include <mongo/bson/bson.h> #include <mongo/client/dbclient.h> namespace { // Check that we can reproduce the example from bsonspec.org TEST(OID, gen) { const mongo::OID anOid = mongo::OID::gen(); } } // namespace
#include <gtest/gtest.h> #include <mongo/bson/bson.h> namespace { TEST(OID, gen) { const mongo::OID oid1 = mongo::OID::gen(); const mongo::OID oid2 = mongo::OID::gen(); EXPECT_NE(oid1, oid2); } } // namespace
Fix leaking QML global object on engine termination.
#include <QtDebug> #include "hsqml.h" #include "HsQMLManager.h" #include "HsQMLEngine.h" #include "HsQMLObject.h" #include "HsQMLWindow.h" HsQMLEngine::HsQMLEngine(HsQMLEngineConfig& config) { mEngine.rootContext()->setContextObject(config.globalObject->object()); HsQMLWindow* win = new HsQMLWindow(this); win->setSource(config.initialURL); win->setVisible(true); mWindows.insert(win); } HsQMLEngine::~HsQMLEngine() { } QDeclarativeEngine* HsQMLEngine::engine() { return &mEngine; } extern "C" void hsqml_create_engine( HsQMLObjectHandle* globalObject, const char* initialURL) { HsQMLEngineConfig config; config.globalObject = (HsQMLObjectProxy*)globalObject; config.initialURL = QUrl(QString(initialURL)); Q_ASSERT (gManager); QMetaObject::invokeMethod( gManager, "createEngine", Qt::QueuedConnection, Q_ARG(HsQMLEngineConfig, config)); }
#include <QtDebug> #include "hsqml.h" #include "HsQMLManager.h" #include "HsQMLEngine.h" #include "HsQMLObject.h" #include "HsQMLWindow.h" HsQMLEngine::HsQMLEngine(HsQMLEngineConfig& config) { // Obtain, re-parent, and set QML global object QObject* globalObject = config.globalObject->object(); globalObject->setParent(this); mEngine.rootContext()->setContextObject(globalObject); // Create window HsQMLWindow* win = new HsQMLWindow(this); win->setSource(config.initialURL); win->setVisible(true); mWindows.insert(win); } HsQMLEngine::~HsQMLEngine() { } QDeclarativeEngine* HsQMLEngine::engine() { return &mEngine; } extern "C" void hsqml_create_engine( HsQMLObjectHandle* globalObject, const char* initialURL) { HsQMLEngineConfig config; config.globalObject = (HsQMLObjectProxy*)globalObject; config.initialURL = QUrl(QString(initialURL)); Q_ASSERT (gManager); QMetaObject::invokeMethod( gManager, "createEngine", Qt::QueuedConnection, Q_ARG(HsQMLEngineConfig, config)); }
Make test pass in Release builds, IR names don't get emitted there.
// RUN: %clang_cc1 -emit-llvm -triple=le32-unknown-nacl -o - %s | FileCheck %s int f(); // Test that PNaCl uses the Itanium/x86 ABI in which the static // variable's guard variable is tested via "load i8 and compare with // zero" rather than the ARM ABI which uses "load i32 and test the // bottom bit". void g() { static int a = f(); } // CHECK: load atomic i8* bitcast (i64* @_ZGVZ1gvE1a to i8*) acquire // CHECK-NEXT: %guard.uninitialized = icmp eq i8 %0, 0 // CHECK-NEXT: br i1 %guard.uninitialized, label %init.check, label %init.end
// RUN: %clang_cc1 -emit-llvm -triple=le32-unknown-nacl -o - %s | FileCheck %s int f(); // Test that PNaCl uses the Itanium/x86 ABI in which the static // variable's guard variable is tested via "load i8 and compare with // zero" rather than the ARM ABI which uses "load i32 and test the // bottom bit". void g() { static int a = f(); } // CHECK: [[LOAD:%.*]] = load atomic i8* bitcast (i64* @_ZGVZ1gvE1a to i8*) acquire // CHECK-NEXT: [[GUARD:%.*]] = icmp eq i8 [[LOAD]], 0 // CHECK-NEXT: br i1 [[GUARD]]
Add some more flag support to unix command line tool...
#include <stdlib.h> #include <stdio.h> #include "TexComp.h" int main(int argc, char **argv) { if(argc != 2) { fprintf(stderr, "Usage: %s <imagefile>\n", argv[0]); exit(1); } ImageFile file (argv[1]); SCompressionSettings settings; CompressedImage *ci = CompressImage(file, settings); // Cleanup delete ci; return 0; }
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "TexComp.h" void PrintUsage() { fprintf(stderr, "Usage: tc [-s|-t <num>] <imagefile>\n"); } int main(int argc, char **argv) { int fileArg = 1; int quality = 50; int numThreads = 1; bool bUseSIMD = false; bool knowArg = false; do { knowArg = false; if(strcmp(argv[fileArg], "-s") == 0) { fileArg++; bUseSIMD = true; knowArg = true; } if(strcmp(argv[fileArg], "-t") == 0) { fileArg++; if(fileArg == argc || (numThreads = atoi(argv[fileArg])) < 1) { PrintUsage(); exit(1); } fileArg++; knowArg = true; } if(strcmp(argv[fileArg], "-q") == 0) { fileArg++; if(fileArg == argc || (quality = atoi(argv[fileArg])) < 1) { PrintUsage(); exit(1); } fileArg++; knowArg = true; } } while(knowArg); if(fileArg == argc) { PrintUsage(); exit(1); } ImageFile file (argv[fileArg]); SCompressionSettings settings; settings.bUseSIMD = bUseSIMD; settings.iNumThreads = numThreads; CompressedImage *ci = CompressImage(file, settings); // Cleanup delete ci; return 0; }
Change the smearing test values to non-zero
/** * @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetSmearingFunctionsTest.cpp */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetSmearingFunctionsTest #include <boost/test/unit_test.hpp> #include "JPetSmearingFunctions/JPetSmearingFunctions.h" BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE(testOne) { JPetHitExperimentalParametrizer parametrizer; parametrizer.addEnergySmearing(0,0,0); parametrizer.addZHitSmearing(0,0,0); parametrizer.addTimeSmearing(0,0,0,0); } BOOST_AUTO_TEST_SUITE_END()
/** * @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetSmearingFunctionsTest.cpp */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetSmearingFunctionsTest #include <boost/test/unit_test.hpp> #include "JPetSmearingFunctions/JPetSmearingFunctions.h" BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE(testOne) { JPetHitExperimentalParametrizer parametrizer; parametrizer.addEnergySmearing(1,1,1); parametrizer.addZHitSmearing(1,1,1); parametrizer.addTimeSmearing(1,1,1,1); } BOOST_AUTO_TEST_SUITE_END()
Clear reachable tiles at the end of turn
// See LICENSE file for copyright and license details. #include "ui/event/end_turn.hpp" #include <cassert> #include <SDL/SDL_opengl.h> #include "core/misc.hpp" #include "core/v2i.hpp" #include "core/dir.hpp" #include "core/core.hpp" #include "core/path.hpp" #include "ui/v2f.hpp" #include "ui/vertex_array.hpp" #include "ui/game.hpp" EventEndTurnVisualizer::EventEndTurnVisualizer(Game& game, const Event& event) : EventVisualizer(game), mEventEndTurn(dynamic_cast<const EventEndTurn&>(event)) { } EventEndTurnVisualizer::~EventEndTurnVisualizer() { } int EventEndTurnVisualizer::framesCount() { return 0; } bool EventEndTurnVisualizer::isUnitVisible(const Unit& u) { UNUSED(u); return false; } void EventEndTurnVisualizer::draw() { // die("TODO"); // TODO: ... } void EventEndTurnVisualizer::end() { game().core().calculateFow(); game().setVaFogOfWar(game().buildFowArray()); }
// See LICENSE file for copyright and license details. #include "ui/event/end_turn.hpp" #include <cassert> #include <SDL/SDL_opengl.h> #include "core/misc.hpp" #include "core/v2i.hpp" #include "core/dir.hpp" #include "core/core.hpp" #include "core/path.hpp" #include "ui/v2f.hpp" #include "ui/vertex_array.hpp" #include "ui/game.hpp" EventEndTurnVisualizer::EventEndTurnVisualizer(Game& game, const Event& event) : EventVisualizer(game), mEventEndTurn(dynamic_cast<const EventEndTurn&>(event)) { } EventEndTurnVisualizer::~EventEndTurnVisualizer() { } int EventEndTurnVisualizer::framesCount() { return 0; } bool EventEndTurnVisualizer::isUnitVisible(const Unit& u) { UNUSED(u); return false; } void EventEndTurnVisualizer::draw() { // die("TODO"); // TODO: ... } void EventEndTurnVisualizer::end() { game().core().calculateFow(); game().setVaFogOfWar(game().buildFowArray()); game().setVaWalkableMap(VertexArray()); }
Add a comment which explains why the assert fired and how to fix it.
//===- llvm/VMCore/TargetTransformInfo.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/TargetTransformInfo.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; /// Default ctor. /// /// @note This has to exist, because this is a pass, but it should never be /// used. TargetTransformInfo::TargetTransformInfo() : ImmutablePass(ID) { report_fatal_error("Bad TargetTransformInfo ctor used. " "Tool did not specify a TargetTransformInfo to use?"); } INITIALIZE_PASS(TargetTransformInfo, "TargetTransformInfo", "Target Transform Info", false, true) char TargetTransformInfo::ID = 0;
//===- llvm/VMCore/TargetTransformInfo.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/TargetTransformInfo.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; /// Default ctor. /// /// @note This has to exist, because this is a pass, but it should never be /// used. TargetTransformInfo::TargetTransformInfo() : ImmutablePass(ID) { /// You are seeing this error because your pass required the TTI /// using a call to "getAnalysis<TargetTransformInfo>()", and you did /// not initialize a machine target which can provide the TTI. /// You should use "getAnalysisIfAvailable<TargetTransformInfo>()" instead. report_fatal_error("Bad TargetTransformInfo ctor used. " "Tool did not specify a TargetTransformInfo to use?"); } INITIALIZE_PASS(TargetTransformInfo, "TargetTransformInfo", "Target Transform Info", false, true) char TargetTransformInfo::ID = 0;
Add unit test for isLayoutIdentical(empty, empty). It was previously asserting in Visual C++ debug mode on a null iterator passed to std::equal.
//===- llvm/unittest/IR/TypesTest.cpp - Type unit tests -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(TypesTest, StructType) { LLVMContext C; // PR13522 StructType *Struct = StructType::create(C, "FooBar"); EXPECT_EQ("FooBar", Struct->getName()); Struct->setName(Struct->getName().substr(0, 3)); EXPECT_EQ("Foo", Struct->getName()); Struct->setName(""); EXPECT_TRUE(Struct->getName().empty()); EXPECT_FALSE(Struct->hasName()); } } // end anonymous namespace
//===- llvm/unittest/IR/TypesTest.cpp - Type unit tests -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(TypesTest, StructType) { LLVMContext C; // PR13522 StructType *Struct = StructType::create(C, "FooBar"); EXPECT_EQ("FooBar", Struct->getName()); Struct->setName(Struct->getName().substr(0, 3)); EXPECT_EQ("Foo", Struct->getName()); Struct->setName(""); EXPECT_TRUE(Struct->getName().empty()); EXPECT_FALSE(Struct->hasName()); } TEST(TypesTest, LayoutIdenticalEmptyStructs) { LLVMContext C; StructType *Foo = StructType::create(C, "Foo"); StructType *Bar = StructType::create(C, "Bar"); EXPECT_TRUE(Foo->isLayoutIdentical(Bar)); } } // end anonymous namespace
Change NOTREACHED for a LOG(WARNING) when we can't delete the cache. This should help the unit tests.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/cache_util.h" #include "base/file_util.h" #include "base/logging.h" #include "base/string_util.h" namespace disk_cache { bool MoveCache(const FilePath& from_path, const FilePath& to_path) { // Just use the version from base. return file_util::Move(from_path, to_path); } void DeleteCache(const FilePath& path, bool remove_folder) { file_util::FileEnumerator iter(path, /* recursive */ false, file_util::FileEnumerator::FILES); for (FilePath file = iter.Next(); !file.value().empty(); file = iter.Next()) { if (!file_util::Delete(file, /* recursive */ false)) NOTREACHED(); } if (remove_folder) { if (!file_util::Delete(path, /* recursive */ false)) NOTREACHED(); } } bool DeleteCacheFile(const FilePath& name) { return file_util::Delete(name, false); } } // namespace disk_cache
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/cache_util.h" #include "base/file_util.h" #include "base/logging.h" #include "base/string_util.h" namespace disk_cache { bool MoveCache(const FilePath& from_path, const FilePath& to_path) { // Just use the version from base. return file_util::Move(from_path, to_path); } void DeleteCache(const FilePath& path, bool remove_folder) { file_util::FileEnumerator iter(path, /* recursive */ false, file_util::FileEnumerator::FILES); for (FilePath file = iter.Next(); !file.value().empty(); file = iter.Next()) { if (!file_util::Delete(file, /* recursive */ false)) { LOG(WARNING) << "Unable to delete cache."; return; } } if (remove_folder) { if (!file_util::Delete(path, /* recursive */ false)) { LOG(WARNING) << "Unable to delete cache folder."; return; } } } bool DeleteCacheFile(const FilePath& name) { return file_util::Delete(name, false); } } // namespace disk_cache
Fix linting errors in FrustumOptimizer.
#include "./frustum_optimizer.h" #include "./nodes.h" FrustumOptimizer::FrustumOptimizer(std::shared_ptr<Nodes> nodes) : nodes(nodes) { } void FrustumOptimizer::update(Eigen::Matrix4f viewMatrix) { float min = std::numeric_limits<float>::max(); float max = -min; for (auto node : nodes->getNodes()) { auto obb = node->getObb(); if (!obb.get()) continue; for (int i = 0; i < 8; ++i) { auto point = obb->corners[i]; Eigen::Vector4f transformed = mul(viewMatrix, point); if (transformed.z() < min) min = transformed.z(); if (transformed.z() > max) max = transformed.z(); } } near = std::max(0.1f, -max - 0.1f); far = -min + 0.1f; } float FrustumOptimizer::getNear() { return near; } float FrustumOptimizer::getFar() { return far; }
#include "./frustum_optimizer.h" #include <limits> #include <algorithm> #include "./nodes.h" FrustumOptimizer::FrustumOptimizer(std::shared_ptr<Nodes> nodes) : nodes(nodes) { } void FrustumOptimizer::update(Eigen::Matrix4f viewMatrix) { float min = std::numeric_limits<float>::max(); float max = -min; for (auto node : nodes->getNodes()) { auto obb = node->getObb(); if (!obb.get()) continue; for (int i = 0; i < 8; ++i) { auto point = obb->corners[i]; Eigen::Vector4f transformed = mul(viewMatrix, point); if (transformed.z() < min) min = transformed.z(); if (transformed.z() > max) max = transformed.z(); } } near = std::max(0.1f, -max - 0.1f); far = -min + 0.1f; } float FrustumOptimizer::getNear() { return near; } float FrustumOptimizer::getFar() { return far; }
Make directory exceptions more usable
#include <dirent.h> #include "../../../../runtime/types/InternalTypes.h" void DirectoryType::__constructor__() { auto self = Program::create<DirectoryInstance>(); auto file_path = Program::argument<TextInstance>(); self->file_path = file_path->text(); Program::push(self); } void DirectoryType::contents() { auto self = Program::argument<DirectoryInstance>(); auto contents = Program::create<ListInstance>(); auto directory = opendir(self->file_path.c_str()); if (directory == nullptr) { throw Program::create<ExceptionInstance>(Program::create<TextInstance>("Cannot read directory contents")); } while(auto entry = readdir(directory)) { contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type))); } Program::push(contents); } std::string DirectoryInstance::text() { return "Directory(" + this->file_path + ")"; } bool DirectoryInstance::boolean() { return true; }
#include <dirent.h> #include "../../../../runtime/types/InternalTypes.h" void DirectoryType::__constructor__() { auto self = Program::create<DirectoryInstance>(); auto file_path = Program::argument<TextInstance>(); self->file_path = file_path->text(); Program::push(self); } void DirectoryType::contents() { auto self = Program::argument<DirectoryInstance>(); auto contents = Program::create<ListInstance>(); auto directory = opendir(self->file_path.c_str()); if (directory == nullptr) { throw Program::create<ExceptionInstance>(Program::create<TextInstance>("Cannot read file list of directory " + self->file_path)); } while(auto entry = readdir(directory)) { contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type))); } Program::push(contents); } std::string DirectoryInstance::text() { return "Directory(" + this->file_path + ")"; } bool DirectoryInstance::boolean() { return true; }
Add missing header for windows.
/** ** \file libport/perror.cc ** \brief perror: implements file libport/perror.hh */ #include <cstdio> #include <iostream> #include "libport/cstring" namespace libport { void perror (const char* s) { #ifndef WIN32 ::perror(s); #else int errnum; const char* errstring; const char* colon; errnum = WSAGetLastError(); errstring = strerror(errnum); if (s == NULL || *s == '\0') s = colon = ""; else colon = ": "; std::cerr << s << colon << errstring << std::endl; #endif } }
/** ** \file libport/perror.cc ** \brief perror: implements file libport/perror.hh */ #include <cstdio> #include <iostream> #include "libport/windows.hh" #include "libport/cstring" namespace libport { void perror (const char* s) { #ifndef WIN32 ::perror(s); #else int errnum; const char* errstring; const char* colon; errnum = WSAGetLastError(); errstring = strerror(errnum); if (s == NULL || *s == '\0') s = colon = ""; else colon = ": "; std::cerr << s << colon << errstring << std::endl; #endif } }
Use CHECK-DAG in a test so that it isn't sensitive to metadata order.
// RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s // Test that the line table info for Foo<T>::bar() is pointing to the // right header file. // CHECK: define{{.*}}bar // CHECK-NOT: define // CHECK: ret {{.*}}, !dbg ![[DBG:.*]] // CHECK: ![[HPP:.*]] = metadata !{metadata !"./template.hpp", // CHECK:![[BLOCK:.*]] = metadata !{{{.*}}, metadata ![[HPP]], {{.*}}} ; [ DW_TAG_lexical_block ] // CHECK: [[DBG]] = metadata !{i32 23, i32 0, metadata ![[BLOCK]], null} # 1 "./template.h" 1 template <typename T> class Foo { public: int bar(); }; # 21 "./template.hpp" template <typename T> int Foo<T>::bar() { } int main (int argc, const char * argv[]) { Foo<int> f; f.bar(); }
// RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s // Test that the line table info for Foo<T>::bar() is pointing to the // right header file. // CHECK: define{{.*}}bar // CHECK-NOT: define // CHECK: ret {{.*}}, !dbg ![[DBG:.*]] // CHECK-DAG: ![[HPP:.*]] = metadata !{metadata !"./template.hpp", // CHECK-DAG: ![[BLOCK:.*]] = metadata !{{{.*}}, metadata ![[HPP]], {{.*}}} ; [ DW_TAG_lexical_block ] // CHECK-DAG: ![[DBG]] = metadata !{i32 23, i32 0, metadata ![[BLOCK]], null} # 1 "./template.h" 1 template <typename T> class Foo { public: int bar(); }; # 21 "./template.hpp" template <typename T> int Foo<T>::bar() { } int main (int argc, const char * argv[]) { Foo<int> f; f.bar(); }
Fix an issue found by purify with my previous submission.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "config.h" #include "webkit/glue/resource_loader_bridge.h" #include "net/http/http_response_headers.h" namespace webkit_glue { ResourceLoaderBridge::ResponseInfo::ResponseInfo() { content_length = -1; #if defined(OS_WIN) response_data_file = base::kInvalidPlatformFileValue; #elif defined(OS_POSIX) response_data_file.fd = base::kInvalidPlatformFileValue; response_data_file.auto_close = false; #endif } ResourceLoaderBridge::ResponseInfo::~ResponseInfo() { } ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() { } ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() { } ResourceLoaderBridge::ResourceLoaderBridge() { } ResourceLoaderBridge::~ResourceLoaderBridge() { } } // namespace webkit_glue
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "config.h" #include "webkit/glue/resource_loader_bridge.h" #include "webkit/glue/webappcachecontext.h" #include "net/http/http_response_headers.h" namespace webkit_glue { ResourceLoaderBridge::ResponseInfo::ResponseInfo() { content_length = -1; app_cache_id = WebAppCacheContext::kNoAppCacheId; #if defined(OS_WIN) response_data_file = base::kInvalidPlatformFileValue; #elif defined(OS_POSIX) response_data_file.fd = base::kInvalidPlatformFileValue; response_data_file.auto_close = false; #endif } ResourceLoaderBridge::ResponseInfo::~ResponseInfo() { } ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() { } ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() { } ResourceLoaderBridge::ResourceLoaderBridge() { } ResourceLoaderBridge::~ResourceLoaderBridge() { } } // namespace webkit_glue
Mark main with a default visibility.
// Microsoft compiler does not allow main to be in a library. // So we define one here. #include <urbi/umain.hh> int main(int argc, const char* argv[]) { return urbi::main(argc, argv); }
// Microsoft compiler does not allow main to be in a library. // So we define one here. #include <urbi/umain.hh> #include <libport/detect-win32.h> #ifndef WIN32 __attribute__((visibility("default"))) #endif int main(int argc, const char* argv[]) { return urbi::main(argc, argv); }
Use --silent instead of --nolog to disable logs
#include "cli.h" #include "../definitions.h" bool flag_set(char** begin, char** end, const std::string& long_option) { return std::find(begin, end, long_option) != end; } Options get_options(int argc, char* argv[]) { char** begin = argv; char** end = argv + argc; if (argc < 2) { fatal_error("Please provide a ROM file to run"); } bool debugger = flag_set(begin, end, "--debug"); bool trace = flag_set(begin, end, "--trace"); bool disable_logs = flag_set(begin, end, "--nolog"); bool headless = flag_set(begin, end, "--headless"); bool show_full_framebuffer = flag_set(begin, end, "--full-framebuffer"); bool exit_on_infinite_jr = flag_set(begin, end, "--exit-on-infinite-jr"); std::string filename = argv[1]; return Options { debugger, trace, disable_logs, headless, show_full_framebuffer, exit_on_infinite_jr, filename }; } LogLevel get_log_level(Options& options) { if (options.disable_logs) return LogLevel::Error; auto log_level = options.trace ? LogLevel::Trace : LogLevel::Debug; return log_level; }
#include "cli.h" #include "../definitions.h" bool flag_set(char** begin, char** end, const std::string& long_option) { return std::find(begin, end, long_option) != end; } Options get_options(int argc, char* argv[]) { char** begin = argv; char** end = argv + argc; if (argc < 2) { fatal_error("Please provide a ROM file to run"); } bool debugger = flag_set(begin, end, "--debug"); bool trace = flag_set(begin, end, "--trace"); bool disable_logs = flag_set(begin, end, "--silent"); bool headless = flag_set(begin, end, "--headless"); bool show_full_framebuffer = flag_set(begin, end, "--full-framebuffer"); bool exit_on_infinite_jr = flag_set(begin, end, "--exit-on-infinite-jr"); std::string filename = argv[1]; return Options { debugger, trace, disable_logs, headless, show_full_framebuffer, exit_on_infinite_jr, filename }; } LogLevel get_log_level(Options& options) { if (options.disable_logs) return LogLevel::Error; auto log_level = options.trace ? LogLevel::Trace : LogLevel::Debug; return log_level; }
Fix follow-up compilation error raised due to warnings treated as errors
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSUIActivator.h" #include "QmitkUSControlsCustomVideoDeviceWidget.h" #include "QmitkUSControlsCustomDiPhASDeviceWidget.h" mitk::USUIActivator::USUIActivator() { } mitk::USUIActivator::~USUIActivator() { } void mitk::USUIActivator::Load(us::ModuleContext* context) { m_USCustomWidgets.push_back(new QmitkUSControlsCustomVideoDeviceWidget()); m_USCustomWidgets.push_back(new QmitkUSControlsCustomDiPhASDeviceWidget()); } void mitk::USUIActivator::Unload(us::ModuleContext* /*context*/) { for (auto &elem : m_USCustomWidgets) { delete elem; } }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSUIActivator.h" #include "QmitkUSControlsCustomVideoDeviceWidget.h" #include "QmitkUSControlsCustomDiPhASDeviceWidget.h" mitk::USUIActivator::USUIActivator() { } mitk::USUIActivator::~USUIActivator() { } void mitk::USUIActivator::Load(us::ModuleContext* /*context*/) { m_USCustomWidgets.push_back(new QmitkUSControlsCustomVideoDeviceWidget()); m_USCustomWidgets.push_back(new QmitkUSControlsCustomDiPhASDeviceWidget()); } void mitk::USUIActivator::Unload(us::ModuleContext* /*context*/) { for (auto &elem : m_USCustomWidgets) { delete elem; } }
Fix my busted FileCheck invocation
// RUN: not %clang_cc1 %s -fno-rtti -triple=i686-pc-win32 -emit-llvm -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK32 // RUN: %clang_cc1 %s -fno-rtti -triple=x86_64-pc-win32 -emit-llvm -o - | FileCheck --check-prefix=CHECK64 namespace byval_thunk { struct Agg { Agg(); Agg(const Agg &); ~Agg(); int x; }; struct A { virtual void foo(Agg x); }; struct B { virtual void foo(Agg x); }; struct C : A, B { virtual void foo(Agg x); }; C c; // CHECK32: cannot compile this non-trivial argument copy for thunk yet // CHECK64-LABEL: define linkonce_odr void @"\01?foo@C@byval_thunk@@W7EAAXUAgg@2@@Z" // CHECK64: (%"struct.byval_thunk::C"* %this, %"struct.byval_thunk::Agg"* %x) // CHECK64: getelementptr i8* %{{.*}}, i32 -8 // CHECK64: call void @"\01?foo@C@byval_thunk@@UEAAXUAgg@2@@Z"(%"struct.byval_thunk::C"* %2, %"struct.byval_thunk::Agg"* %x) // CHECK64-NOT: call // CHECK64: ret void }
// RUN: not %clang_cc1 %s -fno-rtti -triple=i686-pc-win32 -emit-llvm -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK32 %s // RUN: %clang_cc1 %s -fno-rtti -triple=x86_64-pc-win32 -emit-llvm -o - | FileCheck --check-prefix=CHECK64 %s namespace byval_thunk { struct Agg { Agg(); Agg(const Agg &); ~Agg(); int x; }; struct A { virtual void foo(Agg x); }; struct B { virtual void foo(Agg x); }; struct C : A, B { virtual void foo(Agg x); }; C c; // CHECK32: cannot compile this non-trivial argument copy for thunk yet // CHECK64-LABEL: define linkonce_odr void @"\01?foo@C@byval_thunk@@W7EAAXUAgg@2@@Z" // CHECK64: (%"struct.byval_thunk::C"* %this, %"struct.byval_thunk::Agg"* %x) // CHECK64: getelementptr i8* %{{.*}}, i32 -8 // CHECK64: call void @"\01?foo@C@byval_thunk@@UEAAXUAgg@2@@Z"(%"struct.byval_thunk::C"* %2, %"struct.byval_thunk::Agg"* %x) // CHECK64-NOT: call // CHECK64: ret void }
Remove confusing transpose() in setLinSpaced() docs.
VectorXf v; v.setLinSpaced(5,0.5f,1.5f).transpose(); cout << v << endl;
VectorXf v; v.setLinSpaced(5,0.5f,1.5f); cout << v << endl;
Add additional indlude files for future tests
#include <iostream> using namespace std; #include <QCoreApplication> #include <QDebug> #include <QTest> #include "test_canpie_timestamp.hpp" #include "test_qcan_frame.hpp" #include "test_qcan_socket.hpp" int main(int argc, char *argv[]) { int32_t slResultT; cout << "#===========================================================\n"; cout << "# Run test cases for QCan classes \n"; cout << "# \n"; cout << "#===========================================================\n"; cout << "\n"; //---------------------------------------------------------------- // test CpTimestamp // TestCpTimestamp clTestCpTimestampT; slResultT = QTest::qExec(&clTestCpTimestampT, argc, &argv[0]); //---------------------------------------------------------------- // test QCanFrame // TestQCanFrame clTestQCanFrameT; slResultT = QTest::qExec(&clTestQCanFrameT, argc, &argv[0]); //---------------------------------------------------------------- // test QCanStub // TestQCanSocket clTestQCanSockT; slResultT = QTest::qExec(&clTestQCanSockT) + slResultT; cout << "\n"; cout << "#===========================================================\n"; cout << "# Total result \n"; cout << "# " << slResultT << " test cases failed \n"; cout << "#===========================================================\n"; }
#include <iostream> using namespace std; #include <QCoreApplication> #include <QDebug> #include <QTest> #include "canpie_frame.hpp" #include "canpie_frame_error.hpp" #include "test_canpie_timestamp.hpp" #include "test_qcan_frame.hpp" #include "test_qcan_socket.hpp" int main(int argc, char *argv[]) { int32_t slResultT; cout << "#===========================================================\n"; cout << "# Run test cases for QCan classes \n"; cout << "# \n"; cout << "#===========================================================\n"; cout << "\n"; //---------------------------------------------------------------- // test CpTimestamp // TestCpTimestamp clTestCpTimestampT; slResultT = QTest::qExec(&clTestCpTimestampT, argc, &argv[0]); //---------------------------------------------------------------- // test QCanFrame // TestQCanFrame clTestQCanFrameT; slResultT = QTest::qExec(&clTestQCanFrameT, argc, &argv[0]); //---------------------------------------------------------------- // test QCanStub // TestQCanSocket clTestQCanSockT; slResultT = QTest::qExec(&clTestQCanSockT) + slResultT; cout << "\n"; cout << "#===========================================================\n"; cout << "# Total result \n"; cout << "# " << slResultT << " test cases failed \n"; cout << "#===========================================================\n"; }
Check for nullptrs when fuzzing region_deserialize
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCanvas.h" #include "SkPaint.h" #include "SkRegion.h" #include "SkSurface.h" bool FuzzRegionDeserialize(sk_sp<SkData> bytes) { SkRegion region; if (!region.readFromMemory(bytes->data(), bytes->size())) { return false; } region.computeRegionComplexity(); region.isComplex(); SkRegion r2; if (region == r2) { region.contains(0,0); } else { region.contains(1,1); } auto s = SkSurface::MakeRasterN32Premul(1024, 1024); s->getCanvas()->drawRegion(region, SkPaint()); SkDEBUGCODE(region.validate()); return true; } #if defined(IS_FUZZING_WITH_LIBFUZZER) extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { auto bytes = SkData::MakeWithoutCopy(data, size); FuzzRegionDeserialize(bytes); return 0; } #endif
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCanvas.h" #include "SkPaint.h" #include "SkRegion.h" #include "SkSurface.h" bool FuzzRegionDeserialize(sk_sp<SkData> bytes) { SkRegion region; if (!region.readFromMemory(bytes->data(), bytes->size())) { return false; } region.computeRegionComplexity(); region.isComplex(); SkRegion r2; if (region == r2) { region.contains(0,0); } else { region.contains(1,1); } auto s = SkSurface::MakeRasterN32Premul(128, 128); if (!s) { // May return nullptr in memory-constrained fuzzing environments return false; } s->getCanvas()->drawRegion(region, SkPaint()); SkDEBUGCODE(region.validate()); return true; } #if defined(IS_FUZZING_WITH_LIBFUZZER) extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { auto bytes = SkData::MakeWithoutCopy(data, size); FuzzRegionDeserialize(bytes); return 0; } #endif
Change window title to 'Warg'
#include <GL/glew.h> #include <SDL2/SDL.h> int main(void) { int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC; SDL_Init(SDL_INIT_EVERYTHING); auto window = SDL_CreateWindow("title", 0, 0, 320, 240, flags); auto context = SDL_GL_CreateContext(window); glewInit(); glClearColor(0, 1, 0, 1); glClear(GL_COLOR_BUFFER_BIT); SDL_Event event; while (true) { while (SDL_PollEvent(&event)) if (event.type == SDL_QUIT) goto quit; else if (event.type == SDL_KEYDOWN) switch (event.key.keysym.sym) { case SDLK_ESCAPE: goto quit; break; } SDL_Delay(10); SDL_GL_SwapWindow(window); } quit: SDL_DestroyWindow(window); SDL_Quit(); return 0; }
#include <GL/glew.h> #include <SDL2/SDL.h> int main(void) { int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC; SDL_Init(SDL_INIT_EVERYTHING); auto window = SDL_CreateWindow("Warg", 0, 0, 320, 240, flags); auto context = SDL_GL_CreateContext(window); glewInit(); glClearColor(0, 1, 0, 1); glClear(GL_COLOR_BUFFER_BIT); SDL_Event event; while (true) { while (SDL_PollEvent(&event)) if (event.type == SDL_QUIT) goto quit; else if (event.type == SDL_KEYDOWN) switch (event.key.keysym.sym) { case SDLK_ESCAPE: goto quit; break; } SDL_Delay(10); SDL_GL_SwapWindow(window); } quit: SDL_DestroyWindow(window); SDL_Quit(); return 0; }
Set STKALIGN bit in SCB->CCR for ARM Cortex-M3 r1p1
/** * \file * \brief lowLevelInitialization() implementation for ARMv6-M and ARMv7-M * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/architecture/lowLevelInitialization.hpp" #include "distortos/chip/CMSIS-proxy.h" namespace distortos { namespace architecture { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { #if __FPU_PRESENT == 1 && __FPU_USED == 1 SCB->CPACR |= (3 << 10 * 2) | (3 << 11 * 2); // full access to CP10 and CP11 #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 } } // namespace architecture } // namespace distortos
/** * \file * \brief lowLevelInitialization() implementation for ARMv6-M and ARMv7-M * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/architecture/lowLevelInitialization.hpp" #include "distortos/chip/CMSIS-proxy.h" namespace distortos { namespace architecture { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { #ifdef CONFIG_ARCHITECTURE_ARM_CORTEX_M3_R1P1 SCB->CCR |= SCB_CCR_STKALIGN_Msk; #endif // def CONFIG_ARCHITECTURE_ARM_CORTEX_M3_R1P1 #if __FPU_PRESENT == 1 && __FPU_USED == 1 SCB->CPACR |= (3 << 10 * 2) | (3 << 11 * 2); // full access to CP10 and CP11 #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 } } // namespace architecture } // namespace distortos
Use 'auto' for iterator type.
#include <iostream> #include <string> #include <utility> #include "pool.h" void Pool::add_machine(const Machine& new_machine) { const std::string& machine_name = new_machine.get_name(); std::cout << "Adding machine to pool: " << machine_name << std::endl; machines.insert(std::make_pair(machine_name, new_machine)); } void Pool::add_job(const Job& new_job) { const int job_id = new_job.get_id(); const std::string& machine_name = new_job.get_machine(); std::cout << "Adding job to pool: " << job_id << " (" << machine_name << ")" << std::endl; jobs.insert(std::make_pair(job_id, new_job)); std::map<std::string, Machine>::iterator iter = machines.find(machine_name); if (iter != machines.end()) { std::cout << "Adding job to machine: " << machine_name << std::endl; iter->second.add_job(new_job); } }
#include <iostream> #include <string> #include <utility> #include "pool.h" void Pool::add_machine(const Machine& new_machine) { const std::string& machine_name = new_machine.get_name(); std::cout << "Adding machine to pool: " << machine_name << std::endl; machines.insert(std::make_pair(machine_name, new_machine)); } void Pool::add_job(const Job& new_job) { const int job_id = new_job.get_id(); const std::string& machine_name = new_job.get_machine(); std::cout << "Adding job to pool: " << job_id << " (" << machine_name << ")" << std::endl; jobs.insert(std::make_pair(job_id, new_job)); auto iter = machines.find(machine_name); if (iter != machines.end()) { std::cout << "Adding job to machine: " << machine_name << std::endl; iter->second.add_job(new_job); } }
Increase the base font size for touch ui
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/menu/menu_config.h" #include "grit/app_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/resource/resource_bundle.h" namespace views { // static MenuConfig* MenuConfig::Create() { MenuConfig* config = new MenuConfig(); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); config->font = rb.GetFont(ResourceBundle::BaseFont); config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width(); // Add 4 to force some padding between check and label. config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4; config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height(); return config; } } // namespace views
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/menu/menu_config.h" #include "grit/app_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/resource/resource_bundle.h" namespace views { // static MenuConfig* MenuConfig::Create() { MenuConfig* config = new MenuConfig(); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); #if defined(TOUCH_UI) config->font = rb.GetFont(ResourceBundle::LargeFont); #else config->font = rb.GetFont(ResourceBundle::BaseFont); #endif config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width(); // Add 4 to force some padding between check and label. config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4; config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height(); return config; } } // namespace views
Fix test in previous commit to account for compiler warning.
// RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-store=region -verify %s // expected-no-diagnostics bool PR14634(int x) { double y = (double)x; return !y; } bool PR14634_implicit(int x) { double y = (double)x; return y; } void intAsBoolAsSwitchCondition(int c) { switch ((bool)c) { case 0: break; } }
// RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-store=region -verify %s bool PR14634(int x) { double y = (double)x; return !y; } bool PR14634_implicit(int x) { double y = (double)x; return y; } void intAsBoolAsSwitchCondition(int c) { switch ((bool)c) { // expected-warning {{switch condition has boolean value}} case 0: break; } switch ((int)(bool)c) { // no-warning case 0: break; } }
Support parsing numeric block ids, and emit them in textual output.
// RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \ // RUN: | FileCheck %s // RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \ // RUN: -discard-value-names | FileCheck %s --check-prefix=DISCARDVALUE extern "C" void branch(); bool test(bool pred) { // DISCARDVALUE: br i1 %0, label %2, label %3 // CHECK: br i1 %pred, label %if.then, label %if.end if (pred) { // DISCARDVALUE: ; <label>:2: // DISCARDVALUE-NEXT: tail call void @branch() // DISCARDVALUE-NEXT: br label %3 // CHECK: if.then: // CHECK-NEXT: tail call void @branch() // CHECK-NEXT: br label %if.end branch(); } // DISCARDVALUE: ; <label>:3: // DISCARDVALUE-NEXT: ret i1 %0 // CHECK: if.end: // CHECK-NEXT: ret i1 %pred return pred; }
// RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \ // RUN: | FileCheck %s // RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \ // RUN: -discard-value-names | FileCheck %s --check-prefix=DISCARDVALUE extern "C" void branch(); bool test(bool pred) { // DISCARDVALUE: br i1 %0, label %2, label %3 // CHECK: br i1 %pred, label %if.then, label %if.end if (pred) { // DISCARDVALUE: 2: // DISCARDVALUE-NEXT: tail call void @branch() // DISCARDVALUE-NEXT: br label %3 // CHECK: if.then: // CHECK-NEXT: tail call void @branch() // CHECK-NEXT: br label %if.end branch(); } // DISCARDVALUE: 3: // DISCARDVALUE-NEXT: ret i1 %0 // CHECK: if.end: // CHECK-NEXT: ret i1 %pred return pred; }
Fix missing of symbols when linking win32 build
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "osfhandle.h" #include <io.h> #include "v8-profiler.h" #include "v8-inspector.h" namespace node { int open_osfhandle(intptr_t osfhandle, int flags) { return _open_osfhandle(osfhandle, flags); } int close(int fd) { return _close(fd); } void ReferenceSymbols() { // Following symbols are used by electron.exe but got stripped by compiler, // for some reason, adding them to ForceSymbolReferences does not work, // probably because of VC++ bugs. v8::TracingCpuProfiler::Create(nullptr); reinterpret_cast<v8_inspector::V8InspectorClient*>(nullptr)->unmuteMetrics(0); } } // namespace node
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "osfhandle.h" #include <io.h> #include "v8-profiler.h" #include "v8-inspector.h" namespace node { int open_osfhandle(intptr_t osfhandle, int flags) { return _open_osfhandle(osfhandle, flags); } int close(int fd) { return _close(fd); } void ReferenceSymbols() { // Following symbols are used by electron.exe but got stripped by compiler, // for some reason, adding them to ForceSymbolReferences does not work, // probably because of VC++ bugs. v8::TracingCpuProfiler::Create(nullptr); reinterpret_cast<v8_inspector::V8InspectorSession*>(nullptr)-> canDispatchMethod(v8_inspector::StringView()); reinterpret_cast<v8_inspector::V8InspectorClient*>(nullptr)->unmuteMetrics(0); } } // namespace node
Fix a build problem in AppVeyor
#include <QString> #include <QtTest> #include <execinfo.h> #include <signal.h> #include <unistd.h> #include <TestRunner> #include <QtQuickTest> #include "example.h" #include "asyncfuturetests.h" #include "bugtests.h" void handleBacktrace(int sig) { void *array[100]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 100); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } static void waitForFinished(QThreadPool *pool) { QEventLoop loop; while (!pool->waitForDone(10)) { loop.processEvents(); } } int main(int argc, char *argv[]) { signal(SIGSEGV, handleBacktrace); QCoreApplication app(argc, argv); TestRunner runner; runner.add<AsyncFutureTests>(); runner.add<BugTests>(); runner.add<Example>(); bool error = runner.exec(app.arguments()); if (!error) { qDebug() << "All test cases passed!"; } waitForFinished(QThreadPool::globalInstance()); return error; }
#include <QString> #include <QtTest> #include <TestRunner> #include <QtQuickTest> #include "example.h" #include "asyncfuturetests.h" #include "bugtests.h" #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) #include <execinfo.h> #include <signal.h> #include <unistd.h> void handleBacktrace(int sig) { void *array[100]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 100); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } #endif static void waitForFinished(QThreadPool *pool) { QEventLoop loop; while (!pool->waitForDone(10)) { loop.processEvents(); } } int main(int argc, char *argv[]) { #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) signal(SIGSEGV, handleBacktrace); #endif QCoreApplication app(argc, argv); TestRunner runner; runner.add<AsyncFutureTests>(); runner.add<BugTests>(); runner.add<Example>(); bool error = runner.exec(app.arguments()); if (!error) { qDebug() << "All test cases passed!"; } waitForFinished(QThreadPool::globalInstance()); return error; }