Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Patch for PVS-studio related checks.
#include "qobjectfinalizer.h" #include <QVariant> #include "getvalue.h" #include "pushvalue.h" #include "toqobject.h" #include "convert.h" duk_ret_t dukpp03::qt::qobjectfinalizer(duk_context* ctx) { QVariant* v = dukpp03::Finalizer<dukpp03::qt::BasicContext>::getVariantToFinalize(ctx); dukpp03::qt::BasicContext* parent = static_cast<dukpp03::qt::BasicContext*>(dukpp03::AbstractContext::getContext(ctx)); if (v) { if (parent->isVariantRegistered(v)) { QVariant result; if (dukpp03::qt::Convert::convert("QObject*", v, result)) { delete result.value<QObject*>(); } delete v; parent->unregisterVariant(v); } } return 0; }
#include "qobjectfinalizer.h" #include <QVariant> #include "getvalue.h" #include "pushvalue.h" #include "toqobject.h" #include "convert.h" duk_ret_t dukpp03::qt::qobjectfinalizer(duk_context* ctx) { QVariant* v = dukpp03::Finalizer<dukpp03::qt::BasicContext>::getVariantToFinalize(ctx); dukpp03::qt::BasicContext* parent = static_cast<dukpp03::qt::BasicContext*>(dukpp03::AbstractContext::getContext(ctx)); if (v) { if (parent->isVariantRegistered(v)) { QVariant result; if (dukpp03::qt::Convert::convert("QObject*", v, result)) { delete result.value<QObject*>(); } parent->unregisterVariant(v); delete v; } } return 0; }
Remove switch case temporarlily for bulid purposes
//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "common/logger.h" namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { if (parse_tree.get() == nullptr) return NULL; std::shared_ptr<planner::AbstractPlan> plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch(parse_item_node_type){ case PARSE_NODE_TYPE_SCAN: child_plan = new planner::SeqScanPlan(); break; } // if (child_plan != nullptr) { // if (plan_tree != nullptr) // plan_tree->AddChild(child_plan); // else // plan_tree = child_plan; // } return plan_tree; } } // namespace optimizer } // namespace peloton
//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "common/logger.h" namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { if (parse_tree.get() == nullptr) return NULL; std::shared_ptr<planner::AbstractPlan> plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); // if (child_plan != nullptr) { // if (plan_tree != nullptr) // plan_tree->AddChild(child_plan); // else // plan_tree = child_plan; // } return plan_tree; } } // namespace optimizer } // namespace peloton
Remove switch case temporarlily for bulid purposes
//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "common/logger.h" namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { if (parse_tree.get() == nullptr) return NULL; std::shared_ptr<planner::AbstractPlan> plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch(parse_item_node_type){ case PARSE_NODE_TYPE_SCAN: child_plan = new planner::SeqScanPlan(); break; } // if (child_plan != nullptr) { // if (plan_tree != nullptr) // plan_tree->AddChild(child_plan); // else // plan_tree = child_plan; // } return plan_tree; } } // namespace optimizer } // namespace peloton
//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "common/logger.h" namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { if (parse_tree.get() == nullptr) return NULL; std::shared_ptr<planner::AbstractPlan> plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); // if (child_plan != nullptr) { // if (plan_tree != nullptr) // plan_tree->AddChild(child_plan); // else // plan_tree = child_plan; // } return plan_tree; } } // namespace optimizer } // namespace peloton
Mark the log_path ubsan test as requiring a shell. It uses globs.
// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316 // XFAIL: android // RUN: %clangxx -fsanitize=undefined %s -O1 -o %t // Regular run. // RUN: %run %t -4 2> %t.out // RUN: FileCheck %s --check-prefix=CHECK-ERROR < %t.out // Good log_path. // RUN: rm -f %t.log.* // RUN: %env_ubsan_opts=log_path='"%t.log"' %run %t -4 2> %t.out // RUN: FileCheck %s --check-prefix=CHECK-ERROR < %t.log.* // Run w/o errors should not produce any log. // RUN: rm -f %t.log.* // RUN: %env_ubsan_opts=log_path='"%t.log"' %run %t 4 // RUN: not cat %t.log.* // FIXME: log_path is not supported on Windows yet. // XFAIL: win32 #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { double a = atof(argv[1]); unsigned int ai = (unsigned int) a; printf("%f %u\n", a, ai); return 0; } // CHECK-ERROR: runtime error: value -4 is outside the range of representable values of type 'unsigned int'
// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316 // XFAIL: android // The globs below do not work in the lit shell. // REQUIRES: shell // RUN: %clangxx -fsanitize=undefined %s -O1 -o %t // Regular run. // RUN: %run %t -4 2> %t.out // RUN: FileCheck %s --check-prefix=CHECK-ERROR < %t.out // Good log_path. // RUN: rm -f %t.log.* // RUN: %env_ubsan_opts=log_path='"%t.log"' %run %t -4 2> %t.out // RUN: FileCheck %s --check-prefix=CHECK-ERROR < %t.log.* // Run w/o errors should not produce any log. // RUN: rm -f %t.log.* // RUN: %env_ubsan_opts=log_path='"%t.log"' %run %t 4 // RUN: not cat %t.log.* // FIXME: log_path is not supported on Windows yet. // XFAIL: win32 #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { double a = atof(argv[1]); unsigned int ai = (unsigned int) a; printf("%f %u\n", a, ai); return 0; } // CHECK-ERROR: runtime error: value -4 is outside the range of representable values of type 'unsigned int'
Comment out a very annoying NOTIMPLEMENTED().
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_logging.h" #include "base/logging.h" #include "googleurl/src/gurl.h" namespace renderer_logging { // Sets the URL that is logged if the renderer crashes. Use GURL() to clear // the URL. void SetActiveRendererURL(const GURL& url) { // TODO(port): Once breakpad is integrated we can turn this on. NOTIMPLEMENTED(); } } // namespace renderer_logging
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_logging.h" #include "base/logging.h" #include "googleurl/src/gurl.h" namespace renderer_logging { // Sets the URL that is logged if the renderer crashes. Use GURL() to clear // the URL. void SetActiveRendererURL(const GURL& url) { // crbug.com/9646 } } // namespace renderer_logging
Use sync dir engine instead of async
#include "fileplugin.h" #include "direngine.h" #ifdef Q_OS_WIN #include "fileenginewin.h" #endif #include "fileenginefallback.h" FilePlugin::FilePlugin(QObject *parent) : AbstractFileEnginePlugin(parent) { } QStringList FilePlugin::schemes() const { return QStringList() << "file" << "qrc"; } AbstractFileEngine *FilePlugin::createFileEngine(const QString &scheme) const { if (scheme == "qrc") return new FileEngineFallback; if (scheme != "file") return Q_NULLPTR; #ifdef Q_OS_WIN return new FileEngineWin; #else return new FileEngineFallback; #endif } AbstractDirEngine *FilePlugin::createDirEngine(const QString &scheme) const { if (scheme != "qrc" && scheme != "file") return Q_NULLPTR; return new DirEngine; }
#include "fileplugin.h" #include "syncdirengine.h" #ifdef Q_OS_WIN #include "fileenginewin.h" #endif #include "fileenginefallback.h" #include <QIO/SyncDirEngineWrapper> FilePlugin::FilePlugin(QObject *parent) : AbstractFileEnginePlugin(parent) { } QStringList FilePlugin::schemes() const { return QStringList() << "file" << "qrc"; } AbstractFileEngine *FilePlugin::createFileEngine(const QString &scheme) const { if (scheme == "qrc") return new FileEngineFallback; if (scheme != "file") return Q_NULLPTR; #ifdef Q_OS_WIN return new FileEngineWin; #else return new FileEngineFallback; #endif } AbstractDirEngine *FilePlugin::createDirEngine(const QString &scheme) const { if (scheme != "qrc" && scheme != "file") return Q_NULLPTR; return new SyncDirEngineWrapper(new SyncDirEngine); }
Increase minimum threads in test suite to 4.
#include <caf/set_scheduler.hpp> #include "vast.h" #include "vast/filesystem.h" #include "vast/logger.h" #include "vast/serialization.h" #include "framework/unit.h" int main(int argc, char* argv[]) { // Work around CAF bug that blocks VAST in our "distributed" actor unit test // when using less than three threads. if (std::thread::hardware_concurrency() == 1) caf::set_scheduler<>(3); vast::announce_builtin_types(); auto cfg = unit::configuration::parse(argc, argv); if (! cfg) { std::cerr << cfg.error() << '\n'; return 1; } auto log_dir = vast::path{*cfg->get("vast-log-dir")}; if (! vast::logger::instance()->init( vast::logger::quiet, vast::logger::debug, false, false, log_dir)) { std::cerr << "failed to initialize VAST's logger" << std::endl; return 1; } auto rc = unit::engine::run(*cfg); if (! cfg->check("vast-keep-logs")) vast::rm(log_dir); return vast::cleanup() && rc ? 0 : 1; }
#include <caf/set_scheduler.hpp> #include "vast.h" #include "vast/filesystem.h" #include "vast/logger.h" #include "vast/serialization.h" #include "framework/unit.h" int main(int argc, char* argv[]) { // Because we use several blocking actors in the unit tests, we need at least // some real parallelism to avoid a deadlock. if (std::thread::hardware_concurrency() < 4) caf::set_scheduler<>(4); vast::announce_builtin_types(); auto cfg = unit::configuration::parse(argc, argv); if (! cfg) { std::cerr << cfg.error() << '\n'; return 1; } auto log_dir = vast::path{*cfg->get("vast-log-dir")}; if (! vast::logger::instance()->init( vast::logger::quiet, vast::logger::debug, false, false, log_dir)) { std::cerr << "failed to initialize VAST's logger" << std::endl; return 1; } auto rc = unit::engine::run(*cfg); if (! cfg->check("vast-keep-logs")) vast::rm(log_dir); return vast::cleanup() && rc ? 0 : 1; }
Build Fix for Win: Make base_i18n_nacl_win64.dll.lib to be generated
// 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/i18n/icu_util.h" namespace icu_util { bool Initialize() { return true; } } // namespace icu_util
// 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/i18n/icu_util.h" namespace base { namespace i18n { BASE_I18N_EXPORT bool InitializeICU() { return true; } } // namespace i18n } // namespace base
Return a NULL selection if QItemSelectionModel is set.
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDataNodeSelectionProvider.h" #include "internal/QmitkDataNodeSelection.h" QmitkDataNodeSelectionProvider::QmitkDataNodeSelectionProvider() : berry::QtSelectionProvider() { } berry::ISelection::ConstPointer QmitkDataNodeSelectionProvider::GetSelection() const { return this->GetDataNodeSelection(); } mitk::DataNodeSelection::ConstPointer QmitkDataNodeSelectionProvider::GetDataNodeSelection() const { if (qSelectionModel) { QmitkDataNodeSelection::ConstPointer sel(new QmitkDataNodeSelection( qSelectionModel->selection())); return sel; } return QmitkDataNodeSelection::ConstPointer(new QmitkDataNodeSelection()); } void QmitkDataNodeSelectionProvider::FireSelectionChanged( const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { berry::ISelection::ConstPointer sel(this->GetDataNodeSelection()); berry::SelectionChangedEvent::Pointer event(new berry::SelectionChangedEvent( berry::ISelectionProvider::Pointer(this), sel)); selectionEvents.selectionChanged(event); }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDataNodeSelectionProvider.h" #include "internal/QmitkDataNodeSelection.h" QmitkDataNodeSelectionProvider::QmitkDataNodeSelectionProvider() : berry::QtSelectionProvider() { } berry::ISelection::ConstPointer QmitkDataNodeSelectionProvider::GetSelection() const { return this->GetDataNodeSelection(); } mitk::DataNodeSelection::ConstPointer QmitkDataNodeSelectionProvider::GetDataNodeSelection() const { if (qSelectionModel) { QmitkDataNodeSelection::ConstPointer sel(new QmitkDataNodeSelection( qSelectionModel->selection())); return sel; } return QmitkDataNodeSelection::ConstPointer(0); } void QmitkDataNodeSelectionProvider::FireSelectionChanged( const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { berry::ISelection::ConstPointer sel(this->GetDataNodeSelection()); berry::SelectionChangedEvent::Pointer event(new berry::SelectionChangedEvent( berry::ISelectionProvider::Pointer(this), sel)); selectionEvents.selectionChanged(event); }
Remove a stray tab that snuck into a test. No functionality change
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <iterator> // reverse_iterator // template <class Iterator> reverse_iterator<Iterator> // make_reverse_iterator(Iterator i); #include <iterator> #include <cassert> #include "test_iterators.h" #if _LIBCPP_STD_VER > 11 template <class It> void test(It i) { const std::reverse_iterator<It> r = std::make_reverse_iterator(i); assert(r.base() == i); } int main() { const char* s = "1234567890"; random_access_iterator<const char*>b(s); random_access_iterator<const char*>e(s+10); while ( b != e ) test ( b++ ); } #else int main () {} #endif
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <iterator> // reverse_iterator // template <class Iterator> reverse_iterator<Iterator> // make_reverse_iterator(Iterator i); #include <iterator> #include <cassert> #include "test_iterators.h" #if _LIBCPP_STD_VER > 11 template <class It> void test(It i) { const std::reverse_iterator<It> r = std::make_reverse_iterator(i); assert(r.base() == i); } int main() { const char* s = "1234567890"; random_access_iterator<const char*>b(s); random_access_iterator<const char*>e(s+10); while ( b != e ) test ( b++ ); } #else int main () {} #endif
Disable ExtensionApiTest.Popup. It's been timing out for the last 750+ runs.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Flaky, http://crbug.com/46601. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_main")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupFromInfobar) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_from_infobar")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Times out. See http://crbug.com/46601. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_main")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupFromInfobar) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_from_infobar")) << message_; }
Check that include files exists in nmakefiles.
#include "NMakefile.hpp" #include <configure/Build.hpp> #include <configure/Filesystem.hpp> #include <configure/quote.hpp> #include <configure/Node.hpp> namespace configure { namespace generators { bool NMakefile::is_available(Build& build) { return build.fs().which("nmake") != boost::none; } std::string NMakefile::dump_command(std::vector<std::string> const& cmd) const { return quote<CommandParser::nmake>(cmd); } std::vector<std::string> NMakefile::build_command(std::string const& target) const { return { "nmake", "-nologo", "-f", (_build.directory() / "Makefile").string(), target.empty() ? "all" : target }; } bool NMakefile::use_relative_path() const { return false; } void NMakefile::include_dependencies(std::ostream& out, bool /* XXX relative */) const { for (auto& node: _includes) out << "!include " << node->path().string() << std::endl; } }}
#include "NMakefile.hpp" #include <configure/Build.hpp> #include <configure/Filesystem.hpp> #include <configure/quote.hpp> #include <configure/Node.hpp> namespace configure { namespace generators { bool NMakefile::is_available(Build& build) { return build.fs().which("nmake") != boost::none; } std::string NMakefile::dump_command(std::vector<std::string> const& cmd) const { return quote<CommandParser::nmake>(cmd); } std::vector<std::string> NMakefile::build_command(std::string const& target) const { return { "nmake", "-nologo", "-f", (_build.directory() / "Makefile").string(), target.empty() ? "all" : target }; } bool NMakefile::use_relative_path() const { return false; } void NMakefile::include_dependencies(std::ostream& out, bool /* XXX relative */) const { for (auto& node: _includes) out << "!IF EXISTS(" << node->path().string() << ")" << std::endl << " !INCLUDE " << node->path().string() << std::endl << "!ENDIF" << std::endl; } }}
Replace tab to space of indent on static_tf
#include <ros/ros.h> #include <tf/transform_broadcaster.h> int main(int argc, char** argv){ ros::init(argc, argv, "static_tf_node"); ros::NodeHandle n; ros::Rate r(100); tf::TransformBroadcaster broadcaster; while(n.ok()){ broadcaster.sendTransform( tf::StampedTransform( tf::Transform( tf::Quaternion(0, 0, 0, 1), tf::Vector3(0.1, 0.0, 0.2) ), ros::Time::now(),"base_link", "base_laser") ); r.sleep(); } }
#include <ros/ros.h> #include <tf/transform_broadcaster.h> int main(int argc, char** argv){ ros::init(argc, argv, "static_tf_node"); ros::NodeHandle n; ros::Rate r(100); tf::TransformBroadcaster broadcaster; while(n.ok()){ broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0, 0, 0, 1), tf::Vector3(0.1, 0.0, 0.2)), ros::Time::now(), "base_link", "base_laser" ) ); r.sleep(); } }
Use relaxed memory ordering for speed.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "retrytransienterrorspolicy.h" #include <vespa/messagebus/errorcode.h> namespace mbus { RetryTransientErrorsPolicy::RetryTransientErrorsPolicy() : _enabled(true), _baseDelay(1.0) {} RetryTransientErrorsPolicy & RetryTransientErrorsPolicy::setEnabled(bool enabled) { _enabled = enabled; return *this; } RetryTransientErrorsPolicy & RetryTransientErrorsPolicy::setBaseDelay(double baseDelay) { _baseDelay = baseDelay; return *this; } bool RetryTransientErrorsPolicy::canRetry(uint32_t errorCode) const { return _enabled && errorCode < ErrorCode::FATAL_ERROR; } double RetryTransientErrorsPolicy::getRetryDelay(uint32_t retry) const { return _baseDelay * retry; } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "retrytransienterrorspolicy.h" #include <vespa/messagebus/errorcode.h> namespace mbus { RetryTransientErrorsPolicy::RetryTransientErrorsPolicy() : _enabled(true), _baseDelay(1.0) {} RetryTransientErrorsPolicy & RetryTransientErrorsPolicy::setEnabled(bool enabled) { _enabled = enabled; return *this; } RetryTransientErrorsPolicy & RetryTransientErrorsPolicy::setBaseDelay(double baseDelay) { _baseDelay = baseDelay; return *this; } bool RetryTransientErrorsPolicy::canRetry(uint32_t errorCode) const { return _enabled.load(std::memory_order_relaxed) && errorCode < ErrorCode::FATAL_ERROR; } double RetryTransientErrorsPolicy::getRetryDelay(uint32_t retry) const { return _baseDelay.load(std::memory_order_relaxed) * retry; } }
Add an HTTP basic auth unit test for an empty username.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "base/basictypes.h" #include "net/http/http_auth_handler_basic.h" namespace net { TEST(HttpAuthHandlerBasicTest, GenerateCredentials) { static const struct { const wchar_t* username; const wchar_t* password; const char* expected_credentials; } tests[] = { { L"foo", L"bar", "Basic Zm9vOmJhcg==" }, // Empty password { L"anon", L"", "Basic YW5vbjo=" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::string challenge = "Basic realm=\"Atlantis\""; HttpAuthHandlerBasic basic; basic.InitFromChallenge(challenge.begin(), challenge.end(), HttpAuth::AUTH_SERVER); std::string credentials = basic.GenerateCredentials(tests[i].username, tests[i].password, NULL, NULL); EXPECT_STREQ(tests[i].expected_credentials, credentials.c_str()); } } } // namespace net
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "base/basictypes.h" #include "net/http/http_auth_handler_basic.h" namespace net { TEST(HttpAuthHandlerBasicTest, GenerateCredentials) { static const struct { const wchar_t* username; const wchar_t* password; const char* expected_credentials; } tests[] = { { L"foo", L"bar", "Basic Zm9vOmJhcg==" }, // Empty username { L"", L"foobar", "Basic OmZvb2Jhcg==" }, // Empty password { L"anon", L"", "Basic YW5vbjo=" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::string challenge = "Basic realm=\"Atlantis\""; HttpAuthHandlerBasic basic; basic.InitFromChallenge(challenge.begin(), challenge.end(), HttpAuth::AUTH_SERVER); std::string credentials = basic.GenerateCredentials(tests[i].username, tests[i].password, NULL, NULL); EXPECT_STREQ(tests[i].expected_credentials, credentials.c_str()); } } } // namespace net
Change logic to enable for group Enabled (for A/B testing).
// Copyright 2015 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/sessions/session_restore_delegate.h" #include "base/metrics/field_trial.h" #include "chrome/browser/sessions/session_restore_stats_collector.h" #include "chrome/browser/sessions/tab_loader.h" // static void SessionRestoreDelegate::RestoreTabs( const std::vector<RestoredTab>& tabs, const base::TimeTicks& restore_started) { // TODO(georgesak): make tests aware of that behavior so that they succeed if // tab loading is disabled. base::FieldTrial* trial = base::FieldTrialList::Find("SessionRestoreBackgroundLoading"); bool active_only = true; if (!trial || trial->group_name() != "Disabled") { TabLoader::RestoreTabs(tabs, restore_started); active_only = false; } SessionRestoreStatsCollector::TrackTabs(tabs, restore_started, active_only); }
// Copyright 2015 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/sessions/session_restore_delegate.h" #include "base/metrics/field_trial.h" #include "chrome/browser/sessions/session_restore_stats_collector.h" #include "chrome/browser/sessions/tab_loader.h" // static void SessionRestoreDelegate::RestoreTabs( const std::vector<RestoredTab>& tabs, const base::TimeTicks& restore_started) { // TODO(georgesak): make tests aware of that behavior so that they succeed if // tab loading is disabled. base::FieldTrial* trial = base::FieldTrialList::Find("SessionRestoreBackgroundLoading"); bool active_only = true; if (!trial || trial->group_name() == "Enabled") { TabLoader::RestoreTabs(tabs, restore_started); active_only = false; } SessionRestoreStatsCollector::TrackTabs(tabs, restore_started, active_only); }
Allow instantiation of sequence from file path
#include "ofxHapImageSequence.h" ofxHapImageSequence::ofxHapImageSequence() { } ofxHapImageSequence::ofxHapImageSequence(ofDirectory& directory) { load(directory); } ofxHapImageSequence::ofxHapImageSequence(const std::string& path) { load(path); } ofxHapImageSequence::~ofxHapImageSequence() { } void ofxHapImageSequence::load(ofDirectory &directory) { load(directory.path()); } void ofxHapImageSequence::load(const std::string &path) { directory_ = ofDirectory(path); directory_.allowExt(ofxHapImage::HapImageFileExtension()); directory_.listDir(); directory_.sort(); } unsigned int ofxHapImageSequence::size() { return directory_.size(); } ofxHapImage ofxHapImageSequence::getImage(unsigned int index) { return ofxHapImage(directory_[index]); }
#include "ofxHapImageSequence.h" ofxHapImageSequence::ofxHapImageSequence() { } ofxHapImageSequence::ofxHapImageSequence(ofDirectory& directory) { load(directory); } ofxHapImageSequence::ofxHapImageSequence(const std::string& path) { load(path); } ofxHapImageSequence::~ofxHapImageSequence() { } void ofxHapImageSequence::load(ofDirectory &directory) { load(directory.path()); } void ofxHapImageSequence::load(const std::string &path) { ofFile file(path, ofFile::Reference); if (file.exists() && !file.isDirectory()) { file = ofFile(file.getEnclosingDirectory(), ofFile::Reference); } // listDir() and sort() are slow in Debug builds on Windows directory_ = ofDirectory(file.getAbsolutePath()); directory_.allowExt(ofxHapImage::HapImageFileExtension()); directory_.listDir(); directory_.sort(); } unsigned int ofxHapImageSequence::size() { return directory_.size(); } ofxHapImage ofxHapImageSequence::getImage(unsigned int index) { return ofxHapImage(directory_[index]); }
Put an additional print in place.
#include <iostream> class MyClass { public: MyClass(int value) : m_fixedValue(value) {} const int m_fixedValue; static const int m_fixedStaticValue; }; const int MyClass::m_fixedStaticValue = 9; int main() { const MyClass myInstance(9); std::cout << myInstance.m_fixedValue << std::endl; const_cast<int&>(myInstance.m_fixedValue) = 7; const_cast<int&>(myInstance.m_fixedStaticValue) = 7; std::cout << myInstance.m_fixedValue << std::endl; }
#include <iostream> class MyClass { public: MyClass(int value) : m_fixedValue(value) {} const int m_fixedValue; static const int m_fixedStaticValue; }; const int MyClass::m_fixedStaticValue = 9; int main() { const MyClass myInstance(9); std::cout << myInstance.m_fixedValue << std::endl; const_cast<int&>(myInstance.m_fixedValue) = 7; std::cout << myInstance.m_fixedValue << std::endl; const_cast<int&>(myInstance.m_fixedStaticValue) = 7; std::cout << MyClass::m_fixedStaticValue<< std::endl; }
Make sure std::atomic is initialized correctly
#include <thread> #include <atomic> #include <iostream> #include <vector> struct AtomicCounter { std::atomic<int> value; void increment(){ ++value; } void decrement(){ --value; } int get(){ return value.load(); } }; int main(){ AtomicCounter counter; std::vector<std::thread> threads; for(int i = 0; i < 10; ++i){ threads.push_back(std::thread([&counter](){ for(int i = 0; i < 500; ++i){ counter.increment(); } })); } for(auto& thread : threads){ thread.join(); } std::cout << counter.get() << std::endl; return 0; }
#include <thread> #include <atomic> #include <iostream> #include <vector> struct AtomicCounter { std::atomic<int> value; AtomicCounter() : value(0) {} void increment(){ ++value; } void decrement(){ --value; } int get(){ return value.load(); } }; int main(){ AtomicCounter counter; std::vector<std::thread> threads; for(int i = 0; i < 10; ++i){ threads.push_back(std::thread([&counter](){ for(int i = 0; i < 500; ++i){ counter.increment(); } })); } for(auto& thread : threads){ thread.join(); } std::cout << counter.get() << std::endl; return 0; }
Add dummy DeletePlatformShortcuts() for Android.
// 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/web_applications/web_app.h" namespace web_app { namespace internals { bool CreatePlatformShortcut( const FilePath& web_app_path, const FilePath& profile_path, const ShellIntegration::ShortcutInfo& shortcut_info) { return true; } } // namespace internals } // namespace web_app
// 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/web_applications/web_app.h" namespace web_app { namespace internals { bool CreatePlatformShortcut( const FilePath& web_app_path, const FilePath& profile_path, const ShellIntegration::ShortcutInfo& shortcut_info) { return true; } void DeletePlatformShortcuts(const FilePath& profile_path, const std::string& extension_id) {} } // namespace internals } // namespace web_app
Fix findbar visibility when switching between tabs.
// 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/views/dropdown_bar_host.h" #include "base/logging.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" using content::WebContents; NativeWebKeyboardEvent DropdownBarHost::GetKeyboardEvent( const WebContents* contents, const views::KeyEvent& key_event) { return NativeWebKeyboardEvent(key_event.native_event()); } void DropdownBarHost::SetWidgetPositionNative(const gfx::Rect& new_pos, bool no_redraw) { if (!host_->IsVisible()) host_->GetNativeView()->Show(); host_->GetNativeView()->SetBounds(new_pos); }
// 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/dropdown_bar_host.h" #include "base/logging.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" using content::WebContents; NativeWebKeyboardEvent DropdownBarHost::GetKeyboardEvent( const WebContents* contents, const views::KeyEvent& key_event) { return NativeWebKeyboardEvent(key_event.native_event()); } void DropdownBarHost::SetWidgetPositionNative(const gfx::Rect& new_pos, bool no_redraw) { if (!host_->IsVisible()) host_->GetNativeView()->Show(); host_->GetNativeView()->SetBounds(new_pos); host_->StackAtTop(); }
Switch from InterlockedExchangePointer back to APR atomic
/* * Copyright 2003-2005 The Apache Software Foundation. * * 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 <log4cxx/helpers/objectptr.h> #include <log4cxx/helpers/exception.h> #include <apr_atomic.h> using namespace log4cxx::helpers; void ObjectPtrBase::checkNull(const int& null) { if (null != 0) { throw IllegalArgumentException("Attempt to set pointer to a non-zero numeric value."); } } void* ObjectPtrBase::exchange(volatile void** destination, void* newValue) { #if defined(_WIN32) return InterlockedExchangePointer(destination, newValue); #else return apr_atomic_casptr(destination, newValue, (const void*) *destination); #endif }
/* * Copyright 2003-2005 The Apache Software Foundation. * * 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 <log4cxx/helpers/objectptr.h> #include <log4cxx/helpers/exception.h> #include <apr_atomic.h> using namespace log4cxx::helpers; void ObjectPtrBase::checkNull(const int& null) { if (null != 0) { throw IllegalArgumentException("Attempt to set pointer to a non-zero numeric value."); } } void* ObjectPtrBase::exchange(volatile void** destination, void* newValue) { return apr_atomic_casptr(destination, newValue, (const void*) *destination); }
Add newline at end of file to remove gcc warning.
//===-- XCoreTargetObjectFile.cpp - XCore object files --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "XCoreTargetObjectFile.h" #include "XCoreSubtarget.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; void XCoreTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM){ TargetLoweringObjectFileELF::Initialize(Ctx, TM); TextSection = getOrCreateSection("\t.text", true, SectionKind::Text); DataSection = getOrCreateSection("\t.dp.data", false, SectionKind::DataRel); BSSSection_ = getOrCreateSection("\t.dp.bss", false, SectionKind::BSS); // TLS globals are lowered in the backend to arrays indexed by the current // thread id. After lowering they require no special handling by the linker // and can be placed in the standard data / bss sections. TLSDataSection = DataSection; TLSBSSSection = BSSSection_; if (TM.getSubtarget<XCoreSubtarget>().isXS1A()) // FIXME: Why is this writable ("datarel")??? ReadOnlySection = getOrCreateSection("\t.dp.rodata", false, SectionKind::DataRel); else ReadOnlySection = getOrCreateSection("\t.cp.rodata", false, SectionKind::ReadOnly); }
//===-- XCoreTargetObjectFile.cpp - XCore object files --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "XCoreTargetObjectFile.h" #include "XCoreSubtarget.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; void XCoreTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM){ TargetLoweringObjectFileELF::Initialize(Ctx, TM); TextSection = getOrCreateSection("\t.text", true, SectionKind::Text); DataSection = getOrCreateSection("\t.dp.data", false, SectionKind::DataRel); BSSSection_ = getOrCreateSection("\t.dp.bss", false, SectionKind::BSS); // TLS globals are lowered in the backend to arrays indexed by the current // thread id. After lowering they require no special handling by the linker // and can be placed in the standard data / bss sections. TLSDataSection = DataSection; TLSBSSSection = BSSSection_; if (TM.getSubtarget<XCoreSubtarget>().isXS1A()) // FIXME: Why is this writable ("datarel")??? ReadOnlySection = getOrCreateSection("\t.dp.rodata", false, SectionKind::DataRel); else ReadOnlySection = getOrCreateSection("\t.cp.rodata", false, SectionKind::ReadOnly); }
Call the Query Module's init
/* * QueryModule.cc * * Load the query subsystem as a module. * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #include <opencog/query/PatternSCM.h> #include "QueryModule.h" using namespace opencog; DECLARE_MODULE(QueryModule); QueryModule::QueryModule(CogServer& cs) : Module(cs), _pat(NULL) { } QueryModule::~QueryModule() { delete _pat; } void QueryModule::init(void) { _pat = new PatternSCM(); }
/* * QueryModule.cc * * Load the query subsystem as a module. * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #include <opencog/query/PatternSCM.h> #include "QueryModule.h" using namespace opencog; DECLARE_MODULE(QueryModule); QueryModule::QueryModule(CogServer& cs) : Module(cs), _pat(NULL) { } QueryModule::~QueryModule() { delete _pat; } void QueryModule::init(void) { _pat = new PatternSCM(); _pat->module_init(); }
Disable the Bookmarks ExtensionAPITest becuase it is flaky.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Bookmarks) { // TODO(erikkay) no initial state for this test. ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // TODO(brettw) bug 19866: this test is disabled because it is flaky. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Bookmarks) { // TODO(erikkay) no initial state for this test. ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_; }
Disable ExtensionApiTest.Tabs on Mac. TEST=no random redness on Mac OS X 10.6 bot BUG=37387 TBR=skerner@
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // TODO(skerner): This test is flaky in chromeos. Figure out why and fix. #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_Tabs DISABLED_Tabs #else #define MAYBE_Tabs Tabs #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { StartHTTPServer(); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // TODO(skerner): This test is flaky in chromeos and on Mac OS X 10.6. Figure // out why and fix. #if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(OS_MACOSX) #define MAYBE_Tabs DISABLED_Tabs #else #define MAYBE_Tabs Tabs #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { StartHTTPServer(); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; }
Improve validate multiple reads sample
// Validate multiple reads #include <sstream> #include <string> int main() { std::istringstream stream{"John Smith 32"}; std::string first_name; std::string family_name; int age; if (stream >> first_name && stream >> family_name && stream >> age) { // Use values } } // Ensure that multiple stream reads are successful before using the // extracted values. // // We create a [`std::istringstream`](cpp/io/basic_istringstream) as // the example input stream, which contains some values that we wish // to read ([8]). This stream could be replaced by any other // input stream, such as [`std::cin`](cpp/io/cin) or a file stream. // We then create some objects on [10-11] into which we will read // values from the stream. // // In the condition of the `if` statement on [14-16], we perform the // extractions. The `&&` operators ensure that the condition // is `true` only when all extractions succeed. Short-circuiting // also ensures that an extraction is only evaluated if the previous // extractions were successful. // // If you are reading values on multiple lines, consider [reading // from the stream line-by-line](/common-tasks/read-line-by-line.html) // and then parsing each line.
// Validate multiple reads #include <sstream> #include <string> int main() { std::istringstream stream{"Chief Executive Officer\n" "John Smith\n" "32"}; std::string position; std::string first_name; std::string family_name; int age; if (std::getline(stream, position) && stream >> first_name >> family_name >> age) { // Use values } } // Ensure that multiple stream reads are successful before using the // extracted values. // // We create a [`std::istringstream`](cpp/io/basic_istringstream) as // the example input stream, which contains some values that we wish // to read ([8-10]). This stream could be replaced by any other // input stream, such as [`std::cin`](cpp/io/cin) or a file stream. // We then create some objects on [12-15] into which we will read // values from the stream. // // In the condition of the `if` statement on [17-20], we first perform // an unformatted extraction with // [`std::getline`](cpp/string/basic_string/getline) [17] // and then a series of formatted extractions [18]. The `&&` operator // ensures that the condition is `true` only when all extractions // succeed. Short-circuiting also ensures that the second set of // extractions are only attempted if the previous extraction was // successful. // // If you are reading values on multiple lines, consider [reading // from the stream line-by-line](/common-tasks/read-line-by-line.html) // and then parsing each line.
Fix the `accept` prototype in the dataflow taint tests
void sink(...); int source(); // --- accept --- struct sockaddr { unsigned char length; int sa_family; char* sa_data; }; int accept(int, const sockaddr*, int*); void sink(sockaddr); void test_accept() { int s = source(); sockaddr addr; int size = sizeof(sockaddr); int a = accept(s, &addr, &size); sink(a); // $ ast=17:11 ir SPURIOUS: ast=18:12 sink(addr); // $ ast,ir }
void sink(...); int source(); // --- accept --- struct sockaddr { unsigned char length; int sa_family; char* sa_data; }; int accept(int, sockaddr*, int*); void sink(sockaddr); void test_accept() { int s = source(); sockaddr addr; int size = sizeof(sockaddr); int a = accept(s, &addr, &size); sink(a); // $ ast=17:11 ir SPURIOUS: ast=18:12 sink(addr); // $ ast=17:11 ir SPURIOUS: ast=18:12 }
Add true-positive and false-negative warning thresholds to Touche example.
/** @example user_touche.cpp Touche example. See <a href="https://github.com/damellis/ESP/wiki/%5BExample%5D-Touché-swept-frequency-capacitive-sensing">documentation on the wiki</a>. */ #include <ESP.h> BinaryIntArraySerialStream stream(115200, 160); TcpOStream oStream("localhost", 5204); GestureRecognitionPipeline pipeline; void setup() { useStream(stream); useOutputStream(oStream); pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2)); usePipeline(pipeline); useLeaveOneOutScoring(false); }
/** @example user_touche.cpp Touche example. See <a href="https://github.com/damellis/ESP/wiki/%5BExample%5D-Touché-swept-frequency-capacitive-sensing">documentation on the wiki</a>. */ #include <ESP.h> BinaryIntArraySerialStream stream(115200, 160); TcpOStream oStream("localhost", 5204); GestureRecognitionPipeline pipeline; void setup() { useStream(stream); useOutputStream(oStream); pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2)); usePipeline(pipeline); setTruePositiveWarningThreshold(0.90); setFalseNegativeWarningThreshold(0.10); useLeaveOneOutScoring(false); }
Put the symbol requester func into the proper namespace!
// request symbols #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/DynamicExprInfo.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/LookupHelper.h" #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/UserInterface/UserInterface.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" namespace cling { void libcling__symbol_requester() { const char* const argv[] = {"libcling__symbol_requester", 0}; cling::Interpreter I(1, argv); cling::UserInterface U(I); cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call. printValuePublicDefault(llvm::outs(), 0, VPI); cling_PrintValue(0, 0, 0); flushOStream(llvm::outs()); LookupHelper h(0); h.findType(""); h.findScope(""); h.findFunctionProto(0, "", ""); h.findFunctionArgs(0, "", ""); cling::runtime::internal::DynamicExprInfo DEI(0,0,false); DEI.getExpr(); cling::InterpreterCallbacks cb(0); } }
// request symbols #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/DynamicExprInfo.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/LookupHelper.h" #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/UserInterface/UserInterface.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" namespace cling { namespace internal { void libcling__symbol_requester() { const char* const argv[] = {"libcling__symbol_requester", 0}; cling::Interpreter I(1, argv); cling::UserInterface U(I); cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call. printValuePublicDefault(llvm::outs(), 0, VPI); cling_PrintValue(0, 0, 0); flushOStream(llvm::outs()); LookupHelper h(0); h.findType(""); h.findScope(""); h.findFunctionProto(0, "", ""); h.findFunctionArgs(0, "", ""); cling::runtime::internal::DynamicExprInfo DEI(0,0,false); DEI.getExpr(); cling::InterpreterCallbacks cb(0); } } }
Allow both single and double quotes in string literals.
/* Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> */ #include "include.h" #include <QStringList> #include <QtPlugin> #include "parser.h" #include "template.h" #include <QDebug> IncludeNodeFactory::IncludeNodeFactory() { } Node* IncludeNodeFactory::getNode(const QString &tagContent, Parser *p) { QStringList expr = tagContent.split(" ", QString::SkipEmptyParts); QString includeName = expr.at(1); int size = includeName.size(); if (includeName.at(0) == QChar('\"') && includeName.at(size-1) == QChar('\"')) { return new ConstantIncludeNode(includeName.mid(1, size-2)); } return new IncludeNode(includeName); } IncludeNode::IncludeNode(const QString &name) { m_filterExpression = FilterExpression(name); } QString IncludeNode::render(Context *c) { QString filename = m_filterExpression.resolve(c).toString(); TemplateLoader *loader = TemplateLoader::instance(); Template t = loader->loadByName(filename); return t.render(c); } ConstantIncludeNode::ConstantIncludeNode(const QString &name) { m_name = name; } QString ConstantIncludeNode::render(Context *c) { TemplateLoader *loader = TemplateLoader::instance(); Template t = loader->loadByName(m_name); return t.render(c); }
/* Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> */ #include "include.h" #include <QStringList> #include <QtPlugin> #include "parser.h" #include "template.h" #include <QDebug> IncludeNodeFactory::IncludeNodeFactory() { } Node* IncludeNodeFactory::getNode(const QString &tagContent, Parser *p) { QStringList expr = tagContent.split(" ", QString::SkipEmptyParts); QString includeName = expr.at(1); int size = includeName.size(); if ((includeName.startsWith("\"") && includeName.endsWith("\"")) || ( includeName.startsWith("'") && includeName.endsWith("'") )) { return new ConstantIncludeNode(includeName.mid(1, size-2)); } return new IncludeNode(includeName); } IncludeNode::IncludeNode(const QString &name) { m_filterExpression = FilterExpression(name); } QString IncludeNode::render(Context *c) { QString filename = m_filterExpression.resolve(c).toString(); TemplateLoader *loader = TemplateLoader::instance(); Template t = loader->loadByName(filename); return t.render(c); } ConstantIncludeNode::ConstantIncludeNode(const QString &name) { m_name = name; } QString ConstantIncludeNode::render(Context *c) { TemplateLoader *loader = TemplateLoader::instance(); Template t = loader->loadByName(m_name); return t.render(c); }
Use static_assert instead of runtime assert in std::money_base tests.
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <locale> // class money_base // { // public: // enum part {none, space, symbol, sign, value}; // struct pattern {char field[4];}; // }; #include <locale> #include <cassert> int main() { std::money_base mb; assert(mb.none == 0); assert(mb.space == 1); assert(mb.symbol == 2); assert(mb.sign == 3); assert(mb.value == 4); assert(sizeof(std::money_base::pattern) == 4); std::money_base::pattern p; p.field[0] = std::money_base::none; }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <locale> // class money_base // { // public: // enum part {none, space, symbol, sign, value}; // struct pattern {char field[4];}; // }; #include <locale> #include <cassert> int main() { std::money_base mb; ((void)mb); static_assert(std::money_base::none == 0, ""); static_assert(std::money_base::space == 1, ""); static_assert(std::money_base::symbol == 2, ""); static_assert(std::money_base::sign == 3, ""); static_assert(std::money_base::value == 4, ""); static_assert(sizeof(std::money_base::pattern) == 4, ""); std::money_base::pattern p; p.field[0] = std::money_base::none; }
Add memory region to match UVM env
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <svdpi.h> #include <cassert> #include "cosim.h" #include "spike_cosim.h" extern "C" { void *spike_cosim_init(const char *isa_string, svBitVecVal *start_pc, svBitVecVal *start_mtvec, const char *log_file_path_cstr) { assert(isa_string); std::string log_file_path; if (log_file_path_cstr) { log_file_path = log_file_path_cstr; } SpikeCosim *cosim = new SpikeCosim(isa_string, start_pc[0], start_mtvec[0], log_file_path, false, true); cosim->add_memory(0x80000000, 0x80000000); return static_cast<Cosim *>(cosim); } void spike_cosim_release(void *cosim_handle) { auto cosim = static_cast<Cosim *>(cosim_handle); delete cosim; } }
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <svdpi.h> #include <cassert> #include "cosim.h" #include "spike_cosim.h" extern "C" { void *spike_cosim_init(const char *isa_string, svBitVecVal *start_pc, svBitVecVal *start_mtvec, const char *log_file_path_cstr) { assert(isa_string); std::string log_file_path; if (log_file_path_cstr) { log_file_path = log_file_path_cstr; } SpikeCosim *cosim = new SpikeCosim(isa_string, start_pc[0], start_mtvec[0], log_file_path, false, true); cosim->add_memory(0x80000000, 0x80000000); cosim->add_memory(0x00000000, 0x80000000); return static_cast<Cosim *>(cosim); } void spike_cosim_release(void *cosim_handle) { auto cosim = static_cast<Cosim *>(cosim_handle); delete cosim; } }
Debug Info: update testing cases when the context field of subprogram is updated to use DIScopeRef.
// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s template<class X> class B { public: explicit B(X* p = 0); }; class A { public: A(int value) : m_a_value(value) {}; A(int value, A* client_A) : m_a_value (value), m_client_A (client_A) {} virtual ~A() {} private: int m_a_value; B<A> m_client_A; }; int main(int argc, char **argv) { A reallyA (500); } // CHECK: ![[CLASSTYPE:.*]] = {{.*}} ; [ DW_TAG_class_type ] [A] // CHECK: ![[ARTARG:.*]] = {{.*}} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [artificial] [from _ZTS1A] // CHECK: metadata ![[CLASSTYPE]], {{.*}} ; [ DW_TAG_subprogram ] [line 12] [A] // CHECK: metadata [[FUNCTYPE:![0-9]*]], i32 0, null, null, null} ; [ DW_TAG_subroutine_type ] // CHECK: [[FUNCTYPE]] = metadata !{null, metadata ![[ARTARG]], metadata !{{.*}}, metadata !{{.*}}}
// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s template<class X> class B { public: explicit B(X* p = 0); }; class A { public: A(int value) : m_a_value(value) {}; A(int value, A* client_A) : m_a_value (value), m_client_A (client_A) {} virtual ~A() {} private: int m_a_value; B<A> m_client_A; }; int main(int argc, char **argv) { A reallyA (500); } // CHECK: ![[CLASSTYPE:.*]] = {{.*}}, metadata !"_ZTS1A"} ; [ DW_TAG_class_type ] [A] // CHECK: ![[ARTARG:.*]] = {{.*}} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [artificial] [from _ZTS1A] // CHECK: metadata !"_ZTS1A", {{.*}} ; [ DW_TAG_subprogram ] [line 12] [A] // CHECK: metadata [[FUNCTYPE:![0-9]*]], i32 0, null, null, null} ; [ DW_TAG_subroutine_type ] // CHECK: [[FUNCTYPE]] = metadata !{null, metadata ![[ARTARG]], metadata !{{.*}}, metadata !{{.*}}}
Disable ExtensionApiTest.Storage because it crashes the browser_tests too.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // This test is disabled. See bug 25746 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; }
Update node name to cirkit_unit03
/****************************************************** * This is CIR-KIT 3rd robot control driver. * Author : Arita Yuta(Kyutech) ******************************************************/ #include "cirkit_unit03_driver.hpp" int main(int argc, char** argv) { ros::init(argc, argv, "Third_robot_driver_node"); ROS_INFO("Third robot driver for ROS."); ros::NodeHandle nh; cirkit::ThirdRobotDriver driver(nh); driver.run(); return 0; }
/****************************************************** * This is CIR-KIT 3rd robot control driver. * Author : Arita Yuta(Kyutech) ******************************************************/ #include "cirkit_unit03_driver.hpp" int main(int argc, char** argv) { ros::init(argc, argv, "cirkit_unit03_driver_node"); ROS_INFO("cirkit unit03 robot driver for ROS."); ros::NodeHandle nh; cirkit::ThirdRobotDriver driver(nh); driver.run(); return 0; }
Disable this test on Linux, because it will fail as soon as WebKit's version is rolled forward.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << 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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" // Disable this test on Linux, because it fails // http://crbug.com/40976 #if defined(OS_LINUX) #define WebSocket DISABLED_WebSocket #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; }
Remove Ringtone from virtual root
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/experimental/native_file_system/virtual_root_provider.h" #include <tzplatform_config.h> #include <map> #include <string> VirtualRootProvider::VirtualRootProvider() { const char* names[] = { "CAMERA", "DOCUMENTS", "IMAGES", "SOUNDS", "VIDEOS", }; tzplatform_variable dirs[] = { TZ_USER_CAMERA, TZ_USER_DOCUMENTS, TZ_USER_IMAGES, TZ_USER_SOUNDS, TZ_USER_VIDEOS }; for (unsigned int i = 0; i < sizeof(names) / sizeof(names[0]); ++i) { virtual_root_map_[names[i]] = base::FilePath::FromUTF8Unsafe( std::string(tzplatform_getenv(dirs[i]))); } virtual_root_map_["RINGTONES"] = base::FilePath::FromUTF8Unsafe( std::string(tzplatform_mkpath(TZ_USER_SHARE, "settings/Ringtones"))); }
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/experimental/native_file_system/virtual_root_provider.h" #include <tzplatform_config.h> #include <map> #include <string> VirtualRootProvider::VirtualRootProvider() { const char* names[] = { "CAMERA", "DOCUMENTS", "IMAGES", "SOUNDS", "VIDEOS", }; tzplatform_variable dirs[] = { TZ_USER_CAMERA, TZ_USER_DOCUMENTS, TZ_USER_IMAGES, TZ_USER_SOUNDS, TZ_USER_VIDEOS }; for (unsigned int i = 0; i < sizeof(names) / sizeof(names[0]); ++i) { virtual_root_map_[names[i]] = base::FilePath::FromUTF8Unsafe( std::string(tzplatform_getenv(dirs[i]))); } }
Add the argument --portrait to marble-touch to start in portrait mode.
// 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 Daniel Marth <danielmarth@gmx.at> // A QML-interface of Marble for the Meego operating system. #include <QtGui/QApplication> #include <QtDeclarative/QtDeclarative> int main( int argc, char *argv[] ) { QApplication app( argc, argv ); app.setProperty( "NoMStyle", true ); QDir::setCurrent( app.applicationDirPath() ); // Create main window based on QML. QDeclarativeView view; view.setSource( QUrl( "qrc:/main.qml" ) ); #ifdef __arm__ // Window takes up full screen on arm (mobile) devices. view.showFullScreen(); #else view.resize( view.initialSize().width(), view.initialSize().height() ); view.show(); #endif return app.exec(); }
// 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 Daniel Marth <danielmarth@gmx.at> // A QML-interface of Marble for the Meego operating system. #include <QtGui/QApplication> #include <QtDeclarative/QtDeclarative> int main( int argc, char *argv[] ) { QApplication app( argc, argv ); app.setProperty( "NoMStyle", true ); QDir::setCurrent( app.applicationDirPath() ); // Create main window based on QML. QDeclarativeView view; view.setSource( QUrl( "qrc:/main.qml" ) ); #ifdef __arm__ // Window takes up full screen on arm (mobile) devices. view.showFullScreen(); #else if ( app.arguments().contains( "--portrait" ) ) { view.resize( view.initialSize().height(), view.initialSize().width() ); view.setTransform( QTransform().rotate( 90 ) ); } else { view.resize( view.initialSize().width(), view.initialSize().height() ); } view.show(); #endif return app.exec(); }
Disable ExtensionApiTest.WebSocket due to a 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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << 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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" // Disabled, http://crbug.com/38225 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; }
Add a missing writeOption in pacman config
#include "package_manager/packagemanagerconfig.h" #include <boost/log/trivial.hpp> void PackageConfig::updateFromPropertyTree(const boost::property_tree::ptree& pt) { CopyFromConfig(type, "type", pt); CopyFromConfig(os, "os", pt); CopyFromConfig(sysroot, "sysroot", pt); CopyFromConfig(ostree_server, "ostree_server", pt); CopyFromConfig(packages_file, "packages_file", pt); CopyFromConfig(fake_need_reboot, "fake_need_reboot", pt); } void PackageConfig::writeToStream(std::ostream& out_stream) const { writeOption(out_stream, type, "type"); writeOption(out_stream, os, "os"); writeOption(out_stream, sysroot, "sysroot"); writeOption(out_stream, ostree_server, "ostree_server"); writeOption(out_stream, fake_need_reboot, "fake_need_reboot"); } std::ostream& operator<<(std::ostream& os, PackageManager pm) { std::string pm_str; switch (pm) { case PackageManager::kOstree: pm_str = "ostree"; break; case PackageManager::kDebian: pm_str = "debian"; break; case PackageManager::kNone: default: pm_str = "none"; break; } os << '"' << pm_str << '"'; return os; }
#include "package_manager/packagemanagerconfig.h" #include <boost/log/trivial.hpp> void PackageConfig::updateFromPropertyTree(const boost::property_tree::ptree& pt) { CopyFromConfig(type, "type", pt); CopyFromConfig(os, "os", pt); CopyFromConfig(sysroot, "sysroot", pt); CopyFromConfig(ostree_server, "ostree_server", pt); CopyFromConfig(packages_file, "packages_file", pt); CopyFromConfig(fake_need_reboot, "fake_need_reboot", pt); } void PackageConfig::writeToStream(std::ostream& out_stream) const { writeOption(out_stream, type, "type"); writeOption(out_stream, os, "os"); writeOption(out_stream, sysroot, "sysroot"); writeOption(out_stream, ostree_server, "ostree_server"); writeOption(out_stream, packages_file, "packages_file"); writeOption(out_stream, fake_need_reboot, "fake_need_reboot"); } std::ostream& operator<<(std::ostream& os, PackageManager pm) { std::string pm_str; switch (pm) { case PackageManager::kOstree: pm_str = "ostree"; break; case PackageManager::kDebian: pm_str = "debian"; break; case PackageManager::kNone: default: pm_str = "none"; break; } os << '"' << pm_str << '"'; return os; }
Fix getpwnam test on ppc64le Fedora 21.
// Regression test for a crash in getpwnam_r and similar interceptors. // RUN: %clangxx -O0 -g %s -o %t && %run %t #include <assert.h> #include <pwd.h> #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(void) { struct passwd pwd; struct passwd *pwdres; char buf[10000]; int res = getpwnam_r("no-such-user", &pwd, buf, sizeof(buf), &pwdres); assert(res == 0); assert(pwdres == 0); return 0; }
// Regression test for a crash in getpwnam_r and similar interceptors. // RUN: %clangxx -O0 -g %s -o %t && %run %t #include <assert.h> #include <errno.h> #include <pwd.h> #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(void) { struct passwd pwd; struct passwd *pwdres; char buf[10000]; int res = getpwnam_r("no-such-user", &pwd, buf, sizeof(buf), &pwdres); assert(res == 0 || res == ENOENT); assert(pwdres == 0); return 0; }
Use auto and captitalize first word in sentence.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "executor_metrics.h" namespace proton { void ExecutorMetrics::update(const vespalib::ThreadStackExecutorBase::Stats &stats) { maxPending.set(stats.queueSize.max()); accepted.inc(stats.acceptedTasks); rejected.inc(stats.rejectedTasks); const vespalib::ThreadStackExecutorBase::Stats::QueueSizeT & qSize = stats.queueSize; queueSize.addValueBatch(qSize.average(), qSize.count(), qSize.min(), qSize.max()); } ExecutorMetrics::ExecutorMetrics(const std::string &name, metrics::MetricSet *parent) : metrics::MetricSet(name, {}, "Instance specific thread executor metrics", parent), maxPending("maxpending", {}, "Maximum number of pending (active + queued) tasks", this), accepted("accepted", {}, "Number of accepted tasks", this), rejected("rejected", {}, "Number of rejected tasks", this), queueSize("queuesize", {}, "size of task queue", this) { } ExecutorMetrics::~ExecutorMetrics() = default; } // namespace proton
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "executor_metrics.h" namespace proton { void ExecutorMetrics::update(const vespalib::ThreadStackExecutorBase::Stats &stats) { maxPending.set(stats.queueSize.max()); accepted.inc(stats.acceptedTasks); rejected.inc(stats.rejectedTasks); const auto & qSize = stats.queueSize; queueSize.addValueBatch(qSize.average(), qSize.count(), qSize.min(), qSize.max()); } ExecutorMetrics::ExecutorMetrics(const std::string &name, metrics::MetricSet *parent) : metrics::MetricSet(name, {}, "Instance specific thread executor metrics", parent), maxPending("maxpending", {}, "Maximum number of pending (active + queued) tasks", this), accepted("accepted", {}, "Number of accepted tasks", this), rejected("rejected", {}, "Number of rejected tasks", this), queueSize("queuesize", {}, "Size of task queue", this) { } ExecutorMetrics::~ExecutorMetrics() = default; } // namespace proton
Store Engine by value on Windows and keep argv in unique_ptr
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include <cstdlib> #include <shellapi.h> #include "SystemWin.hpp" #include "EngineWin.hpp" #include "../../utils/Log.hpp" int WINAPI WinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ LPSTR, _In_ int) { try { int argc; LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc); auto engine = std::make_unique<ouzel::core::windows::Engine>(argc, argv); if (argv) LocalFree(argv); engine->run(); engine.reset(); // must release engine instance before exit on Windows return EXIT_SUCCESS; } catch (const std::exception& e) { ouzel::logger.log(ouzel::Log::Level::error) << e.what(); return EXIT_FAILURE; } } namespace ouzel::core::windows { }
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include <cstdlib> #include <shellapi.h> #include "SystemWin.hpp" #include "EngineWin.hpp" #include "../../utils/Log.hpp" int WINAPI WinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ LPSTR, _In_ int) { try { int argc; std::unique_ptr<LPWSTR, decltype(&LocalFree)> argv(CommandLineToArgvW(GetCommandLineW(), &argc), LocalFree); ouzel::core::windows::Engine engine(argc, argv.get()); engine.run(); return EXIT_SUCCESS; } catch (const std::exception& e) { ouzel::logger.log(ouzel::Log::Level::error) << e.what(); return EXIT_FAILURE; } } namespace ouzel::core::windows { System::System(int argc, LPWSTR* argv) { } }
Put all frequencies in one definition.
#include "aquila/global.h" #include "aquila/source/generator/SineGenerator.h" #include "aquila/transform/FftFactory.h" #include "aquila/tools/TextPlot.h" int main() { // input signal parameters const std::size_t SIZE = 64; const Aquila::FrequencyType sampleFreq = 2000; const Aquila::FrequencyType f1 = 125, f2 = 700; Aquila::SineGenerator sineGenerator1(sampleFreq); sineGenerator1.setAmplitude(32).setFrequency(f1).generate(SIZE); Aquila::SineGenerator sineGenerator2(sampleFreq); sineGenerator2.setAmplitude(8).setFrequency(f2).setPhase(0.75).generate(SIZE); auto sum = sineGenerator1 + sineGenerator2; Aquila::TextPlot plt("Input signal"); plt.plot(sum); // calculate the FFT auto fft = Aquila::FftFactory::getFft(SIZE); Aquila::SpectrumType spectrum = fft->fft(sum.toArray()); plt.setTitle("Spectrum"); plt.plotSpectrum(spectrum); return 0; }
#include "aquila/global.h" #include "aquila/source/generator/SineGenerator.h" #include "aquila/transform/FftFactory.h" #include "aquila/tools/TextPlot.h" int main() { // input signal parameters const std::size_t SIZE = 64; const Aquila::FrequencyType sampleFreq = 2000, f1 = 125, f2 = 700; Aquila::SineGenerator sineGenerator1(sampleFreq); sineGenerator1.setAmplitude(32).setFrequency(f1).generate(SIZE); Aquila::SineGenerator sineGenerator2(sampleFreq); sineGenerator2.setAmplitude(8).setFrequency(f2).setPhase(0.75).generate(SIZE); auto sum = sineGenerator1 + sineGenerator2; Aquila::TextPlot plt("Input signal"); plt.plot(sum); // calculate the FFT auto fft = Aquila::FftFactory::getFft(SIZE); Aquila::SpectrumType spectrum = fft->fft(sum.toArray()); plt.setTitle("Spectrum"); plt.plotSpectrum(spectrum); return 0; }
Initialize MediaPipelineDevice elements in correct order
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/cma/backend/media_pipeline_device.h" #include "chromecast/media/cma/backend/audio_pipeline_device_default.h" #include "chromecast/media/cma/backend/media_clock_device_default.h" #include "chromecast/media/cma/backend/media_pipeline_device_factory.h" #include "chromecast/media/cma/backend/video_pipeline_device_default.h" namespace chromecast { namespace media { MediaPipelineDevice::MediaPipelineDevice( scoped_ptr<MediaPipelineDeviceFactory> factory) : MediaPipelineDevice(factory->CreateMediaClockDevice(), factory->CreateAudioPipelineDevice(), factory->CreateVideoPipelineDevice()) { } MediaPipelineDevice::MediaPipelineDevice( scoped_ptr<MediaClockDevice> media_clock_device, scoped_ptr<AudioPipelineDevice> audio_pipeline_device, scoped_ptr<VideoPipelineDevice> video_pipeline_device) : media_clock_device_(media_clock_device.Pass()), audio_pipeline_device_(audio_pipeline_device.Pass()), video_pipeline_device_(video_pipeline_device.Pass()) { } MediaPipelineDevice::~MediaPipelineDevice() { } } // namespace media } // namespace chromecast
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/cma/backend/media_pipeline_device.h" #include "chromecast/media/cma/backend/audio_pipeline_device_default.h" #include "chromecast/media/cma/backend/media_clock_device_default.h" #include "chromecast/media/cma/backend/media_pipeline_device_factory.h" #include "chromecast/media/cma/backend/video_pipeline_device_default.h" namespace chromecast { namespace media { MediaPipelineDevice::MediaPipelineDevice( scoped_ptr<MediaPipelineDeviceFactory> factory) : media_clock_device_(factory->CreateMediaClockDevice()), audio_pipeline_device_(factory->CreateAudioPipelineDevice()), video_pipeline_device_(factory->CreateVideoPipelineDevice()) { } MediaPipelineDevice::MediaPipelineDevice( scoped_ptr<MediaClockDevice> media_clock_device, scoped_ptr<AudioPipelineDevice> audio_pipeline_device, scoped_ptr<VideoPipelineDevice> video_pipeline_device) : media_clock_device_(media_clock_device.Pass()), audio_pipeline_device_(audio_pipeline_device.Pass()), video_pipeline_device_(video_pipeline_device.Pass()) { } MediaPipelineDevice::~MediaPipelineDevice() { } } // namespace media } // namespace chromecast
Add commented-out debugging printfs for examining memory layout.
#include "MicroBit.h" extern "C" { void mp_run(void); void microbit_display_event(void); } static void event_listener(MicroBitEvent evt) { if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) { microbit_display_event(); } } void app_main() { uBit.MessageBus.listen(MICROBIT_ID_DISPLAY, MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener); while (1) { mp_run(); } }
#include "MicroBit.h" extern "C" { void mp_run(void); void microbit_display_event(void); } static void event_listener(MicroBitEvent evt) { if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) { microbit_display_event(); } } void app_main() { /* // debugging: print memory layout extern uint32_t __data_start__, __data_end__; extern uint32_t __bss_start__, __bss_end__; extern uint32_t __HeapLimit, __StackLimit, __StackTop; printf("__data_start__ = %p\r\n", &__data_start__); printf("__data_end__ = %p\r\n", &__data_end__); printf("__bss_start_ _ = %p\r\n", &__bss_start__); printf("__bss_end__ = %p\r\n", &__bss_end__); printf("__HeapLimit = %p\r\n", &__HeapLimit); printf("__StackLimit = %p\r\n", &__StackLimit); printf("__StackTop = %p\r\n", &__StackTop); */ uBit.MessageBus.listen(MICROBIT_ID_DISPLAY, MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener); while (1) { mp_run(); } }
Fix variable naming - was method, should be property
// Copyright 2010-2014 The CefSharp Project. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "JavascriptPropertyWrapper.h" #include "JavascriptObjectWrapper.h" #include "CefAppWrapper.h" using namespace System; namespace CefSharp { void JavascriptPropertyWrapper::Bind() { auto methodName = StringUtils::ToNative(_javascriptProperty->JavascriptName); auto clrMethodName = _javascriptProperty->JavascriptName; if (_javascriptProperty->IsComplexType) { auto wrapperObject = gcnew JavascriptObjectWrapper(_javascriptProperty->Value); wrapperObject->V8Value = V8Value.get(); wrapperObject->Bind(); } else { auto propertyAttribute = _javascriptProperty->IsReadOnly ? V8_PROPERTY_ATTRIBUTE_READONLY : V8_PROPERTY_ATTRIBUTE_NONE; V8Value->SetValue(methodName, V8_ACCESS_CONTROL_DEFAULT, propertyAttribute); } }; }
// Copyright 2010-2014 The CefSharp Project. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "JavascriptPropertyWrapper.h" #include "JavascriptObjectWrapper.h" #include "CefAppWrapper.h" using namespace System; namespace CefSharp { void JavascriptPropertyWrapper::Bind() { auto propertyName = StringUtils::ToNative(_javascriptProperty->JavascriptName); auto clrPropertyName = _javascriptProperty->JavascriptName; if (_javascriptProperty->IsComplexType) { auto wrapperObject = gcnew JavascriptObjectWrapper(_javascriptProperty->Value); wrapperObject->V8Value = V8Value.get(); wrapperObject->Bind(); } else { auto propertyAttribute = _javascriptProperty->IsReadOnly ? V8_PROPERTY_ATTRIBUTE_READONLY : V8_PROPERTY_ATTRIBUTE_NONE; V8Value->SetValue(propertyName, V8_ACCESS_CONTROL_DEFAULT, propertyAttribute); } }; }
Update the default location for the data folder for unit_VEHICLE
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Global functions for accessing the model data. // // ============================================================================= #include "chrono_vehicle/ChVehicleModelData.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // Functions for manipulating the ChronoVehicle data directory // ----------------------------------------------------------------------------- static std::string model_data_path("../data/"); // Set the path to the ChronoVehicle model data directory (ATTENTION: not thread safe) void SetDataPath(const std::string& path) { model_data_path = path; } // Obtain the current path to the ChronoVehicle model data directory (thread safe) const std::string& GetDataPath() { return model_data_path; } // Obtain the complete path to the specified filename, given relative to the // ChronoVehicle model data directory (thread safe) std::string GetDataFile(const std::string& filename) { return model_data_path + filename; } } // end namespace vehicle } // end namespace chrono
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Global functions for accessing the model data. // // ============================================================================= #include "chrono_vehicle/ChVehicleModelData.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // Functions for manipulating the ChronoVehicle data directory // ----------------------------------------------------------------------------- static std::string model_data_path("../data/vehicle/"); // Set the path to the ChronoVehicle model data directory (ATTENTION: not thread safe) void SetDataPath(const std::string& path) { model_data_path = path; } // Obtain the current path to the ChronoVehicle model data directory (thread safe) const std::string& GetDataPath() { return model_data_path; } // Obtain the complete path to the specified filename, given relative to the // ChronoVehicle model data directory (thread safe) std::string GetDataFile(const std::string& filename) { return model_data_path + filename; } } // end namespace vehicle } // end namespace chrono
Load images with SDL_image and make transparancy work
#include "SDL.h" #include "resources/imageresource.h" namespace Zabbr { /** * Constructor. * * @param name The name of the image. * @param surface The surface of the image. */ ImageResource::ImageResource(std::string name, SDL_Surface* surface) : SDLSurfaceResource(name, surface) { } /** * Destructor. */ ImageResource::~ImageResource() { } /** * Opens an image. * * @param name the filename of the image. * * @throw ResourceNotLoadedException. */ ImageResource* ImageResource::open(std::string name) { SDL_Surface* temp; SDL_Surface* image; temp = SDL_LoadBMP(("../data/"+name).c_str()); if (temp == NULL) { throw ResourceNotLoadedException(name, SDL_GetError()); } image = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); return new ImageResource(name, image); } }
#include "SDL.h" #include "SDL_image.h" #include "resources/imageresource.h" namespace Zabbr { /** * Constructor. * * @param name The name of the image. * @param surface The surface of the image. */ ImageResource::ImageResource(std::string name, SDL_Surface* surface) : SDLSurfaceResource(name, surface) { } /** * Destructor. */ ImageResource::~ImageResource() { } /** * Opens an image. * * @param name the filename of the image. * * @throw ResourceNotLoadedException. */ ImageResource* ImageResource::open(std::string name) { SDL_Surface* temp; SDL_Surface* image; temp = IMG_Load(("../data/"+name).c_str()); if (temp == NULL) { throw ResourceNotLoadedException(name, IMG_GetError()); } image = SDL_DisplayFormatAlpha(temp); SDL_FreeSurface(temp); return new ImageResource(name, image); } }
Implement strdup's statistics by strlen()
#include "../test.h" #include <cstdlib> class StrdupTest : public TestBase { public: StrdupTest() : TestBase("strdup") { } virtual void* Parse(const char* json) const { return strdup(json); } virtual char* Stringify(void* userdata) const { return strdup((char*)userdata); } virtual char* Prettify(void* userdata) const { return strdup((char*)userdata); } virtual void Free(void* userdata) const { free(userdata); } }; REGISTER_TEST(StrdupTest);
#include "../test.h" #include <cstdlib> class StrdupTest : public TestBase { public: StrdupTest() : TestBase("strdup") { } virtual void* Parse(const char* json) const { return strdup(json); } virtual char* Stringify(void* userdata) const { return strdup((char*)userdata); } virtual char* Prettify(void* userdata) const { return strdup((char*)userdata); } virtual Stat Statistics(void* userdata) const { Stat s; memset(&s, 0, sizeof(s)); s.stringCount = 1; s.stringLength = strlen((char*)userdata); return s; } virtual void Free(void* userdata) const { free(userdata); } }; REGISTER_TEST(StrdupTest);
Fix the broken opencl error test
#ifdef STAN_OPENCL #include <stan/math/prim/mat.hpp> #include <stan/math/prim/arr.hpp> #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrows) { const char* function = "test_func"; const char* msg = "test"; EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error); } #else #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrowsDummy) { EXPECT_NO_THROW(); } #endif
#ifdef STAN_OPENCL #include <stan/math/prim/mat.hpp> #include <stan/math/prim/arr.hpp> #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrows) { const char* function = "test_func"; cl::Error e(-5, "CL_OUT_OF_RESOURCES"); EXPECT_THROW(stan::math::check_ocl_error(function, e), std::system_error); } #else #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrowsDummy) { EXPECT_NO_THROW(); } #endif
Add missing include in test.
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <ios> // template <class charT, class traits> class basic_ios // operator unspecified-bool-type() const; #include <ios> #include <type_traits> #include <cassert> int main() { std::ios ios(0); assert(static_cast<bool>(ios) == !ios.fail()); ios.setstate(std::ios::failbit); assert(static_cast<bool>(ios) == !ios.fail()); static_assert((!std::is_convertible<std::ios, void*>::value), ""); static_assert((!std::is_convertible<std::ios, int>::value), ""); static_assert((!std::is_convertible<std::ios const&, int>::value), ""); #if TEST_STD_VER >= 11 static_assert((!std::is_convertible<std::ios, bool>::value), ""); #endif }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <ios> // template <class charT, class traits> class basic_ios // operator unspecified-bool-type() const; #include <ios> #include <type_traits> #include <cassert> #include "test_macros.h" int main() { std::ios ios(0); assert(static_cast<bool>(ios) == !ios.fail()); ios.setstate(std::ios::failbit); assert(static_cast<bool>(ios) == !ios.fail()); static_assert((!std::is_convertible<std::ios, void*>::value), ""); static_assert((!std::is_convertible<std::ios, int>::value), ""); static_assert((!std::is_convertible<std::ios const&, int>::value), ""); #if TEST_STD_VER >= 11 static_assert((!std::is_convertible<std::ios, bool>::value), ""); #endif }
Fix iter variable not used problem; Adding framweork for multiuthreaded test of VarLenPool
/* * var_len_pool_test.cpp - Test suite for varrable lengthed allocation pool */ #include "test_suite.h" #include "../src/VarLenPool.h" /* * VarLenPoolBasicTest() - This function allocates a series of memory * using an increasing sequence and then check * for correctness */ void VarLenPoolBasicTest() { PrintTestName("VarLenPoolBasicTest"); static const int iter = 10; void *p_list[iter]; // Chunk size = 64 VarLenPool vlp{64}; for(int i = 1;i <= 10;i++) { p_list[i - 1] = vlp.Allocate(i); memset(p_list[i - 1], i, i); dbg_printf("Allocating mem of size = %d\n", i); } // Verify for correctness for(int i = 1;i <= 10;i++) { char *p = reinterpret_cast<char *>(p_list[i - 1]); for(int j = 0;j < i;j++) { assert(p[j] == static_cast<char>(i)); } dbg_printf("Checking content of size = %d\n", i); } return; } int main() { VarLenPoolBasicTest(); return 0; }
/* * var_len_pool_test.cpp - Test suite for varrable lengthed allocation pool */ #include "test_suite.h" #include "../src/VarLenPool.h" /* * VarLenPoolBasicTest() - This function allocates a series of memory * using an increasing sequence and then check * for correctness */ void VarLenPoolBasicTest() { PrintTestName("VarLenPoolBasicTest"); static const int iter = 10; void *p_list[iter]; // Chunk size = 64 VarLenPool vlp{64}; for(int i = 1;i <= iter;i++) { p_list[i - 1] = vlp.Allocate(i); memset(p_list[i - 1], i, i); dbg_printf("Allocating mem of size = %d\n", i); } // Verify for correctness for(int i = 1;i <= iter;i++) { char *p = reinterpret_cast<char *>(p_list[i - 1]); for(int j = 0;j < i;j++) { assert(p[j] == static_cast<char>(i)); } dbg_printf("Checking content of size = %d\n", i); } return; } /* * VarLenPoolThreadTest() - Multithreaded test of VarLenPool */ void VarLenPoolThreadTest(int thread_num, int iter) { } int main() { VarLenPoolBasicTest(); return 0; }
Use standard time() call for Time.now()
/** TimeType.cpp Auto-generated code - do not modify. thinglang C++ transpiler, 0.0.0 **/ #include "../InternalTypes.h" #include "../../execution/Program.h" /** Methods of TimeType **/ void TimeType::__constructor__() { Program::push(Program::create<TimeInstance>()); } void TimeType::now() { Program::push(Program::create<NumberInstance>(std::chrono::system_clock::now().time_since_epoch().count())); }
/** TimeType.cpp Auto-generated code - do not modify. thinglang C++ transpiler, 0.0.0 **/ #include "../InternalTypes.h" #include "../../execution/Program.h" /** Methods of TimeType **/ void TimeType::__constructor__() { Program::push(Program::create<TimeInstance>()); } void TimeType::now() { Program::push(Program::create<NumberInstance>(time(nullptr))); }
Remove xfail tag for darwin from quick_exit test
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // XFAIL: apple-darwin // test quick_exit and at_quick_exit #include <cstdlib> void f() {} int main() { #ifdef _LIBCPP_HAS_QUICK_EXIT std::at_quick_exit(f); std::quick_exit(0); #endif }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // test quick_exit and at_quick_exit #include <cstdlib> void f() {} int main() { #ifdef _LIBCPP_HAS_QUICK_EXIT std::at_quick_exit(f); std::quick_exit(0); #endif }
Fix a typo that broke the posix build.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread_local.h" #include <pthread.h> #include "base/logging.h" namespace base { // static void ThreadLocalPlatform::AllocateSlot(SlotType& slot) { int error = pthread_key_create(&slot, NULL); CHECK(error == 0); } // static void ThreadLocalPlatform::FreeSlot(SlotType& slot) { int error = pthread_key_delete(slot); DCHECK(error == 0); } // static void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) { return pthread_getspecific(slot_); } // static void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) { int error = pthread_setspecific(slot, value); CHECK(error == 0); } } // namespace base
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread_local.h" #include <pthread.h> #include "base/logging.h" namespace base { // static void ThreadLocalPlatform::AllocateSlot(SlotType& slot) { int error = pthread_key_create(&slot, NULL); CHECK(error == 0); } // static void ThreadLocalPlatform::FreeSlot(SlotType& slot) { int error = pthread_key_delete(slot); DCHECK(error == 0); } // static void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) { return pthread_getspecific(slot); } // static void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) { int error = pthread_setspecific(slot, value); CHECK(error == 0); } } // namespace base
Convert sandbox NOTIMPLEMENTED()s into a bug.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { NOTIMPLEMENTED(); return true; } bool RendererMainPlatformDelegate::EnableSandbox() { NOTIMPLEMENTED(); return true; } void RendererMainPlatformDelegate::RunSandboxTests() { NOTIMPLEMENTED(); }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 }
Fix a bug receiving unknown character
#include <iostream> #include <time.h> #include <cassert> #include "SerialPortReceiverThread.h" SerialPortReceiverThread::SerialPortReceiverThread( SerialPort& serialPort, ON_BYTE_RECEIVED onByteReceived) : serialPort(serialPort), onByteReceived(onByteReceived) { } bool SerialPortReceiverThread::run() { uint8_t data; if (serialPort.IsOpen()) { if (serialPort.Read(&data, 0, 1)) { this->onByteReceived(data); } else { Sleep(10); } } return true; }
#include <iostream> #include <time.h> #include <cassert> #include "SerialPortReceiverThread.h" SerialPortReceiverThread::SerialPortReceiverThread( SerialPort& serialPort, ON_BYTE_RECEIVED onByteReceived) : serialPort(serialPort), onByteReceived(onByteReceived) { } bool SerialPortReceiverThread::run() { uint8_t data; if (serialPort.IsOpen()) { if (serialPort.Read(&data, 0, 1) == 1) { this->onByteReceived(data); } else { Sleep(10); } } return true; }
Use the non-touch popup frame instead of NULL.
// 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/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { if (browser_view->IsBrowserTypePopup() || browser_view->IsBrowserTypePanel()) { // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return NULL; } else { return new TouchBrowserFrameView(frame, browser_view); } } } // browser
// 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/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { if (browser_view->IsBrowserTypePopup() || browser_view->IsBrowserTypePanel()) { // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return new PopupNonClientFrameView(frame); } else { return new TouchBrowserFrameView(frame, browser_view); } } } // browser
Use a full if/else block around an exception throw
#include "OptionsFilename.h" #include <stdexcept> namespace { std::string filename; bool filenameSet = false; } const std::string& getOptionsFilename() { return filename; } void setOptionsFilename(const std::string & optionsFilename) { if (filenameSet) throw std::runtime_error("Options filename already set"); filename = optionsFilename; filenameSet = true; }
#include "OptionsFilename.h" #include <stdexcept> namespace { std::string filename; bool filenameSet = false; } const std::string& getOptionsFilename() { return filename; } void setOptionsFilename(const std::string & optionsFilename) { if (filenameSet) { throw std::runtime_error("Options filename already set"); } else { filename = optionsFilename; filenameSet = true; } }
Revert r363298 "[lit] Disable test on darwin when building shared libs."
// Clang on MacOS can find libc++ living beside the installed compiler. // This test makes sure our libTooling-based tools emulate this properly with // fixed compilation database. // // RUN: rm -rf %t // RUN: mkdir %t // // Install the mock libc++ (simulates the libc++ directory structure). // RUN: cp -r %S/Inputs/mock-libcxx %t/ // // RUN: cp clang-check %t/mock-libcxx/bin/ // RUN: cp %s %t/test.cpp // RUN: "%t/mock-libcxx/bin/clang-check" -p %t %t/test.cpp -- \ // RUN: -stdlib=libc++ -target x86_64-apple-darwin \ // RUN: -ccc-install-dir %t/mock-libcxx/bin // // ^ -ccc-install-dir passed to unbreak tests on *BSD where // getMainExecutable() relies on real argv[0] being passed // // UNSUPPORTED: enable_shared #include <mock_vector> vector v;
// Clang on MacOS can find libc++ living beside the installed compiler. // This test makes sure our libTooling-based tools emulate this properly with // fixed compilation database. // // RUN: rm -rf %t // RUN: mkdir %t // // Install the mock libc++ (simulates the libc++ directory structure). // RUN: cp -r %S/Inputs/mock-libcxx %t/ // // RUN: cp clang-check %t/mock-libcxx/bin/ // RUN: cp %s %t/test.cpp // RUN: "%t/mock-libcxx/bin/clang-check" -p %t %t/test.cpp -- \ // RUN: -stdlib=libc++ -target x86_64-apple-darwin \ // RUN: -ccc-install-dir %t/mock-libcxx/bin // // ^ -ccc-install-dir passed to unbreak tests on *BSD where // getMainExecutable() relies on real argv[0] being passed #include <mock_vector> vector v;
Use command line args for client endpoint
#include "Kontroller/Client.h" int main(int argc, char* argv[]) { Kontroller::Client client; client.setButtonCallback([](Kontroller::Button button, bool pressed) { printf("%s %s\n", Kontroller::getName(button), pressed ? "pressed" : "released"); }); client.setDialCallback([](Kontroller::Dial dial, float value) { printf("%s dial value: %f\n", Kontroller::getName(dial), value); }); client.setSliderCallback([](Kontroller::Slider slider, float value) { printf("%s slider value: %f\n", Kontroller::getName(slider), value); }); while (!client.getState().stop) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return 0; }
#include "Kontroller/Client.h" int main(int argc, char* argv[]) { const char* endpoint = argc > 1 ? argv[1] : "127.0.0.1"; Kontroller::Client client(endpoint); client.setButtonCallback([](Kontroller::Button button, bool pressed) { printf("%s %s\n", Kontroller::getName(button), pressed ? "pressed" : "released"); }); client.setDialCallback([](Kontroller::Dial dial, float value) { printf("%s dial value: %f\n", Kontroller::getName(dial), value); }); client.setSliderCallback([](Kontroller::Slider slider, float value) { printf("%s slider value: %f\n", Kontroller::getName(slider), value); }); while (!client.getState().stop) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return 0; }
Fix warning in lazy susan example
#include <iostream> #include <wcl/tracking/LazySusan.h> using namespace std; using namespace wcl; int main(int argc, char* argv[]) { if (argc != 2) { cout << "Usage: lazy_susan [device]" << endl; return 1; } cout << "Connecting to Lazy Susan... "; LazySusan* ls = new LazySusan(argv[1]); TrackedObject* to = ls->getObject("blah"); cout << "Done!" << endl; while (true) { ls->update(); //cout << to->getOrientation().toString() << endl; usleep(30000); } return 0; }
#include <iostream> #include <wcl/tracking/LazySusan.h> using namespace std; using namespace wcl; int main(int argc, char* argv[]) { if (argc != 2) { cout << "Usage: lazy_susan [device]" << endl; return 1; } cout << "Connecting to Lazy Susan... "; LazySusan* ls = new LazySusan(argv[1]); TrackedObject* to = ls->getObject("blah"); cout << to->getOrientation().toString() << endl; cout << "Done!" << endl; while (true) { ls->update(); //cout << to->getOrientation().toString() << endl; usleep(30000); } return 0; }
Change default logging level to debug (was previously set in himan.cpp)
/* * logger.cpp * */ #include "logger.h" namespace himan { HPDebugState logger::MainDebugState = himan::kInfoMsg; logger::logger() : itsDebugState(kInfoMsg), itsUserName("HimanDefaultLogger") { } logger::logger(const std::string& theUserName) : itsDebugState(MainDebugState), itsUserName(theUserName) { } logger::logger(const std::string& theUserName, HPDebugState theDebugState) : itsDebugState(theDebugState), itsUserName(theUserName) { } } // namespace himan
/* * logger.cpp * */ #include "logger.h" namespace himan { HPDebugState logger::MainDebugState = himan::kDebugMsg; logger::logger() : itsDebugState(kInfoMsg), itsUserName("HimanDefaultLogger") { } logger::logger(const std::string& theUserName) : itsDebugState(MainDebugState), itsUserName(theUserName) { } logger::logger(const std::string& theUserName, HPDebugState theDebugState) : itsDebugState(theDebugState), itsUserName(theUserName) { } } // namespace himan
Make sure all code paths return a value
#include "UpdaterWindow.h" #include "../3RVX/3RVX.h" #include "../3RVX/Logger.h" #include "../3RVX/CommCtl.h" #include "../3RVX/NotifyIcon.h" #include "resource.h" UpdaterWindow::UpdaterWindow() : Window(L"3RVX-UpdateWindow") { HRESULT hr = LoadIconMetric( Window::InstanceHandle(), MAKEINTRESOURCE(IDI_MAINICON), LIM_SMALL, &_icon); } LRESULT UpdaterWindow::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == _3RVX::WM_3RVX_SETTINGSCTRL) { switch (wParam) { case _3RVX::MSG_UPDATEICON: CLOG(L"Received request to activate window from external program"); new NotifyIcon(Window::Handle(), L"Update Available", _icon); break; } return Window::WndProc(hWnd, message, wParam, lParam); } }
#include "UpdaterWindow.h" #include "../3RVX/3RVX.h" #include "../3RVX/Logger.h" #include "../3RVX/CommCtl.h" #include "../3RVX/NotifyIcon.h" #include "resource.h" UpdaterWindow::UpdaterWindow() : Window(L"3RVX-UpdateWindow") { HRESULT hr = LoadIconMetric( Window::InstanceHandle(), MAKEINTRESOURCE(IDI_MAINICON), LIM_SMALL, &_icon); } LRESULT UpdaterWindow::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == _3RVX::WM_3RVX_SETTINGSCTRL) { switch (wParam) { case _3RVX::MSG_UPDATEICON: CLOG(L"Received request to activate window from external program"); new NotifyIcon(Window::Handle(), L"Update Available", _icon); break; } } return Window::WndProc(hWnd, message, wParam, lParam); }
Disable this test temporarily in an attempt to green the buildbots.
// RUN: %clang_cc1 -emit-pch -o %t.1.ast %S/Inputs/class1.cpp // RUN: %clang_cc1 -emit-pch -o %t.2.ast %S/Inputs/class2.cpp // RUN: %clang_cc1 -ast-merge %t.1.ast -ast-merge %t.2.ast -fsyntax-only %s 2>&1 | FileCheck %s // CHECK: class1.cpp:5:8: warning: type 'B' has incompatible definitions in different translation units // CHECK: class1.cpp:6:9: note: field 'y' has type 'float' here // CHECK: class2.cpp:6:7: note: field 'y' has type 'int' here // FIXME: we should also complain about mismatched types on the method
// XRUN: %clang_cc1 -emit-pch -o %t.1.ast %S/Inputs/class1.cpp // XRUN: %clang_cc1 -emit-pch -o %t.2.ast %S/Inputs/class2.cpp // XRUN: %clang_cc1 -ast-merge %t.1.ast -ast-merge %t.2.ast -fsyntax-only %s 2>&1 | FileCheck %s // CHECK: class1.cpp:5:8: warning: type 'B' has incompatible definitions in different translation units // CHECK: class1.cpp:6:9: note: field 'y' has type 'float' here // CHECK: class2.cpp:6:7: note: field 'y' has type 'int' here // FIXME: we should also complain about mismatched types on the method
Test is running, but the test sucks
/* * test_setupTunnel.cpp * * Created on: 24 sep. 2015 * Author: Jesper */ #ifdef _MOCK_ #include "gtest/gtest.h" #include "../src/setupTunnel.h" class test_setupTunnel : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() {} }; #endif
/* * test_setupTunnel.cpp * * Created on: 24 sep. 2015 * Author: Jesper */ #ifdef _MOCK_ #include "gtest/gtest.h" #include "../src/setupTunnel.h" class test_setupTunnel : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() {} }; TEST(test_setupTunnel, handleSetupTunnel) { setupTunnel st; StaticJsonBuffer<1000> buffer; JsonObject &reply = buffer.createObject(); StaticJsonBuffer<200> jsonBuffer; char json[] = "{\"sensor\":\"gps\",\"msg_uuid\":1351824120,\"data\":[48.756080,2.302038]}"; JsonObject &root = jsonBuffer.parseObject(json); EXPECT_EQ(1, st.handleSetupTunnel(root ,reply)); } #endif
Add display of program link output in event of linker stage failure
#include "CShader.h" CShader * CompileVertFragShader(string const VertexShaderSource, string const FragmentShaderSource) { ion::GL::VertexShader * VertexShader = new ion::GL::VertexShader; VertexShader->Source(VertexShaderSource); if (! VertexShader->Compile()) std::cerr << "Failed to compile vertex shader!" << std::endl << VertexShader->InfoLog() << std::endl; ion::GL::FragmentShader * FragmentShader = new ion::GL::FragmentShader; FragmentShader->Source(FragmentShaderSource); if (! FragmentShader->Compile()) std::cerr << "Failed to compile fragment shader!" << std::endl << FragmentShader->InfoLog() << std::endl; ion::GL::Program * Program = new ion::GL::Program; Program->AttachShader(VertexShader); Program->AttachShader(FragmentShader); Program->Link(); Program->InfoLog(); return Program; }
#include "CShader.h" CShader * CompileVertFragShader(string const VertexShaderSource, string const FragmentShaderSource) { ion::GL::VertexShader * VertexShader = new ion::GL::VertexShader; VertexShader->Source(VertexShaderSource); if (! VertexShader->Compile()) std::cerr << "Failed to compile vertex shader!" << std::endl << VertexShader->InfoLog() << std::endl; ion::GL::FragmentShader * FragmentShader = new ion::GL::FragmentShader; FragmentShader->Source(FragmentShaderSource); if (! FragmentShader->Compile()) std::cerr << "Failed to compile fragment shader!" << std::endl << FragmentShader->InfoLog() << std::endl; ion::GL::Program * Program = new ion::GL::Program; Program->AttachShader(VertexShader); Program->AttachShader(FragmentShader); if (! Program->Link()) std::cerr << "Failed to link vertex/fragment program!" << std::endl << Program->InfoLog() << std::endl; return Program; }
Modify memory tests to be more robust on different systems
#include <boost/test/unit_test.hpp> #include "Werk/OS/Hardware.hpp" BOOST_AUTO_TEST_SUITE(HardwareTest) BOOST_AUTO_TEST_CASE(TestGetPageSize) { uint64_t pageSize = werk::getPageSize(); //Anything less than 4K won't be adequate anyway BOOST_REQUIRE(pageSize >= 4 * 1024); //And memory should come in at least 1K chunks BOOST_CHECK_EQUAL(pageSize % 1024, 0); } BOOST_AUTO_TEST_CASE(TestGetPhysicalMemorySize) { size_t memorySize = werk::getPhysicalMemorySize(); //Anything less than 64M won't be adequate anyway BOOST_REQUIRE(memorySize >= 64 * 1024 * 1024); //And memory should come in at least 1M chunks BOOST_CHECK_EQUAL(memorySize % (1024 * 1024), 0); } BOOST_AUTO_TEST_CASE(TestGetProcessorCount) { size_t processorCount = werk::getProcessorCount(); BOOST_REQUIRE(processorCount >= 1); } BOOST_AUTO_TEST_SUITE_END()
#include <boost/test/unit_test.hpp> #include "Werk/OS/Hardware.hpp" BOOST_AUTO_TEST_SUITE(HardwareTest) BOOST_AUTO_TEST_CASE(TestGetPageSize) { uint64_t pageSize = werk::getPageSize(); //Anything less than 4K won't be adequate anyway BOOST_REQUIRE(pageSize >= 4 * 1024); //And pages should come in at least 1K chunks BOOST_CHECK_EQUAL(pageSize % 1024, 0); } BOOST_AUTO_TEST_CASE(TestGetPhysicalMemorySize) { size_t memorySize = werk::getPhysicalMemorySize(); //Anything less than 64M won't be adequate anyway BOOST_REQUIRE(memorySize >= 64 * 1024 * 1024); //And memory should come in at least 1K chunks BOOST_CHECK_EQUAL(memorySize % 1024, 0); } BOOST_AUTO_TEST_CASE(TestGetProcessorCount) { size_t processorCount = werk::getProcessorCount(); BOOST_REQUIRE(processorCount >= 1); } BOOST_AUTO_TEST_SUITE_END()
Deal with the situation when the second integer is 0 using run_time exception covered in this chapter.
#include <iostream> using namespace std; int main(void) { int a, b; cin >> a >> b; cout << static_cast<double>(a) / b << endl; return 0; }
#include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int main () { int a=0, b=0; cout<<"Please input two integers: "; while (cin>>a>>b) { try{ if (b==0) { throw std::runtime_error("One of the two integers is 0.");} cout<<static_cast <double>(a)/b<<endl; } catch (std::runtime_error err) {cout<<err.what(); cout<<"\nDo you want to try it again? Yes or No\n"; string a={}; cin>>a; if (a.empty()||a[0]=='N') { break; } } } return 0; }
Change default txn manager to occ
//===----------------------------------------------------------------------===// // // Peloton // // transaction_manager_factory.h // // Identification: src/backend/concurrency/transaction_manager_factory.h // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "transaction_manager_factory.h" namespace peloton { namespace concurrency { ConcurrencyType TransactionManagerFactory::protocol_ = CONCURRENCY_TYPE_PESSIMISTIC; IsolationLevelType TransactionManagerFactory::isolation_level_ = ISOLATION_LEVEL_TYPE_FULL; } }
//===----------------------------------------------------------------------===// // // Peloton // // transaction_manager_factory.h // // Identification: src/backend/concurrency/transaction_manager_factory.h // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "transaction_manager_factory.h" namespace peloton { namespace concurrency { ConcurrencyType TransactionManagerFactory::protocol_ = CONCURRENCY_TYPE_OPTIMISTIC; IsolationLevelType TransactionManagerFactory::isolation_level_ = ISOLATION_LEVEL_TYPE_FULL; } }
Fix state not getting set for button.
#include "ButtonPress.h" #include <assert.h> ButtonPress::ButtonPress(int pinNum, void(*callback)(void)) : m_pinNum(pinNum), m_callback(callback) { assert(m_callback != NULL); pinMode(m_pinNum, INPUT_PULLUP); // Assume pin state at init is the "unpressed" state m_unpressedPinState = digitalRead(m_pinNum); m_lastPinState = m_unpressedPinState; } void ButtonPress::Update() { bool currentPinState = digitalRead(m_pinNum); if (currentPinState != m_lastPinState) { if (currentPinState != m_unpressedPinState) { m_callback(); } } }
#include "ButtonPress.h" #include <assert.h> ButtonPress::ButtonPress(int pinNum, void(*callback)(void)) : m_pinNum(pinNum), m_callback(callback) { assert(m_callback != NULL); pinMode(m_pinNum, INPUT_PULLUP); // Assume pin state at init is the "unpressed" state m_unpressedPinState = digitalRead(m_pinNum); m_lastPinState = m_unpressedPinState; } void ButtonPress::Update() { bool currentPinState = digitalRead(m_pinNum); if (currentPinState != m_lastPinState) { m_lastPinState = currentPinState; if (currentPinState != m_unpressedPinState) { m_callback(); } } }
Remove heave force, not used for test rov
#include "open_loop.h" OpenLoop::OpenLoop() { joySub = n.subscribe("joystick", 1, &OpenLoop::joyCallback, this); tauPub = n.advertise<geometry_msgs::Wrench>("control_forces", 1); } void OpenLoop::joyCallback(const joystick::Joystick &joy_msg) { geometry_msgs::Wrench tau; tau.force.x = joy_msg.strafe_X * NORMALIZATION * SCALING_LIN; tau.force.y = joy_msg.strafe_Y * NORMALIZATION * SCALING_LIN; tau.force.z = joy_msg.ascend * NORMALIZATION * SCALING_LIN; tau.torque.x = 0; tau.torque.y = joy_msg.turn_X * NORMALIZATION * SCALING_ANG; tau.torque.z = joy_msg.turn_Y * NORMALIZATION * SCALING_ANG; tauPub.publish(tau); } int main(int argc, char **argv) { ros::init(argc, argv, "openloop"); ROS_INFO("Launching node open_loop."); OpenLoop openLoop; ros::spin(); return 0; }
#include "open_loop.h" OpenLoop::OpenLoop() { joySub = n.subscribe("joystick", 1, &OpenLoop::joyCallback, this); tauPub = n.advertise<geometry_msgs::Wrench>("control_forces", 1); } void OpenLoop::joyCallback(const joystick::Joystick &joy_msg) { geometry_msgs::Wrench tau; tau.force.x = joy_msg.strafe_X * NORMALIZATION * SCALING_LIN; tau.force.y = joy_msg.strafe_Y * NORMALIZATION * SCALING_LIN; tau.force.z = 0; tau.torque.x = 0; tau.torque.y = joy_msg.turn_X * NORMALIZATION * SCALING_ANG; tau.torque.z = joy_msg.turn_Y * NORMALIZATION * SCALING_ANG; tauPub.publish(tau); } int main(int argc, char **argv) { ros::init(argc, argv, "openloop"); ROS_INFO("Launching node open_loop."); OpenLoop openLoop; ros::spin(); return 0; }
Clean up unused param warning
#include "textures/constant_texture.h" ConstantTexture::ConstantTexture(const Colorf &color) : color(color){} Colorf ConstantTexture::sample(const DifferentialGeometry &) const { return color; } Colorf ConstantTexture::sample(const TextureSample &sample) const { return color; }
#include "textures/constant_texture.h" ConstantTexture::ConstantTexture(const Colorf &color) : color(color){} Colorf ConstantTexture::sample(const DifferentialGeometry&) const { return color; } Colorf ConstantTexture::sample(const TextureSample&) const { return color; }
Refactor changing number to led states
#include "LedController.hpp" #include <algorithm> #include <bitset> LedController::LedController(std::ostream& stream) : out{stream} { } void LedController::runProgram(const Instructions& instructions) { for (const auto& instruction : instructions) { runInstruction(instruction); } } void LedController::runInstruction(const Instruction& instruction) { switch (instruction.type) { case InstructionType::OutA: out << ledState; break; case InstructionType::LdA: ledState = getLedStateFromInteger(instruction.value); break; } } std::string LedController::getLedStateFromInteger(unsigned value) { const std::bitset<8> bitValue{value}; std::stringstream stream; stream << bitValue; auto text = stream.str(); std::transform(text.cbegin(), text.cend(), text.begin(), [](const auto character) { if (character == '1') { constexpr auto ledOnChar = '*'; return ledOnChar; } else { constexpr auto ledOffChar = '.'; return ledOffChar; } }); return text + '\n'; }
#include "LedController.hpp" #include <algorithm> #include <bitset> LedController::LedController(std::ostream& stream) : out{stream} { } void LedController::runProgram(const Instructions& instructions) { for (const auto& instruction : instructions) { runInstruction(instruction); } } void LedController::runInstruction(const Instruction& instruction) { switch (instruction.type) { case InstructionType::OutA: out << ledState; break; case InstructionType::LdA: ledState = getLedStateFromInteger(instruction.value); break; } } std::string LedController::getLedStateFromInteger(unsigned value) { const std::bitset<8> bitValue{value}; constexpr auto ledOnChar = '*'; constexpr auto ledOffChar = '.'; constexpr auto lineEnding = '\n'; return bitValue.to_string(ledOffChar, ledOnChar) + lineEnding; }
Update Problem 7 test case
#include "catch.hpp" #include "ReverseInteger.hpp" TEST_CASE("Reverse Integer") { Solution s; SECTION("Sample test") { REQUIRE(s.reverse(123) == 321); REQUIRE(s.reverse(-123) == -321); } }
#include "catch.hpp" #include "ReverseInteger.hpp" TEST_CASE("Reverse Integer") { Solution s; SECTION("Sample test") { REQUIRE(s.reverse(123) == 321); REQUIRE(s.reverse(-123) == -321); } SECTION("Overflow test") { REQUIRE(s.reverse(-2147483648) == 0); REQUIRE(s.reverse(2147483647) == 0); } SECTION("Leading zeros test") { REQUIRE(s.reverse(1234000) == 4321); REQUIRE(s.reverse(-1234000) == -4321); } }
Fix GCC pragmas. Thanks @simonlindholm
#pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization ("unroll-loops") #include <bits/stdc++.h> using namespace std; #define rep(i,a,b) for (__typeof(a) i=(a); i<(b); ++i) #define iter(it,c) for (__typeof((c).begin()) \ it = (c).begin(); it != (c).end(); ++it) typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef long long ll; const int INF = ~(1<<31); const double EPS = 1e-9; const double pi = acos(-1); typedef unsigned long long ull; typedef vector<vi> vvi; typedef vector<vii> vvii; template <class T> T smod(T a, T b) { return (a % b + b) % b; } // vim: cc=60 ts=2 sts=2 sw=2:
#pragma GCC optimize("Ofast","unroll-loops") #pragma GCC target("avx2,fma") #include <bits/stdc++.h> using namespace std; #define rep(i,a,b) for (__typeof(a) i=(a); i<(b); ++i) #define iter(it,c) for (__typeof((c).begin()) \ it = (c).begin(); it != (c).end(); ++it) typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef long long ll; const int INF = ~(1<<31); const double EPS = 1e-9; const double pi = acos(-1); typedef unsigned long long ull; typedef vector<vi> vvi; typedef vector<vii> vvii; template <class T> T smod(T a, T b) { return (a % b + b) % b; } // vim: cc=60 ts=2 sts=2 sw=2:
Convert sandbox NOTIMPLEMENTED()s into a bug.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { NOTIMPLEMENTED(); return true; } bool RendererMainPlatformDelegate::EnableSandbox() { NOTIMPLEMENTED(); return true; } void RendererMainPlatformDelegate::RunSandboxTests() { NOTIMPLEMENTED(); }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 }
Remove explicit WIN32 references from Console app.
#include "KAI/Console/Console.h" #include <iostream> #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #endif using namespace std; USING_NAMESPACE_KAI //static Color _color; int main(int argc, char **argv) { KAI_UNUSED_2(argc, argv); cout << "pyro v0.1" << endl; Console console; console.SetLanguage(Language::Pi); Process::trace = 0; console.GetExecutor()->SetTraceLevel(0); return console.Run(); }
#include <KAI/Console/Console.h> #include <iostream> using namespace std; USING_NAMESPACE_KAI int main(int argc, char **argv) { KAI_UNUSED_2(argc, argv); cout << "KAI v0.1" << endl; Console console; console.SetLanguage(Language::Pi); // the higher the number, the greater the verbosity of debug output Process::trace = 0; console.GetExecutor()->SetTraceLevel(0); // start the REPL return console.Run(); }
Fix compilation error on OSX
// // Created by monty on 26/09/16. // #include <string> #include <cstdarg> #ifdef __ANDROID__ #include <android/log.h> #else #include <cstdio> #endif #include "Logger.h" namespace odb { void doLog(const char *format, va_list args) { char buffer[255]; std::vsnprintf(buffer, 255, format, args); #ifdef __ANDROID__ __android_log_print(ANDROID_LOG_INFO, "Logger::log", "%s", buffer); #else std::printf( "%s\n", buffer ); #endif } void Logger::log(const char *format, ...) { va_list args; va_start(args, format); doLog(format, args); va_end(args); } void Logger::log(std::string format, ...) { va_list args; va_start(args, format); auto fmt = format.c_str(); doLog(fmt, args); va_end(args); } }
// // Created by monty on 26/09/16. // #include <string> #include <cstdarg> #include <cstring> #ifdef __ANDROID__ #include <android/log.h> #else #include <cstdio> #endif #include "Logger.h" namespace odb { void doLog(const char *format, va_list args) { char buffer[255]; return; memset(&buffer[0], 0, 255); std::vsnprintf(buffer, 255, format, args); #ifdef __ANDROID__ __android_log_print(ANDROID_LOG_INFO, "Logger::log", "%s", buffer); #else std::printf( "%s\n", buffer ); #endif } void Logger::log(const char *format, ...) { va_list args; va_start(args, format); doLog(format, args); va_end(args); } void Logger::log(std::string format, ...) { va_list args; va_start(args, format); auto fmt = format.c_str(); doLog(fmt, args); va_end(args); } }
Disable test failing since r29947.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // Started failing with r29947. WebKit merge 49961:49992. IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; }
Fix uninit memory access in TranslateManagerRenderViewHostTests.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/translate/core/common/language_detection_details.h" namespace translate { LanguageDetectionDetails::LanguageDetectionDetails() {} LanguageDetectionDetails::~LanguageDetectionDetails() {} } // namespace translate
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/translate/core/common/language_detection_details.h" namespace translate { LanguageDetectionDetails::LanguageDetectionDetails() : is_cld_reliable(false) { } LanguageDetectionDetails::~LanguageDetectionDetails() {} } // namespace translate
Use correct name for logger. Do not fail if sterror_r is not there
#include "powerdhcp.hh" namespace PowerDHCP { Logging theL; pthread_rwlock_t Logger::d_lock = PTHREAD_RWLOCK_INITIALIZER; const char* Logger::LEVEL[] = { "DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "CRITICAL" }; std::string stringerror() { std::string ret; char *buf = new char[1024]; #if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE) if (strerror_r(errno, buf, 1024)==0) ret.assign(buf); #elif defined(_GNU_SOURCE) if (strerror_r(errno, buf, 1024)) ret.assign(buf); #else #error "PowerDHCP::stringerror is not threadsafe on this system" #endif delete [] buf; return ret; } };
#include "powerdhcp.hh" namespace PowerDHCP { Logger theL; pthread_rwlock_t Logger::d_lock = PTHREAD_RWLOCK_INITIALIZER; const char* Logger::LEVEL[] = { "DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "CRITICAL" }; std::string stringerror() { std::string ret; char *buf = new char[1024]; #if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE) if (strerror_r(errno, buf, 1024)==0) ret.assign(buf); #elif defined(_GNU_SOURCE) if (strerror_r(errno, buf, 1024)) ret.assign(buf); #else #warning "PowerDHCP::stringerror might not be threadsafe on this system" ret.assign(strerror(errno)); #endif delete [] buf; return ret; } };
Fix crash in deviceinfo query.
/* * Copyright (C) 2017 Google Inc. * * 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 "instance.h" #include "query.h" extern "C" { device_instance get_device_instance(void* platform_data) { auto instance = query::getDeviceInstance(platform_data); // Reserialize the instance with the ID field. device_instance out; out.size = instance->ByteSize(); out.data = new uint8_t[out.size]; instance->SerializeToArray(out.data, out.size); delete instance; return out; } const char* get_device_instance_error() { return query::contextError(); } void free_device_instance(device_instance di) { delete[] di.data; } } // extern "C"
/* * Copyright (C) 2017 Google Inc. * * 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 "instance.h" #include "query.h" extern "C" { device_instance get_device_instance(void* platform_data) { device_instance out = {}; auto instance = query::getDeviceInstance(platform_data); if (!instance) { return out; } // Reserialize the instance with the ID field. out.size = instance->ByteSize(); out.data = new uint8_t[out.size]; instance->SerializeToArray(out.data, out.size); delete instance; return out; } const char* get_device_instance_error() { return query::contextError(); } void free_device_instance(device_instance di) { delete[] di.data; } } // extern "C"
Fix things so that they don't break the compile
#include "PythonModule.h" //#include "agent_finder_api.h" using namespace opencog; DECLARE_MODULE(PythonModule); PythonModule::PythonModule() : Module() { logger().info("[PythonModule] constructor"); do_load_py_register(); } PythonModule::~PythonModule() { logger().info("[PythonModule] destructor"); do_load_py_unregister(); } void PythonModule::init() { logger().info("[PythonModule] init"); } std::string PythonModule::do_load_py(Request *dummy, std::list<std::string> args) { //AtomSpace *space = CogServer::getAtomSpace(); if (args.size() == 0) return "Please specify Python module to load."; PyObject* py_module = load_module(args.front()); // TODO save the py_module somewhere // ... // TODO register the agents //CogServer& cogserver = static_cast<CogServer&>(server()); // How do we initialise a mind agent with a factory that will // load with given Python class //cogserver.registerAgent(PyMindAgent::info().id, &forgettingFactory); // TODO return info on what requests and mindagents were found return "Loaded python module"; }
#include "PythonModule.h" #include "agent_finder_api.h" using namespace opencog; DECLARE_MODULE(PythonModule); PythonModule::PythonModule() : Module() { logger().info("[PythonModule] constructor"); do_load_py_register(); } PythonModule::~PythonModule() { logger().info("[PythonModule] destructor"); do_load_py_unregister(); } void PythonModule::init() { logger().info("[PythonModule] init"); } std::string PythonModule::do_load_py(Request *dummy, std::list<std::string> args) { //AtomSpace *space = CogServer::getAtomSpace(); if (args.size() == 0) return "Please specify Python module to load."; PyObject* py_module = load_module(args.front()); // TODO save the py_module somewhere // ... // TODO register the agents //CogServer& cogserver = static_cast<CogServer&>(server()); // How do we initialise a mind agent with a factory that will // load with given Python class //cogserver.registerAgent(PyMindAgent::info().id, &forgettingFactory); // TODO return info on what requests and mindagents were found return "Loaded python module"; }
Expand the job name column.
#include "JobTree.h" #include "plow.h" #include <QStringList> #include <QString> namespace Plow { namespace Gui { JobTree::JobTree(QWidget *parent) : QWidget(parent) { layout = new QVBoxLayout(this); QStringList header; header << "Job" << "Cores" << "Max" << "Waiting"; treeWidget = new QTreeWidget; treeWidget->setHeaderLabels(header); treeWidget->setColumnCount(4); layout->addWidget(treeWidget); } void JobTree::updateJobs() { PlowClient* client = getClient(); std::vector<JobT> jobs; JobFilterT filter; std::vector<JobState::type> states; states.push_back(JobState::RUNNING); filter.__set_states(states); client->getJobs(jobs, filter); for (std::vector<JobT>::iterator i = jobs.begin(); i != jobs.end(); ++i) { QStringList data; data << QString::fromStdString(i->name) << QString::number(i->runningCoreCount) << QString::number(i->maxCores) << QString::number(i->waitingTaskCount); QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, data); treeWidget->insertTopLevelItem(0, item); } } } }
#include "JobTree.h" #include "plow.h" #include <QStringList> #include <QString> namespace Plow { namespace Gui { JobTree::JobTree(QWidget *parent) : QWidget(parent) { layout = new QVBoxLayout(this); QStringList header; header << "Job" << "Cores" << "Max" << "Waiting"; treeWidget = new QTreeWidget; treeWidget->setHeaderLabels(header); treeWidget->setColumnCount(4); treeWidget->setColumnWidth(0, 300); layout->addWidget(treeWidget); } void JobTree::updateJobs() { PlowClient* client = getClient(); std::vector<JobT> jobs; JobFilterT filter; std::vector<JobState::type> states; states.push_back(JobState::RUNNING); filter.__set_states(states); client->getJobs(jobs, filter); for (std::vector<JobT>::iterator i = jobs.begin(); i != jobs.end(); ++i) { QStringList data; data << QString::fromStdString(i->name) << QString::number(i->runningCoreCount) << QString::number(i->maxCores) << QString::number(i->waitingTaskCount); QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, data); treeWidget->insertTopLevelItem(0, item); } } } // Gui } // Plow
Remove rendering from distance queue tests to fix aero tests
#include <ngraph.h> #include <PCU.h> #include <engpar_support.h> #include "buildGraphs.h" #include "../partition/Diffusive/engpar_diffusive_input.h" #include "../partition/Diffusive/src/engpar_queue.h" int main(int argc, char* argv[]) { MPI_Init(&argc,&argv); EnGPar_Initialize(); agi::Ngraph* g; if (argc==1) if (PCU_Comm_Peers()==2) g = buildDisconnected2Graph(); else g=buildHyperGraphLine(); else { g = agi::createEmptyGraph(); g->loadFromFile(argv[1]); } PCU_Barrier(); engpar::Input* input = engpar::createDiffusiveInput(g,0); engpar::DiffusiveInput* inp = static_cast<engpar::DiffusiveInput*>(input); engpar::Queue* q = engpar::createDistanceQueue(inp); delete q; delete input; if (g->hasCoords()) { std::string filename = "graph"; agi::writeVTK(g,filename.c_str()); } agi::destroyGraph(g); PCU_Barrier(); if (!PCU_Comm_Self()) printf("All Tests Passed\n"); EnGPar_Finalize(); MPI_Finalize(); return 0; }
#include <ngraph.h> #include <PCU.h> #include <engpar_support.h> #include "buildGraphs.h" #include "../partition/Diffusive/engpar_diffusive_input.h" #include "../partition/Diffusive/src/engpar_queue.h" int main(int argc, char* argv[]) { MPI_Init(&argc,&argv); EnGPar_Initialize(); agi::Ngraph* g; if (argc==1) if (PCU_Comm_Peers()==2) g = buildDisconnected2Graph(); else g=buildHyperGraphLine(); else { g = agi::createEmptyGraph(); g->loadFromFile(argv[1]); } PCU_Barrier(); engpar::Input* input = engpar::createDiffusiveInput(g,0); engpar::DiffusiveInput* inp = static_cast<engpar::DiffusiveInput*>(input); engpar::Queue* q = engpar::createDistanceQueue(inp); delete q; delete input; agi::destroyGraph(g); PCU_Barrier(); if (!PCU_Comm_Self()) printf("All Tests Passed\n"); EnGPar_Finalize(); MPI_Finalize(); return 0; }
Fix WebAssembly build after r283702.
//===-- WebAssemblyTargetInfo.cpp - WebAssembly Target Implementation -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file registers the WebAssembly target. /// //===----------------------------------------------------------------------===// #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; #define DEBUG_TYPE "wasm-target-info" Target llvm::getTheWebAssemblyTarget32(); Target llvm::getTheWebAssemblyTarget64(); extern "C" void LLVMInitializeWebAssemblyTargetInfo() { RegisterTarget<Triple::wasm32> X(getTheWebAssemblyTarget32(), "wasm32", "WebAssembly 32-bit"); RegisterTarget<Triple::wasm64> Y(getTheWebAssemblyTarget64(), "wasm64", "WebAssembly 64-bit"); }
//===-- WebAssemblyTargetInfo.cpp - WebAssembly Target Implementation -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file registers the WebAssembly target. /// //===----------------------------------------------------------------------===// #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; #define DEBUG_TYPE "wasm-target-info" Target &llvm::getTheWebAssemblyTarget32() { static Target TheWebAssemblyTarget32; return TheWebAssemblyTarget32; } Target &llvm::getTheWebAssemblyTarget64() { static Target TheWebAssemblyTarget64; return TheWebAssemblyTarget64; } extern "C" void LLVMInitializeWebAssemblyTargetInfo() { RegisterTarget<Triple::wasm32> X(getTheWebAssemblyTarget32(), "wasm32", "WebAssembly 32-bit"); RegisterTarget<Triple::wasm64> Y(getTheWebAssemblyTarget64(), "wasm64", "WebAssembly 64-bit"); }
Fix basic allocation of memory blocks
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <minizinc/allocator.hh> namespace MiniZinc { const size_t BlockAllocator::blockSize; void BlockAllocator::allocateBlock(size_t bs) { bs = std::max(bs,blockSize); MemoryBlock* newBlock = static_cast<MemoryBlock*>(::malloc(bs)); newBlock->size = bs; newBlock->next = curBlock; curBlock = newBlock; curP = curBlock->data; endP = curBlock->data+bs; } void* BlockAllocator::alloc(size_t size) { /// Align to word boundary size += ((8 - (size & 7)) & 7); if (curP + size >= endP) allocateBlock(size); char* ret = curP; curP += size; return ret; } BlockAllocator::~BlockAllocator(void) { while (curBlock) { MemoryBlock* n = curBlock->next; ::free(curBlock); curBlock = n; } } }
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <minizinc/allocator.hh> namespace MiniZinc { const size_t BlockAllocator::blockSize; void BlockAllocator::allocateBlock(size_t bs) { bs = std::max(bs,blockSize); MemoryBlock* newBlock = static_cast<MemoryBlock*>(::malloc(sizeof(MemoryBlock)+bs)); newBlock->size = bs; newBlock->next = curBlock; curBlock = newBlock; curP = curBlock->data; endP = curBlock->data+bs; } void* BlockAllocator::alloc(size_t size) { /// Align to word boundary size += ((8 - (size & 7)) & 7); if (curP + size >= endP) allocateBlock(size); char* ret = curP; curP += size; return ret; } BlockAllocator::~BlockAllocator(void) { while (curBlock) { MemoryBlock* n = curBlock->next; ::free(curBlock); curBlock = n; } } }
Address last TSAN issue exposed by libopflex unit tests
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */ /* * Implementation for OFLogHandler class. * * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ /* This must be included before anything else */ #if HAVE_CONFIG_H # include <config.h> #endif #include "opflex/logging/OFLogHandler.h" #include "opflex/logging/StdOutLogHandler.h" namespace opflex { namespace logging { static OFLogHandler* volatile activeHandler = NULL; OFLogHandler::OFLogHandler(Level logLevel) : logLevel_(logLevel) { }; OFLogHandler::~OFLogHandler() { } void OFLogHandler::registerHandler(OFLogHandler& handler) { activeHandler = &handler; } OFLogHandler* OFLogHandler::getHandler() { static StdOutLogHandler defaultHandler(INFO); if (activeHandler) return activeHandler; return &defaultHandler; } bool OFLogHandler::shouldEmit(const Level level) { return level >= logLevel_; } } /* namespace logging */ } /* namespace opflex */
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */ /* * Implementation for OFLogHandler class. * * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ /* This must be included before anything else */ #if HAVE_CONFIG_H # include <config.h> #endif #include <boost/atomic.hpp> #include "opflex/logging/OFLogHandler.h" #include "opflex/logging/StdOutLogHandler.h" namespace opflex { namespace logging { static boost::atomic<OFLogHandler*> activeHandler(NULL); OFLogHandler::OFLogHandler(Level logLevel) : logLevel_(logLevel) { }; OFLogHandler::~OFLogHandler() { } void OFLogHandler::registerHandler(OFLogHandler& handler) { activeHandler = &handler; } OFLogHandler* OFLogHandler::getHandler() { static StdOutLogHandler defaultHandler(INFO); if (activeHandler) return activeHandler; return &defaultHandler; } bool OFLogHandler::shouldEmit(const Level level) { return level >= logLevel_; } } /* namespace logging */ } /* namespace opflex */
Fix linking on recent Qt for iOS
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QDebug> #include <Qt> #include "QZXingFilter.h" #if defined(Q_OS_IOS) /// Reference for iOS entry point: /// http://stackoverflow.com/questions/25353686/you-are-creating-qapplication-before-calling-uiapplicationmain-error-on-ios extern "C" int qtmn(int argc, char **argv) #else int main(int argc, char *argv[]) #endif { QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<QZXingFilter>("QZXing", 2, 3, "QZXingFilter"); qmlRegisterType<QZXing>("QZXing", 2, 3, "QZXing"); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QDebug> #include <Qt> #include "QZXingFilter.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<QZXingFilter>("QZXing", 2, 3, "QZXingFilter"); qmlRegisterType<QZXing>("QZXing", 2, 3, "QZXing"); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
Fix spacing + llamada a reset_search del mock
#include "OneWire.h" static OneWireMock* gOneWireMock = NULL; OneWireMock* oneWireMockInstance() { if( !gOneWireMock ) { gOneWireMock = new OneWireMock(); } return gOneWireMock; } void releaseOneWireMock() { if( gOneWireMock ) { delete gOneWireMock; gOneWireMock = NULL; } } bool OneWire::search( uint8_t* buf ) { assert( gOneWireMock != NULL ); return gOneWireMock->search(buf); } void OneWire::reset_search( void ) { }
#include "OneWire.h" static OneWireMock* gOneWireMock = NULL; OneWireMock* oneWireMockInstance() { if( !gOneWireMock ) { gOneWireMock = new OneWireMock(); } return gOneWireMock; } void releaseOneWireMock() { if( gOneWireMock ) { delete gOneWireMock; gOneWireMock = NULL; } } bool OneWire::search( uint8_t* buf ) { assert( gOneWireMock != NULL ); return gOneWireMock->search( buf ); } void OneWire::reset_search( void ) { assert( gOneWireMock != NULL ); gOneWireMock->reset_search( ); }
Make a buildbot using a buggy gcc happy
//===- Dominators.cpp - Implementation of dominators tree for Clang CFG ---===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Analysis/Analyses/Dominators.h" using namespace clang; template <> void clang::CFGDominatorTreeImpl</*IsPostDom=*/true>::anchor() {} template <> void clang::CFGDominatorTreeImpl</*IsPostDom=*/false>::anchor() {}
//===- Dominators.cpp - Implementation of dominators tree for Clang CFG ---===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Analysis/Analyses/Dominators.h" namespace clang { template <> void CFGDominatorTreeImpl</*IsPostDom=*/true>::anchor() {} template <> void CFGDominatorTreeImpl</*IsPostDom=*/false>::anchor() {} } // end of namespace clang
Revert "corrected serial port definition of rx test"
#include "mbed.h" #include "test_env.h" int main() { MBED_HOSTTEST_TIMEOUT(20); MBED_HOSTTEST_SELECT(serial_nc_rx_auto); MBED_HOSTTEST_DESCRIPTION(Serial NC RX); MBED_HOSTTEST_START("MBED_37"); Serial *pc = new Serial(USBTX, USBRX); char c = pc->getc(); delete pc; // This should be true if (c == 'E') { Serial *pc = new Serial(USBTX, NC); pc->printf("RX OK - Expected\r\n"); c = pc->getc(); // This should be false/not get here if (c == 'U') { pc->printf("RX OK - Unexpected\r\n"); } delete pc; } while (1) { } }
#include "mbed.h" #include "test_env.h" int main() { MBED_HOSTTEST_TIMEOUT(20); MBED_HOSTTEST_SELECT(serial_nc_rx_auto); MBED_HOSTTEST_DESCRIPTION(Serial NC RX); MBED_HOSTTEST_START("MBED_37"); Serial *pc = new Serial(NC, USBRX); char c = pc->getc(); delete pc; // This should be true if (c == 'E') { Serial *pc = new Serial(USBTX, NC); pc->printf("RX OK - Expected\r\n"); c = pc->getc(); // This should be false/not get here if (c == 'U') { pc->printf("RX OK - Unexpected\r\n"); } delete pc; } while (1) { } }
Use correct header to get PATH_MAX on linux/mac.
#include <linux/limits.h> #include <stdlib.h> #include <sys/stat.h> #include "MagpieString.h" #include "Path.h" namespace magpie { namespace path { char separator() { return '/'; } gc<String> real(gc<String> path) { char absolute[PATH_MAX]; realpath(path->cString(), absolute); return String::create(absolute); } bool fileExists(gc<String> path) { // If we can stat it, it exists. struct stat dummy; return stat(path->cString(), &dummy) == 0; } } }
// TODO(bob): PATH_MAX isn't actually part of POSIX. Need to do something // smarter here. #ifdef __linux__ #include <linux/limits.h> #else #include <limits.h> #endif #include <stdlib.h> #include <sys/stat.h> #include "MagpieString.h" #include "Path.h" namespace magpie { namespace path { char separator() { return '/'; } gc<String> real(gc<String> path) { char absolute[PATH_MAX]; realpath(path->cString(), absolute); return String::create(absolute); } bool fileExists(gc<String> path) { // If we can stat it, it exists. struct stat dummy; return stat(path->cString(), &dummy) == 0; } } }
Exit properly from the dokan filesystem thread.
#include "filesystem.h" #include "remotefileops.h" #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #define DEBUG_FILESYSTEM 0 struct FileSystemPrivate { FileSystemPrivate(FileOps* ops) { m_fileOps = ops; } FileOps* m_fileOps; }; FileSystem::FileSystem(FileOps* ops) : QThread(0) , d(new FileSystemPrivate(ops)) { } FileSystem::~FileSystem() { delete d; } void FileSystem::stop() { QThread::exit(0); } void FileSystem::run() { exec(); }
#include "filesystem.h" #include "remotefileops.h" #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #define DEBUG_FILESYSTEM 0 struct FileSystemPrivate { FileSystemPrivate(FileOps* ops) { m_fileOps = ops; } FileOps* m_fileOps; }; FileSystem::FileSystem(FileOps* ops) : QThread(0) , d(new FileSystemPrivate(ops)) { } FileSystem::~FileSystem() { stop(); delete d; } void FileSystem::stop() { exit(0); if (!wait(5000)) { terminate(); wait(); } } void FileSystem::run() { exec(); }
Add selector for Android tablet
#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include <QQmlFileSelector> #include "screenvalues.h" static QObject *screen_values_provider(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) return new ScreenValues(); } int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; QQmlFileSelector* selector = new QQmlFileSelector(&engine); Q_UNUSED(selector) engine.addImportPath("qrc:/"); qmlRegisterSingletonType<ScreenValues>("QtWorldSummit", 1, 5, "ScreenValues", screen_values_provider); engine.load(QUrl("qrc:/qml/qml/main.qml")); return app.exec(); }
#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include <QQmlFileSelector> #include "screenvalues.h" static QObject *screen_values_provider(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) return new ScreenValues(); } int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; QQmlFileSelector* selector = new QQmlFileSelector(&engine); QStringList extraSelectors; #ifdef Q_OS_ANDROID ScreenValues *sv = new ScreenValues(); if (sv->isTablet()) extraSelectors << "android_tablet"; delete sv; #endif if (!extraSelectors.isEmpty()) selector->setExtraSelectors(extraSelectors); engine.addImportPath("qrc:/"); qmlRegisterSingletonType<ScreenValues>("QtWorldSummit", 1, 5, "ScreenValues", screen_values_provider); engine.load(QUrl("qrc:/qml/qml/main.qml")); return app.exec(); }
Extend witness ask user confirmation
// Copyright (c) 2016-2019 The Gulden developers // Authored by: Willem de Jonge (willem@isnapp.nl) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "extendwitnessdialog.h" #include <qt/_Gulden/forms/ui_extendwitnessdialog.h> #include "wallet/wallet.h" #include "GuldenGUI.h" #define LOG_QT_METHOD LogPrint(BCLog::QT, "%s\n", __PRETTY_FUNCTION__) ExtendWitnessDialog::ExtendWitnessDialog(const QStyle *_platformStyle, QWidget *parent) : QFrame( parent ) , ui( new Ui::ExtendWitnessDialog ) , platformStyle( _platformStyle ) { ui->setupUi(this); connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked())); connect(ui->extendButton, SIGNAL(clicked()), this, SLOT(extendClicked())); } ExtendWitnessDialog::~ExtendWitnessDialog() { delete ui; } void ExtendWitnessDialog::cancelClicked() { LOG_QT_METHOD; Q_EMIT dismiss(this); } void ExtendWitnessDialog::extendClicked() { LOG_QT_METHOD; Q_EMIT dismiss(this); }
// Copyright (c) 2016-2019 The Gulden developers // Authored by: Willem de Jonge (willem@isnapp.nl) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "extendwitnessdialog.h" #include <qt/_Gulden/forms/ui_extendwitnessdialog.h> #include "wallet/wallet.h" #include "gui.h" #define LOG_QT_METHOD LogPrint(BCLog::QT, "%s\n", __PRETTY_FUNCTION__) ExtendWitnessDialog::ExtendWitnessDialog(const QStyle *_platformStyle, QWidget *parent) : QFrame( parent ) , ui( new Ui::ExtendWitnessDialog ) , platformStyle( _platformStyle ) { ui->setupUi(this); connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked())); connect(ui->extendButton, SIGNAL(clicked()), this, SLOT(extendClicked())); } ExtendWitnessDialog::~ExtendWitnessDialog() { delete ui; } void ExtendWitnessDialog::cancelClicked() { LOG_QT_METHOD; Q_EMIT dismiss(this); } void ExtendWitnessDialog::extendClicked() { LOG_QT_METHOD; if(QDialog::Accepted == GUI::createDialog(this, "Confirm extending", tr("Extend"), tr("Cancel"), 600, 360, "ExtendWitnessConfirmationDialog")->exec()) { // TODO: execute extend and dismiss dialog on succes, or alert user on failure Q_EMIT dismiss(this); } }
Fix autoscrolling when dragging near edge of rack
#include "app.hpp" #include "gui.hpp" namespace rack { void RackScrollWidget::step() { Vec pos = gRackWidget->lastMousePos; // Scroll rack if dragging cable near the edge of the screen if (gRackWidget->wireContainer->activeWire) { float margin = 20.0; float speed = 15.0; if (pos.x <= margin) offset.x -= speed; if (pos.x >= box.size.x - margin) offset.x += speed; if (pos.y <= margin) offset.y -= speed; if (pos.y >= box.size.y - margin) offset.y += speed; } ScrollWidget::step(); } } // namespace rack
#include "app.hpp" #include "gui.hpp" namespace rack { void RackScrollWidget::step() { Vec pos = gMousePos; Rect viewport = getViewport(box.zeroPos()); // Scroll rack if dragging cable near the edge of the screen if (gRackWidget->wireContainer->activeWire) { float margin = 20.0; float speed = 15.0; if (pos.x <= viewport.pos.x + margin) offset.x -= speed; if (pos.x >= viewport.pos.x + viewport.size.x - margin) offset.x += speed; if (pos.y <= viewport.pos.y + margin) offset.y -= speed; if (pos.y >= viewport.pos.y + viewport.size.y - margin) offset.y += speed; } ScrollWidget::step(); } } // namespace rack