Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add conditional preprocessor for nomlib's install prefix under Windows
/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ // This file is auto-generated by CMake at build time #include "nomlib/version.hpp" const std::string NOMLIB_INSTALL_PREFIX = "/Users/jeff/Library/Frameworks"; const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";
/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ // This file is auto-generated by CMake at build time #include "nomlib/version.hpp" #if defined (NOM_PLATFORM_WINDOWS) const std::string NOMLIB_INSTALL_PREFIX = "C:/"; #endif const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";
Decrease window size to use less screen space
/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ofMain.h" #include "ofApp.h" //======================================================================== int main(){ ofSetupOpenGL(1024, 768, OF_WINDOW); ofRunApp(new ofApp()); }
/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ofMain.h" #include "ofApp.h" //======================================================================== int main(){ ofSetupOpenGL(126, 64, OF_WINDOW); ofRunApp(new ofApp()); }
Correct nullptr problem (change 'm_target' to 'entity')
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Actions/Generic.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> #include <Rosetta/Tasks/SimpleTasks/ReturnHandTask.hpp> namespace RosettaStone::SimpleTasks { ReturnHandTask::ReturnHandTask(EntityType entityType) : ITask(entityType) { // Do nothing } TaskID ReturnHandTask::GetTaskID() const { return TaskID::RETURN_HAND; } TaskStatus ReturnHandTask::Impl(Player& player) { auto entities = IncludeTask::GetEntities(m_entityType, player, m_source, m_target); for (auto& entity : entities) { Generic::RemoveMinionFromField(m_target->GetOwner(), dynamic_cast<Minion*>(entity)); entity->Reset(); Generic::AddCardToHand(m_target->GetOwner(), entity); } return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Actions/Generic.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> #include <Rosetta/Tasks/SimpleTasks/ReturnHandTask.hpp> namespace RosettaStone::SimpleTasks { ReturnHandTask::ReturnHandTask(EntityType entityType) : ITask(entityType) { // Do nothing } TaskID ReturnHandTask::GetTaskID() const { return TaskID::RETURN_HAND; } TaskStatus ReturnHandTask::Impl(Player& player) { auto entities = IncludeTask::GetEntities(m_entityType, player, m_source, m_target); for (auto& entity : entities) { Generic::RemoveMinionFromField(entity->GetOwner(), dynamic_cast<Minion*>(entity)); entity->Reset(); Generic::AddCardToHand(entity->GetOwner(), entity); } return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks
Add slightly more spacing in output.
#include "fnv_param.hpp" #include "fnv_algo.hpp" #include "constraint.hpp" #include "fnv_solver.hpp" #include <vector> #include <iostream> #include <boost/foreach.hpp> int main(int argc, char** argv) { const std::vector<FNVParam> fnvParams = FNVParam::getAll(); const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll(); const std::vector<Constraint> constraints = Constraint::getAll(); BOOST_FOREACH(const FNVParam& fnvParam, fnvParams) { std::cout << "Problem size: " << fnvParam.getWidth() << std::endl; BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos) { std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl; const Constraint nullConstraint = Constraint::getNull(); std::cout << "Constraint: " << nullConstraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, nullConstraint); solver.solve(); const int solutionLength = solver.getSolutionLength(); BOOST_FOREACH(const Constraint& constraint, constraints) { std::cout << "Constraint: " << constraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength); solver.solve(); } } } }
#include "fnv_param.hpp" #include "fnv_algo.hpp" #include "constraint.hpp" #include "fnv_solver.hpp" #include <vector> #include <iostream> #include <boost/foreach.hpp> int main(int argc, char** argv) { const std::vector<FNVParam> fnvParams = FNVParam::getAll(); const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll(); const std::vector<Constraint> constraints = Constraint::getAll(); BOOST_FOREACH(const FNVParam& fnvParam, fnvParams) { std::cout << "Problem size: " << fnvParam.getWidth() << std::endl; BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos) { std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl; const Constraint nullConstraint = Constraint::getNull(); std::cout << "Constraint: " << nullConstraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, nullConstraint); solver.solve(); const int solutionLength = solver.getSolutionLength(); BOOST_FOREACH(const Constraint& constraint, constraints) { std::cout << "Constraint: " << constraint.getName() << std::endl; FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength); solver.solve(); } } std::cout << std::endl; } }
Update rtcp receiver fuzzer to use generic function IncomingPacket(const uint8_t* packet, size_t size) instead of implementation specific IncomingRTCPPacket(PacketInfo* out, Parser* in) This would allow switch parse implementation
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/base/checks.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h" #include "webrtc/system_wrappers/include/clock.h" namespace webrtc { void FuzzOneInput(const uint8_t* data, size_t size) { RTCPUtility::RTCPParserV2 rtcp_parser(data, size, true); if (!rtcp_parser.IsValid()) return; webrtc::SimulatedClock clock(1234); RTCPReceiver receiver(&clock, false, nullptr, nullptr, nullptr, nullptr, nullptr); RTCPHelp::RTCPPacketInformation rtcp_packet_information; receiver.IncomingRTCPPacket(rtcp_packet_information, &rtcp_parser); } } // namespace webrtc
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/base/checks.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h" #include "webrtc/system_wrappers/include/clock.h" namespace webrtc { namespace { class NullModuleRtpRtcp : public RTCPReceiver::ModuleRtpRtcp { public: void SetTmmbn(std::vector<rtcp::TmmbItem>) override {} void OnRequestSendReport() override {} void OnReceivedNack(const std::vector<uint16_t>&) override {}; void OnReceivedRtcpReportBlocks(const ReportBlockList&) override {}; }; } void FuzzOneInput(const uint8_t* data, size_t size) { NullModuleRtpRtcp rtp_rtcp_module; SimulatedClock clock(1234); RTCPReceiver receiver(&clock, false, nullptr, nullptr, nullptr, nullptr, &rtp_rtcp_module); receiver.IncomingPacket(data, size); } } // namespace webrtc
Add -std=c++98 to the test and minor improvment in addition.
// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s -triple x86_64-apple-darwin10 | FileCheck %s // RUN: %clang_cc1 -S -emit-llvm -o %t.ll %s -triple x86_64-apple-darwin10 // RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o %t-c++11.ll %s -triple x86_64-apple-darwin10 // RUN: diff %t.ll %t-c++11.ll // rdar://12897704 struct sAFSearchPos { unsigned char *pos; unsigned char count; }; static volatile struct sAFSearchPos testPositions; // CHECK: @_ZL13testPositions = internal global %struct.sAFSearchPos zeroinitializer static volatile struct sAFSearchPos arrayPositions[100][10][5]; // CHECK: @_ZL14arrayPositions = internal global [100 x [10 x [5 x %struct.sAFSearchPos]]] zeroinitializer int main() { return testPositions.count + arrayPositions[10][4][3].count; }
// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o %t-c++11.ll %s -triple x86_64-apple-darwin10 // RUN: FileCheck %s < %t-c++11.ll // RUN: %clang_cc1 -std=c++98 -S -emit-llvm -o %t.ll %s -triple x86_64-apple-darwin10 // RUN: diff %t.ll %t-c++11.ll // rdar://12897704 struct sAFSearchPos { unsigned char *pos; unsigned char count; }; static volatile struct sAFSearchPos testPositions; // CHECK: @_ZL13testPositions = internal global %struct.sAFSearchPos zeroinitializer static volatile struct sAFSearchPos arrayPositions[100][10][5]; // CHECK: @_ZL14arrayPositions = internal global [100 x [10 x [5 x %struct.sAFSearchPos]]] zeroinitializer int main() { return testPositions.count + arrayPositions[10][4][3].count; }
Use transform instead of for_each
#include <algorithm> #include <cctype> #include <fstream> #include <iostream> #include <string> int main(int argc, char ** argv) { std::ifstream input{argv[1]}; std::string line; std::getline(input, line); while(input) { std::for_each(std::begin(line), std::end(line), [](char c) { std::cout << static_cast<char>(std::tolower(c)); }); std::cout << '\n'; std::getline(input, line); } return 0; }
#include <algorithm> #include <cctype> #include <fstream> #include <iostream> #include <string> int main(int argc, char ** argv) { std::ifstream input{argv[1]}; std::string line; std::getline(input, line); while(input) { std::transform(std::begin(line), std::end(line), std::begin(line), [](char c) { return static_cast<char>(std::tolower(c)); }); std::cout << line << '\n'; std::getline(input, line); } return 0; }
Print debugging information from tinygltfloader
/* * Copyright (C) 2016 Luke San Antonio * All rights reserved. */ // Include the implementation first so that it actually works. We have to do // this because our header file includes the header as well, we might as well // put the implementation here. #define TINYGLTF_LOADER_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #include "../../gltf/tiny_gltf_loader.h" #include "minigltf.h" #include <cstdio> #include "../common/log.h" namespace redc { boost::optional<tinygltf::Scene> load_gltf_file(std::string name) { std::string err; tinygltf::Scene scene; tinygltf::TinyGLTFLoader loader; if(!loader.LoadASCIIFromFile(&scene, &err, name)) { log_e("Error in '%': %", name, err); return boost::none; } return std::move(scene); } }
/* * Copyright (C) 2016 Luke San Antonio * All rights reserved. */ // Include the implementation first so that it actually works. We have to do // this because our header file includes the header as well, we might as well // put the implementation here. #define TINYGLTF_LOADER_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #include "../../gltf/tiny_gltf_loader.h" #include "minigltf.h" #include <cstdio> #include "../common/log.h" namespace redc { boost::optional<tinygltf::Scene> load_gltf_file(std::string name) { std::string err; tinygltf::Scene scene; tinygltf::TinyGLTFLoader loader; if(!loader.LoadASCIIFromFile(&scene, &err, name)) { log_e("Error in '%': %", name, err); return boost::none; } else { log_i("Information loading '%': %", name, err); } return std::move(scene); } }
Replace the += operator with push_back on file loading operations
// // Created by monty on 08/12/16. // #include <string> #include <iostream> #include <fstream> #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" namespace Knights { std::string CPlainFileLoader::loadFileFromPath( const std::string& path ) { std::string entry; std::ifstream fileToLoad(path); char buffer; while (!fileToLoad.eof()) { fileToLoad >> buffer; entry += buffer; } return entry; } std::string CPlainFileLoader::getFilePathPrefix() { return "res/"; } }
// // Created by monty on 08/12/16. // #include <string> #include <iostream> #include <fstream> #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" namespace Knights { std::string CPlainFileLoader::loadFileFromPath( const std::string& path ) { std::string entry; std::ifstream fileToLoad(path); char buffer; while (!fileToLoad.eof()) { fileToLoad >> buffer; entry.push_back(buffer); } return entry; } std::string CPlainFileLoader::getFilePathPrefix() { return "res/"; } }
Use ImageReader to read the images
#include "picturemodel.h" #include <QFile> PictureModel::PictureModel(QObject *parent) : MediaModel(MediaModel::Picture, parent) { QHash<int, QByteArray> roleNames = MediaModel::roleNames(); setRoleNames(roleNames); } PictureModel::~PictureModel() { } QVariant PictureModel::data(MediaInfo *mediaInfo, int role) const { if (role == Qt::DisplayRole) return mediaInfo->name; return QVariant(); } QImage PictureModel::decoration(MediaInfo *info) const { QImage thumbnail = (static_cast<PictureInfo *>(info))->thumbnail; if (thumbnail.isNull()) return QImage(themeResourcePath() + "/media/Fanart_Fallback_Picture_Small.jpg"); // FIXME: Make this configurable return thumbnail; } MediaInfo *PictureModel::readMediaInfo(const QString &filePath) { QImage image(filePath); PictureInfo *info = new PictureInfo; info->thumbnail = image; return info; }
#include "picturemodel.h" #include <QFile> #include <QImageReader> PictureModel::PictureModel(QObject *parent) : MediaModel(MediaModel::Picture, parent) { QHash<int, QByteArray> roleNames = MediaModel::roleNames(); setRoleNames(roleNames); } PictureModel::~PictureModel() { } QVariant PictureModel::data(MediaInfo *mediaInfo, int role) const { if (role == Qt::DisplayRole) return mediaInfo->name; return QVariant(); } QImage PictureModel::decoration(MediaInfo *info) const { return (static_cast<PictureInfo *>(info))->thumbnail; } MediaInfo *PictureModel::readMediaInfo(const QString &filePath) { QImageReader imageReader(filePath); if (!imageReader.canRead()) return 0; QImage image = imageReader.read(); if (image.isNull()) return 0; PictureInfo *info = new PictureInfo; info->thumbnail = image; return info; }
Add SVM classifier to Touche example.
/** @example user_touche.cpp Touche example. */ #include <ESP.h> BinaryIntArraySerialStream stream(0, 115200, 160); GestureRecognitionPipeline pipeline; void setup() { useInputStream(stream); pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160)); usePipeline(pipeline); }
/** @example user_touche.cpp Touche example. */ #include <ESP.h> BinaryIntArraySerialStream stream(0, 115200, 160); GestureRecognitionPipeline pipeline; void setup() { useInputStream(stream); pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160)); pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2)); usePipeline(pipeline); }
Add unit tests for dummy kernel
/** * Unit tests for base kernel class * @author Vyacheslav Kompan kompan.vo@phystech.edu * Copyright 2018 MIPT-MIPS */ #include "../kernel.h" // Catch2 #include <catch.hpp> TEST_CASE( "Kernel: Execute nothing") { CHECK( Kernel::create_dummy_kernel()->execute() == Trap::SYSCALL); CHECK( Kernel::create_configured_kernel()->execute() == Trap::SYSCALL); }
/** * Unit tests for base kernel class * @author Vyacheslav Kompan kompan.vo@phystech.edu * Copyright 2018 MIPT-MIPS */ #include "../kernel.h" #include <catch.hpp> TEST_CASE( "Kernel: Execute nothing") { CHECK( Kernel::create_dummy_kernel()->execute() == Trap::SYSCALL); CHECK( Kernel::create_configured_kernel()->execute() == Trap::SYSCALL); CHECK_NOTHROW( Kernel::create_dummy_kernel()->set_simulator( nullptr)); CHECK_NOTHROW( Kernel::create_dummy_kernel()->connect_memory( nullptr)); CHECK_NOTHROW( Kernel::create_dummy_kernel()->add_replica_simulator( nullptr)); CHECK_NOTHROW( Kernel::create_dummy_kernel()->add_replica_memory( nullptr)); }
Use top-level must<> instead of seq<>
// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #include <string> #include <iostream> #include <pegtl.hh> namespace hello { struct prefix : pegtl::string< 'H', 'e', 'l', 'l', 'o', ',', ' ' > {}; struct name : pegtl::plus< pegtl::alpha > {}; struct grammar : pegtl::seq< prefix, name, pegtl::one< '!' >, pegtl::eof > {}; template< typename Rule > struct action : pegtl::nothing< Rule > {}; template<> struct action< name > { static void apply( const pegtl::input & in, std::string & name ) { name = in.string(); } }; } int main( int argc, char * argv[] ) { if ( argc > 1 ) { std::string name; pegtl::parse< hello::grammar, hello::action >( 1, argv, name ); std::cout << "Good bye, " << name << "!" << std::endl; } }
// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #include <string> #include <iostream> #include <pegtl.hh> namespace hello { struct prefix : pegtl::string< 'H', 'e', 'l', 'l', 'o', ',', ' ' > {}; struct name : pegtl::plus< pegtl::alpha > {}; struct grammar : pegtl::must< prefix, name, pegtl::one< '!' >, pegtl::eof > {}; template< typename Rule > struct action : pegtl::nothing< Rule > {}; template<> struct action< name > { static void apply( const pegtl::input & in, std::string & name ) { name = in.string(); } }; } int main( int argc, char * argv[] ) { if ( argc > 1 ) { std::string name; pegtl::parse< hello::grammar, hello::action >( 1, argv, name ); std::cout << "Good bye, " << name << "!" << std::endl; } }
Test normal interpolation for triangle.
#include "helper.h" #include "../lib/triangle.h" #include <catch.hpp> TEST_CASE("Test Triangle normal", "[triangle]") { static constexpr int NUM_SAMPLES = 100; for (int j = 0; j < NUM_SAMPLES; ++j) { Triangle triangle = random_triangle(); Vec normal = triangle.normal; // Verify unit lenght of normal. float length = normal.Length(); REQUIRE(length == Approx(1.f)); // Verify normal is perpendicular to edges of triangle. float cos_u = normal * triangle.u.Normalize(); float cos_v = normal * triangle.v.Normalize(); REQUIRE(cos_u == Approx(0.f)); REQUIRE(cos_v == Approx(0.f)); } }
#include "helper.h" #include "../lib/triangle.h" #include <catch.hpp> TEST_CASE("Test Triangle normal", "[triangle]") { static constexpr int NUM_SAMPLES = 100; for (int j = 0; j < NUM_SAMPLES; ++j) { Triangle triangle = random_triangle(); Vec normal = triangle.normal; // Verify unit length of normal. float length = normal.Length(); REQUIRE(length == Approx(1.f)); // Verify normal is perpendicular to edges of triangle. float cos_u = normal * triangle.u.Normalize(); float cos_v = normal * triangle.v.Normalize(); REQUIRE(cos_u == Approx(0.f)); REQUIRE(cos_v == Approx(0.f)); } } TEST_CASE("Test interpolate triangle normal", "[triangle]") { static constexpr int NUM_SAMPLES = 100; for (int j = 0; j < NUM_SAMPLES; ++j) { Triangle triangle = test_triangle( random_vec(), random_vec(), random_vec(), random_vec().Normalize(), random_vec().Normalize(), random_vec().Normalize()); float r = uniform(); float s = uniform(); float t = uniform(); while( r+s+t > 1.0f) { r = uniform(); s = uniform(); t = uniform(); } Vec normal = triangle.interpolate_normal(r, s, t); // Verify unit length of normal. float length = normal.Length(); REQUIRE(length == Approx(1.f)); } }
Add tests to check Device is POD
#include "xchainer/device.h" #include <future> #include <gtest/gtest.h> #include "xchainer/error.h" namespace xchainer { TEST(DeviceTest, SetCurrentDevice) { Device cpu = {"cpu"}; Device cuda = {"cuda"}; auto device = GetCurrentDevice(); SetCurrentDevice("cpu"); ASSERT_EQ(cpu, GetCurrentDevice()); SetCurrentDevice(cuda); ASSERT_EQ(cuda, GetCurrentDevice()); ASSERT_THROW(SetCurrentDevice("invalid_device"), DeviceError); SetCurrentDevice(device); } TEST(DeviceTest, ThreadLocal) { auto device = GetCurrentDevice(); SetCurrentDevice("cpu"); auto future = std::async(std::launch::async, [] { SetCurrentDevice("cuda"); return GetCurrentDevice(); }); ASSERT_NE(GetCurrentDevice(), future.get()); SetCurrentDevice(device); } } // namespace
#include "xchainer/device.h" #include <future> #include <gtest/gtest.h> #include "xchainer/error.h" namespace xchainer { // Device must be POD (plain old data) to be used as a thread local variable safely. // ref. https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables static_assert(std::is_pod<Device>::value, "Device must be POD"); TEST(DeviceTest, SetCurrentDevice) { Device cpu = {"cpu"}; Device cuda = {"cuda"}; auto device = GetCurrentDevice(); SetCurrentDevice("cpu"); ASSERT_EQ(cpu, GetCurrentDevice()); SetCurrentDevice(cuda); ASSERT_EQ(cuda, GetCurrentDevice()); ASSERT_THROW(SetCurrentDevice("invalid_device"), DeviceError); SetCurrentDevice(device); } TEST(DeviceTest, ThreadLocal) { auto device = GetCurrentDevice(); SetCurrentDevice("cpu"); auto future = std::async(std::launch::async, [] { SetCurrentDevice("cuda"); return GetCurrentDevice(); }); ASSERT_NE(GetCurrentDevice(), future.get()); SetCurrentDevice(device); } } // namespace
Fix undefined assignment evaluation order in remoting::Capturer::FinishCapture.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer.h" namespace remoting { Capturer::Capturer() : width_(0), height_(0), pixel_format_(PixelFormatInvalid), bytes_per_pixel_(0), bytes_per_row_(0), current_buffer_(0) { } Capturer::~Capturer() { } void Capturer::GetDirtyRects(DirtyRects* rects) const { *rects = dirty_rects_; } int Capturer::GetWidth() const { return width_; } int Capturer::GetHeight() const { return height_; } PixelFormat Capturer::GetPixelFormat() const { return pixel_format_; } void Capturer::InvalidateRect(gfx::Rect dirty_rect) { inval_rects_.push_back(dirty_rect); } void Capturer::FinishCapture(Task* done_task) { done_task->Run(); delete done_task; // Select the next buffer to be the current buffer. current_buffer_ = ++current_buffer_ % kNumBuffers; } } // namespace remoting
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer.h" namespace remoting { Capturer::Capturer() : width_(0), height_(0), pixel_format_(PixelFormatInvalid), bytes_per_pixel_(0), bytes_per_row_(0), current_buffer_(0) { } Capturer::~Capturer() { } void Capturer::GetDirtyRects(DirtyRects* rects) const { *rects = dirty_rects_; } int Capturer::GetWidth() const { return width_; } int Capturer::GetHeight() const { return height_; } PixelFormat Capturer::GetPixelFormat() const { return pixel_format_; } void Capturer::InvalidateRect(gfx::Rect dirty_rect) { inval_rects_.push_back(dirty_rect); } void Capturer::FinishCapture(Task* done_task) { done_task->Run(); delete done_task; // Select the next buffer to be the current buffer. current_buffer_ = (current_buffer_ + 1) % kNumBuffers; } } // namespace remoting
Set ADC control registers in constructor
#include <avr/io.h> #include <avr/interrupt.h> #include "AnalogAccel.h" volatile Axis currentAxis = X; ISR(ANALOG_COMP_vect) //To be executed once analog compare is completed { //Do stuff... } AnalogAccel::AnalogAccel() { } AnalogAccel::~AnalogAccel() { } volatile Axis& AnalogAccel::currentAxis_ = currentAxis;
#include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include "AnalogAccel.h" volatile Axis currentAxis = X; ISR(ANALOG_COMP_vect) //To be executed once analog compare is completed { //Do stuff... } AnalogAccel::AnalogAccel() { //Prescaler of 64 (12MHz / 64 == 187.5 kHz), //recommended value is 50-200kHz. Also: Enable interrupt, //enable auto-triggering, start conversion and turn the ADC on. ADCSRA |= _BV(ADPS1) | _BV(ADPS2) | _BV(ADIE) | _BV(ADATE) \ | _BV(ADSC) | _BV(ADEN); //Free-running mode: takes measurements as long as the ADC is enabled ADCSRB = 0; //Disable digital input buffers for those pins (saves power) DIDR0 |= _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D); } AnalogAccel::~AnalogAccel() { ADCSRA &= ~_BV(ADEN); //Disable the ADC (also disables the interrupt) } volatile Axis& AnalogAccel::currentAxis_ = currentAxis;
Fix a lolbug, it never worked and returned true always.
/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <cstring> #include <qitype/signature.hpp> namespace qi { bool qi::Signature::isConvertibleTo(const qi::Signature& b) const { if (size() != b.size()) return false; static const char numeric[] = "bcCwWiIlLfd"; static const char container[] = "[{"; Signature::iterator s = begin(); Signature::iterator d = b.begin(); for (;s!=end() && d!= b.end(); ++s,++d) { if (d.type() == Type_Dynamic) continue; // Dynamic can convert to whatever // Main switch on source sig if (strchr(numeric, s.type())) { // Numeric if (!strchr(numeric, d.type())) return false; } else if (strchr(container, s.type())) { // Container, list or map if (d.type() != s.type()) return false; // Must be same container if (!s.children().isConvertibleTo(d.children())) return false; // Just check subtype compatibility } else if (d.type() != s.type()) return false; } assert(s==end() && d==b.end()); // we allready exited on size mismatch return true; } Signature Signature::fromType(Signature::Type t) { char res[2] = { (char)t, 0}; return Signature(res); } }
/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <cstring> #include <qitype/signature.hpp> namespace qi { bool qi::Signature::isConvertibleTo(const qi::Signature& b) const { if (size() != b.size()) return false; static const char numeric[] = "bcCwWiIlLfd"; static const char container[] = "[{("; Signature::iterator s = begin(); Signature::iterator d = b.begin(); for (;s!=end() && d!= b.end(); ++s,++d) { if (d.type() == Type_Dynamic) continue; // Dynamic can convert to whatever // Main switch on source sig if (strchr(numeric, s.type())) { // Numeric if (!strchr(numeric, d.type())) return false; } else if (strchr(container, s.type())) { // Container, list or map if (d.type() != s.type()) return false; // Must be same container if (!s.children().isConvertibleTo(d.children())) return false; // Just check subtype compatibility } else if (d.type() != s.type()) return false; } assert(s==end() && d==b.end()); // we allready exited on size mismatch return true; } Signature Signature::fromType(Signature::Type t) { char res[2] = { (char)t, 0}; return Signature(res); } }
Add json parsing to modem streaming
#include "modem/commands.h" namespace firebase { namespace modem { bool StreamCommand::execute(const String& command, InputStream* in, OutputStream* out) { if (in == nullptr || out == nullptr) { return false; } if (command != "BEGIN_STREAM") { return false; } std::string path = in->readLine().c_str(); std::unique_ptr<FirebaseStream> stream(fbase().streamPtr(path)); if (stream->error()) { out->print("-FAIL "); out->println(stream->error().message().c_str()); return false; } bool running = true; while(running) { if (stream->available()) { std::string json; FirebaseStream::Event event = stream->read(json); out->print("+"); out->print(FirebaseStream::EventToName(event).c_str()); out->print(" "); // TODO(edcoyne): add json parsing and get real path. out->println("/dummy/path"); out->println(json.length()); out->println(json.c_str()); } else if (in->available()) { String command = in->readLine(); if (command == "END_STREAM") { out->println("+OK"); running = false; } else { out->println("-FAIL Cannot call any command but END_STREAM."); } } } return true; } } // modem } // firebase
#include "modem/commands.h" namespace firebase { namespace modem { bool StreamCommand::execute(const String& command, InputStream* in, OutputStream* out) { if (in == nullptr || out == nullptr) { return false; } if (command != "BEGIN_STREAM") { return false; } std::string path = in->readLine().c_str(); std::unique_ptr<FirebaseStream> stream(fbase().streamPtr(path)); if (stream->error()) { out->print("-FAIL "); out->println(stream->error().message().c_str()); return false; } bool running = true; DynamicJsonBuffer buffer; while(running) { if (stream->available()) { std::string json; FirebaseStream::Event event = stream->read(json); out->print("+"); out->print(FirebaseStream::EventToName(event).c_str()); out->print(" "); const auto& object = buffer.parseObject(json.c_str()); String data = object["data"]; out->println(object["path"].asString()); out->println(data.length()); out->println(data); } else if (in->available()) { String command = in->readLine(); if (command == "END_STREAM") { out->println("+OK"); running = false; } else { out->println("-FAIL Cannot call any command but END_STREAM."); } } } return true; } } // modem } // firebase
Add an error code with sendFail
#include "helpers.h" using namespace std; void sendFail(UserHandler * handler, int errorcode, string topic, string message){ JsonDict answer; JsonBool b = JsonBool(false); JsonString s = JsonString(message); answer.add("success", &b); answer.add("reason", &s); handler->writeToClient(topic, &answer); }
#include "helpers.h" using namespace std; void sendFail(UserHandler * handler, int errorcode, string topic, string message){ JsonDict answer; JsonBool b = JsonBool(false); JsonString s = JsonString(message); JsonInt i = JsonInt(errorcode); answer.add("success", &b); answer.add("reason", &s); answer.add("code", &i); handler->writeToClient(topic, &answer); }
Add the current directory to the path.
#include "python_script.h" #include <cstdio> #include <fstream> #include <iterator> #include <boost/log/trivial.hpp> #include <boost/python.hpp> #include <Python.h> using namespace boost::python; using namespace std; using namespace swganh::scripting; PythonScript::PythonScript(const string& filename) : filename_(filename) { ReadFileContents(); Py_Initialize(); try { boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed( PyImport_AddModule("__main__") ))); globals_ = main.attr("__dict__"); globals_["swganh"] = boost::python::import("py_swganh"); globals_["context"] = dict(); } catch (error_already_set &) { PyErr_Print(); } } void PythonScript::Run() { try { #ifdef _DEBUG ReadFileContents(); #endif file_object_ = exec(filecontents_.c_str(), globals_, globals_); } catch (error_already_set &) { PyErr_Print(); } } void PythonScript::ReadFileContents() { ifstream filestream(filename_); filestream >> noskipws; filecontents_ = string( (istreambuf_iterator<char>(filestream)), istreambuf_iterator<char>()); }
#include "python_script.h" #include <cstdio> #include <fstream> #include <iterator> #include <boost/log/trivial.hpp> #include <boost/python.hpp> #include <Python.h> using namespace boost::python; using namespace std; using namespace swganh::scripting; PythonScript::PythonScript(const string& filename) : filename_(filename) { ReadFileContents(); Py_Initialize(); try { PyRun_SimpleString("import sys; sys.path.append('.');"); boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed( PyImport_AddModule("__main__") ))); globals_ = main.attr("__dict__"); globals_["swganh"] = boost::python::import("py_swganh"); globals_["context"] = dict(); } catch (error_already_set &) { PyErr_Print(); } } void PythonScript::Run() { try { #ifdef _DEBUG ReadFileContents(); #endif BOOST_LOG_TRIVIAL(info) << "Executing script: " << filename_; file_object_ = exec(filecontents_.c_str(), globals_, globals_); } catch (error_already_set &) { PyErr_Print(); } } void PythonScript::ReadFileContents() { ifstream filestream(filename_); filestream >> noskipws; filecontents_ = string( (istreambuf_iterator<char>(filestream)), istreambuf_iterator<char>()); }
Add method to determine if the given prop page should save the settings
#include "UIUtils.h" #include <sstream> #include "Settings.h" std::vector<CPropertyPage *> UIUtils::pages = { }; CString UIUtils::Capitalize(std::wstring in) { CString cstr(in.c_str()); return UIUtils::Capitalize(cstr); } CString UIUtils::Capitalize(CString in) { CString newString(in); CString firstLetter = newString.Left(1).MakeUpper(); newString = firstLetter + newString.Mid(1); return newString; } int UIUtils::TextToInt(CWnd &wnd) { int num; CString text; wnd.GetWindowTextW(text); std::wistringstream wistr((LPCWSTR) text); wistr >> num; return num; }
#include "UIUtils.h" #include <sstream> #include "Settings.h" std::vector<CPropertyPage *> UIUtils::pages = { }; CString UIUtils::Capitalize(std::wstring in) { CString cstr(in.c_str()); return UIUtils::Capitalize(cstr); } CString UIUtils::Capitalize(CString in) { CString newString(in); CString firstLetter = newString.Left(1).MakeUpper(); newString = firstLetter + newString.Mid(1); return newString; } int UIUtils::TextToInt(CWnd &wnd) { int num; CString text; wnd.GetWindowTextW(text); std::wistringstream wistr((LPCWSTR) text); wistr >> num; return num; } void UIUtils::SaveSettings(CPropertyPage &page) { HWND hWnd = NULL; for (CPropertyPage *page : pages) { HWND test = page->m_hWnd; if (IsWindow(test)) { hWnd = test; } } if (hWnd == page.m_hWnd) { OutputDebugString(L"Saving Settings XML\n"); Settings::Instance()->Save(); } }
Move a warning comment to where it should have been in the first place.
//===- llvm/System/AIX/Path.cpp - AIX Path Implementation -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides the AIX specific implementation of the Path class. // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only AIX specific code //=== and must not be generic UNIX code (see ../Unix/Path.cpp) //===----------------------------------------------------------------------===// // Include the generic unix implementation #include "../Unix/Path.cpp" namespace llvm { using namespace sys; bool Path::is_valid() const { if (path.empty()) return false; if (path.length() >= MAXPATHLEN) return false; return true; } } // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
//===- llvm/System/AIX/Path.cpp - AIX Path Implementation -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides the AIX specific implementation of the Path class. // //===----------------------------------------------------------------------===// // Include the generic unix implementation #include "../Unix/Path.cpp" namespace llvm { using namespace sys; //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only AIX specific code //=== and must not be generic UNIX code (see ../Unix/Path.cpp) //===----------------------------------------------------------------------===// bool Path::is_valid() const { if (path.empty()) return false; if (path.length() >= MAXPATHLEN) return false; return true; } } // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
Fix ubuntu build fail tuple init list
#include "s3d/cv/image_operation/input_output_adapter.h" #include "s3d/cv/image_operation/image_operations.h" namespace s3d { namespace image_operation { InputOutputAdapter::InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations) : operations_{imageOperations} {} void InputOutputAdapter::setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage) { inputLeftImage = leftImage.clone(); inputRightImage = rightImage.clone(); } std::tuple<cv::Mat&, cv::Mat&> InputOutputAdapter::getOutputImages() { return { outputLeftImage, outputRightImage }; }; bool InputOutputAdapter::applyAllOperations() { copyInputToOutputs(); if (!canApplyOperations()) { return false; } return operations_->applyAll(&outputLeftImage, &outputRightImage); } void InputOutputAdapter::copyInputToOutputs() { outputLeftImage = inputLeftImage.clone(); outputRightImage = inputRightImage.clone(); } bool InputOutputAdapter::canApplyOperations() { return !inputLeftImage.empty() && !inputRightImage.empty(); } } // namespace s3d } // namespace image_operation
#include "s3d/cv/image_operation/input_output_adapter.h" #include "s3d/cv/image_operation/image_operations.h" namespace s3d { namespace image_operation { InputOutputAdapter::InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations) : operations_{imageOperations} {} void InputOutputAdapter::setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage) { inputLeftImage = leftImage.clone(); inputRightImage = rightImage.clone(); } std::tuple<cv::Mat&, cv::Mat&> InputOutputAdapter::getOutputImages() { return std::tuple<cv::Mat&, cv::Mat&>(outputLeftImage, outputRightImage); }; bool InputOutputAdapter::applyAllOperations() { copyInputToOutputs(); if (!canApplyOperations()) { return false; } return operations_->applyAll(&outputLeftImage, &outputRightImage); } void InputOutputAdapter::copyInputToOutputs() { outputLeftImage = inputLeftImage.clone(); outputRightImage = inputRightImage.clone(); } bool InputOutputAdapter::canApplyOperations() { return !inputLeftImage.empty() && !inputRightImage.empty(); } } // namespace s3d } // namespace image_operation
Check for opencv version before using SuperpixelLSC/SLIC
#ifdef HAVE_XIMGPROC #include "ximgproc.h" #include "SuperpixelSEEDS.h" #include "SuperpixelSLIC.h" #include "SuperpixelLSC.h" NAN_MODULE_INIT(XImgproc::Init) { SuperpixelSEEDS::Init(target); SuperpixelSLIC::Init(target); SuperpixelLSC::Init(target); } #endif // HAVE_XIMGPROC
#ifdef HAVE_XIMGPROC #include "ximgproc.h" #include "SuperpixelSEEDS.h" #include "SuperpixelSLIC.h" #include "SuperpixelLSC.h" NAN_MODULE_INIT(XImgproc::Init) { SuperpixelSEEDS::Init(target); #if OPENCV_MINOR_VERSION > 0 SuperpixelSLIC::Init(target); SuperpixelLSC::Init(target); #endif } #endif // HAVE_XIMGPROC
Allow dot and slash as message identifier
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // #include "input_sanitizer.h" #include <regex> namespace influxdb { namespace utility { constexpr const char* regex = R"((^[a-zA-Z0-9_\-]+$|"(?:[^\\"]|\\.)+"))"; const std::regex check_identifier(regex); bool valid_identifier(std::string const & input) { return std::regex_match(input, check_identifier); } void throw_on_invalid_identifier(std::string const & input) { if (!valid_identifier(input)) throw std::runtime_error(std::string("Invalid identifier: ") + input); } } }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // #include "input_sanitizer.h" #include <regex> namespace influxdb { namespace utility { constexpr const char* regex = R"((^[a-zA-Z0-9_/\\.\-]+$|"(?:[^\\"]|\\.)+"))"; const std::regex check_identifier(regex); bool valid_identifier(std::string const & input) { return std::regex_match(input, check_identifier); } void throw_on_invalid_identifier(std::string const & input) { if (!valid_identifier(input)) throw std::runtime_error(std::string("Invalid identifier: ") + input); } } }
Add ros console logging, implement params for ROS properties
#include "ros/ros.h" #include "std_msgs/String.h" #include "geometry_msgs/Twist.h" int main(int argc, char **argv) { ros::init(argc, argv, "publish_fromfile"); ros::NodeHandle pubFromFileHandle; ros::Publisher pubFromFileObj = pubFromFileHandle.advertise<geometry_msgs::Twist>("publish_fromfile",100); /*! * TODO: make this configurable by command line arg */ ros::Rate sendRate(10); while(ros::ok()) { geometry_msgs::Twist currentOutputMsg; currentOutputMsg.linear.x=0.0; currentOutputMsg.angular.z=0.0; pubFromFileObj.publish(currentOutputMsg); ros::spinOnce(); sendRate.sleep(); } return 0; }
// ROS includes #include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "ros/console.h" #include "std_msgs/String.h" // misc includes #include "yaml-cpp/yaml.h" int main(int argc, char **argv) { // local variables for configurable params double rate_param; int msg_buffer_len=100; std::string topic_name("publish_fromfile"); std::string input_file; // TODO: implement // local variables for local scope use const std::string node_name("publish_fromfile"); // initialize ROS ros::init(argc, argv, node_name); // make sure to create the node handle with the node_name used to initialize // (so that param relative scope works) ros::NodeHandle pubFromFileHandle(node_name); pubFromFileHandle.param("rate",rate_param,1.0); ROS_INFO_STREAM("/" << node_name << "/rate value set " << rate_param); pubFromFileHandle.param<std::string>("topic_name",topic_name,"publish_fromfile"); ROS_INFO_STREAM("/" << node_name << "/topic_name value set " << topic_name); pubFromFileHandle.param("msg_buffer_len",msg_buffer_len,msg_buffer_len); ROS_INFO_STREAM("/" << node_name << "/msg_buffer_len value set " << msg_buffer_len); ros::Publisher pubFromFileObj = pubFromFileHandle.advertise<geometry_msgs::Twist>(topic_name,msg_buffer_len); ros::Rate sendRate(rate_param); while(ros::ok()) { geometry_msgs::Twist currentOutputMsg; currentOutputMsg.linear.x=0.0; currentOutputMsg.angular.z=0.0; pubFromFileObj.publish(currentOutputMsg); ros::spinOnce(); sendRate.sleep(); } return 0; }
Revert "GEODE-5968: move protocol to the last release of Geode"
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "Version.hpp" #include "CacheImpl.hpp" namespace apache { namespace geode { namespace client { int8_t Version::m_ordinal = 90; // Geode 1.7.0 } // namespace client } // namespace geode } // namespace apache
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "Version.hpp" #include "CacheImpl.hpp" namespace apache { namespace geode { namespace client { int8_t Version::m_ordinal = 45; // Geode 1.0.0 } // namespace client } // namespace geode } // namespace apache
Fix deletion of Mentats in MentatFactory
/** Responsible for creating and destroying the mentat reference */ #include "d2tmh.h" cMentatFactory::cMentatFactory() { type = -1; } void cMentatFactory::deleteCurrent() { switch (type) { case ATREIDES: delete (cAtreidesMentat *)Mentat; break; case HARKONNEN: delete (cAtreidesMentat *)Mentat; break; case ORDOS: delete (cAtreidesMentat *)Mentat; break; case BENEGES: delete (cAtreidesMentat *)Mentat; break; } } void cMentatFactory::create(int mentatType) { if (type > -1) { if (mentatType != type) { deleteCurrent(); } } /** It is safe to create a new Mentat now **/ switch (mentatType) { case ATREIDES: Mentat = new cAtreidesMentat; break; case HARKONNEN: Mentat = new cHarkonnenMentat; break; case ORDOS: Mentat = new cOrdosMentat; break; case BENEGES: Mentat = new cBenegesMentat; break; } type = mentatType; }
/** Responsible for creating and destroying the mentat reference */ #include "d2tmh.h" cMentatFactory::cMentatFactory() { type = -1; } void cMentatFactory::deleteCurrent() { switch (type) { case ATREIDES: delete (cAtreidesMentat *)Mentat; break; case HARKONNEN: delete (cHarkonnenMentat *)Mentat; break; case ORDOS: delete (cOrdosMentat *)Mentat; break; case BENEGES: delete (cBenegesMentat *)Mentat; break; } } void cMentatFactory::create(int mentatType) { if (type > -1) { if (mentatType != type) { deleteCurrent(); } } /** It is safe to create a new Mentat now **/ switch (mentatType) { case ATREIDES: Mentat = new cAtreidesMentat; break; case HARKONNEN: Mentat = new cHarkonnenMentat; break; case ORDOS: Mentat = new cOrdosMentat; break; case BENEGES: Mentat = new cBenegesMentat; break; } type = mentatType; }
Update the path of header file to avoid a compiling error in chrome
// Copyright 2015 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/embedder_test.h" #include "testing/gtest/include/gtest/gtest.h" class FPDFParserEmbeddertest : public EmbedderTest { }; TEST_F(FPDFParserEmbeddertest, LoadError_454695) { // Test trailer dictionary with $$ze instead of Size. EXPECT_TRUE(OpenDocument("testing/resources/bug_454695.pdf")); }
// Copyright 2015 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "../../../testing/embedder_test.h" #include "testing/gtest/include/gtest/gtest.h" class FPDFParserEmbeddertest : public EmbedderTest { }; TEST_F(FPDFParserEmbeddertest, LoadError_454695) { // Test trailer dictionary with $$ze instead of Size. EXPECT_TRUE(OpenDocument("testing/resources/bug_454695.pdf")); }
Set active_dialog_ before showing it, since showing a dialog can sometimes actually move to the next one in the queue instead.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/app_modal_dialog_queue.h" #include "chrome/browser/browser_list.h" void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) { if (!active_dialog_) { ShowModalDialog(dialog); return; } app_modal_dialog_queue_.push(dialog); } void AppModalDialogQueue::ShowNextDialog() { if (!app_modal_dialog_queue_.empty()) { AppModalDialog* dialog = app_modal_dialog_queue_.front(); app_modal_dialog_queue_.pop(); ShowModalDialog(dialog); } else { active_dialog_ = NULL; } } void AppModalDialogQueue::ActivateModalDialog() { if (active_dialog_) active_dialog_->ActivateModalDialog(); } void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) { dialog->ShowModalDialog(); active_dialog_ = dialog; }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/app_modal_dialog_queue.h" #include "chrome/browser/browser_list.h" void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) { if (!active_dialog_) { ShowModalDialog(dialog); return; } app_modal_dialog_queue_.push(dialog); } void AppModalDialogQueue::ShowNextDialog() { if (!app_modal_dialog_queue_.empty()) { AppModalDialog* dialog = app_modal_dialog_queue_.front(); app_modal_dialog_queue_.pop(); ShowModalDialog(dialog); } else { active_dialog_ = NULL; } } void AppModalDialogQueue::ActivateModalDialog() { if (active_dialog_) active_dialog_->ActivateModalDialog(); } void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) { // Set active_dialog_ before showing it, because ShowModalDialog can wind up // calling ShowNextDialog in some cases, which will change active_dialog_. active_dialog_ = dialog; dialog->ShowModalDialog(); }
Set order of Autonomous Commands in CommandGroup
#include "AutonomousCommandGroup.h" #include "../RobotMap.h" AutonomousCommandGroup::AutonomousCommandGroup() { }
#include "AutonomousCommandGroup.h" #include "RaiseContainer.h" #include "DownContainer.h" #include "RaiseTrash.h" #include "DownTrash.h" #include "MoveContainer.h" #include "../RobotMap.h" AutonomousCommandGroup::AutonomousCommandGroup() { AddSequential(new RaiseTrash()); AddSequential(new DownTrash()); AddSequential(new RaiseContainer()); AddSequential(new MoveContainer()); AddSequential(new DownContainer()); }
Add large sbrk support for 32 bit platforms.
// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved. // Please see the AUTHORS file for details. Use of this source code is governed // by a BSD license that can be found in the LICENSE file. #include "allocators/global_sbrk_allocator.h" #include <sys/mman.h> // mmap #include "log.h" uintptr_t GlobalSbrkAllocator::current_; void GlobalSbrkAllocator::InitModule() { size_t size = 1UL << 35; // 32GiB void* p = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (p == MAP_FAILED) { ErrorOut("mmap failed"); } current_ = reinterpret_cast<uintptr_t>(p); }
// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved. // Please see the AUTHORS file for details. Use of this source code is governed // by a BSD license that can be found in the LICENSE file. #include "allocators/global_sbrk_allocator.h" #include <sys/mman.h> // mmap #include "log.h" uintptr_t GlobalSbrkAllocator::current_; void GlobalSbrkAllocator::InitModule() { #ifdef __x86_64__ size_t size = 1UL << 35; // 32GiB #endif #ifdef __i386__ size_t size = 1UL << 31; #endif void* p = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (p == MAP_FAILED) { ErrorOut("mmap failed"); } current_ = reinterpret_cast<uintptr_t>(p); }
Use atomic to avoid racy version string initialization
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/version.h" #include "vm/cpu.h" #include "vm/os.h" namespace dart { // TODO(iposva): Avoid racy initialization. static const char* formatted_version = NULL; const char* Version::String() { if (formatted_version == NULL) { const char* os = OS::Name(); const char* arch = CPU::Id(); formatted_version = OS::SCreate(NULL, "%s on \"%s_%s\"", str_, os, arch); } return formatted_version; } const char* Version::SnapshotString() { return snapshot_hash_; } const char* Version::CommitString() { return commit_; } const char* Version::SdkHash() { return git_short_hash_; } const char* Version::snapshot_hash_ = "{{SNAPSHOT_HASH}}"; const char* Version::str_ = "{{VERSION_STR}} ({{CHANNEL}}) ({{COMMIT_TIME}})"; const char* Version::commit_ = "{{VERSION_STR}}"; const char* Version::git_short_hash_ = "{{GIT_HASH}}"; } // namespace dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/atomic.h" #include "vm/cpu.h" #include "vm/os.h" #include "vm/version.h" namespace dart { // We use require-release semantics to ensure initializing stores to the string // are visible when the string becomes visible. static AcqRelAtomic<const char*> formatted_version = nullptr; const char* Version::String() { if (formatted_version.load() == nullptr) { const char* os = OS::Name(); const char* arch = CPU::Id(); char* version_string = OS::SCreate(nullptr, "%s on \"%s_%s\"", str_, os, arch); const char* expect_old_is_null = nullptr; if (!formatted_version.compare_exchange_strong(expect_old_is_null, version_string)) { free(version_string); } } return formatted_version.load(); } const char* Version::SnapshotString() { return snapshot_hash_; } const char* Version::CommitString() { return commit_; } const char* Version::SdkHash() { return git_short_hash_; } const char* Version::snapshot_hash_ = "{{SNAPSHOT_HASH}}"; const char* Version::str_ = "{{VERSION_STR}} ({{CHANNEL}}) ({{COMMIT_TIME}})"; const char* Version::commit_ = "{{VERSION_STR}}"; const char* Version::git_short_hash_ = "{{GIT_HASH}}"; } // namespace dart
Revert "Prevent DCE on __lsan_is_turned_off and re-enable test case"
// Test for disabling LSan at link-time. // RUN: LSAN_BASE="use_stacks=0:use_registers=0" // RUN: %clangxx_lsan %s -o %t // RUN: %env_lsan_opts=$LSAN_BASE %run %t // RUN: %env_lsan_opts=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s #include <sanitizer/lsan_interface.h> int argc_copy; extern "C" { int __attribute__((used)) __lsan_is_turned_off() { return (argc_copy == 1); } } int main(int argc, char *argv[]) { volatile int *x = new int; *x = 42; argc_copy = argc; return 0; } // CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 4 byte(s) leaked in 1 allocation(s)
// Test for disabling LSan at link-time. // RUN: LSAN_BASE="use_stacks=0:use_registers=0" // RUN: %clangxx_lsan %s -o %t // RUN: %env_lsan_opts=$LSAN_BASE %run %t // RUN: %env_lsan_opts=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s // // UNSUPPORTED: darwin #include <sanitizer/lsan_interface.h> int argc_copy; extern "C" { int __attribute__((used)) __lsan_is_turned_off() { return (argc_copy == 1); } } int main(int argc, char *argv[]) { volatile int *x = new int; *x = 42; argc_copy = argc; return 0; } // CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 4 byte(s) leaked in 1 allocation(s)
Update to use new DAL feature where stack is not paged.
#include "MicroBit.h" extern "C" { void mp_run(void); void microbit_display_event(void); } static void event_listener(MicroBitEvent evt) { if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) { microbit_display_event(); } } void app_main() { /* // debugging: print memory layout extern uint32_t __data_start__, __data_end__; extern uint32_t __bss_start__, __bss_end__; extern uint32_t __HeapLimit, __StackLimit, __StackTop; printf("__data_start__ = %p\r\n", &__data_start__); printf("__data_end__ = %p\r\n", &__data_end__); printf("__bss_start_ _ = %p\r\n", &__bss_start__); printf("__bss_end__ = %p\r\n", &__bss_end__); printf("__HeapLimit = %p\r\n", &__HeapLimit); printf("__StackLimit = %p\r\n", &__StackLimit); printf("__StackTop = %p\r\n", &__StackTop); */ uBit.MessageBus.listen(MICROBIT_ID_DISPLAY, MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener); while (1) { mp_run(); } }
#include "MicroBit.h" extern "C" { void mp_run(void); void microbit_display_event(void); } static void event_listener(MicroBitEvent evt) { if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) { microbit_display_event(); } } void app_main() { /* // debugging: print memory layout extern uint32_t __data_start__, __data_end__; extern uint32_t __bss_start__, __bss_end__; extern uint32_t __HeapLimit, __StackLimit, __StackTop; printf("__data_start__ = %p\r\n", &__data_start__); printf("__data_end__ = %p\r\n", &__data_end__); printf("__bss_start_ _ = %p\r\n", &__bss_start__); printf("__bss_end__ = %p\r\n", &__bss_end__); printf("__HeapLimit = %p\r\n", &__HeapLimit); printf("__StackLimit = %p\r\n", &__StackLimit); printf("__StackTop = %p\r\n", &__StackTop); */ currentFiber->flags |= MICROBIT_FIBER_FLAG_DO_NOT_PAGE; uBit.MessageBus.listen(MICROBIT_ID_DISPLAY, MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener, MESSAGE_BUS_LISTENER_REENTRANT | MESSAGE_BUS_LISTENER_NONBLOCKING); while (1) { mp_run(); } }
Fix compile errors on win32, update Qt submodule to fix compile errors there
#include <bts/blockchain/address.hpp> #include <bts/blockchain/pts_address.hpp> #include <bts/blockchain/types.hpp> #include <bts/utilities/key_conversion.hpp> #include <fc/crypto/elliptic.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/filesystem.hpp> #include <fc/variant_object.hpp> #include <fc/exception/exception.hpp> #include <iostream> using namespace bts::blockchain; int main( int argc, char** argv ) { if( argc == 2 ) { fc::ecc::private_key k; try{ auto key = bts::blockchain::public_key_type(std::string(argv[1])); auto obj = fc::mutable_variant_object(); obj["public_key"] = public_key_type(key); obj["native_address"] = bts::blockchain::address(key); obj["pts_address"] = bts::blockchain::pts_address(key); std::cout << fc::json::to_pretty_string(obj); return 0; } catch (fc::exception e) { std::cout << e.to_detail_string(); } } return -1; }
#include <bts/blockchain/address.hpp> #include <bts/blockchain/pts_address.hpp> #include <bts/blockchain/types.hpp> #include <bts/utilities/key_conversion.hpp> #include <fc/crypto/elliptic.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/filesystem.hpp> #include <fc/variant_object.hpp> #include <fc/exception/exception.hpp> #include <iostream> using namespace bts::blockchain; int main( int argc, char** argv ) { if( argc == 2 ) { try { bts::blockchain::public_key_type key(argv[1]); fc::mutable_variant_object obj; obj["public_key"] = key; obj["native_address"] = bts::blockchain::address((fc::ecc::public_key_data)key); obj["pts_address"] = bts::blockchain::pts_address((fc::ecc::public_key)key); std::cout << fc::json::to_pretty_string(obj); return 0; } catch (fc::exception e) { std::cout << e.to_detail_string(); } } return -1; }
Add complex support for tan
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/cwise_ops_common.h" namespace tensorflow { REGISTER2(UnaryOp, CPU, "Tan", functor::tan, float, double); #if GOOGLE_CUDA REGISTER2(UnaryOp, GPU, "Tan", functor::tan, float, double); #endif #ifdef TENSORFLOW_USE_SYCL REGISTER2(UnaryOp, SYCL, "Tan", functor::tan, float, double); #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/cwise_ops_common.h" namespace tensorflow { REGISTER4(UnaryOp, CPU, "Tan", functor::tan, float, double, complex64, complex128); #if GOOGLE_CUDA REGISTER2(UnaryOp, GPU, "Tan", functor::tan, float, double); #endif #ifdef TENSORFLOW_USE_SYCL REGISTER2(UnaryOp, SYCL, "Tan", functor::tan, float, double); #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow
Update documentation for main() in tester
#include <cstring> #include <iostream> #include <UnitTest++/UnitTest++.h> #include <UnitTest++/TestReporterStdout.h> using std::cerr; using std::endl; using std::strcmp; /* Function object returning true for a specified test name */ struct MatchTestName { const char * const tname; MatchTestName (const char* tn) : tname {tn} {}; bool operator () (const UnitTest::Test* const test) const { return strcmp(test->m_details.testName, tname) == 0; } }; /* Locate and run all tests */ int main(int argc, const char* argv[]) { if (argc < 2) return UnitTest::RunAllTests(); else if (argc >= 2){ UnitTest::TestReporterStdout reporter; UnitTest::TestRunner runner (reporter); if (argc == 2) return runner.RunTestsIf (UnitTest::Test::GetTestList(), argv[1], UnitTest::True(), 0); else if (argc == 3) return runner.RunTestsIf (UnitTest::Test::GetTestList(), argv[1], MatchTestName(argv[2]), 0); else cerr << "Usage: tester [suite [test]]" << endl; } }
#include <cstring> #include <iostream> #include <UnitTest++/UnitTest++.h> #include <UnitTest++/TestReporterStdout.h> using std::cerr; using std::endl; using std::strcmp; /* Function object returning true for a specified test name */ struct MatchTestName { const char * const tname; MatchTestName (const char* tn) : tname {tn} {}; bool operator () (const UnitTest::Test* const test) const { return strcmp(test->m_details.testName, tname) == 0; } }; /* Runs a specific suite/test if a suite, or a suite and a test, is provided, or all tests if none are provided. To execute, run ./tester [suite [test]] */ int main(int argc, const char* argv[]) { if (argc < 2) return UnitTest::RunAllTests(); else if (argc >= 2){ UnitTest::TestReporterStdout reporter; UnitTest::TestRunner runner (reporter); if (argc == 2) return runner.RunTestsIf (UnitTest::Test::GetTestList(), argv[1], UnitTest::True(), 0); else if (argc == 3) return runner.RunTestsIf (UnitTest::Test::GetTestList(), argv[1], MatchTestName(argv[2]), 0); else cerr << "Usage: ./tester [suite [test]]" << endl; } }
Use initializer syntax to satisfy clang
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "auto_id.h" using namespace autowiring; // Index that will be given to the next auto_id instance. Zero is reserved. static int s_index = 1; const auto_id_block auto_id_t<void>::s_block{ 0, &typeid(void), &typeid(s<void>), 0, 0, nullptr, nullptr }; const auto_id_t_init<void, true> auto_id_t_init<void, true>::init; const auto_id_t_init<void, false> auto_id_t_init<void, false>::init; int autowiring::CreateIndex(void) { return s_index++; } std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT { return nullptr; } std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT { return nullptr; }
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "auto_id.h" using namespace autowiring; // Index that will be given to the next auto_id instance. Zero is reserved. static int s_index = 1; const auto_id_block auto_id_t<void>::s_block{ 0, &typeid(void), &typeid(s<void>), 0, 0, nullptr, nullptr }; const auto_id_t_init<void, true> auto_id_t_init<void, true>::init{}; const auto_id_t_init<void, false> auto_id_t_init<void, false>::init{}; int autowiring::CreateIndex(void) { return s_index++; } std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT { return nullptr; } std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT { return nullptr; }
Add benchmark feature in main functin.
#include "comb.h" int main() { // for(int i=0;i<6;i++){ sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,16,50,600,15,0,0.001,"Gaussian"); sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,17,50,600,15,0,0.001,"Gaussian"); // } //gamma2(Hz),line width(GHz),sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune,A Factor // The last argument is the function type "Sinc" for Sinc Function other for Gaussian function //0.7*2*pi;//0.0052227*2*pi;// system("./mail.py"); return 0; }
#include "comb.h" #include <ctime> int main() { fstream file1; file1.open("./Data/result.txt",ios::out | ios::trunc); file1<<"Function\t"<<"Order\t"<<"Steps\t"<<endl; for(int i=1;i<6;i++){ for(int j=1;j<4;j++){ time_t T1 = clock(),T2; sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,12-i,10*j,600,15,0,0.001,"Gaussian"); T2 = clock(); file1<<"Gaussian\t"<<12-i<<"\t"<<10*j<<"\t"<<(T2-T1)<<endl; sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,12-i,10*j,600,15,0,0.001,"Sinc"); T1 = clock(); file1<<"sinc\t"<<12-i<<"\t"<<10*j<<"\t"<<(T1-T2)<<endl; } } //gamma2(Hz),line width(GHz),sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune,A Factor // The last argument is the function type "Sinc" for Sinc Function other for Gaussian function //0.7*2*pi;//0.0052227*2*pi;// system("./mail.py"); return 0; }
Make let_stuff_happen() wait longer under valgrind.
#include "mock/unittest_utils.hpp" #include <stdlib.h> #include "errors.hpp" #include <boost/bind.hpp> #include "arch/timing.hpp" #include "arch/runtime/starter.hpp" #include "utils.hpp" // randint namespace mock { temp_file_t::temp_file_t(const char *tmpl) { size_t len = strlen(tmpl); filename.init(len + 1); memcpy(filename.data(), tmpl, len+1); int fd = mkstemp(filename.data()); guarantee_err(fd != -1, "Couldn't create a temporary file"); close(fd); } temp_file_t::~temp_file_t() { unlink(filename.data()); } void let_stuff_happen() { nap(100); } int randport() { return 10000 + randint(20000); } void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) { ::run_in_thread_pool(fun, num_workers); } } // namespace mock
#include "mock/unittest_utils.hpp" #include <stdlib.h> #include "errors.hpp" #include <boost/bind.hpp> #include "arch/timing.hpp" #include "arch/runtime/starter.hpp" #include "utils.hpp" // randint namespace mock { temp_file_t::temp_file_t(const char *tmpl) { size_t len = strlen(tmpl); filename.init(len + 1); memcpy(filename.data(), tmpl, len+1); int fd = mkstemp(filename.data()); guarantee_err(fd != -1, "Couldn't create a temporary file"); close(fd); } temp_file_t::~temp_file_t() { unlink(filename.data()); } void let_stuff_happen() { #ifdef VALGRIND nap(2000); #else nap(100); #endif } int randport() { return 10000 + randint(20000); } void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) { ::run_in_thread_pool(fun, num_workers); } } // namespace mock
Fix miner_test unit test bug
#include <boost/test/unit_test.hpp> #include "../uint256.h" extern void SHA256Transform(void* pstate, void* pinput, const void* pinit); BOOST_AUTO_TEST_SUITE(miner_tests) BOOST_AUTO_TEST_CASE(sha256transform_equality) { unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; unsigned char pstate[32]; unsigned char pinput[32]; int i; for (i = 0; i < 32; i++) { pinput[i] = i; pstate[i] = 0; } uint256 hash; SHA256Transform(&hash, pinput, pSHA256InitState); BOOST_TEST_MESSAGE(hash.GetHex()); uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3"); BOOST_CHECK(hash == hash_reference); } BOOST_AUTO_TEST_SUITE_END()
#include <boost/test/unit_test.hpp> #include "../uint256.h" extern void SHA256Transform(void* pstate, void* pinput, const void* pinit); BOOST_AUTO_TEST_SUITE(miner_tests) BOOST_AUTO_TEST_CASE(sha256transform_equality) { unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; unsigned char pstate[32]; unsigned char pinput[64]; int i; for (i = 0; i < 32; i++) { pinput[i] = i; pinput[i+32] = 0; } uint256 hash; SHA256Transform(&hash, pinput, pSHA256InitState); BOOST_TEST_MESSAGE(hash.GetHex()); uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3"); BOOST_CHECK(hash == hash_reference); } BOOST_AUTO_TEST_SUITE_END()
Revert part of r. 325746 D43378
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### // RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### 2>&1 | \ // RUN: FileCheck %s --check-prefix=SHARED // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### -DMAIN // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### 2>&1 -DMAIN \ // RUN: | FileCheck %s --check-prefix=STATIC // // SHARED-NOT: {{clang_rt\.xray-}} // STATIC: {{clang_rt\.xray-}} // // REQUIRES: enable_shared int foo() { return 42; } #ifdef MAIN int main() { return foo(); } #endif
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### // RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### 2>&1 | \ // RUN: FileCheck %s --check-prefix=SHARED // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### -DMAIN // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### 2>&1 -DMAIN \ // RUN: | FileCheck %s --check-prefix=STATIC // // SHARED-NOT: {{clang_rt\.xray-}} // STATIC: {{clang_rt\.xray-}} // // REQUIRES: linux, enable_shared int foo() { return 42; } #ifdef MAIN int main() { return foo(); } #endif
Revert "[FIXED] proxy img dtor"
#include "ProxyImage.h" #include "StringHelper.h" #include <sprite2/S2_Texture.h> namespace gum { ProxyImage::ProxyImage(int id, int w, int h, int format) { Init(id, w, h, format); } ProxyImage::~ProxyImage() { // m_id = 0; // avoid release in Image // // managed by other } void ProxyImage::Init(int id, int w, int h, int format) { m_width = w; m_height = h; m_format = format; m_id = id; m_filepath = GetFilepath(id); m_s2_tex->Init(w, h, id); } std::string ProxyImage::GetFilepath(int id) { return "_proxy" + StringHelper::ToString(id); } }
#include "ProxyImage.h" #include "StringHelper.h" #include <sprite2/S2_Texture.h> namespace gum { ProxyImage::ProxyImage(int id, int w, int h, int format) { Init(id, w, h, format); } ProxyImage::~ProxyImage() { m_id = 0; // avoid release in Image // managed by other } void ProxyImage::Init(int id, int w, int h, int format) { m_width = w; m_height = h; m_format = format; m_id = id; m_filepath = GetFilepath(id); m_s2_tex->Init(w, h, id); } std::string ProxyImage::GetFilepath(int id) { return "_proxy" + StringHelper::ToString(id); } }
Fix error in size for parsing the certificate by mbedtls_x509_crt_parse
#include "HttpClient.h" #include <mbedtls/ssl.h> #include <mbedtls/x509.h> namespace ceema { CURLcode HttpClient::ssl_ctx_callback_mbedtls(CURL *curl, void *ssl_ctx, void *client_ptr) { HttpClient& client = *static_cast<HttpClient*>(client_ptr); if (client.m_cert.empty()) { return CURLE_OK; } LOG_DEBUG(logging::loggerRoot, "Inserting SSL cert"); CURLcode status = CURLE_OK; auto mbed_ctx = static_cast<mbedtls_ssl_config*>(ssl_ctx); mbedtls_x509_crt cacert; mbedtls_x509_crt_init( &cacert ); if (mbedtls_x509_crt_parse( &cacert, reinterpret_cast<const unsigned char*>(client.m_cert.c_str()), client.m_cert.size()) != 0) { status = CURLE_SSL_CERTPROBLEM; } else { mbedtls_ssl_conf_ca_chain(mbed_ctx, &cacert, nullptr); } return status; } }
#include "HttpClient.h" #include <mbedtls/ssl.h> #include <mbedtls/x509.h> namespace ceema { CURLcode HttpClient::ssl_ctx_callback_mbedtls(CURL *curl, void *ssl_ctx, void *client_ptr) { HttpClient& client = *static_cast<HttpClient*>(client_ptr); if (client.m_cert.empty()) { return CURLE_OK; } LOG_DEBUG(logging::loggerRoot, "Inserting SSL cert"); CURLcode status = CURLE_OK; auto mbed_ctx = static_cast<mbedtls_ssl_config*>(ssl_ctx); mbedtls_x509_crt cacert; mbedtls_x509_crt_init( &cacert ); if (mbedtls_x509_crt_parse( &cacert, reinterpret_cast<const unsigned char*>(client.m_cert.c_str()), client.m_cert.size() + 1) != 0) { status = CURLE_SSL_CERTPROBLEM; } else { mbedtls_ssl_conf_ca_chain(mbed_ctx, &cacert, nullptr); } return status; } }
Fix bug. support implicit cast Vec to Array again.
#include "common.h" void siren_ary_to_xyz(VALUE ary, Standard_Real& x, Standard_Real& y, Standard_Real& z) { x = 0.0; y = 0.0; z = 0.0; Check_Type(ary, T_ARRAY); int len = RARRAY_LEN(ary); if (len > 0) { x = NUM2DBL(RARRAY_AREF(ary, 0)); } if (len > 1) { y = NUM2DBL(RARRAY_AREF(ary, 1)); } if (len > 2) { z = NUM2DBL(RARRAY_AREF(ary, 2)); } return; }
#include "common.h" void siren_ary_to_xyz(VALUE ary, Standard_Real& x, Standard_Real& y, Standard_Real& z) { x = 0.0; y = 0.0; z = 0.0; int len = RARRAY_LEN(ary); if (len > 0) { x = NUM2DBL(RARRAY_AREF(ary, 0)); } if (len > 1) { y = NUM2DBL(RARRAY_AREF(ary, 1)); } if (len > 2) { z = NUM2DBL(RARRAY_AREF(ary, 2)); } return; }
Remove explicit WIN32 references from Console app.
#include "KAI/Console/Console.h" #include <iostream> #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #endif using namespace std; USING_NAMESPACE_KAI //static Color _color; int main(int argc, char **argv) { KAI_UNUSED_2(argc, argv); cout << "pyro v0.1" << endl; Console console; console.SetLanguage(Language::Pi); Process::trace = 0; console.GetExecutor()->SetTraceLevel(0); return console.Run(); }
#include <KAI/Console/Console.h> #include <iostream> using namespace std; USING_NAMESPACE_KAI int main(int argc, char **argv) { KAI_UNUSED_2(argc, argv); cout << "KAI v0.1" << endl; Console console; console.SetLanguage(Language::Pi); // the higher the number, the greater the verbosity of debug output Process::trace = 0; console.GetExecutor()->SetTraceLevel(0); // start the REPL return console.Run(); }
Fix tests include for bullet
#include "Rotate.hpp" #include "../../../Libraries/bullet3/src/LinearMath/btTransform.h" #include <Scenes/Entity.hpp> #include <Engine/Engine.hpp> #include <Physics/Colliders/Collider.hpp> #include <Maths/Maths.hpp> namespace test { Rotate::Rotate(const Vector3 &direction, const int &test) : m_direction(direction), m_test(test), m_rotation(Vector3()) { } void Rotate::Start() { } void Rotate::Update() { m_rotation += m_direction * Engine::Get()->GetDelta().AsSeconds(); Transform &transform = GetParent()->GetLocalTransform(); transform.SetRotation(m_rotation); if (m_test == 1) { Quaternion rotation = Quaternion(m_rotation.m_x, m_rotation.m_y, m_rotation.m_z); transform.SetRotation(rotation.ToEuler()); } else if (m_test == 2) { btTransform transform1 = Collider::Convert(transform); transform = Collider::Convert(transform1, transform.GetScaling()); } } void Rotate::Decode(const Metadata &metadata) { m_direction = metadata.GetChild<Vector3>("Direction"); } void Rotate::Encode(Metadata &metadata) const { metadata.SetChild<Vector3>("Direction", m_direction); } }
#include "Rotate.hpp" #include <bullet/LinearMath/btTransform.h> #include <Scenes/Entity.hpp> #include <Engine/Engine.hpp> #include <Physics/Colliders/Collider.hpp> #include <Maths/Maths.hpp> namespace test { Rotate::Rotate(const Vector3 &direction, const int &test) : m_direction(direction), m_test(test), m_rotation(Vector3()) { } void Rotate::Start() { } void Rotate::Update() { m_rotation += m_direction * Engine::Get()->GetDelta().AsSeconds(); Transform &transform = GetParent()->GetLocalTransform(); transform.SetRotation(m_rotation); if (m_test == 1) { Quaternion rotation = Quaternion(m_rotation.m_x, m_rotation.m_y, m_rotation.m_z); transform.SetRotation(rotation.ToEuler()); } else if (m_test == 2) { btTransform transform1 = Collider::Convert(transform); transform = Collider::Convert(transform1, transform.GetScaling()); } } void Rotate::Decode(const Metadata &metadata) { m_direction = metadata.GetChild<Vector3>("Direction"); } void Rotate::Encode(Metadata &metadata) const { metadata.SetChild<Vector3>("Direction", m_direction); } }
Improve error message on bad options.
#include <iostream> #include "libport/cli.hh" #include "libport/sysexits.hh" #include "libport/program-name.hh" namespace libport { void usage_error (const std::string& opt, const std::string& err) { std::cerr << program_name << ": " << opt << ": " << err << std::endl << libport::exit (EX_USAGE); } void required_argument (const std::string& opt) { usage_error (opt, "requires an argument"); } void missing_argument (const std::string& opt) { usage_error (opt, "missing argument"); } void invalid_option (const std::string& opt) { usage_error (opt, "invalid option"); } void invalid_option_val (const std::string& opt, const std::string& arg) { usage_error (opt, "invalid argument: " + arg); } }
#include <iostream> #include "libport/cli.hh" #include "libport/sysexits.hh" #include "libport/program-name.hh" namespace libport { void usage_error (const std::string& opt, const std::string& err) { std::cerr << program_name << ": " << opt << ": " << err << std::endl << "Try `" << program_name << " --help' for more information." << std::endl << libport::exit (EX_USAGE); } void required_argument (const std::string& opt) { usage_error (opt, "requires an argument"); } void missing_argument (const std::string& opt) { usage_error (opt, "missing argument"); } void invalid_option (const std::string& opt) { usage_error (opt, "invalid option"); } void invalid_option_val (const std::string& opt, const std::string& arg) { usage_error (opt, "invalid argument: " + arg); } }
Correct check of number of arguments
// Standard headers #include "InputArgs.hpp" InputArgs::InputArgs(int argc, char const *const *argv) : argstream(argv, argv + argc) { read_input(); process_input(); } void InputArgs::process_input() { if (n_threads == 0) n_threads = std::thread::hardware_concurrency(); } void InputArgs::read_input() { argstream[1] >> n_threads; argstream[2] >> stop_criteria; argstream[3] >> precision; argstream[4] >> angle; if (argstream.size() >= 5) argstream[5] >> debug_level; }
// Standard headers #include "InputArgs.hpp" InputArgs::InputArgs(int argc, char const *const *argv) : argstream(argv, argv + argc) { read_input(); process_input(); } void InputArgs::process_input() { if (n_threads == 0) n_threads = std::thread::hardware_concurrency(); } void InputArgs::read_input() { argstream[1] >> n_threads; argstream[2] >> stop_criteria; argstream[3] >> precision; argstream[4] >> angle; if (argstream.size() > 5) argstream[5] >> debug_level; }
Fix mistake of using size instead of capacity.
#include "misc_util.h" namespace dlib { void string_fmt_time(std::string& ret) { time_t now = time(NULL); struct tm *t = localtime(&now); while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t)) ret.reserve(ret.size() << 1); } }
#include "misc_util.h" namespace dlib { void string_fmt_time(std::string& ret) { time_t now = time(NULL); struct tm *t = localtime(&now); while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t)) ret.reserve(ret.capacity() ? ret.capacity() << 1: 16); } }
Fix the path of header file
#include <iostream> #include <fstream> #include "huffman.hpp" using namespace algorithm; static enum { E_SUCCESS = 0, E_ARGUMENT_NOT_PROVIDED, E_FILE_NOT_FOUND, } StatusType; int main(const int argc, const char * argv[]) { if(argc < 2) { fprintf(stderr, "Usage: %s [file name]\n", argv[0]); return E_ARGUMENT_NOT_PROVIDED; } std::string f_name = argv[1]; std::ifstream f(f_name, std::ios::binary); if(! f.is_open()) { fprintf(stderr, "Error: File '%s' not found.\n", f_name.c_str()); return E_FILE_NOT_FOUND; } Huffman huffman; huffman.CollectRuns(f); huffman.PrintAllRuns(stdout); f.close(); return E_SUCCESS; }
#include <iostream> #include <fstream> #include "include/huffman.hpp" using namespace algorithm; static enum { E_SUCCESS = 0, E_ARGUMENT_NOT_PROVIDED, E_FILE_NOT_FOUND, } StatusType; int main(const int argc, const char * argv[]) { if(argc < 2) { fprintf(stderr, "Usage: %s [file name]\n", argv[0]); return E_ARGUMENT_NOT_PROVIDED; } std::string f_name = argv[1]; std::ifstream f(f_name, std::ios::binary); if(! f.is_open()) { fprintf(stderr, "Error: File '%s' not found.\n", f_name.c_str()); return E_FILE_NOT_FOUND; } Huffman huffman; huffman.CollectRuns(f); huffman.PrintAllRuns(stdout); f.close(); return E_SUCCESS; }
Add execution of simple programs
int main(int argc, char **argv) { return 0; }
#include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sysexits.h> #include <unistd.h> char* getinput(char *buffer, size_t buflen) { printf("$$ "); return fgets(buffer, buflen, stdin); } int main(int argc, char **argv) { char buf[1024]; pid_t pid; int status; while (getinput(buf, sizeof(buf))) { buf[strlen(buf) - 1] = '\0'; if ((pid = fork()) == -1) { fprintf(stderr, "shell: can't fork: %s\n", strerror(errno)); continue; } else if (pid == 0) { execlp(buf, buf, (char*) 0); fprintf(stderr, "shell: couldn't exec %s: %s\n", buf, strerror(errno)); exit(EX_DATAERR); } if ((pid = waitpid(pid, &status, 0)) < 0) { fprintf(stderr, "shell: waitpid error: %s\n", strerror(errno)); } } exit(EX_OK); return 0; }
Update to match edited question.
// https://github.com/KubaO/stackoverflown/tree/master/questions/lambda-list-37615204 #include <QtWidgets> class Widget : public QWidget { struct Buyable { void buy(int) const {} }; QList<Buyable> m_list; QList<QList<QWidget*>> m_widgets; int m_amountMultiplier = 2; public: Widget() { auto button = [this]{ return new QPushButton(this); }; for (int i = 0; i < 5; ++i) { m_list << Buyable(); m_widgets << QList<QWidget*>{button(), button(), button()}; } } void test() { Q_ASSERT(m_list.size() == m_widgets.size()); for (int i = 0; i < m_list.size(); ++i) { connect(static_cast<QAbstractButton*>(m_widgets.at(i).at(2)), &QAbstractButton::clicked, [this, i]() { m_list.at(i).buy(m_amountMultiplier);} ); } } }; int main() {}
// https://github.com/KubaO/stackoverflown/tree/master/questions/lambda-list-37615204 #include <QtWidgets> struct Building { void buy() {} }; class Class : public QObject { QList<Building> m_buildings; QList<QList<QWidget*>> m_widgets; public: Class() { for (int i = 0; i<m_buildings.size(); ++i) connect(static_cast<QAbstractButton*>(m_widgets.at(i).at(2)), &QAbstractButton::clicked, [=] { m_buildings[i].buy(); }); } }; int main() {}
Fix tack poh's merge conflict which he is aware of but doesn't want to fix.
// This file extends the QWebView class to add additional functionality. #include "stdafx.h" using namespace std; void QWebViewWithHooks::watch(string selector, Getter getter, Callback callback){ int uuid = watchUuid++; watches.push_back(make_tuple(QString::fromStdString(selector), getter, callback, uuid) ); watchValues[uuid] = ""; //TODO: Change to return unwatch function. However, quite lazy. } void QWebViewWithHooks::keyReleaseEvent(QKeyEvent * ev) { // Look for all watches and get values that are changed. // If there is a change, call the callback. for(auto it = watches.begin(); it != watches.end(); ++it) { auto selector = get<0>(*it); auto getter = get<1>(*it); auto callback = get<2>(*it); auto uuid = get<3>(*it); auto element = this->page()->mainFrame()->findFirstElement(selector); auto currentValue = getter(element).toStdString(); if(currentValue != watchValues[uuid] || ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return) { watchValues[uuid] = currentValue; callback(currentValue, ev); } } }
// This file extends the QWebView class to add additional functionality. #include "stdafx.h" using namespace std; void QWebViewWithHooks::watch(string selector, Getter getter, Callback callback){ int uuid = watchUuid++; watches.push_back(make_tuple(QString::fromStdString(selector), getter, callback, uuid) ); watchValues[uuid] = ""; //TODO: Change to return unwatch function. However, quite lazy. } void QWebViewWithHooks::keyReleaseEvent(QKeyEvent * ev) { // Look for all watches and get values that are changed. // If there is a change, call the callback. for(auto it = watches.begin(); it != watches.end(); ++it) { auto selector = get<0>(*it); auto getter = get<1>(*it); auto callback = get<2>(*it); auto uuid = get<3>(*it); auto element = this->page()->mainFrame()->findFirstElement(selector); auto currentValue = getter(element).toStdString(); if(currentValue != watchValues[uuid]) { watchValues[uuid] = currentValue; callback(currentValue, ev); } } }
Update the Python interface with the new names
/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include "chemharp-python.hpp" void register_trajectory() { /* Trajectory class *******************************************************/ py::class_<Trajectory, boost::noncopyable>("Trajectory", py::init<string, py::optional<string, string>>()) .def("read_next_step", &Trajectory::read_next_step) .def("read_at_step", &Trajectory::read_at_step) .def("write_step", &Trajectory::write_step) .def("done", &Trajectory::done) .def("close", &Trajectory::close) .def("nsteps", &Trajectory::nsteps) .def("topology", static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology)) .def("topology", static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology)) ; }
/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include "chemharp-python.hpp" void register_trajectory() { /* Trajectory class *******************************************************/ py::class_<Trajectory, boost::noncopyable>("Trajectory", py::init<string, py::optional<string, string>>()) .def("read", &Trajectory::read) .def("read_at", &Trajectory::read_at) .def("write", &Trajectory::write) .def("done", &Trajectory::done) .def("close", &Trajectory::close) .def("nsteps", &Trajectory::nsteps) .def("topology", static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology)) .def("topology", static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology)) ; }
Rename bc_* by ure_* in ure_logger()
/* * URELogger.cc * * Copyright (C) 2016 OpenCog Foundation * * Author: Nil Geisweiller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "URELogger.h" using namespace opencog; // Create and return the single instance Logger& opencog::ure_logger() { auto bc_logger_instantiate = []() { Logger tmp; tmp.set_component("URE"); return tmp; }; static Logger bc_instance(bc_logger_instantiate()); return bc_instance; }
/* * URELogger.cc * * Copyright (C) 2016 OpenCog Foundation * * Author: Nil Geisweiller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "URELogger.h" using namespace opencog; // Create and return the single instance Logger& opencog::ure_logger() { auto ure_logger_instantiate = []() { Logger tmp; tmp.set_component("URE"); return tmp; }; static Logger ure_instance(ure_logger_instantiate()); return ure_instance; }
Add validation for draw method. Don't draw amount if there is not enough in account
#include <iostream> using namespace std; class BankAccount { char clientName[23]; char id[15]; double account; public: BankAccount(const char _clientName[], const char _id[], double _account) { strcpy(clientName, _clientName); strcpy(id, _id); account = _account; } void print() { cout << "Name: " << clientName << '\n' << "Account ID: " << id << '\n' << "Account: " << account << '\n'; } void transfer(double amount) { account += amount; } void draw(double amount) { account -= amount; } }; int main() { BankAccount bankAccount("Ivan", "1", 2000); bankAccount.print(); bankAccount.transfer(300); bankAccount.print(); bankAccount.draw(500); bankAccount.print(); return 0; }
#include <iostream> using namespace std; class BankAccount { char clientName[23]; char id[15]; double account; public: BankAccount(const char _clientName[], const char _id[], double _account) { strcpy(clientName, _clientName); strcpy(id, _id); account = _account; } void print() { cout << "Name: " << clientName << '\n' << "Account ID: " << id << '\n' << "Account: " << account << '\n'; } void transfer(double amount) { account += amount; } void draw(double amount) { if (account >= amount) { account -= amount; } } }; int main() { BankAccount bankAccount("Ivan", "1", 2000); bankAccount.print(); bankAccount.transfer(300); bankAccount.print(); bankAccount.draw(500); bankAccount.print(); return 0; }
Print an error on a bad tiles cost function name instead of silently quitting.
/** * \file tiles_costs.cpp * * * * \author eaburns * \date 05-01-2010 */ #include <string> #include <iostream> using namespace std; #include <stdlib.h> #include <string.h> #include "tiles_costs.h" struct cost_tab_ent { string name; TilesCostFunction &fun; }; static TilesUnitCost unit_cost = TilesUnitCost(); static TilesSqrtCost sqrt_cost = TilesSqrtCost(); static TilesInverseCost inverse_cost = TilesInverseCost(); // Table of cost functions. static cost_tab_ent cost_functions[] = { { "", unit_cost }, // default value { "unit", unit_cost }, { "sqrt", sqrt_cost }, { "inverse", inverse_cost }, }; TilesCostFunction &get_cost_function_by_name(string name) { unsigned int n = sizeof(cost_functions) / sizeof(*cost_functions); unsigned int i; for (i = 0; i < n; i += 1) if (cost_functions[i].name == name) return cost_functions[i].fun; exit(EXIT_FAILURE); }
/** * \file tiles_costs.cpp * * * * \author eaburns * \date 05-01-2010 */ #include <string> #include <iostream> using namespace std; #include <stdlib.h> #include <string.h> #include "tiles_costs.h" struct cost_tab_ent { string name; TilesCostFunction &fun; }; static TilesUnitCost unit_cost = TilesUnitCost(); static TilesSqrtCost sqrt_cost = TilesSqrtCost(); static TilesInverseCost inverse_cost = TilesInverseCost(); // Table of cost functions. static cost_tab_ent cost_functions[] = { { "", unit_cost }, // default value { "unit", unit_cost }, { "sqrt", sqrt_cost }, { "inverse", inverse_cost }, }; TilesCostFunction &get_cost_function_by_name(string name) { unsigned int n = sizeof(cost_functions) / sizeof(*cost_functions); unsigned int i; for (i = 0; i < n; i += 1) if (cost_functions[i].name == name) return cost_functions[i].fun; std::cerr << "Bad cost function: " << name << std::endl; exit(EXIT_FAILURE); }
Test cases print stack trace on sigsegv
#include "google/gtest/gtest.h" int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include "google/gtest/gtest.h" #include <messmer/cpp-utils/assert/backtrace.h> int main(int argc, char **argv) { cpputils::showBacktraceOnSigSegv(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Set window role for Mir backend
/* * This file is part of Maliit framework * * * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@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 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 "mirplatform.h" #include "mirplatformconnection.h" #include <QRegion> #include <QWindow> namespace Maliit { MirPlatform::MirPlatform(): AbstractPlatform(), m_mirPlatformConnection(new MirPlatformConnection) { } void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position) { Q_UNUSED(window) Q_UNUSED(position) } void MirPlatform::setInputRegion(QWindow *window, const QRegion &region) { Q_UNUSED(window) if (!region.rects().isEmpty()) { m_mirPlatformConnection->setGeometry(region.rects().first()); } } }
/* * This file is part of Maliit framework * * * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@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 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 "mirplatform.h" #include "mirplatformconnection.h" #include <QRegion> #include <QWindow> #include <QVariant> #include <ubuntu/application/ui/window_properties.h> namespace Maliit { MirPlatform::MirPlatform(): AbstractPlatform(), m_mirPlatformConnection(new MirPlatformConnection) { } void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position) { Q_UNUSED(position) window->setProperty("role", QVariant(U_ON_SCREEN_KEYBOARD_ROLE)); } void MirPlatform::setInputRegion(QWindow *window, const QRegion &region) { Q_UNUSED(window) if (!region.rects().isEmpty()) { m_mirPlatformConnection->setGeometry(region.rects().first()); } } }
Fix load rom memory boundaries
#include "MMU.hpp" #include <iterator> #include <limits> namespace Core8 { Chip8::BYTE MMU::readByte(const std::size_t address) const { const auto byte = memory.at(address); return byte; } Chip8::WORD MMU::readWord(const std::size_t address) const { const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits; const auto lsb = memory.at(address + 1); return msb | lsb; } void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) { memory.at(address) = byte; } void MMU::load(std::istream& rom, const std::size_t address) { std::noskipws(rom); std::copy(std::istream_iterator<Chip8::BYTE>(rom), std::istream_iterator<Chip8::BYTE>(), &memory.at(address)); } void MMU::clear() { memory.fill(0x0); } } // namespace Core8
#include "MMU.hpp" #include <algorithm> #include <iterator> #include <limits> #include <vector> namespace Core8 { Chip8::BYTE MMU::readByte(const std::size_t address) const { const auto byte = memory.at(address); return byte; } Chip8::WORD MMU::readWord(const std::size_t address) const { const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits; const auto lsb = memory.at(address + 1); return msb | lsb; } void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) { memory.at(address) = byte; } void MMU::load(std::istream& rom, const std::size_t address) { std::noskipws(rom); const std::vector<Chip8::BYTE> data{std::istream_iterator<Chip8::BYTE>(rom), std::istream_iterator<Chip8::BYTE>()}; const auto availableMemory = memory.size() - address; const auto dataSize = data.size(); const auto length = dataSize > availableMemory ? availableMemory : dataSize; std::copy_n(std::begin(data), length, std::next(std::begin(memory), address)); } void MMU::clear() { memory.fill(0x0); } } // namespace Core8
Call WSACleanup only on Windows
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #ifdef _WIN32 #define NOMINMAX #include <winsock2.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <poll.h> #endif #include "Network.hpp" #include "utils/Log.hpp" namespace ouzel { namespace network { Network::Network() { } Network::~Network() { WSACleanup(); } bool Network::init() { #ifdef _WIN32 WORD sockVersion = MAKEWORD(2, 2); WSADATA wsaData; int error = WSAStartup(sockVersion, &wsaData); if (error != 0) { Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error; return false; } if (wsaData.wVersion != sockVersion) { Log(Log::Level::ERR) << "Incorrect Winsock version"; WSACleanup(); return false; } #endif return true; } } // namespace network } // namespace ouzel
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #ifdef _WIN32 #define NOMINMAX #include <winsock2.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <poll.h> #endif #include "Network.hpp" #include "utils/Log.hpp" namespace ouzel { namespace network { Network::Network() { } Network::~Network() { #ifdef _WIN32 WSACleanup(); #endif } bool Network::init() { #ifdef _WIN32 WORD sockVersion = MAKEWORD(2, 2); WSADATA wsaData; int error = WSAStartup(sockVersion, &wsaData); if (error != 0) { Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error; return false; } if (wsaData.wVersion != sockVersion) { Log(Log::Level::ERR) << "Incorrect Winsock version"; WSACleanup(); return false; } #endif return true; } } // namespace network } // namespace ouzel
Add a player circle that can move
#include <SFML/Graphics.hpp> #include <SFML/System/Clock.hpp> #include <iostream> int main() { sf::RenderWindow window(sf::VideoMode(800,600), "Psychic Dangerzone"); window.setVerticalSyncEnabled(true); sf::Clock world_clock; float last_frame_time; while(window.isOpen()) { last_frame_time = world_clock.getElapsedTime().asSeconds(); sf::Event event; while(window.pollEvent(event)) { // TODO: process events if(event.type == sf::Event::Closed) { window.close(); } } window.clear(sf::Color::Black); window.display(); std::cout << world_clock.getElapsedTime().asSeconds() - last_frame_time << std::endl; } return 0; }
#include <SFML/Graphics.hpp> #include <SFML/System/Clock.hpp> #include <iostream> int main() { sf::RenderWindow window(sf::VideoMode(800,600), "Psychic Dangerzone"); window.setVerticalSyncEnabled(true); sf::Clock world_clock; sf::CircleShape player(50); float last_frame_time; while(window.isOpen()) { last_frame_time = world_clock.getElapsedTime().asSeconds(); sf::Event event; while(window.pollEvent(event)) { if(event.type == sf::Event::Closed) { window.close(); } } sf::Vector2f velocity; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { velocity.x -= 10; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { velocity.x += 10; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { velocity.y -= 10; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { velocity.y += 10; } player.move(velocity); //player.move(velocity.x, velocity.y); window.clear(sf::Color::Black); window.draw(player); window.display(); std::cout << world_clock.getElapsedTime().asSeconds() - last_frame_time << std::endl; } return 0; }
Improve test cases for lms::Endian
#include "gtest/gtest.h" #include "lms/endian.h" TEST(Endian, uint16) { using lms::Endian; ASSERT_EQ(uint16_t(0xCAFEu), Endian::betoh(Endian::htobe(uint16_t(0xCAFEu)))); ASSERT_EQ(uint16_t(0xCAFEu), Endian::letoh(Endian::htole(uint16_t(0xCAFEu)))); } TEST(Endian, uint32) { using lms::Endian; ASSERT_EQ(uint32_t(0xDEADBEEFu), Endian::betoh(Endian::htobe(uint32_t(0xDEADBEEFu)))); ASSERT_EQ(uint32_t(0xDEADBEEFu), Endian::letoh(Endian::htole(uint32_t(0xDEADBEEFu)))); } TEST(Endian, uint64) { using lms::Endian; ASSERT_EQ(uint64_t(0xFEEDCAFEDEADBEEFu), Endian::betoh(Endian::htobe(uint64_t(0xFEEDCAFEDEADBEEFu)))); ASSERT_EQ(uint64_t(0xFEEDCAFEDEADBEEFu), Endian::letoh(Endian::htole(uint64_t(0xFEEDCAFEDEADBEEFu)))); }
#include "gtest/gtest.h" #include "lms/endian.h" TEST(Endian, uint16) { using lms::Endian; ASSERT_EQ(0xFECAu, Endian::letoh(Endian::htobe(uint16_t(0xCAFEu)))); ASSERT_EQ(0xFECAu, Endian::betoh(Endian::htole(uint16_t(0xCAFEu)))); } TEST(Endian, uint32) { using lms::Endian; ASSERT_EQ(0xEFBEADDEu, Endian::letoh(Endian::htobe(uint32_t(0xDEADBEEFu)))); ASSERT_EQ(0xEFBEADDEu, Endian::betoh(Endian::htole(uint32_t(0xDEADBEEFu)))); } TEST(Endian, uint64) { using lms::Endian; ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::letoh(Endian::htobe(0xFEEDCAFEDEADBEEFu))); ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::betoh(Endian::htole(0xFEEDCAFEDEADBEEFu))); }
Fix regression of not taking into account environment map
#include "linalg/ray.h" #include "geometry/differential_geometry.h" #include "geometry/geometry.h" #include "scene.h" #include "integrator/surface_integrator.h" #include "renderer/renderer.h" Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator) : surface_integrator(std::move(surface_integrator)) {} Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene) const { DifferentialGeometry dg; if (scene.get_root().intersect(ray, dg)){ dg.compute_differentials(ray); return surface_integrator->illumination(scene, *this, ray, dg); } else { //TODO: Compute light along the ray coming from lights return Colorf{0}; } }
#include "linalg/ray.h" #include "geometry/differential_geometry.h" #include "geometry/geometry.h" #include "scene.h" #include "integrator/surface_integrator.h" #include "renderer/renderer.h" Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator) : surface_integrator(std::move(surface_integrator)) {} Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene) const { DifferentialGeometry dg; if (scene.get_root().intersect(ray, dg)){ dg.compute_differentials(ray); return surface_integrator->illumination(scene, *this, ray, dg); } else if (scene.get_environment()){ //TODO: Compute light along the ray coming from lights DifferentialGeometry dg; dg.point = Point{ray.d.x, ray.d.y, ray.d.z}; return scene.get_environment()->sample(dg); } return Colorf{0}; }
Add testcase for PR5817, although the bug was already fixed
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s // Verify that we can't initialize non-aggregates with an initializer // list. struct NonAggr1 { NonAggr1(int) { } int m; }; struct Base { }; struct NonAggr2 : public Base { int m; }; class NonAggr3 { int m; }; struct NonAggr4 { int m; virtual void f(); }; NonAggr1 na1 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr1' cannot be initialized with an initializer list}} NonAggr2 na2 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr2' cannot be initialized with an initializer list}} NonAggr3 na3 = { 17 }; // expected-error{{non-aggregate type 'class NonAggr3' cannot be initialized with an initializer list}} NonAggr4 na4 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr4' cannot be initialized with an initializer list}}
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s // Verify that we can't initialize non-aggregates with an initializer // list. struct NonAggr1 { NonAggr1(int) { } int m; }; struct Base { }; struct NonAggr2 : public Base { int m; }; class NonAggr3 { int m; }; struct NonAggr4 { int m; virtual void f(); }; NonAggr1 na1 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr1' cannot be initialized with an initializer list}} NonAggr2 na2 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr2' cannot be initialized with an initializer list}} NonAggr3 na3 = { 17 }; // expected-error{{non-aggregate type 'class NonAggr3' cannot be initialized with an initializer list}} NonAggr4 na4 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr4' cannot be initialized with an initializer list}} // PR5817 typedef int type[][2]; const type foo = {0};
Remove unused includes from the C++11 solution for Nov. 2013 Bronze Problem 1
#include <istream> #include <fstream> #include <set> #include <vector> #include <array> #include <algorithm> #include <iterator> using namespace std; int main() { ifstream cin("combo.in"); ofstream cout("combo.out"); int size; cin >> size; set<int> options; for (int i = 0; i < 2; i++) { int a, b, c; cin >> a >> b >> c; // creates permutations of allowable combinations and turns them into // an integer so that set can compare them and only retain uniques // the indexes here start at -3 and end at +1 because the input starts // at 1 but here we want it to start at 0 for (int i = a - 3; i <= a + 1; i++) { for (int j = b - 3; j <= b + 1; j++) { for (int k = c - 3; k <= c + 1; k++) { options.insert(((((i % size) + size) % size) << 0) + ((((j % size) + size) % size) << 8) + ((((k % size) + size) % size) << 16)); } } } } // the size of the set is the number of unique combinations cout << options.size() << endl; return 0; }
#include <fstream> #include <set> using namespace std; int main() { ifstream cin("combo.in"); ofstream cout("combo.out"); int size; cin >> size; set<int> options; for (int i = 0; i < 2; i++) { int a, b, c; cin >> a >> b >> c; // creates permutations of allowable combinations and turns them into // an integer so that set can compare them and only retain uniques // the indexes here start at -3 and end at +1 because the input starts // at 1 but here we want it to start at 0 for (int i = a - 3; i <= a + 1; i++) { for (int j = b - 3; j <= b + 1; j++) { for (int k = c - 3; k <= c + 1; k++) { options.insert(((((i % size) + size) % size) << 0) + ((((j % size) + size) % size) << 8) + ((((k % size) + size) % size) << 16)); } } } } // the size of the set is the number of unique combinations cout << options.size() << endl; return 0; }
Fix the regression test regexp validation
/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "regression/custom_debug_log.h" #include <iostream> #include <string> #include "modsecurity/debug_log.h" #include "utils/regex.h" namespace modsecurity_test { CustomDebugLog *CustomDebugLog::new_instance() { return new CustomDebugLog(); } void CustomDebugLog::write(int level, const std::string& message) { m_log << "[" << level << "] " << message << std::endl; } bool CustomDebugLog::contains(const std::string& pattern) { ModSecurity::Utils::Regex re(pattern); ModSecurity::Utils::SMatch match; std::string s = m_log.str(); return (ModSecurity::Utils::regex_search(s, &match, re) && match.size() >= 1); } std::string CustomDebugLog::log_messages() { return m_log.str(); } } // namespace modsecurity_test
/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "regression/custom_debug_log.h" #include <iostream> #include <string> #include "modsecurity/debug_log.h" #include "utils/regex.h" namespace modsecurity_test { CustomDebugLog *CustomDebugLog::new_instance() { return new CustomDebugLog(); } void CustomDebugLog::write(int level, const std::string& message) { m_log << "[" << level << "] " << message << std::endl; } bool CustomDebugLog::contains(const std::string& pattern) { ModSecurity::Utils::Regex re(pattern); ModSecurity::Utils::SMatch match; std::string s = m_log.str(); return ModSecurity::Utils::regex_search(s, re); } std::string CustomDebugLog::log_messages() { return m_log.str(); } } // namespace modsecurity_test
Fix test for python 3
// RUN: clang-diff -ast-dump %s -- \ // RUN: | %python -c 'import json, sys; json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \ // RUN: | FileCheck %s // CHECK: "begin": 294, // CHECK: "type": "CXXRecordDecl", // CHECK: "type": "FieldDecl", // CHECK: "end": 314, class A { int x; }; // CHECK: "children": [ // CHECK-NEXT: { // CHECK-NEXT: "begin": // CHECK-NEXT: "children": [] // CHECK-NEXT: "end": // CHECK-NEXT: "id": // CHECK-NEXT: "type": "CharacterLiteral" // CHECK-NEXT: } // CHECK: ] // CHECK: "type": "VarDecl", char nl = '\n'; // CHECK: "value": "abc \n\t\u0000\u001f\u0123 \ub370\ubc15" char s[] = "abc \n\t\0\x1f\u0123 데박";
// RUN: clang-diff -ast-dump %s -- \ // RUN: | %python -c 'import json, sys; json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \ // RUN: | FileCheck %s // CHECK: "begin": 294, // CHECK: "type": "CXXRecordDecl", // CHECK: "type": "FieldDecl", // CHECK: "end": 314, class A { int x; }; // CHECK: "children": [ // CHECK-NEXT: { // CHECK-NEXT: "begin": // CHECK-NEXT: "children": [] // CHECK-NEXT: "end": // CHECK-NEXT: "id": // CHECK-NEXT: "type": "CharacterLiteral" // CHECK-NEXT: } // CHECK: ] // CHECK: "type": "VarDecl", char nl = '\n'; // CHECK: "value": "abc \n\t\u0000\u001f" char s[] = "abc \n\t\0\x1f";
Fix incorrect comment on precompiled header
/* // This file is part of SnakePredictor // // (c) Daniel McAssey <hello@glokon.me> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. */ // stdafx.cpp : source file that includes just the standard includes // CallWinsock.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
/* // This file is part of SnakePredictor // // (c) Daniel McAssey <hello@glokon.me> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. */ // stdafx.cpp : source file that includes just the standard includes // SnakePredictor.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
Add unit test for post method
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace YouDataStoreTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(DataStoreDummyTest) { // You::DataStore::DataStore sut; // sut.post(std::unordered_map<std::wstring, std::wstring>()); Assert::IsTrue(true); } }; } // namespace YouDataStoreTests
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; using DataStore = You::DataStore::DataStore; namespace YouDataStoreTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(DataStore_Post_Basic_Test) { You::DataStore::DataStore sut; bool result = sut.post(0, DataStore::STask()); Assert::IsTrue(result); } TEST_METHOD(DataStore_Post_DuplicateId_Test) { You::DataStore::DataStore sut; sut.post(0, DataStore::STask()); bool result = sut.post(0, DataStore::STask()); Assert::IsFalse(result); } }; } // namespace YouDataStoreTests
Add example of log channels
#include <ionWindow.h> #include <ionGraphicsGL.h> using namespace ion; int main() { Log::AddDefaultOutputs(); SingletonPointer<CWindowManager> WindowManager; SingletonPointer<CGraphicsAPI> GraphicsAPI; GraphicsAPI->Init(new Graphics::COpenGLImplementation()); WindowManager->Init(GraphicsAPI); WindowManager->CreateWindow(vec2i(640, 480), "TestWindowManager", EWindowType::Windowed); while (! WindowManager->ShouldClose()) WindowManager->PollEvents(); return 0; }
#include <ionWindow.h> #include <ionGraphicsGL.h> using namespace ion; int main() { Log::AddDefaultOutputs(); Log::Info("Info"); Log::Warn("Warning"); Log::Error("Error"); SingletonPointer<CWindowManager> WindowManager; SingletonPointer<CGraphicsAPI> GraphicsAPI; GraphicsAPI->Init(new Graphics::COpenGLImplementation()); WindowManager->Init(GraphicsAPI); WindowManager->CreateWindow(vec2i(640, 480), "TestWindowManager", EWindowType::Windowed); while (! WindowManager->ShouldClose()) { WindowManager->PollEvents(); } return 0; }
Add support for halo's to TextSymbolizer().
/* This file is part of python_mapnik (c++/python mapping toolkit) * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ #include <boost/python.hpp> #include <mapnik.hpp> using mapnik::text_symbolizer; using mapnik::Color; void export_text_symbolizer() { using namespace boost::python; class_<text_symbolizer>("TextSymbolizer", init<std::string const&,unsigned,Color const&>("TODO")) ; }
/* This file is part of python_mapnik (c++/python mapping toolkit) * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ #include <boost/python.hpp> #include <mapnik.hpp> using mapnik::text_symbolizer; using mapnik::Color; void export_text_symbolizer() { using namespace boost::python; class_<text_symbolizer>("TextSymbolizer", init<std::string const&,unsigned,Color const&>()) .add_property("halo_fill",make_function( &text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()), &text_symbolizer::set_halo_fill) .add_property("halo_radius",&text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius) ; }
Check SHOW_WARNINGS macro in example
#include <boost/config.hpp> struct Foo { char x; #include <leathers/push> #include <leathers/padded> long y; #include <leathers/pop> }; int main() { // struct Foo must be used, otherwise there will be no warning (clang) return static_cast<int>(Foo().y); }
#include <boost/config.hpp> struct Foo { char x; #include <leathers/push> #if !defined(SHOW_WARNINGS) # include <leathers/padded> #endif long y; #include <leathers/pop> }; int main() { // struct Foo must be used, otherwise there will be no warning (clang) return static_cast<int>(Foo().y); }
Add unit test for ControlTask
// 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 <Utils/TestUtils.hpp> #include "gtest/gtest.h" #include <hspp/Cards/Minion.hpp> #include <hspp/Managers/GameAgent.hpp> #include <hspp/Tasks/SimpleTasks/ControlTask.hpp> using namespace Hearthstonepp; using namespace SimpleTasks; using namespace TestUtils; TEST(ControlTask, GetTaskID) { const ControlTask control(EntityType::TARGET); EXPECT_EQ(control.GetTaskID(), +TaskID::CONTROL); }
// 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 <Utils/TestUtils.hpp> #include "gtest/gtest.h" #include <hspp/Cards/Minion.hpp> #include <hspp/Managers/GameAgent.hpp> #include <hspp/Tasks/SimpleTasks/ControlTask.hpp> using namespace Hearthstonepp; using namespace SimpleTasks; using namespace TestUtils; TEST(ControlTask, GetTaskID) { const ControlTask control(EntityType::TARGET); EXPECT_EQ(control.GetTaskID(), +TaskID::CONTROL); } TEST(ControlTask, Run) { GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); std::vector<Card> cards; cards.reserve(5); const std::string name = "test"; for (size_t i = 0; i < 5; ++i) { const auto id = static_cast<char>(i + 0x30); cards.emplace_back(GenerateMinionCard(name + id, 1, 1)); PlayMinionCard(player1, cards[i]); PlayMinionCard(player2, cards[i]); } ControlTask control(EntityType::TARGET); control.SetTarget(player2.GetField()[0]); MetaData result = control.Run(player1); EXPECT_EQ(result, MetaData::CONTROL_SUCCESS); EXPECT_EQ(player1.GetField().size(), 6u); EXPECT_EQ(player2.GetField().size(), 4u); }
Use a faster SPI clock to the LCD
#include <avr/io.h> #include "lcd.h" LCD5110 myGLCD; void LCD_init(void) { /* Set MOSI and SCK output */ DDRB |= (1<<PB3)|(1<<PB5); /* Enable SPI, Master, CPOL=1, CPHA=1 */ /* Also: MSB first, clock=fosc/4 */ SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPOL)|(1<<CPHA) | 3; /* Set the pins for DC, RST and CS to output */ DDRB |= (1<<PB0) | (1<<PB2); DDRC |= (1<<PC0); myGLCD.InitLCD(0x46); }
#include <avr/io.h> #include "lcd.h" LCD5110 myGLCD; void LCD_init(void) { /* Set MOSI and SCK output */ DDRB |= (1<<PB3)|(1<<PB5); /* Enable SPI, Master, CPOL=1, CPHA=1 */ /* Also: MSB first, clock=fosc/4 */ SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPOL)|(1<<CPHA) | (1<<SPR0); /* Set the pins for DC, RST and CS to output */ DDRB |= (1<<PB0) | (1<<PB2); DDRC |= (1<<PC0); myGLCD.InitLCD(0x46); }
Check `parent` for `nullptr`. Cleaning up code.
#include "chunk.hpp" #include "chunk_master.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" namespace yli { namespace ontology { void Chunk::bind_to_parent() { // requirements: // `this->parent` must not be `nullptr`. yli::ontology::ChunkMaster* const chunk_master = this->parent; if (chunk_master == nullptr) { std::cerr << "ERROR: `Chunk::bind_to_parent`: `chunk_master` is `nullptr`!\n"; return; } // get `childID` from the `ChunkMaster` and set pointer to this `Chunk`. chunk_master->bind_chunk(this); } Chunk::~Chunk() { // destructor. // set pointer to this `Chunk` to nullptr. this->parent->set_chunk_pointer(this->childID, nullptr); } void Chunk::render() { if (this->vram_buffer_in_use) { // Render this `Chunk`. // If any vertex of the `Chunk` has changed, the vertex data // of the `Chunk` needs to be reconstructed before rendering. } } } }
#include "chunk.hpp" #include "chunk_master.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" namespace yli { namespace ontology { void Chunk::bind_to_parent() { // requirements: // `this->parent` must not be `nullptr`. yli::ontology::ChunkMaster* const chunk_master = this->parent; if (chunk_master == nullptr) { std::cerr << "ERROR: `Chunk::bind_to_parent`: `chunk_master` is `nullptr`!\n"; return; } // get `childID` from the `ChunkMaster` and set pointer to this `Chunk`. chunk_master->bind_chunk(this); } Chunk::~Chunk() { // destructor. // // requirements: // `this->parent` must not be `nullptr`. yli::ontology::ChunkMaster* const chunk_master = this->parent; if (chunk_master == nullptr) { std::cerr << "ERROR: `Chunk::~Chunk`: `chunk_master` is `nullptr`!\n"; return; } chunk_master->unbind_chunk(this->childID); } void Chunk::render() { if (this->vram_buffer_in_use) { // Render this `Chunk`. // If any vertex of the `Chunk` has changed, the vertex data // of the `Chunk` needs to be reconstructed before rendering. } } } }
Add a way of Input and program loop.
// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h> using namespace std; int main() { }
// Native C++ Libraries #include <iostream> #include <string> // C++ Interpreter Libraries #include <Console.h> using namespace std; int main() { RESTART: string input = ""; getline(cin, input); cin.ignore(); goto RESTART; }
Fix unused variable warning in compiler/debug.cpp.
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // debug.cpp: Debugging utilities. #include "compiler/translator/compilerdebug.h" #include <stdarg.h> #include <stdio.h> #include "compiler/translator/InitializeParseContext.h" #include "compiler/translator/ParseContext.h" static const int kTraceBufferLen = 1024; #ifdef TRACE_ENABLED extern "C" { void Trace(const char *format, ...) { if (!format) return; TParseContext* parseContext = GetGlobalParseContext(); if (parseContext) { char buf[kTraceBufferLen]; va_list args; va_start(args, format); vsnprintf(buf, kTraceBufferLen, format, args); va_end(args); parseContext->trace(buf); } } } // extern "C" #endif // TRACE_ENABLED
// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // debug.cpp: Debugging utilities. #include "compiler/translator/compilerdebug.h" #include <stdarg.h> #include <stdio.h> #include "compiler/translator/InitializeParseContext.h" #include "compiler/translator/ParseContext.h" #ifdef TRACE_ENABLED static const int kTraceBufferLen = 1024; extern "C" { void Trace(const char *format, ...) { if (!format) return; TParseContext* parseContext = GetGlobalParseContext(); if (parseContext) { char buf[kTraceBufferLen]; va_list args; va_start(args, format); vsnprintf(buf, kTraceBufferLen, format, args); va_end(args); parseContext->trace(buf); } } } // extern "C" #endif // TRACE_ENABLED
Fix bug involving printing 'zeroed' matrices
#include <miniMAT/util/NumDigits.hpp> #include <cmath> namespace miniMAT { namespace util { int NumDigits(double num) { return log10(num) + 1; } } }
#include <miniMAT/util/NumDigits.hpp> #include <cmath> namespace miniMAT { namespace util { int NumDigits(double num) { return num == 0 ? 1 : fabs(log10(num)) + 1; } } }
Allow multiple commands to be sent to the server
#include "RestServer.h" #include <qhttpserver.hpp> #include <qhttpserverrequest.hpp> #include <qhttpserverresponse.hpp> #include <QLoggingCategory> Q_LOGGING_CATEGORY(REST, "ledify.restserver", QtWarningMsg) using namespace qhttp::server; RestServer::RestServer(QObject *parent) : QObject(parent) { m_server = new QHttpServer(this); m_server->listen(QHostAddress::Any, 8033, [this] (QHttpRequest* req, QHttpResponse* res) { emit requestReceived(req, res); }); if ( m_server->isListening() ) { qCDebug(REST, "Started REST server"); } else { qCWarning(REST, "Failed to start REST server"); } } void RestServer::requestReceived(QHttpRequest *req, QHttpResponse *res) { QString urlString = req->url().toString(); if (urlString.size() < 2) { res->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE); res->end("Send me more!\n"); return; } auto command = urlString.mid(1); qCDebug(REST) << "Received command" << command; res->setStatusCode(qhttp::ESTATUS_OK); res->end(m_callback(command).toUtf8()); }
#include "RestServer.h" #include <qhttpserver.hpp> #include <qhttpserverrequest.hpp> #include <qhttpserverresponse.hpp> #include <QLoggingCategory> Q_LOGGING_CATEGORY(REST, "ledify.restserver", QtWarningMsg) using namespace qhttp::server; RestServer::RestServer(QObject *parent) : QObject(parent) { m_server = new QHttpServer(this); m_server->listen(QHostAddress::Any, 8033, [this] (QHttpRequest* req, QHttpResponse* res) { emit requestReceived(req, res); }); if ( m_server->isListening() ) { qCDebug(REST, "Started REST server"); } else { qCWarning(REST, "Failed to start REST server"); } } void RestServer::requestReceived(QHttpRequest *req, QHttpResponse *res) { QString urlString = req->url().toString(); if (urlString.size() < 2) { res->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE); res->end("Send me more!\n"); return; } auto commands = urlString.mid(1); QByteArray responses = ""; foreach(auto command, commands.split("+", QString::SplitBehavior::SkipEmptyParts)) { qCDebug(REST) << "Received command" << command; responses += m_callback(command).toUtf8() + ";"; } res->setStatusCode(qhttp::ESTATUS_OK); res->end(responses); }
Fix a layering violation introduced in r177705.
//===--- OpenMPKinds.cpp - Token Kinds Support ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file implements the OpenMP enum and support functions. /// //===----------------------------------------------------------------------===// #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Lex/Token.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace clang; OpenMPDirectiveKind clang::getOpenMPDirectiveKind(StringRef Str) { return llvm::StringSwitch<OpenMPDirectiveKind>(Str) #define OPENMP_DIRECTIVE(Name) \ .Case(#Name, OMPD_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPD_unknown); } const char *clang::getOpenMPDirectiveName(OpenMPDirectiveKind Kind) { assert(Kind < NUM_OPENMP_DIRECTIVES); switch (Kind) { case OMPD_unknown: return ("unknown"); #define OPENMP_DIRECTIVE(Name) \ case OMPD_##Name : return #Name; #include "clang/Basic/OpenMPKinds.def" default: break; } llvm_unreachable("Invalid OpenMP directive kind"); }
//===--- OpenMPKinds.cpp - Token Kinds Support ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file implements the OpenMP enum and support functions. /// //===----------------------------------------------------------------------===// #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace clang; OpenMPDirectiveKind clang::getOpenMPDirectiveKind(StringRef Str) { return llvm::StringSwitch<OpenMPDirectiveKind>(Str) #define OPENMP_DIRECTIVE(Name) \ .Case(#Name, OMPD_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPD_unknown); } const char *clang::getOpenMPDirectiveName(OpenMPDirectiveKind Kind) { assert(Kind < NUM_OPENMP_DIRECTIVES); switch (Kind) { case OMPD_unknown: return ("unknown"); #define OPENMP_DIRECTIVE(Name) \ case OMPD_##Name : return #Name; #include "clang/Basic/OpenMPKinds.def" default: break; } llvm_unreachable("Invalid OpenMP directive kind"); }
Add missing include (fixes compile failure with gcc 4.7).
// vim:sw=2:ai /* * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved. * See COPYRIGHT.txt for details. */ #include <stdlib.h> #include <stdio.h> #include <syslog.h> #include "fatal.hpp" namespace dena { const int opt_syslog = LOG_ERR | LOG_PID | LOG_CONS; void fatal_exit(const std::string& message) { fprintf(stderr, "FATAL_EXIT: %s\n", message.c_str()); syslog(opt_syslog, "FATAL_EXIT: %s", message.c_str()); _exit(1); } void fatal_abort(const std::string& message) { fprintf(stderr, "FATAL_COREDUMP: %s\n", message.c_str()); syslog(opt_syslog, "FATAL_COREDUMP: %s", message.c_str()); abort(); } };
// vim:sw=2:ai /* * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved. * See COPYRIGHT.txt for details. */ #include <stdlib.h> #include <stdio.h> #include <syslog.h> #include <unistd.h> #include "fatal.hpp" namespace dena { const int opt_syslog = LOG_ERR | LOG_PID | LOG_CONS; void fatal_exit(const std::string& message) { fprintf(stderr, "FATAL_EXIT: %s\n", message.c_str()); syslog(opt_syslog, "FATAL_EXIT: %s", message.c_str()); _exit(1); } void fatal_abort(const std::string& message) { fprintf(stderr, "FATAL_COREDUMP: %s\n", message.c_str()); syslog(opt_syslog, "FATAL_COREDUMP: %s", message.c_str()); abort(); } };
Modify the way of GambilingTable construct.
/* * Podrios.cpp * * Created on: 2014年10月23日 * Author: nemo */ #include "GameTable/GamblingTable.h" #include <iostream> using namespace std; int main() { cout << "Start Podrios." << endl; GamblingTable *gamblingTable_Ptr = new GamblingTable(); return 0; }
/* * Podrios.cpp * * Created on: 2014年10月23日 * Author: nemo */ #include "GameTable/GamblingTable.h" #include <iostream> using namespace std; int main() { cout << "Start Podrios." << endl; GamblingTable gamblingTable; return 0; }
Check for negative duration in ThreadSleep on Windows
// Copyright (c) 2011, Christian Rorvik // Distributed under the Simplified BSD License (See accompanying file LICENSE.txt) #include "crunch/concurrency/yield.hpp" #include <windows.h> namespace Crunch { namespace Concurrency { void ThreadYield() { SwitchToThread(); } void ThreadSleep(Duration duration) { Sleep(static_cast<DWORD>(duration.GetTotalMilliseconds())); } }}
// Copyright (c) 2011, Christian Rorvik // Distributed under the Simplified BSD License (See accompanying file LICENSE.txt) #include "crunch/concurrency/yield.hpp" #include <windows.h> namespace Crunch { namespace Concurrency { void ThreadYield() { ::SwitchToThread(); } void ThreadSleep(Duration duration) { if (duration.IsNegative()) return; ::Sleep(static_cast<DWORD>(duration.GetTotalMilliseconds())); } }}
Fix windows/mac builds broken by r333182.
//===-- SystemInitializerLLGS.cpp -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SystemInitializerLLGS.h" #if defined(__APPLE__) #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h" using HostObjectFile = lldb_private::ObjectFileMachO; #elif defined(_WIN32) #include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h" using HostObjectFile = lldb_private::ObjectFilePECOFF; #else #include "Plugins/ObjectFile/ELF/ObjectFileELF.h" using HostObjectFile = ObjectFileELF; #endif using namespace lldb_private; void SystemInitializerLLGS::Initialize() { SystemInitializerCommon::Initialize(); HostObjectFile::Initialize(); } void SystemInitializerLLGS::Terminate() { HostObjectFile::Terminate(); SystemInitializerCommon::Terminate(); }
//===-- SystemInitializerLLGS.cpp -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SystemInitializerLLGS.h" #if defined(__APPLE__) #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h" using HostObjectFile = ObjectFileMachO; #elif defined(_WIN32) #include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h" using HostObjectFile = ObjectFilePECOFF; #else #include "Plugins/ObjectFile/ELF/ObjectFileELF.h" using HostObjectFile = ObjectFileELF; #endif using namespace lldb_private; void SystemInitializerLLGS::Initialize() { SystemInitializerCommon::Initialize(); HostObjectFile::Initialize(); } void SystemInitializerLLGS::Terminate() { HostObjectFile::Terminate(); SystemInitializerCommon::Terminate(); }
Check if invocation of a closure failed due to a compilation error
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sky/engine/tonic/dart_invoke.h" #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "sky/engine/tonic/dart_error.h" namespace blink { bool DartInvokeAppField(Dart_Handle target, Dart_Handle name, int number_of_arguments, Dart_Handle* arguments) { TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppField"); return LogIfError(Dart_Invoke(target, name, number_of_arguments, arguments)); } bool DartInvokeAppClosure(Dart_Handle closure, int number_of_arguments, Dart_Handle* arguments) { TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppClosure"); return LogIfError( Dart_InvokeClosure(closure, number_of_arguments, arguments)); } } // namespace blink
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sky/engine/tonic/dart_invoke.h" #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "sky/engine/tonic/dart_error.h" namespace blink { bool DartInvokeAppField(Dart_Handle target, Dart_Handle name, int number_of_arguments, Dart_Handle* arguments) { TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppField"); return LogIfError(Dart_Invoke(target, name, number_of_arguments, arguments)); } bool DartInvokeAppClosure(Dart_Handle closure, int number_of_arguments, Dart_Handle* arguments) { TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppClosure"); Dart_Handle handle = Dart_InvokeClosure(closure, number_of_arguments, arguments); bool result = LogIfError(handle); CHECK(!Dart_IsCompilationError(handle)); return result; } } // namespace blink
Add an explicit -std=c++14 to this test.
// RUN: %clang_cc1 -debug-info-kind=limited -triple %itanium_abi_triple \ // RUN: -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s template <typename T> void b(T) {} void c() { // CHECK: !DISubprogram(name: "b<(lambda at // CHECK-SAME: SOURCE_ROOT // CHECK-SAME: [[@LINE+1]]:{{[0-9]+}})>" b([]{}); }
// RUN: %clang_cc1 -std=c++14 -debug-info-kind=limited \ // RUN: -triple %itanium_abi_triple \ // RUN: -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s template <typename T> void b(T) {} void c() { // CHECK: !DISubprogram(name: "b<(lambda at // CHECK-SAME: SOURCE_ROOT // CHECK-SAME: [[@LINE+1]]:{{[0-9]+}})>" b([]{}); }
Write output file to temp directory. The tests shouldn't assume that they can write to the current working directory.
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=a %S/Inputs/explicit-build-prefer-self/map -o a.pcm // RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=b %S/Inputs/explicit-build-prefer-self/map -o b.pcm
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=a %S/Inputs/explicit-build-prefer-self/map -o %t/a.pcm // RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=b %S/Inputs/explicit-build-prefer-self/map -o %t/b.pcm
Add range check for set program
#include "AnimationProgram.h" #include "esp_log.h" static const char* TAG = "PROGRAM"; AnimationProgram::AnimationProgram(Timer &animator) : programs(), animator(animator) { } void AnimationProgram::putAnimation(uint8_t index, Animation *animation) { programs[index] = animation; } void AnimationProgram::drawFrame() { // fixme check index programs[index]->drawFrame(); } void AnimationProgram::setProgram(uint8_t index) { ESP_LOGI(TAG, "set program %d", index); this->index = index; animator.setIntervalSecs(index == 4 || index == 5 ? .3 : .03); }
#include "AnimationProgram.h" #include "esp_log.h" static const char* TAG = "AnimationProgram"; AnimationProgram::AnimationProgram(Timer &animator) : programs(), animator(animator) { } void AnimationProgram::putAnimation(uint8_t index, Animation *animation) { programs[index] = animation; } void AnimationProgram::drawFrame() { // fixme check index programs[index]->drawFrame(); } void AnimationProgram::setProgram(uint8_t index) { ESP_LOGI(TAG, "set program %d", index); if (index < programs.size()) { this->index = index; animator.setIntervalSecs(index == 4 || index == 5 ? .3 : .03); } else { ESP_LOGW(TAG, "set program ignored: out of range: 0-%d", programs.size() - 1); } }
Make functions used in tests static
#include "catch.hpp" #include <lua.hpp> #include <luwra.hpp> int test_function_1(int a, int b) { return a - b; } int test_function_2(int a, int b, int c) { return a + b * c; } void test_function_3(int) { } TEST_CASE("stack_interaction") { lua_State* state = luaL_newstate(); luwra::push(state, 1); luwra::push(state, 2); luwra::push(state, 4); // Redundant function luwra::apply(state, test_function_3); // Absolute index REQUIRE(luwra::apply(state, test_function_1) == -1); REQUIRE(luwra::apply(state, 1, test_function_1) == -1); REQUIRE(luwra::apply(state, test_function_2) == 9); REQUIRE(luwra::apply(state, 1, test_function_2) == 9); // Relative index REQUIRE(luwra::apply(state, -2, test_function_1) == -2); REQUIRE(luwra::apply(state, -3, test_function_1) == -1); REQUIRE(luwra::apply(state, -3, test_function_2) == 9); lua_close(state); }
#include "catch.hpp" #include <lua.hpp> #include <luwra.hpp> static int test_function_1(int a, int b) { return a - b; } static int test_function_2(int a, int b, int c) { return a + b * c; } static void test_function_3(int) { } TEST_CASE("stack_interaction") { lua_State* state = luaL_newstate(); luwra::push(state, 1); luwra::push(state, 2); luwra::push(state, 4); // Redundant function luwra::apply(state, test_function_3); // Absolute index REQUIRE(luwra::apply(state, test_function_1) == -1); REQUIRE(luwra::apply(state, 1, test_function_1) == -1); REQUIRE(luwra::apply(state, test_function_2) == 9); REQUIRE(luwra::apply(state, 1, test_function_2) == 9); // Relative index REQUIRE(luwra::apply(state, -2, test_function_1) == -2); REQUIRE(luwra::apply(state, -3, test_function_1) == -1); REQUIRE(luwra::apply(state, -3, test_function_2) == 9); lua_close(state); }
Remove redundant brackets and lines of code
#include "utils/distance.hpp" // Returns the minimum distance (straight line) between two points double distance(cv::Point one, cv::Point two) { return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2)); } // Returns the two dimensional distance between the components of two points double distance2D(double comp1, double comp2) { return std::abs(comp2 - comp1); } double getShortestDistance (cv::Point2f rectPoints[4], double focalLen, int dist, int height) { // 20 inches real width int realWidth = 20; int pixelWidth = 0; double theta = 0; double d = 0; int length = static_cast<int>(distance (rectPoints[0], rectPoints[3])); int width = static_cast<int>(distance (rectPoints[0], rectPoints[1])); if (length > width) { pixelWidth = length; } else { pixelWidth = width; } d = (realWidth * focalLen) / pixelWidth; theta = std::asin(static_cast<double>(height) / dist) * 180 / PI; return d; }
#include "utils/distance.hpp" // Returns the minimum distance (straight line) between two points double distance(cv::Point one, cv::Point two) { return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2)); } double getShortestDistance (cv::Point2f rectPoints[4], double focalLen, int dist, int height) { // The target's base is 20 inches wide in real life int realWidth = 20; int pixelWidth = 0; double theta = 0; double d = 0; int length = static_cast<int>(distance (rectPoints[0], rectPoints[3])); int width = static_cast<int>(distance (rectPoints[0], rectPoints[1])); if (length > width) pixelWidth = length; else pixelWidth = width; d = (realWidth * focalLen) / pixelWidth; return d; }
Revert back to older Catch2
// // Created by Adam Getchell on 2017-12-02. // #define CATCH_CONFIG_RUNNER #include <catch2/catch.hpp> int main( int argc, char* argv[] ) { Catch::Session session; // There must be exactly one instance // writing to session.configData() here sets defaults // this is the preferred way to set them int returnCode = session.applyCommandLine( argc, argv ); if( returnCode != 0 ) // Indicates a command line error return returnCode; // writing to session.configData() or session.Config() here // overrides command line args // only do this if you know you need to int numFailed = session.run(); // numFailed is clamped to 255 as some unices only use the lower 8 bits. // This clamping has already been applied, so just return it here // You can also do any post run clean-up here return numFailed; }
// // Created by Adam Getchell on 2017-12-02. // #define CATCH_CONFIG_RUNNER #include "catch.hpp" int main( int argc, char* argv[] ) { Catch::Session session; // There must be exactly one instance // writing to session.configData() here sets defaults // this is the preferred way to set them int returnCode = session.applyCommandLine( argc, argv ); if( returnCode != 0 ) // Indicates a command line error return returnCode; // writing to session.configData() or session.Config() here // overrides command line args // only do this if you know you need to int numFailed = session.run(); // numFailed is clamped to 255 as some unices only use the lower 8 bits. // This clamping has already been applied, so just return it here // You can also do any post run clean-up here return numFailed; }
Fix chrome compile after the switch from Task to base::Bind.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/ui_controls.h" #include "base/logging.h" #include "views/view.h" namespace ui_controls { bool SendKeyPress(gfx::NativeWindow window, ui::KeyboardCode key, bool control, bool shift, bool alt, bool command) { NOTIMPLEMENTED(); return true; } bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, ui::KeyboardCode key, bool control, bool shift, bool alt, bool command, Task* task) { NOTIMPLEMENTED(); return true; } bool SendMouseMove(long x, long y) { NOTIMPLEMENTED(); return true; } bool SendMouseMoveNotifyWhenDone(long x, long y, Task* task) { NOTIMPLEMENTED(); return true; } bool SendMouseEvents(MouseButton type, int state) { NOTIMPLEMENTED(); return true; } bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, Task* task) { NOTIMPLEMENTED(); return true; } bool SendMouseClick(MouseButton type) { return SendMouseEvents(type, UP | DOWN); } void MoveMouseToCenterAndPress(views::View* view, MouseButton button, int state, Task* task) { NOTIMPLEMENTED(); } } // namespace ui_controls
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/ui_controls.h" #include "base/logging.h" #include "views/view.h" namespace ui_controls { bool SendKeyPress(gfx::NativeWindow window, ui::KeyboardCode key, bool control, bool shift, bool alt, bool command) { NOTIMPLEMENTED(); return true; } bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, ui::KeyboardCode key, bool control, bool shift, bool alt, bool command, const base::Closure& task) { NOTIMPLEMENTED(); return true; } bool SendMouseMove(long x, long y) { NOTIMPLEMENTED(); return true; } bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& task) { NOTIMPLEMENTED(); return true; } bool SendMouseEvents(MouseButton type, int state) { NOTIMPLEMENTED(); return true; } bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, const base::Closure& task) { NOTIMPLEMENTED(); return true; } bool SendMouseClick(MouseButton type) { return SendMouseEvents(type, UP | DOWN); } void MoveMouseToCenterAndPress(views::View* view, MouseButton button, int state, const base::Closure& task) { NOTIMPLEMENTED(); } } // namespace ui_controls
Add implementation of a basic game loop.
#include "Game.hpp" namespace arduino_pong { void Game::run() { while(true) { gameField_.update(); gameField_.render(); } } } // namespace arduino_pong
#include "Game.hpp" #include <Arduino.h> namespace { constexpr uint32_t MsPerUpdate = 16; } // namespace namespace arduino_pong { void Game::run() { uint32_t previous = millis(); uint32_t lag = 0; while(true) { uint32_t current = millis(); uint32_t elapsed = current - previous; previous = current; lag += elapsed; while(lag >= MsPerUpdate) { gameField_.update(); lag -= MsPerUpdate; } gameField_.render(); } } } // namespace arduino_pong
Quit the application when qml engine wants to.
#include "client.h" #include "tests/test.h" #include <QGuiApplication> #include <QQuickView> #include <QQmlContext> #include <QtQml> #include <QUrl> int main(int argc, char* argv[]) { QGuiApplication app(argc, argv); qmlRegisterUncreatableType<AbstractTest>("mplane", 1, 0, "AbstractTest", "abstract class"); qmlRegisterUncreatableType<Client>("mplane", 1, 0, "Client", "This is a singleton"); qmlRegisterUncreatableType<TestScheduler>("mplane", 1, 0, "TestScheduler", "uncreatable type"); QQuickView view; QQmlContext* rootContext = view.rootContext(); rootContext->setContextProperty("client", Client::instance()); view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource( QUrl("qrc:/qml/main.qml") ); view.show(); return app.exec(); }
#include "client.h" #include "tests/test.h" #include <QGuiApplication> #include <QQuickView> #include <QQmlContext> #include <QQmlEngine> #include <QtQml> #include <QUrl> int main(int argc, char* argv[]) { QGuiApplication app(argc, argv); qmlRegisterUncreatableType<AbstractTest>("mplane", 1, 0, "AbstractTest", "abstract class"); qmlRegisterUncreatableType<Client>("mplane", 1, 0, "Client", "This is a singleton"); qmlRegisterUncreatableType<TestScheduler>("mplane", 1, 0, "TestScheduler", "uncreatable type"); QQuickView view; QQmlEngine* engine = view.engine(); QObject::connect(engine, SIGNAL(quit()), &app, SLOT(quit())); QQmlContext* rootContext = view.rootContext(); rootContext->setContextProperty("client", Client::instance()); view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource( QUrl("qrc:/qml/main.qml") ); view.show(); return app.exec(); }
Fix the name of the option
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include "timing.hpp" using namespace eddic; timing_timer::timing_timer(timing_system& system, const std::string& name) : system(system), name(name) { //Nothing } timing_timer::~timing_timer(){ system.register_timing(name, timer.elapsed()); } timing_system::timing_system(std::shared_ptr<Configuration> configuration) : configuration(configuration) { //Nothing } timing_system::~timing_system(){ if(configuration->option_defined("timing")){ for(auto& timing : timings){ std::cout << timing.first << ":" << timing.second << "ms" << std::endl; } } } void timing_system::register_timing(std::string name, double time){ timings[name] += time; }
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include "timing.hpp" using namespace eddic; timing_timer::timing_timer(timing_system& system, const std::string& name) : system(system), name(name) { //Nothing } timing_timer::~timing_timer(){ system.register_timing(name, timer.elapsed()); } timing_system::timing_system(std::shared_ptr<Configuration> configuration) : configuration(configuration) { //Nothing } timing_system::~timing_system(){ if(configuration->option_defined("time")){ for(auto& timing : timings){ std::cout << timing.first << ":" << timing.second << "ms" << std::endl; } } } void timing_system::register_timing(std::string name, double time){ timings[name] += time; }
Upgrade Blink to milliseconds-based last modified filetimes, part 4.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // WebKit now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) { web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); web_file_info->modificationTimeMS = std::numeric_limits<double>::quiet_NaN(); } else { web_file_info->modificationTime = file_info.last_modified.ToDoubleT(); web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime(); } web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // Blink now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) { web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); web_file_info->modificationTimeMS = std::numeric_limits<double>::quiet_NaN(); } else { web_file_info->modificationTime = file_info.last_modified.ToJsTime(); web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime(); } web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content