Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Apply glass to volume slider
#include "VolumeSlider.h" #include "..\Controllers\Volume\CoreAudio.h" #include "..\Error.h" #include "..\Settings.h" #include "..\Skin.h" #include "SliderKnob.h" VolumeSlider::VolumeSlider(CoreAudio &volumeCtrl) : SliderWnd(L"3RVX-VolumeSlider", L"3RVX Volume Slider"), _settings(*Settings::Instance()), _volumeCtrl(volumeCtrl) { Skin *skin = _settings.CurrentSkin(); Gdiplus::Bitmap *bg = skin->SliderBgImg("volume"); BackgroundImage(bg); _knob = skin->Knob("volume"); _vertical = _knob->Vertical(); std::list<Meter*> meters = skin->VolumeSliderMeters(); for (Meter *m : meters) { AddMeter(m); } Knob(_knob); } void VolumeSlider::SliderChanged() { _volumeCtrl.Volume(_knob->Value()); } void VolumeSlider::MeterLevels(float level) { if (Visible() && _dragging == false) { MeterWnd::MeterLevels(level); Update(); } _level = level; } void VolumeSlider::Show() { MeterWnd::MeterLevels(_level); Update(); SliderWnd::Show(); SetActiveWindow(_hWnd); SetForegroundWindow(_hWnd); } bool VolumeSlider::Visible() { return _visible; }
#include "VolumeSlider.h" #include "..\Controllers\Volume\CoreAudio.h" #include "..\Error.h" #include "..\Settings.h" #include "..\Skin.h" #include "SliderKnob.h" VolumeSlider::VolumeSlider(CoreAudio &volumeCtrl) : SliderWnd(L"3RVX-VolumeSlider", L"3RVX Volume Slider"), _settings(*Settings::Instance()), _volumeCtrl(volumeCtrl) { Skin *skin = _settings.CurrentSkin(); Gdiplus::Bitmap *bg = skin->SliderBgImg("volume"); BackgroundImage(bg); Gdiplus::Bitmap *mask = skin->SliderMask("volume"); if (mask != NULL) { CLOG(L"Applying glass to eject OSD"); GlassMask(mask); } _knob = skin->Knob("volume"); _vertical = _knob->Vertical(); std::list<Meter*> meters = skin->VolumeSliderMeters(); for (Meter *m : meters) { AddMeter(m); } Knob(_knob); } void VolumeSlider::SliderChanged() { _volumeCtrl.Volume(_knob->Value()); } void VolumeSlider::MeterLevels(float level) { if (Visible() && _dragging == false) { MeterWnd::MeterLevels(level); Update(); } _level = level; } void VolumeSlider::Show() { MeterWnd::MeterLevels(_level); Update(); SliderWnd::Show(); SetActiveWindow(_hWnd); SetForegroundWindow(_hWnd); } bool VolumeSlider::Visible() { return _visible; }
Fix the leak test (so that it keeps leaking).
#include <gtest/gtest.h> /** * A test case that leaks memory, to check that we can spot this in valgrind */ TEST(Leak, ThisTestLeaks) { EXPECT_TRUE(new int[45]); } #ifndef __NO_MAIN__ int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #endif
#include <gtest/gtest.h> /** * A test case that leaks memory, to check that we can spot this in valgrind */ TEST(Leak, ThisTestLeaks) { int* temp = new int[45]; int temp2 = *temp++; std::cout << temp2; } #ifndef __NO_MAIN__ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #endif
Fix inclusion path as suggested by @ruslo.
#include <avahi-client/client.h> #include <dns_sd.h> int main(int argc, char** argv) { }
#include <avahi-client/client.h> #include <avahi-compat-libdns_sd/dns_sd.h> int main(int argc, char** argv) { }
Use llvmgxx for C++ test.
// RUN: %llvmgcc %s -fasm-blocks -S -o - | FileCheck %s // Complicated expression as jump target // XFAIL: * // XTARGET: x86,i386,i686 void Method3() { // CHECK: Method3 // CHECK-NOT: msasm asm("foo:"); // CHECK: return } void Method4() { // CHECK: Method4 // CHECK: msasm asm { bar: } // CHECK: return }
// RUN: %llvmgxx %s -fasm-blocks -S -o - | FileCheck %s // Complicated expression as jump target // XFAIL: * // XTARGET: x86,i386,i686 void Method3() { // CHECK: Method3 // CHECK-NOT: msasm asm("foo:"); // CHECK: return } void Method4() { // CHECK: Method4 // CHECK: msasm asm { bar: } // CHECK: return }
Fix nodiscard test when modules are enabled
// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Test that _LIBCPP_NODISCARD_AFTER_CXX17 works // #define _LIBCPP_NODISCARD_AFTER_CXX17 [[nodiscard]] // UNSUPPORTED: c++98, c++03, c++11, c++14 #define _LIBCPP_DISABLE_NODISCARD_AFTER_CXX17 #include <__config> _LIBCPP_NODISCARD_AFTER_CXX17 int foo() { return 6; } int main () { foo(); // no error here! }
// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Test that _LIBCPP_NODISCARD_AFTER_CXX17 works // #define _LIBCPP_NODISCARD_AFTER_CXX17 [[nodiscard]] // UNSUPPORTED: c++98, c++03, c++11, c++14 // MODULES_DEFINES: _LIBCPP_DISABLE_NODISCARD_AFTER_CXX17 #define _LIBCPP_DISABLE_NODISCARD_AFTER_CXX17 #include <__config> _LIBCPP_NODISCARD_AFTER_CXX17 int foo() { return 6; } int main () { foo(); // no error here! }
Add start of xml parser for room
#import <iostream> class Room { private: const int width; const int height; public: Room(){} Room(int w, int h) { width = w; height = h; } void print_dimensions(); }; void Room::print_dimensions() { std::cout << width << "x" << height << std::endl; } int main() { Room a_room(25,25); a_room.print_dimensions(); return 0; }
#import <iostream> class Room { private: const int width; const int height; public: Room(){} Room(int w, int h) { width = w; height = h; } void print_dimensions(); bool loadFromXMLFile(); }; void Room::print_dimensions() { std::cout << width << "x" << height << std::endl; } bool Room::loadFromXMLFile (const char* filename) { // Create xml dom TiXmlDocument doc(filename); // Load the document if (!doc.LoadFile()) { cerr << "File " << filename << " not found" << endl; return false; } // Get root element TiXmlElement* root = doc.FirstChildElement(); if (root == NULL) { cerr << "XML Error: No root element" << endl; return false; } // Root element should be 'veld' if (root->Value() !== "VELD") { cerr << "XML Error: Root element has to be called 'veld'" << endl; return false; } // Parse the tags 'NAAM', 'LENGTE', 'BREEDTE', 'SPELER', 'OBSTAKEL' for (TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { string elemName = elem->Value(); if (elemName == "NAAM" || elemName == "LENGTE" || elemName == "BREEDTE") { // Get the text between the name, length and width tags TiXmlNode* node = elem->FirstChild(); TiXmlText* text = node->ToText(); string str = text->Value(); if (elemName == "NAAM") this->set_name(str); if (elemName == "LENGTE") this->set_length(stoi(str)); if (elemName == "BREEDTE") this->set_width(stoi(str)); } if (elemName == "OBSTAKEL") { } if (elemName == "SPELER") { } } return true; } int main() { Room a_room(25,25); a_room.print_dimensions(); return 0; }
Add one more test for optional
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <optional> // UNSUPPORTED: c++98, c++03, c++11, c++14 // UNSUPPORTED: libcpp-no-deduction-guides // template<class T> // optional(T) -> optional<T>; #include <optional> #include <cassert> struct A {}; int main() { // Test the explicit deduction guides { // optional(T) std::optional opt(5); static_assert(std::is_same_v<decltype(opt), std::optional<int>>, ""); assert(static_cast<bool>(opt)); assert(*opt == 5); } { // optional(T) std::optional opt(A{}); static_assert(std::is_same_v<decltype(opt), std::optional<A>>, ""); assert(static_cast<bool>(opt)); } // Test the implicit deduction guides }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <optional> // UNSUPPORTED: c++98, c++03, c++11, c++14 // UNSUPPORTED: libcpp-no-deduction-guides // template<class T> // optional(T) -> optional<T>; #include <optional> #include <cassert> struct A {}; int main() { // Test the explicit deduction guides { // optional(T) std::optional opt(5); static_assert(std::is_same_v<decltype(opt), std::optional<int>>, ""); assert(static_cast<bool>(opt)); assert(*opt == 5); } { // optional(T) std::optional opt(A{}); static_assert(std::is_same_v<decltype(opt), std::optional<A>>, ""); assert(static_cast<bool>(opt)); } // Test the implicit deduction guides { // optional(const optional &); std::optional<char> source('A'); std::optional opt(source); static_assert(std::is_same_v<decltype(opt), std::optional<char>>, ""); assert(static_cast<bool>(opt) == static_cast<bool>(source)); assert(*opt == *source); } }
Fix testcase for MSVC targets where the output ordering is different.
// RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck %s // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A" // CHECK-NOT: DIFlagFwdDecl // CHECK-SAME: ){{$}} class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; } // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "B" // CHECK-SAME: flags: DIFlagFwdDecl class B { public: int y; }; extern int bar(B *b); int baz(B *b) { return bar(b); } // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "C" // CHECK-SAME: flags: DIFlagFwdDecl struct C { }; C (*x)(C);
// RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck %s // RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck --check-prefix=CHECK-C %s // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A" // CHECK-NOT: DIFlagFwdDecl // CHECK-SAME: ){{$}} class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; } // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "B" // CHECK-SAME: flags: DIFlagFwdDecl class B { public: int y; }; extern int bar(B *b); int baz(B *b) { return bar(b); } // CHECK-C: !DICompositeType(tag: DW_TAG_structure_type, name: "C" // CHECK-C-SAME: flags: DIFlagFwdDecl struct C { }; C (*x)(C);
Fix the color inversion on the black score
//===-- ColorSettings.cpp - Stylistic Setup for Colors ------------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/display/GameDisplay.h" #include "uwhd/display/TimeDisplay.h" #include <graphics.h> using namespace rgb_matrix; const Color GameDisplay::Background = Color( 0, 0, 0); const Color GameDisplay::WhiteTeamFG = Color(200, 200, 200); const Color GameDisplay::BlackTeamFG = Color( 0, 0, 0); const Color GameDisplay::WhiteTeamBG = Background; const Color GameDisplay::BlackTeamBG = Color( 0, 0, 255); const Color TimeDisplay::SecondsColor = Color( 0, 255, 0); const Color TimeDisplay::MinutesColor = Color( 0, 255, 0); const Color TimeDisplay::ColonColor = Color( 0, 255, 0); const Color TimeDisplay::RingColor = Color( 0, 0, 0); const Color TimeDisplay::Background = GameDisplay::Background;
//===-- ColorSettings.cpp - Stylistic Setup for Colors ------------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/display/GameDisplay.h" #include "uwhd/display/TimeDisplay.h" #include <graphics.h> using namespace rgb_matrix; const Color GameDisplay::Background = Color( 0, 0, 0); const Color GameDisplay::WhiteTeamFG = Color(255, 255, 255); const Color GameDisplay::BlackTeamFG = Color( 0, 0, 255); const Color GameDisplay::WhiteTeamBG = Background; const Color GameDisplay::BlackTeamBG = Background; const Color TimeDisplay::SecondsColor = Color( 0, 255, 0); const Color TimeDisplay::MinutesColor = Color( 0, 255, 0); const Color TimeDisplay::ColonColor = Color( 0, 255, 0); const Color TimeDisplay::RingColor = Color( 0, 0, 0); const Color TimeDisplay::Background = GameDisplay::Background;
Add code to calculate yield for cash instruments
#include <iostream> void dummy(); int main() { dummy(); } void dummy() { std::cout<<"Welcome to the yield calculator \n"; }
#include <iostream> #include <map> using namespace std; double timeInYears(const string period); double cashDiscountValue(const string period, double rate); int main() { map<string, double> yields; // 1) Assignment using array index notation yields["1W"] = 0.445060000; yields["1M"] = 0.526890000; yields["2M"] = 0.669670000; yields["3M"] = 0.852220000; cout << "Map size: " << yields.size() << endl; for( map<string,double >::iterator ii=yields.begin(); ii!=yields.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << " ==== " << (cashDiscountValue((*ii).first, (*ii).second)) << endl; } } double cashDiscountValue(const string period, double rate) { return 1 / (1 + timeInYears(period) * rate / 100); } double timeInYears(const string period) { double businessDaysInYear = 360.0; if(period == "1W") { return 7.0 / businessDaysInYear; } if(period == "1M") { return 30.0 / businessDaysInYear; } if(period == "2M") { return 60.0 / businessDaysInYear; } if(period =="3M" ||period =="3M-6M" || period =="6M-9M" || period =="9M-12M" || period =="12M-15M" || period =="15M-18M" || period =="18M-21M") { return 90.0 / businessDaysInYear; } return 0; }
Update test to mention it requires C++14.
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -o %t2.o // expected-no-diagnostics #include "a.h"
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -std=c++14 -o %t2.o // expected-no-diagnostics #include "a.h"
Fix set order serialization bug
#include "SetOutputPacket.h" IPOCS::SetOutputPacket::SetOutputPacket() { this->RNID_PACKET = 13; } IPOCS::Packet* IPOCS::SetOutputPacket::create() { return new IPOCS::SetOutputPacket(); } uint8_t IPOCS::SetOutputPacket::parseSpecific(uint8_t buffer[]) { this->RQ_OUTPUT_COMMAND = (SetOutputPacket::E_RQ_OUTPUT_COMMAND)buffer[0]; this->RT_DURATION = (buffer[1] << 8) + buffer[2]; return 3; } uint8_t IPOCS::SetOutputPacket::serializeSpecific(uint8_t buffer[]) { buffer[0] = this->RQ_OUTPUT_COMMAND; buffer[1] = this->RT_DURATION >> 8; buffer[2] = this->RT_DURATION & 0x100; return 3; } __attribute__((constructor)) static void initialize_packet_throwpoints() { IPOCS::Packet::registerCreator(13, &IPOCS::SetOutputPacket::create); }
#include "SetOutputPacket.h" IPOCS::SetOutputPacket::SetOutputPacket() { this->RNID_PACKET = 13; } IPOCS::Packet* IPOCS::SetOutputPacket::create() { return new IPOCS::SetOutputPacket(); } uint8_t IPOCS::SetOutputPacket::parseSpecific(uint8_t buffer[]) { this->RQ_OUTPUT_COMMAND = (SetOutputPacket::E_RQ_OUTPUT_COMMAND)buffer[0]; this->RT_DURATION = (buffer[1] << 8) + buffer[2]; return 3; } uint8_t IPOCS::SetOutputPacket::serializeSpecific(uint8_t buffer[]) { buffer[0] = this->RQ_OUTPUT_COMMAND; buffer[1] = this->RT_DURATION >> 8; buffer[2] = this->RT_DURATION & 0xFF; return 3; } __attribute__((constructor)) static void initialize_packet_throwpoints() { IPOCS::Packet::registerCreator(13, &IPOCS::SetOutputPacket::create); }
Use new LXQt header files.
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2013 Razor team * Authors: * Kuzma Shapran <kuzma.shapran@gmail.com> * * This program or 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.1 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 * * END_COMMON_COPYRIGHT_HEADER */ #include <lxqt/lxqtapplication.h> #include "lxqttranslate.h" #include "main_window.h" int main(int argc, char *argv[]) { LxQt::Application a(argc, argv); TRANSLATE_APP; MainWindow w; w.show(); return a.exec(); }
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2013 Razor team * Authors: * Kuzma Shapran <kuzma.shapran@gmail.com> * * This program or 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.1 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 * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/Application> #include "lxqttranslate.h" #include "main_window.h" int main(int argc, char *argv[]) { LxQt::Application a(argc, argv); TRANSLATE_APP; MainWindow w; w.show(); return a.exec(); }
Fix logging config section width
/* Copyright (c) 2013-2019 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "RotatedHeaderView.h" #include <QPainter> using namespace QGBA; RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent) : QHeaderView(orientation, parent) { } void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const { painter->save(); painter->translate(rect.x() + rect.width(), rect.y()); painter->rotate(90); QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex); painter->restore(); } QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const { return QHeaderView::sectionSizeFromContents(logicalIndex).transposed(); }
/* Copyright (c) 2013-2019 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "RotatedHeaderView.h" #include <QPainter> using namespace QGBA; RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent) : QHeaderView(orientation, parent) { int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this); setMinimumSectionSize(fontMetrics().height() + margin); } void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const { painter->save(); painter->translate(rect.x() + rect.width(), rect.y()); painter->rotate(90); QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex); painter->restore(); } QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const { return QHeaderView::sectionSizeFromContents(logicalIndex).transposed(); }
Use the correct lsb key when fetching the CrOS device type.
// 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 "chromeos/system/devicetype.h" #include <string> #include "base/sys_info.h" namespace chromeos { namespace { const char kDeviceType[] = "CHROMEOS_DEVICE_TYPE"; } DeviceType GetDeviceType() { std::string value; if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) { if (value == "CHROMEBASE") return DeviceType::kChromebase; else if (value == "CHROMEBIT") return DeviceType::kChromebit; // Most devices are Chromebooks, so we will also consider reference boards // as chromebooks. else if (value == "CHROMEBOOK" || value == "REFERENCE") return DeviceType::kChromebook; else if (value == "CHROMEBOX") return DeviceType::kChromebox; else LOG(ERROR) << "Unknown device type \"" << value << "\""; } return DeviceType::kUnknown; } } // namespace chromeos
// 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 "chromeos/system/devicetype.h" #include <string> #include "base/sys_info.h" namespace chromeos { namespace { const char kDeviceType[] = "DEVICETYPE"; } DeviceType GetDeviceType() { std::string value; if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) { if (value == "CHROMEBASE") return DeviceType::kChromebase; else if (value == "CHROMEBIT") return DeviceType::kChromebit; // Most devices are Chromebooks, so we will also consider reference boards // as chromebooks. else if (value == "CHROMEBOOK" || value == "REFERENCE") return DeviceType::kChromebook; else if (value == "CHROMEBOX") return DeviceType::kChromebox; else LOG(ERROR) << "Unknown device type \"" << value << "\""; } return DeviceType::kUnknown; } } // namespace chromeos
Fix message scope level for functional test.
#include "Mocks.hpp" namespace testing { enum level : std::uint8_t { debug, info, warn, error }; } // namespace testing namespace blackhole { namespace sink { template<> struct priority_traits<testing::level> { static inline priority_t map(testing::level lvl) { switch (lvl) { case testing::level::debug: return priority_t::debug; case testing::level::info: return priority_t::info; case testing::level::warn: return priority_t::warning; case testing::level::error: return priority_t::err; } } }; } } // namespace blackhole::sink TEST(Functional, SyslogConfiguredVerboseLogger) { verbose_logger_t<testing::level> log; typedef formatter::string_t formatter_type; typedef sink::syslog_t<testing::level> sink_type; auto formatter = std::make_unique<formatter_type>("%(message)s [%(...L)s]"); auto sink = std::make_unique<sink_type>("testing"); auto frontend = std::make_unique<frontend_t<formatter_type, sink_type, testing::level>>(std::move(formatter), std::move(sink)); log.add_frontend(std::move(frontend)); log::record_t record = log.open_record(level::error); if (record.valid()) { record.attributes["message"] = { utils::format("Some message from: '%s'!", "Hell") }; // Add another attributes. log.push(std::move(record)); } }
#include "Mocks.hpp" namespace testing { enum level : std::uint8_t { debug, info, warn, error }; } // namespace testing namespace blackhole { namespace sink { template<> struct priority_traits<testing::level> { static inline priority_t map(testing::level lvl) { switch (lvl) { case testing::level::debug: return priority_t::debug; case testing::level::info: return priority_t::info; case testing::level::warn: return priority_t::warning; case testing::level::error: return priority_t::err; } } }; } } // namespace blackhole::sink TEST(Functional, SyslogConfiguredVerboseLogger) { verbose_logger_t<testing::level> log; typedef formatter::string_t formatter_type; typedef sink::syslog_t<testing::level> sink_type; auto formatter = std::make_unique<formatter_type>("%(message)s [%(...L)s]"); auto sink = std::make_unique<sink_type>("testing"); auto frontend = std::make_unique<frontend_t<formatter_type, sink_type, testing::level>>(std::move(formatter), std::move(sink)); log.add_frontend(std::move(frontend)); log::record_t record = log.open_record(level::error); if (record.valid()) { record.attributes["message"] = { utils::format("Some message from: '%s'!", "Hell"), log::attribute::scope::event }; log.push(std::move(record)); } }
Handle get command response parsin
#include "devicethread.h" DeviceThread::DeviceThread() { exit = false; } void DeviceThread::finish() { exit = true; } DeviceThread::run() { int ret; while(!exit) { if(!board.isConnected()) { ret = board.attachDevice(); if(ret < 0) { //Failed to attach wait(3000); notConnected(); continue; } else connected(); } //Connected, do actual work in this thread... //Update status getBacklightState(); //Process command queue while(!cmd.isEmpty()) { Command_t c = cmd.dequeue(); if(!IS_GET(c.cmd)) board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3); else { //TODO: } } //Wait for some time period. Number chosen at random as prime. wait(635); } } void DeviceThread::enqueue(const Command_t & c) { cmd.enqueue(c); }
#include "devicethread.h" DeviceThread::DeviceThread() { exit = false; } void DeviceThread::finish() { exit = true; } DeviceThread::run() { int ret; while(!exit) { if(!board.isConnected()) { ret = board.attachDevice(); if(ret < 0) { //Failed to attach wait(3000); notConnected(); continue; } else connected(); } //Connected, do actual work in this thread... //Update status getBacklightState(); //Process command queue while(!cmd.isEmpty()) { Command_t c = cmd.dequeue(); if(!IS_GET(c.cmd)) board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3); else { uint8_t buf[EP_LEN]; board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3, &buf); if(buf[0] == CMD_RES && buf[1] == CMD_BL_GET_STATE) emit(backlightResponse(buf[2], buf[3])); } } //Wait for some time period. Number chosen at random as prime. wait(635); } } void DeviceThread::enqueue(const Command_t & c) { cmd.enqueue(c); }
Use MAP_ANON instead of MAP_ANONYMOUS
// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s #include <stdint.h> #include <stdio.h> #include <errno.h> #include <sys/mman.h> #if defined(__FreeBSD__) // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before // that, it was never implemented. So just define it to zero. #undef MAP_NORESERVE #define MAP_NORESERVE 0 #endif int main() { #ifdef __x86_64__ const size_t kLog2Size = 39; #elif defined(__mips64) || defined(__aarch64__) const size_t kLog2Size = 32; #endif const uintptr_t kLocation = 0x40ULL << kLog2Size; void *p = mmap( reinterpret_cast<void*>(kLocation), 1ULL << kLog2Size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0); fprintf(stderr, "DONE %p %d\n", p, errno); return p == MAP_FAILED; } // CHECK: DONE
// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s #include <stdint.h> #include <stdio.h> #include <errno.h> #include <sys/mman.h> #if defined(__FreeBSD__) // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before // that, it was never implemented. So just define it to zero. #undef MAP_NORESERVE #define MAP_NORESERVE 0 #endif int main() { #ifdef __x86_64__ const size_t kLog2Size = 39; #elif defined(__mips64) || defined(__aarch64__) const size_t kLog2Size = 32; #endif const uintptr_t kLocation = 0x40ULL << kLog2Size; void *p = mmap( reinterpret_cast<void*>(kLocation), 1ULL << kLog2Size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON|MAP_NORESERVE, -1, 0); fprintf(stderr, "DONE %p %d\n", p, errno); return p == MAP_FAILED; } // CHECK: DONE
Use `f` suffix on floating point numbers.
#include <hal.h> #include <pwm_config.hpp> PWMDriver *pwmPlatformInit(void) { pwmStart(&PWMD8, &motor_pwm_config); palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4)); return &PWMD8; } // TODO(yoos): process multiple drivers void pwmPlatformSet(uint8_t ch, float dc) { pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000); pwmEnableChannel(&PWMD8, ch, width); }
#include <hal.h> #include <pwm_config.hpp> PWMDriver *pwmPlatformInit(void) { pwmStart(&PWMD8, &motor_pwm_config); palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4)); palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4)); return &PWMD8; } // TODO(yoos): process multiple drivers void pwmPlatformSet(uint8_t ch, float dc) { pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f); pwmEnableChannel(&PWMD8, ch, width); }
Add a test to verify get's return value behavior
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/auto_tuple.h> #include <string> class TupleTest: public testing::Test {}; TEST_F(TupleTest, CallTest) { autowiring::tuple<int, int, std::string> t(101, 102, "Hello world!"); ASSERT_EQ(101, autowiring::get<0>(t)) << "First tuple value was invalid"; ASSERT_EQ(102, autowiring::get<1>(t)) << "Second tuple value was invalid"; } TEST_F(TupleTest, TieTest) { std::unique_ptr<int> val(new int(22)); autowiring::tuple<std::unique_ptr<int>&> tup(val); ASSERT_EQ(22, *autowiring::get<0>(tup)) << "Tied tuple did not retrieve the expected value"; }
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/auto_tuple.h> #include <string> class TupleTest: public testing::Test {}; TEST_F(TupleTest, CallTest) { autowiring::tuple<int, int, std::string> t(101, 102, "Hello world!"); ASSERT_EQ(101, autowiring::get<0>(t)) << "First tuple value was invalid"; ASSERT_EQ(102, autowiring::get<1>(t)) << "Second tuple value was invalid"; } TEST_F(TupleTest, TieTest) { std::unique_ptr<int> val(new int(22)); autowiring::tuple<std::unique_ptr<int>&> tup(val); ASSERT_EQ(22, *autowiring::get<0>(tup)) << "Tied tuple did not retrieve the expected value"; } TEST_F(TupleTest, AddressTest) { autowiring::tuple<std::unique_ptr<int>> tup; std::unique_ptr<int>& v = autowiring::get<0>(tup); ASSERT_EQ(&tup.value, &v) << "Get operation did not provide a correct reference to the underlying tuple value"; }
Stop marking this test as unsupported on Darwin
// Tests -fsanitize-coverage=inline-8bit-counters // // REQUIRES: has_sancovcc,stable-runtime // UNSUPPORTED: i386-darwin, x86_64-darwin, x86_64h-darwin // // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1 #include <stdio.h> #include <assert.h> const char *first_counter; extern "C" void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) { printf("INIT: %p %p\n", start, end); assert(end - start > 1); first_counter = start; } int main() { assert(first_counter); assert(*first_counter == 1); }
// Tests -fsanitize-coverage=inline-8bit-counters // // REQUIRES: has_sancovcc,stable-runtime // UNSUPPORTED: i386-darwin // // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1 #include <stdio.h> #include <assert.h> const char *first_counter; extern "C" void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) { printf("INIT: %p %p\n", start, end); assert(end - start > 1); first_counter = start; } int main() { assert(first_counter); assert(*first_counter == 1); }
Add a message on the start of CPP-Interpreter.
// Native C++ Libraries #include <iostream> #include <string> #include <sstream> #include <vector> // C++ Interpreter Libraries #include <Console.h> #include <Varible.h> #include <Include.h> using namespace std; int main() { RESTART: string input = ""; ConsoleOutCheck(input); CheckForInt(input); CheckForIntAfterMath(input); CHECKFORIOSTREAM(input); getline(cin, input); goto RESTART; }
// Native C++ Libraries #include <iostream> #include <string> #include <sstream> #include <vector> // C++ Interpreter Libraries #include <Console.h> #include <Varible.h> #include <Include.h> using namespace std; int main() { cout << "CPP Interpreter v0.1. Here you can type C++ code in the terminal and get instant feedback from it.\n\n\n"; RESTART: cout << "--->"; string input = ""; ConsoleOutCheck(input); CheckForInt(input); CheckForIntAfterMath(input); CHECKFORIOSTREAM(input); getline(cin, input); goto RESTART; }
Fix bad test that was previously getting ifdef-ed away
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <chrono> // treat_as_floating_point #include <chrono> #include <type_traits> #include "test_macros.h" template <class T> void test() { static_assert((std::is_base_of<std::is_floating_point<T>, std::chrono::treat_as_floating_point<T> >::value), ""); #if TEST_STD_VER > 14 static_assert((std::is_base_of<std::is_floating_point<T>, std::chrono::treat_as_floating_point_v<T> >), ""); #endif } struct A {}; int main() { test<int>(); test<unsigned>(); test<char>(); test<bool>(); test<float>(); test<double>(); test<long double>(); test<A>(); }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <chrono> // treat_as_floating_point #include <chrono> #include <type_traits> #include "test_macros.h" template <class T> void test() { static_assert((std::is_base_of<std::is_floating_point<T>, std::chrono::treat_as_floating_point<T> >::value), ""); #if TEST_STD_VER > 14 static_assert(std::is_floating_point<T>::value == std::chrono::treat_as_floating_point_v<T>, ""); #endif } struct A {}; int main() { test<int>(); test<unsigned>(); test<char>(); test<bool>(); test<float>(); test<double>(); test<long double>(); test<A>(); }
Add tests on sizeof lambdas
// Copyright 2017, Dawid Kurek, <dawikur@gmail.com> #include "lel.hpp" #include "gtest/gtest.h" class sizeof_lambdas_test : public ::testing::Test { protected: LeL::Placeholder<'x'> _x; LeL::Placeholder<'y'> _y; }; TEST_F(sizeof_lambdas_test, base_placeholder_is_1) { ASSERT_EQ(1, sizeof(_x)); } TEST_F(sizeof_lambdas_test, DISABLED_placeholder_with_one_int_equals_size_of_int) { ASSERT_EQ(sizeof(1), sizeof(_x + 1)); } TEST_F(sizeof_lambdas_test, DISABLED_placeholder_with_two_ints_equals_sizof_to_ints) { ASSERT_EQ(sizeof(1) + sizeof(5), sizeof(_x + 1 < 5)); } TEST_F(sizeof_lambdas_test, DISABLED_multiple_base_placehlder_is_1) { ASSERT_EQ(1, sizeof(_x < _y)); }
Tweak test to check for a bit more.
// RUN: clang-cc -emit-llvm -o - %s | FileCheck %s struct D; struct B { virtual D& operator = (const D&); }; struct D : B { D(); virtual void a(); }; void D::a() {} // CHECK: @_ZTV1D = {{.*}} @_ZN1DaSERKS_
// RUN: clang-cc -emit-llvm -o - %s | FileCheck %s struct D; struct B { virtual D& operator = (const D&); }; struct D : B { D(); virtual void a(); }; void D::a() {} // CHECK: @_ZTV1D = {{.*}} @_ZN1DaSERKS_ // CHECK: define linkonce_odr {{.*}} @_ZN1DaSERKS_
Disable irrelevant unittest on win64
// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: not %run %t 2>&1 | FileCheck %s #include <stdio.h> char bigchunk[1 << 30]; int main() { printf("Hello, world!\n"); scanf("%s", bigchunk); // CHECK-NOT: Hello, world! // CHECK: Shadow memory range interleaves with an existing memory mapping. // CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range. // CHECK: Dumping process modules: // CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure // CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll }
// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: not %run %t 2>&1 | FileCheck %s // REQUIRES: asan-32-bits #include <stdio.h> char bigchunk[1 << 30]; int main() { printf("Hello, world!\n"); scanf("%s", bigchunk); // CHECK-NOT: Hello, world! // CHECK: Shadow memory range interleaves with an existing memory mapping. // CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range. // CHECK: Dumping process modules: // CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure // CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll }
Change requirements for json writer:
#include <UnitTest++.h> #include "../src/ToJsonWriter.h" SUITE(ArticleToJsonWriterTests) { TEST(WriteArticleWithoutLinks) { ToJsonWriter atj; Article a("Farm"); CHECK_EQUAL("{\"Farm\":[]}", atj.convertToJson(&a)); } TEST(WriteArticleWithOneLink) { ToJsonWriter atj; Article a("Farm"); a.addLink(new Article("Animal")); CHECK_EQUAL("{\"Farm\":[\"Animal\"]}", atj.convertToJson(&a)); } TEST(WriteArticleWithMultipleLinks) { ToJsonWriter atj; Article a("Farm"); a.addLink(new Article("Animal")); a.addLink(new Article("Pig")); a.addLink(new Article("Equality")); CHECK_EQUAL("{\"Farm\":[\"Animal\",\"Pig\",\"Equality\"]}", atj.convertToJson(&a)); } TEST(WriteEmptyArticleCollection) { ToJsonWriter atj; ArticleCollection ac; CHECK_EQUAL("{}", atj.convertToJson(ac)); } TEST(WriteArticleCollection_OneArticleWithoutLinks) { ToJsonWriter atj; ArticleCollection ac; ac.add(new Article("Foo")); CHECK_EQUAL("{\"Foo\":[]}", atj.convertToJson(ac)); } }
#include <UnitTest++.h> #include "../src/ToJsonWriter.h" SUITE(ArticleToJsonWriterTests) { TEST(WriteArticleWithoutLinks) { ToJsonWriter atj; Article a("Farm"); CHECK_EQUAL("{\"Farm\":{\"forward_links\":[]}}", atj.convertToJson(&a)); } TEST(WriteArticleWithOneLink) { ToJsonWriter atj; Article a("Farm"); a.addLink(new Article("Animal")); CHECK_EQUAL("{\"Farm\":{\"forward_links\":[\"Animal\"]}}", atj.convertToJson(&a)); } TEST(WriteArticleWithMultipleLinks) { ToJsonWriter atj; Article a("Farm"); a.addLink(new Article("Animal")); a.addLink(new Article("Pig")); a.addLink(new Article("Equality")); CHECK_EQUAL("{\"Farm\":{\"forward_links\":[\"Animal\",\"Pig\",\"Equality\"]}}", atj.convertToJson(&a)); } TEST(WriteEmptyArticleCollection) { ToJsonWriter atj; ArticleCollection ac; CHECK_EQUAL("{}", atj.convertToJson(ac)); } TEST(WriteArticleCollection_OneArticleWithoutLinks) { ToJsonWriter atj; ArticleCollection ac; ac.add(new Article("Foo")); CHECK_EQUAL("{\"Foo\":{\"forward_links\":[]}}", atj.convertToJson(ac)); } }
Correct typo (23 to 24)
// Chapter 23, Try This 1: replace 333 in example with 10 #include<iostream> #include<iomanip> int main() { float x = 1.0/10; float sum = 0; for (int i = 0; i<10; ++i) sum += x; std::cout << std::setprecision(15) << sum << '\n'; }
// Chapter 24, Try This 1: replace 333 in example with 10 #include<iostream> #include<iomanip> int main() { float x = 1.0/10; float sum = 0; for (int i = 0; i<10; ++i) sum += x; std::cout << std::setprecision(15) << sum << '\n'; }
Add null at the of argv when converting from std::vector<std:string>
/* * auxiliary.cpp - Auxiliary public functions * * Copyright 2010 Jesús Torres <jmtorres@ull.es> * * 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 <string> #include <vector> #include <boost/shared_array.hpp> #include <cli/auxiliary.hpp> #include "fileno.hpp" namespace cli { namespace auxiliary { boost::shared_array<const char*> stdVectorStringToArgV(const std::vector<std::string> &strings) { int length = strings.size(); boost::shared_array<const char*> argv = boost::shared_array<const char*>(new const char*[length]); for (int i = 0; i < length; i++) { argv[i] = strings[i].c_str(); } return argv; } }}
/* * auxiliary.cpp - Auxiliary public functions * * Copyright 2010 Jesús Torres <jmtorres@ull.es> * * 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 <string> #include <vector> #include <boost/shared_array.hpp> #include <cli/auxiliary.hpp> #include "fileno.hpp" namespace cli { namespace auxiliary { boost::shared_array<const char*> stdVectorStringToArgV(const std::vector<std::string> &strings) { int length = strings.size(); boost::shared_array<const char*> argv = boost::shared_array<const char*>(new const char*[length + 1]); for (int i = 0; i < length; i++) { argv[i] = strings[i].c_str(); } argv[length] = NULL; return argv; } }}
Add another NVIDIA LSAN suppression.
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #if !defined(__has_feature) #define __has_feature(x) 0 #endif #if __has_feature(address_sanitizer) extern "C" { const char* __lsan_default_suppressions(); const char* __lsan_default_suppressions() { return "leak:libfontconfig\n" // FontConfig looks like it leaks, but it doesn't. "leak:libGL.so\n" // For NVidia driver. "leak:libGLX_nvidia.so\n" // For NVidia driver. "leak:libnvidia-glcore.so\n" // For NVidia driver. "leak:__strdup\n" // An eternal mystery, skia:2916. ; } } #endif
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #if !defined(__has_feature) #define __has_feature(x) 0 #endif #if __has_feature(address_sanitizer) extern "C" { const char* __lsan_default_suppressions(); const char* __lsan_default_suppressions() { return "leak:libfontconfig\n" // FontConfig looks like it leaks, but it doesn't. "leak:libGL.so\n" // For NVidia driver. "leak:libGLX_nvidia.so\n" // For NVidia driver. "leak:libnvidia-glcore.so\n" // For NVidia driver. "leak:libnvidia-tls.so\n" // For NVidia driver. "leak:__strdup\n" // An eternal mystery, skia:2916. ; } } #endif
Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues.
Matrix2f M = Matrix2f::Random(); Matrix2f m; m = M; cout << "Here is the matrix m:" << endl << m << endl; cout << "Now we want to replace m by its own transpose." << endl; cout << "If we do m = m.transpose(), then m becomes:" << endl; m = m.transpose() * 1; cout << m << endl << "which is wrong!" << endl; cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl; m = M; m = m.transpose().eval(); cout << m << endl << "which is right." << endl;
Matrix2f M = Matrix2f::Random(); Matrix2f m; m = M; cout << "Here is the matrix m:" << endl << m << endl; cout << "Now we want to copy a column into a row." << endl; cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl; m.col(1) = m.row(0); cout << m << endl << "which is wrong!" << endl; cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl; m = M; m.col(1) = m.row(0).eval(); cout << m << endl << "which is right." << endl;
Add command line options. WE GOING 1.0
#include "mainwindow.hpp" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setApplicationName("KShare"); a.setOrganizationName("ArsenArsen"); a.setApplicationVersion("1.0"); MainWindow w; w.show(); return a.exec(); }
#include "mainwindow.hpp" #include <QApplication> #include <QCommandLineParser> #include <QDebug> #include <stdio.h> bool verbose = false; void handler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); switch (type) { case QtDebugMsg: if (verbose) fprintf(stdout, "DEBUG %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData()); break; case QtInfoMsg: fprintf(stdout, "INFO %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData()); break; case QtWarningMsg: fprintf(stderr, "WARN %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData()); break; case QtCriticalMsg: fprintf(stderr, "CRIT %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData()); break; case QtFatalMsg: fprintf(stderr, "FATAL %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData()); break; } } int main(int argc, char *argv[]) { qInstallMessageHandler(handler); QApplication a(argc, argv); a.setApplicationName("KShare"); a.setOrganizationName("ArsenArsen"); a.setApplicationVersion("1.0"); QCommandLineParser parser; parser.addHelpOption(); QCommandLineOption h({ "b", "background" }, "Does not show the main window, starts in tray."); QCommandLineOption v({ "v", "verbose" }, "Enables QtDebugMsg outputs"); parser.addOption(h); parser.addOption(v); parser.process(a); verbose = parser.isSet(v); MainWindow w; if (!parser.isSet(h)) w.show(); return a.exec(); }
Enable ExtensionApiTest.GetViews on all platforms.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) // Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms. // See http://crbug.com/39916 for details. #define MAYBE_GetViews GetViews #else #define MAYBE_GetViews DISABLED_GetViews #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViews) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("get_views")) << message_; }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViews) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("get_views")) << message_; }
Fix Windows build when Qt Multimedia is disabled
/* Copyright (c) 2013-2014 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "GBAApp.h" #include "Window.h" #ifdef QT_STATIC #include <QtPlugin> #ifdef _WIN32 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); Q_IMPORT_PLUGIN(QWindowsAudioPlugin); #endif #endif int main(int argc, char* argv[]) { QGBA::GBAApp application(argc, argv); return application.exec(); }
/* Copyright (c) 2013-2014 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "GBAApp.h" #include "Window.h" #ifdef QT_STATIC #include <QtPlugin> #ifdef _WIN32 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #ifdef BUILD_QT_MULTIMEDIA Q_IMPORT_PLUGIN(QWindowsAudioPlugin); #endif #endif #endif int main(int argc, char* argv[]) { QGBA::GBAApp application(argc, argv); return application.exec(); }
Return to driving on Joysticks
#include "OI.h" #include "Commands/DefaultDrive.h" #include "Subsystems/Chassis.h" #include "Misc/ToggleClass.h" /// Default constructor of the class. DefaultDrive::DefaultDrive() { Requires(Chassis::GetInstance()); shifterToggle = new Toggle<bool>(false, true); } /// Called just before this Command runs the first time. void DefaultDrive::Initialize() { Chassis::GetInstance()->ReleaseAngle(); } //Pass values from joysticks to the Drive subsystem void DefaultDrive::Execute() { OI* oi = OI::GetInstance(); double moveSpeed = -oi->gamepad->GetRawAxis(LST_AXS_LJOYSTICKY); double turnSpeed = -oi->gamepad->GetRawAxis(LST_AXS_RJOYSTICKX); // Only driving manual should require Quadratic inputs. By default it should be turned off // Therefore here we turn it on explicitly. Chassis::GetInstance()->DriveArcade(moveSpeed, turnSpeed, true); } /// Make this return true when this Command no longer needs to run execute(). /// \return always false since this is the default command and should never finish. bool DefaultDrive::IsFinished() { return false; } /// Called once after isFinished returns true void DefaultDrive::End() { } /// Called when another command which requires one or more of the same /// subsystems is scheduled to run void DefaultDrive::Interrupted() { }
#include "OI.h" #include "Commands/DefaultDrive.h" #include "Subsystems/Chassis.h" #include "Misc/ToggleClass.h" /// Default constructor of the class. DefaultDrive::DefaultDrive() { Requires(Chassis::GetInstance()); shifterToggle = new Toggle<bool>(false, true); } /// Called just before this Command runs the first time. void DefaultDrive::Initialize() { Chassis::GetInstance()->ReleaseAngle(); } //Pass values from joysticks to the Drive subsystem void DefaultDrive::Execute() { OI* oi = OI::GetInstance(); double moveSpeed = -oi->stickL->GetY(); double turnSpeed = -oi->stickR->GetX(); // Only driving manual should require Quadratic inputs. By default it should be turned off // Therefore here we turn it on explicitly. Chassis::GetInstance()->DriveArcade(moveSpeed, turnSpeed, true); } /// Make this return true when this Command no longer needs to run execute(). /// \return always false since this is the default command and should never finish. bool DefaultDrive::IsFinished() { return false; } /// Called once after isFinished returns true void DefaultDrive::End() { } /// Called when another command which requires one or more of the same /// subsystems is scheduled to run void DefaultDrive::Interrupted() { }
Reset list item image when setting empty URL.
/** * Appcelerator Titanium Mobile * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "BasicListItem.h" using namespace bb::cascades; BasicListItem::BasicListItem() { item_ = new StandardListItem(); setRoot(item_); } void BasicListItem::setData(QObject* data) { updateImage(data->property("leftImage").value<QUrl>()); updateTitle(data->property("title").toString()); connect(data, SIGNAL(leftImageChanged(const QUrl&)), SLOT(updateImage(const QUrl&))); connect(data, SIGNAL(titleChanged(const QString&)), SLOT(updateTitle(const QString&))); data_->disconnect(this); data_ = data; } void BasicListItem::updateImage(const QUrl& url) { item_->setImage(Image(url)); } void BasicListItem::updateTitle(const QString& title) { item_->setTitle(title); }
/** * Appcelerator Titanium Mobile * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "BasicListItem.h" using namespace bb::cascades; BasicListItem::BasicListItem() { item_ = new StandardListItem(); setRoot(item_); } void BasicListItem::setData(QObject* data) { updateImage(data->property("leftImage").value<QUrl>()); updateTitle(data->property("title").toString()); connect(data, SIGNAL(leftImageChanged(const QUrl&)), SLOT(updateImage(const QUrl&))); connect(data, SIGNAL(titleChanged(const QString&)), SLOT(updateTitle(const QString&))); data_->disconnect(this); data_ = data; } void BasicListItem::updateImage(const QUrl& url) { if (url.isEmpty()) { item_->resetImage(); return; } item_->setImage(Image(url)); } void BasicListItem::updateTitle(const QString& title) { item_->setTitle(title); }
Edit of comments in 1.21.
/** * @file * sum_two_sales_data.cpp * @author * Henrik Samuelsson */ #include <iostream> #include "Sales_item.h" /** * @brief * Reads two sales_item's objects prints the sum. * @note * The exercise instructions in the book state that the two objects have * the same ISBN. It is assumed that it is up to the user to enter objects * with the same ISBN, the program will not check this. * @return * 0 upon correct and completed execution */ int main() { Sales_item item1, item2; std::cin >> item1 >> item2; std::cout << item1 + item2; return 0; }
/** * @file * sum_two_sales_data.cpp * @author * Henrik Samuelsson */ #include <iostream> #include "Sales_item.h" /** * @brief * Reads two sales_item's objects and prints the sum. * @note * The exercise instructions in the book state that the two objects have * the same ISBN. It is assumed that it is up to the user to enter objects * with the same ISBN, the program will not check this. * @return * 0 upon correct and completed execution */ int main() { Sales_item item1, item2; std::cin >> item1 >> item2; std::cout << item1 + item2; return 0; }
Update filter for newer TwoInptProc::render() mechanism
#include "../common_includes.h" #include "blend.h" using namespace ogles_gpgpu; const char *BlendProc::fshaderBlendSrc = OG_TO_STR ( #if defined(OGLES_GPGPU_OPENGLES) precision highp float; #endif varying vec2 textureCoordinate; varying vec2 textureCoordinate2; uniform sampler2D inputImageTexture; uniform sampler2D inputImageTexture2; uniform float alpha; void main() { vec4 textureColor = texture2D(inputImageTexture, textureCoordinate); vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate); gl_FragColor = mix(textureColor, textureColor2, alpha); }); BlendProc::BlendProc(float alpha) : alpha(alpha) { } void BlendProc::getUniforms() { TwoInputProc::getUniforms(); shParamUAlpha = shader->getParam(UNIF, "alpha"); } void BlendProc::setUniforms() { TwoInputProc::setUniforms(); glUniform1f(shParamUAlpha, alpha); } int BlendProc::render(int position) { // Always render on position == 0 if(position == 0) { FilterProcBase::render(position); } return position; }
#include "../common_includes.h" #include "blend.h" using namespace ogles_gpgpu; const char *BlendProc::fshaderBlendSrc = OG_TO_STR ( #if defined(OGLES_GPGPU_OPENGLES) precision highp float; #endif varying vec2 textureCoordinate; varying vec2 textureCoordinate2; uniform sampler2D inputImageTexture; uniform sampler2D inputImageTexture2; uniform float alpha; void main() { vec4 textureColor = texture2D(inputImageTexture, textureCoordinate); vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate); gl_FragColor = mix(textureColor, textureColor2, alpha); }); BlendProc::BlendProc(float alpha) : alpha(alpha) { } void BlendProc::getUniforms() { TwoInputProc::getUniforms(); shParamUAlpha = shader->getParam(UNIF, "alpha"); } void BlendProc::setUniforms() { TwoInputProc::setUniforms(); glUniform1f(shParamUAlpha, alpha); } int BlendProc::render(int position) { // Always render on position == 0 TwoInputProc::render(position); return position; }
Use store instead of "=" for atomic.
#include "signal_handlers.h" #include <cstring> #include <iostream> #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> namespace keron { namespace server { std::atomic_int stop(0); static BOOL handler(DWORD fdwCtrlType) { switch (fdwCtrlType) { case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: std::cout << "The server is going DOWN!" << std::endl; stop = 1; return TRUE; case CTRL_BREAK_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: std::cout << "The server is going DOWN!" << std::endl; stop = 1; // Same return as the default case. default: return FALSE; } } int register_signal_handlers() { return SetConsoleCtrlHandler((PHANDLER_ROUTINE)handler, TRUE) == TRUE; } } // namespace server } // namespace keron
#include "signal_handlers.h" #include <cstring> #include <iostream> #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> namespace keron { namespace server { std::atomic_int stop(0); static BOOL handler(DWORD fdwCtrlType) { switch (fdwCtrlType) { case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: std::cout << "The server is going DOWN!" << std::endl; stop.store(1); return TRUE; case CTRL_BREAK_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: std::cout << "The server is going DOWN!" << std::endl; stop.store(1); // Same return as the default case. default: return FALSE; } } int register_signal_handlers() { return SetConsoleCtrlHandler((PHANDLER_ROUTINE)handler, TRUE) == TRUE; } } // namespace server } // namespace keron
Remove wrong parameter from ECSignatureCreator's constructor in openssl implement.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/ec_signature_creator.h" #include "base/logging.h" namespace crypto { // static ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) { NOTIMPLEMENTED(); return NULL; } ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key, HASH_HashType hash_type) : key_(key), hash_type_(hash_type) { NOTIMPLEMENTED(); } ECSignatureCreator::~ECSignatureCreator() { } bool ECSignatureCreator::Sign(const uint8* data, int data_len, std::vector<uint8>* signature) { NOTIMPLEMENTED(); return false; } } // namespace crypto
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/ec_signature_creator.h" #include "base/logging.h" namespace crypto { // static ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) { NOTIMPLEMENTED(); return NULL; } ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key) : key_(key) { NOTIMPLEMENTED(); } ECSignatureCreator::~ECSignatureCreator() { } bool ECSignatureCreator::Sign(const uint8* data, int data_len, std::vector<uint8>* signature) { NOTIMPLEMENTED(); return false; } } // namespace crypto
Fix return value when unfiltered keyboard events are registered.
// 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 "ppapi/shared_impl/instance_impl.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_input_event.h" namespace ppapi { InstanceImpl::~InstanceImpl() { } int32_t InstanceImpl::ValidateRequestInputEvents(bool is_filtering, uint32_t event_classes) { // See if any bits are set we don't know about. if (event_classes & ~static_cast<uint32_t>(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_KEYBOARD | PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_TOUCH | PP_INPUTEVENT_CLASS_IME)) return PP_ERROR_NOTSUPPORTED; // See if the keyboard is requested in non-filtering mode. if (!is_filtering && (event_classes & PP_INPUTEVENT_CLASS_KEYBOARD)) return PP_ERROR_NOTSUPPORTED; // Everything else is valid. return PP_OK; } } // namespace ppapi
// 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 "ppapi/shared_impl/instance_impl.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_input_event.h" namespace ppapi { InstanceImpl::~InstanceImpl() { } int32_t InstanceImpl::ValidateRequestInputEvents(bool is_filtering, uint32_t event_classes) { // See if any bits are set we don't know about. if (event_classes & ~static_cast<uint32_t>(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_KEYBOARD | PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_TOUCH | PP_INPUTEVENT_CLASS_IME)) return PP_ERROR_NOTSUPPORTED; // Everything else is valid. return PP_OK; } } // namespace ppapi
Fix bug in URL parsing
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include "gst_media_binding.h" namespace ti { GstMediaBinding::GstMediaBinding(SharedKObject global) : MediaBinding(global) { char **argv; int argc = 0; gst_init(&argc, &argv); } GstMediaBinding::~GstMediaBinding() { } void GstMediaBinding::Beep() { printf("\a"); // \a to console should cause the beep sound } SharedKObject GstMediaBinding::CreateSound(std::string& url) { //This is a path so, turn it into a file:// URL std::string myurl = url; std::string path = URLUtils::URLToPath(url); if (path.find("://") != std::string::npos) { myurl = URLUtils::PathToFileURL(path); } SharedGstSound sound = new GstSound(myurl); GstSound::RegisterSound(sound); return sound; } }
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include "gst_media_binding.h" namespace ti { GstMediaBinding::GstMediaBinding(SharedKObject global) : MediaBinding(global) { char **argv; int argc = 0; gst_init(&argc, &argv); } GstMediaBinding::~GstMediaBinding() { } void GstMediaBinding::Beep() { printf("\a"); // \a to console should cause the beep sound } SharedKObject GstMediaBinding::CreateSound(std::string& url) { //This is a path so, turn it into a file:// URL std::string myurl = url; std::string path = URLUtils::URLToPath(url); if (path.find("://") == std::string::npos) { myurl = URLUtils::PathToFileURL(path); } SharedGstSound sound = new GstSound(myurl); GstSound::RegisterSound(sound); return sound; } }
Fix silly error in unittest helper.
#include "llvm/Testing/Support/SupportHelpers.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::unittest; extern const char *TestMainArgv0; SmallString<128> llvm::unittest::getInputFileDirectory() { llvm::SmallString<128> Result = llvm::sys::path::parent_path(TestMainArgv0); llvm::sys::fs::make_absolute(Result); llvm::sys::path::append(Result, "llvm.srcdir.txt"); EXPECT_TRUE(llvm::sys::fs::is_directory(Result)) << "Unit test source directory file does not exist."; auto File = MemoryBuffer::getFile(Result); EXPECT_TRUE(static_cast<bool>(File)) << "Could not open unit test source directory file."; Result.clear(); Result.append((*File)->getBuffer().trim()); llvm::sys::path::append(Result, "Inputs"); llvm::sys::path::native(Result); return std::move(Result); }
#include "llvm/Testing/Support/SupportHelpers.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::unittest; extern const char *TestMainArgv0; SmallString<128> llvm::unittest::getInputFileDirectory() { llvm::SmallString<128> Result = llvm::sys::path::parent_path(TestMainArgv0); llvm::sys::fs::make_absolute(Result); llvm::sys::path::append(Result, "llvm.srcdir.txt"); EXPECT_TRUE(llvm::sys::fs::is_regular_file(Result)) << "Unit test source directory file does not exist."; auto File = MemoryBuffer::getFile(Result); EXPECT_TRUE(static_cast<bool>(File)) << "Could not open unit test source directory file."; Result.clear(); Result.append((*File)->getBuffer().trim()); llvm::sys::path::append(Result, "Inputs"); llvm::sys::path::native(Result); return std::move(Result); }
Remove removeParent from javascript ParentedEntity.
#include <emscripten/bind.h> #include "libcellml/parentedentity.h" using namespace emscripten; EMSCRIPTEN_BINDINGS(libcellml_parentedentity) { class_<libcellml::ParentedEntity, base<libcellml::Entity>>("ParentedEntity") .smart_ptr<std::shared_ptr<libcellml::ParentedEntity>>("ParentedEntity") .function("parent", &libcellml::ParentedEntity::parent) .function("removeParent", &libcellml::ParentedEntity::removeParent) .function("hasParent", &libcellml::ParentedEntity::hasParent) .function("hasAncestor", &libcellml::ParentedEntity::hasAncestor) ; }
#include <emscripten/bind.h> #include "libcellml/parentedentity.h" using namespace emscripten; EMSCRIPTEN_BINDINGS(libcellml_parentedentity) { class_<libcellml::ParentedEntity, base<libcellml::Entity>>("ParentedEntity") .smart_ptr<std::shared_ptr<libcellml::ParentedEntity>>("ParentedEntity") .function("parent", &libcellml::ParentedEntity::parent) .function("hasParent", &libcellml::ParentedEntity::hasParent) .function("hasAncestor", &libcellml::ParentedEntity::hasAncestor) ; }
Fix compilation error in the focus manager by returning NULL from unimplemented function.
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/focus/focus_manager.h" #include "base/logging.h" namespace views { void FocusManager::ClearNativeFocus() { NOTIMPLEMENTED(); } void FocusManager::FocusNativeView(gfx::NativeView native_view) { NOTIMPLEMENTED(); } // static FocusManager* FocusManager::GetFocusManagerForNativeView( gfx::NativeView native_view) { NOTIMPLEMENTED(); } } // namespace views
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/focus/focus_manager.h" #include "base/logging.h" namespace views { void FocusManager::ClearNativeFocus() { NOTIMPLEMENTED(); } void FocusManager::FocusNativeView(gfx::NativeView native_view) { NOTIMPLEMENTED(); } // static FocusManager* FocusManager::GetFocusManagerForNativeView( gfx::NativeView native_view) { NOTIMPLEMENTED(); return NULL; } } // namespace views
Add the solution to "Potentate Permutation".
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> using namespace std; typedef map< string, vector<string> > Graph; typedef struct { int finish_time; int visited; }State; void dfs(Graph &g, string v, map<string, State*> &state, int &dfs_time) { state[v]->visited = 0; dfs_time++; vector<string> adjacent = g[v]; for (vector<string>::iterator i = adjacent.begin(); i != adjacent.end(); i++) { if (state[*i]->visited == -1) { dfs(g, *i, state, dfs_time); } } state[v]->visited = 1; dfs_time++; state[v]->finish_time = dfs_time; } bool cmp(const pair<string, State*> &x, const pair<string, State*> &y) { return x.second->finish_time > y.second->finish_time; } int main() { int T; cin >> T; while(T--) { Graph graph; map<string, State*> state; int finish_time = 0; int N; cin >> N; while (N--) { string x, y; cin >> x >> y; graph[x].push_back(y); state[x] = new State; state[x]->finish_time = 0; state[x]->visited = -1; if (graph[y].empty()) { graph[y].clear(); state[y] = new State; state[y]->finish_time = 0; state[y]->visited = -1; } } for (Graph::iterator i = graph.begin(); i != graph.end(); i++) { if (state[i->first]->visited == -1) { dfs(graph, i->first, state, finish_time); } } typedef vector< pair<string, State*> > ResType; ResType res; for (map<string, State*>::iterator i = state.begin(); i != state.end(); i++) { res.push_back(pair<string, State*>(i->first, i->second)); } sort(res.begin(), res.end(), cmp); for (ResType::iterator i = res.begin(); i != res.end(); i++) { cout << i->first << endl; } } return 0; }
Add test for concurrent groups
#include <iostream> #include <execution_policy> int main() { std::async(std::con(10), [](std::concurrent_group &g) { std::cout << "agent " << g.child().index() << " arriving at barrier" << std::endl; g.wait(); std::cout << "departing barrier" << std::endl; }).wait(); return 0; }
Test explicit specializations of static data members that are declarations, not definitions
// RUN: clang-cc -fsyntax-only -verify %s struct NonDefaultConstructible { NonDefaultConstructible(const NonDefaultConstructible&); }; template<typename T, typename U> struct X { static T member; }; template<typename T, typename U> T X<T, U>::member; // expected-error{{no matching constructor}} // Okay; this is a declaration, not a definition. template<> NonDefaultConstructible X<NonDefaultConstructible, long>::member; NonDefaultConstructible &test(bool b) { return b? X<NonDefaultConstructible, int>::member // expected-note{{instantiation}} : X<NonDefaultConstructible, long>::member; }
Add huge coroutine test program
/* g++ huge-threads.cpp ../../objs/st/libst.a -g -O0 -DLINUX -o huge-threads && ./huge-threads 32756 */ #include <stdio.h> #include <stdlib.h> #include "../../objs/st/st.h" void* pfn(void* arg) { char v[32*1024]; // 32KB in stack. for (;;) { v[0] = v[sizeof(v) - 1] = 0xf; st_usleep(1000 * 1000); } return NULL; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s nn_coroutines [verbose]\n", argv[0]); exit(-1); } st_init(); int nn = ::atoi(argv[1]); printf("pid=%d, create %d coroutines\n", ::getpid(), nn); for (int i = 0; i < nn; i++) { st_thread_t thread = st_thread_create(pfn, NULL, 1, 0); if (!thread) { printf("create thread fail, i=%d\n", i); return -1; } if (argc > 2) { printf("thread #%d: %p\n", i, thread); } } printf("done\n"); st_thread_exit(NULL); return 0; }
Fix build failure on Fedora
/* * Copyright (c) 2008, Thomas Jaeger <ThJaeger@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "util.h" #include <sys/time.h> #include <time.h> void show_us(const char *str) { struct timeval tv; gettimeofday(&tv, 0); printf("%s: %ld.%ld\n", str, tv.tv_sec, tv.tv_usec); }
/* * Copyright (c) 2008, Thomas Jaeger <ThJaeger@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "util.h" #include <stdio.h> #include <sys/time.h> #include <time.h> void show_us(const char *str) { struct timeval tv; gettimeofday(&tv, 0); printf("%s: %ld.%ld\n", str, tv.tv_sec, tv.tv_usec); }
Add solution to the second problem
#include <iostream> using namespace std; struct Destination { char city[32]; int kilometers; }; int main() { Destination plovdiv = { "Plovdiv", 165 }, varna = { "Varna", 469 }; cout << plovdiv.city << " " << plovdiv.kilometers << endl; cout << varna.city << " " << varna.kilometers << endl; Destination destinations[30]; for (int i = 0; i < 30; i++) { destinations[i] = {}; } Destination fiveDestinations[5] = { { "Plovdiv", 165 }, { "Varna", 469 }, { "Burgas", 393 }, { "Vidin", 199 }, { "Dobrich", 512 } }; for (int i = 0; i < 5; i++) cout << fiveDestinations[i].city << " " << fiveDestinations[i].kilometers << endl; return 0; }
Convert Sorted List to Binary Search Tree
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedListToBST(ListNode* head) { if(!head) return NULL; int tot=countl(head); if(tot==1){ TreeNode* ret=new TreeNode(head->val); return ret; } int mid=(tot-1)/2; ListNode* t=new ListNode(0); if(mid==0){ t=head; }else{ t=getnth(head,mid); } TreeNode* ret=new TreeNode(t->next->val); ret->right=sortedListToBST(t->next->next); t->next=NULL; ret->left=sortedListToBST(head); return ret; } int countl(ListNode* head){ if(head->next) return countl(head->next)+1; return 1; } ListNode* getnth(ListNode* head, int n){ if(n==1) return head; return getnth(head->next,n-1); } };
Update to version 0.1.0 Add millisecond resolution
#include "ntp-time.h" NtpTime* ntpTime; String hhmmss(unsigned long int now) //format value as "hh:mm:ss" { String hour = String(Time.hourFormat12(now)); String minute = String::format("%02i",Time.minute(now)); String second = String::format("%02i",Time.second(now)); return hour + ":" + minute + ":" + second; }; void setup() { ntpTime = new NtpTime(15); // Do an ntp update every 15 minutes; ntpTime->start(); } void loop() { static unsigned long waitMillis; struct epochMillis now; //holds the unix epoch time to millisecond resolution if(millis() > waitMillis) { ntpTime->nowMillis(&now); //get the current NTP time Particle.publish("NTP clock is: ", hhmmss(now.seconds) + "." + String::format("%03i",now.millis)); Particle.publish("System clock is: ", hhmmss(Time.now())); waitMillis = millis() + (15*1000); // wait 15 seconds } }
Add sample for section: Done States
// done_states.cpp #include "hsm/statemachine.h" using namespace hsm; class Character { public: Character(); void Update(); // Public to simplify sample bool mOpenDoor; private: friend struct CharacterStates; StateMachine mStateMachine; }; struct CharacterStates { struct BaseState : StateWithOwner<Character> { }; struct Alive : BaseState { virtual Transition GetTransition() { return InnerEntryTransition<Stand>(); } }; struct Stand : BaseState { virtual Transition GetTransition() { if (Owner().mOpenDoor) { Owner().mOpenDoor = false; return SiblingTransition<OpenDoor>(); } return NoTransition(); } }; struct OpenDoor : BaseState { virtual Transition GetTransition() { if (IsInInnerState<OpenDoor_Done>()) return SiblingTransition<Stand>(); return InnerEntryTransition<OpenDoor_GetIntoPosition>(); } }; struct OpenDoor_GetIntoPosition : BaseState { bool IsInPosition() const { return true; } // Stub virtual Transition GetTransition() { if (IsInPosition()) return SiblingTransition<OpenDoor_PlayOpenAnim>(); return NoTransition(); } }; struct OpenDoor_PlayOpenAnim : BaseState { bool IsAnimDone() const { return true; } // Stub virtual Transition GetTransition() { if (IsAnimDone()) return SiblingTransition<OpenDoor_Done>(); return NoTransition(); } }; struct OpenDoor_Done : BaseState { }; }; Character::Character() : mOpenDoor(false) { mStateMachine.Initialize<CharacterStates::Alive>(this); mStateMachine.SetDebugInfo("TestHsm", TraceLevel::Basic); } void Character::Update() { printf(">>> Character::Update\n"); // Update state machine mStateMachine.ProcessStateTransitions(); mStateMachine.UpdateStates(); } int main() { Character character; character.Update(); character.mOpenDoor = true; character.Update(); }
Add more testing for -Wc++0x-compat warnings.
// RUN: %clang_cc1 -fsyntax-only -std=c++98 -Wc++0x-compat -verify %s namespace N { template<typename T> void f(T) {} // expected-note {{here}} namespace M { template void f<int>(int); // expected-warning {{explicit instantiation of 'N::f' must occur in namespace 'N'}} } } template<typename T> void f(T) {} // expected-note {{here}} namespace M { template void f<int>(int); // expected-warning {{explicit instantiation of 'f' must occur in the global namespace}} } void f() { auto int n = 0; // expected-warning {{'auto' storage class specifier is redundant and incompatible with C++0x}} } int n; struct S { char c; } s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++0x}} expected-note {{explicit cast}} t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++0x}} expected-warning {{changes value}} expected-note {{explicit cast}}
Add a test for the TLE -> WA behavior
#include <cstdio> using namespace std; // Test that if the validator says WA, that's the verdict given even if we // TLE afterwards (realistically because we tried to read from stdin and didn't // get a response we expected). int main(void) { printf("-1\n"); fflush(stdout); for (;;); }
Test for the force platform Type-4.
#include <cxxtest/TestDrive.h> #include "forceplateTest_def.h" #include <openma/instrument/forceplatetype4.h> CXXTEST_SUITE(ForcePlateType4Test) { CXXTEST_TEST(wrench) { ma::instrument::ForcePlateType4 fp("FP"); forceplatetest_fill_sample10_type4(&fp); forceplatetest_compare_wrench_at_origin(&fp, fp4dataout); }; }; CXXTEST_SUITE_REGISTRATION(ForcePlateType4Test) CXXTEST_TEST_REGISTRATION(ForcePlateType4Test, wrench)
Add missing code snippet file
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * 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. ** * Neither the name of Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] void MyMainWindow::closeEvent(QCloseEvent *event) { QSettings settings("MyCompany", "MyApp"); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); QMainWindow::closeEvent(event); } //! [0] //! [1] void MainWindow::readSettings() { QSettings settings("MyCompany", "MyApp"); restoreGeometry(settings.value("myWidget/geometry").toByteArray()); restoreState(settings.value("myWidget/windowState").toByteArray()); } //! [1]
Disable ExtensionApiTest.Idle on all platforms, since it's flaky everywhere.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // Sometimes this test fails on Linux: crbug.com/130138 #if defined(OS_LINUX) || defined(OS_CHROMEOS) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Idle) { #else IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Idle) { #endif ASSERT_TRUE(RunExtensionTest("idle")) << message_; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // This test is flaky: crbug.com/130138 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Idle) { ASSERT_TRUE(RunExtensionTest("idle")) << message_; }
Add answer for ITP 1-11 D
#include <iostream> #include <iomanip> #include <cmath> using namespace std; void calcMinkowskiDistance(const int& p, const int& numberOfData, const int* x, const int* y); void calcChebyshevDistance(const int& numberOfData, const int* x, const int* y); int main() { int numberOfData(0); cin >> numberOfData; int x[1000], y[1000]; for(int i = 0; i < numberOfData; ++i) cin >> x[i]; for(int i = 0; i < numberOfData; ++i) cin >> y[i]; calcMinkowskiDistance(1, numberOfData, x, y); calcMinkowskiDistance(2, numberOfData, x, y); calcMinkowskiDistance(3, numberOfData, x, y); calcChebyshevDistance(numberOfData, x, y); return 0; } void calcMinkowskiDistance(const int& p, const int& numberOfData, const int* x, const int* y) { double sum(0.0); for(int i = 0; i < numberOfData; ++i ) sum += pow((abs(*(x + i) - *(y + i))), (float)p); cout << fixed << setprecision(8) << pow(sum, 1.0/(float)p) << endl; } void calcChebyshevDistance(const int& numberOfData, const int* x, const int* y) { double distance(0.0); for(int i = 0; i < numberOfData; ++i ) { if(distance < abs(*(x + i) - *(y + i))) distance = abs(*(x + i) - *(y + i)); } cout << fixed << setprecision(8) << distance << endl; }
Add solution for chapter 18 test 20
#include <iostream> using namespace std; namespace primerLib { void compute() { cout << "primerLib::compute()" << endl; } // void compute(const void *p) { // cout << "primerLib::compute(const void *)" << endl; // } } void compute(int i) { cout << "::compute(int)" << endl; } void compute(double d, double d2 = 3.4) { cout << "::compute(double, double = 3.4)" << endl; } void compute(char* p1, char* p2 = 0) { cout << "::compute(char*, char* = 0)" << endl; } void f() { using primerLib::compute; compute(0); } int main() { f(); return 0; }
Add the solution to "Preorder perusal".
#include <iostream> #include <string> using namespace std; struct Node { string s; Node *left; Node *right; }; Node *new_node(string s) { Node *temp = new Node(); temp->s = s; temp->left = NULL; temp->right = NULL; return temp; } bool add_edge(Node *root, Node *father, Node *child) { if (root == NULL) { return false; } if (root->s == father->s) { if (root->left == NULL) { root->left = child; return true; } else { root->right = child; return true; } } if (!add_edge(root->left, father, child)) { return add_edge(root->right, father, child); } return true; } void pre_order(Node *root) { if (root == NULL) { return; } cout << root->s << endl; pre_order(root->left); pre_order(root->right); } int main() { int T; cin >> T; while (T--) { int k; cin >> k; string s1, s2; cin >> s1 >> s2; Node *tree = new_node(s1); Node *left = new_node(s2); tree->left = left; while (--k) { cin >> s1 >> s2; add_edge(tree, new_node(s1), new_node(s2)); } pre_order(tree); } return 0; }
Add solution to the Person with a dog problem
#include <iostream> #include <string> using namespace std; class Dog { string name; public: Dog(string _name = "") { name = _name; } void greet() { cout << "Bark, bark! I am " << name << ", a talking dog." << endl; } }; class Person { string name; int age; Dog dog; public: Person(string _name, int _age, Dog _dog) { name = _name; age = _age; dog = _dog; } void greet() { cout << "Hi! I am " << name << " and I am " << age << " years old." << endl; cout << "And this is my dog:" << endl; dog.greet(); } }; int main() { Person ivan("Ivan", 15, Dog("Johny")); ivan.greet(); return 0; }
Add an Fibonacci example to show the usage of AddTask.
#include "FixedThreadPool.h" #include <iostream> using namespace std; using namespace tpool; void InputPrompt(const unsigned int cnt) { cout << "[" << cnt << "] In: "; } unsigned int GetFibonacciNumber(const unsigned int i) { if (i < 2) { return i; } else { return GetFibonacciNumber(i - 1) + GetFibonacciNumber(i - 2); } } void OutputFibonacciNumber(const unsigned int cnt, const unsigned int i) { cout << "[" << cnt << "] Out: " << GetFibonacciNumber(i) << endl; } void SyncLoop() { unsigned int i = 0, cnt = 1; InputPrompt(cnt); while(cin >> i) { OutputFibonacciNumber(cnt, i); InputPrompt(++cnt); } } void AsyncLoop() { unsigned int i = 0, cnt = 1; LFixedThreadPool threadPool; InputPrompt(cnt); while(cin >> i) { threadPool.AddTask(boost::bind(&OutputFibonacciNumber, cnt, i)); InputPrompt(++cnt); } } int main(int argc, char *argv[]) { // SyncLoop(); AsyncLoop(); return 0; }
Add prim test for mdivide_left_tri_low
#include <stan/math/prim.hpp> #include <test/unit/math/prim/fun/expect_matrix_eq.hpp> #include <gtest/gtest.h> #define EXPECT_MATRIX_NEAR(A, B, DELTA) \ for (int i = 0; i < A.size(); i++) \ EXPECT_NEAR(A(i), B(i), DELTA); TEST(MathMatrixPrim, mdivide_left_tri_low_val) { using stan::math::mdivide_left_tri_low; stan::math::matrix_d I = Eigen::MatrixXd::Identity(2, 2); stan::math::matrix_d Ad(2, 2); Ad << 2.0, 0.0, 5.0, 7.0; expect_matrix_eq(I, mdivide_left_tri_low(Ad, Ad)); stan::math::matrix_d A_Ainv = Ad * mdivide_left_tri_low(Ad); EXPECT_MATRIX_NEAR(I, A_Ainv, 1e-15); } TEST(MathMatrixPrim, mdivide_left_tri_low_size_zero) { using stan::math::mdivide_left_tri_low; stan::math::matrix_d Ad(0, 0); stan::math::matrix_d b0(0, 2); stan::math::matrix_d I; I = mdivide_left_tri_low(Ad, Ad); EXPECT_EQ(0, I.rows()); EXPECT_EQ(0, I.cols()); I = mdivide_left_tri_low(Ad); EXPECT_EQ(0, I.rows()); EXPECT_EQ(0, I.cols()); I = mdivide_left_tri_low(Ad, b0); EXPECT_EQ(0, I.rows()); EXPECT_EQ(b0.cols(), I.cols()); }
Fix use of invalid pointer in MediaStreamAudioSource. If the source is not initiated correctly it can happen that the |audio_capturer_| is not set. MediaStreamAudioSource::DoStop will then crash.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/media_stream_audio_source.h" namespace content { MediaStreamAudioSource::MediaStreamAudioSource( int render_view_id, const StreamDeviceInfo& device_info, const SourceStoppedCallback& stop_callback, MediaStreamDependencyFactory* factory) : render_view_id_(render_view_id), factory_(factory) { SetDeviceInfo(device_info); SetStopCallback(stop_callback); } MediaStreamAudioSource::MediaStreamAudioSource() : render_view_id_(-1), factory_(NULL) { } MediaStreamAudioSource::~MediaStreamAudioSource() {} void MediaStreamAudioSource::DoStopSource() { audio_capturer_->Stop(); } void MediaStreamAudioSource::AddTrack( const blink::WebMediaStreamTrack& track, const blink::WebMediaConstraints& constraints, const ConstraintsCallback& callback) { // TODO(xians): Properly implement for audio sources. bool result = true; if (factory_ && !local_audio_source_) { result = factory_->InitializeMediaStreamAudioSource(render_view_id_, constraints, this); } callback.Run(this, result); } void MediaStreamAudioSource::RemoveTrack( const blink::WebMediaStreamTrack& track) { NOTIMPLEMENTED(); } } // namespace content
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/media_stream_audio_source.h" namespace content { MediaStreamAudioSource::MediaStreamAudioSource( int render_view_id, const StreamDeviceInfo& device_info, const SourceStoppedCallback& stop_callback, MediaStreamDependencyFactory* factory) : render_view_id_(render_view_id), factory_(factory) { SetDeviceInfo(device_info); SetStopCallback(stop_callback); } MediaStreamAudioSource::MediaStreamAudioSource() : render_view_id_(-1), factory_(NULL) { } MediaStreamAudioSource::~MediaStreamAudioSource() {} void MediaStreamAudioSource::DoStopSource() { if (audio_capturer_.get()) audio_capturer_->Stop(); } void MediaStreamAudioSource::AddTrack( const blink::WebMediaStreamTrack& track, const blink::WebMediaConstraints& constraints, const ConstraintsCallback& callback) { // TODO(xians): Properly implement for audio sources. bool result = true; if (factory_ && !local_audio_source_) { result = factory_->InitializeMediaStreamAudioSource(render_view_id_, constraints, this); } callback.Run(this, result); } void MediaStreamAudioSource::RemoveTrack( const blink::WebMediaStreamTrack& track) { NOTIMPLEMENTED(); } } // namespace content
Add Sound unit testing source.
#include "catch.hpp" #include <iostream> #include <string> #include "audio/Sound.h" const std::string sound_file = "sound.wav"; TEST_CASE("Initial value(s) in Sound", "[Sound]") { Sound* sound = new Sound(); // volume should be at max CHECK(sound->get_volume() == 100); delete sound; } TEST_CASE("Opening sound chunk", "[Sound]") { REQUIRE(SDL_Init(SDL_INIT_EVERYTHING) == 0); Sound* sound = new Sound(); REQUIRE(sound != nullptr); SECTION("once w/o close") { sound->open(sound_file); CHECK(sound->get_sound() != nullptr); } SECTION("once") { sound->open(sound_file); REQUIRE(sound->get_sound() != nullptr); sound->close(); CHECK(sound->get_sound() == nullptr); } SECTION("twice") { for(unsigned int i = 0; i < 2; i++) { sound->open(sound_file); REQUIRE(sound->get_sound() != nullptr); sound->close(); CHECK(sound->get_sound() == nullptr); } } SECTION("thrice") { for(unsigned int i = 0; i < 3; i++) { sound->open(sound_file); REQUIRE(sound->get_sound() != nullptr); sound->close(); CHECK(sound->get_sound() == nullptr); } } delete sound; SDL_Quit(); }
Implement Graph using Adjacency Matrix
#include <iostream> #include<stdlib.h> #include <string.h> using namespace std; struct Graph { int V,E; int **adj; }; Graph* createGraph(int V, int E) { Graph *G = new Graph(); if (!G) return NULL; G->V = V; G->E = E; G->adj = new int*[G->V]; //row count for (int i = 0; i < G->V; i++) //column count G->adj[i] = new int[G->V]; for (int i = 0; i < G->V; i++) for (int j = 0; j < G->V; j++) G->adj[i][j] = 0; int u, v; // 0 -> 1 // 1 -> 2 // 2 -> 3 // 2 -> 0 // 3 -> 0 for (int i = 0; i < G->E; i++) { cout<<"Enter edge from u to v: "; cin>>u>>v; G->adj[u][v] = 1; // uncomment this for undirected graph // uses symmetry to initialize //G->adj[v][u] = 1; } return G; } void print(Graph *G) { for (int u = 0; u < G->V; u++) { for (int v = 0; v < G->V; v++) { cout<<G->adj[u][v]<<" "; } cout<<endl; } } void deleteGraph(Graph *G) { if (!G || !G->adj) return; for (int i = 0; i < G->V; i++) delete [] G->adj[i]; delete [] G->adj; delete G; } int main() { Graph *G = createGraph(4, 5); print(G); deleteGraph(G); return 0; }
Add testing file to check output for declaration scopes.
class global { }; namespace n { void external_func() { class floating_func { }; } enum normal_enum {}; enum class class_enum{}; struct str_test {}; namespace m { class in_namespace { class in_class { }; void main() { class in_function { }; { class in_inner_scope { }; } } }; } }
Set max pending frames to the default instead of 1 with ubercomp.
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/gpu/delegated_compositor_output_surface.h" namespace content { DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface( int32 routing_id, uint32 output_surface_id, const scoped_refptr<ContextProviderCommandBuffer>& context_provider, scoped_ptr<cc::SoftwareOutputDevice> software) : CompositorOutputSurface(routing_id, output_surface_id, context_provider, software.Pass(), true) { capabilities_.delegated_rendering = true; capabilities_.max_frames_pending = 1; } } // namespace content
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/gpu/delegated_compositor_output_surface.h" namespace content { DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface( int32 routing_id, uint32 output_surface_id, const scoped_refptr<ContextProviderCommandBuffer>& context_provider, scoped_ptr<cc::SoftwareOutputDevice> software) : CompositorOutputSurface(routing_id, output_surface_id, context_provider, software.Pass(), true) { capabilities_.delegated_rendering = true; } } // namespace content
Add a trivial test for EventHandler
#include "mbed.h" #include "EventHandler.h" class VTest { public: int vprint(void *arg) { if (arg) { int* i = static_cast<int *>(arg); printf("Class Print Integer: %d from %p\r\n", *i, arg); } else { printf("Class Null Arg\r\n"); } return (int)(arg != 0); } }; int barevprint(void *arg) { if (arg) { int* i = static_cast<int *>(arg); printf("Bare Print Integer: %d from %p\r\n", *i, arg); } else { printf("Class Null Arg\r\n"); } return (int)(arg != 0); } int main(void) { VTest test; printf("Testing mbed Event Handler...\r\n"); int i1 = 1; int i2 = 2; EventHandler ebp(barevprint); EventHandler ecp(&test, &VTest::vprint); size_t ebsize = sizeof(ebp); size_t ecsize = sizeof(ecp); printf("sizeof(bp) = %d\r\n", ebsize); printf("sizeof(cp) = %d\r\n", ecsize); ebp.call(&i1); ecp.call(&i2); printf ("Test Complete\r\n"); while(1){__WFI();} return 0; }
Add code for regular expresions in c++.
#include <iostream> #include <iterator> #include <regex> #include <string> using namespace std; int main(){ string s = "123daniel , jajaja, lol, 234234534, I am from Earth"; regex tel("\\d{8},\\sI"); auto words_begin = sregex_iterator(s.begin(), s.end(), tel); auto words_end = sregex_iterator(); cout << "Found " << distance(words_begin, words_end)<< " words\n"; const int N = 6; for (sregex_iterator i = words_begin; i != words_end; ++i) { smatch match = *i; string match_str = match.str(); if (match_str.size() > N) { cout << " " << match_str << '\n'; } } return 0; }
Update Interview question twitter microsoft
#include <iostream> #include<algorithm> using namespace std; class interval { int start; int duration; }; bool myCompare(interval a, interval b) { return a.start<b.start; } bool conflict(interval a, int timestamp) { if(a.start <= timestamp && (a.start + a.duration >= timestamp ) ) return true; return false; } int find_first(vector<interval> Calls, int timestamp) { for(int i=Calls.size()-1; i>0 ;i--) { if(Calls[i].start <= timestamp) return i; } return -1; } int find_first_BS(vector<interval> Calls, int timestamp) { int l =0; int r = Calls.size()-1; if(Calls[0].start > timestamp) // No timestamp found return -1; if(Calls[Calls.size()-1].start <= timestamp) // All Intervals Qualify return Calls.size()-1; while(l<r) { int mid = l+(r-l)/2; if(Calls[mid].start > timestamp) // search left { r= mid - 1; } else { l = mid + 1; } } return l; } int find_overlapping_calls(vector<interval> Calls , int timestamp) { // first sort based on start time // as we know given a instant the possible conflicts would // have start time < instant and end time > instant sort(Calls.begin(),Calls.end(),myCompare); // int ix = find_first(Calls, timestamp); ---- O (n) int ix = find_first_BS(Calls, timestamp); // --- O(log n) Because Using Binary Search if(ix == -1) return 0; int count = 0; for(int i=ix; i>0; i--) { if(conflict(Calls[i], timestamp) == true) count++; } return count; } // Complexity : // No Extra Space // O(n) + O(n) ~ O(n) ---> If we use Linear Search to find the first Qualifying Ix, using the function // find_first; // O(log n) + O(n) ~ O(n) --- > If we Use Binary Search using the function find_first_BS // // Once we have the first Qualifying ix it takes linear time to go over them // But in general on an avg it will not be O(n) // So, Optimization to find the ix using Binary Search Makes sense /// ----- I think a better Performance can be achieved using interval Tree Data Structure /// But Due to time constraint I did not implement the Interval Tree
Add missing file from last commit.
/* * Copyright (C) 2011 The Android Open Source Project * * 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 "logging.h" #include "runtime.h" #include "utils.h" LogMessage::~LogMessage() { if (errno_ != -1) { buffer_ << ": " << strerror(errno_); } std::string msg(buffer_.str()); if (msg.find('\n') == std::string::npos) { LogLine(msg.c_str()); } else { msg += '\n'; size_t i = 0; while (i < msg.size()) { size_t nl = msg.find('\n', i); msg[nl] = '\0'; LogLine(&msg[i]); i = nl + 1; } } if (severity_ == FATAL) { art::Runtime::Abort(file_, line_number_); } } std::ostream& LogMessage::stream() { return buffer_; }
Add solution for chapter 17 test 35
#include <iostream> #include <cmath> using namespace std; int main() { cout << uppercase << hexfloat; cout << sqrt(2) << endl; return 0; }
Check if One String Swap Can Make Strings Equal
class Solution { public: bool areAlmostEqual(string s1, string s2) { size_t index = 0, count = 0; std::vector<size_t> arr; while (index < s1.size()) { if (s1[index] != s2[index]) { ++count; if (count > 2) return false; arr.emplace_back(index); } ++index; } if (count == 0) return true; if (count == 1) return false; if (s1[arr[0]] == s2[arr[1]] && s1[arr[1]] == s2[arr[0]]) return true; return false; } };
Use QueryPerformanceCounter on Windows instead of std::chrono::high_frequency_clock, since this has only 1ms accuracy in VS2013
//------------------------------------------------------------------------------ // Clock.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "Clock.h" #if ORYOL_EMSCRIPTEN #include <emscripten/emscripten.h> #else #include <chrono> #endif namespace Oryol { namespace Time { //------------------------------------------------------------------------------ TimePoint Clock::Now() { #if ORYOL_EMSCRIPTEN // get int64 time in nanosecs (emscripten_now is ms) int64 t = int64(emscripten_get_now() * 1000 * 1000); #else using namespace std; chrono::time_point<chrono::high_resolution_clock, chrono::nanoseconds> now = chrono::high_resolution_clock::now(); int64 t = now.time_since_epoch().count(); #endif return TimePoint(t); } } // namespace Clock } // namespace Oryol
//------------------------------------------------------------------------------ // Clock.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "Clock.h" #if ORYOL_EMSCRIPTEN #include <emscripten/emscripten.h> #elif ORYOL_WINDOWS #include <Windows.h> #include <atomic> #else #include <chrono> #endif namespace Oryol { namespace Time { //------------------------------------------------------------------------------ TimePoint Clock::Now() { #if ORYOL_EMSCRIPTEN // get int64 time in nanosecs (emscripten_now is ms) int64 t = int64(emscripten_get_now() * 1000 * 1000); #elif ORYOL_WINDOWS // VisualStudio2013's chrono::high_resolution_clock isn't actually high_resolution LARGE_INTEGER perfCount; static LARGE_INTEGER perfFreq; static std::atomic_flag perfFreqValid{ false }; if (!perfFreqValid.test_and_set()) { QueryPerformanceFrequency(&perfFreq); } QueryPerformanceCounter(&perfCount); int64 t = (perfCount.QuadPart * 1000000000) / perfFreq.QuadPart; #else using namespace std; chrono::time_point<chrono::high_resolution_clock, chrono::nanoseconds> now = chrono::high_resolution_clock::now(); int64 t = now.time_since_epoch().count(); #endif return TimePoint(t); } } // namespace Clock } // namespace Oryol
Add missing test from r163874.
// RUN: %clang_cc1 -verify -Wunused -Wused-but-marked-unused -fsyntax-only %s namespace ns_unused { typedef int Int_unused __attribute__((unused)); } namespace ns_not_unused { typedef int Int_not_unused; } void f() { ns_not_unused::Int_not_unused i1; // expected-warning {{unused variable}} ns_unused::Int_unused i0; // expected-warning {{'Int_unused' was marked unused but was used}} }
Add Solution for 237 Delete Node in a Linked List
// 237. Delete Node in a Linked List /** * Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. * * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 * after calling your function. * * Tags: Linked List * * Similar Problems: (E) Remove Linked List Elements * * Author: Kuang Qin */ #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *p) : val(x), next(p) {} }; class Solution { public: void deleteNode(ListNode* node) { *node = *(node->next); // equivalent to copy the values: // node->val = node->next->val; // node->next = node->next->next; return; } }; int main() { ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2); Solution sol; sol.deleteNode(&node3); for (ListNode *p = &node1; p != NULL; p = p->next) { cout << p->val << " "; } cout << endl; cin.get(); return 0; }
Add error test for func wrapper
#include "Halide.h" using namespace Halide; using namespace Halide::Internal; int main() { Var x("x"), y("y"); Func f("f"), g("g"), h("h"); f(x, y) = x + y; g(x, y) = 5; h(x, y) = f(x, y) + g(x, y); f.compute_root(); f.in(g).compute_root(); // This should cause an error since f.in(g) was called but 'f' is // never used in 'g'. h.realize(5, 5); return 0; }
Add some tests for worker thread implementation
// Copyright 2012-2013 Samplecount S.L. // // 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. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-private-field" #define CATCH_CONFIG_MAIN #include <catch.hpp> #pragma GCC diagnostic pop #include "Methcla/Utility/MessageQueue.hpp" #include "Methcla/Utility/Semaphore.hpp" #include <atomic> TEST_CASE("Methcla/Utility/Worker", "Check for queue overflow.") { struct Command { void perform() { } }; const size_t queueSize = 1024; Methcla::Utility::Worker<Command> worker(queueSize); for (size_t i=0; i < worker.maxCapacity(); i++) { worker.sendToWorker(Command()); } REQUIRE_THROWS(worker.sendToWorker(Command())); } TEST_CASE("Methcla/Utility/WorkerThread", "Check that all commands pushed to a worker thread are executed.") { struct Command { void perform() { (*m_count)++; m_sem->post(); } std::atomic<size_t>* m_count; Methcla::Utility::Semaphore* m_sem; }; const size_t queueSize = 1024; for (size_t threadCount=1; threadCount <= 4; threadCount++) { Methcla::Utility::WorkerThread<Command> worker(queueSize, threadCount); std::atomic<size_t> count(0); Methcla::Utility::Semaphore sem; for (size_t i=0; i < worker.maxCapacity(); i++) { Command cmd; cmd.m_count = &count; cmd.m_sem = &sem; worker.sendToWorker(cmd); } for (size_t i=0; i < worker.maxCapacity(); i++) { sem.wait(); } REQUIRE(count.load() == worker.maxCapacity()); } }
Add the solution to "Lego Blocks".
#include <iostream> #include <cstring> #define MODULO 1000000007 #define MAX 1001 using namespace std; long long mod_add(long long x, long long y) { return (x + y) % MODULO; } long long mod_sub(long long x, long long y) { return (x - y + MODULO) % MODULO; } long long mod_mult(long long x, long long y) { return (x * y) % MODULO; } long long solve(int n, int m) { long long single_row[MAX]; memset(single_row, 0, sizeof(single_row)); single_row[1] = 1; single_row[2] = 2; single_row[3] = 4; single_row[4] = 8; for (int i = 5; i <= m; i++) { for (int j = 1; j <= 4; j++) { single_row[i] = mod_add(single_row[i], single_row[i - j]); } } long long raw_result[MAX]; for (int i = 1; i <= m; i++) { long long res = 1; for (int j = 1; j <= n; j++) { res = mod_mult(res, single_row[i]); } raw_result[i] = res; } long long result_with_holes[MAX]; long long final_result[MAX]; final_result[1] = raw_result[1]; for (int i = 2; i <= m; i++) { final_result[i] = raw_result[i]; for (int j = 1; j <= i - 1; j++) { final_result[i] = mod_sub(final_result[i], mod_mult(final_result[j], raw_result[i - j])); } } return final_result[m]; } int main() { int T; cin >> T; while (T--) { int n, m; cin >> n >> m; cout << solve(n, m) << endl; } return 0; }
Add Chapter 27, exercise 8
// Chapter 27, exercise 8: write out every character on your keyboard together // with its integer value; then, write the characters out in the order deter- // mined by their integer value #include<iostream> #include<string> #include<algorithm> using namespace std; void print(const string& s) { for (int i = 0; i<s.size(); ++i) cout << '\'' << s[i] << "\': " << (int)unsigned char(s[i]) << '\n'; } bool comp_char(char a, char b) { return unsigned char(a) < unsigned char(b); } int main() { string s = R"(+"*%&/()=?`1234567890'^@#|~![]${}><\;:_,.-)"; s += "QWERTZUIOPASDFGHJKLYXCVBNMqwertzuiopasdfghjklyxcvbnm"; print(s); sort(s.begin(),s.end(),comp_char); cout << "\nAnd sorted:\n"; print(s); }
Add alternative game, you know
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <random> static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dist(5, 30); static std::uniform_int_distribution<> negator(0, 1); static std::uniform_int_distribution<> dir(1, 15); struct animal { private: int answer; public: animal(): answer(dist(gen)) { /*std::cout << answer << '\n';*/ } bool guess(int g) const { if(g >= answer) { std::cout << "Caught one!\n"; return true; } return false; } }; struct player { private: const unsigned max_animals = 20; std::vector<animal> animals{max_animals}; int answer = 0; int up = dir(gen); int down = dir(gen); int left = dir(gen); int right = dir(gen); public: player() = default; void guess() { // get command std::string temp; std::cin >> temp; // update total if(temp == "up") { answer += negator(gen) ? -up : up; } else if(temp == "down") { answer += negator(gen) ? -down : down; } else if(temp == "right") { answer += negator(gen) ? -right : right; } else if(temp == "left") { answer += negator(gen) ? -left : left; } if(answer < 0) { answer = 0; } // refresh command values up = dir(gen); down = dir(gen); left = dir(gen); right = dir(gen); // herd the animals guessed correctly animals.erase(std::remove_if(std::begin(animals), std::end(animals), [this](const animal& x) { return x.guess(answer); }), std::end(animals)); } void status() { std::cout << "[" << max_animals - animals.size() << "/" << max_animals << "] animals herded" << std::endl; } bool won() { return animals.empty(); } }; int main() { player p; std::cout << "The animals have escaped! Try to herd them using the four directions:\n"; std::cout << "- up\n" "- down\n" "- left\n" "- right\n"; while(true) { p.guess(); p.status(); if(p.won()) { std::cout << "You win!\n"; return 0; } } }
Add test case for PR6141, which was fixed a few days ago
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s | FileCheck %s // PR6141 template<typename T> struct X { X(); template<typename U> X(X<U>); X(const X<T>&); }; void f(X<int>) { } struct Y : X<int> { }; struct Z : X<float> { }; // CHECK: define i32 @main() int main() { // CHECK: call void @_ZN1YC1Ev // CHECK: call void @_ZN1XIiEC1ERKS0_ // CHECK: call void @_Z1f1XIiE f(Y()); // CHECK: call void @_ZN1ZC1Ev // CHECK: call void @_ZN1XIfEC1ERKS0_ // CHECK: call void @_ZN1XIiEC1IfEES_IT_E // CHECK: call void @_Z1f1XIiE f(Z()); }
Add test file for tcpserver
#include <gtest/gtest.h> #include "tcpserver.hpp" using namespace OpenSofa; namespace { TEST(TCPServerTest, CanBeCreated) { Server * server = new TCPServer(); delete server; } }
Build first-party C++ deps of OSS React Native with Buck
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #ifndef __ANDROID__ #error "This file should only be compiled for Android." #endif #include <jni/fbjni/References.h> #include <jni/fbjni/CoreClasses.h> namespace facebook { namespace jni { namespace internal { static int32_t getApiLevel() { auto cls = findClassLocal("android/os/Build$VERSION"); auto fld = cls->getStaticField<int32_t>("SDK_INT"); if (fld) { return cls->getStaticFieldValue(fld); } return 0; } bool doesGetObjectRefTypeWork() { static auto level = getApiLevel(); return level >= 14; } } } }
Add variadic template arguments example in c++17.
#include <iostream> void foo() { std::cout << __PRETTY_FUNCTION__ << "\n"; std::cout << " "; } template <typename Arg> void foo(Arg arg) { std::cout << __PRETTY_FUNCTION__ << "\n"; std::cout << arg << " "; } template <typename First, typename... Args> void foo(First first, Args... args) { std::cout << __PRETTY_FUNCTION__ << "\n"; foo(first); foo(args...); } int main() { std::string one = "One"; const char* two = "Two"; float three = 3.33333333; foo(); std::cout << std::endl; foo(one, two); std::cout << std::endl; foo(one, two, three); std::cout << std::endl; foo(1, 2, three, 4, 5.7, 6/2, "lalalala"); return 0; }
Prepare test case for dbn_fast
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "dll/conv_layer.hpp" #include "dll/dense_layer.hpp" #include "dll/conv_rbm.hpp" #include "dll/dbn.hpp" #include "dll/scale_layer.hpp" #include "dll/mp_layer.hpp" #include "dll/avgp_layer.hpp" #include "dll/stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE("fast/cdbn/sgd/1", "[dbn][mnist][sgd]") { typedef dll::dbn_desc< dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 10, 12, dll::momentum, dll::batch_size<10>, dll::weight_type<float>>::layer_t, dll::rbm_desc<12 * 12 * 10, 10, dll::momentum, dll::batch_size<10>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); //dbn->pretrain(dataset.training_images, 20); //auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50); //std::cout << "ft_error:" << ft_error << std::endl; //CHECK(ft_error < 5e-2); //auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); //std::cout << "test_error:" << test_error << std::endl; //REQUIRE(test_error < 0.2); }
Fix bug in __libcpp_db::__iterator_copy. Add debug test for swaping lists.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <list> // template <class T, class Alloc> // void swap(list<T,Alloc>& x, list<T,Alloc>& y); #if _LIBCPP_DEBUG2 >= 1 #define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0)) #endif #include <list> #include <cassert> #include <__debug> int main() { #if _LIBCPP_DEBUG2 >= 1 { int a1[] = {1, 3, 7, 9, 10}; int a2[] = {0, 2, 4, 5, 6, 8, 11}; std::list<int> c1(a1, a1+sizeof(a1)/sizeof(a1[0])); std::list<int> c2(a2, a2+sizeof(a2)/sizeof(a2[0])); std::list<int>::iterator i1 = c1.begin(); std::list<int>::iterator i2 = c2.begin(); swap(c1, c2); c1.erase(i2); c2.erase(i1); std::list<int>::iterator j = i1; c1.erase(i1); assert(false); } #endif }
Use \r in messages so they look decent in serial output.
#include "listener.h" #include "log.h" #include "buffers.h" void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message, int messageSize) { if(queue_available(queue) < messageSize + 1) { debug("Dropped incoming CAN message -- send queue full\r\n"); return; } for(int i = 0; i < messageSize; i++) { QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]); } QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n'); } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { // TODO the more we enqueue here, the slower it gets - cuts the rate by // almost half to do it with 2 queues. we could either figure out how to // share a queue or make the enqueue function faster. right now I believe it // enqueues byte by byte, which could obviously be improved. if(listener->usb->configured) { conditionalEnqueue(&listener->usb->sendQueue, message, messageSize); } else { conditionalEnqueue(&listener->serial->sendQueue, message, messageSize); } } void processListenerQueues(Listener* listener) { // Must always process USB, because this function usually runs the MCU's USB // task that handles SETUP and enumeration. processInputQueue(listener->usb); if(!listener->usb->configured) { processInputQueue(listener->serial); } }
#include "listener.h" #include "log.h" #include "buffers.h" void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message, int messageSize) { if(queue_available(queue) < messageSize + 2) { debug("Dropped incoming CAN message -- send queue full\r\n"); return; } for(int i = 0; i < messageSize; i++) { QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]); } QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r'); QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n'); } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { // TODO the more we enqueue here, the slower it gets - cuts the rate by // almost half to do it with 2 queues. we could either figure out how to // share a queue or make the enqueue function faster. right now I believe it // enqueues byte by byte, which could obviously be improved. if(listener->usb->configured) { conditionalEnqueue(&listener->usb->sendQueue, message, messageSize); } else { conditionalEnqueue(&listener->serial->sendQueue, message, messageSize); } } void processListenerQueues(Listener* listener) { // Must always process USB, because this function usually runs the MCU's USB // task that handles SETUP and enumeration. processInputQueue(listener->usb); if(!listener->usb->configured) { processInputQueue(listener->serial); } }
Fix glitch with Clang and boost
//======================================================================= // Copyright Baptiste Wicht 2011-2013. // 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> namespace boost { void throw_exception(std::exception const & e){ throw e; } } // namespace boost
Add command to test timer (to be deleted on next commit)
#include "command.h" #include "timer.h" #include <ctime> #include <unistd.h> using namespace MR; using namespace App; void usage () { DESCRIPTION + "test timer interface"; REQUIRES_AT_LEAST_ONE_ARGUMENT = false; } void run () { Timer timer; CONSOLE ("printing Timer::current_time() at 10ms intervals:"); for (size_t n = 0; n < 10; ++n) { CONSOLE (" current timestamp: " + str(Timer::current_time(), 16) + " (from C time(): " + str(time(NULL)) + ")"); usleep (10000); } CONSOLE ("execution took " + str(timer.elapsed()) + " seconds"); timer.start(); CONSOLE ("testing IntervalTimer with 10 x 0.2s intervals:"); IntervalTimer itimer (0.2); for (size_t n = 0; n < 10; ++n) { while (!itimer); CONSOLE (" tick"); } CONSOLE ("execution took " + str(timer.elapsed()) + " seconds"); }
Add Chapter 21, exercise 6
// Chapter 21, Exercise 6: implement the Fruit example (set) using a // set<Fruit*,Fruit_comparison> (pointers instead of copies), i.e., define a // comparison operation for Fruit* #include "../lib_files/std_lib_facilities.h" #include<set> //------------------------------------------------------------------------------ struct Fruit { string name; int count; double unit_price; Fruit(string n, int c, double up = 0.0) :name(n), count(c), unit_price(up) { } }; //------------------------------------------------------------------------------ ostream& operator<<(ostream& os, const Fruit* f) { os << setw(7) << left << f->name; os << f->count << '\t' << f->unit_price; return os; } //------------------------------------------------------------------------------ struct Fruit_comparison { bool operator()(const Fruit* a, const Fruit* b) const { return a->name < b->name; } }; //------------------------------------------------------------------------------ int main() try { set<Fruit*,Fruit_comparison> inventory; inventory.insert(new Fruit("Quince",5)); // test default parameter inventory.insert(new Fruit("Apple",200,0.37)); inventory.insert(new Fruit("Orange",150,0.45)); inventory.insert(new Fruit("Grape",13,0.99)); inventory.insert(new Fruit("Kiwi",512,1.15)); inventory.insert(new Fruit("Plum",750,2.33)); typedef set<Fruit*,Fruit_comparison>::const_iterator Si; for (Si p = inventory.begin(); p!=inventory.end(); ++p) cout << *p << '\n'; // Clean up for (Si p = inventory.begin(); p!=inventory.end(); ++p) delete *p; } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; } //------------------------------------------------------------------------------
Print Left View of the tree.
#include <stdio.h> typedef struct _NODE { int data; _NODE* left; _NODE* right; } NODE; NODE* newNode(int data) { NODE* node = new NODE(); node->data = data; node->left = nullptr; node->right = nullptr; return node; } void leftViewUtil(NODE* root, int level, int* max_level) { if (root == nullptr) return; printf("level : [%d] max_level : [%d] \n", level, *max_level); if (*max_level < level) { printf("%d \n", root->data); *max_level = level; } leftViewUtil(root->left, level + 1, max_level); leftViewUtil(root->right, level + 1, max_level); } void leftView(NODE* root) { int max_level = 0; leftViewUtil(root, 1, &max_level); } int main(int argc, char const* argv[]) { NODE* root = newNode(12); root->left = newNode(10); root->right = newNode(30); root->right->left = newNode(25); root->right->right = newNode(40); leftView(root); return 0; }
Add small test program for base64 decoding.
#include "base64inputstream.h" #include <stdio.h> using namespace jstreams; using namespace std; int main(int argc, char** argv) { for (int i=1; i<argc; ++i) { string out = Base64InputStream::decode(argv[i], strlen(argv[i])); printf("%s\n", out.c_str()); } return 0; }
Add queue implemented with 2 stacks
#include <iostream> #include <stack> using std::cout; using std::endl; using std::stack; class Queue { stack<int> stackIn, stackOut; void transfer() { while (!stackIn.empty()) { stackOut.push(stackIn.top()); stackIn.pop(); } } public: bool empty() { return stackIn.empty() && stackOut.empty(); } int front() { if (stackOut.empty()) { transfer(); } return stackOut.top(); } void pop() { if (stackOut.empty()) { transfer(); } stackOut.pop(); } void push(int n) { stackIn.push(n); } }; int main() { Queue q; q.push(1); q.push(2); cout << q.front() << endl; q.pop(); q.push(3); cout << q.front() << endl; q.pop(); q.push(4); q.push(5); q.push(6); cout << q.front() << endl; q.pop(); cout << q.front() << endl; q.pop(); cout << q.front() << endl; q.pop(); cout << q.front() << endl; q.pop(); return 0; }
Add 141 Linked List Cycle
// 141 Linked List Cycle /** * Given a linked list, determine if it has a cycle in it. * * Follow up: * Can you solve it without using extra space? * * Tag: Linked List, Two Pointers * * Author: Yanbin Lu */ #include <stddef.h> #include <vector> #include <string.h> #include <stdio.h> #include <algorithm> #include <iostream> #include <map> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool hasCycle(ListNode *head) { ListNode* slow = head; ListNode* fast = head; while(fast && fast->next){ fast = fast->next->next; slow = slow->next; if(fast == slow) return true; } return false; } }; int main() { // creat a cycle list ListNode* list = new ListNode(3); list->next = new ListNode(2); list->next->next = new ListNode(1); list->next->next->next = new ListNode(4); list->next->next->next->next = list; Solution* sol = new Solution(); cout<<sol->hasCycle(list)<<std::endl; char c; std::cin>>c; return 0; }
Add a test that makes sure coverage works at least in the simple cases
// RUN: rm -rf %T/coverage-basic // RUN: mkdir %T/coverage-basic && cd %T/coverage-basic // RUN: %clangxx_asan -fsanitize-coverage=1 %s -o test.exe // RUN: env ASAN_OPTIONS=coverage=1 %run test.exe // // RUN: %sancov print *.sancov | FileCheck %s #include <stdio.h> void foo() { fprintf(stderr, "FOO\n"); } void bar() { fprintf(stderr, "BAR\n"); } int main(int argc, char **argv) { if (argc == 2) { foo(); bar(); } else { bar(); foo(); } } // CHECK: 0x{{[0-9a-f]*}} // CHECK: 0x{{[0-9a-f]*}} // CHECK: 0x{{[0-9a-f]*}} // CHECK-NOT: 0x{{[0-9a-f]*}}
Copy List with Random Pointer
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { if (!head) return nullptr; Node* temp = head; while (temp) { Node *node = new Node(temp->val); node->next = temp->next; temp->next = node; temp = node->next; } temp = head; while (temp) { temp->next->random = (temp->random) ? temp->random->next : nullptr; temp = temp->next->next; } Node* dummy = head->next; temp = head->next; while (head) { head->next = temp->next; head = head->next; if (!head) break; temp->next = head->next; temp = temp->next; } return dummy; } };