Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Disable test that uses profile runtime on Windows. | // RUN: %clangxx_asan -coverage -O0 %s -o %t
// RUN: %env_asan_opts=check_initialization_order=1 %run %t 2>&1 | FileCheck %s
// XFAIL: android
#include <stdio.h>
int foo() { return 1; }
int XXX = foo();
int main() {
printf("PASS\n");
// CHECK: PASS
}
| // RUN: %clangxx_asan -coverage -O0 %s -o %t
// RUN: %env_asan_opts=check_initialization_order=1 %run %t 2>&1 | FileCheck %s
// XFAIL: android
// We don't really support running tests using profile runtime on Windows.
// UNSUPPORTED: win32
#include <stdio.h>
int foo() { return 1; }
int XXX = foo();
int main() {
printf("PASS\n");
// CHECK: PASS
}
|
Fix an incorrect iteration over EGL attributes. | //
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "libEGL/AttributeMap.h"
namespace egl
{
AttributeMap::AttributeMap()
{
}
AttributeMap::AttributeMap(const EGLint *attributes)
{
for (const EGLint *curAttrib = attributes; curAttrib[0] != EGL_NONE; curAttrib++)
{
insert(curAttrib[0], curAttrib[1]);
}
}
void AttributeMap::insert(EGLint key, EGLint value)
{
mAttributes[key] = value;
}
bool AttributeMap::contains(EGLint key) const
{
return (mAttributes.find(key) != mAttributes.end());
}
EGLint AttributeMap::get(EGLint key, EGLint defaultValue) const
{
std::map<EGLint, EGLint>::const_iterator iter = mAttributes.find(key);
return (mAttributes.find(key) != mAttributes.end()) ? iter->second : defaultValue;
}
}
| //
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "libEGL/AttributeMap.h"
namespace egl
{
AttributeMap::AttributeMap()
{
}
AttributeMap::AttributeMap(const EGLint *attributes)
{
for (const EGLint *curAttrib = attributes; curAttrib[0] != EGL_NONE; curAttrib += 2)
{
insert(curAttrib[0], curAttrib[1]);
}
}
void AttributeMap::insert(EGLint key, EGLint value)
{
mAttributes[key] = value;
}
bool AttributeMap::contains(EGLint key) const
{
return (mAttributes.find(key) != mAttributes.end());
}
EGLint AttributeMap::get(EGLint key, EGLint defaultValue) const
{
std::map<EGLint, EGLint>::const_iterator iter = mAttributes.find(key);
return (mAttributes.find(key) != mAttributes.end()) ? iter->second : defaultValue;
}
}
|
Remove DCHECK on the compositor in OnEnableHidingTopControls. | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/render_view_impl.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "cc/trees/layer_tree_host.h"
#include "content/renderer/gpu/render_widget_compositor.h"
namespace content {
void RenderViewImpl::OnUpdateTopControlsState(bool enable_hiding,
bool enable_showing,
bool animate) {
DCHECK(compositor_);
if (compositor_) {
compositor_->UpdateTopControlsState(enable_hiding, enable_showing, animate);
}
}
} // namespace content
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/render_view_impl.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "cc/trees/layer_tree_host.h"
#include "content/renderer/gpu/render_widget_compositor.h"
namespace content {
void RenderViewImpl::OnUpdateTopControlsState(bool enable_hiding,
bool enable_showing,
bool animate) {
// TODO(tedchoc): Investigate why messages are getting here before the
// compositor has been initialized.
LOG_IF(WARNING, !compositor_) << "OnUpdateTopControlsState was unhandled.";
if (compositor_)
compositor_->UpdateTopControlsState(enable_hiding, enable_showing, animate);
}
} // namespace content
|
Add version command line option | #include "main.h"
#include <boost/program_options.hpp>
#include <iostream>
namespace po = boost::program_options;
using namespace std;
int main(int argc, char **argv)
{
po::options_description program_desc("Simplicity window manager");
program_desc.add_options()
("help", "Display usage")
;
po::variables_map args;
po::store(po::parse_command_line(argc, argv, program_desc), args);
po::notify(args);
if (args.count("help"))
{
cout << program_desc << endl;
return 1;
}
return 0;
}
| #include "main.h"
#include <boost/program_options.hpp>
#include <iostream>
namespace po = boost::program_options;
using namespace std;
void print_version(void);
int main(int argc, char **argv)
{
po::options_description program_desc("Simplicity window manager");
program_desc.add_options()
("help", "Display usage")
("version", "Print simplicity version")
;
po::variables_map args;
po::store(po::parse_command_line(argc, argv, program_desc), args);
po::notify(args);
if (args.count("help"))
{
cout << program_desc << endl;
return 1;
}
if (args.count("version"))
{
print_version();
return 0;
}
return 0;
}
void print_version(void)
{
cout << PACKAGE_STRING << endl;
cout << "Copyright (C) 2014 James Durand\n"
"This is free software; see the source for copying conditions.\n"
"There is NO warranty." << endl;
}
|
Add the barebones logic needed to import a scene into Assimp and start exporting it | /**
* Assimp2XML3D
*
* Copyright (c)2015, Christian Schlinkmann
*
*
**/
#include <assimp/version.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>
#include <iostream>
int invalidUsageExit() {
std::cout << "usage: assimp2xml3d [FLAGS] inputFile [outputFile]" << std::endl;
return -1;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
return invalidUsageExit();
}
} | /**
* Assimp2XML3D
*
* Copyright (c)2015, Christian Schlinkmann
*
*
**/
#include <assimp/version.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>
#include <iostream>
extern Assimp::Exporter::ExportFormatEntry Assimp2XML3D_desc;
int invalidUsageExit() {
std::cout << "usage: assimp2xml3d [FLAGS] inputFile [outputFile]" << std::endl;
return -1;
}
int main(int argc, char *argv[]) {
if (argc < 3) {
return invalidUsageExit();
}
const char* input = argv[1], *output = argv[2];
Assimp::Importer importer;
importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);
const aiScene* const scene = importer.ReadFile(input, aiProcessPreset_TargetRealtime_MaxQuality);
if (!scene) {
std::cerr << "Assimp: Could not read file " << input << std::endl;
return -1;
}
std::cout << "Assimp read file successfully";
Assimp::Exporter exporter;
exporter.RegisterExporter(Assimp2XML3D_desc);
exporter.Export(scene, "xml", output);
}
|
Add error handling to sdl init. |
#include <iostream>
#include <stdexcept>
#include <string>
#include "application.hpp"
#include <GL/glew.h>
void init_glew()
{
GLenum err = glewInit();
if (GLEW_OK != err)
{
throw std::runtime_error(reinterpret_cast<const char *>(glewGetErrorString(err)));
}
}
int main(int argc, char const *argv[])
{
SDL_Init(SDL_INIT_EVERYTHING);
try
{
Application atlasTest {800, 600, "Atlas Tests"};
init_glew();
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
while (atlasTest.process_events())
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
atlasTest.swap();
}
} catch (std::runtime_error &err) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Runtime Error", err.what(), nullptr);
return 1;
}
return 0;
}
|
#include <iostream>
#include <stdexcept>
#include <string>
#include "application.hpp"
#include <GL/glew.h>
void init_sdl()
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
throw std::runtime_error(SDL_GetError());
}
}
void init_glew()
{
GLenum err = glewInit();
if (GLEW_OK != err)
{
throw std::runtime_error(reinterpret_cast<const char *>(glewGetErrorString(err)));
}
}
void run()
{
init_sdl();
Application atlasTest {800, 600, "Atlas Tests"};
init_glew();
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
while (atlasTest.process_events())
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
atlasTest.swap();
}
}
int main(int argc, char const *argv[])
{
// This is mainly is a global exception handler to show friendly messages to users.
try
{
run();
} catch (std::runtime_error &err) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Runtime Error", err.what(), nullptr);
return 1;
}
return 0;
}
|
Use std ostream instead of fprintf. | #include <cstdlib>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <proxylib/proxylib.h>
void signal_handler(int signal) {
fprintf(stderr, "Received signal %d\nExiting...\n", signal);
exit(0);
}
void install_sighandlers() {
signal(SIGHUP, SIG_IGN);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGKILL, signal_handler);
signal(SIGQUIT, signal_handler);
}
int main(int argc, char** argv) {
try {
if (argc != 2) {
std::cerr << "Usage: proxy <port>" << std::endl;
return EXIT_FAILURE;
}
install_sighandlers();
namespace socks4a = proxylib::asio::socks4a;
boost::asio::io_service io_service;
socks4a::server server(io_service, std::atoi(argv[1]));
boost::thread server_thread;
server_thread = boost::thread(boost::bind(&socks4a::server::run, &server));
server_thread.join();
// server.run();
} catch (std::exception& ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
}
return EXIT_SUCCESS;
}
| #include <cstdlib>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <proxylib/proxylib.h>
void signal_handler(int signal) {
std::cerr << "Received signal " << signal << "\nExiting..." << std::endl;
exit(0);
}
void install_sighandlers() {
signal(SIGHUP, SIG_IGN);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGKILL, signal_handler);
signal(SIGQUIT, signal_handler);
}
int main(int argc, char** argv) {
try {
if (argc != 2) {
std::cerr << "Usage: proxy <port>" << std::endl;
return EXIT_FAILURE;
}
install_sighandlers();
namespace socks4a = proxylib::asio::socks4a;
boost::asio::io_service io_service;
socks4a::server server(io_service, std::atoi(argv[1]));
boost::thread server_thread;
server_thread = boost::thread(boost::bind(&socks4a::server::run, &server));
server_thread.join();
// server.run();
} catch (std::exception& ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
}
return EXIT_SUCCESS;
}
|
Copy logfile when crashed so users don't have to do so manually |
#include "crash_reporting.h"
#include "infrastructure/breakpad.h"
#include <fmt/format.h>
#include "platform/windows.h"
Breakpad::Breakpad(const std::wstring &crashDumpFolder, bool fullDump)
{
mHandler = std::make_unique<InProcessCrashReporting>(crashDumpFolder, fullDump, [this](const std::wstring &minidump_path) {
auto msg = fmt::format(L"Sorry! TemplePlus seems to have crashed. A crash report was written to {}.\n\n"
L"If you want to report this issue, please contact us on our forums at RPGCodex or send an email to templeplushelp@gmail.com.",
minidump_path);
if (!extraMessage().empty()) {
msg.append(extraMessage());
}
// Now starts the tedious work of reporting on this crash, heh.
MessageBox(NULL, msg.c_str(), L"TemplePlus Crashed - Oops!", MB_OK);
});
}
Breakpad::~Breakpad()
{
}
|
#include "crash_reporting.h"
#include "infrastructure/breakpad.h"
#include <fmt/format.h>
#include "platform/windows.h"
#include <infrastructure/stringutil.h>
#include <filesystem>
#include <Shlwapi.h>
namespace fs = std::filesystem;
Breakpad::Breakpad(const std::wstring &crashDumpFolder, bool fullDump)
{
mHandler = std::make_unique<InProcessCrashReporting>(crashDumpFolder, fullDump, [this, crashDumpFolder](const std::wstring &minidump_path) {
auto msg = fmt::format(L"Sorry! TemplePlus seems to have crashed. A crash report was written to {}.\n\n"
L"If you want to report this issue, please contact us on our forums at RPGCodex or send an email to templeplushelp@gmail.com.",
minidump_path);
if (!extraMessage().empty()) {
msg.append(extraMessage());
}
// Now starts the tedious work of reporting on this crash, heh.
MessageBox(NULL, msg.c_str(), L"TemplePlus Crashed - Oops!", MB_OK);
// copy the log so it doesn't get erased on next startup
try {
std::wstring logfilename = crashDumpFolder + L"TemplePlus.log";
auto logfilenameNew = fs::path(minidump_path).replace_extension("log");
std::filesystem::copy(logfilename, logfilenameNew);
}
catch (...) {
}
});
}
Breakpad::~Breakpad()
{
}
|
Check that the ExtensionFunction has a callback for attempting to send a response. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_function.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
void ExtensionFunction::SendResponse(bool success) {
if (success) {
dispatcher_->SendResponse(this);
} else {
// TODO(aa): In case of failure, send the error message to an error
// callback.
}
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_function.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
void ExtensionFunction::SendResponse(bool success) {
if (success) {
if (has_callback()) {
dispatcher_->SendResponse(this);
}
} else {
// TODO(aa): In case of failure, send the error message to an error
// callback.
}
}
|
Switch default device type to CUDA if available; now to fix runtime errors and TODO items | #include "Context.hpp"
Context* _global_ctx = nullptr;
namespace Backend {
void init_global_context() {
if (!_global_ctx)
_global_ctx = new Context;
// TODO: Add other device types (esp CUDA)
_global_ctx->device = SPIKE_DEVICE_DUMMY;
}
Context* get_current_context() {
return _global_ctx;
}
}
| #include "Context.hpp"
Context* _global_ctx = nullptr;
namespace Backend {
void init_global_context() {
if (!_global_ctx)
_global_ctx = new Context;
// TODO: Add other device types (esp CUDA)
#ifdef SPIKE_WITH_CUDA
_global_ctx->device = SPIKE_DEVICE_CUDA;
#else
_global_ctx->device = SPIKE_DEVICE_DUMMY;
#endif
}
Context* get_current_context() {
return _global_ctx;
}
}
|
Add long types to names. |
#include "JasonType.h"
using JasonType = triagens::basics::JasonType;
////////////////////////////////////////////////////////////////////////////////
/// @brief get the name for a Jason type
////////////////////////////////////////////////////////////////////////////////
char const* triagens::basics::JasonTypeName (JasonType type) {
switch (type) {
case JasonType::None: return "none";
case JasonType::Null: return "null";
case JasonType::Bool: return "bool";
case JasonType::Double: return "double";
case JasonType::String: return "string";
case JasonType::Array: return "array";
case JasonType::Object: return "object";
case JasonType::External: return "external";
case JasonType::ID: return "id";
case JasonType::ArangoDB_id: return "arangodb_id";
case JasonType::UTCDate: return "utc-date";
case JasonType::Int: return "int";
case JasonType::UInt: return "uint";
case JasonType::Binary: return "binary";
}
return "unknown";
}
|
#include "JasonType.h"
using JasonType = triagens::basics::JasonType;
////////////////////////////////////////////////////////////////////////////////
/// @brief get the name for a Jason type
////////////////////////////////////////////////////////////////////////////////
char const* triagens::basics::JasonTypeName (JasonType type) {
switch (type) {
case JasonType::None: return "none";
case JasonType::Null: return "null";
case JasonType::Bool: return "bool";
case JasonType::Double: return "double";
case JasonType::String: return "string";
case JasonType::Array: return "array";
case JasonType::ArrayLong: return "array_long";
case JasonType::Object: return "object";
case JasonType::ObjectLong: return "object_long";
case JasonType::External: return "external";
case JasonType::ID: return "id";
case JasonType::ArangoDB_id: return "arangodb_id";
case JasonType::UTCDate: return "utc-date";
case JasonType::Int: return "int";
case JasonType::UInt: return "uint";
case JasonType::Binary: return "binary";
}
return "unknown";
}
|
Fix quoting to allow shell expansion to occur for shell variables introduced by the test harness' expansion of %t. | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo '[{"directory":".","command":"clang++ -c %t/test.cpp","file":"%t/test.cpp"}]' > %t/compile_commands.json
// RUN: cp "%s" "%t/test.cpp"
// RUN: PWD="%t" clang-check "%t" "test.cpp" 2>&1|FileCheck %s
// FIXME: Make the above easier.
// CHECK: C++ requires
invalid;
// FIXME: JSON doesn't like path separator '\', on Win32 hosts.
// FIXME: clang-check doesn't like gcc driver on cygming.
// XFAIL: cygwin,mingw32,win32
| // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo "[{\"directory\":\".\",\"command\":\"clang++ -c %t/test.cpp\",\"file\":\"%t/test.cpp\"}]" > %t/compile_commands.json
// RUN: cp "%s" "%t/test.cpp"
// RUN: PWD="%t" clang-check "%t" "test.cpp" 2>&1|FileCheck %s
// FIXME: Make the above easier.
// CHECK: C++ requires
invalid;
// FIXME: JSON doesn't like path separator '\', on Win32 hosts.
// FIXME: clang-check doesn't like gcc driver on cygming.
// XFAIL: cygwin,mingw32,win32
|
Replace non-ASCII quotes from GCC with ASCII quotes. | // C++11 code with initializers.
//
// g++ -std=c++11 -pedantic -fsyntax-only cpp11.cpp
// clang++ -std=c++11 -pedantic -fsyntax-only cpp11.cpp
struct A {
int i = 0;
double j = 0.0;
};
int main() {
A a; // OK, a.i is 0 and a.j is 0.0
A b = {}; // OK, b.i is 0 and b.j is 0.0
A c = {1}; // FAIL (compilation error)
A d = {1, 2.0}; // FAIL (compilation error)
// GCC:
// error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘A’
// error: could not convert ‘{1, 2.0e+0}’ from ‘<brace-enclosed initializer list>’ to ‘A’
//
// Clang:
// error: no matching constructor for initialization of 'A'
return 0;
}
| // C++11 code with initializers.
//
// g++ -std=c++11 -pedantic -fsyntax-only cpp11.cpp
// clang++ -std=c++11 -pedantic -fsyntax-only cpp11.cpp
struct A {
int i = 0;
double j = 0.0;
};
int main() {
A a; // OK, a.i is 0 and a.j is 0.0
A b = {}; // OK, b.i is 0 and b.j is 0.0
A c = {1}; // FAIL (compilation error)
A d = {1, 2.0}; // FAIL (compilation error)
// GCC:
// error: could not convert '{1}' from '<brace-enclosed initializer list>' to 'A'
// error: could not convert '{1, 2.0e+0}' from '<brace-enclosed initializer list>' to 'A'
//
// Clang:
// error: no matching constructor for initialization of 'A'
return 0;
}
|
Make luna app boostable to reduce the start up time. | #include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
int main(int argc, char** argv)
{
// FIXME: Use the (new?) harmattan booster!!
QApplication app(argc, argv);
QDeclarativeView viewer;
viewer.setSource(QUrl("qrc:/qml/main.qml"));
viewer.showFullScreen();
return app.exec();
}
| #include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <MDeclarativeCache>
Q_DECL_EXPORT int main(int argc, char** argv)
{
QApplication* app = MDeclarativeCache::qApplication(argc, argv);
QDeclarativeView viewer;
viewer.setSource(QUrl("qrc:/qml/main.qml"));
viewer.showFullScreen();
return app->exec();
}
|
Remove ARM XFAIL from passing test | // RUN: %clangxx -O0 %s -o %t && %run %t
// XFAIL: arm-linux-gnueabi
#include <assert.h>
#include <pthread.h>
int main(void) {
pthread_mutexattr_t ma;
int res = pthread_mutexattr_init(&ma);
assert(res == 0);
res = pthread_mutexattr_setpshared(&ma, 1);
assert(res == 0);
int pshared;
res = pthread_mutexattr_getpshared(&ma, &pshared);
assert(res == 0);
assert(pshared == 1);
res = pthread_mutexattr_destroy(&ma);
assert(res == 0);
return 0;
}
| // RUN: %clangxx -O0 %s -o %t && %run %t
#include <assert.h>
#include <pthread.h>
int main(void) {
pthread_mutexattr_t ma;
int res = pthread_mutexattr_init(&ma);
assert(res == 0);
res = pthread_mutexattr_setpshared(&ma, 1);
assert(res == 0);
int pshared;
res = pthread_mutexattr_getpshared(&ma, &pshared);
assert(res == 0);
assert(pshared == 1);
res = pthread_mutexattr_destroy(&ma);
assert(res == 0);
return 0;
}
|
Fix color conversions for android | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "Color.h"
namespace facebook {
namespace react {
SharedColor colorFromComponents(ColorComponents components) {
return SharedColor(
((int)components.alpha & 0xff) << 24 |
((int)components.red & 0xff) << 16 |
((int)components.green & 0xff) << 8 |
((int)components.blue & 0xff)
);
}
ColorComponents colorComponentsFromColor(SharedColor sharedColor) {
Color color = *sharedColor;
return ColorComponents {
(float)((color >> 16) & 0xff),
(float)((color >> 8) & 0xff),
(float)((color ) & 0xff),
(float)((color >> 24) & 0xff)
};
}
} // namespace react
} // namespace facebook
| /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "Color.h"
namespace facebook {
namespace react {
SharedColor colorFromComponents(ColorComponents components) {
float ratio = 255.9999;
return SharedColor(
((int)(components.alpha * ratio) & 0xff) << 24 |
((int)(components.red * ratio) & 0xff) << 16 |
((int)(components.green * ratio) & 0xff) << 8 |
((int)(components.blue * ratio) & 0xff)
);
}
ColorComponents colorComponentsFromColor(SharedColor sharedColor) {
float ratio = 256;
Color color = *sharedColor;
return ColorComponents {
(float)((color >> 16) & 0xff) / ratio,
(float)((color >> 8) & 0xff) / ratio,
(float)((color ) & 0xff) / ratio,
(float)((color >> 24) & 0xff) / ratio
};
}
} // namespace react
} // namespace facebook
|
Initialize logging early enough to see VLOGs emitted by InitializeMediaLibraryForTesting(). (specifically, this makes ffmpeg_stubs.cc VLOGs actually get emitted if -v=1 is specified) | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/test/test_suite.h"
#include "media/base/media.h"
int main(int argc, char** argv) {
base::TestSuite suite(argc, argv);
media::InitializeMediaLibraryForTesting();
return suite.Run();
}
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/test/test_suite.h"
#include "media/base/media.h"
class TestSuiteNoAtExit : public base::TestSuite {
public:
TestSuiteNoAtExit(int argc, char** argv) : TestSuite(argc, argv, false) {}
virtual ~TestSuiteNoAtExit() {}
};
int main(int argc, char** argv) {
// By default command-line parsing happens only in TestSuite::Run(), but
// that's too late to get VLOGs and so on from
// InitializeMediaLibraryForTesting() below. Instead initialize logging
// explicitly here (and have it get re-initialized by TestSuite::Run()).
CommandLine::Init(argc, argv);
CHECK(logging::InitLogging(
NULL,
logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
logging::DONT_LOCK_LOG_FILE,
logging::APPEND_TO_OLD_LOG_FILE,
logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS));
base::AtExitManager exit_manager;
media::InitializeMediaLibraryForTesting();
return TestSuiteNoAtExit(argc, argv).Run();
}
|
Enable support for local plugins | #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//These things are used by QSettings to set up setting storage
a.setOrganizationName("EVTV");
a.setApplicationName("SavvyCAN");
a.setOrganizationDomain("evtv.me");
QSettings::setDefaultFormat(QSettings::IniFormat);
MainWindow w;
QSettings settings;
int fontSize = settings.value("Main/FontSize", 9).toUInt();
QFont sysFont = QFont(); //get default font
sysFont.setPointSize(fontSize);
a.setFont(sysFont);
w.show();
return a.exec();
}
| #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//Add a local path for Qt extensions, to allow for per-application extensions.
a.addLibraryPath("plugins");
//These things are used by QSettings to set up setting storage
a.setOrganizationName("EVTV");
a.setApplicationName("SavvyCAN");
a.setOrganizationDomain("evtv.me");
QSettings::setDefaultFormat(QSettings::IniFormat);
MainWindow w;
QSettings settings;
int fontSize = settings.value("Main/FontSize", 9).toUInt();
QFont sysFont = QFont(); //get default font
sysFont.setPointSize(fontSize);
a.setFont(sysFont);
w.show();
return a.exec();
}
|
Add type checking for boolean link types. | /*
* opencog/atoms/core/Checkers.cc
*
* Copyright (C) 2017 Linas Vepstas
* All Rights Reserved
*
* 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 <opencog/atoms/base/Atom.h>
#include <opencog/atoms/base/ClassServer.h>
using namespace opencog;
bool check_evaluatable(const Handle& bool_atom)
{
return true;
}
/* This runs when the shared lib is loaded. */
static __attribute__ ((constructor)) void init(void)
{
classserver().addValidator(BOOLEAN_LINK, check_evaluatable);
}
| /*
* opencog/atoms/core/Checkers.cc
*
* Copyright (C) 2017 Linas Vepstas
* All Rights Reserved
*
* 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 <opencog/atoms/base/Atom.h>
#include <opencog/atoms/base/ClassServer.h>
using namespace opencog;
/// Check to see if every input atom is of Evaluatable type.
bool check_evaluatable(const Handle& bool_atom)
{
for (const Handle& h: bool_atom->getOutgoingSet())
{
if (not h->is_type(EVALUATABLE_LINK)) return false;
}
return true;
}
/* This runs when the shared lib is loaded. */
static __attribute__ ((constructor)) void init(void)
{
classserver().addValidator(BOOLEAN_LINK, check_evaluatable);
}
|
Remove spurious required field from Cylinders codec | #pragma once
#include "CylindersWrapperCodec.h"
namespace spotify
{
namespace json
{
using CylindersWrapper = noise::module::Wrapper<noise::module::Cylinders>;
codec::object_t<CylindersWrapper> default_codec_t<CylindersWrapper>::codec()
{
auto codec = codec::object<CylindersWrapper>();
codec.required("type", codec::eq<std::string>("Cylinders"));
codec.required("SourceModule", codec::ignore_t<int>());
codec.optional("Frequency",
[](const CylindersWrapper& mw) {return mw.module->GetFrequency(); },
[](CylindersWrapper& mw, double frequency) {mw.module->SetFrequency(frequency); });
return codec;
}
}
}
| #pragma once
#include "CylindersWrapperCodec.h"
namespace spotify
{
namespace json
{
using CylindersWrapper = noise::module::Wrapper<noise::module::Cylinders>;
codec::object_t<CylindersWrapper> default_codec_t<CylindersWrapper>::codec()
{
auto codec = codec::object<CylindersWrapper>();
codec.required("type", codec::eq<std::string>("Cylinders"));
codec.optional("Frequency",
[](const CylindersWrapper& mw) {return mw.module->GetFrequency(); },
[](CylindersWrapper& mw, double frequency) {mw.module->SetFrequency(frequency); });
return codec;
}
}
}
|
Use an array to store the size of the types | //=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <string>
#include "Types.hpp"
#include "CompilerException.hpp"
using namespace eddic;
int eddic::size(Type type){
return type == Type::INT ? 4 : 8;
}
bool eddic::isType(std::string type){
return type == "int" || type == "void" || type == "string";
}
Type eddic::stringToType(std::string type){
if (type == "int") {
return Type::INT;
} else if (type == "string"){
return Type::STRING;
} else if(type == "void") {
return Type::VOID;
}
throw CompilerException("Invalid type");
}
| //=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <string>
#include "Types.hpp"
#include "CompilerException.hpp"
using namespace eddic;
const int typeSizes[(int) Type::COUNT] = { 8, 4, 0 };
int eddic::size(Type type){
return typeSizes[(int) type];
}
bool eddic::isType(std::string type){
return type == "int" || type == "void" || type == "string";
}
Type eddic::stringToType(std::string type){
if (type == "int") {
return Type::INT;
} else if (type == "string"){
return Type::STRING;
} else if(type == "void") {
return Type::VOID;
}
throw CompilerException("Invalid type");
}
|
Add an eol at the end to shut gcc sup. | //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing dwarf debug info into asm files.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/DwarfWriter.h" | //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing dwarf debug info into asm files.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/DwarfWriter.h"
|
Mark lock_guard nodiscard test as unsupported in C++03 | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: libcpp-has-no-threads
// [[nodiscard]] on constructors isn't supported by all compilers
// UNSUPPORTED: clang-6, clang-7, clang-8, clang-9
// UNSUPPORTED: apple-clang-9, apple-clang-10, apple-clang-11
// <mutex>
// template <class Mutex> class lock_guard;
// [[nodiscard]] explicit lock_guard(mutex_type& m);
// [[nodiscard]] lock_guard(mutex_type& m, adopt_lock_t);
// Test that we properly apply [[nodiscard]] to lock_guard's constructors,
// which is a libc++ extension.
// MODULES_DEFINES: _LIBCPP_ENABLE_NODISCARD
#define _LIBCPP_ENABLE_NODISCARD
#include <mutex>
int main(int, char**) {
std::mutex m;
std::lock_guard<std::mutex>{m}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
std::lock_guard<std::mutex>{m, std::adopt_lock}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
return 0;
}
| //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: libcpp-has-no-threads
// [[nodiscard]] on constructors isn't supported by all compilers
// UNSUPPORTED: clang-6, clang-7, clang-8, clang-9
// UNSUPPORTED: apple-clang-9, apple-clang-10, apple-clang-11
// [[nodiscard]] isn't supported in C++98 and C++03 (not even as an extension)
// UNSUPPORTED: c++98, c++03
// <mutex>
// template <class Mutex> class lock_guard;
// [[nodiscard]] explicit lock_guard(mutex_type& m);
// [[nodiscard]] lock_guard(mutex_type& m, adopt_lock_t);
// Test that we properly apply [[nodiscard]] to lock_guard's constructors,
// which is a libc++ extension.
// MODULES_DEFINES: _LIBCPP_ENABLE_NODISCARD
#define _LIBCPP_ENABLE_NODISCARD
#include <mutex>
int main(int, char**) {
std::mutex m;
std::lock_guard<std::mutex>{m}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
std::lock_guard<std::mutex>{m, std::adopt_lock}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
return 0;
}
|
Fix toggle text after first video recording start. | #include "./video_recorder_controller.h"
#include <QDateTime>
#include "./video_recorder.h"
VideoRecorderController::VideoRecorderController(
std::shared_ptr<VideoRecorder> videoRecorder)
: videoRecorder(videoRecorder)
{
connect(this, SIGNAL(toggleRecording()), this,
SLOT(toggleRecordingInMainThread()), Qt::QueuedConnection);
}
void VideoRecorderController::startNewVideo()
{
const QDateTime now = QDateTime::currentDateTime();
const QString timestamp = now.toString(QLatin1String("yyyy-MM-dd-hhmmsszzz"));
auto filename = QString::fromLatin1("video_%1.mpeg").arg(timestamp);
videoRecorder->createNewVideo(filename.toStdString());
videoRecorder->startRecording();
}
QString VideoRecorderController::getToggleText()
{
if (videoRecorder->getIsRecording())
return "Stop recording";
return "Start recording";
}
void VideoRecorderController::toggleRecordingInMainThread()
{
if (videoRecorder->getIsRecording())
{
videoRecorder->stopRecording();
}
else
{
videoRecorder->startRecording();
}
emit recordingStateSwitched();
}
| #include "./video_recorder_controller.h"
#include <QDateTime>
#include "./video_recorder.h"
VideoRecorderController::VideoRecorderController(
std::shared_ptr<VideoRecorder> videoRecorder)
: videoRecorder(videoRecorder)
{
connect(this, SIGNAL(toggleRecording()), this,
SLOT(toggleRecordingInMainThread()), Qt::QueuedConnection);
}
void VideoRecorderController::startNewVideo()
{
const QDateTime now = QDateTime::currentDateTime();
const QString timestamp = now.toString(QLatin1String("yyyy-MM-dd-hhmmsszzz"));
auto filename = QString::fromLatin1("video_%1.mpeg").arg(timestamp);
videoRecorder->createNewVideo(filename.toStdString());
videoRecorder->startRecording();
emit recordingStateSwitched();
}
QString VideoRecorderController::getToggleText()
{
if (videoRecorder->getIsRecording())
return "Stop recording";
return "Start recording";
}
void VideoRecorderController::toggleRecordingInMainThread()
{
if (videoRecorder->getIsRecording())
{
videoRecorder->stopRecording();
}
else
{
videoRecorder->startRecording();
}
emit recordingStateSwitched();
}
|
Remove the unused ZoomArea from the elements | /*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <glib-object.h>
#include <QDir>
#include "components.h"
#include "launcher.h"
#include "roundedimage.h"
#include "viewfinder.h"
#include "zoomarea.h"
components::components ()
{
// Initialise the GObject type system
g_type_init ();
if (QDir::home ().mkpath ("Pictures/Camera") == false) {
qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
}
if (QDir::home ().mkpath ("Videos/Camera") == false) {
qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
}
}
void components::registerTypes(const char *uri)
{
qmlRegisterType<Launcher>(uri, 0, 1, "Launcher");
qmlRegisterType<RoundedImage>(uri, 0, 1, "RoundedImage");
qmlRegisterType<ViewFinder>(uri, 0, 1, "ViewFinder");
qmlRegisterType<ZoomArea>(uri, 0, 1, "ZoomArea");
}
Q_EXPORT_PLUGIN(components);
| /*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <glib-object.h>
#include <QDir>
#include "components.h"
#include "launcher.h"
#include "roundedimage.h"
#include "viewfinder.h"
components::components ()
{
// Initialise the GObject type system
g_type_init ();
if (QDir::home ().mkpath ("Pictures/Camera") == false) {
qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
}
if (QDir::home ().mkpath ("Videos/Camera") == false) {
qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
}
}
void components::registerTypes(const char *uri)
{
qmlRegisterType<Launcher>(uri, 0, 1, "Launcher");
qmlRegisterType<RoundedImage>(uri, 0, 1, "RoundedImage");
qmlRegisterType<ViewFinder>(uri, 0, 1, "ViewFinder");
}
Q_EXPORT_PLUGIN(components);
|
Use QCoreApplication for unit tests as it should not depend on GUI stuff. | #include <QApplication>
#include "gtest/gtest.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
::testing::InitGoogleTest(&argc, argv);
int returnValue = RUN_ALL_TESTS();
return returnValue;
}
| #include <QCoreApplication>
#include "gtest/gtest.h"
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
::testing::InitGoogleTest(&argc, argv);
int returnValue = RUN_ALL_TESTS();
return returnValue;
}
|
Remove an element from a list completed | #include<iostream>
using namespace std;
int removeElement(int A[], int n, int elem) {
int length = n-1;
for(int i = 0; i <= length; ++i) {
if(A[i] == elem) {
while (A[length] != elem) {
length--;
}
A[i] = A[length--];
}
}
return length + 1;
}
int main() {
int A[] = {1,2,3,4,1,6,3,4};
int length = removeElement(A, 8, 1);
for(int i = 0; i < length; ++i) {
cout << A[i] << endl;
}
return 0;
}
| #include<iostream>
using namespace std;
int removeElement(int A[], int n, int elem) {
if (n == 0) {
return n;
}
if (n == 1 && A[0] == elem) {
return 0;
}
if (n == 1 && A[0] != elem) {
return n;
}
int tail = n - 1;
int i = 0;
while (i <= tail) {
if (A[i] == elem) {
A[i] = A[tail];
--tail;
} else {
++i;
}
}
return tail + 1;
}
int main() {
int A[] = {1,2,3};
int length = removeElement(A, 3, 1);
for(int i = 0; i < length; ++i) {
cout << A[i] << endl;
}
cout << endl;
int B[] = {1,1};
length = removeElement(B, 2, 1);
for(int i = 0; i < length; ++i) {
cout << B[i] << endl;
}
return 0;
}
|
Fix includes in integration test example. | // Copyright 2019 DeepMind Technologies Ltd. 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 "//third_party/open_spiel/spiel_utils.h"
#include "<torch/torch.h>"
namespace {
void TestMatrixMultiplication() {
at::Tensor mat = torch::rand({3, 3});
at::Tensor identity = torch::ones({3, 3});
at::Tensor multiplied = mat * identity;
int num_identical_elements = (mat == multiplied).sum().item().to<int>();
SPIEL_CHECK_EQ(num_identical_elements, 9);
}
} // namespace
int main() { TestMatrixMultiplication(); }
| // Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/spiel_utils.h"
#include "torch/torch.h"
namespace {
void TestMatrixMultiplication() {
at::Tensor mat = torch::rand({3, 3});
at::Tensor identity = torch::ones({3, 3});
at::Tensor multiplied = mat * identity;
int num_identical_elements = (mat == multiplied).sum().item().to<int>();
SPIEL_CHECK_EQ(num_identical_elements, 9);
}
} // namespace
int main() { TestMatrixMultiplication(); }
|
Test UTF-16 output of GetUserName | #include <unistd.h>
#include <gtest/gtest.h>
#include "getusername.h"
TEST(GetUserName,simple)
{
// allocate a WCHAR_T buffer to receive username
DWORD lpnSize = 64;
WCHAR_T lpBuffer[lpnSize];
BOOL result = GetUserName(lpBuffer, &lpnSize);
// GetUserName returns 1 on success
ASSERT_EQ(1, result);
// get expected username
const char *username = getlogin();
// GetUserName sets lpnSize to length of username including null
ASSERT_EQ(strlen(username)+1, lpnSize);
// TODO: ASSERT_STREQ(username, Utf16leToUtf8(lpBuffer))
}
| #include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"
using std::string;
using std::vector;
using SCXCoreLib::Utf16leToUtf8;
TEST(GetUserName,simple)
{
// allocate a WCHAR_T buffer to receive username
DWORD lpnSize = 64;
WCHAR_T lpBuffer[lpnSize];
BOOL result = GetUserName(lpBuffer, &lpnSize);
// GetUserName returns 1 on success
ASSERT_EQ(1, result);
// get expected username
string username = string(getlogin());
// GetUserName sets lpnSize to length of username including null
ASSERT_EQ(username.size()+1, lpnSize);
// copy UTF-16 bytes from lpBuffer to vector for conversion
vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]),
reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1]));
// convert to UTF-8 for assertion
string output;
Utf16leToUtf8(input, output);
EXPECT_EQ(username, output);
}
|
Enable output buffer in log only for Release | /**
* \file bs_log_scribers.cpp
* \brief
* \author Sergey Miryanov
* \date 07.07.2009
* */
#include "bs_log_scribers.h"
using namespace std;
namespace blue_sky {
namespace log {
namespace detail {
void cout_scriber::write(const std::string &str) const {
//#ifdef _DEBUG
// TODO: miryanov
static bool is_buffer_installed = false;
if (!is_buffer_installed)
{
static char cout_buffer [2*4096] = {0};
cout.rdbuf ()->pubsetbuf (cout_buffer, sizeof (cout_buffer));
is_buffer_installed = true;
}
cout << str.c_str ();
//#endif
}
file_scriber::file_scriber(const std::string &filename, ios_base::openmode mode)
: file(new fstream(filename.c_str(),mode))
{}
//file_scriber::~file_scriber() {
// file.lock()->close();
//}
void file_scriber::write(const std::string &str) const {
#ifdef _DEBUG
// TODO: miryanov
*(file.lock()) << str;
#endif
}
} // namespace detail
} // namespace log
} // namespace blue_sky
| /**
* \file bs_log_scribers.cpp
* \brief
* \author Sergey Miryanov
* \date 07.07.2009
* */
#include "bs_log_scribers.h"
using namespace std;
namespace blue_sky {
namespace log {
namespace detail {
void cout_scriber::write(const std::string &str) const {
#ifndef _DEBUG
static bool is_buffer_installed = false;
if (!is_buffer_installed)
{
static char cout_buffer [2*4096] = {0};
cout.rdbuf ()->pubsetbuf (cout_buffer, sizeof (cout_buffer));
is_buffer_installed = true;
}
#endif
cout << str.c_str ();
}
file_scriber::file_scriber(const std::string &filename, ios_base::openmode mode)
: file(new fstream(filename.c_str(),mode))
{}
//file_scriber::~file_scriber() {
// file.lock()->close();
//}
void file_scriber::write(const std::string &str) const {
#ifdef _DEBUG
// TODO: miryanov
*(file.lock()) << str;
#endif
}
} // namespace detail
} // namespace log
} // namespace blue_sky
|
Add a missing license header | #include "prng_user.hpp"
PrngUser::PrngUser(std::shared_ptr<std::mt19937> generator)
: generator_{generator}
{
}
std::shared_ptr<std::mt19937> PrngUser::getGenerator() const
{
return generator_;
}
void PrngUser::setGenerator(std::shared_ptr<std::mt19937> generator)
{
generator_ = generator;
}
| /* Copyright 2014 Juhani Numminen
*
* 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 "prng_user.hpp"
PrngUser::PrngUser(std::shared_ptr<std::mt19937> generator)
: generator_{generator}
{
}
std::shared_ptr<std::mt19937> PrngUser::getGenerator() const
{
return generator_;
}
void PrngUser::setGenerator(std::shared_ptr<std::mt19937> generator)
{
generator_ = generator;
}
|
Refactor the resolver test code | #include "net/resolver.h"
#include <string>
#include <gtest/gtest.h>
using namespace net;
TEST(LookupAddress, Localhost) {
{
std::string addr;
error err = LookupAddress("localhost", &addr);
EXPECT_EQ(error::nil, err);
EXPECT_EQ("127.0.0.1", addr);
}
{
std::string addr;
error err = LookupAddress("127.0.0.1", &addr);
EXPECT_EQ(error::nil, err);
EXPECT_EQ("127.0.0.1", addr);
}
}
TEST(LookupAddress, Nullptr) {
ASSERT_DEATH({ LookupAddress("localhost", nullptr); }, "");
}
| #include "net/resolver.h"
#include <string>
#include <gtest/gtest.h>
using namespace net;
TEST(LookupAddress, Localhost) {
std::string addr;
error err = LookupAddress("localhost", &addr);
EXPECT_EQ(error::nil, err);
EXPECT_EQ("127.0.0.1", addr);
}
TEST(LookupAddress, LocalIPv4) {
std::string addr;
error err = LookupAddress("127.0.0.1", &addr);
EXPECT_EQ(error::nil, err);
EXPECT_EQ("127.0.0.1", addr);
}
TEST(LookupAddress, Nullptr) {
ASSERT_DEATH({ LookupAddress("localhost", nullptr); }, "");
}
|
Fix unused variable on outdated example | #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <qitype/signature.hpp>
//sample foo function to take the signature from
int foo(int a, int b)
{
return a + b + 42;
}
int main()
{
typedef std::map<std::string , std::string> StringMap;
typedef std::vector<int> IntVector;
StringMap mymap;
int myint;
std::string mystring;
IntVector myvector;
return 0;
}
| #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <qitype/signature.hpp>
//sample foo function to take the signature from
int foo(int a, int b)
{
return a + b + 42;
}
int main()
{
typedef std::map<std::string , std::string> StringMap;
typedef std::vector<int> IntVector;
StringMap mymap;
// int myint;
std::string mystring;
IntVector myvector;
return 0;
}
|
Fix warnings map to be thread-local | /*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
namespace unimplemented {
static std::unordered_map<cause, bool> _warnings;
std::ostream& operator<<(std::ostream& out, cause c) {
switch(c) {
case cause::INDEXES: return out << "INDEXES";
case cause::LWT: return out << "LWT";
case cause::PAGING: return out << "PAGING";
case cause::AUTH: return out << "AUTH";
case cause::PERMISSIONS: return out << "PERMISSIONS";
case cause::TRIGGERS: return out << "TRIGGERS";
case cause::COLLECTIONS: return out << "COLLECTIONS";
case cause::COUNTERS: return out << "COUNTERS";
case cause::METRICS: return out << "METRICS";
case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
}
assert(0);
}
void warn(cause c) {
auto i = _warnings.find(c);
if (i == _warnings.end()) {
_warnings.insert({c, true});
std::cerr << "WARNING: Not implemented: " << c << std::endl;
}
}
void fail(cause c) {
throw std::runtime_error(sprint("Not implemented: %s", c));
}
}
| /*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
namespace unimplemented {
static thread_local std::unordered_map<cause, bool> _warnings;
std::ostream& operator<<(std::ostream& out, cause c) {
switch(c) {
case cause::INDEXES: return out << "INDEXES";
case cause::LWT: return out << "LWT";
case cause::PAGING: return out << "PAGING";
case cause::AUTH: return out << "AUTH";
case cause::PERMISSIONS: return out << "PERMISSIONS";
case cause::TRIGGERS: return out << "TRIGGERS";
case cause::COLLECTIONS: return out << "COLLECTIONS";
case cause::COUNTERS: return out << "COUNTERS";
case cause::METRICS: return out << "METRICS";
case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
}
assert(0);
}
void warn(cause c) {
auto i = _warnings.find(c);
if (i == _warnings.end()) {
_warnings.insert({c, true});
std::cerr << "WARNING: Not implemented: " << c << std::endl;
}
}
void fail(cause c) {
throw std::runtime_error(sprint("Not implemented: %s", c));
}
}
|
Add command line argument support | /* localsearch.cpp
Ian Westrope
Evolutionary Computation
Spring 2015
*/
#include <iostream>
#include <cstdlib>
#include "bitHelpers.h"
#include "rand.h"
using namespace std;
int main() {
cout << "Test makefile" << endl;
}
| /* localsearch.cpp
Ian Westrope
Evolutionary Computation
Spring 2015
*/
#include <iostream>
#include <cstdlib>
#include "bitHelpers.h"
#include "rand.h"
using namespace std;
int main( int argc, char* argv[] ) {
// variables for command line arguments
int grayFlag = 0; // Gray code
int binaryFlag = 0;
int randomFlag = 0;
int bitFlag = 0;
int incFlag = 0; // increment decrement mutation
// check if there are the correct number of arguments
if( argc > 3 || argc < 3 ) {
cout << "Two arguments required" << endl;
exit( -1 );
}
int arg1 = atoi( argv[1] );
int arg2 = atoi( argv[2] );
// get first argument
if( arg1 == 0 ) {
grayFlag = 1;
} else if( arg1 == 1 ) {
binaryFlag = 1;
} else {
cout << "First argument must be a 0 or 1" << endl;
exit( -1 );
}
// get second argument
if( arg2 == 0 ) {
randomFlag = 1;
} else if( arg2 == 1 ) {
bitFlag = 1;
} else if( arg2 == 2 ) {
incFlag = 1;
} else {
cout << "Second argument must be a 0, 1, or 2" << endl;
exit( -1 );
}
cout << "Test makefile" << endl;
}
|
Fix timer overflow on 16-bit int (milliseconds is an unsigned long) | #include "zg01_fsm.h"
// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS 3
// all of the state of the FSM
typedef struct {
uint8_t *buffer;
int num_bits;
int prev_ms;
} fsm_t;
static fsm_t fsm;
static fsm_t *s = &fsm;
// resets the FSM
static void fsm_reset(void)
{
s->num_bits = 0;
}
void zg01_init(uint8_t buffer[5])
{
s->buffer = buffer;
fsm_reset();
}
bool zg01_process(unsigned long ms, uint8_t data)
{
// check if a new message has started, based on time since previous bit
if ((ms - s->prev_ms) > ZG01_MAX_MS) {
fsm_reset();
}
s->prev_ms = ms;
// number of bits received is basically the "state"
if (s->num_bits < 40) {
// store it while it fits
int idx = s->num_bits / 8;
s->buffer[idx] = (s->buffer[idx] << 1) | data;
// are we done yet?
s->num_bits++;
if (s->num_bits == 40) {
return true;
}
}
// else do nothing, wait until fsm is reset
return false;
}
| #include "zg01_fsm.h"
// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS 3
// all of the state of the FSM
typedef struct {
uint8_t *buffer;
int num_bits;
unsigned long prev_ms;
} fsm_t;
static fsm_t fsm;
static fsm_t *s = &fsm;
// resets the FSM
static void fsm_reset(void)
{
s->num_bits = 0;
}
void zg01_init(uint8_t buffer[5])
{
s->buffer = buffer;
fsm_reset();
}
bool zg01_process(unsigned long ms, uint8_t data)
{
// check if a new message has started, based on time since previous bit
if ((ms - s->prev_ms) > ZG01_MAX_MS) {
fsm_reset();
}
s->prev_ms = ms;
// number of bits received is basically the "state"
if (s->num_bits < 40) {
// store it while it fits
int idx = s->num_bits / 8;
s->buffer[idx] = (s->buffer[idx] << 1) | data;
// are we done yet?
s->num_bits++;
if (s->num_bits == 40) {
return true;
}
}
// else do nothing, wait until fsm is reset
return false;
}
|
Add couple of debug statements | // ===============================
// Slots for long running Library Tasks
// Available under the 3-clause BSD License
// Written by: Kris Moore <kris@pcbsd.org> FEB 2016
// =================================
#include <WebSocket.h>
#define DEBUG 0
// Iohyve Fetch is done
void WebSocket::slotIohyveFetchDone(QString id, int retcode, QString log)
{
}
// Iohyve Fetch has output to read
void WebSocket::slotIohyveFetchProcessOutput(QString output)
{
}
| // ===============================
// Slots for long running Library Tasks
// Available under the 3-clause BSD License
// Written by: Kris Moore <kris@pcbsd.org> FEB 2016
// =================================
#include <WebSocket.h>
#define DEBUG 0
// Iohyve Fetch is done
void WebSocket::slotIohyveFetchDone(QString id, int retcode, QString log)
{
//qDebug() << "Fetch Done" << id << retcode << log;
}
// Iohyve Fetch has output to read
void WebSocket::slotIohyveFetchProcessOutput(QString output)
{
//qDebug() << "Fetch Do" << output;
}
|
Change invalid signature of DownloadGridcoinBlocks. | #include <string>
#include "grcrestarter.h"
// Old VB based NeuralNet.
double qtPushGridcoinDiagnosticData(std::string data);
int RestartClient();
bool CheckForUpgrade();
void UpgradeClient();
int DownloadBlocks();
int ReindexWallet();
int CreateRestorePoint();
// While transitioning to dotnet the NeuralNet implementation has been split
// into 3 implementations; Win32 with Qt, Win32 without Qt and the rest.
// After the transition both Win32 implementations can be removed.
namespace Restarter
{
// Win32 with Qt enabled.
double PushGridcoinDiagnosticData(std::string data)
{
return qtPushGridcoinDiagnosticData(data);
}
int RestartGridcoin()
{
return RestartClient();
}
bool IsUpgradeAvailable()
{
return IsUpgradeAvailable();
}
void UpgradeClient()
{
return UpgradeClient();
}
bool DownloadGridcoinBlocks()
{
return DownloadBlocks();
}
int ReindexGridcoinWallet()
{
return ReindexWallet();
}
int CreateGridcoinRestorePoint()
{
return CreateRestorePoint();
}
}
| #include <string>
#include "grcrestarter.h"
// Old VB based NeuralNet.
double qtPushGridcoinDiagnosticData(std::string data);
int RestartClient();
bool CheckForUpgrade();
void UpgradeClient();
int DownloadBlocks();
int ReindexWallet();
int CreateRestorePoint();
// While transitioning to dotnet the NeuralNet implementation has been split
// into 3 implementations; Win32 with Qt, Win32 without Qt and the rest.
// After the transition both Win32 implementations can be removed.
namespace Restarter
{
// Win32 with Qt enabled.
double PushGridcoinDiagnosticData(std::string data)
{
return qtPushGridcoinDiagnosticData(data);
}
int RestartGridcoin()
{
return RestartClient();
}
bool IsUpgradeAvailable()
{
return IsUpgradeAvailable();
}
void UpgradeClient()
{
return UpgradeClient();
}
int DownloadGridcoinBlocks()
{
return DownloadBlocks();
}
int ReindexGridcoinWallet()
{
return ReindexWallet();
}
int CreateGridcoinRestorePoint()
{
return CreateRestorePoint();
}
}
|
Scale internal times for Break objects. | /*
This file is part of VROOM.
Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "structures/vroom/break.h"
#include "utils/helpers.h"
namespace vroom {
Break::Break(Id id,
const std::vector<TimeWindow>& tws,
Duration service,
const std::string& description)
: id(id), tws(tws), service(service), description(description) {
utils::check_tws(tws);
}
bool Break::is_valid_start(Duration time) const {
bool valid = false;
for (const auto& tw : tws) {
if (tw.contains(time)) {
valid = true;
break;
}
}
return valid;
}
} // namespace vroom
| /*
This file is part of VROOM.
Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "structures/vroom/break.h"
#include "utils/helpers.h"
namespace vroom {
Break::Break(Id id,
const std::vector<TimeWindow>& tws,
Duration service,
const std::string& description)
: id(id),
tws(tws),
service(DURATION_FACTOR * service),
description(description) {
utils::check_tws(tws);
}
bool Break::is_valid_start(Duration time) const {
bool valid = false;
for (const auto& tw : tws) {
if (tw.contains(time)) {
valid = true;
break;
}
}
return valid;
}
} // namespace vroom
|
Change naming scheme for files | /*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2020 by Kaushik Ghose. Some rights reserved, see LICENSE
*/
#include <exception>
#include <string>
#include "serialize.hpp"
namespace groho {
Serialize::Serialize(
double dt, const std::vector<NAIFbody>& objects, fs::path path)
{
if (fs::exists(path)) {
if (!fs::is_directory(path)) {
throw std::runtime_error("Output path must be directory");
}
} else {
fs::create_directories(path);
}
history.reserve(objects.size());
for (size_t i = 0; i < objects.size(); i++) {
auto fname = path / (std::to_string(int(objects[i])) + "-pos.bin");
history.emplace_back(dt, objects[i], fname);
}
}
void Serialize::append(const v3d_vec_t& pos)
{
for (size_t i = 0; i < history.size(); i++) {
history[i].sample(pos[i]);
}
}
}
| /*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2020 by Kaushik Ghose. Some rights reserved, see LICENSE
*/
#include <exception>
#include <string>
#include "serialize.hpp"
namespace groho {
Serialize::Serialize(
double dt, const std::vector<NAIFbody>& objects, fs::path path)
{
if (fs::exists(path)) {
if (!fs::is_directory(path)) {
throw std::runtime_error("Output path must be directory");
}
} else {
fs::create_directories(path);
}
history.reserve(objects.size());
for (size_t i = 0; i < objects.size(); i++) {
auto fname = path / ("pos" + std::to_string(int(objects[i])) + ".bin");
history.emplace_back(dt, objects[i], fname);
}
}
void Serialize::append(const v3d_vec_t& pos)
{
for (size_t i = 0; i < history.size(); i++) {
history[i].sample(pos[i]);
}
}
}
|
Update locale handling on Windows | #include <system/Locale.h>
#if defined(HX_WINDOWS)
#include <windows.h>
#elif defined(HX_LINUX)
#include <stdlib.h>
#include <string.h>
#include <clocale>
#endif
namespace lime {
std::string* Locale::GetSystemLocale () {
#if defined(HX_WINDOWS)
char locale[8];
int length = GetLocaleInfo (GetSystemDefaultUILanguage (), LOCALE_SISO639LANGNAME, locale, sizeof (locale));
std::string* result = new std::string (locale);
return result;
#elif defined(HX_LINUX)
const char* locale = getenv ("LANG");
if (!locale) {
locale = setlocale (LC_ALL, "");
}
if (locale) {
std::string* result = new std::string (locale);
return result;
}
return 0;
#else
return 0;
#endif
}
} | #include <system/Locale.h>
#if defined(HX_WINDOWS)
#include <windows.h>
#elif defined(HX_LINUX)
#include <stdlib.h>
#include <string.h>
#include <clocale>
#endif
namespace lime {
std::string* Locale::GetSystemLocale () {
#if defined(HX_WINDOWS)
char language[5] = {0};
char country[5] = {0};
GetLocaleInfoA (LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, language, sizeof (language) / sizeof (char));
GetLocaleInfoA (LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, sizeof (country) / sizeof (char));
std::string* locale = new std::string (std::string (language) + "_" + std::string (country));
return locale;
#elif defined(HX_LINUX)
const char* locale = getenv ("LANG");
if (!locale) {
locale = setlocale (LC_ALL, "");
}
if (locale) {
std::string* result = new std::string (locale);
return result;
}
return 0;
#else
return 0;
#endif
}
} |
Decrease sensitivity of timer test. | // Copyright 2010-2014 RethinkDB, all rights reserved.
#include "unittest/gtest.hpp"
#include "arch/timing.hpp"
#include "concurrency/pmap.hpp"
#include "unittest/unittest_utils.hpp"
#include "utils.hpp"
namespace unittest {
int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 },
{ 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } };
void walk_wait_times(int i) {
ticks_t t = get_ticks();
for (int j = 0; j < 10; ++j) {
nap(wait_array[i][j]);
const ticks_t t2 = get_ticks();
const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t);
// Asserts that we're off by less than two milliseconds.
ASSERT_LT(llabs(diff - wait_array[i][j] * MILLION), 2 * MILLION);
t = t2;
}
}
TPTEST(TimerTest, TestApproximateWaitTimes) {
pmap(2, walk_wait_times);
}
} // namespace unittest
| // Copyright 2010-2014 RethinkDB, all rights reserved.
#include "unittest/gtest.hpp"
#include "arch/timing.hpp"
#include "concurrency/pmap.hpp"
#include "unittest/unittest_utils.hpp"
#include "utils.hpp"
namespace unittest {
int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 },
{ 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } };
void walk_wait_times(int i) {
ticks_t t = get_ticks();
for (int j = 0; j < 10; ++j) {
nap(wait_array[i][j]);
const ticks_t t2 = get_ticks();
const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t);
// Asserts that we're off by less than 25% of the sleep time
// or two milliseconds, whichever is larger.
ASSERT_LT(llabs(diff - wait_array[i][j] * MILLION), std::max(diff / 4, 2 * MILLION));
t = t2;
}
}
TPTEST(TimerTest, TestApproximateWaitTimes) {
pmap(2, walk_wait_times);
}
} // namespace unittest
|
Return !0 when qt tests fail. | #include <QTest>
#include <QObject>
#include "uritests.h"
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
URITests test1;
QTest::qExec(&test1);
}
| #include <QTest>
#include <QObject>
#include "uritests.h"
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
bool fInvalid = false;
URITests test1;
if (QTest::qExec(&test1) != 0)
fInvalid = true;
return fInvalid;
}
|
Update Windows runner from template | #include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include <vector>
#include "flutter_window.h"
#include "run_loop.h"
#include "window_configuration.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance,
_In_opt_ HINSTANCE prev,
_In_ wchar_t* command_line,
_In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
::AllocConsole();
}
RunLoop run_loop;
flutter::DartProject project(L"data");
#ifndef _DEBUG
project.SetEngineSwitches({"--disable-dart-asserts"});
#endif
FlutterWindow window(&run_loop, project);
Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY);
Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight);
if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
run_loop.Run();
return EXIT_SUCCESS;
}
| #include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include <vector>
#include "flutter_window.h"
#include "run_loop.h"
#include "window_configuration.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance,
_In_opt_ HINSTANCE prev,
_In_ wchar_t* command_line,
_In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
::AllocConsole();
}
// Initialize COM, so that it is available for use in the library and/or plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
RunLoop run_loop;
flutter::DartProject project(L"data");
#ifndef _DEBUG
project.SetEngineSwitches({"--disable-dart-asserts"});
#endif
FlutterWindow window(&run_loop, project);
Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY);
Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight);
if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
run_loop.Run();
::CoUninitialize();
return EXIT_SUCCESS;
}
|
Add comment about suppress the warning C4251 of Visual Studio. | #ifdef _WINDOWS
/*
* NOTE: Some macros must be defined in project options of Visual Studio.
* - _CRT_SECURE_NO_WARNINGS
* To use strncpy().
* - NOMINMAX
* To use std::min(), std::max().
*/
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
| #ifdef _WINDOWS
/*
* NOTE: Some macros must be defined in project options of Visual Studio.
* - _CRT_SECURE_NO_WARNINGS
* To use strncpy().
* - NOMINMAX
* To use std::min(), std::max().
* NOTE: Suppress some warnings of Visual Studio.
* - C4251
*/
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
|
Use Chrome's user agent string for content_shell, since some sites (i.e. Gmail) give a degraded experience otherwise. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/shell_content_client.h"
#include "base/string_piece.h"
namespace content {
ShellContentClient::~ShellContentClient() {
}
void ShellContentClient::SetActiveURL(const GURL& url) {
}
void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}
void ShellContentClient::AddPepperPlugins(
std::vector<PepperPluginInfo>* plugins) {
}
bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
return false;
}
bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
return false;
}
std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
return std::string();
}
string16 ShellContentClient::GetLocalizedString(int message_id) const {
return string16();
}
base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
return base::StringPiece();
}
#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
return false;
}
#endif
} // namespace content
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/shell_content_client.h"
#include "base/string_piece.h"
#include "webkit/glue/user_agent.h"
namespace content {
ShellContentClient::~ShellContentClient() {
}
void ShellContentClient::SetActiveURL(const GURL& url) {
}
void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}
void ShellContentClient::AddPepperPlugins(
std::vector<PepperPluginInfo>* plugins) {
}
bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
return false;
}
bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
return false;
}
std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
return webkit_glue::BuildUserAgentHelper(mimic_windows, "Chrome/15.16.17.18");
}
string16 ShellContentClient::GetLocalizedString(int message_id) const {
return string16();
}
base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
return base::StringPiece();
}
#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
return false;
}
#endif
} // namespace content
|
Fix main file's init function for C++, and comment out unimplemented functions. | #include "pdfium_ruby.h"
void Init_pdfium_ruby (void) {
VALUE rb_PDFium = rb_define_module("PDFium");
// Define `Document` and `Page` classes
Define_Document();
Define_Page();
Define_PageSet();
}
| #include "pdfium_ruby.h"
extern "C"
void Init_pdfium_ruby (void) {
// Define `PDFium` module as a namespace for all of our other objects
VALUE rb_PDFium = rb_define_module("PDFium");
// Define `Document` and `Page` classes
Define_Document();
//Define_Page();
//Define_PageSet();
}
|
Add benchmark to write JSON into a string | // Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <bench/data.h>
#include <rpc/blockchain.h>
#include <streams.h>
#include <test/util/setup_common.h>
#include <validation.h>
#include <univalue.h>
static void BlockToJsonVerbose(benchmark::Bench& bench)
{
TestingSetup test_setup{};
CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION);
char a = '\0';
stream.write(&a, 1); // Prevent compaction
CBlock block;
stream >> block;
CBlockIndex blockindex;
const uint256 blockHash = block.GetHash();
blockindex.phashBlock = &blockHash;
blockindex.nBits = 403014710;
bench.run([&] {
(void)blockToJSON(block, &blockindex, &blockindex, /*verbose*/ true);
});
}
BENCHMARK(BlockToJsonVerbose);
| // Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <bench/data.h>
#include <rpc/blockchain.h>
#include <streams.h>
#include <test/util/setup_common.h>
#include <validation.h>
#include <univalue.h>
namespace {
struct TestBlockAndIndex {
TestingSetup test_setup{};
CBlock block{};
uint256 blockHash{};
CBlockIndex blockindex{};
TestBlockAndIndex()
{
CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION);
char a = '\0';
stream.write(&a, 1); // Prevent compaction
stream >> block;
blockHash = block.GetHash();
blockindex.phashBlock = &blockHash;
blockindex.nBits = 403014710;
}
};
} // namespace
static void BlockToJsonVerbose(benchmark::Bench& bench)
{
TestBlockAndIndex data;
bench.run([&] {
auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, /*verbose*/ true);
ankerl::nanobench::doNotOptimizeAway(univalue);
});
}
BENCHMARK(BlockToJsonVerbose);
static void BlockToJsonVerboseWrite(benchmark::Bench& bench)
{
TestBlockAndIndex data;
auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, /*verbose*/ true);
bench.run([&] {
auto str = univalue.write();
ankerl::nanobench::doNotOptimizeAway(str);
});
}
BENCHMARK(BlockToJsonVerboseWrite);
|
Fix warning on startup from theme watcher | #include "theme-loader.h"
#include <QApplication>
#include <QDir>
#include <QFile>
ThemeLoader::ThemeLoader(QString path, QObject *parent)
: QObject(parent), m_path(std::move(path))
{
connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &ThemeLoader::themeFileChanged);
}
QStringList ThemeLoader::getAllThemes() const
{
return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}
bool ThemeLoader::setTheme(const QString &name)
{
const QString dir = QString(m_path).replace('\\', '/') + name + "/";
const QString cssFile = dir + "style.css";
QFile f(cssFile);
if (!f.open(QFile::ReadOnly | QFile::Text)) {
return false;
}
QString css = f.readAll();
f.close();
// Replace urls relative paths by absolute ones
css.replace("url(", "url(" + dir);
// Update watcher if necessary
if (m_currentTheme != name) {
m_currentTheme = name;
m_watcher.removePaths(m_watcher.files());
m_watcher.addPath(cssFile);
}
qApp->setStyleSheet(css);
return true;
}
void ThemeLoader::themeFileChanged()
{
setTheme(m_currentTheme);
}
| #include "theme-loader.h"
#include <QApplication>
#include <QDir>
#include <QFile>
ThemeLoader::ThemeLoader(QString path, QObject *parent)
: QObject(parent), m_path(std::move(path))
{
connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &ThemeLoader::themeFileChanged);
}
QStringList ThemeLoader::getAllThemes() const
{
return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}
bool ThemeLoader::setTheme(const QString &name)
{
const QString dir = QString(m_path).replace('\\', '/') + name + "/";
const QString cssFile = dir + "style.css";
QFile f(cssFile);
if (!f.open(QFile::ReadOnly | QFile::Text)) {
return false;
}
QString css = f.readAll();
f.close();
// Replace urls relative paths by absolute ones
css.replace("url(", "url(" + dir);
// Update watcher if necessary
if (m_currentTheme != name) {
m_currentTheme = name;
if (!m_watcher.files().isEmpty()) {
m_watcher.removePaths(m_watcher.files());
}
m_watcher.addPath(cssFile);
}
qApp->setStyleSheet(css);
return true;
}
void ThemeLoader::themeFileChanged()
{
setTheme(m_currentTheme);
}
|
Convert arg string to utf8 on Windows | // Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/node_debugger.h"
#include "base/command_line.h"
#include "libplatform/libplatform.h"
namespace atom {
NodeDebugger::NodeDebugger(node::Environment* env) : env_(env) {
}
NodeDebugger::~NodeDebugger() {
}
void NodeDebugger::Start() {
auto inspector = env_->inspector_agent();
if (inspector == nullptr)
return;
node::DebugOptions options;
for (auto& arg : base::CommandLine::ForCurrentProcess()->argv())
options.ParseOption(arg);
if (options.inspector_enabled()) {
// Use custom platform since the gin platform does not work correctly
// with node's inspector agent
platform_.reset(v8::platform::CreateDefaultPlatform());
inspector->Start(platform_.get(), nullptr, options);
}
}
} // namespace atom
| // Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/node_debugger.h"
#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "libplatform/libplatform.h"
namespace atom {
NodeDebugger::NodeDebugger(node::Environment* env) : env_(env) {
}
NodeDebugger::~NodeDebugger() {
}
void NodeDebugger::Start() {
auto inspector = env_->inspector_agent();
if (inspector == nullptr)
return;
node::DebugOptions options;
for (auto& arg : base::CommandLine::ForCurrentProcess()->argv()) {
#if defined(OS_WIN)
options.ParseOption(base::UTF16ToUTF8(arg));
#else
options.ParseOption(arg);
#endif
}
if (options.inspector_enabled()) {
// Use custom platform since the gin platform does not work correctly
// with node's inspector agent
platform_.reset(v8::platform::CreateDefaultPlatform());
inspector->Start(platform_.get(), nullptr, options);
}
}
} // namespace atom
|
Add the code to init the ActiveMQ-CPP library and shut it down when finished. | /*
* 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 <cms.h>
////////////////////////////////////////////////////////////////////////////////
void cms_initialize() {
}
////////////////////////////////////////////////////////////////////////////////
void cms_terminate() {
}
| /*
* 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 <cms.h>
#include <activemq/library/ActiveMQCPP.h>
////////////////////////////////////////////////////////////////////////////////
void cms_initialize() {
activemq::library::ActiveMQCPP::initializeLibrary();
}
////////////////////////////////////////////////////////////////////////////////
void cms_terminate() {
activemq::library::ActiveMQCPP::shutdownLibrary();
}
|
Fix compilation warning caused by use of "auto" | #include "threadpool.h"
ThreadPool::ThreadPool(size_t size)
{
for (auto i=0; i<size; ++i) {
workers.emplace_back([this] {
for (;;) {
std::unique_lock<std::mutex> lock(this->queue_mutex);
while (!this->m_stop && this->tasks.empty())
this->condition.wait(lock);
if (this->m_stop && this->tasks.empty())
return;
std::function<void()> task(this->tasks.front());
this->tasks.pop();
lock.unlock();
task();
}
});
}
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
m_stop = true;
}
condition.notify_all();
for (auto i=0; i<workers.size(); ++i)
workers[i].join();
}
| #include "threadpool.h"
ThreadPool::ThreadPool(size_t size)
{
for (size_t i=0; i<size; ++i) {
workers.emplace_back([this] {
for (;;) {
std::unique_lock<std::mutex> lock(this->queue_mutex);
while (!this->m_stop && this->tasks.empty())
this->condition.wait(lock);
if (this->m_stop && this->tasks.empty())
return;
std::function<void()> task(this->tasks.front());
this->tasks.pop();
lock.unlock();
task();
}
});
}
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
m_stop = true;
}
condition.notify_all();
for (auto i=0; i<workers.size(); ++i)
workers[i].join();
}
|
Add check in ultrasound sensor when reading from the serial port | #include "Sensor/UltrasoundSensor.h"
#include "Data/UltrasoundData.h"
UltrasoundSensor::UltrasoundSensor(string port, int baudrate) : Sensor("Ultrasound Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)) {
}
UltrasoundSensor::~UltrasoundSensor() {
}
bool UltrasoundSensor::ping() {
return conn->isConnected() == 1;
}
void UltrasoundSensor::fillData(SensorData& sensorData) {
if (conn->isConnected()) {
char data[256];
int bytesRead = conn->read(data, 256);
// Decode the incoming data
R2Protocol::Packet params;
std::vector<uint8_t> input(data, data + bytesRead);
int32_t read;
ptr<UltrasoundData> udata = std::make_shared<UltrasoundData>();
while ((read = R2Protocol::decode(input, params)) >= 0) {
if (params.source == "U1SENSOR") {
udata->distance = std::atof((char *) params.data.data());
}
std::vector<uint8_t>(input.begin() + read, input.end()).swap(input);
}
sensorData["ULTRASOUND"] = udata;
printf("Ultrasound: %f\n", udata->distance);
}
} | #include "Sensor/UltrasoundSensor.h"
#include "Data/UltrasoundData.h"
UltrasoundSensor::UltrasoundSensor(string port, int baudrate) : Sensor("Ultrasound Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)) {
}
UltrasoundSensor::~UltrasoundSensor() {
}
bool UltrasoundSensor::ping() {
return conn->isConnected() == 1;
}
void UltrasoundSensor::fillData(SensorData& sensorData) {
if (conn->isConnected()) {
char data[256];
int bytesRead = conn->read(data, 256);
if (bytesRead <= 0) {
return;
}
// Decode the incoming data
R2Protocol::Packet params;
std::vector<uint8_t> input(data, data + bytesRead);
int32_t read;
ptr<UltrasoundData> udata = std::make_shared<UltrasoundData>();
while ((read = R2Protocol::decode(input, params)) >= 0) {
if (params.source == "U1SENSOR") {
udata->distance = std::atof((char *) params.data.data());
}
std::vector<uint8_t> newinput(input.begin() + read, input.end());
newinput.swap(input);
}
sensorData["ULTRASOUND"] = udata;
printf("Ultrasound: %f\n", udata->distance);
}
} |
Remove erroneous check for reference params. | /*
* File.cpp
*
* Created on: Jun 24, 2015
* Author: gatanasov
*/
#include "File.h"
#include <sstream>
using namespace std;
namespace tns
{
string File::ReadText(const string& filePath)
{
int len;
bool isNew;
const char *content = ReadText(filePath, len, isNew);
string s(content, len);
if(isNew)
{
delete[] content;
}
return s;
}
const char* File::ReadText(const string& filePath, int& charLength, bool& isNew)
{
FILE *file = fopen(filePath.c_str(), "rb");
fseek(file, 0, SEEK_END);
int len = ftell(file);
if(charLength)
{
charLength = len;
}
bool exceedBuffer = len > BUFFER_SIZE;
if(isNew)
{
isNew = exceedBuffer;
}
rewind(file);
if(exceedBuffer)
{
char* newBuffer = new char[len];
fread(newBuffer, 1, len, file);
fclose(file);
return newBuffer;
}
fread(Buffer, 1, len, file);
fclose(file);
return Buffer;
}
char* File::Buffer = new char[BUFFER_SIZE];
}
| /*
* File.cpp
*
* Created on: Jun 24, 2015
* Author: gatanasov
*/
#include "File.h"
#include <sstream>
using namespace std;
namespace tns
{
string File::ReadText(const string& filePath)
{
int len;
bool isNew;
const char *content = ReadText(filePath, len, isNew);
string s(content, len);
if(isNew)
{
delete[] content;
}
return s;
}
const char* File::ReadText(const string& filePath, int& charLength, bool& isNew)
{
FILE *file = fopen(filePath.c_str(), "rb");
fseek(file, 0, SEEK_END);
charLength = ftell(file);
isNew = charLength > BUFFER_SIZE;
rewind(file);
if(isNew)
{
char* newBuffer = new char[charLength];
fread(newBuffer, 1, charLength, file);
fclose(file);
return newBuffer;
}
fread(Buffer, 1, charLength, file);
fclose(file);
return Buffer;
}
char* File::Buffer = new char[BUFFER_SIZE];
}
|
Change catch statement to catch by reference | #include <memory>
#include <miniMAT/checker/Checker.hpp>
#include <iostream>
namespace miniMAT {
namespace checker {
Checker::Checker(std::shared_ptr<std::map<std::string, Matrix>> vars,
std::shared_ptr<reporter::ErrorReporter> reporter) {
this->vars = vars;
this->reporter = reporter;
}
std::shared_ptr<ast::AST> Checker::check(std::shared_ptr<ast::AST> ast) {
try {
ast->VisitCheck(this->vars, this->reporter);
return ast;
} catch (std::string error) {
reporter->AddCheckError(error);
return nullptr;
}
}
}
}
| #include <memory>
#include <miniMAT/checker/Checker.hpp>
#include <iostream>
namespace miniMAT {
namespace checker {
Checker::Checker(std::shared_ptr<std::map<std::string, Matrix>> vars,
std::shared_ptr<reporter::ErrorReporter> reporter) {
this->vars = vars;
this->reporter = reporter;
}
std::shared_ptr<ast::AST> Checker::check(std::shared_ptr<ast::AST> ast) {
try {
ast->VisitCheck(this->vars, this->reporter);
return ast;
} catch (std::string& error) {
reporter->AddCheckError(error);
return nullptr;
}
}
}
}
|
Add a simple login feature | #include <iostream>
#include "server.h"
Server::Server(unsigned short port) {
// logging settings
bottleserve.set_access_channels(websocketpp::log::alevel::all);
bottleserve.clear_access_channels(websocketpp::log::alevel::frame_payload);
bottleserve.init_asio();
bottleserve.set_message_handler([this] (websocketpp::connection_hdl hdl, message_ptr msg) {
bottleserve.send(hdl, msg->get_payload(), msg->get_opcode());
std::cout << msg->get_raw_payload() << std::endl;
});
bottleserve.listen(port);
}
void Server::run() {
bottleserve.start_accept();
bottleserve.run();
}
| #include <iostream>
#include <sstream>
#include "server.h"
using namespace std;
/*
* Splits a string based on a delimiter character
*
* Won't split into more than 'max' strings. Returns the number of strings that were added
*/
template<typename Iter>
size_t split(const string& str, char val, size_t max, Iter out) {
stringstream ss(str);
string s;
size_t len = 0;
// I love the "goes to" operator (-->)
while( max --> 0 ) {
if(!getline(ss, s, max ? val : '\0')) {
return len;
}
len++;
*out++ = s;
}
return len;
}
bool valid_user(const string& user, const string& pass) {
// TODO: Actually check the username and password here
return user == "anon" || (user == "corny" && pass == "1234");
}
Server::Server(unsigned short port) {
// logging settings
bottleserve.set_access_channels(websocketpp::log::alevel::all);
bottleserve.clear_access_channels(websocketpp::log::alevel::frame_payload);
bottleserve.init_asio();
bottleserve.set_message_handler([this] (websocketpp::connection_hdl hdl, message_ptr msg) {
using namespace websocketpp;
if(msg->get_opcode() != frame::opcode::text) {
bottleserve.close(hdl, close::status::unsupported_data, "Only text data allowed");
return;
}
const auto & line = msg->get_payload();
array<string,3> login;
if(login.size() != split(line, ' ', login.size(), login.begin())
|| login[0] != "login"
|| !valid_user(login[1], login[2])) {
bottleserve.close(hdl, close::status::unsupported_data, "Invalid login");
return;
}
// TODO: Create a connection
bottleserve.send(hdl, msg->get_payload(), msg->get_opcode());
cout << msg->get_opcode() << endl;
cout << msg->get_raw_payload() << endl;
});
bottleserve.listen(port);
}
void Server::run() {
bottleserve.start_accept();
bottleserve.run();
}
|
Convert newly-added test from -std=c++0x to -std=c++11. | // RUN: %clang_cc1 -fsyntax-only -std=c++0x -Wc++98-compat -verify %s
template<typename ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic1 {};
template<template<typename> class ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic2 {};
template<int ...I> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic3 {};
| // RUN: %clang_cc1 -fsyntax-only -std=c++11 -Wc++98-compat -verify %s
template<typename ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic1 {};
template<template<typename> class ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic2 {};
template<int ...I> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic3 {};
|
Fix relative location of bitfile | #include "libbbn-ni-r.h"
//global to hold on to session handle
NiFpga_Session session;
bool isOpen = false;
//Initialize FPGA on loading the library -- constructor hook in header
void init() {
NiFpga_Status status = NiFpga_Initialize();
}
//Cleanup NI library -- destructor hook in header
void cleanup(){
if (isOpen) {NiFpga_Close(session, 0);};
NiFpga_Finalize();
}
BBN_NI_R_STATUS open_load_run(){
NiFpga_Status status = NiFpga_Open(NiFpga_SimpleDigitizer_VI_Bitfile,
NiFpga_SimpleDigitizer_VI_Signature,
"RIO0", 0, &session);
if (status == NiFpga_Status_Success){
isOpen = true;
}
return status;
}
BBN_NI_R_STATUS set_numSamples(unsigned numSamples){
return 0;
};
BBN_NI_R_STATUS get_numSamples(unsigned* numSamples){
return 0;
};
BBN_NI_R_STATUS set_sampleInterval(unsigned sampleInterval){
return 0;
};
BBN_NI_R_STATUS get_sampleInterval(unsigned* sampleInterval){
return 0;
};
| #include "libbbn-ni-r.h"
//global to hold on to session handle
NiFpga_Session session;
bool isOpen = false;
//Initialize FPGA on loading the library -- constructor hook in header
void init() {
NiFpga_Status status = NiFpga_Initialize();
}
//Cleanup NI library -- destructor hook in header
void cleanup(){
if (isOpen) {NiFpga_Close(session, 0);};
NiFpga_Finalize();
}
BBN_NI_R_STATUS open_load_run(){
NiFpga_Status status = NiFpga_Open("../" NiFpga_SimpleDigitizer_VI_Bitfile,
NiFpga_SimpleDigitizer_VI_Signature,
"RIO0", 0, &session);
if (status == NiFpga_Status_Success){
isOpen = true;
}
return status;
}
BBN_NI_R_STATUS set_numSamples(unsigned numSamples){
return 0;
};
BBN_NI_R_STATUS get_numSamples(unsigned* numSamples){
return 0;
};
BBN_NI_R_STATUS set_sampleInterval(unsigned sampleInterval){
return 0;
};
BBN_NI_R_STATUS get_sampleInterval(unsigned* sampleInterval){
return 0;
};
|
Change constructor to set OutputFile. | #include "PlainPrinter.h"
PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
ASTAction<PlainPrinterAction>() {
OutputFile = std::make_shared<std::fstream>();
OutputFile->open(filename, std::fstream::out);
}
PlainPrinterAction::~PlainPrinterAction() {
OutputFile->close();
}
std::fstream &PlainPrinterAction::getStream() {
return *OutputFile;
}
PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }
| #include "PlainPrinter.h"
PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
ASTAction<PlainPrinterAction>(),
OutputFile(std::make_shared<std::fstream>()) {
OutputFile->open(filename, std::fstream::out);
}
PlainPrinterAction::~PlainPrinterAction() {
OutputFile->close();
}
std::fstream &PlainPrinterAction::getStream() {
return *OutputFile;
}
PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }
|
Edit ``contents.is_inserting`` in insert modes | #include <ncurses.h>
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"
void enter_insert_mode(contents& contents, boost::optional<int>) {
char ch;
while((ch = getch()) != _escape) {
contents.cont[contents.y].insert(contents.x, 1, ch);
mvf(contents);
if(get_contents().refresh) {
print_contents(get_contents());
}
}
}
void enter_replace_mode(contents& contents, boost::optional<int>) {
char ch;
while((ch = getch()) != _escape) {
if(contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
} else {
contents.cont[contents.y][contents.x] = ch;
}
if(get_contents().refresh) {
print_contents(get_contents());
}
}
}
| #include <ncurses.h>
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"
void enter_insert_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
contents.cont[contents.y].insert(contents.x, 1, ch);
mvf(contents);
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
void enter_replace_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
if(contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
} else {
contents.cont[contents.y][contents.x] = ch;
}
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
|
Support for blksize option (RFC 2348). | #include "wvtftps.h"
int main()
{
WvTFTPs tftps("/tftpboot", 30*1000);
while (tftps.isok())
{
if (tftps.select(0))
tftps.callback();
}
wvcon->print("TFTPs is not okay; aborting.\n");
}
| #include "wvtftps.h"
int main()
{
WvTFTPs tftps("/tftpboot", 30, 30);
while (tftps.isok())
{
if (tftps.select(0))
tftps.callback();
}
wvcon->print("TFTPs is not okay; aborting.\n");
}
|
Define this in the correct n/s | //===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ManagedStatic class and llvm_shutdown().
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ManagedStatic.h"
#include <cassert>
using namespace llvm;
static const ManagedStaticBase *StaticList = 0;
void ManagedStaticBase::RegisterManagedStatic(void *ObjPtr,
void (*Deleter)(void*)) const {
assert(Ptr == 0 && DeleterFn == 0 && Next == 0 &&
"Partially init static?");
Ptr = ObjPtr;
DeleterFn = Deleter;
// Add to list of managed statics.
Next = StaticList;
StaticList = this;
}
void ManagedStaticBase::destroy() const {
assert(Ptr && DeleterFn && "ManagedStatic not initialized correctly!");
assert(StaticList == this &&
"Not destroyed in reverse order of construction?");
// Unlink from list.
StaticList = Next;
Next = 0;
// Destroy memory.
DeleterFn(Ptr);
// Cleanup.
Ptr = 0;
DeleterFn = 0;
}
/// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
void llvm_shutdown() {
while (StaticList)
StaticList->destroy();
}
| //===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ManagedStatic class and llvm_shutdown().
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ManagedStatic.h"
#include <cassert>
using namespace llvm;
static const ManagedStaticBase *StaticList = 0;
void ManagedStaticBase::RegisterManagedStatic(void *ObjPtr,
void (*Deleter)(void*)) const {
assert(Ptr == 0 && DeleterFn == 0 && Next == 0 &&
"Partially init static?");
Ptr = ObjPtr;
DeleterFn = Deleter;
// Add to list of managed statics.
Next = StaticList;
StaticList = this;
}
void ManagedStaticBase::destroy() const {
assert(Ptr && DeleterFn && "ManagedStatic not initialized correctly!");
assert(StaticList == this &&
"Not destroyed in reverse order of construction?");
// Unlink from list.
StaticList = Next;
Next = 0;
// Destroy memory.
DeleterFn(Ptr);
// Cleanup.
Ptr = 0;
DeleterFn = 0;
}
/// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
void llvm::llvm_shutdown() {
while (StaticList)
StaticList->destroy();
}
|
Test formatting of special numbers | // Formatting library for C++ - Grisu tests
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#define FMT_USE_GRISU std::numeric_limits<double>::is_iec559
#include "fmt/format.h"
#include "gtest.h"
bool reported_skipped;
#undef TEST
#define TEST(test_fixture, test_name) \
void test_fixture##test_name(); \
GTEST_TEST(test_fixture, test_name) { \
if (FMT_USE_GRISU) { \
test_fixture##test_name(); \
} else if (!reported_skipped) { \
reported_skipped = true; \
fmt::print("Skipping Grisu tests.\n"); \
} \
} \
void test_fixture##test_name()
TEST(GrisuTest, NaN) {
EXPECT_EQ("nan", fmt::format("{}", std::numeric_limits<double>::quiet_NaN()));
}
| // Formatting library for C++ - Grisu tests
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#define FMT_USE_GRISU std::numeric_limits<double>::is_iec559
#include "fmt/format.h"
#include "gtest.h"
bool reported_skipped;
#undef TEST
#define TEST(test_fixture, test_name) \
void test_fixture##test_name(); \
GTEST_TEST(test_fixture, test_name) { \
if (FMT_USE_GRISU) { \
test_fixture##test_name(); \
} else if (!reported_skipped) { \
reported_skipped = true; \
fmt::print("Skipping Grisu tests.\n"); \
} \
} \
void test_fixture##test_name()
TEST(GrisuTest, NaN) {
auto nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_EQ("nan", fmt::format("{}", nan));
EXPECT_EQ("-nan", fmt::format("{}", -nan));
}
TEST(GrisuTest, Inf) {
auto inf = std::numeric_limits<double>::infinity();
EXPECT_EQ("inf", fmt::format("{}", inf));
EXPECT_EQ("-inf", fmt::format("{}", -inf));
}
TEST(GrisuTest, Zero) {
EXPECT_EQ("0", fmt::format("{}", 0.0));
}
|
Fix compile error in TestCxxWCharT on Linux | //===-- main.c --------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
template <typename T>
class Foo
{
public:
Foo () : object() {}
Foo (T x) : object(x) {}
T getObject() { return object; }
private:
T object;
};
int main (int argc, char const *argv[])
{
Foo<int> foo_x('a');
Foo<wchar_t> foo_y(L'a');
const wchar_t *mazeltov = L"מזל טוב";
wchar_t *ws_NULL = nullptr;
wchar_t *ws_empty = L"";
wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž";
memcpy(array, array_source, 39 * sizeof(wchar_t));
return 0; // Set break point at this line.
}
| //===-- main.c --------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cstring>
template <typename T>
class Foo
{
public:
Foo () : object() {}
Foo (T x) : object(x) {}
T getObject() { return object; }
private:
T object;
};
int main (int argc, char const *argv[])
{
Foo<int> foo_x('a');
Foo<wchar_t> foo_y(L'a');
const wchar_t *mazeltov = L"מזל טוב";
wchar_t *ws_NULL = nullptr;
wchar_t *ws_empty = L"";
wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž";
memcpy(array, array_source, 39 * sizeof(wchar_t));
return 0; // Set break point at this line.
}
|
Handle return memory of size 0 and large offset |
#include "Runtime.h"
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>
namespace dev
{
namespace eth
{
namespace jit
{
Runtime::Runtime(RuntimeData* _data, Env* _env) :
m_data(*_data),
m_env(*_env),
m_currJmpBuf(m_jmpBuf)
{}
bytes Runtime::getReturnData() const // FIXME: Reconsider returning by copy
{
// TODO: Handle large indexes
auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset]));
auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize]));
assert(offset + size <= m_memory.size());
// TODO: Handle invalid data access by returning empty ref
auto dataBeg = m_memory.begin() + offset;
return {dataBeg, dataBeg + size};
}
}
}
}
|
#include "Runtime.h"
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>
namespace dev
{
namespace eth
{
namespace jit
{
Runtime::Runtime(RuntimeData* _data, Env* _env) :
m_data(*_data),
m_env(*_env),
m_currJmpBuf(m_jmpBuf)
{}
bytes Runtime::getReturnData() const // FIXME: Reconsider returning by copy
{
// TODO: Handle large indexes
auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset]));
auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize]));
assert(offset + size <= m_memory.size() || size == 0);
if (offset + size > m_memory.size())
return {};
auto dataBeg = m_memory.begin() + offset;
return {dataBeg, dataBeg + size};
}
}
}
}
|
Simplify stack check in accert.cc Somehow on arm bots stack does not include main. | // Test the handle_abort option.
// clang-format off
// RUN: %clangxx %s -o %t
// RUN: not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=0 not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=1 not %run %t
// RUN: %env_tool_opts=handle_abort=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK1 %s
// clang-format on
// FIXME: implement in other sanitizers.
// XFAIL: tsan
#include <assert.h>
#include <stdio.h>
#include <sanitizer/asan_interface.h>
void death() {
fprintf(stderr, "DEATH CALLBACK\n");
}
int main(int argc, char **argv) {
__sanitizer_set_death_callback(death);
assert(argc == 100);
}
// CHECK0-NOT: Sanitizer:DEADLYSIGNAL
// CHECK1: ERROR: {{.*}}Sanitizer: ABRT
// CHECK1: {{#[0-9]+.* main .*assert\.cc}}:[[@LINE-5]]
// CHECK1: DEATH CALLBACK
// CHECK0-NOT: Sanitizer
| // Test the handle_abort option.
// clang-format off
// RUN: %clangxx %s -o %t
// RUN: not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=0 not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK1 %s
// clang-format on
// FIXME: implement in other sanitizers.
// XFAIL: tsan
#include <assert.h>
#include <stdio.h>
#include <sanitizer/asan_interface.h>
void death() {
fprintf(stderr, "DEATH CALLBACK\n");
}
int main(int argc, char **argv) {
__sanitizer_set_death_callback(death);
assert(argc == 100);
}
// CHECK0-NOT: Sanitizer:DEADLYSIGNAL
// CHECK1: ERROR: {{.*}}Sanitizer: ABRT
// CHECK1-NEXT: {{ #0 }}
// CHECK1-NEXT: {{ #1 }}
// CHECK1: DEATH CALLBACK
// CHECK0-NOT: Sanitizer
|
Fix return type in c_api_func | #include <im_str/im_str.hpp>
#include <cstring>
#include <string>
#include <iostream>
int c_api_func(const char* str) {
return std::strlen( str );
}
int main() {
using namespace std::string_literals;
mba::im_str str1 = "Hello ";
auto greeting = mba::concat( str1, "World"s, "!" );
std::cout << greeting << std::endl;
std::cout << greeting.size() << " == " << c_api_func( greeting.c_str() ) << std::endl;
} | #include <im_str/im_str.hpp>
#include <cstring>
#include <string>
#include <iostream>
std::size_t c_api_func(const char* str) {
return std::strlen( str );
}
int main() {
using namespace std::string_literals;
mba::im_str str1 = "Hello ";
auto greeting = mba::concat( str1, "World"s, "!" );
std::cout << greeting << std::endl;
std::cout << greeting.size() << " == " << c_api_func( greeting.c_str() ) << std::endl;
} |
Fix issue with static order creation | #include "dukbind_validation.h"
#include <regex>
namespace dukbind
{
namespace validation
{
static std::regex identifer_regex( "[a-zA-Z$_][a-zA-Z0-9$_]*" );
bool IsValidIdentifier( const char * identifier )
{
return std::regex_match( identifier, identifer_regex );
}
}
}
| #include "dukbind_validation.h"
#include <regex>
namespace dukbind
{
namespace validation
{
const std::regex & getIndentifierRegex()
{
static std::regex identifer_regex( "[a-zA-Z$_][a-zA-Z0-9$_]*" );
return identifer_regex;
}
bool IsValidIdentifier( const char * identifier )
{
return std::regex_match( identifier, getIndentifierRegex() );
}
}
}
|
Implement automatic refreshing in ncurses::Session using halfdelay | #include "session.h"
#include <ncurses.h>
namespace ncurses
{
std::shared_ptr < Panel > Session::panel;
void Session::init ()
{
// Standard ncurses init methods
initscr ();
cbreak ();
noecho ();
start_color ();
use_default_colors ();
refresh ();
// Initialize all possible color combinations, using a simple calculation
// This enables us to change the colors in Window way comfortably than any
// other solution
for ( int fg = -1; fg < 8; fg++ )
{
for ( int bg = -1; bg < 8; bg++ )
{
init_pair ( 2 + fg + 8 * ( 1 + bg ), fg, bg );
}
}
}
void Session::end ()
{
endwin ();
}
void Session::update ()
{
char input = getch ();
// This is only temporary
int max_x, max_y;
getmaxyx ( stdscr, max_y, max_x );
std::shared_ptr < Window > window = std::make_shared < Window > ( 0, 0, max_x, max_y );
if ( panel.get () != nullptr )
{
panel->update ( input, window );
}
}
void Session::set_panel ( const std::shared_ptr < Panel >& panel_ )
{
panel = panel_;
}
std::shared_ptr < Panel > Session::get_panel ()
{
return panel;
}
}
| #include "session.h"
#include <ncurses.h>
namespace ncurses
{
std::shared_ptr < Panel > Session::panel;
void Session::init ()
{
// Standard ncurses init methods
initscr ();
// Update every 2.5 seconds
halfdelay ( 25 );
noecho ();
start_color ();
use_default_colors ();
refresh ();
// Initialize all possible color combinations, using a simple calculation
// This enables us to change the colors in Window way comfortably than any
// other solution
for ( int fg = -1; fg < 8; fg++ )
{
for ( int bg = -1; bg < 8; bg++ )
{
init_pair ( 2 + fg + 8 * ( 1 + bg ), fg, bg );
}
}
}
void Session::end ()
{
endwin ();
}
void Session::update ()
{
char input = getch ();
// This is only temporary
int max_x, max_y;
getmaxyx ( stdscr, max_y, max_x );
std::shared_ptr < Window > window = std::make_shared < Window > ( 0, 0, max_x, max_y );
if ( panel.get () != nullptr )
{
panel->update ( input, window );
}
}
void Session::set_panel ( const std::shared_ptr < Panel >& panel_ )
{
panel = panel_;
}
std::shared_ptr < Panel > Session::get_panel ()
{
return panel;
}
}
|
Reconfigure zeus for 38400 baud operation on USART1 and 3. | #include "variant/usart_platform.hpp"
#include "hal.h"
// USART1 configuration
static const SerialConfig usart1_config = {
115200,
0,
USART_CR2_STOP1_BITS | USART_CR2_LINEN,
0
};
// USART3 configuration
static const SerialConfig usart3_config = {
115200,
0,
USART_CR2_STOP1_BITS | USART_CR2_LINEN,
0
};
USARTPlatform::USARTPlatform() {
sdStart(&SD1, &usart1_config);
sdStart(&SD3, &usart3_config);
palSetPadMode(GPIOB, 6, PAL_MODE_ALTERNATE(7)); // USART1 TX
palSetPadMode(GPIOB, 7, PAL_MODE_ALTERNATE(7)); // USART1 RX
palSetPadMode(GPIOB, 10, PAL_MODE_ALTERNATE(7)); // USART3 TX
palSetPadMode(GPIOB, 11, PAL_MODE_ALTERNATE(7)); // USART3 RX
}
chibios_rt::BaseSequentialStreamInterface& USARTPlatform::getPrimaryStream() {
return reinterpret_cast<chibios_rt::BaseSequentialStreamInterface&>(SD1);
}
| #include "variant/usart_platform.hpp"
#include "hal.h"
// USART1 configuration
static const SerialConfig usart1_config = {
38400,
0,
USART_CR2_STOP1_BITS | USART_CR2_LINEN,
0
};
// USART3 configuration
static const SerialConfig usart3_config = {
38400,
0,
USART_CR2_STOP1_BITS | USART_CR2_LINEN,
0
};
USARTPlatform::USARTPlatform() {
sdStart(&SD1, &usart1_config);
sdStart(&SD3, &usart3_config);
palSetPadMode(GPIOB, 6, PAL_MODE_ALTERNATE(7)); // USART1 TX
palSetPadMode(GPIOB, 7, PAL_MODE_ALTERNATE(7)); // USART1 RX
palSetPadMode(GPIOB, 10, PAL_MODE_ALTERNATE(7)); // USART3 TX
palSetPadMode(GPIOB, 11, PAL_MODE_ALTERNATE(7)); // USART3 RX
}
chibios_rt::BaseSequentialStreamInterface& USARTPlatform::getPrimaryStream() {
return reinterpret_cast<chibios_rt::BaseSequentialStreamInterface&>(SD1);
}
|
Add code to add aura to game and battlefield | // 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/Enchants/Aura.hpp>
#include <Rosetta/Models/Battlefield.hpp>
#include <Rosetta/Models/Player.hpp>
namespace RosettaStone
{
Aura::Aura(std::string&& enchantmentID, AuraType type)
: m_enchantmentID(enchantmentID), m_type(type)
{
// Do nothing
}
void Aura::Activate(Entity& owner)
{
switch (m_type)
{
case AuraType::FIELD_EXCEPT_SOURCE:
{
for (auto& minion : owner.GetOwner().GetField().GetAllMinions())
{
if (minion == &owner)
{
continue;
}
}
break;
}
}
}
} // namespace RosettaStone
| // 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/Enchants/Aura.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Battlefield.hpp>
#include <Rosetta/Models/Player.hpp>
namespace RosettaStone
{
Aura::Aura(std::string&& enchantmentID, AuraType type)
: m_enchantmentID(enchantmentID), m_type(type)
{
// Do nothing
}
void Aura::Activate(Entity& owner)
{
owner.GetOwner().GetGame()->auras.emplace_back(this);
switch (m_type)
{
case AuraType::FIELD_EXCEPT_SOURCE:
{
owner.GetOwner().GetField().AddAura(this);
break;
}
}
}
} // namespace RosettaStone
|
Change std::regex detection test to detect bug in libstdc++. | #include <regex>
#include <string>
int main() {
const std::string str = "test0159";
const std::regex re(
"^[a-z]+[0-9]+$",
std::regex_constants::extended | std::regex_constants::nosubs);
return std::regex_search(str, re) ? 0 : -1;
}
| #include <regex>
#include <string>
int main() {
const std::string str = "test0159";
std::regex re;
re = std::regex("^[a-z]+[0-9]+$",
std::regex_constants::extended | std::regex_constants::nosubs);
return std::regex_search(str, re) ? 0 : -1;
}
|
Fix wrong reference to header | #include "vm.hpp"
#include "vm/object_utils.hpp"
#include "capi/capi.hpp"
#include "capi/include/ruby.h"
using namespace rubinius;
using namespace rubinius::capi;
extern "C" {
VALUE rb_file_open(const char* name, const char* mode) {
NativeMethodEnvironment* env = NativeMethodEnvironment::get();
VALUE n = env->get_handle(String::create(env->state(), name));
VALUE m = env->get_handle(String::create(env->state(), mode));
return rb_funcall(rb_cFile, rb_intern("open"), 2, n, m);
}
}
| #include "vm.hpp"
#include "vm/object_utils.hpp"
#include "capi/capi.hpp"
#include "capi/18/include/ruby.h"
using namespace rubinius;
using namespace rubinius::capi;
extern "C" {
VALUE rb_file_open(const char* name, const char* mode) {
NativeMethodEnvironment* env = NativeMethodEnvironment::get();
VALUE n = env->get_handle(String::create(env->state(), name));
VALUE m = env->get_handle(String::create(env->state(), mode));
return rb_funcall(rb_cFile, rb_intern("open"), 2, n, m);
}
}
|
Add default parameters for constructor | #include "../Swarm.h"
#include <Eigen/Core>
#include <pybind11/eigen.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace MetaOpt
{
namespace Python {
namespace py = pybind11;
void init_swarm(py::module &m) {
py::class_<Swarm>(m, "Swarm")
.def(py::init<const ParameterSpace &, const Parameters &, std::size_t,
const int>())
.def("optimize", &Swarm::optimize)
.def("getSolution", &Swarm::getBestSolution);
}
}
}
| #include "../Swarm.h"
#include <Eigen/Core>
#include <pybind11/eigen.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace MetaOpt {
namespace Python {
namespace py = pybind11;
void init_swarm(py::module &m) {
auto constructor = py::init<const ParameterSpace &, const Parameters &,
std::size_t, const int>();
py::class_<Swarm>(m, "Swarm")
.def(constructor, py::arg("parameter_space"), py::arg("hyper_params"),
py::arg("num_particles") = 10, py::arg("seed") = -1)
.def("optimize", &Swarm::optimize)
.def("getBestSolution", &Swarm::getBestSolution)
.def("getBestParameters", &Swarm::getBestParameters);
}
}
}
|
Solve some silly problems with the algorithm. | #include <algorithm>
#include <set>
using namespace std;
typedef set<int> si;
/* Get the divisors of a number */
si divisores(int n) {
vi d;
int r = sqrt(n);
for(int i = 1; i <= r; i++) {
if(n % i == 0) {
d.insert(i);
d.insert(n / i);
}
}
return d;
}
int main() {
si divi = divisores(10);
for (set<int>::iterator it=divi.begin(); it!=divi.end(); ++it)
printf("%d ", *it);
printf("\n");
}
| #include <algorithm>
#include <math.h>
#include <set>
#include <stdio.h>
using namespace std;
typedef set<int> si;
/* Get the divisors of a number */
si divisores(int n) {
si d;
int r = sqrt(n);
for(int i = 1; i <= r; i++) {
if(n % i == 0) {
d.insert(i);
d.insert(n / i);
}
}
return d;
}
int main() {
si divi = divisores(10);
for (set<int>::iterator it=divi.begin(); it!=divi.end(); ++it)
printf("%d ", *it);
printf("\n");
}
|
Fix multiple compilations for one file | #include "dependency_tree.hpp"
#include "osal.hpp"
#include "file_exist.hpp"
#include "resolver.hpp"
#include <algorithm>
Resolver *DependencyTree::addTarget(const std::string &fileName)
{
auto &&res = tree.insert(std::make_pair(fileName, std::make_unique<Resolver>()));
if (!res.second)
throw std::runtime_error("Duplicated target: " + fileName);
return res.first->second.get();
}
void DependencyTree::resolve()
{
resolvedList.clear();
for (auto &&target : tree)
resolve(target.first);
}
// TODO run in parallel
void DependencyTree::resolve(const std::string &target)
{
auto &&resolver = tree.find(target);
if (resolver == std::end(tree))
{
resolvedList.insert(target);
return;
}
time_t newestModificationTime = 0;
for (auto &&dependency : resolver->second->dependencies)
{
resolve(dependency);
newestModificationTime = std::max(getFileModification(dependency), newestModificationTime);
}
if (!isFileExist(target))
{
resolver->second->exec();
resolvedList.insert(target);
return;
}
auto time = getFileModification(target);
if (time < newestModificationTime)
resolver->second->exec();
resolvedList.insert(target);
return;
}
| #include "dependency_tree.hpp"
#include "osal.hpp"
#include "file_exist.hpp"
#include "resolver.hpp"
#include <algorithm>
Resolver *DependencyTree::addTarget(const std::string &fileName)
{
auto &&res = tree.insert(std::make_pair(fileName, std::make_unique<Resolver>()));
if (!res.second)
throw std::runtime_error("Duplicated target: " + fileName);
return res.first->second.get();
}
void DependencyTree::resolve()
{
resolvedList.clear();
for (auto &&target : tree)
resolve(target.first);
}
// TODO run in parallel
void DependencyTree::resolve(const std::string &target)
{
if (resolvedList.find(target) != std::end(resolvedList))
return;
auto &&resolver = tree.find(target);
if (resolver == std::end(tree))
{
resolvedList.insert(target);
return;
}
time_t newestModificationTime = 0;
for (auto &&dependency : resolver->second->dependencies)
{
resolve(dependency);
newestModificationTime = std::max(getFileModification(dependency), newestModificationTime);
}
if (!isFileExist(target))
{
resolver->second->exec();
resolvedList.insert(target);
return;
}
auto time = getFileModification(target);
if (time < newestModificationTime)
resolver->second->exec();
resolvedList.insert(target);
return;
}
|
Add posix process popen streambufs | #ifndef PIPED_PROCESS_CPP
#define PIPED_PROCESS_CPP
#include<iostream>
class child_process_streambuf: public std::streambuf
{
public:
virtual int underflow()
{
}
virtual std::streamsize xsgetn(char* bufout,std::streamsize n)
{
}
virtual std::streamsize xsputn(const char* bufin,std::streamsize n)
{
}
};
#endif | #include<iostream>
#include<streambuf>
#include<unistd.h>
#include<cstdio>
#include<cerrno>
#include<stdexcept>
#include<system_error>
class process_streambuf_base: public std::streambuf
{
protected:
FILE* pipefile;
public:
enum ReadWriteType
{
READ_ONLY=0,
WRITE_ONLY
};
process_streambuf_base(const std::string& cmd,ReadWriteType rwflag)
{
static const char* typestring[2]={"re","we"};
pipefile=popen(cmd.c_str(),typestring[(int)rwflag]);
if(!pipefile)
{
throw std::system_error(errno,strerror(errno));
}
}
virtual ~process_streambuf_base()
{
int pclose(pipefile);
}
};
class process_readstreambuf: public process_streambuf_base
{
public:
process_readstreambuf(const std::string& cmd):
process_streambuf_base(cmd,READ_ONLY)
{}
virtual int underflow()
{
return fgetc(pipefile);
}
virtual std::streamsize xsgetn(char* bufout, streamsize n)
{
return fread(bufout,n,1,pipefile);
}
};
class process_writestreambuf: public process_streambuf_base
{
public:
process_writestreambuf(const std::string& cmd):
process_streambuf_base(cmd,WRITE_ONLY)
{}
virtual int overflow(int c=EOF)
{
return fputc(pipefile);
}
virtual std::streamsize xsputn(const char* bufin, streamsize n)
{
return fwrite(bufin,n,1,pipefile);
}
}; |
Apply naming rule to dataSet -> dataset | //=======================================================================
// Copyright (c) 2017 Adrian Schneider
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include "mnist/mnist_reader.hpp"
int main(int argc, char* argv[]) {
// MNIST_DATA_LOCATION set by MNIST cmake config
std::cout << "MNIST data directory: " << MNIST_DATA_LOCATION << std::endl;
// Load MNIST data
mnist::MNIST_dataset<std::vector, std::vector<uint8_t>, uint8_t> dataSet =
mnist::read_dataset<std::vector, std::vector, uint8_t, uint8_t>(MNIST_DATA_LOCATION);
std::cout << "Nbr of training images = " << dataSet.training_images.size() << std::endl;
std::cout << "Nbr of training labels = " << dataSet.training_labels.size() << std::endl;
std::cout << "Nbr of test images = " << dataSet.test_images.size() << std::endl;
std::cout << "Nbr of test labels = " << dataSet.test_labels.size() << std::endl;
return 0;
}
| //=======================================================================
// Copyright (c) 2017 Adrian Schneider
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include "mnist/mnist_reader.hpp"
int main(int argc, char* argv[]) {
// MNIST_DATA_LOCATION set by MNIST cmake config
std::cout << "MNIST data directory: " << MNIST_DATA_LOCATION << std::endl;
// Load MNIST data
mnist::MNIST_dataset<std::vector, std::vector<uint8_t>, uint8_t> dataset =
mnist::read_dataset<std::vector, std::vector, uint8_t, uint8_t>(MNIST_DATA_LOCATION);
std::cout << "Nbr of training images = " << dataset.training_images.size() << std::endl;
std::cout << "Nbr of training labels = " << dataset.training_labels.size() << std::endl;
std::cout << "Nbr of test images = " << dataset.test_images.size() << std::endl;
std::cout << "Nbr of test labels = " << dataset.test_labels.size() << std::endl;
return 0;
}
|
Add 500 ms delay on boot | #include <HX711.h>
#include "TimerDisplay.h"
#include "GramsDisplay.h"
#include "SmoothingFilter.h"
#define DISP_TIMER_CLK 2
#define DISP_TIMER_DIO 3
#define DISP_SCALE_CLK 8
#define DISP_SCALE_DIO 9
#define FILTER_SIZE 10
#define HYSTERESIS_SIZE 0.1
#define LOAD_CELL_DT A2
#define LOAD_CELL_SCK A1
#define SCALE_FACTOR 1874
#define TARE_AVERAGES 10
HX711 loadCell(LOAD_CELL_DT, LOAD_CELL_SCK);
TimerDisplay timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO);
GramsDisplay gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO);
SmoothingFilter filter(FILTER_SIZE, HYSTERESIS_SIZE);
void setup()
{
// Serial comm
Serial.begin(38400);
loadCell.set_scale(SCALE_FACTOR);
loadCell.tare(TARE_AVERAGES);
}
void loop()
{
filter.addValue(loadCell.get_units());
float weight_in_grams = filter.getValue();
gramsDisplay.display(weight_in_grams);
if (weight_in_grams > 1)
timerDisplay.start();
timerDisplay.refresh();
}
| #include <HX711.h>
#include "TimerDisplay.h"
#include "GramsDisplay.h"
#include "SmoothingFilter.h"
#define DISP_TIMER_CLK 2
#define DISP_TIMER_DIO 3
#define DISP_SCALE_CLK 8
#define DISP_SCALE_DIO 9
#define FILTER_SIZE 10
#define HYSTERESIS_SIZE 0.1
#define LOAD_CELL_DT A2
#define LOAD_CELL_SCK A1
#define SCALE_FACTOR 1874
#define TARE_AVERAGES 10
HX711 loadCell(LOAD_CELL_DT, LOAD_CELL_SCK);
TimerDisplay timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO);
GramsDisplay gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO);
SmoothingFilter filter(FILTER_SIZE, HYSTERESIS_SIZE);
void setup()
{
// Serial comm
Serial.begin(38400);
delay(500);
loadCell.set_scale(SCALE_FACTOR);
loadCell.tare(TARE_AVERAGES);
}
void loop()
{
filter.addValue(loadCell.get_units());
float weight_in_grams = filter.getValue();
gramsDisplay.display(weight_in_grams);
if (weight_in_grams > 1)
timerDisplay.start();
timerDisplay.refresh();
}
|
Disable webrtc cast api test | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
class WebrtcCastApiTest : public ExtensionApiTest {
};
// Test running the test extension for Cast Mirroring API.
IN_PROC_BROWSER_TEST_F(WebrtcCastApiTest, Basics) {
ASSERT_TRUE(RunExtensionSubtest("webrtc_cast", "basics.html"));
}
} // namespace extensions
| // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
class WebrtcCastApiTest : public ExtensionApiTest {
};
// Test running the test extension for Cast Mirroring API.
IN_PROC_BROWSER_TEST_F(WebrtcCastApiTest, DISABLED_Basics) {
ASSERT_TRUE(RunExtensionSubtest("webrtc_cast", "basics.html"));
}
} // namespace extensions
|
Fix after @rafaelcn did blame me crying about incorrect usage of cerr | /**
* C++ algorithm to get the sum of all prime numbers between a range of 2 and the number desired.
*/
#include <iostream>
#include <cstdlib>
bool is_prime(unsigned int number);
int main(int argc, char* argv[])
{
const char *num = "2000000";
if(argv[1])
num = argv[1];
else if (argv[1] == "--help")
std::cerr << "Usage: primes <number_of_primes>" << std::endl;
std::cerr << "You've choosen the sum of the first " << num
<< " prime numbers." << std::endl;
// iteration variables.
int i = 1;
int j = 0;
// the number to reach.
int number_to = atoi(num);
int sum = 0;
while(j < number_to)
{
if(is_prime(i))
{
std::cerr << i << std::endl;
sum += i;
j++;
}
i++;
}
std::cerr << "The sum of the numbers between 2 and " << number_to
<< " are: " << sum << std::endl;
std::cout << sum << std::endl;
}
bool is_prime(unsigned int number)
{
if (number <= 1)
return false;
unsigned int i;
for (i=2; i*i<=number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
} | /**
* C++ algorithm to get the sum of all prime numbers between a range of 2 and the number desired.
*/
#include <iostream>
#include <cstdlib>
#include <string.h>
bool is_prime(unsigned int number);
int main(int argc, char* argv[])
{
const char *num = "2000000";
if (strcmp(argv[1],"--help") == 0){
std::cerr << "Usage: primes <number_of_primes>" << std::endl;
exit(0);
}
else if(argv[1]) {
num = argv[1];
}
// iteration variables.
int i = 1;
int j = 0;
// the number to reach.
int number_to = atoi(num);
int sum = 0;
while(j < number_to)
{
if(is_prime(i))
{
sum += i;
j++;
}
i++;
}
std::cout << sum << std::endl;
}
bool is_prime(unsigned int number)
{
if (number <= 1)
return false;
unsigned int i;
for (i=2; i*i<=number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
} |
Add some missing includes, necessary on some platforms. | #include <iostream>
// Entry point for Dinit.
int dinit_main(int argc, char **argv);
int main(int argc, char **argv)
{
try {
return dinit_main(argc, argv);
}
catch (std::bad_alloc &badalloc) {
std::cout << "dinit: Out-of-memory during initialisation" << std::endl;
return 1;
}
catch (std::system_error &syserr) {
std::cout << "dinit: unexpected system error during initialisation: " << syserr.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "dinit: unexpected error during initialisation" << std::endl;
return 1;
}
}
| #include <iostream>
#include <system_error>
#include <new>
// Entry point for Dinit.
int dinit_main(int argc, char **argv);
int main(int argc, char **argv)
{
try {
return dinit_main(argc, argv);
}
catch (std::bad_alloc &badalloc) {
std::cout << "dinit: Out-of-memory during initialisation" << std::endl;
return 1;
}
catch (std::system_error &syserr) {
std::cout << "dinit: unexpected system error during initialisation: " << syserr.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "dinit: unexpected error during initialisation" << std::endl;
return 1;
}
}
|
Fix for libc++ not properly declaring nan() functions. | // Standard Dependencies
#include <cmath>
#include <random>
// Module Dependencies
#include "../include/math.h"
namespace native
{
static std::default_random_engine engine;
double Math::sqrt(double value)
{
return (double)std::sqrt((long double)value);
}
long double Math::random(long double min, long double outerMax)
{
return std::uniform_real_distribution<long double>(min, outerMax)(engine);
}
double Math::random(double min, double outerMax)
{
return std::uniform_real_distribution<double>(min, outerMax)(engine);
}
float Math::random(float min, float outerMax)
{
return std::uniform_real_distribution<float>(min, outerMax)(engine);
}
int Math::random(int min, int outerMax)
{
return int(std::uniform_real_distribution<double>(double(min), double(outerMax))(engine));
}
}
| #ifdef __ANDROID__
double nan(const char*);
float nanf(const char*);
long double nanl(const char*);
#endif // __ANDROID__
// Standard Dependencies
#include <cmath>
#include <random>
// Module Dependencies
#include "../include/math.h"
namespace native
{
static std::default_random_engine engine;
double Math::sqrt(double value)
{
return (double)std::sqrt((long double)value);
}
long double Math::random(long double min, long double outerMax)
{
return std::uniform_real_distribution<long double>(min, outerMax)(engine);
}
double Math::random(double min, double outerMax)
{
return std::uniform_real_distribution<double>(min, outerMax)(engine);
}
float Math::random(float min, float outerMax)
{
return std::uniform_real_distribution<float>(min, outerMax)(engine);
}
int Math::random(int min, int outerMax)
{
return int(std::uniform_real_distribution<double>(double(min), double(outerMax))(engine));
}
}
|
Fix testPipeEventWatcher test case failed |
#include "test_common.h"
#include <evpp/exp.h>
#include <evpp/libevent_headers.h>
#include <evpp/libevent_watcher.h>
#include <thread>
namespace {
static bool g_event_handler_called = false;
static void Handle(struct event_base* base) {
g_event_handler_called = true;
event_base_loopexit(base, 0);
}
static void MyEventThread(struct event_base* base, evpp::PipeEventWatcher* ev) {
if (ev->Init()) {
ev->AsyncWait();
}
event_base_loop(base, 0);
}
}
TEST_UNIT(testPipeEventWatcher) {
struct event_base* base = event_base_new();
evpp::PipeEventWatcher ev(base, std::bind(&Handle, base));
std::thread th(MyEventThread, base, &ev);
::usleep(1000 * 100);
ev.Notify();
th.join();
event_base_free(base);
H_TEST_ASSERT(g_event_handler_called == true);
}
|
#include "test_common.h"
#include <evpp/exp.h>
#include <evpp/libevent_headers.h>
#include <evpp/libevent_watcher.h>
#include <thread>
namespace {
static bool g_event_handler_called = false;
static void Handle(struct event_base* base) {
g_event_handler_called = true;
event_base_loopexit(base, 0);
}
static void MyEventThread(struct event_base* base, evpp::PipeEventWatcher* ev) {
if (ev->Init()) {
ev->AsyncWait();
}
event_base_loop(base, 0);
delete ev;// ȷʼͬһ߳
}
}
TEST_UNIT(testPipeEventWatcher) {
struct event_base* base = event_base_new();
evpp::PipeEventWatcher* ev = new evpp::PipeEventWatcher(base, std::bind(&Handle, base));
std::thread th(MyEventThread, base, ev);
::usleep(1000 * 100);
ev->Notify();
th.join();
event_base_free(base);
H_TEST_ASSERT(g_event_handler_called == true);
}
|
Prepare bounding box transform for Ellipse | #include "SketchItemEllipse.h"
#include <QGraphicsEllipseItem>
SketchItemEllipse::SketchItemEllipse(qreal x, qreal y)
: SketchItemBezier(x, y)
{
addPath(QPointF(30, 0), QPointF(50, 20), QPointF(50, 50));
addPath(QPointF(50, 80), QPointF(30, 100), QPointF(0, 100));
addPath(QPointF(-30, 100), QPointF(-40, 80), QPointF(-40, 50));
addPath(QPointF(-40, 20), QPointF(-30, 0), QPointF(0, 0));
closePath();
}
SketchItemEllipse::~SketchItemEllipse()
{
}
void SketchItemEllipse::boundBoxPointMoved(BoundingBoxPoint::TranslationDirection direction, QPointF delta)
{
}
| #include "SketchItemEllipse.h"
#include <QGraphicsEllipseItem>
// Constants
static const uint TOP_INDEX = 12;
static const uint RIGHT_INDEX = 3;
static const uint BOTTOM_INDEX = 6;
static const uint LEFT_INDEX = 9;
SketchItemEllipse::SketchItemEllipse(qreal x, qreal y)
: SketchItemBezier(x, y)
{
addPath(QPointF(30, 0), QPointF(50, 20), QPointF(50, 50));
addPath(QPointF(50, 80), QPointF(30, 100), QPointF(0, 100));
addPath(QPointF(-40, 100), QPointF(-50, 80), QPointF(-50, 50));
addPath(QPointF(-40, 20), QPointF(-30, 0), QPointF(0, 0));
closePath();
mBoundingBox->updateRect();
}
SketchItemEllipse::~SketchItemEllipse()
{
}
void SketchItemEllipse::boundBoxPointMoved(BoundingBoxPoint::TranslationDirection direction, QPointF delta)
{
// because the path is closed, we don't have to
// move the first item, the last is enough
switch (direction) {
default:
qErrnoWarning("Unexpected TranslationDirection!");
break;
}
mBoundingBox->updateRect(direction);
}
|
Add implementation to cache reader | #include "CacheJsonToArticleConverter.h"
ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache)
{
return articleCache;
}
| #include "CacheJsonToArticleConverter.h"
#include <json/json.h>
#include "WalkerException.h"
#include "Article.h"
ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache)
{
Json::Reader reader;
Json::Value document;
bool success = reader.parse(json, document, false);
if(!success) {
throw WalkerException("Error parsing JSON");
}
// get all "main" articles first
for(auto &titleElement : document.getMemberNames()) {
std::string title = titleElement;
Article *a = articleCache.get(title);
if(a == nullptr) {
a = new Article(title);
articleCache.add(a);
}
for(auto linkedArticle :
document.get(title, Json::Value::nullSingleton())
.get("forward_links", Json::Value::nullSingleton()))
{
std::string linkedTitle = linkedArticle.asString();
Article *la = articleCache.get(linkedTitle);
if(la == nullptr) {
la = new Article(linkedTitle);
articleCache.add(la);
}
a->addLink(la);
}
}
return articleCache;
/*
a->setAnalyzed(true); ?
*/
}
|
Fix some PowerPC issues in the byteswap test | /*
* Copyright 2015 - 2017 gtalent2@gmail.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 <iostream>
#include <map>
#include <functional>
#include <ox/std/std.hpp>
using namespace std;
using namespace ox::std;
template<typename T>
int testBigEndianAdapt(string str) {
auto i = (T) stoul(str, nullptr, 16);
return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}
map<string, function<int(string)>> tests = {
{
{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
},
};
int main(int argc, const char **args) {
if (argc > 1) {
auto testName = args[1];
auto testArg = args[2];
if (tests.find(testName) != tests.end()) {
return tests[testName](testArg);
}
}
return -1;
}
| /*
* Copyright 2015 - 2017 gtalent2@gmail.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 <map>
#include <ox/std/std.hpp>
using namespace std;
using namespace ox::std;
template<typename T>
int testBigEndianAdapt(string str) {
auto i = (T) stoull(str, nullptr, 16);
return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}
map<string, int(*)(string)> tests = {
{
{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
},
};
int main(int argc, const char **args) {
int retval = -1;
if (argc > 1) {
auto testName = args[1];
string testArg = args[2];
if (tests.find(testName) != tests.end()) {
retval = tests[testName](testArg);
}
}
return retval;
}
|
Return !0 when qt tests fail. | #include <QTest>
#include <QObject>
#include "uritests.h"
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
URITests test1;
QTest::qExec(&test1);
}
| #include <QTest>
#include <QObject>
#include "uritests.h"
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
bool fInvalid = false;
URITests test1;
if (QTest::qExec(&test1) != 0)
fInvalid = true;
return fInvalid;
}
|
Modify window raise on windows | #include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>
int main(int argc, char *argv[])
{
// Only allow a single instance running.
QtSingleApplication app(argc, argv);
if (app.sendMessage("")) {
return 0;
}
QQmlApplicationEngine engine;
app.setWindowIcon(QIcon("resources/icons/ykman.png"));
QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
putenv(pythonNoBytecode.toUtf8().data());
QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
putenv(frameworks.toUtf8().data());
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
// Raise the root window on a message from new instance.
for (auto object : engine.rootObjects()) {
if (QWindow *window = qobject_cast<QWindow*>(object)) {
QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
window->raise();
});
}
}
return app.exec();
}
| #include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>
int main(int argc, char *argv[])
{
// Only allow a single instance running.
QtSingleApplication app(argc, argv);
if (app.sendMessage("")) {
return 0;
}
QQmlApplicationEngine engine;
app.setWindowIcon(QIcon("resources/icons/ykman.png"));
QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
putenv(pythonNoBytecode.toUtf8().data());
QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
putenv(frameworks.toUtf8().data());
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
// Wake up the root window on a message from new instance.
for (auto object : engine.rootObjects()) {
if (QWindow *window = qobject_cast<QWindow*>(object)) {
QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
window->show();
window->raise();
window->requestActivate();
});
}
}
return app.exec();
}
|
Remove comment about where to put ShouldQuit. | #include <algorithm>
#include <cctype>
#include <sstream>
#include "cons.h"
#include "utils.h"
namespace mclisp
{
template<typename T>
std::string ContainerToString(T items)
{
std::ostringstream oss;
for(auto item : items)
oss << item;
return oss.str();
}
template std::string ContainerToString<>(std::set<Token> items);
// TODO Figure out where to put ShouldQuit
bool ShouldQuit(ConsCell *exp)
{
std::ostringstream oss;
oss << *exp;
return EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)";
}
std::string ToUpper(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
return s;
}
std::string ToLower(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return s;
}
} // namespace mclisp
| #include <algorithm>
#include <cctype>
#include <sstream>
#include "cons.h"
#include "utils.h"
namespace mclisp
{
template<typename T>
std::string ContainerToString(T items)
{
std::ostringstream oss;
for(auto item : items)
oss << item;
return oss.str();
}
template std::string ContainerToString<>(std::set<Token> items);
bool ShouldQuit(ConsCell *exp)
{
std::ostringstream oss;
oss << *exp;
return EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)";
}
std::string ToUpper(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
return s;
}
std::string ToLower(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return s;
}
} // namespace mclisp
|
Fix out of bounds error on Linux. | #include "polyChecksum.h"
PolyChecksum::PolyChecksum()
{
// for all possible byte values
for (unsigned i = 0; i < 256; ++i)
{
unsigned long reg = i << 24;
// for all bits in a byte
for (int j = 0; j < 8; ++j)
{
bool topBit = (reg & 0x80000000) != 0;
reg <<= 1;
if (topBit)
reg ^= _key;
}
_table [i] = reg;
}
}
void PolyChecksum::putBytes(void* bytes, size_t dataSize)
{
unsigned char* ptr = (unsigned char*) bytes;
for (int i = 0; i < dataSize; i++)
{
unsigned byte = (unsigned) ptr[i];
unsigned top = _register >> 24;
top ^= byte;
_register = (_register << 8) ^ _table [top];
}
}
int PolyChecksum::getResult()
{
return (int) this->_register;
} | #include "polyChecksum.h"
PolyChecksum::PolyChecksum()
{
// for all possible byte values
for (unsigned i = 0; i < 256; ++i)
{
unsigned long reg = i << 24;
// for all bits in a byte
for (int j = 0; j < 8; ++j)
{
bool topBit = (reg & 0x80000000) != 0;
reg <<= 1;
if (topBit)
reg ^= _key;
}
_table [i] = reg;
}
}
void PolyChecksum::putBytes(void* bytes, size_t dataSize)
{
unsigned char* ptr = (unsigned char*) bytes;
for (size_t i = 0; i < dataSize; i++)
{
unsigned byte = *(ptr + i);
unsigned top = _register >> 24;
top ^= byte;
top &= 255;
_register = (_register << 8) ^ _table [top];
}
}
int PolyChecksum::getResult()
{
return (int) this->_register;
}
|
Remove capturing lambda capturing of static variable | #include <MinConsole.hpp>
#include <Windows.h>
#include <mutex>
namespace MinConsole
{
void* GetOutputHandle()
{
static void* Handle = nullptr;
std::once_flag HandleCached;
std::call_once(HandleCached, [=]()
{
Handle = GetStdHandle(STD_OUTPUT_HANDLE);
});
return Handle;
}
void SetTextColor(Color NewColor)
{
SetConsoleTextAttribute(
GetOutputHandle(),
static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
);
}
std::size_t GetWidth()
{
CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
if( GetConsoleScreenBufferInfo(
GetOutputHandle(),
&ConsoleInfo) )
{
return static_cast<size_t>(ConsoleInfo.dwSize.X);
}
return 0;
}
}
| #include <MinConsole.hpp>
#include <Windows.h>
#include <mutex>
namespace MinConsole
{
void* GetOutputHandle()
{
static void* Handle = nullptr;
std::once_flag HandleCached;
std::call_once(HandleCached, []()
{
Handle = GetStdHandle(STD_OUTPUT_HANDLE);
});
return Handle;
}
void SetTextColor(Color NewColor)
{
SetConsoleTextAttribute(
GetOutputHandle(),
static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
);
}
std::size_t GetWidth()
{
CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
if( GetConsoleScreenBufferInfo(
GetOutputHandle(),
&ConsoleInfo) )
{
return static_cast<size_t>(ConsoleInfo.dwSize.X);
}
return 0;
}
}
|
Add copyright notice required for open-sourcing | //dummy file, so Android Studio will 'see' these folders
| /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//dummy file, so Android Studio will 'see' these folders
|
Add identifying block number in rotation test | #include "logic.cpp"
#include <iostream>
#include <cstdlib>
int main( void );
void printCoords( block* b );
int rotationTest( void );
int main( void )
{
std::cout << "Rotation Test : " << (rotationTest())? "PASSED\n" : "FAILED\n";
exit( EXIT_SUCCESS );
}
void printCoords( block *b )
{
for( int i = 0; i < 4; ++i )
{
std::cout << i << "(" << b->coord[i].x << "," << b->coord[i].y << ")" << std::endl;
}
std::cout << std::endl;
}
int rotationTest( void )
{
for( int i = 0; i < 5; ++i )
{
auto b1 = new block( i );
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
delete b1;
}
return 1;
}
| #include "logic.cpp"
#include <iostream>
#include <cstdlib>
int main( void );
void printCoords( block* b );
int rotationTest( void );
int main( void )
{
std::cout << "Rotation Test : " << (rotationTest())? "PASSED\n" : "FAILED\n";
exit( EXIT_SUCCESS );
}
void printCoords( block *b )
{
for( int i = 0; i < 4; ++i )
{
std::cout << i << "(" << b->coord[i].x << "," << b->coord[i].y << ")" << std::endl;
}
std::cout << std::endl;
}
int rotationTest( void )
{
for( int i = 0; i < 5; ++i )
{
auto b1 = new block( i );
std::cout << i << " {" << std::endl;
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
std::cout << "}" << std::endl;
delete b1;
}
return 1;
}
|
Include string.h instead of string | #include "unicode-utils.h"
#include <clocale>
#include <stdlib.h>
#include <string>
int UnicodeUtils::characters_in_bytes(const char* string, int bytes) {
if (bytes == 0)
return 0;
mblen(NULL, 0);
setlocale(LC_CTYPE, "en_US.UTF-8");
int characters = 0;
while (bytes > 0) {
int characterLength = mblen(string, bytes);
if (characterLength < 1)
break;
characters++;
bytes -= characterLength;
string += characterLength;
}
return characters;
}
int UnicodeUtils::bytes_in_characters(const char* string, int characters) {
if (characters == 0)
return 0;
mblen(NULL, 0);
setlocale(LC_CTYPE, "en_US.UTF-8");
int bytes = 0;
int length = strlen(string);
while (length > 0) {
int characterLength = mblen(string, length);
if (characterLength < 1)
break;
bytes += characterLength;
if (--characters == 0)
break;
length -= characterLength;
string += characterLength;
}
return bytes;
}
| #include "unicode-utils.h"
#include <clocale>
#include <stdlib.h>
#include <string.h>
int UnicodeUtils::characters_in_bytes(const char* string, int bytes) {
if (bytes == 0)
return 0;
mblen(NULL, 0);
setlocale(LC_CTYPE, "en_US.UTF-8");
int characters = 0;
while (bytes > 0) {
int characterLength = mblen(string, bytes);
if (characterLength < 1)
break;
characters++;
bytes -= characterLength;
string += characterLength;
}
return characters;
}
int UnicodeUtils::bytes_in_characters(const char* string, int characters) {
if (characters == 0)
return 0;
mblen(NULL, 0);
setlocale(LC_CTYPE, "en_US.UTF-8");
int bytes = 0;
int length = strlen(string);
while (length > 0) {
int characterLength = mblen(string, length);
if (characterLength < 1)
break;
bytes += characterLength;
if (--characters == 0)
break;
length -= characterLength;
string += characterLength;
}
return bytes;
}
|
Update wheel diameter for Create 2 | #include "create/types.h"
namespace create {
RobotModel::RobotModel(const ProtocolVersion version, const float axleLength, const unsigned int baud, const float maxVelocity, const float wheelDiameter):
id(nextId),
version(version),
axleLength(axleLength),
baud(baud),
maxVelocity(maxVelocity),
wheelDiameter(wheelDiameter) {
nextId <<= 1;
}
bool RobotModel::operator ==(RobotModel& other) const {
return id == other.id;
}
RobotModel::operator uint32_t() const {
return id;
}
uint32_t RobotModel::getId() const {
return id;
}
ProtocolVersion RobotModel::getVersion() const {
return version;
}
float RobotModel::getAxleLength() const {
return axleLength;
}
unsigned int RobotModel::getBaud() const {
return baud;
}
float RobotModel::getMaxVelocity() const {
return maxVelocity;
}
float RobotModel::getWheelDiameter() const {
return wheelDiameter;
}
uint32_t RobotModel::nextId = 1;
RobotModel RobotModel::ROOMBA_400(V_1, 0.258, 57600);
RobotModel RobotModel::CREATE_1(V_2, 0.258, 57600);
RobotModel RobotModel::CREATE_2(V_3, 0.235, 115200);
}
| #include "create/types.h"
namespace create {
RobotModel::RobotModel(const ProtocolVersion version, const float axleLength, const unsigned int baud, const float maxVelocity, const float wheelDiameter):
id(nextId),
version(version),
axleLength(axleLength),
baud(baud),
maxVelocity(maxVelocity),
wheelDiameter(wheelDiameter) {
nextId <<= 1;
}
bool RobotModel::operator ==(RobotModel& other) const {
return id == other.id;
}
RobotModel::operator uint32_t() const {
return id;
}
uint32_t RobotModel::getId() const {
return id;
}
ProtocolVersion RobotModel::getVersion() const {
return version;
}
float RobotModel::getAxleLength() const {
return axleLength;
}
unsigned int RobotModel::getBaud() const {
return baud;
}
float RobotModel::getMaxVelocity() const {
return maxVelocity;
}
float RobotModel::getWheelDiameter() const {
return wheelDiameter;
}
uint32_t RobotModel::nextId = 1;
RobotModel RobotModel::ROOMBA_400(V_1, 0.258, 57600);
RobotModel RobotModel::CREATE_1(V_2, 0.258, 57600);
RobotModel RobotModel::CREATE_2(V_3, 0.235, 115200, 0.5, 0.072);
}
|
Convert to std::make_shared() to avoid allocation overhead | #include "test.h"
#include "test-job.h"
#include "test-machine.h"
#include <iostream>
int main()
{
Test::TestSuite tests(std::cout);
{ // Job
std::shared_ptr<Test::Test> jt1(new Test::JobID);
tests.register_test(jt1);
std::shared_ptr<Test::Test> jt2(new Test::JobMachineName);
tests.register_test(jt2);
std::shared_ptr<Test::Test> jt3(new Test::JobDefaultState);
tests.register_test(jt3);
}
{ // Machine
std::shared_ptr<Test::Test> mt1(new Test::MachineName);
tests.register_test(mt1);
std::shared_ptr<Test::Test> mt2(new Test::MachineAddJob);
tests.register_test(mt2);
}
{ // Pool
}
bool all_ok = tests.run_all();
if (all_ok)
return 0;
else
return 1;
}
| #include "test.h"
#include "test-job.h"
#include "test-machine.h"
#include <iostream>
#include <memory>
int main()
{
Test::TestSuite tests(std::cout);
// Set up tests - class Job
tests.register_test(std::make_shared<Test::JobID>());
tests.register_test(std::make_shared<Test::JobMachineName>());
tests.register_test(std::make_shared<Test::JobDefaultState>());
// Set up tests - class Machine
tests.register_test(std::make_shared<Test::MachineName>());
tests.register_test(std::make_shared<Test::MachineAddJob>());
// Set up tests - class Pool
// Run the tests
bool all_ok = tests.run_all();
if (all_ok)
return 0;
else
return 1;
}
|
Create device enumerator and get default device for WASAPI | // Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#include "AudioDeviceWASAPI.hpp"
namespace ouzel
{
namespace audio
{
AudioDeviceWASAPI::AudioDeviceWASAPI(Mixer& initMixer):
AudioDevice(Driver::WASAPI, initMixer)
{
}
} // namespace audio
} // namespace ouzel
| // Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#include <string>
#include <Audioclient.h>
#include <mmdeviceapi.h>
#include "AudioDeviceWASAPI.hpp"
namespace ouzel
{
namespace audio
{
class WASAPIErrorCategory : public std::error_category
{
public:
const char* name() const noexcept override
{
return "DirectSound";
}
std::string message(int condition) const override
{
switch (condition)
{
default: return "Unknown error (" + std::to_string(condition) + ")";
}
}
};
const WASAPIErrorCategory wasapiErrorCategory{};
AudioDeviceWASAPI::AudioDeviceWASAPI(Mixer& initMixer):
AudioDevice(Driver::WASAPI, initMixer)
{
IMMDeviceEnumerator* enumerator = nullptr;
HRESULT hr;
if (FAILED(hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, reinterpret_cast<LPVOID*>(&enumerator))))
throw std::system_error(hr, wasapiErrorCategory, "Failed to create device enumerator");
IMMDevice* device;
if (FAILED(hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device)))
throw std::system_error(hr, wasapiErrorCategory, "Failed to get audio endpoint");
if (enumerator) enumerator->Release();
}
} // namespace audio
} // namespace ouzel
|
Use the GFA output format | /*
* Copyright (c) 2017-2018 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <vcf2multialign/graph_writer.hh>
namespace vcf2multialign
{
// Dummy implementation.
void graph_writer_impl::init(std::size_t n_rows)
{
graph.Init(n_rows);
}
void graph_writer_impl::process_segment(std::vector <std::vector <std::uint8_t>> const &segment_vec)
{
graph.AppendMatrixRange(segment_vec);
}
void graph_writer_impl::finish()
{
graph.CompleteConstruction();
graph.PrintToDot(*m_dst_file);
}
}
| /*
* Copyright (c) 2017-2018 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <vcf2multialign/graph_writer.hh>
namespace vcf2multialign
{
// Dummy implementation.
void graph_writer_impl::init(std::size_t n_rows)
{
graph.Init(n_rows);
}
void graph_writer_impl::process_segment(std::vector <std::vector <std::uint8_t>> const &segment_vec)
{
graph.AppendMatrixRange(segment_vec);
}
void graph_writer_impl::finish()
{
graph.CompleteConstruction();
graph.PrintToGFA(*m_dst_file);
}
}
|
Support comments in Cover files | #include "CoverReader.h"
#include <fstream>
NetworKit::Cover NetworKit::CoverReader::read(std::string path, NetworKit::Graph &G)
{
std::ifstream file;
file.open(path);
if (!file.good()) {
throw std::runtime_error("unable to read from file");
}
Cover communities(G.upperNodeIdBound());
std::string line;
count i = 0;
node current;
while (std::getline(file, line)) {
communities.setUpperBound(i+1);
std::stringstream linestream(line);
while (linestream >> current) {
communities.addToSubset(i, current);
}
++i;
}
file.close();
return communities;
}
| #include "CoverReader.h"
#include <fstream>
NetworKit::Cover NetworKit::CoverReader::read(std::string path, NetworKit::Graph &G)
{
std::ifstream file;
file.open(path);
if (!file.good()) {
throw std::runtime_error("unable to read from file");
}
Cover communities(G.upperNodeIdBound());
std::string line;
count i = 0;
node current;
while (std::getline(file, line)) {
if (line.substr(0, 1) != "#") {
communities.setUpperBound(i+1);
std::stringstream linestream(line);
while (linestream >> current) {
communities.addToSubset(i, current);
}
++i;
}
}
file.close();
return communities;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.