Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use std::async() instead of std::thread()
#include "Halide.h" #include <stdio.h> #include <thread> using namespace Halide; int main(int argc, char **argv) { // Test if the compiler itself is thread-safe. This test is // intended to be run in a thread-sanitizer. std::vector<std::thread> threads; for (int i = 0; i < 1000; i++) { threads.emplace_back([]{ Func f; Var x; f(x) = x; f.realize(100); }); } for (auto &t : threads) { t.join(); } printf("Success!\n"); return 0; }
#include "Halide.h" #include <stdio.h> #include <future> using namespace Halide; static std::atomic<int> foo; int main(int argc, char **argv) { // Test if the compiler itself is thread-safe. This test is // intended to be run in a thread-sanitizer. std::vector<std::future<void>> futures; for (int i = 0; i < 1000; i++) { futures.emplace_back(std::async(std::launch::async, []{ Func f; Var x; f(x) = x; f.realize(100); })); } for (auto &f : futures) { f.wait(); } printf("Success!\n"); return 0; }
Handle return memory of size 0 and large offset
#include "Runtime.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <llvm/IR/IntrinsicInst.h> namespace dev { namespace eth { namespace jit { Runtime::Runtime(RuntimeData* _data, Env* _env) : m_data(*_data), m_env(*_env), m_currJmpBuf(m_jmpBuf) {} bytes Runtime::getReturnData() const // FIXME: Reconsider returning by copy { // TODO: Handle large indexes auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset])); auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize])); assert(offset + size <= m_memory.size()); // TODO: Handle invalid data access by returning empty ref auto dataBeg = m_memory.begin() + offset; return {dataBeg, dataBeg + size}; } } } }
#include "Runtime.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <llvm/IR/IntrinsicInst.h> namespace dev { namespace eth { namespace jit { Runtime::Runtime(RuntimeData* _data, Env* _env) : m_data(*_data), m_env(*_env), m_currJmpBuf(m_jmpBuf) {} bytes Runtime::getReturnData() const // FIXME: Reconsider returning by copy { // TODO: Handle large indexes auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset])); auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize])); assert(offset + size <= m_memory.size() || size == 0); if (offset + size > m_memory.size()) return {}; auto dataBeg = m_memory.begin() + offset; return {dataBeg, dataBeg + size}; } } } }
Disable DCHECK'ing that all NetworkChangeNotifiers are removed. BUG=34391
// 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 "net/base/network_change_notifier_helper.h" #include <algorithm> #include "base/logging.h" namespace net { namespace internal { NetworkChangeNotifierHelper::NetworkChangeNotifierHelper() : is_notifying_observers_(false) {} NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() { DCHECK(observers_.empty()); } void NetworkChangeNotifierHelper::AddObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.push_back(observer); } void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.erase(std::remove(observers_.begin(), observers_.end(), observer)); } void NetworkChangeNotifierHelper::OnIPAddressChanged() { DCHECK(!is_notifying_observers_); is_notifying_observers_ = true; for (std::vector<Observer*>::iterator it = observers_.begin(); it != observers_.end(); ++it) { (*it)->OnIPAddressChanged(); } is_notifying_observers_ = false; } } // namespace internal } // namespace net
// 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 "net/base/network_change_notifier_helper.h" #include <algorithm> #include "base/logging.h" namespace net { namespace internal { NetworkChangeNotifierHelper::NetworkChangeNotifierHelper() : is_notifying_observers_(false) {} NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() { // TODO(willchan): Re-enable this DCHECK after fixing http://crbug.com/34391 // since we're leaking URLRequestContextGetters that cause this DCHECK to // fire. // DCHECK(observers_.empty()); } void NetworkChangeNotifierHelper::AddObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.push_back(observer); } void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.erase(std::remove(observers_.begin(), observers_.end(), observer)); } void NetworkChangeNotifierHelper::OnIPAddressChanged() { DCHECK(!is_notifying_observers_); is_notifying_observers_ = true; for (std::vector<Observer*>::iterator it = observers_.begin(); it != observers_.end(); ++it) { (*it)->OnIPAddressChanged(); } is_notifying_observers_ = false; } } // namespace internal } // namespace net
Print not found when coordinates not found
#include "geocoder.h" #include <stdio.h> using namespace std; int main(int argc, char *argv[]) { if (argc < 3) { printf("USAGE: %s <geodb> <expression>\n", argv[0]); return 1; } GeoCoder g(argv[1]); pair<float, float> *latlng = g.get_latlng(argv[2]); printf("%f, %f\n", latlng->first, latlng->second); delete latlng; return 0; }
#include "geocoder.h" #include <stdio.h> using namespace std; int main(int argc, char *argv[]) { if (argc < 3) { printf("USAGE: %s <geodb> <expression>\n", argv[0]); return 1; } GeoCoder g(argv[1]); pair<float, float> *latlng = g.get_latlng(argv[2]); if (latlng) printf("%f, %f\n", latlng->first, latlng->second); else printf("NOT FOUND\n"); delete latlng; return 0; }
Send actual node transformation as Model matrix
#include "CMeshComponent.h" #include "CGLGraphicsEngine.h" CMeshComponent::CMeshComponent(CMesh * Mesh, ion::GL::Program * Shader) { this->Mesh = Mesh; this->Shader = Shader; } void CMeshComponent::Update(CSceneNode * Node) {} void CMeshComponent::Draw(CSceneNode * Node, IGraphicsEngine * Engine) { if (InstanceOf<CGLGraphicsEngine>(Engine)) { CGLGraphicsEngine * GLEngine = As<CGLGraphicsEngine>(Engine); CGLGraphicsEngine::SDrawDefinition Definition{Mesh->Root->Buffers[0]->ArrayObject}; Definition.AddUniform("Model", new ion::GL::UniformValue<glm::mat4>()); GLEngine->RenderPasses[0].Elements[Shader].push_back(Definition); } }
#include "CMeshComponent.h" #include "CGLGraphicsEngine.h" CMeshComponent::CMeshComponent(CMesh * Mesh, ion::GL::Program * Shader) { this->Mesh = Mesh; this->Shader = Shader; } void CMeshComponent::Update(CSceneNode * Node) {} void CMeshComponent::Draw(CSceneNode * Node, IGraphicsEngine * Engine) { if (InstanceOf<CGLGraphicsEngine>(Engine)) { CGLGraphicsEngine * GLEngine = As<CGLGraphicsEngine>(Engine); CGLGraphicsEngine::SDrawDefinition Definition{Mesh->Root->Buffers[0]->ArrayObject}; Definition.AddUniform("Model", new ion::GL::UniformValue<glm::mat4>(Node->GetAbsoluteTransformation())); GLEngine->RenderPasses[0].Elements[Shader].push_back(Definition); } }
Make RAM class reusable between cpu and ppu
#include "ram.h" #include "memorymap.h" #include <cstring> #include <cassert> RAM::RAM(uint8_t * const ram, size_t size) : ram(ram), size(size) { assert(size == MemoryMap::RAM_MIRROR_START); (void)std::memset(ram, 0U, size); } RAM::~RAM() { } // ---------------------------------------------------------------------------------------------- // uint8_t RAM::read(uint16_t addr) { assert(addr >= MemoryMap::RAM_START); assert(addr <= MemoryMap::RAM_END); if (addr >= MemoryMap::RAM_MIRROR_START) { addr -= MemoryMap::RAM_MIRROR_START - MemoryMap::RAM_START; } return ram[addr - MemoryMap::RAM_START]; } // ---------------------------------------------------------------------------------------------- // void RAM::write(uint16_t addr, uint8_t value) { assert(addr >= MemoryMap::RAM_START); assert(addr <= MemoryMap::RAM_END); if (addr >= MemoryMap::RAM_MIRROR_START) { addr -= MemoryMap::RAM_MIRROR_START - MemoryMap::RAM_START; } ram[addr - MemoryMap::RAM_START] = value; }
#include "ram.h" #include "memorymap.h" #include <cstring> #include <cassert> // ---------------------------------------------------------------------------------------------- // RAM::RAM(uint8_t * const ram, size_t size) : ram(ram), size(size) { assert(size > 0); (void)std::memset(ram, 0U, size); } // ---------------------------------------------------------------------------------------------- // RAM::~RAM() { } // ---------------------------------------------------------------------------------------------- // uint8_t RAM::read(uint16_t addr) { assert(addr < size); return ram[addr]; } // ---------------------------------------------------------------------------------------------- // void RAM::write(uint16_t addr, uint8_t value) { assert(addr < size); ram[addr] = value; }
Fix the linux build by adding a string.h include.
// 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 "ppapi/cpp/directory_entry.h" #include "ppapi/cpp/module.h" namespace pp { DirectoryEntry::DirectoryEntry() { memset(&data_, 0, sizeof(data_)); } DirectoryEntry::DirectoryEntry(const DirectoryEntry& other) { data_.file_ref = other.data_.file_ref; data_.file_type = other.data_.file_type; if (data_.file_ref) Module::Get()->core().AddRefResource(data_.file_ref); } DirectoryEntry::~DirectoryEntry() { if (data_.file_ref) Module::Get()->core().ReleaseResource(data_.file_ref); } DirectoryEntry& DirectoryEntry::operator=(const DirectoryEntry& other) { DirectoryEntry copy(other); swap(copy); return *this; } void DirectoryEntry::swap(DirectoryEntry& other) { std::swap(data_.file_ref, other.data_.file_ref); std::swap(data_.file_type, other.data_.file_type); } } // namespace pp
// 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 "ppapi/cpp/directory_entry.h" #include <string.h> #include "ppapi/cpp/module.h" namespace pp { DirectoryEntry::DirectoryEntry() { memset(&data_, 0, sizeof(data_)); } DirectoryEntry::DirectoryEntry(const DirectoryEntry& other) { data_.file_ref = other.data_.file_ref; data_.file_type = other.data_.file_type; if (data_.file_ref) Module::Get()->core().AddRefResource(data_.file_ref); } DirectoryEntry::~DirectoryEntry() { if (data_.file_ref) Module::Get()->core().ReleaseResource(data_.file_ref); } DirectoryEntry& DirectoryEntry::operator=(const DirectoryEntry& other) { DirectoryEntry copy(other); swap(copy); return *this; } void DirectoryEntry::swap(DirectoryEntry& other) { std::swap(data_.file_ref, other.data_.file_ref); std::swap(data_.file_type, other.data_.file_type); } } // namespace pp
Fix test when modules are enabled
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <memory> // template <class RandomAccessIterator> // void // random_shuffle(RandomAccessIterator first, RandomAccessIterator last); // // template <class RandomAccessIterator, class RandomNumberGenerator> // void // random_shuffle(RandomAccessIterator first, RandomAccessIterator last, // RandomNumberGenerator& rand); // // In C++17, random_shuffle has been removed. // However, for backwards compatibility, if _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE // is defined before including <algorithm>, then random_shuffle will be restored. #define _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE #include <algorithm> #include <vector> struct gen { std::ptrdiff_t operator()(std::ptrdiff_t n) { return n-1; } }; int main() { std::vector<int> v; std::random_shuffle(v.begin(), v.end()); gen r; std::random_shuffle(v.begin(), v.end(), r); }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <memory> // template <class RandomAccessIterator> // void // random_shuffle(RandomAccessIterator first, RandomAccessIterator last); // // template <class RandomAccessIterator, class RandomNumberGenerator> // void // random_shuffle(RandomAccessIterator first, RandomAccessIterator last, // RandomNumberGenerator& rand); // // In C++17, random_shuffle has been removed. // However, for backwards compatibility, if _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE // is defined before including <algorithm>, then random_shuffle will be restored. // MODULES_DEFINES: _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE #define _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE #include <algorithm> #include <vector> struct gen { std::ptrdiff_t operator()(std::ptrdiff_t n) { return n-1; } }; int main() { std::vector<int> v; std::random_shuffle(v.begin(), v.end()); gen r; std::random_shuffle(v.begin(), v.end(), r); }
Improve solution to avoid misinterpretation
#include <iomanip> #include <iostream> double sqrtt(int n) { double result = 1 / 6; for (int i = 0; i < n; i++) { result = 1 / (6 + result); } return result + 3; } int main() { int n; while (std::cin >> n) { std::cout << std::fixed << std::setprecision(10) << sqrtt(n) << std::endl; } return 0; }
#include <iomanip> #include <iostream> double sqrtt(int n) { double result = 0.0; for (int i = 0; i < n; i++) { result = 1 / (6 + result); } return result + 3; } int main() { int n; while (std::cin >> n) { std::cout << std::fixed << std::setprecision(10) << sqrtt(n) << std::endl; } return 0; }
Mark one test as only supported on x86
// RUN: %clangxx_msan -O0 %s -o %t && %run %t // RUN: %clangxx_msan -DPOSITIVE -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s #include <emmintrin.h> int to_int(double v) { __m128d t = _mm_set_sd(v); int x = _mm_cvtsd_si32(t); return x; // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value // CHECK: #{{.*}} in to_int{{.*}}vector_cvt.cc:[[@LINE-3]] } int main() { #ifdef POSITIVE double v; #else double v = 1.1; #endif double* volatile p = &v; int x = to_int(*p); return !x; }
// RUN: %clangxx_msan -O0 %s -o %t && %run %t // RUN: %clangxx_msan -DPOSITIVE -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s // REQUIRES: x86_64-supported-target #include <emmintrin.h> int to_int(double v) { __m128d t = _mm_set_sd(v); int x = _mm_cvtsd_si32(t); return x; // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value // CHECK: #{{.*}} in to_int{{.*}}vector_cvt.cc:[[@LINE-3]] } int main() { #ifdef POSITIVE double v; #else double v = 1.1; #endif double* volatile p = &v; int x = to_int(*p); return !x; }
Make aura_unittests opt into real GL NullDraw contexts.
// 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/bind.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" int main(int argc, char** argv) { base::TestSuite test_suite(argc, argv); return base::LaunchUnitTests( argc, argv, base::Bind(&base::TestSuite::Run, base::Unretained(&test_suite))); }
// 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/bind.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "ui/gl/gl_surface.h" int main(int argc, char** argv) { base::TestSuite test_suite(argc, argv); gfx::GLSurface::InitializeOneOffForTests(true); return base::LaunchUnitTests( argc, argv, base::Bind(&base::TestSuite::Run, base::Unretained(&test_suite))); }
Refactor adding a new state.
#include "state_machine.hpp" namespace kg { void StateMachine::startState(StateRef newState, bool isReplacing) { if (isReplacing && !_states.empty()) { _states.pop(); } if (!isReplacing) { _states.top()->pause(); } _states.push(std::move(newState)); _states.top()->start(); } void StateMachine::exitState() { if (_states.empty()) return; _states.pop(); if (!_states.empty()) { _states.top()->resume(); } } }
#include "state_machine.hpp" namespace kg { void StateMachine::startState(StateRef newState, bool isReplacing) { if (!_states.empty()) { if (isReplacing) { _states.pop(); } else { _states.top()->pause(); } } _states.push(std::move(newState)); _states.top()->start(); } void StateMachine::exitState() { if (_states.empty()) return; _states.pop(); if (!_states.empty()) { _states.top()->resume(); } } }
Check that the ExtensionFunction has a callback for attempting to send a response.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_function.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" void ExtensionFunction::SendResponse(bool success) { if (success) { dispatcher_->SendResponse(this); } else { // TODO(aa): In case of failure, send the error message to an error // callback. } }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_function.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" void ExtensionFunction::SendResponse(bool success) { if (success) { if (has_callback()) { dispatcher_->SendResponse(this); } } else { // TODO(aa): In case of failure, send the error message to an error // callback. } }
Switch from using /dev/random directly to use gnutls_rnd.
#include <QFile> #include "randomgenerator.h" QT_BEGIN_NAMESPACE_CERTIFICATE /*! \class RandomGenerator \brief The RandomGenerator class is a tool for creating hard random numbers. The RandomGenerator class provides a source of secure random numbers using the system's random source (/dev/random on UNIX). The numbers are suitable for uses such as certificate serial numbers. */ /*! Generates a set of random bytes of the specified size. In order to allow these to be conveniently used as serial numbers, this method ensures that the value returned is positive (ie. that the first bit is 0). This means that you get one less bit of entropy than requested, but avoids interoperability issues. Note that this method will either return the number of bytes requested, or a null QByteArray. It will never return a smaller number. */ QByteArray RandomGenerator::getPositiveBytes(int size) { // TODO: Steal win32 version from peppe's change #if defined(Q_OS_UNIX) QFile randomDevice(QLatin1String("/dev/random")); randomDevice.open(QIODevice::ReadOnly|QIODevice::Unbuffered); QByteArray result = randomDevice.read(size); if (result.size() != size) return QByteArray(); // We return what's asked for or not at all // Clear the top bit to ensure the number is positive char *data = result.data(); *data = *data & 0x07f; return result; #endif return QByteArray(); } QT_END_NAMESPACE_CERTIFICATE
#include <QFile> #include <gnutls/gnutls.h> #include <gnutls/crypto.h> #include "randomgenerator.h" QT_BEGIN_NAMESPACE_CERTIFICATE /*! \class RandomGenerator \brief The RandomGenerator class is a tool for creating hard random numbers. The RandomGenerator class provides a source of secure random numbers using the gnutls rnd API. The numbers are suitable for uses such as certificate serial numbers. */ /*! Generates a set of random bytes of the specified size. In order to allow these to be conveniently used as serial numbers, this method ensures that the value returned is positive (ie. that the first bit is 0). This means that you get one less bit of entropy than requested, but avoids interoperability issues. Note that this method will either return the number of bytes requested, or a null QByteArray. It will never return a smaller number. */ QByteArray RandomGenerator::getPositiveBytes(int size) { QByteArray result(size, 0); int errno = gnutls_rnd(GNUTLS_RND_RANDOM, result.data(), size); if (GNUTLS_E_SUCCESS != errno) return QByteArray(); // Clear the top bit to ensure the number is positive char *data = result.data(); *data = *data & 0x07f; return result; } QT_END_NAMESPACE_CERTIFICATE
Add the rest of the standard C++ code to main file.
// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h>
// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h> using namespace std; int main() { }
Use right event type Wheel instead of Scroll.
#include "./mouse_wheel_transition.h" #include <QDebug> MouseWheelTransition::MouseWheelTransition(QObject *object, QState *sourceState) : QEventTransition(object, QEvent::Scroll, sourceState) { } MouseWheelTransition::~MouseWheelTransition() { } bool MouseWheelTransition::eventTest(QEvent *event) { qWarning() << "eventTest" << event->type(); return event->type() == QEvent::Scroll; } void MouseWheelTransition::onTransition(QEvent *event) { this->event = event; }
#include "./mouse_wheel_transition.h" #include <QDebug> MouseWheelTransition::MouseWheelTransition(QObject *object, QState *sourceState) : QEventTransition(object, QEvent::Wheel, sourceState) { } MouseWheelTransition::~MouseWheelTransition() { } bool MouseWheelTransition::eventTest(QEvent *event) { qWarning() << "eventTest" << event->type(); return event->type() == QEvent::Scroll; } void MouseWheelTransition::onTransition(QEvent *event) { this->event = event; }
Exit if multiple instances are running
#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #include <QtSingleApplication> int main(int argc, char *argv[]) { QtSingleApplication app(argc, argv); QQmlApplicationEngine engine; app.setWindowIcon(QIcon("resources/icons/ykman.png")); QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1"; putenv(pythonNoBytecode.toUtf8().data()); QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks"; putenv(frameworks.toUtf8().data()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec(); }
#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #include <QtSingleApplication> int main(int argc, char *argv[]) { QtSingleApplication app(argc, argv); if (app.isRunning()) { return 0; } QQmlApplicationEngine engine; app.setWindowIcon(QIcon("resources/icons/ykman.png")); QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1"; putenv(pythonNoBytecode.toUtf8().data()); QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks"; putenv(frameworks.toUtf8().data()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec(); }
Fix Segmentation fault on Linux Skylake server
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*++ Module Name: common.c Abstract: Implementation of the common mapping functions. --*/ #include "pal/palinternal.h" #include "pal/dbgmsg.h" #include "common.h" #include <sys/mman.h> SET_DEFAULT_DEBUG_CHANNEL(VIRTUAL); /***** * * W32toUnixAccessControl( DWORD ) - Maps Win32 to Unix memory access controls . * */ INT W32toUnixAccessControl( IN DWORD flProtect ) { INT MemAccessControl = 0; switch ( flProtect & 0xff ) { case PAGE_READONLY : MemAccessControl = PROT_READ; break; case PAGE_READWRITE : MemAccessControl = PROT_READ | PROT_WRITE; break; case PAGE_EXECUTE_READWRITE: MemAccessControl = PROT_EXEC | PROT_READ | PROT_WRITE; break; case PAGE_EXECUTE : MemAccessControl = PROT_EXEC; break; case PAGE_EXECUTE_READ : MemAccessControl = PROT_EXEC | PROT_READ; break; case PAGE_NOACCESS : MemAccessControl = PROT_NONE; break; default: MemAccessControl = 0; ERROR( "Incorrect or no protection flags specified.\n" ); break; } return MemAccessControl; }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*++ Module Name: common.c Abstract: Implementation of the common mapping functions. --*/ #include "pal/palinternal.h" #include "pal/dbgmsg.h" #include "common.h" #include <sys/mman.h> SET_DEFAULT_DEBUG_CHANNEL(VIRTUAL); /***** * * W32toUnixAccessControl( DWORD ) - Maps Win32 to Unix memory access controls . * */ INT W32toUnixAccessControl( IN DWORD flProtect ) { INT MemAccessControl = 0; switch ( flProtect & 0xff ) { case PAGE_READONLY : MemAccessControl = PROT_READ; break; case PAGE_READWRITE : MemAccessControl = PROT_READ | PROT_WRITE; break; case PAGE_EXECUTE_READWRITE: MemAccessControl = PROT_EXEC | PROT_READ | PROT_WRITE; break; case PAGE_EXECUTE : MemAccessControl = PROT_EXEC | PROT_READ; // WinAPI PAGE_EXECUTE also implies readable break; case PAGE_EXECUTE_READ : MemAccessControl = PROT_EXEC | PROT_READ; break; case PAGE_NOACCESS : MemAccessControl = PROT_NONE; break; default: MemAccessControl = 0; ERROR( "Incorrect or no protection flags specified.\n" ); break; } return MemAccessControl; }
Add some missing explicit instantiations.
//---------------------------- sparse_decomposition.cc --------------------------- // Copyright (C) 1998, 1999, 2000, 2001, 2002 // by the deal.II authors and Stephen "Cheffo" Kolaroff // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- sparse_decomposition.h --------------------------- #include <lac/sparse_decomposition.templates.h> template class SparseLUDecomposition<double>; template void SparseLUDecomposition<double>::decompose<double> (const SparseMatrix<double> &, const double); template void SparseLUDecomposition<double>::decompose<float> (const SparseMatrix<float> &, const double); template class SparseLUDecomposition<float>; template void SparseLUDecomposition<float>::decompose<double> (const SparseMatrix<double> &, const double); template void SparseLUDecomposition<float>::decompose<float> (const SparseMatrix<float> &, const double);
//---------------------------- sparse_decomposition.cc --------------------------- // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // by the deal.II authors and Stephen "Cheffo" Kolaroff // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- sparse_decomposition.h --------------------------- #include <lac/sparse_decomposition.templates.h> template class SparseLUDecomposition<double>; template void SparseLUDecomposition<double>::decompose<double> (const SparseMatrix<double> &, const double); template void SparseLUDecomposition<double>::decompose<float> (const SparseMatrix<float> &, const double); template void SparseLUDecomposition<double>::copy_from<double> (const SparseMatrix<double> &); template void SparseLUDecomposition<double>::copy_from<float> (const SparseMatrix<float> &); template class SparseLUDecomposition<float>; template void SparseLUDecomposition<float>::decompose<double> (const SparseMatrix<double> &, const double); template void SparseLUDecomposition<float>::decompose<float> (const SparseMatrix<float> &, const double); template void SparseLUDecomposition<float>::copy_from<double> (const SparseMatrix<double> &); template void SparseLUDecomposition<float>::copy_from<float> (const SparseMatrix<float> &);
Add Intel VPU driver to known driver list
/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include "source/inc/ze_util.h" #include <iostream> #include <sstream> #include <string> namespace loader { static const char *knownDriverNames[] = { MAKE_LIBRARY_NAME("ze_intel_gpu", "1"), }; std::vector<DriverLibraryPath> discoverEnabledDrivers() { std::vector<DriverLibraryPath> enabledDrivers; const char *altDrivers = nullptr; // ZE_ENABLE_ALT_DRIVERS is for development/debug only altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS"); if (altDrivers == nullptr) { for (auto path : knownDriverNames) { enabledDrivers.emplace_back(path); } } else { std::stringstream ss(altDrivers); while (ss.good()) { std::string substr; getline(ss, substr, ','); enabledDrivers.emplace_back(substr); } } return enabledDrivers; } } // namespace loader
/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include "source/inc/ze_util.h" #include <iostream> #include <sstream> #include <string> namespace loader { static const char *knownDriverNames[] = { MAKE_LIBRARY_NAME("ze_intel_gpu", "1"), MAKE_LIBRARY_NAME("ze_intel_vpu", "1"), }; std::vector<DriverLibraryPath> discoverEnabledDrivers() { std::vector<DriverLibraryPath> enabledDrivers; const char *altDrivers = nullptr; // ZE_ENABLE_ALT_DRIVERS is for development/debug only altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS"); if (altDrivers == nullptr) { for (auto path : knownDriverNames) { enabledDrivers.emplace_back(path); } } else { std::stringstream ss(altDrivers); while (ss.good()) { std::string substr; getline(ss, substr, ','); enabledDrivers.emplace_back(substr); } } return enabledDrivers; } } // namespace loader
Speed up the game a bit
#include "Game.hpp" #include <Arduino.h> namespace { constexpr uint32_t MsPerUpdate = 200; } // namespace namespace arduino_pong { void Game::run() { while(true) { uint32_t start = millis(); gameField_.update(); gameField_.render(renderer_); int32_t delayValue = start + MsPerUpdate - millis(); Serial.println(delayValue); delay(delayValue < 0 ? 0 : delayValue); } } } // namespace arduino_pong
#include "Game.hpp" #include <Arduino.h> namespace { constexpr uint32_t MsPerUpdate = 30; } // namespace namespace arduino_pong { void Game::run() { while(true) { uint32_t start = millis(); gameField_.update(); gameField_.render(renderer_); int32_t delayValue = start + MsPerUpdate - millis(); #ifdef ARDUINO_PONG_DEBUG Serial.println(delayValue); #endif delay(delayValue < 0 ? 0 : delayValue); } } } // namespace arduino_pong
Move some resources to heap
#include <logging/Logger.h> #include <graphics/GlfwContext.h> #include <graphics/GlfwWindow.h> #include <graphics/Renderer.h> #include <gamemodel/GameState.h> #include <input/Input.h> int main(int argc, char ** argv) { Logger::initSystem(argc, argv); GlfwContext glfwContext(Logger::glfwErrorCallback); GlfwWindow glfwWindow(1200, 800); GameState gameState; Input input(gameState); Renderer renderer(glfwWindow, gameState); glfwWindow.makeCurrent(); glfwWindow.setKeyCallback(input.handleKeyboardFcnPtr); glfwWindow.enterMainLoop([&] { const double t = glfwGetTime(); input.update(t); gameState.update(t); renderer.draw(t); return t < 3600.0; }); return 0; }
#include <memory> #include <logging/Logger.h> #include <graphics/GlfwContext.h> #include <graphics/GlfwWindow.h> #include <graphics/Renderer.h> #include <gamemodel/GameState.h> #include <input/Input.h> int main(int argc, char ** argv) { Logger::initSystem(argc, argv); GlfwContext glfwContext(Logger::glfwErrorCallback); GlfwWindow glfwWindow(1200, 800); auto gameState = std::make_unique<GameState>(); auto input = std::make_unique<Input>(*gameState); auto renderer = std::make_unique<Renderer>(glfwWindow, *gameState); glfwWindow.makeCurrent(); glfwWindow.setKeyCallback(input->handleKeyboardFcnPtr); glfwWindow.enterMainLoop([&] { const double t = glfwGetTime(); input->update(t); gameState->update(t); renderer->draw(t); return t < 3600.0; }); return 0; }
Write namespaces using the respective methods, not via attributes.
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <g.real.ate@gmail.com> // #include "KmlTagWriter.h" #include "GeoWriter.h" #include "KmlElementDictionary.h" namespace Marble { static GeoTagWriterRegistrar s_writerKml( GeoTagWriter::QualifiedName( "", kml::kmlTag_nameSpace22), new KmlTagWriter() ); bool KmlTagWriter::write( const GeoNode *node, GeoWriter& writer ) const { Q_UNUSED(node); writer.writeStartElement( "kml" ); writer.writeAttribute( "xmlns", kml::kmlTag_nameSpace22 ); writer.writeAttribute( "xmlns:gx", kml::kmlTag_nameSpaceGx22 ); // Do not write an end element for document handlers return true; } }
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Andrew Manson <g.real.ate@gmail.com> // #include "KmlTagWriter.h" #include "GeoWriter.h" #include "KmlElementDictionary.h" namespace Marble { static GeoTagWriterRegistrar s_writerKml( GeoTagWriter::QualifiedName( "", kml::kmlTag_nameSpace22), new KmlTagWriter() ); bool KmlTagWriter::write( const GeoNode *node, GeoWriter& writer ) const { Q_UNUSED(node); writer.writeDefaultNamespace( kml::kmlTag_nameSpace22 ); writer.writeNamespace( kml::kmlTag_nameSpaceGx22, "gx" ); writer.writeStartElement( "kml" ); // Do not write an end element for document handlers return true; } }
Disable DCHECK'ing that all NetworkChangeNotifiers are removed. BUG=34391
// 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 "net/base/network_change_notifier_helper.h" #include <algorithm> #include "base/logging.h" namespace net { namespace internal { NetworkChangeNotifierHelper::NetworkChangeNotifierHelper() : is_notifying_observers_(false) {} NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() { DCHECK(observers_.empty()); } void NetworkChangeNotifierHelper::AddObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.push_back(observer); } void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.erase(std::remove(observers_.begin(), observers_.end(), observer)); } void NetworkChangeNotifierHelper::OnIPAddressChanged() { DCHECK(!is_notifying_observers_); is_notifying_observers_ = true; for (std::vector<Observer*>::iterator it = observers_.begin(); it != observers_.end(); ++it) { (*it)->OnIPAddressChanged(); } is_notifying_observers_ = false; } } // namespace internal } // namespace net
// 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 "net/base/network_change_notifier_helper.h" #include <algorithm> #include "base/logging.h" namespace net { namespace internal { NetworkChangeNotifierHelper::NetworkChangeNotifierHelper() : is_notifying_observers_(false) {} NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() { // TODO(willchan): Re-enable this DCHECK after fixing http://crbug.com/34391 // since we're leaking URLRequestContextGetters that cause this DCHECK to // fire. // DCHECK(observers_.empty()); } void NetworkChangeNotifierHelper::AddObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.push_back(observer); } void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.erase(std::remove(observers_.begin(), observers_.end(), observer)); } void NetworkChangeNotifierHelper::OnIPAddressChanged() { DCHECK(!is_notifying_observers_); is_notifying_observers_ = true; for (std::vector<Observer*>::iterator it = observers_.begin(); it != observers_.end(); ++it) { (*it)->OnIPAddressChanged(); } is_notifying_observers_ = false; } } // namespace internal } // namespace net
Add stubbed out code for leak checking on MSVC
// // FormulaEngine Project // By Mike Lewis - 2015 // // Project entry point routine // #include "Pch.h" #include "Tests.h" #include "Simulation.h" // This is Microsoft-specific for _TCHAR and _tmain. // The entry point can be trivially rewritten for other // compilers/platforms, so I'm not putting much effort // into abstracting away those dependencies for now. #include <tchar.h> // // Entry point for the program // int _tmain() { // TODO - memory leak checking // // Optionally run the test suite // Tests::RunAll(); // // Run the simulation // Simulation::RunKingdomWar(); return 0; }
// // FormulaEngine Project // By Mike Lewis - 2015 // // Project entry point routine // #include "Pch.h" #include "Tests.h" #include "Simulation.h" // This is Microsoft-specific for _TCHAR and _tmain. // The entry point can be trivially rewritten for other // compilers/platforms, so I'm not putting much effort // into abstracting away those dependencies for now. #include <tchar.h> // // Entry point for the program // int _tmain() { // Optional memory leak checking /* { int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); flag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(flag); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); //_CrtSetBreakAlloc(207737); } */ // // Optionally run the test suite // Tests::RunAll(); // // Run the simulation // Simulation::RunKingdomWar(); return 0; }
Fix a test that never compiled under -fmodules
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdio.h> class Point { public: int x; int y; Point(int a, int b): x(a), y(b) {} }; class Data { public: int id; Point point; Data(int i): id(i), point(0, 0) {} }; int main(int argc, char const *argv[]) { Data *data[1000]; Data **ptr = data; for (int i = 0; i < 1000; ++i) { ptr[i] = new Data(i); ptr[i]->point.x = i; ptr[i]->point.y = i+1; } printf("Finished populating data.\n"); for (int i = 0; i < 1000; ++i) { bool dump = argc > 1; // Set breakpoint here. // Evaluate a couple of expressions (2*1000 = 2000 exprs): // expr ptr[i]->point.x // expr ptr[i]->point.y if (dump) { printf("data[%d] = %d (%d, %d)\n", i, ptr[i]->id, ptr[i]->point.x, ptr[i]->point.y); } } return 0; }
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// class Point { public: int x; int y; Point(int a, int b): x(a), y(b) {} }; class Data { public: int id; Point point; Data(int i): id(i), point(0, 0) {} }; int main(int argc, char const *argv[]) { Data *data[1000]; Data **ptr = data; for (int i = 0; i < 1000; ++i) { ptr[i] = new Data(i); ptr[i]->point.x = i; ptr[i]->point.y = i+1; } for (int i = 0; i < 1000; ++i) { bool dump = argc > 1; // Set breakpoint here. // Evaluate a couple of expressions (2*1000 = 2000 exprs): // expr ptr[i]->point.x // expr ptr[i]->point.y } return 0; }
Fix test that used raw string literals. Doesn't work in C++03
//===----------------------------------------------------------------------===// // // 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-no-exceptions // <regex> // template <class charT, class traits = regex_traits<charT>> class basic_regex; // template <class ST, class SA> // basic_regex(const basic_string<charT, ST, SA>& s); #include <regex> #include <cassert> #include "test_macros.h" static bool error_range_thrown(const char *pat) { bool result = false; try { std::regex re(pat); } catch (const std::regex_error &ex) { result = (ex.code() == std::regex_constants::error_range); } return result; } int main(int, char**) { assert(error_range_thrown(R"([\w-a])")); assert(error_range_thrown(R"([a-\w])")); return 0; }
//===----------------------------------------------------------------------===// // // 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-no-exceptions // <regex> // template <class charT, class traits = regex_traits<charT>> class basic_regex; // template <class ST, class SA> // basic_regex(const basic_string<charT, ST, SA>& s); #include <regex> #include <cassert> #include "test_macros.h" static bool error_range_thrown(const char *pat) { bool result = false; try { std::regex re(pat); } catch (const std::regex_error &ex) { result = (ex.code() == std::regex_constants::error_range); } return result; } int main(int, char**) { assert(error_range_thrown("([\\w-a])")); assert(error_range_thrown("([a-\\w])")); return 0; }
Enable wrong_file_name test for ElfParser
// generic C #include <cassert> #include <cstdlib> // Google Test library #include <gtest/gtest.h> // uArchSim modules #include "../elf_parser.h" static const char * valid_elf_file = "./mips_bin_exmpl.out"; //static const char * valid_section_name = ".data"; // // Check that all incorect input params of the constructor // are properly handled. // TEST( Elf_parser_init, Process_Wrong_Args_Of_Constr) { std::list<ElfSection> sections_array; ASSERT_NO_THROW( ElfSection::getAllElfSections( valid_elf_file, sections_array)); // test behavior when the file name does not exist // const char * wrong_file_name = "./1234567890/qwertyuiop"; // must exit and return EXIT_FAILURE // ASSERT_EXIT( ElfSection::getAllElfSections( wrong_file_name, sections_array), // ::testing::ExitedWithCode( EXIT_FAILURE), "ERROR.*"); } int main( int argc, char* argv[]) { ::testing::InitGoogleTest( &argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); }
// generic C #include <cassert> #include <cstdlib> // Google Test library #include <gtest/gtest.h> // uArchSim modules #include "../elf_parser.h" static const char * valid_elf_file = "./mips_bin_exmpl.out"; //static const char * valid_section_name = ".data"; // // Check that all incorect input params of the constructor // are properly handled. // TEST( Elf_parser_init, Process_Wrong_Args_Of_Constr) { std::list<ElfSection> sections_array; ASSERT_NO_THROW( ElfSection::getAllElfSections( valid_elf_file, sections_array)); // test behavior when the file name does not exist const char * wrong_file_name = "./1234567890/qwertyuiop"; // must exit and return EXIT_FAILURE ASSERT_EXIT( ElfSection::getAllElfSections( wrong_file_name, sections_array), ::testing::ExitedWithCode( EXIT_FAILURE), "ERROR.*"); } int main( int argc, char* argv[]) { ::testing::InitGoogleTest( &argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); }
Fix bug with string user identifiers.
#include "MirandaContact.h" #include <exception> #include <sstream> #include <m_contacts.h> #include <m_core.h> std::wstring MirandaContact::GetUID(HANDLE contactHandle) { auto contactInfo = CONTACTINFO(); contactInfo.hContact = contactHandle; contactInfo.dwFlag = CNF_UNIQUEID | CNF_UNICODE; if (CallService(MS_CONTACT_GETCONTACTINFO, 0, reinterpret_cast<LPARAM>(&contactInfo))) { throw std::exception("Contact not found"); } // There are unique identifiers of different types, so: auto stream = std::wostringstream(); switch (contactInfo.type) { case CNFT_BYTE: stream << contactInfo.bVal; break; case CNFT_WORD: stream << contactInfo.wVal; break; case CNFT_DWORD: stream << contactInfo.dVal; break; case CNFT_ASCIIZ: stream << contactInfo.pszVal; default: throw std::exception("Unknown contact info value type"); } return stream.str(); }
#include "MirandaContact.h" #include <exception> #include <sstream> #include <m_contacts.h> #include <m_core.h> std::wstring MirandaContact::GetUID(HANDLE contactHandle) { auto contactInfo = CONTACTINFO(); contactInfo.hContact = contactHandle; contactInfo.dwFlag = CNF_UNIQUEID | CNF_UNICODE; if (CallService(MS_CONTACT_GETCONTACTINFO, 0, reinterpret_cast<LPARAM>(&contactInfo))) { throw std::exception("Contact not found"); } // There are unique identifiers of different types, so: auto stream = std::wostringstream(); switch (contactInfo.type) { case CNFT_BYTE: stream << contactInfo.bVal; break; case CNFT_WORD: stream << contactInfo.wVal; break; case CNFT_DWORD: stream << contactInfo.dVal; break; case CNFT_ASCIIZ: stream << contactInfo.pszVal; break; default: throw std::exception("Unknown contact info value type"); } return stream.str(); }
Patch broken build. To be reviewed by the author.
#include "findCollidingNames.h" #include "symtab.h" #include "stringutil.h" /* Goal: * Find symbols that have names which already exist and munge those. * Strategy: * Keep track of all function symbols, type symbols and variable symbols in vector structures. * Search those structures for colliding names and change the cname to a unique name. * Initially all the cnames are the same as name; then we change them as needed. * */ void FindCollidingNames::processSymbol(Symbol* sym) { if (_adhoc_to_uniform_mangling) { if (FnSymbol* fnsym = dynamic_cast<FnSymbol*>(sym)) { fnsyms.add(fnsym); } if (TypeSymbol* typesym = dynamic_cast<TypeSymbol*>(sym)) { typesyms.add(typesym); } if (VarSymbol* varsym = dynamic_cast<VarSymbol*>(sym)) { if (varsym->parentScope->type == SCOPE_MODULE) { globalvars.add(varsym); } } } } /*void FindCollidingNames::run(ModuleList* moduleList) { SymtabTraversal::run(moduleList); //RED: for test purposes only fnsyms.quickSort(0, fnsyms.length()-1); }*/
#include "findCollidingNames.h" #include "symtab.h" #include "stringutil.h" /* Goal: * Find symbols that have names which already exist and munge those. * Strategy: * Keep track of all function symbols, type symbols and variable symbols in vector structures. * Search those structures for colliding names and change the cname to a unique name. * Initially all the cnames are the same as name; then we change them as needed. * */ void FindCollidingNames::processSymbol(Symbol* sym) { if (_adhoc_to_uniform_mangling) { if (FnSymbol* fnsym = dynamic_cast<FnSymbol*>(sym)) { fnsyms.add(fnsym); } if (TypeSymbol* typesym = dynamic_cast<TypeSymbol*>(sym)) { typesyms.add(typesym); } if (VarSymbol* varsym = dynamic_cast<VarSymbol*>(sym)) { if (varsym->parentScope->type == SCOPE_MODULE) { globalvars.add(varsym); } } } } void FindCollidingNames::run(ModuleList* moduleList) { /* SymtabTraversal::run(moduleList); //RED: for test purposes only fnsyms.quickSort(0, fnsyms.length()-1); */ }
Make snapshot buffer shorter so we don't touch uninitialized memory.
#include "buffers.h" #include "strutil.h" #include "log.h" void processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) { uint8_t snapshot[QUEUE_MAX_LENGTH(uint8_t)]; queue_snapshot(queue, snapshot); if(callback == NULL) { debug("Callback is NULL (%p) -- unable to handle queue at %p\r\n", callback, queue); return; } if(callback(snapshot)) { queue_init(queue); } else if(queue_full(queue)) { debug("Incoming write is too long\r\n"); queue_init(queue); } else if(strnchr((char*)snapshot, queue_length(queue) - 1, '\0') != NULL) { debug("Incoming buffered write corrupted (%s) -- clearing buffer\r\n", snapshot); queue_init(queue); } }
#include "buffers.h" #include "strutil.h" #include "log.h" void processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) { uint8_t snapshot[queue_length(queue)]; queue_snapshot(queue, snapshot); if(callback == NULL) { debug("Callback is NULL (%p) -- unable to handle queue at %p\r\n", callback, queue); return; } if(callback(snapshot)) { queue_init(queue); } else if(queue_full(queue)) { debug("Incoming write is too long\r\n"); queue_init(queue); } else if(strnchr((char*)snapshot, queue_length(queue) - 1, '\0') != NULL) { debug("Incoming buffered write corrupted (%s) -- clearing buffer\r\n", snapshot); queue_init(queue); } }
Simplify fib by one instruction
// Conventions: // O is the stack pointer (post-decrement) // B is the (so far only) return register // C is the (so far only) argument register // N is the relative-jump temp register #ifndef ARGUMENT #define ARGUMENT 10 #endif #include "common.th" _start: prologue // sets up base/stack pointer c <- ARGUMENT // argument call(fib) illegal fib: push(d) d <- 1 d <- d < c // zero or one ? jnzrel(d,_recurse) // not-zero is true (c >= 2) b <- c pop(d) ret _recurse: push(c) c <- c - 1 call(fib) pop(c) push(b) c <- c - 2 call(fib) d <- b pop(b) b <- d + b pop(d) ret
// Conventions: // O is the stack pointer (post-decrement) // B is the (so far only) return register // C is the (so far only) argument register // N is the relative-jump temp register #ifndef ARGUMENT #define ARGUMENT 10 #endif #include "common.th" _start: prologue // sets up base/stack pointer c <- ARGUMENT // argument call(fib) illegal fib: push(d) d <- c > 1 // not zero or one ? jnzrel(d,_recurse) // not-zero is true (c >= 2) b <- c pop(d) ret _recurse: push(c) c <- c - 1 call(fib) pop(c) push(b) c <- c - 2 call(fib) d <- b pop(b) b <- d + b pop(d) ret
Add comment about Retina display support
#include <QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setAttribute(Qt::AA_UseHighDpiPixmaps); QIcon appIcon; appIcon.addFile(":/Icons/AppIcon32"); appIcon.addFile(":/Icons/AppIcon128"); app.setWindowIcon(appIcon); MainWindow mainWindow; mainWindow.show(); return app.exec(); }
#include <QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); // Retina display support for Mac OS, iOS and X11: // http://blog.qt.digia.com/blog/2013/04/25/retina-display-support-for-mac-os-ios-and-x11/ // // AA_UseHighDpiPixmaps attribute is off by default in Qt 5.1 but will most // likely be on by default in a future release of Qt. app.setAttribute(Qt::AA_UseHighDpiPixmaps); QIcon appIcon; appIcon.addFile(":/Icons/AppIcon32"); appIcon.addFile(":/Icons/AppIcon128"); app.setWindowIcon(appIcon); MainWindow mainWindow; mainWindow.show(); return app.exec(); }
Fix breakpoint_set_restart test for Windows
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <iostream> #include <stdio.h> int main(int argc, char const *argv[]) { getchar(); printf("Set a breakpoint here.\n"); return 0; }
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <chrono> #include <stdio.h> #include <thread> int main(int argc, char const *argv[]) { static bool done = false; while (!done) { std::this_thread::sleep_for(std::chrono::milliseconds{100}); } printf("Set a breakpoint here.\n"); return 0; }
Fix name of generated SpriteSheet assets and enable compression for them
#include "spritesheet_importer.h" #include "halley/core/graphics/sprite/sprite_sheet.h" #include "halley/tools/file/filesystem.h" #include "halley/bytes/byte_serializer.h" #include "halley/file_formats/yaml_convert.h" using namespace Halley; void SpriteSheetImporter::import(const ImportingAsset& asset, IAssetCollector& collector) { SpriteSheet sheet; sheet.load(YAMLConvert::parseConfig(asset.inputFiles.at(0).data).getRoot()); collector.output(asset.assetId, AssetType::SpriteSheet, Serializer::toBytes(sheet)); }
#include "spritesheet_importer.h" #include "halley/core/graphics/sprite/sprite_sheet.h" #include "halley/tools/file/filesystem.h" #include "halley/bytes/byte_serializer.h" #include "halley/file_formats/yaml_convert.h" using namespace Halley; void SpriteSheetImporter::import(const ImportingAsset& asset, IAssetCollector& collector) { SpriteSheet sheet; sheet.load(YAMLConvert::parseConfig(asset.inputFiles.at(0).data).getRoot()); Metadata meta = asset.inputFiles.at(0).metadata; meta.set("asset_compression", "deflate"); collector.output(Path(asset.assetId).replaceExtension("").string(), AssetType::SpriteSheet, Serializer::toBytes(sheet), meta); }
Fix mapper0 readPrg ignoring ram
#include <cstdint> #include <Mapper0.h> uint8_t Mapper0::readPrg(uint16_t addr) { int index = addr % cartMemory.prg.size(); return cartMemory.prg[index]; } uint8_t Mapper0::readChr(uint16_t addr) { int index = addr % cartMemory.chr.size(); return cartMemory.chr[index]; } void Mapper0::writeChr(uint16_t addr, uint8_t value) { if (cartMemory.chrIsRam) { int index = addr % cartMemory.chr.size(); cartMemory.chr[index] = value; } }
#include <cstdint> #include <Mapper0.h> uint8_t Mapper0::readPrg(uint16_t addr) { if (addr >= 0x8000) { int index = addr % cartMemory.prg.size(); return cartMemory.prg[index]; } else if (addr >= 0x6000) { int index = addr % 0x2000; return cartMemory.ram[index]; } else { return 0; } } uint8_t Mapper0::readChr(uint16_t addr) { int index = addr % cartMemory.chr.size(); return cartMemory.chr[index]; } void Mapper0::writeChr(uint16_t addr, uint8_t value) { if (cartMemory.chrIsRam) { int index = addr % cartMemory.chr.size(); cartMemory.chr[index] = value; } }
Update use of audio cache function after rename
#include "stdafx.h" #include "ExampleState.h" ExampleState::ExampleState() { // Create an example object to display on screen std::unique_ptr<ExampleObject> player(new ExampleObject()); object_manager_.Add(std::move(player)); // SFML will play audio in a seperate thread so we dont have to worry about that // and just play the song auto song = audio_cache_.GetSong("sounds/example.flac"); if (song != nullptr) { song->setLoop(true); song->play(); } } ExampleState::~ExampleState() { } void ExampleState::Draw(sf::RenderWindow& window, int32_t dt) { object_manager_.DrawAll(window, dt); } void ExampleState::Update(int32_t dt) { object_manager_.UpdateAll(dt); } void ExampleState::HandleInput() { }
#include "stdafx.h" #include "ExampleState.h" ExampleState::ExampleState() { // Create an example object to display on screen std::unique_ptr<ExampleObject> player(new ExampleObject()); object_manager_.Add(std::move(player)); // SFML will play audio in a seperate thread so we dont have to worry about that // and just play the song auto song = audio_cache_.GetMusic("sounds/example.flac"); if (song != nullptr) { song->setLoop(true); song->play(); } } ExampleState::~ExampleState() { } void ExampleState::Draw(sf::RenderWindow& window, int32_t dt) { object_manager_.DrawAll(window, dt); } void ExampleState::Update(int32_t dt) { object_manager_.UpdateAll(dt); } void ExampleState::HandleInput() { }
Use div instead of span to gain flexibility
#ifdef __WAND__ target[name[item.o] type[object]] #endif #include "item.h" #include "macro.h" #include "commentprocessor.h" #include <herbs/intformat/intformat.h> #include <herbs/exceptionmissing/exceptionmissing.h> Herbs::String Doxymax::Item::expand(const Macro& macro,CommentProcessor& processor) { if(macro.args.length()<1) {throw Herbs::ExceptionMissing(___FILE__,__LINE__);} Herbs::String str_out(64); str_out.append(STR("<li class=\"itemdoxmax\"")); if(processor.macroExpansionDepth()==1) {str_out.append(STR(" style=\"position:relative\""));} str_out.append(STR("><span class=\"itemhead\">")).append(macro.args[0]) .append(STR("</span>")); if(macro.args.length()>2) { str_out.append(STR("<span class=\"itemcomment\">")) .append(macro.args[2]) .append(STR("</span>")); } if(macro.args.length()>1) { str_out.append(macro.args[1]); } str_out.append(STR("</li>")); return std::move(str_out); }
#ifdef __WAND__ target[name[item.o] type[object]] #endif #include "item.h" #include "macro.h" #include "commentprocessor.h" #include <herbs/intformat/intformat.h> #include <herbs/exceptionmissing/exceptionmissing.h> Herbs::String Doxymax::Item::expand(const Macro& macro,CommentProcessor& processor) { if(macro.args.length()<1) {throw Herbs::ExceptionMissing(___FILE__,__LINE__);} Herbs::String str_out(64); str_out.append(STR("<li class=\"itemdoxmax\"")); if(processor.macroExpansionDepth()==1) {str_out.append(STR(" style=\"position:relative\""));} str_out.append(STR("><div class=\"itemhead\">")).append(macro.args[0]) .append(STR("</div>")); if(macro.args.length()>2) { str_out.append(STR("<div class=\"itemcomment\">")) .append(macro.args[2]) .append(STR("</div>")); } if(macro.args.length()>1) { str_out.append(macro.args[1]); } str_out.append(STR("</li>")); return std::move(str_out); }
Add try-block handling failed connections
#include "paxos/logging.hpp" #include "paxos/sender.hpp" #include <boost/asio/io_service.hpp> using boost::asio::ip::tcp; BoostTransport::BoostTransport() : io_service_(), socket_(io_service_) { } BoostTransport::~BoostTransport() { socket_.close(); } void BoostTransport::Connect(std::string hostname, short port) { tcp::resolver resolver(io_service_); auto endpoint = resolver.resolve({hostname, std::to_string(port)}); boost::asio::connect(socket_, endpoint); } void BoostTransport::Write(std::string content) { boost::asio::write(socket_, boost::asio::buffer(content.c_str(), content.size())); }
#include "paxos/logging.hpp" #include "paxos/sender.hpp" #include <boost/asio/io_service.hpp> using boost::asio::ip::tcp; BoostTransport::BoostTransport() : io_service_(), socket_(io_service_) { } BoostTransport::~BoostTransport() { socket_.close(); } void BoostTransport::Connect(std::string hostname, short port) { tcp::resolver resolver(io_service_); auto endpoint = resolver.resolve({hostname, std::to_string(port)}); try { boost::asio::connect(socket_, endpoint); } catch (const boost::system::system_error& e) { LOG(LogLevel::Warning) << "Could not connect to " << hostname << ":" << port; } } void BoostTransport::Write(std::string content) { try { boost::asio::write(socket_, boost::asio::buffer(content.c_str(), content.size())); } catch (const boost::system::system_error& e) { LOG(LogLevel::Warning) << "Could not write to transport"; } }
Call initialize method during WM_INITDIALOG
#include "Tab.h" #include "UIContext.h" Tab::Tab() { } Tab::~Tab() { delete _ctxt; } DLGPROC Tab::TabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { unsigned short nCode, ctrlId; switch (message) { case WM_INITDIALOG: _hWnd = hDlg; _ctxt = new UIContext(hDlg); LoadSettings(); return FALSE; case WM_COMMAND: PropSheet_Changed(GetParent(hDlg), NULL); nCode = HIWORD(wParam); ctrlId = LOWORD(wParam); return Command(nCode, ctrlId); case WM_NOTIFY: NMHDR *nHdr = (NMHDR *) lParam; return Notification(nHdr); } return FALSE; }
#include "Tab.h" #include "UIContext.h" Tab::Tab() { } Tab::~Tab() { delete _ctxt; } DLGPROC Tab::TabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { unsigned short nCode, ctrlId; switch (message) { case WM_INITDIALOG: _hWnd = hDlg; _ctxt = new UIContext(hDlg); Initialize(); LoadSettings(); return FALSE; case WM_COMMAND: PropSheet_Changed(GetParent(hDlg), NULL); nCode = HIWORD(wParam); ctrlId = LOWORD(wParam); return Command(nCode, ctrlId); case WM_NOTIFY: NMHDR *nHdr = (NMHDR *) lParam; return Notification(nHdr); } return FALSE; }
Make the test not crash.
// // Copyright © 2016 D.E. Goodman-Wilson. All rights reserved. // #include <gtest/gtest.h> #include <slack/slack.h> #include <cpr/cpr.h> #include "environment.h" ::Environment* env; int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); env = dynamic_cast<::Environment*>(::testing::AddGlobalTestEnvironment(new ::Environment(std::getenv("SLACK_TOKEN")))); return RUN_ALL_TESTS(); }
// // Copyright © 2016 D.E. Goodman-Wilson. All rights reserved. // #include <gtest/gtest.h> #include <slack/slack.h> #include <cpr/cpr.h> #include "environment.h" ::Environment* env; int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); if(!std::getenv("SLACK_TOKEN")) { std::cerr << "please set environment variable SLACK_TOKEN" << std::endl; exit(1); } env = dynamic_cast<::Environment*>(::testing::AddGlobalTestEnvironment(new ::Environment(std::getenv("SLACK_TOKEN")))); return RUN_ALL_TESTS(); }
Adjust M113 simple powertrain parameters.
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Simple powertrain model for the M113 vehicle. // - simple speed-torque curve // - no torque converter // - no transmission box // // ============================================================================= #include "m113/M113_SimplePowertrain.h" using namespace chrono; using namespace chrono::vehicle; namespace m113 { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double M113_SimplePowertrain::m_max_torque = 1000; const double M113_SimplePowertrain::m_max_speed = 3000; const double M113_SimplePowertrain::m_fwd_gear_ratio = 0.3; const double M113_SimplePowertrain::m_rev_gear_ratio = -0.3; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- M113_SimplePowertrain::M113_SimplePowertrain() : ChSimplePowertrain() { } } // end namespace m113
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Simple powertrain model for the M113 vehicle. // - simple speed-torque curve // - no torque converter // - no transmission box // // ============================================================================= #include "m113/M113_SimplePowertrain.h" using namespace chrono; using namespace chrono::vehicle; namespace m113 { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double M113_SimplePowertrain::m_max_torque = 1000; const double M113_SimplePowertrain::m_max_speed = 3000 * CH_C_2PI; const double M113_SimplePowertrain::m_fwd_gear_ratio = 0.1; const double M113_SimplePowertrain::m_rev_gear_ratio = -0.3; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- M113_SimplePowertrain::M113_SimplePowertrain() : ChSimplePowertrain() { } } // end namespace m113
Fix const qualifer, since that's the most critical thing according to CLion
#include <iostream> #include <vector> #include <fstream> #include "../include/args.h" #include "errors/RuntimeError.h" #include "execution/Program.h" #include "loader/ProgramReader.h" int main(int argc, char **argv) { args::ArgumentParser parser("thinglang's runtime environment"); args::HelpFlag help(parser, "help", "Display this help", {'h', "help"}); args::Group group(parser, "", args::Group::Validators::Xor); args::Positional<std::string> filename(group, "file", "a file containing thinglang bytecode"); args::Flag version(group, "version", "Prints the version and exits", {'v', "version"}); try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::Error e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } if(version) { std::cerr << "thinglang runtime, version 0.0.0" << std::endl; return 0; } auto reader = ProgramReader(filename.Get()); try { auto info = reader.process(); Program::load(info); Program::start(); } catch (const RuntimeError &err) { std::cerr << "Error during execution: " << err.what() << std::endl; return 1; } }
#include <iostream> #include <vector> #include <fstream> #include "../include/args.h" #include "errors/RuntimeError.h" #include "execution/Program.h" #include "loader/ProgramReader.h" int main(const int argc, const char **argv) { args::ArgumentParser parser("thinglang's runtime environment"); args::HelpFlag help(parser, "help", "Display this help", {'h', "help"}); args::Group group(parser, "", args::Group::Validators::Xor); args::Positional<std::string> filename(group, "file", "a file containing thinglang bytecode"); args::Flag version(group, "version", "Prints the version and exits", {'v', "version"}); try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::Error e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } if(version) { std::cerr << "thinglang runtime, version 0.0.0" << std::endl; return 0; } auto reader = ProgramReader(filename.Get()); try { auto info = reader.process(); Program::load(info); Program::start(); } catch (const RuntimeError &err) { std::cerr << "Error during execution: " << err.what() << std::endl; return 1; } }
Optimize printf -> puts — just one useless step
//============================================================================= // ■ ASM76/ASM76.cpp //----------------------------------------------------------------------------- // 全局变量与实用函数。 //============================================================================= #include "ASM76.hpp" namespace ASM76 { //------------------------------------------------------------------------- // ● 全局变量 //------------------------------------------------------------------------- //------------------------------------------------------------------------- // ● 初始化 //------------------------------------------------------------------------- void init() { printf("Init ASM76 environment\n"); // nothing to do here now } //------------------------------------------------------------------------- // ● 结束处理 //------------------------------------------------------------------------- void terminate() { printf("Terminate ASM76 environment\n"); } }
//============================================================================= // ■ ASM76/ASM76.cpp //----------------------------------------------------------------------------- // 全局变量与实用函数。 //============================================================================= #include "ASM76.hpp" namespace ASM76 { //------------------------------------------------------------------------- // ● 全局变量 //------------------------------------------------------------------------- //------------------------------------------------------------------------- // ● 初始化 //------------------------------------------------------------------------- void init() { puts("Init ASM76 environment"); // nothing to do here now } //------------------------------------------------------------------------- // ● 结束处理 //------------------------------------------------------------------------- void terminate() { puts("Terminate ASM76 environment"); } }
Remove intentional failure again, so build can pass
static void (*real_one) (); static void stub(){} /* in CheatSheetTest.cpp */ #include "CppUTest/TestHarness.h" /* Declare TestGroup with name CheatSheet */ TEST_GROUP(CheatSheet) { /* declare a setup method for the test group. Optional. */ void setup () { /* Set method real_one to stub. Automatically restore in teardown */ UT_PTR_SET(real_one, stub); } /* Declare a teardown method for the test group. Optional */ void teardown() { } }; /* Do not forget semicolumn */ /* Declare one test within the test group */ TEST(CheatSheet, TestName) { /* Check two longs are equal */ LONGS_EQUAL(1, 2); /* Check a condition */ CHECK(true == true); /* Check a string */ STRCMP_EQUAL("HelloWorld", "HelloWorld"); }
static void (*real_one) (); static void stub(){} /* in CheatSheetTest.cpp */ #include "CppUTest/TestHarness.h" /* Declare TestGroup with name CheatSheet */ TEST_GROUP(CheatSheet) { /* declare a setup method for the test group. Optional. */ void setup () { /* Set method real_one to stub. Automatically restore in teardown */ UT_PTR_SET(real_one, stub); } /* Declare a teardown method for the test group. Optional */ void teardown() { } }; /* Do not forget semicolumn */ /* Declare one test within the test group */ TEST(CheatSheet, TestName) { /* Check two longs are equal */ LONGS_EQUAL(1, 1); /* Check a condition */ CHECK(true == true); /* Check a string */ STRCMP_EQUAL("HelloWorld", "HelloWorld"); }
Make it more obvious that a file name should follow.
#include "Image.h" namespace hm { Image::Image() { } Image::Image(std::string filename, SDL_Renderer* renderer) { loadImage(filename, renderer); } void Image::loadImage(std::string filename, SDL_Renderer* renderer) { // Unload a previous image. if(texture != nullptr) { SDL_DestroyTexture(texture); texture = nullptr; } SDL_Surface* surface = IMG_Load(filename.c_str()); // Check if it was loaded. if(surface == NULL) { std::cout << "Could not open " << filename << std::endl; return; } // Color key surface Uint32 key = SDL_MapRGB(surface->format, 0xFF, 0x00, 0xFF); SDL_SetColorKey(surface, SDL_TRUE, key); // Convert to texture. texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); surface = nullptr; // Get dimensions. SDL_QueryTexture(texture, nullptr, nullptr, &info.w, &info.h); return; } void Image::setColorKey(Uint8 r, Uint8 g, Uint8 b) { color_key = { r, g, b, 0 }; return; } }
#include "Image.h" namespace hm { Image::Image() { } Image::Image(std::string filename, SDL_Renderer* renderer) { loadImage(filename, renderer); } void Image::loadImage(std::string filename, SDL_Renderer* renderer) { // Unload a previous image. if(texture != nullptr) { SDL_DestroyTexture(texture); texture = nullptr; } SDL_Surface* surface = IMG_Load(filename.c_str()); // Check if it was loaded. if(surface == NULL) { std::cout << "Could not open image: " << filename << std::endl; return; } // Color key surface Uint32 key = SDL_MapRGB(surface->format, 0xFF, 0x00, 0xFF); SDL_SetColorKey(surface, SDL_TRUE, key); // Convert to texture. texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); surface = nullptr; // Get dimensions. SDL_QueryTexture(texture, nullptr, nullptr, &info.w, &info.h); return; } void Image::setColorKey(Uint8 r, Uint8 g, Uint8 b) { color_key = { r, g, b, 0 }; return; } }
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_; }
Use vprDEBUG instead of std::cout to print the current string value.
#include <iostream> #include <StringObserverImpl.h> void StringObserverImpl::update() { char* cur_value = mSubject->getValue(); std::cout << "Current string value is now '" << cur_value << "'\n"; delete cur_value; }
#include <vpr/Util/Debug.h> #include <StringObserverImpl.h> void StringObserverImpl::update() { char* cur_value = mSubject->getValue(); vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) << "Current string value is now '" << cur_value << "'\n" << vprDEBUG_FLUSH; delete cur_value; }
Expand test of C++0x [class.copymove]p15 to make sure we're actually calling the copy constructor of a base/member from an explicitly-defaulted copy constructor, rather than the default constructor
// RUN: %clang_cc1 -fsyntax-only -std=c++0x -verify %s namespace PR10622 { struct foo { const int first; foo(const foo&) = default; }; void find_or_insert(const foo& __obj) { foo x(__obj); } }
// RUN: %clang_cc1 -fsyntax-only -std=c++0x -verify %s namespace PR10622 { struct foo { const int first; foo(const foo&) = default; }; void find_or_insert(const foo& __obj) { foo x(__obj); } struct bar : foo { bar(const bar&) = default; }; void test_bar(const bar &obj) { bar obj2(obj); } }
Fix build error in versions below MSVC 12.0
#include "tgbot/Bot.h" #include "tgbot/EventBroadcaster.h" #if __cplusplus < 201402L namespace std { template<class T> struct _Unique_if { typedef unique_ptr<T> _Single_object; }; template<class T> struct _Unique_if<T[]> { typedef unique_ptr<T[]> _Unknown_bound; }; template<class T, size_t N> struct _Unique_if<T[N]> { typedef void _Known_bound; }; template<class T, class... Args> typename _Unique_if<T>::_Single_object make_unique(Args&&... args) { return unique_ptr<T>(new T(std::forward<Args>(args)...)); } template<class T> typename _Unique_if<T>::_Unknown_bound make_unique(size_t n) { typedef typename remove_extent<T>::type U; return unique_ptr<T>(new U[n]()); } template<class T, class... Args> typename _Unique_if<T>::_Known_bound make_unique(Args&&...) = delete; } #endif namespace TgBot { Bot::Bot(std::string token, const HttpClient& httpClient) : _token(std::move(token)) , _api(_token, httpClient) , _eventBroadcaster(std::make_unique<EventBroadcaster>()) , _eventHandler(getEvents()) { } }
#include "tgbot/Bot.h" #include "tgbot/EventBroadcaster.h" #if __cplusplus == 201103L namespace std { template<typename T> inline std::unique_ptr<T> make_unique() { return std::unique_ptr<T>(new T()); } } #endif namespace TgBot { Bot::Bot(std::string token, const HttpClient& httpClient) : _token(std::move(token)) , _api(_token, httpClient) , _eventBroadcaster(std::make_unique<EventBroadcaster>()) , _eventHandler(getEvents()) { } }
Add variable to capture arguments that should be passed to the user program This is unused so far.
//===- bugpoint.cpp - The LLVM BugPoint utility ---------------------------===// // // This program is an automated compiler debugger tool. It is used to narrow // down miscompilations and crash problems to a specific pass in the compiler, // and the specific Module or Function input that is causing the problem. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "Support/CommandLine.h" #include "llvm/Support/PassNameParser.h" static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input llvm ll/bc files>")); // The AnalysesList is automatically populated with registered Passes by the // PassNameParser. // static cl::list<const PassInfo*, bool, PassNameParser> PassList(cl::desc("Passes available:"), cl::ZeroOrMore); //cl::list<std::string> //InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); BugDriver D(argv[0]); if (D.addSources(InputFilenames)) return 1; D.addPasses(PassList.begin(), PassList.end()); return D.run(); }
//===- bugpoint.cpp - The LLVM BugPoint utility ---------------------------===// // // This program is an automated compiler debugger tool. It is used to narrow // down miscompilations and crash problems to a specific pass in the compiler, // and the specific Module or Function input that is causing the problem. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "Support/CommandLine.h" #include "llvm/Support/PassNameParser.h" static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input llvm ll/bc files>")); // The AnalysesList is automatically populated with registered Passes by the // PassNameParser. // static cl::list<const PassInfo*, bool, PassNameParser> PassList(cl::desc("Passes available:"), cl::ZeroOrMore); // Anything specified after the --args option are taken as arguments to the // program being debugged. cl::list<std::string> InputArgv("args", cl::Positional, cl::desc("<program arguments>..."), cl::ZeroOrMore); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); BugDriver D(argv[0]); if (D.addSources(InputFilenames)) return 1; D.addPasses(PassList.begin(), PassList.end()); return D.run(); }
Disable a broken test on windows 64-bits
// RUN: %clang_cl_asan -O0 %p/dll_host.cc -Fe%t // RUN: %clang_cl_asan -LD -O0 %s -Fe%t.dll // RUN: not %run %t %t.dll 2>&1 | FileCheck %s #include <string.h> extern "C" __declspec(dllexport) int test_function() { char buff[6] = "Hello"; memchr(buff, 'z', 7); // CHECK: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: READ of size 7 at [[ADDR]] thread T0 // CHECK-NEXT: __asan_wrap_memchr // CHECK-NEXT: memchr // CHECK-NEXT: test_function {{.*}}dll_intercept_memchr.cc:[[@LINE-5]] // CHECK: Address [[ADDR]] is located in stack of thread T0 at offset {{.*}} in frame // CHECK-NEXT: test_function {{.*}}dll_intercept_memchr.cc // CHECK: 'buff' <== Memory access at offset {{.*}} overflows this variable return 0; }
// RUN: %clang_cl_asan -O0 %p/dll_host.cc -Fe%t // RUN: %clang_cl_asan -LD -O0 %s -Fe%t.dll // RUN: not %run %t %t.dll 2>&1 | FileCheck %s // On windows 64-bit, the memchr function is written in assembly and is not // hookable with the interception library. There is not enough padding before // the function and there is a short jump on the second instruction which // doesn't not allow enough space to encode a 64-bit indirect jump. // UNSUPPORTED: x86_64-windows #include <string.h> extern "C" __declspec(dllexport) int test_function() { char buff[6] = "Hello"; memchr(buff, 'z', 7); // CHECK: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: READ of size 7 at [[ADDR]] thread T0 // CHECK-NEXT: __asan_wrap_memchr // CHECK-NEXT: memchr // CHECK-NEXT: test_function {{.*}}dll_intercept_memchr.cc:[[@LINE-5]] // CHECK: Address [[ADDR]] is located in stack of thread T0 at offset {{.*}} in frame // CHECK-NEXT: test_function {{.*}}dll_intercept_memchr.cc // CHECK: 'buff' <== Memory access at offset {{.*}} overflows this variable return 0; }
Reduce search space when looking for pawns
#include "Genes/Stacked_Pawns_Gene.h" #include <memory> #include <string> #include "Game/Board.h" #include "Game/Piece.h" #include "Game/Color.h" #include "Genes/Gene.h" double Stacked_Pawns_Gene::score_board(const Board& board, Color perspective, size_t) const { double score = 0.0; auto own_pawn = board.piece_instance(PAWN, perspective); for(char file = 'a'; file <= 'h'; ++file) { int pawn_count = 0; for(int rank = 1; rank <= 8; ++rank) { if(board.piece_on_square(file, rank) == own_pawn) { ++pawn_count; } } if(pawn_count > 1) { score += pawn_count - 1; } } return -score/6; // negative since, presumably, stacked pawns are bad; // priority can still evolve to be negative. // Divide by six since six is the maximum number of pawns // that can be blocked by other pawns. } std::unique_ptr<Gene> Stacked_Pawns_Gene::duplicate() const { return std::make_unique<Stacked_Pawns_Gene>(*this); } std::string Stacked_Pawns_Gene::name() const { return "Stacked Pawns Gene"; }
#include "Genes/Stacked_Pawns_Gene.h" #include <memory> #include <string> #include "Game/Board.h" #include "Game/Piece.h" #include "Game/Color.h" #include "Genes/Gene.h" double Stacked_Pawns_Gene::score_board(const Board& board, Color perspective, size_t) const { double score = 0.0; auto own_pawn = board.piece_instance(PAWN, perspective); for(char file = 'a'; file <= 'h'; ++file) { int pawn_count = 0; for(int rank = 2; rank <= 7; ++rank) { if(board.piece_on_square(file, rank) == own_pawn) { ++pawn_count; } } if(pawn_count > 1) { score += pawn_count - 1; } } return -score/6; // negative since, presumably, stacked pawns are bad; // priority can still evolve to be negative. // Divide by six since six is the maximum number of pawns // that can be blocked by other pawns. } std::unique_ptr<Gene> Stacked_Pawns_Gene::duplicate() const { return std::make_unique<Stacked_Pawns_Gene>(*this); } std::string Stacked_Pawns_Gene::name() const { return "Stacked Pawns Gene"; }
Set integrator microseconds value at end of tick
#include "common.h" #include "Integrator.h" #include "IntegrableProperty.h" #include "EventManager.h" void Integrator::Update(DeltaTicks &dt) { accumulator += dt; if(accumulator.Seconds() > 1.0f) { accumulator.SetSeconds(1.0f); } alphaMicroseconds = static_cast<uint32_t>(accumulator.Seconds() * 1000000.0f); while(accumulator >= timestep) { Tick(timestep.Seconds()); accumulator -= timestep; } } void Integrator::Tick(DeltaTicks::seconds_type seconds) { for(auto it = engine->objects.left.begin(); it != engine->objects.left.end(); ++it) { auto property = it->info->Get<IntegrableProperty>().lock(); if(property) { for(auto integrable : *property->GetIntegrables()) { integrable->Integrate(seconds); } } } engine->GetSystem<EventManager>().lock()->FireIn("integrator", "ticked", seconds); }
#include "common.h" #include "Integrator.h" #include "IntegrableProperty.h" #include "EventManager.h" void Integrator::Update(DeltaTicks &dt) { accumulator += dt; if(accumulator.Seconds() > 1.0f) { accumulator.SetSeconds(1.0f); } while(accumulator >= timestep) { Tick(timestep.Seconds()); accumulator -= timestep; } alphaMicroseconds = static_cast<uint32_t>(accumulator.Seconds() * 1000000.0f); } void Integrator::Tick(DeltaTicks::seconds_type seconds) { for(auto it = engine->objects.left.begin(); it != engine->objects.left.end(); ++it) { auto property = it->info->Get<IntegrableProperty>().lock(); if(property) { for(auto integrable : *property->GetIntegrables()) { integrable->Integrate(seconds); } } } engine->GetSystem<EventManager>().lock()->FireIn("integrator", "ticked", seconds); }
Use CPR by default now.
// // Copyright © 2015 Slack Technologies, Inc. All rights reserved. // #include "slack/http.h" namespace slack { namespace http { std::function<response(std::string url, params)> get; std::function<response(std::string url, params)> post; } //namespace http } //namespace slack
// // Copyright © 2015 Slack Technologies, Inc. All rights reserved. // #include "slack/http.h" #include <cpr.h> namespace slack { namespace http { std::function<response(std::string url, params)> get = [](std::string url, slack::http::params params) -> slack::http::response { cpr::Parameters p; for (auto &kv : params) { p.AddParameter({kv.first, kv.second}); } auto response = cpr::Get(cpr::Url{url}, p); return {static_cast<uint32_t>(response.status_code), response.text}; }; std::function<response(std::string url, params)> post = [](std::string url, slack::http::params params) -> slack::http::response { cpr::Parameters p; for (auto &kv : params) { p.AddParameter({kv.first, kv.second}); } auto response = cpr::Post(cpr::Url{url}, p); return {static_cast<uint32_t>(response.status_code), response.text}; }; } //namespace http } //namespace slack
Debug info - generalize namespace test to not depend on a DW_TAG_file_type entry
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s namespace A { #line 1 "foo.cpp" namespace B { int i; } } // CHECK: [[FILE:![0-9]*]]} ; [ DW_TAG_file_type ] [{{.*}}/test/CodeGenCXX/debug-info-namespace.cpp] // CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i] // CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1] // CHECK: [[CTXT]] = {{.*}}, metadata [[FILE:![0-9]*]], null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3] // CHECK: [[FILE2]]} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s namespace A { #line 1 "foo.cpp" namespace B { int i; } } // CHECK: [[FILE:![0-9]*]] {{.*}}debug-info-namespace.cpp" // CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i] // CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1] // CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3] // CHECK: [[FILE2]]} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]
Add a message when unloading a module.
/* * modules.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #pragma once #include "stdafx.h" #include "modules.h" void ModuleManager::UnloadAllModules() { for (auto iterator = modules.begin(); iterator != modules.end(); ++iterator) { delete iterator->second; } modules.clear(); }
/* * modules.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #pragma once #include "stdafx.h" #include "modules.h" void ModuleManager::UnloadAllModules() { for (auto iterator = modules.begin(); iterator != modules.end(); ++iterator) { PRINT_TAG(); ConColorMsg(Color(0, 255, 0, 255), "Module %s unloaded!\n", iterator->first.c_str()); delete iterator->second; } modules.clear(); }
Add expected note. Surely people test before the check in stuff.
// RUN: clang -fsyntax-only -verify %s class A { }; class B1 : A { }; class B2 : virtual A { }; class B3 : virtual virtual A { }; // expected-error{{duplicate 'virtual' in base specifier}} class C : public B1, private B2 { }; class D; class E : public D { }; // expected-error{{base class has incomplete type}} typedef int I; class F : public I { }; // expected-error{{base specifier must name a class}} union U1 : public A { }; // expected-error{{unions cannot have base classes}} union U2 {}; class G : public U2 { }; // expected-error{{unions cannot be base classes}} typedef G G_copy; typedef G G_copy_2; typedef G_copy G_copy_3; class H : G_copy, A, G_copy_2, // expected-error{{base class 'G_copy' specified more than once as a direct base class}} public G_copy_3 { }; // expected-error{{base class 'G_copy' specified more than once as a direct base class}}
// RUN: clang -fsyntax-only -verify %s class A { }; class B1 : A { }; class B2 : virtual A { }; class B3 : virtual virtual A { }; // expected-error{{duplicate 'virtual' in base specifier}} class C : public B1, private B2 { }; class D; // expected-note {{forward declaration of 'class D'}} class E : public D { }; // expected-error{{base class has incomplete type}} typedef int I; class F : public I { }; // expected-error{{base specifier must name a class}} union U1 : public A { }; // expected-error{{unions cannot have base classes}} union U2 {}; class G : public U2 { }; // expected-error{{unions cannot be base classes}} typedef G G_copy; typedef G G_copy_2; typedef G_copy G_copy_3; class H : G_copy, A, G_copy_2, // expected-error{{base class 'G_copy' specified more than once as a direct base class}} public G_copy_3 { }; // expected-error{{base class 'G_copy' specified more than once as a direct base class}}
Add cpp11 for test also.
void build(Solution &s) { auto &tgbot = s.addTarget<StaticLibraryTarget>("reo7sp.tgbot", "1.2.0"); { tgbot += Git("https://github.com/reo7sp/tgbot-cpp", "v{M}.{m}"); tgbot += cpp11; tgbot.Public += "org.sw.demo.boost.property_tree"_dep; tgbot.Public += "org.sw.demo.openssl.ssl"_dep; tgbot.Public += "org.sw.demo.boost.system"_dep; tgbot.Public += "org.sw.demo.boost.date_time"_dep; tgbot.Public += "org.sw.demo.badger.curl.libcurl"_dep, "HAVE_CURL"_def; tgbot.Public += "org.sw.demo.boost.asio"_dep; } auto &t = tgbot.addExecutable("test"); { t.Scope = TargetScope::Test; t += "test/.*"_rr; t += "test"_idir; t += "SW_BUILD"_def; t += tgbot; t += "org.sw.demo.boost.test"_dep; } tgbot.addTest(t); }
void build(Solution &s) { auto &tgbot = s.addTarget<StaticLibraryTarget>("reo7sp.tgbot", "1.2.0"); { tgbot += Git("https://github.com/reo7sp/tgbot-cpp", "v{M}.{m}"); tgbot += cpp11; tgbot.Public += "org.sw.demo.boost.property_tree"_dep; tgbot.Public += "org.sw.demo.openssl.ssl"_dep; tgbot.Public += "org.sw.demo.boost.system"_dep; tgbot.Public += "org.sw.demo.boost.date_time"_dep; tgbot.Public += "org.sw.demo.badger.curl.libcurl"_dep, "HAVE_CURL"_def; tgbot.Public += "org.sw.demo.boost.asio"_dep; } auto &t = tgbot.addExecutable("test"); { t.Scope = TargetScope::Test; t += cpp11; t += "test/.*"_rr; t += "test"_idir; t += "SW_BUILD"_def; t += tgbot; t += "org.sw.demo.boost.test"_dep; } tgbot.addTest(t); }
Revert "fixed typo" and "fixed crash for Windows"
#include "Log.h" #include <boost/date_time/posix_time/posix_time.hpp> Log * g_Log = nullptr; static const char * g_LogLevelStr[eNumLogLevels] = { "error", // eLogError "warn", // eLogWarning "info", // eLogInfo "debug" // eLogDebug }; void LogMsg::Process() { output << boost::posix_time::second_clock::local_time().time_of_day () << "/" << g_LogLevelStr[level] << " - "; output << s.str(); } void Log::Flush () { #ifndef _WIN32 if (m_LogFile) m_LogFile->flush(); #endif // TODO: find out what's wrong with flush for Windows } void Log::SetLogFile (const std::string& fullFilePath) { if (m_LogFile) delete m_LogFile; m_LogFile = new std::ofstream (fullFilePath, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc); if (m_LogFile->is_open ()) LogPrint("Logging to file ", fullFilePath, " enabled."); else { delete m_LogFile; m_LogFile = nullptr; } }
#include "Log.h" #include <boost/date_time/posix_time/posix_time.hpp> Log * g_Log = nullptr; static const char * g_LogLevelStr[eNumLogLevels] = { "error", // eLogError "warn", // eLogWarning "info", // eLogInfo "debug" // eLogDebug }; void LogMsg::Process() { output << boost::posix_time::second_clock::local_time().time_of_day () << "/" << g_LogLevelStr[level] << " - "; output << s.str(); } void Log::Flush () { if (m_LogFile) m_LogFile->flush(); } void Log::SetLogFile (const std::string& fullFilePath) { if (m_LogFile) delete m_LogFile; m_LogFile = new std::ofstream (fullFilePath, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc); if (m_LogFile->is_open ()) LogPrint("Logging to file ", fullFilePath, " enabled."); else { delete m_LogFile; m_LogFile = nullptr; } }
Remove dead includes in folly/python
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/python/executor.h> #include <stdexcept> #include <folly/CppAttributes.h> #include <folly/python/executor_api.h> // @manual namespace folly { namespace python { namespace { void ensure_imported() { static bool imported = false; if (!imported) { if (0 != import_folly__executor()) { throw std::runtime_error("import_folly__executor failed"); } imported = true; } } } // namespace folly::Executor* getExecutor() { ensure_imported(); return get_running_executor(false); // TODO: fried set this to true } int setExecutorForLoop(PyObject* loop, AsyncioExecutor* executor) { ensure_imported(); return set_executor_for_loop(loop, executor); } } // namespace python } // namespace folly
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/python/executor.h> #include <stdexcept> #include <folly/python/executor_api.h> // @manual namespace folly { namespace python { namespace { void ensure_imported() { static bool imported = false; if (!imported) { if (0 != import_folly__executor()) { throw std::runtime_error("import_folly__executor failed"); } imported = true; } } } // namespace folly::Executor* getExecutor() { ensure_imported(); return get_running_executor(false); // TODO: fried set this to true } int setExecutorForLoop(PyObject* loop, AsyncioExecutor* executor) { ensure_imported(); return set_executor_for_loop(loop, executor); } } // namespace python } // namespace folly
Fix the safe functions calculations function to handle the new function names
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "tac/Utils.hpp" using namespace eddic; void eddic::tac::computeBlockUsage(std::shared_ptr<tac::Function> function, std::unordered_set<std::shared_ptr<tac::BasicBlock>>& usage){ for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ if(auto* ptr = boost::get<std::shared_ptr<tac::Goto>>(&statement)){ usage.insert((*ptr)->block); } else if(auto* ptr = boost::get<std::shared_ptr<tac::IfFalse>>(&statement)){ usage.insert((*ptr)->block); } else if(auto* ptr = boost::get<std::shared_ptr<tac::If>>(&statement)){ usage.insert((*ptr)->block); } } } } bool eddic::tac::safe(std::shared_ptr<tac::Call> call){ auto function = call->function; //These three functions are considered as safe because they save/restore all the registers and does not return anything return function == "print_integer" || function == "print_string" || function == "print_line"; }
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "tac/Utils.hpp" using namespace eddic; void eddic::tac::computeBlockUsage(std::shared_ptr<tac::Function> function, std::unordered_set<std::shared_ptr<tac::BasicBlock>>& usage){ for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ if(auto* ptr = boost::get<std::shared_ptr<tac::Goto>>(&statement)){ usage.insert((*ptr)->block); } else if(auto* ptr = boost::get<std::shared_ptr<tac::IfFalse>>(&statement)){ usage.insert((*ptr)->block); } else if(auto* ptr = boost::get<std::shared_ptr<tac::If>>(&statement)){ usage.insert((*ptr)->block); } } } } bool eddic::tac::safe(std::shared_ptr<tac::Call> call){ auto function = call->function; //These functions are considered as safe because they save/restore all the registers and does not return anything return function == "_F5printB" || function == "_F5printI" || function == "_F5printS" || function == "_F7printlnB" || function == "_F7printlnI" || function == "_F7printlnS" || function == "_F7println"; }
Update comments and remove bogus DCHECK in windows-specific broadcasted power message status.
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/system_monitor.h" namespace base { void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) { PowerEvent power_event; switch (event_id) { case PBT_APMPOWERSTATUSCHANGE: power_event = POWER_STATE_EVENT; break; case PBT_APMRESUMEAUTOMATIC: power_event = RESUME_EVENT; break; case PBT_APMSUSPEND: power_event = SUSPEND_EVENT; break; default: DCHECK(false); } ProcessPowerMessage(power_event); } // Function to query the system to see if it is currently running on // battery power. Returns true if running on battery. bool SystemMonitor::IsBatteryPower() { SYSTEM_POWER_STATUS status; if (!GetSystemPowerStatus(&status)) { LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError(); return false; } return (status.ACLineStatus == 0); } } // namespace base
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/system_monitor.h" namespace base { void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) { PowerEvent power_event; switch (event_id) { case PBT_APMPOWERSTATUSCHANGE: // The power status changed. power_event = POWER_STATE_EVENT; break; case PBT_APMRESUMEAUTOMATIC: // Non-user initiated resume from suspend. case PBT_APMRESUMESUSPEND: // User initiated resume from suspend. power_event = RESUME_EVENT; break; case PBT_APMSUSPEND: // System has been suspended. power_event = SUSPEND_EVENT; break; default: return; // Other Power Events: // PBT_APMBATTERYLOW - removed in Vista. // PBT_APMOEMEVENT - removed in Vista. // PBT_APMQUERYSUSPEND - removed in Vista. // PBT_APMQUERYSUSPENDFAILED - removed in Vista. // PBT_APMRESUMECRITICAL - removed in Vista. // PBT_POWERSETTINGCHANGE - user changed the power settings. } ProcessPowerMessage(power_event); } // Function to query the system to see if it is currently running on // battery power. Returns true if running on battery. bool SystemMonitor::IsBatteryPower() { SYSTEM_POWER_STATUS status; if (!GetSystemPowerStatus(&status)) { LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError(); return false; } return (status.ACLineStatus == 0); } } // namespace base
Switch to nesting for less repetitive error handling.
#include <ShObjIdl.h> #include <atlbase.h> #include <wchar.h> int wmain(int argc, wchar_t* argv[]) { HRESULT hr = S_OK; if (argc < 2) { hr = E_INVALIDARG; wprintf(L"Supply an app ID (AppUserModelId) for the application to launch."); return hr; } const wchar_t* appId = argv[1]; hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); if (FAILED(hr)) { wprintf(L"Error initializing COM"); return hr; } CComPtr<IApplicationActivationManager> aam = nullptr; hr = CoCreateInstance(CLSID_ApplicationActivationManager, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&aam)); if (FAILED(hr)) { wprintf(L"Error creating ApplicationActivationManager"); CoUninitialize(); return hr; } hr = CoAllowSetForegroundWindow(aam, nullptr); if (FAILED(hr)) { wprintf(L"Error calling CoAllowSetForegroundWindow"); CoUninitialize(); return hr; } unsigned long pid = 0; hr = aam->ActivateApplication(appId, nullptr, AO_NONE, &pid); if (FAILED(hr)) { wprintf(L"Error calling ActivateApplication"); CoUninitialize(); return hr; } CoUninitialize(); return hr; }
#include <ShObjIdl.h> #include <wchar.h> HRESULT CreateAAM(IApplicationActivationManager*& aam) { return CoCreateInstance(CLSID_ApplicationActivationManager, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&aam)); } HRESULT ActivateApp(IApplicationActivationManager* aam, const wchar_t* appId) { unsigned long unused = 0; return aam->ActivateApplication(appId, nullptr, AO_NONE, &unused); } int wmain(int argc, wchar_t* argv[]) { HRESULT hr = S_OK; if (argc < 2) { hr = E_INVALIDARG; wprintf(L"Supply an app ID (AppUserModelId) for the application to launch."); } else { hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); if (FAILED(hr)) { wprintf(L"Error initializing COM"); } else { IApplicationActivationManager* aam = nullptr; hr = CreateAAM(aam); if (FAILED(hr)) { wprintf(L"Error creating ApplicationActivationManager"); } else { hr = CoAllowSetForegroundWindow(aam, nullptr); if (FAILED(hr)) { wprintf(L"Error calling CoAllowSetForegroundWindow"); } else { hr = ActivateApp(aam, argv[1]); if (FAILED(hr)) { wprintf(L"Error calling ActivateApplication"); } } aam->Release(); } CoUninitialize(); } } return hr; }
Fix memory leak when initializing a device object fails.
// // Copyright 2012 Francisco Jerez // // 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 "core/platform.hpp" using namespace clover; platform::platform() : adaptor_range(derefs(), devs) { int n = pipe_loader_probe(NULL, 0); std::vector<pipe_loader_device *> ldevs(n); pipe_loader_probe(&ldevs.front(), n); for (pipe_loader_device *ldev : ldevs) { try { devs.push_back(transfer(new device(*this, ldev))); } catch (error &) {} } }
// // Copyright 2012 Francisco Jerez // // 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 "core/platform.hpp" using namespace clover; platform::platform() : adaptor_range(derefs(), devs) { int n = pipe_loader_probe(NULL, 0); std::vector<pipe_loader_device *> ldevs(n); pipe_loader_probe(&ldevs.front(), n); for (pipe_loader_device *ldev : ldevs) { try { devs.push_back(transfer(new device(*this, ldev))); } catch (error &) { pipe_loader_release(&ldev, 1); } } }
Return 0 bits in Darwin_SecRandom::poll on SecRandomCopyBytes failure
/* * Darwin SecRandomCopyBytes EntropySource * (C) 2015 Daniel Seither (Kullo GmbH) * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/darwin_secrandom.h> #include <Security/Security.h> #include <Security/SecRandom.h> namespace Botan { /** * Gather entropy from SecRandomCopyBytes */ size_t Darwin_SecRandom::poll(RandomNumberGenerator& rng) { secure_vector<uint8_t> buf(BOTAN_SYSTEM_RNG_POLL_REQUEST); if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data())) { rng.add_entropy(buf.data(), buf.size()); return buf.size() * 8; } } }
/* * Darwin SecRandomCopyBytes EntropySource * (C) 2015 Daniel Seither (Kullo GmbH) * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/darwin_secrandom.h> #include <Security/Security.h> #include <Security/SecRandom.h> namespace Botan { /** * Gather entropy from SecRandomCopyBytes */ size_t Darwin_SecRandom::poll(RandomNumberGenerator& rng) { secure_vector<uint8_t> buf(BOTAN_SYSTEM_RNG_POLL_REQUEST); if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data())) { rng.add_entropy(buf.data(), buf.size()); return buf.size() * 8; } return 0; } }
Make code compile with Qt 5.2
// Copyright (c) 2015 Klaralvdalens Datakonsult AB (KDAB). // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "debug.h" #include <QString> #include <QDebug> #include <iostream> std::ostream& operator<<(std::ostream& stream, const wchar_t *input) { return stream << qPrintable(QString::fromWCharArray(input)); } QDebug operator<<(QDebug stream, const CefString& string) { return stream << QString::fromStdString(string.ToString()); } Q_LOGGING_CATEGORY(handler, "phantomjs.handler", QtWarningMsg) Q_LOGGING_CATEGORY(print, "phantomjs.print", QtWarningMsg) Q_LOGGING_CATEGORY(app, "phantomjs.app", QtWarningMsg)
// Copyright (c) 2015 Klaralvdalens Datakonsult AB (KDAB). // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "debug.h" #include <QString> #include <QDebug> #include <iostream> std::ostream& operator<<(std::ostream& stream, const wchar_t *input) { return stream << qPrintable(QString::fromWCharArray(input)); } QDebug operator<<(QDebug stream, const CefString& string) { return stream << QString::fromStdString(string.ToString()); } #if QT_VERSION >= 0x050400 #define WARNING_BY_DEFAULT , QtWarningMsg #else #define WARNING_BY_DEFAULT #endif Q_LOGGING_CATEGORY(handler, "phantomjs.handler" WARNING_BY_DEFAULT) Q_LOGGING_CATEGORY(print, "phantomjs.print" WARNING_BY_DEFAULT) Q_LOGGING_CATEGORY(app, "phantomjs.app" WARNING_BY_DEFAULT)
Fix wrongly changed include path when removing cameo/src dir
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cameo/runtime/app/cameo_main_delegate.h" #include "content/public/app/content_main.h" #if defined(OS_WIN) #include "content/public/app/startup_helper_win.h" #include "sandbox/win/sandbox_types.h" #endif #if defined(OS_WIN) int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) { sandbox::SandboxInterfaceInfo sandbox_info = {0}; content::InitializeSandboxInfo(&sandbox_info); cameo::CameoMainDelegate delegate; return content::ContentMain(instance, &sandbox_info, &delegate); } #elif defined(OS_LINUX) int main(int argc, const char** argv) { cameo::CameoMainDelegate delegate; return content::ContentMain(argc, argv, &delegate); } #else #error "Unsupport platform." #endif
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cameo/runtime/app/cameo_main_delegate.h" #include "content/public/app/content_main.h" #if defined(OS_WIN) #include "content/public/app/startup_helper_win.h" #include "sandbox/win/src/sandbox_types.h" #endif #if defined(OS_WIN) int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) { sandbox::SandboxInterfaceInfo sandbox_info = {0}; content::InitializeSandboxInfo(&sandbox_info); cameo::CameoMainDelegate delegate; return content::ContentMain(instance, &sandbox_info, &delegate); } #elif defined(OS_LINUX) int main(int argc, const char** argv) { cameo::CameoMainDelegate delegate; return content::ContentMain(argc, argv, &delegate); } #else #error "Unsupport platform." #endif
Fix multiple definition link error
// Copyright 2016 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 "ozone/ui/desktop_aura/desktop_factory_ozone_wayland.h" #include "ozone/ui/desktop_aura/desktop_screen_wayland.h" #include "ozone/ui/desktop_aura/desktop_window_tree_host_ozone.cc" namespace views { DesktopWindowTreeHost* DesktopFactoryOzoneWayland::CreateWindowTreeHost( internal::NativeWidgetDelegate* native_widget_delegate, DesktopNativeWidgetAura* desktop_native_widget_aura) { return new DesktopWindowTreeHostOzone(native_widget_delegate, desktop_native_widget_aura); } gfx::Screen* DesktopFactoryOzoneWayland::CreateDesktopScreen() { return new DesktopScreenWayland; } DesktopFactoryOzone* CreateDesktopFactoryOzoneWayland() { return new DesktopFactoryOzoneWayland; } } // namespace views
// Copyright 2016 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 "ozone/ui/desktop_aura/desktop_factory_ozone_wayland.h" #include "ozone/ui/desktop_aura/desktop_screen_wayland.h" #include "ozone/ui/desktop_aura/desktop_window_tree_host_ozone.h" namespace views { DesktopWindowTreeHost* DesktopFactoryOzoneWayland::CreateWindowTreeHost( internal::NativeWidgetDelegate* native_widget_delegate, DesktopNativeWidgetAura* desktop_native_widget_aura) { return new DesktopWindowTreeHostOzone(native_widget_delegate, desktop_native_widget_aura); } gfx::Screen* DesktopFactoryOzoneWayland::CreateDesktopScreen() { return new DesktopScreenWayland; } DesktopFactoryOzone* CreateDesktopFactoryOzoneWayland() { return new DesktopFactoryOzoneWayland; } } // namespace views
Use LinearMemoryConfig when creating LinearMemory in test
#include <Ab/Config.hpp> #include <Ab/LinearMemory.hpp> #include <gtest/gtest.h> namespace Ab::Test { TEST(LinearMemoryTest, InitAndKill) { LinearMemory m; } TEST(LinearMemoryTest, GrowThreeTimes) { LinearMemory m; for (std::size_t i = 0; i < 3; i++) { m.grow(); } } TEST(LinearMemoryTest, AssignToMemory) { LinearMemoryConfig cfg; cfg.page_count_min = 1; cfg.page_count_max = 1; LinearMemory m(cfg); auto ptr = to_ptr<int>(m.address()); EXPECT_NE(ptr, nullptr); EXPECT_EQ(*ptr, 0); *ptr = 123; EXPECT_EQ(*ptr, 123); } } // namespace Ab::Test
#include <Ab/Config.hpp> #include <Ab/LinearMemory.hpp> #include <gtest/gtest.h> namespace Ab::Test { TEST(LinearMemoryTest, InitAndKill) { LinearMemory m; } TEST(LinearMemoryTest, GrowThreeTimes) { LinearMemoryConfig cfg; cfg.page_count_min = 0; cfg.page_count_max = 3; LinearMemory m(cfg); for (std::size_t i = 0; i < 3; i++) { m.grow(); } } TEST(LinearMemoryTest, AssignToMemory) { LinearMemoryConfig cfg; cfg.page_count_min = 1; cfg.page_count_max = 1; LinearMemory m(cfg); auto ptr = to_ptr<int>(m.address()); EXPECT_NE(ptr, nullptr); EXPECT_EQ(*ptr, 0); *ptr = 123; EXPECT_EQ(*ptr, 123); } } // namespace Ab::Test
Add missing: using namespace lld; to try to fix windows bot
//===- lib/ReaderWriter/ELF/AMDGPU/AMDGPURelocationHandler.cpp -----------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "AMDGPURelocationHandler.h" using namespace lld::elf; std::error_code AMDGPUTargetRelocationHandler::applyRelocation( ELFWriter &writer, llvm::FileOutputBuffer &buf, const AtomLayout &atom, const Reference &ref) const { return std::error_code(); }
//===- lib/ReaderWriter/ELF/AMDGPU/AMDGPURelocationHandler.cpp -----------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "AMDGPURelocationHandler.h" using namespace lld; using namespace lld::elf; std::error_code AMDGPUTargetRelocationHandler::applyRelocation( ELFWriter &writer, llvm::FileOutputBuffer &buf, const AtomLayout &atom, const Reference &ref) const { return std::error_code(); }
Fix null pointer access in HackyPassabilityAgent
#include "hackypassabilityagent.h" #include <QQuickItem> #include <QQuickWindow> #include "quickentity.h" #include "utils.h" HackyPassabilityAgent::HackyPassabilityAgent() : mGridItem(nullptr) { } bool HackyPassabilityAgent::isPassable(const QPointF &pos, AbstractEntity *entity) { if (!mGridItem) return false; QuickEntity *quickEntity = dynamic_cast<QuickEntity*>(entity); Q_ASSERT(quickEntity); // very basic, hacky check that doesn't take into account a radius. QQuickItem *child = mGridItem->childAt(pos.x(), pos.y()); if (child->property("blocksMovement").toBool()) { return false; } return true; } QQuickItem *HackyPassabilityAgent::gridItem() const { return mGridItem; } void HackyPassabilityAgent::setGridItem(QQuickItem *gridItem) { if (gridItem == mGridItem) return; mGridItem = gridItem; emit gridItemChanged(); }
#include "hackypassabilityagent.h" #include <QQuickItem> #include <QQuickWindow> #include "quickentity.h" #include "utils.h" HackyPassabilityAgent::HackyPassabilityAgent() : mGridItem(nullptr) { } bool HackyPassabilityAgent::isPassable(const QPointF &pos, AbstractEntity *entity) { if (!mGridItem) return false; QuickEntity *quickEntity = dynamic_cast<QuickEntity*>(entity); Q_ASSERT(quickEntity); // very basic, hacky check that doesn't take into account a radius. QQuickItem *child = mGridItem->childAt(pos.x(), pos.y()); if (child && child->property("blocksMovement").toBool()) { return false; } return true; } QQuickItem *HackyPassabilityAgent::gridItem() const { return mGridItem; } void HackyPassabilityAgent::setGridItem(QQuickItem *gridItem) { if (gridItem == mGridItem) return; mGridItem = gridItem; emit gridItemChanged(); }
Make while loop more compact
#include "Client.hh" #include <string> #include "Socket.hh" #include "http/Response.hh" #include "http/Request.hh" #include "methods/Get.hh" #include "Config.hh" ss::Client::Client(Socket* socket) : socket(socket) { auto request = get_request(); http::Response response; response.headers["protocol"] = "HTTP/1.1"; if (request.headers["method"] == "GET") { methods::Get(request, &response); } send_response(response); } ss::http::Request ss::Client::get_request() { std::string response; // An endless wait may happen if the last response is the same size as buffer. while (true) { char buffer[1024]; int received; socket->receive(&buffer, sizeof(buffer), &received); response.append(buffer, received); if (received < sizeof(buffer)) { break; } } return http::Request(response); } void ss::Client::send_response(const http::Response& response) { const auto response_string = response.as_string(); socket->send(response_string.data(), response_string.size()); socket->disconnect(); }
#include "Client.hh" #include <string> #include "Socket.hh" #include "http/Response.hh" #include "http/Request.hh" #include "methods/Get.hh" #include "Config.hh" ss::Client::Client(Socket* socket) : socket(socket) { auto request = get_request(); http::Response response; response.headers["protocol"] = "HTTP/1.1"; if (request.headers["method"] == "GET") { methods::Get(request, &response); } send_response(response); } ss::http::Request ss::Client::get_request() { std::string response; char buffer[1024]; int received = sizeof(buffer); // An endless wait may happen if the last response is the same size as buffer. while (received == sizeof(buffer)) { socket->receive(&buffer, sizeof(buffer), &received); response.append(buffer, received); } return http::Request(response); } void ss::Client::send_response(const http::Response& response) { const auto response_string = response.as_string(); socket->send(response_string.data(), response_string.size()); socket->disconnect(); }
Add missing keyword to UnRegister definition
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkToolGUI.h" #include <iostream> QmitkToolGUI::~QmitkToolGUI() { m_ReferenceCountLock.Lock(); m_ReferenceCount = 0; // otherwise ITK will complain in LightObject's destructor m_ReferenceCountLock.Unlock(); } void QmitkToolGUI::Register() const { // empty on purpose, just don't let ITK handle calls to Register() } void QmitkToolGUI::UnRegister() const { // empty on purpose, just don't let ITK handle calls to UnRegister() } void QmitkToolGUI::SetReferenceCount(int) { // empty on purpose, just don't let ITK handle calls to SetReferenceCount() } void QmitkToolGUI::SetTool( mitk::Tool* tool ) { m_Tool = tool; emit( NewToolAssociated(tool) ); }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkToolGUI.h" #include <iostream> QmitkToolGUI::~QmitkToolGUI() { m_ReferenceCountLock.Lock(); m_ReferenceCount = 0; // otherwise ITK will complain in LightObject's destructor m_ReferenceCountLock.Unlock(); } void QmitkToolGUI::Register() const { // empty on purpose, just don't let ITK handle calls to Register() } void QmitkToolGUI::UnRegister() const ITK_NOEXCEPT { // empty on purpose, just don't let ITK handle calls to UnRegister() } void QmitkToolGUI::SetReferenceCount(int) { // empty on purpose, just don't let ITK handle calls to SetReferenceCount() } void QmitkToolGUI::SetTool( mitk::Tool* tool ) { m_Tool = tool; emit( NewToolAssociated(tool) ); }
Update to Kate's First Function Prototype
#include <iostream> //Thomas' Prototypes //Hannah's Prototypes int atomic_distance (int distance); //Kate's Prototype: defines atomic distance as integer int (main) { using nedit file... create new input "hannah's test changes" }
#include <iostream> //Thomas' Prototypes //Hannah's Prototypes int atomic_distance (int x, int y, int z); //Kate's Prototype: defines atomic distance as combination of x, y, z coordinates int (main) { using nedit file... create new input "hannah's test changes" }
Use RTLD_DEEPBIND to make sure plugins don't use Chrome's symbols instead of their own
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY); if (!dl) NOTREACHED() << "dlopen failed: " << dlerror(); return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) NOTREACHED() << "dlclose failed: " << dlerror(); } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, NativeLibraryFunctionNameType name) { return dlsym(library, name); } } // namespace base
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY|RTLD_DEEPBIND); if (!dl) NOTREACHED() << "dlopen failed: " << dlerror(); return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) NOTREACHED() << "dlclose failed: " << dlerror(); } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, NativeLibraryFunctionNameType name) { return dlsym(library, name); } } // namespace base
Add code to remove effects
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Models/Enchantment.hpp> #include <Rosetta/Tasks/SimpleTasks/RemoveEnchantmentTask.hpp> namespace RosettaStone::SimpleTasks { TaskID RemoveEnchantmentTask::GetTaskID() const { return TaskID::REMOVE_ENCHANTMENT; } TaskStatus RemoveEnchantmentTask::Impl(Player&) { auto enchantment = dynamic_cast<Enchantment*>(m_source); if (enchantment == nullptr) { return TaskStatus::STOP; } enchantment->Remove(); return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Models/Enchantment.hpp> #include <Rosetta/Tasks/SimpleTasks/RemoveEnchantmentTask.hpp> namespace RosettaStone::SimpleTasks { TaskID RemoveEnchantmentTask::GetTaskID() const { return TaskID::REMOVE_ENCHANTMENT; } TaskStatus RemoveEnchantmentTask::Impl(Player&) { auto enchantment = dynamic_cast<Enchantment*>(m_source); if (enchantment == nullptr) { return TaskStatus::STOP; } if (enchantment->card.power.GetEnchant() != nullptr) { for (auto& effect : enchantment->card.power.GetEnchant()->effects) { effect->Remove(m_target); } } enchantment->Remove(); return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks
Add parameter for config file
#include <boost/log/trivial.hpp> #include <boost/program_options.hpp> #include <dsnutil/log/init.h> namespace po = boost::program_options; int main(int argc, char** argv) { dsn::log::init(); try { po::options_description descr; descr.add_options()("help,?", "Display list of valid arguments"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, descr), vm); po::notify(vm); } catch (po::error& ex) { BOOST_LOG_TRIVIAL(error) << "Failed to parse command line arguments: " << ex.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; }
#include <iostream> #include <boost/log/trivial.hpp> #include <boost/program_options.hpp> #include <dsnutil/log/init.h> #include <build-bot/bot.h> namespace po = boost::program_options; int main(int argc, char** argv) { dsn::log::init(); std::string configFile; try { po::options_description descr; descr.add_options()("help,?", "Display list of valid arguments"); descr.add_options()("config,c", po::value<std::string>()->required()->default_value(dsn::build_bot::Bot::DEFAULT_CONFIG_FILE), "Path to configuration file"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, descr), vm); po::notify(vm); if (vm.count("help")) { std::cerr << descr << std::endl; return EXIT_SUCCESS; } configFile = vm["config"].as<std::string>(); } catch (po::error& ex) { BOOST_LOG_TRIVIAL(error) << "Failed to parse command line arguments: " << ex.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; }
Replace && with and for readability.
/*************************************************************************** * @file The code is for the exercises in C++ Primmer 5th Edition * @author @Yue Wang @gupenghu * @date 29.11.2014 * @remark ***************************************************************************/ //! //! Exercise 12.26: //! Rewrite the program on page 481 using an allocator. //! #include <iostream> #include <memory> int main() { //! create a allocator object and use it to handle string. //! create a movable pointer to the address p points std::allocator<std::string> alloc; std::string* const p = alloc.allocate(5); std::string* p_movable = p; //! constuct each object using copy constructor std::cout << "enter 4 times\n"; for(std::string word ;std::cin >> word && p_movable != p + 3; ++p_movable) alloc.construct(p_movable,word); //! move the movable pointer back home p_movable = p; //! print the strings constructed. for( ; p_movable != p + 3; ++p_movable){ std::cout << *p_movable <<"\n"; alloc.destroy(p_movable); } //! free the allocated memory. alloc.deallocate(p, 5); std::cout << "exit normally\n"; return 0; } //! output //! //enter 4 times //ss //ss //ss //ss //ss //ss //ss //exit normally
/*************************************************************************** * @file The code is for the exercises in C++ Primmer 5th Edition * @author @Yue Wang @gupenghu * @date 29.11.2014 * @remark ***************************************************************************/ //! //! Exercise 12.26: //! Rewrite the program on page 481 using an allocator. //! #include <iostream> #include <memory> int main() { //! create a allocator object and use it to handle string. //! create a movable pointer to the address p points std::allocator<std::string> alloc; std::string* const p = alloc.allocate(5); std::string* p_movable = p; //! constuct each object using copy constructor std::cout << "enter 4 times\n"; for(std::string word ;std::cin >> word and p_movable != p + 3; ++p_movable) alloc.construct(p_movable,word); //! move the movable pointer back home p_movable = p; //! print the strings constructed. for( ; p_movable != p + 3; ++p_movable){ std::cout << *p_movable <<"\n"; alloc.destroy(p_movable); } //! free the allocated memory. alloc.deallocate(p, 5); std::cout << "exit normally\n"; return 0; } //! output //! //enter 4 times //ss //ss //ss //ss //ss //ss //ss //exit normally
Add new line to oxErr output
/* * Copyright 2016 - 2021 gary@drinkingtea.net * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <nostalgia/core/core.hpp> #include "app.hpp" static ox::Error run(int argc, const char **argv) noexcept { ox::trace::init(); if (argc < 2) { oxErr("Please provide path to project directory or OxFS file."); return OxError(1); } const auto path = argv[1]; oxRequire(fs, nostalgia::core::loadRomFs(path)); return run(fs.get()); } int main(int argc, const char **argv) { const auto err = run(argc, argv); oxAssert(err, "Something went wrong..."); return static_cast<int>(err); }
/* * Copyright 2016 - 2021 gary@drinkingtea.net * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <nostalgia/core/core.hpp> #include "app.hpp" static ox::Error run(int argc, const char **argv) noexcept { ox::trace::init(); if (argc < 2) { oxErr("Please provide path to project directory or OxFS file.\n"); return OxError(1); } const auto path = argv[1]; oxRequire(fs, nostalgia::core::loadRomFs(path)); return run(fs.get()); } int main(int argc, const char **argv) { const auto err = run(argc, argv); oxAssert(err, "Something went wrong..."); return static_cast<int>(err); }
Use more precise kernel timers for HIP.
#include <miopen/hipoc_kernel.hpp> #include <miopen/errors.hpp> #include <hip/hip_hcc.h> namespace miopen { void HIPOCKernelInvoke::run(void* args, std::size_t size) const { HipEventPtr start = nullptr; HipEventPtr stop = nullptr; void *config[] = { HIP_LAUNCH_PARAM_BUFFER_POINTER, args, HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, HIP_LAUNCH_PARAM_END }; if (callback) { start = make_hip_event(); stop = make_hip_event(); hipEventRecord(start.get(), stream); } // std::cerr << "Launch kernel: " << name << std::endl; auto status = hipHccModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config); if(status != hipSuccess) MIOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel"); if (callback) { hipEventRecord(stop.get(), stream); hipEventSynchronize(stop.get()); callback(start.get(), stop.get()); } } HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback) { return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback}; } }
#include <miopen/hipoc_kernel.hpp> #include <miopen/errors.hpp> #include <hip/hip_hcc.h> namespace miopen { void HIPOCKernelInvoke::run(void* args, std::size_t size) const { HipEventPtr start = nullptr; HipEventPtr stop = nullptr; void *config[] = { HIP_LAUNCH_PARAM_BUFFER_POINTER, args, HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, HIP_LAUNCH_PARAM_END }; if (callback) { start = make_hip_event(); stop = make_hip_event(); } // std::cerr << "Launch kernel: " << name << std::endl; auto status = hipHccModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config, start.get(), stop.get()); if(status != hipSuccess) MIOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel"); if (callback) { hipEventSynchronize(stop.get()); callback(start.get(), stop.get()); } } HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback) { return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback}; } }
Update to reflect changes to signs.
#include "../../valhalla/mjolnir/signbuilder.h" using namespace valhalla::baldr; namespace valhalla { namespace mjolnir { // Constructor with arguments SignBuilder::SignBuilder(const uint32_t idx, const Sign::Type& type, const uint32_t text_offset) : Sign(idx, type, text_offset) { } // Set the directed edge index. void SignBuilder::set_edgeindex(const uint32_t idx) { edgeindex_ = idx; } } }
#include "../../valhalla/mjolnir/signbuilder.h" using namespace valhalla::baldr; namespace valhalla { namespace mjolnir { // Constructor with arguments SignBuilder::SignBuilder(const uint32_t idx, const Sign::Type& type, const uint32_t text_offset) : Sign(idx, type, text_offset) { } // Set the directed edge index. void SignBuilder::set_edgeindex(const uint32_t idx) { data_.edgeindex = idx; } } }
Enable color transformations for bitstrips
// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "Bitstrip.h" Bitstrip::Bitstrip(std::wstring bitmapName, int x, int y, int units) : Meter(bitmapName, x, y, units) { _rect.Height = _bitmap->GetHeight() / _units; } void Bitstrip::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) { int units = CalcUnits(); int stripY = (units - 1) * _rect.Height; if (units == 0) { /* The mute OSD should be shown here, but we'll do something sane * rather than go negative. */ stripY = 0; } graphics->DrawImage(_bitmap, _rect, 0, stripY, _rect.Width, _rect.Height, Gdiplus::UnitPixel); UpdateDrawnValues(); }
// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "Bitstrip.h" Bitstrip::Bitstrip(std::wstring bitmapName, int x, int y, int units) : Meter(bitmapName, x, y, units) { _rect.Height = _bitmap->GetHeight() / _units; } void Bitstrip::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) { int units = CalcUnits(); int stripY = (units - 1) * _rect.Height; if (units == 0) { /* The mute OSD should be shown here, but we'll do something sane * rather than go negative. */ stripY = 0; } graphics->DrawImage(_bitmap, _rect, 0, stripY, _rect.Width, _rect.Height, Gdiplus::UnitPixel, &_imageAttributes, NULL, NULL); UpdateDrawnValues(); }
Fix testcase for MSVC targets where the output ordering is different.
// RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck %s // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A" // CHECK-NOT: DIFlagFwdDecl // CHECK-SAME: ){{$}} class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; } // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "B" // CHECK-SAME: flags: DIFlagFwdDecl class B { public: int y; }; extern int bar(B *b); int baz(B *b) { return bar(b); } // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "C" // CHECK-SAME: flags: DIFlagFwdDecl struct C { }; C (*x)(C);
// RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck %s // RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck --check-prefix=CHECK-C %s // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A" // CHECK-NOT: DIFlagFwdDecl // CHECK-SAME: ){{$}} class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; } // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "B" // CHECK-SAME: flags: DIFlagFwdDecl class B { public: int y; }; extern int bar(B *b); int baz(B *b) { return bar(b); } // CHECK-C: !DICompositeType(tag: DW_TAG_structure_type, name: "C" // CHECK-C-SAME: flags: DIFlagFwdDecl struct C { }; C (*x)(C);
Mark ExtensionApiTest.ExecuteScript DISABLED because it's not only flaky, but crashy and it has been ignored for weeks!
// Copyright (c) 20109 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // This test failed at times on the Vista dbg builder and has been marked as // flaky for now. Bug http://code.google.com/p/chromium/issues/detail?id=28630 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_ExecuteScript) { // We need a.com to be a little bit slow to trigger a race condition. host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500); host_resolver()->AddRule("b.com", "127.0.0.1"); host_resolver()->AddRule("c.com", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_; }
// Copyright (c) 20109 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // EXTREMELY flaky, crashy, and bad. See http://crbug.com/28630 and don't dare // to re-enable without a real fix or at least adding more debugging info. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ExecuteScript) { // We need a.com to be a little bit slow to trigger a race condition. host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500); host_resolver()->AddRule("b.com", "127.0.0.1"); host_resolver()->AddRule("c.com", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_; }
Fix deprecation warning in "Resampling" tutorial
#include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> int main (int argc, char** argv) { // Load input file into a PointCloud<T> with an appropriate type pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ()); // Load bun0.pcd -- should be available with the PCL archive in test pcl::io::loadPCDFile ("bun0.pcd", *cloud); // Create a KD-Tree pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); // Output has the PointNormal type in order to store the normals calculated by MLS pcl::PointCloud<pcl::PointNormal> mls_points; // Init object (second point type is for the normals, even if unused) pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls; mls.setComputeNormals (true); // Set parameters mls.setInputCloud (cloud); mls.setPolynomialFit (true); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.process (mls_points); // Save output pcl::io::savePCDFile ("bun0-mls.pcd", mls_points); }
#include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> int main (int argc, char** argv) { // Load input file into a PointCloud<T> with an appropriate type pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ()); // Load bun0.pcd -- should be available with the PCL archive in test pcl::io::loadPCDFile ("bun0.pcd", *cloud); // Create a KD-Tree pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); // Output has the PointNormal type in order to store the normals calculated by MLS pcl::PointCloud<pcl::PointNormal> mls_points; // Init object (second point type is for the normals, even if unused) pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls; mls.setComputeNormals (true); // Set parameters mls.setInputCloud (cloud); mls.setPolynomialOrder (2); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.process (mls_points); // Save output pcl::io::savePCDFile ("bun0-mls.pcd", mls_points); }
Set up a native screen on Windows
// 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-CHROMIUM file. #include "browser/browser_main_parts.h" #include "browser/browser_context.h" #include "browser/web_ui_controller_factory.h" #include "net/proxy/proxy_resolver_v8.h" namespace brightray { BrowserMainParts::BrowserMainParts() { } BrowserMainParts::~BrowserMainParts() { } void BrowserMainParts::PreMainMessageLoopRun() { browser_context_.reset(CreateBrowserContext()); browser_context_->Initialize(); web_ui_controller_factory_.reset( new WebUIControllerFactory(browser_context_.get())); content::WebUIControllerFactory::RegisterFactory( web_ui_controller_factory_.get()); } void BrowserMainParts::PostMainMessageLoopRun() { browser_context_.reset(); } int BrowserMainParts::PreCreateThreads() { #if defined(OS_WIN) net::ProxyResolverV8::CreateIsolate(); #else net::ProxyResolverV8::RememberDefaultIsolate(); #endif return 0; } BrowserContext* BrowserMainParts::CreateBrowserContext() { return new BrowserContext; } } // namespace brightray
// 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-CHROMIUM file. #include "browser/browser_main_parts.h" #include "browser/browser_context.h" #include "browser/web_ui_controller_factory.h" #include "net/proxy/proxy_resolver_v8.h" #include "ui/gfx/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" namespace brightray { BrowserMainParts::BrowserMainParts() { } BrowserMainParts::~BrowserMainParts() { } void BrowserMainParts::PreMainMessageLoopRun() { browser_context_.reset(CreateBrowserContext()); browser_context_->Initialize(); web_ui_controller_factory_.reset( new WebUIControllerFactory(browser_context_.get())); content::WebUIControllerFactory::RegisterFactory( web_ui_controller_factory_.get()); #if defined(OS_WIN) gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen()); #endif } void BrowserMainParts::PostMainMessageLoopRun() { browser_context_.reset(); } int BrowserMainParts::PreCreateThreads() { #if defined(OS_WIN) net::ProxyResolverV8::CreateIsolate(); #else net::ProxyResolverV8::RememberDefaultIsolate(); #endif return 0; } BrowserContext* BrowserMainParts::CreateBrowserContext() { return new BrowserContext; } } // namespace brightray
Fix chain ordering in budget tests
// Copyright (c) 2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include <tinyformat.h> #include <utilmoneystr.h> #include "masternode-budget.h" BOOST_AUTO_TEST_SUITE(budget_tests) void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue) { CBudgetManager budget; CAmount nBudget = budget.GetTotalBudget(nHeight); std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue)); BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError); } BOOST_AUTO_TEST_CASE(budget_value) { SelectParams(CBaseChainParams::MAIN); int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN); SelectParams(CBaseChainParams::TESTNET); nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "testnet", 7300*COIN); } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode-budget.h" #include "tinyformat.h" #include "utilmoneystr.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(budget_tests) void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue) { CBudgetManager budget; CAmount nBudget = budget.GetTotalBudget(nHeight); std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue)); BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError); } BOOST_AUTO_TEST_CASE(budget_value) { SelectParams(CBaseChainParams::TESTNET); int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "testnet", 7300*COIN); SelectParams(CBaseChainParams::MAIN); nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN); } BOOST_AUTO_TEST_SUITE_END()
Fix to removing nulls from column names
// // Created by Chris Richards on 27/04/2016. // #include <iomanip> #include <sstream> #include "DbfColumn.h" #include "DbfUtils.h" const int kDbfFieldDescriptorSize = 32; DbfColumn::DbfColumn(std::istream &stream, int index) : index_(index) { read(stream); } void DbfColumn::read(std::istream &stream) { name_.clear(); name_.resize(10); stream.read(&name_[0], 11); std::vector<char>::iterator it = std::find(name_.begin(), name_.end(), '\0'); if (it != name_.end()) { name_.erase(it, name_.end()); } type_ = (DbfColumnType)read_raw<uint8_t>(stream); uint32_t address = read_raw<uint32_t>(stream); length_ = read_raw<uint8_t>(stream); decimal_ = read_raw<uint8_t>(stream); // skip the next 14 bytes stream.seekg(14, std::ios_base::cur); } int DbfColumn::index() const { return index_; } std::string DbfColumn::name() const { return name_; } DbfColumn::DbfColumnType DbfColumn::type() const { return type_; } int DbfColumn::length() const { return length_; } int DbfColumn::decimal() const { return decimal_; }
// // Created by Chris Richards on 27/04/2016. // #include <iomanip> #include <sstream> #include "DbfColumn.h" #include "DbfUtils.h" const int kDbfFieldDescriptorSize = 32; DbfColumn::DbfColumn(std::istream &stream, int index) : index_(index) { read(stream); } void DbfColumn::read(std::istream &stream) { name_.clear(); name_.resize(10); stream.read(&name_[0], 11); size_t pos = name_.find('\0'); if (pos != std::string::npos) { name_.erase(pos); } type_ = (DbfColumnType)read_raw<uint8_t>(stream); uint32_t address = read_raw<uint32_t>(stream); length_ = read_raw<uint8_t>(stream); decimal_ = read_raw<uint8_t>(stream); // skip the next 14 bytes stream.seekg(14, std::ios_base::cur); } int DbfColumn::index() const { return index_; } std::string DbfColumn::name() const { return name_; } DbfColumn::DbfColumnType DbfColumn::type() const { return type_; } int DbfColumn::length() const { return length_; } int DbfColumn::decimal() const { return decimal_; }
Use version number from qmake if possible
#include "myapplication.h" #include "eventdispatcher_libevent.h" #include "msghandler.h" int main(int argc, char** argv) { #if QT_VERSION < 0x050000 qInstallMsgHandler(messageHandler); #else qInstallMessageHandler(messageHandler); #endif #if QT_VERSION >= 0x050000 QCoreApplication::setEventDispatcher(new EventDispatcherLibEvent()); #else EventDispatcherLibEvent e; #endif QCoreApplication::setApplicationName(QLatin1String("Proxy")); QCoreApplication::setOrganizationName(QLatin1String("Goldbar Enterprises")); QCoreApplication::setOrganizationDomain(QLatin1String("goldbar.net")); #if QT_VERSION >= 0x040400 QCoreApplication::setApplicationVersion(QLatin1String("0.0.1")); #endif MyApplication app(argc, argv); return app.exec(); }
#include "myapplication.h" #include "eventdispatcher_libevent.h" #include "msghandler.h" #include "qt4compat.h" int main(int argc, char** argv) { #if QT_VERSION < 0x050000 qInstallMsgHandler(messageHandler); #else qInstallMessageHandler(messageHandler); #endif #if QT_VERSION >= 0x050000 QCoreApplication::setEventDispatcher(new EventDispatcherLibEvent()); #else EventDispatcherLibEvent e; #endif QCoreApplication::setApplicationName(QLatin1String("Proxy")); QCoreApplication::setOrganizationName(QLatin1String("Goldbar Enterprises")); QCoreApplication::setOrganizationDomain(QLatin1String("goldbar.net")); #if QT_VERSION >= 0x040400 #if defined(REPWATCHPROXY_VERSION) #define RPV QT_STRINGIFY(REPWATCHPROXY_VERSION) QCoreApplication::setApplicationVersion(QLatin1String(RPV)); #undef RPV #else QCoreApplication::setApplicationVersion(QLatin1String("0.0.1")); #endif #endif MyApplication app(argc, argv); return app.exec(); }
Add more parser tests for the override control keywords.
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s struct S { virtual void final() final; virtual void override() override; virtual void n() new; };
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s struct S { virtual void final() final; virtual void override() override; virtual void n() new; int i : 3 new; int j new; }; struct T { // virt-specifier-seq is only valid in member-declarators, and a function definition is not a member-declarator. virtual void f() const override { } // expected-error {{expected ';' at end of declaration list}} };
Format CValidationState properly in all cases
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Bitcoin Signed Message:\n";
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { if (state.IsValid()) { return "Valid"; } return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Bitcoin Signed Message:\n";
Use container to store acceptable instructions
//#include "InstructionParser.h" #include <string> #include <stdexcept> #include "gtest/gtest.h" class InstructionParser { public: class UnknownInstruction : public std::runtime_error { public: UnknownInstruction(const std::string& msg) : std::runtime_error{msg} {} }; void parseInstructions(const std::string& instruction) { const std::vector<std::string> acceptableInstructions{"ld a,", "out (0),a"}; if (std::find(acceptableInstructions.begin(), acceptableInstructions.end(), instruction) == acceptableInstructions.end()) { throw UnknownInstruction{"Unknown instruction" + instruction}; } } }; TEST(InstructionParser, ParserShouldDeclineUnknownInstruction) { InstructionParser parser; EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction); } TEST(InstructionParser, ParserShouldAcceptInstuctionLd) { InstructionParser parser; EXPECT_NO_THROW(parser.parseInstructions("ld a,")); } TEST(InstructionParser, ParserShouldAcceptInstructionOut) { InstructionParser parser; EXPECT_NO_THROW(parser.parseInstructions("out (0),a")); }
//#include "InstructionParser.h" #include <string> #include <stdexcept> #include "gtest/gtest.h" class InstructionParser { public: class UnknownInstruction : public std::runtime_error { public: UnknownInstruction(const std::string& msg) : std::runtime_error{msg} {} }; void parseInstructions(const std::string& instruction) { const std::vector<std::string> acceptableInstructions{"ld a,", "out (0),a"}; if (std::find(acceptableInstructions.begin(), acceptableInstructions.end(), instruction) == acceptableInstructions.end()) { throw UnknownInstruction{"Unknown instruction" + instruction}; } } }; using namespace ::testing; struct InstructionParserTest : public Test { InstructionParser parser; }; TEST(InstructionParserTest, ParserShouldDeclineUnknownInstruction) { EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction); } TEST(InstructionParserTest, ParserShouldAcceptInstuctionLd) { EXPECT_NO_THROW(parser.parseInstructions("ld a,")); } TEST(InstructionParserTest, ParserShouldAcceptInstructionOut) { EXPECT_NO_THROW(parser.parseInstructions("out (0),a")); }
Fix to decimal point rejection in float fields
#include "mainwindow.h" #include <QApplication> #include <QDialog> #include <QGridLayout> #include <QLayout> #include <QDebug> #include "application.h" int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("JASP"); QCoreApplication::setOrganizationDomain("jasp-stats.org"); QCoreApplication::setApplicationName("JASP"); Application a(argc, argv); MainWindow w; w.show(); QStringList args = QApplication::arguments(); if (args.length() > 1) w.open(args.at(1)); return a.exec(); }
#include "mainwindow.h" #include <QApplication> #include <QDialog> #include <QGridLayout> #include <QLayout> #include <QDebug> #include "application.h" int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("JASP"); QCoreApplication::setOrganizationDomain("jasp-stats.org"); QCoreApplication::setApplicationName("JASP"); QLocale::setDefault(QLocale(QLocale::English)); // make decimal points == . Application a(argc, argv); MainWindow w; w.show(); QStringList args = QApplication::arguments(); if (args.length() > 1) w.open(args.at(1)); return a.exec(); }
Use GetModuleFileName on win32 to get exe name
#include "bundle.h" #include "exec.h" int main(int argc, char *argv[]) { bool enable_assert = true; unsigned short debug_port = 0; run_from_bundle(argv[0], enable_assert, debug_port, argc, argv); return 0; }
#include "bundle.h" #include "exec.h" #ifdef _WIN32 #include <windows.h> #endif int main(int argc, char *argv[]) { bool enable_assert = true; unsigned short debug_port = 0; const char *exe = argv[0]; #ifdef _WIN32 char buf[MAX_PATH]; GetModuleFileName(NULL, buf, sizeof(buf)); exe = buf; #endif run_from_bundle(exe, enable_assert, debug_port, argc, argv); return 0; }
Change the test application to one that works.
#include <iostream> #include <yaml-cpp/yaml.h> int main() { YAML::Emitter out; out << "Hello, World!"; std::cout << "Here's the output YAML:\n" << out.c_str(); return 0; }
#include <cassert> #include <yaml-cpp/yaml.h> int main() { YAML::Node node = YAML::Load("[1, 2, 3]"); assert(node.IsSequence()); return 0; }
Use the next exception for functions error reporting
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include "AssemblyFileWriter.hpp" #include "Functions.hpp" #include "Utils.hpp" using namespace eddic; using std::endl; void MainDeclaration::write(AssemblyFileWriter& writer){ writer.stream() << ".text" << endl << ".globl main" << endl << "\t.type main, @function" << endl; } void FunctionCall::checkFunctions(Program& program){ if(!program.exists(m_function)){ throw CompilerException("The function \"" + m_function + "()\" does not exists at line " + toString<int>(token()->line()) + ":" + toString<int>(token()->col())); } } void Function::write(AssemblyFileWriter& writer){ writer.stream() << endl << m_name << ":" << endl; writer.stream() << "pushl %ebp" << std::endl; writer.stream() << "movl %esp, %ebp" << std::endl; ParseNode::write(writer); writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void FunctionCall::write(AssemblyFileWriter& writer){ writer.stream() << "call " << m_function << endl; }
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include "AssemblyFileWriter.hpp" #include "Functions.hpp" #include "Utils.hpp" using namespace eddic; using std::endl; void MainDeclaration::write(AssemblyFileWriter& writer){ writer.stream() << ".text" << endl << ".globl main" << endl << "\t.type main, @function" << endl; } void FunctionCall::checkFunctions(Program& program){ if(!program.exists(m_function)){ throw CompilerException("The function \"" + m_function + "()\" does not exists", token()); } } void Function::write(AssemblyFileWriter& writer){ writer.stream() << endl << m_name << ":" << endl; writer.stream() << "pushl %ebp" << std::endl; writer.stream() << "movl %esp, %ebp" << std::endl; ParseNode::write(writer); writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void FunctionCall::write(AssemblyFileWriter& writer){ writer.stream() << "call " << m_function << endl; }
Define class pointer for MongoCursorException
#include "ext_mongo.h" namespace HPHP { // PHP Exceptions and Classes HPHP::Class* MongoException::cls = nullptr; HPHP::Class* MongoConnectionException::cls = nullptr; HPHP::Class* MongoCursorTimeoutException::cls = nullptr; HPHP::Class* MongoDuplicateKeyException::cls = nullptr; HPHP::Class* MongoExecutionTimeoutException::cls = nullptr; HPHP::Class* MongoGridFSException::cls = nullptr; HPHP::Class* MongoProtocolException::cls = nullptr; HPHP::Class* MongoResultException::cls = nullptr; HPHP::Class* MongoWriteConcernException::cls = nullptr; mongoExtension s_mongo_extension; HHVM_GET_MODULE(mongo); } // namespace HPHP
#include "ext_mongo.h" namespace HPHP { // PHP Exceptions and Classes HPHP::Class* MongoException::cls = nullptr; HPHP::Class* MongoConnectionException::cls = nullptr; HPHP::Class* MongoCursorException::cls = nullptr; HPHP::Class* MongoCursorTimeoutException::cls = nullptr; HPHP::Class* MongoDuplicateKeyException::cls = nullptr; HPHP::Class* MongoExecutionTimeoutException::cls = nullptr; HPHP::Class* MongoGridFSException::cls = nullptr; HPHP::Class* MongoProtocolException::cls = nullptr; HPHP::Class* MongoResultException::cls = nullptr; HPHP::Class* MongoWriteConcernException::cls = nullptr; mongoExtension s_mongo_extension; HHVM_GET_MODULE(mongo); } // namespace HPHP
Add a body of prob 6
#include <stdio.h> int main(void) { return 0; }
#include <stdio.h> #define MAX_LOOP 10000 double formula(const double x, const double k) { return (x * x) / ((2 * k - 1) * (2 * k)); } int main(void) { double x; printf("Enter x= "); scanf("%lf", &x); double cosx = 1, sinx = x; int k = 2; while(k < MAX_LOOP) { cosx = cosx - cosx * formula(x, k++); sinx = sinx - sinx * formula(x, k++); cosx = cosx + cosx * formula(x, k++); sinx = sinx + sinx * formula(x, k++); } printf("Result is: cosx=%f sinx=%f\n", cosx, sinx); return 0; }
Fix bug with component_add() on Class type
#include <type/class.hh> namespace type { Class::Class(const std::string& name) : name_(name) {} Class::~Class() {} const std::string& Class::name_get() const { return name_; } ast::Ast* Class::component_get(const std::string& name) { return content_[name]; } bool Class::component_add(const std::string& name, ast::Ast* dec) { // Component already exists if (!content_[name]) return false; content_[name] = dec; return true; } std::ostream& Class::dump(std::ostream& o) const { o << "Class (" << name_ << ")"; return o; } std::string Class::cpp_type() const { return name_ + "*"; } } // namespace type
#include <type/class.hh> namespace type { Class::Class(const std::string& name) : name_(name) {} Class::~Class() {} const std::string& Class::name_get() const { return name_; } ast::Ast* Class::component_get(const std::string& name) { return content_[name]; } bool Class::component_add(const std::string& name, ast::Ast* dec) { // Component already exists if (content_[name]) return false; content_[name] = dec; return true; } std::ostream& Class::dump(std::ostream& o) const { o << "Class (" << name_ << ")"; return o; } std::string Class::cpp_type() const { return name_ + "*"; } } // namespace type