Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use more powerfull complex type
#include "parserPrivate.h" complexType getNumber(std::string string, bool negative, bool &a) { complexType complex; char haveI = 0; size_t size = string.size(); double value; if(string.at(0) == 'i') { haveI++; string.erase(0, 1); size--; } if(string.at(size-1) == 'i') { haveI++; string.erase(size-1, 1); size--; } if(string.at(0) == '[') { value = 0; } else value = atof(string.c_str()); if(haveI == 1) complex.isComplex = true; else { complex.isComplex = false; if(haveI == 2) value *= -1; } if(negative) value *= -1; complex.coefficient = value; return complex; }
#include "parserPrivate.h" complexType getNumber(std::string string, bool negative, bool &a) { complexType complex; size_t size = string.size(); double value; char haveI = 0; bool isComplex; if(string.at(0) == 'i') { haveI++; string.erase(0, 1); size--; } if(string.at(size-1) == 'i') { haveI++; string.erase(size-1, 1); size--; } if(string.at(0) == '[') { value = 0; } else value = atof(string.c_str()); if(negative) value *= -1; if(haveI == 1) isComplex = true; else { isComplex = false; if(haveI == 2) value *= -1; } if(isComplex) complex.coefComplex = value; else complex.coefReal = value; return complex; } bool isOperator
Add a test of array initialization
#include <iostream> #include <gtest/gtest.h> TEST(sizeof, test1) { char str1[10]; char str2[] = "Hello World!"; EXPECT_EQ(10, sizeof(str1)); EXPECT_EQ(13, sizeof(str2)); } TEST(memcpy, test1) { int a[] = {1, 2, 3}; int b[3]; memcpy(b, a, sizeof(int) * 3); EXPECT_EQ(1, b[0]); EXPECT_EQ(2, b[1]); EXPECT_EQ(3, b[2]); } TEST(swap, test1) { int a = 1; int b = 2; std::swap(a, b); EXPECT_EQ(2, a); EXPECT_EQ(1, b); }
#include <iostream> #include <gtest/gtest.h> TEST(sizeof, test1) { char str1[10]; char str2[] = "Hello World!"; EXPECT_EQ(10, sizeof(str1)); EXPECT_EQ(13, sizeof(str2)); } TEST(memcpy, test1) { int a[] = {1, 2, 3}; int b[3]; memcpy(b, a, sizeof(int) * 3); EXPECT_EQ(1, b[0]); EXPECT_EQ(2, b[1]); EXPECT_EQ(3, b[2]); } TEST(swap, test1) { int a = 1; int b = 2; std::swap(a, b); EXPECT_EQ(2, a); EXPECT_EQ(1, b); } TEST(array, test1) { int foo[2] = {1}; EXPECT_EQ(1, foo[0]); EXPECT_EQ(0, foo[1]); }
Add descriptory comment to specimen4 example
// #include <stdio.h> int main() { int n; scanf("%d", &n); int *A = new int[n]; for (int i = 0; i < n; ++i) { scanf("%d", &A[i]); } int sum = 0; int i = 0; L0: if (A[i] % 2 == 0) { left0: sum += A[i]; } else { right0: sum -= A[i]; } printf("%d", sum); if (A[i] % 2 == 0) { sum += A[i]; if (++i < n) { goto left0; } } else { sum -= A[i]; if (++i < n) { goto right0; } } printf("%d\n", sum); delete[] A; }
// Let's call this CFG the 'butterfly'. // It looks like this: // // A // ,. / \,-, // | B1 B2 | // | \ / | // | C | // | / \ | // | D1 D2 | // `-`\ /`-` // E // // Where the edges between B1-D1 and B2-D2 are actually 'back-edges' which is to // say the direction is from D1 to B1 and from D2 to B2 (illustrated by edges // always leaving from the bottom of a node and entering through the top). #include <stdio.h> int main() { int n; scanf("%d", &n); int *A = new int[n]; for (int i = 0; i < n; ++i) { scanf("%d", &A[i]); } int sum = 0; int i = 0; A: if (A[i] % 2 == 0) { B1: sum += A[i]; } else { B2: sum -= A[i]; } C: if (A[i] % 2 == 0) { D1: sum += A[i]; if (++i < n) { goto B1; } } else { D2: sum -= A[i]; if (++i < n) { goto B2; } } E: printf("%d\n", sum); delete[] A; }
Use correct pair type order in map::emplace test
#include <map> int main() { typedef std::map<int, int> ContainerType; typedef std::pair<bool, ContainerType::iterator> EmplaceReturnType; ContainerType m; // pair move constructor EmplaceReturnType aResult = m.emplace(std::make_pair(int(1), int(2))); bool aValid = (aResult.first) && ((*(aResult.second)).second == 2); // pair converting move constructor EmplaceReturnType bResult = m.emplace(std::make_pair(2, 4)); bool bValid = (bResult.first) && ((*(bResult.second)).second == 4); // pair template constructor EmplaceReturnType cResult = m.emplace(3, 6); bool cValid = (cResult.first) && ((*(cResult.second)).second == 6); return (aValid && bValid && cValid) ? 0 : 1; }
#include <map> #include <iostream> int main() { typedef std::map<int, int> ContainerType; typedef std::pair<ContainerType::iterator, bool> EmplaceReturnType; ContainerType m; // pair move constructor EmplaceReturnType aResult = m.emplace(std::make_pair(int(1), int(2))); bool aValid = (aResult.second) && ((*(aResult.first)).second == 2); // pair converting move constructor EmplaceReturnType bResult = m.emplace(std::make_pair(2, 4)); bool bValid = (bResult.second) && ((*(bResult.first)).second == 4); // pair template constructor EmplaceReturnType cResult = m.emplace(3, 6); bool cValid = (cResult.second) && ((*(cResult.first)).second == 6); return (aValid && bValid && cValid) ? 0 : 1; }
Set error upload rate to 0.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { static const double kErrorUploadRatio = 0.15; void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // We only want to upload |kErrorUploadRatio| ratio of errors. if (kErrorUploadRatio <= 0.0) return; // We are not allowed to upload errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { static const double kErrorUploadRatio = 0.0; void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // We only want to upload |kErrorUploadRatio| ratio of errors. if (kErrorUploadRatio <= 0.0) return; // We are not allowed to upload errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync
Test disabled colorizer on Windows
#ifndef _WIN32 #include <specs/specs.h> go_bandit([]() { describe("colorizer: ", [&]() { describe("colors enabled", [&]() { bandit::detail::colorizer colorizer; it("can set color to green", [&]() { AssertThat(colorizer.green(), Equals("\033[1;32m")); }); it("set color to red", [&]() { AssertThat(colorizer.red(), Equals("\033[1;31m")); }); it("resets color", [&]() { AssertThat(colorizer.reset(), Equals("\033[0m")); }); }); describe("colors disabled", [&]() { bandit::detail::colorizer colorizer(false); it("ignores setting color to green", [&]() { AssertThat(colorizer.green(), Equals("")); }); it("ignores setting color to red", [&]() { AssertThat(colorizer.red(), Equals("")); }); it("ignores resetting colors", [&]() { AssertThat(colorizer.reset(), Equals("")); }); }); }); }); #endif
#include <specs/specs.h> go_bandit([]() { describe("colorizer: ", [&]() { #if !defined(_WIN32) || defined(BANDIT_CONFIG_COLOR_ANSI) describe("colors enabled", [&]() { bandit::detail::colorizer colorizer; it("can set color to green", [&]() { AssertThat(colorizer.green(), Equals("\033[1;32m")); }); it("set color to red", [&]() { AssertThat(colorizer.red(), Equals("\033[1;31m")); }); it("resets color", [&]() { AssertThat(colorizer.reset(), Equals("\033[0m")); }); }); #endif describe("colors disabled", [&]() { bandit::detail::colorizer colorizer(false); it("ignores setting color to green", [&]() { AssertThat(colorizer.green(), Equals("")); }); it("ignores setting color to red", [&]() { AssertThat(colorizer.red(), Equals("")); }); it("ignores resetting colors", [&]() { AssertThat(colorizer.reset(), Equals("")); }); }); }); });
Remove output_spontaneous use for now.
#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_encoder_pipe.h> XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec) : PipeSimple("/xcodec/encoder/pipe"), encoder_(codec) { encoder_.set_pipe(this); } XCodecEncoderPipe::~XCodecEncoderPipe() { encoder_.set_pipe(NULL); } void XCodecEncoderPipe::output_ready(void) { PipeSimple::output_spontaneous(); } bool XCodecEncoderPipe::process(Buffer *out, Buffer *in) { encoder_.encode(out, in); return (true); }
#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_encoder_pipe.h> XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec) : PipeSimple("/xcodec/encoder/pipe"), encoder_(codec) { encoder_.set_pipe(this); } XCodecEncoderPipe::~XCodecEncoderPipe() { encoder_.set_pipe(NULL); } void XCodecEncoderPipe::output_ready(void) { } bool XCodecEncoderPipe::process(Buffer *out, Buffer *in) { encoder_.encode(out, in); return (true); }
Move gyro to class scope.
#include <chrono> #include <iostream> #include <thread> #include "AHRS.h" #include "WPILib.h" /* * This program is used to measure the frequency of NavX errors. * * It prints a stream of millisecond timestamps corresponding to the last good * sensor read. Any errors noted by the NavX library are printed to standard * output and are interleaved with the timestamps. * * Excessive SPI errors have been noted while running this when * /etc/init.d/nilvrt is running so run `/etc/init.d/nilvrt stop` first. * * TIMESTAMP_PERIOD_MS = how often a timestamp is printed to standard output * LOOP_SLEEP_MS = run loop wait period */ static constexpr double TIMESTAMP_PERIOD_MS = 10 / 1000; static constexpr auto LOOP_SLEEP_MS = std::chrono::milliseconds(1); class Robot : public SampleRobot { public: void OperatorControl() { AHRS gyro{SPI::Port::kMXP}; frc::Timer timer; timer.Start(); while (IsEnabled()) { if (timer.HasPeriodPassed(TIMESTAMP_PERIOD_MS)) { std::cout << gyro.GetLastSensorTimestamp() << std::endl; } std::this_thread::sleep_for(LOOP_SLEEP_MS); } } void RobotInit() {} void Disabled() { while (IsDisabled()) { std::this_thread::sleep_for(LOOP_SLEEP_MS); } } }; START_ROBOT_CLASS(Robot)
#include <chrono> #include <iostream> #include <thread> #include "AHRS.h" #include "WPILib.h" /* * This program is used to measure the frequency of NavX errors. * * It prints a stream of millisecond timestamps corresponding to the last good * sensor read. Any errors noted by the NavX library are printed to standard * output and are interleaved with the timestamps. * * Excessive SPI errors have been noted while running this when * /etc/init.d/nilvrt is running so run `/etc/init.d/nilvrt stop` first. * * TIMESTAMP_PERIOD_MS = how often a timestamp is printed to standard output * LOOP_SLEEP_MS = run loop wait period */ static constexpr double TIMESTAMP_PERIOD_MS = 10 / 1000; static constexpr auto LOOP_SLEEP_MS = std::chrono::milliseconds(1); class Robot : public SampleRobot { public: AHRS gyro{SPI::Port::kMXP}; void OperatorControl() { frc::Timer timer; timer.Start(); while (IsEnabled()) { if (timer.HasPeriodPassed(TIMESTAMP_PERIOD_MS)) { std::cout << gyro.GetLastSensorTimestamp() << std::endl; } std::this_thread::sleep_for(LOOP_SLEEP_MS); } } void RobotInit() {} void Disabled() { while (IsDisabled()) { std::this_thread::sleep_for(LOOP_SLEEP_MS); } } }; START_ROBOT_CLASS(Robot)
Use new signals (again) + fix list/dict
#include "views.h" using namespace std; namespace rviews { void login(JsonValue * message, ServerHandler * handler) { JsonDict * dictMessage = JDICT(message); if (dictMessage == NULL) { throw BadRequest("Malformatted request. Need a JSON dict"); } bool success = getBool(dictMessage, "success"); if(success){ emit handler->getWindow()->loginSuccess(); } else { emit handler->getWindow()->loginFailure(getInt(dictMessage, "code")); } } void signup(JsonValue * message, ServerHandler * handler) { JsonDict * dictMessage = JDICT(message); if (dictMessage == NULL) { throw BadRequest("Malformatted request. Need a JSON dict"); } bool success = getBool(dictMessage, "success"); if(success){ emit handler->getWindow()->registerSuccess(); } else { emit handler->getWindow()->registerFailure(getInt(dictMessage, "code")); } } void userlist(JsonValue * message, ServerHandler * handler) { JsonDict * listMessage = JLIST(message); if (listMessage == NULL) { throw BadRequest("Malformatted request. Need a JSON list"); } JsonList * jlist = getList(dictMessage, "userlist"); vector<string> ulist; for(int i = 0; i < jlist->size(); i++){ ulist.push_back(getString(jlist, i)); } emit handler->getWindow()->refreshRegisterList(ulist); }
#include "views.h" using namespace std; namespace rviews { void login(JsonValue * message, ServerHandler * handler) { JsonDict * dictMessage = JDICT(message); if (dictMessage == NULL) { throw BadRequest("Malformatted request. Need a JSON dict"); } bool success = getBool(dictMessage, "success"); if(success){ emit handler->getWindow()->loginSuccess(); } else { emit handler->getWindow()->loginFailure(getInt(dictMessage, "code")); } } void signup(JsonValue * message, ServerHandler * handler) { JsonDict * dictMessage = JDICT(message); if (dictMessage == NULL) { throw BadRequest("Malformatted request. Need a JSON dict"); } bool success = getBool(dictMessage, "success"); if(success){ emit handler->getWindow()->registerSuccess(); } else { emit handler->getWindow()->registerFailure(getInt(dictMessage, "code")); } } void userlist(JsonValue * message, ServerHandler * handler) { JsonDict * dictMessage = JDICT(message); if (dictMessage == NULL) { throw BadRequest("Malformatted request. Need a JSON list"); } JsonList * jlist = getList(dictMessage, "userlist"); vector<string> ulist; for(int i = 0; i < jlist->size(); i++){ ulist.push_back(getString(jlist, i)); } emit handler->getWindow()->userList(ulist); } }
Add the missing FileCheck invocation to this testcase.
// RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-obj \ // RUN: -debug-info-kind=line-tables-only -fms-extensions class __declspec(dllexport) A { A(int * = new int) {} }; // CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ" // CHECK-SAME: !dbg ![[SP:[0-9]+]] // CHECK-NOT: {{ret }} // CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0) // CHECK-SAME: !dbg ![[DBG:[0-9]+]] // CHECK: ret void, !dbg ![[DBG]] // // CHECK: ![[SP]] = distinct !DISubprogram( // CHECK-SAME: line: 3 // CHECK-SAME: isDefinition: true // CHECK-SAME: DIFlagArtificial // CHECK-SAME: ){{$}} // // CHECK: ![[DBG]] = !DILocation(line: 0
// RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-llvm \ // RUN: -debug-info-kind=line-tables-only -fms-extensions -o - | FileCheck %s class __declspec(dllexport) A { A(int * = new int) {} }; // CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ" // CHECK-SAME: !dbg ![[SP:[0-9]+]] // CHECK-NOT: {{ret }} // CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0) // CHECK-SAME: !dbg ![[DBG:[0-9]+]] // CHECK: ret void, !dbg ![[DBG1:[0-9]+]] // // CHECK: ![[SP]] = distinct !DISubprogram( // CHECK-SAME: line: 4 // CHECK-SAME: isDefinition: true // CHECK-SAME: DIFlagArtificial // CHECK-SAME: ){{$}} // // CHECK: ![[DBG1]] = !DILocation(line: 0 // CHECK: ![[DBG]] = !DILocation(line: 0
Fix test to not write output to the test directory, as it may not be writable.
// RUN: rm -rf %t // RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s 2>&1 | FileCheck %s -check-prefix=CHECK_1 // RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s 2>&1 | FileCheck %s -check-prefix=CHECK_2 -allow-empty // For modules, the warning should only fire the first time, when the module is // built. // CHECK_1: warning: unused typedef // CHECK_2-NOT: warning: unused typedef @import warn_unused_local_typedef;
// RUN: rm -rf %t // RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -o /dev/null 2>&1 | FileCheck %s -check-prefix=CHECK_1 // RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -o /dev/null 2>&1 | FileCheck %s -check-prefix=CHECK_2 -allow-empty // For modules, the warning should only fire the first time, when the module is // built. // CHECK_1: warning: unused typedef // CHECK_2-NOT: warning: unused typedef @import warn_unused_local_typedef;
Add noexcept test for offsetof macro per [support.types]/p4.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// #include <cstddef> #ifndef offsetof #error offsetof not defined #endif int main() { }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// #include <cstddef> #ifndef offsetof #error offsetof not defined #endif struct A { int x; }; int main() { #if (__has_feature(cxx_noexcept)) static_assert(noexcept(offsetof(A, x)), ""); #endif }
Update playback extension so that javascript functions return consistent (but not constant) values in an attempt to preserve the functionality but improve compatibility of the extension.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "webkit/extensions/v8/playback_extension.h" namespace extensions_v8 { const char* kPlaybackExtensionName = "v8/PlaybackMode"; v8::Extension* PlaybackExtension::Get() { v8::Extension* extension = new v8::Extension( kPlaybackExtensionName, "(function () {" " var orig_date = Date;" " Math.random = function() {" " return 0.5;" " };" " Date.__proto__.now = function() {" " return new orig_date(1204251968254);" " };" " Date = function() {" " return Date.now();" " };" "})()"); return extension; } } // namespace extensions_v8
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "webkit/extensions/v8/playback_extension.h" namespace extensions_v8 { const char* kPlaybackExtensionName = "v8/PlaybackMode"; v8::Extension* PlaybackExtension::Get() { v8::Extension* extension = new v8::Extension( kPlaybackExtensionName, "(function () {" " var orig_date = Date;" " var x = 0;" " var time_seed = 1204251968254;" " Math.random = function() {" " x += .1;" " return (x % 1);" " };" " Date.__proto__.now = function() {" " time_seed += 50;" " return new orig_date(time_seed);" " };" " Date = function() {" " return Date.now();" " };" "})()"); return extension; } } // namespace extensions_v8
Fix constructor with noexcept of Parameter class
#include "ics3/parameter.hpp" ics::Parameter ics::Parameter::stretch() noexcept { static const Parameter STRETCH(0x01, 1, 127); return STRETCH; } ics::Parameter ics::Parameter::speed() noexcept { static const Parameter SPEED(0x02, 1, 127); return SPEED; } ics::Parameter ics::Parameter::current() noexcept { static const Parameter CURRENT(0x03, 0, 63); return CURRENT; } ics::Parameter ics::Parameter::temperature() noexcept { static const Parameter TEMPERATURE(0x04, 1, 127); return TEMPERATURE; } unsigned char ics::Parameter::get() const noexcept { return data; } void ics::Parameter::set(unsigned char input) throw(std::invalid_argument) { if (input < min) throw std::invalid_argument("Too small value"); if (max < input) throw std::invalid_argument("Too big value"); data = input; } ics::parameter::Parameter(unsigned char sc, unsigned char min, unsigned char max) : sc(sc), min(min), max(max) {}
#include "ics3/parameter.hpp" ics::Parameter ics::Parameter::stretch() noexcept { static const Parameter STRETCH(0x01, 1, 127); return STRETCH; } ics::Parameter ics::Parameter::speed() noexcept { static const Parameter SPEED(0x02, 1, 127); return SPEED; } ics::Parameter ics::Parameter::current() noexcept { static const Parameter CURRENT(0x03, 0, 63); return CURRENT; } ics::Parameter ics::Parameter::temperature() noexcept { static const Parameter TEMPERATURE(0x04, 1, 127); return TEMPERATURE; } unsigned char ics::Parameter::get() const noexcept { return data; } void ics::Parameter::set(unsigned char input) throw(std::invalid_argument) { if (input < min) throw std::invalid_argument("Too small value"); if (max < input) throw std::invalid_argument("Too big value"); data = input; } ics::Parameter::Parameter(unsigned char sc, unsigned char min, unsigned char max) noexcept : sc(sc), min(min), max(max) {}
Add memory declaration, and refactor comments
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <deque> #define MEM_SIZE (1<<20) #define CACHE_SIZE (1<<8) #define DATA_SIZE (1<<8) using namespace std; int main() { // Variables used int dir, cmd, op; unsigned char dat, wait; // Plant the seed srand(time(0)); // Infinit Loop while(true){ // Each command is 32 bits, // 19...0 bits for dir, // 27...20 bits for data // 28 bit indicates operation type 1:read 0:write cmd = rand(); dir = cmd & 0xFFFFF; dat = (cmd & 0xF00000)>>20; op = (cmd>>28)&1; printf("op=%c on dir(0x%x) data:%d\n","wr"[op],dir,dat); wait = getchar(); } return 0; }
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <bitset> #include <deque> #define MEM_SIZE (1<<20) #define CACHE_SIZE (1<<8) using namespace std; enum{ read, write }; int main() { // Variables used int dir, cmd, op; unsigned char dat, wait; // Memory simulated unsigned char rawMemory[MEM_SIZE]; int cacheDirection[CACHE_SIZE]; unsigned char cacheData[CACHE_SIZE]; // To simulate the circular queue int front = 0, tail = 0; // Initialize the cached Directions memset(cacheDirection, -1, sizeof cacheDirection); // Plant the seed srand(time(0)); // Infinit Loop while(true){ // Each command is 32 bits, cmd = rand(); // 19...0 bits for dir dir = ((cmd)&(0xFFFFF)); // 27...20 bits for data dat = (((cmd)&(0xF00000))>>20); // 28 bit indicates operation type 0:read 1:write op = ((cmd>>28)&(1)); //Perform operation according if(op == read) { } else { // write } wait = getchar(); } return 0; }
Make test EOL tolerant by moving the symbol ot the first line before any EOL changes the byte offset count and enable it on Windows.
// RUN: cat %s > %t.cpp // RUN: clang-rename -offset=170 -new-name=hector %t.cpp -i -- // RUN: sed 's,//.*,,' %t.cpp | FileCheck %s // REQUIRES: shell namespace A { int foo; // CHECK: int hector; } int foo; // CHECK: int foo; int bar = foo; // CHECK: bar = foo; int baz = A::foo; // CHECK: baz = A::hector; void fun1() { struct { int foo; // CHECK: int foo; } b = { 100 }; int foo = 100; // CHECK: int foo baz = foo; // CHECK: baz = foo; { extern int foo; // CHECK: int foo; baz = foo; // CHECK: baz = foo; foo = A::foo + baz; // CHECK: foo = A::hector + baz; A::foo = b.foo; // CHECK: A::hector = b.foo; } foo = b.foo; // CHECK: foo = b.foo; } // Use grep -FUbo 'foo;' <file> to get the correct offset of foo when changing // this file.
namespace A { int foo; // CHECK: int hector; } // RUN: cat %s > %t.cpp // RUN: clang-rename -offset=18 -new-name=hector %t.cpp -i -- // RUN: sed 's,//.*,,' %t.cpp | FileCheck %s int foo; // CHECK: int foo; int bar = foo; // CHECK: bar = foo; int baz = A::foo; // CHECK: baz = A::hector; void fun1() { struct { int foo; // CHECK: int foo; } b = { 100 }; int foo = 100; // CHECK: int foo baz = foo; // CHECK: baz = foo; { extern int foo; // CHECK: int foo; baz = foo; // CHECK: baz = foo; foo = A::foo + baz; // CHECK: foo = A::hector + baz; A::foo = b.foo; // CHECK: A::hector = b.foo; } foo = b.foo; // CHECK: foo = b.foo; } // Use grep -FUbo 'foo;' <file> to get the correct offset of foo when changing // this file.
Enable xword directive in sparcv9.
//===-- SparcMCAsmInfo.cpp - Sparc asm properties -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the declarations of the SparcMCAsmInfo properties. // //===----------------------------------------------------------------------===// #include "SparcMCAsmInfo.h" #include "llvm/ADT/Triple.h" using namespace llvm; void SparcELFMCAsmInfo::anchor() { } SparcELFMCAsmInfo::SparcELFMCAsmInfo(StringRef TT) { IsLittleEndian = false; Triple TheTriple(TT); if (TheTriple.getArch() == Triple::sparcv9) { PointerSize = CalleeSaveStackSlotSize = 8; } Data16bitsDirective = "\t.half\t"; Data32bitsDirective = "\t.word\t"; Data64bitsDirective = 0; // .xword is only supported by V9. ZeroDirective = "\t.skip\t"; CommentString = "!"; HasLEB128 = true; SupportsDebugInformation = true; SunStyleELFSectionSwitchSyntax = true; UsesELFSectionDirectiveForBSS = true; WeakRefDirective = "\t.weak\t"; PrivateGlobalPrefix = ".L"; }
//===-- SparcMCAsmInfo.cpp - Sparc asm properties -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the declarations of the SparcMCAsmInfo properties. // //===----------------------------------------------------------------------===// #include "SparcMCAsmInfo.h" #include "llvm/ADT/Triple.h" using namespace llvm; void SparcELFMCAsmInfo::anchor() { } SparcELFMCAsmInfo::SparcELFMCAsmInfo(StringRef TT) { IsLittleEndian = false; Triple TheTriple(TT); bool isV9 = (TheTriple.getArch() == Triple::sparcv9); if (isV9) { PointerSize = CalleeSaveStackSlotSize = 8; } Data16bitsDirective = "\t.half\t"; Data32bitsDirective = "\t.word\t"; // .xword is only supported by V9. Data64bitsDirective = (isV9) ? "\t.xword\t" : 0; ZeroDirective = "\t.skip\t"; CommentString = "!"; HasLEB128 = true; SupportsDebugInformation = true; SunStyleELFSectionSwitchSyntax = true; UsesELFSectionDirectiveForBSS = true; WeakRefDirective = "\t.weak\t"; PrivateGlobalPrefix = ".L"; }
Use enums for keys in test
#include <gtest/gtest.h> #include <Eigen/Core> #include <Eigen/Geometry> #include "Integrator.h" #include "StateVector.h" TEST(StateTest, Instantiation) { using MyStateVector = UKF::StateVector< IntegratorRK4, UKF::Field<1, Eigen::Vector2f>, UKF::Field<2, Eigen::Vector3f>, UKF::Field<3, Eigen::Quaternionf>, UKF::Field<4, float> >; MyStateVector test_state; EXPECT_EQ(10, MyStateVector::MaxRowsAtCompileTime); EXPECT_EQ(10, test_state.size()); }
#include <gtest/gtest.h> #include <Eigen/Core> #include <Eigen/Geometry> #include "Integrator.h" #include "StateVector.h" TEST(StateTest, Instantiation) { enum MyFields { LatLon, Altitude, Velocity, Attitude }; using MyStateVector = UKF::StateVector< IntegratorRK4, UKF::Field<LatLon, Eigen::Vector2f>, UKF::Field<Altitude, Eigen::Vector3f>, UKF::Field<Velocity, Eigen::Quaternionf>, UKF::Field<Attitude, float> >; MyStateVector test_state; EXPECT_EQ(10, MyStateVector::MaxRowsAtCompileTime); EXPECT_EQ(10, test_state.size()); }
Call resizeAddresses only if you manage more than one sensor
#include "DSTemperature.h" DSTemperature::DSTemperature(byte pin) { _wire = new OneWire(pin); _addresses = (DSAddress*)malloc(sizeof(DSAddress)); } void DSTemperature::begin(void) { DSAddress addr; while (_wire->search(addr.value)) { if (OneWire::crc8(addr.value, 7) == addr.value[7]) { resizeAddresses(); _addresses[_nSensors++] = addr; } } _wire->reset_search(); delay(250); return; } void DSTemperature::resizeAddresses() { if (_nSensors == 0) return; DSAddress* new_addresses = (DSAddress*)malloc(sizeof(DSAddress) * _nSensors); for (byte i = 0 ; i < _nSensors ; i++) new_addresses[i] = _addresses[i]; free(_addresses); _addresses = new_addresses; } float DSTemperature::getCelsius(byte ds) { return CELSIUS(getRawTemperature(ds)); } float DSTemperature::getFahrenheit(byte ds) { return FAHRENHEIT(getRawTemperature(ds)); }
#include "DSTemperature.h" DSTemperature::DSTemperature(byte pin) { _wire = new OneWire(pin); _addresses = (DSAddress*)malloc(sizeof(DSAddress)); } void DSTemperature::begin(void) { DSAddress addr; while (_wire->search(addr.value)) { if (OneWire::crc8(addr.value, 7) == addr.value[7]) { if (_nSensors != 0) resizeAddresses(); _addresses[_nSensors++] = addr; } } _wire->reset_search(); delay(250); return; } void DSTemperature::resizeAddresses() { DSAddress* new_addresses = (DSAddress*)malloc(sizeof(DSAddress) * _nSensors); for (byte i = 0 ; i < _nSensors ; i++) new_addresses[i] = _addresses[i]; free(_addresses); _addresses = new_addresses; } float DSTemperature::getCelsius(byte ds) { return CELSIUS(getRawTemperature(ds)); } float DSTemperature::getFahrenheit(byte ds) { return FAHRENHEIT(getRawTemperature(ds)); }
Fix gl error debug print.
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLConfig.h" #include "GrGLInterface.h" void GrGLClearErr(const GrGLInterface* gl) { while (GR_GL_NO_ERROR != gl->fGetError()) {} } void GrGLCheckErr(const GrGLInterface* gl, const char* location, const char* call) { uint32_t err = GR_GL_GET_ERROR(gl); if (GR_GL_NO_ERROR != err) { GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl)); if (NULL != location) { GrPrintf(" at\n\t%s", location); } if (NULL != call) { GrPrintf("\n\t\t%s", call); } GrPrintf("\n"); } } void GrGLResetRowLength(const GrGLInterface* gl) { if (gl->supportsDesktop()) { GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0)); } } /////////////////////////////////////////////////////////////////////////////// #if GR_GL_LOG_CALLS bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START); #endif #if GR_GL_CHECK_ERROR bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START); #endif
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLConfig.h" #include "GrGLInterface.h" void GrGLClearErr(const GrGLInterface* gl) { while (GR_GL_NO_ERROR != gl->fGetError()) {} } void GrGLCheckErr(const GrGLInterface* gl, const char* location, const char* call) { uint32_t err = GR_GL_GET_ERROR(gl); if (GR_GL_NO_ERROR != err) { GrPrintf("---- glGetError %x", err); if (NULL != location) { GrPrintf(" at\n\t%s", location); } if (NULL != call) { GrPrintf("\n\t\t%s", call); } GrPrintf("\n"); } } void GrGLResetRowLength(const GrGLInterface* gl) { if (gl->supportsDesktop()) { GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0)); } } /////////////////////////////////////////////////////////////////////////////// #if GR_GL_LOG_CALLS bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START); #endif #if GR_GL_CHECK_ERROR bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START); #endif
Support unrecoverable error uploading on non-win platforms
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) const double kErrorUploadRatio = 0.15; // We only want to upload |kErrorUploadRatio| ratio of errors. if (kErrorUploadRatio <= 0.0) return; // We are not allowed to upload errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/dump_without_crashing.h" namespace browser_sync { void ChromeReportUnrecoverableError() { // Only upload on canary/dev builds to avoid overwhelming crash server. chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel(); if (channel != chrome::VersionInfo::CHANNEL_CANARY && channel != chrome::VersionInfo::CHANNEL_DEV) { return; } // We only want to upload |kErrorUploadRatio| ratio of errors. const double kErrorUploadRatio = 0.15; if (kErrorUploadRatio <= 0.0) return; // We are not allowed to upload errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; logging::DumpWithoutCrashing(); } } // namespace browser_sync
Use RTLD_DEEPBIND to make sure plugins don't use Chrome's symbols instead of their own
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY); if (!dl) NOTREACHED() << "dlopen failed: " << dlerror(); return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) NOTREACHED() << "dlclose failed: " << dlerror(); } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, NativeLibraryFunctionNameType name) { return dlsym(library, name); } } // namespace base
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY|RTLD_DEEPBIND); if (!dl) NOTREACHED() << "dlopen failed: " << dlerror(); return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) NOTREACHED() << "dlclose failed: " << dlerror(); } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, NativeLibraryFunctionNameType name) { return dlsym(library, name); } } // namespace base
Set local to C. Maybe not the best longterm solution.
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); std::locale::global( std::locale( "C" ) ); MainWindow w; w.show(); return a.exec(); }
Add 10 pixels to tooltip because of Retina text width bug
#include "ui.hpp" #include "window.hpp" namespace rack { Tooltip::Tooltip() { } void Tooltip::draw(NVGcontext *vg) { // Wrap size to contents box.size.x = bndLabelWidth(vg, -1, text.c_str()); box.size.y = bndLabelHeight(vg, -1, text.c_str(), INFINITY); bndTooltipBackground(vg, 0.0, 0.0, box.size.x, box.size.y); bndMenuLabel(vg, 0.0, 0.0, box.size.x, box.size.y, -1, text.c_str()); Widget::draw(vg); } } // namespace rack
#include "ui.hpp" #include "window.hpp" namespace rack { Tooltip::Tooltip() { } void Tooltip::draw(NVGcontext *vg) { // Wrap size to contents box.size.x = bndLabelWidth(vg, -1, text.c_str()) + 10.0; box.size.y = bndLabelHeight(vg, -1, text.c_str(), INFINITY); bndTooltipBackground(vg, 0.0, 0.0, box.size.x, box.size.y); bndMenuLabel(vg, 0.0, 0.0, box.size.x, box.size.y, -1, text.c_str()); Widget::draw(vg); } } // namespace rack
Initialize libsodium in this routine, which is now necessary because libsnark uses its PRNG.
#include "zcash/JoinSplit.hpp" #include <iostream> int main(int argc, char **argv) { if(argc != 3) { std::cerr << "Usage: " << argv[0] << " provingKeyFileName verificationKeyFileName" << std::endl; return 1; } std::string pkFile = argv[1]; std::string vkFile = argv[2]; auto p = ZCJoinSplit::Generate(); p->saveProvingKey(pkFile); p->saveVerifyingKey(vkFile); return 0; }
#include "zcash/JoinSplit.hpp" #include <iostream> #include "sodium.h" int main(int argc, char **argv) { if (sodium_init() == -1) { return 1; } if(argc != 3) { std::cerr << "Usage: " << argv[0] << " provingKeyFileName verificationKeyFileName" << std::endl; return 1; } std::string pkFile = argv[1]; std::string vkFile = argv[2]; auto p = ZCJoinSplit::Generate(); p->saveProvingKey(pkFile); p->saveVerifyingKey(vkFile); return 0; }
Change time pause while visionning
#include "visionnage.h" #include "mainwindow.h" #include <QDebug> #include <QException> Visionnage::Visionnage(MainWindow *parent, Projet *projet, int nPreviousImage) : QThread(parent), _parent(parent), _projet(projet), _nPreviousImage(nPreviousImage), _initFrame(parent->getNbFrame()), _stop(false) { } void Visionnage::run() { int frame = _initFrame; while(!_stop) { _parent->loadFrame(frame); if(_nPreviousImage == -1) { if(frame == _projet->getNbFrameVideo()) { frame = 0; } else { frame += 1; } } else { if(frame == _initFrame) { frame -= _nPreviousImage; if(frame < 0) frame = 0; } else { frame += 1; } } msleep(20); } } void Visionnage::stop() { _stop = true; msleep(20); _parent->loadFrame(_initFrame); }
#include "visionnage.h" #include "mainwindow.h" #include <QDebug> #include <QException> Visionnage::Visionnage(MainWindow *parent, Projet *projet, int nPreviousImage) : QThread(parent), _parent(parent), _projet(projet), _nPreviousImage(nPreviousImage), _initFrame(parent->getNbFrame()), _stop(false) { } void Visionnage::run() { int frame = _initFrame; while(!_stop) { _parent->loadFrame(frame); if(_nPreviousImage == -1) { if(frame == _projet->getNbFrameVideo()) { frame = 0; } else { frame += 1; } } else { if(frame == _initFrame) { frame -= _nPreviousImage; if(frame < 0) frame = 0; } else { frame += 1; } } msleep(100); } } void Visionnage::stop() { _stop = true; msleep(20); _parent->loadFrame(_initFrame); }
Implement fn to build lookup table
// Copyright 2015 Matt Heard // http://mattheard.net // matt@mattheard.net // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> using cv::Mat; Mat buildLookUpTable(const int divideWith) { return Mat(); } int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 3; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path> <Reduce_By>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } const int divideWith = atoi(argv[2]); if (divideWith < 1) { std::cout << "Invalid number entered for dividing." << std::endl; return -1; } const Mat lookUpTable = buildLookUpTable(divideWith); return 0; }
// Copyright 2015 Matt Heard // http://mattheard.net // matt@mattheard.net // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> using cv::Mat; Mat buildLookUpTable(const int divideWith) { const int rows = 1; const int cols = 256; const int type = CV_8U; const Mat table(rows, cols, type); for (int i = 0; i < 256; ++i) { const int reduced = divideWith * (i / divideWith); table.data[i] = (uchar) reduced; } return table; } int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 3; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path> <Reduce_By>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } const int divideWith = atoi(argv[2]); if (divideWith < 1) { std::cout << "Invalid number entered for dividing." << std::endl; return -1; } const Mat lookUpTable = buildLookUpTable(divideWith); return 0; }
Use the normal panel-frame until there's a touch-friendly version.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { if (browser_view->IsBrowserTypePopup() || browser_view->IsBrowserTypePanel()) { // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return new PopupNonClientFrameView(frame); } else { return new TouchBrowserFrameView(frame, browser_view); } } } // browser
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h" #include "base/command_line.h" #include "chrome/browser/ui/panels/panel_browser_frame_view.h" #include "chrome/browser/ui/panels/panel_browser_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h" #include "chrome/common/chrome_switches.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { Browser::Type type = browser_view->browser()->type(); switch (type) { case Browser::TYPE_PANEL: if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnablePanels)) { return new PanelBrowserFrameView( frame, static_cast<PanelBrowserView*>(browser_view)); } // else, fall-through and treat as popup case Browser::TYPE_POPUP: // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return new PopupNonClientFrameView(frame); default: return new TouchBrowserFrameView(frame, browser_view); } } } // browser
Change this test to not try to emit any IR. (It should fail to, but it tries to create an output file before encountering the error.)
// RUN: not %clang_cc1 -triple i686-pc-win32 -emit-llvm -fno-rtti %s 2>&1 | FileCheck %s // CHECK: error: v-table layout for classes with non-virtual base classes that override methods in virtual bases is not supported yet struct A { virtual int foo() { return a; } int a; }; struct B : virtual A { B() : b(1) {} virtual int bar() { return b; } int b; }; struct C : virtual A { C() : c(2) {} virtual int foo() { return c; } int c; }; struct D : B, C { D() : d(3) {} virtual int bar() { return d; } int d; }; int main() { D d; return d.foo(); }
// RUN: not %clang_cc1 -triple i686-pc-win32 -emit-llvm-only -fno-rtti %s 2>&1 | FileCheck %s // CHECK: error: v-table layout for classes with non-virtual base classes that override methods in virtual bases is not supported yet struct A { virtual int foo() { return a; } int a; }; struct B : virtual A { B() : b(1) {} virtual int bar() { return b; } int b; }; struct C : virtual A { C() : c(2) {} virtual int foo() { return c; } int c; }; struct D : B, C { D() : d(3) {} virtual int bar() { return d; } int d; }; int main() { D d; return d.foo(); }
Add GetCurrentWorkingDirectory for Windows platform
#include "nucleus/Config.h" #include "nucleus/Files/FilePath.h" #if OS(POSIX) #include <unistd.h> #endif namespace nu { #if OS(POSIX) FilePath getCurrentWorkingDirectory(Allocator* allocator) { char buf[PATH_MAX] = {0}; const char* result = ::getcwd(buf, PATH_MAX); return FilePath{String{result, String::npos, allocator}, allocator}; } #endif } // namespace nu
#include "nucleus/Config.h" #include "nucleus/Files/FilePath.h" #if OS(POSIX) #include <unistd.h> #elif OS(WIN) #include "nucleus/Win/WindowsMixin.h" #endif namespace nu { FilePath getCurrentWorkingDirectory(Allocator* allocator) { #if OS(POSIX) char buf[PATH_MAX] = {0}; const char* result = ::getcwd(buf, PATH_MAX); return FilePath{String{result, String::npos, allocator}, allocator}; #elif OS(WIN) char buf[MAX_PATH] = {0}; DWORD result = ::GetCurrentDirectoryA(MAX_PATH, buf); return FilePath{String{buf, static_cast<I32>(result), allocator}, allocator}; #endif } } // namespace nu
Use Qt to load init.lua
#include "Bootstrapper.hpp" #include <functional> #include <lua-cxx/LuaValue.hpp> #include <lua-cxx/loaders.hpp> #include <lua-cxx/userdata.hpp> #include "LuaPainter.hpp" #include "LuaFont.hpp" Bootstrapper::Bootstrapper() : _lua(), _desktop(_lua), _rainback(_lua) { _rainback.setWidget(&_desktop); lua::load_file(_lua, "../../demo/init.lua"); } QWidget& Bootstrapper::mainWidget() { return _desktop; } // vim: set ts=4 sw=4 :
#include "Bootstrapper.hpp" #include <functional> #include <lua-cxx/LuaValue.hpp> #include <lua-cxx/loaders.hpp> #include <lua-cxx/userdata.hpp> #include "LuaPainter.hpp" #include "LuaFont.hpp" Bootstrapper::Bootstrapper() : _lua(), _desktop(_lua), _rainback(_lua) { _rainback.setWidget(&_desktop); QFile file("../../demo/init.lua"); _lua(file); } QWidget& Bootstrapper::mainWidget() { return _desktop; } // vim: set ts=4 sw=4 :
Raise window if new instance is started
#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #include <QtSingleApplication> int main(int argc, char *argv[]) { QtSingleApplication app(argc, argv); if (app.isRunning()) { return 0; } QQmlApplicationEngine engine; app.setWindowIcon(QIcon("resources/icons/ykman.png")); QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1"; putenv(pythonNoBytecode.toUtf8().data()); QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks"; putenv(frameworks.toUtf8().data()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec(); }
#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #include <QtSingleApplication> int main(int argc, char *argv[]) { // Only allow a single instance running. QtSingleApplication app(argc, argv); if (app.sendMessage("")) { return 0; } QQmlApplicationEngine engine; app.setWindowIcon(QIcon("resources/icons/ykman.png")); QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1"; putenv(pythonNoBytecode.toUtf8().data()); QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks"; putenv(frameworks.toUtf8().data()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); // Raise the root window on a message from new instance. for (auto object : engine.rootObjects()) { if (QWindow *window = qobject_cast<QWindow*>(object)) { QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() { window->raise(); }); } } return app.exec(); }
Use namespace std, if we do not set this there is a bug?.
#include "math_container.h" using std::complex; /******************************************************/ /*solve the equation cosh(x)=exp(y), input y, return x*/ /******************************************************/ complex<double> coshx_eq_expy(double y) { complex<double> ey={exp(y),0}; complex<double> gamma=log(ey-sqrt(ey*ey-1.0)); //Since gamma is pure real or pure imaginary, set it: if( abs( gamma.real() ) < abs( gamma.imag() ) ) gamma=complex<double>( 0, gamma.imag() ); else gamma=complex<double>( gamma.real(), 0 ); return gamma; }
#include "math_container.h" using namespace std; /******************************************************/ /*solve the equation cosh(x)=exp(y), input y, return x*/ /******************************************************/ complex<double> coshx_eq_expy(double y) { complex<double> ey={exp(y),0}; complex<double> gamma=log(ey-sqrt(ey*ey-1.0)); //Since gamma is pure real or pure imaginary, set it: if( abs( gamma.real() ) < abs( gamma.imag() ) ) gamma=complex<double>( 0, gamma.imag() ); else gamma=complex<double>( gamma.real(), 0 ); return gamma; }
Fix linking error (again, but for Unix this time)
#ifdef __unix__ #include <iostream> #include <signal.h> #include <stdio.h> #include <unistd.h> #include "Tools.h" void StartBotProcess(const std::string& CommandLine) { FILE* pipe = popen(CommandLine.c_str(), "r"); if (!pipe) { std::cerr << "Can't launch command '" << CommandLine << "'" << std::endl; return; } int returnCode = pclose(pipe); if (returnCode != 0) { std::cerr << "Failed to finish command '" << CommandLine << "', code: " << returnCode << std::endl; } } void SleepFor(int seconds) { sleep(seconds); } void KillSc2Process(unsigned long pid) { kill(pid, SIGKILL); } bool MoveReplayFile(char* lpExistingFileName, char* lpNewFileName) { // todo throw "MoveFile is not implemented for linux yet."; } #endif
#ifdef __unix__ #include <iostream> #include <signal.h> #include <stdio.h> #include <unistd.h> #include "Tools.h" void StartBotProcess(const std::string& CommandLine) { FILE* pipe = popen(CommandLine.c_str(), "r"); if (!pipe) { std::cerr << "Can't launch command '" << CommandLine << "'" << std::endl; return; } int returnCode = pclose(pipe); if (returnCode != 0) { std::cerr << "Failed to finish command '" << CommandLine << "', code: " << returnCode << std::endl; } } void SleepFor(int seconds) { sleep(seconds); } void KillSc2Process(unsigned long pid) { kill(pid, SIGKILL); } bool MoveReplayFile(const char* lpExistingFileName, const char* lpNewFileName) { // todo throw "MoveFile is not implemented for linux yet."; } #endif
Make cpptest main return 0 for SUCCESS.
/* This file is part of VoltDB. * Copyright (C) 2008-2015 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> int main (int argc, char **argv) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest( registry.makeTest() ); return runner.run( "" ); }
/* This file is part of VoltDB. * Copyright (C) 2008-2015 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> int main (int argc, char **argv) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest( registry.makeTest() ); return !runner.run( "" ); }
Mark ExtensionApiTest.ExecuteScript DISABLED because it's not only flaky, but crashy and it has been ignored for weeks!
// Copyright (c) 20109 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // This test failed at times on the Vista dbg builder and has been marked as // flaky for now. Bug http://code.google.com/p/chromium/issues/detail?id=28630 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_ExecuteScript) { // We need a.com to be a little bit slow to trigger a race condition. host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500); host_resolver()->AddRule("b.com", "127.0.0.1"); host_resolver()->AddRule("c.com", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_; }
// Copyright (c) 20109 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // EXTREMELY flaky, crashy, and bad. See http://crbug.com/28630 and don't dare // to re-enable without a real fix or at least adding more debugging info. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ExecuteScript) { // We need a.com to be a little bit slow to trigger a race condition. host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500); host_resolver()->AddRule("b.com", "127.0.0.1"); host_resolver()->AddRule("c.com", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_; }
Change the element builder semantic
/* * INTEL CONFIDENTIAL * Copyright © 2011 Intel * Corporation All Rights Reserved. * * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Intel Corporation or its suppliers * or licensors. Title to the Material remains with Intel Corporation or its * suppliers and licensors. The Material contains trade secrets and proprietary * and confidential information of Intel or its suppliers and licensors. The * Material is protected by worldwide copyright and trade secret laws and * treaty provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed, or * disclosed in any way without Intel’s prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Intel in writing. * * CREATED: 2012-03-29 * UPDATED: 2012-03-29 */ #include "SubsystemLibrary.h" #include "NamedElementBuilderTemplate.h" #include "FSSubsystem.h" extern "C" { void getFSSubsystemBuilder(CSubsystemLibrary* pSubsystemLibrary) { pSubsystemLibrary->addElementBuilder(new TNamedElementBuilderTemplate<CFSSubsystem>("FS")); } }
/* * INTEL CONFIDENTIAL * Copyright © 2011 Intel * Corporation All Rights Reserved. * * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Intel Corporation or its suppliers * or licensors. Title to the Material remains with Intel Corporation or its * suppliers and licensors. The Material contains trade secrets and proprietary * and confidential information of Intel or its suppliers and licensors. The * Material is protected by worldwide copyright and trade secret laws and * treaty provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed, or * disclosed in any way without Intel’s prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Intel in writing. * * CREATED: 2012-03-29 * UPDATED: 2012-03-29 */ #include "SubsystemLibrary.h" #include "NamedElementBuilderTemplate.h" #include "FSSubsystem.h" extern "C" { void getFSSubsystemBuilder(CSubsystemLibrary* pSubsystemLibrary) { pSubsystemLibrary->addElementBuilder("FS", new TNamedElementBuilderTemplate<CFSSubsystem>()); } }
Use the non-touch popup frame instead of NULL.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { if (browser_view->IsBrowserTypePopup() || browser_view->IsBrowserTypePanel()) { // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return NULL; } else { return new TouchBrowserFrameView(frame, browser_view); } } } // browser
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h" namespace browser { BrowserNonClientFrameView* CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { if (browser_view->IsBrowserTypePopup() || browser_view->IsBrowserTypePanel()) { // TODO(anicolao): implement popups for touch NOTIMPLEMENTED(); return new PopupNonClientFrameView(frame); } else { return new TouchBrowserFrameView(frame, browser_view); } } } // browser
Set the default starting penalty to 10
/** * @file lrsdp.cpp * @author Ryan Curtin * * An implementation of Monteiro and Burer's formulation of low-rank * semidefinite programs (LR-SDP). */ #include "lrsdp.hpp" using namespace mlpack; using namespace mlpack::optimization; using namespace std; LRSDP::LRSDP(const size_t numSparseConstraints, const size_t numDenseConstraints, const arma::mat& initialPoint) : function(numSparseConstraints, numDenseConstraints, initialPoint), augLag(function) { } double LRSDP::Optimize(arma::mat& coordinates) { augLag.Sigma() = 20; augLag.Optimize(coordinates, 1000); return augLag.Function().Evaluate(coordinates); } // Convert the object to a string. std::string LRSDP::ToString() const { std::ostringstream convert; convert << "LRSDP [" << this << "]" << std::endl; convert << " Optimizer: " << util::Indent(augLag.ToString(), 1) << std::endl; return convert.str(); }
/** * @file lrsdp.cpp * @author Ryan Curtin * * An implementation of Monteiro and Burer's formulation of low-rank * semidefinite programs (LR-SDP). */ #include "lrsdp.hpp" using namespace mlpack; using namespace mlpack::optimization; using namespace std; LRSDP::LRSDP(const size_t numSparseConstraints, const size_t numDenseConstraints, const arma::mat& initialPoint) : function(numSparseConstraints, numDenseConstraints, initialPoint), augLag(function) { } double LRSDP::Optimize(arma::mat& coordinates) { augLag.Sigma() = 10; augLag.Optimize(coordinates, 1000); return augLag.Function().Evaluate(coordinates); } // Convert the object to a string. std::string LRSDP::ToString() const { std::ostringstream convert; convert << "LRSDP [" << this << "]" << std::endl; convert << " Optimizer: " << util::Indent(augLag.ToString(), 1) << std::endl; return convert.str(); }
Change default log level to >= FATAL
#include "Logging.h" #include <SenseKit/sensekit_types.h> INITIALIZE_LOGGING namespace sensekit { void initialize_logging(const char* logFilePath) { const char TRUE_STRING[] = "true"; el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Configurations defaultConf; defaultConf.setToDefault(); defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath); el::Loggers::setDefaultConfigurations(defaultConf, true); el::Loggers::setLoggingLevel(el::Level::Debug); defaultConf.clear(); } }
#include "Logging.h" #include <SenseKit/sensekit_types.h> INITIALIZE_LOGGING namespace sensekit { void initialize_logging(const char* logFilePath) { const char TRUE_STRING[] = "true"; el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Configurations defaultConf; defaultConf.setToDefault(); defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath); el::Loggers::setDefaultConfigurations(defaultConf, true); el::Loggers::setLoggingLevel(el::Level::Fatal); defaultConf.clear(); } }
Use GetXDisplay() instead of XOpenDisplay() in IdleQueryLinux.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/idle_query_linux.h" #include <X11/Xlib.h> #include <X11/extensions/scrnsaver.h> namespace browser { class IdleData { public: IdleData() { int event_base; int error_base; display = XOpenDisplay(NULL); if (XScreenSaverQueryExtension(display, &event_base, &error_base)) { mit_info = XScreenSaverAllocInfo(); } else { mit_info = NULL; } } ~IdleData() { if (display) { XCloseDisplay(display); display = NULL; } if (mit_info) XFree(mit_info); } XScreenSaverInfo *mit_info; Display *display; }; IdleQueryLinux::IdleQueryLinux() : idle_data_(new IdleData()) {} IdleQueryLinux::~IdleQueryLinux() {} int IdleQueryLinux::IdleTime() { if (!idle_data_->mit_info || !idle_data_->display) return 0; if (XScreenSaverQueryInfo(idle_data_->display, RootWindow(idle_data_->display, 0), idle_data_->mit_info)) { return (idle_data_->mit_info->idle) / 1000; } else { return 0; } } } // namespace browser
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/idle_query_linux.h" #include <X11/extensions/scrnsaver.h> #include "ui/base/x/x11_util.h" namespace browser { class IdleData { public: IdleData() { int event_base; int error_base; if (XScreenSaverQueryExtension(ui::GetXDisplay(), &event_base, &error_base)) { mit_info = XScreenSaverAllocInfo(); } else { mit_info = NULL; } } ~IdleData() { if (mit_info) XFree(mit_info); } XScreenSaverInfo *mit_info; }; IdleQueryLinux::IdleQueryLinux() : idle_data_(new IdleData()) {} IdleQueryLinux::~IdleQueryLinux() {} int IdleQueryLinux::IdleTime() { if (!idle_data_->mit_info) return 0; if (XScreenSaverQueryInfo(ui::GetXDisplay(), RootWindow(ui::GetXDisplay(), 0), idle_data_->mit_info)) { return (idle_data_->mit_info->idle) / 1000; } else { return 0; } } } // namespace browser
Create a simple example of sniffing
#include <iostream> #include <system_error> #include "controllers/main/MainModule.hpp" #include "network/bsdsocket/Manager.hpp" int main() { tin::controllers::main::ControllerQueue ctrlQueue; tin::network::bsdsocket::ManagerQueue netManagerQueue; tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue); tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333); std::cout << "Hello agent!\n"; auto mainCtrlThread = mainCtrl.createThread(); auto netManager = networkManager.createThread(); try { mainCtrlThread.join(); netManager.join(); } catch (std::system_error& e) { // Could not join one of the threads } return 0; }
#include <iostream> #include <system_error> #include "controllers/main/MainModule.hpp" #include "network/bsdsocket/Manager.hpp" #include "network/sniffer/SnifferManager.hpp" int main() { tin::controllers::main::ControllerQueue ctrlQueue; tin::network::bsdsocket::ManagerQueue netManagerQueue; tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue); tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333); tin::network::sniffer::SnifferManager sniffManager(ctrlQueue, "lo", "src 127.0.0.1"); std::cout << "Hello agent!\n"; auto mainCtrlThread = mainCtrl.createThread(); auto netManager = networkManager.createThread(); try { mainCtrlThread.join(); netManager.join(); } catch (std::system_error& e) { // Could not join one of the threads } return 0; }
Add missing -pthread in tests.
// RUN: %clangxx_asan -std=c++11 %s -o %t && %run %t 2>&1 // Regression test for the versioned pthread_create interceptor on linux/i386. // pthread_attr_init is not intercepted and binds to the new abi // pthread_create is intercepted; dlsym always returns the oldest version. // This results in a crash inside pthread_create in libc. #include <pthread.h> #include <stdlib.h> void *ThreadFunc(void *) { return nullptr; } int main() { pthread_t t; const size_t sz = 1024 * 1024; void *p = malloc(sz); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstack(&attr, p, sz); pthread_create(&t, &attr, ThreadFunc, nullptr); pthread_join(t, nullptr); free(p); return 0; }
// RUN: %clangxx_asan -std=c++11 -pthread %s -o %t && %run %t 2>&1 // Regression test for the versioned pthread_create interceptor on linux/i386. // pthread_attr_init is not intercepted and binds to the new abi // pthread_create is intercepted; dlsym always returns the oldest version. // This results in a crash inside pthread_create in libc. #include <pthread.h> #include <stdlib.h> void *ThreadFunc(void *) { return nullptr; } int main() { pthread_t t; const size_t sz = 1024 * 1024; void *p = malloc(sz); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstack(&attr, p, sz); pthread_create(&t, &attr, ThreadFunc, nullptr); pthread_join(t, nullptr); free(p); return 0; }
Remove debugging aids from this test and fix its expectations.
// RUN: rm -rf %t // RUN: %clang_cc1 -fsyntax-only -verify %s -fmodules -fmodules-cache-path=%t -I%S/Inputs/PR28438 -fimplicit-module-maps #include "a.h" #include "b2.h" #pragma clang __debug macro FOO FOO // xpected-no-diagnostics
// RUN: rm -rf %t // RUN: %clang_cc1 -fsyntax-only -verify %s -fmodules -fmodules-cache-path=%t -I%S/Inputs/PR28438 -fimplicit-module-maps #include "a.h" #include "b2.h" FOO // expected-no-diagnostics
Fix var name in GameState::handle_events.
#include "game_state.hpp" #include "start_game_state.hpp" namespace Quoridor { GameState::GameState() { } GameState::~GameState() { } void GameState::handle_events(StateManager *stm, std::shared_ptr<UI::UIImpl> ui) { UI::Event ev; if (ui->poll_event(&ev)) { switch (ev) { case UI::kEnter: break; case UI::kEsc: { std::shared_ptr<Quoridor::IState> menu_state(new StartGameState()); stm->change_state(std::shared_ptr<IState>(menu_state)); } break; default: break; } } } void GameState::update() { } void GameState::draw(std::shared_ptr<UI::UIImpl> ui) { ui->update(repr_); } void GameState::change_state() { } void GameState::init_board_repr() const { } } /* namespace Quoridor */
#include "game_state.hpp" #include "start_game_state.hpp" namespace Quoridor { GameState::GameState() { } GameState::~GameState() { } void GameState::handle_events(StateManager *stm, std::shared_ptr<UI::UIImpl> ui) { UI::Event ev; if (ui->poll_event(&ev)) { switch (ev) { case UI::kEnter: break; case UI::kEsc: { std::shared_ptr<IState> start_game_state(new StartGameState(ui)); stm->change_state(std::shared_ptr<IState>(start_game_state)); } break; default: break; } } } void GameState::update() { } void GameState::draw(std::shared_ptr<UI::UIImpl> ui) { ui->update(repr_); } void GameState::change_state() { } void GameState::init_board_repr() const { } } /* namespace Quoridor */
Remove unneeded OpenMP header import.
#include <omp.h> #include "proctor/detector.h" #include "proctor/proctor.h" #include "proctor/scanning_model_source.h" #include "proctor/basic_proposer.h" using pcl::proctor::Detector; //using pcl::proctor::ProctorMPI; using pcl::proctor::Proctor; using pcl::proctor::ScanningModelSource; using pcl::proctor::BasicProposer; int main(int argc, char **argv) { unsigned int model_seed = 2; unsigned int test_seed = 0; //time(NULL); if (argc >= 2) { model_seed = atoi(argv[1]); } if (argc >= 3) { test_seed = atoi(argv[2]); } Detector detector; Proctor proctor; BasicProposer::Ptr proposer(new BasicProposer); detector.setProposer(proposer); ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db"); model_source.loadModels(); //detector.enableVisualization(); proctor.setModelSource(&model_source); proctor.train(detector); proctor.test(detector, test_seed); proctor.printResults(detector); sleep(100000); return 0; }
#include "proctor/detector.h" #include "proctor/proctor.h" #include "proctor/scanning_model_source.h" #include "proctor/basic_proposer.h" using pcl::proctor::Detector; //using pcl::proctor::ProctorMPI; using pcl::proctor::Proctor; using pcl::proctor::ScanningModelSource; using pcl::proctor::BasicProposer; int main(int argc, char **argv) { unsigned int model_seed = 2; unsigned int test_seed = 0; //time(NULL); if (argc >= 2) { model_seed = atoi(argv[1]); } if (argc >= 3) { test_seed = atoi(argv[2]); } Detector detector; Proctor proctor; BasicProposer::Ptr proposer(new BasicProposer); detector.setProposer(proposer); ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db"); model_source.loadModels(); //detector.enableVisualization(); proctor.setModelSource(&model_source); proctor.train(detector); proctor.test(detector, test_seed); proctor.printResults(detector); sleep(100000); return 0; }
Add missing import for string.h
#include "runtime/helpers/spy_reader.h" #include <algorithm> using std::string; static const char * spy_read(void *data, size_t *bytes_read) { SpyReader *reader = static_cast<SpyReader *>(data); string result = reader->content.substr(reader->position, reader->chunk_size); reader->position += result.size(); reader->strings_read.back() += result; *bytes_read = result.size(); memcpy(reader->buffer, result.data(), result.size()); return reader->buffer; } static int spy_seek(void *data, TSLength position) { SpyReader *reader = static_cast<SpyReader *>(data); reader->strings_read.push_back(""); reader->position = position.bytes; return 0; } SpyReader::SpyReader(string content, size_t chunk_size) : buffer(new char[chunk_size]), content(content), position(0), chunk_size(chunk_size), input({ this, spy_read, spy_seek, nullptr, }) {} void SpyReader::clear() { strings_read.clear(); } SpyReader::~SpyReader() { delete buffer; }
#include "runtime/helpers/spy_reader.h" #include <string.h> #include <algorithm> using std::string; static const char * spy_read(void *data, size_t *bytes_read) { SpyReader *reader = static_cast<SpyReader *>(data); string result = reader->content.substr(reader->position, reader->chunk_size); reader->position += result.size(); reader->strings_read.back() += result; *bytes_read = result.size(); memcpy(reader->buffer, result.data(), result.size()); return reader->buffer; } static int spy_seek(void *data, TSLength position) { SpyReader *reader = static_cast<SpyReader *>(data); reader->strings_read.push_back(""); reader->position = position.bytes; return 0; } SpyReader::SpyReader(string content, size_t chunk_size) : buffer(new char[chunk_size]), content(content), position(0), chunk_size(chunk_size), input({ this, spy_read, spy_seek, nullptr, }) {} void SpyReader::clear() { strings_read.clear(); } SpyReader::~SpyReader() { delete buffer; }
Fix walking move in Game.
#include "game.hpp" #include "exception.hpp" #include "walk_move.hpp" #include "wall_move.hpp" namespace Quoridor { Game::Game() : board_(new Board(9, 9)), pawn_list_() { } Game::~Game() { } void Game::add_pawn(std::shared_ptr<Pawn> pawn) { board_->add_pawn(pawn); pawn_list_.push_back(pawn); } pos_t Game::pawn_pos(std::shared_ptr<Pawn> pawn) const { return board_->pawn_pos(pawn); } int Game::make_move(IMove *move, std::shared_ptr<Pawn> pawn) { if (WalkMove *walk_move = dynamic_cast<WalkMove *>(move)) { return board_->make_walking_move(walk_move->dir(), pawn); } else if (WallMove *wall_move = dynamic_cast<WallMove *>(move)) { return board_->add_wall(wall_move->wall()); } else { return -1; } } bool Game::is_win(std::shared_ptr<Pawn> pawn) const { return board_->is_at_opposite_side(pawn); } } /* namespace Quoridor */
#include "game.hpp" #include "exception.hpp" #include "walk_move.hpp" #include "wall_move.hpp" namespace Quoridor { Game::Game() : board_(new Board(9, 9)), pawn_list_() { } Game::~Game() { } void Game::add_pawn(std::shared_ptr<Pawn> pawn) { board_->add_pawn(pawn); pawn_list_.push_back(pawn); } pos_t Game::pawn_pos(std::shared_ptr<Pawn> pawn) const { return board_->pawn_pos(pawn); } int Game::make_move(IMove *move, std::shared_ptr<Pawn> pawn) { if (WalkMove *walk_move = dynamic_cast<WalkMove *>(move)) { return board_->make_walking_move(pawn, walk_move->node()); } else if (WallMove *wall_move = dynamic_cast<WallMove *>(move)) { return board_->add_wall(wall_move->wall()); } else { return -1; } } bool Game::is_win(std::shared_ptr<Pawn> pawn) const { return board_->is_at_opposite_side(pawn); } } /* namespace Quoridor */
Make it so that serialisation to PBF happens in only one place.
#include "tile.hpp" #include "vector_tile.pb.h" #include <google/protobuf/io/zero_copy_stream_impl.h> namespace avecado { tile::tile(unsigned int z_, unsigned int x_, unsigned int y_) : z(z_), x(x_), y(y_), m_mapnik_tile(new mapnik::vector::tile) { } tile::~tile() { } std::string tile::get_data() const { std::string buffer; if (m_mapnik_tile->SerializeToString(&buffer)) { return buffer; } else { throw std::runtime_error("Error while serializing protocol buffer tile."); } } mapnik::vector::tile const &tile::mapnik_tile() const { return *m_mapnik_tile; } mapnik::vector::tile &tile::mapnik_tile() { return *m_mapnik_tile; } std::ostream &operator<<(std::ostream &out, const tile &t) { google::protobuf::io::OstreamOutputStream stream(&out); bool write_ok = t.mapnik_tile().SerializeToZeroCopyStream(&stream); if (!write_ok) { throw std::runtime_error("Unable to write tile to output stream."); } return out; } } // namespace avecado
#include "tile.hpp" #include "vector_tile.pb.h" #include <google/protobuf/io/zero_copy_stream_impl.h> namespace avecado { tile::tile(unsigned int z_, unsigned int x_, unsigned int y_) : z(z_), x(x_), y(y_), m_mapnik_tile(new mapnik::vector::tile) { } tile::~tile() { } std::string tile::get_data() const { std::ostringstream buffer; buffer << *this; return buffer.str(); } mapnik::vector::tile const &tile::mapnik_tile() const { return *m_mapnik_tile; } mapnik::vector::tile &tile::mapnik_tile() { return *m_mapnik_tile; } std::ostream &operator<<(std::ostream &out, const tile &t) { google::protobuf::io::OstreamOutputStream stream(&out); bool write_ok = t.mapnik_tile().SerializeToZeroCopyStream(&stream); if (!write_ok) { throw std::runtime_error("Unable to write tile to output stream."); } return out; } } // namespace avecado
Add missing attribute to Terrace codec
#pragma once #include "TerraceWrapperCodec.h" namespace spotify { namespace json { using TerraceWrapper = noise::module::Wrapper<noise::module::Terrace>; codec::object_t<TerraceWrapper> default_codec_t<TerraceWrapper>::codec() { auto codec = codec::object<TerraceWrapper>(); codec.required("type", codec::eq<std::string>("Terrace")); codec.required("SourceModule", codec::ignore_t<int>()); codec.optional("ControlPoints", [](const TerraceWrapper& mw) { std::vector<double> control_points; const double* raw_control_points = mw.module->GetControlPointArray(); const int control_point_count = mw.module->GetControlPointCount(); for (int i = 0; i < control_point_count; i++) { control_points.push_back(raw_control_points[i]); } return control_points; }, [](TerraceWrapper& mw, std::vector<double> all_control_points) { for (double control_point : all_control_points) { mw.module->AddControlPoint(control_point); } }, default_codec<std::vector<double>>()); return codec; } } }
#pragma once #include "TerraceWrapperCodec.h" namespace spotify { namespace json { using TerraceWrapper = noise::module::Wrapper<noise::module::Terrace>; codec::object_t<TerraceWrapper> default_codec_t<TerraceWrapper>::codec() { auto codec = codec::object<TerraceWrapper>(); codec.required("type", codec::eq<std::string>("Terrace")); codec.required("SourceModule", codec::ignore_t<int>()); codec.optional("InvertTerraces", [](const TerraceWrapper& mw) { return mw.module->IsTerracesInverted(); }, [](const TerraceWrapper& mw, bool invert_terraces) { mw.module->InvertTerraces(true); }); codec.optional("ControlPoints", [](const TerraceWrapper& mw) { std::vector<double> control_points; const double* raw_control_points = mw.module->GetControlPointArray(); const int control_point_count = mw.module->GetControlPointCount(); for (int i = 0; i < control_point_count; i++) { control_points.push_back(raw_control_points[i]); } return control_points; }, [](TerraceWrapper& mw, std::vector<double> all_control_points) { for (double control_point : all_control_points) { mw.module->AddControlPoint(control_point); } }, default_codec<std::vector<double>>()); return codec; } } }
Set the transform editor's size.
#include "EntityEditor.hpp" #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ResourceManager.hpp> #include <Engine/Geometry/Rectangle.hpp> #include "TransformEditor.hpp" using namespace GUI; EntityEditor::EntityEditor(Widget* parent) : Widget(parent) { rectangle = Managers().resourceManager->CreateRectangle(); entity = nullptr; transformEditor = new TransformEditor(this); } EntityEditor::~EntityEditor() { Managers().resourceManager->FreeRectangle(); delete transformEditor; } void EntityEditor::Update() { transformEditor->Update(); } void EntityEditor::Render(const glm::vec2& screenSize) { glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f); rectangle->Render(GetPosition(), size, color, screenSize); transformEditor->Render(screenSize); } void EntityEditor::SetPosition(const glm::vec2& position) { Widget::SetPosition(position); transformEditor->SetPosition(position); } glm::vec2 EntityEditor::GetSize() const { return size; } void EntityEditor::SetSize(const glm::vec2& size) { this->size = size; } void EntityEditor::SetEntity(Entity* entity) { this->entity = entity; transformEditor->SetEntity(entity); }
#include "EntityEditor.hpp" #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ResourceManager.hpp> #include <Engine/Geometry/Rectangle.hpp> #include "TransformEditor.hpp" using namespace GUI; EntityEditor::EntityEditor(Widget* parent) : Widget(parent) { rectangle = Managers().resourceManager->CreateRectangle(); entity = nullptr; transformEditor = new TransformEditor(this); } EntityEditor::~EntityEditor() { Managers().resourceManager->FreeRectangle(); delete transformEditor; } void EntityEditor::Update() { transformEditor->Update(); } void EntityEditor::Render(const glm::vec2& screenSize) { glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f); rectangle->Render(GetPosition(), size, color, screenSize); transformEditor->Render(screenSize); } void EntityEditor::SetPosition(const glm::vec2& position) { Widget::SetPosition(position); transformEditor->SetPosition(position); } glm::vec2 EntityEditor::GetSize() const { return size; } void EntityEditor::SetSize(const glm::vec2& size) { this->size = size; transformEditor->SetSize(size); } void EntityEditor::SetEntity(Entity* entity) { this->entity = entity; transformEditor->SetEntity(entity); }
Replace a DCHECK with DCHECK_EQ.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/cancellation_flag.h" #include "base/logging.h" namespace base { void CancellationFlag::Set() { #if !defined(NDEBUG) DCHECK(set_on_ == PlatformThread::CurrentId()); #endif base::subtle::Release_Store(&flag_, 1); } bool CancellationFlag::IsSet() const { return base::subtle::Acquire_Load(&flag_) != 0; } } // namespace base
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/cancellation_flag.h" #include "base/logging.h" namespace base { void CancellationFlag::Set() { #if !defined(NDEBUG) DCHECK_EQ(set_on_, PlatformThread::CurrentId()); #endif base::subtle::Release_Store(&flag_, 1); } bool CancellationFlag::IsSet() const { return base::subtle::Acquire_Load(&flag_) != 0; } } // namespace base
Add test taking the address of a member function template and converting it to a member pointer.
// RUN: clang-cc -fsyntax-only -verify %s struct X { template<typename T> T& f0(T); void g0(int i, double d) { int &ir = f0(i); double &dr = f0(d); } template<typename T> T& f1(T); template<typename T, typename U> U& f1(T, U); void g1(int i, double d) { int &ir1 = f1(i); int &ir2 = f1(d, i); int &ir3 = f1(i, i); } }; void test_X_f0(X x, int i, float f) { int &ir = x.f0(i); float &fr = x.f0(f); } void test_X_f1(X x, int i, float f) { int &ir1 = x.f1(i); int &ir2 = x.f1(f, i); int &ir3 = x.f1(i, i); }
// RUN: clang-cc -fsyntax-only -verify %s struct X { template<typename T> T& f0(T); void g0(int i, double d) { int &ir = f0(i); double &dr = f0(d); } template<typename T> T& f1(T); template<typename T, typename U> U& f1(T, U); void g1(int i, double d) { int &ir1 = f1(i); int &ir2 = f1(d, i); int &ir3 = f1(i, i); } }; void test_X_f0(X x, int i, float f) { int &ir = x.f0(i); float &fr = x.f0(f); } void test_X_f1(X x, int i, float f) { int &ir1 = x.f1(i); int &ir2 = x.f1(f, i); int &ir3 = x.f1(i, i); } void test_X_f0_address() { int& (X::*pm1)(int) = &X::f0; float& (X::*pm2)(float) = &X::f0; } void test_X_f1_address() { int& (X::*pm1)(int) = &X::f1; float& (X::*pm2)(float) = &X::f1; int& (X::*pm3)(float, int) = &X::f1; }
Fix failure of the Timer unit test.
#include "Timer.h" #define BOOST_TEST_MODULE TimerTest #include <boost/test/unit_test.hpp> #include <string> #include <iostream> BOOST_AUTO_TEST_CASE(timer_basic_test) { Timer timer; timer.start(); BOOST_REQUIRE(timer.is_running()); BOOST_REQUIRE(timer.get_elapsed_cpu_time() > 0.0); BOOST_REQUIRE(timer.get_elapsed_cpu_time_microseconds() > 0); BOOST_REQUIRE(timer.get_elapsed_wall_time() > 0.0); BOOST_REQUIRE(timer.get_elapsed_wall_time_microseconds() > 0); timer.restart(); BOOST_REQUIRE(timer.is_running()); BOOST_REQUIRE(timer.get_elapsed_cpu_time() > 0.0); BOOST_REQUIRE(timer.get_elapsed_cpu_time_microseconds() > 0); BOOST_REQUIRE(timer.get_elapsed_wall_time() > 0.0); BOOST_REQUIRE(timer.get_elapsed_wall_time_microseconds() > 0); const std::string s = timer.ToString(); BOOST_REQUIRE(!s.empty()); }
#include "Timer.h" #define BOOST_TEST_MODULE TimerTest #include <boost/test/unit_test.hpp> #include <string> #include <iostream> #include <unistd.h> BOOST_AUTO_TEST_CASE(timer_basic_test) { Timer timer; const int sleep_time_microsec = 40; // ad-hoc microseconds to pass unit tests. timer.start(); BOOST_REQUIRE(timer.is_running()); BOOST_REQUIRE(usleep(sleep_time_microsec) == 0); BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0); BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0); BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0); BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0); timer.restart(); BOOST_REQUIRE(timer.is_running()); BOOST_REQUIRE(usleep(sleep_time_microsec) == 0); BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0); BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0); BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0); BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0); const std::string s = timer.ToString(); BOOST_CHECK(!s.empty()); }
Reset the stdair service shared pointer in order to decrease the count by one every time (and not only when owning the stdair service).
// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> // TravelCCM Basic #include <travelccm/service/TRAVELCCM_ServiceContext.hpp> namespace TRAVELCCM { // ////////////////////////////////////////////////////////////////////// TRAVELCCM_ServiceContext::TRAVELCCM_ServiceContext() : _ownStdairService (false) { } // ////////////////////////////////////////////////////////////////////// TRAVELCCM_ServiceContext:: TRAVELCCM_ServiceContext (const TRAVELCCM_ServiceContext&) { assert (false); } // ////////////////////////////////////////////////////////////////////// TRAVELCCM_ServiceContext::~TRAVELCCM_ServiceContext() { } // ////////////////////////////////////////////////////////////////////// const std::string TRAVELCCM_ServiceContext::shortDisplay() const { std::ostringstream oStr; oStr << "TRAVELCCM_ServiceContext -- Owns StdAir service: " << _ownStdairService; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string TRAVELCCM_ServiceContext::display() const { std::ostringstream oStr; oStr << shortDisplay(); return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string TRAVELCCM_ServiceContext::describe() const { return shortDisplay(); } // ////////////////////////////////////////////////////////////////////// void TRAVELCCM_ServiceContext::reset() { if (_ownStdairService == true) { _stdairService.reset(); } } }
// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> // TravelCCM Basic #include <travelccm/service/TRAVELCCM_ServiceContext.hpp> namespace TRAVELCCM { // ////////////////////////////////////////////////////////////////////// TRAVELCCM_ServiceContext::TRAVELCCM_ServiceContext() : _ownStdairService (false) { } // ////////////////////////////////////////////////////////////////////// TRAVELCCM_ServiceContext:: TRAVELCCM_ServiceContext (const TRAVELCCM_ServiceContext&) { assert (false); } // ////////////////////////////////////////////////////////////////////// TRAVELCCM_ServiceContext::~TRAVELCCM_ServiceContext() { } // ////////////////////////////////////////////////////////////////////// const std::string TRAVELCCM_ServiceContext::shortDisplay() const { std::ostringstream oStr; oStr << "TRAVELCCM_ServiceContext -- Owns StdAir service: " << _ownStdairService; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string TRAVELCCM_ServiceContext::display() const { std::ostringstream oStr; oStr << shortDisplay(); return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string TRAVELCCM_ServiceContext::describe() const { return shortDisplay(); } // ////////////////////////////////////////////////////////////////////// void TRAVELCCM_ServiceContext::reset() { // The shared_ptr<>::reset() method drops the refcount by one. // If the count result is dropping to zero, the resource pointed to // by the shared_ptr<> will be freed. // Reset the stdair shared pointer _stdairService.reset(); } }
Test other sampling rates for good measure.
#include "audio_mixer.hpp" #include "timer.hpp" #include "vorbis_stream.hpp" #include <chrono> #include <thread> #include <cmath> using namespace Granite::Audio; using namespace std; struct SineAudio : BackendCallback { void mix_samples(float * const *channels, size_t num_frames) noexcept override { float *left = channels[0]; float *right = channels[1]; for (size_t i = 0; i < num_frames; i++) { double v = 0.15 * sin(phase); *left++ = float(v); *right++ = float(v); phase += 0.015; } } double phase = 0.0; }; int main() { Mixer mixer; auto *stream = create_vorbis_stream("/tmp/test.ogg"); mixer.add_mixer_stream(stream); auto backend = create_default_audio_backend(44100.0f, 2); backend->start(&mixer); std::this_thread::sleep_for(std::chrono::seconds(100)); backend->stop(); std::this_thread::sleep_for(std::chrono::seconds(3)); backend->start(&mixer); std::this_thread::sleep_for(std::chrono::seconds(100)); }
#include "audio_mixer.hpp" #include "timer.hpp" #include "vorbis_stream.hpp" #include <chrono> #include <thread> #include <cmath> using namespace Granite::Audio; using namespace std; struct SineAudio : BackendCallback { void mix_samples(float * const *channels, size_t num_frames) noexcept override { float *left = channels[0]; float *right = channels[1]; for (size_t i = 0; i < num_frames; i++) { double v = 0.15 * sin(phase); *left++ = float(v); *right++ = float(v); phase += 0.015; } } double phase = 0.0; }; int main() { Mixer mixer; auto *stream = create_vorbis_stream("/tmp/test.ogg"); if (stream) mixer.add_mixer_stream(stream); auto backend = create_default_audio_backend(32000.0f, 2); backend->start(&mixer); std::this_thread::sleep_for(std::chrono::seconds(100)); backend->stop(); std::this_thread::sleep_for(std::chrono::seconds(3)); backend->start(&mixer); std::this_thread::sleep_for(std::chrono::seconds(100)); }
Disable the systray animation setting if Qt lacks mng support and tell the user about it in the tooltip BUG: 161800
/* behaviourconfig_events.cpp Copyright (c) 2006 by Thorben Kröger <thorbenk@gmx.net> Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "behaviorconfig_events.h" BehaviorConfig_Events::BehaviorConfig_Events(QWidget *parent) : QWidget(parent) { setupUi(this); } #include "behaviorconfig_events.moc"
/* behaviourconfig_events.cpp Copyright (c) 2006 by Thorben Kröger <thorbenk@gmx.net> Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "behaviorconfig_events.h" #include <QMovie> BehaviorConfig_Events::BehaviorConfig_Events(QWidget *parent) : QWidget(parent) { setupUi(this); bool supportsMng(false); QList<QByteArray> supportedFormats = QMovie::supportedFormats(); foreach ( QByteArray format, supportedFormats ) { supportsMng = supportsMng || format.toLower() == QByteArray("mng"); } if ( !supportsMng ) { kcfg_trayflashNotify->setEnabled(false); kcfg_trayflashNotify->setToolTip(i18n("Animation is not possible as your Qt version does not support the mng video format.")); } } #include "behaviorconfig_events.moc"
Implement the BMP180 container class
#include "Bmp180.h"
#include "Bmp180.h" namespace rcr { namespace level1payload { Bmp180::Bmp180(void) { // Start the BMP-180. Trap the thread if no sensor is found. if (!bmp_.begin()) { Serial.println("No BMP sensor found. Program will not proceed."); while (1) { /* Trap the thread. */ } } } float Bmp180::temperature(void) { return bmp_.readTemperature(); } int32_t Bmp180::ambient_pressure(void) { return bmp_.readPressure(); } float Bmp180::pressure_altitude(void) { // Use default altimeter setting, // sealevelPressure = 101325 Pascals (std. atmosphere) return bmp_.readAltitude(); } } // namespace level1_payload } // namespace rcr
Fix test result under XFA. This gives an error at an earlier stage, but is fine so long as the crashes don't happen.
// Copyright 2015 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "../../testing/embedder_test.h" #include "../../fpdfsdk/include/fpdfview.h" #include "../../fpdfsdk/include/fpdfdoc.h" #include "testing/gtest/include/gtest/gtest.h" class FPDFDataAvailEmbeddertest : public EmbedderTest { }; TEST_F(FPDFDataAvailEmbeddertest, TrailerUnterminated) { // Document must open without crashing but is too malformed to be available. EXPECT_TRUE(OpenDocument("testing/resources/trailer_unterminated.pdf")); EXPECT_FALSE(FPDFAvail_IsDocAvail(avail_, &hints_)); } TEST_F(FPDFDataAvailEmbeddertest, TrailerAsHexstring) { // Document must open without crashing but is too malformed to be available. EXPECT_TRUE(OpenDocument("testing/resources/trailer_as_hexstring.pdf")); EXPECT_FALSE(FPDFAvail_IsDocAvail(avail_, &hints_)); }
// Copyright 2015 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "../../testing/embedder_test.h" #include "../../fpdfsdk/include/fpdfview.h" #include "../../fpdfsdk/include/fpdfdoc.h" #include "testing/gtest/include/gtest/gtest.h" class FPDFDataAvailEmbeddertest : public EmbedderTest { }; TEST_F(FPDFDataAvailEmbeddertest, TrailerUnterminated) { // Document doesn't even open under XFA but must not crash. EXPECT_FALSE(OpenDocument("testing/resources/trailer_unterminated.pdf")); } TEST_F(FPDFDataAvailEmbeddertest, TrailerAsHexstring) { // Document doesn't even open under XFA but must not crash. EXPECT_FALSE(OpenDocument("testing/resources/trailer_as_hexstring.pdf")); }
Remove unnecessary header from AsyncTimer
#include <aerial_autonomy/common/async_timer.h> #include <iostream> #include <stdexcept> AsyncTimer::AsyncTimer(std::function<void()> function, std::chrono::duration<double> timer_duration) : function_(function), timer_duration_(timer_duration), running_(false) {} AsyncTimer::~AsyncTimer() { running_ = false; if (timer_thread_.joinable()) { timer_thread_.join(); } } void AsyncTimer::start() { if (!running_) { running_ = true; timer_thread_ = std::thread(std::bind(&AsyncTimer::functionTimer, this)); } else { throw std::logic_error("Cannot start AsyncTimer twice!"); } } void AsyncTimer::functionTimer() { while (running_) { auto start = std::chrono::high_resolution_clock::now(); function_(); std::this_thread::sleep_until(start + timer_duration_); } }
#include <aerial_autonomy/common/async_timer.h> #include <stdexcept> AsyncTimer::AsyncTimer(std::function<void()> function, std::chrono::duration<double> timer_duration) : function_(function), timer_duration_(timer_duration), running_(false) {} AsyncTimer::~AsyncTimer() { running_ = false; if (timer_thread_.joinable()) { timer_thread_.join(); } } void AsyncTimer::start() { if (!running_) { running_ = true; timer_thread_ = std::thread(std::bind(&AsyncTimer::functionTimer, this)); } else { throw std::logic_error("Cannot start AsyncTimer twice!"); } } void AsyncTimer::functionTimer() { while (running_) { auto start = std::chrono::high_resolution_clock::now(); function_(); std::this_thread::sleep_until(start + timer_duration_); } }
Add effect2d scene variants to default benchmarks
/* * Copyright © 2017 Collabora Ltd. * * This file is part of vkmark. * * vkmark 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. * * vkmark 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 vkmark. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Alexandros Frantzis <alexandros.frantzis@collabora.com> */ #include "default_benchmarks.h" std::vector<std::string> DefaultBenchmarks::get() { return std::vector<std::string>{ "vertex:device-local=true", "vertex:device-local=false", "texture:anisotropy=0", "texture:anisotropy=16", "shading:shading=gouraud", "shading:shading=blinn-phong-inf", "shading:shading=phong", "shading:shading=cel", "desktop", "cube", "clear" }; }
/* * Copyright © 2017 Collabora Ltd. * * This file is part of vkmark. * * vkmark 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. * * vkmark 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 vkmark. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Alexandros Frantzis <alexandros.frantzis@collabora.com> */ #include "default_benchmarks.h" std::vector<std::string> DefaultBenchmarks::get() { return std::vector<std::string>{ "vertex:device-local=true", "vertex:device-local=false", "texture:anisotropy=0", "texture:anisotropy=16", "shading:shading=gouraud", "shading:shading=blinn-phong-inf", "shading:shading=phong", "shading:shading=cel", "effect2d:kernel=edge", "effect2d:kernel=blur", "desktop", "cube", "clear" }; }
Fix unsigned/signed comparison failure in unittest.
#include "Target.h" #include <cassert> #include <memory> #include "MCTargetDesc/X86MCTargetDesc.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace exegesis { void InitializeX86ExegesisTarget(); namespace { using testing::Gt; using testing::NotNull; using testing::SizeIs; class X86TargetTest : public ::testing::Test { protected: X86TargetTest() : Target_(ExegesisTarget::lookup(llvm::Triple("x86_64-unknown-linux"))) { EXPECT_THAT(Target_, NotNull()); } static void SetUpTestCase() { InitializeX86ExegesisTarget(); } const ExegesisTarget *const Target_; }; TEST_F(X86TargetTest, SetRegToConstantGPR) { const auto Insts = Target_->setRegToConstant(llvm::X86::EAX); EXPECT_THAT(Insts, SizeIs(1)); EXPECT_EQ(Insts[0].getOpcode(), llvm::X86::MOV32ri); EXPECT_EQ(Insts[0].getOperand(0).getReg(), llvm::X86::EAX); } TEST_F(X86TargetTest, SetRegToConstantXMM) { const auto Insts = Target_->setRegToConstant(llvm::X86::XMM1); EXPECT_THAT(Insts, SizeIs(Gt(0))); } } // namespace } // namespace exegesis
#include "Target.h" #include <cassert> #include <memory> #include "MCTargetDesc/X86MCTargetDesc.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace exegesis { void InitializeX86ExegesisTarget(); namespace { using testing::Gt; using testing::NotNull; using testing::SizeIs; class X86TargetTest : public ::testing::Test { protected: X86TargetTest() : Target_(ExegesisTarget::lookup(llvm::Triple("x86_64-unknown-linux"))) { EXPECT_THAT(Target_, NotNull()); } static void SetUpTestCase() { InitializeX86ExegesisTarget(); } const ExegesisTarget *const Target_; }; TEST_F(X86TargetTest, SetRegToConstantGPR) { const auto Insts = Target_->setRegToConstant(llvm::X86::EAX); EXPECT_THAT(Insts, SizeIs(1)); EXPECT_EQ(Insts[0].getOpcode(), llvm::X86::MOV32ri); EXPECT_EQ(Insts[0].getOperand(0).getReg(), llvm::X86::EAX); } TEST_F(X86TargetTest, SetRegToConstantXMM) { const auto Insts = Target_->setRegToConstant(llvm::X86::XMM1); EXPECT_THAT(Insts, SizeIs(Gt(0U))); } } // namespace } // namespace exegesis
Remove some dead math intrinsics
#include "runtime_internal.h" #define INLINE inline __attribute__((weak)) __attribute__((used)) __attribute__((always_inline)) __attribute__((nothrow)) __attribute__((pure)) extern "C" { INLINE float float_from_bits(uint32_t bits) { union { uint32_t as_uint; float as_float; } u; u.as_uint = bits; return u.as_float; } INLINE float nan_f32() { return float_from_bits(0x7fc00000); } INLINE float neg_inf_f32() { return float_from_bits(0xff800000); } INLINE float inf_f32() { return float_from_bits(0x7f800000); } INLINE float maxval_f32() { return float_from_bits(0x7f7fffff); } INLINE float minval_f32() { return float_from_bits(0xff7fffff); } }
#include "runtime_internal.h" #define INLINE inline __attribute__((weak)) __attribute__((used)) __attribute__((always_inline)) __attribute__((nothrow)) __attribute__((pure)) extern "C" { INLINE float float_from_bits(uint32_t bits) { union { uint32_t as_uint; float as_float; } u; u.as_uint = bits; return u.as_float; } INLINE float nan_f32() { return float_from_bits(0x7fc00000); } INLINE float neg_inf_f32() { return float_from_bits(0xff800000); } INLINE float inf_f32() { return float_from_bits(0x7f800000); } }
Check that the ExtensionFunction has a callback for attempting to send a response.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_function.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" void ExtensionFunction::SendResponse(bool success) { if (success) { dispatcher_->SendResponse(this); } else { // TODO(aa): In case of failure, send the error message to an error // callback. } }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_function.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" void ExtensionFunction::SendResponse(bool success) { if (success) { if (has_callback()) { dispatcher_->SendResponse(this); } } else { // TODO(aa): In case of failure, send the error message to an error // callback. } }
Set FunctionVar def_ to nullptr
#include <ast/function-var.hh> #include <ast/any-list.hh> namespace ast { FunctionVar::FunctionVar(const yy::location& location, Var* var, ExprList* params) : Var(location) , var_(var) , params_(params) {} FunctionVar::~FunctionVar() { delete var_; delete params_; } const Var* FunctionVar::var_get() const { return var_; } Var* FunctionVar::var_get() { return var_; } const ExprList* FunctionVar::params_get() const { return params_; } ExprList* FunctionVar::params_get() { return params_; } const FunctionDec* FunctionVar::def_get() const { return def_; } FunctionDec* FunctionVar::def_get() { return def_; } void FunctionVar::def_set(FunctionDec* d) { def_ = d; } void FunctionVar::add_component(Var* v) { if (var_ == nullptr) { var_ = v; return; } var_->add_component(v); } void FunctionVar::accept(Visitor& v) { v(*this); } void FunctionVar::accept(ConstVisitor& v) const { v(*this); } } // namespace ast
#include <ast/function-var.hh> #include <ast/any-list.hh> namespace ast { FunctionVar::FunctionVar(const yy::location& location, Var* var, ExprList* params) : Var(location) , var_(var) , params_(params) , def_(nullptr) {} FunctionVar::~FunctionVar() { delete var_; delete params_; } const Var* FunctionVar::var_get() const { return var_; } Var* FunctionVar::var_get() { return var_; } const ExprList* FunctionVar::params_get() const { return params_; } ExprList* FunctionVar::params_get() { return params_; } const FunctionDec* FunctionVar::def_get() const { return def_; } FunctionDec* FunctionVar::def_get() { return def_; } void FunctionVar::def_set(FunctionDec* d) { def_ = d; } void FunctionVar::add_component(Var* v) { if (var_ == nullptr) { var_ = v; return; } var_->add_component(v); } void FunctionVar::accept(Visitor& v) { v(*this); } void FunctionVar::accept(ConstVisitor& v) const { v(*this); } } // namespace ast
Change task 8 a little Previously it calculated quantity of tables for all studens without taking into account classes. Now it calulates tables needed for each class and then summarise results.
/* Author: vpetrigo Task: . . . , . : ( 1000). - . */ #include <iostream> using namespace std; int main() { int a, b, c; const int p_t = 2; cin >> a >> b >> c; int sum_p = a + b + c; cout << (sum_p + p_t - 1) / p_t << endl; return 0; }
/* Author: vpetrigo Task: . . . , . : ( 1000). - . */ #include <iostream> using namespace std; int table_count(int st); int main() { int a, b, c; cin >> a >> b >> c; cout << table_count(a) + table_count(b) + table_count(c) << endl; return 0; } int table_count(int st) { static const int p_t = 2; return (st + p_t - 1) / 2; }
Fix copy paste error in file_clock tests
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // // TODO: Remove this when filesystem gets integrated into the dylib // REQUIRES: c++filesystem // <chrono> // file_clock // check clock invariants #include <chrono> template <class T> void test(const T &) {} int main() { typedef std::chrono::system_clock C; static_assert((std::is_same<C::rep, C::duration::rep>::value), ""); static_assert((std::is_same<C::period, C::duration::period>::value), ""); static_assert((std::is_same<C::duration, C::time_point::duration>::value), ""); static_assert((std::is_same<C::time_point::clock, C>::value), ""); static_assert((C::is_steady || !C::is_steady), ""); test(std::chrono::system_clock::is_steady); }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // // TODO: Remove this when filesystem gets integrated into the dylib // REQUIRES: c++filesystem // <chrono> // file_clock // check clock invariants #include <chrono> template <class T> void test(const T &) {} int main() { typedef std::chrono::file_clock C; static_assert((std::is_same<C::rep, C::duration::rep>::value), ""); static_assert((std::is_same<C::period, C::duration::period>::value), ""); static_assert((std::is_same<C::duration, C::time_point::duration>::value), ""); static_assert((std::is_same<C::time_point::clock, C>::value), ""); static_assert(!C::is_steady, ""); test(std::chrono::file_clock::is_steady); }
Add new stub function for single threaded tests.
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Ports filebundle.cpp for different OS. #include <common/port_flags.h> #include <errno.h> #include "khThread.h" void khMutexBase::Lock(void) {} void khMutexBase::Unlock(void) {} khMutex::khMutex(void) {}; khMutex::~khMutex() {}; khCondVar::khCondVar(void) {} khCondVar::~khCondVar() {} void khCondVar::signal_one(void) {} void khCondVar::broadcast_all(void) {} void khCondVar::wait(khMutexBase &mutex) {}
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Ports filebundle.cpp for different OS. #include <common/port_flags.h> #include <errno.h> #include "khThread.h" void khMutexBase::Lock(void) {} void khMutexBase::Unlock(void) {} bool khMutexBase::TimedTryLock(uint) { return true; } khMutex::khMutex(void) {}; khMutex::~khMutex() {}; khCondVar::khCondVar(void) {} khCondVar::~khCondVar() {} void khCondVar::signal_one(void) {} void khCondVar::broadcast_all(void) {} void khCondVar::wait(khMutexBase &mutex) {}
Use correct format specifier in HelloWorld
#include <cstdio> #include "Werk/Math/SummaryStatistics.hpp" int main() { werk::SummaryStatistics<double> s; s.sample(5.0); s.sample(1.0); std::printf("Hello world! count=%llu average=%f stddev=%f", s.count(), s.average(), s.stddev()); return 0; }
#include <cinttypes> #include <cstdio> #include "Werk/Math/SummaryStatistics.hpp" int main() { werk::SummaryStatistics<double> s; s.sample(5.0); s.sample(1.0); std::printf("Hello world! count=%" PRIu64 " average=%f stddev=%f", s.count(), s.average(), s.stddev()); return 0; }
Implement archiving list of files
#include "archive.hpp" void archive(const char* in_file, const char* out_file) { throw "Not implemented"; } void archive(const char* in_file, std::ostream& out_stream) { throw "Not implemented"; } void archive(std::istream& in_stream, std::ostream& out_stream) { throw "Not implemented"; }
#include "archive.hpp" #include "../huffman/compress.hpp" #include<fstream> #include<vector> void archive_files(const std::vector<std::string>& filenames, std::ostream& out_stream) { std::ostreambuf_iterator<char> out_iterator(out_stream); for(auto& fn : filenames) { for(char c : fn) *out_iterator = c; *out_iterator = '\0'; } *out_iterator = '\0'; for(auto& fn : filenames) { std::ifstream in(fn); auto freq_table = readTable(in); in.close(); in.open(fn); compress(freq_table, in, out_iterator); } } void archive(const char* in_file, const char* out_file) { std::ofstream out(out_file); archive(in_file, out); } void archive(const char* in_file, std::ostream& out_stream) { throw "Not implemented"; } void archive(std::istream& in_stream, std::ostream& out_stream) { std::vector<std::string> filenames; std::string fn; while(std::getline(in_stream, fn)) filenames.push_back(fn); archive_files(filenames, out_stream); }
Remove pwd to fix WinASan bot
// Test that coverage and MSVC CRT stdio work from a DLL. This ensures that the // __local_stdio_printf_options function isn't instrumented for coverage. // RUN: rm -rf %t && mkdir %t && cd %t // RUN: %clang_cl_asan -fsanitize-coverage=func -O0 %p/dll_host.cc -Fet.exe // RUN: %clang_cl_asan -fsanitize-coverage=func -LD -O0 %s -Fet.dll // RUN: pwd // RUN: %run ./t.exe t.dll 2>&1 | FileCheck %s #include <stdio.h> extern "C" __declspec(dllexport) int test_function() { printf("hello world\n"); // CHECK: hello world return 0; }
// Test that coverage and MSVC CRT stdio work from a DLL. This ensures that the // __local_stdio_printf_options function isn't instrumented for coverage. // RUN: rm -rf %t && mkdir %t && cd %t // RUN: %clang_cl_asan -fsanitize-coverage=func -O0 %p/dll_host.cc -Fet.exe // RUN: %clang_cl_asan -fsanitize-coverage=func -LD -O0 %s -Fet.dll // RUN: %run ./t.exe t.dll 2>&1 | FileCheck %s #include <stdio.h> extern "C" __declspec(dllexport) int test_function() { printf("hello world\n"); // CHECK: hello world return 0; }
Fix linking error at device orientation
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "system_info/system_info_device_orientation.h" #include "system_info/system_info_utils.h" void SysInfoDeviceOrientation::Get(picojson::value& error, picojson::value& data) { system_info::SetPicoJsonObjectValue(error, "message", picojson::value("Device Orientation is not supported on desktop.")); } void PlatformInitialize() { }
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "system_info/system_info_device_orientation.h" #include "system_info/system_info_utils.h" void SysInfoDeviceOrientation::Get(picojson::value& error, picojson::value& data) { system_info::SetPicoJsonObjectValue(error, "message", picojson::value("Device Orientation is not supported on desktop.")); } void SysInfoDeviceOrientation::PlatformInitialize() { }
Fix failure of VPsilane_test when debug_verbose=y
/* * Copyright 2002 California Institute of Technology */ #include "cantera/IdealGasMix.h" #include "cantera/equilibrium.h" #include "cantera/thermo/IdealSolnGasVPSS.h" #include "cantera/thermo/ThermoFactory.h" using namespace std; using namespace Cantera; int main(int argc, char** argv) { #ifdef _MSC_VER _set_output_format(_TWO_DIGIT_EXPONENT); #endif try { Cantera::IdealSolnGasVPSS gg("silane.xml", "silane"); ThermoPhase* g = &gg; //ThermoPhase *g = newPhase("silane.xml", "silane"); cout.precision(4); g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99"); //g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99"); Cantera::ChemEquil_print_lvl = 40; equilibrate(*g, "TP"); std::string r = g->report(true); cout << r; cout << endl; return 0; } catch (CanteraError& err) { std::cerr << err.what() << std::endl; cerr << "program terminating." << endl; return -1; } }
/* * Copyright 2002 California Institute of Technology */ #include "cantera/IdealGasMix.h" #include "cantera/equilibrium.h" #include "cantera/thermo/IdealSolnGasVPSS.h" #include "cantera/thermo/ThermoFactory.h" using namespace std; using namespace Cantera; int main(int argc, char** argv) { #ifdef _MSC_VER _set_output_format(_TWO_DIGIT_EXPONENT); #endif try { Cantera::IdealSolnGasVPSS gg("silane.xml", "silane"); ThermoPhase* g = &gg; //ThermoPhase *g = newPhase("silane.xml", "silane"); cout.precision(4); g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99"); //g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99"); equilibrate(*g, "TP"); std::string r = g->report(true); cout << r; cout << endl; return 0; } catch (CanteraError& err) { std::cerr << err.what() << std::endl; cerr << "program terminating." << endl; return -1; } }
Add license to this test file so license checkers don't complain
#include <regex> int main() { std::regex r(R"(\s*(SIGNAL|SLOT)\s*\(\s*(.+)\s*\(.*)"); return 0; }
/* This file is part of the clang-lazy static checker. Copyright (C) 2015 Sergio Martins <smartins@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <regex> int main() { std::regex r(R"(\s*(SIGNAL|SLOT)\s*\(\s*(.+)\s*\(.*)"); return 0; }
Refactor main to use a test method.
/* * Entry point for the raytracer binary. * Autor: Dino Wernli */ #include <google/protobuf/stubs/common.h> #include <memory> #include "exporter/bmp_exporter.h" #include "proto/configuration.pb.h" #include "renderer/image.h" #include "renderer/renderer.h" #include "scene/camera.h" #include "scene/point_light.h" #include "scene/scene.h" #include "util/point3.h" #include "util/ray.h" #include "util/vector3.h" int main(int argc, char **argv) { raytracer::Configuration config; Scene scene; std::unique_ptr<Renderer> renderer(Renderer::FromConfig(config)); Image image(300, 400); Vector3 vec(1, 2, 4); Point3 p(0, 0, 0); Camera* cam = new Camera(p, vec, vec, 0, 300, 500); Light* light = new PointLight(Point3(0, 0, 0), Color3(0, 0, 0)); scene.AddLight(light); scene.set_camera(cam); scene.Init(); BmpExporter* exporter = new BmpExporter(); renderer->AddListener(exporter); // Free all memory in the protocol buffer library. google::protobuf::ShutdownProtobufLibrary(); return 0; }
/* * Entry point for the raytracer binary. * Autor: Dino Wernli */ #include <google/protobuf/stubs/common.h> #include <memory> #include "exporter/bmp_exporter.h" #include "proto/configuration.pb.h" #include "renderer/image.h" #include "renderer/renderer.h" #include "scene/camera.h" #include "scene/point_light.h" #include "scene/scene.h" #include "util/point3.h" #include "util/ray.h" #include "util/vector3.h" // This is just to test some objects. // TODO(dinow): Remove this when actual functionality... happens. void TestStuff() { Image image(300, 400); Vector3 vec(1, 2, 4); Point3 p(0, 0, 0); raytracer::Configuration config; std::unique_ptr<Renderer> renderer(Renderer::FromConfig(config)); Scene scene; Camera* cam = new Camera(p, vec, vec, 0, 300, 500); Light* light = new PointLight(Point3(0, 0, 0), Color3(0, 0, 0)); scene.AddLight(light); scene.set_camera(cam); scene.Init(); BmpExporter* exporter = new BmpExporter(); renderer->AddListener(exporter); } int main(int argc, char **argv) { TestStuff(); // Free all memory in the protocol buffer library. google::protobuf::ShutdownProtobufLibrary(); return 0; }
Add NSNumber cast from JavaScript function
#include <node.h> #include <v8.h> #include "helpers.h" using namespace v8; using namespace node; namespace node_objc { // Cast a JavaScript "String" to an "NSString" v8::Handle<Value> Cast_NSString (const Arguments& args) { HandleScope scope; String::Utf8Value val(args[0]->ToString()); NSString *rtn = [NSString stringWithUTF8String: *val]; v8::Handle<Object> rtnWrap = WrapId(rtn); return scope.Close(rtnWrap); } void castsInit(v8::Handle<v8::Object> target) { HandleScope scope; NODE_SET_METHOD(target, "NSString", Cast_NSString); } } // namespace node_objc
#import <Foundation/Foundation.h> #include <node.h> #include <v8.h> #include "helpers.h" using namespace v8; using namespace node; namespace node_objc { // Cast a JavaScript "String" to an "NSString" v8::Handle<Value> Cast_NSString (const Arguments& args) { HandleScope scope; String::Utf8Value val(args[0]->ToString()); NSString *rtn = [NSString stringWithUTF8String: *val]; v8::Handle<Object> rtnWrap = WrapId(rtn); return scope.Close(rtnWrap); } // Cast a JavaScript "Number" to an "NSNumber" v8::Handle<Value> Cast_NSNumber (const Arguments& args) { HandleScope scope; double val = args[0]->NumberValue(); NSNumber *rtn = [NSNumber numberWithDouble: val]; v8::Handle<Object> rtnWrap = WrapId(rtn); return scope.Close(rtnWrap); } void castsInit(v8::Handle<v8::Object> target) { HandleScope scope; NODE_SET_METHOD(target, "NSString", Cast_NSString); NODE_SET_METHOD(target, "NSNumber", Cast_NSNumber); } } // namespace node_objc
Fix unused member warning in Release build.
/* * Copyright 2022 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/ResourceCache.h" #include "experimental/graphite/src/Resource.h" #include "include/private/SingleOwner.h" namespace skgpu { #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner) ResourceCache::ResourceCache(SingleOwner* singleOwner) : fSingleOwner(singleOwner) {} void ResourceCache::insertResource(Resource* resource) { ASSERT_SINGLE_OWNER SkASSERT(resource); } } // namespace skgpu
/* * Copyright 2022 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/ResourceCache.h" #include "experimental/graphite/src/Resource.h" #include "include/private/SingleOwner.h" namespace skgpu { #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner) ResourceCache::ResourceCache(SingleOwner* singleOwner) : fSingleOwner(singleOwner) { // TODO: Maybe when things start using ResourceCache, then like Ganesh the compiler won't complain // about not using fSingleOwner in Release builds and we can delete this. #ifndef SK_DEBUG (void)fSingleOwner; #endif } void ResourceCache::insertResource(Resource* resource) { ASSERT_SINGLE_OWNER SkASSERT(resource); } } // namespace skgpu
Change UI to dark style
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include "mainwindow.h" #include <QApplication> #include <QStyleFactory> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setStyle(QStyleFactory::create("Fusion")); QPalette dark; dark.setColor(QPalette::Window, QColor(53, 53, 53)); dark.setColor(QPalette::WindowText, Qt::white); dark.setColor(QPalette::Base, QColor(25, 25, 25)); dark.setColor(QPalette::AlternateBase, QColor(53, 53, 53)); dark.setColor(QPalette::ToolTipBase, Qt::white); dark.setColor(QPalette::ToolTipText, Qt::white); dark.setColor(QPalette::Text, Qt::white); dark.setColor(QPalette::Button, QColor(53, 53, 53)); dark.setColor(QPalette::ButtonText, Qt::white); dark.setColor(QPalette::BrightText, Qt::red); dark.setColor(QPalette::Link, QColor(42, 130, 218)); dark.setColor(QPalette::Highlight, QColor(254,165,0)); dark.setColor(QPalette::HighlightedText, Qt::black); a.setPalette(dark); Main_window w; w.show(); return a.exec(); }
Add debug for server responses
#include "utils/connection.h" namespace utils { Connection::Connection(const std::string& host, const std::string& port) : socket(io_service) { tcp::resolver resolver(io_service); tcp::resolver::query query(host, port); boost::asio::connect(socket, resolver.resolve(query)); response_buf.prepare(8192); } Connection::~Connection() { socket.close(); } jsoncons::json Connection::receive_response(boost::system::error_code* error) { auto len = boost::asio::read_until(socket, response_buf, "\n", *error); if (*error) { return jsoncons::json(); } auto buf = response_buf.data(); std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len); response_buf.consume(len); return jsoncons::json::parse_string(reply); } void Connection::send_requests(const std::vector<jsoncons::json>& msgs) { jsoncons::output_format format; format.escape_all_non_ascii(true); boost::asio::streambuf request_buf; std::ostream s(&request_buf); for (const auto& m : msgs) { // std::cout << "Responded with: " << pretty_print(m) << std::endl; m.to_stream(s, format); s << std::endl; } socket.send(request_buf.data()); } } // namespace utils
#include "utils/connection.h" namespace utils { Connection::Connection(const std::string& host, const std::string& port) : socket(io_service) { tcp::resolver resolver(io_service); tcp::resolver::query query(host, port); boost::asio::connect(socket, resolver.resolve(query)); response_buf.prepare(8192); } Connection::~Connection() { socket.close(); } jsoncons::json Connection::receive_response(boost::system::error_code* error) { auto len = boost::asio::read_until(socket, response_buf, "\n", *error); if (*error) { return jsoncons::json(); } auto buf = response_buf.data(); std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len); response_buf.consume(len); return jsoncons::json::parse_string(reply); } void Connection::send_requests(const std::vector<jsoncons::json>& msgs) { jsoncons::output_format format; format.escape_all_non_ascii(true); boost::asio::streambuf request_buf; std::ostream s(&request_buf); for (const auto& m : msgs) { std::cout << "Responded with: " << pretty_print(m) << std::endl; m.to_stream(s, format); s << std::endl; } socket.send(request_buf.data()); } } // namespace utils
Use tempfiles for the .o outputs.
// Test reading of PCH without original input files. // Generate the PCH, removing the original file: // RUN: echo 'struct S{char c; int i; }; void foo() {}' > %t.h // RUN: echo 'template <typename T> void tf() { T::foo(); }' >> %t.h // RUN: echo '#define RETURN return &i' >> %t.h // RUN: %clang_cc1 -x c++ -emit-pch -o %t.h.pch %t.h // RUN: rm %t.h // Check diagnostic with location in original source: // RUN: %clang_cc1 -include-pch %t.h.pch -Wpadded -emit-obj %s 2> %t.stderr // RUN: grep 'bytes to align' %t.stderr // Check diagnostic with 2nd location in original source: // RUN: not %clang_cc1 -DREDECL -include-pch %t.h.pch -emit-obj %s 2> %t.stderr // RUN: grep 'previous definition is here' %t.stderr // Check diagnostic with instantiation location in original source: // RUN: not %clang_cc1 -DINSTANTIATION -include-pch %t.h.pch -emit-obj %s 2> %t.stderr // RUN: grep 'cannot be used prior to' %t.stderr void qq(S*) {} #ifdef REDECL float foo() {return 0f;} #endif #ifdef INSTANTIATION void f() { tf<int>(); } #endif
// Test reading of PCH without original input files. // Generate the PCH, removing the original file: // RUN: echo 'struct S{char c; int i; }; void foo() {}' > %t.h // RUN: echo 'template <typename T> void tf() { T::foo(); }' >> %t.h // RUN: echo '#define RETURN return &i' >> %t.h // RUN: %clang_cc1 -x c++ -emit-pch -o %t.h.pch %t.h // RUN: rm %t.h // Check diagnostic with location in original source: // RUN: %clang_cc1 -include-pch %t.h.pch -Wpadded -emit-obj -o %t.o %s 2> %t.stderr // RUN: grep 'bytes to align' %t.stderr // Check diagnostic with 2nd location in original source: // RUN: not %clang_cc1 -DREDECL -include-pch %t.h.pch -emit-obj -o %t.o %s 2> %t.stderr // RUN: grep 'previous definition is here' %t.stderr // Check diagnostic with instantiation location in original source: // RUN: not %clang_cc1 -DINSTANTIATION -include-pch %t.h.pch -emit-obj -o %t.o %s 2> %t.stderr // RUN: grep 'cannot be used prior to' %t.stderr void qq(S*) {} #ifdef REDECL float foo() {return 0f;} #endif #ifdef INSTANTIATION void f() { tf<int>(); } #endif
Clean up MetricsService unit test.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metrics/metrics_service.h" #include <string> #include "base/base64.h" #include "testing/gtest/include/gtest/gtest.h" class MetricsServiceTest : public ::testing::Test { }; // Ensure the ClientId is formatted as expected. TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) { std::string clientid = MetricsService::GenerateClientID(); EXPECT_EQ(36U, clientid.length()); std::string hexchars = "0123456789ABCDEF"; for (uint32 i = 0; i < clientid.length(); i++) { char current = clientid.at(i); if (i == 8 || i == 13 || i == 18 || i == 23) { EXPECT_EQ('-', current); } else { EXPECT_TRUE(std::string::npos != hexchars.find(current)); } } } TEST(MetricsServiceTest, IsPluginProcess) { EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN)); EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN)); EXPECT_FALSE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU)); }
// 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 <ctype.h> #include <string> #include "chrome/browser/metrics/metrics_service.h" #include "testing/gtest/include/gtest/gtest.h" // Ensure the ClientId is formatted as expected. TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) { std::string clientid = MetricsService::GenerateClientID(); EXPECT_EQ(36U, clientid.length()); for (size_t i = 0; i < clientid.length(); ++i) { char current = clientid[i]; if (i == 8 || i == 13 || i == 18 || i == 23) EXPECT_EQ('-', current); else EXPECT_TRUE(isxdigit(current)); } } TEST(MetricsServiceTest, IsPluginProcess) { EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN)); EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN)); EXPECT_FALSE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU)); }
Fix MSVC bots which include '__attribute__((thiscall))' in pretty-printed member function types.
// RUN: %clang_cc1 -std=c++2a %s -verify struct X { void ref() & {} void cref() const& {} }; void test() { X{}.ref(); // expected-error{{cannot initialize object parameter of type 'X' with an expression of type 'X'}} X{}.cref(); // expected-no-error (X{}.*&X::ref)(); // expected-error{{pointer-to-member function type 'void (X::*)() &' can only be called on an lvalue}} (X{}.*&X::cref)(); // expected-no-error }
// RUN: %clang_cc1 -std=c++2a %s -verify struct X { void ref() & {} void cref() const& {} }; void test() { X{}.ref(); // expected-error{{cannot initialize object parameter of type 'X' with an expression of type 'X'}} X{}.cref(); // expected-no-error (X{}.*&X::ref)(); // expected-error-re{{pointer-to-member function type 'void (X::*)() {{.*}}&' can only be called on an lvalue}} (X{}.*&X::cref)(); // expected-no-error }
Create useful function to convert a number to string.
#include <bits/stdc++.h> #define pb push_back using namespace std; typedef vector <string> vs; int toNum(string a){ stringstream toNum(a); int num; toNum >> num; return num; } vs split(string line, char d){ vector < string > elements; stringstream ss(line); string item; while(getline(ss, item, d)) elements.pb(item); return elements; } int main(){ vs d1 = split("1990/10/5", '/'); for (string s: d1){ cout << toNum(s) << endl; } char a = 'a'; cout << (isalnum(a)?"true":"false") << endl; cout <<( isalpha(a)?"true":"false") << endl; cout << (isblank(a)?"true":"false") << endl; cout << (isdigit(a)?"true":"false") << endl; cout << (islower(a)?"true":"false") << endl; cout << (ispunct(a)?"true":"false") << endl; cout << (isupper(a)?"true":"false") << endl; cout << (isxdigit(a) ?"true":"false") << endl; cout << (char)tolower(a) << endl; cout << (char)toupper(a) << endl; return 0; }
#include <bits/stdc++.h> #define pb push_back using namespace std; typedef vector <string> vs; int toNum(string a){ stringstream toNum(a); int num; toNum >> num; return num; } string toString(double d){ stringstream ss; ss << fixed << setprecision(10) << fl; string num = ss.str(); return num; } vs split(string line, char d){ vector < string > elements; stringstream ss(line); string item; while(getline(ss, item, d)) elements.pb(item); return elements; } int main(){ vs d1 = split("1990/10/5", '/'); for (string s: d1){ cout << toNum(s) << endl; } char a = 'a'; cout << (isalnum(a)?"true":"false") << endl; cout <<( isalpha(a)?"true":"false") << endl; cout << (isblank(a)?"true":"false") << endl; cout << (isdigit(a)?"true":"false") << endl; cout << (islower(a)?"true":"false") << endl; cout << (ispunct(a)?"true":"false") << endl; cout << (isupper(a)?"true":"false") << endl; cout << (isxdigit(a) ?"true":"false") << endl; cout << (char)tolower(a) << endl; cout << (char)toupper(a) << endl; return 0; }
Fix compilation error on MSVC++.
/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "logaction.h" LogAction::LogAction(Application *application) : mDialog(application) { } QString LogAction::name() const { return "log"; } bool LogAction::ui() const { return true; } QString LogAction::title() const { return tr("View Log"); } bool LogAction::invoke(const QVariantMap &) { mDialog.show(); }
/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "logaction.h" LogAction::LogAction(Application *application) : mDialog(application) { } QString LogAction::name() const { return "log"; } bool LogAction::ui() const { return true; } QString LogAction::title() const { return tr("View Log"); } bool LogAction::invoke(const QVariantMap &) { mDialog.show(); return true; }
Allow for struct padding in test
#include <stdio.h> #include "Halide.h" #define CHECK(f, s32, s64) \ static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong") int main(int argc, char **argv) { CHECK(dev, 0, 0); CHECK(host, 8, 8); CHECK(extent, 12, 16); CHECK(stride, 28, 32); CHECK(min, 44, 48); CHECK(elem_size, 60, 64); CHECK(host_dirty, 64, 68); CHECK(dev_dirty, 65, 69); CHECK(_padding, 66, 70); static_assert(sizeof(buffer_t) == (sizeof(void*) == 8 ? 72 : 68), "size is wrong"); // Ensure alignment is at least that of a pointer. static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong"); printf("Success!\n"); return 0; }
#include <stdio.h> #include "Halide.h" #define CHECK(f, s32, s64) \ static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong") int main(int argc, char **argv) { CHECK(dev, 0, 0); CHECK(host, 8, 8); CHECK(extent, 12, 16); CHECK(stride, 28, 32); CHECK(min, 44, 48); CHECK(elem_size, 60, 64); CHECK(host_dirty, 64, 68); CHECK(dev_dirty, 65, 69); CHECK(_padding, 66, 70); static_assert(sizeof(void*) == 8 ? sizeof(buffer_t) == 72 : // Some compilers may insert padding at the end of the struct // so that an array will stay appropriately aligned for // the int64 field. (sizeof(buffer_t) == 68 || sizeof(buffer_t) == 72), "size is wrong"); // Ensure alignment is at least that of a pointer. static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong"); printf("Success!\n"); return 0; }
Add getting keybindings from argv
#include <ncurses.h> #include "print.hpp" #include "lightsout.hpp" #include "keybindings.hpp" using namespace roadagain; int main() { initscr(); cbreak(); noecho(); curs_set(0); start_color(); init_colors(); board b(5, 5); keybindings k("emacs"); while (!b.is_perfect()){ char c = getch(); const char* key = keyname(c); b.move_board(k.dy(key), k.dx(key)); } endwin(); return 0; }
#include <ncurses.h> #include <cstring> #include <string> #include "print.hpp" #include "lightsout.hpp" #include "keybindings.hpp" using namespace roadagain; int main(int argc, char** argv) { initscr(); cbreak(); noecho(); curs_set(0); start_color(); init_colors(); std::string key = "vim"; for (int i = 1; i < argc; i++){ if (std::strncmp("--key=", argv[i], 6) == 0){ key = argv[i] + 6; } } board b(5, 5); keybindings k(key.c_str()); while (!b.is_perfect()){ char c = getch(); const char* key = keyname(c); b.move_board(k.dy(key), k.dx(key)); } endwin(); return 0; }
Update comments and remove bogus DCHECK in windows-specific broadcasted power message status.
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/system_monitor.h" namespace base { void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) { PowerEvent power_event; switch (event_id) { case PBT_APMPOWERSTATUSCHANGE: power_event = POWER_STATE_EVENT; break; case PBT_APMRESUMEAUTOMATIC: power_event = RESUME_EVENT; break; case PBT_APMSUSPEND: power_event = SUSPEND_EVENT; break; default: DCHECK(false); } ProcessPowerMessage(power_event); } // Function to query the system to see if it is currently running on // battery power. Returns true if running on battery. bool SystemMonitor::IsBatteryPower() { SYSTEM_POWER_STATUS status; if (!GetSystemPowerStatus(&status)) { LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError(); return false; } return (status.ACLineStatus == 0); } } // namespace base
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/system_monitor.h" namespace base { void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) { PowerEvent power_event; switch (event_id) { case PBT_APMPOWERSTATUSCHANGE: // The power status changed. power_event = POWER_STATE_EVENT; break; case PBT_APMRESUMEAUTOMATIC: // Non-user initiated resume from suspend. case PBT_APMRESUMESUSPEND: // User initiated resume from suspend. power_event = RESUME_EVENT; break; case PBT_APMSUSPEND: // System has been suspended. power_event = SUSPEND_EVENT; break; default: return; // Other Power Events: // PBT_APMBATTERYLOW - removed in Vista. // PBT_APMOEMEVENT - removed in Vista. // PBT_APMQUERYSUSPEND - removed in Vista. // PBT_APMQUERYSUSPENDFAILED - removed in Vista. // PBT_APMRESUMECRITICAL - removed in Vista. // PBT_POWERSETTINGCHANGE - user changed the power settings. } ProcessPowerMessage(power_event); } // Function to query the system to see if it is currently running on // battery power. Returns true if running on battery. bool SystemMonitor::IsBatteryPower() { SYSTEM_POWER_STATUS status; if (!GetSystemPowerStatus(&status)) { LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError(); return false; } return (status.ACLineStatus == 0); } } // namespace base
Add dummy test for memory allocator.
//////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 17.07.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include <memory/allocator.h> #include <memory/regions.h> using namespace Memory; int main() { IAllocator::init(); MemoryRegions& regions = MemoryRegions::instance(); regions.count(); return 0; }
//////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 17.07.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include <memory/allocator.h> #include <memory/regions.h> #include <memory/page.h> using namespace Memory; int main() { IAllocator::init(); MemoryRegions& regions = MemoryRegions::instance(); regions.count(); Page* page = new Page(); delete page; return 0; }
Add static shape inference to BytesLimit and MaxBytesInUse.
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/op.h" namespace tensorflow { REGISTER_OP("BytesLimit").Output("out: int64").SetIsStateful(); REGISTER_OP("MaxBytesInUse").Output("out: int64").SetIsStateful(); } // namespace tensorflow
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" namespace tensorflow { REGISTER_OP("BytesLimit") .Output("out: int64") .SetIsStateful() .SetShapeFn(shape_inference::ScalarShape); REGISTER_OP("MaxBytesInUse") .Output("out: int64") .SetIsStateful() .SetShapeFn(shape_inference::ScalarShape); } // namespace tensorflow
Convert the result of xla::ReplicaId to S32
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/xla_builder.h" namespace tensorflow { namespace { class XlaReplicaIdOp : public XlaOpKernel { public: explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override; private: TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp); }; void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) { ctx->SetOutput(0, xla::ReplicaId(ctx->builder())); } REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp); } // namespace } // namespace tensorflow
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/xla_builder.h" namespace tensorflow { namespace { class XlaReplicaIdOp : public XlaOpKernel { public: explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override; private: TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp); }; void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) { ctx->SetOutput( 0, xla::ConvertElementType(xla::ReplicaId(ctx->builder()), xla::S32)); } REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp); } // namespace } // namespace tensorflow
Add tests for registering the formats
#include <string> #include "catch.hpp" #include "Chemharp.hpp" #include "FormatFactory.hpp" #include "Frame.hpp" #include "formats/XYZ.hpp" using namespace harp; // Dummy format clase class DummyFormat : public Format { public: DummyFormat(){} std::string description() const {return "";} REGISTER_FORMAT; }; REGISTER(DummyFormat, "Dummy"); REGISTER_EXTENSION(DummyFormat, ".dummy"); TEST_CASE("Get registered format", "[format factory]"){ auto dummy = DummyFormat(); auto format = FormatFactory::by_extension(".dummy"); REQUIRE(typeid(dummy) == typeid(*format)); format = FormatFactory::format("Dummy"); REQUIRE(typeid(dummy) == typeid(*format)); auto XYZ = XYZFormat(); format = FormatFactory::by_extension(".xyz"); REQUIRE(typeid(XYZ) == typeid(*format)); format = FormatFactory::format("XYZ"); REQUIRE(typeid(XYZ) == typeid(*format)); }
#include <string> #include "catch.hpp" #include "Chemharp.hpp" #include "FormatFactory.hpp" #include "Error.hpp" #include "formats/XYZ.hpp" #include "Frame.hpp" using namespace harp; // Dummy format clase class DummyFormat : public Format { public: DummyFormat(){} std::string description() const {return "";} REGISTER_FORMAT; }; REGISTER(DummyFormat, "Dummy"); REGISTER_EXTENSION(DummyFormat, ".dummy"); TEST_CASE("Registering a new format", "[format factory]"){ CHECK(FormatFactory::register_extension(".testing",[](){ return unique_ptr<Format>(new DummyFormat()); }) ); // We can not register the same format twice CHECK_THROWS_AS(FormatFactory::register_extension(".testing",[](){ return unique_ptr<Format>(new DummyFormat()); }), FormatError ); CHECK(FormatFactory::register_format("DummyFormat",[](){ return unique_ptr<Format>(new DummyFormat()); }) ); // We can not register the same format twice CHECK_THROWS_AS(FormatFactory::register_format("DummyFormat",[](){ return unique_ptr<Format>(new DummyFormat()); }), FormatError ); } TEST_CASE("Geting registered format", "[format factory]"){ auto dummy = DummyFormat(); auto format = FormatFactory::by_extension(".dummy"); REQUIRE(typeid(dummy) == typeid(*format)); format = FormatFactory::format("Dummy"); REQUIRE(typeid(dummy) == typeid(*format)); auto XYZ = XYZFormat(); format = FormatFactory::by_extension(".xyz"); REQUIRE(typeid(XYZ) == typeid(*format)); format = FormatFactory::format("XYZ"); REQUIRE(typeid(XYZ) == typeid(*format)); }
Add newline at end of file.
// For now, this is an empty .cc file that only serves to confirm // named_value_vector.h is // a stand-alone header. #include "drake/systems/framework/named_value_vector.h"
// For now, this is an empty .cc file that only serves to confirm // named_value_vector.h is // a stand-alone header. #include "drake/systems/framework/named_value_vector.h"
Fix heap corruption that occurs when RenderViewHostObserver calls RenderViewHost to unregister when the latter is in its destructor.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/render_view_host_observer.h" #include "content/browser/renderer_host/render_view_host.h" RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host) : render_view_host_(render_view_host), routing_id_(render_view_host->routing_id()) { render_view_host_->AddObserver(this); } RenderViewHostObserver::~RenderViewHostObserver() { if (render_view_host_) render_view_host_->RemoveObserver(this); } void RenderViewHostObserver::RenderViewHostDestroyed() { delete this; } bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) { return false; } bool RenderViewHostObserver::Send(IPC::Message* message) { if (!render_view_host_) { delete message; return false; } return render_view_host_->Send(message); } void RenderViewHostObserver::RenderViewHostDestruction() { render_view_host_->RemoveObserver(this); RenderViewHostDestroyed(); render_view_host_ = NULL; }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/render_view_host_observer.h" #include "content/browser/renderer_host/render_view_host.h" RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host) : render_view_host_(render_view_host), routing_id_(render_view_host->routing_id()) { render_view_host_->AddObserver(this); } RenderViewHostObserver::~RenderViewHostObserver() { if (render_view_host_) render_view_host_->RemoveObserver(this); } void RenderViewHostObserver::RenderViewHostDestroyed() { delete this; } bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) { return false; } bool RenderViewHostObserver::Send(IPC::Message* message) { if (!render_view_host_) { delete message; return false; } return render_view_host_->Send(message); } void RenderViewHostObserver::RenderViewHostDestruction() { render_view_host_ = NULL; RenderViewHostDestroyed(); }
Remove color transformation test code
// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "VerticalBar.h" VerticalBar::VerticalBar(std::wstring bitmapName, int x, int y, int units, bool reversed) : Meter(bitmapName, x, y, units), _pixelsPerUnit(_rect.Height / _units), _reversed(reversed) { } void VerticalBar::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) { int height = _pixelsPerUnit * CalcUnits(); int yOffset = _rect.Y + _rect.Height - height; Gdiplus::Rect drawRect(_rect.X, yOffset, _rect.Width, height); if (_reversed) { drawRect.Y = _rect.Y; } Gdiplus::ImageAttributes ia; Gdiplus::ColorMap blackToRed; blackToRed.oldColor = Gdiplus::Color(255, 255, 0, 255); // black blackToRed.newColor = Gdiplus::Color(255, 255, 0, 0);// red ia.SetRemapTable(1, &blackToRed); graphics->DrawImage(_bitmap, drawRect, 0, 0, _rect.Width, height, Gdiplus::UnitPixel, &ia, NULL, NULL); UpdateDrawnValues(); }
// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "VerticalBar.h" VerticalBar::VerticalBar(std::wstring bitmapName, int x, int y, int units, bool reversed) : Meter(bitmapName, x, y, units), _pixelsPerUnit(_rect.Height / _units), _reversed(reversed) { } void VerticalBar::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) { int height = _pixelsPerUnit * CalcUnits(); int yOffset = _rect.Y + _rect.Height - height; Gdiplus::Rect drawRect(_rect.X, yOffset, _rect.Width, height); if (_reversed) { drawRect.Y = _rect.Y; } graphics->DrawImage(_bitmap, drawRect, 0, 0, _rect.Width, height, Gdiplus::UnitPixel, &_imageAttributes,NULL, NULL); UpdateDrawnValues(); }
Improve error message when a component descriptor is not implemented
// Copyright (c) 2004-present, Facebook, Inc. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "ComponentDescriptorRegistry.h" namespace facebook { namespace react { void ComponentDescriptorRegistry::registerComponentDescriptor(SharedComponentDescriptor componentDescriptor) { ComponentHandle componentHandle = componentDescriptor->getComponentHandle(); _registryByHandle[componentHandle] = componentDescriptor; ComponentName componentName = componentDescriptor->getComponentName(); _registryByName[componentName] = componentDescriptor; } const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const SharedShadowNode &shadowNode) const { ComponentHandle componentHandle = shadowNode->getComponentHandle(); return _registryByHandle.at(componentHandle); } const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const ComponentName &componentName) const { return _registryByName.at(componentName); } } // namespace react } // namespace facebook
// Copyright (c) 2004-present, Facebook, Inc. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "ComponentDescriptorRegistry.h" namespace facebook { namespace react { void ComponentDescriptorRegistry::registerComponentDescriptor(SharedComponentDescriptor componentDescriptor) { ComponentHandle componentHandle = componentDescriptor->getComponentHandle(); _registryByHandle[componentHandle] = componentDescriptor; ComponentName componentName = componentDescriptor->getComponentName(); _registryByName[componentName] = componentDescriptor; } const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const SharedShadowNode &shadowNode) const { ComponentHandle componentHandle = shadowNode->getComponentHandle(); return _registryByHandle.at(componentHandle); } const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const ComponentName &componentName) const { auto it = _registryByName.find(componentName); if (it == _registryByName.end()) { throw std::invalid_argument(("Unable to find componentDescriptor for " + componentName).c_str()); } return it->second; } } // namespace react } // namespace facebook
Comment out broken parts of Demo04 to fix build
#include <ionWindow.h> #include <ionGraphics.h> #include <ionGraphicsGL.h> #include <ionScene.h> using namespace ion; using namespace Scene; using namespace Graphics; int main() { //////////////////// // ionEngine Init // //////////////////// Log::AddDefaultOutputs(); SingletonPointer<CWindowManager> WindowManager; SingletonPointer<CSceneManager> SceneManager; WindowManager->Init(); CWindow * Window = WindowManager->CreateWindow(vec2i(640, 480), "DemoScene", EWindowType::Windowed); IGraphicsAPI * GraphicsAPI = new COpenGLAPI(); CSimpleMesh * Mesh = CGeometryCreator::CreateSphere(); ICamera * Camera = nullptr; SceneManager->GetScene()->SetActiveCamera(Camera = SceneManager->GetFactory()->AddPerspectiveCamera((Window->GetAspectRatio()))); Camera->SetPosition(vec3f(0, 0, -3)); ion::GL::Context::Init(); while (! WindowManager->ShouldClose()) { WindowManager->PollEvents(); SceneManager->DrawAll(); Window->SwapBuffers(); } return 0; }
#include <ionWindow.h> #include <ionGraphics.h> #include <ionGraphicsGL.h> #include <ionScene.h> using namespace ion; using namespace Scene; using namespace Graphics; int main() { //////////////////// // ionEngine Init // //////////////////// Log::AddDefaultOutputs(); SingletonPointer<CWindowManager> WindowManager; SingletonPointer<CSceneManager> SceneManager; WindowManager->Init(); CWindow * Window = WindowManager->CreateWindow(vec2i(640, 480), "DemoScene", EWindowType::Windowed); IGraphicsAPI * GraphicsAPI = new COpenGLAPI(); CSimpleMesh * Mesh = CGeometryCreator::CreateSphere(); ICamera * Camera = nullptr; //SceneManager->GetScene()->SetActiveCamera(Camera = SceneManager->GetFactory()->AddPerspectiveCamera((Window->GetAspectRatio()))); //Camera->SetPosition(vec3f(0, 0, -3)); //ion::GL::Context::Init(); while (WindowManager->Run()) { SceneManager->DrawAll(); Window->SwapBuffers(); } return 0; }
Remove unused header and function
//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=// // // This inserts a global constant table with function pointers all along // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Instrumentation/EmitFunctions.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Module.h" using std::vector; namespace { struct EmitFunctionTable : public Pass { bool run(Module &M); }; RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table"); } // Create a new pass to add function table // Pass *createEmitFunctionTablePass() { return new EmitFunctionTable(); } // Per Module pass for inserting function table bool EmitFunctionTable::run(Module &M){ vector<const Type*> vType; vector<Constant *> vConsts; for(Module::iterator MI = M.begin(), ME = M.end(); MI!=ME; ++MI) if (!MI->isExternal()) { ConstantPointerRef *CP = ConstantPointerRef::get(MI); vType.push_back(MI->getType()); vConsts.push_back(CP); } StructType *sttype = StructType::get(vType); ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts); GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true, false, cstruct, "llvmFunctionTable"); M.getGlobalList().push_back(gb); return true; // Always modifies program }
//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=// // // This inserts a global constant table with function pointers all along // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Module.h" using std::vector; namespace { struct EmitFunctionTable : public Pass { bool run(Module &M); }; RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table"); } // Per Module pass for inserting function table bool EmitFunctionTable::run(Module &M){ vector<const Type*> vType; vector<Constant *> vConsts; for(Module::iterator MI = M.begin(), ME = M.end(); MI!=ME; ++MI) if (!MI->isExternal()) { ConstantPointerRef *CP = ConstantPointerRef::get(MI); vType.push_back(MI->getType()); vConsts.push_back(CP); } StructType *sttype = StructType::get(vType); ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts); GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true, false, cstruct, "llvmFunctionTable"); M.getGlobalList().push_back(gb); return true; // Always modifies program }
Improve testing for extern temp templates, slightly. We are (properly) suppressing the implicit instantiation of members of extern templates
// RUN: clang-cc -fsyntax-only %s template<typename T> class X0 { public: void f(T t); }; template<typename T> void X0<T>::f(T t) { t = 17; } // FIXME: Later, we'll want to write an explicit template // declaration (extern template) for X0<int*>, then try to // call X0<int*>::f. The translation unit should succeed, // because we're not allowed to instantiate the out-of-line // definition of X0<T>::f. For now, this is just a parsing // test. extern template class X0<int>;
// RUN: clang-cc -fsyntax-only %s template<typename T> class X0 { public: void f(T t); struct Inner { void g(T t); }; }; template<typename T> void X0<T>::f(T t) { t = 17; } extern template class X0<int>; extern template class X0<int*>; template<typename T> void X0<T>::Inner::g(T t) { t = 17; } void test_intptr(X0<int*> xi, X0<int*>::Inner xii) { xi.f(0); xii.g(0); }
Add exception description string to log for runtime_error
/* * Copyright 2014 The Imaging Source Europe GmbH * * 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 "DeviceInterface.h" #include "logging.h" #include "BackendLoader.h" #include <algorithm> #include <memory> using namespace tcam; std::shared_ptr<DeviceInterface> tcam::openDeviceInterface (const DeviceInfo& device) { try { return BackendLoader::getInstance().open_device(device); } catch (...) { tcam_log(TCAM_LOG_ERROR, "Encountered Error while creating device interface."); return nullptr; } return nullptr; }
/* * Copyright 2014 The Imaging Source Europe GmbH * * 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 "DeviceInterface.h" #include "logging.h" #include "BackendLoader.h" #include <algorithm> #include <memory> using namespace tcam; std::shared_ptr<DeviceInterface> tcam::openDeviceInterface (const DeviceInfo& device) { try { return BackendLoader::getInstance().open_device(device); } catch (const std::runtime_error& err) { tcam_error("Encountered Error while creating device interface. %s", err.what()); return nullptr; } catch (...) { tcam_error("Caught unhandled exception while opening device."); } return nullptr; }
Remove NSLog statements. Add WrapInstance support for FileTrack.
#include "Item.h" using namespace node; using namespace v8; namespace node_iTunes { // Convenience function that takes an iTunesItem instance (or any subclass) // and wraps it up into the proper JS class type, and returns it. // TODO: Implement some kind of Object Cache, so if the same instance is // attempting to be wrapped again, then the same JS Object is returned. v8::Handle<Value> Item::WrapInstance(iTunesItem* item) { HandleScope scope; NSLog(@"%@", item); if (item == nil) { return scope.Close(Null()); } NSString* className = NSStringFromClass([item class]); NSLog(@"Class: %@", className); Local<Object> jsItem; if ([className isEqualToString:@"ITunesURLTrack" ]) { jsItem = url_track_constructor_template->GetFunction()->NewInstance(); } else { jsItem = track_constructor_template->GetFunction()->NewInstance(); } Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem); itemWrap->itemRef = item; return scope.Close(jsItem); } }
#include "Item.h" using namespace node; using namespace v8; namespace node_iTunes { // Convenience function that takes an iTunesItem instance (or any subclass) // and wraps it up into the proper JS class type, and returns it. // TODO: Implement some kind of Object Cache, so if the same instance is // attempting to be wrapped again, then the same JS Object is returned. v8::Handle<Value> Item::WrapInstance(iTunesItem* item) { HandleScope scope; //NSLog(@"%@", [item persistentID]); if (item == nil) { return scope.Close(Null()); } NSString* className = NSStringFromClass([item class]); //NSLog(@"Class: %@", className); Local<Object> jsItem; if ([className isEqualToString:@"ITunesURLTrack" ]) { jsItem = url_track_constructor_template->GetFunction()->NewInstance(); } else if ([className isEqualToString:@"ITunesFileTrack" ]) { jsItem = file_track_constructor_template->GetFunction()->NewInstance(); } else if ([className isEqualToString:@"ITunesTrack" ]) { jsItem = track_constructor_template->GetFunction()->NewInstance(); } else { jsItem = item_constructor_template->GetFunction()->NewInstance(); } Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem); itemWrap->itemRef = item; return scope.Close(jsItem); } }