Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Set some names and titles just in case they are useful to set.
#include <QtQuick> #include <sailfishapp.h> #include <QScopedPointer> #include <QQuickView> #include <QQmlEngine> #include <QGuiApplication> #include "factor.h" int main(int argc, char *argv[]) { // For this example, wizard-generates single line code would be good enough, // but very soon it won't be enough for you anyway, so use this more detailed example from start QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); Factorizer fact; runUnitTests(); // Here's how you will add QML components whenever you start using them // Check https://github.com/amarchen/Wikipedia for a more full example // view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString()); view->engine()->rootContext()->setContextProperty("fact", &fact); view->setSource(SailfishApp::pathTo("qml/main.qml")); view->show(); return app->exec(); }
#include <QtQuick> #include <sailfishapp.h> #include <QScopedPointer> #include <QQuickView> #include <QQmlEngine> #include <QGuiApplication> #include "factor.h" int main(int argc, char *argv[]) { // For this example, wizard-generates single line code would be good enough, // but very soon it won't be enough for you anyway, so use this more detailed example from start QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); Factorizer fact; runUnitTests(); // Here's how you will add QML components whenever you start using them // Check https://github.com/amarchen/Wikipedia for a more full example // view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString()); view->engine()->rootContext()->setContextProperty("fact", &fact); view->setSource(SailfishApp::pathTo("qml/main.qml")); view->setTitle("Sailfactor"); app->setApplicationName("harbour-sailfactor"); app->setApplicationDisplayName("Sailfactor"); view->show(); return app->exec(); }
Use IListNodeBase instead of type redefinition.
//===- IListIterator.cpp --------------------------------------------------===// // // The Bold Project // // This file is distributed under the New BSD License. // See LICENSE for details. // //===----------------------------------------------------------------------===// #include <bold/ADT/IListIterator.h> #include <cassert> using namespace bold; //===----------------------------------------------------------------------===// // IListIteratorBase //===----------------------------------------------------------------------===// IListIteratorBase::IListIteratorBase() : m_pNodePtr(NULL) { } IListIteratorBase::IListIteratorBase(NodeBase* pNode) : m_pNodePtr(pNode) { } void IListIteratorBase::advance() { assert(NULL != m_pNodePtr && "trivial iterator can not advance"); m_pNodePtr = m_pNodePtr->getNext(); } void IListIteratorBase::retreat() { assert(NULL != m_pNodePtr && "trivial iterator can not retreat"); m_pNodePtr = m_pNodePtr->getPrev(); }
//===- IListIterator.cpp --------------------------------------------------===// // // The Bold Project // // This file is distributed under the New BSD License. // See LICENSE for details. // //===----------------------------------------------------------------------===// #include <bold/ADT/IListIterator.h> #include <cassert> using namespace bold; //===----------------------------------------------------------------------===// // IListIteratorBase //===----------------------------------------------------------------------===// IListIteratorBase::IListIteratorBase() : m_pNodePtr(NULL) { } IListIteratorBase::IListIteratorBase(IListNodeBase* pNode) : m_pNodePtr(pNode) { } void IListIteratorBase::advance() { assert(NULL != m_pNodePtr && "trivial iterator can not advance"); m_pNodePtr = m_pNodePtr->getNext(); } void IListIteratorBase::retreat() { assert(NULL != m_pNodePtr && "trivial iterator can not retreat"); m_pNodePtr = m_pNodePtr->getPrev(); }
Replace Seen_table with Seen_table_wrapper in the binding
#include <boost/python.hpp> #include "mue_algorithm.h" #include "teams.h" #include "distances.h" #include "seen_table.h" char const * peng() { return mue::peng().c_str(); } BOOST_PYTHON_MODULE (_pymue) { using namespace boost::python; def ("peng", peng); class_<mue::Team>("Team", init<int>()) .def("id", &mue::Team::id); class_<mue::Distance_matrix>("DistanceMatrix", init<int>()) .def("set_cost", &mue::Distance_matrix::set_cost) .def("lookup", &mue::Distance_matrix::lookup); class_<mue::Seen_table>("SeenTable", init<int>()) .def("clone", &mue::Seen_table::clone) .def("generation", &mue::Seen_table::generation) .def("seen", &mue::Seen_table::seen) .def("add_meeting", &mue::Seen_table::add_meeting); }
#include <boost/python.hpp> #include "mue_algorithm.h" #include "teams.h" #include "distances.h" #include "seen_table_wrapper.h" char const * peng() { return mue::peng().c_str(); } BOOST_PYTHON_MODULE (_pymue) { using namespace boost::python; def ("peng", peng); class_<mue::Team>("Team", init<int>()) .def("id", &mue::Team::id); class_<mue::Distance_matrix>("DistanceMatrix", init<int>()) .def("set_cost", &mue::Distance_matrix::set_cost) .def("lookup", &mue::Distance_matrix::lookup); class_<pymue::Seen_table_wrapper>("SeenTable", init<int>()) .def("clone", &pymue::Seen_table_wrapper::clone) .def("generation", &pymue::Seen_table_wrapper::generation) .def("seen", &pymue::Seen_table_wrapper::seen) .def("add_meeting", &pymue::Seen_table_wrapper::add_meeting); }
Mark another test as flaky
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // <mutex> // class mutex; // void lock(); #include <mutex> #include <thread> #include <cstdlib> #include <cassert> #include <iostream> std::mutex m; typedef std::chrono::system_clock Clock; typedef Clock::time_point time_point; typedef Clock::duration duration; typedef std::chrono::milliseconds ms; typedef std::chrono::nanoseconds ns; void f() { time_point t0 = Clock::now(); m.lock(); time_point t1 = Clock::now(); m.unlock(); ns d = t1 - t0 - ms(250); assert(d < ms(50)); // within 50ms } int main() { m.lock(); std::thread t(f); std::this_thread::sleep_for(ms(250)); m.unlock(); t.join(); }
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // FLAKY_TEST. // <mutex> // class mutex; // void lock(); #include <mutex> #include <thread> #include <cstdlib> #include <cassert> #include <iostream> std::mutex m; typedef std::chrono::system_clock Clock; typedef Clock::time_point time_point; typedef Clock::duration duration; typedef std::chrono::milliseconds ms; typedef std::chrono::nanoseconds ns; void f() { time_point t0 = Clock::now(); m.lock(); time_point t1 = Clock::now(); m.unlock(); ns d = t1 - t0 - ms(250); assert(d < ms(50)); // within 50ms } int main() { m.lock(); std::thread t(f); std::this_thread::sleep_for(ms(250)); m.unlock(); t.join(); }
Fix the logic of Insertion sort which is not working
#include "insertion.hpp" #include "swap.hpp" void insertion(int *data, const int size_of_data) { for(int i = 0; i < size_of_data; ++i) { int j; for(j = i; j >= 0 && data[j] < data[i]; --j); swap(data[i], data[j]); } }
#include "insertion.hpp" #include "swap.hpp" void insertion(int *data, const int size_of_data) { for(int i = 0; i < size_of_data; ++i) { for(int j = i; j > 0 && data[j] < data[j - 1]; --j) swap(data[j], data[j - 1]); } }
Rename creation method to avoid ambiguity with resource loading
#include <Bull/Core/Exception/RuntimeError.hpp> #include <Bull/Render/Buffer/VertexArrayObject.hpp> #include <Bull/Render/OpenGL.hpp> namespace Bull { VertexArrayObject::VertexArrayObject() : m_vao(0) { gl::genVertexArrays(1, &m_vao); if(!gl::isVertexArray(m_vao)) { throw RuntimeError("Failed to create VAO"); } } VertexArrayObject::~VertexArrayObject() { gl::deleteVertexArrays(1, &m_vao); } void VertexArrayObject::runBound(const Functor<void>& functor) const { gl::bindVertexArray(m_vao); functor(); gl::bindVertexArray(0); } }
#include <Bull/Core/Exception/RuntimeError.hpp> #include <Bull/Render/Buffer/VertexArrayObject.hpp> #include <Bull/Render/OpenGL.hpp> namespace Bull { VertexArrayObject::VertexArrayObject() : m_vao(0) { gl::genVertexArrays(1, &m_vao); if(!m_vao) { throw RuntimeError("Failed to create VAO"); } } VertexArrayObject::~VertexArrayObject() { gl::deleteVertexArrays(1, &m_vao); } void VertexArrayObject::runBound(const Functor<void>& functor) const { gl::bindVertexArray(m_vao); functor(); gl::bindVertexArray(0); } }
Work around bug in gcc's name mangling causing linker to crash on Mac OS X.
// 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 "../client/gles2_lib.h" #include "../common/thread_local.h" namespace gles2 { namespace { gpu::ThreadLocalKey g_gl_context_key; } // namespace anonymous void Initialize() { g_gl_context_key = gpu::ThreadLocalAlloc(); } void Terminate() { gpu::ThreadLocalFree(g_gl_context_key); g_gl_context_key = 0; } gpu::gles2::GLES2Implementation* GetGLContext() { return static_cast<gpu::gles2::GLES2Implementation*>( gpu::ThreadLocalGetValue(g_gl_context_key)); } void SetGLContext(gpu::gles2::GLES2Implementation* context) { gpu::ThreadLocalSetValue(g_gl_context_key, context); } } // namespace gles2
// 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 "../client/gles2_lib.h" #include "../common/thread_local.h" namespace gles2 { // TODO(kbr): the use of this anonymous namespace core dumps the // linker on Mac OS X 10.6 when the symbol ordering file is used // namespace { static gpu::ThreadLocalKey g_gl_context_key; // } // namespace anonymous void Initialize() { g_gl_context_key = gpu::ThreadLocalAlloc(); } void Terminate() { gpu::ThreadLocalFree(g_gl_context_key); g_gl_context_key = 0; } gpu::gles2::GLES2Implementation* GetGLContext() { return static_cast<gpu::gles2::GLES2Implementation*>( gpu::ThreadLocalGetValue(g_gl_context_key)); } void SetGLContext(gpu::gles2::GLES2Implementation* context) { gpu::ThreadLocalSetValue(g_gl_context_key, context); } } // namespace gles2
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_; }
Change define name to prevent name clashes with the python interpreter
#include "stdafx.h" #include <string> #include "Logger.h" #ifdef _WIN64 #define PYTHONPATH L"python-embed-amd64" #else #define PYTHONPATH L"python-embed-win32" #endif EXTERN_C IMAGE_DOS_HEADER __ImageBase; std::wstring getPythonPath() { // https://stackoverflow.com/questions/6924195/get-dll-path-at-runtime WCHAR DllPath[MAX_PATH] = { 0 }; if (GetModuleFileNameW((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath)) == 0) { LOG_ERROR("Error getting Pythia DLL path"); return L""; } std::wstring DllPath_s = DllPath; std::wstring directory; const size_t last_slash_idx = DllPath_s.rfind(L'\\'); if (std::string::npos != last_slash_idx) { directory = DllPath_s.substr(0, last_slash_idx); } std::wstring pythonPath = directory + L"\\" + PYTHONPATH; return pythonPath; }
#include "stdafx.h" #include <string> #include "Logger.h" #ifdef _WIN64 #define EMBEDDEDPYTHONPATH L"python-embed-amd64" #else #define EMBEDDEDPYTHONPATH L"python-embed-win32" #endif EXTERN_C IMAGE_DOS_HEADER __ImageBase; std::wstring getPythonPath() { // https://stackoverflow.com/questions/6924195/get-dll-path-at-runtime WCHAR DllPath[MAX_PATH] = { 0 }; if (GetModuleFileNameW((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath)) == 0) { LOG_ERROR("Error getting Pythia DLL path"); return L""; } std::wstring DllPath_s = DllPath; std::wstring directory; const size_t last_slash_idx = DllPath_s.rfind(L'\\'); if (std::string::npos != last_slash_idx) { directory = DllPath_s.substr(0, last_slash_idx); } std::wstring pythonPath = directory + L"\\" + EMBEDDEDPYTHONPATH; return pythonPath; }
Revert dummy handle signal definition
/* * * Copyright 2019 Asylo authors * * 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 <unistd.h> namespace asylo { extern "C" { int __asylo_handle_signal(const char *input, size_t input_len) { return 0; } int __asylo_take_snapshot(char **output, size_t *output_len) { return 0; } int __asylo_restore(const char *snapshot_layout, size_t snapshot_layout_len, char **output, size_t *output_len) { return 0; } int __asylo_transfer_secure_snapshot_key(const char *input, size_t input_len, char **output, size_t *output_len) { return 0; } } // extern "C" } // namespace asylo
/* * * Copyright 2019 Asylo authors * * 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 <unistd.h> namespace asylo { extern "C" { int __asylo_take_snapshot(char **output, size_t *output_len) { return 0; } int __asylo_restore(const char *snapshot_layout, size_t snapshot_layout_len, char **output, size_t *output_len) { return 0; } int __asylo_transfer_secure_snapshot_key(const char *input, size_t input_len, char **output, size_t *output_len) { return 0; } } // extern "C" } // namespace asylo
Revert "Revert "Ajout de methode de test (incomplete) de Dictionnaire""
#include "stdafx.h" #include "CppUnitTest.h" #include "../DNAnalyzerServer/Dictionnaire.h" #include <exception> #include <cstring> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace DNAnalyzerServerTest { TEST_CLASS(DictionnaireTest) { public: //ObtenirInstance TEST_METHOD(ObtenirInstance_NotNull) { // L'instance retourne ne doit pas tre null Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr); } TEST_METHOD(ObtenirInstance_SameReference) { // L'instance retourne doit toujours tre la mme Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance())); } }; }
#include "stdafx.h" #include "CppUnitTest.h" #include "../DNAnalyzerServer/Dictionnaire.h" #include "../DNAnalyzerServer/Mots.h" #include <exception> #include <unordered_set> #include <cstring> #include <string> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace DNAnalyzerServerTest { TEST_CLASS(DictionnaireTest) { public: //ObtenirInstance TEST_METHOD(ObtenirInstance_NotNull) { // L'instance retourne ne doit pas tre null Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr); } TEST_METHOD(ObtenirInstance_SameReference) { // L'instance retourne doit toujours tre la mme Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance())); } TEST_METHOD(ObtenirMaladie_KnownMaladie) { } TEST_METHOD(ObtenirMaladie_UnKnownMaladie) { } TEST_METHOD(ObtenirMaladies_NoMaladies) { char motInexistant[] = "ATCGINEXISTANT"; unsigned int indexMotInexistant = Mots::ObtenirInstance().InsererMot(motInexistant); const unordered_set<const Maladie*> resutat = Dictionnaire::ObtenirInstance().ObtenirMaladies(indexMotInexistant); Assert::AreEqual(resutat.size, 0); } TEST_METHOD(ObtenirMaladies_OneMaladies) { } TEST_METHOD(ObtenirMaladies_TwoMaladies) { } TEST_METHOD(ObtenirNomMaladies_EmptyDictionnaire) { } TEST_METHOD(ObtenirNomMaladies_NotEmptyDictionnaire) { } }; }
Use test fixture in GetUserName unit tests
#include <string> #include <vector> #include <unistd.h> #include <gtest/gtest.h> #include <scxcorelib/scxstrencodingconv.h> #include "getusername.h" TEST(GetUserName,simple) { // allocate a WCHAR_T buffer to receive username DWORD lpnSize = L_cuserid; WCHAR_T lpBuffer[lpnSize]; BOOL result = GetUserName(lpBuffer, &lpnSize); // GetUserName returns 1 on success ASSERT_EQ(1, result); // get expected username std::string username(getlogin()); // GetUserName sets lpnSize to length of username including null ASSERT_EQ(username.size()+1, lpnSize); // copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]); // -1 to skip null; *2 because UTF-16 encodes two bytes per character unsigned char *end = begin + (lpnSize-1)*2; std::vector<unsigned char> input(begin, end); // convert to UTF-8 for assertion std::string output; SCXCoreLib::Utf16leToUtf8(input, output); EXPECT_EQ(username, output); }
#include <string> #include <vector> #include <unistd.h> #include <gtest/gtest.h> #include <scxcorelib/scxstrencodingconv.h> #include "getusername.h" class GetUserNameTest : public ::testing::Test { protected: DWORD lpnSize; std::vector<WCHAR_T> lpBuffer; BOOL result; std::string userName; GetUserNameTest(): userName(std::string(getlogin())) {} void GetUserNameWithSize(DWORD size) { lpnSize = size; // allocate a WCHAR_T buffer to receive username lpBuffer.assign(lpnSize, '\0'); result = GetUserName(&lpBuffer[0], &lpnSize); } }; TEST_F(GetUserNameTest, NormalUse) { GetUserNameWithSize(L_cuserid); // GetUserName returns 1 on success ASSERT_EQ(1, result); // GetUserName sets lpnSize to length of username including null ASSERT_EQ(userName.size()+1, lpnSize); // copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]); // -1 to skip null; *2 because UTF-16 encodes two bytes per character unsigned char *end = begin + (lpnSize-1)*2; std::vector<unsigned char> input(begin, end); // convert to UTF-8 for assertion std::string output; SCXCoreLib::Utf16leToUtf8(input, output); EXPECT_EQ(userName, output); }
Fix a flawed check in indexedcorpus::readFile.
#include "textfile.ih" vector<unsigned char> indexedcorpus::readFile(string const &filename) { QFileInfo p(filename.c_str()); if (p.isFile()) throw runtime_error(string("readFile: '") + filename + "' is not a regular file!"); vector<unsigned char> data; ifstream dataStream(filename.c_str()); if (!dataStream) throw runtime_error(string("readFile: '") + filename + "' could be read!"); dataStream >> noskipws; copy(istream_iterator<char>(dataStream), istream_iterator<char>(), back_inserter(data)); return data; }
#include "textfile.ih" vector<unsigned char> indexedcorpus::readFile(string const &filename) { QFileInfo p(filename.c_str()); if (!p.isFile()) throw runtime_error(string("readFile: '") + filename + "' is not a regular file!"); vector<unsigned char> data; ifstream dataStream(filename.c_str()); if (!dataStream) throw runtime_error(string("readFile: '") + filename + "' could be read!"); dataStream >> noskipws; copy(istream_iterator<char>(dataStream), istream_iterator<char>(), back_inserter(data)); return data; }
Change virtual dtor to empty bodies
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ #include "Exceptions.h" using namespace antlr4; RuntimeException::RuntimeException(const std::string &msg) : std::exception(), _message(msg) { } const char* RuntimeException::what() const NOEXCEPT { return _message.c_str(); } //------------------ IOException --------------------------------------------------------------------------------------- IOException::IOException(const std::string &msg) : std::exception(), _message(msg) { } const char* IOException::what() const NOEXCEPT { return _message.c_str(); } IllegalStateException::~IllegalStateException() = default; IllegalArgumentException::~IllegalArgumentException() = default; NullPointerException::~NullPointerException() = default; IndexOutOfBoundsException::~IndexOutOfBoundsException() = default; UnsupportedOperationException::~UnsupportedOperationException() = default; EmptyStackException::~EmptyStackException() = default; CancellationException::~CancellationException() = default; ParseCancellationException::~ParseCancellationException() = default;
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ #include "Exceptions.h" using namespace antlr4; RuntimeException::RuntimeException(const std::string &msg) : std::exception(), _message(msg) { } const char* RuntimeException::what() const NOEXCEPT { return _message.c_str(); } //------------------ IOException --------------------------------------------------------------------------------------- IOException::IOException(const std::string &msg) : std::exception(), _message(msg) { } const char* IOException::what() const NOEXCEPT { return _message.c_str(); } //------------------ IllegalStateException ----------------------------------------------------------------------------- IllegalStateException::~IllegalStateException() { } //------------------ IllegalArgumentException -------------------------------------------------------------------------- IllegalArgumentException::~IllegalArgumentException() { } //------------------ NullPointerException ------------------------------------------------------------------------------ NullPointerException::~NullPointerException() { } //------------------ IndexOutOfBoundsException ------------------------------------------------------------------------- IndexOutOfBoundsException::~IndexOutOfBoundsException() { } //------------------ UnsupportedOperationException --------------------------------------------------------------------- UnsupportedOperationException::~UnsupportedOperationException() { } //------------------ EmptyStackException ------------------------------------------------------------------------------- EmptyStackException::~EmptyStackException() { } //------------------ CancellationException ----------------------------------------------------------------------------- CancellationException::~CancellationException() { } //------------------ ParseCancellationException ------------------------------------------------------------------------ ParseCancellationException::~ParseCancellationException() { }
Mark ExtensionApiTest.Popup as FLAKY, it is still flaky.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Flaky, http://crbug.com/46601. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup")) << message_; }
Revert "Re-enable absl FailureSignalHandler in tests."
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <memory> #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/symbolize.h" #include "test/test_main_lib.h" int main(int argc, char* argv[]) { // Initialize the symbolizer to get a human-readable stack trace absl::InitializeSymbolizer(argv[0]); absl::FailureSignalHandlerOptions options; absl::InstallFailureSignalHandler(options); std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create(); int err_code = main->Init(&argc, argv); if (err_code != 0) { return err_code; } return main->Run(argc, argv); }
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <memory> #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/symbolize.h" #include "test/test_main_lib.h" int main(int argc, char* argv[]) { // Initialize the symbolizer to get a human-readable stack trace // TODO(crbug.com/1050976): Breaks iossim tests, re-enable when fixed. // absl::InitializeSymbolizer(argv[0]); // absl::FailureSignalHandlerOptions options; // absl::InstallFailureSignalHandler(options); std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create(); int err_code = main->Init(&argc, argv); if (err_code != 0) { return err_code; } return main->Run(argc, argv); }
Revert some casts that are needed.
#include "cpr/timeout.h" #include <limits> #include <stdexcept> #include <string> #include <type_traits> namespace cpr { long Timeout::Milliseconds() const { static_assert(std::is_same<std::chrono::milliseconds, decltype(ms)>::value, "Following casting expects milliseconds."); if (ms.count() > std::numeric_limits<long>::max()) { throw std::overflow_error("cpr::Timeout: timeout value overflow: " + std::to_string(ms.count()) + " ms."); } if (ms.count() < std::numeric_limits<long>::min()) { throw std::underflow_error("cpr::Timeout: timeout value underflow: " + std::to_string(ms.count()) + " ms."); } return ms.count(); } } // namespace cpr
#include "cpr/timeout.h" #include <limits> #include <stdexcept> #include <string> #include <type_traits> namespace cpr { long Timeout::Milliseconds() const { static_assert(std::is_same<std::chrono::milliseconds, decltype(ms)>::value, "Following casting expects milliseconds."); if (ms.count() > std::numeric_limits<long>::max()) { throw std::overflow_error("cpr::Timeout: timeout value overflow: " + std::to_string(ms.count()) + " ms."); } if (ms.count() < std::numeric_limits<long>::min()) { throw std::underflow_error("cpr::Timeout: timeout value underflow: " + std::to_string(ms.count()) + " ms."); } return static_cast<long>(ms.count()); } } // namespace cpr
Add EQ, COND, CAR, CDR and CONS to Eval.
#include "eval.h" #include "env.h" namespace mclisp { ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */) { if (Atom(exp)) return env::Lookup(env, exp); if (Atom(Car(exp))) { if (Eq(Car(exp), g_builtin_symbols["QUOTE"])) return Cadr(exp); if (Eq(Car(exp), g_builtin_symbols["ATOM"])) return FromBool(Atom(Eval(Cadr(exp), env))); } return MakeSymbol("42"); } } // namespace mclisp
#include "eval.h" #include "env.h" namespace { using namespace mclisp; ConsCell *Evcon(const ConsCell *clauses, ConsCell *env) { // TODO Might want throw something more descriptive than TypeError. TYPECHECK(clauses, Listp); if (Null(clauses)) return kNil; TYPECHECK(Car(clauses), Consp); if (*Eval(Caar(clauses), env)) return Eval(Cadar(clauses), env); return Evcon(Cdr(clauses), env); } } // namespace namespace mclisp { ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */) { #define EQ(exp, sym) Eq(exp, g_builtin_symbols[#sym]) if (Atom(exp)) return env::Lookup(env, exp); if (Atom(Car(exp))) { if (EQ(Car(exp), QUOTE)) return Cadr(exp); if (EQ(Car(exp), ATOM)) return FromBool(Atom(Eval(Cadr(exp), env))); if (EQ(Car(exp), EQ)) return FromBool(Eq(Eval(Cadr(exp), env), Eval(Caddr(exp), env))); if (EQ(Car(exp), COND)) return Evcon(Cdr(exp), env); if (EQ(Car(exp), CAR)) return Car(Eval(Cadr(exp), env)); if (EQ(Car(exp), CDR)) return Cdr(Eval(Cadr(exp), env)); if (EQ(Car(exp), CONS)) return Cons(Eval(Cadr(exp), env), Eval(Caddr(exp), env)); } #undef EQ return MakeSymbol("42"); } } // namespace mclisp
Change default running state to true
#include "gamescene.h" void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem) { GameScene *scene = qobject_cast<GameScene *>(list->object); if (scene) { gameItem->setParentItem(scene); scene->m_gameItems.append(gameItem); } } GameScene::GameScene(QQuickItem *parent) : QQuickItem(parent) { } QDeclarativeListProperty<GameItem> GameScene::gameItems() { return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem); } void GameScene::update(long delta) { if (!m_running) // TODO: stop Qt animations as well return; GameItem *item; foreach (item, m_gameItems) item->update(delta); } bool GameScene::running() const { return m_running; } void GameScene::setRunning(bool running) { m_running = running; emit runningChanged(); }
#include "gamescene.h" void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem) { GameScene *scene = qobject_cast<GameScene *>(list->object); if (scene) { gameItem->setParentItem(scene); scene->m_gameItems.append(gameItem); } } GameScene::GameScene(QQuickItem *parent) : QQuickItem(parent) , m_running(true) { } QDeclarativeListProperty<GameItem> GameScene::gameItems() { return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem); } void GameScene::update(long delta) { if (!m_running) // TODO: stop Qt animations as well return; GameItem *item; foreach (item, m_gameItems) item->update(delta); } bool GameScene::running() const { return m_running; } void GameScene::setRunning(bool running) { m_running = running; emit runningChanged(); }
Add tests for variadic calls
#include <stan/math/prim/scal.hpp> #include <gtest/gtest.h> #include <limits> TEST(MathFunctions, is_nan) { using stan::math::is_nan; double infinity = std::numeric_limits<double>::infinity(); double nan = std::numeric_limits<double>::quiet_NaN(); double min = std::numeric_limits<double>::min(); double max = std::numeric_limits<double>::max(); EXPECT_TRUE(stan::math::is_nan(nan)); EXPECT_FALSE(stan::math::is_nan(infinity)); EXPECT_FALSE(stan::math::is_nan(0)); EXPECT_FALSE(stan::math::is_nan(1)); EXPECT_FALSE(stan::math::is_nan(min)); EXPECT_FALSE(stan::math::is_nan(max)); }
#include <stan/math/prim/scal.hpp> #include <gtest/gtest.h> #include <limits> TEST(MathFunctions, is_nan) { using stan::math::is_nan; double infinity = std::numeric_limits<double>::infinity(); double nan = std::numeric_limits<double>::quiet_NaN(); double min = std::numeric_limits<double>::min(); double max = std::numeric_limits<double>::max(); EXPECT_TRUE(is_nan(nan)); EXPECT_FALSE(is_nan(infinity)); EXPECT_FALSE(is_nan(0)); EXPECT_FALSE(is_nan(1)); EXPECT_FALSE(is_nan(min)); EXPECT_FALSE(is_nan(max)); } TEST(MathFunctions, is_nan_variadic) { using stan::math::is_nan; double infinity = std::numeric_limits<double>::infinity(); double nan = std::numeric_limits<double>::quiet_NaN(); double min = std::numeric_limits<double>::min(); double max = std::numeric_limits<double>::max(); EXPECT_TRUE(is_nan(nan, infinity, 1.0)); EXPECT_TRUE(is_nan(max, infinity, nan, 2.0, 5.0)); EXPECT_TRUE(is_nan(max, min, nan)); EXPECT_FALSE(is_nan(1.0, 2.0, 20.0, 1, 2)); }
Fix iteration through loop bb
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "mtac/Loop.hpp" #include "mtac/basic_block.hpp" using namespace eddic; mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) { //Nothing } mtac::Loop::iterator mtac::Loop::begin(){ return m_blocks.begin(); } mtac::Loop::iterator mtac::Loop::end(){ return m_blocks.begin(); } int mtac::Loop::estimate(){ return m_estimate; } void mtac::Loop::set_estimate(int estimate){ this->m_estimate = estimate; } mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){ return loop->end(); } mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){ return loop->begin(); } std::set<mtac::basic_block_p>& mtac::Loop::blocks(){ return m_blocks; }
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "mtac/Loop.hpp" #include "mtac/basic_block.hpp" using namespace eddic; mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) { //Nothing } mtac::Loop::iterator mtac::Loop::begin(){ return m_blocks.begin(); } mtac::Loop::iterator mtac::Loop::end(){ return m_blocks.end(); } int mtac::Loop::estimate(){ return m_estimate; } void mtac::Loop::set_estimate(int estimate){ this->m_estimate = estimate; } mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){ return loop->begin(); } mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){ return loop->end(); } std::set<mtac::basic_block_p>& mtac::Loop::blocks(){ return m_blocks; }
Add missing includes for Windows
#include <turbodbc/time_helpers.h> #include <sql.h> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> namespace turbodbc { boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0}); int64_t timestamp_to_microseconds(char const * data_pointer) { auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer); intptr_t const microseconds = sql_ts.fraction / 1000; boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day}, {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds}); return (ts - timestamp_epoch).total_microseconds(); } boost::gregorian::date const date_epoch(1970, 1, 1); intptr_t date_to_days(char const * data_pointer) { auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer); boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day); return (date - date_epoch).days(); } }
#include <turbodbc/time_helpers.h> #ifdef _WIN32 #include <windows.h> #endif #include <cstring> #include <sql.h> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> namespace turbodbc { boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0}); int64_t timestamp_to_microseconds(char const * data_pointer) { auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer); intptr_t const microseconds = sql_ts.fraction / 1000; boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day}, {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds}); return (ts - timestamp_epoch).total_microseconds(); } boost::gregorian::date const date_epoch(1970, 1, 1); intptr_t date_to_days(char const * data_pointer) { auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer); boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day); return (date - date_epoch).days(); } }
Remove an include not needed
#include <iostream> #include <QtConcurrent> #include <QCoreApplication> #include <stdint.h> #include <pulse/simple.h> #include "DBMeter.hpp" using namespace std; DBMeter::DBMeter() { settings.setCodec("audio/PCM"); settings.setChannelCount(1); settings.setSampleRate(16000); recorder = new QAudioRecorder(this); recorder->setAudioInput("pulseaudio:"); recorder->setAudioSettings(settings); QUrl url = QString("/dev/null"); recorder->setOutputLocation(url); probe = new QAudioProbe(this); connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer))); probe->setSource(recorder); } DBMeter::~DBMeter() { delete recorder; } void DBMeter::Start() { recorder->record(); } void DBMeter::Stop() { recorder->stop(); } void DBMeter::AudioCb(const QAudioBuffer &buffer) { const int16_t *ptr = buffer.constData<int16_t>(); uint16_t maxVal = 0, val; int nbFrame = buffer.sampleCount(); while (nbFrame--) { val = abs(*ptr++); if (val > maxVal) maxVal = val; } cerr << " maxVal " << maxVal << endl; }
#include <iostream> #include <QtConcurrent> #include <QCoreApplication> #include <stdint.h> #include "DBMeter.hpp" using namespace std; DBMeter::DBMeter() { settings.setCodec("audio/PCM"); settings.setChannelCount(1); settings.setSampleRate(16000); recorder = new QAudioRecorder(this); recorder->setAudioInput("pulseaudio:"); recorder->setAudioSettings(settings); QUrl url = QString("/dev/null"); recorder->setOutputLocation(url); probe = new QAudioProbe(this); connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer))); probe->setSource(recorder); } DBMeter::~DBMeter() { delete recorder; } void DBMeter::Start() { recorder->record(); } void DBMeter::Stop() { recorder->stop(); } void DBMeter::AudioCb(const QAudioBuffer &buffer) { const int16_t *ptr = buffer.constData<int16_t>(); uint16_t maxVal = 0, val; int nbFrame = buffer.sampleCount(); while (nbFrame--) { val = abs(*ptr++); if (val > maxVal) maxVal = val; } cerr << " maxVal " << maxVal << endl; }
Fix compiler use wrong version std::remove
// Copyright 2016 Zheng Xian Qiu #include "Seeker.h" namespace Seeker { vector<ISubscriber*> Event::subscribers; void Event::Refresh() { SDL_Event ev; while(SDL_PollEvent(&ev)) { switch(ev.type) { case SDL_KEYDOWN: Dispatch(EventType::Key); break; case SDL_QUIT: Dispatch(EventType::Quit); break; case SDL_MOUSEBUTTONDOWN: Dispatch(EventType::Mouse); break; } } } void Event::On(ISubscriber* event) { if(Exists(event)) return; subscribers.push_back(event); } void Event::Off(ISubscriber* event) { if(Exists(event)) { subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end()); } } bool Event::Exists(ISubscriber* event) { for(auto &current : subscribers) { if(current == event) { return true; } } return false; } void Event::Dispatch(const EventType type) { for(auto &current : subscribers) { current->OnEvent(type); } } }
// Copyright 2016 Zheng Xian Qiu #include "Seeker.h" #include<algorithm> // Prevent use C++17 std::remove namespace Seeker { vector<ISubscriber*> Event::subscribers; void Event::Refresh() { SDL_Event ev; while(SDL_PollEvent(&ev)) { switch(ev.type) { case SDL_KEYDOWN: Dispatch(EventType::Key); break; case SDL_QUIT: Dispatch(EventType::Quit); break; case SDL_MOUSEBUTTONDOWN: Dispatch(EventType::Mouse); break; } } } void Event::On(ISubscriber* event) { if(Exists(event)) return; subscribers.push_back(event); } void Event::Off(ISubscriber* event) { if(Exists(event)) { subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end()); } } bool Event::Exists(ISubscriber* event) { for(auto &current : subscribers) { if(current == event) { return true; } } return false; } void Event::Dispatch(const EventType type) { for(auto &current : subscribers) { current->OnEvent(type); } } }
Fix bug in ECOC OvO encoder
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Chiyuan Zhang * Copyright (C) 2012 Chiyuan Zhang */ #include <shogun/multiclass/ecoc/ECOCOVOEncoder.h> using namespace shogun; SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes) { SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true); code_book.zero(); int32_t k=0; for (int32_t i=0; i < num_classes; ++i) { for (int32_t j=0; j < num_classes; ++j) { code_book(k, i) = 1; code_book(k, j) = -1; k++; } } return code_book; }
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Chiyuan Zhang * Copyright (C) 2012 Chiyuan Zhang */ #include <shogun/multiclass/ecoc/ECOCOVOEncoder.h> using namespace shogun; SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes) { SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true); code_book.zero(); int32_t k=0; for (int32_t i=0; i < num_classes; ++i) { for (int32_t j=i+1; j < num_classes; ++j) { code_book(k, i) = 1; code_book(k, j) = -1; k++; } } return code_book; }
Call glewInit before trying to load shaders
// Standard includes #include <stdlib.h> // OpenGL includes #include <GL/glew.h> #include <GLFW/glfw3.h> #include "fluidDynamics.h" void simulate() { // We ping-pong back and forth between two buffers on the GPU // u = advect(u); // u = diffuse(u); // u = addForces(u); // // p = computePressure(u); // u = subtractPressureGradient(u, p); } int main(int argc, char** argv) { GLFWmonitor* monitor = glfwGetPrimaryMonitor(); GLFWwindow* window; if (!glfwInit()) { return -1; } window = glfwCreateWindow(640, 480, "FlickFlow", monitor, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); while (!glfwWindowShouldClose(window)) { /* Render here */ glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return EXIT_SUCCESS; }
// Standard includes #include <stdlib.h> // OpenGL includes #include <GL/glew.h> #include <GLFW/glfw3.h> #include "fluidDynamics.h" #define DEFAULT_WIDTH 640 #define DEFAULT_HEIGHT 480 void simulate() { // We ping-pong back and forth between two buffers on the GPU // u = advect(u); // u = diffuse(u); // u = addForces(u); // // p = computePressure(u); // u = subtractPressureGradient(u, p); } int main(int argc, char** argv) { GLFWmonitor* monitor = glfwGetPrimaryMonitor(); GLFWwindow* window; if (!glfwInit()) { return -1; } window = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "FlickFlow", monitor, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { return -1; } printf("%s", glGetString(GL_VERSION)); loadShaders(); while (!glfwWindowShouldClose(window)) { /* Render here */ glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return EXIT_SUCCESS; }
Add newlines to control commands.
#include "serialutil.h" #include "usbutil.h" #include "listener.h" #include "signals.h" #include "log.h" #define VERSION_CONTROL_COMMAND 0x80 #define RESET_CONTROL_COMMAND 0x81 // USB #define DATA_ENDPOINT 1 extern void reset(); void setup(); void loop(); const char* VERSION = "2.0-pre"; #ifdef __CHIPKIT__ SerialDevice serialDevice = {&Serial1}; #else SerialDevice serialDevice; #endif // __CHIPKIT__ UsbDevice USB_DEVICE = { #ifdef CHIPKIT USBDevice(usbCallback), #endif // CHIPKIT DATA_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES}; Listener listener = {&USB_DEVICE, &serialDevice}; int main(void) { #ifdef CHIPKIT init(); #endif setup(); for (;;) loop(); return 0; } bool handleControlRequest(uint8_t request) { switch(request) { case VERSION_CONTROL_COMMAND: char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4]; sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet()); debug("Version: %s", combinedVersion); sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion)); return true; case RESET_CONTROL_COMMAND: debug("Resetting..."); reset(); return true; default: return false; } }
#include "serialutil.h" #include "usbutil.h" #include "listener.h" #include "signals.h" #include "log.h" #define VERSION_CONTROL_COMMAND 0x80 #define RESET_CONTROL_COMMAND 0x81 // USB #define DATA_ENDPOINT 1 extern void reset(); void setup(); void loop(); const char* VERSION = "2.0-pre"; #ifdef __CHIPKIT__ SerialDevice serialDevice = {&Serial1}; #else SerialDevice serialDevice; #endif // __CHIPKIT__ UsbDevice USB_DEVICE = { #ifdef CHIPKIT USBDevice(usbCallback), #endif // CHIPKIT DATA_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES}; Listener listener = {&USB_DEVICE, &serialDevice}; int main(void) { #ifdef CHIPKIT init(); #endif setup(); for (;;) loop(); return 0; } bool handleControlRequest(uint8_t request) { switch(request) { case VERSION_CONTROL_COMMAND: char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4]; sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet()); debug("Version: %s\r\n", combinedVersion); sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion)); return true; case RESET_CONTROL_COMMAND: debug("Resetting...\r\n"); reset(); return true; default: return false; } }
Add backend name to AVR Target to enable runtime info to be fed back into TableGen
//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Module.h" #include "llvm/Support/TargetRegistry.h" namespace llvm { Target &getTheAVRTarget() { static Target TheAVRTarget; return TheAVRTarget; } } extern "C" void LLVMInitializeAVRTargetInfo() { llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr", "Atmel AVR Microcontroller"); }
//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Module.h" #include "llvm/Support/TargetRegistry.h" namespace llvm { Target &getTheAVRTarget() { static Target TheAVRTarget; return TheAVRTarget; } } extern "C" void LLVMInitializeAVRTargetInfo() { llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr", "Atmel AVR Microcontroller", "AVR"); }
ADD fullscreen option for sfml window, press F atm
#include <SFML\Window.hpp> int main() { sf::Window window(sf::VideoMode(800, 600), "SFML works!"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.display(); } return 0; }
#include <SFML\Window.hpp> int main() { bool fullscreen = false; sf::Window window(sf::VideoMode(800, 600), "SFML works!"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::F) { window.close(); if (fullscreen) { window.create(sf::VideoMode(800, 600), "SFML works!"); fullscreen = false; } else { window.create(sf::VideoMode(800, 600), "SFML works!", sf::Style::Fullscreen); fullscreen = true; } } else if (event.key.code == sf::Keyboard::Escape) { window.close(); } } } window.display(); } return 0; }
Add secure comparator C++ wrapper test
/* * Copyright (c) 2015 Cossack Labs Limited * * 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 <common/sput.h> #include "secure_cell_test.hpp" #include "secure_message_test.hpp" #include "secure_session_test.hpp" int main(){ sput_start_testing(); themispp::secure_cell_test::run_secure_cell_test(); themispp::secure_message_test::run_secure_message_test(); themispp::secure_session_test::run_secure_session_test(); sput_finish_testing(); return sput_get_return_value(); }
/* * Copyright (c) 2015 Cossack Labs Limited * * 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 <common/sput.h> #include "secure_cell_test.hpp" #include "secure_message_test.hpp" #include "secure_session_test.hpp" #include "secure_comparator_test.hpp" int main(){ sput_start_testing(); themispp::secure_cell_test::run_secure_cell_test(); themispp::secure_message_test::run_secure_message_test(); themispp::secure_session_test::run_secure_session_test(); themispp::secure_session_test::run_secure_comparator_test(); sput_finish_testing(); return sput_get_return_value(); }
Support Python-level Device ctor and comparison
#include "xchainer/python/device.h" #include <sstream> #include "xchainer/device.h" namespace xchainer { namespace py = pybind11; // standard convention void InitXchainerDevice(pybind11::module& m) { py::class_<Device>(m, "Device").def("__repr__", [](Device device) { std::ostringstream os; os << "<Device " << device.name << ">"; return os.str(); }); m.def("get_current_device", []() { return GetCurrentDevice(); }); m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); }); m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); }); } } // namespace xchainer
#include "xchainer/python/device.h" #include <sstream> #include "xchainer/device.h" namespace xchainer { namespace py = pybind11; // standard convention void InitXchainerDevice(pybind11::module& m) { py::class_<Device>(m, "Device") .def(py::init(&MakeDevice)) .def("__eq__", py::overload_cast<const Device&, const Device&>(&operator==)) .def("__ne__", py::overload_cast<const Device&, const Device&>(&operator!=)) .def("__repr__", [](Device device) { std::ostringstream os; os << "<Device " << device.name << ">"; return os.str(); }); m.def("get_current_device", []() { return GetCurrentDevice(); }); m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); }); m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); }); } } // namespace xchainer
Improve the dependent nested-name-specifier test a bit
// RUN: clang-cc -fsyntax-only -verify %s struct add_pointer { template<typename T> struct apply { typedef T* type; }; }; struct add_reference { template<typename T> struct apply { typedef T& type; // expected-error{{cannot form a reference to 'void'}} }; }; template<typename MetaFun, typename T> struct apply1 { typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}} }; int i; apply1<add_pointer, int>::type ip = &i; apply1<add_reference, int>::type ir = i; apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}} void test() { apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \ // FIXME: expected-error{{unexpected type name 'type': expected expression}} }
// RUN: clang-cc -fsyntax-only -verify %s struct add_pointer { template<typename T> struct apply { typedef T* type; }; }; struct add_reference { template<typename T> struct apply { typedef T& type; // expected-error{{cannot form a reference to 'void'}} }; }; struct bogus { struct apply { typedef int type; }; }; template<typename MetaFun, typename T> struct apply1 { typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}} \ // expected-error{{'apply' following the 'template' keyword does not refer to a template}} \ // FIXME: expected-error{{type 'MetaFun::template apply<int>' cannot be used prior to '::' because it has no members}} }; int i; apply1<add_pointer, int>::type ip = &i; apply1<add_reference, int>::type ir = i; apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}} void test() { apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \ // FIXME: expected-error{{unexpected type name 'type': expected expression}} apply1<bogus, int>::type t2; // expected-note{{in instantiation of template class 'struct apply1<struct bogus, int>' requested here}} \ // FIXME: expected-error{{unexpected type name 'type': expected expression}} }
Use the new argument ordering for mx_cprng_draw
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(TARGET_OS_FUCHSIA) #include "bin/crypto.h" #include <magenta/syscalls.h> namespace dart { namespace bin { bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) { intptr_t read = 0; while (read < count) { const intptr_t remaining = count - read; const intptr_t len = (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN : remaining; const mx_ssize_t res = mx_cprng_draw(buffer + read, len); if (res == ERR_INVALID_ARGS) { return false; } read += res; } return true; } } // namespace bin } // namespace dart #endif // defined(TARGET_OS_FUCHSIA)
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(TARGET_OS_FUCHSIA) #include "bin/crypto.h" #include <magenta/syscalls.h> namespace dart { namespace bin { bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) { intptr_t read = 0; while (read < count) { const intptr_t remaining = count - read; const intptr_t len = (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN : remaining; mx_size_t res = 0; const mx_status_t status = mx_cprng_draw(buffer + read, len, &res); if (status != NO_ERROR) { return false; } read += res; } return true; } } // namespace bin } // namespace dart #endif // defined(TARGET_OS_FUCHSIA)
Adjust Draw node bounds for paint
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSGDraw.h" #include "SkSGGeometryNode.h" #include "SkSGInvalidationController.h" #include "SkSGPaintNode.h" namespace sksg { Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint) : fGeometry(std::move(geometry)) , fPaint(std::move(paint)) { fGeometry->addInvalReceiver(this); fPaint->addInvalReceiver(this); } Draw::~Draw() { fGeometry->removeInvalReceiver(this); fPaint->removeInvalReceiver(this); } void Draw::onRender(SkCanvas* canvas) const { fGeometry->draw(canvas, fPaint->makePaint()); } SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) { SkASSERT(this->hasInval()); // TODO: adjust bounds for paint const auto bounds = fGeometry->revalidate(ic, ctm); fPaint->revalidate(ic, ctm); return bounds; } } // namespace sksg
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSGDraw.h" #include "SkSGGeometryNode.h" #include "SkSGInvalidationController.h" #include "SkSGPaintNode.h" namespace sksg { Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint) : fGeometry(std::move(geometry)) , fPaint(std::move(paint)) { fGeometry->addInvalReceiver(this); fPaint->addInvalReceiver(this); } Draw::~Draw() { fGeometry->removeInvalReceiver(this); fPaint->removeInvalReceiver(this); } void Draw::onRender(SkCanvas* canvas) const { fGeometry->draw(canvas, fPaint->makePaint()); } SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) { SkASSERT(this->hasInval()); auto bounds = fGeometry->revalidate(ic, ctm); fPaint->revalidate(ic, ctm); const auto& paint = fPaint->makePaint(); SkASSERT(paint.canComputeFastBounds()); return paint.computeFastBounds(bounds, &bounds); } } // namespace sksg
Allow user to specify the initial painter on the commandline for gloperate-viewer
// [TODO] This belongs into the cmake platform files!! #if defined(WIN32) && !defined(_DEBUG) #pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup") #endif #include <memory> #include <gloperate/ext-includes-begin.h> #include <widgetzeug/dark_fusion_style.hpp> #include <gloperate/ext-includes-end.h> #include <gloperate-qt/viewer/Viewer.h> #include "Application.h" int main(int argc, char * argv[]) { Application app(argc, argv); widgetzeug::enableDarkFusionStyle(); gloperate_qt::Viewer viewer; viewer.show(); viewer.loadPainter("Logo"); return app.exec(); }
// [TODO] This belongs into the cmake platform files!! #if defined(WIN32) && !defined(_DEBUG) #pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup") #endif #include <memory> #include <gloperate/ext-includes-begin.h> #include <widgetzeug/dark_fusion_style.hpp> #include <gloperate/ext-includes-end.h> #include <gloperate-qt/viewer/Viewer.h> #include "Application.h" int main(int argc, char * argv[]) { Application app(argc, argv); widgetzeug::enableDarkFusionStyle(); gloperate_qt::Viewer viewer; viewer.show(); std::string painterName = (argc > 1) ? argv[1] : "Logo"; viewer.loadPainter(painterName); return app.exec(); }
Remove unnecessary "this->" (style issue)
#include "ofxShadersFX.h" namespace ofxShadersFX { Shader::Shader(ShaderType p_type) { setShaderType(p_type); } void Shader::begin() { // The shader needs reload if not loaded // or if modifications in attributes occurred since last frame if (!m_shader.isLoaded() || m_needsReload) { reload(); m_needsReload = false; } m_shader.begin(); } void Shader::end() { m_shader.end(); } ShaderType Shader::shaderType() const { return m_type; } void Shader::setShaderType(ShaderType p_type) { m_type = p_type; } void Shader::reload() { this->m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER)); this->m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER)); if(ofIsGLProgrammableRenderer()) { this->m_shader.bindDefaults(); } this->m_shader.linkProgram(); } }
// The MIT License (MIT) // Copyright (c) 2016 Alexandre Baron (Scylardor) // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "ofxShadersFX.h" namespace ofxShadersFX { Shader::Shader(ShaderType p_type) { setShaderType(p_type); } void Shader::begin() { // The shader needs reload if not loaded // or if modifications in attributes occurred since last frame if (!m_shader.isLoaded() || m_needsReload) { reload(); m_needsReload = false; } m_shader.begin(); } void Shader::end() { m_shader.end(); } ShaderType Shader::shaderType() const { return m_type; } void Shader::setShaderType(ShaderType p_type) { m_type = p_type; } void Shader::reload() { m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER)); m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER)); if(ofIsGLProgrammableRenderer()) { m_shader.bindDefaults(); } m_shader.linkProgram(); } }
Add comments in the source code
#include <cstdio> #include <algorithm> using namespace std; const int NMAX = 100000, PASI_INFINITI = NMAX*2; int v[NMAX], nVector, sizeOfCheat; int back(int pozitieCurenta, int cheatsAvailable) { if (pozitieCurenta > nVector) return PASI_INFINITI; if (pozitieCurenta == nVector) return 0; int sol = min(back(pozitieCurenta+1, cheatsAvailable) + 1, back(pozitieCurenta+v[pozitieCurenta], cheatsAvailable) + 1); if (cheatsAvailable) sol = min(sol, back(pozitieCurenta+sizeOfCheat, cheatsAvailable-1) + 1); return sol; } int main() { freopen("teleport.in", "r", stdin); freopen("teleport.out", "w", stdout); int nCheats; scanf("%d%d%d", &nVector, &nCheats, &sizeOfCheat); for(int i=0; i<nVector; i++) scanf("%d", &v[i]); printf("%d\n", back(0, nCheats)); return 0; }
// @palcu // InfoOltenia 2015, teleport, backtracking #include <cstdio> #include <algorithm> using namespace std; const int NMAX = 100000, PASI_INFINITI = NMAX*2; int v[NMAX], nVector, sizeOfCheat; int back(int pozitieCurenta, int cheatsAvailable) { if (pozitieCurenta > nVector) return PASI_INFINITI; if (pozitieCurenta == nVector) return 0; int sol = min(back(pozitieCurenta+1, cheatsAvailable) + 1, back(pozitieCurenta+v[pozitieCurenta], cheatsAvailable) + 1); if (cheatsAvailable) sol = min(sol, back(pozitieCurenta+sizeOfCheat, cheatsAvailable-1) + 1); return sol; } int main() { freopen("teleport.in", "r", stdin); freopen("teleport.out", "w", stdout); int nCheats; scanf("%d%d%d", &nVector, &nCheats, &sizeOfCheat); for(int i=0; i<nVector; i++) scanf("%d", &v[i]); printf("%d\n", back(0, nCheats)); return 0; }
Make my test case test what it meant to
// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem -analyzer-experimental-checks -verify %s struct X0 { }; bool operator==(const X0&, const X0&); // PR7287 struct test { int a[2]; }; void t2() { test p = {{1,2}}; test q; q = p; } bool PR7287(X0 a, X0 b) { return a == b; }
// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem -analyzer-experimental-checks -verify %s struct X0 { }; bool operator==(const X0&, const X0&); // PR7287 struct test { int a[2]; }; void t2() { test p = {{1,2}}; test q; q = p; } bool PR7287(X0 a, X0 b) { return operator==(a, b); }
Fix problems with multiple tips
/* Copyright 2012 Dietrich Epp <depp@zdome.net> */ #include "level.hpp" #include "gamescreen.hpp" using namespace LD24; Level::~Level() { } void Level::nextLevel() { screen.nextLevel(); } void Level::setTipFlags(unsigned flags) { if (flags == m_tipflag) return; levelTips.clear(); for (int i = 0; i < 32; ++i) { if (flags & (1u << i)) levelTips.push_back(m_allTips[i]); } } void Level::addTip(int index) { setTipFlags(m_tipflag | (1u << index)); } void Level::removeTip(int index) { setTipFlags(m_tipflag & ~(1u << index)); }
/* Copyright 2012 Dietrich Epp <depp@zdome.net> */ #include "level.hpp" #include "gamescreen.hpp" using namespace LD24; Level::~Level() { } void Level::nextLevel() { screen.nextLevel(); } void Level::setTipFlags(unsigned flags) { if (flags == m_tipflag) return; levelTips.clear(); for (int i = 0; i < 32; ++i) { if (flags & (1u << i)) levelTips.push_back(m_allTips[i]); } m_tipflag = flags; } void Level::addTip(int index) { setTipFlags(m_tipflag | (1u << index)); } void Level::removeTip(int index) { setTipFlags(m_tipflag & ~(1u << index)); }
Add double-quote delimiters to args.
// Rel native launcher for Linux. #include <iostream> #include <cstdlib> #include <unistd.h> #include <libgen.h> #include <string> #include <fstream> #include <streambuf> int main(int argc, char **argv) { // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found char *dir = dirname(argv[0]); chdir(dir); // Read the ini file std::string iniFileName("lib/Rel.ini"); std::ifstream configfile(iniFileName); std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>()); // Empty or no ini file? if (cmd.length() == 0) { std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl; return 10; } // Include command-line args. std::string args(""); for (int i = 1; i < argc; i++) args += std::string(" ") + std::string(argv[i]); setenv("SWT_GTK3", "0", 1); return system((cmd + args).c_str()); }
// Rel native launcher for Linux. #include <iostream> #include <cstdlib> #include <unistd.h> #include <libgen.h> #include <string> #include <fstream> #include <streambuf> int main(int argc, char **argv) { // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found char *dir = dirname(argv[0]); chdir(dir); // Read the ini file std::string iniFileName("lib/Rel.ini"); std::ifstream configfile(iniFileName); std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>()); // Empty or no ini file? if (cmd.length() == 0) { std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl; return 10; } // Include command-line args. std::string args(""); for (int i = 1; i < argc; i++) args += std::string(" \"") + std::string(argv[i]) + std::string("\""); setenv("SWT_GTK3", "0", 1); return system((cmd + args).c_str()); }
Initialize all members of ContextMenuParams in the ctor
// 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 "content/public/common/context_menu_params.h" namespace content { const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max; CustomContextMenuContext::CustomContextMenuContext() : is_pepper_menu(false), request_id(0), render_widget_id(kCurrentRenderWidget) { } ContextMenuParams::ContextMenuParams() : media_type(blink::WebContextMenuData::MediaTypeNone), x(0), y(0), has_image_contents(true), frame_id(0), media_flags(0), misspelling_hash(0), speech_input_enabled(false), spellcheck_enabled(false), is_editable(false), writing_direction_default( blink::WebContextMenuData::CheckableMenuItemDisabled), writing_direction_left_to_right( blink::WebContextMenuData::CheckableMenuItemEnabled), writing_direction_right_to_left( blink::WebContextMenuData::CheckableMenuItemEnabled), edit_flags(0), referrer_policy(blink::WebReferrerPolicyDefault) { } ContextMenuParams::~ContextMenuParams() { } } // namespace content
// 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 "content/public/common/context_menu_params.h" namespace content { const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max; CustomContextMenuContext::CustomContextMenuContext() : is_pepper_menu(false), request_id(0), render_widget_id(kCurrentRenderWidget) { } ContextMenuParams::ContextMenuParams() : media_type(blink::WebContextMenuData::MediaTypeNone), x(0), y(0), has_image_contents(true), frame_id(0), media_flags(0), misspelling_hash(0), speech_input_enabled(false), spellcheck_enabled(false), is_editable(false), writing_direction_default( blink::WebContextMenuData::CheckableMenuItemDisabled), writing_direction_left_to_right( blink::WebContextMenuData::CheckableMenuItemEnabled), writing_direction_right_to_left( blink::WebContextMenuData::CheckableMenuItemEnabled), edit_flags(0), referrer_policy(blink::WebReferrerPolicyDefault), source_type(ui::MENU_SOURCE_NONE) { } ContextMenuParams::~ContextMenuParams() { } } // namespace content
Fix test failure from r351495
// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17 void foo(int* a, int *b) { a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from 'long'}} } template<typename T> T declval(); struct true_type { static const bool value = true; }; struct false_type { static const bool value = false; }; template<bool, typename T, typename U> struct select { using type = T; }; template<typename T, typename U> struct select<false, T, U> { using type = U; }; template<typename T> typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...); template<typename T> false_type test(...); template<typename T> static const auto has_minus_assign = decltype(test<T>())::value; static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}
// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17 void foo(int* a, int *b) { a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from}} } template<typename T> T declval(); struct true_type { static const bool value = true; }; struct false_type { static const bool value = false; }; template<bool, typename T, typename U> struct select { using type = T; }; template<typename T, typename U> struct select<false, T, U> { using type = U; }; template<typename T> typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...); template<typename T> false_type test(...); template<typename T> static const auto has_minus_assign = decltype(test<T>())::value; static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}
Fix PWM period on F3.
#include "variant/pwm_platform.hpp" #include "hal.h" static const PWMConfig motor_pwm_config = { 500000, // 500 kHz PWM clock frequency. 1000, // PWM period 2.0 ms. NULL, // No callback. { {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL} }, // Channel configurations 0,0 // HW dependent }; PWMPlatform::PWMPlatform() { pwmStart(&PWMD8, &motor_pwm_config); palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4)); } void PWMPlatform::set(std::uint8_t ch, float dc) { pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f); pwmEnableChannel(&PWMD8, ch, width); }
#include "variant/pwm_platform.hpp" #include "hal.h" static const PWMConfig motor_pwm_config = { 500000, // 500 kHz PWM clock frequency. 2000, // PWM period 2.0 ms. NULL, // No callback. { {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL} }, // Channel configurations 0,0 // HW dependent }; PWMPlatform::PWMPlatform() { pwmStart(&PWMD8, &motor_pwm_config); palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4)); } void PWMPlatform::set(std::uint8_t ch, float dc) { pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f); pwmEnableChannel(&PWMD8, ch, width); }
Update tests - allow checking the output
#include "yebash.hpp" #include "History.hpp" #include "catch.hpp" #include <sstream> using namespace yb; TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) { std::stringstream ss; History history; history.read(ss); HistorySuggestion suggestion(history); auto c = yebash(suggestion, 'a'); REQUIRE(c == 'a'); }
#include "yebash.hpp" #include "History.hpp" #include "catch.hpp" #include <sstream> using namespace yb; TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) { std::stringstream ss; std::stringstream output; History history; history.read(ss); HistorySuggestion suggestion(history); Printer printer(output); auto c = yebash(suggestion, printer, 'a'); std::string result{output.str()}; REQUIRE(c == 'a'); REQUIRE(output.str() == ""); }
Replace gui application by core app to run in cli
#include <QTest> #include "mainwindow.h" #include "test-suite.h" QMap<QDateTime, QString> _log; QMap<QString, QString> _md5; mainWindow *_mainwindow; int main(int argc, char *argv[]) { QApplication a(argc, argv); int failed = 0; for (QObject *suite : TestSuite::suites) { int result = QTest::qExec(suite); if (result != 0) { failed++; } } return failed; }
#include <QTest> #include "mainwindow.h" #include "test-suite.h" QMap<QDateTime, QString> _log; QMap<QString, QString> _md5; mainWindow *_mainwindow; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); int failed = 0; for (QObject *suite : TestSuite::suites) { int result = QTest::qExec(suite); if (result != 0) { failed++; } } return failed; }
Set the Thread as inactive when terminating it.
#include "Thread/Unix/ThreadImpl.hh" #include "Thread/ThreadException.hh" namespace LilWrapper { ThreadImpl::ThreadImpl(Thread *thread) { this->_isActive = pthread_create(&this->_thread, NULL, &ThreadImpl::entryPoint, thread) == 0; if (!this->_isActive) throw ThreadException("Thread Exception: " "Error while creating the Thread."); } ThreadImpl::~ThreadImpl() { if (this->_isActive) terminate(); } void ThreadImpl::wait() { if (this->_isActive) { if (pthread_equal(pthread_self(), this->_thread) != 0) throw ThreadException("Thread Exception: " "A thread cannot wait for itself."); pthread_join(this->_thread, NULL); } } void ThreadImpl::terminate() { if (this->_isActive) pthread_cancel(this->_thread); } void *ThreadImpl::entryPoint(void *data) { Thread *self = static_cast<Thread *>(data); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); self->run(); return (NULL); } }
#include "Thread/Unix/ThreadImpl.hh" #include "Thread/ThreadException.hh" namespace LilWrapper { ThreadImpl::ThreadImpl(Thread *thread) { this->_isActive = pthread_create(&this->_thread, NULL, &ThreadImpl::entryPoint, thread) == 0; if (!this->_isActive) throw ThreadException("Thread Exception: " "Error while creating the Thread."); } ThreadImpl::~ThreadImpl() { if (this->_isActive) terminate(); } void ThreadImpl::wait() { if (this->_isActive) { if (pthread_equal(pthread_self(), this->_thread) != 0) throw ThreadException("Thread Exception: " "A thread cannot wait for itself."); pthread_join(this->_thread, NULL); } } void ThreadImpl::terminate() { if (this->_isActive) pthread_cancel(this->_thread); this->_isActive = false; } void *ThreadImpl::entryPoint(void *data) { Thread *self = static_cast<Thread *>(data); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); self->run(); return (NULL); } }
Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs.
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" static const size_t kBufferSize = 256; #define LOG_TAG "skia" #include <android/log.h> void SkDebugf(const char format[], ...) { va_list args; va_start(args, format); __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args); va_end(args); }
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" static const size_t kBufferSize = 256; #define LOG_TAG "skia" #include <android/log.h> static bool gSkDebugToStdOut = false; extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) { gSkDebugToStdOut = debugToStdOut; } void SkDebugf(const char format[], ...) { va_list args; va_start(args, format); __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args); // Print debug output to stdout as well. This is useful for command // line applications (e.g. skia_launcher) if (gSkDebugToStdOut) { vprintf(format, args); } va_end(args); }
Initialize FileSystem and ResourcesCache from config file
/* * Copyright (c) 2016 Lech Kulina * * This file is part of the Realms Of Steel. * For conditions of distribution and use, see copyright details in the LICENSE file. */ #include <cstdlib> #include <boost/property_tree/info_parser.hpp> #include <application/Logger.h> #include <application/Application.h> #include <resources/ResourceCache.h> int main() { int exitCode = EXIT_FAILURE; ros::PropertyTree config; boost::property_tree::read_info("Config.info", config); if (!ros::Logger::initInstance(config.get_child("Logger")) || !ros::Application::initInstance(config.get_child("application")) || !ros::ResourceCache::initInstance(config.get_child("resources"))) { return exitCode; } ros::ApplicationPtr application = ros::Application::getInstance(); if (application) { exitCode = application->run(); application->uninit(); } return exitCode; }
/* * Copyright (c) 2016 Lech Kulina * * This file is part of the Realms Of Steel. * For conditions of distribution and use, see copyright details in the LICENSE file. */ #include <cstdlib> #include <boost/property_tree/info_parser.hpp> #include <application/Logger.h> #include <application/Application.h> #include <resources/FileSystem.h> #include <resources/ResourcesCache.h> int main() { int exitCode = EXIT_FAILURE; ros::PropertyTree config; boost::property_tree::read_info("Config.info", config); if (!ros::Logger::initInstance(config.get_child("Logger")) || !ros::Application::initInstance(config.get_child("application")) || !ros::FileSystem::initInstance(config.get_child("file-system")) || !ros::ResourcesCache::initInstance(config.get_child("resources-cache"))) { return exitCode; } ros::ApplicationPtr application = ros::Application::getInstance(); if (application) { exitCode = application->run(); application->uninit(); } return exitCode; }
Use fscanf to read in file.
#include <iostream> #include <cstlib> #include <vector>
#include <iostream> #include <cstdlib> #include <vector> #include <bitset> #include <cstring> #include <string> #include <fstream> #include <cstdio> #include "rand.h" using namespace std; class individual { public: int key[26]; float fit; }; // user functions go here int main() { // get cipher from cin string cipher, tmp; while( getline( cin, tmp ) ) { cipher.append( tmp ); } // read in freq.txt FILE *freq = fopen( "freq.txt", "r" ); char eng1[488], eng2[488]; float engnum[488]; // check if file is open if( freq != NULL ) { for( int i = 0; i < 488; i++ ) { fscanf( freq, "%c%c %f ", &eng1[i], &eng2[i], &engnum[i] ); // eng1[i] = fgetc( freq ); //eng2[i] = fgetc( freq ); cout << eng1[i] << eng2[i] << " " << engnum[i] <<endl; } } // create cipher count tables char cipher1[488], cipher2[488]; float ciphernum[488]; for( int i = 0; i < cipher.size(); i++ ){ } } // end main
Add verification to Person constructor
#include <stdexcept> #include "Person.h" Person::Person(std::string name) { if(name.empty()){ throw std::invalid_argument("Name can not be empty."); } this->name = name; };
#include <stdexcept> #include "Person.h" Person::Person(std::string name) { if(name.empty()){ throw std::invalid_argument("Name cannot be empty."); } this->name = name; };
Make ASSERTs in helper functions fail the parent testcase
#include "gtest/gtest.h" int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include "gtest/gtest.h" class ThrowListener : public testing::EmptyTestEventListener { void OnTestPartResult(const testing::TestPartResult& result) override { if (result.type() == testing::TestPartResult::kFatalFailure) { throw testing::AssertionException(result); } } }; int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); ::testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); return RUN_ALL_TESTS(); }
Allow set_char when char is the same - updating words
#include "BoardMarker.hpp" BoardMarker::BoardMarker (void) : m(NONE), c(' ') {} bool BoardMarker::apply_modifier(Modifier& m) { if (this->m != NONE) { return false; } this->m = m; return true; } bool BoardMarker::set_char(char& c) { if (this->c != ' ') { return false; } this->c = toupper(c); return true; } void BoardMarker::print_marker(void) { string pre = " "; string col = ""; string post = " "; if (this->m != NONE) { pre = " \033["; post = "\033[0m "; switch (this->m) { case DOUBLE_L: col = "1;43;37m"; break; case DOUBLE_W: col = "1;42;37m"; break; case TRIPLE_L: col = "1;44;37m"; break; case TRIPLE_W: col = "1;41;37m"; break; case NONE: cout << "Shouldn't reach this line!" << endl; } } cout << pre << col << this->c << post; }
#include "BoardMarker.hpp" BoardMarker::BoardMarker (void) : m(NONE), c(' ') {} bool BoardMarker::apply_modifier(Modifier& m) { if (this->m != NONE) { return false; } this->m = m; return true; } bool BoardMarker::set_char(char& c) { if (this->c != ' ') { return this->c == c; } this->c = toupper(c); return true; } void BoardMarker::print_marker(void) { string pre = " "; string col = ""; string post = " "; if (this->m != NONE) { pre = " \033["; post = "\033[0m "; switch (this->m) { case DOUBLE_L: col = "1;43;37m"; break; case DOUBLE_W: col = "1;42;37m"; break; case TRIPLE_L: col = "1;44;37m"; break; case TRIPLE_W: col = "1;41;37m"; break; case NONE: cout << "Shouldn't reach this line!" << endl; } } cout << pre << col << this->c << post; }
Fix win_aura build enabling GetHotSpotDeltaY() in aura too.
// 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/tabs/dock_info.h" #include "chrome/browser/ui/views/tabs/tab.h" #include "build/build_config.h" #if !defined(OS_WIN) // static int DockInfo::GetHotSpotDeltaY() { return Tab::GetMinimumUnselectedSize().height() - 1; } #endif
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/tabs/dock_info.h" #include "chrome/browser/ui/views/tabs/tab.h" #include "build/build_config.h" #if defined(USE_AURA) || defined(USE_ASH) || defined(OS_CHROMEOS) // static int DockInfo::GetHotSpotDeltaY() { return Tab::GetMinimumUnselectedSize().height() - 1; } #endif
Add additional 'UNSUPPORTED' to the test case.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // UNSUPPORTED: c++98, c++03 // <future> // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(F&& f, Args&&... args); // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(launch policy, F&& f, Args&&... args); #include <future> #include <atomic> #include <memory> #include <cassert> #include "test_macros.h" int foo (int x) { return x; } int main () { std::async( foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // UNSUPPORTED: clang-3.3, clang-3.4, clang-3.5, clang-3.6, clang-3.7, clang-3.8 // <future> // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(F&& f, Args&&... args); // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(launch policy, F&& f, Args&&... args); #include <future> #include <atomic> #include <memory> #include <cassert> #include "test_macros.h" int foo (int x) { return x; } int main () { std::async( foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} }
Add a test to verify that -flimit-debug-info is working in some way.
// RUN: %clang -emit-llvm -g -S %s -o - | FileCheck %s // TAG_member is used to encode debug info for 'z' in A. // CHECK: TAG_member class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; }
// RUN: %clang -emit-llvm -g -S %s -o - | FileCheck %s // TAG_member is used to encode debug info for 'z' in A. // CHECK: TAG_member class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; } // Verify that we're not emitting a full definition of B in limit debug mode. // RUN: %clang -emit-llvm -g -flimit-debug-info -S %s -o - | FileCheck %s // CHECK-NOT: TAG_member class B { public: int y; }; extern int bar(B *b); int baz(B *b) { return bar(b); }
Make a more robust streamer
#include <opencv2/opencv.hpp> #include <unistd.h> int main(int argc, char** argv){ if(argc!=2){ std::cout << "Nope.\n"; return -1; } cv::VideoCapture _capture(CV_CAP_OPENNI); std::cout << "Started streaming data to main system..\n"; int c=0; while(1){ cv::Mat depthMap, rgb; usleep(500000); _capture.grab(); _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP); _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE); imwrite(std::string(argv[1])+"/rgb.png", rgb); imwrite(std::string(argv[1])+"/depth.png", depthMap); std::cout << ++c << "\n"; } return 0; }
#include <opencv2/opencv.hpp> #include <opencv/highgui.h> #include <unistd.h> int main(int argc, char** argv){ if(argc!=2){ std::cout << "Nope.\n"; return -1; } cv::VideoCapture _capture(CV_CAP_OPENNI); std::cout << "Started streaming data to main system..\n"; int c=0; cv::namedWindow("DEPTH"); while(1){ cv::Mat depthMap, rgb; usleep(500000); _capture.grab(); _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP); cv::imshow("DEPTH", depthMap); cv::waitKey(1); _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE); cv::imshow("RGB", rgb); cv::waitKey(1); std::string name=std::string(argv[1])+"/"; imwrite(name+"/rgb1.png", rgb); imwrite(name+"/depth1.png", depthMap); system(("mv "+name+"rgb1.png "+name+"rgb.png ; mv "+name+"depth1.png "+name+"depth.png").c_str()); std::cout << ++c << "\n"; } return 0; }
Fix Windows window icon failure.
/* This file is part of Fabula. Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com> Fabula is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Fabula is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Fabula. If not, see <http://www.gnu.org/licenses/>. */ #include "MainWindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication application(argc, argv); application.setApplicationName(QString::fromAscii("Fabula")); application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION)); application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com")); application.setOrganizationName(QString::fromAscii("Mike McQuaid")); #ifdef Q_WS_MAC application.setAttribute(Qt::AA_DontShowIconsInMenus); #else application.setWindowIcon(":/icons/audio-input-microphone.png"); #endif MainWindow mainWindow; mainWindow.show(); return application.exec(); }
/* This file is part of Fabula. Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com> Fabula is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Fabula is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Fabula. If not, see <http://www.gnu.org/licenses/>. */ #include "MainWindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication application(argc, argv); application.setApplicationName(QString::fromAscii("Fabula")); application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION)); application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com")); application.setOrganizationName(QString::fromAscii("Mike McQuaid")); #ifdef Q_WS_MAC application.setAttribute(Qt::AA_DontShowIconsInMenus); #else application.setWindowIcon(QIcon(":/icons/audio-input-microphone.png")); #endif MainWindow mainWindow; mainWindow.show(); return application.exec(); }
Set imageLabel and scrollArea properties
#include "imageviewer.h" #include "ui_imageviewer.h" ImageViewer::ImageViewer(QWidget *parent) : QMainWindow(parent), ui(new Ui::ImageViewer) { ui->setupUi(this); QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg"); ui->imageLabel->setPixmap(QPixmap::fromImage(image)); } ImageViewer::~ImageViewer() { delete ui; }
#include "imageviewer.h" #include "ui_imageviewer.h" ImageViewer::ImageViewer(QWidget *parent) : QMainWindow(parent), ui(new Ui::ImageViewer) { ui->setupUi(this); ui->imageLabel->setBackgroundRole(QPalette::Base); ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); ui->imageLabel->setScaledContents(true); ui->scrollArea->setBackgroundRole(QPalette::Dark); QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg"); ui->imageLabel->setPixmap(QPixmap::fromImage(image)); setWindowTitle(tr("Image Viewer")); } ImageViewer::~ImageViewer() { delete ui; }
Fix missing symbols for RPi
#include <stdio.h> #include <stdarg.h> #include <iostream> #include <fstream> #include <string> #include "platform.h" void logMsg(const char* fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); } std::string stringFromResource(const char* _path) { std::string into; std::ifstream file; std::string buffer; file.open(_path); if(!file.is_open()) { return std::string(); } while(!file.eof()) { getline(file, buffer); into += buffer + "\n"; } file.close(); return into; } unsigned char* bytesFromResource(const char* _path, unsigned int* _size) { std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary); if(!resource.is_open()) { logMsg("Failed to read file at path: %s\n", _path); *_size = 0; return nullptr; } *_size = resource.tellg(); resource.seekg(std::ifstream::beg); char* cdata = (char*) malloc(sizeof(char) * (*_size)); resource.read(cdata, *_size); resource.close(); return reinterpret_cast<unsigned char *>(cdata); }
#include <stdio.h> #include <stdarg.h> #include <iostream> #include <fstream> #include <string> #include "platform.h" void logMsg(const char* fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); } void requestRender() { // TODO: implement non-continuous rendering on RPi } void setContinuousRendering(bool _isContinuous) { // TODO: implement non-continuous rendering on RPi } bool isContinuousRendering() { // TODO: implement non-continuous rendering on RPi } std::string stringFromResource(const char* _path) { std::string into; std::ifstream file; std::string buffer; file.open(_path); if(!file.is_open()) { return std::string(); } while(!file.eof()) { getline(file, buffer); into += buffer + "\n"; } file.close(); return into; } unsigned char* bytesFromResource(const char* _path, unsigned int* _size) { std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary); if(!resource.is_open()) { logMsg("Failed to read file at path: %s\n", _path); *_size = 0; return nullptr; } *_size = resource.tellg(); resource.seekg(std::ifstream::beg); char* cdata = (char*) malloc(sizeof(char) * (*_size)); resource.read(cdata, *_size); resource.close(); return reinterpret_cast<unsigned char *>(cdata); }
Update the test with the schedule input filename.
// STL #include <cassert> #include <iostream> #include <sstream> #include <fstream> #include <string> // DSIM #include <dsim/DSIM_Service.hpp> #include <dsim/config/dsim-paths.hpp> // ///////// M A I N //////////// int main (int argc, char* argv[]) { try { // Output log File std::string lLogFilename ("simulate.log"); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the list of classes/buckets DSIM::DSIM_Service dsimService (logOutputFile); // Perform a simulation dsimService.simulate(); } catch (const std::exception& stde) { std::cerr << "Standard exception: " << stde.what() << std::endl; return -1; } catch (...) { return -1; } return 0; }
// STL #include <cassert> #include <iostream> #include <sstream> #include <fstream> #include <string> // DSIM #include <dsim/DSIM_Service.hpp> #include <dsim/config/dsim-paths.hpp> // ///////// M A I N //////////// int main (int argc, char* argv[]) { try { // Schedule input file name std::string lScheduleInputFilename ("../samples/schedule01.csv"); // Output log File std::string lLogFilename ("simulate.log"); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the list of classes/buckets DSIM::DSIM_Service dsimService (lScheduleInputFilename, logOutputFile); // Perform a simulation dsimService.simulate(); } catch (const std::exception& stde) { std::cerr << "Standard exception: " << stde.what() << std::endl; return -1; } catch (...) { return -1; } return 0; }
Correct compile error on Linux and macOS
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Tasks/SimpleTasks/IncludeTask.hpp> namespace Hearthstonepp::SimpleTasks { TaskID IncludeTask::GetTaskID() const { return TaskID::INCLUDE; } std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType, Player& player) { std::vector<Entity*> entities; switch (entityType) { case EntityType::HERO: entities.emplace_back(player.GetHero()); break; case EntityType::FRIENDS: for (auto& minion : player.GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetHero()); break; case EntityType::ENEMIES: for (auto& minion : player.GetOpponent().GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetOpponent().GetHero()); break; default: throw std::exception("Not implemented"); } return entities; } MetaData IncludeTask::Impl(Player&) { return MetaData::INCLUDE_SUCCESS; } } // namespace Hearthstonepp::SimpleTasks
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Tasks/SimpleTasks/IncludeTask.hpp> #include <stdexcept> namespace Hearthstonepp::SimpleTasks { TaskID IncludeTask::GetTaskID() const { return TaskID::INCLUDE; } std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType, Player& player) { std::vector<Entity*> entities; switch (entityType) { case EntityType::HERO: entities.emplace_back(player.GetHero()); break; case EntityType::FRIENDS: for (auto& minion : player.GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetHero()); break; case EntityType::ENEMIES: for (auto& minion : player.GetOpponent().GetField()) { entities.emplace_back(minion); } entities.emplace_back(player.GetOpponent().GetHero()); break; default: throw std::domain_error("Invalid entity type"); } return entities; } MetaData IncludeTask::Impl(Player&) { return MetaData::INCLUDE_SUCCESS; } } // namespace Hearthstonepp::SimpleTasks
Add tests for operator bool().
#include <test.hpp> TEST_CASE("basic") { SECTION("default constructed pbf message is okay") { mapbox::util::pbf item; REQUIRE(!item.next()); } SECTION("empty buffer is okay") { std::string buffer; mapbox::util::pbf item(buffer.data(), 0); REQUIRE(!item.next()); } SECTION("check every possible value for single byte in buffer") { char buffer[1]; for (int i = 0; i <= 255; ++i) { *buffer = static_cast<char>(i); mapbox::util::pbf item(buffer, 1); REQUIRE_THROWS({ item.next(); item.skip(); }); } } }
#include <test.hpp> TEST_CASE("basic") { SECTION("default constructed pbf message is okay") { mapbox::util::pbf item; REQUIRE(!item.next()); } SECTION("empty buffer is okay") { std::string buffer; mapbox::util::pbf item(buffer.data(), 0); REQUIRE(!item); // test operator bool() REQUIRE(!item.next()); } SECTION("check every possible value for single byte in buffer") { char buffer[1]; for (int i = 0; i <= 255; ++i) { *buffer = static_cast<char>(i); mapbox::util::pbf item(buffer, 1); REQUIRE(!!item); // test operator bool() REQUIRE_THROWS({ item.next(); item.skip(); }); } } }
Create a QCoreApplication when testing Lua
#include "Rainback.hpp" #include <lua-cxx/LuaEnvironment.hpp> #include <lua-cxx/LuaValue.hpp> #include <QFile> int main(int argc, char* argv[]) { Lua lua; rainback::Rainback rainback(lua); std::string srcdir(getenv("srcdir")); QFile testRunner(QString(srcdir.c_str()) + "/test_lua.lua"); return (bool)lua(testRunner) ? 0 : 1; }
#include "Rainback.hpp" #include <lua-cxx/LuaEnvironment.hpp> #include <lua-cxx/LuaValue.hpp> #include <QFile> #include <QCoreApplication> int main(int argc, char* argv[]) { QCoreApplication app(argc, argv); Lua lua; rainback::Rainback rainback(lua); std::string srcdir(getenv("srcdir")); QFile testRunner(QString(srcdir.c_str()) + "/test_lua.lua"); return (bool)lua(testRunner) ? 0 : 1; }
Enable the RendererScheduler by default.
// 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 "content/renderer/scheduler/renderer_scheduler.h" #include "content/renderer/scheduler/null_renderer_scheduler.h" namespace content { RendererScheduler::RendererScheduler() { } RendererScheduler::~RendererScheduler() { } // static scoped_ptr<RendererScheduler> RendererScheduler::Create() { // TODO(rmcilroy): Use the RendererSchedulerImpl when the scheduler is enabled return make_scoped_ptr(new NullRendererScheduler()); } } // namespace content
// 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 "content/renderer/scheduler/renderer_scheduler.h" #include "base/command_line.h" #include "base/message_loop/message_loop_proxy.h" #include "content/public/common/content_switches.h" #include "content/renderer/scheduler/null_renderer_scheduler.h" #include "content/renderer/scheduler/renderer_scheduler_impl.h" namespace content { RendererScheduler::RendererScheduler() { } RendererScheduler::~RendererScheduler() { } // static scoped_ptr<RendererScheduler> RendererScheduler::Create() { CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableBlinkScheduler)) { return make_scoped_ptr(new NullRendererScheduler()); } else { return make_scoped_ptr( new RendererSchedulerImpl(base::MessageLoopProxy::current())); } } } // namespace content
Fix error in Travic CI
#include "gns/test_util/random_number.h" namespace gns { namespace test_util { RandomNumber::RandomNumber(const size_t seed) : engine_(), distribution_() { } double RandomNumber::operator()() { return distribution_(engine_); } double RandomNumber::operator()(const double min, const double max) { const int diff = max - min; return (*this)() * diff + min; } } // namespace test_util } // namespace gns
#include "gns/test_util/random_number.h" namespace gns { namespace test_util { RandomNumber::RandomNumber(const size_t seed) : engine_(), distribution_() { engine_.seed(seed); } double RandomNumber::operator()() { return distribution_(engine_); } double RandomNumber::operator()(const double min, const double max) { const int diff = max - min; return (*this)() * diff + min; } } // namespace test_util } // namespace gns
Remove Touche feature extraction module.
/** @example user_touche.cpp Touche example. */ #include <ESP.h> BinaryIntArraySerialStream stream(0, 115200, 160); GestureRecognitionPipeline pipeline; void setup() { useInputStream(stream); pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160)); pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2)); usePipeline(pipeline); }
/** @example user_touche.cpp Touche example. */ #include <ESP.h> BinaryIntArraySerialStream stream(0, 115200, 160); GestureRecognitionPipeline pipeline; void setup() { useInputStream(stream); pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2)); usePipeline(pipeline); }
Fix delete ordering for input/output facets
#include "Logger.h" #include <iostream> // // (plesslie) // posix_time_zone is just parsing the "-XX" portion and subtracting that from UTC meaning // that it isn't adjusting for daylight savings time. not sure how to fix that, and I don't // really care for now. // Logger::Logger() : ss_(), tz_(new boost::local_time::posix_time_zone("CST-05")), output_facet_(new boost::local_time::local_time_facet()), input_facet_(new boost::local_time::local_time_input_facet()) { ss_.imbue(std::locale(std::locale::classic(), output_facet_)); ss_.imbue(std::locale(ss_.getloc(), input_facet_)); output_facet_->format(boost::local_time::local_time_facet::iso_time_format_extended_specifier); } Logger::~Logger() { delete output_facet_; delete input_facet_; } Logger& Logger::instance() { static Logger logger; return logger; }
#include "Logger.h" #include <iostream> // // (plesslie) // posix_time_zone is just parsing the "-XX" portion and subtracting that from UTC meaning // that it isn't adjusting for daylight savings time. not sure how to fix that, and I don't // really care for now. // Logger::Logger() : ss_(), tz_(new boost::local_time::posix_time_zone("CST-05")), output_facet_(new boost::local_time::local_time_facet()), input_facet_(new boost::local_time::local_time_input_facet()) { ss_.imbue(std::locale(std::locale::classic(), output_facet_)); ss_.imbue(std::locale(ss_.getloc(), input_facet_)); output_facet_->format(boost::local_time::local_time_facet::iso_time_format_extended_specifier); } Logger::~Logger() { delete input_facet_; delete output_facet_; } Logger& Logger::instance() { static Logger logger; return logger; }
Fix bug where it was assuming that error messages won't contain format strings.
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/core/error_reporter.h" #include <cstdarg> #include <cstdio> #include <cstring> #include "tensorflow/lite/minimal_logging.h" namespace tflite { namespace task { namespace core { int ErrorReporter::Report(const char* format, va_list args) { last_message_[0] = '\0'; int num_characters = vsnprintf(last_message_, kBufferSize, format, args); // To mimic tflite::StderrReporter. tflite::logging_internal::MinimalLogger::Log(TFLITE_LOG_ERROR, last_message_); return num_characters; } std::string ErrorReporter::message() { return last_message_; } } // namespace core } // namespace task } // namespace tflite
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/core/error_reporter.h" #include <cstdarg> #include <cstdio> #include <cstring> #include "tensorflow/lite/minimal_logging.h" namespace tflite { namespace task { namespace core { int ErrorReporter::Report(const char* format, va_list args) { last_message_[0] = '\0'; int num_characters = vsnprintf(last_message_, kBufferSize, format, args); // To mimic tflite::StderrReporter. tflite::logging_internal::MinimalLogger::Log(TFLITE_LOG_ERROR, "%s", last_message_); return num_characters; } std::string ErrorReporter::message() { return last_message_; } } // namespace core } // namespace task } // namespace tflite
Check NULL value of result.
#include <stdlib.h> #include <string> // include the sql parser #include "SQLParser.h" // contains printing utilities #include "sqlhelper.h" int main(int argc, char *argv[]) { if (argc <= 1) { fprintf(stderr, "Usage: ./example \"SELECT * FROM test;\"\n"); return -1; } std::string query = argv[1]; // parse a given query hsql::SQLParserResult* result = hsql::SQLParser::parseSQLString(query); // check whether the parsing was successful if (result->isValid()) { printf("Parsed successfully!\n"); printf("Number of statements: %lu\n", result->size()); for (uint i = 0; i < result->size(); ++i) { // Print a statement summary. hsql::printStatementInfo(result->getStatement(i)); } delete result; return 0; } else { fprintf(stderr, "Given string is not a valid SQL query.\n"); fprintf(stderr, "%s (L%d:%d)\n", result->errorMsg(), result->errorLine(), result->errorColumn()); delete result; return -1; } }
#include <stdlib.h> #include <string> // include the sql parser #include "SQLParser.h" // contains printing utilities #include "sqlhelper.h" int main(int argc, char *argv[]) { if (argc <= 1) { fprintf(stderr, "Usage: ./example \"SELECT * FROM test;\"\n"); return -1; } std::string query = argv[1]; // parse a given query hsql::SQLParserResult* result = hsql::SQLParser::parseSQLString(query); // check whether the parsing was successful if (!result) { return -1; } if (result->isValid()) { printf("Parsed successfully!\n"); printf("Number of statements: %lu\n", result->size()); for (uint i = 0; i < result->size(); ++i) { // Print a statement summary. hsql::printStatementInfo(result->getStatement(i)); } delete result; return 0; } else { fprintf(stderr, "Given string is not a valid SQL query.\n"); fprintf(stderr, "%s (L%d:%d)\n", result->errorMsg(), result->errorLine(), result->errorColumn()); delete result; return -1; } }
Work around bug in gcc's name mangling causing linker to crash on Mac OS X.
// 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 "../client/gles2_lib.h" #include "../common/thread_local.h" namespace gles2 { namespace { gpu::ThreadLocalKey g_gl_context_key; } // namespace anonymous void Initialize() { g_gl_context_key = gpu::ThreadLocalAlloc(); } void Terminate() { gpu::ThreadLocalFree(g_gl_context_key); g_gl_context_key = 0; } gpu::gles2::GLES2Implementation* GetGLContext() { return static_cast<gpu::gles2::GLES2Implementation*>( gpu::ThreadLocalGetValue(g_gl_context_key)); } void SetGLContext(gpu::gles2::GLES2Implementation* context) { gpu::ThreadLocalSetValue(g_gl_context_key, context); } } // namespace gles2
// 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 "../client/gles2_lib.h" #include "../common/thread_local.h" namespace gles2 { // TODO(kbr): the use of this anonymous namespace core dumps the // linker on Mac OS X 10.6 when the symbol ordering file is used // namespace { static gpu::ThreadLocalKey g_gl_context_key; // } // namespace anonymous void Initialize() { g_gl_context_key = gpu::ThreadLocalAlloc(); } void Terminate() { gpu::ThreadLocalFree(g_gl_context_key); g_gl_context_key = 0; } gpu::gles2::GLES2Implementation* GetGLContext() { return static_cast<gpu::gles2::GLES2Implementation*>( gpu::ThreadLocalGetValue(g_gl_context_key)); } void SetGLContext(gpu::gles2::GLES2Implementation* context) { gpu::ThreadLocalSetValue(g_gl_context_key, context); } } // namespace gles2
Fix compile error when using test_ukvm.sh
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <service> extern "C" __attribute__((noreturn)) void panic(const char* reason); __attribute__((noreturn)) extern "C" void abort(){ panic("Abort called"); } const char* service_name__ = SERVICE_NAME; const char* service_binary_name__ = SERVICE;
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <service> extern "C" __attribute__((noreturn)) void panic(const char* reason); extern "C" __attribute__((noreturn)) void abort(){ panic("Abort called"); } const char* service_name__ = SERVICE_NAME; const char* service_binary_name__ = SERVICE;
Return update ever 50 ms (if idle)
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /*********************************************************************************** ** ** OrionApplication.cpp ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "stdafx.h" //---------------------------------------------------------------------------------- COrionApplication g_App; //---------------------------------------------------------------------------------- void COrionApplication::OnMainLoop() { WISPFUN_DEBUG("c193_f1"); g_Ticks = timeGetTime(); if (m_NextRenderTime <= g_Ticks) { //m_NextUpdateTime = g_Ticks + 50; m_NextRenderTime = g_Ticks + g_OrionWindow.RenderTimerDelay; g_Orion.Process(true); } /*else if (m_NextUpdateTime <= g_Ticks) { m_NextUpdateTime = g_Ticks + 50; g_Orion.Process(false); }*/ else Sleep(1); } //----------------------------------------------------------------------------------
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /*********************************************************************************** ** ** OrionApplication.cpp ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "stdafx.h" //---------------------------------------------------------------------------------- COrionApplication g_App; //---------------------------------------------------------------------------------- void COrionApplication::OnMainLoop() { WISPFUN_DEBUG("c193_f1"); g_Ticks = timeGetTime(); if (m_NextRenderTime <= g_Ticks) { m_NextUpdateTime = g_Ticks + 50; m_NextRenderTime = g_Ticks + g_OrionWindow.RenderTimerDelay; g_Orion.Process(true); } else if (m_NextUpdateTime <= g_Ticks) { m_NextUpdateTime = g_Ticks + 50; g_Orion.Process(false); } else Sleep(1); } //----------------------------------------------------------------------------------
Fix for compile problems under IRIX.
//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield // Distributed under the terms of the GNU General Public License (GPL) // as published by the Free Software Foundation. // // All software using osgSim must be GPL'd or excempted via the // purchase of the Open Scene Graph Professional License (OSGPL) // for further information contact robert@openscenegraph.com. #include <osgSim/BlinkSequence> #include <stdlib.h> using namespace osgSim; BlinkSequence::BlinkSequence(): Referenced(), _pulsePeriod(0.0), _phaseShift(0.0), _pulseData(), _sequenceGroup(0) {} BlinkSequence::BlinkSequence(const BlinkSequence& bs): Referenced(), _pulsePeriod(bs._pulsePeriod), _phaseShift(bs._phaseShift), _pulseData(bs._pulseData), _sequenceGroup(bs._sequenceGroup) {} BlinkSequence::SequenceGroup::SequenceGroup(): Referenced() { // set a random base time between 0 and 1000.0 _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0; } BlinkSequence::SequenceGroup::SequenceGroup(double baseTime): Referenced(), _baseTime(baseTime) {}
//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield // Distributed under the terms of the GNU General Public License (GPL) // as published by the Free Software Foundation. // // All software using osgSim must be GPL'd or excempted via the // purchase of the Open Scene Graph Professional License (OSGPL) // for further information contact robert@openscenegraph.com. #include <osgSim/BlinkSequence> #include <stdlib.h> using namespace osgSim; BlinkSequence::BlinkSequence(): _pulsePeriod(0.0), _phaseShift(0.0), _pulseData(), _sequenceGroup(0) { } BlinkSequence::BlinkSequence(const BlinkSequence& bs): _pulsePeriod(bs._pulsePeriod), _phaseShift(bs._phaseShift), _pulseData(bs._pulseData), _sequenceGroup(bs._sequenceGroup) { } BlinkSequence::SequenceGroup::SequenceGroup() { // set a random base time between 0 and 1000.0 _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0; } BlinkSequence::SequenceGroup::SequenceGroup(double baseTime): _baseTime(baseTime) { }
Fix missing LoadLibrary symbol on windows.
#include "runtime_internal.h" #ifdef BITS_64 #define WIN32API #else #define WIN32API __stdcall #endif extern "C" { WIN32API void *LoadLibrary(const char *); WIN32API void *GetProcAddress(void *, const char *); WEAK void *halide_get_symbol(const char *name) { return GetProcAddress(NULL, name); } WEAK void *halide_load_library(const char *name) { return LoadLibrary(name); } WEAK void *halide_get_library_symbol(void *lib, const char *name) { return GetProcAddress(lib, name); } }
#include "runtime_internal.h" #ifdef BITS_64 #define WIN32API #else #define WIN32API __stdcall #endif extern "C" { WIN32API void *LoadLibraryA(const char *); WIN32API void *GetProcAddress(void *, const char *); WEAK void *halide_get_symbol(const char *name) { return GetProcAddress(NULL, name); } WEAK void *halide_load_library(const char *name) { return LoadLibraryA(name); } WEAK void *halide_get_library_symbol(void *lib, const char *name) { return GetProcAddress(lib, name); } }
Use QFile to do file comparison
#include "FileOperations.h" #include <QFile> #include <QtGlobal> template <class InputIterator1, class InputIterator2> bool FileOperations::equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2) { while ((first1 != last1) && (first2 != last2)) { if (*first1 != *first2) { return false; } ++first1; ++first2; } return (first1 == last1) && (first2 == last2); } bool FileOperations::filesEqual(const QString& filePath1, const QString& filePath2) { bool equivalent = false; QFile file1(filePath1); QFile file2(filePath2); if (file1.exists() && file2.exists()) { file1.open(QFile::ReadOnly); uchar* fileMemory1 = file1.map(0, file1.size()); file2.open(QFile::ReadOnly); uchar* fileMemory2 = file2.map(0, file2.size()); equivalent = equal(fileMemory1, fileMemory1 + file1.size(), fileMemory2, fileMemory2 + file2.size()); } return equivalent; }
#include "FileOperations.h" #include <QFile> #include <QtGlobal> bool FileOperations::filesEqual(const QString& filePath1, const QString& filePath2) { bool equivalent = false; QFile file1(filePath1); QFile file2(filePath2); if (file1.exists() && file2.exists()) { file1.open(QFile::ReadOnly); file2.open(QFile::ReadOnly); while (!file1.atEnd()) { QByteArray file1Buffer; const qint64 file1BytesRead = file1.read(file1Buffer.data(), 16384); if (-1 == file1BytesRead) { break; } QByteArray file2Buffer; const qint64 file2BytesRead = file2.read(file2Buffer.data(), 16384); if (-1 == file1BytesRead) { break; } if (file1Buffer != file2Buffer) { break; } if (file1.atEnd() && !file2.atEnd()) { break; } if (file1.atEnd() && file2.atEnd()) { equivalent = true; } } } return equivalent; }
Enable ExtensionApiTest.GetViews on all platforms.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) // Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms. // See http://crbug.com/39916 for details. #define MAYBE_GetViews GetViews #else #define MAYBE_GetViews DISABLED_GetViews #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViews) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("get_views")) << message_; }
// 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 "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViews) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("get_views")) << message_; }
Call libport::program_initialize in every entry point.
/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file libuco/urbi-main.cc #include <libport/cli.hh> #include <libport/containers.hh> #include <urbi/umain.hh> extern "C" { int urbi_main(int argc, const char* argv[], bool block, bool errors) { return urbi::main(argc, argv, block, errors); } int urbi_main_args(const libport::cli_args_type& args, bool block, bool errors) { return urbi::main(args, block, errors); } } namespace urbi { int main(int argc, const char* argv[], bool block, bool errors) { libport::cli_args_type args; // For some reason, I failed to use std::copy here. for (int i = 0; i < argc; ++i) args << std::string(argv[i]); return main(args, block, errors); } }
/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file libuco/urbi-main.cc #include <libport/cli.hh> #include <libport/containers.hh> #include <urbi/umain.hh> extern "C" { int urbi_main(int argc, const char* argv[], bool block, bool errors) { libport::program_initialize(argc, const_cast<char**>(argv)); return urbi::main(argc, argv, block, errors); } int urbi_main_args(const libport::cli_args_type& args, bool block, bool errors) { libport::program_initialize(args); return urbi::main(args, block, errors); } } namespace urbi { int main(int argc, const char* argv[], bool block, bool errors) { libport::program_initialize(argc, const_cast<char**>(argv)); libport::cli_args_type args; // For some reason, I failed to use std::copy here. for (int i = 0; i < argc; ++i) args << std::string(argv[i]); return main(args, block, errors); } }
Use new API in rtc-blinker app
#include "gpio.h" #include "nvic.h" #include "driver/timer.hpp" extern "C" void __cxa_pure_virtual() { while (1); } namespace { int counter = 0; void toggle_leds() { ++counter; auto gpio_n = 17 + (counter & 3); gpio_toggle(0, (1 << gpio_n)); } } int main(void) { nvic_init(); auto* rtc = driver::Timer::get_by_id(driver::Timer::ID::RTC0); rtc->set_prescaler(0xfff - 1); rtc->set_irq_handler(toggle_leds); rtc->enable_tick_interrupt(); rtc->start(); while (1); }
#include "gpio.h" #include "nvic.h" #include "driver/timer.hpp" #include "memio.h" namespace { int counter = 0; void toggle_leds(int) { auto gpio_n = 17 + (counter++ & 3); gpio_toggle(0, (1 << gpio_n)); } } int main(void) { nvic_init(); gpio_set_option(0, (1 << 17) | (1 << 18) | (1 << 19) | (1 << 20), GPIO_OPT_OUTPUT); auto* rtc = driver::Timer::get_by_id(driver::Timer::ID::RTC0); rtc->stop(); rtc->set_prescaler(0xffd); rtc->add_event_handler(0, toggle_leds); rtc->enable_tick_interrupt(); rtc->start(); while (1); }
Fix Windows build issues by removing posix only code.
#include <iostream> #include <limits.h> #include <thread> #include <unistd.h> int main() { char name[_POSIX_HOST_NAME_MAX + 1]; gethostname(name, sizeof(name)); std::cout << "Host name: " << name << std::endl; unsigned int cores = std::thread::hardware_concurrency(); std::cout << "Total cores: " << cores << std::endl; return 0; }
#include <iostream> #include <limits.h> #include <thread> int main() { unsigned int cores = std::thread::hardware_concurrency(); std::cout << "Total cores: " << cores << std::endl; return 0; }
Add support for uint uniforms
#include "Uniforms.h" namespace ion { namespace Graphics { template <> EValueType IUniformTyped<float>::GetType() const { return EValueType::Float; } template <> EValueType IUniformTyped<vec2f>::GetType() const { return EValueType::Float2; } template <> EValueType IUniformTyped<vec3f>::GetType() const { return EValueType::Float3; } template <> EValueType IUniformTyped<vec4f>::GetType() const { return EValueType::Float4; } template <> EValueType IUniformTyped<color3f>::GetType() const { return EValueType::Float3; } template <> EValueType IUniformTyped<color4f>::GetType() const { return EValueType::Float4; } template <> EValueType IUniformTyped<glm::mat4>::GetType() const { return EValueType::Matrix4x4; } template <> EValueType IUniformTyped<int>::GetType() const { return EValueType::SignedInt32; } } }
#include "Uniforms.h" namespace ion { namespace Graphics { template <> EValueType IUniformTyped<float>::GetType() const { return EValueType::Float; } template <> EValueType IUniformTyped<vec2f>::GetType() const { return EValueType::Float2; } template <> EValueType IUniformTyped<vec3f>::GetType() const { return EValueType::Float3; } template <> EValueType IUniformTyped<vec4f>::GetType() const { return EValueType::Float4; } template <> EValueType IUniformTyped<color3f>::GetType() const { return EValueType::Float3; } template <> EValueType IUniformTyped<color4f>::GetType() const { return EValueType::Float4; } template <> EValueType IUniformTyped<glm::mat4>::GetType() const { return EValueType::Matrix4x4; } template <> EValueType IUniformTyped<int>::GetType() const { return EValueType::SignedInt32; } template <> EValueType IUniformTyped<uint>::GetType() const { return EValueType::UnsignedInt32; } } }
Fix klocwork issues with uninitialized variables in the "apps" module.
#include <legato.h> #include <thread> #include <string> #include <list> #include <iostream> #ifndef MUST_BE_DEFINED #error MUST_BE_DEFINED was not defined. #endif COMPONENT_INIT { LE_INFO("Hello world, from thread 1."); std::thread newThread([]() { le_thread_InitLegatoThreadData("thread 2"); // This will crash if the Legato thread-specific data has not been initialized. le_thread_GetCurrent(); LE_INFO("Hello world, from %s.", le_thread_GetMyName()); le_thread_CleanupLegatoThreadData(); }); LE_INFO("Thead 2 stared, and waiting for it to complete."); newThread.join(); LE_INFO("Thead 2 ended, all done with init."); std::list<std::string> stuff; // C++ 11 for (auto s : stuff) { std::cout << "stuff: " << s << std::endl; } exit(EXIT_SUCCESS); }
#include <legato.h> #include <thread> #include <string> #include <list> #include <iostream> #ifndef MUST_BE_DEFINED #error MUST_BE_DEFINED was not defined. #endif COMPONENT_INIT { LE_INFO("Hello world, from thread 1."); std::thread newThread([]() { le_thread_InitLegatoThreadData("thread 2"); // This will crash if the Legato thread-specific data has not been initialized. le_thread_GetCurrent(); LE_INFO("Hello world, from %s.", le_thread_GetMyName()); le_thread_CleanupLegatoThreadData(); }); LE_INFO("Thead 2 stared, and waiting for it to complete."); newThread.join(); LE_INFO("Thead 2 ended, all done with init."); std::list<std::string> stuff; // C++ 11 for (auto const &s : stuff) { std::cout << "stuff: " << s << std::endl; } exit(EXIT_SUCCESS); }
Improve structure of encoding different version addresses
#include "HM3Pointers.h" HM3Pointers::HM3Pointers(HM3Version version) { Setup(version); } HM3Pointers::~HM3Pointers() { } void HM3Pointers::Setup(HM3Version version) { uint8_t** difficultyPtr = nullptr; uint8_t** timePtr = nullptr; switch (version) { case HM3_GOG: m_Stats = (HM3Stats*)0x009B3B38; difficultyPtr = (uint8_t**)0x0082083C; timePtr = (uint8_t**)0x00820820; break; case HM3_STEAM: m_Stats = (HM3Stats*)0x009B2538; difficultyPtr = (uint8_t**)0x0081F83C; timePtr = (uint8_t**)0x0081F820; break; case HM3_UNKNOWN: m_Stats = nullptr; break; } m_Difficulty = difficultyPtr != nullptr ? *difficultyPtr + 0x6664 : nullptr; m_Time = timePtr != nullptr ? *timePtr + 0x48 : nullptr; }
#include "HM3Pointers.h" struct DataAddresses { uint32_t Stats; uint32_t DifficultyPtr; uint32_t TimePtr; }; static const DataAddresses DataVersions[] { { 0x00000000, 0x00000000, 0x00000000 }, // Unknown version { 0x009B2538, 0x0081F83C, 0x0081F820 }, // Steam { 0x009B3B38, 0x0082083C, 0x00820820 } // GOG }; HM3Pointers::HM3Pointers(HM3Version version) { Setup(version); } HM3Pointers::~HM3Pointers() { } void HM3Pointers::Setup(HM3Version version) { const DataAddresses& addresses(DataVersions[version]); m_Stats = (HM3Stats*)addresses.Stats; uint8_t** difficultyPtr = (uint8_t**)addresses.DifficultyPtr; uint8_t** timePtr = (uint8_t**)addresses.TimePtr; m_Difficulty = difficultyPtr != nullptr ? *difficultyPtr + 0x6664 : nullptr; m_Time = timePtr != nullptr ? *timePtr + 0x48 : nullptr; }
Update nanoFramework.Networking.Sntp version to 1.0.2-preview-049 ***NO_CI***
// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_networking_sntp.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp = { "nanoFramework.Networking.Sntp", 0x733B4551, method_lookup, { 1, 0, 2, 48 } };
// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_networking_sntp.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp = { "nanoFramework.Networking.Sntp", 0x733B4551, method_lookup, { 1, 0, 2, 49 } };
Add placeholder value to script component
#include "Script.hpp" using namespace Component; Script::Script(Entity* entity) : SuperComponent(entity) { } Json::Value Script::Save() const { Json::Value component; return component; } void Script::Load(const Json::Value& node) { }
#include "Script.hpp" using namespace Component; Script::Script(Entity* entity) : SuperComponent(entity) { } Json::Value Script::Save() const { Json::Value component; component["placeholderValue"] = ""; return component; } void Script::Load(const Json::Value& node) { }
Fix a brace style inconsistency
#include "Isosurface.h" Vector3D Isosurface::gradientAt(float x, float y, float z) const { const float epsilon = 0.0001; float dx = valueAt(x + epsilon, y, z) - valueAt(x - epsilon, y, z); float dy = valueAt(x, y + epsilon, z) - valueAt(x, y - epsilon, z); float dz = valueAt(x, y, z + epsilon) - valueAt(x, y, z - epsilon); Vector3D result = { dx, dy, dz }; normalize(result); return result; } Isosurface::~Isosurface() { }
#include "Isosurface.h" Vector3D Isosurface::gradientAt(float x, float y, float z) const { const float epsilon = 0.0001; float dx = valueAt(x + epsilon, y, z) - valueAt(x - epsilon, y, z); float dy = valueAt(x, y + epsilon, z) - valueAt(x, y - epsilon, z); float dz = valueAt(x, y, z + epsilon) - valueAt(x, y, z - epsilon); Vector3D result = { dx, dy, dz }; normalize(result); return result; } Isosurface::~Isosurface() { }
Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } // Disabled, flakily exceeds timeout, http://crbug.com/72165. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_; }
Test that test suites with broken initializers don't get added to the list of suites
#include "mettle.hpp" using namespace mettle; suite<suites_list> test_suite("test suite", [](auto &_) { _.test("create a test suite", [](suites_list &suites) { suite<> inner("inner test suite", [](auto &_){ _.test("inner test", []() {}); }, suites); expect(suites, array(&inner)); }); _.test("create a test suite with fixture", [](suites_list &suites) { suite<int> inner("inner test suite", [](auto &_){ _.test("inner test", [](int &) {}); }, suites); expect(suites, array(&inner)); }); });
#include "mettle.hpp" using namespace mettle; suite<suites_list> test_suite("test suite", [](auto &_) { _.test("create a test suite", [](suites_list &suites) { suite<> inner("inner test suite", [](auto &_){ _.test("inner test", []() {}); }, suites); expect(suites, array(&inner)); }); _.test("create a test suite with fixture", [](suites_list &suites) { suite<int> inner("inner test suite", [](auto &_){ _.test("inner test", [](int &) {}); }, suites); expect(suites, array(&inner)); }); _.test("create a test suite that throws", [](suites_list &suites) { try { suite<int> inner("broken test suite", [](auto &){ throw "bad"; }, suites); } catch(...) {} expect(suites, array()); }); });
Revert "content: Enable the RendererScheduler by default."
// 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 "content/renderer/scheduler/renderer_scheduler.h" #include "base/command_line.h" #include "base/message_loop/message_loop_proxy.h" #include "content/public/common/content_switches.h" #include "content/renderer/scheduler/null_renderer_scheduler.h" #include "content/renderer/scheduler/renderer_scheduler_impl.h" namespace content { RendererScheduler::RendererScheduler() { } RendererScheduler::~RendererScheduler() { } // static scoped_ptr<RendererScheduler> RendererScheduler::Create() { CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableBlinkScheduler)) { return make_scoped_ptr(new NullRendererScheduler()); } else { return make_scoped_ptr( new RendererSchedulerImpl(base::MessageLoopProxy::current())); } } } // namespace content
// 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 "content/renderer/scheduler/renderer_scheduler.h" #include "content/renderer/scheduler/null_renderer_scheduler.h" namespace content { RendererScheduler::RendererScheduler() { } RendererScheduler::~RendererScheduler() { } // static scoped_ptr<RendererScheduler> RendererScheduler::Create() { // TODO(rmcilroy): Use the RendererSchedulerImpl when the scheduler is enabled return make_scoped_ptr(new NullRendererScheduler()); } } // namespace content
Fix msvc windows 64 build; Add windows 64 bit prebuilt lib
/* Copyright Sven Bergström 2014 created for snow https://github.com/underscorediscovery/snow MIT license */ #ifdef HX_WINDOWS #include <windows.h> #include "SDL.h" #include "SDL_syswm.h" namespace snow { namespace platform { namespace window { void load_icon(SDL_Window* _window) { SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version) if (SDL_GetWindowWMInfo(_window,&wminfo)) { HINSTANCE handle = ::GetModuleHandle(NULL); HWND hwnd = wminfo.info.win.window; HICON icon = ::LoadIcon(handle, "IDI_MAIN_ICON"); ::SetClassLong(hwnd, GCL_HICON, (LONG) icon); } } //load_icon } //window } //platform namespace } //snow namespace #endif //HX_WINDOWS
/* Copyright Sven Bergström 2014 created for snow https://github.com/underscorediscovery/snow MIT license */ #ifdef HX_WINDOWS #include <windows.h> #include "SDL.h" #include "SDL_syswm.h" namespace snow { namespace platform { namespace window { void load_icon(SDL_Window* _window) { SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version) if (SDL_GetWindowWMInfo(_window,&wminfo)) { HINSTANCE handle = ::GetModuleHandle(NULL); HWND hwnd = wminfo.info.win.window; HICON icon = ::LoadIcon(handle, "IDI_MAIN_ICON"); ::SetClassLong(hwnd, GCLP_HICON, (LONG) icon); } } //load_icon } //window } //platform namespace } //snow namespace #endif //HX_WINDOWS
Fix TSAN issue with BlockingCall test.
// Copyright 2019 The Marl Authors // // 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 // // https://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 "marl/blockingcall.h" #include "marl/defer.h" #include "marl_test.h" #include <mutex> TEST_P(WithBoundScheduler, BlockingCall) { auto mutex = std::make_shared<std::mutex>(); mutex->lock(); marl::WaitGroup wg(100); for (int i = 0; i < 100; i++) { marl::schedule([=] { defer(wg.done()); marl::blocking_call([=] { mutex->lock(); defer(mutex->unlock()); }); }); } marl::schedule([=] { mutex->unlock(); }); wg.wait(); }
// Copyright 2019 The Marl Authors // // 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 // // https://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 "marl/blockingcall.h" #include "marl/defer.h" #include "marl_test.h" #include <mutex> TEST_P(WithBoundScheduler, BlockingCall) { auto mutex = std::make_shared<std::mutex>(); mutex->lock(); marl::WaitGroup wg(100); for (int i = 0; i < 100; i++) { marl::schedule([=] { defer(wg.done()); marl::blocking_call([=] { mutex->lock(); defer(mutex->unlock()); }); }); } mutex->unlock(); wg.wait(); }
Test of the tnc function.
//============================================================================ // Name : TimeSeriesStatisticsDemo.cpp // Author : Dominik Skoda <skoda@d3s.mff.cuni.cz> // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cstdlib> #include "TimeSeries.h" #include "StudentsDistribution.h" using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! TimeSeries<10000,1000> s; for(size_t i = 0; i < 20; ++i){ s.addSample(i%5, i*300); } StudentsDistribution d = s.getMean(); cout << d.isLessThan(2, 0.95) << endl; return 0; }
//============================================================================ // Name : TimeSeriesStatisticsDemo.cpp // Author : Dominik Skoda <skoda@d3s.mff.cuni.cz> // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cstdlib> #include "TimeSeries.h" #include "StudentsDistribution.h" #include "TDistribution.h" using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! TimeSeries<10000,1000> s; for(size_t i = 0; i < 20; ++i){ s.addSample(i%5, i*300); } StudentsDistribution d = s.getMean(); cout << d.isLessThan(2, 0.95) << endl; TDistribution td; int err; for(size_t i = 0; i < 100; ++i){ double t = td.tnc(0.975, i, 0, &err); if(err){ cout << "err " << err << endl; } cout << t << endl; } return 0; }
Enable HiDPI rendering if supported
#include "application.h" #include "mainwindow.h" #include <QApplication> #include <QMainWindow> int main(int argc, char *argv[]) { // QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication app(argc, argv); app.setOrganizationName("lpd8-editor"); app.setApplicationName("lpd8-editor"); app.setApplicationVersion("0.0.0"); Application application; MainWindow win(&application); win.show(); // Application app; return app.exec(); }
#include "application.h" #include "mainwindow.h" #include <QApplication> #include <QMainWindow> int main(int argc, char *argv[]) { #if QT_VERSION >= 0x050600 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QApplication app(argc, argv); app.setOrganizationName("lpd8-editor"); app.setApplicationName("lpd8-editor"); app.setApplicationVersion("0.0.0"); Application application; MainWindow win(&application); win.show(); return app.exec(); }
Fix testing same condition twice (copy paste)
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ #include "../lib.hh" #include "catch.hpp" using namespace vick; using vick::move::mvcol; TEST_CASE("mvcol", "[mvcol]") { contents contents({"asert"}); visual_setup _; mvcol(contents, 3); CHECK(contents.y == 0); CHECK(contents.x == 3); mvcol(contents, 10); // doesn't do anything CHECK(contents.y == 0); CHECK(contents.y == 0); mvcol(contents, 0); CHECK(contents.y == 0); CHECK(contents.x == 0); }
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ #include "../lib.hh" #include "catch.hpp" using namespace vick; using vick::move::mvcol; TEST_CASE("mvcol", "[mvcol]") { contents contents({"asert"}); visual_setup _; mvcol(contents, 3); CHECK(contents.y == 0); CHECK(contents.x == 3); mvcol(contents, 10); // doesn't do anything CHECK(contents.y == 0); CHECK(contents.x == 3); mvcol(contents, 0); CHECK(contents.y == 0); CHECK(contents.x == 0); }
Add test for C++ DR899.
// RUN: %clang_cc1 -std=c++11 -fsyntax-only %s -verify namespace ExplicitConv { struct X { }; // expected-note 2{{candidate constructor}} struct Y { explicit operator X() const; }; void test(const Y& y) { X x(static_cast<X>(y)); X x2((X)y); X x3 = y; // expected-error{{no viable conversion from 'const ExplicitConv::Y' to 'ExplicitConv::X'}} } }
// RUN: %clang_cc1 -std=c++11 -fsyntax-only %s -verify namespace ExplicitConv { struct X { }; // expected-note 2{{candidate constructor}} struct Y { explicit operator X() const; }; void test(const Y& y) { X x(static_cast<X>(y)); X x2((X)y); X x3 = y; // expected-error{{no viable conversion from 'const ExplicitConv::Y' to 'ExplicitConv::X'}} } } namespace DR899 { struct C { }; // expected-note 2 {{candidate constructor}} struct A { explicit operator int() const; explicit operator C() const; }; struct B { int i; B(const A& a): i(a) { } }; int main() { A a; int i = a; // expected-error{{no viable conversion}} int j(a); C c = a; // expected-error{{no viable conversion}} C c2(a); } }
Check that assets are opened properly.
#include <fstream> #include <VBE/system/sdl2/StorageImpl.hpp> // static std::unique_ptr<std::istream> StorageImpl::openAsset(const std::string& filename) { // Open in binary mode so Windows doesn't change LF to CRLF, // which will corrupt binary files such as images. return std::unique_ptr<std::istream>(new std::ifstream("assets/"+filename, std::ios::binary)); }
#include <fstream> #include <VBE/system/sdl2/StorageImpl.hpp> #include <VBE/system/Log.hpp> // static std::unique_ptr<std::istream> StorageImpl::openAsset(const std::string& filename) { // Open in binary mode so Windows doesn't change LF to CRLF, // which will corrupt binary files such as images. std::ifstream* stream = new std::ifstream("assets/"+filename, std::ios::binary); VBE_ASSERT(stream->good(), "Could not open asset: "+filename); return std::unique_ptr<std::istream>(stream); }
Remove optimization dependent on cpp
#include "common.th" // c <- multiplicand // d <- multiplier // b -> product .global imul imul: #if IMUL_EARLY_EXITS b <- c == 0 d <- d &~ b // d = (c == 0) ? 0 : d b <- d == 0 p <- @+L_done & b + p #endif o <- o - 3 h -> [o + (3 - 0)] i -> [o + (3 - 1)] j -> [o + (3 - 2)] b <- 0 h <- 1 j <- d >> 31 // save sign bit in j d <- d ^ j // adjust multiplier d <- d - j L_top: // use constant 1 in h to combine instructions i <- d & h - 1 i <- c &~ i b <- b + i c <- c << 1 d <- d >> 1 i <- d == 0 p <- @+L_top &~ i + p b <- b ^ j // adjust product for signed math b <- b - j o <- o + 3 j <- [o - 2] i <- [o - 1] h <- [o - 0] L_done: o <- o + 1 p <- [o]
#include "common.th" // c <- multiplicand // d <- multiplier // b -> product .global imul imul: o <- o - 3 h -> [o + (3 - 0)] i -> [o + (3 - 1)] j -> [o + (3 - 2)] b <- 0 h <- 1 j <- d >> 31 // save sign bit in j d <- d ^ j // adjust multiplier d <- d - j L_top: // use constant 1 in h to combine instructions i <- d & h - 1 i <- c &~ i b <- b + i c <- c << 1 d <- d >> 1 i <- d == 0 p <- @+L_top &~ i + p b <- b ^ j // adjust product for signed math b <- b - j o <- o + 3 j <- [o - 2] i <- [o - 1] h <- [o - 0] L_done: o <- o + 1 p <- [o]
Use safer cast from const char* literal to char*
#include "gmock/gmock.h" #include "tcframe/experimental/runner.hpp" using ::testing::Test; namespace tcframe { class FakeProblem : public BaseProblem { protected: void InputFormat() {} }; class FakeGenerator : public BaseGenerator<FakeProblem> {}; class RunnerTests : public Test { protected: int argc = 1; char* argv[1] = {const_cast<char*>("./runner")}; Runner<FakeProblem> runner = Runner<FakeProblem>(argc, argv); }; TEST_F(RunnerTests, CompilationSuccessful) { runner.setGenerator(new FakeGenerator()); } }
#include "gmock/gmock.h" #include "tcframe/experimental/runner.hpp" using ::testing::Test; namespace tcframe { class FakeProblem : public BaseProblem { protected: void InputFormat() {} }; class FakeGenerator : public BaseGenerator<FakeProblem> {}; class RunnerTests : public Test { protected: int argc = 1; char* argv[1] = {toChar("./runner")}; Runner<FakeProblem> runner = Runner<FakeProblem>(argc, argv); private: static char* toChar(const string& str) { char* cstr = new char[str.length() + 1]; strcpy(cstr, str.c_str()); return cstr; } }; TEST_F(RunnerTests, CompilationSuccessful) { runner.setGenerator(new FakeGenerator()); } }
Fix boolean expectation from strcmp.
/* * Copyright 2004-2014 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 <cstdio> #include "driver.h" #include "version.h" #include "version_num.h" void get_version(char *v) { v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION); if (strcmp(BUILD_VERSION, "") || developer) sprintf(v, ".%s", BUILD_VERSION); }
/* * Copyright 2004-2014 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 <cstdio> #include "driver.h" #include "version.h" #include "version_num.h" void get_version(char *v) { v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION); if (!strcmp(BUILD_VERSION, "") || developer) sprintf(v, ".%s", BUILD_VERSION); }
Replace a DCHECK with DCHECK_EQ.
// 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/cancellation_flag.h" #include "base/logging.h" namespace base { void CancellationFlag::Set() { #if !defined(NDEBUG) DCHECK(set_on_ == PlatformThread::CurrentId()); #endif base::subtle::Release_Store(&flag_, 1); } bool CancellationFlag::IsSet() const { return base::subtle::Acquire_Load(&flag_) != 0; } } // namespace base
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/cancellation_flag.h" #include "base/logging.h" namespace base { void CancellationFlag::Set() { #if !defined(NDEBUG) DCHECK_EQ(set_on_, PlatformThread::CurrentId()); #endif base::subtle::Release_Store(&flag_, 1); } bool CancellationFlag::IsSet() const { return base::subtle::Acquire_Load(&flag_) != 0; } } // namespace base
Use the overloaded std::abs rather than C's abs(int) to address Clang's -Wabsolute-value
//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/TimeValue.h" #include <time.h> using namespace llvm; namespace { TEST(TimeValue, time_t) { sys::TimeValue now = sys::TimeValue::now(); time_t now_t = time(NULL); EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2); } TEST(TimeValue, Win32FILETIME) { uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL; uint32_t ns = 765432100; sys::TimeValue epoch; // FILETIME has 100ns of intervals. uint64_t ft1970 = epoch_as_filetime + ns / 100; epoch.fromWin32Time(ft1970); // The "seconds" part in Posix time may be expected as zero. EXPECT_EQ(0u, epoch.toEpochTime()); EXPECT_EQ(ns, static_cast<uint32_t>(epoch.nanoseconds())); // Confirm it reversible. EXPECT_EQ(ft1970, epoch.toWin32Time()); } }
//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/TimeValue.h" #include <time.h> using namespace llvm; namespace { TEST(TimeValue, time_t) { sys::TimeValue now = sys::TimeValue::now(); time_t now_t = time(NULL); EXPECT_TRUE(std::abs(static_cast<long>(now_t - now.toEpochTime())) < 2); } TEST(TimeValue, Win32FILETIME) { uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL; uint32_t ns = 765432100; sys::TimeValue epoch; // FILETIME has 100ns of intervals. uint64_t ft1970 = epoch_as_filetime + ns / 100; epoch.fromWin32Time(ft1970); // The "seconds" part in Posix time may be expected as zero. EXPECT_EQ(0u, epoch.toEpochTime()); EXPECT_EQ(ns, static_cast<uint32_t>(epoch.nanoseconds())); // Confirm it reversible. EXPECT_EQ(ft1970, epoch.toWin32Time()); } }