Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Check that sample frequencies agree between original generator and buffer.
#include "aquila/source/generator/SineGenerator.h" #include "aquila/wrappers/SoundBufferAdapter.h" #include "UnitTest++/UnitTest++.h" SUITE(SoundBufferAdapter) { TEST(NumSamples) { Aquila::SineGenerator generator(128); generator.setAmplitude(1).setFrequency(8).generate(64); Aquila::SoundBufferAdapter buffer(generator); CHECK_EQUAL(generator.length(), buffer.getSampleCount()); } }
#include "aquila/source/generator/SineGenerator.h" #include "aquila/wrappers/SoundBufferAdapter.h" #include "UnitTest++/UnitTest++.h" SUITE(SoundBufferAdapter) { TEST(NumSamples) { Aquila::SineGenerator generator(128); generator.setAmplitude(1).setFrequency(8).generate(64); Aquila::SoundBufferAdapter buffer(generator); CHECK_EQUAL(generator.length(), buffer.getSampleCount()); } TEST(SampleFrequency) { Aquila::SineGenerator generator(128); generator.setAmplitude(1).setFrequency(8).generate(64); Aquila::SoundBufferAdapter buffer(generator); CHECK_EQUAL(static_cast<unsigned int>(generator.getSampleFrequency()), buffer.getSampleRate()); } }
Fix detection of lib if we use `-Werror`
/** * @file * * @brief compilation test for checking if the Botan library is available. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include <botan/init.h> int main (int argc, char ** argv) { Botan::LibraryInitializer::initialize (""); return 0; }
/** * @file * * @brief compilation test for checking if the Botan library is available. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include <botan/init.h> int main (void) { Botan::LibraryInitializer::initialize (""); return 0; }
Update clang test for r350939
// REQUIRES: x86-registered-target // RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s // Basic functionality test. Function merging doesn't kick in on functions that // are too simple. struct A { virtual int f(int x, int *p) { return x ? *p : 1; } virtual int g(int x, int *p) { return x ? *p : 1; } } a; // CHECK: define {{.*}} @_ZN1A1gEiPi // CHECK-NEXT: tail call i32 @_ZN1A1fEiPi // CHECK-NEXT: ret
// REQUIRES: x86-registered-target // RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s -implicit-check-not=_ZN1A1gEiPi // Basic functionality test. Function merging doesn't kick in on functions that // are too simple. struct A { virtual int f(int x, int *p) { return x ? *p : 1; } virtual int g(int x, int *p) { return x ? *p : 1; } } a; // CHECK: define {{.*}} @_ZN1A1fEiPi
Add checks for unique value of array<T, 0>.begin() and array<T, 0>.end()
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <array> // iterator begin(); #include <array> #include <cassert> // std::array is explicitly allowed to be initialized with A a = { init-list };. // Disable the missing braces warning for this reason. #include "disable_missing_braces_warning.h" struct NoDefault { NoDefault(int) {} }; int main() { { typedef double T; typedef std::array<T, 3> C; C c = {1, 2, 3.5}; C::iterator i; i = c.begin(); assert(*i == 1); assert(&*i == c.data()); *i = 5.5; assert(c[0] == 5.5); } { typedef NoDefault T; typedef std::array<T, 0> C; C c = {}; assert(c.begin() == c.end()); } }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <array> // iterator begin(); #include <array> #include <cassert> #include "test_macros.h" // std::array is explicitly allowed to be initialized with A a = { init-list };. // Disable the missing braces warning for this reason. #include "disable_missing_braces_warning.h" struct NoDefault { NoDefault(int) {} }; int main() { { typedef double T; typedef std::array<T, 3> C; C c = {1, 2, 3.5}; C::iterator i; i = c.begin(); assert(*i == 1); assert(&*i == c.data()); *i = 5.5; assert(c[0] == 5.5); } { typedef NoDefault T; typedef std::array<T, 0> C; C c = {}; C::iterator ib, ie; ib = c.begin(); ie = c.end(); assert(ib == ie); LIBCPP_ASSERT(ib != nullptr); LIBCPP_ASSERT(ie != nullptr); } }
Test sk_linear_to_srgb() less exhaustively in Debug mode.
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSRGB.h" #include "SkTypes.h" #include "Test.h" #include <math.h> static uint8_t linear_to_srgb(float l) { return (uint8_t)sk_linear_to_srgb(Sk4f{l})[0]; } DEF_TEST(sk_linear_to_srgb, r) { // All bytes should round trip. for (int i = 0; i < 256; i++) { int actual = linear_to_srgb(sk_linear_from_srgb[i]); if (i != actual) { ERRORF(r, "%d -> %d\n", i, actual); } } // Should be monotonic between 0 and 1. uint8_t prev = 0; for (float f = FLT_MIN; f <= 1.0f; ) { // We don't bother checking denorm values. uint8_t srgb = linear_to_srgb(f); REPORTER_ASSERT(r, srgb >= prev); prev = srgb; union { float flt; uint32_t bits; } pun = { f }; pun.bits++; f = pun.flt; } }
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSRGB.h" #include "SkTypes.h" #include "Test.h" #include <math.h> static uint8_t linear_to_srgb(float l) { return (uint8_t)sk_linear_to_srgb(Sk4f{l})[0]; } DEF_TEST(sk_linear_to_srgb, r) { // All bytes should round trip. for (int i = 0; i < 256; i++) { int actual = linear_to_srgb(sk_linear_from_srgb[i]); if (i != actual) { ERRORF(r, "%d -> %d\n", i, actual); } } // Should be monotonic between 0 and 1. uint8_t prev = 0; for (float f = FLT_MIN; f <= 1.0f; ) { // We don't bother checking denorm values. uint8_t srgb = linear_to_srgb(f); REPORTER_ASSERT(r, srgb >= prev); prev = srgb; union { float flt; uint32_t bits; } pun = { f }; pun.bits++; SkDEBUGCODE(pun.bits += 127); f = pun.flt; } }
Add an example of how to use the logging library.
#include <iostream> #include <QApplication> #include <QPushButton> #include "src/common/Game.h" int main(int argc, char *argv[]) { std::cout << "Welcome to the client interface of Bomberman :)" << std::endl; // This part should be moved to another class, that's just for test QApplication app(argc, argv); QWidget mainWindow; mainWindow.setFixedSize(300, 300); QPushButton createGameButton("Create game", &mainWindow); createGameButton.setCursor(Qt::PointingHandCursor); createGameButton.move(100, 75); QPushButton joinGameButton("Join game", &mainWindow); joinGameButton.setCursor(Qt::PointingHandCursor); joinGameButton.move(100, 150); QPushButton quitWindowButton("Quit Bomberman", &mainWindow); quitWindowButton.setCursor(Qt::PointingHandCursor); quitWindowButton.move(100, 225); QObject::connect(&quitWindowButton, SIGNAL(clicked()), &app, SLOT(quit())); mainWindow.show(); return app.exec(); }
#include <iostream> #include <QApplication> #include <QPushButton> #include "src/common/Game.h" #include "easylogging++.h" _INITIALIZE_EASYLOGGINGPP int main(int argc, char *argv[]) { std::cout << "Welcome to the client interface of Bomberman :)" << std::endl; _START_EASYLOGGINGPP(argc, argv); LOG(INFO) << "Started client"; // This part should be moved to another class, that's just for test QApplication app(argc, argv); QWidget mainWindow; mainWindow.setFixedSize(300, 300); QPushButton createGameButton("Create game", &mainWindow); createGameButton.setCursor(Qt::PointingHandCursor); createGameButton.move(100, 75); QPushButton joinGameButton("Join game", &mainWindow); joinGameButton.setCursor(Qt::PointingHandCursor); joinGameButton.move(100, 150); QPushButton quitWindowButton("Quit Bomberman", &mainWindow); quitWindowButton.setCursor(Qt::PointingHandCursor); quitWindowButton.move(100, 225); QObject::connect(&quitWindowButton, SIGNAL(clicked()), &app, SLOT(quit())); mainWindow.show(); return app.exec(); }
Add stringstream and vector library to main source.
// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h> using namespace std; int main() { RESTART: string input = ""; getline(cin, input); goto RESTART; }
// Native C++ Libraries #include <iostream> #include <string> #include <sstream> #include <vector> // C++ Interpreter Libraries #include <Console.h> using namespace std; int main() { RESTART: string input = ""; getline(cin, input); goto RESTART; }
Increase core count for PerfettoDeviceFeatureTest
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/sysinfo.h> #include "test/gtest_and_gmock.h" namespace perfetto { TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) { // Check that there are no more than 16 CPUs so that the assumption in the // atrace.rc for clearing CPU buffers is valid. ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 16); } } // namespace perfetto
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/sysinfo.h> #include "test/gtest_and_gmock.h" namespace perfetto { TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) { // Check that there are no more than 24 CPUs so that the assumption in the // atrace.rc for clearing CPU buffers is valid. ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 24); } } // namespace perfetto
Make testing utility function `static`
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ #include "catch.hpp" #include "hooks.hh" static int i; void inc_i(vick::contents&) { ++i; } TEST_CASE("hook proc", "[hook]") { vick::hook h; vick::contents c; h.add(inc_i); int li = i; h.proc(c); REQUIRE(li + 1 == i); } TEST_CASE("hook remove", "[hook]") { vick::hook h; vick::contents c; int li = i; h.add(inc_i); REQUIRE(li == i); h.proc(c); REQUIRE(li + 1 == i); REQUIRE(h.remove(inc_i)); REQUIRE_FALSE(h.remove(inc_i)); REQUIRE(li + 1 == i); h.proc(c); REQUIRE(li + 1 == i); } TEST_CASE("hook add multiple", "[hook]") { vick::hook h; vick::contents c; int li = i; h.add(inc_i); h.add(inc_i); REQUIRE(li == i); h.proc(c); REQUIRE(li + 2 == i); REQUIRE(h.remove(inc_i)); REQUIRE_FALSE(h.remove(inc_i)); REQUIRE(li + 2 == i); h.proc(c); REQUIRE(li + 2 == i); }
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ #include "catch.hpp" #include "hooks.hh" static int i; static void inc_i(vick::contents&) { ++i; } TEST_CASE("hook proc", "[hook]") { vick::hook h; vick::contents c; h.add(inc_i); int li = i; h.proc(c); REQUIRE(li + 1 == i); } TEST_CASE("hook remove", "[hook]") { vick::hook h; vick::contents c; int li = i; h.add(inc_i); REQUIRE(li == i); h.proc(c); REQUIRE(li + 1 == i); REQUIRE(h.remove(inc_i)); REQUIRE_FALSE(h.remove(inc_i)); REQUIRE(li + 1 == i); h.proc(c); REQUIRE(li + 1 == i); } TEST_CASE("hook add multiple", "[hook]") { vick::hook h; vick::contents c; int li = i; h.add(inc_i); h.add(inc_i); REQUIRE(li == i); h.proc(c); REQUIRE(li + 2 == i); REQUIRE(h.remove(inc_i)); REQUIRE_FALSE(h.remove(inc_i)); REQUIRE(li + 2 == i); h.proc(c); REQUIRE(li + 2 == i); }
Revert "One more ASAN fix."
/* * 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 "Test.h" // This is a GPU-backend specific test #if SK_SUPPORT_GPU #include "GrContextFactory.h" DEF_GPUTEST(GLInterfaceValidation, reporter, factory) { for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) { GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i; // this forces the factory to make the context if it hasn't yet factory->get(glCtxType); SkGLContext* glCtx = factory->getGLContext(glCtxType); // We're supposed to fail the NVPR context type when we the native context that does not // support the NVPR extension. if (GrContextFactory::kNVPR_GLContextType == glCtxType && factory->getGLContext(GrContextFactory::kNative_GLContextType) && !factory->getGLContext(GrContextFactory::kNative_GLContextType)->gl()->hasExtension("GL_NV_path_rendering")) { REPORTER_ASSERT(reporter, NULL == glCtx); continue; } if (glCtx) { const GrGLInterface* interface = glCtx->gl(); REPORTER_ASSERT(reporter, interface->validate()); } } } #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 "Test.h" // This is a GPU-backend specific test #if SK_SUPPORT_GPU #include "GrContextFactory.h" DEF_GPUTEST(GLInterfaceValidation, reporter, factory) { for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) { GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i; // this forces the factory to make the context if it hasn't yet factory->get(glCtxType); SkGLContext* glCtx = factory->getGLContext(glCtxType); // We're supposed to fail the NVPR context type when we the native context that does not // support the NVPR extension. if (GrContextFactory::kNVPR_GLContextType == glCtxType && factory->getGLContext(GrContextFactory::kNative_GLContextType) && !factory->getGLContext(GrContextFactory::kNative_GLContextType)->gl()->hasExtension("GL_NV_path_rendering")) { REPORTER_ASSERT(reporter, NULL == glCtx); continue; } REPORTER_ASSERT(reporter, glCtx); if (glCtx) { const GrGLInterface* interface = glCtx->gl(); REPORTER_ASSERT(reporter, interface->validate()); } } } #endif
Undo r13; clustering coefficient should ignore loops.
#include "bct.h" #include <cassert> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> /* * Computes the clustering coefficient for a binary undirected graph. Results * are returned in a vector where each element is the clustering coefficient of * the corresponding node. */ gsl_vector* bct::clustering_coef_bu(const gsl_matrix* m) { assert(m->size1 == m->size2); gsl_vector* clustering_coef = gsl_vector_calloc(m->size1); for (int i = 0; i < m->size1; i++) { gsl_vector_const_view row = gsl_matrix_const_row(m, i); int k = bct::nnz(&row.vector); if (k >= 2) { gsl_vector* neighbors = bct::find(&row.vector); gsl_matrix* s = bct::submatrix(m, neighbors, neighbors); int actual_connections = bct::nnz(s); int possible_connections = k * (k - 1); gsl_vector_set(clustering_coef, i, (double)actual_connections / (double)possible_connections); gsl_matrix_free(s); gsl_vector_free(neighbors); } } return clustering_coef; }
#include "bct.h" #include <cassert> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> /* * Computes the clustering coefficient for a binary undirected graph. Results * are returned in a vector where each element is the clustering coefficient of * the corresponding node. */ gsl_vector* bct::clustering_coef_bu(const gsl_matrix* m) { assert(m->size1 == m->size2); gsl_vector* clustering_coef = gsl_vector_calloc(m->size1); gsl_matrix* zdm = zero_diagonal(m); for (int i = 0; i < zdm->size1; i++) { gsl_vector_const_view row = gsl_matrix_const_row(zdm, i); int k = bct::nnz(&row.vector); if (k >= 2) { gsl_vector* neighbors = bct::find(&row.vector); gsl_matrix* s = bct::submatrix(zdm, neighbors, neighbors); int actual_connections = bct::nnz(s); int possible_connections = k * (k - 1); gsl_vector_set(clustering_coef, i, (double)actual_connections / (double)possible_connections); gsl_matrix_free(s); gsl_vector_free(neighbors); } } gsl_matrix_free(zdm); return clustering_coef; }
Stop overriding the logging behaviour in tests.
#include "util/testing.h" #include <event2/thread.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <gtest/gtest.h> namespace cert_trans { namespace test { void InitTesting(const char* name, int* argc, char*** argv, bool remove_flags) { // Change the defaults. Can be overridden on command line. // Log to stderr instead of log files. FLAGS_logtostderr = true; // Only log fatal messages by default. FLAGS_minloglevel = 3; ::testing::InitGoogleTest(argc, *argv); google::ParseCommandLineFlags(argc, argv, remove_flags); google::InitGoogleLogging(name); evthread_use_pthreads(); } } // namespace test } // namespace cert_trans
#include "util/testing.h" #include <event2/thread.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <gtest/gtest.h> namespace cert_trans { namespace test { void InitTesting(const char* name, int* argc, char*** argv, bool remove_flags) { ::testing::InitGoogleTest(argc, *argv); google::ParseCommandLineFlags(argc, argv, remove_flags); google::InitGoogleLogging(name); evthread_use_pthreads(); } } // namespace test } // namespace cert_trans
Add a solution with better space cost to "Cached Calculations".
#include <iostream> using namespace std; long long solve(int n) { long long *res = new long long[n + 1]; switch (n) { case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 6; } res[1] = 1; res[2] = 2; res[3] = 3; res[4] = 6; for (int i = 5; i <= n; i++) { res[i] = res[i - 1] + res[i - 2] + res[i - 4]; } long long x = res[n]; delete [] res; return x; } int main() { int T; cin >> T; while (T--) { int x; cin >> x; cout << solve(x) << endl; } return 0; }
#include <iostream> using namespace std; long long solve_1(int n) { long long *res = new long long[n + 1]; switch (n) { case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 6; } res[1] = 1; res[2] = 2; res[3] = 3; res[4] = 6; for (int i = 5; i <= n; i++) { res[i] = res[i - 1] + res[i - 2] + res[i - 4]; } long long x = res[n]; delete [] res; return x; } long long solve_2(int n) { switch (n) { case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 6; } long long a = 1; long long b = 2; long long c = 3; long long d = 6; long long res; for (int i = 5; i <= n; i++) { res = d + c + a; a = b; b = c; c = d; d = res; } return d; } int main() { int T; cin >> T; while (T--) { int x; cin >> x; cout << solve_2(x) << endl; } return 0; }
Save password also to selection clipboard.
#include "hash.h" #include <QClipboard> #include <QGuiApplication> #include <QQmlContext> #include <QStringList> const int password_length = 30; Hash::Hash(QQmlContext *c, QObject *parent) : QObject(parent), hash(QCryptographicHash::Sha3_224), settings("pasgen"), context(c) { context->setContextProperty("myModel", settings.value("pages").toStringList()); } QString Hash::Do(QString password, QString page, bool isCheck) { QStringList pages = settings.value("pages").toStringList(); if (!isCheck && !page.isEmpty()) { if (!pages.contains(page)) pages.append(page); pages.move(pages.indexOf(page), 0); settings.setValue("pages", pages); context->setContextProperty("myModel", pages); } hash.reset(); hash.addData(password.toUtf8()); hash.addData(page.toUtf8()); QString result = hash.result().toHex().left(password_length); if (!isCheck) qApp->clipboard()->setText(result); return result; } void Hash::Remove(QString page) { QStringList pages = settings.value("pages").toStringList(); pages.removeAll(page); settings.setValue("pages", pages); context->setContextProperty("myModel", pages); }
#include "hash.h" #include <QClipboard> #include <QGuiApplication> #include <QQmlContext> #include <QStringList> const int password_length = 30; Hash::Hash(QQmlContext *c, QObject *parent) : QObject(parent), hash(QCryptographicHash::Sha3_224), settings("pasgen"), context(c) { context->setContextProperty("myModel", settings.value("pages").toStringList()); } QString Hash::Do(QString password, QString page, bool isCheck) { QStringList pages = settings.value("pages").toStringList(); if (!isCheck && !page.isEmpty()) { if (!pages.contains(page)) pages.append(page); pages.move(pages.indexOf(page), 0); settings.setValue("pages", pages); context->setContextProperty("myModel", pages); } hash.reset(); hash.addData(password.toUtf8()); hash.addData(page.toUtf8()); QString result = hash.result().toHex().left(password_length); if (!isCheck) { qApp->clipboard()->setText(result, QClipboard::Clipboard); qApp->clipboard()->setText(result, QClipboard::Selection); } return result; } void Hash::Remove(QString page) { QStringList pages = settings.value("pages").toStringList(); pages.removeAll(page); settings.setValue("pages", pages); context->setContextProperty("myModel", pages); }
Use FileReadStream instead of multiple conversions.
#include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; void read_file(string filename, stringstream &buffer){ ifstream f(filename.c_str()); if (f) { buffer << f.rdbuf(); f.close(); } } using namespace rapidjson; int main() { std::stringstream ss; read_file("./1.json", ss); string text = ss.str(); Document jobj; jobj.Parse(text.c_str()); const Value &coordinates = jobj["coordinates"]; int len = coordinates.Size(); double x = 0, y = 0, z = 0; for (SizeType i = 0; i < len; i++) { const Value &coord = coordinates[i]; x += coord["x"].GetDouble(); y += coord["y"].GetDouble(); z += coord["z"].GetDouble(); } std::cout << x / len << std::endl; std::cout << y / len << std::endl; std::cout << z / len << std::endl; return 0; }
#include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include <cstdio> #include <iostream> using namespace std; using namespace rapidjson; int main() { FILE* fp = std::fopen("./1.json", "r"); char buffer[65536]; FileReadStream frs(fp, buffer, sizeof(buffer)); Document jobj; jobj.ParseStream(frs); const Value &coordinates = jobj["coordinates"]; int len = coordinates.Size(); double x = 0, y = 0, z = 0; for (SizeType i = 0; i < len; i++) { const Value &coord = coordinates[i]; x += coord["x"].GetDouble(); y += coord["y"].GetDouble(); z += coord["z"].GetDouble(); } std::cout << x / len << std::endl; std::cout << y / len << std::endl; std::cout << z / len << std::endl; fclose(fp); return 0; }
Remove simple to fix warnings
#include "MainWindow.h" #include <QBoxLayout> #include <QLabel> #include <QSpinBox> #include <fiblib/Fibonacci.h> MainWindow::MainWindow() { // Create content widget QWidget * content = new QWidget(this); setCentralWidget(content); // Create layout QBoxLayout * layout = new QVBoxLayout(); content->setLayout(layout); // Add title QLabel * title = new QLabel(content); title->setText("Please enter n:"); layout->addWidget(title); // Add input field QSpinBox * editNumber = new QSpinBox(content); editNumber->setMinimum(0); layout->addWidget(editNumber); // Add result QLabel * result = new QLabel(content); result->setText("Fib(0) = 0"); layout->addWidget(result); // When input changes, calculate and output the fibonacci number connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n) { fiblib::Fibonacci fib; result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(n))); }); } MainWindow::~MainWindow() { }
#include "MainWindow.h" #include <QBoxLayout> #include <QLabel> #include <QSpinBox> #include <fiblib/Fibonacci.h> MainWindow::MainWindow() { // Create content widget QWidget * content = new QWidget(this); setCentralWidget(content); // Create layout QBoxLayout * boxLayout = new QVBoxLayout(); content->setLayout(boxLayout); // Add title QLabel * title = new QLabel(content); title->setText("Please enter n:"); boxLayout->addWidget(title); // Add input field QSpinBox * editNumber = new QSpinBox(content); editNumber->setMinimum(0); boxLayout->addWidget(editNumber); // Add result QLabel * result = new QLabel(content); result->setText("Fib(0) = 0"); boxLayout->addWidget(result); // When input changes, calculate and output the fibonacci number connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n) { fiblib::Fibonacci fib; result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(static_cast<unsigned int>(n)))); }); } MainWindow::~MainWindow() { }
Print generated public key in ECDSA example
#include <botan/botan.h> #include <botan/ecdsa.h> #include <memory> #include <iostream> using namespace Botan; int main() { try { std::auto_ptr<RandomNumberGenerator> rng( RandomNumberGenerator::make_rng()); EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.0.8"); std::cout << params.get_curve().get_p() << "\n"; std::cout << params.get_order() << "\n"; ECDSA_PrivateKey ecdsa(*rng, params); } catch(std::exception& e) { std::cout << e.what() << "\n"; } }
#include <botan/botan.h> #include <botan/ecdsa.h> #include <memory> #include <iostream> using namespace Botan; int main() { try { std::auto_ptr<RandomNumberGenerator> rng( RandomNumberGenerator::make_rng()); EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.0.8"); std::cout << params.get_curve().get_p() << "\n"; std::cout << params.get_order() << "\n"; ECDSA_PrivateKey ecdsa(*rng, params); std::cout << X509::PEM_encode(ecdsa); } catch(std::exception& e) { std::cout << e.what() << "\n"; } }
Make Other jump after star
#include "other.hpp" #include "item.hpp" using namespace LD22; Other::~Other() { } void Other::advance() { scanItems(); if (m_item) { int wx = centerx(), wy = centery(); int ix = m_item->centerx(), iy = m_item->centery(); int dx = ix - wx, dy = iy - wy; if (dx < -20) m_xpush = -PUSH_SCALE; else if (dx > 20) m_xpush = PUSH_SCALE; else m_xpush = 0; (void) dy; } else { m_xpush = 0; } Walker::advance(); }
#include "other.hpp" #include "item.hpp" using namespace LD22; Other::~Other() { } void Other::advance() { scanItems(); if (m_item) { int wx = centerx(), wy = centery(); int ix = m_item->centerx(), iy = m_item->centery(); int dx = ix - wx, dy = iy - wy; if (dx < -20) m_xpush = -PUSH_SCALE; else if (dx > 20) m_xpush = PUSH_SCALE; else m_xpush = 0; if (dy > 80) m_ypush = 1; else m_ypush = 0; } else { m_xpush = 0; m_ypush = 0; } Walker::advance(); }
Disable alias report by default
// Author: Jingyue // Hook functions are declared with extern "C", because we want to disable // the C++ name mangling and make the instrumentation easier. #include <cstdio> #include <cstdlib> extern "C" void ReportMissingAlias(unsigned VIDOfP, unsigned VIDOfQ, void *V) { fprintf(stderr, "value(%u) = value(%u) = %p\n", VIDOfP, VIDOfQ, V); } extern "C" void AbortIfMissed(void *P, unsigned VIDOfP, void *Q, unsigned VIDOfQ) { if (P == Q && P) { ReportMissingAlias(VIDOfP, VIDOfQ, P); abort(); } } extern "C" void ReportIfMissed(void *P, unsigned VIDOfP, void *Q, unsigned VIDOfQ) { if (P == Q && P) { ReportMissingAlias(VIDOfP, VIDOfQ, P); } }
// Author: Jingyue // Hook functions are declared with extern "C", because we want to disable // the C++ name mangling and make the instrumentation easier. #include <cstdio> #include <cstdlib> #define DISABLE_REPORT extern "C" void ReportMissingAlias(unsigned VIDOfP, unsigned VIDOfQ, void *V) { #ifndef DISABLE_REPORT fprintf(stderr, "value(%u) = value(%u) = %p\n", VIDOfP, VIDOfQ, V); #endif } extern "C" void AbortIfMissed(void *P, unsigned VIDOfP, void *Q, unsigned VIDOfQ) { if (P == Q && P) { ReportMissingAlias(VIDOfP, VIDOfQ, P); abort(); } } extern "C" void ReportIfMissed(void *P, unsigned VIDOfP, void *Q, unsigned VIDOfQ) { if (P == Q && P) { ReportMissingAlias(VIDOfP, VIDOfQ, P); } }
Delete temporary file after unit test
#include "../../testing/testing.hpp" #include "../country.hpp" #include "../../coding/file_writer.hpp" #include "../../coding/file_reader.hpp" #include "../../base/start_mem_debug.hpp" UNIT_TEST(CountrySerialization) { string const TEST_URL = "http://someurl.com/somemap.dat"; uint64_t const TEST_SIZE = 123456790; char const * TEST_FILE_NAME = "some_temporary_update_file.tmp"; mapinfo::Country c("North America", "USA", "Alaska"); c.AddUrl(mapinfo::TUrl(TEST_URL, TEST_SIZE)); { mapinfo::TCountriesContainer countries; countries[c.Group()].push_back(c); FileWriter writer(TEST_FILE_NAME); mapinfo::SaveCountries(countries, writer); } mapinfo::TCountriesContainer loadedCountries; { TEST( mapinfo::LoadCountries(loadedCountries, TEST_FILE_NAME), ()); } TEST_GREATER(loadedCountries.size(), 0, ()); mapinfo::Country const & c2 = loadedCountries.begin()->second.front(); TEST_EQUAL(c.Group(), loadedCountries.begin()->first, ()); TEST_EQUAL(c.Group(), c2.Group(), ()); TEST_EQUAL(c.Name(), c2.Name(), ()); TEST_GREATER(c2.Urls().size(), 0, ()); TEST_EQUAL(*c.Urls().begin(), *c2.Urls().begin(), ()); }
#include "../../testing/testing.hpp" #include "../country.hpp" #include "../../coding/file_writer.hpp" #include "../../coding/file_reader.hpp" #include "../../base/start_mem_debug.hpp" UNIT_TEST(CountrySerialization) { string const TEST_URL = "http://someurl.com/somemap.dat"; uint64_t const TEST_SIZE = 123456790; char const * TEST_FILE_NAME = "some_temporary_update_file.tmp"; mapinfo::Country c("North America", "USA", "Alaska"); c.AddUrl(mapinfo::TUrl(TEST_URL, TEST_SIZE)); { mapinfo::TCountriesContainer countries; countries[c.Group()].push_back(c); FileWriter writer(TEST_FILE_NAME); mapinfo::SaveCountries(countries, writer); } mapinfo::TCountriesContainer loadedCountries; { TEST( mapinfo::LoadCountries(loadedCountries, TEST_FILE_NAME), ()); } TEST_GREATER(loadedCountries.size(), 0, ()); mapinfo::Country const & c2 = loadedCountries.begin()->second.front(); TEST_EQUAL(c.Group(), loadedCountries.begin()->first, ()); TEST_EQUAL(c.Group(), c2.Group(), ()); TEST_EQUAL(c.Name(), c2.Name(), ()); TEST_GREATER(c2.Urls().size(), 0, ()); TEST_EQUAL(*c.Urls().begin(), *c2.Urls().begin(), ()); FileWriter::DeleteFile(TEST_FILE_NAME); }
Replace hard coded string with QPlatformInputContextFactoryInterface_iid (fixes compatibility with Qt 5.5 where this string has changed)
/* * This file is part of Maliit framework * * * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). * * All rights reserved. * * Contact: maliit-discuss@lists.maliit.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include <qpa/qplatforminputcontextplugin_p.h> #include <QtCore/QStringList> #include <QDebug> #include "minputcontext.h" class MaliitPlatformInputContextPlugin: public QPlatformInputContextPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QPlatformInputContextFactoryInterface" FILE "maliit.json") public: QPlatformInputContext *create(const QString&, const QStringList&); }; QPlatformInputContext *MaliitPlatformInputContextPlugin::create(const QString &system, const QStringList &paramList) { Q_UNUSED(paramList); if (system.compare(system, QStringLiteral("maliit"), Qt::CaseInsensitive) == 0) { return new MInputContext; } return 0; } #include "main.moc"
/* * This file is part of Maliit framework * * * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). * * All rights reserved. * * Contact: maliit-discuss@lists.maliit.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include <qpa/qplatforminputcontextplugin_p.h> #include <QtCore/QStringList> #include <QDebug> #include "minputcontext.h" class MaliitPlatformInputContextPlugin: public QPlatformInputContextPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID QPlatformInputContextFactoryInterface_iid FILE "maliit.json") public: QPlatformInputContext *create(const QString&, const QStringList&); }; QPlatformInputContext *MaliitPlatformInputContextPlugin::create(const QString &system, const QStringList &paramList) { Q_UNUSED(paramList); if (system.compare(system, QStringLiteral("maliit"), Qt::CaseInsensitive) == 0) { return new MInputContext; } return 0; } #include "main.moc"
Implement basic cpu mining logic
/** * This is free and unencumbered software released into the public domain. **/ #include "Miner.h" #include <memory> class CpuMiner : public Miner { public: ~CpuMiner() {} public: static MinerPtr createInstance() { return MinerPtr( new CpuMiner ); } }; MinerRegistration<CpuMiner> registration( "cpu" );
/** * This is free and unencumbered software released into the public domain. **/ #include "Miner.h" #include <memory> #include <limits> #include <cassert> class CpuMiner : public Miner { public: ~CpuMiner() {} public: static MinerPtr createInstance() { return MinerPtr( new CpuMiner ); } protected: virtual Result _mine( const Sha256& preHash, const ByteArray& reverseTarget, uint32_t& nonce ) { assert( reverseTarget.size() == sizeof(Sha256::Digest) ); nonce = 0; do { // Complete the first hash Sha256 hash( preHash ); Sha256::Digest digest; hash.update( &nonce, sizeof(nonce) * CHAR_BIT ); hash.digest( digest ); // Do it again auto result = Sha256::hash( digest.toByteArray() ); for( int i = result.size() - 1; i >= 0; --i ) { if( result[i] > reverseTarget[i] ) { break; } if( result[i] < reverseTarget[i] ) { return SolutionFound; } } } while( nonce++ < std::numeric_limits<uint32_t>::max() ); return NoSolutionFound; } }; MinerRegistration<CpuMiner> registration( "cpu" );
Clear should also clear filter.
/* RMS power gauge, based on the one in csound. -JGG */ #include "RMS.h" RMS :: RMS(double srate) : Filter(srate) { gain = 1.0; subLowFilter = new OnePole(srate); subLowFilter->setFreq(10.0); windowSize = DEFAULT_CONTROL_RATE; counter = 0; lastOutput = 0.0; outputs = inputs = NULL; // unused } RMS :: ~RMS() { delete subLowFilter; } void RMS :: clear() { lastOutput = 0.0; counter = 0; } void RMS :: setFreq(double freq) { subLowFilter->setFreq(freq); } void RMS :: setWindowSize(int nsamples) { windowSize = nsamples; counter = 0; } double RMS :: tick(double sample) { double temp = subLowFilter->tick(sample * sample); if (--counter < 0) { lastOutput = sqrt(temp); counter = windowSize; } return lastOutput; }
/* RMS power gauge, based on the one in csound. -JGG */ #include "RMS.h" RMS :: RMS(double srate) : Filter(srate) { gain = 1.0; subLowFilter = new OnePole(srate); subLowFilter->setFreq(10.0); windowSize = DEFAULT_CONTROL_RATE; counter = 0; lastOutput = 0.0; outputs = inputs = NULL; // unused } RMS :: ~RMS() { delete subLowFilter; } void RMS :: clear() { lastOutput = 0.0; counter = 0; subLowFilter->clear(); } void RMS :: setFreq(double freq) { subLowFilter->setFreq(freq); } void RMS :: setWindowSize(int nsamples) { windowSize = nsamples; counter = 0; } double RMS :: tick(double sample) { double temp = subLowFilter->tick(sample * sample); if (--counter < 0) { lastOutput = sqrt(temp); counter = windowSize; } return lastOutput; }
Add prototypes for the debug printer
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <boost/variant.hpp> #include "tac/Printer.hpp" #include "tac/Program.hpp" #include "VisitorUtils.hpp" using namespace eddic; struct DebugVisitor : public boost::static_visitor<> { void operator()(tac::Program& program){ std::cout << "TAC Program " << std::endl << std::endl; visit_each_non_variant(*this, program.functions); } void operator()(std::shared_ptr<tac::Function> function){ std::cout << "Function " << function->getName() << std::endl; } }; void tac::Printer::print(tac::Program& program) const { DebugVisitor visitor; visitor(program); }
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <boost/variant.hpp> #include "tac/Printer.hpp" #include "tac/Program.hpp" #include "VisitorUtils.hpp" using namespace eddic; struct DebugVisitor : public boost::static_visitor<> { void operator()(tac::Program& program){ std::cout << "TAC Program " << std::endl << std::endl; visit_each_non_variant(*this, program.functions); } void operator()(std::shared_ptr<tac::Function> function){ std::cout << "Function " << function->getName() << std::endl; visit_each(*this, function->getStatements()); } void operator()(tac::Quadruple& quadruple){ } void operator()(tac::IfFalse& ifFalse){ } void operator()(tac::Goto& goto_){ } void operator()(tac::Param& param){ } void operator()(tac::Return& return_){ } void operator()(tac::Call& call){ } void operator()(std::string& label){ std::cout << label << ":" << std::endl; } }; void tac::Printer::print(tac::Program& program) const { DebugVisitor visitor; visitor(program); }
Change default cursor-image location to non-test path
#include "Cursor.h" Cursor* Cursor::instance = NULL; Cursor::Cursor() : Sprite() { // Status m_show = true; // Arrangement m_anchor = Vec2<double>(0.0, 0.0); m_texture_dst = new SDL_Rect; m_texture_dst->x = -m_size.x; m_texture_dst->y = -m_size.y; m_texture_dst->w = m_size.x; m_texture_dst->h = m_size.y; // Image m_sprite_path = "resources/cursor.png"; m_sprite_path = "resources/potato.jpg"; } Cursor* Cursor::getInstance() { if (instance == NULL) instance = new Cursor; return instance; } Cursor::~Cursor() {} void Cursor::update() { }
#include "Cursor.h" Cursor* Cursor::instance = NULL; Cursor::Cursor() : Sprite() { // Status m_show = true; // Arrangement m_anchor = Vec2<double>(0.0, 0.0); m_texture_dst = new SDL_Rect; m_texture_dst->x = -m_size.x; m_texture_dst->y = -m_size.y; m_texture_dst->w = m_size.x; m_texture_dst->h = m_size.y; // Image m_sprite_path = "resources/cursor.png"; } Cursor* Cursor::getInstance() { if (instance == NULL) instance = new Cursor; return instance; } Cursor::~Cursor() {} void Cursor::update() { }
Fix VertexBuffer move-constructor, vao was not copied.
#include "vertexbuffer.hpp" #include "collisiondetection/axisalignedboundingbox.hpp" using namespace modelloader; VertexBuffer::VertexBuffer(VertexBuffer&& other) : vBO{other.vBO}, iBO{other.iBO}, nBO{other.nBO}, numIndices{other.numIndices}, extremes{other.extremes}, bounds(std::move(other.bounds)){ } VertexBuffer::VertexBuffer(GLuint myVBO, GLuint myIBO, GLuint myNBO, unsigned int myNumIndices, std::tuple<glm::vec3, glm::vec3> myExtremes) : vBO(myVBO), iBO(myIBO), nBO(myNBO), numIndices(myNumIndices), extremes(myExtremes), bounds{new collisiondetection::AxisAlignedBoundingBox(extremes)} { //Generate VAO glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vBO); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, nBO); glVertexAttribPointer(1, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(1); } void VertexBuffer::bindBuffers() const { glBindVertexArray(vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iBO); }
#include "vertexbuffer.hpp" #include "collisiondetection/axisalignedboundingbox.hpp" using namespace modelloader; VertexBuffer::VertexBuffer(VertexBuffer&& other) : vBO{other.vBO}, iBO{other.iBO}, nBO{other.nBO}, vao(other.vao), numIndices{other.numIndices}, extremes{other.extremes}, bounds(std::move(other.bounds)){ } VertexBuffer::VertexBuffer(GLuint myVBO, GLuint myIBO, GLuint myNBO, unsigned int myNumIndices, std::tuple<glm::vec3, glm::vec3> myExtremes) : vBO(myVBO), iBO(myIBO), nBO(myNBO), numIndices(myNumIndices), extremes(myExtremes), bounds{new collisiondetection::AxisAlignedBoundingBox(extremes)} { //Generate VAO glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vBO); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, nBO); glVertexAttribPointer(1, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(1); } void VertexBuffer::bindBuffers() const { glBindVertexArray(vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iBO); }
Migrate to smart pointers, part five
//! \file CacheJsonToArticleConverter.cpp #include "CacheJsonToArticleConverter.h" #include <json/json.h> #include "WalkerException.h" #include "Article.h" ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache) { Json::Reader reader; Json::Value document; bool success = reader.parse(json, document, false); if(!success) { throw WalkerException("Error parsing JSON"); } // get all "main" articles first for(auto& titleElement : document.getMemberNames()) { std::string title = titleElement; Article* a = articleCache.get(title); if(a == nullptr) { a = new Article(title); articleCache.add(a); } auto links = document .get(title, Json::Value::nullSingleton()) .get("forward_links", Json::Value::nullSingleton()); if(links.isNull()) { /* don't need to set article analyzed to false, * since that's the default */ continue; } a->setAnalyzed(true); for(auto linkedArticle : links) { std::string linkedTitle = linkedArticle.asString(); Article* la = articleCache.get(linkedTitle); if(la == nullptr) { la = new Article(linkedTitle); articleCache.add(la); } a->addLink(la); } } return articleCache; /* a->setAnalyzed(true); ? */ }
//! \file CacheJsonToArticleConverter.cpp #include "CacheJsonToArticleConverter.h" #include <json/json.h> #include "WalkerException.h" #include "Article.h" ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache) { Json::Reader reader; Json::Value document; bool success = reader.parse(json, document, false); if(!success) { throw WalkerException("Error parsing JSON"); } // get all "main" articles first for(auto& titleElement : document.getMemberNames()) { std::string title = titleElement; auto a = articleCache.get(title); if(a == nullptr) { a = std::make_shared<Article>(title); articleCache.add(a); } auto links = document .get(title, Json::Value::nullSingleton()) .get("forward_links", Json::Value::nullSingleton()); if(links.isNull()) { /* don't need to set article analyzed to false, * since that's the default */ continue; } a->setAnalyzed(true); for(auto linkedArticle : links) { std::string linkedTitle = linkedArticle.asString(); std::shared_ptr<Article> la = articleCache.get(linkedTitle); if(la == nullptr) { la = std::make_shared<Article>(linkedTitle); articleCache.add(la); } a->addLink(la); } } return articleCache; /* a->setAnalyzed(true); ? */ }
Move title screen init to private fn
#include <ncurses.h> #include <string> int main() { /* * init term */ initscr(); cbreak(); noecho(); clear(); /* * init title */ move(5, 5); std::string title = "TERMINAL QUEST"; for (int i; i < title.size(); i++) { addch(title[i]); addch(' '); } refresh(); while(true); /* * exit */ return 0; }
#include <ncurses.h> #include <string> using namespace std; void menuShow(); void menuAdd(int pos, string str); void menuDone(); int main() { /* * init term */ initscr(); cbreak(); noecho(); clear(); /* * init title */ menuShow(); refresh(); while(true); /* * exit */ return 0; } void menuShow() { move(5, 5); // move cursor to (x,y) string text = "TERMINAL QUEST"; for (size_t i = 0; i < text.size(); i++) { addch(text[i]); addch(' '); } menuAdd(1, "start"); menuAdd(2, "quit"); menuDone(); refresh(); while(1); } void close() { endwin(); } // Private functions void menuAdd(int pos, string str) { if (pos > 0 && str.length() > 0) { move((pos + 6), 8); addstr(str.c_str()); } } void menuDone() { move(7, 6); }
Add proper licensing to file
#include "qcalparser.h" #include "qcalevent.h" #include <QtCore/QCoreApplication> #include <QFile> #include <QString> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QFile *file = new QFile(a.arguments().at(1)); QCalParser *parser = new QCalParser(file); foreach(QCalEvent* event, parser->getEventList()) { qDebug() << event->eventUID(); qDebug() << event->categoryList(); qDebug() << event->eventDescription(); qDebug() << event->eventUrl(); qDebug() << event->eventUrlType(); qDebug() << event->eventLocation(); qDebug() << event->eventRoomName(); qDebug() << event->eventStartDate(); qDebug() << event->eventStopDate(); } }
/* * This file is part of libqcalparser * * Copyright (C) Rohan Garg <rohan16garg@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "qcalparser.h" #include "qcalevent.h" #include <QtCore/QCoreApplication> #include <QFile> #include <QString> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QFile *file = new QFile(a.arguments().at(1)); QCalParser *parser = new QCalParser(file); foreach(QCalEvent* event, parser->getEventList()) { qDebug() << event->eventUID(); qDebug() << event->categoryList(); qDebug() << event->eventDescription(); qDebug() << event->eventUrl(); qDebug() << event->eventUrlType(); qDebug() << event->eventLocation(); qDebug() << event->eventRoomName(); qDebug() << event->eventStartDate(); qDebug() << event->eventStopDate(); } }
Initialize target_message_loop_ in the constructor.
// 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/icon_loader.h" #include "base/message_loop.h" #include "base/mime_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); #if defined(OS_LINUX) // This call must happen on the UI thread before we can start loading icons. mime_util::DetectGtkTheme(); #endif g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { if (delegate_->OnBitmapLoaded(this, bitmap_)) bitmap_ = NULL; }
// 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/icon_loader.h" #include "base/message_loop.h" #include "base/mime_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : target_message_loop_(NULL), group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); #if defined(OS_LINUX) // This call must happen on the UI thread before we can start loading icons. mime_util::DetectGtkTheme(); #endif g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { if (delegate_->OnBitmapLoaded(this, bitmap_)) bitmap_ = NULL; }
Clean the playground since the test was moved into the unit tests
/* Copyright(c) 2015 - 2019 Denis Blank <denis.blank at outlook dot com> 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 <continuable/continuable.hpp> using namespace cti; int main(int, char**) { // ... auto e = std::make_exception_ptr(std::exception("huhu")); async_on( [] { // int i = 0; }, [&](work work) { int i = 0; (void)i; work.set_exception(e); // }) .fail([](exception_t e) { // int i = 0; (void)i; }); }
/* Copyright(c) 2015 - 2019 Denis Blank <denis.blank at outlook dot com> 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 <continuable/continuable.hpp> using namespace cti; int main(int, char**) { }
Fix to make it compile in Windows.. Hope it still compiles in Linux...
#include "audiobase.h" namespace openalpp { AudioBase::AudioBase(int frequency,int refresh,int synchronous) throw (InitError) { if(!instances_) { // Open a write (output) device. This should (in theory) make it possible // to open a read (input) device later.. device_=alcOpenDevice((const ALubyte *)"'((direction \"write\"))"); if(!device_) throw InitError("Couldn't open device."); int attributes[7],i=0; attributes[0]=0; if(frequency>0) { attributes[i++]=ALC_FREQUENCY; attributes[i++]=frequency; attributes[i]=0; } if(refresh>0) { attributes[i++]=ALC_REFRESH; attributes[i++]=refresh; attributes[i]=0; } if(synchronous>0) { attributes[i++]=ALC_SYNC; attributes[i++]=synchronous; attributes[i]=0; } context_=alcCreateContext(device_,attributes); if(!context_ || alcGetError(device_)!=AL_FALSE) { if(context_) alcDestroyContext(context_); else alcCloseDevice(device_); throw InitError("Couldn't create context."); } alcMakeContextCurrent(context_); reverbinitiated_=false; } instances_++; } AudioBase::~AudioBase() { instances_--; if(!instances_) { alcDestroyContext(context_); } } // Static member int AudioBase::instances_=0; }
#include "audiobase.h" namespace openalpp { AudioBase::AudioBase(int frequency,int refresh,int synchronous) throw (InitError) { if(!instances_) { // Open a write (output) device. This should (in theory) make it possible // to open a read (input) device later.. device_=alcOpenDevice((/*const */ALubyte *)"'((direction \"write\"))"); if(!device_) throw InitError("Couldn't open device."); int attributes[7],i=0; attributes[0]=0; if(frequency>0) { attributes[i++]=ALC_FREQUENCY; attributes[i++]=frequency; attributes[i]=0; } if(refresh>0) { attributes[i++]=ALC_REFRESH; attributes[i++]=refresh; attributes[i]=0; } if(synchronous>0) { attributes[i++]=ALC_SYNC; attributes[i++]=synchronous; attributes[i]=0; } context_=alcCreateContext(device_,attributes); if(!context_ || alcGetError(device_)!=AL_FALSE) { if(context_) alcDestroyContext(context_); else alcCloseDevice(device_); throw InitError("Couldn't create context."); } alcMakeContextCurrent(context_); reverbinitiated_=false; } instances_++; } AudioBase::~AudioBase() { instances_--; if(!instances_) { alcDestroyContext(context_); } } // Static member int AudioBase::instances_=0; }
Add Python binding for GradientError
#include "chainerx/python/error.h" #include "chainerx/error.h" #include "chainerx/python/common.h" namespace chainerx { namespace python { namespace python_internal { namespace py = pybind11; // standard convention void InitChainerxError(pybind11::module& m) { py::register_exception<ChainerxError>(m, "ChainerxError"); py::register_exception<ContextError>(m, "ContextError"); py::register_exception<BackendError>(m, "BackendError"); py::register_exception<DeviceError>(m, "DeviceError"); py::register_exception<DimensionError>(m, "DimensionError"); py::register_exception<DtypeError>(m, "DtypeError"); py::register_exception<NotImplementedError>(m, "NotImplementedError"); py::register_exception<GradientCheckError>(m, "GradientCheckError"); } } // namespace python_internal } // namespace python } // namespace chainerx
#include "chainerx/python/error.h" #include "chainerx/error.h" #include "chainerx/python/common.h" namespace chainerx { namespace python { namespace python_internal { namespace py = pybind11; // standard convention void InitChainerxError(pybind11::module& m) { py::register_exception<ChainerxError>(m, "ChainerxError"); py::register_exception<ContextError>(m, "ContextError"); py::register_exception<BackendError>(m, "BackendError"); py::register_exception<DeviceError>(m, "DeviceError"); py::register_exception<DimensionError>(m, "DimensionError"); py::register_exception<DtypeError>(m, "DtypeError"); py::register_exception<NotImplementedError>(m, "NotImplementedError"); py::register_exception<GradientError>(m, "GradientError"); py::register_exception<GradientCheckError>(m, "GradientCheckError"); } } // namespace python_internal } // namespace python } // namespace chainerx
Return 0 instead of NULL for a non-pointer type. Eliminates a warning in GCC.
#include "SkTypeface.h" // ===== Begin Chrome-specific definitions ===== uint32_t SkTypeface::UniqueID(const SkTypeface* face) { return NULL; } void SkTypeface::serialize(SkWStream* stream) const { } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return NULL; } // ===== End Chrome-specific definitions =====
#include "SkTypeface.h" // ===== Begin Chrome-specific definitions ===== uint32_t SkTypeface::UniqueID(const SkTypeface* face) { return 0; } void SkTypeface::serialize(SkWStream* stream) const { } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return NULL; } // ===== End Chrome-specific definitions =====
Add comments and use ToLocal instead of ToLocalChecked
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/event_emitter_caller.h" #include "atom/common/api/locker.h" #include "atom/common/node_includes.h" namespace mate { namespace internal { v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate, v8::Local<v8::Object> obj, const char* method, ValueVector* args) { // Perform microtask checkpoint after running JavaScript. v8::MicrotasksScope script_scope(isolate, v8::MicrotasksScope::kRunMicrotasks); // Use node::MakeCallback to call the callback, and it will also run pending // tasks in Node.js. v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(), {0, 0}); if (ret.IsEmpty()) { return v8::Boolean::New(isolate, false); } return ret.ToLocalChecked(); } } // namespace internal } // namespace mate
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/event_emitter_caller.h" #include "atom/common/api/locker.h" #include "atom/common/node_includes.h" namespace mate { namespace internal { v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate, v8::Local<v8::Object> obj, const char* method, ValueVector* args) { // Perform microtask checkpoint after running JavaScript. v8::MicrotasksScope script_scope(isolate, v8::MicrotasksScope::kRunMicrotasks); // Use node::MakeCallback to call the callback, and it will also run pending // tasks in Node.js. v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(), {0, 0}); // If the JS function throws an exception (doesn't return a value) the result // of MakeCallback will be empty, in this case we need to return "false" as // that indicates that the event emitter did not handle the event if (ret.IsEmpty()) { return v8::Boolean::New(isolate, false); } v8::Local<v8::Value> localRet; if (ret.ToLocal(&localRet)) { return localRet; } // Should be unreachable, but the compiler complains if we don't check // the result of ToLocal return v8::Undefined(isolate); } } // namespace internal } // namespace mate
Validate one genome at a time
/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <cstdlib> #include <iostream> #include "halStats.h" using namespace std; using namespace hal; int main(int argc, char** argv) { CLParserPtr optionsParser = hdf5CLParserInstance(); optionsParser->addArgument("halFile", "path to hal file to validate"); optionsParser->setDescription("Check if hal database is valid"); string path; try { optionsParser->parseOptions(argc, argv); path = optionsParser->getArgument<string>("halFile"); } catch(exception& e) { cerr << e.what() << endl; optionsParser->printUsage(cerr); exit(1); } try { AlignmentConstPtr alignment = openHalAlignmentReadOnly(path, optionsParser); validateAlignment(alignment); } catch(hal_exception& e) { cerr << "hal exception caught: " << e.what() << endl; return 1; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return 1; } cout << "\nFile valid" << endl; return 0; }
/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <cstdlib> #include <iostream> #include "halStats.h" using namespace std; using namespace hal; int main(int argc, char** argv) { CLParserPtr optionsParser = hdf5CLParserInstance(); optionsParser->addArgument("halFile", "path to hal file to validate"); optionsParser->addOption("genome", "specific genome to validate instead of entire file", ""); optionsParser->setDescription("Check if hal database is valid"); string path, genomeName; try { optionsParser->parseOptions(argc, argv); path = optionsParser->getArgument<string>("halFile"); genomeName = optionsParser->getOption<string>("genome"); } catch(exception& e) { cerr << e.what() << endl; optionsParser->printUsage(cerr); exit(1); } try { AlignmentConstPtr alignment = openHalAlignmentReadOnly(path, optionsParser); if (genomeName == "") { validateAlignment(alignment); } else { const Genome *genome = alignment->openGenome(genomeName); validateGenome(genome); } } catch(hal_exception& e) { cerr << "hal exception caught: " << e.what() << endl; return 1; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return 1; } cout << "\nFile valid" << endl; return 0; }
Use balance dsp only in stereo
#include "pch.h" #include "DspBalance.h" #include "AudioRenderer.h" namespace SaneAudioRenderer { void DspBalance::Process(DspChunk& chunk) { float balance = m_renderer.GetBalance(); if (!chunk.IsEmpty() && balance != 0.0f) { assert(balance >= -1.0f && balance <= 1.0f); DspChunk::ToFloat(chunk); auto data = reinterpret_cast<float*>(chunk.GetData()); float gain = abs(balance); for (size_t i = (balance < 0 ? 1 : 0), n = chunk.GetSampleCount(); i < n; i += 2) data[i] *= gain; } } void DspBalance::Finish(DspChunk& chunk) { Process(chunk); } }
#include "pch.h" #include "DspBalance.h" #include "AudioRenderer.h" namespace SaneAudioRenderer { void DspBalance::Process(DspChunk& chunk) { float balance = m_renderer.GetBalance(); if (!chunk.IsEmpty() && balance != 0.0f && chunk.GetChannelCount() == 2) { assert(balance >= -1.0f && balance <= 1.0f); DspChunk::ToFloat(chunk); auto data = reinterpret_cast<float*>(chunk.GetData()); float gain = abs(balance); for (size_t i = (balance < 0 ? 1 : 0), n = chunk.GetSampleCount(); i < n; i += 2) data[i] *= gain; } } void DspBalance::Finish(DspChunk& chunk) { Process(chunk); } }
UPDATE Sets values for components properly
#include "LevelState.h" LevelState::LevelState() { } LevelState::~LevelState() { } int LevelState::ShutDown() { int result = 1; return result; } int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler) { int result = 0; result = GameState::InitializeBase(gsh, cHandler); //Read from file //Get Components GraphicsComponent* tempComp = this->m_cHandler->GetGraphicsComponent(); //Set Component values tempComp->active = 1; tempComp->modelID = 1337; tempComp->worldMatrix = DirectX::XMMatrixIdentity(); //Give Components to entities this->m_player1.Initialize(); return result; } int LevelState::Update(float dt, InputHandler * inputHandler) { int result = 0; this->m_player1.Update(dt, inputHandler); return result; }
#include "LevelState.h" LevelState::LevelState() { } LevelState::~LevelState() { } int LevelState::ShutDown() { int result = 1; return result; } int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler) { int result = 0; result = GameState::InitializeBase(gsh, cHandler); //Read from file //Get Components GraphicsComponent* tempGComp = this->m_cHandler->GetGraphicsComponent(); PhysicsComponent* tempPComp = this->m_cHandler->GetPhysicsComponent(); //Set Component values tempGComp->active = 1; tempGComp->modelID = 1337; tempGComp->worldMatrix = DirectX::XMMatrixIdentity(); tempPComp->PC_active = 1; tempPComp->PC_pos = DirectX::XMVectorSet(0.0f, 2.0f, 1.0f, 1.0f); //Give Components to entities this->m_player1.Initialize(); this->m_player1.SetGraphicsComponent(tempGComp); this->m_player1.SetPhysicsComponent(tempPComp); return result; } int LevelState::Update(float dt, InputHandler * inputHandler) { int result = 0; this->m_player1.Update(dt, inputHandler); return result; }
Use strerror_s for SysErrorString on Windows
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <tinyformat.h> #include <util/syserror.h> #include <cstring> std::string SysErrorString(int err) { char buf[256]; buf[0] = 0; /* Too bad there are two incompatible implementations of the * thread-safe strerror. */ const char *s; #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ s = buf; if (strerror_r(err, buf, sizeof(buf))) buf[0] = 0; #endif return strprintf("%s (%d)", s, err); }
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <tinyformat.h> #include <util/syserror.h> #include <cstring> std::string SysErrorString(int err) { char buf[256]; buf[0] = 0; /* Too bad there are three incompatible implementations of the * thread-safe strerror. */ const char *s; #ifdef WIN32 s = buf; if (strerror_s(buf, sizeof(buf), err) != 0) buf[0] = 0; #else #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ s = buf; if (strerror_r(err, buf, sizeof(buf))) buf[0] = 0; #endif #endif return strprintf("%s (%d)", s, err); }
Use more generic language in a log message, could be serial or USB.
#include "listener.h" #include "log.h" #include "buffers.h" void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message, int messageSize) { if(queue_available(queue) < messageSize + 1) { debug("Dropped incoming CAN message -- send queue full for USB\r\n"); return; } for(int i = 0; i < messageSize; i++) { QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]); } QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n'); } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { // TODO the more we enqueue here, the slower it gets - cuts the rate by // almost half to do it with 2 queues. we could either figure out how to // share a queue or make the enqueue function faster. right now I believe it // enqueues byte by byte, which could obviously be improved. conditionalEnqueue(&listener->usb->sendQueue, message, messageSize); #ifdef SERIAL conditionalEnqueue(&listener->serial->sendQueue, message, messageSize); #endif } void processListenerQueues(Listener* listener) { processInputQueue(listener->usb); #ifdef SERIAL processInputQueue(listener->serial); #endif }
#include "listener.h" #include "log.h" #include "buffers.h" void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message, int messageSize) { if(queue_available(queue) < messageSize + 1) { debug("Dropped incoming CAN message -- send queue full\r\n"); return; } for(int i = 0; i < messageSize; i++) { QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]); } QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n'); } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { // TODO the more we enqueue here, the slower it gets - cuts the rate by // almost half to do it with 2 queues. we could either figure out how to // share a queue or make the enqueue function faster. right now I believe it // enqueues byte by byte, which could obviously be improved. conditionalEnqueue(&listener->usb->sendQueue, message, messageSize); #ifdef SERIAL conditionalEnqueue(&listener->serial->sendQueue, message, messageSize); #endif } void processListenerQueues(Listener* listener) { processInputQueue(listener->usb); #ifdef SERIAL processInputQueue(listener->serial); #endif }
Fix console output to use tstring.
#include <sstream> #include "backend.h" tstring CommandConsole::receiveStandardInput() { char input [1024]; std::cin >> input; return input; } void CommandConsole::processStandardOutput(const tstring& output) { std::cout << output; }
#include <sstream> #include "backend.h" tstring CommandConsole::receiveStandardInput() { tstring input; std::cin >> input; return input; } void CommandConsole::processStandardOutput(const tstring& output) { std::cout << output; }
Fix regression where we didn't ever start watching for network address changes on Windows.
// 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 "net/base/network_change_notifier_win.h" #include <iphlpapi.h> #include <winsock2.h> #pragma comment(lib, "iphlpapi.lib") namespace net { NetworkChangeNotifierWin::NetworkChangeNotifierWin() { memset(&addr_overlapped_, 0, sizeof addr_overlapped_); addr_overlapped_.hEvent = WSACreateEvent(); } NetworkChangeNotifierWin::~NetworkChangeNotifierWin() { CancelIPChangeNotify(&addr_overlapped_); addr_watcher_.StopWatching(); WSACloseEvent(addr_overlapped_.hEvent); } void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) { NotifyObserversOfIPAddressChange(); // Start watching for the next address change. WatchForAddressChange(); } void NetworkChangeNotifierWin::WatchForAddressChange() { HANDLE handle = NULL; DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_); CHECK(ret == ERROR_IO_PENDING); addr_watcher_.StartWatching(addr_overlapped_.hEvent, this); } } // namespace net
// 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 "net/base/network_change_notifier_win.h" #include <iphlpapi.h> #include <winsock2.h> #pragma comment(lib, "iphlpapi.lib") namespace net { NetworkChangeNotifierWin::NetworkChangeNotifierWin() { memset(&addr_overlapped_, 0, sizeof addr_overlapped_); addr_overlapped_.hEvent = WSACreateEvent(); WatchForAddressChange(); } NetworkChangeNotifierWin::~NetworkChangeNotifierWin() { CancelIPChangeNotify(&addr_overlapped_); addr_watcher_.StopWatching(); WSACloseEvent(addr_overlapped_.hEvent); } void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) { NotifyObserversOfIPAddressChange(); // Start watching for the next address change. WatchForAddressChange(); } void NetworkChangeNotifierWin::WatchForAddressChange() { HANDLE handle = NULL; DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_); CHECK(ret == ERROR_IO_PENDING); addr_watcher_.StartWatching(addr_overlapped_.hEvent, this); } } // namespace net
Revert "AccessObject objects are owned by QML"
#include "accessobject.h" #include "accessclass.h" #include "util.h" #include <QSet> #include <QQmlEngine> namespace RubyQml { AccessObject::AccessObject(const SP<ForeignClass> &klass, VALUE value) : ForeignObject(klass), mValue(value) { globalMarkValues() << value; QQmlEngine::setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } AccessObject::~AccessObject() { globalMarkValues().remove(mValue); } } // namespace RubyQml
#include "accessobject.h" #include "accessclass.h" #include "util.h" #include <QSet> namespace RubyQml { AccessObject::AccessObject(const SP<ForeignClass> &klass, VALUE value) : ForeignObject(klass), mValue(value) { globalMarkValues() << value; } AccessObject::~AccessObject() { globalMarkValues().remove(mValue); } } // namespace RubyQml
Add test case from PR6064, which now works
// RUN: %clang_cc1 -fsyntax-only -verify %s struct S { S (S); // expected-error {{copy constructor must pass its first argument by reference}} }; S f(); void g() { S a( f() ); }
// RUN: %clang_cc1 -fsyntax-only -verify %s struct S { S (S); // expected-error {{copy constructor must pass its first argument by reference}} }; S f(); void g() { S a( f() ); } namespace PR6064 { struct A { A() { } inline A(A&, int); }; A::A(A&, int = 0) { } void f() { A const a; A b(a); } }
Disable static-tls test on PowerPC.
// REQUIRES: asan-64-bits // Regression test: __tls_get_addr interceptor must recognize static TLS. // // RUN: %clangxx_asan -DSHARED %s -shared -o %t-so.so -fPIC // RUN: %clangxx_asan %s -ldl -pthread -o %t %t-so.so // RUN: ASAN_OPTIONS=verbosity=2 %run %t 2>&1 | FileCheck %s // CHECK: before // CHECK: __tls_get_addr: static tls // CHECK: after #ifndef SHARED #include <stdio.h> unsigned *f(); int main(int argc, char *argv[]) { fprintf(stderr, "before\n"); f(); fprintf(stderr, "after\n"); return 0; } #else // SHARED static __thread unsigned ThreadLocal; unsigned *f() { return &ThreadLocal; } #endif
// REQUIRES: asan-64-bits // Regression test: __tls_get_addr interceptor must recognize static TLS. // // RUN: %clangxx_asan -DSHARED %s -shared -o %t-so.so -fPIC // RUN: %clangxx_asan %s -ldl -pthread -o %t %t-so.so // RUN: ASAN_OPTIONS=verbosity=2 %run %t 2>&1 | FileCheck %s // CHECK: before // CHECK: __tls_get_addr: static tls // CHECK: after // XFAIL: powerpc64 #ifndef SHARED #include <stdio.h> unsigned *f(); int main(int argc, char *argv[]) { fprintf(stderr, "before\n"); f(); fprintf(stderr, "after\n"); return 0; } #else // SHARED static __thread unsigned ThreadLocal; unsigned *f() { return &ThreadLocal; } #endif
Support id() method for RGroup resources used in rules
#include "event.h" #include "deconz.h" #include "resource.h" /*! Constructor. */ Event::Event() : m_resource(0), m_what(0), m_num(0), m_numPrev(0) { } Event::Event(const char *resource, const char *what, const QString &id, ResourceItem *item) : m_resource(resource), m_what(what), m_id(id), m_num(0), m_numPrev(0) { DBG_Assert(item != 0); if (item) { m_num = item->toNumber(); m_numPrev = item->toNumberPrevious(); } } /*! Constructor. */ Event::Event(const char *resource, const char *what, const QString &id) : m_resource(resource), m_what(what), m_id(id), m_num(0), m_numPrev(0) { } /*! Constructor. */ Event::Event(const char *resource, const char *what, int num) : m_resource(resource), m_what(what), m_num(num), m_numPrev(0) { }
#include "event.h" #include "deconz.h" #include "resource.h" /*! Constructor. */ Event::Event() : m_resource(0), m_what(0), m_num(0), m_numPrev(0) { } Event::Event(const char *resource, const char *what, const QString &id, ResourceItem *item) : m_resource(resource), m_what(what), m_id(id), m_num(0), m_numPrev(0) { DBG_Assert(item != 0); if (item) { m_num = item->toNumber(); m_numPrev = item->toNumberPrevious(); } } /*! Constructor. */ Event::Event(const char *resource, const char *what, const QString &id) : m_resource(resource), m_what(what), m_id(id), m_num(0), m_numPrev(0) { } /*! Constructor. */ Event::Event(const char *resource, const char *what, int num) : m_resource(resource), m_what(what), m_num(num), m_numPrev(0) { if (resource == RGroups) { m_id = QString::number(num); } }
Add Logmessage on Module Start and Stop
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. // // Copyright 2015 Heiko Fink, All Rights Reserved. // // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // // Perception Neuron (TM) is a trademark of Beijing Noitom Technology Ltd. // // Description: // This code implements the module startup and shutdown functions. // #include "PerceptionNeuronPrivatePCH.h" #define LOCTEXT_NAMESPACE "FPerceptionNeuronModule" void FPerceptionNeuronModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module } void FPerceptionNeuronModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FPerceptionNeuronModule, PerceptionNeuron)
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. // // Copyright 2015 Heiko Fink, All Rights Reserved. // // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // // Perception Neuron (TM) is a trademark of Beijing Noitom Technology Ltd. // // Description: // This code implements the Perception Neuron (TM) module startup and shutdown functions. // #include "PerceptionNeuronPrivatePCH.h" #define LOCTEXT_NAMESPACE "FPerceptionNeuronModule" void FPerceptionNeuronModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module UE_LOG(LogInit, Log, TEXT("Unofficial Perception Neuron (TM) Plugin started.")); } void FPerceptionNeuronModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. UE_LOG(LogExit, Log, TEXT("Unofficial Perception Neuron (TM) Plugin unloaded.")); } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FPerceptionNeuronModule, PerceptionNeuron)
Print the random seed at startup
#include <gtest/gtest.h> #include <stdlib.h> #include <time.h> #if defined (ANDROID_NDK) #include <stdio.h> #endif #if (defined(ANDROID_NDK)||defined(APPLE_IOS)) int CodecUtMain (int argc , char** argv) { #else int main (int argc, char** argv) { #endif #if (defined(ANDROID_NDK)||defined(APPLE_IOS)) char xmlPath[1024] = ""; sprintf (xmlPath, "xml:%s", argv[1]); ::testing::GTEST_FLAG (output) = xmlPath; #endif srand ((unsigned int)time (NULL)); ::testing::InitGoogleTest (&argc, argv); return RUN_ALL_TESTS(); }
#include <gtest/gtest.h> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <string.h> #if (defined(ANDROID_NDK)||defined(APPLE_IOS)) int CodecUtMain (int argc , char** argv) { #else int main (int argc, char** argv) { #endif #if (defined(ANDROID_NDK)||defined(APPLE_IOS)) char xmlPath[1024] = ""; sprintf (xmlPath, "xml:%s", argv[1]); ::testing::GTEST_FLAG (output) = xmlPath; #endif ::testing::InitGoogleTest (&argc, argv); unsigned int seed = (unsigned int) time (NULL); if (argc >= 2 && !strncmp (argv[1], "--seed=", 7)) seed = atoi (argv[1] + 7); printf ("Random seed: %u\n", seed); srand (seed); return RUN_ALL_TESTS(); }
Add integration-ish test for the boot
#include <gtest/gtest.h> #include "../../include/Cpu.h" // The fixture for testing class Foo. class CpuTest : public Cpu, public ::testing::Test { protected: CpuTest() { } ~CpuTest() override { } void SetUp() override { } void TearDown() override { } }; TEST_F(CpuTest, pcNop) { runOpcode(0x01); EXPECT_EQ(getPC(), 3); } TEST_F(CpuTest, integrationBlop) { //run bootstrap rom to see if we crash? getMMU().injectBoot(); for (long long unsigned int i = 0; i < 1000000; i++) execute(); // std::cout << getInfo() << std::endl // << "Cyles: " << getTotalCycles(); }
#include <gtest/gtest.h> #include "../../include/Cpu.h" // The fixture for testing class Foo. class CpuTest : public Cpu, public ::testing::Test { protected: CpuTest() { } ~CpuTest() override { } void SetUp() override { } void TearDown() override { } }; TEST_F(CpuTest, pcNop) { runOpcode(0x01); EXPECT_EQ(getPC(), 3); } TEST_F(CpuTest, DMGboot) { //run bootstrap rom to see if we crash getMMU().injectBoot(); getMMU().writeByte(0xff44, 0x90); //$0064, screen frame skip getMMU().writeByte(0x0135, 0xe7); //ensure the checksum is correct long long unsigned int i = 0; while(getRegisters().pc != 0x100) { execute(); ASSERT_LT(i++, 15000000); //shouldn't take more? } }
Remove isnan of an int
#include "Halide.h" #include <stdint.h> #include <stdio.h> #include <cmath> using namespace Halide; // FIXME: Why aren't we using a unit test framework for this? // See Issue #898 void h_assert(bool condition, const char* msg) { if (!condition) { printf("FAIL: %s\n", msg); abort(); } } int main() { // Number is larger than can be represented in half and won't be rounded // down to the largest representable value in half(65504). but should be // representable in single precision const int32_t largeNum = 65536; h_assert(!std::isnan(largeNum), "largeNum should not be NaN"); h_assert(!std::isinf(largeNum), "largeNum should not be inf"); // This should fail as it triggers overflow float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven); // Supress -Wunused-but-set-variable fail.is_infinity(); printf("Should not be reached!\n"); return 0; }
#include "Halide.h" #include <stdint.h> #include <stdio.h> #include <cmath> using namespace Halide; // FIXME: Why aren't we using a unit test framework for this? // See Issue #898 void h_assert(bool condition, const char* msg) { if (!condition) { printf("FAIL: %s\n", msg); abort(); } } int main() { // Number is larger than can be represented in half and won't be rounded // down to the largest representable value in half(65504). but should be // representable in single precision const int32_t largeNum = 65536; // This should fail as it triggers overflow float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven); // Supress -Wunused-but-set-variable fail.is_infinity(); printf("Should not be reached!\n"); return 0; }
Fix ignored return type warning.
/* Copyright c1997-2006 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 2.5 http://www.bombaydigital.com/ */ /** @file */ #include "vwritebufferedstream.h" #include "vexception.h" VWriteBufferedStream::VWriteBufferedStream(VStream& rawStream, Vs64 initialBufferSize, Vs64 resizeIncrement) : VMemoryStream(initialBufferSize, resizeIncrement), mRawStream(rawStream) { } Vs64 VWriteBufferedStream::read(Vu8* /*targetBuffer*/, Vs64 /*numBytesToRead*/) { throw VException("VWriteBufferedStream::read: Read is not permitted on buffered write stream."); return CONST_S64(0); } void VWriteBufferedStream::flush() { // Flush the complete contents of our buffer to the raw stream. this->seek(SEEK_SET, 0); // set our i/o offset back to 0 ::streamCopy(*this, mRawStream, this->eofOffset()); // Reset ourself to be "empty" and at i/o offset 0. this->seek(SEEK_SET, 0); this->setEOF(0); } bool VWriteBufferedStream::skip(Vs64 /*numBytesToSkip*/) { throw VException("VWriteBufferedStream::skip: Skip is not permitted on buffered write stream."); return false; }
/* Copyright c1997-2006 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 2.5 http://www.bombaydigital.com/ */ /** @file */ #include "vwritebufferedstream.h" #include "vexception.h" VWriteBufferedStream::VWriteBufferedStream(VStream& rawStream, Vs64 initialBufferSize, Vs64 resizeIncrement) : VMemoryStream(initialBufferSize, resizeIncrement), mRawStream(rawStream) { } Vs64 VWriteBufferedStream::read(Vu8* /*targetBuffer*/, Vs64 /*numBytesToRead*/) { throw VException("VWriteBufferedStream::read: Read is not permitted on buffered write stream."); return CONST_S64(0); } void VWriteBufferedStream::flush() { // Flush the complete contents of our buffer to the raw stream. this->seek(SEEK_SET, 0); // set our i/o offset back to 0 (void) streamCopy(*this, mRawStream, this->eofOffset()); // Reset ourself to be "empty" and at i/o offset 0. this->seek(SEEK_SET, 0); this->setEOF(0); } bool VWriteBufferedStream::skip(Vs64 /*numBytesToSkip*/) { throw VException("VWriteBufferedStream::skip: Skip is not permitted on buffered write stream."); return false; }
Fix an error of tv range normalization
#include "BezierCurve.h" BezierCurve::BezierCurve(int range, double accur, int bits) { m_range = range; m_accur = accur; m_bits = bits; } double BezierCurve::normalize(int x) { double result; int scale = ((1 << m_bits) - 1) / 255; if (m_range == 0) // PC range { result = x / (255. * scale); } else // TV range { if (x < 16 * scale) result = 0; else if (x > 255 * scale) result = 1; else result = (x - 16 * scale) / (235. * scale - 16. * scale); } return result; }
#include "BezierCurve.h" BezierCurve::BezierCurve(int range, double accur, int bits) { m_range = range; m_accur = accur; m_bits = bits; } double BezierCurve::normalize(int x) { double result; int scale = ((1 << m_bits) - 1) / 255; if (m_range == 0) // PC range { result = x / (255. * scale); } else // TV range { if (x < 16 * scale) result = 0; else if (x > 235 * scale) result = 1; else result = (x - 16 * scale) / (235. * scale - 16. * scale); } return result; }
Disable KCatalogLoader for kdelibs below 4.6.2
/* Copyright 2011 Thomas McGuire <mcguire@kde.org> Copyright 2011 Alexander Potashev <aspotashev@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "util.h" #include <KGlobal> static const KCatalogLoader loader("libkvkontakte"); KDateTime unixTimeToKDateTime(const QString &unixTime) { KDateTime res; res.setTime_t(unixTime.toLongLong()); return res; }
/* Copyright 2011 Thomas McGuire <mcguire@kde.org> Copyright 2011 Alexander Potashev <aspotashev@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "util.h" #include <kdeversion.h> #if KDE_IS_VERSION(4,6,2) #include <KDE/KGlobal> static const KCatalogLoader loader("libkvkontakte"); #endif KDateTime unixTimeToKDateTime(const QString &unixTime) { KDateTime res; res.setTime_t(unixTime.toLongLong()); return res; }
Add link to github in about text.
#include "stdafx.h" #include "foobar2000/SDK/foobar2000.h" #include "ServerProxy.h" DECLARE_COMPONENT_VERSION( "foo_rest", "0.1", "REST interface for foobar." ) class InitQuit : public initquit { public: virtual void on_init(); virtual void on_quit(); }; std::unique_ptr<ServerProxy> serverProxy; void InitQuit::on_init() { serverProxy = std::make_unique<ServerProxy>(); } void InitQuit::on_quit() { serverProxy.release(); } initquit_factory_t<InitQuit> initQuitFactory;
#include "stdafx.h" #include "foobar2000/SDK/foobar2000.h" #include "ServerProxy.h" DECLARE_COMPONENT_VERSION( "foo_rest", "0.1", "REST interface for foobar.\nhttps://github.com/ivarboms/foo_rest" ) class InitQuit : public initquit { public: virtual void on_init(); virtual void on_quit(); }; std::unique_ptr<ServerProxy> serverProxy; void InitQuit::on_init() { serverProxy = std::make_unique<ServerProxy>(); } void InitQuit::on_quit() { serverProxy.release(); } initquit_factory_t<InitQuit> initQuitFactory;
Fix up TestRegisters for Linux ptracer lock-down.
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdio.h> #include <unistd.h> int main (int argc, char const *argv[]) { char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0}; double my_double = 1234.5678; // For simplicity assume that any cmdline argument means wait for attach. if (argc > 1) { volatile int wait_for_attach=1; while (wait_for_attach) usleep(1); } printf("my_string=%s\n", my_string); printf("my_double=%g\n", my_double); return 0; }
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdio.h> #include <unistd.h> #if defined(__linux__) #include <sys/prctl.h> #endif int main (int argc, char const *argv[]) { #if defined(__linux__) // Immediately enable any ptracer so that we can allow the stub attach // operation to succeed. Some Linux kernels are locked down so that // only an ancestor process can be a ptracer of a process. This disables that // restriction. Without it, attach-related stub tests will fail. #if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY) // For now we execute on best effort basis. If this fails for // some reason, so be it. const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0); static_cast<void> (prctl_result); #endif #endif char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0}; double my_double = 1234.5678; // For simplicity assume that any cmdline argument means wait for attach. if (argc > 1) { volatile int wait_for_attach=1; while (wait_for_attach) usleep(1); } printf("my_string=%s\n", my_string); printf("my_double=%g\n", my_double); return 0; }
Add a blank line to force this file to be recompiled on Mac on the bots.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/ppapi_messages.h" #include "base/file_path.h" #include "ipc/ipc_channel_handle.h" #include "ppapi/c/dev/pp_file_info_dev.h" #include "ppapi/c/ppb_var.h" // This actually defines the implementations of all the IPC message functions. #define MESSAGES_INTERNAL_IMPL_FILE "ppapi/proxy/ppapi_messages_internal.h" #include "ipc/ipc_message_impl_macros.h"
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/ppapi_messages.h" #include "base/file_path.h" #include "ipc/ipc_channel_handle.h" #include "ppapi/c/dev/pp_file_info_dev.h" #include "ppapi/c/ppb_var.h" // This actually defines the implementations of all the IPC message functions. #define MESSAGES_INTERNAL_IMPL_FILE "ppapi/proxy/ppapi_messages_internal.h" #include "ipc/ipc_message_impl_macros.h"
Improve usage message, according to nickrw's suggestion.
#include "tmfs.hh" int main(int argc, char ** argv) { if (argc < 3) { fprintf(stderr, "%s: <path> fuse-options...\n", argv[0]); return 2; } /* global structure setup */ tmfs::instance().hfs_root_ = argv[1]; --argc; for (int i = 1; i < argc; ++i) argv[i] = argv[i + 1]; /* check that hfs_root is a directory */ struct stat st; if (lstat(tmfs::instance().hfs_root_.c_str(), &st)) { fprintf(stderr, "%s: %m\n", tmfs::instance().hfs_root_.c_str()); return 1; } if (!S_ISDIR(st.st_mode)) { fprintf(stderr, "%s: is not a directory\n", tmfs::instance().hfs_root_.c_str()); return 1; } /* vtable setup */ struct fuse_operations ops; memset(&ops, 0, sizeof (ops)); ops.read = tmfs_read; ops.getattr = tmfs_getattr; ops.readdir = tmfs_readdir; /* lets go */ fuse_main(argc, argv, &ops, NULL); return 0; }
#include "tmfs.hh" int main(int argc, char ** argv) { if (argc < 3) { fprintf(stderr, "usage: %s: <HFS+ mount> <Time Machine Mount>" " [fuse options]\n", argv[0]); return 2; } /* global structure setup */ tmfs::instance().hfs_root_ = argv[1]; --argc; for (int i = 1; i < argc; ++i) argv[i] = argv[i + 1]; /* check that hfs_root is a directory */ struct stat st; if (lstat(tmfs::instance().hfs_root_.c_str(), &st)) { fprintf(stderr, "%s: %m\n", tmfs::instance().hfs_root_.c_str()); return 1; } if (!S_ISDIR(st.st_mode)) { fprintf(stderr, "%s: is not a directory\n", tmfs::instance().hfs_root_.c_str()); return 1; } /* vtable setup */ struct fuse_operations ops; memset(&ops, 0, sizeof (ops)); ops.read = tmfs_read; ops.getattr = tmfs_getattr; ops.readdir = tmfs_readdir; /* lets go */ fuse_main(argc, argv, &ops, NULL); return 0; }
Use map range for iterator
#include "fdsb/fabric.hpp" #include "fdsb/nid.hpp" #include "fdsb/harc.hpp" #include <unordered_map> using namespace fdsb; std::unordered_multimap<unsigned long long,Harc*> fabric; Harc &fdsb::get(const Nid &a, const Nid &b) { for (auto i : fabric.find(Nid::dual_hash(a,b))) { if ((i->tail(0) == a && i->tail(1) == b) || (i->tail(0) == b && i->tail(1) == a)) { return *i; } } Harc *nh = new Harc(a,b); add(*nh); return *nh; } void fdsb::add(Harc &h) { fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}}); } void fdsb::add(const Nid &n1, const Nid &n2) { fdsb::add(*(new Harc(n1,n2))); } Harc &Nid::operator[](const Nid &n) { return fdsb::get(*this,n); } Harc &Harc::operator[](const Nid &n) { return fdsb::get(query(),n); }
#include "fdsb/fabric.hpp" #include "fdsb/nid.hpp" #include "fdsb/harc.hpp" #include <unordered_map> using namespace fdsb; std::unordered_multimap<unsigned long long,Harc*> fabric; Harc &fdsb::get(const Nid &a, const Nid &b) { auto range = fabric.equal_range(Nid::dual_hash(a,b)); for (auto i : range) { if ((i->tail(0) == a && i->tail(1) == b) || (i->tail(0) == b && i->tail(1) == a)) { return *i; } } Harc *nh = new Harc(a,b); add(*nh); return *nh; } void fdsb::add(Harc &h) { fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}}); } void fdsb::add(const Nid &n1, const Nid &n2) { fdsb::add(*(new Harc(n1,n2))); } Harc &Nid::operator[](const Nid &n) { return fdsb::get(*this,n); } Harc &Harc::operator[](const Nid &n) { return fdsb::get(query(),n); }
Use SingleApplication rather than Application
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Christian Surlykke <christian@surlykke.dk> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/Application> #include "mainwindow.h" int main(int argc, char *argv[]) { LxQt::Application a(argc, argv); MainWindow mainWindow; mainWindow.setWindowIcon(QIcon::fromTheme("preferences-system-power-management")); mainWindow.show(); return a.exec(); }
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Christian Surlykke <christian@surlykke.dk> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/SingleApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { LxQt::SingleApplication a(argc, argv); MainWindow mainWindow; mainWindow.setWindowIcon(QIcon::fromTheme("preferences-system-power-management")); mainWindow.show(); a.setActivationWindow(&mainWindow); return a.exec(); }
Make cpp test a unit test
#include <iostream> int main(void) { std::cout << "woooot" << std::endl; }
#define BOOST_TEST_MODULE simple_test #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(simple_cpp_test) { BOOST_CHECK(true); }
Fix broken benchmark of Lossy count.
// Copyright 2020 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/benchmark.h" #include "benchmark_utils.h" #include "lossy_count.h" #include "sketch.h" #include "utils.h" static void BM_LossyCountAdd(benchmark::State& state) { sketch::LossyCount sketch(/*window_size=*/2000); Add(state, &sketch); } static void BM_LossyCountFallbackAdd(benchmark::State& state) { sketch::LossyCount_Fallback sketch(/*window_size=*/2000, /*hash_count=*/5, /*hash_size=*/2048); Add(state, &sketch); } BENCHMARK(BM_LossyCountAdd)->Range(1 << 12, 1 << 21); BENCHMARK(BM_LossyCountFallbackAdd)->Range(1 << 12, 1 << 21); BENCHMARK_MAIN();
// Copyright 2020 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/benchmark.h" #include "benchmark_utils.h" #include "lossy_count.h" #include "sketch.h" #include "utils.h" static void BM_LossyCountAdd(benchmark::State& state) { sketch::LossyCount sketch(/*window_size=*/2000); Add(state, &sketch); } static void BM_LossyCountFallbackAdd(benchmark::State& state) { sketch::LossyCountFallback sketch(/*window_size=*/2000, /*hash_count=*/5, /*hash_size=*/2048); Add(state, &sketch); } BENCHMARK(BM_LossyCountAdd)->Range(1 << 12, 1 << 21); BENCHMARK(BM_LossyCountFallbackAdd)->Range(1 << 12, 1 << 21); BENCHMARK_MAIN();
Correct 'unused private field' warning
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Commons/Utils.hpp> #include <hspp/Policies/IoPolicy.hpp> namespace Hearthstonepp { IoPolicy::IoPolicy(std::ostream& out, std::istream& in) : m_out(out), m_in(in) { // Do nothing } TaskMeta IoPolicy::RequireMulligan(Player& player) { TaskMetaTrait trait(TaskID::MULLIGAN, TaskStatus::MULLIGAN_SUCCESS, player.GetID()); return TaskMeta(trait, SizedPtr<std::size_t>(3)); } TaskMeta IoPolicy::RequirePlayCard(Player& player) { (void)player; return TaskMeta(); } TaskMeta IoPolicy::RequireCombat(Player& player) { (void)player; return TaskMeta(); } void IoPolicy::NotifyOverDraw(const TaskMeta& meta) { (void)meta; } } // namespace Hearthstonepp
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Commons/Utils.hpp> #include <hspp/Policies/IoPolicy.hpp> namespace Hearthstonepp { IoPolicy::IoPolicy(std::ostream& out, std::istream& in) : m_out(out), m_in(in) { // Do nothing } TaskMeta IoPolicy::RequireMulligan(Player& player) { TaskMetaTrait trait(TaskID::MULLIGAN, TaskStatus::MULLIGAN_SUCCESS, player.GetID()); return TaskMeta(trait, SizedPtr<std::size_t>(3)); } TaskMeta IoPolicy::RequirePlayCard(Player& player) { (void)player; return TaskMeta(); } TaskMeta IoPolicy::RequireCombat(Player& player) { (void)player; return TaskMeta(); } void IoPolicy::NotifyOverDraw(const TaskMeta& meta) { (void)m_in; (void)m_out; (void)meta; } } // namespace Hearthstonepp
Make application open only if file is provided
/* * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include "window.h" #include <string> int main(int argc, char const* argv[]) { Window window; if (argc > 1) { std::string filename = argv[1]; window.create(filename); } else { window.create(); } return 0; }
/* * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include "window.h" #include <iostream> #include <string> int main(int argc, char const* argv[]) { Window window; if (argc > 1) { std::string filename = argv[1]; window.create(filename); } else { std::cout << "SFML Image Viewer (c) 2017" << std::endl; std::cout << std::endl; std::cout << "Usage: sfiv FILE" << std::endl; } return 0; }
Change infinite loop to sleep
#include <cstdio> int main(int argc, char* argv[]) { printf("testapp reporting in!\n"); for (;;) ; return 0; }
#include <cstdio> #include <unistd.h> int main(int argc, char* argv[]) { printf("testapp reporting in!\n"); sleep(100000000); return 0; }
Fix diagnostics when using Clang compilation API
#include "clang.h" #include <memory> #include <utility> #pragma warning(push, 0) #include <clang/Basic/Diagnostic.h> #include <clang/Basic/DiagnosticIDs.h> #include <clang/Basic/VirtualFileSystem.h> // Fixes "Member access into incomplete type 'clang::vfs::FileSystem'". #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <llvm/ADT/ArrayRef.h> #include <llvm/Support/Host.h> #include <llvm/Support/Path.h> #include <llvm/Support/raw_ostream.h> #pragma warning(pop) int delta::invokeClang(llvm::ArrayRef<const char*> args) { auto* diagClient = new clang::TextDiagnosticPrinter(llvm::errs(), nullptr); diagClient->setPrefix(llvm::sys::path::filename(args[0])); clang::DiagnosticsEngine diags(new clang::DiagnosticIDs(), nullptr, diagClient); clang::driver::Driver driver(args[0], llvm::sys::getDefaultTargetTriple(), diags); std::unique_ptr<clang::driver::Compilation> compilation(driver.BuildCompilation(args)); if (compilation) { llvm::SmallVector<std::pair<int, const clang::driver::Command*>, 4> failingCommands; return driver.ExecuteCompilation(*compilation, failingCommands); } diags.getClient()->finish(); return 1; }
#include "clang.h" #include <memory> #include <utility> #pragma warning(push, 0) #include <clang/Basic/Diagnostic.h> #include <clang/Basic/DiagnosticIDs.h> #include <clang/Basic/VirtualFileSystem.h> // Fixes "Member access into incomplete type 'clang::vfs::FileSystem'". #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <llvm/ADT/ArrayRef.h> #include <llvm/Support/Host.h> #include <llvm/Support/Path.h> #include <llvm/Support/raw_ostream.h> #pragma warning(pop) int delta::invokeClang(llvm::ArrayRef<const char*> args) { auto* diagClient = new clang::TextDiagnosticPrinter(llvm::errs(), new clang::DiagnosticOptions()); diagClient->setPrefix(llvm::sys::path::filename(args[0])); clang::DiagnosticsEngine diags(new clang::DiagnosticIDs(), nullptr, diagClient); clang::driver::Driver driver(args[0], llvm::sys::getDefaultTargetTriple(), diags); std::unique_ptr<clang::driver::Compilation> compilation(driver.BuildCompilation(args)); if (compilation) { llvm::SmallVector<std::pair<int, const clang::driver::Command*>, 4> failingCommands; return driver.ExecuteCompilation(*compilation, failingCommands); } diags.getClient()->finish(); return 1; }
Fix wrong member names in Cell
#include "cell.hpp" namespace roadagain { Cell::Cell() : color(EMPTY) { } Cell::Cell(const Point& point, CellColor color) : point(point), color(color) { } void Cell::reverse() { color_ = reversed(color_); } } // namespace roadagain
#include "cell.hpp" namespace roadagain { Cell::Cell() : color(EMPTY) { } Cell::Cell(const Point& point, CellColor color) : point_(point), color_(color) { } void Cell::reverse() { color_ = reversed(color_); } } // namespace roadagain
Include correct version of <boost/test/.../output_test_stream.hpp>
#define BOOST_TEST_MODULE VexIO #include <boost/test/unit_test.hpp> #include <boost/test/tools/output_test_stream.hpp> #include <vexcl/vector.hpp> #include <vexcl/element_index.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(stream_vector) { boost::test_tools::output_test_stream output; vex::vector<int> x(ctx, 32); x = vex::element_index(); output << x; BOOST_CHECK(output.is_equal( "{\n" " 0: 0 1 2 3 4 5 6 7 8 9\n" " 10: 10 11 12 13 14 15 16 17 18 19\n" " 20: 20 21 22 23 24 25 26 27 28 29\n" " 30: 30 31\n" "}\n" )); } BOOST_AUTO_TEST_SUITE_END()
#define BOOST_TEST_MODULE VexIO #include <boost/test/unit_test.hpp> #if BOOST_VERSION >= 107100 # include <boost/test/tools/output_test_stream.hpp> #else # include <boost/test/output_test_stream.hpp> #endif #include <vexcl/vector.hpp> #include <vexcl/element_index.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(stream_vector) { boost::test_tools::output_test_stream output; vex::vector<int> x(ctx, 32); x = vex::element_index(); output << x; BOOST_CHECK(output.is_equal( "{\n" " 0: 0 1 2 3 4 5 6 7 8 9\n" " 10: 10 11 12 13 14 15 16 17 18 19\n" " 20: 20 21 22 23 24 25 26 27 28 29\n" " 30: 30 31\n" "}\n" )); } BOOST_AUTO_TEST_SUITE_END()
Fix for map get iteration
#include "fdsb/fabric.hpp" #include "fdsb/nid.hpp" #include "fdsb/harc.hpp" #include <unordered_map> using namespace fdsb; std::unordered_multimap<unsigned long long,Harc*> fabric; Harc &fdsb::get(const Nid &a, const Nid &b) { auto range = fabric.equal_range(Nid::dual_hash(a,b)); for (auto i : range) { if ((i->tail(0) == a && i->tail(1) == b) || (i->tail(0) == b && i->tail(1) == a)) { return *i; } } Harc *nh = new Harc(a,b); add(*nh); return *nh; } void fdsb::add(Harc &h) { fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}}); } void fdsb::add(const Nid &n1, const Nid &n2) { fdsb::add(*(new Harc(n1,n2))); } Harc &Nid::operator[](const Nid &n) { return fdsb::get(*this,n); } Harc &Harc::operator[](const Nid &n) { return fdsb::get(query(),n); }
#include "fdsb/fabric.hpp" #include "fdsb/nid.hpp" #include "fdsb/harc.hpp" #include <unordered_map> using namespace fdsb; std::unordered_multimap<unsigned long long,Harc*> fabric; Harc &fdsb::get(const Nid &a, const Nid &b) { auto range = fabric.equal_range(Nid::dual_hash(a,b)); for (auto i = range.first; i != range.second; i++) { if (((*i)->tail(0) == a && (*i)->tail(1) == b) || ((*i)->tail(0) == b && (*i)->tail(1) == a)) { return *(*i); } } Harc *nh = new Harc(a,b); add(*nh); return *nh; } void fdsb::add(Harc &h) { fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}}); } void fdsb::add(const Nid &n1, const Nid &n2) { fdsb::add(*(new Harc(n1,n2))); } Harc &Nid::operator[](const Nid &n) { return fdsb::get(*this,n); } Harc &Harc::operator[](const Nid &n) { return fdsb::get(query(),n); }
Use static buffer instead of allocation in libport::getWinErrorMessage.
/** ** \file libport/string.cc ** \brief string: implements file libport/string.hh */ #include <boost/lexical_cast.hpp> #include "libport/cstring" #include "libport/detect_win32.h" namespace libport { #ifdef WIN32 # define LIBPORT_BUFFER_SIZE 1024 const char* getWinErrorMessage() { static char msg_buf[LIBPORT_BUFFER_SIZE]; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), 0, (LPTSTR)msg_buf, LIBPORT_BUFFER_SIZE, NULL); return msg_buf; } # undef LIBPORT_BUFFER_SIZE #endif const char* strerror(int errnum) { #ifndef WIN32 return ::strerror(errnum); #else const char* str; if (errnum != 0) str = ::strerror(errnum); else str = getWinErrorMessage(); return str; #endif } }
/** ** \file libport/string.cc ** \brief string: implements file libport/string.hh */ #include <boost/lexical_cast.hpp> #include "libport/cstring" #include "libport/detect_win32.h" namespace libport { #ifdef WIN32 # define LIBPORT_BUFFER_SIZE 1024 const char* getWinErrorMessage() { static char msg_buf[LIBPORT_BUFFER_SIZE]; FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, GetLastError(), 0, (LPTSTR)msg_buf, LIBPORT_BUFFER_SIZE, 0); return msg_buf; } # undef LIBPORT_BUFFER_SIZE #endif const char* strerror(int errnum) { #ifndef WIN32 return ::strerror(errnum); #else const char* str; if (errnum != 0) str = ::strerror(errnum); else str = getWinErrorMessage(); return str; #endif } }
Fix multithreading issue for MSVC caused by setlocale
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2008 Sean Gillies * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: ORIGINAL WORK * **********************************************************************/ #include <geos/io/CLocalizer.h> #include <string> #include <clocale> using namespace std; namespace geos { namespace io { CLocalizer::CLocalizer() { char* p = std::setlocale(LC_NUMERIC, NULL); if (0 != p) { saved_locale = p; } std::setlocale(LC_NUMERIC, "C"); } CLocalizer::~CLocalizer() { std::setlocale(LC_NUMERIC, saved_locale.c_str()); } } // namespace geos.io } // namespace geos
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2008 Sean Gillies * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: ORIGINAL WORK * **********************************************************************/ #include <geos/io/CLocalizer.h> #include <string> #include <clocale> using namespace std; namespace geos { namespace io { CLocalizer::CLocalizer() { #ifdef _MSC_VER // Avoid multithreading issues caused by setlocale _configthreadlocale(_ENABLE_PER_THREAD_LOCALE); #endif char* p = std::setlocale(LC_NUMERIC, NULL); if (0 != p) { saved_locale = p; } std::setlocale(LC_NUMERIC, "C"); } CLocalizer::~CLocalizer() { std::setlocale(LC_NUMERIC, saved_locale.c_str()); } } // namespace geos.io } // namespace geos
Make the program crash if vasprintf cannot allocate memory.
// 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. // /////////////////////////////////////////////////////////////////////////////// #ifndef _GNU_SOURCE #define _GNU_SOURCE // needed for vasprintf(3) #endif #include "tink/util/errors.h" #include <stdarg.h> #include <stdlib.h> #include "tink/util/status.h" using crypto::tink::util::error::Code; using crypto::tink::util::Status; namespace crypto { namespace tink { // Construct a Status object given a printf-style va list. Status ToStatusF(Code code, const char* format, ...) { va_list ap; va_start(ap, format); char* p; vasprintf(&p, format, ap); va_end(ap); Status status(code, p); free(p); return status; } } // namespace tink } // namespace crypto
// 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. // /////////////////////////////////////////////////////////////////////////////// #ifndef _GNU_SOURCE #define _GNU_SOURCE // needed for vasprintf(3) #endif #include "tink/util/errors.h" #include <stdarg.h> #include <stdlib.h> #include "tink/util/status.h" using crypto::tink::util::error::Code; using crypto::tink::util::Status; namespace crypto { namespace tink { // Construct a Status object given a printf-style va list. Status ToStatusF(Code code, const char* format, ...) { va_list ap; va_start(ap, format); char* p; if (vasprintf(&p, format, ap) < 0) { abort(); } va_end(ap); Status status(code, p); free(p); return status; } } // namespace tink } // namespace crypto
Add a (commented out) incorrect conversion
#include "output.h" Output output; float a = 123.0; int b = 79; unsigned int c = 24; int main() { float d = b; float e = c; output << (int) a; // CHECK: 0x0000007b output << (unsigned int) a; // CHECK: 0x0000007b output << (int) d; // CHECK: 0x0000004f }
#include "output.h" Output output; float a = 123.0; int b = 79; unsigned int c = 24; int main() { float d = b; float e = c; output << (int) a; // CHECK: 0x0000007b output << (unsigned int) a; // CHECK: 0x0000007b output << (int) d; // CHECK: 0x0000004f // output << (int) e; // XXX should be 0x18, but is 0x17 for some reason }
Verify that clock domain sources are nodes of expected SOURCE type
#include "validate_timing_graph_constraints.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" #include "tatum_error.hpp" #include "loop_detect.hpp" namespace tatum { bool validate_timing_graph_constraints(const TimingGraph& /*timing_graph*/, const TimingConstraints& /*timing_constraints*/) { //Nothing here for now return true; } } //namespace
#include "validate_timing_graph_constraints.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" #include "tatum_error.hpp" #include "loop_detect.hpp" namespace tatum { bool validate_timing_graph_constraints(const TimingGraph& timing_graph, const TimingConstraints& timing_constraints) { //Check that all clocks are defined as sources for(DomainId domain : timing_constraints.clock_domains()) { NodeId source_node = timing_constraints.clock_domain_source_node(domain); if(timing_graph.node_type(source_node) != NodeType::SOURCE) { std::string msg; msg = "Clock Domain " + std::to_string(size_t(domain)) + " (" + timing_constraints.clock_domain_name(domain) + ")" " source node " + std::to_string(size_t(source_node)) + " is not a node of type SOURCE."; throw tatum::Error(msg); } } //Nothing here for now return true; } } //namespace
Fix the windows allocator to behave properly on realloc.
// 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. // This is a simple allocator based on the windows heap. extern "C" { HANDLE win_heap; bool win_heap_init(bool use_lfh) { win_heap = HeapCreate(0, 0, 0); if (win_heap == NULL) return false; if (use_lfh) { ULONG enable_lfh = 2; HeapSetInformation(win_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); // NOTE: Setting LFH may fail. Vista already has it enabled. // And under the debugger, it won't use LFH. So we // ignore any errors. } return true; } void* win_heap_malloc(size_t s) { return HeapAlloc(win_heap, 0, s); } void* win_heap_realloc(void* p, size_t s) { if (!p) return win_heap_malloc(s); return HeapReAlloc(win_heap, 0, p, s); } void win_heap_free(void* s) { HeapFree(win_heap, 0, s); } size_t win_heap_msize(void* p) { return HeapSize(win_heap, 0, p); } } // extern "C"
// 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. // This is a simple allocator based on the windows heap. extern "C" { HANDLE win_heap; bool win_heap_init(bool use_lfh) { win_heap = HeapCreate(0, 0, 0); if (win_heap == NULL) return false; if (use_lfh) { ULONG enable_lfh = 2; HeapSetInformation(win_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); // NOTE: Setting LFH may fail. Vista already has it enabled. // And under the debugger, it won't use LFH. So we // ignore any errors. } return true; } void* win_heap_malloc(size_t size) { return HeapAlloc(win_heap, 0, size); } void win_heap_free(void* size) { HeapFree(win_heap, 0, size); } void* win_heap_realloc(void* ptr, size_t size) { if (!ptr) return win_heap_malloc(size); if (!size) { win_heap_free(ptr); return NULL; } return HeapReAlloc(win_heap, 0, ptr, size); } size_t win_heap_msize(void* ptr) { return HeapSize(win_heap, 0, ptr); } } // extern "C"
Disable Metal renderer for sample project
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Application.h" void ouzelMain(const std::vector<std::string>& args) { OUZEL_UNUSED(args); ouzel::Settings settings; settings.driver = ouzel::video::Renderer::Driver::METAL; settings.size = ouzel::Size2(800.0f, 600.0f); settings.resizable = true; ouzel::sharedEngine->init(settings); std::shared_ptr<Application> application = std::make_shared<Application>(); ouzel::sharedEngine->setApp(application); }
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Application.h" void ouzelMain(const std::vector<std::string>& args) { OUZEL_UNUSED(args); ouzel::Settings settings; //settings.driver = ouzel::video::Renderer::Driver::METAL; settings.size = ouzel::Size2(800.0f, 600.0f); settings.resizable = true; ouzel::sharedEngine->init(settings); std::shared_ptr<Application> application = std::make_shared<Application>(); ouzel::sharedEngine->setApp(application); }
Make parser unit test slightly more complex
// gtest macros raise -Wsign-compare #pragma GCC diagnostic ignored "-Wsign-compare" #include <string> #include "gtest/gtest.h" #include "libparse/driver.h" #include "libparse/parser.tab.h" extern casmi_driver *global_driver; class ParserTest: public ::testing::Test { protected: virtual void SetUp() { global_driver = &driver_; } casmi_string_driver driver_; }; TEST_F(ParserTest, parse_simple) { std::string test = "init main\n" "rule main = {\n" " x := 1 - 2\n" "}\n"; AstNode *root = driver_.parse(test); AstListNode *stmts = new AstListNode(NodeType::STATEMENTS); stmts->add(new UpdateNode( new Expression( new Expression(nullptr, create_atom(1)), create_atom(2)) )); AstListNode *ast = new AstListNode(NodeType::BODY_ELEMENTS); ast->add(new AstNode(NodeType::INIT)); ast->add(new UnaryNode(NodeType::RULE, new UnaryNode(NodeType::PARBLOCK, stmts))); EXPECT_EQ(true, root->equals(ast)); delete ast; delete root; } TEST_F(ParserTest, parse_error) { std::string test = "init\n"; EXPECT_EQ(nullptr, driver_.parse(test)); }
// gtest macros raise -Wsign-compare #pragma GCC diagnostic ignored "-Wsign-compare" #include <string> #include "gtest/gtest.h" #include "libparse/driver.h" #include "libparse/parser.tab.h" extern casmi_driver *global_driver; class ParserTest: public ::testing::Test { protected: virtual void SetUp() { global_driver = &driver_; } casmi_string_driver driver_; }; TEST_F(ParserTest, parse_simple) { std::string test = "init main\n" "rule main = {\n" " x := 1 - 2\n" " y := 5 - 10\n" "}\n"; AstNode *root = driver_.parse(test); AstListNode *stmts = new AstListNode(NodeType::STATEMENTS); stmts->add(new UpdateNode( new Expression( new Expression(nullptr, create_atom(1)), create_atom(2)) )); stmts->add(new UpdateNode( new Expression( new Expression(nullptr, create_atom(5)), create_atom(10)) )); AstListNode *ast = new AstListNode(NodeType::BODY_ELEMENTS); ast->add(new AstNode(NodeType::INIT)); ast->add(new UnaryNode(NodeType::RULE, new UnaryNode(NodeType::PARBLOCK, stmts))); EXPECT_EQ(true, root->equals(ast)); delete ast; delete root; } TEST_F(ParserTest, parse_error) { std::string test = "init\n"; EXPECT_EQ(nullptr, driver_.parse(test)); }
Increase mutation size of Priority Threshold Gene
#include "Genes/Priority_Threshold_Gene.h" #include <memory> #include <string> #include <algorithm> #include "Utility.h" class Board; Priority_Threshold_Gene::Priority_Threshold_Gene() : threshold(0.0) { } void Priority_Threshold_Gene::reset_properties() const { properties["Threshold"] = threshold; } void Priority_Threshold_Gene::load_properties() { threshold = properties["Threshold"]; } std::unique_ptr<Gene> Priority_Threshold_Gene::duplicate() const { return std::make_unique<Priority_Threshold_Gene>(*this); } std::string Priority_Threshold_Gene::name() const { return "Priority Threshold Gene"; } double Priority_Threshold_Gene::score_board(const Board&) const { return 0.0; } double Priority_Threshold_Gene::get_threshold() const { return threshold; } void Priority_Threshold_Gene::gene_specific_mutation() { threshold = std::max(0.0, threshold + Random::random_normal(1.0)); }
#include "Genes/Priority_Threshold_Gene.h" #include <memory> #include <string> #include <algorithm> #include "Utility.h" class Board; Priority_Threshold_Gene::Priority_Threshold_Gene() : threshold(0.0) { } void Priority_Threshold_Gene::reset_properties() const { properties["Threshold"] = threshold; } void Priority_Threshold_Gene::load_properties() { threshold = properties["Threshold"]; } std::unique_ptr<Gene> Priority_Threshold_Gene::duplicate() const { return std::make_unique<Priority_Threshold_Gene>(*this); } std::string Priority_Threshold_Gene::name() const { return "Priority Threshold Gene"; } double Priority_Threshold_Gene::score_board(const Board&) const { return 0.0; } double Priority_Threshold_Gene::get_threshold() const { return threshold; } void Priority_Threshold_Gene::gene_specific_mutation() { threshold = std::max(0.0, threshold + Random::random_normal(2.0)); }
Use the new Regex::isValid() with no parameter
//===-- RegularExpression.cpp -----------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Utility/RegularExpression.h" #include <string> using namespace lldb_private; RegularExpression::RegularExpression(llvm::StringRef str) : m_regex_text(str), // m_regex does not reference str anymore after it is constructed. m_regex(llvm::Regex(str)) {} RegularExpression::RegularExpression(const RegularExpression &rhs) : RegularExpression(rhs.GetText()) {} bool RegularExpression::Execute( llvm::StringRef str, llvm::SmallVectorImpl<llvm::StringRef> *matches) const { if (!IsValid()) return false; return m_regex.match(str, matches); } bool RegularExpression::IsValid() const { std::string discarded; return m_regex.isValid(discarded); } llvm::StringRef RegularExpression::GetText() const { return m_regex_text; } llvm::Error RegularExpression::GetError() const { std::string error; if (!m_regex.isValid(error)) return llvm::make_error<llvm::StringError>(llvm::inconvertibleErrorCode(), error); return llvm::Error::success(); }
//===-- RegularExpression.cpp -----------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Utility/RegularExpression.h" #include <string> using namespace lldb_private; RegularExpression::RegularExpression(llvm::StringRef str) : m_regex_text(str), // m_regex does not reference str anymore after it is constructed. m_regex(llvm::Regex(str)) {} RegularExpression::RegularExpression(const RegularExpression &rhs) : RegularExpression(rhs.GetText()) {} bool RegularExpression::Execute( llvm::StringRef str, llvm::SmallVectorImpl<llvm::StringRef> *matches) const { if (!IsValid()) return false; return m_regex.match(str, matches); } bool RegularExpression::IsValid() const { return m_regex.isValid(); } llvm::StringRef RegularExpression::GetText() const { return m_regex_text; } llvm::Error RegularExpression::GetError() const { std::string error; if (!m_regex.isValid(error)) return llvm::make_error<llvm::StringError>(llvm::inconvertibleErrorCode(), error); return llvm::Error::success(); }
Duplicate FixedCube test, move initializing cube data to fixture
#include <gtest/gtest.h> #include <fixedcube.hh> #include <side.hh> using namespace Rubik; class FixedCubeTests : public testing::Test { private: static int n; public: int generateInteger() { return n++; } Side::Data generateSideData() { Side::Data result; for(unsigned int i=0; i<result.size(); i++) result[i] = generateInteger(); return result; } }; int FixedCubeTests::n = 0; TEST_F(FixedCubeTests, Initialize) { CubeData data = top(generateSideData()). left(generateSideData()). front(generateSideData()). right(generateSideData()). bottom(generateSideData()). back(generateSideData()); FixedCube::Ptr cube = FixedCube::create(data); EXPECT_EQ(data, cube->data()); }
#include <gtest/gtest.h> #include <fixedcube.hh> #include <side.hh> using namespace Rubik; class FixedCubeTests : public testing::Test { private: static int n; public: CubeData data; public: FixedCubeTests() : data(top(generateSideData()). left(generateSideData()). front(generateSideData()). right(generateSideData()). bottom(generateSideData()). back(generateSideData())) { } ~FixedCubeTests() { // Keep square values relatively small n=0; } int generateInteger() { return n++; } Side::Data generateSideData() { Side::Data result; for(unsigned int i=0; i<result.size(); i++) result[i] = generateInteger(); return result; } }; int FixedCubeTests::n = 0; TEST_F(FixedCubeTests, Initialize) { FixedCube::Ptr cube = FixedCube::create(data); EXPECT_EQ(data, cube->data()); } TEST_F(FixedCubeTests, InitializeWithFactory) { FixedCube::Ptr cube = FixedCube::create(data); EXPECT_EQ(data, cube->data()); }
Use "REQUIRES: x86_64-target-arch" to disable the test on i386.
// RUN: %clangxx -O0 %s -o %t // RUN: %env_tool_opts=strip_path_prefix=/TestCases/ %run %t 2>&1 | FileCheck %s // UNSUPPORTED: i386-apple // // Tests __sanitizer_symbolize_pc. #include <stdio.h> #include <sanitizer/common_interface_defs.h> void SymbolizeCaller() { char data[1000]; __sanitizer_symbolize_pc(__builtin_return_address(0), "%p %F %L", data, sizeof(data)); printf("FIRST_FORMAT %s\n", data); __sanitizer_symbolize_pc(__builtin_return_address(0), "FUNC:%f LINE:%l FILE:%s", data, sizeof(data)); printf("SECOND_FORMAT %s\n", data); } // CHECK: FIRST_FORMAT 0x{{.*}} in main symbolize_pc.cc:[[@LINE+3]] // CHECK: SECOND_FORMAT FUNC:main LINE:[[@LINE+2]] FILE:symbolize_pc.cc int main() { SymbolizeCaller(); }
// RUN: %clangxx -O0 %s -o %t // RUN: %env_tool_opts=strip_path_prefix=/TestCases/ %run %t 2>&1 | FileCheck %s // REQUIRES: x86_64-target-arch // // Tests __sanitizer_symbolize_pc. #include <stdio.h> #include <sanitizer/common_interface_defs.h> void SymbolizeCaller() { char data[1000]; __sanitizer_symbolize_pc(__builtin_return_address(0), "%p %F %L", data, sizeof(data)); printf("FIRST_FORMAT %s\n", data); __sanitizer_symbolize_pc(__builtin_return_address(0), "FUNC:%f LINE:%l FILE:%s", data, sizeof(data)); printf("SECOND_FORMAT %s\n", data); } // CHECK: FIRST_FORMAT 0x{{.*}} in main symbolize_pc.cc:[[@LINE+3]] // CHECK: SECOND_FORMAT FUNC:main LINE:[[@LINE+2]] FILE:symbolize_pc.cc int main() { SymbolizeCaller(); }
Make this test pass if llvm-g++ was built without exception handling support.
// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | grep _Unwind_Resume | wc -l | grep {\[03\]} struct One { }; struct Two { }; void handle_unexpected () { try { throw; } catch (One &) { throw Two (); } }
// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | grep -c {handle\\|_Unwind_Resume} | grep {\[14\]} struct One { }; struct Two { }; void handle_unexpected () { try { throw; } catch (One &) { throw Two (); } }
Fix another layering violation in assmebly macro dumping
//===- MCAsmMacro.h - Assembly Macros ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCAsmMacro.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; void MCAsmMacroParameter::dump(raw_ostream &OS) const { OS << "\"" << Name << "\""; if (Required) OS << ":req"; if (Vararg) OS << ":vararg"; if (!Value.empty()) { OS << " = "; bool first = true; for (const AsmToken &T : Value) { if (!first) OS << ", "; first = false; T.dump(); } } OS << "\n"; } void MCAsmMacro::dump(raw_ostream &OS) const { OS << "Macro " << Name << ":\n"; OS << " Parameters:\n"; for (const MCAsmMacroParameter &P : Parameters) { OS << " "; P.dump(); } OS << " (BEGIN BODY)" << Body << "(END BODY)\n"; }
//===- MCAsmMacro.h - Assembly Macros ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCAsmMacro.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; void MCAsmMacroParameter::dump(raw_ostream &OS) const { OS << "\"" << Name << "\""; if (Required) OS << ":req"; if (Vararg) OS << ":vararg"; if (!Value.empty()) { OS << " = "; bool first = true; for (const AsmToken &T : Value) { if (!first) OS << ", "; first = false; OS << T.getString(); } } OS << "\n"; } void MCAsmMacro::dump(raw_ostream &OS) const { OS << "Macro " << Name << ":\n"; OS << " Parameters:\n"; for (const MCAsmMacroParameter &P : Parameters) { OS << " "; P.dump(); } OS << " (BEGIN BODY)" << Body << "(END BODY)\n"; }
Make sure this test doesn't break when we disallow throwing an exception in -fno-exceptions mode.
// RUN: %clang_cc1 %s -emit-llvm-only -verify // PR7281 class A { public: ~A(); }; class B : public A { void ice_throw(); }; void B::ice_throw() { throw *this; }
// RUN: %clang_cc1 %s -emit-llvm -o - -fexceptions | FileCheck %s // PR7281 class A { public: ~A(); }; class B : public A { void ice_throw(); }; void B::ice_throw() { throw *this; }
Add int * complex double
// complex double * int // originally found in package 'snd_7.8-1' // b.ii:7:19: error: invalid complex arithmetic operand types `double _Complex &' and `int &' // ERR-MATCH: invalid complex arithmetic operand types int main() { _Complex double a; int b; _Complex double c = a * b; }
// complex double * int // originally found in package 'snd_7.8-1' // b.ii:7:19: error: invalid complex arithmetic operand types `double _Complex &' and `int &' // ERR-MATCH: invalid complex arithmetic operand types int main() { _Complex double a; int b; _Complex double c = a * b; _Complex double d = b * a; }
Indent and fix include statement
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include <QApplication> #include "gui/mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow window; window.show(); return app.exec(); }
Make inner call instead of duplicating the code.
#include <rewrite/desugarer.hh> #include <rewrite/pattern-binder.hh> #include <rewrite/rewrite.hh> #include <rewrite/rescoper.hh> namespace rewrite { // FIXME: template-factor those two ast::rNary rewrite(ast::rConstNary nary) { Desugarer desugar; Rescoper rescope; ast::rAst res; desugar(nary.get()); res = desugar.result_get(); rescope(res.get()); res = rescope.result_get(); return res.unsafe_cast<ast::Nary>(); } ast::rExp rewrite(ast::rConstExp nary) { Desugarer desugar; Rescoper rescope; ast::rAst res; desugar(nary.get()); res = desugar.result_get(); rescope(res.get()); res = rescope.result_get(); return res.unsafe_cast<ast::Exp>(); } }
#include <rewrite/desugarer.hh> #include <rewrite/pattern-binder.hh> #include <rewrite/rewrite.hh> #include <rewrite/rescoper.hh> namespace rewrite { ast::rNary rewrite(ast::rConstNary nary) { return rewrite(ast::rConstExp(nary)).unsafe_cast<ast::Nary>(); } ast::rExp rewrite(ast::rConstExp nary) { Desugarer desugar; Rescoper rescope; ast::rAst res; desugar(nary.get()); res = desugar.result_get(); rescope(res.get()); res = rescope.result_get(); return res.unsafe_cast<ast::Exp>(); } }
Disable auto-enqueue functionality in message destructor.
#include "MessageBase.hpp" #include "MessageBaseImpl.hpp" namespace Grappa { /// Internal messaging functions namespace impl { /// @addtogroup Communication /// @{ void Grappa::impl::MessageBase::legacy_send_message_am( char * buf, size_t size, void * payload, size_t payload_size ) { Grappa::impl::MessageBase::deserialize_and_call( static_cast< char * >( buf ) ); } /// Block until message can be deallocated. void Grappa::impl::MessageBase::block_until_sent() { // if message has not been enqueued to be sent, do so. // if it has already been sent somehow, then don't worry about it. if( !is_sent_ && !is_enqueued_ ) { DVLOG(5) << this << " not sent, so enqueuing"; enqueue(); } // now block until message is sent while( !is_sent_ ) { DVLOG(5) << this << " blocking until sent"; Grappa::wait( &cv_ ); DVLOG(5) << this << " woken"; } } /// @} } }
#include "MessageBase.hpp" #include "MessageBaseImpl.hpp" namespace Grappa { /// Internal messaging functions namespace impl { /// @addtogroup Communication /// @{ void Grappa::impl::MessageBase::legacy_send_message_am( char * buf, size_t size, void * payload, size_t payload_size ) { Grappa::impl::MessageBase::deserialize_and_call( static_cast< char * >( buf ) ); } /// Block until message can be deallocated. void Grappa::impl::MessageBase::block_until_sent() { // if enqueued, block until message is sent while( is_enqueued_ && !is_sent_ ) { DVLOG(5) << this << " blocking until sent"; Grappa::wait( &cv_ ); DVLOG(5) << this << " woken"; } } /// @} } }
Fix taint attribute in sym element
#include "SymbolicEngine.h" SymbolicElement::SymbolicElement(std::stringstream &dst, std::stringstream &src, uint64_t id) { //this->isTainted = !TAINTED; this->source = new std::stringstream(src.str()); this->destination = new std::stringstream(dst.str()); this->expression = new std::stringstream(); *this->expression << (*this->destination).str() << " = " << (*this->source).str(); this->id = id; } SymbolicElement::~SymbolicElement() { delete this->source; delete this->destination; delete this->expression; } /* Returns the SMT dst and src expression of the symbolic element */ std::stringstream *SymbolicElement::getExpression() { return this->expression; } /* Returns the SMT src expression of the symbolic element */ std::stringstream *SymbolicElement::getSource() { return this->source; } /* Returns the ID of the symbolic element */ uint64_t SymbolicElement::getID() { return this->id; }
#include "SymbolicEngine.h" SymbolicElement::SymbolicElement(std::stringstream &dst, std::stringstream &src, uint64_t id) { this->isTainted = false; this->source = new std::stringstream(src.str()); this->destination = new std::stringstream(dst.str()); this->expression = new std::stringstream(); *this->expression << (*this->destination).str() << " = " << (*this->source).str(); this->id = id; } SymbolicElement::~SymbolicElement() { delete this->source; delete this->destination; delete this->expression; } /* Returns the SMT dst and src expression of the symbolic element */ std::stringstream *SymbolicElement::getExpression() { return this->expression; } /* Returns the SMT src expression of the symbolic element */ std::stringstream *SymbolicElement::getSource() { return this->source; } /* Returns the ID of the symbolic element */ uint64_t SymbolicElement::getID() { return this->id; }
Check that the assertion macro does not throw when the condition is satisfied
/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <DTK_Search_Exception.hpp> #include <boost/test/unit_test.hpp> #define BOOST_TEST_MODULE DesignByContract BOOST_AUTO_TEST_CASE( dumb ) { using namespace DataTransferKit; BOOST_CHECK_THROW( DTK_SEARCH_ASSERT( false ), SearchException ); std::string const prefix = "DTK Search exception: "; std::string const message = "Keep calm and chive on!"; BOOST_CHECK_EXCEPTION( throw SearchException( message ), SearchException, [&]( SearchException const &e ) { return prefix + message == e.what(); } ); }
/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <DTK_Search_Exception.hpp> #include <boost/test/unit_test.hpp> #define BOOST_TEST_MODULE DesignByContract BOOST_AUTO_TEST_CASE( dumb ) { using namespace DataTransferKit; BOOST_CHECK_NO_THROW( DTK_SEARCH_ASSERT( true ) ); BOOST_CHECK_THROW( DTK_SEARCH_ASSERT( false ), SearchException ); std::string const prefix = "DTK Search exception: "; std::string const message = "Keep calm and chive on!"; BOOST_CHECK_EXCEPTION( throw SearchException( message ), SearchException, [&]( SearchException const &e ) { return prefix + message == e.what(); } ); }
Refactor error messages for worker threads
#include "WorkerThread.h" #include "Logger.h" #include <sstream> namespace comm { WorkerThread::WorkerThread() : tasks(folly::MPMCQueue<std::unique_ptr<taskType>>(20)) { auto job = [this]() { while (true) { std::unique_ptr<taskType> lastTask; this->tasks.blockingRead(lastTask); if (lastTask == nullptr) { break; } (*lastTask)(); } }; this->thread = std::make_unique<std::thread>(job); } void WorkerThread::scheduleTask(const taskType task) { if (!this->tasks.write(std::make_unique<taskType>(std::move(task)))) { throw std::runtime_error("Error scheduling task on Database thread"); } } WorkerThread::~WorkerThread() { this->tasks.blockingWrite(nullptr); try { this->thread->join(); } catch (const std::system_error &error) { std::ostringstream stringStream; stringStream << "Error occurred joining the Database thread: " << error.what(); Logger::log(stringStream.str()); } } } // namespace comm
#include "WorkerThread.h" #include "Logger.h" #include <sstream> namespace comm { WorkerThread::WorkerThread() : tasks(folly::MPMCQueue<std::unique_ptr<taskType>>(20)) { auto job = [this]() { while (true) { std::unique_ptr<taskType> lastTask; this->tasks.blockingRead(lastTask); if (lastTask == nullptr) { break; } (*lastTask)(); } }; this->thread = std::make_unique<std::thread>(job); } void WorkerThread::scheduleTask(const taskType task) { if (!this->tasks.write(std::make_unique<taskType>(std::move(task)))) { throw std::runtime_error("Error scheduling task on a worker thread"); } } WorkerThread::~WorkerThread() { this->tasks.blockingWrite(nullptr); try { this->thread->join(); } catch (const std::system_error &error) { std::ostringstream stringStream; stringStream << "Error occurred joining a worker thread: " << error.what(); Logger::log(stringStream.str()); } } } // namespace comm
Use std::string instead of string (error fix, compiles now)
#include <string> #include "runDiff.h" int main(int argc, const char * argv[]) { if (argc != 2 ) { std::cerr<<"Usage: "<<argv[0]<<" input file name"<<std::endl; return 1; } runFiles(string(argv[1])); return 0; }
#include <string> #include "runDiff.h" int main(int argc, const char * argv[]) { if (argc != 2 ) { std::cerr<<"Usage: "<<argv[0]<<" input file name"<<std::endl; return 1; } runFiles(std::string(argv[1])); return 0; }
Change example a little bit
#include <iostream> #include "List.h" using namespace std; using namespace List_h; void foo() { Skip_list ll; for (auto i = -50; i < 50000; ++i) { ll.push_back(i); } ll.display(); } int main() { Skip_list sl; sl.push_back(3); sl.push_back(6); sl.push_back(7); sl.push_back(9); sl.push_back(12); sl.push_back(17); sl.push_back(19); sl.push_back(25); sl.push_back(26); sl.insert(40, 40); sl.push_front(1); sl.delete_node(1); sl.delete_node(17); sl.display(); int val; std::cout << "Please enter a number to search: "; std::cin >> val; if (sl.search(val)) { std::cout << val << " was found" << std::endl; } else { std::cout << val << " was not found" << std::endl; } return 0; }
#include <vector> #include <initializer_list> #include <algorithm> #include <random> #include <iostream> #include <ctime> #include "List.h" using namespace std; using namespace List_h; void foo() { Skip_list ll; for (auto i = -50; i < 50000; ++i) { ll.push_back(i); } ll.display(); } int main() { constexpr int border = 8000000; Skip_list sl; Slink_list sll; for (auto i = 0; i < border; ++i) { sl.push_back(i); sll.push_back(i); } int val; std::cout << "Please enter a number to search: "; while (std::cin >> val) { clock_t t; t = clock(); /*if (sl.search(val)) { std::cout << val << " was found" << std::endl; } else { std::cout << val << " was not found" << std::endl; }*/ bool vt = sl.search(val); t = clock() - t; std::cout << "Search in the skip list took me " << t << " cycles (" << static_cast<float> (t) / CLOCKS_PER_SEC << " seconds).\n"; t = clock(); const Link *p = sll.find(val); t = clock() - t; std::cout << "Search in the singly linked list took me " << t << " cycles (" << static_cast<float> (t) / CLOCKS_PER_SEC << " seconds).\n"; if (vt) { std::cout << "Value " << p->val << " was found\n"; } } return 0; }
Correct call to remove empty queues.
#include "Animator.h" namespace hm { Animator::Animator() { } Animator::~Animator() { } void Animator::add(Animation a) { animations.push_back(a); return; } void Animator::add(AnimationQueue q) { queues.push_back(q); return; } void Animator::clearAnimations() { animations.clear(); return; } void Animator::clearQueues() { queues.clear(); return; } void Animator::clear() { animations.clear(); queues.clear(); return; } void Animator::animate() { // Iteratively animate all given animations. for(std::vector<Animation>::iterator it = animations.begin(); it != animations.end(); it++) { it->animate(); // Remove completed animations. if(it->isComplete()) { it = animations.erase(it); it--; } } // Iteratively animate all given queues. for(std::vector<AnimationQueue>::iterator it = queues.begin(); it != queues.end(); it++) { it->animate(); // Remove empty queues. if(it->isComplete()) { it = animations.erase(it); it--; } } return; } }
#include "Animator.h" namespace hm { Animator::Animator() { } Animator::~Animator() { } void Animator::add(Animation a) { animations.push_back(a); return; } void Animator::add(AnimationQueue q) { queues.push_back(q); return; } void Animator::clearAnimations() { animations.clear(); return; } void Animator::clearQueues() { queues.clear(); return; } void Animator::clear() { animations.clear(); queues.clear(); return; } void Animator::animate() { // Iteratively animate all given animations. for(std::vector<Animation>::iterator it = animations.begin(); it != animations.end(); it++) { it->animate(); // Remove completed animations. if(it->isComplete()) { it = animations.erase(it); it--; } } // Iteratively animate all given queues. for(std::vector<AnimationQueue>::iterator it = queues.begin(); it != queues.end(); it++) { it->animate(); // Remove empty queues. if(it->isComplete()) { it = queues.erase(it); it--; } } return; } }
Fix ambiguity for 32-bit gcc.
// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #include "ofp/protocoliterator.h" #include "ofp/unittest.h" using namespace ofp; TEST(protocoliterator, ProtocolRangeItemCount) { UInt64 buffer; ByteRange data{&buffer, 0UL}; const size_t unused = ~0UL; EXPECT_EQ( 0, detail::ProtocolRangeItemCount(8, data, PROTOCOL_ITERATOR_SIZE_FIXED)); for (size_t offset = 0; offset < 32; offset += 2) { EXPECT_EQ(0, detail::ProtocolRangeItemCount(unused, data, offset)); } } TEST(protocoliterator, ProtocolRangeSplitOffset) { UInt64 buffer = 0; ByteRange data{&buffer, 0UL}; const size_t unused = ~0UL; EXPECT_EQ(0, detail::ProtocolRangeSplitOffset(8, unused, data, 0)); *Big16_cast(&buffer) = 8; ByteRange data8{&buffer, sizeof(buffer)}; EXPECT_EQ(8, detail::ProtocolRangeSplitOffset(8, unused, data8, 0)); }
// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #include "ofp/protocoliterator.h" #include "ofp/unittest.h" using namespace ofp; TEST(protocoliterator, ProtocolRangeItemCount) { UInt64 buffer; ByteRange data{&buffer, static_cast<size_t>(0)}; const size_t unused = ~0UL; EXPECT_EQ( 0, detail::ProtocolRangeItemCount(8, data, PROTOCOL_ITERATOR_SIZE_FIXED)); for (size_t offset = 0; offset < 32; offset += 2) { EXPECT_EQ(0, detail::ProtocolRangeItemCount(unused, data, offset)); } } TEST(protocoliterator, ProtocolRangeSplitOffset) { UInt64 buffer = 0; ByteRange data{&buffer, static_cast<size_t>(0)}; const size_t unused = ~0UL; EXPECT_EQ(0, detail::ProtocolRangeSplitOffset(8, unused, data, 0)); *Big16_cast(&buffer) = 8; ByteRange data8{&buffer, sizeof(buffer)}; EXPECT_EQ(8, detail::ProtocolRangeSplitOffset(8, unused, data8, 0)); }
Test for FileWriter (not enough disk space).
#include "../../base/SRC_FIRST.hpp" #include "../../testing/testing.hpp" #include "../writer.hpp" #include "../../base/macros.hpp" UNIT_TEST(MemWriterEmpty) { vector<char> data; { MemWriter< vector<char> > writer(data); } TEST(data.empty(), (data)); } UNIT_TEST(MemWriterSimple) { vector<char> data; MemWriter< vector<char> > writer(data); writer.Write("Hello", 5); writer.Write(",", 1); writer.Write("world!", 6); char const expected_string[] = "Hello,world!"; vector<char> expected_data(&expected_string[0], &expected_string[ARRAY_SIZE(expected_string)-1]); TEST_EQUAL(data, expected_data, ()); }
#include "../../base/SRC_FIRST.hpp" #include "../../testing/testing.hpp" #include "../writer.hpp" #include "../file_writer.hpp" #include "../../base/macros.hpp" UNIT_TEST(MemWriterEmpty) { vector<char> data; { MemWriter< vector<char> > writer(data); } TEST(data.empty(), (data)); } UNIT_TEST(MemWriterSimple) { vector<char> data; MemWriter< vector<char> > writer(data); writer.Write("Hello", 5); writer.Write(",", 1); writer.Write("world!", 6); char const expected[] = "Hello,world!"; TEST_EQUAL(data.size(), ARRAY_SIZE(expected)-1, ()); TEST(equal(data.begin(), data.end(), &expected[0]), (data)); } /* UNIT_TEST(FileWriter_NoDiskSpace) { FileWriter w("/Volumes/Untitled/file.bin"); vector<uint8_t> bytes(100000000); for (size_t i = 0; i < 10; ++i) w.Write(&bytes[0], bytes.size()); } */
Add newline to end of file.
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/launcher/unit_test_launcher.h" namespace base { int LaunchUnitTests(int argc, char** argv, const RunTestSuiteCallback& run_test_suite) { // Stub implementation - iOS doesn't support features we need for // the full test launcher (e.g. process_util). return run_test_suite.Run(); } } // namespace base
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/launcher/unit_test_launcher.h" namespace base { int LaunchUnitTests(int argc, char** argv, const RunTestSuiteCallback& run_test_suite) { // Stub implementation - iOS doesn't support features we need for // the full test launcher (e.g. process_util). return run_test_suite.Run(); } } // namespace base
Use target hide method instead of custom code on initialization
/* * Author: Laurent Goderre */ #include <stdio.h> #include <Arduino.h> #include "Target.h" //------------------------------------- // TODO: CALIBRATE THESE FOR SERVOS const int servoOffPosition = 150; const int servoOnPosition = 400; //------------------------------------- const String showingStr = "Showing target #"; const String hidingStr = "Hiding target #"; Target::Target(int targetNumber, Adafruit_PWMServoDriver pwm, int servoNumber) : number(targetNumber), pwm(pwm), servoNumber(servoNumber) { //Set Servo to initial position pwm.setPWM(servoNumber, 0, servoOffPosition); } Target::~Target(void){} void Target::show() { Serial.println(showingStr + (number + 1)); for (uint16_t pulselen = servoOffPosition; pulselen < servoOnPosition; pulselen++) { pwm.setPWM(servoNumber, 0, pulselen); } } void Target::hide() { Serial.println(hidingStr + (number + 1)); for (uint16_t pulselen = servoOnPosition; pulselen > servoOffPosition; pulselen--) { pwm.setPWM(servoNumber, 0, pulselen); } }
/* * Author: Laurent Goderre */ #include <stdio.h> #include <Arduino.h> #include "Target.h" //------------------------------------- // TODO: CALIBRATE THESE FOR SERVOS const int servoOffPosition = 150; const int servoOnPosition = 400; //------------------------------------- const String showingStr = "Showing target #"; const String hidingStr = "Hiding target #"; Target::Target(int targetNumber, Adafruit_PWMServoDriver pwm, int servoNumber) : number(targetNumber), pwm(pwm), servoNumber(servoNumber) { //Hide the target on initalization this->hide(); } Target::~Target(void){} void Target::show() { Serial.println(showingStr + (number + 1)); for (uint16_t pulselen = servoOffPosition; pulselen < servoOnPosition; pulselen++) { pwm.setPWM(servoNumber, 0, pulselen); } } void Target::hide() { Serial.println(hidingStr + (number + 1)); for (uint16_t pulselen = servoOnPosition; pulselen > servoOffPosition; pulselen--) { pwm.setPWM(servoNumber, 0, pulselen); } }
Extend async DNS field trial to other supported 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/net/async_dns_field_trial.h" #include "base/metrics/field_trial.h" #include "build/build_config.h" #include "chrome/common/chrome_version_info.h" namespace chrome_browser_net { bool ConfigureAsyncDnsFieldTrial() { #if defined(OS_ANDROID) || defined(OS_IOS) // There is no DnsConfigService on those platforms so disable the field trial. return false; #endif const base::FieldTrial::Probability kAsyncDnsDivisor = 100; base::FieldTrial::Probability enabled_probability = 0; #if defined(OS_CHROMEOS) if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_DEV) enabled_probability = 50; #endif scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 10, 30, NULL)); int enabled_group = trial->AppendGroup("enabled", enabled_probability); return trial->group() == enabled_group; } } // namespace chrome_browser_net
// 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/net/async_dns_field_trial.h" #include "base/metrics/field_trial.h" #include "build/build_config.h" #include "chrome/common/chrome_version_info.h" namespace chrome_browser_net { bool ConfigureAsyncDnsFieldTrial() { #if defined(OS_ANDROID) || defined(OS_IOS) // There is no DnsConfigService on those platforms so disable the field trial. return false; #endif const base::FieldTrial::Probability kAsyncDnsDivisor = 100; base::FieldTrial::Probability enabled_probability = 0; if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_DEV) enabled_probability = 50; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 10, 30, NULL)); int enabled_group = trial->AppendGroup("enabled", enabled_probability); return trial->group() == enabled_group; } } // namespace chrome_browser_net
Add include line that may be required on some platforms
/* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC * See the file LICENSE for full license information. */ #include <errno.h> #include "posix.hh" FD_Reader::FD_Reader(int fd) throw() : _fd(fd), _errno(0) { } FD_Reader::~FD_Reader() throw(){ /* Assume file is read only; don't really care about successful close. */ if(-1 != _fd) close(_fd); } int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){ /* If file closed just return 0. */ if(-1 == _fd) return 0; /* BLOCKING read until data comes or unrecoverable error. */ while(true){ int ret = read(_fd, buff, len); if(ret < 0){ if(EINTR == errno) continue; _errno = errno; close(_fd); _fd = -1; } else if(0 == ret){ close(_fd); _fd = -1; } return ret; } }
/* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC * See the file LICENSE for full license information. */ #include <errno.h> #include <unistd.h> #include "posix.hh" FD_Reader::FD_Reader(int fd) throw() : _fd(fd), _errno(0) { } FD_Reader::~FD_Reader() throw(){ /* Assume file is read only; don't really care about successful close. */ if(-1 != _fd) close(_fd); } int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){ /* If file closed just return 0. */ if(-1 == _fd) return 0; /* BLOCKING read until data comes or unrecoverable error. */ while(true){ int ret = read(_fd, buff, len); if(ret < 0){ if(EINTR == errno) continue; _errno = errno; close(_fd); _fd = -1; } else if(0 == ret){ close(_fd); _fd = -1; } return ret; } }
Delete unnecessary code in transform class.
#include "Transform.h" BEGIN_NAMESPACE_CA_DRAWING Transform::Transform() : position(0, 0) , scale(1, 1) , angle(0) { } Transform::~Transform() { } //########################################################################### void Transform::addTransform(const Transform& other) { position += other.position; scale.x *= other.scale.x; scale.y *= other.scale.y; angle += other.angle; while (angle >= 360.0f) angle -= 360.0f; while (angle < 0.0f) angle += 360.0f; } END_NAMESPACE_CA_DRAWING
#include "Transform.h" BEGIN_NAMESPACE_CA_DRAWING Transform::Transform() : position(0, 0) , scale(1, 1) , angle(0) { } Transform::~Transform() { } //########################################################################### void Transform::addTransform(const Transform& other) { position += other.position; scale.x *= other.scale.x; scale.y *= other.scale.y; angle += other.angle; } END_NAMESPACE_CA_DRAWING