Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Replace Demo with macro in CpuCode.cpp.
/*** This is a simple demo project that you can copy to get started. Comments blocks starting with '***' and subsequent non-empty lines are automatically added to this project's wiki page. */ #include <stdio.h> #include <vector> #include <iostream> #include "Maxfiles.h" #include "MaxSLiCInterface.h" int main(void) { const int inSize = 384; std::vector<int> a(inSize), b(inSize), expected(inSize), out(inSize, 0); for(int i = 0; i < inSize; ++i) { a[i] = i + 1; b[i] = i - 1; expected[i] = 2 * i; } std::cout << "Running on DFE." << std::endl; Demo(inSize, &a[0], &b[0], &out[0]); /*** Note that you should always test the output of your DFE design against a CPU version to ensure correctness. */ for (int i = 0; i < inSize; i++) if (out[i] != expected[i]) { printf("Output from DFE did not match CPU: %d : %d != %d\n", i, out[i], expected[i]); return 1; } std::cout << "Test passed!" << std::endl; return 0; }
/*** This is a simple demo project that you can copy to get started. Comments blocks starting with '***' and subsequent non-empty lines are automatically added to this project's wiki page. */ #include <stdio.h> #include <vector> #include <iostream> #include "Maxfiles.h" #include "MaxSLiCInterface.h" int main(void) { const int inSize = 384; std::vector<int> a(inSize), b(inSize), expected(inSize), out(inSize, 0); for(int i = 0; i < inSize; ++i) { a[i] = i + 1; b[i] = i - 1; expected[i] = 2 * i; } std::cout << "Running on DFE." << std::endl; %%%ProjectName%%%(inSize, &a[0], &b[0], &out[0]); /*** Note that you should always test the output of your DFE design against a CPU version to ensure correctness. */ for (int i = 0; i < inSize; i++) if (out[i] != expected[i]) { printf("Output from DFE did not match CPU: %d : %d != %d\n", i, out[i], expected[i]); return 1; } std::cout << "Test passed!" << std::endl; return 0; }
Fix corner case of comparing preparedpoint to point
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/prep/PreparedPoint.java rev. 1.2 (JTS-1.10) * **********************************************************************/ #include <geos/geom/prep/PreparedPoint.h> namespace geos { namespace geom { // geos.geom namespace prep { // geos.geom.prep bool PreparedPoint::intersects(const geom::Geometry* g) const { if (! envelopesIntersect( g)) return false; // This avoids computing topology for the test geometry return isAnyTargetComponentInTest( g); } } // namespace geos.geom.prep } // namespace geos.geom } // namespace geos
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/prep/PreparedPoint.java rev. 1.2 (JTS-1.10) * **********************************************************************/ #include <geos/geom/prep/PreparedPoint.h> #include <geos/geom/Point.h> namespace geos { namespace geom { // geos.geom namespace prep { // geos.geom.prep bool PreparedPoint::intersects(const geom::Geometry* g) const { if (! envelopesIntersect( g)) return false; const Point *pt_geom = dynamic_cast<const Point *>(g); if (pt_geom) return getGeometry().equals(g); // This avoids computing topology for the test geometry return isAnyTargetComponentInTest( g); } } // namespace geos.geom.prep } // namespace geos.geom } // namespace geos
Fix bug causing a wrong frame index
#include "gamelib/sprite/SpriteData.hpp" #include <cmath> namespace gamelib { AnimationData::AnimationData() : length(1), speed(0), offset(0) { } void AnimationData::update(float fps) { offset = std::fmod(offset + speed / fps, length); } sf::IntRect AnimationData::getRect(int texw, int texh) const { int x = rect.left + (int)offset * rect.width; return sf::IntRect(x % texw, (rect.top + x / texw * rect.height) % texh, rect.width, rect.height); } }
#include "gamelib/sprite/SpriteData.hpp" #include <cmath> namespace gamelib { AnimationData::AnimationData() : length(1), speed(0), offset(0) { } void AnimationData::update(float fps) { if (length > 1 && speed != 0) offset = std::fmod(offset + speed / fps, length); } sf::IntRect AnimationData::getRect(int texw, int texh) const { int x = rect.left + (int)offset * rect.width; return sf::IntRect(x % texw, (rect.top + x / texw * rect.height) % texh, rect.width, rect.height); } }
Add Use JSON as a command line argument
/* MIT License Copyright (c) 2017 Blockchain-VCS 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. */ bool __nosha256 = false;
/* MIT License Copyright (c) 2017 Blockchain-VCS 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. */ bool __nosha256 = false; bool __useJSONFormat = false;
Add symbol to empty file
/* Copyright (c) 2014, J.D. Koftinoff Software, Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "JDKSAvdeccMCU_World.hpp" #include "JDKSAvdeccMCU_AppMessageHandler.hpp" namespace JDKSAvdeccMCU { }
/* Copyright (c) 2014, J.D. Koftinoff Software, Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "JDKSAvdeccMCU_World.hpp" #include "JDKSAvdeccMCU_AppMessageHandler.hpp" namespace JDKSAvdeccMCU { const char *jdksavdeccmcu_appmessagehandler_file = __FILE__; }
Remove cxx11 namespace from Error
#include "librt_error.h" using namespace librt; Error::Error() : errorCode_(Error::Code::Ok), message_() { } Error::Error(Error::Code errorCode, std::__cxx11::string &&message) : errorCode_(errorCode), message_(message) { } Error::Error(Error &&other) : errorCode_(other.errorCode_), message_(std::move(other.message_)) { } Error &Error::operator =(Error &&other) { errorCode_ = other.errorCode_; message_ = std::move(other.message_); return *this; } Error &Error::operator =(std::pair<Error::Code, std::string> &&other) { errorCode_ = other.first; message_ = std::move(other.second); return *this; } Error::Code Error::errorCode() const { return errorCode_; } const std::string &Error::message() const { return message_; }
#include "librt_error.h" using namespace librt; Error::Error() : errorCode_(Error::Code::Ok), message_() { } Error::Error(Error::Code errorCode, std::string &&message) : errorCode_(errorCode), message_(message) { } Error::Error(Error &&other) : errorCode_(other.errorCode_), message_(std::move(other.message_)) { } Error &Error::operator =(Error &&other) { errorCode_ = other.errorCode_; message_ = std::move(other.message_); return *this; } Error &Error::operator =(std::pair<Error::Code, std::string> &&other) { errorCode_ = other.first; message_ = std::move(other.second); return *this; } Error::Code Error::errorCode() const { return errorCode_; } const std::string &Error::message() const { return message_; }
Add the function name on the 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" 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 does not exists"); } } 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" 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"); } } 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; }
Use ts_tree_root_node in fuzz driver
#include <string.h> #include "tree_sitter/runtime.h" void test_log(void *payload, TSLogType type, const char *string) { } TSLogger logger = { .log = test_log, }; extern "C" const TSLanguage *TS_LANG(); extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { const char *str = reinterpret_cast<const char *>(data); TSParser *parser = ts_parser_new(); ts_parser_set_language(parser, TS_LANG()); ts_parser_halt_on_error(parser, TS_HALT_ON_ERROR); TSTree *tree = ts_parser_parse_string(parser, NULL, str, size); TSNode root_node = ts_document_root_node(tree); ts_tree_delete(tree); ts_parser_delete(parser); return 0; }
#include <string.h> #include "tree_sitter/runtime.h" void test_log(void *payload, TSLogType type, const char *string) { } TSLogger logger = { .log = test_log, }; extern "C" const TSLanguage *TS_LANG(); extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { const char *str = reinterpret_cast<const char *>(data); TSParser *parser = ts_parser_new(); ts_parser_set_language(parser, TS_LANG()); ts_parser_halt_on_error(parser, TS_HALT_ON_ERROR); TSTree *tree = ts_parser_parse_string(parser, NULL, str, size); TSNode root_node = ts_tree_root_node(tree); ts_tree_delete(tree); ts_parser_delete(parser); return 0; }
Rename incomplete test on datastore to DataStoreDummyTest
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace YouDataStoreTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(Post_EmptyTask_Test) { // You::DataStore::DataStore sut; // sut.post(std::unordered_map<std::wstring, std::wstring>()); Assert::IsTrue(true); } }; } // namespace YouDataStoreTests
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace YouDataStoreTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(DataStoreDummyTest) { // You::DataStore::DataStore sut; // sut.post(std::unordered_map<std::wstring, std::wstring>()); Assert::IsTrue(true); } }; } // namespace YouDataStoreTests
Remove printout from event action
#include <iostream> #include "EventAction.hh" #include "G4Event.hh" #include "RunAction.hh" #include "Run.hh" EventAction::EventAction(): G4UserEventAction{}, _draw_flag("all") { } EventAction::~EventAction() { } void EventAction::BeginOfEventAction(const G4Event* evt) { G4cout << "EV: " << evt->GetEventID() << G4endl; } void EventAction::EndOfEventAction(const G4Event*) { }
#include <iostream> #include "EventAction.hh" #include "G4Event.hh" #include "RunAction.hh" #include "Run.hh" EventAction::EventAction(): G4UserEventAction{}, _draw_flag("all") { } EventAction::~EventAction() { } void EventAction::BeginOfEventAction(const G4Event*) { // G4cout << "EV: " << evt->GetEventID() << G4endl; } void EventAction::EndOfEventAction(const G4Event*) { }
Simplify card string before emitting, in case any key characters are added by the return.
#include "cardreader.h" #include <QEvent> #include <QKeyEvent> bool CardReader::eventFilter(QObject *object, QEvent *event) { if (event->type() != QEvent::KeyPress) { return false; } if (cardNumber.isEmpty()) { writeTime.start(); } //accumulate characters QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); cardNumber += keyEvent->text(); //send signal on enter (RFID card reader ends string input with an enter) if (keyEvent->key() == Qt::Key_Return) { //disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) { emit newCardNumber(cardNumber); } cardNumber.clear(); } return true; }
#include "cardreader.h" #include <QEvent> #include <QKeyEvent> bool CardReader::eventFilter(QObject *object, QEvent *event) { if (event->type() != QEvent::KeyPress) { return false; } if (cardNumber.isEmpty()) { writeTime.start(); } //accumulate characters QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); cardNumber += keyEvent->text(); //send signal on enter (RFID card reader ends string input with an enter) if (keyEvent->key() == Qt::Key_Return) { //disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) { emit newCardNumber(cardNumber.simplified()); } cardNumber.clear(); } return true; }
Initialize the default serial port properly
#include <hw/serial.hpp> extern "C" void __serial_print1(const char* cstr) { const uint16_t port = 0x3F8; // Serial 1 while (*cstr) { while (not (hw::inb(port + 5) & 0x20)); hw::outb(port, *cstr++); } }
#include <hw/serial.hpp> extern "C" void __serial_print1(const char* cstr) { const uint16_t port = 0x3F8; // Serial 1 static bool init = false; if (!init) { init = true; // properly initialize serial port hw::outb(port + 1, 0x00); // Disable all interrupts hw::outb(port + 3, 0x80); // Enable DLAB (set baud rate divisor) hw::outb(port + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud hw::outb(port + 1, 0x00); // (hi byte) hw::outb(port + 3, 0x03); // 8 bits, no parity, one stop bit hw::outb(port + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold } while (*cstr) { while (not (hw::inb(port + 5) & 0x20)); hw::outb(port, *cstr++); } }
Test qlabel for displaying string from card reader.
#include "mainwindow.h" #include <QGridLayout> #include <QLabel> #include <QEvent> #include <QKeyEvent> #include <iostream> MainWindow::MainWindow(QWidget *parent) { QGridLayout *layout = new QGridLayout(this); layout->addWidget(new QLabel("ARK kryssesystem")); //install cardReader as an filter which intercepts keyboard events CardReader *cardReader = new CardReader(this); installEventFilter(cardReader); } bool CardReader::eventFilter(QObject *object, QEvent *event) { if (event->type() != QEvent::KeyPress) { return false; } if (cardNumber.isEmpty()) { writeTime.start(); } //accumulate characters QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); cardNumber += keyEvent->text(); //send signal on enter (RFID card reader ends string input with an enter) if (keyEvent->key() == Qt::Key_Return) { //disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) { emit newCardNumber(cardNumber); } cardNumber.clear(); } return true; }
#include "mainwindow.h" #include <QGridLayout> #include <QLabel> #include <QEvent> #include <QKeyEvent> #include <iostream> MainWindow::MainWindow(QWidget *parent) { QGridLayout *layout = new QGridLayout(this); layout->addWidget(new QLabel("ARK kryssesystem. Bipp et kort:")); QLabel *testLabel = new QLabel; layout->addWidget(testLabel); //install cardReader as an filter which intercepts keyboard events CardReader *cardReader = new CardReader(this); installEventFilter(cardReader); connect(cardReader, SIGNAL(newCardNumber(QString)), testLabel, SLOT(setText(QString))); } bool CardReader::eventFilter(QObject *object, QEvent *event) { if (event->type() != QEvent::KeyPress) { return false; } if (cardNumber.isEmpty()) { writeTime.start(); } //accumulate characters QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); cardNumber += keyEvent->text(); //send signal on enter (RFID card reader ends string input with an enter) if (keyEvent->key() == Qt::Key_Return) { //disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) { emit newCardNumber(cardNumber); } cardNumber.clear(); } return true; }
Fix compilation against Qt 5.13.
/* Copyright (C) 2014,2015,2018 Rodrigo Jose Hernandez Cordoba 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 "SettingsDialog.h" #include <QColorDialog> namespace AeonGames { SettingsDialog::SettingsDialog() { setupUi ( this ); settings.beginGroup ( "MainWindow" ); backgroundColorPushButton->setPalette ( QPalette ( settings.value ( "background color", QColor ( 57, 57, 57 ) ).value<QColor>() ) ); settings.endGroup(); } SettingsDialog::~SettingsDialog() { } void SettingsDialog::onChangeBackgroundColor() { QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().background().color() ); settings.beginGroup ( "MainWindow" ); settings.setValue ( "background color", color ); settings.endGroup(); backgroundColorPushButton->setPalette ( QPalette ( color ) ); emit backgroundColor ( color ); } }
/* Copyright (C) 2014,2015,2018,2019 Rodrigo Jose Hernandez Cordoba 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 "SettingsDialog.h" #include <QColorDialog> namespace AeonGames { SettingsDialog::SettingsDialog() { setupUi ( this ); settings.beginGroup ( "MainWindow" ); backgroundColorPushButton->setPalette ( QPalette ( settings.value ( "background color", QColor ( 57, 57, 57 ) ).value<QColor>() ) ); settings.endGroup(); } SettingsDialog::~SettingsDialog() { } void SettingsDialog::onChangeBackgroundColor() { #if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().background().color() ); #else QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().window().color() ); #endif settings.beginGroup ( "MainWindow" ); settings.setValue ( "background color", color ); settings.endGroup(); backgroundColorPushButton->setPalette ( QPalette ( color ) ); emit backgroundColor ( color ); } }
Update to latest perforce change
#include "Core.h" #include "IntPtr.h" #include "uhx/ue/RuntimeLibrary.h" #include "HAL/PlatformAtomics.h" static int uhx_tls_slot = 0; #if defined(_MSC_VER) unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr; #elif defined(__GNUC__) thread_local unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr; #else static int uhx_tls_obj = FPlatformTLS::AllocTlsSlot(); unreal::UIntPtr uhx::ue::RuntimeLibrary_obj::getTlsObj() { unreal::UIntPtr *ret = (unreal::UIntPtr *) FPlatformTLS::GetTlsValue(uhx_tls_obj); if (!ret) { ret = (unreal::UIntPtr*) uhx::GcRef::createRoot(); FPlatformTLS::SetTlsValue(uhx_tls_obj, (void*) ret); return *ret = uhx::expose::HxcppRuntime::createArray(); } return *ret; } #endif int uhx::ue::RuntimeLibrary_obj::allocTlsSlot() { return FPlatformAtomics::InterlockedIncrement(&uhx_tls_slot); }
#ifndef UHX_NO_UOBJECT #include "Core.h" #include "IntPtr.h" #include "uhx/ue/RuntimeLibrary.h" #include "HAL/PlatformAtomics.h" static int uhx_tls_slot = 0; #if defined(_MSC_VER) unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr; #elif defined(__GNUC__) thread_local unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr; #else static int uhx_tls_obj = FPlatformTLS::AllocTlsSlot(); unreal::UIntPtr uhx::ue::RuntimeLibrary_obj::getTlsObj() { unreal::UIntPtr *ret = (unreal::UIntPtr *) FPlatformTLS::GetTlsValue(uhx_tls_obj); if (!ret) { ret = (unreal::UIntPtr*) uhx::GcRef::createRoot(); FPlatformTLS::SetTlsValue(uhx_tls_obj, (void*) ret); return *ret = uhx::expose::HxcppRuntime::createArray(); } return *ret; } #endif int uhx::ue::RuntimeLibrary_obj::allocTlsSlot() { return FPlatformAtomics::InterlockedIncrement(&uhx_tls_slot); } #endif
Fix error [FATAL:at_exit.cc(40)] Check failed: false. Tried to RegisterCallback without an AtExitManager in (possibly unused) binary perf_tests
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/perf_test_suite.h" #include "chrome/common/chrome_paths.cc" int main(int argc, char **argv) { chrome::RegisterPathProvider(); MessageLoop main_message_loop; return PerfTestSuite(argc, argv).Run(); }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/perf_test_suite.h" #include "chrome/common/chrome_paths.cc" int main(int argc, char **argv) { PerfTestSuite suite(argc, argv); chrome::RegisterPathProvider(); MessageLoop main_message_loop; return suite.Run(); }
Test code from assignment description
// Test main file for the Player and Team classes #include "Player.hpp" #include "Team.hpp" int main() { // Don't do anything return 0; }
// Test main file for the Player and Team classes #include "Player.hpp" #include "Team.hpp" #include <string> #include <iostream> int main() { // Test code from the assignment description Player::Player p1("Charlotte", 24, 10, 7); Player::Player p2("Emily", 21, 13, 9); Player::Player p3("Anne", 20, 10, 8); Player::Player p4("Jane", 19, 10, 10); Player::Player p5("Mary", 18, 11, 8); p5.setRebounds(12); Team::Team team1(p1, p2, p3, p4, p5); Player::Player p = team1.getShootingGuard(); std::cout << p.getName() << std::endl; return 0; }
Disable DefaultPluginUITest::DefaultPluginLoadTest on windows as it crashes.
// 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/basictypes.h" #include "base/file_path.h" #include "build/build_config.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" class DefaultPluginUITest : public UITest { public: DefaultPluginUITest() { dom_automation_enabled_ = true; } }; TEST_F(DefaultPluginUITest, DefaultPluginLoadTest) { // Open page with default plugin. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("default_plugin.html"); NavigateToURL(net::FilePathToFileURL(test_file)); // Check that the default plugin was loaded. It executes a bit of javascript // in the HTML file which replaces the innerHTML of div |result| with "DONE". scoped_refptr<TabProxy> tab(GetActiveTab()); std::wstring out; ASSERT_TRUE(tab->ExecuteAndExtractString(L"", L"domAutomationController.send(" L"document.getElementById('result').innerHTML)", &out)); ASSERT_EQ(L"DONE", out); }
// 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/basictypes.h" #include "base/file_path.h" #include "build/build_config.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" class DefaultPluginUITest : public UITest { public: DefaultPluginUITest() { dom_automation_enabled_ = true; } }; #if defined(OS_WIN) #define MAYBE_DefaultPluginLoadTest DISABLED_DefaultPluginLoadTest #else #define MAYBE_DefaultPluginLoadTest DefaultPluginLoadTest #endif TEST_F(DefaultPluginUITest, MAYBE_DefaultPluginLoadTest) { // Open page with default plugin. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("default_plugin.html"); NavigateToURL(net::FilePathToFileURL(test_file)); // Check that the default plugin was loaded. It executes a bit of javascript // in the HTML file which replaces the innerHTML of div |result| with "DONE". scoped_refptr<TabProxy> tab(GetActiveTab()); std::wstring out; ASSERT_TRUE(tab->ExecuteAndExtractString(L"", L"domAutomationController.send(" L"document.getElementById('result').innerHTML)", &out)); ASSERT_EQ(L"DONE", out); }
Fix initial render of RN Android TextInput
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "AndroidTextInputState.h" #include <react/renderer/components/text/conversions.h> #include <react/renderer/debug/debugStringConvertibleUtils.h> namespace facebook { namespace react { #ifdef ANDROID folly::dynamic AndroidTextInputState::getDynamic() const { // Java doesn't need all fields, so we don't pass them along. folly::dynamic newState = folly::dynamic::object(); newState["mostRecentEventCount"] = mostRecentEventCount; if (mostRecentEventCount != 0) { newState["attributedString"] = toDynamic(attributedString); newState["hash"] = newState["attributedString"]["hash"]; } newState["paragraphAttributes"] = toDynamic(paragraphAttributes); // TODO: can we memoize this in Java? return newState; } #endif } // namespace react } // namespace facebook
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "AndroidTextInputState.h" #include <react/renderer/components/text/conversions.h> #include <react/renderer/debug/debugStringConvertibleUtils.h> namespace facebook { namespace react { #ifdef ANDROID folly::dynamic AndroidTextInputState::getDynamic() const { // Java doesn't need all fields, so we don't pass them along. folly::dynamic newState = folly::dynamic::object(); newState["mostRecentEventCount"] = mostRecentEventCount; newState["attributedString"] = toDynamic(attributedString); newState["hash"] = newState["attributedString"]["hash"]; newState["paragraphAttributes"] = toDynamic(paragraphAttributes); // TODO: can we memoize this in Java? return newState; } #endif } // namespace react } // namespace facebook
Use make_shared instead of new for creation of Application instance
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Application.h" ouzel::AppPtr ouzelMain(const std::vector<std::string>& args) { std::shared_ptr<ouzel::Application> application(new ouzel::Application()); return application; }
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Application.h" ouzel::AppPtr ouzelMain(const std::vector<std::string>& args) { std::shared_ptr<ouzel::Application> application = std::make_shared<ouzel::Application>(); return application; }
Change C99 VLA C++ dynamic array
/** * fastcall.cpp * * This file holds some PHP functions implementation in C directly. * */ #include "includes.h" namespace Php { bool class_exists(const std::string &classname, bool autoload) { // we need the tsrm_ls variable TSRMLS_FETCH(); zend_class_entry **ce; int found; const char * str = classname.c_str(); int32_t len = (int32_t)classname.length(); if (autoload) { char lc_name[len + 1]; zend_str_tolower_copy(lc_name, str, len); char *name = lc_name; if (lc_name[0] == '\\') { name = &lc_name[1]; --len; } found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce); return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)); } if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) { return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0); } return false; } }
/** * fastcall.cpp * * This file holds some PHP functions implementation in C directly. * */ #include "includes.h" namespace Php { bool class_exists(const std::string &classname, bool autoload) { // we need the tsrm_ls variable TSRMLS_FETCH(); zend_class_entry **ce; int found; const char * str = classname.c_str(); int32_t len = (int32_t)classname.length(); if (autoload) { char *lc_name = new char[len + 1]; zend_str_tolower_copy(lc_name, str, len); char *name = lc_name; if (lc_name[0] == '\\') { name = &lc_name[1]; --len; } found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce); delete [] lc_name; return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)); } if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) { return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0); } return false; } }
Move heart rate calculation to cpp
#include <jni.h> #include <string> #include "SpatialFilter.h" #include "VideoProcessor.h" extern "C" jstring Java_cn_edu_seu_evmhr_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */, jstring jFileName) { const char* jnamestr = env->GetStringUTFChars(jFileName, NULL); VideoProcessor VP; VP.setInput(jnamestr); std::stringstream ss; ss << VP.colorMagnify(); std::string peaks; ss >> peaks; return env->NewStringUTF(peaks.c_str()); }
#include <jni.h> #include <string> #include "SpatialFilter.h" #include "VideoProcessor.h" extern "C" jstring Java_cn_edu_seu_evmhr_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */, jstring jFileName) { const char* jnamestr = env->GetStringUTFChars(jFileName, NULL); VideoProcessor VP; VP.setInput(jnamestr); double length = VP.getLengthMS() / 1000; int peaks = VP.colorMagnify(); std::stringstream ss; ss << std::floor(60 / length * peaks); std::string heartRate; ss >> heartRate; return env->NewStringUTF(heartRate.c_str()); }
Test for SharedResourse::Accessor::isValid method added
#include "SharedResource.h" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(Basic_construction) { SharedResource<int> shared_int; } BOOST_AUTO_TEST_CASE(Construction_with_argument) { SharedResource<int> shared_int(5); } BOOST_AUTO_TEST_CASE(Construction_no_default_constructor) { struct TestClass { TestClass() = delete; TestClass(int) { } }; SharedResource<TestClass> stc2(5); } BOOST_AUTO_TEST_CASE(Basic_Locking) { SharedResource<int> shared_int(0); shared_int.lock(); } BOOST_AUTO_TEST_CASE(Locking_with_accessor) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); }
#include "SharedResource.h" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(Basic_construction) { SharedResource<int> shared_int; } BOOST_AUTO_TEST_CASE(Construction_with_argument) { SharedResource<int> shared_int(5); } BOOST_AUTO_TEST_CASE(Construction_no_default_constructor) { struct TestClass { TestClass() = delete; TestClass(int) { } }; SharedResource<TestClass> stc2(5); } BOOST_AUTO_TEST_CASE(Basic_Locking) { SharedResource<int> shared_int(0); shared_int.lock(); } BOOST_AUTO_TEST_CASE(Locking_with_accessor) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); } BOOST_AUTO_TEST_CASE(Accessor_isValid) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); BOOST_CHECK(shared_int_accessor.isValid()); auto shared_int_accessor_new(std::move(shared_int_accessor)); BOOST_CHECK(!shared_int_accessor.isValid()); BOOST_CHECK(shared_int_accessor_new.isValid()); }
Use abort instead to signal unreachable code.
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "checksumaggregators.h" namespace proton::bucketdb { std::unique_ptr<ChecksumAggregator> ChecksumAggregator::create(ChecksumType type, BucketChecksum seed) { switch (type) { case ChecksumType::LEGACY: return std::make_unique<LegacyChecksumAggregator>(seed); case ChecksumType::XXHASH64: return std::make_unique<XXH64ChecksumAggregator>(seed); } return std::unique_ptr<ChecksumAggregator>(); } }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "checksumaggregators.h" namespace proton::bucketdb { std::unique_ptr<ChecksumAggregator> ChecksumAggregator::create(ChecksumType type, BucketChecksum seed) { switch (type) { case ChecksumType::LEGACY: return std::make_unique<LegacyChecksumAggregator>(seed); case ChecksumType::XXHASH64: return std::make_unique<XXH64ChecksumAggregator>(seed); } abort(); } }
Fix gcc compilation issue, thanks to Evan Driscoll.
// cc.in79 // problem with templatized forward decl? // no, was a problem with templatized prototypes class istream; template<class TP> class smanip; //template<class TP> class smanip {}; template<class TP> inline istream& operator>>(istream& i, const smanip<TP>& m); //int foo(smanip<TP> &m); typedef smanip<int> smanip_int; template<class TP> class smanip { smanip *whatever; smanip<TP> *whatever2; }; void f() { smanip_int s; s.whatever; }
// in/t0079.cc // problem with templatized forward decl? // no, was a problem with templatized prototypes class istream; template<class TP> class smanip; //template<class TP> class smanip {}; template<class TP> inline istream& operator>>(istream& i, const smanip<TP>& m); //int foo(smanip<TP> &m); typedef smanip<int> smanip_int; template<class TP> class smanip { public: smanip *whatever; smanip<TP> *whatever2; }; void f() { smanip_int s; s.whatever; }
Fix mem leak in test code
#include <ostree.h> #include <stdlib.h> extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) { (void)self; const char *hash = getenv("OSTREE_HASH"); return ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1); } extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) { (void)self; return getenv("OSTREE_HASH"); }
#include <ostree.h> #include <stdlib.h> extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) { (void)self; static OstreeDeployment *deployment; if (deployment != nullptr) { return deployment; } const char *hash = getenv("OSTREE_HASH"); deployment = ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1); return deployment; } extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) { (void)self; return getenv("OSTREE_HASH"); }
Replace int_8 with size_t to fix conversion bug
#include <memory> #include "PPMLoader.hpp" std::shared_ptr<Image> PPMLoader::load(const char *pathToImage) { FILE *file = fopen(pathToImage, "r"); char magicNumber[8]; fscanf(file, "%s\n", magicNumber); int width, height; fscanf(file, "%d %d\n", &width, &height); int maxValue; fscanf(file, "%d\n", &maxValue); auto image = std::make_shared<Image>(width, height); size_t index = 0; while (1) { uint8_t r, g, b; int elementsRead = fscanf(file, "%d %d %d", &r, &g, &b); if (elementsRead < 3) { break; } image->setValueOnChannel1(index, normalize(r, maxValue, 255)); image->setValueOnChannel2(index, normalize(g, maxValue, 255)); image->setValueOnChannel3(index, normalize(b, maxValue, 255)); index++; } image->colorSpace = ColorSpaceRGB; return image; } size_t PPMLoader::normalize(size_t colorValue, int originalMaxValue, int normalizedMaxValue) { return (size_t) ((colorValue / (float) originalMaxValue) * normalizedMaxValue); }
#include <memory> #include "PPMLoader.hpp" std::shared_ptr<Image> PPMLoader::load(const char *pathToImage) { FILE *file = fopen(pathToImage, "r"); char magicNumber[8]; fscanf(file, "%s\n", magicNumber); int width, height; fscanf(file, "%d %d\n", &width, &height); int maxValue; fscanf(file, "%d\n", &maxValue); auto image = std::make_shared<Image>(width, height); size_t index = 0; while (1) { size_t r, g, b; int elementsRead = fscanf(file, "%d %d %d", &r, &g, &b); if (elementsRead < 3) { break; } image->setValueOnChannel1(index, normalize(r, maxValue, 255)); image->setValueOnChannel2(index, normalize(g, maxValue, 255)); image->setValueOnChannel3(index, normalize(b, maxValue, 255)); index++; } image->colorSpace = ColorSpaceRGB; return image; } size_t PPMLoader::normalize(size_t colorValue, int originalMaxValue, int normalizedMaxValue) { return (size_t) ((colorValue / (float) originalMaxValue) * normalizedMaxValue); }
Use function to load all script files in script directory.
// Includes. #include "UI/mainwindow.h" #include "App/App.h" #include "App/Factories/AdditionNFDelegate.h" #include "App/Factories/ConstantNFDelegate.h" #include "App/Factories/PrinterNFDelegate.h" #include "App/Factories/TextFileNFDelegate.h" #include "System/QtBasedFileSystem.h" // Qt. #include <QApplication> QString titleString() { QString name = QString::fromStdString(App::appName()); QString version = QString::fromStdString(App::appVersion()); return QString("%1 - v%2").arg(name).arg(version); } int main(int argc, char *argv[]) { QApplication a(argc, argv); QtBasedFileSystem file_system; App app(&file_system); app.addNodeFactory(new AdditionNFDelegate); app.addNodeFactory(new ConstantNFDelegate); app.addNodeFactory(new PrinterNFDelegate); app.addNodeFactory(new TextFileNFDelegate); MainWindow w(&app); w.setWindowTitle(titleString()); w.setMinimumSize(800, 600); w.show(); app.setUI(&w); app.setDelegate(&w); return a.exec(); }
// Includes. #include "UI/mainwindow.h" #include "App/App.h" #include "App/Factories/AdditionNFDelegate.h" #include "App/Factories/ConstantNFDelegate.h" #include "App/Factories/PrinterNFDelegate.h" #include "App/Factories/TextFileNFDelegate.h" #include "System/QtBasedFileSystem.h" // Qt. #include <QApplication> QString titleString() { QString name = QString::fromStdString(App::appName()); QString version = QString::fromStdString(App::appVersion()); return QString("%1 - v%2").arg(name).arg(version); } int main(int argc, char *argv[]) { QApplication a(argc, argv); QtBasedFileSystem file_system; App app(&file_system); app.addNodeFactory(new AdditionNFDelegate); app.addNodeFactory(new ConstantNFDelegate); app.addNodeFactory(new PrinterNFDelegate); app.addNodeFactory(new TextFileNFDelegate); app.loadScriptNodes("Nodin/NodeScripts/Lua"); MainWindow w(&app); w.setWindowTitle(titleString()); w.setMinimumSize(800, 600); w.show(); app.setUI(&w); app.setDelegate(&w); return a.exec(); }
Remove unnecessary dynamic_cast to base class
#include <QApplication> #include <QtDeclarative> #include <QDeclarativeView> #include <QDeclarativeContext> #include "settingspersistor.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QSettings settings("qmltweeter.conf", QSettings::IniFormat); settings.sync(); QDeclarativeView view; QDeclarativeContext *context = view.rootContext(); SettingsPersistor settingsPersistor(context, &settings); context->setContextProperty("settings", &settingsPersistor); QString searchTerm = settings.value("searchTerm", QString("meego")).toString(); context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm)); view.setSource(QUrl("qrc:///qml/qmltweeter.qml")); QObject *rootObject = dynamic_cast<QObject*>(view.rootObject()); QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant))); view.show(); return app.exec(); }
#include <QApplication> #include <QtDeclarative> #include <QDeclarativeView> #include <QDeclarativeContext> #include "settingspersistor.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QSettings settings("qmltweeter.conf", QSettings::IniFormat); settings.sync(); QDeclarativeView view; QDeclarativeContext *context = view.rootContext(); SettingsPersistor settingsPersistor(context, &settings); context->setContextProperty("settings", &settingsPersistor); QString searchTerm = settings.value("searchTerm", QString("meego")).toString(); context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm)); view.setSource(QUrl("qrc:///qml/qmltweeter.qml")); QObject *rootObject = view.rootObject(); QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant))); view.show(); return app.exec(); }
Put the symbol requester func into the proper namespace!
// request symbols #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/DynamicExprInfo.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/LookupHelper.h" #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/UserInterface/UserInterface.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" namespace cling { void libcling__symbol_requester() { const char* const argv[] = {"libcling__symbol_requester", 0}; cling::Interpreter I(1, argv); cling::UserInterface U(I); cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call. printValuePublicDefault(llvm::outs(), 0, VPI); cling_PrintValue(0, 0, 0); flushOStream(llvm::outs()); LookupHelper h(0); h.findType(""); h.findScope(""); h.findFunctionProto(0, "", ""); h.findFunctionArgs(0, "", ""); cling::runtime::internal::DynamicExprInfo DEI(0,0,false); DEI.getExpr(); cling::InterpreterCallbacks cb(0); } }
// request symbols #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/DynamicExprInfo.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/LookupHelper.h" #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/UserInterface/UserInterface.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" namespace cling { namespace internal { void libcling__symbol_requester() { const char* const argv[] = {"libcling__symbol_requester", 0}; cling::Interpreter I(1, argv); cling::UserInterface U(I); cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call. printValuePublicDefault(llvm::outs(), 0, VPI); cling_PrintValue(0, 0, 0); flushOStream(llvm::outs()); LookupHelper h(0); h.findType(""); h.findScope(""); h.findFunctionProto(0, "", ""); h.findFunctionArgs(0, "", ""); cling::runtime::internal::DynamicExprInfo DEI(0,0,false); DEI.getExpr(); cling::InterpreterCallbacks cb(0); } } }
Allow unit tests to be compiled with -fno-exception
/* * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "platform/mbed_assert.h" #include "gtest/gtest.h" #include <stdio.h> #include <stdbool.h> bool mbed_assert_throw_errors = false; extern "C" void mbed_assert_internal(const char *expr, const char *file, int line) { fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line); if (mbed_assert_throw_errors) { throw 1; } /* Ensure we fail the unit test if the Mbed assertion fails. Without this, * we might not notice the assertion failure as it wouldn't be bubbled up * to googletest. Note that this is after the above throw, as some tests * check that an exception is thrown (i.e. negative tests). */ FAIL(); }
/* * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "platform/mbed_assert.h" #include "gtest/gtest.h" #include <stdio.h> #include <stdbool.h> bool mbed_assert_throw_errors = false; extern "C" void mbed_assert_internal(const char *expr, const char *file, int line) { fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line); if (mbed_assert_throw_errors) { #ifdef __EXCEPTIONS throw 1; #else FAIL(); #endif } /* Ensure we fail the unit test if the Mbed assertion fails. Without this, * we might not notice the assertion failure as it wouldn't be bubbled up * to googletest. Note that this is after the above throw, as some tests * check that an exception is thrown (i.e. negative tests). */ FAIL(); }
Fix a lit test failure after MallocChecker changes
// REQUIRES: static-analyzer // RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s extern void *malloc(unsigned long); extern void free(void *); void f() { int *p = new int(42); delete p; delete p; // CHECK: warning: Attempt to free released memory [clang-analyzer-cplusplus.NewDelete] } void g() { void *q = malloc(132); free(q); free(q); // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc] }
// REQUIRES: static-analyzer // RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s extern void *malloc(unsigned long); extern void free(void *); void f() { int *p = new int(42); delete p; delete p; // CHECK: warning: Attempt to delete released memory [clang-analyzer-cplusplus.NewDelete] } void g() { void *q = malloc(132); free(q); free(q); // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc] }
Fix bug to see Travis succeed
#include "arithmetics.hpp" namespace arithmetics { int add(int a, int b) { return a + b; } int add_buggy(int a, int b) { return a + b + 1; } }
#include "arithmetics.hpp" namespace arithmetics { int add(int a, int b) { return a + b; } int add_buggy(int a, int b) { return a + b; } }
Fix double to unsigned error
#include <numeric> #include <vector> #include SPECIFIC_HEADER int main(int /*argc*/, char** /*argv*/) { constexpr unsigned num_entries = 1e7; std::vector<int> in(num_entries); std::iota(std::begin(in), std::end(in), 0); auto out = product_except(in); bool success = out[1] == 0; return !success; }
#include <numeric> #include <vector> #include SPECIFIC_HEADER int main(int /*argc*/, char** /*argv*/) { constexpr unsigned num_entries = 10000000; std::vector<int> in(num_entries); std::iota(std::begin(in), std::end(in), 0); auto out = product_except(in); bool success = out[1] == 0; return !success; }
Update for removal of type-specifier from reader
#include <iostream> #include <algorithm> #include "io/PGMIO.hpp" #include "matrix/Matrix.hpp" using namespace sipl; int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage:" << std::endl; std::cout << " " << argv[0] << " file.pgm" << std::endl; std::exit(1); } // const std::string filename{argv[1]}; PGMIO pgm; auto mat = pgm.read<uint8_t>("tmp_ascii.pgm"); // pgm.write(mat, "tmp_binary.pgm", PGMIO::PType::BINARY); pgm.write(mat, "tmp_ascii2.pgm", PGMIO::PType::ASCII); }
#include <iostream> #include <algorithm> #include "io/PgmIO.hpp" #include "matrix/Matrix.hpp" using namespace sipl; int main(int argc, char** argv) { if (argc < 3) { std::cout << "Usage:" << std::endl; std::cout << " " << argv[0] << " infile.pgm outfile.pgm" << std::endl; std::exit(1); } // const std::string filename{argv[1]}; PgmIO pgm; auto mat = pgm.read(argv[1]); pgm.write(mat, argv[2], PGMIO::PType::BINARY); // pgm.write(mat, argv[2], PGMIO::PType::ASCII); }
Implement method for finding single element by counting occurrences of each bit across all elements in the input array
#include <iostream> #include <fstream> #include <memory> #include "..\..\shared\ProblemEngine.h" int FindSingleElement(const std::shared_ptr<int>& inputArray, int size); int main(int argc, char * argv[]) { ProblemEngine engine("input.txt"); if (!engine.IsFileOk()) { std::cout << "Unable to open input.txt" << std::endl; return 1; } auto testCases = engine.LoadTestCases(); for (const auto& testCase : testCases) { if (testCase.Size % 2 == 0) //only odd inputs accepted continue; auto singleElement = FindSingleElement(testCase.Data, testCase.Size); std::cout << singleElement << std::endl; } return 0; } int FindSingleElement(const std::shared_ptr<int>& inputArray, int size) { return 0; }
#include <iostream> #include <fstream> #include <memory> #include "..\..\shared\ProblemEngine.h" int FindSingleElement(const std::shared_ptr<int>& inputArray, int size); int main(int argc, char * argv[]) { ProblemEngine engine("input.txt"); if (!engine.IsFileOk()) { std::cout << "Unable to open input.txt" << std::endl; return 1; } auto testCases = engine.LoadTestCases(); for (const auto& testCase : testCases) { if (testCase.Size % 2 == 0) //only odd inputs accepted continue; auto singleElement = FindSingleElement(testCase.Data, testCase.Size); std::cout << singleElement << std::endl; } return 0; } int FindSingleElement(const std::shared_ptr<int>& inputArray, int size) { const int INT_SIZE_IN_BITS = 32; //this method only works if there are 'n' occurrences of each element other than the single element //in the case of this test data, there are two occurrences of every other element since the problem states pairs of people const int EXPECTED_ELEMENT_OCCURRENCES = 2; int result = 0; auto ptr = inputArray.get(); for (int bit = 0; bit < INT_SIZE_IN_BITS; ++bit) { int sum = 0; int bitMask = 1 << bit; for (int i = 0; i < size; ++i) if (ptr[i] & bitMask) sum++; if (sum % EXPECTED_ELEMENT_OCCURRENCES != 0) result |= bitMask; } return result; }
Add test for removing a label.
#include <Eigen/Core> #include "./test.h" #include "../src/labelling/labels.h" #include "../src/labelling/label.h" TEST(Test_Labels, ChangeNotification) { Labels labels; int changedLabelId = -1; Labels::Action receivedAction; auto removeSubscription = labels.subscribe([&changedLabelId, &receivedAction]( Labels::Action action, const Label &label) { receivedAction = action; changedLabelId = label.id; }); labels.add(Label(1, "Label text", Eigen::Vector3f(1, 2, 3))); ASSERT_EQ(1, changedLabelId); ASSERT_EQ(Labels::Action::Add, receivedAction); removeSubscription(); labels.add(Label(2, "Label text", Eigen::Vector3f(1, 2, 3))); ASSERT_EQ(1, changedLabelId); }
#include <Eigen/Core> #include "./test.h" #include "../src/labelling/labels.h" #include "../src/labelling/label.h" TEST(Test_Labels, ChangeNotification) { Labels labels; int changedLabelId = -1; Labels::Action receivedAction; auto removeSubscription = labels.subscribe([&changedLabelId, &receivedAction]( Labels::Action action, const Label &label) { receivedAction = action; changedLabelId = label.id; }); labels.add(Label(1, "Label text", Eigen::Vector3f(1, 2, 3))); ASSERT_EQ(1, changedLabelId); ASSERT_EQ(Labels::Action::Add, receivedAction); removeSubscription(); labels.add(Label(2, "Label text", Eigen::Vector3f(1, 2, 3))); ASSERT_EQ(1, changedLabelId); } TEST(Test_Labels, Remove) { Labels labels; Label label(1, "Label text", Eigen::Vector3f(1, 2, 3)); labels.add(label); ASSERT_EQ(1, labels.count()); int changedLabelId = -1; Labels::Action receivedAction; auto removeSubscription = labels.subscribe([&changedLabelId, &receivedAction]( Labels::Action action, const Label &label) { receivedAction = action; changedLabelId = label.id; }); labels.remove(label); ASSERT_EQ(0, labels.count()); ASSERT_EQ(1, changedLabelId); ASSERT_EQ(Labels::Action::Delete, receivedAction); }
Mark thread exit test as unsupported w/o threads
//===--------------------- cxa_thread_atexit_test.cpp ---------------------===// // // 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. // //===----------------------------------------------------------------------===// // REQUIRES: linux #include <assert.h> #include <cxxabi.h> static bool AtexitImplCalled = false; extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj, void *dso_symbol) { assert(dtor == reinterpret_cast<void (*)(void *)>(1)); assert(obj == reinterpret_cast<void *>(2)); assert(dso_symbol == reinterpret_cast<void *>(3)); AtexitImplCalled = true; return 4; } int main() { int RV = __cxxabiv1::__cxa_thread_atexit( reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2), reinterpret_cast<void *>(3)); assert(RV == 4); assert(AtexitImplCalled); return 0; }
//===--------------------- cxa_thread_atexit_test.cpp ---------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: libcppabi-no-threads // REQUIRES: linux #include <assert.h> #include <cxxabi.h> static bool AtexitImplCalled = false; extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj, void *dso_symbol) { assert(dtor == reinterpret_cast<void (*)(void *)>(1)); assert(obj == reinterpret_cast<void *>(2)); assert(dso_symbol == reinterpret_cast<void *>(3)); AtexitImplCalled = true; return 4; } int main() { int RV = __cxxabiv1::__cxa_thread_atexit( reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2), reinterpret_cast<void *>(3)); assert(RV == 4); assert(AtexitImplCalled); return 0; }
Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } // Disabled, flakily exceeds timeout, http://crbug.com/72165. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_; }
Set default stroke-width to 1
#include "pch.h" #include "style.h" using namespace Windows::Foundation; style::style() : fill_(paint_type::color, Colors::Black) , stroke_(paint_type::none, Colors::Black) , strokeWidth_(length{ 0, unit::unspecified }) { } ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator) { return fill_.brush(resourceCreator); } ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator) { return stroke_.brush(resourceCreator); } float style::stroke_width() { return strokeWidth_.Number; // TODO: respect the Unit! } inherited_style::inherited_style() { style defaultStyle; stack_.push(defaultStyle); } void inherited_style::push() { stack_.push(stack_.top()); } void inherited_style::pop() { stack_.pop(); assert(!stack_.empty()); }
#include "pch.h" #include "style.h" using namespace Windows::Foundation; style::style() : fill_(paint_type::color, Colors::Black) , stroke_(paint_type::none, Colors::Black) , strokeWidth_(length{ 1, unit::unspecified }) { } ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator) { return fill_.brush(resourceCreator); } ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator) { return stroke_.brush(resourceCreator); } float style::stroke_width() { return strokeWidth_.Number; // TODO: respect the Unit! } inherited_style::inherited_style() { style defaultStyle; stack_.push(defaultStyle); } void inherited_style::push() { stack_.push(stack_.top()); } void inherited_style::pop() { stack_.pop(); assert(!stack_.empty()); }
Fix memory leak in float literal parsing Issue=93
// // Copyright (c) 2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include <math.h> #include <stdlib.h> #include "util.h" #ifdef _MSC_VER #include <locale.h> #else #include <sstream> #endif double atof_dot(const char *str) { #ifdef _MSC_VER return _atof_l(str, _create_locale(LC_NUMERIC, "C")); #else double result; std::istringstream s(str); std::locale l("C"); s.imbue(l); s >> result; return result; #endif }
// // Copyright (c) 2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include <math.h> #include <stdlib.h> #include "util.h" #ifdef _MSC_VER #include <locale.h> #else #include <sstream> #endif double atof_dot(const char *str) { #ifdef _MSC_VER _locale_t l = _create_locale(LC_NUMERIC, "C"); double result = _atof_l(str, l); _free_locale(l); return result; #else double result; std::istringstream s(str); std::locale l("C"); s.imbue(l); s >> result; return result; #endif }
Add GCController.minorCollect(), which triggers one minor GC cycle
// 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 "webkit/support/gc_extension.h" #include "v8/include/v8.h" const char kGCExtensionName[] = "v8/GCController"; namespace extensions_v8 { // static v8::Extension* GCExtension::Get() { v8::Extension* extension = new v8::Extension( kGCExtensionName, "(function () {" " var v8_gc;" " if (gc) v8_gc = gc;" " GCController = new Object();" " GCController.collect =" " function() {if (v8_gc) v8_gc(); };" " })();"); return extension; } } // namespace extensions_v8
// 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 "webkit/support/gc_extension.h" #include "v8/include/v8.h" const char kGCExtensionName[] = "v8/GCController"; namespace extensions_v8 { // static v8::Extension* GCExtension::Get() { v8::Extension* extension = new v8::Extension( kGCExtensionName, "(function () {" " var v8_gc;" " if (gc) v8_gc = gc;" " GCController = new Object();" " GCController.collect =" " function() {if (v8_gc) v8_gc(); };" " GCController.minorCollect =" " function() {if (v8_gc) v8_gc(true); };" " })();"); return extension; } } // namespace extensions_v8
Use a volatile store instead of a memory barrier
#include "HalideRuntime.h" #include "runtime_internal.h" extern "C" { WEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) { __sync_synchronize(); state->current_func = tok + t; __sync_synchronize(); return 0; } }
#include "HalideRuntime.h" #include "runtime_internal.h" extern "C" { WEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) { // Do a volatile store to discourage llvm from reordering it. volatile int *ptr = &(state->current_func); *ptr = tok + t; return 0; } }
Remove inclusion of non-existing precompiled header
#include "pch.h" #include "json_rpc_debug_logger.h" #include <QDebug> namespace jcon { void JsonRpcDebugLogger::logInfo(const QString& message) { qDebug().noquote() << message; } void JsonRpcDebugLogger::logWarning(const QString& message) { qDebug().noquote() << message; } void JsonRpcDebugLogger::logError(const QString& message) { qDebug().noquote() << message; } }
#include "json_rpc_debug_logger.h" #include <QDebug> namespace jcon { void JsonRpcDebugLogger::logInfo(const QString& message) { qDebug().noquote() << message; } void JsonRpcDebugLogger::logWarning(const QString& message) { qDebug().noquote() << message; } void JsonRpcDebugLogger::logError(const QString& message) { qDebug().noquote() << message; } }
Fix compile errors on Linux
#include "reg_filter_mode_translator.h" #include "orz/types.h" namespace Reg { namespace Internal { boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) { if (sval.empty()) return boost::none; if (sval == "Bilinear") { return Filter::Mode::Bilinear; } if (sval == "Nearest") { return Filter::Mode::NearestNeighbor; } if (sval == "Lanczos3") { return Filter::Mode::Lanczos3; } switch (FromAString<int>(sval)) { case 1: return Filter::Mode::NearestNeighbor; case 2: return Filter::Mode::Bilinear; case 3: return Filter::Mode::Lanczos3; } return boost::none; } boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) { switch (val) { case Filter::Mode::NearestNeighbor: return "Nearest"; case Filter::Mode::Bilinear: return "Bilinear"; case Filter::Mode::Lanczos3: return "Lanczos3"; } return boost::none; } } }
#include "reg_filter_mode_translator.h" #include "orz/types.h" namespace Reg { namespace Internal { boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) { if (sval.empty()) return boost::none; if (sval == "Bilinear") { return Filter::Mode::Bilinear; } if (sval == "Nearest") { return Filter::Mode::NearestNeighbor; } if (sval == "Lanczos3") { return Filter::Mode::Lanczos3; } switch (FromAString<int>(sval)) { case 1: return Filter::Mode::NearestNeighbor; case 2: return Filter::Mode::Bilinear; case 3: return Filter::Mode::Lanczos3; } return boost::none; } boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) { switch (val) { case Filter::Mode::NearestNeighbor: return std::string("Nearest"); case Filter::Mode::Bilinear: return std::string("Bilinear"); case Filter::Mode::Lanczos3: return std::string("Lanczos3"); } return boost::none; } } }
Include sdk/config.h before testing configuration macros.
#ifndef SCHEDULER_CORO_OSTHREAD # include "Coro.c" #endif
#include <sdk/config.h> #ifndef SCHEDULER_CORO_OSTHREAD # include "Coro.c" #endif
Fix build issue on certain compilers.
//===- MachineDominators.cpp - Machine Dominator Calculation --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements simple dominator construction algorithms for finding // forward dominators on machine functions. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/Passes.h" using namespace llvm; TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>); TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>); namespace { char MachineDominatorTree::ID = 0; RegisterPass<MachineDominatorTree> E("machinedomtree", "MachineDominator Tree Construction", true); } const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();
//===- MachineDominators.cpp - Machine Dominator Calculation --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements simple dominator construction algorithms for finding // forward dominators on machine functions. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/Passes.h" using namespace llvm; TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>); TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>); char MachineDominatorTree::ID = 0; namespace { RegisterPass<MachineDominatorTree> E("machinedomtree", "MachineDominator Tree Construction", true); } const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();
Revert updating file/folder parameter for Global File unit tests
#include "gtest/gtest.h" #include "braincloud/BrainCloudClient.h" #include "TestResult.h" #include "TestBCGlobalFile.h" #include <vector> using namespace BrainCloud; static const std::string testfileName = "png1.png"; static const std::string testFileId = "34802251-0da0-419e-91b5-59d91790af15"; static const std::string testFolderPath = "/existingfolder/"; TEST_F(TestBCGlobalFile, GetFileInfo) { TestResult tr; m_bc->getGlobalFileService()->getFileInfo(testFileId, &tr); tr.run(m_bc); } TEST_F(TestBCGlobalFile, GetFileInfoSimple) { TestResult tr; m_bc->getGlobalFileService()->getFileInfoSimple(testFolderPath, testfileName, &tr); tr.run(m_bc); } TEST_F(TestBCGlobalFile, GetGlobalCDNUrl) { TestResult tr; m_bc->getGlobalFileService()->getGlobalCDNUrl(testFileId, &tr); tr.run(m_bc); } TEST_F(TestBCGlobalFile, GetGlobalFileList) { TestResult tr; m_bc->getGlobalFileService()->getGlobalFileList(testFolderPath, true, &tr); tr.run(m_bc); }
#include "gtest/gtest.h" #include "braincloud/BrainCloudClient.h" #include "TestResult.h" #include "TestBCGlobalFile.h" #include <vector> using namespace BrainCloud; static const std::string testfileName = "testGlobalFile.png"; static const std::string testFileId = "ed2d2924-4650-4a88-b095-94b75ce9aa18"; static const std::string testFolderPath = "/fname/"; TEST_F(TestBCGlobalFile, GetFileInfo) { TestResult tr; m_bc->getGlobalFileService()->getFileInfo(testFileId, &tr); tr.run(m_bc); } TEST_F(TestBCGlobalFile, GetFileInfoSimple) { TestResult tr; m_bc->getGlobalFileService()->getFileInfoSimple(testFolderPath, testfileName, &tr); tr.run(m_bc); } TEST_F(TestBCGlobalFile, GetGlobalCDNUrl) { TestResult tr; m_bc->getGlobalFileService()->getGlobalCDNUrl(testFileId, &tr); tr.run(m_bc); } TEST_F(TestBCGlobalFile, GetGlobalFileList) { TestResult tr; m_bc->getGlobalFileService()->getGlobalFileList(testFolderPath, true, &tr); tr.run(m_bc); }
Add alert when Google API key was not specified
#include "JNIRhodes.h" #include "gapikey.h" #include <common/rhoparams.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "MapView" RHO_GLOBAL void mapview_create(rho_param *p) { #ifdef GOOGLE_API_KEY jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!clsMapView) return; jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V"); if (!midCreate) return; if (p->type != RHO_PARAM_HASH) { RAWLOG_ERROR("create: wrong input parameter (expect Hash)"); return; } JNIEnv *env = jnienv(); jobject paramsObj = RhoValueConverter(env).createObject(p); env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj); #else RHO_NOT_IMPLEMENTED; #endif }
#include "JNIRhodes.h" #include "gapikey.h" #include <common/rhoparams.h> #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "MapView" extern "C" void alert_show_popup(char *); RHO_GLOBAL void mapview_create(rho_param *p) { #ifdef GOOGLE_API_KEY jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW); if (!clsMapView) return; jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V"); if (!midCreate) return; if (p->type != RHO_PARAM_HASH) { RAWLOG_ERROR("create: wrong input parameter (expect Hash)"); return; } JNIEnv *env = jnienv(); jobject paramsObj = RhoValueConverter(env).createObject(p); env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj); #else alert_show_popup("Google API key problem"); #endif }
Add edges values and proper labels to node in Dot output
#include "DotGraphOutput.hh" #include "EdgeType.hh" string getEdgeStyle(EdgeType t) { switch (t) { case EdgeType::Plane: return "[color=red]"; case EdgeType::Train: return "[color=blue,style=dotted]"; default: return ""; } } template <typename V> void DotGraphOutput<V>::output(string path) { cout << "Exporting " << this->graph_.name() << " to " << path << endl; ofstream st(path, ofstream::out); st << "digraph " << this->graph_.name() << " {" << endl; for (unsigned int i = 0; i < this->graph_.verticesNb(); i++) for (auto e : this->graph_.outgoingEdges(i)) { st << "\t" << this->graph_.getVertex(i).name() << " -> " << this->graph_.getVertex(e->getOtherEnd(i)).name() << " " << getEdgeStyle(e->type()) << ";" << endl; } st << "}" << endl; st.close(); } template class DotGraphOutput<double>;
#include "DotGraphOutput.hh" #include "EdgeType.hh" #include <sstream> template <typename V> string getEdgeStyle(EdgeType t, V val) { stringstream ss; string end("\"]"); switch (t) { case EdgeType::Plane: ss << string("[color=red, label=\"") << val << end; break; case EdgeType::Train: ss << string("[color=blue, style=dotted, label=\"") << val << end ; break; default: ss << string("[label=\"") << val << end; break; } return ss.str(); } template <typename V> void DotGraphOutput<V>::output(string path) { cout << "Exporting " << this->graph_.name() << " to " << path << endl; ofstream st(path, ofstream::out); st << "digraph " << this->graph_.name() << " {" << endl; for (unsigned int i = 0; i < this->graph_.verticesNb(); i++) st << "\t" << i << " [label=\"" << this->graph_.getVertex(i).name() << "\"];" << endl; for (unsigned int i = 0; i < this->graph_.verticesNb(); i++) for (auto e : this->graph_.outgoingEdges(i)) { st << "\t" << i << " -> " << e->getOtherEnd(i) << " " << getEdgeStyle(e->type(), e->distance()) << ";" << endl; } st << "}" << endl; st.close(); } template class DotGraphOutput<double>;
Fix a compiler error glitch with some bullshit.
#ifdef LEGACY_LINUX // Wrappers for eventfd(), since CentOS backported the system // calls but not the libc wrappers. #include "arch/linux/system_event/eventfd.hpp" #include "utils.hpp" #include <sys/syscall.h> int eventfd(int count, int flags) { rassert(flags == 0); // Legacy kernel doesn't have eventfd2. return syscall(SYS_eventfd, count); } int eventfd_read(int fd, eventfd_t *value) { int res = read(fd, value, sizeof(eventfd_t)); return (res == sizeof(eventfd_t)) ? 0 : -1; } int eventfd_write(int fd, eventfd_t value) { int res = write(fd, &value, sizeof(eventfd_t)); return (res == sizeof(eventfd_t)) ? 0 : -1; } #endif
#ifdef LEGACY_LINUX // Wrappers for eventfd(), since CentOS backported the system // calls but not the libc wrappers. #include "arch/linux/system_event/eventfd.hpp" #include "utils.hpp" #include <sys/syscall.h> int eventfd(int count, UNUSED int flags) { rassert(flags == 0); // Legacy kernel doesn't have eventfd2. return syscall(SYS_eventfd, count); } int eventfd_read(int fd, eventfd_t *value) { int res = read(fd, value, sizeof(eventfd_t)); return (res == sizeof(eventfd_t)) ? 0 : -1; } int eventfd_write(int fd, eventfd_t value) { int res = write(fd, &value, sizeof(eventfd_t)); return (res == sizeof(eventfd_t)) ? 0 : -1; } #endif
Use an ini file to store GUI settings in windows
/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "mainwindow.h" #include "version.h" #include <QApplication> #include <QCommandLineParser> using namespace UnTech::GuiQt; int main(int argc, char* argv[]) { QApplication app(argc, argv); app.setApplicationDisplayName("UnTech Editor GUI"); app.setOrganizationDomain(UNTECH_DOMAIN); app.setApplicationVersion(UNTECH_VERSION); QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("file", "utres file", "[file]"); parser.process(app); MainWindow* window = new MainWindow(); window->show(); const QStringList args = parser.positionalArguments(); if (args.size() > 0) { window->loadProject(args.first()); } return app.exec(); }
/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "mainwindow.h" #include "version.h" #include <QApplication> #include <QCommandLineParser> #include <QSettings> using namespace UnTech::GuiQt; int main(int argc, char* argv[]) { QApplication app(argc, argv); app.setApplicationDisplayName("UnTech Editor GUI"); app.setOrganizationDomain(UNTECH_DOMAIN); app.setApplicationVersion(UNTECH_VERSION); #ifdef Q_OS_WIN // Use an ini file instead of the registry to store GUI settings. // // The `window_state` QSettings key is ~5.3KB (as of December 2019) and // Microsoft's documentation recommends that we do not store values > 2048 bytes in the registry. // https://docs.microsoft.com/en-us/windows/win32/sysinfo/registry-element-size-limits QSettings::setDefaultFormat(QSettings::IniFormat); #endif QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("file", "utres file", "[file]"); parser.process(app); MainWindow* window = new MainWindow(); window->show(); const QStringList args = parser.positionalArguments(); if (args.size() > 0) { window->loadProject(args.first()); } return app.exec(); }
Create BasicProtocolCodec if _protocolCodec is null
#include "nwg_service.h" #include "nwg_eventloop.h" namespace Nwg { Service::Service(EventLoop *eventLoop) : _eventLoop(eventLoop), _protocolCodec(nullptr), _handler(nullptr) { } Service::~Service() { _protocolCodec.reset(); _handler.reset(); } void Service::setBuffSize(int buffSize) { _buffSize = buffSize; } void Service::setReadBuffSize(int readBuffSize) { _readBuffSize = readBuffSize; } void Service::setProtocolCodec(const std::shared_ptr<ProtocolCodec> &protocolCodec) { _protocolCodec = protocolCodec; } void Service::setHandler(const std::shared_ptr<Handler> &handler) { _handler = handler; } EventLoop *Service::getEventLoop() const { return _eventLoop; } size_t Service::getBuffSize() { return _buffSize; } size_t Service::getReadBuffSize() { return _readBuffSize; } ProtocolCodec &Service::getProtocolCodec() { return *_protocolCodec; } Handler &Service::getHandler() { return *_handler; } } /* namespace Nwg */
#include "nwg_service.h" #include "nwg_eventloop.h" #include "nwg_basicprotocolcodec.h" namespace Nwg { Service::Service(EventLoop *eventLoop) : _eventLoop(eventLoop), _protocolCodec(nullptr), _handler(nullptr) { } Service::~Service() { _protocolCodec.reset(); _handler.reset(); } void Service::setBuffSize(int buffSize) { _buffSize = buffSize; } void Service::setReadBuffSize(int readBuffSize) { _readBuffSize = readBuffSize; } void Service::setProtocolCodec(const std::shared_ptr<ProtocolCodec> &protocolCodec) { _protocolCodec = protocolCodec; } void Service::setHandler(const std::shared_ptr<Handler> &handler) { _handler = handler; } EventLoop *Service::getEventLoop() const { return _eventLoop; } size_t Service::getBuffSize() { return _buffSize; } size_t Service::getReadBuffSize() { return _readBuffSize; } ProtocolCodec &Service::getProtocolCodec() { if (_protocolCodec == nullptr) { _protocolCodec = std::make_shared<Nwg::BasicProtocolCodec>(); } return *_protocolCodec; } Handler &Service::getHandler() { return *_handler; } } /* namespace Nwg */
Use PL_cleanup instead of PL_halt
#include "PrologInterface.h" void PrologLifetime::begin(int argc, char *argv[]) { if (!PL_initialise(argc, argv)) { PL_halt(EXIT_FAILURE); } } void PrologLifetime::end() { PL_halt(EXIT_SUCCESS); }
#include "PrologInterface.h" void PrologLifetime::begin(int argc, char *argv[]) { if (!PL_initialise(argc, argv)) { PL_halt(EXIT_FAILURE); } } void PrologLifetime::end() { PL_cleanup(EXIT_SUCCESS); }
Use node::MakeCallback to emit events in C++
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/event_emitter_caller.h" namespace mate { namespace internal { v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate, v8::Local<v8::Object> obj, ValueVector* args) { v8::Local<v8::String> emit_name = StringToSymbol(isolate, "emit"); v8::Local<v8::Value> emit = obj->Get(emit_name); if (emit.IsEmpty() || !emit->IsFunction()) { isolate->ThrowException(v8::Exception::TypeError( StringToV8(isolate, "\"emit\" is not a function"))); return v8::Undefined(isolate); } v8::MaybeLocal<v8::Value> result = emit.As<v8::Function>()->Call( isolate->GetCurrentContext(), obj, args->size(), &args->front()); if (result.IsEmpty()) { return v8::Undefined(isolate); } return result.ToLocalChecked(); } } // namespace internal } // namespace mate
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/event_emitter_caller.h" #include "atom/common/node_includes.h" namespace mate { namespace internal { v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate, v8::Local<v8::Object> obj, ValueVector* args) { return node::MakeCallback( isolate, obj, "emit", args->size(), &args->front()); } } // namespace internal } // namespace mate
Remove logic that isn't supported on Ubuntu/Debian
#include "GoogleLogFatalHandler.hpp" #include "Headers.hpp" namespace google { namespace glog_internal_namespace_ { void DumpStackTraceToString(string* stacktrace); } } // namespace google static void DumpStackTraceToFileAndExit() { string s; google::glog_internal_namespace_::DumpStackTraceToString(&s); LOG(ERROR) << "STACK TRACE:\n" << s; // TOOD(hamaji): Use signal instead of sigaction? if (google::glog_internal_namespace_::IsFailureSignalHandlerInstalled()) { // Set the default signal handler for SIGABRT, to avoid invoking our // own signal handler installed by InstallFailureSignalHandler(). #ifdef HAVE_SIGACTION struct sigaction sig_action; memset(&sig_action, 0, sizeof(sig_action)); sigemptyset(&sig_action.sa_mask); sig_action.sa_handler = SIG_DFL; sigaction(SIGABRT, &sig_action, NULL); #elif defined(OS_WINDOWS) signal(SIGABRT, SIG_DFL); #endif // HAVE_SIGACTION } abort(); } namespace et { void GoogleLogFatalHandler::handle() { google::InstallFailureFunction(&DumpStackTraceToFileAndExit); } } // namespace et
#include "GoogleLogFatalHandler.hpp" #include "Headers.hpp" namespace google { namespace glog_internal_namespace_ { void DumpStackTraceToString(string* stacktrace); } } // namespace google static void DumpStackTraceToFileAndExit() { string s; google::glog_internal_namespace_::DumpStackTraceToString(&s); LOG(ERROR) << "STACK TRACE:\n" << s; abort(); } namespace et { void GoogleLogFatalHandler::handle() { google::InstallFailureFunction(&DumpStackTraceToFileAndExit); } } // namespace et
Correct for color order inside PNG
#include <RGBColor.h> RGBColor RGBColor::black(glm::vec3(0.f, 0.f, 0.f)); RGBColor RGBColor::red(glm::vec3(1.f, 0.f, 0.f)); RGBColor::RGBColor() : color(glm::vec3(0.f, 0.f, 0.f)) { } RGBColor::RGBColor(const glm::vec3& color) : color(color) { } glm::vec3 RGBColor::GetRGBComponents() const { return this->color; } uint32_t RGBColor::GetRGBAIntPacked() const { uint32_t col = 0xFF; col = col | ((uint32_t)(color.x * 0xFF) << 24); col = col | ((uint32_t)(color.y * 0xFF) << 16); col = col | ((uint32_t)(color.z * 0xFF) << 8); return col; }
#include <RGBColor.h> RGBColor RGBColor::black(glm::vec3(0.f, 0.f, 0.f)); RGBColor RGBColor::red(glm::vec3(1.f, 0.f, 0.f)); RGBColor::RGBColor() : color(glm::vec3(0.f, 0.f, 0.f)) { } RGBColor::RGBColor(const glm::vec3& color) : color(color) { } glm::vec3 RGBColor::GetRGBComponents() const { return this->color; } uint32_t RGBColor::GetRGBAIntPacked() const { uint32_t col = 0; col = col | ((uint32_t)(color.x * 0xFF)); col = col | ((uint32_t)(color.y * 0xFF) << 8); col = col | ((uint32_t)(color.z * 0xFF) << 16); col = col | (0xFF << 24); return col; }
Use more specific checks filter in the test.
// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp // RUN: clang-tidy %t.cpp -fix -checks=llvm.* -- // RUN: FileCheck -input-file=%t.cpp %s namespace i { } // CHECK: } // namespace i class A { A(int i); }; // Not fixing this, because the check is in google-. // CHECK: class A { A(int i); };
// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp // RUN: clang-tidy %t.cpp -fix -checks=^llvm-.* -- // RUN: FileCheck -input-file=%t.cpp %s namespace i { } // CHECK: } // namespace i class A { A(int i); }; // Not fixing this, because the check is in google-. // CHECK: class A { A(int i); };
Remove XFAIL now that the test is standalone.
// XFAIL: hexagon // Test this without pch. // RUN: %clang_cc1 -include %S/cxx-typeid.h -fsyntax-only -verify %s // RUN: %clang_cc1 -x c++-header -emit-pch -o %t.pch %S/cxx-typeid.h // RUN: %clang_cc1 -include-pch %t.pch -fsyntax-only -verify %s // expected-no-diagnostics void f() { (void)typeid(int); }
// Test this without pch. // RUN: %clang_cc1 -include %S/cxx-typeid.h -fsyntax-only -verify %s // RUN: %clang_cc1 -x c++-header -emit-pch -o %t.pch %S/cxx-typeid.h // RUN: %clang_cc1 -include-pch %t.pch -fsyntax-only -verify %s // expected-no-diagnostics void f() { (void)typeid(int); }
Reset all styles in sample
#include <tabulate/table.hpp> using namespace tabulate; int main() { Table employees; // Add rows employees.add_row({"Emp. ID", "First Name", "Last Name", "Department / Business Unit"}); employees.add_row({"101", "Donald", "Patrick", "Finance"}); employees.add_row({"102", "Donald", "Patrick", "Marketing and Operational Logistics Planning"}); employees.add_row({"103", "Ian", "Jacob", "Engineering"}); employees.format() .font_color(Color::cyan) .font_background_color(Color::white) .corner_color(Color::blue) .border_color(Color::yellow) .padding_top(1) .padding_bottom(1); employees.column(3).format() .width(16); employees[0][3].format() .font_color(Color::none) .border_color(Color::red) .width(20); // employees[1].format() // .width(15); // employees[1][2].format() // .width(20); // // Print the table // employees.print(std::cout); // // Set width of column 1 to 13 // employees.column(1).format() // .width(13); // Print the table employees.print(std::cout); }
#include <tabulate/table.hpp> using namespace tabulate; int main() { Table employees; // Add rows employees.add_row({"Emp. ID", "First Name", "Last Name", "Department / Business Unit"}); employees.add_row({"101", "Donald", "Patrick", "Finance"}); employees.add_row({"102", "Donald", "Patrick", "Marketing and Operational Logistics Planning"}); employees.add_row({"103", "Ian", "Jacob", "Engineering"}); // Print the table employees.print(std::cout); }
Fix functions' names according to last change
#include <iostream> #include <ctime> #include <QCPP.h> int main() { // make it more non-deterministic srand(time(NULL)); // initialize Quantum state with 5 qubits Quantum qubits(5); // turns all qubits into every state with same probabilities qubits.Hadamard(0, 1, 2, 3, 4); // or // for(int i = 0;i < qubits.size();i++) qubits.Hadamard(i); // or // qubits.Hadamard({0, 1, 2, 3, 4}); // would result the same // the possibility should be the same for(int i = 0;i < (1 << qubits.size());i++) { std::cout << "Probabilities of being " << i << " : " << qubits.getProbability(i) << std::endl; } // try to observe for(int i = 0;i < 10;i++) { std::cout << "State of qubits : " << qubits.getState() << std::endl; } return 0; }
#include <iostream> #include <ctime> #include <QCPP.h> int main() { // make it more non-deterministic srand(time(NULL)); // initialize Quantum state with 5 qubits Quantum qubits(5); // turns all qubits into every state with same probabilities qubits.hadamard(0, 1, 2, 3, 4); // or // for(int i = 0;i < qubits.size();i++) qubits.Hadamard(i); // or // qubits.hadamard({0, 1, 2, 3, 4}); // would result the same // the possibility should be the same for(int i = 0;i < (1 << qubits.size());i++) { std::cout << "Probabilities of being " << i << " : " << qubits.getProbability(i) << std::endl; } // try to observe for(int i = 0;i < 10;i++) { std::cout << "State of qubits : " << qubits.getState() << std::endl; } return 0; }
Add longer instruction test to sample
#include <iostream> #include <fstream> #include <spv_utils.h> #include <cstdint> int main() { // Read spv binary module from a file std::ifstream spv_file("../sample_spv_modules/test.frag.spv", std::ios::binary | std::ios::ate | std::ios::in); if (spv_file.is_open()) { std::streampos size = spv_file.tellg(); spv_file.seekg(0, std::ios::beg); char *data = new char[size]; spv_file.read(data, size); spv_file.close(); // Parse the module sut::OpcodeStream stream(data, size); for (auto &i : stream) { if (i.GetOpcode() == spv::Op::OpCapability) { uint32_t instruction = 0xDEADBEEF; i.InsertAfter(&instruction, 1U); i.Remove(); } } std::vector<uint32_t> filtered_stream = stream.EmitFilteredStream(); delete[] data; data = nullptr; } return 0; };
#include <iostream> #include <fstream> #include <spv_utils.h> #include <cstdint> int main() { // Read spv binary module from a file std::ifstream spv_file("../sample_spv_modules/test.frag.spv", std::ios::binary | std::ios::ate | std::ios::in); if (spv_file.is_open()) { std::streampos size = spv_file.tellg(); spv_file.seekg(0, std::ios::beg); char *data = new char[size]; spv_file.read(data, size); spv_file.close(); // Parse the module sut::OpcodeStream stream(data, size); for (auto &i : stream) { if (i.GetOpcode() == spv::Op::OpCapability) { uint32_t instruction = 0xDEADBEEF; std::vector<uint32_t> longer_instruction = { 0xFFFFEEEE, 0xFFFFDDDD, 0xFFFFFFFF, 0xDEADBEEF }; uint32_t instruction2 = 0xDEADBEEF; i.InsertBefore(longer_instruction.data(), longer_instruction.size()); i.InsertAfter(&instruction, 1U); i.Remove(); } } std::vector<uint32_t> filtered_stream = stream.EmitFilteredStream(); delete[] data; data = nullptr; } return 0; };
Add note about _printf_float and _scanf_float
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdio.h> #include "Arduino.h" asm(".global _printf_float"); asm(".global _scanf_float"); extern "C" { size_t _write(int handle, const unsigned char *buf, size_t bufSize) { /* Check for the command to flush all handles */ if (handle == -1) { return 0; } /* Check for stdout and stderr (only necessary if FILE descriptors are enabled.) */ if (handle != 1 && handle != 2) { return -1; } size_t nChars = 0; for (; bufSize > 0; --bufSize, ++buf, ++nChars) { Serial.write(*buf); } return nChars; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdio.h> #include "Arduino.h" // these are needed by the serializer, so force link asm(".global _printf_float"); asm(".global _scanf_float"); extern "C" { size_t _write(int handle, const unsigned char *buf, size_t bufSize) { /* Check for the command to flush all handles */ if (handle == -1) { return 0; } /* Check for stdout and stderr (only necessary if FILE descriptors are enabled.) */ if (handle != 1 && handle != 2) { return -1; } size_t nChars = 0; for (; bufSize > 0; --bufSize, ++buf, ++nChars) { Serial.write(*buf); } return nChars; } }
Use correct type for millisec
/********************************************************************* * thread-sleep: Force Node.js to sleep * * Copyright (c) 2015 Forbes Lindesay * Copyright (c) 2015 Tiancheng "Timothy" Gu * * MIT License ********************************************************************/ #include <nan.h> #ifdef _WIN32 #include <windows.h> #else #include <ctime> #endif using v8::FunctionTemplate; using Nan::GetFunction; using Nan::New; using Nan::Set; void SleepSync(const Nan::FunctionCallbackInfo<v8::Value>& info) { // expect a number as the first argument int millisec = args[0]->Uint32Value(); #ifdef _WIN32 Sleep(millisec); #else struct timespec req; req.tv_sec = millisec / 1000; req.tv_nsec = (millisec % 1000) * 1000000L; nanosleep(&req, (struct timespec *)NULL); #endif info.GetReturnValue().Set(millisec); } // Expose SleepSync() as sleep() in JS NAN_MODULE_INIT(InitAll) { Set(target, New("sleep").ToLocalChecked(), GetFunction(New<FunctionTemplate>(SleepSync)).ToLocalChecked()); } NODE_MODULE(thread_sleep, InitAll)
/********************************************************************* * thread-sleep: Force Node.js to sleep * * Copyright (c) 2015 Forbes Lindesay * Copyright (c) 2015 Tiancheng "Timothy" Gu * * MIT License ********************************************************************/ #include <nan.h> #ifdef _WIN32 #include <windows.h> #else #include <ctime> #endif using v8::FunctionTemplate; using Nan::GetFunction; using Nan::New; using Nan::Set; void SleepSync(const Nan::FunctionCallbackInfo<v8::Value>& info) { #ifdef _WIN32 // expect a number as the first argument DWORD millisec = info[0]->Uint32Value(); Sleep(millisec); #else // expect a number as the first argument uint32_t millisec = info[0]->Uint32Value(); struct timespec req; req.tv_sec = millisec / 1000; req.tv_nsec = (millisec % 1000) * 1000000L; nanosleep(&req, (struct timespec *)NULL); #endif info.GetReturnValue().Set(millisec); } // Expose SleepSync() as sleep() in JS NAN_MODULE_INIT(InitAll) { Set(target, New("sleep").ToLocalChecked(), GetFunction(New<FunctionTemplate>(SleepSync)).ToLocalChecked()); } NODE_MODULE(thread_sleep, InitAll)
Simplify testcase from r200797 some more.
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin -g -emit-llvm -o - | FileCheck %s // This test is for a crash when emitting debug info for not-yet-completed types. // Test that we don't actually emit a forward decl for the offending class: // CHECK: [ DW_TAG_class_type ] [Derived<const __CFString, Foo>] {{.*}} [def] // rdar://problem/15931354 typedef const struct __CFString * CFStringRef; template <class R> class Returner {}; typedef const __CFString String; template <class A, class B> class Derived; template <class A, class B> class Base { static Derived<A, B>* create(); }; template <class A, class B> class Derived : public Base<A, B> { public: static void foo(); }; class Foo { Foo(); static Returner<Base<String,Foo> > all(); }; Foo::Foo(){} Returner<Base<String,Foo> > Foo::all() { Derived<String,Foo>::foo(); return Foo::all(); }
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin -g -emit-llvm -o - | FileCheck %s // This test is for a crash when emitting debug info for not-yet-completed types. // Test that we don't actually emit a forward decl for the offending class: // CHECK: [ DW_TAG_class_type ] [Derived<Foo>] {{.*}} [def] // rdar://problem/15931354 template <class R> class Returner {}; template <class A> class Derived; template <class A> class Base { static Derived<A>* create(); }; template <class A> class Derived : public Base<A> { public: static void foo(); }; class Foo { Foo(); static Returner<Base<Foo> > all(); }; Foo::Foo(){} Returner<Base<Foo> > Foo::all() { Derived<Foo>::foo(); return Foo::all(); }
Change file locking from Posix to BSD style
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/drm/gpu/gpu_lock.h" #include <fcntl.h> #include <unistd.h> #include "base/logging.h" #include "base/posix/eintr_wrapper.h" namespace ui { namespace { const char kGpuLockFile[] = "/run/frecon"; } GpuLock::GpuLock() { fd_ = open(kGpuLockFile, O_RDWR); if (fd_ < 0) { PLOG(ERROR) << "Failed to open lock file '" << kGpuLockFile << "'"; return; } struct flock data; memset(&data, 0, sizeof(data)); data.l_type = F_WRLCK; data.l_whence = SEEK_SET; VLOG(1) << "Taking write lock on '" << kGpuLockFile << "'"; if (HANDLE_EINTR(fcntl(fd_, F_SETLKW, &data))) PLOG(ERROR) << "Error while trying to get lock on '" << kGpuLockFile << "'"; VLOG(1) << "Done trying to take write lock on '" << kGpuLockFile << "'"; } GpuLock::~GpuLock() { // Failed to open the lock file, so nothing to do here. if (fd_ < 0) return; VLOG(1) << "Releasing write lock on '" << kGpuLockFile << "'"; close(fd_); } } // namespace ui
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/drm/gpu/gpu_lock.h" #include <sys/file.h> #include <unistd.h> #include "base/logging.h" #include "base/posix/eintr_wrapper.h" namespace ui { namespace { const char kGpuLockFile[] = "/run/frecon"; } GpuLock::GpuLock() { fd_ = open(kGpuLockFile, O_RDWR); if (fd_ < 0) { PLOG(ERROR) << "Failed to open lock file '" << kGpuLockFile << "'"; return; } VLOG(1) << "Taking write lock on '" << kGpuLockFile << "'"; if (HANDLE_EINTR(flock(fd_, LOCK_EX))) PLOG(ERROR) << "Error while trying to get lock on '" << kGpuLockFile << "'"; VLOG(1) << "Done trying to take write lock on '" << kGpuLockFile << "'"; } GpuLock::~GpuLock() { // Failed to open the lock file, so nothing to do here. if (fd_ < 0) return; VLOG(1) << "Releasing write lock on '" << kGpuLockFile << "'"; close(fd_); } } // namespace ui
Add –Bezouts identity, very useful.
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector < ll > vl; vl arr(3); /* returs gcd(a,b) and find the coeficcients of bezout such that d = ax + by arr[0] gcd arr[1] x arr[2] y */ void extended(ll a, ll b){ ll y =0; ll x =1; ll xx =0; ll yy =1; while(b){ ll q = a / b; ll t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y -q*yy; y = t; } arr[0] = a; arr[1] = x; arr[2] = y; } int main(){ ll a = 20, b = 50; extended(a,b); printf("gcd(%lld, %lld) = %lld = %lld * %lld + %lld * %lld\n", a, b, arr[0], a,arr[1], b, arr[2]); return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector < ll > vl; vl arr(3); /* returs gcd(a,b) and find the coeficcients of bezout such that d = ax + by arr[0] gcd arr[1] x arr[2] y */ void extended(ll a, ll b){ ll y =0; ll x =1; ll xx =0; ll yy =1; while(b){ ll q = a / b; ll t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y -q*yy; y = t; } arr[0] = a; arr[1] = x; arr[2] = y; } /* ax + by = c mcd(a,b) = d ax0 + by0 = d c = d * c' Bezouts identity X = x0 * c' - (b/d) * k Y = y0 * c' + (a/d) * k */ int main(){ ll a = 20, b = 50; extended(a,b); printf("gcd(%lld, %lld) = %lld = %lld * %lld + %lld * %lld\n", a, b, arr[0], a,arr[1], b, arr[2]); return 0; }
Refactor C++ code to real C++ code
#include <cstdio> #include <algorithm> using namespace std; #define X(a,b) (x[a]*10+x[b]) int main() { int x[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9 }; do { int ab = X(0, 1), cd = X(2, 3), ef = X(4, 5), gh = X(6, 7); if ((ab >= 10 && cd >= 10 && ef >= 10 && gh >= 10) && (ab - cd) == ef && (ef + gh) == 111) { printf("%02d + %02d = %02d, %02d - %02d = 111\n", ab, cd, ef, ef, gh); } } while (next_permutation(x, x + 9)); return 0; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; #define X(a,b) (x[a]*10+x[b]) int mkInt(vector<int> &v) { int ret = 0; for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) { ret = ret * 10 + *it; } return ret; } int main() { int init_x[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9 }; vector<int> x = vector<int>(init_x, init_x + 9); do { vector<int> vec_ab = vector<int>(x.begin() + 0, x.begin() + 2); vector<int> vec_cd = vector<int>(x.begin() + 2, x.begin() + 4); vector<int> vec_ef = vector<int>(x.begin() + 4, x.begin() + 6); vector<int> vec_gh = vector<int>(x.begin() + 6, x.begin() + 8); int ab = mkInt(vec_ab), cd = mkInt(vec_cd), ef = mkInt(vec_ef), gh = mkInt(vec_gh); if ((ab >= 10 && cd >= 10 && ef >= 10 && gh >= 10) && (ab - cd) == ef && (ef + gh) == 111) { cout << ab << " + " << cd << " = " << ef << ", " << ef << " - " << gh << " = 111" << endl; } } while (next_permutation(x.begin(), x.end())); return 0; }
Use char[] instead of std::string
#include <iostream> using namespace std; const int MAX = 100; struct Person { string firstName; string lastName; void input() { cout << "Enter person's first and last names separated by a space: "; cin >> firstName >> lastName; } void print() { cout << firstName << ' ' << lastName << '\n'; } }; struct Client { Person person; double account; void input() { person.input(); cout << "Enter account: "; cin >> account; } void print() { person.print(); cout << "Account: " << account << '\n'; }; }; void inputClients(Client clients[], int n) { for (int i = 0; i < n; ++i) { clients[i].input(); } } void printClients(Client clients[], int n) { for (int i = 0; i < n; ++i) { clients[i].print(); } } double sumAccounts(Client clients[], int n) { double sum = 0; for (int i = 0; i < n; ++i) { sum += clients[i].account; } return sum; } int main() { Client clients[MAX]; int clientsCount = 3; inputClients(clients, clientsCount); printClients(clients, clientsCount); cout << sumAccounts(clients, clientsCount) << '\n'; return 0; }
#include <iostream> using namespace std; struct Person { char firstName[32]; char lastName[32]; void input() { cout << "Enter person's first and last names separated by a space: "; cin >> firstName >> lastName; } void print() { cout << firstName << ' ' << lastName << '\n'; } }; struct Client { Person person; double account; void input() { person.input(); cout << "Enter account: "; cin >> account; } void print() { person.print(); cout << "Account: " << account << '\n'; }; }; void inputClients(Client clients[], int n) { for (int i = 0; i < n; ++i) { clients[i].input(); } } void printClients(Client clients[], int n) { for (int i = 0; i < n; ++i) { clients[i].print(); } } double sumAccounts(Client clients[], int n) { double sum = 0; for (int i = 0; i < n; ++i) { sum += clients[i].account; } return sum; } int main() { Client clients[100]; int clientsCount = 3; inputClients(clients, clientsCount); printClients(clients, clientsCount); cout << sumAccounts(clients, clientsCount) << '\n'; return 0; }
Fix build break on mac. TBR=ajwong
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/event_executor_mac.h" namespace remoting { EventExecutorMac::EventExecutorMac(Capturer* capturer) : EventExecutor(capturer) { } EventExecutorMac::~EventExecutorMac() { } void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) { delete message; } } // namespace remoting
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/event_executor_mac.h" #include "remoting/protocol/messages_decoder.h" namespace remoting { EventExecutorMac::EventExecutorMac(Capturer* capturer) : EventExecutor(capturer) { } EventExecutorMac::~EventExecutorMac() { } void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) { delete message; } } // namespace remoting
Change NOTREACHED for a LOG(WARNING) when we can't delete the cache. This should help the unit tests.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/cache_util.h" #include "base/file_util.h" #include "base/logging.h" #include "base/string_util.h" namespace disk_cache { bool MoveCache(const FilePath& from_path, const FilePath& to_path) { // Just use the version from base. return file_util::Move(from_path, to_path); } void DeleteCache(const FilePath& path, bool remove_folder) { file_util::FileEnumerator iter(path, /* recursive */ false, file_util::FileEnumerator::FILES); for (FilePath file = iter.Next(); !file.value().empty(); file = iter.Next()) { if (!file_util::Delete(file, /* recursive */ false)) NOTREACHED(); } if (remove_folder) { if (!file_util::Delete(path, /* recursive */ false)) NOTREACHED(); } } bool DeleteCacheFile(const FilePath& name) { return file_util::Delete(name, false); } } // namespace disk_cache
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/cache_util.h" #include "base/file_util.h" #include "base/logging.h" #include "base/string_util.h" namespace disk_cache { bool MoveCache(const FilePath& from_path, const FilePath& to_path) { // Just use the version from base. return file_util::Move(from_path, to_path); } void DeleteCache(const FilePath& path, bool remove_folder) { file_util::FileEnumerator iter(path, /* recursive */ false, file_util::FileEnumerator::FILES); for (FilePath file = iter.Next(); !file.value().empty(); file = iter.Next()) { if (!file_util::Delete(file, /* recursive */ false)) { LOG(WARNING) << "Unable to delete cache."; return; } } if (remove_folder) { if (!file_util::Delete(path, /* recursive */ false)) { LOG(WARNING) << "Unable to delete cache folder."; return; } } } bool DeleteCacheFile(const FilePath& name) { return file_util::Delete(name, false); } } // namespace disk_cache
Allow to change path to translations
#include <QApplication> #include <QSettings> #include <QLocale> #include <QTranslator> #include <QLibraryInfo> #include "trayicon.h" int main(int argc, char **argv) { QApplication app(argc, argv); QApplication::setOrganizationName("Restnotifier"); app.setQuitOnLastWindowClosed(false); // Set language QSettings settings; QString lang; QTranslator translator, qtTranslator; if (settings.contains("lang")) lang = settings.value("lang").toString(); else lang = QLocale::languageToString(QLocale::system().language()); if (lang == "ru") { QLocale::setDefault(QLocale("ru")); // install qt translator #if defined Q_WS_X11 const QString loc = QLibraryInfo::location(QLibraryInfo::TranslationsPath); #elif defined Q_WS_WIN const QString loc(); #endif qtTranslator.load("qt_ru", loc); app.installTranslator(&qtTranslator); // install app translator translator.load("restnotifier_ru"); app.installTranslator(&translator); } TrayIcon *trayIcon = new TrayIcon(); trayIcon->show(); QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit())); int code = app.exec(); delete trayIcon; return code; }
#include <QApplication> #include <QSettings> #include <QLocale> #include <QTranslator> #include <QLibraryInfo> #include "trayicon.h" int main(int argc, char **argv) { QApplication app(argc, argv); QApplication::setOrganizationName("Restnotifier"); app.setQuitOnLastWindowClosed(false); // Set language QSettings settings; QString lang; QTranslator translator, qtTranslator; if (settings.contains("lang")) lang = settings.value("lang").toString(); else lang = QLocale::languageToString(QLocale::system().language()); if (lang == "ru") { QLocale::setDefault(QLocale("ru")); // install qt translator #if defined Q_WS_X11 const QString loc = QLibraryInfo::location(QLibraryInfo::TranslationsPath); #elif defined Q_WS_WIN const QString loc(); #endif qtTranslator.load("qt_ru", loc); app.installTranslator(&qtTranslator); // install app translator QString translationsPath = settings.value("tr_path", QString()).toString(); translator.load("restnotifier_ru", translationsPath); app.installTranslator(&translator); } TrayIcon *trayIcon = new TrayIcon(); trayIcon->show(); QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit())); int code = app.exec(); delete trayIcon; return code; }
Fix assert accessing pipeline from initBatchTracker
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrDrawBatch.h" GrDrawBatch::GrDrawBatch(uint32_t classID) : INHERITED(classID), fPipelineInstalled(false) { } GrDrawBatch::~GrDrawBatch() { if (fPipelineInstalled) { this->pipeline()->~GrPipeline(); } } void GrDrawBatch::getPipelineOptimizations(GrPipelineOptimizations* opt) const { GrInitInvariantOutput color; GrInitInvariantOutput coverage; this->computePipelineOptimizations(&color, &coverage, &opt->fOverrides); opt->fColorPOI.initUsingInvariantOutput(color); opt->fCoveragePOI.initUsingInvariantOutput(coverage); } bool GrDrawBatch::installPipeline(const GrPipeline::CreateArgs& args) { GrXPOverridesForBatch overrides; void* location = fPipelineStorage.get(); if (!GrPipeline::CreateAt(location, args, &overrides)) { return false; } this->initBatchTracker(overrides); fPipelineInstalled = true; return true; }
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrDrawBatch.h" GrDrawBatch::GrDrawBatch(uint32_t classID) : INHERITED(classID), fPipelineInstalled(false) { } GrDrawBatch::~GrDrawBatch() { if (fPipelineInstalled) { this->pipeline()->~GrPipeline(); } } void GrDrawBatch::getPipelineOptimizations(GrPipelineOptimizations* opt) const { GrInitInvariantOutput color; GrInitInvariantOutput coverage; this->computePipelineOptimizations(&color, &coverage, &opt->fOverrides); opt->fColorPOI.initUsingInvariantOutput(color); opt->fCoveragePOI.initUsingInvariantOutput(coverage); } bool GrDrawBatch::installPipeline(const GrPipeline::CreateArgs& args) { GrXPOverridesForBatch overrides; void* location = fPipelineStorage.get(); if (!GrPipeline::CreateAt(location, args, &overrides)) { return false; } fPipelineInstalled = true; this->initBatchTracker(overrides); return true; }
Revert "Rename Error call to GLError"
// This file is part of the GLERI project // // Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net> // This file is free software, distributed under the MIT License. #include "rglrp.h" #define N(n,s) #n "\0" #s "\0" /*static*/ const char PRGLR::_cmdNames[] = "\0" // Dirty trick: object name is 4 bytes, but must be zero terminated N(GLError,s) N(Restate,(nnqqyyyy)) N(Expose,) N(Event,(unnuu)) ; #undef N /*static*/ inline const char* PRGLR::LookupCmdName (ECmd cmd, size_type& sz) noexcept { return (CCmdBuf::LookupCmdName((unsigned)cmd,sz,_cmdNames+1,sizeof(_cmdNames)-2)); } /*static*/ PRGLR::ECmd PRGLR::LookupCmd (const char* name, size_type bleft) noexcept { return (ECmd(CCmdBuf::LookupCmd(name+1,bleft,_cmdNames+1,sizeof(_cmdNames)-2))); } bstro PRGLR::CreateCmd (ECmd cmd, size_type sz) noexcept { size_type msz; const char* m = LookupCmdName(cmd, msz); return (CCmdBuf::CreateCmd (RGLRObject, m-1, msz+1, sz)); }
// This file is part of the GLERI project // // Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net> // This file is free software, distributed under the MIT License. #include "rglrp.h" #define N(n,s) #n "\0" #s "\0" /*static*/ const char PRGLR::_cmdNames[] = N(Error,s) N(Restate,(nnqqyyyy)) N(Expose,) N(Event,(unnuu)) ; #undef N /*static*/ inline const char* PRGLR::LookupCmdName (ECmd cmd, size_type& sz) noexcept { return (CCmdBuf::LookupCmdName((unsigned)cmd,sz,_cmdNames+1,sizeof(_cmdNames)-2)); } /*static*/ PRGLR::ECmd PRGLR::LookupCmd (const char* name, size_type bleft) noexcept { return (ECmd(CCmdBuf::LookupCmd(name+1,bleft,_cmdNames+1,sizeof(_cmdNames)-2))); } bstro PRGLR::CreateCmd (ECmd cmd, size_type sz) noexcept { size_type msz; const char* m = LookupCmdName(cmd, msz); return (CCmdBuf::CreateCmd (RGLRObject, m-1, msz+1, sz)); }
Fix includes for AVAR typedef.
#include <stan/math/rev/scal.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/scal/util.hpp> #include <limits> TEST(MathFunctions, is_any_nan_variadic_rev) { using stan::math::is_any_nan; double dbl_inf = std::numeric_limits<double>::infinity(); double dbl_nan = std::numeric_limits<double>::quiet_NaN(); AVAR var_nan(dbl_nan); AVAR var_inf(dbl_inf); AVAR a = 7.0; AVAR b = 2.0; EXPECT_TRUE(is_any_nan(var_nan, b, 6, 5.0)); EXPECT_TRUE(is_any_nan(var_nan, var_inf, 6, 5.0)); EXPECT_TRUE(is_any_nan(dbl_nan, a, b, 6, 5.0)); EXPECT_FALSE(is_any_nan(dbl_inf, b, 6, var_inf)); EXPECT_FALSE(is_any_nan(a, b, 6, 7.0)); }
#include <stan/math/rev/scal.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/scal/util.hpp> #include <test/unit/math/rev/scal/fun/util.hpp> #include <limits> TEST(MathFunctions, is_any_nan_variadic_rev) { using stan::math::is_any_nan; double dbl_inf = std::numeric_limits<double>::infinity(); double dbl_nan = std::numeric_limits<double>::quiet_NaN(); AVAR var_nan(dbl_nan); AVAR var_inf(dbl_inf); AVAR a = 7.0; AVAR b = 2.0; EXPECT_TRUE(is_any_nan(var_nan, b, 6, 5.0)); EXPECT_TRUE(is_any_nan(var_nan, var_inf, 6, 5.0)); EXPECT_TRUE(is_any_nan(dbl_nan, a, b, 6, 5.0)); EXPECT_FALSE(is_any_nan(dbl_inf, b, 6, var_inf)); EXPECT_FALSE(is_any_nan(a, b, 6, 7.0)); }
Check IR in this test.
// REQUIRES: x86-registered-target,x86-64-registered-target // RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -S %s -o %t-64.s // RUN: FileCheck -check-prefix CHECK-LP64 --input-file=%t-64.s %s // RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -S %s -o %t-32.s // RUN: FileCheck -check-prefix CHECK-LP32 --input-file=%t-32.s %s extern "C" int printf(...); static int count; static float fcount; class xpto { public: xpto() : i(count++), f(fcount++) { printf("xpto::xpto()\n"); } int i; float f; ~xpto() { printf("xpto::~xpto()\n"); } }; int main() { xpto array[2][3][4]; for (int h = 0; h < 2; h++) for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) printf("array[%d][%d][%d] = {%d, %f}\n", h, i, j, array[h][i][j].i, array[h][i][j].f); } // CHECK-LP64: callq __ZN4xptoC1Ev // CHECK-LP32: calll L__ZN4xptoC1Ev
// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm %s -o - | \ // RUN: FileCheck %s // RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -emit-llvm %s -o - | \ // RUN: FileCheck %s extern "C" int printf(...); static int count; static float fcount; class xpto { public: xpto() : i(count++), f(fcount++) { printf("xpto::xpto()\n"); } int i; float f; ~xpto() { printf("xpto::~xpto()\n"); } }; int main() { xpto array[2][3][4]; for (int h = 0; h < 2; h++) for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) printf("array[%d][%d][%d] = {%d, %f}\n", h, i, j, array[h][i][j].i, array[h][i][j].f); } // CHECK: call void @_ZN4xptoC1Ev
Test amended to ensure that potential naming collisions do not necessarily affect execution
#include "stdafx.h" #include "MultipleSenderTest.h" #include "EventSender.h" class MultiEventA: public virtual EventReceiver { public: virtual void EventA(void) = 0; }; class MultiEventB: public virtual EventReceiver { public: virtual void EventB(void) = 0; }; class MultiSender: public EventSender<MultiEventA, MultiEventB> { }; MultipleSenderTest::MultipleSenderTest(void) {} TEST_F(MultipleSenderTest, VerifyMultiSendA) { m_sender->Fire(&MultiEventA::EventA)(); } TEST_F(MultipleSenderTest, VerifyMultiSendB) { m_sender->Fire(&MultiEventB::EventB)(); }
#include "stdafx.h" #include "MultipleSenderTest.h" #include "EventSender.h" class MultiEventA: public virtual EventReceiver { public: virtual void Event(void) = 0; }; class MultiEventB: public virtual EventReceiver { public: virtual void Event(void) = 0; }; class MultiSender: public EventSender<MultiEventA, MultiEventB> { }; MultipleSenderTest::MultipleSenderTest(void) {} TEST_F(MultipleSenderTest, VerifyMultiSendA) { m_sender->Fire(&MultiEventA::Event)(); } TEST_F(MultipleSenderTest, VerifyMultiSendB) { m_sender->Fire(&MultiEventB::Event)(); }
Check that we have an unknown upper bound range for our flexible array members.
// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s // CHECK: DW_TAG_subrange_type struct StructName { int member[]; }; struct StructName SN;
// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s // CHECK: metadata !{i32 {{.*}}, i64 1, i64 0} ; [ DW_TAG_subrange_type ] struct StructName { int member[]; }; struct StructName SN;
Fix memory leak: IORequest needed 3 calls (instead of 2) to deRef to delete itself
#include "iorequest.h" #include <QtDebug> #include "event.h" #include "actions/action.h" IORequest::IORequest(Player* source, IORequest::RequestType type, int refCount) : QObject(NULL), mRefCount(refCount), m_source(source), m_type(type), m_response(NULL) { } IORequest::~IORequest() { } IORequest::RequestType IORequest::type() const { return m_type; } void IORequest::putExtra(const QString& key, const QVariant& value) { m_extras.insert(key, value); } QVariant IORequest::extra(const QString& key) const { Q_ASSERT(m_extras.contains(key)); return m_extras.value(key); } void IORequest::setResponse(void* r) { m_response = r; } void* IORequest::response() const { return m_response; } void IORequest::clearRef() { if (mRefCount-- <= 0) delete this; }
#include "iorequest.h" #include <QtDebug> #include "event.h" #include "actions/action.h" IORequest::IORequest(Player* source, IORequest::RequestType type, int refCount) : QObject(NULL), mRefCount(refCount), m_source(source), m_type(type), m_response(NULL) { } IORequest::~IORequest() { } IORequest::RequestType IORequest::type() const { return m_type; } void IORequest::putExtra(const QString& key, const QVariant& value) { m_extras.insert(key, value); } QVariant IORequest::extra(const QString& key) const { Q_ASSERT(m_extras.contains(key)); return m_extras.value(key); } void IORequest::setResponse(void* r) { m_response = r; } void* IORequest::response() const { return m_response; } void IORequest::clearRef() { if (--mRefCount <= 0) delete this; }
Fix orientation of black areas (value left uninitialized).
#include "StdAfx.h" #include "BlackArea.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { BlackArea::BlackArea( int _offset, int _size, bool _isVertical ) : offset(_offset), size(_size), isVertical(isVertical) { } BlackArea::~BlackArea(void) { } } // namespace RawSpeed
#include "StdAfx.h" #include "BlackArea.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { BlackArea::BlackArea( int _offset, int _size, bool _isVertical ) : offset(_offset), size(_size), isVertical(_isVertical) { } BlackArea::~BlackArea(void) { } } // namespace RawSpeed
Adjust AGAST perftest to be at parity (better) with FAST ones.
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::make_tuple; using std::tr1::get; CV_ENUM(AgastType, AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d, AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16) typedef std::tr1::tuple<string, AgastType> File_Type_t; typedef perf::TestBaseWithParam<File_Type_t> agast; #define AGAST_IMAGES \ "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\ "stitching/a3.png" PERF_TEST_P(agast, detect, testing::Combine( testing::Values(AGAST_IMAGES), AgastType::all() )) { string filename = getDataPath(get<0>(GetParam())); int type = get<1>(GetParam()); Mat frame = imread(filename, IMREAD_GRAYSCALE); if (frame.empty()) FAIL() << "Unable to load source image " << filename; declare.in(frame); Ptr<FeatureDetector> fd = AgastFeatureDetector::create(20, true, type); ASSERT_FALSE( fd.empty() ); vector<KeyPoint> points; TEST_CYCLE() fd->detect(frame, points); SANITY_CHECK_KEYPOINTS(points); }
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::make_tuple; using std::tr1::get; CV_ENUM(AgastType, AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d, AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16) typedef std::tr1::tuple<string, AgastType> File_Type_t; typedef perf::TestBaseWithParam<File_Type_t> agast; #define AGAST_IMAGES \ "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\ "stitching/a3.png" PERF_TEST_P(agast, detect, testing::Combine( testing::Values(AGAST_IMAGES), AgastType::all() )) { string filename = getDataPath(get<0>(GetParam())); int type = get<1>(GetParam()); Mat frame = imread(filename, IMREAD_GRAYSCALE); if (frame.empty()) FAIL() << "Unable to load source image " << filename; declare.in(frame); Ptr<FeatureDetector> fd = AgastFeatureDetector::create(70, true, type); ASSERT_FALSE( fd.empty() ); vector<KeyPoint> points; TEST_CYCLE() fd->detect(frame, points); SANITY_CHECK_KEYPOINTS(points); }
Fix warning about deleting non full type
#include "filename/ast/filename-node-conditional.h" #include "filename/ast/filename-visitor.h" FilenameNodeConditional::FilenameNodeConditional(FilenameNodeCondition *condition, FilenameNode *ifTrue, FilenameNode *ifFalse) : condition(condition), ifTrue(ifTrue), ifFalse(ifFalse) {} FilenameNodeConditional::~FilenameNodeConditional() { delete condition; delete ifTrue; delete ifFalse; } void FilenameNodeConditional::accept(FilenameVisitor &v) const { v.visit(*this); }
#include "filename/ast/filename-node-conditional.h" #include "filename/ast/filename-node-condition.h" #include "filename/ast/filename-visitor.h" FilenameNodeConditional::FilenameNodeConditional(FilenameNodeCondition *condition, FilenameNode *ifTrue, FilenameNode *ifFalse) : condition(condition), ifTrue(ifTrue), ifFalse(ifFalse) {} FilenameNodeConditional::~FilenameNodeConditional() { delete condition; delete ifTrue; delete ifFalse; } void FilenameNodeConditional::accept(FilenameVisitor &v) const { v.visit(*this); }
Remove test that have not to be here
#include <cstdlib> #include "Application/Parameters/ApplicationParameters.h" #include "Application/Parameters/ApplicationParametersBuilder.h" #include "Application/Parameters/ApplicationParametersManager.h" #include "Application/Parameters/ApplicationParametersReader.h" #include "FileSystem/Entities/Executable.h" #include "FileSystem/Factories/EntityFactory.h" #include "FileSystem/Entities/Exceptions/InvalidExecutablePathException.h" #include <memory> #include <iostream> using namespace clt::filesystem; using namespace clt::filesystem::factories; using namespace clt::filesystem::entities; using namespace clt::filesystem::entities::exceptions; using namespace application::parameters; int main(int argc, char* argv[]) { if (argc < 2) { // TODO: real arguments management printf("not enough argument, need the path of your executable"); return EXIT_FAILURE; } ApplicationParametersManager parametersManager(std::make_unique<ApplicationParametersBuilder>(), std::make_unique<ApplicationParametersReader>()); parametersManager.start(argc, argv); ApplicationParameters parameters = parametersManager.getParameters(); EntityFactory entityFactory; try { Executable executable = entityFactory.createExecutable(parameters.getExecutablePath()); executable.execute(); } catch (InvalidExecutablePathException exception) { std::cout << "Invalid executable path : " << std::endl << "\t - " << exception.getDescription() << std::endl; } return EXIT_SUCCESS; }
#include <cstdlib> #include "Application/Parameters/ApplicationParameters.h" #include "Application/Parameters/ApplicationParametersBuilder.h" #include "Application/Parameters/ApplicationParametersManager.h" #include "Application/Parameters/ApplicationParametersReader.h" #include "FileSystem/Entities/Executable.h" #include "FileSystem/Factories/EntityFactory.h" #include "FileSystem/Entities/Exceptions/InvalidExecutablePathException.h" #include <memory> #include <iostream> using namespace clt::filesystem; using namespace clt::filesystem::factories; using namespace clt::filesystem::entities; using namespace clt::filesystem::entities::exceptions; using namespace application::parameters; int main(int argc, char* argv[]) { ApplicationParametersManager parametersManager(std::make_unique<ApplicationParametersBuilder>(), std::make_unique<ApplicationParametersReader>()); parametersManager.start(argc, argv); ApplicationParameters parameters = parametersManager.getParameters(); EntityFactory entityFactory; try { Executable executable = entityFactory.createExecutable(parameters.getExecutablePath()); executable.execute(); } catch (InvalidExecutablePathException exception) { std::cout << "Invalid executable path : " << std::endl << "\t - " << exception.getDescription() << std::endl; } return EXIT_SUCCESS; }
Fix case of cauchy.h header in test to allow to compile on Linux.
#include <stan/prob/distributions/univariate/continuous/Cauchy.hpp> #include <gtest/gtest.h> TEST(stanProbDistributionsUnivariateContinuousCauchy,headerParses) { EXPECT_TRUE(true); }
#include <stan/prob/distributions/univariate/continuous/cauchy.hpp> #include <gtest/gtest.h> TEST(stanProbDistributionsUnivariateContinuousCauchy,headerParses) { EXPECT_TRUE(true); }
Fix link from "use RAII" to rule of five
// Use RAII types #include <map> #include <memory> #include <string> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::map<std::string, int> map = {{"Foo", 10}, {"Bar", 20}}; std::string str = "Some text"; std::unique_ptr<int> ptr1 = std::make_unique<int>(8); std::shared_ptr<int> ptr2 = std::make_shared<int>(16); } // Avoid manual memory management to improve safety and reduce bugs // and memory leaks. // // Every object created on [10-14] will internally manage some // dynamically allocated memory (allocated with the `new` keyword). // They are all, however, implemented such that they deallocate that // memory when they are destroyed. This practice is known as RAII. // // The user of these classes does not need to perform manual memory // management, reducing the risk of memory leaks and other bugs. In // fact, the use of `new` and `delete` can be avoided entirely by // using these RAII types. // // Likewise, it is good practice to ensure your own classes also // implement the RAII idiom with the // [rule of three](/common-tasks/rule-of-three.html) // or [rule of zero](/common-tasks/rule-of-zero.html).
// Use RAII types #include <map> #include <memory> #include <string> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::map<std::string, int> map = {{"Foo", 10}, {"Bar", 20}}; std::string str = "Some text"; std::unique_ptr<int> ptr1 = std::make_unique<int>(8); std::shared_ptr<int> ptr2 = std::make_shared<int>(16); } // Avoid manual memory management to improve safety and reduce bugs // and memory leaks. // // Every object created on [10-14] will internally manage some // dynamically allocated memory (allocated with the `new` keyword). // They are all, however, implemented such that they deallocate that // memory when they are destroyed. This practice is known as RAII. // // The user of these classes does not need to perform manual memory // management, reducing the risk of memory leaks and other bugs. In // fact, the use of `new` and `delete` can be avoided entirely by // using these RAII types. // // Likewise, it is good practice to ensure your own classes also // implement the RAII idiom with the // [rule of five](/common-tasks/rule-of-five.html) // or [rule of zero](/common-tasks/rule-of-zero.html).
Add one test (example) to use a lamba.
#include "brents_fun.h" using namespace std; double fun1(double x) { return -2.0*x+1; } double fun2(double x) { return x*x-2.0*x-3; } void brents_fun_test() { double eta=1e-8; double x; x=brents_fun(fun1,-1.0,5.0,eta); if(abs(x-0.5)<eta) cout<<"brents_fun passed quadratic order test!\n"; else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n"; x=brents_fun(fun2,1.0,5.0,eta); if(abs(x-3.0)<eta) cout<<"brents_fun passed quadratic order test!\n"; else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n"; }
#include "brents_fun.h" using namespace std; double fun1(double x) { return -2.0*x+1; } double fun2(double x) { return x*x-2.0*x-3; } double fun3(double x,double y) { return x*x-2.0*x-1.0-y; } void brents_fun_test() { double eta=1e-8; double x; x=brents_fun(fun1,-1.0,5.0,eta); if(abs(x-0.5)<eta) cout<<"brents_fun passed quadratic order test!\n"; else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n"; x=brents_fun(fun2,1.0,5.0,eta); if(abs(x-3.0)<eta) cout<<"brents_fun passed quadratic order test!\n"; else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n"; x=brents_fun([](double x) { return fun3(x, 7.0); },0.0,5.0,eta); if(abs(x-4.0)<eta) cout<<"brents_fun passed partially function quadratic order test!\n"; else cout<<"Warning!!!!brents_fun failed partially function quadratic order test!!\n"; }
Fix rounding in chunk adding
#include "AddChunksStage.h" #include <globjects/globjects.h> #include <gloperate/painter/AbstractCameraCapability.h> using namespace gl; using namespace glm; using namespace globjects; AddChunksStage::AddChunksStage() : AbstractStage("AddChunks") { addInput("camera", camera); addOutput("chunksToAdd", chunksToAdd); } void AddChunksStage::initialize() { } void AddChunksStage::process() { std::queue<vec3> empty; std::swap(chunksToAdd.data(), empty); int directionMax = 8; int upMax = 3; int rightMax = 4; auto startPosition = camera.data()->eye(); auto direction = normalize(camera.data()->center() - camera.data()->eye()); auto up = normalize(camera.data()->up()); auto right = normalize(cross(up, direction)); for (int z = 0; z < directionMax; ++z) { for (int y = -upMax; y < upMax; ++y) { for (int x = -rightMax; x < rightMax; ++x) { auto newOffset = ivec3(startPosition + right * float(x) + up * float(y) + direction * float(z)); chunksToAdd->push(vec3(newOffset)); } } } invalidateOutputs(); }
#include "AddChunksStage.h" #include <globjects/globjects.h> #include <gloperate/painter/AbstractCameraCapability.h> using namespace gl; using namespace glm; using namespace globjects; AddChunksStage::AddChunksStage() : AbstractStage("AddChunks") { addInput("camera", camera); addOutput("chunksToAdd", chunksToAdd); } void AddChunksStage::initialize() { } void AddChunksStage::process() { std::queue<vec3> empty; std::swap(chunksToAdd.data(), empty); int directionMax = 8; int upMax = 3; int rightMax = 4; auto startPosition = camera.data()->eye(); auto direction = normalize(camera.data()->center() - camera.data()->eye()); auto up = normalize(camera.data()->up()); auto right = normalize(cross(up, direction)); for (int z = 0; z < directionMax; ++z) { for (int y = -upMax; y < upMax; ++y) { for (int x = -rightMax; x < rightMax; ++x) { auto pos = startPosition + right * float(x) + up * float(y) + direction * float(z); auto newOffset = vec3(floor(pos.x), floor(pos.y), floor(pos.z)); chunksToAdd->push(newOffset); } } } invalidateOutputs(); }
Fix warning for unreferenced parameter
#include <QtCore/QCoreApplication> #include <QNetworkAccessManager> #include <QTimer> #include <QJSonDocument> #include <QJsonObject> #include <QDebug> #include "../QPubNub.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QNetworkAccessManager networkAccessManager; QPubNub pubnub(&networkAccessManager); pubnub.connect(&pubnub, &QPubNub::trace, [](QString message) { qDebug() << "Trace:" << qPrintable(message); }); pubnub.time(); pubnub.setPublishKey("demo"); pubnub.setSubscribeKey("demo"); pubnub.connect(&pubnub, &QPubNub::error, [](QString message, int code) { qDebug() << "error:" << qPrintable(message); }); pubnub.setCipherKey("enigma"); pubnub.publish("qwertz", QJsonValue(QString("test"))); pubnub.subscribe("qwertz"); pubnub.connect(&pubnub, &QPubNub::message, [](QJsonValue value, QString timeToken, QString channel) { qDebug().nospace() << "[" << qPrintable(channel) << "]:" << value; }); return a.exec(); }
#include <QtCore/QCoreApplication> #include <QNetworkAccessManager> #include <QTimer> #include <QJSonDocument> #include <QJsonObject> #include <QDebug> #include "../QPubNub.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QNetworkAccessManager networkAccessManager; QPubNub pubnub(&networkAccessManager); pubnub.connect(&pubnub, &QPubNub::trace, [](QString message) { qDebug() << "Trace:" << qPrintable(message); }); pubnub.time(); pubnub.setPublishKey("demo"); pubnub.setSubscribeKey("demo"); pubnub.connect(&pubnub, &QPubNub::error, [](QString message, int /* code */) { qDebug() << "error:" << qPrintable(message); }); pubnub.setCipherKey("enigma"); pubnub.publish("qwertz", QJsonValue(QString("test"))); pubnub.subscribe("qwertz"); pubnub.connect(&pubnub, &QPubNub::message, [](QJsonValue value, QString timeToken, QString channel) { qDebug().nospace() << "[" << qPrintable(channel) << "]:" << value; }); return a.exec(); }
Fix a typo in a test.
// Test for the leak_check_at_exit flag. // RUN: LSAN_BASE="use_stacks=0:use_registers=0" // RUN: %clangxx_lsan %s -o %t // RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do // RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-do // RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do // RUN: LSAN_OPTIONS=%LSAN_BASE:"leak_check_at_exit=0" %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-dont #include <stdio.h> #include <stdlib.h> #include <sanitizer/lsan_interface.h> int main(int argc, char *argv[]) { fprintf(stderr, "Test alloc: %p.\n", malloc(1337)); if (argc > 1) __lsan_do_leak_check(); return 0; } // CHECK-do: SUMMARY: {{(Leak|Address)}}Sanitizer: // CHECK-dont-NOT: SUMMARY: {{(Leak|Address)}}Sanitizer:
// Test for the leak_check_at_exit flag. // RUN: LSAN_BASE="use_stacks=0:use_registers=0" // RUN: %clangxx_lsan %s -o %t // RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do // RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-do // RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do // RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-dont #include <stdio.h> #include <stdlib.h> #include <sanitizer/lsan_interface.h> int main(int argc, char *argv[]) { fprintf(stderr, "Test alloc: %p.\n", malloc(1337)); if (argc > 1) __lsan_do_leak_check(); return 0; } // CHECK-do: SUMMARY: {{(Leak|Address)}}Sanitizer: // CHECK-dont-NOT: SUMMARY: {{(Leak|Address)}}Sanitizer:
Change two-level detection result output to 255 (was 1).
#include "TwoLevelDetection.h" #include <opencv2/imgproc/imgproc.hpp> void TwoLevelDetection(const cv::Mat& input, cv::Mat& output, double detectionLevel, double measurementLevel, TwoLevelDetectionTemp& temp) { if (measurementLevel > detectionLevel) { throw std::runtime_error("TwoLevelDetection: it is required that measurementLevel <= detectionLevel"); } cv::threshold(input, output, measurementLevel, 1, cv::THRESH_BINARY); temp.contours.clear(); cv::findContours(output, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); temp.mask.create(input.size(), CV_8UC1); output.setTo(0); for (size_t i = 0, end = temp.contours.size(); i < end; ++i) { temp.mask.setTo(0); cv::drawContours(temp.mask, temp.contours, static_cast<int>(i), 255, -1); double minVal, maxVal; cv::minMaxIdx(input, &minVal, &maxVal, NULL, NULL, temp.mask); if (maxVal >= detectionLevel) { output.setTo(1, temp.mask); } } }
#include "TwoLevelDetection.h" #include <opencv2/imgproc/imgproc.hpp> void TwoLevelDetection(const cv::Mat& input, cv::Mat& output, double detectionLevel, double measurementLevel, TwoLevelDetectionTemp& temp) { if (measurementLevel > detectionLevel) { throw std::runtime_error("TwoLevelDetection: it is required that measurementLevel <= detectionLevel"); } cv::threshold(input, output, measurementLevel, 1, cv::THRESH_BINARY); temp.contours.clear(); cv::findContours(output, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); temp.mask.create(input.size(), CV_8UC1); output.setTo(0); for (size_t i = 0, end = temp.contours.size(); i < end; ++i) { temp.mask.setTo(0); cv::drawContours(temp.mask, temp.contours, static_cast<int>(i), 255, -1); double minVal, maxVal; cv::minMaxIdx(input, &minVal, &maxVal, NULL, NULL, temp.mask); if (maxVal >= detectionLevel) { output.setTo(std::numeric_limits<unsigned char>::max(), temp.mask); } } }
Fix an issue with possible minimizing of CropEditor by a WM
#include "cropview.hpp" CropView::CropView(QGraphicsScene *scene) : QGraphicsView(scene) { setFrameShape(QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing); setCursor(QCursor(Qt::CrossCursor)); } void CropView::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) { close(); e->accept(); return; } QGraphicsView::keyPressEvent(e); }
#include "cropview.hpp" CropView::CropView(QGraphicsScene *scene) : QGraphicsView(scene) { setFrameShape(QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing); setCursor(QCursor(Qt::CrossCursor)); } void CropView::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) { close(); e->accept(); return; } QGraphicsView::keyPressEvent(e); }
Use unique_ptr for pwalletMain (CWallet)
// Copyright (c) 2016-2018 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 <wallet/test/wallet_test_fixture.h> #include <rpc/server.h> #include <wallet/db.h> #include <wallet/wallet.h> CWallet *pwalletMain; WalletTestingSetup::WalletTestingSetup(const std::string& chainName): TestingSetup(chainName) { bitdb.MakeMock(); bool fFirstRun; std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat")); pwalletMain = new CWallet(std::move(dbw)); pwalletMain->LoadWallet(fFirstRun); RegisterValidationInterface(pwalletMain); RegisterWalletRPCCommands(tableRPC); } WalletTestingSetup::~WalletTestingSetup() { UnregisterValidationInterface(pwalletMain); delete pwalletMain; pwalletMain = nullptr; bitdb.Flush(true); bitdb.Reset(); }
// Copyright (c) 2016-2018 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 <wallet/test/wallet_test_fixture.h> #include <rpc/server.h> #include <wallet/db.h> #include <wallet/wallet.h> std::unique_ptr<CWallet> pwalletMain; WalletTestingSetup::WalletTestingSetup(const std::string& chainName): TestingSetup(chainName) { bitdb.MakeMock(); bool fFirstRun; std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat")); pwalletMain = std::unique_ptr<CWallet>(new CWallet(std::move(dbw))); pwalletMain->LoadWallet(fFirstRun); RegisterValidationInterface(pwalletMain.get()); RegisterWalletRPCCommands(tableRPC); } WalletTestingSetup::~WalletTestingSetup() { UnregisterValidationInterface(pwalletMain.get()); pwalletMain.reset(); bitdb.Flush(true); bitdb.Reset(); }
Fix a syscall number for 64-bit arm
#define SYS_CLOCK_GETTIME 263 #include "linux_clock.cpp"
#ifdef BITS_64 #define SYS_CLOCK_GETTIME 113 #endif #ifdef BITS_32 #define SYS_CLOCK_GETTIME 263 #endif #include "linux_clock.cpp"
Use a pool of 8 threads.
#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; }
#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::thread has implementation-dependent behavior; some implementations // may refuse to create an arbitrary number. So let's create a smallish // number (8) and have each one do enough work that contention is likely // to be encountered. constexpr int total_iters = 1024; constexpr int num_threads = 8; std::vector<std::thread> threads; for (int i = 0; i < num_threads; i++) { threads.emplace_back([]{ for (int i = 0; i < (total_iters / num_threads); i++) { Func f; Var x; f(x) = x; f.realize(100); } }); } for (auto &t : threads) { t.join(); } printf("Success!\n"); return 0; }
Fix build for Mac OS X
#include "application.hpp" #include <SDL2/SDL.h> #include <stdexcept> Application *Application::instance_ = nullptr; Application::Application(int &argc, char **argv) { if (instance_ != nullptr) throw std::runtime_error("The program can have only one instance of Application"); instance_ = this; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) throw std::runtime_error("SDL_Init Error: " + std::string(SDL_GetError())); } Application::~Application() { SDL_Quit(); instance_ = nullptr; } int Application::exec() { bool done = false; while (!done) { SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: done = true; break; } } } return 0; } Application *Application::instance() { return instance_; } void Application::addWidget(Widget *) { } void Application::removeWidget(Widget *) { }
#include "application.hpp" #include <SDL2/SDL.h> #include <stdexcept> #include <string> Application *Application::instance_ = nullptr; Application::Application(int &argc, char **argv) { if (instance_ != nullptr) throw std::runtime_error("The program can have only one instance of Application"); instance_ = this; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) throw std::runtime_error("SDL_Init Error: " + std::string(SDL_GetError())); } Application::~Application() { SDL_Quit(); instance_ = nullptr; } int Application::exec() { bool done = false; while (!done) { SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: done = true; break; } } } return 0; } Application *Application::instance() { return instance_; } void Application::addWidget(Widget *) { } void Application::removeWidget(Widget *) { }
Add tests for Lithuanian special case mapping.
#include "tests-base.hpp" #include "helpers-casemapping.hpp" #include "helpers-strings.hpp" TEST(SpecialCasing, LithuanianRemoveDotAbove) { // Remove DOT ABOVE after "i" with upper or titlecase // U+0049 U+0307 // U+0069 EXPECT_STREQ("lt-LT", setlocale(LC_ALL, "lt-LT")); EXPECT_CASEMAPPING_EQ("i\xCC\x87", "i\xCC\x87", "I", "I"); setlocale(LC_ALL, "C"); }
#include "tests-base.hpp" #include "helpers-casemapping.hpp" #include "helpers-strings.hpp" TEST(SpecialCasing, LithuanianRemoveDotAbove) { EXPECT_STREQ("lt-LT", setlocale(LC_ALL, "lt-LT")); // Remove DOT ABOVE after "i" with upper or titlecase EXPECT_CASEMAPPING_EQ("i\xCC\x87", "i\xCC\x87", "I", "I"); // COMBINING DOT ABOVE setlocale(LC_ALL, "C"); } TEST(SpecialCasing, LithuanianIntroduceExplicitDot) { EXPECT_STREQ("lt-LT", setlocale(LC_ALL, "lt-LT")); // Introduce an explicit dot above when lowercasing capital I's and J's // whenever there are more accents above. // (of the accents used in Lithuanian: grave, acute, tilde above, and ogonek) EXPECT_CASEMAPPING_EQ("I", "i\xCC\x87", "I", "I"); // LATIN CAPITAL LETTER I EXPECT_CASEMAPPING_EQ("J", "j\xCC\x87", "J", "J"); // LATIN CAPITAL LETTER J EXPECT_CASEMAPPING_EQ("\xC4\xAE", "\xC4\xAF\xCC\x87", "\xC4\xAE", "\xC4\xAE"); // LATIN CAPITAL LETTER I WITH OGONEK EXPECT_CASEMAPPING_EQ("\xC3\x8C", "i\xCC\x87\xCC\x80", "\xC3\x8C", "\xC3\x8C"); // LATIN CAPITAL LETTER I WITH GRAVE EXPECT_CASEMAPPING_EQ("\xC3\x8D", "i\xCC\x87\xCC\x81", "\xC3\x8D", "\xC3\x8D"); // LATIN CAPITAL LETTER I WITH ACUTE EXPECT_CASEMAPPING_EQ("\xC4\xA8", "i\xCC\x87\xCC\x83", "\xC4\xA8", "\xC4\xA8"); // LATIN CAPITAL LETTER I WITH TILDE setlocale(LC_ALL, "C"); }
Simplify LightingFilter in add-free case am: 0698300cc5 am: a184d5e49d
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorMatrixFilter.h" static SkScalar byte_to_scale(U8CPU byte) { if (0xFF == byte) { // want to get this exact return 1; } else { return byte * 0.00392156862745f; } } SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) { SkColorMatrix matrix; matrix.setScale(byte_to_scale(SkColorGetR(mul)), byte_to_scale(SkColorGetG(mul)), byte_to_scale(SkColorGetB(mul)), 1); matrix.postTranslate(SkIntToScalar(SkColorGetR(add)), SkIntToScalar(SkColorGetG(add)), SkIntToScalar(SkColorGetB(add)), 0); return SkColorMatrixFilter::Create(matrix); }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorMatrixFilter.h" static SkScalar byte_to_scale(U8CPU byte) { if (0xFF == byte) { // want to get this exact return 1; } else { return byte * 0.00392156862745f; } } SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) { if (0 == add) { return SkColorFilter::CreateModeFilter(mul | SK_ColorBLACK, SkXfermode::Mode::kModulate_Mode); } SkColorMatrix matrix; matrix.setScale(byte_to_scale(SkColorGetR(mul)), byte_to_scale(SkColorGetG(mul)), byte_to_scale(SkColorGetB(mul)), 1); matrix.postTranslate(SkIntToScalar(SkColorGetR(add)), SkIntToScalar(SkColorGetG(add)), SkIntToScalar(SkColorGetB(add)), 0); return SkColorMatrixFilter::Create(matrix); }
Adjust test to handle fallout from r217102.
// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -O3 -emit-llvm -gline-tables-only -S -verify -o /dev/null // REQUIRES: x86-registered-target // Test verifies optimization failures generated by the backend are handled // correctly by clang. LLVM tests verify all of the failure conditions. void test_switch(int *A, int *B, int Length) { #pragma clang loop vectorize(enable) unroll(disable) for (int i = 0; i < Length; i++) { /* expected-warning {{loop not vectorized: failed explicitly specified loop vectorization}} */ switch (A[i]) { case 0: B[i] = 1; break; case 1: B[i] = 2; break; default: B[i] = 3; } } }
// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -O3 -emit-llvm -gline-tables-only -S -verify -o /dev/null // REQUIRES: x86-registered-target // Test verifies optimization failures generated by the backend are handled // correctly by clang. LLVM tests verify all of the failure conditions. void test_switch(int *A, int *B, int Length) { #pragma clang loop vectorize(enable) unroll(disable) /* expected-warning {{loop not vectorized: failed explicitly specified loop vectorization}} */ for (int i = 0; i < Length; i++) { switch (A[i]) { case 0: B[i] = 1; break; case 1: B[i] = 2; break; default: B[i] = 3; } } }
Enable XINPUT right away maybe?
#include "WindowsAPIs.h" #include "TaskIcon.h" INT WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, INT) { hinstance = hinst; TaskIcon().MessageLoop(); return 0; }
#include "WindowsAPIs.h" #include "TaskIcon.h" INT WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, INT) { hinstance = hinst; XInputEnable(TRUE); TaskIcon().MessageLoop(); return 0; }
Fix for in-unit hooks not passing the cookie on to C.
#include "cg-operator-common.h" #include <binpac/autogen/operators/function.h> using namespace binpac; using namespace binpac::codegen; void CodeBuilder::visit(expression::operator_::function::Call* i) { auto func = ast::checkedCast<expression::Function>(i->op1()); auto args = callParameters(i->op2()); shared_ptr<hilti::Expression> cookie = nullptr; if ( in<declaration::Function>() || in<declaration::Hook>() ) cookie = hilti::builder::id::create("__cookie", i->location()); else cookie = hilti::builder::reference::createNull(i->location()); auto result = cg()->hiltiCall(func, args, cookie); setResult(result); }
#include "cg-operator-common.h" #include <binpac/autogen/operators/function.h> using namespace binpac; using namespace binpac::codegen; void CodeBuilder::visit(expression::operator_::function::Call* i) { auto func = ast::checkedCast<expression::Function>(i->op1()); auto args = callParameters(i->op2()); shared_ptr<hilti::Expression> cookie = nullptr; if ( in<declaration::Function>() || in<declaration::Hook>() || in<declaration::Type>() ) cookie = hilti::builder::id::create("__cookie", i->location()); else cookie = hilti::builder::reference::createNull(i->location()); auto result = cg()->hiltiCall(func, args, cookie); setResult(result); }