Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add C++ Interpreter Libraries to the main source.
// Native C++ Libraries #include <iostream> #include <string>
// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h>
Remove corpses from old code
#include <cmath> #include <stdexcept> #include "Layer/filter.hpp" #include "Utility/utility.hpp" using namespace Convolutional; using namespace Convolutional::Layer; Filter::Filter(std::size_t size) : bias{Utility::GetRandomNumberBetween(-1.0, 1.0)} { // TODO jnf: constexpr check if size is perfect square weights.reserve(size); for (size_t i = 0; i < size; ++i) { weights.push_back(Utility::GetRandomNumberBetween(-1.0, 1.0)); } } auto Filter::ProcessMatrix(Matrix matrix) const -> Matrix { if (matrix.GetElementCount() != weights.size()) { throw std::invalid_argument("Number of weights in filter does not match number of elements in matrix"); } Matrix featureMap{matrix.GetSubmatrix(position, GetReceptiveField(matrix.GetSize()))}; auto featureValue = bias; auto weight = weights.begin(); for (const auto& element : featureMap) { featureValue += element * *weight; ++weight; } featureValue = sigmoid(featureValue); for (auto& element : featureMap) { element = featureValue; } return featureMap; } auto Filter::sigmoid(Matrix::element_t n) -> double { return tanh(n); }
#include <cmath> #include <stdexcept> #include "Layer/filter.hpp" #include "Utility/utility.hpp" using namespace Convolutional; using namespace Convolutional::Layer; Filter::Filter(std::size_t size) : bias{Utility::GetRandomNumberBetween(-1.0, 1.0)} { // TODO jnf: constexpr check if size is perfect square weights.reserve(size); for (size_t i = 0; i < size; ++i) { weights.push_back(Utility::GetRandomNumberBetween(-1.0, 1.0)); } } auto Filter::ProcessMatrix(Matrix matrix) const -> Matrix { if (matrix.GetElementCount() != weights.size()) { throw std::invalid_argument("Number of weights in filter does not match number of elements in matrix"); } auto featureValue = bias; auto weight = weights.begin(); for (const auto& element : matrix) { featureValue += element * *weight; ++weight; } featureValue = sigmoid(featureValue); for (auto& element : matrix) { element = featureValue; } return matrix; } auto Filter::sigmoid(Matrix::element_t n) -> double { return tanh(n); }
MAke it simpler to vectorize (even if this is not the proper way)
#include <cstdlib> #include <ATK/EQ/BesselFilter.h> #include <ATK/EQ/IIRFilter.h> #include <ATK/Mock/SimpleSinusGeneratorFilter.h> int main(int argc, char** argv) { ATK::SimpleSinusGeneratorFilter<double> generator; generator.set_output_sampling_rate(1024 * 64); generator.set_amplitude(1); generator.set_frequency(1000); ATK::IIRFilter<ATK::BesselLowPassCoefficients<double> > filter; filter.set_input_sampling_rate(1024 * 64); filter.set_output_sampling_rate(1024 * 64); filter.set_cut_frequency(100); filter.set_order(3); filter.set_input_port(0, &generator, 0); for(size_t i = 0; i < 1024*1024; ++i) filter.process(1024); return EXIT_SUCCESS; }
#include <cstdlib> #include <ATK/EQ/BesselFilter.h> #include <ATK/EQ/IIRFilter.h> #include <ATK/Mock/SimpleSinusGeneratorFilter.h> int main(int argc, char** argv) { ATK::SimpleSinusGeneratorFilter<double> generator; generator.set_output_sampling_rate(1024 * 64); generator.set_amplitude(1); generator.set_frequency(1000); ATK::IIRFilter<ATK::BesselLowPassCoefficients<double> > filter; filter.set_input_sampling_rate(1024 * 64); filter.set_output_sampling_rate(1024 * 64); filter.set_cut_frequency(100); filter.set_order(7); filter.set_input_port(0, &generator, 0); for(size_t i = 0; i < 1024*1024; ++i) filter.process(1024); return EXIT_SUCCESS; }
Increase number of iterations in libFuzzer test
// Copyright 2017 Google Inc. 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 <stdlib.h> #include <sys/wait.h> #include "gtest/gtest.h" const int kDefaultLibFuzzerError = 77; TEST(LibFuzzerExampleTest, Crash) { char dir_template[] = "/tmp/libfuzzer_example_test_XXXXXX"; auto dir = mkdtemp(dir_template); ASSERT_TRUE(dir); std::string cmd = "./libfuzzer_example -max_len=10000 -runs=100000 -artifact_prefix=" + std::string(dir) + "/ " + dir; int retvalue = std::system(cmd.c_str()); EXPECT_EQ(kDefaultLibFuzzerError, WSTOPSIG(retvalue)); // Cleanup. EXPECT_EQ(0, std::system((std::string("rm -rf ") + dir).c_str())); }
// Copyright 2017 Google Inc. 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 <stdlib.h> #include <sys/wait.h> #include "gtest/gtest.h" const int kDefaultLibFuzzerError = 77; TEST(LibFuzzerExampleTest, Crash) { char dir_template[] = "/tmp/libfuzzer_example_test_XXXXXX"; auto dir = mkdtemp(dir_template); ASSERT_TRUE(dir); std::string cmd = "./libfuzzer_example -max_len=10000 -runs=300000 -artifact_prefix=" + std::string(dir) + "/ " + dir; int retvalue = std::system(cmd.c_str()); EXPECT_EQ(kDefaultLibFuzzerError, WSTOPSIG(retvalue)); // Cleanup. EXPECT_EQ(0, std::system((std::string("rm -rf ") + dir).c_str())); }
Change return NULL -> return Py_None.
#include <Python.h> #include "Quantuccia/ql/time/calendars/unitedstates.hpp" static PyObject* get_holiday_date(PyObject *self, PyObject *args) { return NULL; } static PyMethodDef QuantucciaMethods[] = { {"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef quantuccia_module_def = { PyModuleDef_HEAD_INIT, "quantuccia", NULL, -1, QuantucciaMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_quantuccia(void){ PyObject *m; m = PyModule_Create(&quantuccia_module_def); return m; }
#include <Python.h> #include "Quantuccia/ql/time/calendars/unitedstates.hpp" static PyObject* get_holiday_date(PyObject *self, PyObject *args) { return Py_None; } static PyMethodDef QuantucciaMethods[] = { {"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef quantuccia_module_def = { PyModuleDef_HEAD_INIT, "quantuccia", NULL, -1, QuantucciaMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_quantuccia(void){ PyObject *m; m = PyModule_Create(&quantuccia_module_def); return m; }
Add todo for automatic html validation
#include <aerial_autonomy/common/html_utils.h> #include <gtest/gtest.h> #include <iostream> /// \brief TEST /// Simple Html table tests TEST(HtmlTableWriterTests, SimpleTable) { HtmlTableWriter table_writer; table_writer.beginRow(); table_writer.addHeader("Header"); table_writer.beginRow(); double data = 2.0; table_writer.addCell(data, "Hello"); table_writer.addCell("Data"); table_writer.addCell("Data", "Hello", Colors::white); std::cout << "Table: \n" << table_writer.getTableString() << std::endl; } TEST(HtmlTableWriterTests, TableError) { HtmlTableWriter table_writer; EXPECT_THROW(table_writer.addHeader("Hello"), std::runtime_error); EXPECT_THROW(table_writer.addCell("Hello"), std::runtime_error); } /// Simple Html division tests TEST(HtmlTableWriterTests, SimpleDivision) { HtmlDivisionWriter division_writer; division_writer.addHeader("Hello", 1); division_writer.addText("My text"); std::cout << "Division: \n" << division_writer.getDivisionText() << std::endl; } /// int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <aerial_autonomy/common/html_utils.h> #include <gtest/gtest.h> #include <iostream> /// \brief TEST /// Simple Html table tests TEST(HtmlTableWriterTests, SimpleTable) { HtmlTableWriter table_writer; table_writer.beginRow(); table_writer.addHeader("Header"); table_writer.beginRow(); double data = 2.0; table_writer.addCell(data, "Hello"); table_writer.addCell("Data"); table_writer.addCell("Data", "Hello", Colors::white); ///\todo Add an automatic way of validating html string std::cout << "Table: \n" << table_writer.getTableString() << std::endl; } TEST(HtmlTableWriterTests, TableError) { HtmlTableWriter table_writer; EXPECT_THROW(table_writer.addHeader("Hello"), std::runtime_error); EXPECT_THROW(table_writer.addCell("Hello"), std::runtime_error); } /// Simple Html division tests TEST(HtmlTableWriterTests, SimpleDivision) { HtmlDivisionWriter division_writer; division_writer.addHeader("Hello", 1); division_writer.addText("My text"); std::cout << "Division: \n" << division_writer.getDivisionText() << std::endl; } /// int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Use the same User-Agent everywhere, just because
#include "KVNetworkAccessManager.h" #include <QDebug> #include "KVNetworkReply.h" KVNetworkAccessManager::KVNetworkAccessManager(QObject *parent) : QNetworkAccessManager(parent) { } QNetworkReply *KVNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData) { QNetworkRequest request = req; request.setRawHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); if(request.url().host() != "localhost" && request.url().host() != "127.0.0.1") { if(op == QNetworkAccessManager::PostOperation) { qDebug() << "POST" << request.url().path(); QNetworkReply *r = QNetworkAccessManager::createRequest(op, request, outgoingData); KVNetworkReply *reply = new KVNetworkReply(r->parent(), r, this); return reply; } else if(op == QNetworkAccessManager::GetOperation) { qDebug() << "GET" << request.url().path(); } } QNetworkReply *reply = QNetworkAccessManager::createRequest(op, request, outgoingData); return reply; }
#include "KVNetworkAccessManager.h" #include <QDebug> #include "KVNetworkReply.h" KVNetworkAccessManager::KVNetworkAccessManager(QObject *parent) : QNetworkAccessManager(parent) { } QNetworkReply *KVNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData) { QNetworkRequest request = req; request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"); if(request.url().host() != "localhost" && request.url().host() != "127.0.0.1") { if(op == QNetworkAccessManager::PostOperation) { qDebug() << "POST" << request.url().path(); QNetworkReply *r = QNetworkAccessManager::createRequest(op, request, outgoingData); KVNetworkReply *reply = new KVNetworkReply(r->parent(), r, this); return reply; } else if(op == QNetworkAccessManager::GetOperation) { qDebug() << "GET" << request.url().path(); } } QNetworkReply *reply = QNetworkAccessManager::createRequest(op, request, outgoingData); return reply; }
Mark sancov test as unsupported on Darwin
// Tests -fsanitize-coverage=inline-8bit-counters // // REQUIRES: has_sancovcc,stable-runtime // UNSUPPORTED: i386-darwin // // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1 #include <stdio.h> #include <assert.h> const char *first_counter; extern "C" void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) { printf("INIT: %p %p\n", start, end); assert(end - start > 1); first_counter = start; } int main() { assert(first_counter); assert(*first_counter == 1); }
// Tests -fsanitize-coverage=inline-8bit-counters // // REQUIRES: has_sancovcc,stable-runtime // UNSUPPORTED: i386-darwin, x86_64-darwin // // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1 #include <stdio.h> #include <assert.h> const char *first_counter; extern "C" void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) { printf("INIT: %p %p\n", start, end); assert(end - start > 1); first_counter = start; } int main() { assert(first_counter); assert(*first_counter == 1); }
Allow to only run some test suites from the test runner
#include <QTest> #include "test-suite.h" #include "custom-network-access-manager.h" #include <iostream> int main(int argc, char *argv[]) { #ifdef HEADLESS QCoreApplication a(argc, argv); #else QGuiApplication a(argc, argv); #endif QMap<QString,int> results; int failed = 0; CustomNetworkAccessManager::TestMode = true; for (QObject *suite : TestSuite::suites) { int result = QTest::qExec(suite); results.insert(suite->metaObject()->className(), result); if (result != 0) { failed++; } } for (auto key : results.keys()) { std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl; } return failed; }
#include <QTest> #include "test-suite.h" #include "custom-network-access-manager.h" #include <iostream> int main(int argc, char *argv[]) { #ifdef HEADLESS QCoreApplication a(argc, argv); #else QGuiApplication a(argc, argv); #endif QStringList testSuites; for (int i = 1; i < argc; ++i) testSuites.append(argv[i]); QMap<QString,int> results; int failed = 0; CustomNetworkAccessManager::TestMode = true; for (QObject *suite : TestSuite::suites) { if (!testSuites.isEmpty() && !testSuites.contains(suite->metaObject()->className())) continue; int result = QTest::qExec(suite); results.insert(suite->metaObject()->className(), result); if (result != 0) { failed++; } } for (auto key : results.keys()) { std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl; } return failed; }
Fix CrOS Official build from options2 copy.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/user_metrics.h" namespace chromeos { StatsOptionsHandler::StatsOptionsHandler() { } // OptionsPageUIHandler implementation. void StatsOptionsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { } void StatsOptionsHandler::Initialize() { } // WebUIMessageHandler implementation. void StatsOptionsHandler::RegisterMessages() { web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction", base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox, base::Unretained(this))); } void StatsOptionsHandler::HandleMetricsReportingCheckbox( const ListValue* args) { #if defined(GOOGLE_CHROME_BUILD) const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args)); const bool enabled = (checked_str == "true"); UserMetrics::RecordAction( enabled ? UserMetricsAction("Options_MetricsReportingCheckbox_Enable") : UserMetricsAction("Options_MetricsReportingCheckbox_Disable")); #endif } } // namespace chromeos
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/user_metrics.h" using content::UserMetricsAction; namespace chromeos { StatsOptionsHandler::StatsOptionsHandler() { } // OptionsPageUIHandler implementation. void StatsOptionsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { } void StatsOptionsHandler::Initialize() { } // WebUIMessageHandler implementation. void StatsOptionsHandler::RegisterMessages() { web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction", base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox, base::Unretained(this))); } void StatsOptionsHandler::HandleMetricsReportingCheckbox( const ListValue* args) { #if defined(GOOGLE_CHROME_BUILD) const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args)); const bool enabled = (checked_str == "true"); content::RecordAction( enabled ? UserMetricsAction("Options_MetricsReportingCheckbox_Enable") : UserMetricsAction("Options_MetricsReportingCheckbox_Disable")); #endif } } // namespace chromeos
Remove special showMaximized case for Maemo 5
#include <%QAPP_INCLUDE%> #include "%INCLUDE%" int main(int argc, char *argv[]) { QApplication a(argc, argv); %CLASS% w; #if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5) w.showMaximized(); #else w.show(); #endif return a.exec(); }
#include <%QAPP_INCLUDE%> #include "%INCLUDE%" int main(int argc, char *argv[]) { QApplication a(argc, argv); %CLASS% w; #if defined(Q_WS_S60) w.showMaximized(); #else w.show(); #endif return a.exec(); }
Correct after hook exception message
#include <string> #include <ccspec/core/hooks.h> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { void before(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addBeforeEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addBeforeAllHook(hook); else throw "no such before hook type"; } void after(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addAfterEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addAfterAllHook(hook); else throw "no such before hook type"; } } // namespace core } // namespace ccspec
#include <string> #include <ccspec/core/hooks.h> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { void before(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addBeforeEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addBeforeAllHook(hook); else throw "no such before hook type"; } void after(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addAfterEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addAfterAllHook(hook); else throw "no such after hook type"; } } // namespace core } // namespace ccspec
Remove NOTIMPLEMENTED() in FindBarHost::AudibleAlert() for ChromeOS.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/find_bar_host.h" #include "base/logging.h" #include "ui/base/events/event.h" void FindBarHost::AudibleAlert() { #if defined(OS_WIN) MessageBeep(MB_OK); #else // TODO(mukai): NOTIMPLEMENTED(); #endif } bool FindBarHost::ShouldForwardKeyEventToWebpageNative( const ui::KeyEvent& key_event) { return true; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/find_bar_host.h" #include "base/logging.h" #include "ui/base/events/event.h" void FindBarHost::AudibleAlert() { #if defined(OS_WIN) MessageBeep(MB_OK); #endif } bool FindBarHost::ShouldForwardKeyEventToWebpageNative( const ui::KeyEvent& key_event) { return true; }
Fix build after r319688: s/CPlusPlus1z/CPlusPlus17/
//===--- UnaryStaticAssertCheck.cpp - clang-tidy---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "UnaryStaticAssertCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace modernize { void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) { if (!getLangOpts().CPlusPlus1z) return; Finder->addMatcher(staticAssertDecl().bind("static_assert"), this); } void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) { const auto *MatchedDecl = Result.Nodes.getNodeAs<StaticAssertDecl>("static_assert"); const StringLiteral *AssertMessage = MatchedDecl->getMessage(); SourceLocation Loc = MatchedDecl->getLocation(); if (!AssertMessage || AssertMessage->getLength() || AssertMessage->getLocStart().isMacroID() || Loc.isMacroID()) return; diag(Loc, "use unary 'static_assert' when the string literal is an empty string") << FixItHint::CreateRemoval(AssertMessage->getSourceRange()); } } // namespace modernize } // namespace tidy } // namespace clang
//===--- UnaryStaticAssertCheck.cpp - clang-tidy---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "UnaryStaticAssertCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace modernize { void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) { if (!getLangOpts().CPlusPlus17) return; Finder->addMatcher(staticAssertDecl().bind("static_assert"), this); } void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) { const auto *MatchedDecl = Result.Nodes.getNodeAs<StaticAssertDecl>("static_assert"); const StringLiteral *AssertMessage = MatchedDecl->getMessage(); SourceLocation Loc = MatchedDecl->getLocation(); if (!AssertMessage || AssertMessage->getLength() || AssertMessage->getLocStart().isMacroID() || Loc.isMacroID()) return; diag(Loc, "use unary 'static_assert' when the string literal is an empty string") << FixItHint::CreateRemoval(AssertMessage->getSourceRange()); } } // namespace modernize } // namespace tidy } // namespace clang
Check if the result of graphics_get_display_size is less than 0
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <bcm_host.h> #include "WindowResourceRasp.hpp" #include "utils/Log.hpp" namespace ouzel { WindowResourceRasp::WindowResourceRasp() { bcm_host_init(); } WindowResourceRasp::~WindowResourceRasp() { bcm_host_deinit(); } bool WindowResourceRasp::init(const Size2& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, bool newHighDpi, bool depth) { if (!WindowResource::init(newSize, newResizable, newFullscreen, newExclusiveFullscreen, newTitle, newHighDpi, depth)) { return false; } uint32_t screenWidth; uint32_t screenHeight; int32_t success = graphics_get_display_size(0, &screenWidth, &screenHeight); if (success == -1) { Log(Log::Level::ERR) << "Failed to get display size"; return false; } size.width = static_cast<float>(screenWidth); size.height = static_cast<float>(screenHeight); resolution = size; return true; } }
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <bcm_host.h> #include "WindowResourceRasp.hpp" #include "utils/Log.hpp" namespace ouzel { WindowResourceRasp::WindowResourceRasp() { bcm_host_init(); } WindowResourceRasp::~WindowResourceRasp() { bcm_host_deinit(); } bool WindowResourceRasp::init(const Size2& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, bool newHighDpi, bool depth) { if (!WindowResource::init(newSize, newResizable, newFullscreen, newExclusiveFullscreen, newTitle, newHighDpi, depth)) { return false; } uint32_t screenWidth; uint32_t screenHeight; int32_t success = graphics_get_display_size(0, &screenWidth, &screenHeight); if (success < 0) { Log(Log::Level::ERR) << "Failed to get display size"; return false; } size.width = static_cast<float>(screenWidth); size.height = static_cast<float>(screenHeight); resolution = size; return true; } }
Update Rule of Five Example
/************************************************************************* > File Name: ruleOfFive.cpp > Author: Chan-Ho Chris Ohk > E-mail: utilForever@gmail.com, utilForever@kaist.ac.kr > Created Time: 2015/4/24 > Personal Blog: https://github.com/utilForever ************************************************************************/
/************************************************************************* > File Name: ruleOfFive.cpp > Author: Chan-Ho Chris Ohk > E-mail: utilForever@gmail.com, utilForever@kaist.ac.kr > Created Time: 2015/4/26 > Personal Blog: https://github.com/utilForever ************************************************************************/ #include <utility> class Resource { private: int x = 0; }; class RO3 { private: Resource* pResource; }; class RO5 { private: Resource* pResource; public: RO5() : pResource{ new Resource{} } { } RO5(const RO5& rhs) : pResource{ new Resource(*(rhs.pResource)) } { } RO5(RO5&& rhs) : pResource{ rhs.pResource } { rhs.pResource = nullptr; } RO5& operator=(const RO5& rhs) { if (&rhs != this) { delete pResource; pResource = nullptr; pResource = new Resource(*(rhs.pResource)); } return *this; } RO5& operator=(RO5&& rhs) { if (&rhs != this) { delete pResource; pResource = rhs.pResource; rhs.pResource = nullptr; } return *this; } ~RO5() { delete pResource; } };
Add functions to new problem for CheckUniqueChar
#include "check_unique_char.h"
// Solution to problem from Crack Coding interviews. Implement an // algorithm to determine if a string has all unique characters #include "check_unique_char.h" CheckUniqueChar::CheckUniqueChar() { } CheckUniqueChar::~CheckUniqueChar() { } // Takes O(n) running time bool CheckUniqueChar::solver_boolean(std::string test_string) { } // Takes O(nlogn) running time bool CheckUniqueChar::solver_sorted(std::string test_string) { } bool CheckUniqueChar:test_case() { }
Create OpenGl texture object when creating OpenGlTexture
#include <GL/gl.h> #include <orz/exception.h> #include "hw3d_opengl_texture.h" namespace Hw3D { Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt &region, bool readOnly) { return Texture::Lock(); } void OpenGlTexture::UnlockRegion() { } OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool): Texture(dimensions, fmt), m_textureName(0) { glGenTextures(1, &m_textureName); if(m_textureName == GL_INVALID_VALUE) { m_textureName = 0; DO_THROW(Err::CriticalError, "Failed allocating texture"); } } OpenGlTexture::~OpenGlTexture() { glDeleteTextures(1, &m_textureName); } }
#include <GL/gl.h> #include <orz/exception.h> #include "hw3d_opengl_texture.h" #include "hw3d_opengl_common.h" namespace Hw3D { Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt &region, bool readOnly) { return Texture::Lock(); } void OpenGlTexture::UnlockRegion() { } OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool): Texture(dimensions, fmt), m_textureName(0) { glGenTextures(1, &m_textureName); if(m_textureName == GL_INVALID_VALUE) { m_textureName = 0; DO_THROW(Err::CriticalError, "Failed allocating texture"); } glBindTexture(GL_TEXTURE_2D, m_textureName); glTexImage2D( GL_TEXTURE_2D, 0, GetGlInternalFormat(fmt), dimensions.Width, dimensions.Height, 0, GetGlFormat(fmt), GetGlDataType(fmt), nullptr ); GLenum err; if((err = glGetError()) != GL_NO_ERROR) { DO_THROW(Err::CriticalError, "glTexImage2D failed: " + GetGlErrorString(err)); } } OpenGlTexture::~OpenGlTexture() { glDeleteTextures(1, &m_textureName); } }
Remove an include path with undefined behaviour on non-windows systems
#include "CppUTest\CommandLineTestRunner.h" #include <stdio.h> #include "mbed.h" #include "testrunner.h" #include "test_env.h" /** Object 'console' is used to show prints on console. It is declared in \cpputest\src\Platforms\armcc\UtestPlatform.cpp */ Serial console(STDIO_UART_TX, STDIO_UART_RX); int main(int ac, char** av) { unsigned failureCount = 0; { // Some compilers may not pass ac, av so we need to supply them ourselves int ac = 2; char* av[] = {__FILE__, "-v"}; failureCount = CommandLineTestRunner::RunAllTests(ac, av); } notify_completion(failureCount == 0); return failureCount; }
#include "CommandLineTestRunner.h" #include <stdio.h> #include "mbed.h" #include "testrunner.h" #include "test_env.h" /** Object 'console' is used to show prints on console. It is declared in \cpputest\src\Platforms\armcc\UtestPlatform.cpp */ Serial console(STDIO_UART_TX, STDIO_UART_RX); int main(int ac, char** av) { unsigned failureCount = 0; { // Some compilers may not pass ac, av so we need to supply them ourselves int ac = 2; char* av[] = {__FILE__, "-v"}; failureCount = CommandLineTestRunner::RunAllTests(ac, av); } notify_completion(failureCount == 0); return failureCount; }
Implement all the integer comparison operators in swift.swift. Despite the indirection, each of these compiles into nice simple IR at -O3, with: swift swift.swift -I test -emit-llvm | opt -O3 -S | less
#include <inttypes.h> #include <stdio.h> extern "C" bool _TSsop2leFT3lhsNSs5int643rhsS__NSs4bool(int64_t l, int64_t r) { return l <= r; } extern "C" double _TSsop1sFT1aNSs6double_S_(double x) { return -x; } extern "C" void _T3fib5printFT1iNSs5int64_T_(int64_t l) { printf("%lld\n", l); } extern "C" void _T3fib5printFT1iNS_6double_T_(double l) { printf("%f\n", l); } extern "C" void _T5nbody5printFT1iNSs6double_T_(double l) { printf("%f\n", l); } extern "C" bool _TSs19convertToLogicValueFT1vNSs4bool_i1(bool b) { return b; } extern "C" double _TNSs6double26convert_from_float_literalFT3valf64_S_(double x) { return x; }
#include <inttypes.h> #include <stdio.h> extern "C" void _T3fib5printFT1iNSs5int64_T_(int64_t l) { printf("%lld\n", l); } extern "C" void _T3fib5printFT1iNS_6double_T_(double l) { printf("%f\n", l); } extern "C" void _T5nbody5printFT1iNSs6double_T_(double l) { printf("%f\n", l); } // This cannot be implemented in swift.swift until we have pattern matching. extern "C" bool _TSs19convertToLogicValueFT1vNSs4bool_i1(bool b) { return b; } extern "C" double _TNSs6double26convert_from_float_literalFT3valf64_S_(double x) { return x; }
Check that image in message dialog is not bigger than screen
#include <QPixmap> #include "restdialog.h" RestDialog::RestDialog(QWidget *parent) : QDialog(parent) { Qt::WindowFlags flags = windowFlags(); setWindowFlags((flags & ~Qt::WindowContextHelpButtonHint) | Qt::WindowStaysOnTopHint); ui_restDialog = QSharedPointer<Ui::RestDialog>(new Ui::RestDialog()); ui_restDialog->setupUi(this); // set message QString message = settings.value("message", QString()).toString(); ui_restDialog->messageLabel->setText(message); // possibly set image bool useImage = settings.value("use_img", false).toBool(); if (useImage) setImage(); activateWindow(); } void RestDialog::setImage() { QString imagePath = settings.value("img_path", QString()).toString(); QPixmap image(imagePath); if (image.isNull()) return; ui_restDialog->imageLabel->setPixmap(image); } bool RestDialog::isPostponed() const { return ui_restDialog->afterCheckBox->isChecked(); }
#include <QPixmap> #include <QDesktopWidget> #include "restdialog.h" RestDialog::RestDialog(QWidget *parent) : QDialog(parent) { Qt::WindowFlags flags = windowFlags(); setWindowFlags((flags & ~Qt::WindowContextHelpButtonHint) | Qt::WindowStaysOnTopHint); ui_restDialog = QSharedPointer<Ui::RestDialog>(new Ui::RestDialog()); ui_restDialog->setupUi(this); // set message QString message = settings.value("message", QString()).toString(); ui_restDialog->messageLabel->setText(message); // possibly set image bool useImage = settings.value("use_img", false).toBool(); if (useImage) setImage(); activateWindow(); } void RestDialog::setImage() { QString imagePath = settings.value("img_path", QString()).toString(); QPixmap image(imagePath); if (image.isNull()) return; // check that image is not bigger than screen resolution QSize imageSize = image.size(); int screenWidth = QApplication::desktop()->width(); int screenHeight = QApplication::desktop()->height(); if ((imageSize.height() >= screenHeight) || (imageSize.width() >= screenWidth)) { // let's scale it image = image.scaled((screenWidth - width() - 50), (screenHeight - height() - 50), Qt::KeepAspectRatio); } ui_restDialog->imageLabel->setPixmap(image); } bool RestDialog::isPostponed() const { return ui_restDialog->afterCheckBox->isChecked(); }
Change AudioVoiceFadeBehaviour to use userGain
#include "behaviours/audio_voice_fade_behaviour.h" #include "../audio_voice.h" #include "audio_facade.h" #include "halley/utils/utils.h" using namespace Halley; AudioVoiceFadeBehaviour::AudioVoiceFadeBehaviour(float fadeTime, float sourceVolume, float targetVolume, bool stopAtEnd) : curTime(0) , fadeTime(fadeTime) , volume0(sourceVolume) , volume1(targetVolume) , stopAtEnd(stopAtEnd) { } void AudioVoiceFadeBehaviour::onAttach(AudioVoice& audioSource) { } bool AudioVoiceFadeBehaviour::update(float elapsedTime, AudioVoice& audioSource) { curTime += elapsedTime; const float t = clamp(curTime / fadeTime, 0.0f, 1.0f); const float volume = lerp(volume0, volume1, t); audioSource.getDynamicGainRef() *= gainToVolume(volume); if (curTime >= fadeTime) { if (stopAtEnd) { audioSource.stop(); } return false; } return true; }
#include "behaviours/audio_voice_fade_behaviour.h" #include "../audio_voice.h" #include "audio_facade.h" #include "halley/utils/utils.h" using namespace Halley; AudioVoiceFadeBehaviour::AudioVoiceFadeBehaviour(float fadeTime, float sourceVolume, float targetVolume, bool stopAtEnd) : curTime(0) , fadeTime(fadeTime) , volume0(sourceVolume) , volume1(targetVolume) , stopAtEnd(stopAtEnd) { } void AudioVoiceFadeBehaviour::onAttach(AudioVoice& audioSource) { } bool AudioVoiceFadeBehaviour::update(float elapsedTime, AudioVoice& audioSource) { curTime += elapsedTime; const float t = fadeTime == 0.0f ? 1.0f : clamp(curTime / fadeTime, 0.0f, 1.0f); const float volume = lerp(volume0, volume1, t); audioSource.setUserGain(audioSource.getDynamicGainRef() * gainToVolume(volume)); if (curTime >= fadeTime) { if (stopAtEnd) { audioSource.stop(); } return false; } return true; }
Mark a test case as unsupported on Windows
// RUN: %clangxx -w -fsanitize=bool %s -o %t // RUN: %run %t 2>&1 | FileCheck %s #include <iostream> extern "C" { void __ubsan_get_current_report_data(const char **OutIssueKind, const char **OutMessage, const char **OutFilename, unsigned *OutLine, unsigned *OutCol, char **OutMemoryAddr); // Override the weak definition of __ubsan_on_report from the runtime, just // for testing purposes. void __ubsan_on_report(void) { const char *IssueKind, *Message, *Filename; unsigned Line, Col; char *Addr; __ubsan_get_current_report_data(&IssueKind, &Message, &Filename, &Line, &Col, &Addr); std::cout << "Issue: " << IssueKind << "\n" << "Location: " << Filename << ":" << Line << ":" << Col << "\n" << "Message: " << Message << std::endl; (void)Addr; } } int main() { char C = 3; bool B = *(bool *)&C; // CHECK: Issue: invalid-bool-load // CHECK-NEXT: Location: {{.*}}monitor.cpp:[[@LINE-2]]:12 // CHECK-NEXT: Message: Load of value 3, which is not a valid value for type 'bool' return 0; }
// RUN: %clangxx -w -fsanitize=bool %s -o %t // RUN: %run %t 2>&1 | FileCheck %s // __ubsan_on_report is not defined as weak. Redefining it here isn't supported // on Windows. // // UNSUPPORTED: win32 #include <iostream> extern "C" { void __ubsan_get_current_report_data(const char **OutIssueKind, const char **OutMessage, const char **OutFilename, unsigned *OutLine, unsigned *OutCol, char **OutMemoryAddr); // Override the definition of __ubsan_on_report from the runtime, just for // testing purposes. void __ubsan_on_report(void) { const char *IssueKind, *Message, *Filename; unsigned Line, Col; char *Addr; __ubsan_get_current_report_data(&IssueKind, &Message, &Filename, &Line, &Col, &Addr); std::cout << "Issue: " << IssueKind << "\n" << "Location: " << Filename << ":" << Line << ":" << Col << "\n" << "Message: " << Message << std::endl; (void)Addr; } } int main() { char C = 3; bool B = *(bool *)&C; // CHECK: Issue: invalid-bool-load // CHECK-NEXT: Location: {{.*}}monitor.cpp:[[@LINE-2]]:12 // CHECK-NEXT: Message: Load of value 3, which is not a valid value for type 'bool' return 0; }
Remove an unused const kInvalidExtensionNamespace.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/extensions/api_definitions_natives.h" #include <algorithm> #include "chrome/common/extensions/features/base_feature_provider.h" namespace { const char kInvalidExtensionNamespace[] = "Invalid extension namespace"; } namespace extensions { ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher, ChromeV8Context* context) : ChromeV8Extension(dispatcher, context) { RouteFunction("GetExtensionAPIDefinitionsForTest", base::Bind( &ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest, base::Unretained(this))); } void ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest( const v8::FunctionCallbackInfo<v8::Value>& args) { std::vector<std::string> apis; FeatureProvider* feature_provider = BaseFeatureProvider::GetByName("api"); const std::vector<std::string>& feature_names = feature_provider->GetAllFeatureNames(); for (std::vector<std::string>::const_iterator i = feature_names.begin(); i != feature_names.end(); ++i) { if (!feature_provider->GetParent(feature_provider->GetFeature(*i)) && context()->GetAvailability(*i).is_available()) { apis.push_back(*i); } } args.GetReturnValue().Set( dispatcher()->v8_schema_registry()->GetSchemas(apis)); } } // namespace extensions
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/extensions/api_definitions_natives.h" #include <algorithm> #include "chrome/common/extensions/features/base_feature_provider.h" namespace extensions { ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher, ChromeV8Context* context) : ChromeV8Extension(dispatcher, context) { RouteFunction("GetExtensionAPIDefinitionsForTest", base::Bind( &ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest, base::Unretained(this))); } void ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest( const v8::FunctionCallbackInfo<v8::Value>& args) { std::vector<std::string> apis; FeatureProvider* feature_provider = BaseFeatureProvider::GetByName("api"); const std::vector<std::string>& feature_names = feature_provider->GetAllFeatureNames(); for (std::vector<std::string>::const_iterator i = feature_names.begin(); i != feature_names.end(); ++i) { if (!feature_provider->GetParent(feature_provider->GetFeature(*i)) && context()->GetAvailability(*i).is_available()) { apis.push_back(*i); } } args.GetReturnValue().Set( dispatcher()->v8_schema_registry()->GetSchemas(apis)); } } // namespace extensions
Use cerr in preference to stderr for assertion message.
#include <cstdio> #include <cstdlib> #include "util/debug.hpp" bool nest::mc::util::failed_assertion(const char *assertion, const char *file, int line, const char *func) { std::fprintf(stderr, "%s:%d %s: Assertion `%s' failed.\n", file, line, func, assertion); std::abort(); return false; }
#include <cstdlib> #include <iostream> #include "util/debug.hpp" bool nest::mc::util::failed_assertion(const char *assertion, const char *file, int line, const char *func) { // Explicit flush, as we can't assume default buffering semantics on stderr/cerr, // and abort() mignt not flush streams. std::cerr << file << ':' << line << " " << func << ": Assertion `" << assertion << "' failed." << std::endl; std::abort(); return false; }
Optimize sphere sampling code using trig identity
#include "./Sphere.hpp" #include "./misc.hpp" #include <algorithm> #include <cmath> namespace yks { Optional<float> intersect(const vec3& origin, float radius, const Ray& r) { const vec3 o = r.origin - origin; const vec3 v = r.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2); if (solutions == 0) { return Optional<float>(); } else if (solutions == 1) { return make_optional<float>(t1); } else { return make_optional<float>(std::min(t1, t2)); } } vec3 uniform_point_on_sphere(float a, float b) { const float y = 2.0f * a - 1.0f; const float latitude = std::asin(y); const float longitude = b * two_pi; const float cos_latitude = std::cos(latitude); return mvec3(cos_latitude * cos(longitude), y, cos_latitude * sin(longitude)); } }
#include "./Sphere.hpp" #include "./misc.hpp" #include <algorithm> #include <cmath> namespace yks { Optional<float> intersect(const vec3& origin, float radius, const Ray& r) { const vec3 o = r.origin - origin; const vec3 v = r.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2); if (solutions == 0) { return Optional<float>(); } else if (solutions == 1) { return make_optional<float>(t1); } else { return make_optional<float>(std::min(t1, t2)); } } vec3 uniform_point_on_sphere(float a, float b) { const float y = 2.0f * a - 1.0f; const float longitude = b * two_pi; const float cos_latitude = std::sqrt(1.0f - sqr(y)); return mvec3(cos_latitude * std::cos(longitude), y, cos_latitude * std::sin(longitude)); } }
Initialize and enable LEDs in animation to test
/* * AnimationTask.cpp * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <esp_log.h> #include "nvs_flash.h" #include "esp_wifi.h" #include "esp_system.h" #include "esp_event.h" #include "esp_event_loop.h" #include "AnimationTask.h" #include "sdkconfig.h" static char tag[] = "AnimationTask"; AnimationTask::AnimationTask(const char* taskName, I2C* i2c) : Esp32RtosTask(taskName), m_i2c(i2c) { } AnimationTask::~AnimationTask() { } void AnimationTask::run(void* data) { while (1) { ESP_LOGW(tag, "AnimationTask::run"); delay(1000); } }
/* * AnimationTask.cpp * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <esp_log.h> #include "nvs_flash.h" #include "esp_wifi.h" #include "esp_system.h" #include "esp_event.h" #include "esp_event_loop.h" #include "AnimationTask.h" #include "sdkconfig.h" static char tag[] = "AnimationTask"; AnimationTask::AnimationTask(const char* taskName, I2C* i2c) : Esp32RtosTask(taskName), m_i2c(i2c) { } AnimationTask::~AnimationTask() { } void AnimationTask::run(void* data) { m_i2c->init(I2C_NUM_1, I2C_MODE_MASTER, GPIO_NUM_18, GPIO_NUM_19, GPIO_PULLUP_DISABLE, GPIO_PULLUP_DISABLE, 100000); m_i2c->i2c_is31_init(I2C_NUM_1); while (1) { ESP_LOGW(tag, "AnimationTask::run"); m_i2c->i2c_is31_pwm(I2C_NUM_1); m_i2c->i2c_is31_en(I2C_NUM_1); delay(1000); } }
Fix animation task, run should not return
/* * AnimationTask.cpp * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <esp_log.h> #include "AnimationTask.h" #include "sdkconfig.h" static char tag[] = "AnimationTask"; AnimationTask::AnimationTask(std::string taskName) : Task(taskName) { } AnimationTask::~AnimationTask() { } void AnimationTask::run(void *data) { ESP_LOGW(tag, "AnimationTask::run"); }
/* * AnimationTask.cpp * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <esp_log.h> #include "AnimationTask.h" #include "sdkconfig.h" static char tag[] = "AnimationTask"; AnimationTask::AnimationTask(std::string taskName) : Task(taskName) { } AnimationTask::~AnimationTask() { } void AnimationTask::run(void *data) { while (1) { ESP_LOGW(tag, "AnimationTask::run"); delay(1000); } }
Fix miner_test unit test bug
#include <boost/test/unit_test.hpp> #include "../uint256.h" extern void SHA256Transform(void* pstate, void* pinput, const void* pinit); BOOST_AUTO_TEST_SUITE(miner_tests) BOOST_AUTO_TEST_CASE(sha256transform_equality) { unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; unsigned char pstate[32]; unsigned char pinput[32]; int i; for (i = 0; i < 32; i++) { pinput[i] = i; pstate[i] = 0; } uint256 hash; SHA256Transform(&hash, pinput, pSHA256InitState); BOOST_TEST_MESSAGE(hash.GetHex()); uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3"); BOOST_CHECK(hash == hash_reference); } BOOST_AUTO_TEST_SUITE_END()
#include <boost/test/unit_test.hpp> #include "../uint256.h" extern void SHA256Transform(void* pstate, void* pinput, const void* pinit); BOOST_AUTO_TEST_SUITE(miner_tests) BOOST_AUTO_TEST_CASE(sha256transform_equality) { unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; unsigned char pstate[32]; unsigned char pinput[64]; int i; for (i = 0; i < 32; i++) { pinput[i] = i; pinput[i+32] = 0; } uint256 hash; SHA256Transform(&hash, pinput, pSHA256InitState); BOOST_TEST_MESSAGE(hash.GetHex()); uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3"); BOOST_CHECK(hash == hash_reference); } BOOST_AUTO_TEST_SUITE_END()
Improve removal of dead basic blocks to remove all dead basic blocks at once
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // 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 "mtac/remove_dead_basic_blocks.hpp" #include "mtac/Function.hpp" using namespace eddic; bool mtac::remove_dead_basic_blocks::operator()(mtac::Function& function){ unsigned int before = function.bb_count(); if(before <= 2){ return false; } auto it = iterate(function); //ENTRY is always accessed ++it; while(it.has_next()){ auto& block = *it; if(block->predecessors.empty()){ it.erase(); } else { ++it; } } return function.bb_count() < before; }
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // 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 <unordered_set> #include "mtac/remove_dead_basic_blocks.hpp" #include "mtac/Function.hpp" using namespace eddic; bool mtac::remove_dead_basic_blocks::operator()(mtac::Function& function){ bool optimized; bool optimized_once = false; do { optimized = false; unsigned int before = function.bb_count(); if(before <= 2){ return optimized_once; } std::unordered_set<basic_block_p> live_basic_blocks; for(auto& basic_block : function){ if(basic_block->index < 0){ live_basic_blocks.insert(basic_block); } else { for(auto& predecessor : basic_block->predecessors){ if(live_basic_blocks.find(predecessor) != live_basic_blocks.end()){ live_basic_blocks.insert(basic_block); break; } } } } auto it = iterate(function); while(it.has_next()){ auto& block = *it; if(live_basic_blocks.find(block) == live_basic_blocks.end()){ it.erase(); } else { ++it; } } optimized = function.bb_count() < before; if(optimized){ optimized_once = true; } } while(optimized); return optimized_once; }
Switch default tag database from TXT to SQLite
#include "tags/tag-database-factory.h" #include <QFile> #include "tags/tag-database-in-memory.h" #include "tags/tag-database-sqlite.h" TagDatabase *TagDatabaseFactory::Create(QString directory) { if (!directory.endsWith("/") && !directory.endsWith("\\")) { directory += "/"; } const QString typesFile = directory + "tag-types.txt"; if (QFile::exists(directory + "tags.db")) { return new TagDatabaseSqlite(typesFile, directory + "tags.db"); } return new TagDatabaseInMemory(typesFile, directory + "tags.txt"); }
#include "tags/tag-database-factory.h" #include <QFile> #include "tags/tag-database-in-memory.h" #include "tags/tag-database-sqlite.h" TagDatabase *TagDatabaseFactory::Create(QString directory) { if (!directory.endsWith("/") && !directory.endsWith("\\")) { directory += "/"; } const QString typesFile = directory + "tag-types.txt"; if (QFile::exists(directory + "tags.txt")) { return new TagDatabaseInMemory(typesFile, directory + "tags.txt"); } return new TagDatabaseSqlite(typesFile, directory + "tags.db"); }
Fix buildbot break after r360195
// FIXME: The standalone module still seems to cause clang to want to test for // the existence of a 'foo' directory: // RUN: mkdir %t // RUN: cp %s %t // RUN: mkdir %t/foo // RUN: cd %t // RUN: not %clang_cc1 -fmodules -fsyntax-only %s 2>&1 | FileCheck %s // CHECK: error: no matching function for call to 'foo' // CHECK: note: candidate function not viable: requires 0 arguments, but 1 was provided // FIXME: This should use -verify, but it seems it doesn't hook up the // SourceManager correctly or something, and the foo.h note gets attributed to // the synthetic module translation unit "foo.map Line 2:...". // %clang_cc1 -fmodules -verify %s #pragma clang module build foo module foo { umbrella "foo" module * { export * } } #pragma clang module contents #pragma clang module begin foo.foo # 1 "foo.h" 1 #ifndef FOO_FOO_H void foo(); #endif #pragma clang module end #pragma clang module endbuild #pragma clang module import foo.foo // expected-note@foo.h:2 {{candidate function not viable: requires 0 arguments, but 1 was provided}} int main() { foo(1); // expected-error {{no matching function for call to 'foo'}} }
// FIXME: The standalone module still seems to cause clang to want to test for // the existence of a 'foo' directory: // RUN: rm -rf %t // RUN: mkdir %t // RUN: cp %s %t // RUN: rm -rf %t/foo // RUN: mkdir %t/foo // RUN: cd %t // RUN: not %clang_cc1 -fmodules -fsyntax-only %s 2>&1 | FileCheck %s // CHECK: error: no matching function for call to 'foo' // CHECK: note: candidate function not viable: requires 0 arguments, but 1 was provided // FIXME: This should use -verify, but it seems it doesn't hook up the // SourceManager correctly or something, and the foo.h note gets attributed to // the synthetic module translation unit "foo.map Line 2:...". // %clang_cc1 -fmodules -verify %s #pragma clang module build foo module foo { umbrella "foo" module * { export * } } #pragma clang module contents #pragma clang module begin foo.foo # 1 "foo.h" 1 #ifndef FOO_FOO_H void foo(); #endif #pragma clang module end #pragma clang module endbuild #pragma clang module import foo.foo // expected-note@foo.h:2 {{candidate function not viable: requires 0 arguments, but 1 was provided}} int main() { foo(1); // expected-error {{no matching function for call to 'foo'}} }
Remove old windows workaround for V8 function invokations.
#include <vector> #include <boost/any.hpp> #include <v8.h> #include "JSFunctionInvokable.hpp" #include "../JSObjectScript.hpp" #include "JSInvokableUtil.hpp" namespace Sirikata { namespace JS { boost::any JSFunctionInvokable::invoke(std::vector<boost::any>& params) { /* Invoke the function handle */ int argc = #ifdef _WIN32 1 #else 0 #endif ; int base_offset = argc; // need to work around windows weirdness argc += params.size(); v8::HandleScope handle_scope; v8::Context::Scope context_scope(script_->context()); std::vector<v8::Handle<v8::Value> >argv(argc); if (base_offset) argv[0] = v8::Handle<v8::Value>(); for(uint32 i = 0; i < params.size(); i++) argv[base_offset+i] = InvokableUtil::AnyToV8(script_, params[i]); //TryCatch try_catch; // We are currently executing in the global context of the entity // FIXME: need to take care fo the "this" pointer v8::Handle<v8::Value> result = script_->invokeCallback(function_, argc, &argv[0]); if(result.IsEmpty()) { /* v8::String::Utf8Value error(try_catch.Exception()); const char* cMsg = ToCString(error); std::cerr << cMsg << "\n"; */ } return boost::any(result) ; } } }
#include <vector> #include <boost/any.hpp> #include <v8.h> #include "JSFunctionInvokable.hpp" #include "../JSObjectScript.hpp" #include "JSInvokableUtil.hpp" namespace Sirikata { namespace JS { boost::any JSFunctionInvokable::invoke(std::vector<boost::any>& params) { /* Invoke the function handle */ int argc = params.size(); v8::HandleScope handle_scope; v8::Context::Scope context_scope(script_->context()); std::vector<v8::Handle<v8::Value> >argv(argc); for(uint32 i = 0; i < params.size(); i++) argv[i] = InvokableUtil::AnyToV8(script_, params[i]); //TryCatch try_catch; // We are currently executing in the global context of the entity // FIXME: need to take care fo the "this" pointer v8::Handle<v8::Value> result = script_->invokeCallback(function_, argc, &argv[0]); if(result.IsEmpty()) { /* v8::String::Utf8Value error(try_catch.Exception()); const char* cMsg = ToCString(error); std::cerr << cMsg << "\n"; */ } return boost::any(result) ; } } }
Fix warnings about conversion from string literal to char*
#include "TestUpdaterOptions.h" #include "TestUtils.h" #include "UpdaterOptions.h" void TestUpdaterOptions::testOldFormatArgs() { const int argc = 6; char* argv[argc]; argv[0] = "updater"; argv[1] = "CurrentDir=/path/to/app"; argv[2] = "TempDir=/tmp/updater"; argv[3] = "UpdateScriptFileName=/tmp/updater/file_list.xml"; argv[4] = "AppFileName=/path/to/app/theapp"; argv[5] = "PID=123456"; UpdaterOptions options; options.parse(argc,argv); TEST_COMPARE(options.mode,UpdateInstaller::Setup); TEST_COMPARE(options.installDir,"/path/to/app"); TEST_COMPARE(options.packageDir,"/tmp/updater"); TEST_COMPARE(options.scriptPath,"/tmp/updater/file_list.xml"); TEST_COMPARE(options.waitPid,123456); } int main(int,char**) { TestList<TestUpdaterOptions> tests; tests.addTest(&TestUpdaterOptions::testOldFormatArgs); return TestUtils::runTest(tests); }
#include "TestUpdaterOptions.h" #include "TestUtils.h" #include "UpdaterOptions.h" void TestUpdaterOptions::testOldFormatArgs() { const int argc = 6; char* argv[argc]; argv[0] = strdup("updater"); argv[1] = strdup("CurrentDir=/path/to/app"); argv[2] = strdup("TempDir=/tmp/updater"); argv[3] = strdup("UpdateScriptFileName=/tmp/updater/file_list.xml"); argv[4] = strdup("AppFileName=/path/to/app/theapp"); argv[5] = strdup("PID=123456"); UpdaterOptions options; options.parse(argc,argv); TEST_COMPARE(options.mode,UpdateInstaller::Setup); TEST_COMPARE(options.installDir,"/path/to/app"); TEST_COMPARE(options.packageDir,"/tmp/updater"); TEST_COMPARE(options.scriptPath,"/tmp/updater/file_list.xml"); TEST_COMPARE(options.waitPid,123456); for (int i=0; i < argc; i++) { free(argv[i]); } } int main(int,char**) { TestList<TestUpdaterOptions> tests; tests.addTest(&TestUpdaterOptions::testOldFormatArgs); return TestUtils::runTest(tests); }
Add support for 'Source' in Item::WrapInstance.
#include "Item.h" using namespace node; using namespace v8; namespace node_iTunes { // Convenience function that takes an iTunesItem instance (or any subclass) // and wraps it up into the proper JS class type, and returns it. // TODO: Implement some kind of Object Cache, so if the same instance is // attempting to be wrapped again, then the same JS Object is returned. v8::Handle<Value> Item::WrapInstance(iTunesItem* item) { HandleScope scope; //NSLog(@"%@", [item persistentID]); if (item == nil) { return scope.Close(Null()); } NSString* className = NSStringFromClass([item class]); //NSLog(@"Class: %@", className); Local<Object> jsItem; if ([className isEqualToString:@"ITunesURLTrack" ]) { jsItem = url_track_constructor_template->GetFunction()->NewInstance(); } else if ([className isEqualToString:@"ITunesFileTrack" ]) { jsItem = file_track_constructor_template->GetFunction()->NewInstance(); } else if ([className isEqualToString:@"ITunesTrack" ]) { jsItem = track_constructor_template->GetFunction()->NewInstance(); } else { jsItem = item_constructor_template->GetFunction()->NewInstance(); } Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem); itemWrap->itemRef = item; return scope.Close(jsItem); } }
#include "Item.h" using namespace node; using namespace v8; namespace node_iTunes { // Convenience function that takes an iTunesItem instance (or any subclass) // and wraps it up into the proper JS class type, and returns it. // TODO: Implement some kind of Object Cache, so if the same instance is // attempting to be wrapped again, then the same JS Object is returned. v8::Handle<Value> Item::WrapInstance(iTunesItem* item) { HandleScope scope; //NSLog(@"%@", [item persistentID]); if (item == nil) { return scope.Close(Null()); } NSString* className = NSStringFromClass([item class]); //NSLog(@"Class: %@", className); Local<Object> jsItem; if ([className isEqualToString:@"ITunesURLTrack" ]) { jsItem = url_track_constructor_template->GetFunction()->NewInstance(); } else if ([className isEqualToString:@"ITunesFileTrack" ]) { jsItem = file_track_constructor_template->GetFunction()->NewInstance(); } else if ([className isEqualToString:@"ITunesTrack" ]) { jsItem = track_constructor_template->GetFunction()->NewInstance(); } else if ([className isEqualToString:@"ITunesSource" ]) { jsItem = source_constructor_template->GetFunction()->NewInstance(); } else { jsItem = item_constructor_template->GetFunction()->NewInstance(); } Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem); itemWrap->itemRef = item; return scope.Close(jsItem); } }
Address potential issues encountered in non-ROCm systems.
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/rocm_rocdl_path.h" #include <stdlib.h> #if !defined(PLATFORM_GOOGLE) #include "third_party/gpus/rocm/rocm_config.h" #endif #include "tensorflow/core/platform/logging.h" namespace tensorflow { string ROCmRoot() { VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH; return TF_ROCM_TOOLKIT_PATH; } } // namespace tensorflow
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/rocm_rocdl_path.h" #include <stdlib.h> #if !defined(PLATFORM_GOOGLE) && TENSORFLOW_USE_ROCM #include "third_party/gpus/rocm/rocm_config.h" #endif #include "tensorflow/core/platform/logging.h" namespace tensorflow { string ROCmRoot() { #if TENSORFLOW_USE_ROCM VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH; return TF_ROCM_TOOLKIT_PATH; #else return ""; #endif } } // namespace tensorflow
Add python binding to BackendError
#include "xchainer/python/error.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; // standard convention void InitXchainerError(pybind11::module& m) { py::register_exception<XchainerError>(m, "XchainerError"); py::register_exception<DeviceError>(m, "DeviceError"); py::register_exception<DtypeError>(m, "DtypeError"); py::register_exception<DimensionError>(m, "DimensionError"); } } // namespace xchainer
#include "xchainer/python/error.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; // standard convention void InitXchainerError(pybind11::module& m) { py::register_exception<XchainerError>(m, "XchainerError"); py::register_exception<BackendError>(m, "BackendError"); py::register_exception<DeviceError>(m, "DeviceError"); py::register_exception<DtypeError>(m, "DtypeError"); py::register_exception<DimensionError>(m, "DimensionError"); } } // namespace xchainer
Remove needless hack for the newest oj version
#include "../include/graph/dijkstra.cpp" #include "../include/graph/weighted_graph.cpp" #include "../include/others/fast_cin.cpp" #include "../include/others/fast_cout.cpp" using Graph = WeightedGraph<long long>; int main() { int n, m, s, t; fcin >> n >> m >> s >> t; Graph rg(n); for (int i = 0; i < m; ++i) { int a, b; long long c; fcin >> a >> b >> c; add_edge(rg, b, a, c); } std::vector<int> prev; auto d = dijkstra(rg, t, prev); if (d[s] == inf<long long>()) { fcout << -1 << fendl; return 0; } if (d[s] == 0) { // Hack for multiple solutions. fcout << 0 << " " << 1 << fendl; fcout << s << " " << t << fendl; return 0; } std::vector<int> trace; trace.reserve(m); trace.push_back(s); while (trace.back() != t) { int v = trace.back(); trace.push_back(prev[v]); } int size = trace.size() - 1; fcout << d[s] << " " << size << fendl; for (int i = 0; i < size; ++i) { fcout << trace[i] << " " << trace[i + 1] << fendl; } return 0; }
#include "../include/graph/dijkstra.cpp" #include "../include/graph/weighted_graph.cpp" #include "../include/others/fast_cin.cpp" #include "../include/others/fast_cout.cpp" using Graph = WeightedGraph<long long>; int main() { int n, m, s, t; fcin >> n >> m >> s >> t; Graph rg(n); for (int i = 0; i < m; ++i) { int a, b; long long c; fcin >> a >> b >> c; add_edge(rg, b, a, c); } std::vector<int> prev; auto d = dijkstra(rg, t, prev); if (d[s] == inf<long long>()) { fcout << -1 << fendl; return 0; } std::vector<int> trace; trace.reserve(m); trace.push_back(s); while (trace.back() != t) { int v = trace.back(); trace.push_back(prev[v]); } int size = trace.size() - 1; fcout << d[s] << " " << size << fendl; for (int i = 0; i < size; ++i) { fcout << trace[i] << " " << trace[i + 1] << fendl; } return 0; }
Remove some dead code in the printgcode test.
#include <catch.hpp> #include <string> #include "test_data.hpp" #include "libslic3r.h" using namespace Slic3r::Test; using namespace std::literals; SCENARIO("PrintObject: object layer heights") { GIVEN("20mm cube and config that has a 3mm nozzle and a 2mm requested layer height") { auto config {Slic3r::Config::new_from_defaults()}; TestMesh m { TestMesh::cube_20x20x20 }; Slic3r::Model model; auto event_counter {0U}; std::string stage; int value {0}; config->set("fill_density", 0); config->set("nozzle_diameter", "3"); config->set("layer_height", 2.0); config->set("first_layer_height", 2.0); WHEN("generate_object_layers() is called with a starting layer of 2mm") { auto print {Slic3r::Test::init_print({m}, model, config)}; const auto& object = *(print->objects.at(0)); auto result {print->objects[0]->generate_object_layers(2.0)}; THEN("The output vector has 10 entries") { REQUIRE(result.size() == 10); } AND_THEN("Each layer is approximately 2mm above the previous Z") { coordf_t last = 0.0; for (size_t i = 0; i < result.size(); i++) { REQUIRE((result[i] - last) == Approx(2.0)); last = result[i]; } } } } }
#include <catch.hpp> #include <string> #include "test_data.hpp" #include "libslic3r.h" using namespace Slic3r::Test; using namespace std::literals; SCENARIO("PrintObject: object layer heights") { GIVEN("20mm cube and config that has a 3mm nozzle and a 2mm requested layer height") { auto config {Slic3r::Config::new_from_defaults()}; TestMesh m { TestMesh::cube_20x20x20 }; Slic3r::Model model; config->set("nozzle_diameter", "3"); config->set("layer_height", 2.0); config->set("first_layer_height", 2.0); WHEN("generate_object_layers() is called with a starting layer of 2mm") { auto print {Slic3r::Test::init_print({m}, model, config)}; auto result {print->objects[0]->generate_object_layers(2.0)}; THEN("The output vector has 10 entries") { REQUIRE(result.size() == 10); } AND_THEN("Each layer is approximately 2mm above the previous Z") { coordf_t last = 0.0; for (size_t i = 0; i < result.size(); i++) { REQUIRE((result[i] - last) == Approx(2.0)); last = result[i]; } } } } }
Move braces up onto same line as conditional.
#include "log.h" #include "ethernetutil.h" void initializeEthernet(EthernetDevice* device, Server* server, uint8_t MACAddr[], uint8_t IPAddr[]) { debug("initializing Ethernet..."); device->ptrServer = server; Ethernet.begin(MACAddr, IPAddr); device->ptrServer->begin(); } // The message bytes are sequentially popped from the // send queue to the send buffer. After the buffer is full // or the queue is emtpy, the contents of the buffer are // sent over the ethernet to listening clients. void processEthernetSendQueue(EthernetDevice* device) { unsigned int byteCount = 0; char sendBuffer[MAX_MESSAGE_SIZE]; while(!QUEUE_EMPTY(uint8_t, &device->sendQueue) && byteCount < MAX_MESSAGE_SIZE) { sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue); } device->ptrServer->write((uint8_t*) sendBuffer, byteCount); }
#include "log.h" #include "ethernetutil.h" void initializeEthernet(EthernetDevice* device, Server* server, uint8_t MACAddr[], uint8_t IPAddr[]) { debug("initializing Ethernet..."); device->ptrServer = server; Ethernet.begin(MACAddr, IPAddr); device->ptrServer->begin(); } // The message bytes are sequentially popped from the // send queue to the send buffer. After the buffer is full // or the queue is emtpy, the contents of the buffer are // sent over the ethernet to listening clients. void processEthernetSendQueue(EthernetDevice* device) { unsigned int byteCount = 0; char sendBuffer[MAX_MESSAGE_SIZE]; while(!QUEUE_EMPTY(uint8_t, &device->sendQueue) && byteCount < MAX_MESSAGE_SIZE) { sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue); } device->ptrServer->write((uint8_t*) sendBuffer, byteCount); }
Remove unneeded include which is breaking build.
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFontHost.h" #include "SkTypeface.h" #include "SkTypeface_win.h" //static void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) { //No sandbox, nothing to do. }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFontHost.h" #include "SkTypeface.h" //static void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) { //No sandbox, nothing to do. }
Fix logic error in kml region parsing (region never attached to doc).
// // 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 2009 Bastian Holst <bastianholst@gmx.de> // #include "KmlRegionTagHandler.h" #include "MarbleDebug.h" #include "KmlElementDictionary.h" #include "GeoDataFeature.h" #include "GeoParser.h" #include "GeoDataRegion.h" namespace Marble { namespace kml { KML_DEFINE_TAG_HANDLER( Region ) GeoNode* KmlRegionTagHandler::parse( GeoParser& parser ) const { Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_Region ) ); GeoDataRegion region; GeoStackItem parentItem = parser.parentElement(); #ifdef DEBUG_TAGS mDebug() << "Parsed <" << kmlTag_Region << ">" << " parent item name: " << parentItem.qualifiedName().first; #endif if( parentItem.represents( kmlTag_Region ) || parentItem.represents( kmlTag_Region ) ) { parentItem.nodeAs<GeoDataFeature>()->setRegion( region ); return &parentItem.nodeAs<GeoDataFeature>()->region(); } else { return 0; } } } }
// // 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 2009 Bastian Holst <bastianholst@gmx.de> // #include "KmlRegionTagHandler.h" #include "MarbleDebug.h" #include "KmlElementDictionary.h" #include "GeoDataFeature.h" #include "GeoParser.h" #include "GeoDataRegion.h" namespace Marble { namespace kml { KML_DEFINE_TAG_HANDLER( Region ) GeoNode* KmlRegionTagHandler::parse( GeoParser& parser ) const { Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_Region ) ); GeoDataRegion region; GeoStackItem parentItem = parser.parentElement(); #ifdef DEBUG_TAGS mDebug() << "Parsed <" << kmlTag_Region << ">" << " parent item name: " << parentItem.qualifiedName().first; #endif if( parentItem.is<GeoDataFeature>() ) { parentItem.nodeAs<GeoDataFeature>()->setRegion( region ); return &parentItem.nodeAs<GeoDataFeature>()->region(); } else { return 0; } } } }
Fix DecodeHexTx fuzzing harness issue
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <primitives/transaction.h> #include <test/fuzz/fuzz.h> #include <util/strencodings.h> #include <cassert> #include <cstdint> #include <string> #include <vector> void test_one_input(const std::vector<uint8_t>& buffer) { const std::string tx_hex = HexStr(buffer); CMutableTransaction mtx; const bool result_none = DecodeHexTx(mtx, tx_hex, false, false); const bool result_try_witness = DecodeHexTx(mtx, tx_hex, false, true); const bool result_try_witness_and_maybe_no_witness = DecodeHexTx(mtx, tx_hex, true, true); const bool result_try_no_witness = DecodeHexTx(mtx, tx_hex, true, false); assert(!result_none); if (result_try_witness_and_maybe_no_witness) { assert(result_try_no_witness || result_try_witness); } // if (result_try_no_witness) { // Uncomment when https://github.com/bitcoin/bitcoin/pull/17775 is merged if (result_try_witness) { // Remove stop-gap when https://github.com/bitcoin/bitcoin/pull/17775 is merged assert(result_try_witness_and_maybe_no_witness); } }
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <primitives/transaction.h> #include <test/fuzz/fuzz.h> #include <util/strencodings.h> #include <cassert> #include <cstdint> #include <string> #include <vector> void test_one_input(const std::vector<uint8_t>& buffer) { const std::string tx_hex = HexStr(buffer); CMutableTransaction mtx; const bool result_none = DecodeHexTx(mtx, tx_hex, false, false); const bool result_try_witness = DecodeHexTx(mtx, tx_hex, false, true); const bool result_try_witness_and_maybe_no_witness = DecodeHexTx(mtx, tx_hex, true, true); const bool result_try_no_witness = DecodeHexTx(mtx, tx_hex, true, false); assert(!result_none); if (result_try_witness_and_maybe_no_witness) { assert(result_try_no_witness || result_try_witness); } if (result_try_no_witness) { assert(result_try_witness_and_maybe_no_witness); } }
Add support for basic ops in LLVM
#include "mem/st/visitor/DepBuilder.hpp" namespace mem { namespace st { namespace visitor { DepBuilder::DepBuilder () { _name = "st.DepBuilder"; } bool DepBuilder::visit (st::Symbol* sym) { printf("Visit...\n"); if (sym->isClassSymbol()) { visitClass(static_cast<st::Class*>(sym)); } return true; } void DepBuilder::visitClass (st::Class* cls_sym) { printf("Visiting CLS !\n"); _dep_tree.addDependency(NULL, cls_sym); } } } }
#include "mem/st/visitor/DepBuilder.hpp" namespace mem { namespace st { namespace visitor { DepBuilder::DepBuilder () { _name = "st.DepBuilder"; } bool DepBuilder::visit (st::Symbol* sym) { if (sym->isClassSymbol()) { visitClass(static_cast<st::Class*>(sym)); } return true; } void DepBuilder::visitClass (st::Class* cls_sym) { _dep_tree.addDependency(NULL, cls_sym); } } } }
Add MetaEvent EventType cast test
#include <MetaEvent.h> #include <MetaFactory.h> #include <ratio> namespace test { namespace metaEventSuite { using namespace id::attribute; using namespace std; class MetaEventSuite : public ::testing::Test { public: ID posID = Position::value(); MetaFactory& f=MetaFactory::instance(); MetaEvent e; MetaEventSuite(){ MetaAttribute position = posID; position.value() = f.create({{0,1}, {1,1}, {2,1}}); position.unit() = Meter(); position.scale() = ratio<1, 1000>(); e.add(position); } }; TEST_F(MetaEventSuite, findAttributeTest) { MetaAttribute test = posID; test.value() = f.create({{0,1}, {1,1}, {2,1}}); test.unit() = Meter(); test.scale() = ratio<1, 1000>(); const MetaAttribute* posPtr = e.attribute(posID); ASSERT_NE(posPtr, nullptr) << "Position attribute could not be retrieved"; const MetaAttribute& pos = *posPtr; EXPECT_EQ(pos, test) << "Position attribute not stored correctly"; } }}
#include <MetaEvent.h> #include <MetaFactory.h> #include <ratio> namespace test { namespace metaEventSuite { using namespace id::attribute; using namespace std; class MetaEventSuite : public ::testing::Test { public: ID posID = Position::value(); MetaFactory& f=MetaFactory::instance(); MetaEvent e; MetaEventSuite(){ MetaAttribute position = posID; position.value() = f.create({{{0,1}, {1,1}, {2,1}}}); position.unit() = Meter(); position.scale() = ratio<1, 1000>(); e.add(position); } }; TEST_F(MetaEventSuite, findAttributeTest) { MetaAttribute test = posID; test.value() = f.create({{0, 1, 2}}); test.unit() = Meter(); test.scale() = ratio<1, 1000>(); const MetaAttribute* posPtr = e.attribute(posID); ASSERT_NE(posPtr, nullptr) << "Position attribute could not be retrieved"; const MetaAttribute& pos = *posPtr; EXPECT_EQ(pos, test) << "Position attribute not stored correctly"; } TEST_F(MetaEventSuite, typeTest) { EventType eT; eT.add(AttributeType(posID, ValueType(id::type::Double::value(), 1, 3, true), ratio<1,1000>(), Meter())); EXPECT_EQ((EventType)e, eT) << "Inferred MetaEvent-Type is wrong"; } }}
Add a test case for attribute print.
// RUN: %clang_cc1 %s -ast-print -fms-extensions | FileCheck %s // FIXME: align attribute print // CHECK: int x __attribute__((aligned(4, 0))); int x __attribute__((aligned(4))); // FIXME: Print this at a valid location for a __declspec attr. // CHECK: int y __declspec(align(4, 1)); __declspec(align(4)) int y; // CHECK: void foo() __attribute__((const)); void foo() __attribute__((const)); // CHECK: void bar() __attribute__((__const)); void bar() __attribute__((__const));
// RUN: %clang_cc1 %s -ast-print -fms-extensions | FileCheck %s // FIXME: align attribute print // CHECK: int x __attribute__((aligned(4, 0))); int x __attribute__((aligned(4))); // FIXME: Print this at a valid location for a __declspec attr. // CHECK: int y __declspec(align(4, 1)); __declspec(align(4)) int y; // CHECK: void foo() __attribute__((const)); void foo() __attribute__((const)); // CHECK: void bar() __attribute__((__const)); void bar() __attribute__((__const)); // FIXME: Print this with correct format and order. // CHECK: void foo1() __attribute__((pure)) __attribute__((noinline)); void foo1() __attribute__((noinline, pure));
Remove duplicate class from testbench. Otherwise wrong constructor gets run on OS X without any flaw in nbind itself.
// This file is part of nbind, copyright (C) 2014-2015 BusFaster Ltd. // Released under the MIT license, see LICENSE. #include <cstdio> #include "nbind/api.h" #include "Coord.h" class Nullable { public: static Coord *getCoord() { return(new Coord(60, 25)); } static Coord *getNull() { return(nullptr); } static void foo(Coord *coord) { printf("%p\n", coord); } static void bar(Coord *coord) { printf("%p\n", coord); } }; #include "nbind/nbind.h" #ifdef NBIND_CLASS NBIND_CLASS(Coord) {} NBIND_CLASS(Nullable) { method(getCoord); method(getNull); method(foo); method(bar, "bar", nbind::Nullable()); } #endif
// This file is part of nbind, copyright (C) 2014-2015 BusFaster Ltd. // Released under the MIT license, see LICENSE. #include <cstdio> #include "nbind/api.h" #include "Coord.h" class Nullable { public: static Coord *getCoord() { return(new Coord(60, 25)); } static Coord *getNull() { return(nullptr); } static void foo(Coord *coord) { printf("%p\n", coord); } static void bar(Coord *coord) { printf("%p\n", coord); } }; #include "nbind/nbind.h" #ifdef NBIND_CLASS NBIND_CLASS(Nullable) { method(getCoord); method(getNull); method(foo); method(bar, "bar", nbind::Nullable()); } #endif
Switch search algorithms via command-line arguments.
#include "mdist.hpp" #include "../search/idastar.hpp" #include "../search/astar.hpp" #include "../incl/utils.hpp" #include <cstdio> static void search(TilesMdist &, Search<TilesMdist> &, TilesMdist::State &); int main(int argc, char *argv[]) { TilesMdist d(stdin); // Idastar<TilesMdist, true, true> srch; Astar<TilesMdist, true> srch; TilesMdist::State s0 = d.initstate(); search(d, srch, s0); return 0; } static void search(TilesMdist &d, Search<TilesMdist> &srch, TilesMdist::State &s0) { dfheader(stdout); dfpair(stdout, "initial heuristic", "%d", d.h(s0)); Result<TilesMdist> res = srch.search(d, s0); res.output(stdout); dffooter(stdout); }
#include "mdist.hpp" #include "../search/idastar.hpp" #include "../search/astar.hpp" #include "../incl/utils.hpp" #include <cstdio> static void search(TilesMdist&, Search<TilesMdist>&, TilesMdist::State&); static Search<TilesMdist> *getsearch(int, char *[]); int main(int argc, char *argv[]) { TilesMdist d(stdin); Search<TilesMdist> *srch = getsearch(argc, argv); TilesMdist::State s0 = d.initstate(); search(d, *srch, s0); delete srch; return 0; } static void search(TilesMdist &d, Search<TilesMdist> &srch, TilesMdist::State &s0) { dfheader(stdout); dfpair(stdout, "initial heuristic", "%d", d.h(s0)); Result<TilesMdist> res = srch.search(d, s0); res.output(stdout); dffooter(stdout); } static Search<TilesMdist> *getsearch(int argc, char *argv[]) { Search<TilesMdist> *srch = NULL; if (argc > 1 && strcmp(argv[1], "idastar") == 0) srch = new Idastar<TilesMdist, true, true>(); else srch = new Astar<TilesMdist, true>(); return srch; }
Add SinogramCreatorMC to manager list
/** * @copyright Copyright 2017 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 main.cpp */ #include "JPetManager/JPetManager.h" #include "ImageReco.h" #include "SinogramCreator.h" using namespace std; int main(int argc, const char* argv[]) { JPetManager& manager = JPetManager::getManager(); manager.registerTask<ImageReco>("ImageReco"); manager.registerTask<SinogramCreator>("SinogramCreator"); manager.useTask("ImageReco", "unk.evt", "reco"); manager.useTask("SinogramCreator", "unk.evt", "sino"); manager.run(argc, argv); }
/** * @copyright Copyright 2017 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 main.cpp */ #include "JPetManager/JPetManager.h" #include "ImageReco.h" #include "SinogramCreator.h" #include "SinogramCreatorMC.h" using namespace std; int main(int argc, const char* argv[]) { JPetManager& manager = JPetManager::getManager(); manager.registerTask<ImageReco>("ImageReco"); manager.registerTask<SinogramCreator>("SinogramCreator"); manager.registerTask<SinogramCreator>("SinogramCreatorMC"); manager.useTask("ImageReco", "unk.evt", "reco"); manager.useTask("SinogramCreator", "unk.evt", "sino"); manager.useTask("SinogramCreatorMC", "unk.evt", "sino"); manager.run(argc, argv); }
Change this triple back to %itanium_abi_triple
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instr-generate | FileCheck %s struct Member { ~Member(); }; struct A { virtual ~A(); }; struct B : A { Member m; virtual ~B(); }; // Complete dtor // CHECK: @__llvm_profile_name__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev" // Deleting dtor // CHECK: @__llvm_profile_name__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev" // Complete dtor counters and profile data // CHECK: @__llvm_profile_counters__ZN1BD1Ev = private global [1 x i64] zeroinitializer // CHECK: @__llvm_profile_data__ZN1BD1Ev = // Deleting dtor counters and profile data // CHECK: @__llvm_profile_counters__ZN1BD0Ev = private global [1 x i64] zeroinitializer // CHECK: @__llvm_profile_data__ZN1BD0Ev = B::~B() { }
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instr-generate | FileCheck %s struct Member { ~Member(); }; struct A { virtual ~A(); }; struct B : A { Member m; virtual ~B(); }; // Complete dtor // CHECK: @__llvm_profile_name__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev" // Deleting dtor // CHECK: @__llvm_profile_name__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev" // Complete dtor counters and profile data // CHECK: @__llvm_profile_counters__ZN1BD1Ev = private global [1 x i64] zeroinitializer // CHECK: @__llvm_profile_data__ZN1BD1Ev = // Deleting dtor counters and profile data // CHECK: @__llvm_profile_counters__ZN1BD0Ev = private global [1 x i64] zeroinitializer // CHECK: @__llvm_profile_data__ZN1BD0Ev = B::~B() { }
Make linear scan the default
//===-- Passes.cpp - Target independent code generation passes ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines interfaces to access the target independent code // generation passes provided by the LLVM backend. // //===---------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "Support/CommandLine.h" #include <iostream> using namespace llvm; namespace { enum RegAllocName { simple, local, linearscan, iterativescan }; cl::opt<RegAllocName> RegAlloc( "regalloc", cl::desc("Register allocator to use: (default = simple)"), cl::Prefix, cl::values( clEnumVal(simple, " simple register allocator"), clEnumVal(local, " local register allocator"), clEnumVal(linearscan, " linear scan register allocator"), clEnumVal(iterativescan, " iterative scan register allocator"), clEnumValEnd), cl::init(local)); } FunctionPass *llvm::createRegisterAllocator() { switch (RegAlloc) { default: std::cerr << "no register allocator selected"; abort(); case simple: return createSimpleRegisterAllocator(); case local: return createLocalRegisterAllocator(); case linearscan: return createLinearScanRegisterAllocator(); case iterativescan: return createIterativeScanRegisterAllocator(); } }
//===-- Passes.cpp - Target independent code generation passes ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines interfaces to access the target independent code // generation passes provided by the LLVM backend. // //===---------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "Support/CommandLine.h" #include <iostream> using namespace llvm; namespace { enum RegAllocName { simple, local, linearscan, iterativescan }; cl::opt<RegAllocName> RegAlloc( "regalloc", cl::desc("Register allocator to use: (default = simple)"), cl::Prefix, cl::values( clEnumVal(simple, " simple register allocator"), clEnumVal(local, " local register allocator"), clEnumVal(linearscan, " linear scan register allocator"), clEnumVal(iterativescan, " iterative scan register allocator"), clEnumValEnd), cl::init(linearscan)); } FunctionPass *llvm::createRegisterAllocator() { switch (RegAlloc) { default: std::cerr << "no register allocator selected"; abort(); case simple: return createSimpleRegisterAllocator(); case local: return createLocalRegisterAllocator(); case linearscan: return createLinearScanRegisterAllocator(); case iterativescan: return createIterativeScanRegisterAllocator(); } }
Use RTLD_DEEPBIND to make sure plugins don't use Chrome's symbols instead of their own
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY); if (!dl) NOTREACHED() << "dlopen failed: " << dlerror(); return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) NOTREACHED() << "dlclose failed: " << dlerror(); } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, NativeLibraryFunctionNameType name) { return dlsym(library, name); } } // namespace base
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY|RTLD_DEEPBIND); if (!dl) NOTREACHED() << "dlopen failed: " << dlerror(); return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) NOTREACHED() << "dlclose failed: " << dlerror(); } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, NativeLibraryFunctionNameType name) { return dlsym(library, name); } } // namespace base
Fix SRM 147, Div 2, Problem CCipher
#include<string> using namespace std; class CCipher { public: string decode(string cipherText, int shift) { string orig; for (char c : cipherText) { orig += 'A' + (c - 'A' - shift) % 26 ; //orig.append(); } return orig; } };
#include<cassert> #include<string> using namespace std; class CCipher { public: string decode(string cipherText, int shift) { string orig; for (char c : cipherText) { orig += 'A' + (c - 'A' - shift + 26) % 26 ; } return orig; } }; int main() { CCipher cc; assert(cc.decode("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10) == "QRSTUVWXYZABCDEFGHIJKLMNOP"); }
Add a few more API bindings
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/node_includes.h" namespace { void Initialize(v8::Handle<v8::Object> exports, v8::Handle<v8::Value> unused, v8::Handle<v8::Context> context, void* priv) { gfx::Screen* screen = gfx::Screen::GetNativeScreen(); mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("getCursorScreenPoint", base::Bind(&gfx::Screen::GetCursorScreenPoint, base::Unretained(screen))); dict.SetMethod("getPrimaryDisplay", base::Bind(&gfx::Screen::GetPrimaryDisplay, base::Unretained(screen))); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_screen, Initialize)
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/node_includes.h" namespace { void Initialize(v8::Handle<v8::Object> exports, v8::Handle<v8::Value> unused, v8::Handle<v8::Context> context, void* priv) { auto screen = base::Unretained(gfx::Screen::GetNativeScreen()); mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("getCursorScreenPoint", base::Bind(&gfx::Screen::GetCursorScreenPoint, screen)); dict.SetMethod("getPrimaryDisplay", base::Bind(&gfx::Screen::GetPrimaryDisplay, screen)); dict.SetMethod("getAllDisplays", base::Bind(&gfx::Screen::GetAllDisplays, screen)); dict.SetMethod("getDisplayNearestPoint", base::Bind(&gfx::Screen::GetDisplayNearestPoint, screen)); dict.SetMethod("getDisplayMatching", base::Bind(&gfx::Screen::GetDisplayMatching, screen)); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_screen, Initialize)
Modify the check line to be happier on windows.
// PR1013 // Check to make sure debug symbols use the correct name for globals and // functions. Will not assemble if it fails to. // RUN: %clang_cc1 -emit-llvm -g -o - %s | FileCheck %s // CHECK: @"\01f\01oo" int foo __asm__("f\001oo"); int bar() { return foo; }
// PR1013 // Check to make sure debug symbols use the correct name for globals and // functions. Will not assemble if it fails to. // RUN: %clang_cc1 -emit-llvm -g -o - %s | FileCheck %s // CHECK: f\01oo" int foo __asm__("f\001oo"); int bar() { return foo; }
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; }
Add 'env' to fix test failures in windows bots.
// RUN: CINDEXTEST_EDITING=1 c-index-test -test-load-source local %s -Wuninitialized -Werror=unused 2>&1 | FileCheck -check-prefix=DIAGS %s // Make sure -Wuninitialized works even though the header had a warn-as-error occurrence. // DIAGS: error: unused variable 'x' // DIAGS: warning: variable 'x1' is uninitialized // DIAGS-NOT: error: use of undeclared identifier // DIAGS: warning: variable 'x1' is uninitialized #include "pch-warn-as-error-code-split.h" void test() { int x1; // expected-note {{initialize}} int x2 = x1; // expected-warning {{uninitialized}} (void)x2; foo_head(); }
// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source local %s -Wuninitialized -Werror=unused 2>&1 | FileCheck -check-prefix=DIAGS %s // Make sure -Wuninitialized works even though the header had a warn-as-error occurrence. // DIAGS: error: unused variable 'x' // DIAGS: warning: variable 'x1' is uninitialized // DIAGS-NOT: error: use of undeclared identifier // DIAGS: warning: variable 'x1' is uninitialized #include "pch-warn-as-error-code-split.h" void test() { int x1; // expected-note {{initialize}} int x2 = x1; // expected-warning {{uninitialized}} (void)x2; foo_head(); }
Use type3 to simplify expressions
#include "common.th" .global putnum // putnum takes number in C, (row,col) in D,E, and field width in F putnum: pushall(h,i,j,k,l,m) h <- 0x100 h <- h << 8 // h is video base k <- d * 80 + e // k is offset into display k <- k + f // start at right side of field i <- rel(hexes) // i is base of hex transform putnumloop: j <- [c & 0xf + i] // j is character for bottom 4 bits of c j -> [h + k] // write character to display k <- k - 1 // go to the left one character c <- c >>> 4 // shift down for next iteration l <- c == 0 // shall we loop ? jzrel(l,putnumloop) putnumdone: popall_ret(h,i,j,k,l,m) hexes: .word '0', '1', '2', '3', '4', '5', '6', '7' .word '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
#include "common.th" .global putnum // putnum takes number in C, (row,col) in D,E, and field width in F putnum: pushall(h,i,j,k,l,m) h <- 0x10000 // h is video base k <- d * 80 + e // k is offset into display k <- k + f // start at right side of field i <- rel(hexes) // i is base of hex transform putnumloop: j <- [c & 0xf + i] // j is character for bottom 4 bits of c j -> [h + k] // write character to display k <- k - 1 // go to the left one character c <- c >>> 4 // shift down for next iteration l <- c == 0 // shall we loop ? jzrel(l,putnumloop) putnumdone: popall_ret(h,i,j,k,l,m) hexes: .word '0', '1', '2', '3', '4', '5', '6', '7' .word '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
Fix the KeyEvent unit test failure due to the aura implementation of GetUnmodifiedCharacter().
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/events/event.h" #include "base/logging.h" #include "ui/aura/event.h" namespace views { //////////////////////////////////////////////////////////////////////////////// // LocatedEvent, protected: LocatedEvent::LocatedEvent(const NativeEvent& native_event) : Event(native_event, native_event->type(), native_event->flags()), location_(static_cast<aura::LocatedEvent*>(native_event)->location()) { } //////////////////////////////////////////////////////////////////////////////// // KeyEvent, public: KeyEvent::KeyEvent(const NativeEvent& native_event) : Event(native_event, native_event->type(), native_event->flags()), key_code_(static_cast<aura::KeyEvent*>(native_event)->key_code()), character_(GetCharacterFromKeyCode(key_code_, flags())), unmodified_character_(0) { } uint16 KeyEvent::GetCharacter() const { return character_; } uint16 KeyEvent::GetUnmodifiedCharacter() const { return unmodified_character_; } //////////////////////////////////////////////////////////////////////////////// // MouseWheelEvent, public: MouseWheelEvent::MouseWheelEvent(const NativeEvent& native_event) : MouseEvent(native_event), offset_(ui::GetMouseWheelOffset(native_event->native_event())) { } } // namespace views
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/events/event.h" #include "base/logging.h" #include "ui/aura/event.h" namespace views { //////////////////////////////////////////////////////////////////////////////// // LocatedEvent, protected: LocatedEvent::LocatedEvent(const NativeEvent& native_event) : Event(native_event, native_event->type(), native_event->flags()), location_(static_cast<aura::LocatedEvent*>(native_event)->location()) { } //////////////////////////////////////////////////////////////////////////////// // KeyEvent, public: KeyEvent::KeyEvent(const NativeEvent& native_event) : Event(native_event, native_event->type(), native_event->flags()), key_code_(static_cast<aura::KeyEvent*>(native_event)->key_code()), character_(GetCharacterFromKeyCode(key_code_, flags())), unmodified_character_(0) { } uint16 KeyEvent::GetCharacter() const { return character_; } uint16 KeyEvent::GetUnmodifiedCharacter() const { if (unmodified_character_) return unmodified_character_; return GetCharacterFromKeyCode(key_code_, flags() & ui::EF_SHIFT_DOWN); } //////////////////////////////////////////////////////////////////////////////// // MouseWheelEvent, public: MouseWheelEvent::MouseWheelEvent(const NativeEvent& native_event) : MouseEvent(native_event), offset_(ui::GetMouseWheelOffset(native_event->native_event())) { } } // namespace views
Include cstdlib just in case.
// Nikita Kouevda // 2013/11/04 #include <iostream> #include "prime.hpp" using namespace std; int main(int argc, char *argv[]) { int i, n; char *endptr; if (argc < 2) { cerr << "usage: prime number ..." << endl; return 1; } for (i = 1; i < argc; ++i) { n = strtol(argv[i], &endptr, 10); if (*endptr) { cerr << "prime: illegal argument: " << argv[i] << endl; continue; } cout << argv[i] << " is"; if (!isPrime(n)) { cout << " not"; } cout << " prime" << endl; } return 0; }
// Nikita Kouevda // 2013/11/04 #include <cstdlib> #include <iostream> #include "prime.hpp" using namespace std; int main(int argc, char *argv[]) { int i, n; char *endptr; if (argc < 2) { cerr << "usage: prime number ..." << endl; return 1; } for (i = 1; i < argc; ++i) { n = strtol(argv[i], &endptr, 10); if (*endptr) { cerr << "prime: illegal argument: " << argv[i] << endl; continue; } cout << argv[i] << " is"; if (!isPrime(n)) { cout << " not"; } cout << " prime" << endl; } return 0; }
Add some minor error checking
#include <curses.h> #include <iostream> #include "mopViewer.h" #include <string> int main() { mopViewer mopViewers; std::string fileName; int skipCount; std::cout << "Enter the MopFile Name (No need to use extension/location: "; std::cin >> fileName; std::cout << std::endl << "Enter Required Skip Count: "; std::cin >> skipCount; mopViewers.selectGame(fileName, skipCount); return 0; }
#include <curses.h> #include <iostream> #include "mopViewer.h" #include <string> int main() { mopViewer mopViewers; std::string fileName; int skipCount; std::cout << "Enter the MopFile Name (No need to use extension/location: "; std::cin >> fileName; std::cout << std::endl << "Enter Required Skip Count: "; std::cin >> skipCount; if(skipCount < 0){ std::cout << "Skip Count Must be 0 or larger" << std::endl; std::cout << "Exiting Now!" << std::endl; return 0; } mopViewers.selectGame(fileName, skipCount); return 0; }
Fix test because repo moved
#include <catch.hpp> #include <chi/Context.hpp> #include <chi/DataType.hpp> #include <chi/LangModule.hpp> #include <chi/NodeType.hpp> #include <chi/Support/Result.hpp> #include <chi/Fetcher/Fetcher.hpp> #include <llvm/IR/DerivedTypes.h> using namespace chi; namespace fs = boost::filesystem; TEST_CASE("Contexts can fetch remote modules", "[Context]") { // create a temporary directory for a workspace fs::path workspaceDir = boost::filesystem::temp_directory_path() / fs::unique_path(); // this is a tmp file fs::create_directories(workspaceDir); // create the .chigraphworkspace file { fs::ofstream stream{workspaceDir / ".chigraphworkspace"}; } auto res = fetchModule(workspaceDir, "github.com/russelltg/hellochigraph/hello/main", true); REQUIRE(res.dump() == ""); REQUIRE(fs::is_directory(workspaceDir / "src" / "github.com" / "russelltg" / "hellochigraph")); }
#include <catch.hpp> #include <chi/Context.hpp> #include <chi/DataType.hpp> #include <chi/LangModule.hpp> #include <chi/NodeType.hpp> #include <chi/Support/Result.hpp> #include <chi/Fetcher/Fetcher.hpp> #include <llvm/IR/DerivedTypes.h> using namespace chi; namespace fs = boost::filesystem; TEST_CASE("Contexts can fetch remote modules", "[Context]") { // create a temporary directory for a workspace fs::path workspaceDir = boost::filesystem::temp_directory_path() / fs::unique_path(); // this is a tmp file fs::create_directories(workspaceDir); // create the .chigraphworkspace file { fs::ofstream stream{workspaceDir / ".chigraphworkspace"}; } auto res = fetchModule(workspaceDir, "github.com/chigraph/hellochigraph/hello/main", true); REQUIRE(res.dump() == ""); REQUIRE(fs::is_directory(workspaceDir / "src" / "github.com" / "chigraph" / "hellochigraph")); }
UPDATE the style of the search bar
#include "includes/SWidgets/SSearchArea.hpp" #include "includes/SMainWindow.hpp" SSearchArea::SSearchArea(const QIcon & icon, SMainWindow * parent) : QLineEdit(parent), m_parent(parent), m_icon(icon) { setTextMargins(18, 0, 0, 0); connect(this, &SSearchArea::returnPressed, this, &SSearchArea::loadSearch); setClearButtonEnabled(true); } SSearchArea::~SSearchArea() { // Empty } void SSearchArea::paintEvent(QPaintEvent * event) { // Paint the shearch icon before the line edit QLineEdit::paintEvent(event); QPainter painter(this); m_icon.paint(&painter, (height() - 16) / 2, (height() - 16) / 2, 16, 16); } void SSearchArea::loadSearch() { // Load the search // TODO: fix the bug when we seach with "+" QString search{ text() }; search.replace(" ", "+"); m_parent->currentPage()->load(QUrl("http://www.google.com/search?q=" + search)); }
#include "includes/SWidgets/SSearchArea.hpp" #include "includes/SMainWindow.hpp" SSearchArea::SSearchArea(const QIcon & icon, SMainWindow * parent) : QLineEdit(parent), m_parent(parent), m_icon(icon) { setTextMargins(18, 0, 0, 0); connect(this, &SSearchArea::returnPressed, this, &SSearchArea::loadSearch); setClearButtonEnabled(true); setStyleSheet("QLineEdit{ border: none; background-color: #FFFFFF; }"); } SSearchArea::~SSearchArea() { // Empty } void SSearchArea::paintEvent(QPaintEvent * event) { // Paint the shearch icon before the line edit QLineEdit::paintEvent(event); QPainter painter(this); m_icon.paint(&painter, (height() - 16) / 2, (height() - 16) / 2, 16, 16); } void SSearchArea::loadSearch() { // Load the search // TODO: fix the bug when we seach with "+" QString search{ text() }; search.replace(" ", "+"); m_parent->currentPage()->load(QUrl("http://www.google.com/search?q=" + search)); }
Remove database file before Course instantiation
#include "Course.h" #include <iostream> using namespace std; int main() { // test instantiation of a Course object. cout << "Testing instantiation of a Course object:" << endl; Course course("test-0"); cout << "Created " << course.getName() << endl; cout << "All Assignments:" << endl; for (auto it : course.assignments) { cout << it.first << "=>" << it.second << '\n'; } }
#include "Course.h" #include <cstdio> #include <iostream> using namespace std; int main() { if (remove("test-0.sqlite") != 0) { cout << "Error with deletion of database file\n"; } else { cout << "Database file successfully deleted\n"; } // test instantiation of a Course object. cout << "Testing instantiation of a Course object:" << endl; Course course("test-0"); cout << "Created " << course.getName() << endl; cout << "All Assignments:" << endl; for (auto it : course.assignments) { cout << it.first << "=>" << it.second << '\n'; } }
Fix ClosureThread unittest crash in release build
// Copyright 2014 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "media/base/closure_thread.h" namespace media { ClosureThread::ClosureThread( const std::string& name_prefix, const base::Closure& task) : base::SimpleThread(name_prefix), task_(task) {} ClosureThread::~ClosureThread() { if (!HasBeenJoined()) Join(); } void ClosureThread::Run() { task_.Run(); } } // namespace media
// Copyright 2014 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "media/base/closure_thread.h" namespace media { ClosureThread::ClosureThread( const std::string& name_prefix, const base::Closure& task) : base::SimpleThread(name_prefix), task_(task) {} ClosureThread::~ClosureThread() { if (HasBeenStarted() && !HasBeenJoined()) Join(); } void ClosureThread::Run() { task_.Run(); } } // namespace media
Use bool operator instead of null-check for std::function
#include "catch.hpp" #include "library.hpp" #include <functional> namespace { #ifdef _WIN32 const std::string testlibname("testlib.dll"); #else const std::string testlibname("libtestlib.so"); #endif } SCENARIO("Loading a shared library") { GIVEN("library is loaded successfully") { loader::Library lib(testlibname); REQUIRE(lib.loaded() == true); WHEN("symbol is loaded successfully") { auto testfunc = lib.func<int(int)>("test"); THEN("function pointed by symbol is called successfully") { REQUIRE(testfunc(3) == 3); } } } } SCENARIO("Loading non-existent library") { GIVEN("a non-existing library name") { WHEN("an attempt is made to load the library") { loader::Library lib("not there"); THEN("library is not loaded") { REQUIRE(lib.loaded() == false); } THEN("symbol loads return null") { REQUIRE(lib.func<int(int)>("test") == nullptr); } } } }
#include "catch.hpp" #include "library.hpp" #include <functional> namespace { #ifdef _WIN32 const std::string testlibname("testlib.dll"); #else const std::string testlibname("libtestlib.so"); #endif } SCENARIO("Loading a shared library") { GIVEN("library is loaded successfully") { loader::Library lib(testlibname); REQUIRE(lib.loaded() == true); WHEN("symbol is loaded successfully") { auto testfunc = lib.func<int(int)>("test"); THEN("function pointed by symbol is called successfully") { REQUIRE(testfunc(3) == 3); } } } } SCENARIO("Loading non-existent library") { GIVEN("a non-existing library name") { WHEN("an attempt is made to load the library") { loader::Library lib("not there"); THEN("library is not loaded") { REQUIRE(lib.loaded() == false); } THEN("symbol loads return null") { REQUIRE(!lib.func<int(int)>("test")); } } } }
Use only single header in main file
#include "tcframe/aggregator.hpp" #include "tcframe/evaluator.hpp" #include "tcframe/generator.hpp" #include "tcframe/grader.hpp" #include "tcframe/os.hpp" #include "tcframe/runner.hpp" #include "tcframe/spec.hpp" #include __TCFRAME_SPEC_FILE__ using tcframe::Runner; int main(int argc, char* argv[]) { Runner<ProblemSpec> runner( __TCFRAME_SPEC_FILE__, new TestSpec(), new SimpleLoggerEngine(), new OperatingSystem(), new RunnerLoggerFactory(), new GraderLoggerFactory(), new GeneratorFactory(), new GraderFactory(), new EvaluatorRegistry(new EvaluatorHelperRegistry()), new AggregatorRegistry()); return runner.run(argc, argv); }
#include "tcframe/runner.hpp" #include __TCFRAME_SPEC_FILE__ using tcframe::Runner; int main(int argc, char* argv[]) { Runner<ProblemSpec> runner( __TCFRAME_SPEC_FILE__, new TestSpec(), new SimpleLoggerEngine(), new OperatingSystem(), new RunnerLoggerFactory(), new GraderLoggerFactory(), new GeneratorFactory(), new GraderFactory(), new EvaluatorRegistry(new EvaluatorHelperRegistry()), new AggregatorRegistry()); return runner.run(argc, argv); }
Check that an application has been set
#include "include/vortex.hpp" #include "include/app.hpp" #include "include/logger.hpp" #include "common_def_priv.hpp" #include <memory> namespace vtx { struct PRIVATE_STRUCT_NAME(Vortex) { std::unique_ptr<Application> m_application; }; void Vortex::setApplication(Application &&app) { m_private->m_application.reset(&app); } Vortex::Vortex() : m_private{ new PRIVATE_STRUCT_NAME(Vortex) } { Logger::createInstance(); ldebug() << "Vortex library instance created" << endline(); } Vortex::~Vortex() { ldebug() << "Vortex library instance beeing deleted" << endline(); DELETE_PRIVATE_MPRIVATE_PIMPL(Vortex); ldebug() << "Vortex library instance deleted" << endline(); } void Vortex::initialize() { linfo() << "Initializing Vortex library..." << endline(); } void Vortex::deinitialize() { linfo() << "Deinitializing Vortex library..." << endline(); } }
#include "include/vortex.hpp" #include "include/app.hpp" #include "include/logger.hpp" #include "common_def_priv.hpp" #include <memory> namespace vtx { struct PRIVATE_STRUCT_NAME(Vortex) { std::unique_ptr<Application> m_application; }; void Vortex::setApplication(Application &&app) { m_private->m_application.reset(&app); } Vortex::Vortex() : m_private{ new PRIVATE_STRUCT_NAME(Vortex) } { Logger::createInstance(); ldebug() << "Vortex library instance created" << endline(); } Vortex::~Vortex() { ldebug() << "Vortex library instance beeing deleted" << endline(); DELETE_PRIVATE_MPRIVATE_PIMPL(Vortex); ldebug() << "Vortex library instance deleted" << endline(); } void Vortex::initialize() { linfo() << "Initializing Vortex library..." << endline(); if (!m_private->m_application) { lerror() << "No application set" << endline(); return; } } void Vortex::deinitialize() { linfo() << "Deinitializing Vortex library..." << endline(); } }
Set xml files to moved files
#include <iostream> #include "Room.h" #include "XMLParser.cpp" int main() { Room current_room; current_room.loadFromXMLFile("Speelveld1.0.xml"); current_room.loadMovesFromXMLFile("Bewegingen1.0.xml"); current_room.executeAllMoves("HuidigSpeelveld.txt", "ResterendeBewegingen.txt"); return 0; }
#include <iostream> #include "Room.h" #include "XMLParser.cpp" int main() { Room current_room; current_room.loadFromXMLFile("xmlfiles/Speelveld1.0.xml"); current_room.loadMovesFromXMLFile("xmlfiles/Bewegingen1.0.xml"); current_room.executeAllMoves("HuidigSpeelveld.txt", "ResterendeBewegingen.txt"); return 0; }
Test Runner added to check the NetworkBalancer class
#include <QCoreApplication> #include "Network/NetworkBalancer.hpp" int main(int argc, char *argv[]) { Network::NetworkBalancer aBalancerExample = Network::NetworkBalancer(); return( 0 ); }
#include <QCoreApplication> #include "Tests/Unit/Network/TestNetworkBalancer.hpp" #include <cppunit/extensions/HelperMacros.h> #include <cppunit/ui/text/TestRunner.h> using namespace std; using namespace CppUnit; int main(int argc, char *argv[]) { // Initialice test runner CppUnit::TextUi::TestRunner aRunner; // Add network balancer test suite aRunner.addTest( TestNetworkBalancer::suite() ); // Start test runner aRunner.run(); return( 0 ); }
Use 18 significant digits for TopologyException point coordinates
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Coordinate.h> #include <geos/platform.h> // for ISNAN #include <sstream> #include <string> #ifndef GEOS_INLINE # include <geos/geom/Coordinate.inl> #endif using namespace std; namespace geos { namespace geom { // geos::geom Coordinate Coordinate::nullCoord=Coordinate(DoubleNotANumber,DoubleNotANumber,DoubleNotANumber); Coordinate& Coordinate::getNull() { return nullCoord; } string Coordinate::toString() const { ostringstream s; s<<*this; return s.str(); } std::ostream& operator<< (std::ostream& os, const Coordinate& c) { if ( ISNAN(c.z) ) { os << c.x << " " << c.y; } else { os << c.x << " " << c.y << " " << c.z; } return os; } } // namespace geos::geom } // namespace geos
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Coordinate.h> #include <geos/platform.h> // for ISNAN #include <sstream> #include <string> #include <iomanip> #ifndef GEOS_INLINE # include <geos/geom/Coordinate.inl> #endif using namespace std; namespace geos { namespace geom { // geos::geom Coordinate Coordinate::nullCoord=Coordinate(DoubleNotANumber,DoubleNotANumber,DoubleNotANumber); Coordinate& Coordinate::getNull() { return nullCoord; } string Coordinate::toString() const { ostringstream s; s << std::setprecision(17) << *this; return s.str(); } std::ostream& operator<< (std::ostream& os, const Coordinate& c) { if ( ISNAN(c.z) ) { os << c.x << " " << c.y; } else { os << c.x << " " << c.y << " " << c.z; } return os; } } // namespace geos::geom } // namespace geos
Fix undefined assignment evaluation order in remoting::Capturer::FinishCapture.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer.h" namespace remoting { Capturer::Capturer() : width_(0), height_(0), pixel_format_(PixelFormatInvalid), bytes_per_pixel_(0), bytes_per_row_(0), current_buffer_(0) { } Capturer::~Capturer() { } void Capturer::GetDirtyRects(DirtyRects* rects) const { *rects = dirty_rects_; } int Capturer::GetWidth() const { return width_; } int Capturer::GetHeight() const { return height_; } PixelFormat Capturer::GetPixelFormat() const { return pixel_format_; } void Capturer::InvalidateRect(gfx::Rect dirty_rect) { inval_rects_.push_back(dirty_rect); } void Capturer::FinishCapture(Task* done_task) { done_task->Run(); delete done_task; // Select the next buffer to be the current buffer. current_buffer_ = ++current_buffer_ % kNumBuffers; } } // namespace remoting
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer.h" namespace remoting { Capturer::Capturer() : width_(0), height_(0), pixel_format_(PixelFormatInvalid), bytes_per_pixel_(0), bytes_per_row_(0), current_buffer_(0) { } Capturer::~Capturer() { } void Capturer::GetDirtyRects(DirtyRects* rects) const { *rects = dirty_rects_; } int Capturer::GetWidth() const { return width_; } int Capturer::GetHeight() const { return height_; } PixelFormat Capturer::GetPixelFormat() const { return pixel_format_; } void Capturer::InvalidateRect(gfx::Rect dirty_rect) { inval_rects_.push_back(dirty_rect); } void Capturer::FinishCapture(Task* done_task) { done_task->Run(); delete done_task; // Select the next buffer to be the current buffer. current_buffer_ = (current_buffer_ + 1) % kNumBuffers; } } // namespace remoting
Use minimum instead of do-while in Box-Muller
#include "test.h" #include "lcg.h" #include <cassert> #include <limits> template <class T> void boxmuller(T* data, size_t count) { assert(count % 2 == 0); static const T twopi = T(2.0 * 3.14159265358979323846); LCG r; for (size_t i = 0; i < count; i += 2) { T u1, u2; do { u1 = r(); u2 = r(); } while (u1 <= std::numeric_limits<T>::min()); T radius = std::sqrt(-2 * std::log(u1)); T theta = twopi * u2; data[i ] = radius * std::cos(theta); data[i + 1] = radius * std::sin(theta); } } static void normaldistf_boxmuller(float* data, size_t count) { boxmuller(data, count); } static void normaldist_boxmuller(double* data, size_t count) { boxmuller(data, count); } REGISTER_TEST(boxmuller);
#include "test.h" #include "lcg.h" #include <cassert> #include <limits> #include <algorithm> template <class T> void boxmuller(T* data, size_t count) { assert(count % 2 == 0); static const T twopi = T(2.0 * 3.14159265358979323846); LCG r; for (size_t i = 0; i < count; i += 2) { T u1, u2; u1 = r(); u2 = r(); u1 = std::max(u1, std::numeric_limits<T>::min()); T radius = std::sqrt(-2 * std::log(u1)); T theta = twopi * u2; data[i ] = radius * std::cos(theta); data[i + 1] = radius * std::sin(theta); } } static void normaldistf_boxmuller(float* data, size_t count) { boxmuller(data, count); } static void normaldist_boxmuller(double* data, size_t count) { boxmuller(data, count); } REGISTER_TEST(boxmuller);
Replace QCoreApplication to QAppliation for QWidget work.
#include <QCoreApplication> #include <QTest> #include "test_engine.hpp" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QTest::qExec( new Test_Engine, argc, argv ); return a.exec(); }
#include <QApplication> #include <QTest> #include "test_engine.hpp" int main( int argc, char *argv[] ) { QApplication a( argc, argv ); QTest::qExec( new Test_Engine, argc, argv ); return a.exec(); }
Add support for implicit function
#include <tiramisu/tiramisu.h> using namespace tiramisu; void gen(std::string name, int size, int val0, int val1) { tiramisu::init(name); tiramisu::function *function0 = global::get_implicit_function(); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0); tiramisu::var i("i", 0, 10), j("j", 0, 10); tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1"); tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j); //S0.tile(i, j, 2, 2, i0, j0, i1, j1); S0.tag_parallel_level(i); tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, &function0); S0.store_in(&buf0, {i ,j}); function0.codegen({&buf0}, "build/generated_fct_test_114.o"); } int main(int argc, char **argv) { gen("func", 10, 3, 4); return 0; }
#include <tiramisu/tiramisu.h> using namespace tiramisu; void gen(std::string name, int size, int val0, int val1) { tiramisu::init(name); tiramisu::function *function0 = global::get_implicit_function(); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0); tiramisu::var i("i", 0, 10), j("j", 0, 10); tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1"); tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j); //S0.tile(i, j, 2, 2, i0, j0, i1, j1); S0.tag_parallel_level(i); tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0); S0.store_in(&buf0, {i ,j}); function0->codegen({&buf0}, "build/generated_fct_test_114.o"); } int main(int argc, char **argv) { gen("func", 10, 3, 4); return 0; }
Rearrange code to be clearer
/*----------------------------------------*/ // Test sending messages from master. // // In this script, master sends a message (command = 0x01) // with alternating 0s and 1s for each node on the bus. // /*----------------------------------------*/ #include <stdint.h> #include <util/delay.h> #include "MultidropMaster.h" #include "MultidropDataUart.h" #define NODE_COUNT 1 int main() { MultidropDataUart serial; serial.begin(9600); MultidropMaster master(&serial); uint8_t iteration = 1, i = 0; master.setNodeLength(NODE_COUNT); while(1) { master.startMessage(0x01, MultidropMaster::BROADCAST_ADDRESS, 1, true); // Send alternating 1s and 0s for (i = 0; i < NODE_COUNT; i++) { if ((i + iteration) % 2 == 0) { master.sendData(0x01); } else { master.sendData(0x00); } } master.finishMessage(); iteration++; _delay_ms(1000); } }
/*----------------------------------------*/ // Test sending messages from master. // // In this script, master sends a message (command = 0x01) // with alternating 0s and 1s for each node on the bus. // /*----------------------------------------*/ #include <stdint.h> #include <util/delay.h> #include "MultidropMaster.h" #include "MultidropDataUart.h" #define NODE_COUNT 1 int main() { uint8_t iteration = 1, i = 0; MultidropDataUart serial; MultidropMaster master(&serial); serial.begin(9600); master.setNodeLength(NODE_COUNT); while(1) { master.startMessage(0x01, MultidropMaster::BROADCAST_ADDRESS, 1, true); // Send alternating 1s and 0s for (i = 0; i < NODE_COUNT; i++) { if ((i + iteration) % 2 == 0) { master.sendData(0x01); } else { master.sendData(0x00); } } master.finishMessage(); iteration++; _delay_ms(1000); } }
Allow mapping for paths with no eye subpath.
/*! \file PathToImage.cpp * \author Jared Hoberock * \brief Implementation of PathToImage class. */ #include "PathToImage.h" void PathToImage ::evaluate(const PathSampler::Result &r, const PathSampler::HyperPoint &x, const Path &xPath, float &u, float &v) const { if(r.mEyeLength == 0) { std::cerr << "PathToImage::evaluate(): Implement me!" << std::endl; } // end if else if(r.mEyeLength == 1) { // we need to invert the sensor function unsigned int endOfLightPath = xPath.getSubpathLengths().sum() - r.mLightLength; ::Vector w = xPath[endOfLightPath].mDg.getPoint(); w -= xPath[0].mDg.getPoint(); xPath[0].mSensor->invert(w, xPath[0].mDg, u, v); } // end if else { // the first coordinate naturally corresponds to (u,v) u = x[0][0]; v = x[0][1]; } // end else } // end PathToImage::evaluate() void PathToImage ::operator()(const PathSampler::Result &r, const PathSampler::HyperPoint &x, const Path &xPath, float &u, float &v) const { return evaluate(r,x,xPath,u,v); } // end PathToImage::operator()()
/*! \file PathToImage.cpp * \author Jared Hoberock * \brief Implementation of PathToImage class. */ #include "PathToImage.h" void PathToImage ::evaluate(const PathSampler::Result &r, const PathSampler::HyperPoint &x, const Path &xPath, float &u, float &v) const { if(r.mEyeLength <= 1) { // we need to invert the sensor function unsigned int endOfLightPath = xPath.getSubpathLengths().sum() - r.mLightLength; ::Vector w = xPath[endOfLightPath].mDg.getPoint(); w -= xPath[0].mDg.getPoint(); xPath[0].mSensor->invert(w, xPath[0].mDg, u, v); } // end if else { // the first coordinate naturally corresponds to (u,v) u = x[0][0]; v = x[0][1]; } // end else } // end PathToImage::evaluate() void PathToImage ::operator()(const PathSampler::Result &r, const PathSampler::HyperPoint &x, const Path &xPath, float &u, float &v) const { return evaluate(r,x,xPath,u,v); } // end PathToImage::operator()()
Fix some issue with coloring of specular highlights
#include <cmath> #include "lights/light.h" #include "material/blinn_phong.h" BlinnPhong::BlinnPhong(const Colorf &diffuse, const Colorf &specular, float gloss) : diffuse(diffuse), specular(specular), gloss(gloss) {} Colorf BlinnPhong::shade(const Ray &r, const HitInfo &hitinfo, const LightCache &lights) const { Colorf illum; for (const auto &lit : lights){ const auto &light = lit.second; if (light->is_ambient()){ illum += diffuse * light->illuminate(hitinfo.point); } else { Vector l = -light->direction(hitinfo.point); Vector v = -r.d.normalized(); Vector h = (l + v).normalized(); //Normal may not be normalized due to translation into world space Normal n = hitinfo.normal.normalized(); float dif = std::max(l.dot(n), 0.f); float spec = std::pow(std::max(n.dot(h), 0.f), gloss); illum += (diffuse * dif + specular * spec) * light->illuminate(hitinfo.point); } } illum.normalize(); return illum; }
#include <cmath> #include "lights/light.h" #include "material/blinn_phong.h" BlinnPhong::BlinnPhong(const Colorf &diffuse, const Colorf &specular, float gloss) : diffuse(diffuse), specular(specular), gloss(gloss) {} Colorf BlinnPhong::shade(const Ray &r, const HitInfo &hitinfo, const LightCache &lights) const { Colorf illum; for (const auto &lit : lights){ const auto &light = lit.second; if (light->is_ambient()){ illum += diffuse * light->illuminate(hitinfo.point); } else { Vector l = -light->direction(hitinfo.point); Vector v = -r.d.normalized(); Vector h = (l + v).normalized(); //Normal may not be normalized due to translation into world space Normal n = hitinfo.normal.normalized(); float dif = std::max(l.dot(n), 0.f); float spec = std::pow(std::max(n.dot(h), 0.f), gloss); illum += diffuse * dif * light->illuminate(hitinfo.point) + specular * spec * light->illuminate(hitinfo.point); } } illum.normalize(); return illum; }
Add include file is utility
/****************************************************** * This is CIR-KIT 3rd robot control driver. * Author : Arita Yuta(Kyutech) ******************************************************/ #include "cirkit_unit03_driver.hpp" #include <string> int main(int argc, char** argv) { ros::init(argc, argv, "cirkit_unit03_driver_node"); ROS_INFO("cirkit unit03 robot driver for ROS."); ros::NodeHandle n {"~"}; std::string imcs01_port {"/dev/urbtc0"}; n.param<std::string>("imcs01_port", imcs01_port, imcs01_port); cirkit::CirkitUnit03Driver driver(std::move(imcs01_port), ros::NodeHandle {}); driver.run(); return 0; }
/****************************************************** * This is CIR-KIT 3rd robot control driver. * Author : Arita Yuta(Kyutech) ******************************************************/ #include "cirkit_unit03_driver.hpp" #include <string> #include <utility> int main(int argc, char** argv) { ros::init(argc, argv, "cirkit_unit03_driver_node"); ROS_INFO("cirkit unit03 robot driver for ROS."); ros::NodeHandle n {"~"}; std::string imcs01_port {"/dev/urbtc0"}; n.param<std::string>("imcs01_port", imcs01_port, imcs01_port); cirkit::CirkitUnit03Driver driver(std::move(imcs01_port), ros::NodeHandle {}); driver.run(); return 0; }
Revert "[profiling] Update test case to deal with name variable change (NFC)"
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instrument=clang | FileCheck %s struct Member { ~Member(); }; struct A { virtual ~A(); }; struct B : A { Member m; virtual ~B(); }; // Base dtor counters and profile data // CHECK: @__profc__ZN1BD2Ev = private global [1 x i64] zeroinitializer // CHECK: @__profd__ZN1BD2Ev = // Complete dtor counters and profile data must absent // CHECK-NOT: @__profc__ZN1BD1Ev = private global [1 x i64] zeroinitializer // CHECK-NOT: @__profd__ZN1BD1Ev = // Deleting dtor counters and profile data must absent // CHECK-NOT: @__profc__ZN1BD0Ev = private global [1 x i64] zeroinitializer // CHECK-NOT: @__profd__ZN1BD0Ev = B::~B() { }
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instrument=clang | FileCheck %s struct Member { ~Member(); }; struct A { virtual ~A(); }; struct B : A { Member m; virtual ~B(); }; // Base dtor // CHECK: @__profn__ZN1BD2Ev = private constant [9 x i8] c"_ZN1BD2Ev" // Complete dtor must not be instrumented // CHECK-NOT: @__profn__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev" // Deleting dtor must not be instrumented // CHECK-NOT: @__profn__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev" // Base dtor counters and profile data // CHECK: @__profc__ZN1BD2Ev = private global [1 x i64] zeroinitializer // CHECK: @__profd__ZN1BD2Ev = // Complete dtor counters and profile data must absent // CHECK-NOT: @__profc__ZN1BD1Ev = private global [1 x i64] zeroinitializer // CHECK-NOT: @__profd__ZN1BD1Ev = // Deleting dtor counters and profile data must absent // CHECK-NOT: @__profc__ZN1BD0Ev = private global [1 x i64] zeroinitializer // CHECK-NOT: @__profd__ZN1BD0Ev = B::~B() { }
Fix for compile problems under IRIX.
//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield // Distributed under the terms of the GNU General Public License (GPL) // as published by the Free Software Foundation. // // All software using osgSim must be GPL'd or excempted via the // purchase of the Open Scene Graph Professional License (OSGPL) // for further information contact robert@openscenegraph.com. #include <osgSim/BlinkSequence> #include <stdlib.h> using namespace osgSim; BlinkSequence::BlinkSequence(): Referenced(), _pulsePeriod(0.0), _phaseShift(0.0), _pulseData(), _sequenceGroup(0) {} BlinkSequence::BlinkSequence(const BlinkSequence& bs): Referenced(), _pulsePeriod(bs._pulsePeriod), _phaseShift(bs._phaseShift), _pulseData(bs._pulseData), _sequenceGroup(bs._sequenceGroup) {} BlinkSequence::SequenceGroup::SequenceGroup(): Referenced() { // set a random base time between 0 and 1000.0 _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0; } BlinkSequence::SequenceGroup::SequenceGroup(double baseTime): Referenced(), _baseTime(baseTime) {}
//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield // Distributed under the terms of the GNU General Public License (GPL) // as published by the Free Software Foundation. // // All software using osgSim must be GPL'd or excempted via the // purchase of the Open Scene Graph Professional License (OSGPL) // for further information contact robert@openscenegraph.com. #include <osgSim/BlinkSequence> #include <stdlib.h> using namespace osgSim; BlinkSequence::BlinkSequence(): _pulsePeriod(0.0), _phaseShift(0.0), _pulseData(), _sequenceGroup(0) { } BlinkSequence::BlinkSequence(const BlinkSequence& bs): _pulsePeriod(bs._pulsePeriod), _phaseShift(bs._phaseShift), _pulseData(bs._pulseData), _sequenceGroup(bs._sequenceGroup) { } BlinkSequence::SequenceGroup::SequenceGroup() { // set a random base time between 0 and 1000.0 _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0; } BlinkSequence::SequenceGroup::SequenceGroup(double baseTime): _baseTime(baseTime) { }
Fix the ASSERT_NEAR() parameter bug.
/** * @file equationTest.cpp * @brief equation header tester. * @author zer0 * @date 2016-08-26 */ #include <gtest/gtest.h> #include <libtbag/math/equation.hpp> using namespace libtbag; using namespace libtbag::math; TEST(equationTest, getLinearEquationWithTwoPoint) { auto e = getLinearEquationWithTwoPoint(1, 1, 2, 2); ASSERT_EQ(1, e.a); ASSERT_EQ(0, e.b); } TEST(equationTest, getIntersectionWithTwoLinearEquation) { LinearEquation<double> e1{ 2, 0}; LinearEquation<double> e2{-2, 2}; auto p = getIntersectionWithTwoLinearEquation(e1, e2); ASSERT_NEAR(0.5, p.x, 1); ASSERT_NEAR(1.0, p.y, 1); }
/** * @file equationTest.cpp * @brief equation header tester. * @author zer0 * @date 2016-08-26 */ #include <gtest/gtest.h> #include <libtbag/math/equation.hpp> using namespace libtbag; using namespace libtbag::math; TEST(equationTest, getLinearEquationWithTwoPoint) { auto e = getLinearEquationWithTwoPoint(1, 1, 2, 2); ASSERT_EQ(1, e.a); ASSERT_EQ(0, e.b); } TEST(equationTest, isParallelWithTwoLinearEquation) { LinearEquation<double> e1{2.4, 1}; LinearEquation<double> e2{2.4, 2}; ASSERT_TRUE(isParallelWithTwoLinearEquation(e1, e2)); } TEST(equationTest, getIntersectionWithTwoLinearEquation) { LinearEquation<double> e1{ 2, 0}; LinearEquation<double> e2{-2, 2}; auto p = getIntersectionWithTwoLinearEquation(e1, e2); ASSERT_NEAR(0.5, p.x, 0.1); ASSERT_NEAR(1.0, p.y, 0.1); }
Disable ExtensionApiTest.WebSocket instead of marked as FAILS_
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "base/path_service.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/ui_test_utils.h" #include "net/base/mock_host_resolver.h" // http://crbug.com/111165 #if defined(OS_WIN) #define MAYBE_WebSocket FAILS_WebSocket #else #define MAYBE_WebSocket WebSocket #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) { FilePath websocket_root_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir)); // TODO(toyoshim): Remove following logging after a bug investigation. // http://crbug.com/107836 . LOG(INFO) << "Assume LayoutTests in " << websocket_root_dir.MaybeAsASCII(); ui_test_utils::TestWebSocketServer server; ASSERT_TRUE(server.Start(websocket_root_dir)); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "base/path_service.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/ui_test_utils.h" #include "net/base/mock_host_resolver.h" // http://crbug.com/111165 #if defined(OS_WIN) #define MAYBE_WebSocket DISABLED_WebSocket #else #define MAYBE_WebSocket WebSocket #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) { FilePath websocket_root_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir)); // TODO(toyoshim): Remove following logging after a bug investigation. // http://crbug.com/107836 . LOG(INFO) << "Assume LayoutTests in " << websocket_root_dir.MaybeAsASCII(); ui_test_utils::TestWebSocketServer server; ASSERT_TRUE(server.Start(websocket_root_dir)); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; }
Add a few more headers to the native test project
// dllmain.cpp : Defines the entry point for the DLL application. #include "stdafx.h" #include "commctrl.h" #include "accctrl.h" #include "shellapi.h" #include "shlobj.h" #include "aclapi.h" #include "lm.h" #include "d2d1.h" #include "dwrite.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
// dllmain.cpp : Defines the entry point for the DLL application. #include "stdafx.h" #include "commctrl.h" #include "accctrl.h" #include "shellapi.h" #include "shlobj.h" #include "aclapi.h" #include "lm.h" #include "d2d1.h" #include "dwrite.h" #include "richedit.h" #include "shlwapi.h" #include "uxtheme.h" #include "Mshtmhst.h" #include "richole.h" #include "OleCtl.h" #include "winternl.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
Fix compiler warning (moc has nothing to generate)
// // 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 2011 Utku Aydın <utkuaydin34@gmail.com> // #include "GeoSceneGeodata.h" #include "GeoSceneTypes.h" namespace Marble { GeoSceneGeodata::GeoSceneGeodata( QString name ) : GeoSceneAbstractDataset( name ), m_name( name ), m_sourceFile( QString() ), m_sourceFileFormat( QString() ) { } GeoSceneGeodata::~GeoSceneGeodata() { } const char* GeoSceneGeodata::nodeType() const { return GeoSceneTypes::GeoSceneGeodataType; } QString GeoSceneGeodata::name() const { return m_name; } QString GeoSceneGeodata::sourceFile() const { return m_sourceFile; } void GeoSceneGeodata::setSourceFile(QString sourceFile) { m_sourceFile = sourceFile; } QString GeoSceneGeodata::sourceFileFormat() const { return m_sourceFileFormat; } void GeoSceneGeodata::setSourceFileFormat(QString format) { m_sourceFileFormat = format; } QString GeoSceneGeodata::type() { return "geodata"; } } #include "GeoSceneGeodata.moc"
// // 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 2011 Utku Aydın <utkuaydin34@gmail.com> // #include "GeoSceneGeodata.h" #include "GeoSceneTypes.h" namespace Marble { GeoSceneGeodata::GeoSceneGeodata( QString name ) : GeoSceneAbstractDataset( name ), m_name( name ), m_sourceFile( QString() ), m_sourceFileFormat( QString() ) { } GeoSceneGeodata::~GeoSceneGeodata() { } const char* GeoSceneGeodata::nodeType() const { return GeoSceneTypes::GeoSceneGeodataType; } QString GeoSceneGeodata::name() const { return m_name; } QString GeoSceneGeodata::sourceFile() const { return m_sourceFile; } void GeoSceneGeodata::setSourceFile(QString sourceFile) { m_sourceFile = sourceFile; } QString GeoSceneGeodata::sourceFileFormat() const { return m_sourceFileFormat; } void GeoSceneGeodata::setSourceFileFormat(QString format) { m_sourceFileFormat = format; } QString GeoSceneGeodata::type() { return "geodata"; } } // #include "GeoSceneGeodata.moc"
Move chrome/browser/printing out of the chrome namespace
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_error_dialog.h" namespace chrome { void ShowPrintErrorDialog() {} } // namespace chrome
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_error_dialog.h" void ShowPrintErrorDialog() {}
Revert r247, unbreak the build
// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gtest/gtest.h" #include "base/common.h" TEST(CheckTest, CheckTrueSucceedsTest) { CHECK(1); CHECK(42); } TEST(CheckTest, AssertionsAndChecksTest) { CHECK(2 + 2 == 4); // NOLINT ASSERT_TRUE(2 + 2 == 4); // NOLINT ASSERT_EQ(5, 2 + 2); ASSERT_LE(2 + 2, 5); printf("Passed all ASSERT macros, now EXPECT macros\n"); EXPECT_EQ(4, 2 + 2); printf("End of test\n"); } // C preprocessor magic, see // http://www.decompile.com/cpp/faq/file_and_line_error_string.htm #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define __FILE_LINE__ __FILE__ ":" TOSTRING(__LINE__) TEST(CheckTest, CheckFalseDeathTest) { ASSERT_DEATH(CHECK(0), "CHECK failed: .* at " __FILE_LINE__); } TEST(CheckTest, DCheckFalseDeathTest) { ASSERT_DEBUG_DEATH(DCHECK(0), "CHECK failed: .* at " __FILE_LINE__); }
// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gtest/gtest.h" #include "base/common.h" TEST(CheckTest, CheckTrueSucceedsTest) { CHECK(1); CHECK(42); } TEST(CheckTest, AssertionsAndChecksTest) { CHECK(2 + 2 == 4); // NOLINT ASSERT_TRUE(2 + 2 == 4); // NOLINT ASSERT_EQ(4, 2 + 2); ASSERT_LE(2 + 2, 5); printf("Passed all ASSERT macros, now EXPECT macros\n"); EXPECT_EQ(4, 2 + 2); printf("End of test\n"); } // C preprocessor magic, see // http://www.decompile.com/cpp/faq/file_and_line_error_string.htm #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define __FILE_LINE__ __FILE__ ":" TOSTRING(__LINE__) TEST(CheckTest, CheckFalseDeathTest) { ASSERT_DEATH(CHECK(0), "CHECK failed: .* at " __FILE_LINE__); } TEST(CheckTest, DCheckFalseDeathTest) { ASSERT_DEBUG_DEATH(DCHECK(0), "CHECK failed: .* at " __FILE_LINE__); }
Fix warnings in OpenGL backend
#include "ImwWindowManagerOGL.h" #include "ImwPlatformWindowOGL.h" #include "windows.h" using namespace ImWindow; ImwWindowManagerOGL::ImwWindowManagerOGL() { } ImwWindowManagerOGL::~ImwWindowManagerOGL() { Destroy(); } ImwPlatformWindow* ImwWindowManagerOGL::CreatePlatformWindow(EPlatformWindowType eType, ImwPlatformWindow* pParent) { IM_ASSERT(m_pCurrentPlatformWindow == NULL); ImwPlatformWindowOGL* pWindow = new ImwPlatformWindowOGL(eType, CanCreateMultipleWindow()); if (pWindow->Init(pParent)) { return (ImwPlatformWindow*)pWindow; } else { delete pWindow; return NULL; } } ImVec2 ImwWindowManagerOGL::GetCursorPos() { POINT oPoint; ::GetCursorPos(&oPoint); return ImVec2(oPoint.x, oPoint.y); } bool ImwWindowManagerOGL::IsLeftClickDown() { return GetAsyncKeyState(VK_LBUTTON); }
#include "ImwWindowManagerOGL.h" #include "ImwPlatformWindowOGL.h" #include "windows.h" using namespace ImWindow; ImwWindowManagerOGL::ImwWindowManagerOGL() { } ImwWindowManagerOGL::~ImwWindowManagerOGL() { Destroy(); } ImwPlatformWindow* ImwWindowManagerOGL::CreatePlatformWindow(EPlatformWindowType eType, ImwPlatformWindow* pParent) { IM_ASSERT(m_pCurrentPlatformWindow == NULL); ImwPlatformWindowOGL* pWindow = new ImwPlatformWindowOGL(eType, CanCreateMultipleWindow()); if (pWindow->Init(pParent)) { return (ImwPlatformWindow*)pWindow; } else { delete pWindow; return NULL; } } ImVec2 ImwWindowManagerOGL::GetCursorPos() { POINT oPoint; ::GetCursorPos(&oPoint); return ImVec2((float)oPoint.x, (float)oPoint.y); } bool ImwWindowManagerOGL::IsLeftClickDown() { return GetAsyncKeyState(VK_LBUTTON) != 0; }
Complete printing of SP/BP registers
//======================================================================= // 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 "ltac/Register.hpp" using namespace eddic; ltac::Register::Register(){ //Nothing to init } ltac::Register::Register(unsigned short reg) : reg(reg) { //Nothing to init } ltac::Register::operator int(){ return reg; } bool ltac::Register::operator<(const Register& rhs) const { return reg > rhs.reg; } bool ltac::Register::operator>(const Register& rhs) const { return reg < rhs.reg; } bool ltac::Register::operator==(const Register& rhs) const { return reg == rhs.reg; } bool ltac::Register::operator!=(const Register& rhs) const { return !(*this == rhs); } std::ostream& ltac::operator<<(std::ostream& out, const ltac::Register& reg){ return out << "r" << reg.reg; }
//======================================================================= // 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 "ltac/Register.hpp" using namespace eddic; ltac::Register::Register(){ //Nothing to init } ltac::Register::Register(unsigned short reg) : reg(reg) { //Nothing to init } ltac::Register::operator int(){ return reg; } bool ltac::Register::operator<(const Register& rhs) const { return reg > rhs.reg; } bool ltac::Register::operator>(const Register& rhs) const { return reg < rhs.reg; } bool ltac::Register::operator==(const Register& rhs) const { return reg == rhs.reg; } bool ltac::Register::operator!=(const Register& rhs) const { return !(*this == rhs); } std::ostream& ltac::operator<<(std::ostream& out, const ltac::Register& reg){ if(reg == ltac::BP){ return out << "bp"; } else if(reg == ltac::SP){ return out << "sp"; } return out << "r" << reg.reg; }
Check that white noise mean value is close to 0.
#include "aquila/global.h" #include "aquila/source/generator/WhiteNoiseGenerator.h" #include <unittestpp.h> #include <algorithm> #include <cstddef> #include <cstdlib> #include <ctime> SUITE(WhiteNoiseGenerator) { // sample frequency is fixed at 1 kHz Aquila::WhiteNoiseGenerator gen(1000); TEST(DoesNotOverrunAplitude) { std::srand(std::time(0)); Aquila::SampleType amplitude = 1000; gen.setAmplitude(amplitude).generate(2048); auto result = std::minmax_element(std::begin(gen), std::end(gen)); CHECK(*result.first > -amplitude); CHECK(*result.second < amplitude); } }
#include "aquila/global.h" #include "aquila/source/generator/WhiteNoiseGenerator.h" #include <unittestpp.h> #include <algorithm> #include <cstddef> #include <cstdlib> #include <ctime> SUITE(WhiteNoiseGenerator) { // sample frequency is fixed at 1 kHz Aquila::WhiteNoiseGenerator gen(1000); TEST(DoesNotOverrunAplitude) { std::srand(std::time(0)); Aquila::SampleType amplitude = 1000; gen.setAmplitude(amplitude).generate(2048); auto result = std::minmax_element(std::begin(gen), std::end(gen)); CHECK(*result.first > -amplitude); CHECK(*result.second < amplitude); } TEST(ZeroMean) { std::srand(std::time(0)); gen.setAmplitude(1).generate(2048); auto mean = Aquila::mean(gen); CHECK_CLOSE(0.0, mean, 0.01); } }
Make BMP decoder handle failed surface locks
#include "c_bmp_decoder.h" namespace Img { namespace Internal { using namespace Geom; bool BmpDataDecoder::Process() { return OnProcess(); } BmpDataDecoder::BmpDataDecoder(std::shared_ptr<Img::Surface> destination, BMPHeader header): m_header{ header }, m_destination{ destination } { } std::shared_ptr<Img::Surface::LockedArea> BmpDataDecoder::GetScanlinePtr(int row) { if (m_header.FlipVertical) { row = m_destination->Height() - row - 1; } return m_destination->LockSurface({ PointInt{0, row}, SizeInt{m_destination->Width(), 1} }, Img::LockReadWrite); } } }
#include "c_bmp_decoder.h" namespace Img { namespace Internal { using namespace Geom; bool BmpDataDecoder::Process() { return OnProcess(); } BmpDataDecoder::BmpDataDecoder(std::shared_ptr<Img::Surface> destination, BMPHeader header): m_header{ header }, m_destination{ destination } { } std::shared_ptr<Img::Surface::LockedArea> BmpDataDecoder::GetScanlinePtr(int row) { if (m_header.FlipVertical) { row = m_destination->Height() - row - 1; } return m_destination->LockSurface({ PointInt{0, row}, SizeInt{m_destination->Width(), 1} }, Img::LockReadWrite); auto area = m_destination->LockSurface({ PointInt{0, row}, SizeInt{m_destination->Width(), 1} }, Img::LockReadWrite); if(area == nullptr) { DO_THROW(Err::CriticalError, "Could not get scanline ptr"); } return area; } } }
Disable one test on Android.
// Test that no data is collected without a runtime flag. // // RUN: %clangxx_asan -fsanitize-coverage=1 %s -o %t // // RUN: rm -rf %T/coverage-disabled // // RUN: mkdir -p %T/coverage-disabled/normal // RUN: ASAN_OPTIONS=coverage_direct=0:coverage_dir=%T/coverage-disabled/normal:verbosity=1 %run %t // RUN: not %sancov print %T/coverage-disabled/normal/*.sancov 2>&1 // // RUN: mkdir -p %T/coverage-disabled/direct // RUN: ASAN_OPTIONS=coverage_direct=1:coverage_dir=%T/coverage-disabled/direct:verbosity=1 %run %t // RUN: cd %T/coverage-disabled/direct // RUN: not %sancov rawunpack *.sancov int main(int argc, char **argv) { return 0; }
// Test that no data is collected without a runtime flag. // // RUN: %clangxx_asan -fsanitize-coverage=1 %s -o %t // // RUN: rm -rf %T/coverage-disabled // // RUN: mkdir -p %T/coverage-disabled/normal // RUN: ASAN_OPTIONS=coverage_direct=0:coverage_dir=%T/coverage-disabled/normal:verbosity=1 %run %t // RUN: not %sancov print %T/coverage-disabled/normal/*.sancov 2>&1 // // RUN: mkdir -p %T/coverage-disabled/direct // RUN: ASAN_OPTIONS=coverage_direct=1:coverage_dir=%T/coverage-disabled/direct:verbosity=1 %run %t // RUN: cd %T/coverage-disabled/direct // RUN: not %sancov rawunpack *.sancov // // XFAIL: android int main(int argc, char **argv) { return 0; }
Add a test case for r258339.
// RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s // Malloc/free hooks are not supported on Windows. // XFAIL: win32 #include <stdlib.h> #include <unistd.h> #include <sanitizer/allocator_interface.h> extern "C" { const volatile void *global_ptr; // Note: avoid calling functions that allocate memory in malloc/free // to avoid infinite recursion. void __sanitizer_malloc_hook(const volatile void *ptr, size_t sz) { if (__sanitizer_get_ownership(ptr)) { write(1, "MallocHook\n", sizeof("MallocHook\n")); global_ptr = ptr; } } void __sanitizer_free_hook(const volatile void *ptr) { if (__sanitizer_get_ownership(ptr) && ptr == global_ptr) write(1, "FreeHook\n", sizeof("FreeHook\n")); } } // extern "C" int main() { volatile int *x = new int; // CHECK: MallocHook // Check that malloc hook was called with correct argument. if (global_ptr != (void*)x) { _exit(1); } *x = 0; delete x; // CHECK: FreeHook return 0; }
// RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s // Malloc/free hooks are not supported on Windows. // XFAIL: win32 #include <stdlib.h> #include <unistd.h> #include <sanitizer/allocator_interface.h> extern "C" { const volatile void *global_ptr; // Note: avoid calling functions that allocate memory in malloc/free // to avoid infinite recursion. void __sanitizer_malloc_hook(const volatile void *ptr, size_t sz) { if (__sanitizer_get_ownership(ptr) && sz == 4) { write(1, "MallocHook\n", sizeof("MallocHook\n")); global_ptr = ptr; } } void __sanitizer_free_hook(const volatile void *ptr) { if (__sanitizer_get_ownership(ptr) && ptr == global_ptr) write(1, "FreeHook\n", sizeof("FreeHook\n")); } } // extern "C" volatile int *x; // Call this function with uninitialized arguments to poison // TLS shadow for function parameters before calling operator // new and, eventually, user-provided hook. __attribute__((noinline)) void allocate(int *unused1, int *unused2) { x = new int; } int main() { int *undef1, *undef2; allocate(undef1, undef2); // CHECK: MallocHook // Check that malloc hook was called with correct argument. if (global_ptr != (void*)x) { _exit(1); } *x = 0; delete x; // CHECK: FreeHook return 0; }
Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout
// 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" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << 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" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } // Disabled, flakily exceeds timeout, http://crbug.com/72165. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_; }
Allow thinglang bytecode to be piped directly into the VM
#include <iostream> #include <vector> #include <fstream> #include "errors/RuntimeError.h" #include "execution/Program.h" #include "loader/ProgramReader.h" int main(int argc, char **argv) { if (argc != 2) { std::cerr << "Usage: thingc filename.thingc" << std::endl; return 1; } auto reader = ProgramReader(argv[1]); try { auto info = reader.process(); Program::load(info); Program::start(); } catch (const RuntimeError &err) { std::cerr << "Error during execution: " << err.what() << std::endl; return 1; } return 0; }
#include <iostream> #include <vector> #include <fstream> #include "errors/RuntimeError.h" #include "execution/Program.h" #include "loader/ProgramReader.h" int main(int argc, char **argv) { if (argc != 2) { std::cerr << "Usage: thingc filename.thingc" << std::endl; return 1; } auto filename = std::string(argv[1]); if(filename == "--build-only"){ std::cerr << "Build completed, not executing." << std::endl; return 0; } auto reader = filename == "-" ? ProgramReader() : ProgramReader(filename); try { auto info = reader.process(); Program::load(info); Program::start(); } catch (const RuntimeError &err) { std::cerr << "Error during execution: " << err.what() << std::endl; return 1; } return 0; }
Improve auto declination test, not great coverage yet.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <systemlib/mixer/mixer.h> #include <systemlib/err.h> #include <drivers/drv_hrt.h> #include <px4iofirmware/px4io.h> #include "../../src/systemcmds/tests/tests.h" #include <geo/geo.h> int main(int argc, char *argv[]) { warnx("autodeclination test started"); if (argc < 3) errx(1, "Need lat/lon!"); char* p_end; float lat = strtod(argv[1], &p_end); float lon = strtod(argv[2], &p_end); float declination = get_mag_declination(lat, lon); printf("lat: %f lon: %f, dec: %f\n", lat, lon, declination); }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> #include <systemlib/mixer/mixer.h> #include <systemlib/err.h> #include <drivers/drv_hrt.h> #include <px4iofirmware/px4io.h> // #include "../../src/systemcmds/tests/tests.h" #include <geo/geo.h> int main(int argc, char *argv[]) { warnx("autodeclination test started"); char* latstr = 0; char* lonstr = 0; char* declstr = 0; if (argc < 4) { warnx("Too few arguments. Using default lat / lon and declination"); latstr = "47.0"; lonstr = "8.0"; declstr = "0.6"; } else { latstr = argv[1]; lonstr = argv[2]; declstr = argv[3]; } char* p_end; float lat = strtod(latstr, &p_end); float lon = strtod(lonstr, &p_end); float decl_truth = strtod(declstr, &p_end); float declination = get_mag_declination(lat, lon); printf("lat: %f lon: %f, expected dec: %f, estimated dec: %f\n", lat, lon, declination, decl_truth); int ret = 0; // Fail if the declination differs by more than one degree float decldiff = fabs(decl_truth - declination); if (decldiff > 0.5f) { warnx("declination differs more than 1 degree: difference: %12.8f", decldiff); ret = 1; } return ret; }
Fix wrong event type for mouse move events
#include <gloperate/input/MouseDevice.h> #include <gloperate/input/MouseEvent.h> #include <gloperate/input/InputManager.h> namespace gloperate { MouseDevice::MouseDevice(InputManager * inputManager, const std::string & deviceDescriptor) : AbstractDevice(inputManager, deviceDescriptor) { } MouseDevice::~MouseDevice() { } void MouseDevice::move(const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseButtonPress, this, pos }; m_inputManager->onEvent(inputEvent); } void MouseDevice::buttonPress(int button, const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseButtonPress, this, pos, button }; m_inputManager->onEvent(inputEvent); } void MouseDevice::buttonRelease(int button, const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseButtonRelease, this, pos, button }; m_inputManager->onEvent(inputEvent); } void MouseDevice::wheelScroll(const glm::vec2 & delta, const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseWheelScroll, this, pos, delta }; m_inputManager->onEvent(inputEvent); } void MouseDevice::update() { } } // namespace gloperate
#include <gloperate/input/MouseDevice.h> #include <gloperate/input/MouseEvent.h> #include <gloperate/input/InputManager.h> namespace gloperate { MouseDevice::MouseDevice(InputManager * inputManager, const std::string & deviceDescriptor) : AbstractDevice(inputManager, deviceDescriptor) { } MouseDevice::~MouseDevice() { } void MouseDevice::move(const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseMove, this, pos }; m_inputManager->onEvent(inputEvent); } void MouseDevice::buttonPress(int button, const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseButtonPress, this, pos, button }; m_inputManager->onEvent(inputEvent); } void MouseDevice::buttonRelease(int button, const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseButtonRelease, this, pos, button }; m_inputManager->onEvent(inputEvent); } void MouseDevice::wheelScroll(const glm::vec2 & delta, const glm::ivec2 & pos) { auto inputEvent = new MouseEvent{ InputEvent::Type::MouseWheelScroll, this, pos, delta }; m_inputManager->onEvent(inputEvent); } void MouseDevice::update() { } } // namespace gloperate
Fix output of non-integer parameters
#include <chrono> #include <cstdint> #include <iostream> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> std::mutex output; void func(unsigned int value) { using std::chrono::seconds; using std::cout; using std::endl; using std::lock_guard; using std::mutex; std::this_thread::sleep_for(seconds(value)); { lock_guard<mutex> lock{output}; cout << value << endl; } } int main(int argc, char** argv) { using std::cout; using std::endl; using std::string; using std::stringstream; using std::thread; using std::vector; vector<thread>::size_type amount = argc - 1; vector<thread> threads; threads.reserve(amount); for (auto i = 1; i < argc; ++i) { stringstream ss; ss << argv[i]; unsigned int value; if (!(ss >> value)) { string invalid; ss >> invalid; cout << "You input a non-integer: " << invalid << endl; } else { threads.emplace_back(func, value); } } for (auto& thread : threads) { thread.join(); } return 0; }
#include <chrono> #include <cstdint> #include <iostream> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> std::mutex output; void func(unsigned int value) { using std::chrono::seconds; using std::cout; using std::endl; using std::lock_guard; using std::mutex; std::this_thread::sleep_for(seconds(value)); { lock_guard<mutex> lock{output}; cout << value << endl; } } int main(int argc, char** argv) { using std::cout; using std::endl; using std::string; using std::stringstream; using std::thread; using std::vector; vector<thread>::size_type amount = argc - 1; vector<thread> threads; threads.reserve(amount); for (auto i = 1; i < argc; ++i) { stringstream ss; ss << argv[i]; unsigned int value; if (!(ss >> value)) { cout << "You input a non-integer: " << argv[i] << endl; } else { threads.emplace_back(func, value); } } for (auto& thread : threads) { thread.join(); } return 0; }
Fix build failure with GCC <= 4.7
#include "config.h" #ifdef HAVE_ASPRINTF #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include "globit.c" #endif
#include "config.h" #ifdef HAVE_ASPRINTF #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include "globit.c" #endif
Replace random seed with something more unique
// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Plate/detail/Seed.h> #include <vw/Core/Thread.h> #include <boost/cast.hpp> namespace { vw::RunOnce seed_once = VW_RUNONCE_INIT; void hidden_seed_random() { srandom(boost::numeric_cast<unsigned int>(clock())); } } namespace vw { namespace platefile { void plate_seed_random() { seed_once.run( hidden_seed_random ); } }}
// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Plate/detail/Seed.h> #include <vw/Core/Thread.h> #include <vw/Core/Stopwatch.h> #include <sys/types.h> namespace { vw::RunOnce seed_once = VW_RUNONCE_INIT; void hidden_seed_random() { srandom(vw::Stopwatch::microtime()*::getpid()); } } namespace vw { namespace platefile { void plate_seed_random() { seed_once.run( hidden_seed_random ); } }}