text stringlengths 54 60.6k |
|---|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Martin Schoenert
////////////////////////////////////////////////////////////////////////////////
#include "SchedulerThread.h"
#include "Logger/Logger.h"
#include "Basics/MutexLocker.h"
#ifdef _WIN32
#include "Basics/win-utils.h"
#endif
#include "Scheduler/Scheduler.h"
#include "Scheduler/Task.h"
#include <velocypack/Value.h>
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb::basics;
using namespace arangodb::rest;
SchedulerThread::SchedulerThread(Scheduler* scheduler, EventLoop loop,
bool defaultLoop)
: Thread("Scheduler"),
_scheduler(scheduler),
_defaultLoop(defaultLoop),
_loop(loop),
_numberTasks(0),
_taskData(100) {}
////////////////////////////////////////////////////////////////////////////////
/// @brief begin shutdown sequence
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::beginShutdown() {
Thread::beginShutdown();
LOG(TRACE) << "beginning shutdown sequence of scheduler thread ("
<< threadId() << ")";
_scheduler->wakeupLoop(_loop);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief registers a task
////////////////////////////////////////////////////////////////////////////////
bool SchedulerThread::registerTask(Scheduler* scheduler, Task* task) {
// thread has already been stopped
if (isStopping()) {
// do nothing
deleteTask(task);
return false;
}
TRI_ASSERT(scheduler != nullptr);
TRI_ASSERT(task != nullptr);
// same thread, in this case it does not matter if we are inside the loop
if (threadId() == currentThreadId()) {
bool ok = setupTask(task, scheduler, _loop);
if (ok) {
++_numberTasks;
} else {
LOG(WARN) << "In SchedulerThread::registerTask setupTask has failed";
cleanupTask(task);
deleteTask(task);
}
return ok;
}
Work w(SETUP, scheduler, task);
// different thread, be careful - we have to stop the event loop
// put the register request onto the queue
MUTEX_LOCKER(mutexLocker, _queueLock);
_queue.push_back(w);
scheduler->wakeupLoop(_loop);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief unregisters a task
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::unregisterTask(Task* task) {
// thread has already been stopped
if (isStopping()) {
return;
}
// same thread, in this case it does not matter if we are inside the loop
if (threadId() == currentThreadId()) {
cleanupTask(task);
--_numberTasks;
}
// different thread, be careful - we have to stop the event loop
else {
Work w(CLEANUP, nullptr, task);
// put the unregister request into the queue
MUTEX_LOCKER(mutexLocker, _queueLock);
_queue.push_back(w);
_scheduler->wakeupLoop(_loop);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief unregisters a task
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::destroyTask(Task* task) {
// thread has already been stopped
if (isStopping()) {
deleteTask(task);
return;
}
// same thread, in this case it does not matter if we are inside the loop
if (threadId() == currentThreadId()) {
cleanupTask(task);
deleteTask(task);
--_numberTasks;
}
// different thread, be careful - we have to stop the event loop
else {
// put the unregister request into the queue
Work w(DESTROY, nullptr, task);
MUTEX_LOCKER(mutexLocker, _queueLock);
_queue.push_back(w);
_scheduler->wakeupLoop(_loop);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sends data to a task
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::signalTask(std::unique_ptr<TaskData>& data) {
_taskData.push(data.release());
_scheduler->wakeupLoop(_loop);
}
void SchedulerThread::run() {
LOG(TRACE) << "scheduler thread started (" << threadId() << ")";
if (_defaultLoop) {
#ifdef TRI_HAVE_POSIX_THREADS
sigset_t all;
sigemptyset(&all);
pthread_sigmask(SIG_SETMASK, &all, 0);
#endif
}
while (!isStopping()) {
// handle the returned data
TaskData* data;
while (_taskData.pop(data)) {
Task* task = _scheduler->lookupTaskById(data->_taskId);
if (task != nullptr) {
task->signalTask(data);
}
delete data;
}
// handle the events
try {
_scheduler->eventLoop(_loop);
} catch (std::exception const& e) {
#ifdef TRI_HAVE_POSIX_THREADS
if (isStopping()) {
LOG(WARN) << "caught cancelation exception during work";
throw;
}
#endif
LOG(WARN) << "caught exception from ev_loop: " << e.what();
} catch (...) {
#ifdef TRI_HAVE_POSIX_THREADS
if (isStopping()) {
LOG(WARN) << "caught cancelation exception during work";
throw;
}
#endif
LOG(WARN) << "caught exception from ev_loop";
}
#if defined(DEBUG_SCHEDULER_THREAD)
LOG(TRACE) << "left scheduler loop " << threadId();
#endif
while (true) {
Work w;
{
MUTEX_LOCKER(mutexLocker,
_queueLock); // TODO(fc) XXX goto boost lockfree
if (_queue.empty()) {
break;
}
w = _queue.front();
_queue.pop_front();
}
// will only get here if there is something to do
switch (w.work) {
case CLEANUP: {
cleanupTask(w.task);
--_numberTasks;
break;
}
case SETUP: {
bool ok = setupTask(w.task, w.scheduler, _loop);
if (ok) {
++_numberTasks;
} else {
cleanupTask(w.task);
deleteTask(w.task);
}
break;
}
case DESTROY: {
cleanupTask(w.task);
deleteTask(w.task);
--_numberTasks;
break;
}
case INVALID: {
LOG(ERR) << "logic error. got invalid Work item";
break;
}
}
}
}
LOG(TRACE) << "scheduler thread stopped (" << threadId() << ")";
// pop all undeliviered task data
{
TaskData* data;
while (_taskData.pop(data)) {
delete data;
}
}
// pop all elements from the queue and delete them
while (true) {
Work w;
{
MUTEX_LOCKER(mutexLocker, _queueLock);
if (_queue.empty()) {
break;
}
w = _queue.front();
_queue.pop_front();
}
// will only get here if there is something to do
switch (w.work) {
case CLEANUP:
break;
case SETUP:
break;
case DESTROY:
deleteTask(w.task);
break;
case INVALID:
LOG(ERR) << "logic error. got invalid Work item";
break;
}
}
}
void SchedulerThread::addStatus(VPackBuilder* b) {
Thread::addStatus(b);
b->add("numberTasks", VPackValue(_numberTasks.load()));
}
<commit_msg>potentially fix leak<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Martin Schoenert
////////////////////////////////////////////////////////////////////////////////
#include "SchedulerThread.h"
#include "Logger/Logger.h"
#include "Basics/MutexLocker.h"
#ifdef _WIN32
#include "Basics/win-utils.h"
#endif
#include "Scheduler/Scheduler.h"
#include "Scheduler/Task.h"
#include <velocypack/Value.h>
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb::basics;
using namespace arangodb::rest;
SchedulerThread::SchedulerThread(Scheduler* scheduler, EventLoop loop,
bool defaultLoop)
: Thread("Scheduler"),
_scheduler(scheduler),
_defaultLoop(defaultLoop),
_loop(loop),
_numberTasks(0),
_taskData(100) {}
////////////////////////////////////////////////////////////////////////////////
/// @brief begin shutdown sequence
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::beginShutdown() {
Thread::beginShutdown();
LOG(TRACE) << "beginning shutdown sequence of scheduler thread ("
<< threadId() << ")";
_scheduler->wakeupLoop(_loop);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief registers a task
////////////////////////////////////////////////////////////////////////////////
bool SchedulerThread::registerTask(Scheduler* scheduler, Task* task) {
// thread has already been stopped
if (isStopping()) {
// do nothing
deleteTask(task);
return false;
}
TRI_ASSERT(scheduler != nullptr);
TRI_ASSERT(task != nullptr);
// same thread, in this case it does not matter if we are inside the loop
if (threadId() == currentThreadId()) {
bool ok = setupTask(task, scheduler, _loop);
if (ok) {
++_numberTasks;
} else {
LOG(WARN) << "In SchedulerThread::registerTask setupTask has failed";
cleanupTask(task);
deleteTask(task);
}
return ok;
}
Work w(SETUP, scheduler, task);
// different thread, be careful - we have to stop the event loop
// put the register request onto the queue
MUTEX_LOCKER(mutexLocker, _queueLock);
_queue.push_back(w);
scheduler->wakeupLoop(_loop);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief unregisters a task
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::unregisterTask(Task* task) {
// thread has already been stopped
if (isStopping()) {
return;
}
// same thread, in this case it does not matter if we are inside the loop
if (threadId() == currentThreadId()) {
cleanupTask(task);
--_numberTasks;
}
// different thread, be careful - we have to stop the event loop
else {
Work w(CLEANUP, nullptr, task);
// put the unregister request into the queue
MUTEX_LOCKER(mutexLocker, _queueLock);
_queue.push_back(w);
_scheduler->wakeupLoop(_loop);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief unregisters a task
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::destroyTask(Task* task) {
// thread has already been stopped
if (isStopping()) {
deleteTask(task);
return;
}
// same thread, in this case it does not matter if we are inside the loop
if (threadId() == currentThreadId()) {
cleanupTask(task);
deleteTask(task);
--_numberTasks;
}
// different thread, be careful - we have to stop the event loop
else {
// put the unregister request into the queue
Work w(DESTROY, nullptr, task);
MUTEX_LOCKER(mutexLocker, _queueLock);
_queue.push_back(w);
_scheduler->wakeupLoop(_loop);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sends data to a task
////////////////////////////////////////////////////////////////////////////////
void SchedulerThread::signalTask(std::unique_ptr<TaskData>& data) {
bool result = _taskData.push(data.get());
if (result) {
data.release();
_scheduler->wakeupLoop(_loop);
}
}
void SchedulerThread::run() {
LOG(TRACE) << "scheduler thread started (" << threadId() << ")";
if (_defaultLoop) {
#ifdef TRI_HAVE_POSIX_THREADS
sigset_t all;
sigemptyset(&all);
pthread_sigmask(SIG_SETMASK, &all, 0);
#endif
}
while (!isStopping()) {
// handle the returned data
TaskData* data;
while (_taskData.pop(data)) {
Task* task = _scheduler->lookupTaskById(data->_taskId);
if (task != nullptr) {
task->signalTask(data);
}
delete data;
}
// handle the events
try {
_scheduler->eventLoop(_loop);
} catch (std::exception const& e) {
#ifdef TRI_HAVE_POSIX_THREADS
if (isStopping()) {
LOG(WARN) << "caught cancelation exception during work";
throw;
}
#endif
LOG(WARN) << "caught exception from ev_loop: " << e.what();
} catch (...) {
#ifdef TRI_HAVE_POSIX_THREADS
if (isStopping()) {
LOG(WARN) << "caught cancelation exception during work";
throw;
}
#endif
LOG(WARN) << "caught exception from ev_loop";
}
#if defined(DEBUG_SCHEDULER_THREAD)
LOG(TRACE) << "left scheduler loop " << threadId();
#endif
while (true) {
Work w;
{
MUTEX_LOCKER(mutexLocker,
_queueLock); // TODO(fc) XXX goto boost lockfree
if (_queue.empty()) {
break;
}
w = _queue.front();
_queue.pop_front();
}
// will only get here if there is something to do
switch (w.work) {
case CLEANUP: {
cleanupTask(w.task);
--_numberTasks;
break;
}
case SETUP: {
bool ok = setupTask(w.task, w.scheduler, _loop);
if (ok) {
++_numberTasks;
} else {
cleanupTask(w.task);
deleteTask(w.task);
}
break;
}
case DESTROY: {
cleanupTask(w.task);
deleteTask(w.task);
--_numberTasks;
break;
}
case INVALID: {
LOG(ERR) << "logic error. got invalid Work item";
break;
}
}
}
}
LOG(TRACE) << "scheduler thread stopped (" << threadId() << ")";
// pop all undeliviered task data
{
TaskData* data;
while (_taskData.pop(data)) {
delete data;
}
}
// pop all elements from the queue and delete them
while (true) {
Work w;
{
MUTEX_LOCKER(mutexLocker, _queueLock);
if (_queue.empty()) {
break;
}
w = _queue.front();
_queue.pop_front();
}
// will only get here if there is something to do
switch (w.work) {
case CLEANUP:
break;
case SETUP:
break;
case DESTROY:
deleteTask(w.task);
break;
case INVALID:
LOG(ERR) << "logic error. got invalid Work item";
break;
}
}
}
void SchedulerThread::addStatus(VPackBuilder* b) {
Thread::addStatus(b);
b->add("numberTasks", VPackValue(_numberTasks.load()));
}
<|endoftext|> |
<commit_before><commit_msg>Cosmetic changes<commit_after><|endoftext|> |
<commit_before>#include <phypp.hpp>
void print_help();
int phypp_main(int argc, char* argv[]) {
if (argc < 3) {
print_help();
return 0;
}
vec1s suffix;
std::string fitmask;
std::string outdir;
bool residuals = false;
read_args(argc-2, argv+2, arg_list(suffix, fitmask, residuals, outdir));
if (!outdir.empty()) {
outdir = file::directorize(outdir);
file::mkdir(outdir);
}
// Read cube
fits::input_image fimg(argv[1]);
vec3d flx;
fimg.reach_hdu(1);
fimg.read(flx);
// Read uncertainty
vec3d err;
fimg.reach_hdu(2);
fimg.read(err);
// Get wavelength WCS
double crpix, crval, cdelt;
fimg.read_keyword("CRPIX3", crpix);
fimg.read_keyword("CRVAL3", crval);
fimg.read_keyword("CDELT3", cdelt);
// Read fit mask (optional)
vec2d mask; {
if (!fitmask.empty()) {
fits::read(fitmask, mask);
} else {
mask = replicate(1, flx.dims[1], flx.dims[2]);
}
}
// Read models
vec2d models;
uint_t nmodel; {
fits::input_image fmodel(argv[2]);
if (fmodel.axis_count() == 2) {
nmodel = 1;
fits::read(argv[2], models);
models = reform(models, 1, models.size());
} else {
vec3d tmp;
fits::read(argv[2], tmp);
nmodel = tmp.dims[0];
models = reform(tmp, nmodel, tmp.dims[1]*tmp.dims[2]);
}
// Make sure each model has unit integral
for (uint_t i : range(nmodel)) {
vec1u idg = where(is_finite(models(i,_)));
models(i,_) /= total(models(i,_)[idg]);
}
if (suffix.size() != nmodel && nmodel != 1) {
error("please provide as many suffixes as there are models (", nmodel,
") in suffix=[...]");
return 1;
}
}
// Adjust suffixes to include "_"
if (nmodel == 1 && suffix.empty()) {
suffix = {""};
}
for (std::string& s : suffix) {
if (!s.empty() && s[0] != '_') {
s = "_"+s;
}
}
// Do the fit wavelength by wavelength
vec2d flx1d(flx.dims[0], nmodel);
vec2d err1d(flx.dims[0], nmodel);
for (uint_t l : range(flx.dims[0])) {
vec1u idg = where(is_finite(flx(l,_,_)) && is_finite(err(l,_,_)) && mask > 0.0);
auto res = linfit_pack(flx(l,_,_)[idg], err(l,_,_)[idg], models(_,idg));
flx1d(l,_) = res.params;
err1d(l,_) = res.errors;
}
// Write spectra to disk
std::string filebase = outdir+file::get_basename(erase_end(argv[1], ".fits"));
for (uint_t i : range(nmodel)) {
fits::output_image fspec(filebase+suffix[i]+"_spec.fits");
fspec.write(vec1d(0)); // empty primary extension, KMOS convention
fspec.reach_hdu(1);
fspec.write(flx1d(_,i));
fspec.write_keyword("CRPIX1", crpix);
fspec.write_keyword("CRVAL1", crval);
fspec.write_keyword("CDELT1", cdelt);
fspec.reach_hdu(2);
fspec.write(err1d(_,i));
fspec.write_keyword("CRPIX1", crpix);
fspec.write_keyword("CRVAL1", crval);
fspec.write_keyword("CDELT1", cdelt);
}
// Compute residuals if asked
if (residuals) {
fimg.reach_hdu(1);
fits::header hdr = fimg.read_header();
for (uint_t i : range(nmodel)) {
vec3d res = flx;
for (uint_t l : range(res.dims[0])) {
flatten(res(l,_,_)) -= flx1d(l,i)*models(i,_);
}
fits::output_image fspec(filebase+suffix[i]+"_residual.fits");
fspec.write(vec3d(0,0,0)); // empty primary HDU
fspec.reach_hdu(1);
fspec.write(res);
fspec.write_header(hdr);
fspec.reach_hdu(2);
fspec.write(err);
fspec.write_header(hdr);
}
}
return 0;
}
void print_help() {
using namespace format;
print("multispecfit v1.0");
print("usage: multispecfit <kmos_cube.fits> <models.fits> suffix=[...] [options]");
print("");
print("Main parameters:");
paragraph("'kmos_cube.fits' must be a cube created by the KMOS pipeline, with 3 "
"extensions: the first is empty (KMOS convention), the second contains the flux, "
"and the third contains the uncertainty. 'models.fits' must be a cube created by "
"yourself (e.g., with IDL or Python) containing the models to fit. Each slice of "
"this cube corresponds to a different model. Note that you have to include a "
"uniform model (all pixels equal to 1) if you want to fit a constant background. "
"Finally, 'suffix' must contain the names of each model, with the following "
"format: [name1,name1,name3,...]. There must be as many suffixes as there are "
"models in the 'models.fits' file.");
print("Available options:");
bullet("fitmask=...", "Must be a 2D FITS file containing the mask to define the fitting "
"region. Only the pixels with a non-zero value in the mask will be used "
"(default: all valid pixels are used).");
bullet("residuals", "Set this flag if you want the program to generate residual cubes, "
"removing the contribution of each component separately (default: do not "
"generate residuals)");
bullet("outdir", "Name of the directory into which the output files should be created. "
"Default is the current directory.");
}
<commit_msg>Make sure we only fit valid pixels in multispecfit<commit_after>#include <phypp.hpp>
void print_help();
int phypp_main(int argc, char* argv[]) {
if (argc < 3) {
print_help();
return 0;
}
vec1s suffix;
std::string fitmask;
std::string outdir;
bool residuals = false;
read_args(argc-2, argv+2, arg_list(suffix, fitmask, residuals, outdir));
if (!outdir.empty()) {
outdir = file::directorize(outdir);
file::mkdir(outdir);
}
// Read cube
fits::input_image fimg(argv[1]);
vec3d flx;
fimg.reach_hdu(1);
fimg.read(flx);
// Read uncertainty
vec3d err;
fimg.reach_hdu(2);
fimg.read(err);
// Get wavelength WCS
double crpix, crval, cdelt;
fimg.read_keyword("CRPIX3", crpix);
fimg.read_keyword("CRVAL3", crval);
fimg.read_keyword("CDELT3", cdelt);
// Read fit mask (optional)
vec2d mask; {
if (!fitmask.empty()) {
fits::read(fitmask, mask);
} else {
mask = vec2d{partial_count(0, is_finite(flx)) > 1};
}
}
// Read models
vec2d models;
uint_t nmodel; {
fits::input_image fmodel(argv[2]);
if (fmodel.axis_count() == 2) {
nmodel = 1;
fits::read(argv[2], models);
models = reform(models, 1, models.size());
} else {
vec3d tmp;
fits::read(argv[2], tmp);
nmodel = tmp.dims[0];
models = reform(tmp, nmodel, tmp.dims[1]*tmp.dims[2]);
}
// Make sure each model has unit integral
for (uint_t i : range(nmodel)) {
vec1u idg = where(is_finite(models(i,_)));
models(i,_) /= total(models(i,_)[idg]);
}
if (suffix.size() != nmodel && nmodel != 1) {
error("please provide as many suffixes as there are models (", nmodel,
") in suffix=[...]");
return 1;
}
}
// Adjust suffixes to include "_"
if (nmodel == 1 && suffix.empty()) {
suffix = {""};
}
for (std::string& s : suffix) {
if (!s.empty() && s[0] != '_') {
s = "_"+s;
}
}
// Do the fit wavelength by wavelength
vec2d flx1d(flx.dims[0], nmodel);
vec2d err1d(flx.dims[0], nmodel);
for (uint_t l : range(flx.dims[0])) {
vec1u idg = where(is_finite(flx(l,_,_)) && is_finite(err(l,_,_)) && err(l,_,_) > 0 && mask > 0.0);
auto res = linfit_pack(flx(l,_,_)[idg], err(l,_,_)[idg], models(_,idg));
flx1d(l,_) = res.params;
err1d(l,_) = res.errors;
}
// Write spectra to disk
std::string filebase = outdir+file::get_basename(erase_end(argv[1], ".fits"));
for (uint_t i : range(nmodel)) {
fits::output_image fspec(filebase+suffix[i]+"_spec.fits");
fspec.write(vec1d(0)); // empty primary extension, KMOS convention
fspec.reach_hdu(1);
fspec.write(flx1d(_,i));
fspec.write_keyword("CRPIX1", crpix);
fspec.write_keyword("CRVAL1", crval);
fspec.write_keyword("CDELT1", cdelt);
fspec.reach_hdu(2);
fspec.write(err1d(_,i));
fspec.write_keyword("CRPIX1", crpix);
fspec.write_keyword("CRVAL1", crval);
fspec.write_keyword("CDELT1", cdelt);
}
// Compute residuals if asked
if (residuals) {
fimg.reach_hdu(1);
fits::header hdr = fimg.read_header();
for (uint_t i : range(nmodel)) {
vec3d res = flx;
for (uint_t l : range(res.dims[0])) {
flatten(res(l,_,_)) -= flx1d(l,i)*models(i,_);
}
fits::output_image fspec(filebase+suffix[i]+"_residual.fits");
fspec.write(vec3d(0,0,0)); // empty primary HDU
fspec.reach_hdu(1);
fspec.write(res);
fspec.write_header(hdr);
fspec.reach_hdu(2);
fspec.write(err);
fspec.write_header(hdr);
}
}
return 0;
}
void print_help() {
using namespace format;
print("multispecfit v1.0");
print("usage: multispecfit <kmos_cube.fits> <models.fits> suffix=[...] [options]");
print("");
print("Main parameters:");
paragraph("'kmos_cube.fits' must be a cube created by the KMOS pipeline, with 3 "
"extensions: the first is empty (KMOS convention), the second contains the flux, "
"and the third contains the uncertainty. 'models.fits' must be a cube created by "
"yourself (e.g., with IDL or Python) containing the models to fit. Each slice of "
"this cube corresponds to a different model. Note that you have to include a "
"uniform model (all pixels equal to 1) if you want to fit a constant background. "
"Finally, 'suffix' must contain the names of each model, with the following "
"format: [name1,name1,name3,...]. There must be as many suffixes as there are "
"models in the 'models.fits' file.");
print("Available options:");
bullet("fitmask=...", "Must be a 2D FITS file containing the mask to define the fitting "
"region. Only the pixels with a non-zero value in the mask will be used "
"(default: all valid pixels are used).");
bullet("residuals", "Set this flag if you want the program to generate residual cubes, "
"removing the contribution of each component separately (default: do not "
"generate residuals)");
bullet("outdir", "Name of the directory into which the output files should be created. "
"Default is the current directory.");
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Marius Staring, Stefan Klein, David Doria. 2011.
*
* 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.txt
*
* 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.
*
*=========================================================================*/
/** \file
\brief Stack images into one big vector image.
\verbinclude imagestovectorimage.help
*/
#include "itkCommandLineArgumentParser.h"
#include "ITKToolsHelpers.h"
#include "imagestovectorimage.h"
/**
* ******************* GetHelpString *******************
*/
std::string GetHelpString( void )
{
std::stringstream ss;
ss << "ITKTools v" << itktools::GetITKToolsVersion() << "\n"
<< "Usage:\n"
<< "pximagetovectorimage\n"
<< " -in inputFilenames, at least 2\n"
<< " [-out] outputFilename, default VECTOR.mhd\n"
<< " [-s] number of streams, default 1.\n"
<< "Supported: 2D, 3D, (unsigned) char, (unsigned) short,\n"
<< "(unsigned) int, (unsigned) long, float, double.\n"
<< "Note: make sure that the input images are of the same type, size, etc.";
return ss.str();
} // end GetHelpString()
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText( GetHelpString() );
parser->MarkArgumentAsRequired( "-in", "The input filename." );
itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();
if( validateArguments == itk::CommandLineArgumentParser::FAILED )
{
return EXIT_FAILURE;
}
else if( validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED )
{
return EXIT_SUCCESS;
}
/** Get arguments. */
std::vector<std::string> inputFileNames( 0, "" );
parser->GetCommandLineArgument( "-in", inputFileNames );
std::string outputFileName = "VECTOR.mhd";
parser->GetCommandLineArgument( "-out", outputFileName );
unsigned int numberOfStreams = 1;
parser->GetCommandLineArgument( "-s", numberOfStreams );
/** Check if the required arguments are given. */
if( inputFileNames.size() < 2 )
{
std::cerr << "ERROR: You should specify at least two (2) input files." << std::endl;
return EXIT_FAILURE;
}
/** Determine image properties. */
itk::ImageIOBase::IOPixelType pixelType = itk::ImageIOBase::UNKNOWNPIXELTYPE;
itk::ImageIOBase::IOComponentType componentType = itk::ImageIOBase::UNKNOWNCOMPONENTTYPE;
unsigned int dim = 0;
unsigned int numberOfComponents = 0;
bool retgip = itktools::GetImageProperties(
inputFileNames[ 0 ], pixelType, componentType, dim, numberOfComponents );
if( !retgip ) return EXIT_FAILURE;
/** Check for vector images. */
bool retNOCCheck = itktools::NumberOfComponentsCheck( numberOfComponents );
if( !retNOCCheck ) return EXIT_FAILURE;
/** Class that does the work. */
ITKToolsImagesToVectorImageBase * filter = NULL;
try
{
// now call all possible template combinations.
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, float >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, double >::New( dim, componentType );
#ifdef ITKTOOLS_3D_SUPPORT
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, float >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, double >::New( dim, componentType );
#endif
/** Check if filter was instantiated. */
bool supported = itktools::IsFilterSupportedCheck( filter, dim, componentType );
if( !supported ) return EXIT_FAILURE;
/** Set the filter arguments. */
filter->m_InputFileNames = inputFileNames;
filter->m_OutputFileName = outputFileName;
filter->m_NumberOfStreams = numberOfStreams;
filter->Run();
delete filter;
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "ERROR: Caught ITK exception: " << excp << std::endl;
delete filter;
return EXIT_FAILURE;
}
/** End program. */
return EXIT_SUCCESS;
} // end main
<commit_msg>BUG: vector input images are supported by pximagestovectorimages<commit_after>/*=========================================================================
*
* Copyright Marius Staring, Stefan Klein, David Doria. 2011.
*
* 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.txt
*
* 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.
*
*=========================================================================*/
/** \file
\brief Stack images into one big vector image.
\verbinclude imagestovectorimage.help
*/
#include "itkCommandLineArgumentParser.h"
#include "ITKToolsHelpers.h"
#include "imagestovectorimage.h"
/**
* ******************* GetHelpString *******************
*/
std::string GetHelpString( void )
{
std::stringstream ss;
ss << "ITKTools v" << itktools::GetITKToolsVersion() << "\n"
<< "Usage:\n"
<< "pximagetovectorimage\n"
<< " -in inputFilenames, at least 2\n"
<< " [-out] outputFilename, default VECTOR.mhd\n"
<< " [-s] number of streams, default 1.\n"
<< "Supported: 2D, 3D, (unsigned) char, (unsigned) short,\n"
<< "(unsigned) int, (unsigned) long, float, double.\n"
<< "Note: make sure that the input images are of the same type, size, etc.";
return ss.str();
} // end GetHelpString()
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText( GetHelpString() );
parser->MarkArgumentAsRequired( "-in", "The input filename." );
itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();
if( validateArguments == itk::CommandLineArgumentParser::FAILED )
{
return EXIT_FAILURE;
}
else if( validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED )
{
return EXIT_SUCCESS;
}
/** Get arguments. */
std::vector<std::string> inputFileNames( 0, "" );
parser->GetCommandLineArgument( "-in", inputFileNames );
std::string outputFileName = "VECTOR.mhd";
parser->GetCommandLineArgument( "-out", outputFileName );
unsigned int numberOfStreams = 1;
parser->GetCommandLineArgument( "-s", numberOfStreams );
/** Check if the required arguments are given. */
if( inputFileNames.size() < 2 )
{
std::cerr << "ERROR: You should specify at least two (2) input files." << std::endl;
return EXIT_FAILURE;
}
/** Determine image properties. */
itk::ImageIOBase::IOPixelType pixelType = itk::ImageIOBase::UNKNOWNPIXELTYPE;
itk::ImageIOBase::IOComponentType componentType = itk::ImageIOBase::UNKNOWNCOMPONENTTYPE;
unsigned int dim = 0;
unsigned int numberOfComponents = 0;
bool retgip = itktools::GetImageProperties(
inputFileNames[ 0 ], pixelType, componentType, dim, numberOfComponents );
if( !retgip ) return EXIT_FAILURE;
/** Class that does the work. */
ITKToolsImagesToVectorImageBase * filter = NULL;
try
{
// now call all possible template combinations.
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, unsigned long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, float >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 2, double >::New( dim, componentType );
#ifdef ITKTOOLS_3D_SUPPORT
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned char >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned short >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned int >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, unsigned long >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, float >::New( dim, componentType );
if( !filter ) filter = ITKToolsImagesToVectorImage< 3, double >::New( dim, componentType );
#endif
/** Check if filter was instantiated. */
bool supported = itktools::IsFilterSupportedCheck( filter, dim, componentType );
if( !supported ) return EXIT_FAILURE;
/** Set the filter arguments. */
filter->m_InputFileNames = inputFileNames;
filter->m_OutputFileName = outputFileName;
filter->m_NumberOfStreams = numberOfStreams;
filter->Run();
delete filter;
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "ERROR: Caught ITK exception: " << excp << std::endl;
delete filter;
return EXIT_FAILURE;
}
/** End program. */
return EXIT_SUCCESS;
} // end main
<|endoftext|> |
<commit_before>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImageFileReader.h"
#include "itkImageToVectorImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( ComponentTypeIn == #type && Dimension == dim ) \
{ \
typedef itk::VectorImage< type, dim > InputImageType; \
typedef itk::VectorImage< type, dim > OutputImageType; \
function< InputImageType, OutputImageType >( inputFileNames, outputFileName, numberOfStreams ); \
supported = true; \
}
//-------------------------------------------------------------------------------------
/** Declare ComposeVectorImage. */
template< class InputImageType, class OutputImageType >
void ComposeVectorImage(
const std::vector<std::string> & inputFileNames,
const std::string & outputFileName,
const unsigned int & numberOfStreams );
/** Declare PrintHelp. */
void PrintHelp( void );
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Check arguments for help. */
if ( argc < 4 )
{
PrintHelp();
return 1;
}
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
/** Get arguments. */
std::vector<std::string> inputFileNames( 0, "" );
bool retin = parser->GetCommandLineArgument( "-in", inputFileNames );
std::string outputFileName = "VECTOR.mhd";
parser->GetCommandLineArgument( "-out", outputFileName );
/** Support for streaming. */
unsigned int numberOfStreams = 1;
parser->GetCommandLineArgument( "-s", numberOfStreams );
/** Check if the required arguments are given. */
if ( !retin )
{
std::cerr << "ERROR: You should specify \"-in\"." << std::endl;
return 1;
}
if ( inputFileNames.size() < 2 )
{
std::cerr << "ERROR: You should specify at least two (2) input files." << std::endl;
return 1;
}
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int Dimension = 3;
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( Dimension, 0 );
int retgip = GetImageProperties(
inputFileNames[ 0 ],
PixelType,
ComponentTypeIn,
Dimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 )
{
return 1;
}
/** Get rid of the possible "_" in ComponentType. */
ReplaceUnderscoreWithSpace( ComponentTypeIn );
/** Run the program. */
bool supported = false;
try
{
run( ComposeVectorImage, char, 2 );
run( ComposeVectorImage, unsigned char, 2 );
run( ComposeVectorImage, short, 2 );
run( ComposeVectorImage, unsigned short, 2 );
run( ComposeVectorImage, int, 2 );
run( ComposeVectorImage, unsigned int, 2 );
run( ComposeVectorImage, long, 2 );
run( ComposeVectorImage, unsigned long, 2 );
run( ComposeVectorImage, float, 2 );
run( ComposeVectorImage, double, 2 );
run( ComposeVectorImage, char, 3 );
run( ComposeVectorImage, unsigned char, 3 );
run( ComposeVectorImage, short, 3 );
run( ComposeVectorImage, unsigned short, 3 );
run( ComposeVectorImage, int, 3 );
run( ComposeVectorImage, unsigned int, 3 );
run( ComposeVectorImage, long, 3 );
run( ComposeVectorImage, unsigned long, 3 );
run( ComposeVectorImage, float, 3 );
run( ComposeVectorImage, double, 3 );
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr
<< "pixel (component) type = " << ComponentTypeIn
<< " ; dimension = " << Dimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* ComposeVectorImage *******************
*/
template< class InputImageType, class OutputImageType >
void ComposeVectorImage(
const std::vector<std::string> & inputFileNames,
const std::string & outputFileName,
const unsigned int & numberOfStreams )
{
/** Typedef's. */
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::Image<typename InputImageType::InternalPixelType, InputImageType::ImageDimension> ScalarImageType;
typedef itk::ImageToVectorImageFilter< ScalarImageType > ImageToVectorImageFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
/** Read in the input images. */
std::vector<typename ReaderType::Pointer> readers( inputFileNames.size() );
for ( unsigned int i = 0; i < inputFileNames.size(); ++i )
{
readers[ i ] = ReaderType::New();
readers[ i ]->SetFileName( inputFileNames[ i ] );
readers[ i ]->Update();
}
/** Create index extractor and writer. */
typename ImageToVectorImageFilterType::Pointer imageToVectorImageFilter = ImageToVectorImageFilterType::New();
// For each input image
std::cout << "There are " << inputFileNames.size() << " input images." << std::endl;
unsigned int currentOutputIndex = 0;
for ( unsigned int inputImageIndex = 0; inputImageIndex < inputFileNames.size(); ++inputImageIndex )
{
typedef itk::VectorIndexSelectionCastImageFilter<InputImageType, ScalarImageType> ComponentExtractionType;
// For each component of the current image
std::cout << "There are " << readers[inputImageIndex]->GetOutput()->GetNumberOfComponentsPerPixel() << " components in image "
<< inputImageIndex << std::endl;
for ( unsigned int component = 0; component < readers[inputImageIndex]->GetOutput()->GetNumberOfComponentsPerPixel(); ++component )
{
typename ComponentExtractionType::Pointer componentExtractionFilter = ComponentExtractionType::New();
componentExtractionFilter->SetIndex(component);
componentExtractionFilter->SetInput(readers[inputImageIndex]->GetOutput());
componentExtractionFilter->Update();
imageToVectorImageFilter->SetNthInput( currentOutputIndex, componentExtractionFilter->GetOutput());
currentOutputIndex++;
}
}
imageToVectorImageFilter->Update();
std::cout << "Output image has " << imageToVectorImageFilter->GetOutput()->GetNumberOfComponentsPerPixel() << " components." << std::endl;
/** Write vector image. */
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileName );
writer->SetInput( imageToVectorImageFilter->GetOutput() );
writer->SetNumberOfStreamDivisions( numberOfStreams );
writer->Update();
} // end ComposeVectorImage()
/**
* ******************* PrintHelp *******************
*/
void PrintHelp( void )
{
std::cout << "Usage:" << std::endl << "pximagetovectorimage\n";
std::cout << " -in inputFilenames, at least 2\n";
std::cout << " [-out] outputFilename, default VECTOR.mhd\n";
std::cout << " [-s] number of streams, default 1.\n";
std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, "
<< "(unsigned) int, (unsigned) long, float, double.\n";
std::cout << "Note: make sure that the input images are of the same type, size, etc." << std::endl;
} // end PrintHelp()
<commit_msg>New style arguments for imagestovectorimage<commit_after>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImageFileReader.h"
#include "itkImageToVectorImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( ComponentTypeIn == #type && Dimension == dim ) \
{ \
typedef itk::VectorImage< type, dim > InputImageType; \
typedef itk::VectorImage< type, dim > OutputImageType; \
function< InputImageType, OutputImageType >( inputFileNames, outputFileName, numberOfStreams ); \
supported = true; \
}
//-------------------------------------------------------------------------------------
/** Declare ComposeVectorImage. */
template< class InputImageType, class OutputImageType >
void ComposeVectorImage(
const std::vector<std::string> & inputFileNames,
const std::string & outputFileName,
const unsigned int & numberOfStreams );
/** Declare PrintHelp. */
std::string PrintHelp( void );
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText(PrintHelp());
parser->MarkArgumentAsRequired( "-in", "The input filename." );
bool validateArguments = parser->CheckForRequiredArguments();
if(!validateArguments)
{
return EXIT_FAILURE;
}
/** Get arguments. */
std::vector<std::string> inputFileNames( 0, "" );
parser->GetCommandLineArgument( "-in", inputFileNames );
std::string outputFileName = "VECTOR.mhd";
parser->GetCommandLineArgument( "-out", outputFileName );
/** Support for streaming. */
unsigned int numberOfStreams = 1;
parser->GetCommandLineArgument( "-s", numberOfStreams );
/** Check if the required arguments are given. */
if ( inputFileNames.size() < 2 )
{
std::cerr << "ERROR: You should specify at least two (2) input files." << std::endl;
return 1;
}
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int Dimension = 3;
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( Dimension, 0 );
int retgip = GetImageProperties(
inputFileNames[ 0 ],
PixelType,
ComponentTypeIn,
Dimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 )
{
return 1;
}
/** Get rid of the possible "_" in ComponentType. */
ReplaceUnderscoreWithSpace( ComponentTypeIn );
/** Run the program. */
bool supported = false;
try
{
run( ComposeVectorImage, char, 2 );
run( ComposeVectorImage, unsigned char, 2 );
run( ComposeVectorImage, short, 2 );
run( ComposeVectorImage, unsigned short, 2 );
run( ComposeVectorImage, int, 2 );
run( ComposeVectorImage, unsigned int, 2 );
run( ComposeVectorImage, long, 2 );
run( ComposeVectorImage, unsigned long, 2 );
run( ComposeVectorImage, float, 2 );
run( ComposeVectorImage, double, 2 );
run( ComposeVectorImage, char, 3 );
run( ComposeVectorImage, unsigned char, 3 );
run( ComposeVectorImage, short, 3 );
run( ComposeVectorImage, unsigned short, 3 );
run( ComposeVectorImage, int, 3 );
run( ComposeVectorImage, unsigned int, 3 );
run( ComposeVectorImage, long, 3 );
run( ComposeVectorImage, unsigned long, 3 );
run( ComposeVectorImage, float, 3 );
run( ComposeVectorImage, double, 3 );
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr
<< "pixel (component) type = " << ComponentTypeIn
<< " ; dimension = " << Dimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* ComposeVectorImage *******************
*/
template< class InputImageType, class OutputImageType >
void ComposeVectorImage(
const std::vector<std::string> & inputFileNames,
const std::string & outputFileName,
const unsigned int & numberOfStreams )
{
/** Typedef's. */
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::Image<typename InputImageType::InternalPixelType, InputImageType::ImageDimension> ScalarImageType;
typedef itk::ImageToVectorImageFilter< ScalarImageType > ImageToVectorImageFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
/** Read in the input images. */
std::vector<typename ReaderType::Pointer> readers( inputFileNames.size() );
for ( unsigned int i = 0; i < inputFileNames.size(); ++i )
{
readers[ i ] = ReaderType::New();
readers[ i ]->SetFileName( inputFileNames[ i ] );
readers[ i ]->Update();
}
/** Create index extractor and writer. */
typename ImageToVectorImageFilterType::Pointer imageToVectorImageFilter = ImageToVectorImageFilterType::New();
// For each input image
std::cout << "There are " << inputFileNames.size() << " input images." << std::endl;
unsigned int currentOutputIndex = 0;
for ( unsigned int inputImageIndex = 0; inputImageIndex < inputFileNames.size(); ++inputImageIndex )
{
typedef itk::VectorIndexSelectionCastImageFilter<InputImageType, ScalarImageType> ComponentExtractionType;
// For each component of the current image
std::cout << "There are " << readers[inputImageIndex]->GetOutput()->GetNumberOfComponentsPerPixel() << " components in image "
<< inputImageIndex << std::endl;
for ( unsigned int component = 0; component < readers[inputImageIndex]->GetOutput()->GetNumberOfComponentsPerPixel(); ++component )
{
typename ComponentExtractionType::Pointer componentExtractionFilter = ComponentExtractionType::New();
componentExtractionFilter->SetIndex(component);
componentExtractionFilter->SetInput(readers[inputImageIndex]->GetOutput());
componentExtractionFilter->Update();
imageToVectorImageFilter->SetNthInput( currentOutputIndex, componentExtractionFilter->GetOutput());
currentOutputIndex++;
}
}
imageToVectorImageFilter->Update();
std::cout << "Output image has " << imageToVectorImageFilter->GetOutput()->GetNumberOfComponentsPerPixel() << " components." << std::endl;
/** Write vector image. */
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileName );
writer->SetInput( imageToVectorImageFilter->GetOutput() );
writer->SetNumberOfStreamDivisions( numberOfStreams );
writer->Update();
} // end ComposeVectorImage()
/**
* ******************* PrintHelp *******************
*/
std::string PrintHelp( void )
{
std::string helpText = "Usage: \
pximagetovectorimage\n \
-in inputFilenames, at least 2\n \
[-out] outputFilename, default VECTOR.mhd\n \
[-s] number of streams, default 1.\n \
Supported: 2D, 3D, (unsigned) char, (unsigned) short, \
(unsigned) int, (unsigned) long, float, double.\n \
Note: make sure that the input images are of the same type, size, etc.";
return helpText;
} // end PrintHelp()
<|endoftext|> |
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file AuxiliarySimulationFunctions.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-06-30
//!
//! @brief Contiains a second order integrator utility with provision for some damping
//!
//$Id$
#include "ComponentUtilities/AuxiliarySimulationFunctions.h"
#include <cmath>
#include <limits>
using namespace hopsan;
//! @defgroup ComponentUtilities ComponentUtilities
//! @defgroup AuxiliarySimulationFunctions AuxiliarySimulationFunctions
//! @ingroup ComponentUtilities
//! @defgroup ComponentUtilityClasses ComponentUtilityClasses
//! @ingroup ComponentUtilities
//! @brief Limits a value so it is between min and max
//! @ingroup AuxiliarySimulationFunctions
//! @param &rValue Reference pointer to the value
//! @param min Lower limit of the value
//! @param max Upper limit of the value
void hopsan::limitValue(double &rValue, double min, double max)
{
if(min>max)
{
double temp;
temp = max;
max = min;
min = temp;
}
if(rValue > max)
{
rValue = max;
}
else if(rValue < min)
{
rValue = min;
}
}
//! @brief checks if two double varaiables are equal with a tolerance
//! @ingroup AuxiliarySimulationFunctions
//! @param [in] x First value
//! @param [in] y Second value
//! @param [in] eps Allowed relative error
//! @note Based on http://floating-point-gui.de/errors/comparison (20130429)
bool hopsan::fuzzyEqual(const double x, const double y, const double epsilon)
{
const double absX = fabs(x);
const double absY = fabs(y);
const double diff = fabs(x-y);
// shortcut, handles infinities
if (x == y)
{
return true;
}
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
else if (x == 0 || y == 0 || diff < std::numeric_limits<double>::epsilon() )
{
return diff < (epsilon * std::numeric_limits<double>::epsilon() );
}
// use relative error
else
{
return diff / (absX + absY) < epsilon;
}
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::signedSquareL(const double x, const double x0)
{
return (-sqrt(x0) + sqrt(x0 + fabs(x))) * sign(x);
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSignedSquareL(const double x, const double x0)
{
return (1.0 / (sqrt(x0 + fabs(x)) * 2.0));
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::squareAbsL(const double x, const double x0)
{
return (-sqrt(x0) + sqrt(x0 + fabs(x)));
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSquareAbsL(const double x, const double x0)
{
return 1.0 / (sqrt(x0 + fabs(x)) * 2.0) * sign(x);
}
//! @brief Safe variant of atan2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::Atan2L(const double y, const double x)
{
if (x >0. || x<0.)
{ return atan2(y,x);}
else
{return 0.;}
}
//! @brief Returns 1.0 if input variables have same sign, else returns 0.0
//! @ingroup AuxiliarySimulationFunctions
double hopsan::equalSigns(const double x, const double y)
{
// //! @warning This will NOT work (double != double)
// if (hopsan::sign(x) != hopsan::sign(y)) {
// return 0.0;
// }
// return 1.0;
if ( ((x < 0.0) && ( y < 0.0)) || ((x >= 0.0) && (y >= 0.0)) )
{
return 1.0;
}
else
{
return 0.0;
}
}
//! @brief Safe variant of asin
//! @ingroup AuxiliarySimulationFunctions
double hopsan::ArcSinL(const double x)
{
return asin(limit(x,-0.999,0.999));
}
//! @brief derivative of AsinL
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxArcSinL(const double x)
{
return 1.0/sqrt(1 - pow(limit(x,-0.999,0.999),2));
}
//! @brief difference between two angles, fi1-fi2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::diffAngle(const double fi1, const double fi2)
{ double output;
double output0 = fi1-fi2;
double output1 = fi1-fi2 + 2.0*pi;//3.14159;
double output2 = fi1-fi2 - 2.0*pi;//3.14159;
output = output0;
if (fabs(output0)> fabs(output1)){output = output1;}
if (fabs(output0)> fabs(output2)){output = output2;}
return output;
}
//! @brief Lift coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CLift(const double alpha, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*alpha*
CLalpha + 0.707107*(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) +
1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*sin(2*alpha);
}
//! @brief Induced drag coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CDragInd(const double alpha, const double AR, const double e, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (0.31831*(1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(alpha,2)*pow(CLalpha,2))/(AR*e) +
(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(sin(alpha),2);
}
//! @brief Moment coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CMoment(const double alpha, const double Cm0, const double Cmfs, const double /*ap*/, const double /*an*/, const double /*awp*/, const double /*awn*/)
{
return (1 - 1/(1 + pow(2.71828,-20.*(-0.5 - alpha))) - 1/(1 + pow(2.71828,-20.*(-0.5 + alpha))))*Cm0 +
(1/(1 + pow(2.71828,-20.*(-0.5 - alpha))) + 1/(1 + pow(2.71828,-20.*(-0.5 + alpha))))*Cmfs*sign(alpha);
}
//! @brief Overloads void hopsan::limitValue() with a return value.
//! @ingroup AuxiliarySimulationFunctions
//! @see void hopsan::limitValue(&value, min, max)
//! @param x Value to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
double hopsan::limit(const double x, const double xmin, const double xmax)
{
double output = x;
limitValue(output, xmin, xmax);
return output;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whos derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit(const double x, const double xmin, const double xmax)
{
if (x >= xmax) { return 0.000000001; }
if (x <= xmin) { return 0.000000001; }
return 1.0;
}
//! @brief Limits the derivative of x when x is outside of its limits.
//! @ingroup AuxiliarySimulationFunctions
//! Returns 1.0 if x is within borders, or if x is outside borders but derivative has opposite sign (so that x can only move back to the limited range).
//! @param x Value whos derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit2(const double x, const double sx, const double xmin, const double xmax)
{
if (x >= xmax && sx >= 0.0) { return 0.0000001; }
if (x <= xmin && sx <= 0.0) { return 0.0000001; }
return 1.0;
}
//! @brief Returns the algebraic quotient x/y with any fractional parts discarded
//! @ingroup AuxiliarySimlationFunctions
//! @ingroup ModelicaWrapperFunctions
//! @param x Numinator
//! @param y Denominator
//! @returns Algebraic quotient with any fracrional parts discarded
double div(const double x, const double y)
{
if(x/y > 0)
{
return floor(x/y);
}
else
{
return ceil(x/y);
}
}
<commit_msg>lowLimits added<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file AuxiliarySimulationFunctions.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-06-30
//!
//! @brief Contiains a second order integrator utility with provision for some damping
//!
//$Id$
#include "ComponentUtilities/AuxiliarySimulationFunctions.h"
#include <cmath>
#include <limits>
using namespace hopsan;
//! @defgroup ComponentUtilities ComponentUtilities
//! @defgroup AuxiliarySimulationFunctions AuxiliarySimulationFunctions
//! @ingroup ComponentUtilities
//! @defgroup ComponentUtilityClasses ComponentUtilityClasses
//! @ingroup ComponentUtilities
//! @brief Limits a value so it is between min and max
//! @ingroup AuxiliarySimulationFunctions
//! @param &rValue Reference pointer to the value
//! @param min Lower limit of the value
//! @param max Upper limit of the value
void hopsan::limitValue(double &rValue, double min, double max)
{
if(min>max)
{
double temp;
temp = max;
max = min;
min = temp;
}
if(rValue > max)
{
rValue = max;
}
else if(rValue < min)
{
rValue = min;
}
}
//! @brief checks if two double varaiables are equal with a tolerance
//! @ingroup AuxiliarySimulationFunctions
//! @param [in] x First value
//! @param [in] y Second value
//! @param [in] eps Allowed relative error
//! @note Based on http://floating-point-gui.de/errors/comparison (20130429)
bool hopsan::fuzzyEqual(const double x, const double y, const double epsilon)
{
const double absX = fabs(x);
const double absY = fabs(y);
const double diff = fabs(x-y);
// shortcut, handles infinities
if (x == y)
{
return true;
}
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
else if (x == 0 || y == 0 || diff < std::numeric_limits<double>::epsilon() )
{
return diff < (epsilon * std::numeric_limits<double>::epsilon() );
}
// use relative error
else
{
return diff / (absX + absY) < epsilon;
}
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::signedSquareL(const double x, const double x0)
{
return (-sqrt(x0) + sqrt(x0 + fabs(x))) * sign(x);
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSignedSquareL(const double x, const double x0)
{
return (1.0 / (sqrt(x0 + fabs(x)) * 2.0));
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::squareAbsL(const double x, const double x0)
{
return (-sqrt(x0) + sqrt(x0 + fabs(x)));
}
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSquareAbsL(const double x, const double x0)
{
return 1.0 / (sqrt(x0 + fabs(x)) * 2.0) * sign(x);
}
//! @brief Safe variant of atan2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::Atan2L(const double y, const double x)
{
if (x >0. || x<0.)
{ return atan2(y,x);}
else
{return 0.;}
}
//! @brief Returns 1.0 if input variables have same sign, else returns 0.0
//! @ingroup AuxiliarySimulationFunctions
double hopsan::equalSigns(const double x, const double y)
{
// //! @warning This will NOT work (double != double)
// if (hopsan::sign(x) != hopsan::sign(y)) {
// return 0.0;
// }
// return 1.0;
if ( ((x < 0.0) && ( y < 0.0)) || ((x >= 0.0) && (y >= 0.0)) )
{
return 1.0;
}
else
{
return 0.0;
}
}
//! @brief Safe variant of asin
//! @ingroup AuxiliarySimulationFunctions
double hopsan::ArcSinL(const double x)
{
return asin(limit(x,-0.999,0.999));
}
//! @brief derivative of AsinL
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxArcSinL(const double x)
{
return 1.0/sqrt(1 - pow(limit(x,-0.999,0.999),2));
}
//! @brief difference between two angles, fi1-fi2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::diffAngle(const double fi1, const double fi2)
{ double output;
double output0 = fi1-fi2;
double output1 = fi1-fi2 + 2.0*pi;//3.14159;
double output2 = fi1-fi2 - 2.0*pi;//3.14159;
output = output0;
if (fabs(output0)> fabs(output1)){output = output1;}
if (fabs(output0)> fabs(output2)){output = output2;}
return output;
}
//! @brief Lift coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CLift(const double alpha, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*alpha*
CLalpha + 0.707107*(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) +
1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*sin(2*alpha);
}
//! @brief Induced drag coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CDragInd(const double alpha, const double AR, const double e, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
return (0.31831*(1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(alpha,2)*pow(CLalpha,2))/(AR*e) +
(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
pow(sin(alpha),2);
}
//! @brief Moment coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CMoment(const double alpha, const double Cm0, const double Cmfs, const double /*ap*/, const double /*an*/, const double /*awp*/, const double /*awn*/)
{
return (1 - 1/(1 + pow(2.71828,-20.*(-0.5 - alpha))) - 1/(1 + pow(2.71828,-20.*(-0.5 + alpha))))*Cm0 +
(1/(1 + pow(2.71828,-20.*(-0.5 - alpha))) + 1/(1 + pow(2.71828,-20.*(-0.5 + alpha))))*Cmfs*sign(alpha);
}
//! @brief Overloads void hopsan::limitValue() with a return value.
//! @ingroup AuxiliarySimulationFunctions
//! @see void hopsan::limitValue(&value, min, max)
//! @param x Value to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
double hopsan::limit(const double x, const double xmin, const double xmax)
{
double output = x;
limitValue(output, xmin, xmax);
return output;
}
//! @brief Overloads void hopsan::limitValue() with a return value.
//! @ingroup AuxiliarySimulationFunctions
//! @see void hopsan::limitValue(&value, min, max)
//! @param x Value to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
double hopsan::lowLimit(const double x, const double xmin)
{
double output = x;
if(x < xmin)
{
output = xmin;
}
return output;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whos derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit(const double x, const double xmin, const double xmax)
{
if (x >= xmax) { return 0.000000001; }
if (x <= xmin) { return 0.000000001; }
return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whos derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit(const double x,const double xmin)
{
if (x <= xmin) { return 0.0000001; }
return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whos derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit2(const double x, const double sx, const double xmin)
{
if (x <= xmin && sx <= 0.0) { return 0.0000001; }
return 1.0;
}
//! @brief Limits the derivative of x when x is outside of its limits.
//! @ingroup AuxiliarySimulationFunctions
//! Returns 1.0 if x is within borders, or if x is outside borders but derivative has opposite sign (so that x can only move back to the limited range).
//! @param x Value whos derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit2(const double x, const double sx, const double xmin, const double xmax)
{
if (x >= xmax && sx >= 0.0) { return 0.0000001; }
if (x <= xmin && sx <= 0.0) { return 0.0000001; }
return 1.0;
}
//! @brief Returns the algebraic quotient x/y with any fractional parts discarded
//! @ingroup AuxiliarySimlationFunctions
//! @ingroup ModelicaWrapperFunctions
//! @param x Numinator
//! @param y Denominator
//! @returns Algebraic quotient with any fracrional parts discarded
double div(const double x, const double y)
{
if(x/y > 0)
{
return floor(x/y);
}
else
{
return ceil(x/y);
}
}
<|endoftext|> |
<commit_before><commit_msg>Add 1 problem<commit_after>/*
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal,
where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*/
#include <stdio.h>
// Definition for a binary tree node.
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x)
: val(x), left(NULL), right(NULL)
{
}
};
class Solution
{
public:
bool isValidBST(TreeNode* root)
{
if (root == NULL)
{
return true;
}
TreeNode* prev = NULL;
return doIsValidBst(root, prev);
}
bool doIsValidBst(TreeNode* node, TreeNode*& prev)
{
if (node == NULL)
{
return true;
}
if (!doIsValidBst(node->left, prev))
{
return false;
}
if (prev != NULL && prev->val >= node->val)
{
return false;
}
prev = node;
return doIsValidBst(node->right, prev);
}
};
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qHasFeature_OpenSSL
#include <openssl/evp.h>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/provider.h>
#endif
#endif
#include "../../Debug/Assertions.h"
#include "../../Execution/Exceptions.h"
#include "LibraryContext.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Cryptography;
using namespace Stroika::Foundation::Cryptography::OpenSSL;
#if qHasFeature_OpenSSL && defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#else
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "crypt32.lib")
#endif
#endif
#if qHasFeature_OpenSSL
namespace {
optional<String> GetCiphrName_ (CipherAlgorithm a)
{
if (auto i = ::EVP_CIPHER_name (a)) {
return String::FromASCII (i);
}
return nullopt;
}
}
/*
********************************************************************************
******************* Cryptography::OpenSSL::LibraryContext **********************
********************************************************************************
*/
LibraryContext LibraryContext::sDefault;
LibraryContext::LibraryContext ()
: pAvailableAlgorithms{
[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> ciphers;
::EVP_CIPHER_do_all_provided (
nullptr,
[] (EVP_CIPHER* ciph, void* arg) {
Set<String>* ciphers = reinterpret_cast<Set<String>*> (arg);
if (ciph != nullptr) {
DbgTrace (L"cipher: %p (name: %s), provider: %p", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_provider (ciph));
Assert (GetCiphrName_ (ciph));
if (auto cipherName = GetCiphrName_ (ciph)) {
#if OPENSSL_VERSION_MAJOR >= 3
if (auto provider = ::EVP_CIPHER_provider (ciph)) {
DbgTrace ("providername = %s", ::OSSL_PROVIDER_name (provider));
}
#endif
int flags = ::EVP_CIPHER_flags (ciph);
DbgTrace ("flags=%x", flags);
ciphers->Add (*cipherName);
}
}
},
&ciphers);
DbgTrace (L"Found kAllLoadedCiphers=%s", Characters::ToString (ciphers).c_str ());
auto fn = [] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); };
Traversal::Iterable<int> yyy{};
Set<int> resultyyy{yyy};
using namespace Configuration;
static_assert (IsIterable_v<Traversal::Iterable<CipherAlgorithm>>);
using ITERABLE_OF_T = Traversal::Iterable<CipherAlgorithm>;
//Configuration::Private:: IsIterableOfT_Impl2_<set<int>, int> aa;
#if 1
Set<CipherAlgorithm> result{ciphers.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); })};
WeakAssert (result.size () == ciphers.size ());
#endif
return result;
}}
{
LoadProvider (kDefaultProvider);
}
LibraryContext ::~LibraryContext ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
for (auto i : fLoadedProviders_) {
Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1);
}
#endif
}
void LibraryContext::LoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (NULL, providerName.AsNarrowSDKString ().c_str ());
static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv};
Execution::ThrowIfNull (p, kErr_);
if (auto l = fLoadedProviders_.Lookup (providerName)) {
l->second++;
fLoadedProviders_.Add (providerName, *l);
}
else {
fLoadedProviders_.Add (providerName, {p, 1});
}
#else
Require (providerName == kDefaultProvider or providerName == kLegacyProvider);
#endif
}
void LibraryContext ::UnLoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
Require (fLoadedProviders_.ContainsKey (providerName));
auto l = fLoadedProviders_.Lookup (providerName);
Assert (l);
l->second--;
if (l->second == 0) {
fLoadedProviders_.Remove (providerName);
Verify (::OSSL_PROVIDER_unload (l->first) == 1);
}
else {
fLoadedProviders_.Add (providerName, *l);
}
#endif
}
#endif
<commit_msg>call EVP_CIPHER_do_all_provided in openssl 3 and EVP_CIPHER_do_all_sorted in openssl 1 (to avoid failures - not fully clear why)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qHasFeature_OpenSSL
#include <openssl/evp.h>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/provider.h>
#endif
#endif
#include "../../Debug/Assertions.h"
#include "../../Execution/Exceptions.h"
#include "LibraryContext.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Cryptography;
using namespace Stroika::Foundation::Cryptography::OpenSSL;
#if qHasFeature_OpenSSL && defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#else
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "crypt32.lib")
#endif
#endif
#if qHasFeature_OpenSSL
namespace {
optional<String> GetCiphrName_ (CipherAlgorithm a)
{
if (auto i = ::EVP_CIPHER_name (a)) {
return String::FromASCII (i);
}
return nullopt;
}
}
/*
********************************************************************************
******************* Cryptography::OpenSSL::LibraryContext **********************
********************************************************************************
*/
LibraryContext LibraryContext::sDefault;
namespace {
void f (const EVP_CIPHER* ciph, void* arg) {
Set<String>* ciphers = reinterpret_cast<Set<String>*> (arg);
if (ciph != nullptr) {
#if OPENSSL_VERSION_MAJOR >= 3
DbgTrace (L"cipher: %p (name: %s), provider: %p", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_provider (ciph));
#else
DbgTrace (L"cipher: %p (name: %s), ciph, CipherAlgorithm{ciph}.pName ().c_str ());
#endif
Assert (GetCiphrName_ (ciph));
if (auto cipherName = GetCiphrName_ (ciph)) {
#if OPENSSL_VERSION_MAJOR >= 3
if (auto provider = ::EVP_CIPHER_provider (ciph)) {
DbgTrace ("providername = %s", ::OSSL_PROVIDER_name (provider));
}
#endif
int flags = ::EVP_CIPHER_flags (ciph);
DbgTrace ("flags=%x", flags);
ciphers->Add (*cipherName);
}
}
};
}
LibraryContext::LibraryContext ()
: pAvailableAlgorithms{
[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> ciphers;
#if OPENSSL_VERSION_MAJOR >= 3
::EVP_CIPHER_do_all_provided (
nullptr,
[] (EVP_CIPHER* ciph, void* arg) { f (ciph, arg); },
&ciphers);
#else
::EVP_CIPHER_do_all_sorted (
[] (const EVP_CIPHER* ciph, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { f (ciph, arg); },
&ciphers);
#endif
DbgTrace (L"Found kAllLoadedCiphers=%s", Characters::ToString (ciphers).c_str ());
auto fn = [] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); };
Traversal::Iterable<int> yyy{};
Set<int> resultyyy{yyy};
using namespace Configuration;
static_assert (IsIterable_v<Traversal::Iterable<CipherAlgorithm>>);
using ITERABLE_OF_T = Traversal::Iterable<CipherAlgorithm>;
//Configuration::Private:: IsIterableOfT_Impl2_<set<int>, int> aa;
#if 1
Set<CipherAlgorithm> result{ciphers.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); })};
WeakAssert (result.size () == ciphers.size ());
#endif
return result;
}}
{
LoadProvider (kDefaultProvider);
}
LibraryContext ::~LibraryContext ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
for (auto i : fLoadedProviders_) {
Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1);
}
#endif
}
void LibraryContext::LoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (NULL, providerName.AsNarrowSDKString ().c_str ());
static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv};
Execution::ThrowIfNull (p, kErr_);
if (auto l = fLoadedProviders_.Lookup (providerName)) {
l->second++;
fLoadedProviders_.Add (providerName, *l);
}
else {
fLoadedProviders_.Add (providerName, {p, 1});
}
#else
Require (providerName == kDefaultProvider or providerName == kLegacyProvider);
#endif
}
void LibraryContext ::UnLoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
Require (fLoadedProviders_.ContainsKey (providerName));
auto l = fLoadedProviders_.Lookup (providerName);
Assert (l);
l->second--;
if (l->second == 0) {
fLoadedProviders_.Remove (providerName);
Verify (::OSSL_PROVIDER_unload (l->first) == 1);
}
else {
fLoadedProviders_.Add (providerName, *l);
}
#endif
}
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkBSplineControlPointImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkN4MRIBiasFieldCorrectionImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkShrinkImageFilter.h"
template<class TFilter>
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {}
public:
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *) caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
const TFilter * filter =
dynamic_cast< const TFilter * >( object );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{ return; }
if( filter->GetElapsedIterations() == 1 )
{
std::cout << "Current level = " << filter->GetCurrentLevel() + 1
<< std::endl;
}
std::cout << " Iteration " << filter->GetElapsedIterations()
<< " (of "
<< filter->GetMaximumNumberOfIterations()[
filter->GetCurrentLevel()]
<< "). ";
std::cout << " Current convergence value = "
<< filter->GetCurrentConvergenceMeasurement()
<< " (threshold = " << filter->GetConvergenceThreshold()
<< ")" << std::endl;
}
};
#include <string>
#include <vector>
template<class TValue>
TValue Convert( std::string optionString )
{
TValue value;
std::istringstream iss( optionString );
iss >> value;
return value;
}
template<class TValue>
std::vector<TValue> ConvertVector( std::string optionString )
{
std::vector<TValue> values;
std::string::size_type crosspos = optionString.find( 'x', 0 );
if ( crosspos == std::string::npos )
{
values.push_back( Convert<TValue>( optionString ) );
}
else
{
std::string element = optionString.substr( 0, crosspos );
TValue value;
std::istringstream iss( element );
iss >> value;
values.push_back( value );
while ( crosspos != std::string::npos )
{
std::string::size_type crossposfrom = crosspos;
crosspos = optionString.find( 'x', crossposfrom + 1 );
if ( crosspos == std::string::npos )
{
element = optionString.substr( crossposfrom + 1, optionString.length() );
}
else
{
element = optionString.substr( crossposfrom + 1, crosspos );
}
std::istringstream iss2( element );
iss2 >> value;
values.push_back( value );
}
}
return values;
}
template<unsigned int ImageDimension>
int N4( int argc, char *argv[] )
{
typedef float RealType;
typedef itk::Image<RealType, ImageDimension> ImageType;
typedef typename ImageType::Pointer ImagePointer;
typedef itk::ImageFileReader<ImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
ImagePointer inputImage = reader->GetOutput();
inputImage->DisconnectPipeline();
// handle the mask image
typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
typename MaskImageType::Pointer maskImage = NULL;
if( argc > 6 )
{
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
maskreader->SetFileName( argv[6] );
try
{
maskreader->Update();
maskImage = maskreader->GetOutput();
maskImage->DisconnectPipeline();
}
catch( ... )
{
maskImage = NULL;
}
}
if( !maskImage )
{
std::cout << "Mask not read. Creating Otsu mask." << std::endl;
typedef itk::OtsuThresholdImageFilter<ImageType, MaskImageType>
ThresholderType;
typename ThresholderType::Pointer otsu = ThresholderType::New();
otsu->SetInput( inputImage );
otsu->SetNumberOfHistogramBins( 200 );
otsu->SetInsideValue( 0 );
otsu->SetOutsideValue( 1 );
otsu->Update();
maskImage = otsu->GetOutput();
maskImage->DisconnectPipeline();
}
// instantiate N4 and assign variables not exposed to the user in this test.
typedef itk::N4MRIBiasFieldCorrectionImageFilter<ImageType, MaskImageType,
ImageType> CorrecterType;
typename CorrecterType::Pointer correcter = CorrecterType::New();
correcter->SetMaskLabel( 1 );
correcter->SetSplineOrder( 3 );
correcter->SetWienerFilterNoise( 0.01 );
correcter->SetBiasFieldFullWidthAtHalfMaximum( 0.15 );
correcter->SetConvergenceThreshold( 0.0000001 );
// handle the number of iterations
std::vector<unsigned int> numIters = ConvertVector<unsigned int>(
std::string( "100x50x50" ) );
if( argc > 5 )
{
numIters = ConvertVector<unsigned int>( argv[5] );
}
typename CorrecterType::VariableSizeArrayType
maximumNumberOfIterations( numIters.size() );
for( unsigned int d = 0; d < numIters.size(); d++ )
{
maximumNumberOfIterations[d] = numIters[d];
}
correcter->SetMaximumNumberOfIterations( maximumNumberOfIterations );
typename CorrecterType::ArrayType numberOfFittingLevels;
numberOfFittingLevels.Fill( numIters.size() );
correcter->SetNumberOfFittingLevels( numberOfFittingLevels );
/* B-spline options -- we place this here to take care of the case where
* the user wants to specify things in terms of the spline distance.
* 1. need to pad the images to get as close to possible to the
* requested domain size.
*/
typename ImageType::PointType newOrigin = inputImage->GetOrigin();
typename CorrecterType::ArrayType numberOfControlPoints;
float splineDistance = 200;
if( argc > 7 )
{
splineDistance = atof( argv[7] );
}
itk::SizeValueType lowerBound[ImageDimension];
itk::SizeValueType upperBound[ImageDimension];
for( unsigned int d = 0; d < ImageDimension; d++ )
{
float domain = static_cast<RealType>( inputImage->
GetLargestPossibleRegion().GetSize()[d] - 1 ) *
inputImage->GetSpacing()[d];
unsigned int numberOfSpans = static_cast<unsigned int>(
vcl_ceil( domain / splineDistance ) );
unsigned long extraPadding = static_cast<unsigned long>( ( numberOfSpans *
splineDistance - domain ) / inputImage->GetSpacing()[d] + 0.5 );
lowerBound[d] = static_cast<unsigned long>( 0.5 * extraPadding );
upperBound[d] = extraPadding - lowerBound[d];
newOrigin[d] -= ( static_cast<RealType>( lowerBound[d] ) *
inputImage->GetSpacing()[d] );
numberOfControlPoints[d] = numberOfSpans + correcter->GetSplineOrder();
}
typedef itk::ConstantPadImageFilter<ImageType, ImageType> PadderType;
typename PadderType::Pointer padder = PadderType::New();
padder->SetInput( inputImage );
padder->SetPadLowerBound( lowerBound );
padder->SetPadUpperBound( upperBound );
padder->SetConstant( 0 );
padder->Update();
inputImage = padder->GetOutput();
inputImage->DisconnectPipeline();
typedef itk::ConstantPadImageFilter<MaskImageType, MaskImageType>
MaskPadderType;
typename MaskPadderType::Pointer maskPadder = MaskPadderType::New();
maskPadder->SetInput( maskImage );
maskPadder->SetPadLowerBound( lowerBound );
maskPadder->SetPadUpperBound( upperBound );
maskPadder->SetConstant( 0 );
maskPadder->Update();
maskImage = maskPadder->GetOutput();
maskImage->DisconnectPipeline();
correcter->SetNumberOfControlPoints( numberOfControlPoints );
// handle the shrink factor
typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkerType;
typename ShrinkerType::Pointer shrinker = ShrinkerType::New();
shrinker->SetInput( reader->GetOutput() );
shrinker->SetShrinkFactors( 1 );
typedef itk::ShrinkImageFilter<MaskImageType, MaskImageType>
MaskShrinkerType;
typename MaskShrinkerType::Pointer maskshrinker = MaskShrinkerType::New();
maskshrinker->SetInput( maskImage );
maskshrinker->SetShrinkFactors( 1 );
if( argc > 4 )
{
shrinker->SetShrinkFactors( atoi( argv[4] ) );
maskshrinker->SetShrinkFactors( atoi( argv[4] ) );
}
shrinker->Update();
inputImage = shrinker->GetOutput();
inputImage->DisconnectPipeline();
maskshrinker->Update();
maskImage = maskshrinker->GetOutput();
maskImage->DisconnectPipeline();
// set the input image and mask image
correcter->SetInput( inputImage );
correcter->SetMaskImage( maskImage );
typedef CommandIterationUpdate<CorrecterType> CommandType;
typename CommandType::Pointer observer = CommandType::New();
correcter->AddObserver( itk::IterationEvent(), observer );
try
{
correcter->Update();
}
catch( itk::ExceptionObject &excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
correcter->Print( std::cout, 3 );
// Test the reconstruction of the log bias field
ImagePointer originalInputImage = reader->GetOutput();
typedef itk::BSplineControlPointImageFilter
<typename CorrecterType::BiasFieldControlPointLatticeType, typename
CorrecterType::ScalarImageType> BSplinerType;
typename BSplinerType::Pointer bspliner = BSplinerType::New();
bspliner->SetInput( correcter->GetLogBiasFieldControlPointLattice() );
bspliner->SetSplineOrder( correcter->GetSplineOrder() );
bspliner->SetSize(
originalInputImage->GetLargestPossibleRegion().GetSize() );
bspliner->SetOrigin( originalInputImage->GetOrigin() );
bspliner->SetDirection( originalInputImage->GetDirection() );
bspliner->SetSpacing( originalInputImage->GetSpacing() );
bspliner->Update();
// output the log bias field control point lattice
typedef itk::ImageFileWriter<
typename CorrecterType::BiasFieldControlPointLatticeType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[3] );
writer->SetInput( correcter->GetLogBiasFieldControlPointLattice() );
writer->Update();
return EXIT_SUCCESS;
}
int itkN4MRIBiasFieldCorrectionImageFilterTest( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Usage: " << argv[0] << " imageDimension inputImage "
<< "outputLogControlPointLattice [shrinkFactor,default=1] "
<< "[numberOfIterations,default=100x50x50] "
<< " [maskImageWithLabelEqualTo1] [splineDistance,default=200]"
<< std::endl;
exit( EXIT_FAILURE );
}
switch( atoi( argv[1] ) )
{
case 2:
N4<2>( argc, argv );
break;
case 3:
N4<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
return EXIT_SUCCESS;
}
<commit_msg>BUG: return value not propagated, incorrect image in sequence<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkBSplineControlPointImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkN4MRIBiasFieldCorrectionImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkShrinkImageFilter.h"
template<class TFilter>
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {}
public:
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *) caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
const TFilter * filter =
dynamic_cast< const TFilter * >( object );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{ return; }
if( filter->GetElapsedIterations() == 1 )
{
std::cout << "Current level = " << filter->GetCurrentLevel() + 1
<< std::endl;
}
std::cout << " Iteration " << filter->GetElapsedIterations()
<< " (of "
<< filter->GetMaximumNumberOfIterations()[
filter->GetCurrentLevel()]
<< "). ";
std::cout << " Current convergence value = "
<< filter->GetCurrentConvergenceMeasurement()
<< " (threshold = " << filter->GetConvergenceThreshold()
<< ")" << std::endl;
}
};
#include <string>
#include <vector>
template<class TValue>
TValue Convert( std::string optionString )
{
TValue value;
std::istringstream iss( optionString );
iss >> value;
return value;
}
template<class TValue>
std::vector<TValue> ConvertVector( std::string optionString )
{
std::vector<TValue> values;
std::string::size_type crosspos = optionString.find( 'x', 0 );
if ( crosspos == std::string::npos )
{
values.push_back( Convert<TValue>( optionString ) );
}
else
{
std::string element = optionString.substr( 0, crosspos );
TValue value;
std::istringstream iss( element );
iss >> value;
values.push_back( value );
while ( crosspos != std::string::npos )
{
std::string::size_type crossposfrom = crosspos;
crosspos = optionString.find( 'x', crossposfrom + 1 );
if ( crosspos == std::string::npos )
{
element = optionString.substr( crossposfrom + 1, optionString.length() );
}
else
{
element = optionString.substr( crossposfrom + 1, crosspos );
}
std::istringstream iss2( element );
iss2 >> value;
values.push_back( value );
}
}
return values;
}
template<unsigned int ImageDimension>
int N4( int argc, char *argv[] )
{
typedef float RealType;
typedef itk::Image<RealType, ImageDimension> ImageType;
typedef typename ImageType::Pointer ImagePointer;
typedef itk::ImageFileReader<ImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
ImagePointer inputImage = reader->GetOutput();
inputImage->DisconnectPipeline();
// handle the mask image
typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
typename MaskImageType::Pointer maskImage = NULL;
if( argc > 6 )
{
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
maskreader->SetFileName( argv[6] );
try
{
maskreader->Update();
maskImage = maskreader->GetOutput();
maskImage->DisconnectPipeline();
}
catch( ... )
{
maskImage = NULL;
}
}
if( !maskImage )
{
std::cout << "Mask not read. Creating Otsu mask." << std::endl;
typedef itk::OtsuThresholdImageFilter<ImageType, MaskImageType>
ThresholderType;
typename ThresholderType::Pointer otsu = ThresholderType::New();
otsu->SetInput( inputImage );
otsu->SetNumberOfHistogramBins( 200 );
otsu->SetInsideValue( 0 );
otsu->SetOutsideValue( 1 );
otsu->Update();
maskImage = otsu->GetOutput();
maskImage->DisconnectPipeline();
}
// instantiate N4 and assign variables not exposed to the user in this test.
typedef itk::N4MRIBiasFieldCorrectionImageFilter<ImageType, MaskImageType,
ImageType> CorrecterType;
typename CorrecterType::Pointer correcter = CorrecterType::New();
correcter->SetMaskLabel( 1 );
correcter->SetSplineOrder( 3 );
correcter->SetWienerFilterNoise( 0.01 );
correcter->SetBiasFieldFullWidthAtHalfMaximum( 0.15 );
correcter->SetConvergenceThreshold( 0.0000001 );
// handle the number of iterations
std::vector<unsigned int> numIters = ConvertVector<unsigned int>(
std::string( "100x50x50" ) );
if( argc > 5 )
{
numIters = ConvertVector<unsigned int>( argv[5] );
}
typename CorrecterType::VariableSizeArrayType
maximumNumberOfIterations( numIters.size() );
for( unsigned int d = 0; d < numIters.size(); d++ )
{
maximumNumberOfIterations[d] = numIters[d];
}
correcter->SetMaximumNumberOfIterations( maximumNumberOfIterations );
typename CorrecterType::ArrayType numberOfFittingLevels;
numberOfFittingLevels.Fill( numIters.size() );
correcter->SetNumberOfFittingLevels( numberOfFittingLevels );
/* B-spline options -- we place this here to take care of the case where
* the user wants to specify things in terms of the spline distance.
* 1. need to pad the images to get as close to possible to the
* requested domain size.
*/
typename ImageType::PointType newOrigin = inputImage->GetOrigin();
typename CorrecterType::ArrayType numberOfControlPoints;
float splineDistance = 200;
if( argc > 7 )
{
splineDistance = atof( argv[7] );
}
itk::SizeValueType lowerBound[ImageDimension];
itk::SizeValueType upperBound[ImageDimension];
for( unsigned int d = 0; d < ImageDimension; d++ )
{
float domain = static_cast<RealType>( inputImage->
GetLargestPossibleRegion().GetSize()[d] - 1 ) *
inputImage->GetSpacing()[d];
unsigned int numberOfSpans = static_cast<unsigned int>(
vcl_ceil( domain / splineDistance ) );
unsigned long extraPadding = static_cast<unsigned long>( ( numberOfSpans *
splineDistance - domain ) / inputImage->GetSpacing()[d] + 0.5 );
lowerBound[d] = static_cast<unsigned long>( 0.5 * extraPadding );
upperBound[d] = extraPadding - lowerBound[d];
newOrigin[d] -= ( static_cast<RealType>( lowerBound[d] ) *
inputImage->GetSpacing()[d] );
numberOfControlPoints[d] = numberOfSpans + correcter->GetSplineOrder();
}
typedef itk::ConstantPadImageFilter<ImageType, ImageType> PadderType;
typename PadderType::Pointer padder = PadderType::New();
padder->SetInput( inputImage );
padder->SetPadLowerBound( lowerBound );
padder->SetPadUpperBound( upperBound );
padder->SetConstant( 0 );
padder->Update();
inputImage = padder->GetOutput();
inputImage->DisconnectPipeline();
typedef itk::ConstantPadImageFilter<MaskImageType, MaskImageType>
MaskPadderType;
typename MaskPadderType::Pointer maskPadder = MaskPadderType::New();
maskPadder->SetInput( maskImage );
maskPadder->SetPadLowerBound( lowerBound );
maskPadder->SetPadUpperBound( upperBound );
maskPadder->SetConstant( 0 );
maskPadder->Update();
maskImage = maskPadder->GetOutput();
maskImage->DisconnectPipeline();
correcter->SetNumberOfControlPoints( numberOfControlPoints );
// handle the shrink factor
typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkerType;
typename ShrinkerType::Pointer shrinker = ShrinkerType::New();
shrinker->SetInput( inputImage );
shrinker->SetShrinkFactors( 1 );
typedef itk::ShrinkImageFilter<MaskImageType, MaskImageType>
MaskShrinkerType;
typename MaskShrinkerType::Pointer maskshrinker = MaskShrinkerType::New();
maskshrinker->SetInput( maskImage );
maskshrinker->SetShrinkFactors( 1 );
if( argc > 4 )
{
shrinker->SetShrinkFactors( atoi( argv[4] ) );
maskshrinker->SetShrinkFactors( atoi( argv[4] ) );
}
shrinker->Update();
inputImage = shrinker->GetOutput();
inputImage->DisconnectPipeline();
maskshrinker->Update();
maskImage = maskshrinker->GetOutput();
maskImage->DisconnectPipeline();
// set the input image and mask image
correcter->SetInput( inputImage );
correcter->SetMaskImage( maskImage );
typedef CommandIterationUpdate<CorrecterType> CommandType;
typename CommandType::Pointer observer = CommandType::New();
correcter->AddObserver( itk::IterationEvent(), observer );
try
{
correcter->Update();
}
catch( itk::ExceptionObject &excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
correcter->Print( std::cout, 3 );
// Test the reconstruction of the log bias field
ImagePointer originalInputImage = reader->GetOutput();
reader->UpdateOutputInformation();
typedef itk::BSplineControlPointImageFilter
<typename CorrecterType::BiasFieldControlPointLatticeType, typename
CorrecterType::ScalarImageType> BSplinerType;
typename BSplinerType::Pointer bspliner = BSplinerType::New();
bspliner->SetInput( correcter->GetLogBiasFieldControlPointLattice() );
bspliner->SetSplineOrder( correcter->GetSplineOrder() );
bspliner->SetSize(
originalInputImage->GetLargestPossibleRegion().GetSize() );
bspliner->SetOrigin( originalInputImage->GetOrigin() );
bspliner->SetDirection( originalInputImage->GetDirection() );
bspliner->SetSpacing( originalInputImage->GetSpacing() );
bspliner->Update();
// output the log bias field control point lattice
typedef itk::ImageFileWriter<
typename CorrecterType::BiasFieldControlPointLatticeType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[3] );
writer->SetInput( correcter->GetLogBiasFieldControlPointLattice() );
writer->Update();
return EXIT_SUCCESS;
}
int itkN4MRIBiasFieldCorrectionImageFilterTest( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Usage: " << argv[0] << " imageDimension inputImage "
<< "outputLogControlPointLattice [shrinkFactor,default=1] "
<< "[numberOfIterations,default=100x50x50] "
<< " [maskImageWithLabelEqualTo1] [splineDistance,default=200]"
<< std::endl;
exit( EXIT_FAILURE );
}
switch( atoi( argv[1] ) )
{
case 2:
return N4<2>( argc, argv );
break;
case 3:
return N4<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperCommandLineLauncher.h"
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cerr << "Usage : " << argv[0] << " module_name module_path [arguments]" << std::endl;
return EXIT_FAILURE;
}
// Construct the string expression
std::string exp;
for( unsigned int i=1; i<argc; i++)
{
if( i!= argc-1)
{
exp.append(argv[i]);
exp.append(" ");
}
else
{
exp.append(argv[i]);
}
}
typedef otb::Wrapper::CommandLineLauncher LauncherType;
LauncherType::Pointer launcher = LauncherType::New();
if (launcher->Load( exp ) == true )
{
if (launcher->ExecuteAndWriteOutput() == false)
{
return EXIT_FAILURE;
}
}
else
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>WRG: comparison signed/unsigned<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperCommandLineLauncher.h"
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cerr << "Usage : " << argv[0] << " module_name module_path [arguments]" << std::endl;
return EXIT_FAILURE;
}
// Construct the string expression
std::string exp;
for (int i = 1; i < argc; i++)
{
if (i != argc - 1)
{
exp.append(argv[i]);
exp.append(" ");
}
else
{
exp.append(argv[i]);
}
}
typedef otb::Wrapper::CommandLineLauncher LauncherType;
LauncherType::Pointer launcher = LauncherType::New();
if (launcher->Load(exp) == true)
{
if (launcher->ExecuteAndWriteOutput() == false)
{
return EXIT_FAILURE;
}
}
else
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkUSImageToIGTLMessageFilter.h"
#include "igtlImageMessage.h"
mitk::USImageToIGTLMessageFilter::USImageToIGTLMessageFilter()
{
mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New();
this->SetNumberOfRequiredOutputs(1);
this->SetNthOutput(0, output.GetPointer());
this->SetNumberOfRequiredInputs(1);
m_CurrentTimeStep = 0;
}
mitk::USImageToIGTLMessageFilter::~USImageToIGTLMessageFilter() {}
void mitk::USImageToIGTLMessageFilter::GenerateData()
{
for (size_t i = 0; i < this->GetNumberOfIndexedOutputs(); ++i)
{
mitk::IGTLMessage* output = this->GetOutput(i);
assert(output);
const mitk::USImage* input = this->GetInput(i);
assert(input);
int dim = input->GetDimension();
if (dim > 3)
{
mitkThrow() << "Too many dimensions";
}
igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();
// TODO: Find out, if MITK uses RAS or LPS or something else entirely and we
// need to convert
imgMsg->SetCoordinateSystem(igtl::ImageMessage::COORDINATE_RAS);
mitk::USImageMetadata::Pointer md = input->GetMetadata();
imgMsg->SetDeviceName(md->GetProbeName().c_str());
const mitk::PixelType pt = input->GetPixelType(0);
switch (pt.GetComponentType())
{
case itk::ImageIOBase::UCHAR:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_UINT8);
case itk::ImageIOBase::CHAR:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_INT8);
case itk::ImageIOBase::USHORT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_UINT16);
case itk::ImageIOBase::SHORT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_INT16);
case itk::ImageIOBase::UINT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_UINT32);
case itk::ImageIOBase::INT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_INT32);
case itk::ImageIOBase::FLOAT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_FLOAT32);
case itk::ImageIOBase::DOUBLE:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_FLOAT64);
default:
mitkThrow() << "Incompatible PixelType " << pt.GetPixelTypeAsString();
}
imgMsg->SetNumComponents(pt.GetNumberOfComponents());
// TODO: Endian
switch (dim)
{
case 2:
imgMsg->SetDimensions(input->GetDimension(0), input->GetDimension(1),
1);
case 3:
imgMsg->SetDimensions((int*)input->GetDimensions());
default:
mitkThrow() << "Too few dimensions";
}
// TODO: Origin, Geometry, spacing…
mitk::SlicedGeometry3D* geometry = input->GetSlicedGeometry();
Vector3D x = geometry->GetAxisVector(0);
Vector3D y = geometry->GetAxisVector(1);
Vector3D z = geometry->GetAxisVector(2);
float t[3] = {(float)x[0], (float)x[1], (float)x[2]};
float s[3] = {(float)y[0], (float)y[1], (float)y[2]};
float n[3] = {(float)z[0], (float)z[1], (float)z[2]};
imgMsg->SetNormals(t, s, n);
mitk::Vector3D spacing = geometry->GetSpacing();
imgMsg->SetSpacing(spacing[0], spacing[1], spacing[2]);
Point3D origin = geometry->GetOrigin();
float forigin[3] = {(float)origin[0], (float)origin[1], (float)origin[2]};
imgMsg->SetOrigin(forigin);
}
}
void mitk::USImageToIGTLMessageFilter::SetInput(const USImage* im)
{
this->ProcessObject::SetNthInput(0, const_cast<USImage*>(im));
this->CreateOutputsForAllInputs();
}
void mitk::USImageToIGTLMessageFilter::SetInput(unsigned int idx, const USImage* im)
{
this->ProcessObject::SetNthInput(idx, const_cast<USImage*>(im));
this->CreateOutputsForAllInputs();
}
const mitk::USImage* mitk::USImageToIGTLMessageFilter::GetInput(void)
{
if (this->GetNumberOfInputs() < 1)
{
return NULL;
}
return static_cast<const USImage*>(this->ProcessObject::GetInput(0));
}
const mitk::USImage* mitk::USImageToIGTLMessageFilter::GetInput(unsigned int idx)
{
if (this->GetNumberOfInputs() < idx + 1)
{
return NULL;
}
return static_cast<const USImage*>(this->ProcessObject::GetInput(idx));
}
void mitk::USImageToIGTLMessageFilter::CreateOutputsForAllInputs()
{
// create one message output for all image inputs
this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs());
for (size_t idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx)
{
if (this->GetOutput(idx) == NULL)
{
this->SetNthOutput(idx, this->MakeOutput(idx));
}
this->Modified();
}
}
void mitk::USImageToIGTLMessageFilter::ConnectTo(mitk::USImageSource* upstream)
{
this->SetInput(static_cast<USImage*>(upstream->GetNextImage().GetPointer()));
}
<commit_msg>Just send something<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkUSImageToIGTLMessageFilter.h"
#include "igtlImageMessage.h"
mitk::USImageToIGTLMessageFilter::USImageToIGTLMessageFilter()
{
mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New();
this->SetNumberOfRequiredOutputs(1);
this->SetNthOutput(0, output.GetPointer());
this->SetNumberOfRequiredInputs(1);
m_CurrentTimeStep = 0;
}
mitk::USImageToIGTLMessageFilter::~USImageToIGTLMessageFilter() {}
void mitk::USImageToIGTLMessageFilter::GenerateData()
{
for (size_t i = 0; i < this->GetNumberOfIndexedInputs(); ++i) {
mitk::IGTLMessage* output = this->GetOutput(i);
igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();
imgMsg->SetDimensions(1, 1, 1);
imgMsg->SetCoordinateSystem(igtl::ImageMessage::COORDINATE_LPS);
imgMsg->SetEndian(igtl::ImageMessage::ENDIAN_LITTLE);
igtl::Matrix4x4 atm;
memset(atm, '\0', sizeof(atm));
atm[0][0] = 1;
atm[1][1] = -1;
atm[2][2] = 1;
atm[3][3] = 1;
imgMsg->SetMatrix(atm);
imgMsg->SetNumComponents(1);
imgMsg->SetScalarTypeToUint8();
output->SetMessage((igtl::MessageBase::Pointer)imgMsg);
}
return;
for (size_t i = 0; i < this->GetNumberOfIndexedOutputs(); ++i)
{
mitk::IGTLMessage* output = this->GetOutput(i);
assert(output);
const mitk::USImage* input = this->GetInput(i);
assert(input);
int dim = input->GetDimension();
if (dim > 3)
{
mitkThrow() << "Too many dimensions";
}
igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();
// TODO: Find out, if MITK uses RAS or LPS or something else entirely and we
// need to convert
imgMsg->SetCoordinateSystem(igtl::ImageMessage::COORDINATE_RAS);
mitk::USImageMetadata::Pointer md = input->GetMetadata();
imgMsg->SetDeviceName(md->GetProbeName().c_str());
const mitk::PixelType pt = input->GetPixelType(0);
switch (pt.GetComponentType())
{
case itk::ImageIOBase::UCHAR:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_UINT8);
case itk::ImageIOBase::CHAR:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_INT8);
case itk::ImageIOBase::USHORT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_UINT16);
case itk::ImageIOBase::SHORT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_INT16);
case itk::ImageIOBase::UINT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_UINT32);
case itk::ImageIOBase::INT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_INT32);
case itk::ImageIOBase::FLOAT:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_FLOAT32);
case itk::ImageIOBase::DOUBLE:
imgMsg->SetScalarType(igtl::ImageMessage::TYPE_FLOAT64);
default:
mitkThrow() << "Incompatible PixelType " << pt.GetPixelTypeAsString();
}
imgMsg->SetNumComponents(pt.GetNumberOfComponents());
// TODO: Endian
switch (dim)
{
case 2:
imgMsg->SetDimensions(input->GetDimension(0), input->GetDimension(1),
1);
case 3:
imgMsg->SetDimensions((int*)input->GetDimensions());
default:
mitkThrow() << "Too few dimensions";
}
// TODO: Origin, Geometry, spacing…
mitk::SlicedGeometry3D* geometry = input->GetSlicedGeometry();
Vector3D x = geometry->GetAxisVector(0);
Vector3D y = geometry->GetAxisVector(1);
Vector3D z = geometry->GetAxisVector(2);
float t[3] = {(float)x[0], (float)x[1], (float)x[2]};
float s[3] = {(float)y[0], (float)y[1], (float)y[2]};
float n[3] = {(float)z[0], (float)z[1], (float)z[2]};
imgMsg->SetNormals(t, s, n);
mitk::Vector3D spacing = geometry->GetSpacing();
imgMsg->SetSpacing(spacing[0], spacing[1], spacing[2]);
Point3D origin = geometry->GetOrigin();
float forigin[3] = {(float)origin[0], (float)origin[1], (float)origin[2]};
imgMsg->SetOrigin(forigin);
}
}
void mitk::USImageToIGTLMessageFilter::SetInput(const USImage* im)
{
this->ProcessObject::SetNthInput(0, const_cast<USImage*>(im));
this->CreateOutputsForAllInputs();
}
void mitk::USImageToIGTLMessageFilter::SetInput(unsigned int idx, const USImage* im)
{
this->ProcessObject::SetNthInput(idx, const_cast<USImage*>(im));
this->CreateOutputsForAllInputs();
}
const mitk::USImage* mitk::USImageToIGTLMessageFilter::GetInput(void)
{
if (this->GetNumberOfInputs() < 1)
{
return NULL;
}
return static_cast<const USImage*>(this->ProcessObject::GetInput(0));
}
const mitk::USImage* mitk::USImageToIGTLMessageFilter::GetInput(unsigned int idx)
{
if (this->GetNumberOfInputs() < idx + 1)
{
return NULL;
}
return static_cast<const USImage*>(this->ProcessObject::GetInput(idx));
}
void mitk::USImageToIGTLMessageFilter::CreateOutputsForAllInputs()
{
// create one message output for all image inputs
this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs());
for (size_t idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx)
{
if (this->GetOutput(idx) == NULL)
{
this->SetNthOutput(idx, this->MakeOutput(idx));
}
this->Modified();
}
}
void mitk::USImageToIGTLMessageFilter::ConnectTo(mitk::USImageSource* upstream)
{
this->SetInput(static_cast<USImage*>(upstream->GetNextImage().GetPointer()));
}
<|endoftext|> |
<commit_before>// 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/chromeos/preferences.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/input_method_library.h"
#include "chrome/browser/chromeos/cros/synaptics_library.h"
#include "chrome/browser/pref_member.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "unicode/timezone.h"
namespace chromeos {
// static
void Preferences::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kTapToClickEnabled, false);
prefs->RegisterBooleanPref(prefs::kAccessibilityEnabled, false);
prefs->RegisterBooleanPref(prefs::kVertEdgeScrollEnabled, false);
prefs->RegisterIntegerPref(prefs::kTouchpadSpeedFactor, 9);
prefs->RegisterIntegerPref(prefs::kTouchpadSensitivity, 5);
prefs->RegisterStringPref(prefs::kLanguageCurrentInputMethod, "");
prefs->RegisterStringPref(prefs::kLanguagePreviousInputMethod, "");
prefs->RegisterStringPref(prefs::kLanguageHotkeyNextEngineInMenu,
kHotkeyNextEngineInMenu);
prefs->RegisterStringPref(prefs::kLanguageHotkeyPreviousEngine,
kHotkeyPreviousEngine);
prefs->RegisterStringPref(prefs::kLanguagePreloadEngines,
kFallbackInputMethodId); // EN layout
for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
prefs->RegisterBooleanPref(kChewingBooleanPrefs[i].pref_name,
kChewingBooleanPrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
prefs->RegisterStringPref(
kChewingMultipleChoicePrefs[i].pref_name,
kChewingMultipleChoicePrefs[i].default_pref_value);
}
prefs->RegisterIntegerPref(kChewingHsuSelKeyType.pref_name,
kChewingHsuSelKeyType.default_pref_value);
for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
prefs->RegisterIntegerPref(kChewingIntegerPrefs[i].pref_name,
kChewingIntegerPrefs[i].default_pref_value);
}
prefs->RegisterStringPref(
prefs::kLanguageHangulKeyboard,
kHangulKeyboardNameIDPairs[0].keyboard_id);
for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) {
prefs->RegisterBooleanPref(kPinyinBooleanPrefs[i].pref_name,
kPinyinBooleanPrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) {
prefs->RegisterIntegerPref(kPinyinIntegerPrefs[i].pref_name,
kPinyinIntegerPrefs[i].default_pref_value);
}
prefs->RegisterIntegerPref(kPinyinDoublePinyinSchema.pref_name,
kPinyinDoublePinyinSchema.default_pref_value);
for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) {
prefs->RegisterBooleanPref(kMozcBooleanPrefs[i].pref_name,
kMozcBooleanPrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) {
prefs->RegisterStringPref(
kMozcMultipleChoicePrefs[i].pref_name,
kMozcMultipleChoicePrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) {
prefs->RegisterIntegerPref(kMozcIntegerPrefs[i].pref_name,
kMozcIntegerPrefs[i].default_pref_value);
}
}
void Preferences::Init(PrefService* prefs) {
tap_to_click_enabled_.Init(prefs::kTapToClickEnabled, prefs, this);
accessibility_enabled_.Init(prefs::kAccessibilityEnabled, prefs, this);
vert_edge_scroll_enabled_.Init(prefs::kVertEdgeScrollEnabled, prefs, this);
speed_factor_.Init(prefs::kTouchpadSpeedFactor, prefs, this);
sensitivity_.Init(prefs::kTouchpadSensitivity, prefs, this);
language_hotkey_next_engine_in_menu_.Init(
prefs::kLanguageHotkeyNextEngineInMenu, prefs, this);
language_hotkey_previous_engine_.Init(
prefs::kLanguageHotkeyPreviousEngine, prefs, this);
language_preload_engines_.Init(prefs::kLanguagePreloadEngines, prefs, this);
for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
language_chewing_boolean_prefs_[i].Init(
kChewingBooleanPrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
language_chewing_multiple_choice_prefs_[i].Init(
kChewingMultipleChoicePrefs[i].pref_name, prefs, this);
}
language_chewing_hsu_sel_key_type_.Init(
kChewingHsuSelKeyType.pref_name, prefs, this);
for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
language_chewing_integer_prefs_[i].Init(
kChewingIntegerPrefs[i].pref_name, prefs, this);
}
language_hangul_keyboard_.Init(prefs::kLanguageHangulKeyboard, prefs, this);
for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) {
language_pinyin_boolean_prefs_[i].Init(
kPinyinBooleanPrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) {
language_pinyin_int_prefs_[i].Init(
kPinyinIntegerPrefs[i].pref_name, prefs, this);
}
language_pinyin_double_pinyin_schema_.Init(
kPinyinDoublePinyinSchema.pref_name, prefs, this);
for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) {
language_mozc_boolean_prefs_[i].Init(
kMozcBooleanPrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) {
language_mozc_multiple_choice_prefs_[i].Init(
kMozcMultipleChoicePrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) {
language_mozc_integer_prefs_[i].Init(
kMozcIntegerPrefs[i].pref_name, prefs, this);
}
// Initialize touchpad settings to what's saved in user preferences.
NotifyPrefChanged(NULL);
}
void Preferences::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED)
NotifyPrefChanged(Details<std::wstring>(details).ptr());
}
void Preferences::NotifyPrefChanged(const std::wstring* pref_name) {
if (!pref_name || *pref_name == prefs::kTapToClickEnabled) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(
PARAM_BOOL_TAP_TO_CLICK,
tap_to_click_enabled_.GetValue());
}
if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(
PARAM_BOOL_VERTICAL_EDGE_SCROLLING,
vert_edge_scroll_enabled_.GetValue());
}
if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(
PARAM_RANGE_SPEED_SENSITIVITY,
speed_factor_.GetValue());
}
if (!pref_name || *pref_name == prefs::kTouchpadSensitivity) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(
PARAM_RANGE_TOUCH_SENSITIVITY,
sensitivity_.GetValue());
}
// We don't handle prefs::kLanguageCurrentInputMethod and PreviousInputMethod
// here.
if (!pref_name || *pref_name == prefs::kLanguageHotkeyNextEngineInMenu) {
SetLanguageConfigStringListAsCSV(
kHotKeySectionName,
kNextEngineInMenuConfigName,
language_hotkey_next_engine_in_menu_.GetValue());
}
if (!pref_name || *pref_name == prefs::kLanguageHotkeyPreviousEngine) {
SetLanguageConfigStringListAsCSV(
kHotKeySectionName,
kPreviousEngineConfigName,
language_hotkey_previous_engine_.GetValue());
}
if (!pref_name || *pref_name == prefs::kLanguagePreloadEngines) {
SetLanguageConfigStringListAsCSV(kGeneralSectionName,
kPreloadEnginesConfigName,
language_preload_engines_.GetValue());
}
for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
if (!pref_name || *pref_name == kChewingBooleanPrefs[i].pref_name) {
SetLanguageConfigBoolean(kChewingSectionName,
kChewingBooleanPrefs[i].ibus_config_name,
language_chewing_boolean_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
if (!pref_name || *pref_name == kChewingMultipleChoicePrefs[i].pref_name) {
SetLanguageConfigString(
kChewingSectionName,
kChewingMultipleChoicePrefs[i].ibus_config_name,
language_chewing_multiple_choice_prefs_[i].GetValue());
}
}
if (!pref_name || *pref_name == kChewingHsuSelKeyType.pref_name) {
SetLanguageConfigInteger(
kChewingSectionName,
kChewingHsuSelKeyType.ibus_config_name,
language_chewing_hsu_sel_key_type_.GetValue());
}
for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
if (!pref_name || *pref_name == kChewingIntegerPrefs[i].pref_name) {
SetLanguageConfigInteger(kChewingSectionName,
kChewingIntegerPrefs[i].ibus_config_name,
language_chewing_integer_prefs_[i].GetValue());
}
}
if (!pref_name || *pref_name == prefs::kLanguageHangulKeyboard) {
SetLanguageConfigString(kHangulSectionName, kHangulKeyboardConfigName,
language_hangul_keyboard_.GetValue());
}
for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) {
if (!pref_name || *pref_name == kPinyinBooleanPrefs[i].pref_name) {
SetLanguageConfigBoolean(kPinyinSectionName,
kPinyinBooleanPrefs[i].ibus_config_name,
language_pinyin_boolean_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) {
if (!pref_name || *pref_name == kPinyinIntegerPrefs[i].pref_name) {
SetLanguageConfigInteger(kPinyinSectionName,
kPinyinIntegerPrefs[i].ibus_config_name,
language_pinyin_int_prefs_[i].GetValue());
}
}
if (!pref_name || *pref_name == kPinyinDoublePinyinSchema.pref_name) {
SetLanguageConfigInteger(
kPinyinSectionName,
kPinyinDoublePinyinSchema.ibus_config_name,
language_pinyin_double_pinyin_schema_.GetValue());
}
for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) {
if (!pref_name || *pref_name == kMozcBooleanPrefs[i].pref_name) {
SetLanguageConfigBoolean(kMozcSectionName,
kMozcBooleanPrefs[i].ibus_config_name,
language_mozc_boolean_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) {
if (!pref_name || *pref_name == kMozcMultipleChoicePrefs[i].pref_name) {
SetLanguageConfigString(
kMozcSectionName,
kMozcMultipleChoicePrefs[i].ibus_config_name,
language_mozc_multiple_choice_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) {
if (!pref_name || *pref_name == kMozcIntegerPrefs[i].pref_name) {
SetLanguageConfigInteger(kMozcSectionName,
kMozcIntegerPrefs[i].ibus_config_name,
language_mozc_integer_prefs_[i].GetValue());
}
}
}
void Preferences::SetLanguageConfigBoolean(const char* section,
const char* name,
bool value) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeBool;
config.bool_value = value;
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigInteger(const char* section,
const char* name,
int value) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeInt;
config.int_value = value;
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigString(const char* section,
const char* name,
const std::string& value) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeString;
config.string_value = value;
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigStringList(
const char* section,
const char* name,
const std::vector<std::string>& values) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeStringList;
for (size_t i = 0; i < values.size(); ++i)
config.string_list_value.push_back(values[i]);
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigStringListAsCSV(const char* section,
const char* name,
const std::string& value) {
LOG(INFO) << "Setting " << name << " to '" << value << "'";
std::vector<std::string> split_values;
if (!value.empty())
SplitString(value, ',', &split_values);
// We should call the cros API even when |value| is empty, to disable default
// config.
SetLanguageConfigStringList(section, name, split_values);
}
} // namespace chromeos
<commit_msg>Preload all IMEs/Layouts for the UI Language on login, if the value has not yet been set.<commit_after>// 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/chromeos/preferences.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/input_method_library.h"
#include "chrome/browser/chromeos/cros/synaptics_library.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/pref_member.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "unicode/timezone.h"
namespace chromeos {
static const char kFallbackInputMethodLocale[] = "en-US";
// static
void Preferences::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kTapToClickEnabled, false);
prefs->RegisterBooleanPref(prefs::kAccessibilityEnabled, false);
prefs->RegisterBooleanPref(prefs::kVertEdgeScrollEnabled, false);
prefs->RegisterIntegerPref(prefs::kTouchpadSpeedFactor, 9);
prefs->RegisterIntegerPref(prefs::kTouchpadSensitivity, 5);
prefs->RegisterStringPref(prefs::kLanguageCurrentInputMethod, "");
prefs->RegisterStringPref(prefs::kLanguagePreviousInputMethod, "");
prefs->RegisterStringPref(prefs::kLanguageHotkeyNextEngineInMenu,
kHotkeyNextEngineInMenu);
prefs->RegisterStringPref(prefs::kLanguageHotkeyPreviousEngine,
kHotkeyPreviousEngine);
prefs->RegisterStringPref(prefs::kLanguagePreloadEngines,
kFallbackInputMethodId); // EN layout
for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
prefs->RegisterBooleanPref(kChewingBooleanPrefs[i].pref_name,
kChewingBooleanPrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
prefs->RegisterStringPref(
kChewingMultipleChoicePrefs[i].pref_name,
kChewingMultipleChoicePrefs[i].default_pref_value);
}
prefs->RegisterIntegerPref(kChewingHsuSelKeyType.pref_name,
kChewingHsuSelKeyType.default_pref_value);
for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
prefs->RegisterIntegerPref(kChewingIntegerPrefs[i].pref_name,
kChewingIntegerPrefs[i].default_pref_value);
}
prefs->RegisterStringPref(
prefs::kLanguageHangulKeyboard,
kHangulKeyboardNameIDPairs[0].keyboard_id);
for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) {
prefs->RegisterBooleanPref(kPinyinBooleanPrefs[i].pref_name,
kPinyinBooleanPrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) {
prefs->RegisterIntegerPref(kPinyinIntegerPrefs[i].pref_name,
kPinyinIntegerPrefs[i].default_pref_value);
}
prefs->RegisterIntegerPref(kPinyinDoublePinyinSchema.pref_name,
kPinyinDoublePinyinSchema.default_pref_value);
for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) {
prefs->RegisterBooleanPref(kMozcBooleanPrefs[i].pref_name,
kMozcBooleanPrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) {
prefs->RegisterStringPref(
kMozcMultipleChoicePrefs[i].pref_name,
kMozcMultipleChoicePrefs[i].default_pref_value);
}
for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) {
prefs->RegisterIntegerPref(kMozcIntegerPrefs[i].pref_name,
kMozcIntegerPrefs[i].default_pref_value);
}
}
void Preferences::Init(PrefService* prefs) {
tap_to_click_enabled_.Init(prefs::kTapToClickEnabled, prefs, this);
accessibility_enabled_.Init(prefs::kAccessibilityEnabled, prefs, this);
vert_edge_scroll_enabled_.Init(prefs::kVertEdgeScrollEnabled, prefs, this);
speed_factor_.Init(prefs::kTouchpadSpeedFactor, prefs, this);
sensitivity_.Init(prefs::kTouchpadSensitivity, prefs, this);
language_hotkey_next_engine_in_menu_.Init(
prefs::kLanguageHotkeyNextEngineInMenu, prefs, this);
language_hotkey_previous_engine_.Init(
prefs::kLanguageHotkeyPreviousEngine, prefs, this);
language_preload_engines_.Init(prefs::kLanguagePreloadEngines, prefs, this);
for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
language_chewing_boolean_prefs_[i].Init(
kChewingBooleanPrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
language_chewing_multiple_choice_prefs_[i].Init(
kChewingMultipleChoicePrefs[i].pref_name, prefs, this);
}
language_chewing_hsu_sel_key_type_.Init(
kChewingHsuSelKeyType.pref_name, prefs, this);
for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
language_chewing_integer_prefs_[i].Init(
kChewingIntegerPrefs[i].pref_name, prefs, this);
}
language_hangul_keyboard_.Init(prefs::kLanguageHangulKeyboard, prefs, this);
for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) {
language_pinyin_boolean_prefs_[i].Init(
kPinyinBooleanPrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) {
language_pinyin_int_prefs_[i].Init(
kPinyinIntegerPrefs[i].pref_name, prefs, this);
}
language_pinyin_double_pinyin_schema_.Init(
kPinyinDoublePinyinSchema.pref_name, prefs, this);
for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) {
language_mozc_boolean_prefs_[i].Init(
kMozcBooleanPrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) {
language_mozc_multiple_choice_prefs_[i].Init(
kMozcMultipleChoicePrefs[i].pref_name, prefs, this);
}
for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) {
language_mozc_integer_prefs_[i].Init(
kMozcIntegerPrefs[i].pref_name, prefs, this);
}
std::string locale(g_browser_process->GetApplicationLocale());
if (locale != kFallbackInputMethodLocale &&
!prefs->HasPrefPath(prefs::kLanguagePreloadEngines)) {
std::string preload_engines(language_preload_engines_.GetValue());
std::vector<std::string> input_method_ids;
input_method::GetInputMethodIdsFromLanguageCode(
locale, input_method::kAllInputMethods, &input_method_ids);
if (!input_method_ids.empty()) {
if (!preload_engines.empty())
preload_engines += ',';
preload_engines += JoinString(input_method_ids, ',');
}
language_preload_engines_.SetValue(preload_engines);
}
// Initialize touchpad settings to what's saved in user preferences.
NotifyPrefChanged(NULL);
}
void Preferences::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED)
NotifyPrefChanged(Details<std::wstring>(details).ptr());
}
void Preferences::NotifyPrefChanged(const std::wstring* pref_name) {
if (!pref_name || *pref_name == prefs::kTapToClickEnabled) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(
PARAM_BOOL_TAP_TO_CLICK,
tap_to_click_enabled_.GetValue());
}
if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(
PARAM_BOOL_VERTICAL_EDGE_SCROLLING,
vert_edge_scroll_enabled_.GetValue());
}
if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(
PARAM_RANGE_SPEED_SENSITIVITY,
speed_factor_.GetValue());
}
if (!pref_name || *pref_name == prefs::kTouchpadSensitivity) {
CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(
PARAM_RANGE_TOUCH_SENSITIVITY,
sensitivity_.GetValue());
}
// We don't handle prefs::kLanguageCurrentInputMethod and PreviousInputMethod
// here.
if (!pref_name || *pref_name == prefs::kLanguageHotkeyNextEngineInMenu) {
SetLanguageConfigStringListAsCSV(
kHotKeySectionName,
kNextEngineInMenuConfigName,
language_hotkey_next_engine_in_menu_.GetValue());
}
if (!pref_name || *pref_name == prefs::kLanguageHotkeyPreviousEngine) {
SetLanguageConfigStringListAsCSV(
kHotKeySectionName,
kPreviousEngineConfigName,
language_hotkey_previous_engine_.GetValue());
}
if (!pref_name || *pref_name == prefs::kLanguagePreloadEngines) {
SetLanguageConfigStringListAsCSV(kGeneralSectionName,
kPreloadEnginesConfigName,
language_preload_engines_.GetValue());
}
for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
if (!pref_name || *pref_name == kChewingBooleanPrefs[i].pref_name) {
SetLanguageConfigBoolean(kChewingSectionName,
kChewingBooleanPrefs[i].ibus_config_name,
language_chewing_boolean_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
if (!pref_name || *pref_name == kChewingMultipleChoicePrefs[i].pref_name) {
SetLanguageConfigString(
kChewingSectionName,
kChewingMultipleChoicePrefs[i].ibus_config_name,
language_chewing_multiple_choice_prefs_[i].GetValue());
}
}
if (!pref_name || *pref_name == kChewingHsuSelKeyType.pref_name) {
SetLanguageConfigInteger(
kChewingSectionName,
kChewingHsuSelKeyType.ibus_config_name,
language_chewing_hsu_sel_key_type_.GetValue());
}
for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
if (!pref_name || *pref_name == kChewingIntegerPrefs[i].pref_name) {
SetLanguageConfigInteger(kChewingSectionName,
kChewingIntegerPrefs[i].ibus_config_name,
language_chewing_integer_prefs_[i].GetValue());
}
}
if (!pref_name || *pref_name == prefs::kLanguageHangulKeyboard) {
SetLanguageConfigString(kHangulSectionName, kHangulKeyboardConfigName,
language_hangul_keyboard_.GetValue());
}
for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) {
if (!pref_name || *pref_name == kPinyinBooleanPrefs[i].pref_name) {
SetLanguageConfigBoolean(kPinyinSectionName,
kPinyinBooleanPrefs[i].ibus_config_name,
language_pinyin_boolean_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) {
if (!pref_name || *pref_name == kPinyinIntegerPrefs[i].pref_name) {
SetLanguageConfigInteger(kPinyinSectionName,
kPinyinIntegerPrefs[i].ibus_config_name,
language_pinyin_int_prefs_[i].GetValue());
}
}
if (!pref_name || *pref_name == kPinyinDoublePinyinSchema.pref_name) {
SetLanguageConfigInteger(
kPinyinSectionName,
kPinyinDoublePinyinSchema.ibus_config_name,
language_pinyin_double_pinyin_schema_.GetValue());
}
for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) {
if (!pref_name || *pref_name == kMozcBooleanPrefs[i].pref_name) {
SetLanguageConfigBoolean(kMozcSectionName,
kMozcBooleanPrefs[i].ibus_config_name,
language_mozc_boolean_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) {
if (!pref_name || *pref_name == kMozcMultipleChoicePrefs[i].pref_name) {
SetLanguageConfigString(
kMozcSectionName,
kMozcMultipleChoicePrefs[i].ibus_config_name,
language_mozc_multiple_choice_prefs_[i].GetValue());
}
}
for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) {
if (!pref_name || *pref_name == kMozcIntegerPrefs[i].pref_name) {
SetLanguageConfigInteger(kMozcSectionName,
kMozcIntegerPrefs[i].ibus_config_name,
language_mozc_integer_prefs_[i].GetValue());
}
}
}
void Preferences::SetLanguageConfigBoolean(const char* section,
const char* name,
bool value) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeBool;
config.bool_value = value;
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigInteger(const char* section,
const char* name,
int value) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeInt;
config.int_value = value;
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigString(const char* section,
const char* name,
const std::string& value) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeString;
config.string_value = value;
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigStringList(
const char* section,
const char* name,
const std::vector<std::string>& values) {
ImeConfigValue config;
config.type = ImeConfigValue::kValueTypeStringList;
for (size_t i = 0; i < values.size(); ++i)
config.string_list_value.push_back(values[i]);
CrosLibrary::Get()->GetInputMethodLibrary()->
SetImeConfig(section, name, config);
}
void Preferences::SetLanguageConfigStringListAsCSV(const char* section,
const char* name,
const std::string& value) {
LOG(INFO) << "Setting " << name << " to '" << value << "'";
std::vector<std::string> split_values;
if (!value.empty())
SplitString(value, ',', &split_values);
// We should call the cros API even when |value| is empty, to disable default
// config.
SetLanguageConfigStringList(section, name, split_values);
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <windows.h>
#include "base/command_line.h"
#include "base/basictypes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/test/ui/ui_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class ChromeLoggingTest : public testing::Test {
public:
// Stores the current value of the log file name environment
// variable and sets the variable to new_value.
void SaveEnvironmentVariable(std::wstring new_value) {
unsigned status = GetEnvironmentVariable(env_vars::kLogFileName,
environment_filename_,
MAX_PATH);
if (!status) {
wcscpy_s(environment_filename_, L"");
}
SetEnvironmentVariable(env_vars::kLogFileName, new_value.c_str());
}
// Restores the value of the log file nave environment variable
// previously saved by SaveEnvironmentVariable().
void RestoreEnvironmentVariable() {
SetEnvironmentVariable(env_vars::kLogFileName, environment_filename_);
}
private:
wchar_t environment_filename_[MAX_PATH]; // Saves real environment value.
};
};
// Tests the log file name getter without an environment variable.
TEST_F(ChromeLoggingTest, LogFileName) {
SaveEnvironmentVariable(std::wstring());
std::wstring filename = logging::GetLogFileName();
ASSERT_NE(std::wstring::npos, filename.find(L"chrome_debug.log"));
RestoreEnvironmentVariable();
}
// Tests the log file name getter with an environment variable.
TEST_F(ChromeLoggingTest, EnvironmentLogFileName) {
SaveEnvironmentVariable(std::wstring(L"test value"));
std::wstring filename = logging::GetLogFileName();
ASSERT_EQ(std::wstring(L"test value"), filename);
RestoreEnvironmentVariable();
}
#ifndef NDEBUG // We don't have assertions in release builds.
// Tests whether we correctly fail on browser assertions during tests.
class AssertionTest : public UITest {
protected:
AssertionTest() : UITest()
{
// Initial loads will never complete due to assertion.
wait_for_initial_loads_ = false;
// We're testing the renderer rather than the browser assertion here,
// because the browser assertion would flunk the test during SetUp()
// (since TAU wouldn't be able to find the browser window).
launch_arguments_.AppendSwitch(switches::kRendererAssertTest);
}
};
// Launch the app in assertion test mode, then close the app.
TEST_F(AssertionTest, Assertion) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_errors_ = 0;
expected_crashes_ = 0;
} else {
expected_errors_ = 1;
expected_crashes_ = 1;
}
}
#endif // NDEBUG
// Tests whether we correctly fail on browser crashes during UI Tests.
class RendererCrashTest : public UITest {
protected:
RendererCrashTest() : UITest()
{
// Initial loads will never complete due to crash.
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitch(switches::kRendererCrashTest);
}
};
// Launch the app in renderer crash test mode, then close the app.
TEST_F(RendererCrashTest, Crash) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_crashes_ = 0;
} else {
// Wait while the process is writing the crash dump.
PlatformThread::Sleep(5000);
expected_crashes_ = 1;
}
}
// Tests whether we correctly fail on browser crashes during UI Tests.
class BrowserCrashTest : public UITest {
protected:
BrowserCrashTest() : UITest()
{
// Initial loads will never complete due to crash.
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitch(switches::kBrowserCrashTest);
}
};
// Launch the app in browser crash test mode.
// This test is disabled. See bug 1198934.
TEST_F(BrowserCrashTest, DISABLED_Crash) {
// Wait while the process is writing the crash dump.
PlatformThread::Sleep(5000);
expected_crashes_ = 1;
}
<commit_msg>Speed up RendererCrashTest.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <windows.h>
#include "base/command_line.h"
#include "base/basictypes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class ChromeLoggingTest : public testing::Test {
public:
// Stores the current value of the log file name environment
// variable and sets the variable to new_value.
void SaveEnvironmentVariable(std::wstring new_value) {
unsigned status = GetEnvironmentVariable(env_vars::kLogFileName,
environment_filename_,
MAX_PATH);
if (!status) {
wcscpy_s(environment_filename_, L"");
}
SetEnvironmentVariable(env_vars::kLogFileName, new_value.c_str());
}
// Restores the value of the log file nave environment variable
// previously saved by SaveEnvironmentVariable().
void RestoreEnvironmentVariable() {
SetEnvironmentVariable(env_vars::kLogFileName, environment_filename_);
}
private:
wchar_t environment_filename_[MAX_PATH]; // Saves real environment value.
};
};
// Tests the log file name getter without an environment variable.
TEST_F(ChromeLoggingTest, LogFileName) {
SaveEnvironmentVariable(std::wstring());
std::wstring filename = logging::GetLogFileName();
ASSERT_NE(std::wstring::npos, filename.find(L"chrome_debug.log"));
RestoreEnvironmentVariable();
}
// Tests the log file name getter with an environment variable.
TEST_F(ChromeLoggingTest, EnvironmentLogFileName) {
SaveEnvironmentVariable(std::wstring(L"test value"));
std::wstring filename = logging::GetLogFileName();
ASSERT_EQ(std::wstring(L"test value"), filename);
RestoreEnvironmentVariable();
}
#ifndef NDEBUG // We don't have assertions in release builds.
// Tests whether we correctly fail on browser assertions during tests.
class AssertionTest : public UITest {
protected:
AssertionTest() : UITest()
{
// Initial loads will never complete due to assertion.
wait_for_initial_loads_ = false;
// We're testing the renderer rather than the browser assertion here,
// because the browser assertion would flunk the test during SetUp()
// (since TAU wouldn't be able to find the browser window).
launch_arguments_.AppendSwitch(switches::kRendererAssertTest);
}
};
// Launch the app in assertion test mode, then close the app.
TEST_F(AssertionTest, Assertion) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_errors_ = 0;
expected_crashes_ = 0;
} else {
expected_errors_ = 1;
expected_crashes_ = 1;
}
}
#endif // NDEBUG
// Tests whether we correctly fail on browser crashes during UI Tests.
class RendererCrashTest : public UITest {
protected:
RendererCrashTest() : UITest()
{
// Initial loads will never complete due to crash.
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitch(switches::kRendererCrashTest);
}
};
// Launch the app in renderer crash test mode, then close the app.
TEST_F(RendererCrashTest, Crash) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_crashes_ = 0;
} else {
scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));
expected_crashes_ = 1;
}
}
// Tests whether we correctly fail on browser crashes during UI Tests.
class BrowserCrashTest : public UITest {
protected:
BrowserCrashTest() : UITest()
{
// Initial loads will never complete due to crash.
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitch(switches::kBrowserCrashTest);
}
};
// Launch the app in browser crash test mode.
// This test is disabled. See bug 6910.
TEST_F(BrowserCrashTest, DISABLED_Crash) {
// Wait while the process is writing the crash dump.
PlatformThread::Sleep(5000);
expected_crashes_ = 1;
}
<|endoftext|> |
<commit_before>// metar interface class
//
// Written by Melchior FRANZ, started December 2003.
//
// Copyright (C) 2003 Melchior FRANZ - mfranz@aon.at
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
//
// $Id$
#ifndef _METAR_HXX
#define _METAR_HXX
#include <vector>
#include <map>
#include <string>
#include <simgear/constants.h>
SG_USING_STD(vector);
SG_USING_STD(map);
SG_USING_STD(string);
const double SGMetarNaN = -1E20;
#define NaN SGMetarNaN
struct Token {
char *id;
char *text;
};
class SGMetar;
class SGMetarVisibility {
friend class SGMetar;
public:
SGMetarVisibility() :
_distance(NaN),
_direction(-1),
_modifier(EQUALS),
_tendency(NONE) {}
enum Modifier {
NOGO,
EQUALS,
LESS_THAN,
GREATER_THAN
};
enum Tendency {
NONE,
STABLE,
INCREASING,
DECREASING
};
inline double getVisibility_m() const { return _distance; }
inline double getVisibility_ft() const { return _distance == NaN ? NaN : _distance * SG_METER_TO_FEET; }
inline double getVisibility_sm() const { return _distance == NaN ? NaN : _distance * SG_METER_TO_SM; }
inline int getDirection() const { return _direction; }
inline int getModifier() const { return _modifier; }
inline int getTendency() const { return _tendency; }
protected:
double _distance;
int _direction;
int _modifier;
int _tendency;
};
// runway condition (surface and visibility)
class SGMetarRunway {
friend class SGMetar;
public:
SGMetarRunway() :
_deposit(0),
_extent(-1),
_extent_string(0),
_depth(NaN),
_friction(NaN),
_friction_string(0),
_comment(0),
_wind_shear(false) {}
inline const char *getDeposit() const { return _deposit; }
inline double getExtent() const { return _extent; }
inline const char *getExtentString() const { return _extent_string; }
inline double getDepth() const { return _depth; }
inline double getFriction() const { return _friction; }
inline const char *getFrictionString() const { return _friction_string; }
inline const char *getComment() const { return _comment; }
inline const bool getWindShear() const { return _wind_shear; }
inline SGMetarVisibility getMinVisibility() const { return _min_visibility; }
inline SGMetarVisibility getMaxVisibility() const { return _max_visibility; }
protected:
SGMetarVisibility _min_visibility;
SGMetarVisibility _max_visibility;
const char *_deposit;
int _extent;
const char *_extent_string;
double _depth;
double _friction;
const char *_friction_string;
const char *_comment;
bool _wind_shear;
};
// cloud layer
class SGMetarCloud {
friend class SGMetar;
public:
SGMetarCloud() :
_coverage(-1),
_altitude(NaN),
_type(0),
_type_long(0) {}
inline int getCoverage() const { return _coverage; }
inline double getAltitude_m() const { return _altitude; }
inline double getAltitude_ft() const { return _altitude == NaN ? NaN : _altitude * SG_METER_TO_FEET; }
inline char *getTypeString() const { return _type; }
inline char *getTypeLongString() const { return _type_long; }
protected:
int _coverage; // quarters: 0 -> clear ... 4 -> overcast
double _altitude; // 1000 m
char *_type; // CU
char *_type_long; // cumulus
};
class SGMetar {
public:
SGMetar(const char *m);
SGMetar(const string m) { SGMetar(m.c_str()); }
~SGMetar();
enum ReportType {
NONE,
AUTO,
COR,
RTD
};
inline const char *getData() const { return _data; }
inline const char *getUnusedData() const { return _m; }
inline const char *getId() const { return _icao; }
inline int getYear() const { return _year; }
inline int getMonth() const { return _month; }
inline int getDay() const { return _day; }
inline int getHour() const { return _hour; }
inline int getMinute() const { return _minute; }
inline int getReportType() const { return _report_type; }
inline int getWindDir() const { return _wind_dir; }
inline double getWindSpeed_mps() const { return _wind_speed; }
inline double getWindSpeed_kmh() const { return _wind_speed == NaN ? NaN : _wind_speed * 3.6; }
inline double getWindSpeed_kt() const { return _wind_speed == NaN ? NaN : _wind_speed * SG_MPS_TO_KT; }
inline double getWindSpeed_mph() const { return _wind_speed == NaN ? NaN : _wind_speed * SG_MPS_TO_MPH; }
inline double getGustSpeed_mps() const { return _gust_speed; }
inline double getGustSpeed_kmh() const { return _gust_speed == NaN ? NaN : _gust_speed * 3.6; }
inline double getGustSpeed_kt() const { return _gust_speed == NaN ? NaN : _gust_speed * SG_MPS_TO_KT; }
inline double getGustSpeed_mph() const { return _gust_speed == NaN ? NaN : _gust_speed * SG_MPS_TO_MPH; }
inline int getWindRangeFrom() const { return _wind_range_from; }
inline int getWindRangeTo() const { return _wind_range_to; }
inline SGMetarVisibility& getMinVisibility() { return _min_visibility; }
inline SGMetarVisibility& getMaxVisibility() { return _max_visibility; }
inline SGMetarVisibility& getVertVisibility() { return _vert_visibility; }
inline SGMetarVisibility *getDirVisibility() { return _dir_visibility; }
inline double getTemperature_C() const { return _temp; }
inline double getTemperature_F() const { return _temp == NaN ? NaN : 1.8 * _temp + 32; }
inline double getDewpoint_C() const { return _dewp; }
inline double getDewpoint_F() const { return _dewp == NaN ? NaN : 1.8 * _dewp + 32; }
inline double getPressure_hPa() const { return _pressure == NaN ? NaN : _pressure / 100; }
inline double getPressure_inHg() const { return _pressure == NaN ? NaN : _pressure * SG_PA_TO_INHG; }
double getRelHumidity() const;
inline vector<SGMetarCloud>& getClouds() { return _clouds; }
inline map<string, SGMetarRunway>& getRunways() { return _runways; }
inline vector<string>& getWeather() { return _weather; }
protected:
int _grpcount;
char *_data;
char *_m;
char _icao[5];
int _year;
int _month;
int _day;
int _hour;
int _minute;
int _report_type;
int _wind_dir;
double _wind_speed;
double _gust_speed;
int _wind_range_from;
int _wind_range_to;
double _temp;
double _dewp;
double _pressure;
SGMetarVisibility _min_visibility;
SGMetarVisibility _max_visibility;
SGMetarVisibility _vert_visibility;
SGMetarVisibility _dir_visibility[8];
vector<SGMetarCloud> _clouds;
map<string, SGMetarRunway> _runways;
vector<string> _weather;
bool scanPreambleDate();
bool scanPreambleTime();
bool scanType();
bool scanId();
bool scanDate();
bool scanModifier();
bool scanWind();
bool scanVariability();
bool scanVisibility();
bool scanRwyVisRange();
bool scanSkyCondition();
bool scanWeather();
bool scanTemperature();
bool scanPressure();
bool scanRunwayReport();
bool scanWindShear();
bool scanTrendForecast();
bool scanColorState();
bool scanRemark();
bool scanRemainder();
int scanNumber(char **str, int *num, int min, int max = 0);
bool scanBoundary(char **str);
const struct Token *scanToken(char **str, const struct Token *list);
char *loadData(const char *id);
void normalizeData();
};
#undef NaN
#endif // _METAR_HXX
<commit_msg>Comment out an improperly written constructor.<commit_after>// metar interface class
//
// Written by Melchior FRANZ, started December 2003.
//
// Copyright (C) 2003 Melchior FRANZ - mfranz@aon.at
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
//
// $Id$
#ifndef _METAR_HXX
#define _METAR_HXX
#include <vector>
#include <map>
#include <string>
#include <simgear/constants.h>
SG_USING_STD(vector);
SG_USING_STD(map);
SG_USING_STD(string);
const double SGMetarNaN = -1E20;
#define NaN SGMetarNaN
struct Token {
char *id;
char *text;
};
class SGMetar;
class SGMetarVisibility {
friend class SGMetar;
public:
SGMetarVisibility() :
_distance(NaN),
_direction(-1),
_modifier(EQUALS),
_tendency(NONE) {}
enum Modifier {
NOGO,
EQUALS,
LESS_THAN,
GREATER_THAN
};
enum Tendency {
NONE,
STABLE,
INCREASING,
DECREASING
};
inline double getVisibility_m() const { return _distance; }
inline double getVisibility_ft() const { return _distance == NaN ? NaN : _distance * SG_METER_TO_FEET; }
inline double getVisibility_sm() const { return _distance == NaN ? NaN : _distance * SG_METER_TO_SM; }
inline int getDirection() const { return _direction; }
inline int getModifier() const { return _modifier; }
inline int getTendency() const { return _tendency; }
protected:
double _distance;
int _direction;
int _modifier;
int _tendency;
};
// runway condition (surface and visibility)
class SGMetarRunway {
friend class SGMetar;
public:
SGMetarRunway() :
_deposit(0),
_extent(-1),
_extent_string(0),
_depth(NaN),
_friction(NaN),
_friction_string(0),
_comment(0),
_wind_shear(false) {}
inline const char *getDeposit() const { return _deposit; }
inline double getExtent() const { return _extent; }
inline const char *getExtentString() const { return _extent_string; }
inline double getDepth() const { return _depth; }
inline double getFriction() const { return _friction; }
inline const char *getFrictionString() const { return _friction_string; }
inline const char *getComment() const { return _comment; }
inline const bool getWindShear() const { return _wind_shear; }
inline SGMetarVisibility getMinVisibility() const { return _min_visibility; }
inline SGMetarVisibility getMaxVisibility() const { return _max_visibility; }
protected:
SGMetarVisibility _min_visibility;
SGMetarVisibility _max_visibility;
const char *_deposit;
int _extent;
const char *_extent_string;
double _depth;
double _friction;
const char *_friction_string;
const char *_comment;
bool _wind_shear;
};
// cloud layer
class SGMetarCloud {
friend class SGMetar;
public:
SGMetarCloud() :
_coverage(-1),
_altitude(NaN),
_type(0),
_type_long(0) {}
inline int getCoverage() const { return _coverage; }
inline double getAltitude_m() const { return _altitude; }
inline double getAltitude_ft() const { return _altitude == NaN ? NaN : _altitude * SG_METER_TO_FEET; }
inline char *getTypeString() const { return _type; }
inline char *getTypeLongString() const { return _type_long; }
protected:
int _coverage; // quarters: 0 -> clear ... 4 -> overcast
double _altitude; // 1000 m
char *_type; // CU
char *_type_long; // cumulus
};
class SGMetar {
public:
SGMetar(const char *m);
// The following contructor is tempting, but it is not
// correct, it creates an anonymous instance of SGMetar and
// then immediately throws it away.
// SGMetar(const string m) { SGMetar(m.c_str()); }
~SGMetar();
enum ReportType {
NONE,
AUTO,
COR,
RTD
};
inline const char *getData() const { return _data; }
inline const char *getUnusedData() const { return _m; }
inline const char *getId() const { return _icao; }
inline int getYear() const { return _year; }
inline int getMonth() const { return _month; }
inline int getDay() const { return _day; }
inline int getHour() const { return _hour; }
inline int getMinute() const { return _minute; }
inline int getReportType() const { return _report_type; }
inline int getWindDir() const { return _wind_dir; }
inline double getWindSpeed_mps() const { return _wind_speed; }
inline double getWindSpeed_kmh() const { return _wind_speed == NaN ? NaN : _wind_speed * 3.6; }
inline double getWindSpeed_kt() const { return _wind_speed == NaN ? NaN : _wind_speed * SG_MPS_TO_KT; }
inline double getWindSpeed_mph() const { return _wind_speed == NaN ? NaN : _wind_speed * SG_MPS_TO_MPH; }
inline double getGustSpeed_mps() const { return _gust_speed; }
inline double getGustSpeed_kmh() const { return _gust_speed == NaN ? NaN : _gust_speed * 3.6; }
inline double getGustSpeed_kt() const { return _gust_speed == NaN ? NaN : _gust_speed * SG_MPS_TO_KT; }
inline double getGustSpeed_mph() const { return _gust_speed == NaN ? NaN : _gust_speed * SG_MPS_TO_MPH; }
inline int getWindRangeFrom() const { return _wind_range_from; }
inline int getWindRangeTo() const { return _wind_range_to; }
inline SGMetarVisibility& getMinVisibility() { return _min_visibility; }
inline SGMetarVisibility& getMaxVisibility() { return _max_visibility; }
inline SGMetarVisibility& getVertVisibility() { return _vert_visibility; }
inline SGMetarVisibility *getDirVisibility() { return _dir_visibility; }
inline double getTemperature_C() const { return _temp; }
inline double getTemperature_F() const { return _temp == NaN ? NaN : 1.8 * _temp + 32; }
inline double getDewpoint_C() const { return _dewp; }
inline double getDewpoint_F() const { return _dewp == NaN ? NaN : 1.8 * _dewp + 32; }
inline double getPressure_hPa() const { return _pressure == NaN ? NaN : _pressure / 100; }
inline double getPressure_inHg() const { return _pressure == NaN ? NaN : _pressure * SG_PA_TO_INHG; }
double getRelHumidity() const;
inline vector<SGMetarCloud>& getClouds() { return _clouds; }
inline map<string, SGMetarRunway>& getRunways() { return _runways; }
inline vector<string>& getWeather() { return _weather; }
protected:
int _grpcount;
char *_data;
char *_m;
char _icao[5];
int _year;
int _month;
int _day;
int _hour;
int _minute;
int _report_type;
int _wind_dir;
double _wind_speed;
double _gust_speed;
int _wind_range_from;
int _wind_range_to;
double _temp;
double _dewp;
double _pressure;
SGMetarVisibility _min_visibility;
SGMetarVisibility _max_visibility;
SGMetarVisibility _vert_visibility;
SGMetarVisibility _dir_visibility[8];
vector<SGMetarCloud> _clouds;
map<string, SGMetarRunway> _runways;
vector<string> _weather;
bool scanPreambleDate();
bool scanPreambleTime();
bool scanType();
bool scanId();
bool scanDate();
bool scanModifier();
bool scanWind();
bool scanVariability();
bool scanVisibility();
bool scanRwyVisRange();
bool scanSkyCondition();
bool scanWeather();
bool scanTemperature();
bool scanPressure();
bool scanRunwayReport();
bool scanWindShear();
bool scanTrendForecast();
bool scanColorState();
bool scanRemark();
bool scanRemainder();
int scanNumber(char **str, int *num, int min, int max = 0);
bool scanBoundary(char **str);
const struct Token *scanToken(char **str, const struct Token *list);
char *loadData(const char *id);
void normalizeData();
};
#undef NaN
#endif // _METAR_HXX
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layers_interim/base_featuretransformationlayer.h"
#include <memory>
#include "gtest/gtest.h"
#include "elm/core/layerionames.h"
#include "elm/core/signal.h"
#include "elm/ts/layer_assertions.h"
#include "elm/ts/mat_assertions.h"
using namespace std;
using namespace cv;
using namespace elm;
namespace {
const string NAME_IN_M = "in";
const string NAME_OUT_M = "out";
/** @brief class deriving from intermediate base_FeatureTransformationLayer for test purposes
*/
class DummyFeatureTransformationLayer : public base_FeatureTransformationLayer
{
public:
void Clear() {}
void Reconfigure(const LayerConfig &config) {}
void Activate(const Signal &signal) {
m_ = signal.MostRecentMat1f(name_input_)*2.f;
}
DummyFeatureTransformationLayer() {}
};
class FeatureTransformationLayerTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
to_.reset(new DummyFeatureTransformationLayer());
LayerIONames io;
io.Input(DummyFeatureTransformationLayer::KEY_INPUT_STIMULUS, NAME_IN_M);
io.Output(DummyFeatureTransformationLayer::KEY_OUTPUT_RESPONSE, NAME_OUT_M);
to_->IONames(io);
sig_.Append(NAME_IN_M, Mat1f(3, 4, 1.f));
}
virtual void TearDown()
{
sig_.Clear();
}
// members:
shared_ptr<base_Layer> to_; ///< test object
Signal sig_;
};
TEST_F(FeatureTransformationLayerTest, Sanity)
{
EXPECT_EQ(base_FeatureTransformationLayer::KEY_INPUT_STIMULUS,
DummyFeatureTransformationLayer::KEY_INPUT_STIMULUS);
EXPECT_EQ(base_FeatureTransformationLayer::KEY_OUTPUT_RESPONSE,
DummyFeatureTransformationLayer::KEY_OUTPUT_RESPONSE);
}
TEST_F(FeatureTransformationLayerTest, ActivateAndResponse)
{
to_->Activate(sig_);
to_->Response(sig_);
EXPECT_MAT_EQ(sig_.MostRecentMat1f(NAME_IN_M)*2,
sig_.MostRecentMat1f(NAME_OUT_M));
}
} // annonymous namespace for test cases and test fixtures
<commit_msg>test with pointer declared of type base_FeatureTransformationLayer<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layers_interim/base_featuretransformationlayer.h"
#include <memory>
#include "gtest/gtest.h"
#include "elm/core/layerionames.h"
#include "elm/core/signal.h"
#include "elm/ts/layer_assertions.h"
#include "elm/ts/mat_assertions.h"
using namespace std;
using namespace cv;
using namespace elm;
namespace {
const string NAME_IN_M = "in";
const string NAME_OUT_M = "out";
/** @brief class deriving from intermediate base_FeatureTransformationLayer for test purposes
*/
class DummyFeatureTransformationLayer : public base_FeatureTransformationLayer
{
public:
void Clear() {}
void Reconfigure(const LayerConfig &config) {}
void Activate(const Signal &signal) {
m_ = signal.MostRecentMat1f(name_input_)*2.f;
}
DummyFeatureTransformationLayer() {}
};
class FeatureTransformationLayerTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
to_.reset(new DummyFeatureTransformationLayer());
LayerIONames io;
io.Input(DummyFeatureTransformationLayer::KEY_INPUT_STIMULUS, NAME_IN_M);
io.Output(DummyFeatureTransformationLayer::KEY_OUTPUT_RESPONSE, NAME_OUT_M);
to_->IONames(io);
sig_.Append(NAME_IN_M, Mat1f(3, 4, 1.f));
}
virtual void TearDown()
{
sig_.Clear();
}
// members:
shared_ptr<base_Layer> to_; ///< test object
Signal sig_;
};
TEST_F(FeatureTransformationLayerTest, Sanity)
{
EXPECT_EQ(base_FeatureTransformationLayer::KEY_INPUT_STIMULUS,
DummyFeatureTransformationLayer::KEY_INPUT_STIMULUS);
EXPECT_EQ(base_FeatureTransformationLayer::KEY_OUTPUT_RESPONSE,
DummyFeatureTransformationLayer::KEY_OUTPUT_RESPONSE);
}
TEST_F(FeatureTransformationLayerTest, IONames)
{
to_.reset(new DummyFeatureTransformationLayer);
ASSERT_TRUE(sig_.Exists(NAME_IN_M));
// activate before setting io names
ASSERT_FALSE(sig_.Exists(NAME_OUT_M));
EXPECT_THROW(to_->Activate(sig_), ExceptionKeyError);
LayerIONames io;
io.Input(DummyFeatureTransformationLayer::KEY_INPUT_STIMULUS, NAME_IN_M);
io.Output(DummyFeatureTransformationLayer::KEY_OUTPUT_RESPONSE, NAME_OUT_M);
to_->IONames(io);
// re-attempt activation with I/O names properly set
// activate before setting io names
EXPECT_FALSE(sig_.Exists(NAME_OUT_M));
EXPECT_NO_THROW(to_->Activate(sig_));\
to_->Response(sig_);
EXPECT_TRUE(sig_.Exists(NAME_OUT_M)) << "Response missing";
}
TEST_F(FeatureTransformationLayerTest, ActivateAndResponse)
{
to_->Activate(sig_);
to_->Response(sig_);
EXPECT_MAT_EQ(sig_.MostRecentMat1f(NAME_IN_M)*2,
sig_.MostRecentMat1f(NAME_OUT_M));
}
class FeatureTransformationLayerInstTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
to_.reset(new DummyFeatureTransformationLayer());
LayerIONames io;
io.Input(DummyFeatureTransformationLayer::KEY_INPUT_STIMULUS, NAME_IN_M);
io.Output(DummyFeatureTransformationLayer::KEY_OUTPUT_RESPONSE, NAME_OUT_M);
to_->IONames(io);
sig_.Append(NAME_IN_M, Mat1f(3, 4, 1.f));
}
virtual void TearDown()
{
sig_.Clear();
}
// members:
shared_ptr<base_FeatureTransformationLayer> to_; ///< test object
Signal sig_;
};
TEST_F(FeatureTransformationLayerInstTest, IONames)
{
to_.reset(new DummyFeatureTransformationLayer);
ASSERT_TRUE(sig_.Exists(NAME_IN_M));
// activate before setting io names
ASSERT_FALSE(sig_.Exists(NAME_OUT_M));
EXPECT_THROW(to_->Activate(sig_), ExceptionKeyError);
LayerIONames io;
io.Input(DummyFeatureTransformationLayer::KEY_INPUT_STIMULUS, NAME_IN_M);
io.Output(DummyFeatureTransformationLayer::KEY_OUTPUT_RESPONSE, NAME_OUT_M);
to_->IONames(io);
// re-attempt activation with I/O names properly set
// activate before setting io names
EXPECT_FALSE(sig_.Exists(NAME_OUT_M));
EXPECT_NO_THROW(to_->Activate(sig_));\
to_->Response(sig_);
EXPECT_TRUE(sig_.Exists(NAME_OUT_M)) << "Response missing";
}
TEST_F(FeatureTransformationLayerInstTest, ActivateAndResponse)
{
to_->Activate(sig_);
to_->Response(sig_);
EXPECT_MAT_EQ(sig_.MostRecentMat1f(NAME_IN_M)*2,
sig_.MostRecentMat1f(NAME_OUT_M));
}
} // annonymous namespace for test cases and test fixtures
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <zlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <math.h>
#include "vector_tile.pb.h"
extern "C" {
#include "tile.h"
}
#define CMD_BITS 3
// https://github.com/mapbox/mapnik-vector-tile/blob/master/src/vector_tile_compression.hpp
static inline int compress(std::string const& input, std::string& output) {
z_stream deflate_s;
deflate_s.zalloc = Z_NULL;
deflate_s.zfree = Z_NULL;
deflate_s.opaque = Z_NULL;
deflate_s.avail_in = 0;
deflate_s.next_in = Z_NULL;
deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);
deflate_s.next_in = (Bytef *)input.data();
deflate_s.avail_in = input.size();
size_t length = 0;
do {
size_t increase = input.size() / 2 + 1024;
output.resize(length + increase);
deflate_s.avail_out = increase;
deflate_s.next_out = (Bytef *)(output.data() + length);
int ret = deflate(&deflate_s, Z_FINISH);
if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {
return -1;
}
length += (increase - deflate_s.avail_out);
} while (deflate_s.avail_out == 0);
deflateEnd(&deflate_s);
output.resize(length);
return 0;
}
struct draw {
int op;
long long x;
long long y;
};
int decode_feature(char **meta, struct draw *out, int z, unsigned tx, unsigned ty, int detail) {
int len = 0;
while (1) {
int op;
deserialize_int(meta, &op);
if (op == VT_END) {
break;
}
if (out != NULL) {
out[len].op = op;
}
if (op == VT_MOVETO || op == VT_LINETO) {
int wx, wy;
deserialize_int(meta, &wx);
deserialize_int(meta, &wy);
long long wwx = (unsigned) wx;
long long wwy = (unsigned) wy;
if (z != 0) {
wwx -= tx << (32 - z);
wwy -= ty << (32 - z);
}
wwx >>= (32 - detail - z);
wwy >>= (32 - detail - z);
if (out != NULL) {
out[len].x = wwx;
out[len].y = wwy;
}
}
len++;
}
return len;
}
int draw(struct draw *geom, int n, mapnik::vector::tile_feature *feature) {
int px = 0, py = 0;
int cmd_idx = -1;
int cmd = -1;
int length = 0;
int drew = 0;
int i;
for (i = 0; i < n; i++) {
int op = geom[i].op;
if (op != cmd) {
if (cmd_idx >= 0) {
if (feature != NULL) {
feature->set_geometry(cmd_idx, (length << CMD_BITS) | (cmd & ((1 << CMD_BITS) - 1)));
}
}
cmd = op;
length = 0;
if (feature != NULL) {
cmd_idx = feature->geometry_size();
feature->add_geometry(0);
}
}
if (op == VT_MOVETO || op == VT_LINETO) {
long long wwx = geom[i].x;
long long wwy = geom[i].y;
int dx = wwx - px;
int dy = wwy - py;
if (dx == 0 && dy == 0 && op == VT_LINETO) {
printf("0 delta\n");
}
if (feature != NULL) {
feature->add_geometry((dx << 1) ^ (dx >> 31));
feature->add_geometry((dy << 1) ^ (dy >> 31));
}
px = wwx;
py = wwy;
length++;
if (op == VT_LINETO && (dx != 0 || dy != 0)) {
drew = 1;
}
} else if (op == VT_CLOSEPATH) {
length++;
}
}
if (cmd_idx >= 0) {
if (feature != NULL) {
feature->set_geometry(cmd_idx, (length << CMD_BITS) | (cmd & ((1 << CMD_BITS) - 1)));
}
}
return drew;
}
int remove_noop(struct draw *geom, int n) {
// first pass: remove empty linetos
long long x = 0, y = 0;
int out = 0;
int i;
for (i = 0; i < n; i++) {
if (geom[i].op == VT_LINETO && geom[i].x == x && geom[i].y == y) {
continue;
}
if (geom[i].op == VT_CLOSEPATH) {
geom[out++] = geom[i];
} else { /* moveto or lineto */
geom[out++] = geom[i];
x = geom[i].x;
y = geom[i].y;
}
}
// second pass: remove unused movetos
n = out;
out = 0;
for (i = 0; i < n; i++) {
if (geom[i].op == VT_MOVETO) {
if (i + 1 >= n) {
continue;
}
if (geom[i + 1].op == VT_MOVETO) {
continue;
}
if (geom[i + 1].op == VT_CLOSEPATH) {
i++; // also remove unused closepath
continue;
}
}
geom[out++] = geom[i];
}
return out;
}
long long write_tile(struct index *start, struct index *end, char *metabase, unsigned *file_bbox, int z, unsigned tx, unsigned ty, int detail, int basezoom, struct pool *file_keys) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
mapnik::vector::tile tile;
mapnik::vector::tile_layer *layer = tile.add_layers();
layer->set_name("name");
layer->set_version(1);
layer->set_extent(1 << detail);
struct pool keys;
keys.n = 0;
keys.vals = NULL;
keys.head = NULL;
keys.tail = NULL;
struct pool values;
values.n = 0;
values.vals = NULL;
values.head = NULL;
values.tail = NULL;
struct pool dup;
dup.n = 1;
dup.vals = NULL;
dup.head = NULL;
dup.tail = NULL;
double interval = 1;
double seq = 0;
long long count = 0;
if (z < basezoom) {
interval = exp(log(2.5) * (basezoom - z));
}
struct index *i;
for (i = start; i < end; i++) {
int t;
char *meta = metabase + i->fpos;
deserialize_int(&meta, &t);
if (t == VT_POINT) {
seq++;
if (seq >= 0) {
seq -= interval;
} else {
continue;
}
}
int len = decode_feature(&meta, NULL, z, tx, ty, detail);
struct draw geom[len];
meta = metabase + i->fpos;
deserialize_int(&meta, &t);
decode_feature(&meta, geom, z, tx, ty, detail);
if (t == VT_LINE || t == VT_POLYGON) {
len = remove_noop(geom, len);
}
if (t == VT_POINT || draw(geom, len, NULL)) {
struct pool_val *pv = pool_long_long(&dup, &i->fpos, 0);
if (pv->n == 0) {
continue;
}
pv->n = 0;
mapnik::vector::tile_feature *feature = layer->add_features();
if (t == VT_POINT) {
feature->set_type(mapnik::vector::tile::Point);
} else if (t == VT_LINE) {
feature->set_type(mapnik::vector::tile::LineString);
} else if (t == VT_POLYGON) {
feature->set_type(mapnik::vector::tile::Polygon);
} else {
feature->set_type(mapnik::vector::tile::Unknown);
}
draw(geom, len, feature);
count += len;
int m;
deserialize_int(&meta, &m);
int i;
for (i = 0; i < m; i++) {
int t;
deserialize_int(&meta, &t);
struct pool_val *key = deserialize_string(&meta, &keys, VT_STRING);
struct pool_val *value = deserialize_string(&meta, &values, t);
feature->add_tags(key->n);
feature->add_tags(value->n);
// Dup to retain after munmap
pool(file_keys, strdup(key->s), t);
}
}
}
struct pool_val *pv;
for (pv = keys.head; pv != NULL; pv = pv->next) {
layer->add_keys(pv->s, strlen(pv->s));
}
for (pv = values.head; pv != NULL; pv = pv->next) {
mapnik::vector::tile_value *tv = layer->add_values();
if (pv->type == VT_NUMBER) {
tv->set_double_value(atof(pv->s));
} else {
tv->set_string_value(pv->s);
}
}
pool_free(&keys);
pool_free(&values);
pool_free(&dup);
std::string s;
std::string compressed;
tile.SerializeToString(&s);
compress(s, compressed);
if (compressed.size() > 500000) {
fprintf(stderr, "tile %d/%u/%u size is %lld, >500000\n", z, tx, ty, (long long) compressed.size());
exit(EXIT_FAILURE);
}
const char *prefix = "tiles";
char path[strlen(prefix) + 200];
mkdir(prefix, 0777);
sprintf(path, "%s/%d", prefix, z);
mkdir(path, 0777);
sprintf(path, "%s/%d/%u", prefix, z, tx);
mkdir(path, 0777);
sprintf(path, "%s/%d/%u/%u.pbf", prefix, z, tx, ty);
FILE *f = fopen(path, "wb");
fwrite(compressed.data(), 1, compressed.size(), f);
fclose(f);
return count;
}
<commit_msg>Stay in (tile-relative) world-scaled coordinates initially<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <zlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <math.h>
#include "vector_tile.pb.h"
extern "C" {
#include "tile.h"
}
#define CMD_BITS 3
// https://github.com/mapbox/mapnik-vector-tile/blob/master/src/vector_tile_compression.hpp
static inline int compress(std::string const& input, std::string& output) {
z_stream deflate_s;
deflate_s.zalloc = Z_NULL;
deflate_s.zfree = Z_NULL;
deflate_s.opaque = Z_NULL;
deflate_s.avail_in = 0;
deflate_s.next_in = Z_NULL;
deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);
deflate_s.next_in = (Bytef *)input.data();
deflate_s.avail_in = input.size();
size_t length = 0;
do {
size_t increase = input.size() / 2 + 1024;
output.resize(length + increase);
deflate_s.avail_out = increase;
deflate_s.next_out = (Bytef *)(output.data() + length);
int ret = deflate(&deflate_s, Z_FINISH);
if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {
return -1;
}
length += (increase - deflate_s.avail_out);
} while (deflate_s.avail_out == 0);
deflateEnd(&deflate_s);
output.resize(length);
return 0;
}
struct draw {
int op;
long long x;
long long y;
};
int decode_feature(char **meta, struct draw *out, int z, unsigned tx, unsigned ty, int detail) {
int len = 0;
while (1) {
int op;
deserialize_int(meta, &op);
if (op == VT_END) {
break;
}
if (out != NULL) {
out[len].op = op;
}
if (op == VT_MOVETO || op == VT_LINETO) {
int wx, wy;
deserialize_int(meta, &wx);
deserialize_int(meta, &wy);
long long wwx = (unsigned) wx;
long long wwy = (unsigned) wy;
if (z != 0) {
wwx -= tx << (32 - z);
wwy -= ty << (32 - z);
}
if (out != NULL) {
out[len].x = wwx;
out[len].y = wwy;
}
}
len++;
}
return len;
}
int draw(struct draw *geom, int n, mapnik::vector::tile_feature *feature) {
int px = 0, py = 0;
int cmd_idx = -1;
int cmd = -1;
int length = 0;
int drew = 0;
int i;
for (i = 0; i < n; i++) {
int op = geom[i].op;
if (op != cmd) {
if (cmd_idx >= 0) {
if (feature != NULL) {
feature->set_geometry(cmd_idx, (length << CMD_BITS) | (cmd & ((1 << CMD_BITS) - 1)));
}
}
cmd = op;
length = 0;
if (feature != NULL) {
cmd_idx = feature->geometry_size();
feature->add_geometry(0);
}
}
if (op == VT_MOVETO || op == VT_LINETO) {
long long wwx = geom[i].x;
long long wwy = geom[i].y;
int dx = wwx - px;
int dy = wwy - py;
if (feature != NULL) {
feature->add_geometry((dx << 1) ^ (dx >> 31));
feature->add_geometry((dy << 1) ^ (dy >> 31));
}
px = wwx;
py = wwy;
length++;
if (op == VT_LINETO && (dx != 0 || dy != 0)) {
drew = 1;
}
} else if (op == VT_CLOSEPATH) {
length++;
}
}
if (cmd_idx >= 0) {
if (feature != NULL) {
feature->set_geometry(cmd_idx, (length << CMD_BITS) | (cmd & ((1 << CMD_BITS) - 1)));
}
}
return drew;
}
int remove_noop(struct draw *geom, int n) {
// first pass: remove empty linetos
long long x = 0, y = 0;
int out = 0;
int i;
for (i = 0; i < n; i++) {
if (geom[i].op == VT_LINETO && geom[i].x == x && geom[i].y == y) {
continue;
}
if (geom[i].op == VT_CLOSEPATH) {
geom[out++] = geom[i];
} else { /* moveto or lineto */
geom[out++] = geom[i];
x = geom[i].x;
y = geom[i].y;
}
}
// second pass: remove unused movetos
n = out;
out = 0;
for (i = 0; i < n; i++) {
if (geom[i].op == VT_MOVETO) {
if (i + 1 >= n) {
continue;
}
if (geom[i + 1].op == VT_MOVETO) {
continue;
}
if (geom[i + 1].op == VT_CLOSEPATH) {
i++; // also remove unused closepath
continue;
}
}
geom[out++] = geom[i];
}
return out;
}
void to_tile_scale(struct draw *geom, int n, int z, int detail) {
int i;
for (i = 0; i < n; i++) {
geom[i].x >>= (32 - detail - z);
geom[i].y >>= (32 - detail - z);
}
}
long long write_tile(struct index *start, struct index *end, char *metabase, unsigned *file_bbox, int z, unsigned tx, unsigned ty, int detail, int basezoom, struct pool *file_keys) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
mapnik::vector::tile tile;
mapnik::vector::tile_layer *layer = tile.add_layers();
layer->set_name("name");
layer->set_version(1);
layer->set_extent(1 << detail);
struct pool keys;
keys.n = 0;
keys.vals = NULL;
keys.head = NULL;
keys.tail = NULL;
struct pool values;
values.n = 0;
values.vals = NULL;
values.head = NULL;
values.tail = NULL;
struct pool dup;
dup.n = 1;
dup.vals = NULL;
dup.head = NULL;
dup.tail = NULL;
double interval = 1;
double seq = 0;
long long count = 0;
if (z < basezoom) {
interval = exp(log(2.5) * (basezoom - z));
}
struct index *i;
for (i = start; i < end; i++) {
int t;
char *meta = metabase + i->fpos;
deserialize_int(&meta, &t);
if (t == VT_POINT) {
seq++;
if (seq >= 0) {
seq -= interval;
} else {
continue;
}
}
int len = decode_feature(&meta, NULL, z, tx, ty, detail);
struct draw geom[len];
meta = metabase + i->fpos;
deserialize_int(&meta, &t);
decode_feature(&meta, geom, z, tx, ty, detail);
to_tile_scale(geom, len, z, detail);
if (t == VT_LINE || t == VT_POLYGON) {
len = remove_noop(geom, len);
}
if (t == VT_POINT || draw(geom, len, NULL)) {
struct pool_val *pv = pool_long_long(&dup, &i->fpos, 0);
if (pv->n == 0) {
continue;
}
pv->n = 0;
mapnik::vector::tile_feature *feature = layer->add_features();
if (t == VT_POINT) {
feature->set_type(mapnik::vector::tile::Point);
} else if (t == VT_LINE) {
feature->set_type(mapnik::vector::tile::LineString);
} else if (t == VT_POLYGON) {
feature->set_type(mapnik::vector::tile::Polygon);
} else {
feature->set_type(mapnik::vector::tile::Unknown);
}
draw(geom, len, feature);
count += len;
int m;
deserialize_int(&meta, &m);
int i;
for (i = 0; i < m; i++) {
int t;
deserialize_int(&meta, &t);
struct pool_val *key = deserialize_string(&meta, &keys, VT_STRING);
struct pool_val *value = deserialize_string(&meta, &values, t);
feature->add_tags(key->n);
feature->add_tags(value->n);
// Dup to retain after munmap
pool(file_keys, strdup(key->s), t);
}
}
}
struct pool_val *pv;
for (pv = keys.head; pv != NULL; pv = pv->next) {
layer->add_keys(pv->s, strlen(pv->s));
}
for (pv = values.head; pv != NULL; pv = pv->next) {
mapnik::vector::tile_value *tv = layer->add_values();
if (pv->type == VT_NUMBER) {
tv->set_double_value(atof(pv->s));
} else {
tv->set_string_value(pv->s);
}
}
pool_free(&keys);
pool_free(&values);
pool_free(&dup);
std::string s;
std::string compressed;
tile.SerializeToString(&s);
compress(s, compressed);
if (compressed.size() > 500000) {
fprintf(stderr, "tile %d/%u/%u size is %lld, >500000\n", z, tx, ty, (long long) compressed.size());
exit(EXIT_FAILURE);
}
const char *prefix = "tiles";
char path[strlen(prefix) + 200];
mkdir(prefix, 0777);
sprintf(path, "%s/%d", prefix, z);
mkdir(path, 0777);
sprintf(path, "%s/%d/%u", prefix, z, tx);
mkdir(path, 0777);
sprintf(path, "%s/%d/%u/%u.pbf", prefix, z, tx, ty);
FILE *f = fopen(path, "wb");
fwrite(compressed.data(), 1, compressed.size(), f);
fclose(f);
return count;
}
<|endoftext|> |
<commit_before>// 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 "kudu/client/client.h"
#include "kudu/integration-tests/cluster_verifier.h"
#include "kudu/integration-tests/external_mini_cluster.h"
#include "kudu/integration-tests/test_workload.h"
#include "kudu/util/random.h"
#include "kudu/util/random_util.h"
#include "kudu/util/test_util.h"
#include <string>
using std::string;
namespace kudu {
using client::KuduClient;
using client::KuduClientBuilder;
using client::KuduInsert;
using client::KuduSession;
using client::KuduTable;
using client::KuduUpdate;
using client::sp::shared_ptr;
namespace {
// Generate a row key such that an increasing sequence (0...N) ends up spreading writes
// across the key space as several sequential streams rather than a single sequential
// sequence.
int IntToKey(int i) {
return 100000000 * (i % 3) + i;
}
} // anonymous namespace
class TsRecoveryITest : public KuduTest {
public:
virtual void TearDown() OVERRIDE {
if (cluster_) cluster_->Shutdown();
KuduTest::TearDown();
}
protected:
void StartCluster(const vector<string>& extra_tserver_flags = vector<string>(),
int num_tablet_servers = 1);
gscoped_ptr<ExternalMiniCluster> cluster_;
};
void TsRecoveryITest::StartCluster(const vector<string>& extra_tserver_flags,
int num_tablet_servers) {
ExternalMiniClusterOptions opts;
opts.num_tablet_servers = num_tablet_servers;
opts.extra_tserver_flags = extra_tserver_flags;
cluster_.reset(new ExternalMiniCluster(opts));
ASSERT_OK(cluster_->Start());
}
// Test crashing a server just before appending a COMMIT message.
// We then restart the server and ensure that all rows successfully
// inserted before the crash are recovered.
TEST_F(TsRecoveryITest, TestRestartWithOrphanedReplicates) {
NO_FATALS(StartCluster());
cluster_->SetFlag(cluster_->tablet_server(0),
"fault_crash_before_append_commit", "0.05");
TestWorkload work(cluster_.get());
work.set_num_replicas(1);
work.set_num_write_threads(4);
work.set_write_timeout_millis(100);
work.set_timeout_allowed(true);
work.Setup();
work.Start();
// Wait for the process to crash due to the injected fault.
while (cluster_->tablet_server(0)->IsProcessAlive()) {
SleepFor(MonoDelta::FromMilliseconds(10));
}
// Stop the writers.
work.StopAndJoin();
// Restart the server, and it should recover.
cluster_->tablet_server(0)->Shutdown();
ASSERT_OK(cluster_->tablet_server(0)->Restart());
// TODO(KUDU-796): after a restart, we may have to replay some
// orphaned replicates from the log. However, we currently
// allow reading while those are being replayed, which means we
// can "go back in time" briefly. So, we have some retries here.
// When KUDU-796 is fixed, remove the retries.
ClusterVerifier v(cluster_.get());
NO_FATALS(v.CheckRowCountWithRetries(work.table_name(),
ClusterVerifier::AT_LEAST,
work.rows_inserted(),
MonoDelta::FromSeconds(20)));
}
// Test that we replay from the recovery directory, if it exists.
TEST_F(TsRecoveryITest, TestCrashDuringLogReplay) {
NO_FATALS(StartCluster({ "--fault_crash_during_log_replay=0.05" }));
TestWorkload work(cluster_.get());
work.set_num_replicas(1);
work.set_num_write_threads(4);
work.set_write_batch_size(1);
work.set_write_timeout_millis(100);
work.set_timeout_allowed(true);
work.Setup();
work.Start();
while (work.rows_inserted() < 200) {
SleepFor(MonoDelta::FromMilliseconds(10));
}
work.StopAndJoin();
// Now restart the server, which will result in log replay, which will crash
// mid-replay with very high probability since we wrote at least 200 log
// entries and we're injecting a fault 5% of the time.
cluster_->tablet_server(0)->Shutdown();
// Restart might crash very quickly and actually return a bad status, so we
// ignore the result.
ignore_result(cluster_->tablet_server(0)->Restart());
// Wait for the process to crash during log replay.
for (int i = 0; i < 3000 && cluster_->tablet_server(0)->IsProcessAlive(); i++) {
SleepFor(MonoDelta::FromMilliseconds(10));
}
ASSERT_FALSE(cluster_->tablet_server(0)->IsProcessAlive()) << "TS didn't crash!";
// Now remove the crash flag, so the next replay will complete, and restart
// the server once more.
cluster_->tablet_server(0)->Shutdown();
cluster_->tablet_server(0)->mutable_flags()->clear();
ASSERT_OK(cluster_->tablet_server(0)->Restart());
ClusterVerifier v(cluster_.get());
NO_FATALS(v.CheckRowCountWithRetries(work.table_name(),
ClusterVerifier::AT_LEAST,
work.rows_inserted(),
MonoDelta::FromSeconds(30)));
}
// A set of threads which pick rows which are known to exist in the table
// and issue random updates against them.
class UpdaterThreads {
public:
static const int kNumThreads = 4;
// 'inserted' is an atomic integer which stores the number of rows
// which have been inserted up to that point.
UpdaterThreads(AtomicInt<int32_t>* inserted,
const shared_ptr<KuduClient>& client,
const shared_ptr<KuduTable>& table)
: should_run_(false),
inserted_(inserted),
client_(client),
table_(table) {
}
// Start running the updater threads.
void Start() {
CHECK(!should_run_.Load());
should_run_.Store(true);
threads_.resize(kNumThreads);
for (int i = 0; i < threads_.size(); i++) {
CHECK_OK(kudu::Thread::Create("test", "updater",
&UpdaterThreads::Run, this,
&threads_[i]));
}
}
// Stop running the updater threads, and wait for them to exit.
void StopAndJoin() {
CHECK(should_run_.Load());
should_run_.Store(false);
for (const auto& t : threads_) {
t->Join();
}
threads_.clear();
}
protected:
void Run() {
Random rng(GetRandomSeed32());
shared_ptr<KuduSession> session = client_->NewSession();
session->SetTimeoutMillis(2000);
CHECK_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH));
while (should_run_.Load()) {
int i = inserted_->Load();
if (i == 0) continue;
gscoped_ptr<KuduUpdate> up(table_->NewUpdate());
CHECK_OK(up->mutable_row()->SetInt32("key", IntToKey(rng.Uniform(i) + 1)));
CHECK_OK(up->mutable_row()->SetInt32("int_val", rng.Next32()));
CHECK_OK(session->Apply(up.release()));
// The server might crash due to a compaction while we're still updating.
// That's OK - we expect the main thread to shut us down quickly.
WARN_NOT_OK(session->Flush(), "failed to flush updates");
}
}
AtomicBool should_run_;
AtomicInt<int32_t>* inserted_;
shared_ptr<KuduClient> client_;
shared_ptr<KuduTable> table_;
vector<scoped_refptr<Thread> > threads_;
};
// Parameterized test which acts as a regression test for KUDU-969.
//
// This test is parameterized on the name of a fault point configuration.
// The fault points exercised crashes right before flushing the tablet metadata
// during a flush/compaction. Meanwhile, a set of threads hammer rows with
// a lot of updates. The goal here is to trigger the following race:
//
// - a compaction is in "duplicating" phase (i.e. updates are written to both
// the input and output rowsets
// - we crash (due to the fault point) before writing the new metadata
//
// This exercises the bootstrap code path which replays duplicated updates
// in the case where the flush did not complete. Prior to fixing KUDU-969,
// these updates would be mistakenly considered as "already flushed", despite
// the fact that they were only written to the input rowset's memory stores, and
// never hit disk.
class Kudu969Test : public TsRecoveryITest,
public ::testing::WithParamInterface<const char*> {
};
INSTANTIATE_TEST_CASE_P(DifferentFaultPoints,
Kudu969Test,
::testing::Values("fault_crash_before_flush_tablet_meta_after_compaction",
"fault_crash_before_flush_tablet_meta_after_flush_mrs"));
TEST_P(Kudu969Test, Test) {
if (!AllowSlowTests()) return;
// We use a replicated cluster here so that the 'REPLICATE' messages
// and 'COMMIT' messages are spread out further in time, and it's
// more likely to trigger races. We can also verify that the server
// with the injected fault recovers to the same state as the other
// servers.
ExternalMiniClusterOptions opts;
opts.num_tablet_servers = 3;
// Jack up the number of maintenance manager threads to try to trigger
// concurrency bugs where a compaction and a flush might be happening
// at the same time during the crash.
opts.extra_tserver_flags.push_back("--maintenance_manager_num_threads=3");
cluster_.reset(new ExternalMiniCluster(opts));
ASSERT_OK(cluster_->Start());
// Set a small flush threshold so that we flush a lot (causing more compactions
// as well).
cluster_->SetFlag(cluster_->tablet_server(0), "flush_threshold_mb", "1");
// Use TestWorkload to create a table
TestWorkload work(cluster_.get());
work.set_num_replicas(3);
work.Setup();
// Open the client and table.
KuduClientBuilder builder;
shared_ptr<KuduClient> client;
ASSERT_OK(cluster_->CreateClient(builder, &client));
shared_ptr<KuduTable> table;
CHECK_OK(client->OpenTable(work.table_name(), &table));
// Keep track of how many rows have been inserted.
AtomicInt<int32_t> inserted(0);
// Start updater threads.
UpdaterThreads updater(&inserted, client, table);
updater.Start();
// Enable the fault point to crash after a few flushes or compactions.
auto ts = cluster_->tablet_server(0);
cluster_->SetFlag(ts, GetParam(), "0.3");
// Insert some data.
shared_ptr<KuduSession> session = client->NewSession();
session->SetTimeoutMillis(1000);
CHECK_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH));
for (int i = 1; ts->IsProcessAlive(); i++) {
gscoped_ptr<KuduInsert> ins(table->NewInsert());
ASSERT_OK(ins->mutable_row()->SetInt32("key", IntToKey(i)));
ASSERT_OK(ins->mutable_row()->SetInt32("int_val", i));
ASSERT_OK(ins->mutable_row()->SetNull("string_val"));
ASSERT_OK(session->Apply(ins.release()));
if (i % 100 == 0) {
WARN_NOT_OK(session->Flush(), "could not flush session");
inserted.Store(i);
}
}
LOG(INFO) << "successfully detected TS crash!";
updater.StopAndJoin();
// Restart the TS to trigger bootstrap, and wait for it to start up.
ts->Shutdown();
ASSERT_OK(ts->Restart());
ASSERT_OK(cluster_->WaitForTabletsRunning(ts, MonoDelta::FromSeconds(90)));
// Verify that the bootstrapped server matches the other replications, which
// had no faults.
ClusterVerifier v(cluster_.get());
v.SetVerificationTimeout(MonoDelta::FromSeconds(30));
NO_FATALS(v.CheckCluster());
}
} // namespace kudu
<commit_msg>ts_recovery-itest: enable never_fsync in tablet server<commit_after>// 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 "kudu/client/client.h"
#include "kudu/integration-tests/cluster_verifier.h"
#include "kudu/integration-tests/external_mini_cluster.h"
#include "kudu/integration-tests/test_workload.h"
#include "kudu/util/random.h"
#include "kudu/util/random_util.h"
#include "kudu/util/test_util.h"
#include <string>
using std::string;
namespace kudu {
using client::KuduClient;
using client::KuduClientBuilder;
using client::KuduInsert;
using client::KuduSession;
using client::KuduTable;
using client::KuduUpdate;
using client::sp::shared_ptr;
namespace {
// Generate a row key such that an increasing sequence (0...N) ends up spreading writes
// across the key space as several sequential streams rather than a single sequential
// sequence.
int IntToKey(int i) {
return 100000000 * (i % 3) + i;
}
} // anonymous namespace
class TsRecoveryITest : public KuduTest {
public:
virtual void TearDown() OVERRIDE {
if (cluster_) cluster_->Shutdown();
KuduTest::TearDown();
}
protected:
void StartCluster(const vector<string>& extra_tserver_flags = vector<string>(),
int num_tablet_servers = 1);
gscoped_ptr<ExternalMiniCluster> cluster_;
};
void TsRecoveryITest::StartCluster(const vector<string>& extra_tserver_flags,
int num_tablet_servers) {
ExternalMiniClusterOptions opts;
opts.num_tablet_servers = num_tablet_servers;
opts.extra_tserver_flags = extra_tserver_flags;
cluster_.reset(new ExternalMiniCluster(opts));
ASSERT_OK(cluster_->Start());
}
// Test crashing a server just before appending a COMMIT message.
// We then restart the server and ensure that all rows successfully
// inserted before the crash are recovered.
TEST_F(TsRecoveryITest, TestRestartWithOrphanedReplicates) {
NO_FATALS(StartCluster());
cluster_->SetFlag(cluster_->tablet_server(0),
"fault_crash_before_append_commit", "0.05");
TestWorkload work(cluster_.get());
work.set_num_replicas(1);
work.set_num_write_threads(4);
work.set_write_timeout_millis(100);
work.set_timeout_allowed(true);
work.Setup();
work.Start();
// Wait for the process to crash due to the injected fault.
while (cluster_->tablet_server(0)->IsProcessAlive()) {
SleepFor(MonoDelta::FromMilliseconds(10));
}
// Stop the writers.
work.StopAndJoin();
// Restart the server, and it should recover.
cluster_->tablet_server(0)->Shutdown();
ASSERT_OK(cluster_->tablet_server(0)->Restart());
// TODO(KUDU-796): after a restart, we may have to replay some
// orphaned replicates from the log. However, we currently
// allow reading while those are being replayed, which means we
// can "go back in time" briefly. So, we have some retries here.
// When KUDU-796 is fixed, remove the retries.
ClusterVerifier v(cluster_.get());
NO_FATALS(v.CheckRowCountWithRetries(work.table_name(),
ClusterVerifier::AT_LEAST,
work.rows_inserted(),
MonoDelta::FromSeconds(20)));
}
// Test that we replay from the recovery directory, if it exists.
TEST_F(TsRecoveryITest, TestCrashDuringLogReplay) {
NO_FATALS(StartCluster({ "--fault_crash_during_log_replay=0.05" }));
TestWorkload work(cluster_.get());
work.set_num_replicas(1);
work.set_num_write_threads(4);
work.set_write_batch_size(1);
work.set_write_timeout_millis(100);
work.set_timeout_allowed(true);
work.Setup();
work.Start();
while (work.rows_inserted() < 200) {
SleepFor(MonoDelta::FromMilliseconds(10));
}
work.StopAndJoin();
// Now restart the server, which will result in log replay, which will crash
// mid-replay with very high probability since we wrote at least 200 log
// entries and we're injecting a fault 5% of the time.
cluster_->tablet_server(0)->Shutdown();
// Restart might crash very quickly and actually return a bad status, so we
// ignore the result.
ignore_result(cluster_->tablet_server(0)->Restart());
// Wait for the process to crash during log replay.
for (int i = 0; i < 3000 && cluster_->tablet_server(0)->IsProcessAlive(); i++) {
SleepFor(MonoDelta::FromMilliseconds(10));
}
ASSERT_FALSE(cluster_->tablet_server(0)->IsProcessAlive()) << "TS didn't crash!";
// Now remove the crash flag, so the next replay will complete, and restart
// the server once more.
cluster_->tablet_server(0)->Shutdown();
cluster_->tablet_server(0)->mutable_flags()->clear();
ASSERT_OK(cluster_->tablet_server(0)->Restart());
ClusterVerifier v(cluster_.get());
NO_FATALS(v.CheckRowCountWithRetries(work.table_name(),
ClusterVerifier::AT_LEAST,
work.rows_inserted(),
MonoDelta::FromSeconds(30)));
}
// A set of threads which pick rows which are known to exist in the table
// and issue random updates against them.
class UpdaterThreads {
public:
static const int kNumThreads = 4;
// 'inserted' is an atomic integer which stores the number of rows
// which have been inserted up to that point.
UpdaterThreads(AtomicInt<int32_t>* inserted,
const shared_ptr<KuduClient>& client,
const shared_ptr<KuduTable>& table)
: should_run_(false),
inserted_(inserted),
client_(client),
table_(table) {
}
// Start running the updater threads.
void Start() {
CHECK(!should_run_.Load());
should_run_.Store(true);
threads_.resize(kNumThreads);
for (int i = 0; i < threads_.size(); i++) {
CHECK_OK(kudu::Thread::Create("test", "updater",
&UpdaterThreads::Run, this,
&threads_[i]));
}
}
// Stop running the updater threads, and wait for them to exit.
void StopAndJoin() {
CHECK(should_run_.Load());
should_run_.Store(false);
for (const auto& t : threads_) {
t->Join();
}
threads_.clear();
}
protected:
void Run() {
Random rng(GetRandomSeed32());
shared_ptr<KuduSession> session = client_->NewSession();
session->SetTimeoutMillis(2000);
CHECK_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH));
while (should_run_.Load()) {
int i = inserted_->Load();
if (i == 0) continue;
gscoped_ptr<KuduUpdate> up(table_->NewUpdate());
CHECK_OK(up->mutable_row()->SetInt32("key", IntToKey(rng.Uniform(i) + 1)));
CHECK_OK(up->mutable_row()->SetInt32("int_val", rng.Next32()));
CHECK_OK(session->Apply(up.release()));
// The server might crash due to a compaction while we're still updating.
// That's OK - we expect the main thread to shut us down quickly.
WARN_NOT_OK(session->Flush(), "failed to flush updates");
}
}
AtomicBool should_run_;
AtomicInt<int32_t>* inserted_;
shared_ptr<KuduClient> client_;
shared_ptr<KuduTable> table_;
vector<scoped_refptr<Thread> > threads_;
};
// Parameterized test which acts as a regression test for KUDU-969.
//
// This test is parameterized on the name of a fault point configuration.
// The fault points exercised crashes right before flushing the tablet metadata
// during a flush/compaction. Meanwhile, a set of threads hammer rows with
// a lot of updates. The goal here is to trigger the following race:
//
// - a compaction is in "duplicating" phase (i.e. updates are written to both
// the input and output rowsets
// - we crash (due to the fault point) before writing the new metadata
//
// This exercises the bootstrap code path which replays duplicated updates
// in the case where the flush did not complete. Prior to fixing KUDU-969,
// these updates would be mistakenly considered as "already flushed", despite
// the fact that they were only written to the input rowset's memory stores, and
// never hit disk.
class Kudu969Test : public TsRecoveryITest,
public ::testing::WithParamInterface<const char*> {
};
INSTANTIATE_TEST_CASE_P(DifferentFaultPoints,
Kudu969Test,
::testing::Values("fault_crash_before_flush_tablet_meta_after_compaction",
"fault_crash_before_flush_tablet_meta_after_flush_mrs"));
TEST_P(Kudu969Test, Test) {
if (!AllowSlowTests()) return;
// We use a replicated cluster here so that the 'REPLICATE' messages
// and 'COMMIT' messages are spread out further in time, and it's
// more likely to trigger races. We can also verify that the server
// with the injected fault recovers to the same state as the other
// servers.
ExternalMiniClusterOptions opts;
opts.num_tablet_servers = 3;
// Jack up the number of maintenance manager threads to try to trigger
// concurrency bugs where a compaction and a flush might be happening
// at the same time during the crash.
opts.extra_tserver_flags.push_back("--maintenance_manager_num_threads=3");
// Speed up test by not fsyncing.
opts.extra_tserver_flags.push_back("--never_fsync");
cluster_.reset(new ExternalMiniCluster(opts));
ASSERT_OK(cluster_->Start());
// Set a small flush threshold so that we flush a lot (causing more compactions
// as well).
cluster_->SetFlag(cluster_->tablet_server(0), "flush_threshold_mb", "1");
// Use TestWorkload to create a table
TestWorkload work(cluster_.get());
work.set_num_replicas(3);
work.Setup();
// Open the client and table.
KuduClientBuilder builder;
shared_ptr<KuduClient> client;
ASSERT_OK(cluster_->CreateClient(builder, &client));
shared_ptr<KuduTable> table;
CHECK_OK(client->OpenTable(work.table_name(), &table));
// Keep track of how many rows have been inserted.
AtomicInt<int32_t> inserted(0);
// Start updater threads.
UpdaterThreads updater(&inserted, client, table);
updater.Start();
// Enable the fault point to crash after a few flushes or compactions.
auto ts = cluster_->tablet_server(0);
cluster_->SetFlag(ts, GetParam(), "0.3");
// Insert some data.
shared_ptr<KuduSession> session = client->NewSession();
session->SetTimeoutMillis(1000);
CHECK_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH));
for (int i = 1; ts->IsProcessAlive(); i++) {
gscoped_ptr<KuduInsert> ins(table->NewInsert());
ASSERT_OK(ins->mutable_row()->SetInt32("key", IntToKey(i)));
ASSERT_OK(ins->mutable_row()->SetInt32("int_val", i));
ASSERT_OK(ins->mutable_row()->SetNull("string_val"));
ASSERT_OK(session->Apply(ins.release()));
if (i % 100 == 0) {
WARN_NOT_OK(session->Flush(), "could not flush session");
inserted.Store(i);
}
}
LOG(INFO) << "successfully detected TS crash!";
updater.StopAndJoin();
// Restart the TS to trigger bootstrap, and wait for it to start up.
ts->Shutdown();
ASSERT_OK(ts->Restart());
ASSERT_OK(cluster_->WaitForTabletsRunning(ts, MonoDelta::FromSeconds(90)));
// Verify that the bootstrapped server matches the other replications, which
// had no faults.
ClusterVerifier v(cluster_.get());
v.SetVerificationTimeout(MonoDelta::FromSeconds(30));
NO_FATALS(v.CheckCluster());
}
} // namespace kudu
<|endoftext|> |
<commit_before>// Copyright CERN. This software is distributed under the terms of the GNU
// General Public License v3 (GPL Version 3).
//
// See http://www.gnu.org/licenses/ for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
//**************************************************************************************
// \class AliHFMLResponseDplustoKpipi
// \brief helper class to handle application of ML models for D+ analyses trained
// with python libraries
// \authors:
// F. Catalano, fabio.catalano@cern.ch
// F. Grosa, fabrizio.grosa@cern.ch
/////////////////////////////////////////////////////////////////////////////////////////
#include <TDatabasePDG.h>
#include "AliHFMLResponseDplustoKpipi.h"
#include "AliAODRecoDecayHF3Prong.h"
/// \cond CLASSIMP
ClassImp(AliHFMLResponseDplustoKpipi);
/// \endcond
//________________________________________________________________
AliHFMLResponseDplustoKpipi::AliHFMLResponseDplustoKpipi() : AliHFMLResponse()
{
//
// Default constructor
//
}
//________________________________________________________________
AliHFMLResponseDplustoKpipi::AliHFMLResponseDplustoKpipi(string configfilename) : AliHFMLResponse(configfilename)
{
//
// Standard constructor
//
if (configfilename != "")
SetConfigFile(configfilename);
}
//________________________________________________________________
AliHFMLResponseDplustoKpipi::~AliHFMLResponseDplustoKpipi()
{
//
// Destructor
//
}
//--------------------------------------------------------------------------
AliHFMLResponseDplustoKpipi::AliHFMLResponseDplustoKpipi(const AliHFMLResponseDplustoKpipi &source) : AliHFMLResponse(source)
{
//
// Copy constructor
//
}
AliHFMLResponseDplustoKpipi &AliHFMLResponseDplustoKpipi::operator=(const AliHFMLResponseDplustoKpipi &source)
{
//
// assignment operator
//
if (&source == this)
return *this;
AliHFMLResponse::operator=(source);
return *this;
}
//________________________________________________________________
void AliHFMLResponseDplustoKpipi::SetMapOfVariables(AliAODRecoDecayHF *cand, double bfield, AliAODPidHF *pidHF, int /*masshypo*/)
{
fVars["pt_cand"] = cand->Pt();
fVars["d_len"] = cand->DecayLength();
fVars["d_len_xy"] = cand->DecayLengthXY();
fVars["norm_dl"] = cand->NormalizedDecayLength();
fVars["norm_dl_xy"] = cand->NormalizedDecayLengthXY();
fVars["cos_p"] = cand->CosPointingAngle();
fVars["cos_p_xy"] = cand->CosPointingAngleXY();
fVars["imp_par_xy"] = cand->ImpParXY();
fVars["sig_vert"] = dynamic_cast<AliAODRecoDecayHF3Prong *>(cand)->GetSigmaVert();
fVars["max_norm_d0d0exp"] = ComputeMaxd0MeasMinusExp(cand, bfield);
for (int iProng = 0; iProng < 3; iProng++)
{
AliAODTrack *dautrack = dynamic_cast<AliAODTrack *>(cand->GetDaughter(iProng));
pidHF->GetnSigmaTPC(dautrack, 2, fVars[Form("nsigTPC_Pi_%d", iProng)]);
pidHF->GetnSigmaTPC(dautrack, 3, fVars[Form("nsigTPC_K_%d", iProng)]);
pidHF->GetnSigmaTOF(dautrack, 2, fVars[Form("nsigTOF_Pi_%d", iProng)]);
pidHF->GetnSigmaTOF(dautrack, 3, fVars[Form("nsigTOF_K_%d", iProng)]);
fVars[Form("nsigComb_Pi_%d", iProng)] = CombineNsigmaTPCTOF(fVars[Form("nsigTPC_Pi_%d", iProng)], fVars[Form("nsigTOF_Pi_%d", iProng)]);
fVars[Form("nsigComb_K_%d", iProng)] = CombineNsigmaTPCTOF(fVars[Form("nsigTPC_K_%d", iProng)], fVars[Form("nsigTOF_K_%d", iProng)]);
}
}
<commit_msg>Fix map initialisation for PID variables - D+<commit_after>// Copyright CERN. This software is distributed under the terms of the GNU
// General Public License v3 (GPL Version 3).
//
// See http://www.gnu.org/licenses/ for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
//**************************************************************************************
// \class AliHFMLResponseDplustoKpipi
// \brief helper class to handle application of ML models for D+ analyses trained
// with python libraries
// \authors:
// F. Catalano, fabio.catalano@cern.ch
// F. Grosa, fabrizio.grosa@cern.ch
/////////////////////////////////////////////////////////////////////////////////////////
#include <TDatabasePDG.h>
#include "AliHFMLResponseDplustoKpipi.h"
#include "AliAODRecoDecayHF3Prong.h"
/// \cond CLASSIMP
ClassImp(AliHFMLResponseDplustoKpipi);
/// \endcond
//________________________________________________________________
AliHFMLResponseDplustoKpipi::AliHFMLResponseDplustoKpipi() : AliHFMLResponse()
{
//
// Default constructor
//
}
//________________________________________________________________
AliHFMLResponseDplustoKpipi::AliHFMLResponseDplustoKpipi(string configfilename) : AliHFMLResponse(configfilename)
{
//
// Standard constructor
//
if (configfilename != "")
SetConfigFile(configfilename);
}
//________________________________________________________________
AliHFMLResponseDplustoKpipi::~AliHFMLResponseDplustoKpipi()
{
//
// Destructor
//
}
//--------------------------------------------------------------------------
AliHFMLResponseDplustoKpipi::AliHFMLResponseDplustoKpipi(const AliHFMLResponseDplustoKpipi &source) : AliHFMLResponse(source)
{
//
// Copy constructor
//
}
AliHFMLResponseDplustoKpipi &AliHFMLResponseDplustoKpipi::operator=(const AliHFMLResponseDplustoKpipi &source)
{
//
// assignment operator
//
if (&source == this)
return *this;
AliHFMLResponse::operator=(source);
return *this;
}
//________________________________________________________________
void AliHFMLResponseDplustoKpipi::SetMapOfVariables(AliAODRecoDecayHF *cand, double bfield, AliAODPidHF *pidHF, int /*masshypo*/)
{
fVars["pt_cand"] = cand->Pt();
fVars["d_len"] = cand->DecayLength();
fVars["d_len_xy"] = cand->DecayLengthXY();
fVars["norm_dl"] = cand->NormalizedDecayLength();
fVars["norm_dl_xy"] = cand->NormalizedDecayLengthXY();
fVars["cos_p"] = cand->CosPointingAngle();
fVars["cos_p_xy"] = cand->CosPointingAngleXY();
fVars["imp_par_xy"] = cand->ImpParXY();
fVars["sig_vert"] = dynamic_cast<AliAODRecoDecayHF3Prong *>(cand)->GetSigmaVert();
fVars["max_norm_d0d0exp"] = ComputeMaxd0MeasMinusExp(cand, bfield);
for (int iProng = 0; iProng < 3; iProng++)
{
AliAODTrack *dautrack = dynamic_cast<AliAODTrack *>(cand->GetDaughter(iProng));
double nsigma = -999.
pidHF->GetnSigmaTPC(dautrack, 2, nsigma);
fVars[Form("nsigTPC_Pi_%d", iProng)] = nsigma;
pidHF->GetnSigmaTPC(dautrack, 3, nsigma);
fVars[Form("nsigTPC_K_%d", iProng)] = nsigma;
pidHF->GetnSigmaTOF(dautrack, 2, nsigma);
fVars[Form("nsigTOF_Pi_%d", iProng)] = nsigma;
pidHF->GetnSigmaTOF(dautrack, 3, nsigma);
fVars[Form("nsigTOF_K_%d", iProng)] = nsigma;
fVars[Form("nsigComb_Pi_%d", iProng)] = CombineNsigmaTPCTOF(fVars[Form("nsigTPC_Pi_%d", iProng)], fVars[Form("nsigTOF_Pi_%d", iProng)]);
fVars[Form("nsigComb_K_%d", iProng)] = CombineNsigmaTPCTOF(fVars[Form("nsigTPC_K_%d", iProng)], fVars[Form("nsigTOF_K_%d", iProng)]);
}
}
<|endoftext|> |
<commit_before>#include "IP.h"
bool IP::atBearerSettings(unsigned char cmdType, unsigned char cid, const char paramTag[], const char paramValue[]) {
char buffer[22 + strlen(paramTag) + strlen(paramValue)]; // "AT+SAPBR=X,X,\"{paramTag}\",\"{paramValue}\"\r\r\n"
struct BearerProfile bearerProfile;
if(cmdType <= 5 && cmdType != 3) {
const __FlashStringHelper *command = F("AT+SAPBR=%d,%d\r");
sprintf_P(buffer, (const char *)command, cmdType, cid);
}
else if(cmdType == 3) {
const __FlashStringHelper *command = F("AT+SAPBR=%d,%d,\"%s\",\"%s\"\r");
sprintf_P(buffer, (const char *)command, cmdType, cid, paramTag, paramValue);
}
else
return false;
const __FlashStringHelper *response = F("+SAPBR: ");
bearerProfile = this->bearerProfile[cid-1];
dte->clearReceivedBuffer();
if(!dte->ATCommand(buffer)) return false;
if(cmdType == 2) {
if(!dte->ATResponseContain(response)) return false;
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
for (unsigned char i = 0; i < 3 && str != NULL; i++) {
if(i == 0) bearerProfile.cid = str[0] - '0';
if(i == 1) bearerProfile.connStatus.status = str[0] - '0';
if(i == 2) strcpy(bearerProfile.connStatus.ip, str);
str = strtok(NULL, ",\"");
}
if(!dte->ATResponseOk()) return false;
this->bearerProfile[cid-1] = bearerProfile;
}
else if(cmdType == 4) {
if(!dte->ATResponseContain(response)) return false;
for (unsigned char i = 0; i < 6; i++) {
if(!dte->ATResponse()) return false;
if(dte->isResponseContain("CONTYPE: ")) {
const __FlashStringHelper *response = F("CONTYPE: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.contype, str);
}
else if (dte->isResponseContain("APN: ")) {
const __FlashStringHelper *response = F("APN: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.apn, str);
}
else if (dte->isResponseContain("USER: ")) {
const __FlashStringHelper *response = F("USER: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.user, str);
}
else if (dte->isResponseContain("PWD: ")) {
const __FlashStringHelper *response = F("PWD: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.pwd, str);
}
else if (dte->isResponseContain("PHONENUM: ")) {
const __FlashStringHelper *response = F("PHONENUM: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.phonenum, str);
}
else if (dte->isResponseContain("RATE: ")) {
const __FlashStringHelper *response = F("RATE: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
bearerProfile.connParam.rate = str[0] - '0';
}
}
if(!dte->ATResponseOk()) return false;
this->bearerProfile[cid-1] = bearerProfile;
}
else if(!dte->ATResponseOk(10000)) return false;
return true;
}
/* IP Class */
IP::IP(DTE &dte, GPRS &gprs)
{
this->dte = &dte;
this->gprs = &gprs;
}
void IP::setConnectionParamGprs(const char apn[], const char user[], const char pwd[], unsigned char cid) {
struct ConnParam connParam = this->bearerProfile[cid-1].connParam;
bool change = false;
if (strcmp(connParam.apn, apn) != 0) {
atBearerSettings(3, cid, "APN", apn);
change = true;
}
if (strcmp(connParam.user, user) != 0) {
atBearerSettings(3, cid, "USER", user);
change = true;
}
if (strcmp(connParam.pwd, pwd) != 0) {
atBearerSettings(3, cid, "PWD", pwd);
change = true;
}
if (change) getConnectionParam(cid);
}
struct ConnStatus IP::getConnectionStatus(unsigned char cid) {
atBearerSettings(2, cid);
return bearerProfile[cid-1].connStatus;
}
struct ConnParam IP::getConnectionParam(unsigned char cid) {
atBearerSettings(4, cid);
return bearerProfile[cid-1].connParam;
}
bool IP::openConnection(unsigned char cid) {
struct ConnStatus connStatus= getConnectionStatus(cid);
if (connStatus.status == 3) {
if (!gprs->isAttached()) return false;
if (!atBearerSettings(1, cid)) return false;
connStatus = getConnectionStatus(cid);
}
if (connStatus.status >= 2) return false;
return true;
}
bool IP::closeConnection(unsigned char cid) {
struct ConnStatus connStatus= getConnectionStatus(cid);
if (connStatus.status == 1) {
if (!atBearerSettings(0, cid)) return false;
connStatus = getConnectionStatus(cid);
}
if (connStatus.status <= 1) return false;
return true;
}
<commit_msg>Add save value to NVRAM<commit_after>#include "IP.h"
bool IP::atBearerSettings(unsigned char cmdType, unsigned char cid, const char paramTag[], const char paramValue[]) {
char buffer[22 + strlen(paramTag) + strlen(paramValue)]; // "AT+SAPBR=X,X,\"{paramTag}\",\"{paramValue}\"\r\r\n"
struct BearerProfile bearerProfile;
if(cmdType <= 5 && cmdType != 3) {
const __FlashStringHelper *command = F("AT+SAPBR=%d,%d\r");
sprintf_P(buffer, (const char *)command, cmdType, cid);
}
else if(cmdType == 3) {
const __FlashStringHelper *command = F("AT+SAPBR=%d,%d,\"%s\",\"%s\"\r");
sprintf_P(buffer, (const char *)command, cmdType, cid, paramTag, paramValue);
}
else
return false;
const __FlashStringHelper *response = F("+SAPBR: ");
bearerProfile = this->bearerProfile[cid-1];
dte->clearReceivedBuffer();
if(!dte->ATCommand(buffer)) return false;
if(cmdType == 2) {
if(!dte->ATResponseContain(response)) return false;
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
for (unsigned char i = 0; i < 3 && str != NULL; i++) {
if(i == 0) bearerProfile.cid = str[0] - '0';
if(i == 1) bearerProfile.connStatus.status = str[0] - '0';
if(i == 2) strcpy(bearerProfile.connStatus.ip, str);
str = strtok(NULL, ",\"");
}
if(!dte->ATResponseOk()) return false;
this->bearerProfile[cid-1] = bearerProfile;
}
else if(cmdType == 4) {
if(!dte->ATResponseContain(response)) return false;
for (unsigned char i = 0; i < 6; i++) {
if(!dte->ATResponse()) return false;
if(dte->isResponseContain("CONTYPE: ")) {
const __FlashStringHelper *response = F("CONTYPE: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.contype, str);
}
else if (dte->isResponseContain("APN: ")) {
const __FlashStringHelper *response = F("APN: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.apn, str);
}
else if (dte->isResponseContain("USER: ")) {
const __FlashStringHelper *response = F("USER: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.user, str);
}
else if (dte->isResponseContain("PWD: ")) {
const __FlashStringHelper *response = F("PWD: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.pwd, str);
}
else if (dte->isResponseContain("PHONENUM: ")) {
const __FlashStringHelper *response = F("PHONENUM: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
strcpy(bearerProfile.connParam.phonenum, str);
}
else if (dte->isResponseContain("RATE: ")) {
const __FlashStringHelper *response = F("RATE: ");
char *pointer = strstr_P(dte->getResponse(), (const char *)response) + strlen_P((const char *)response);
char *str = strtok(pointer, ",\"");
bearerProfile.connParam.rate = str[0] - '0';
}
}
if(!dte->ATResponseOk()) return false;
this->bearerProfile[cid-1] = bearerProfile;
}
else if(!dte->ATResponseOk(10000)) return false;
return true;
}
/* IP Class */
IP::IP(DTE &dte, GPRS &gprs)
{
this->dte = &dte;
this->gprs = &gprs;
}
void IP::setConnectionParamGprs(const char apn[], const char user[], const char pwd[], unsigned char cid) {
struct ConnParam connParam = this->bearerProfile[cid-1].connParam;
bool change = false;
if (strcmp(connParam.contype, "GPRS") != 0) {
atBearerSettings(3, cid, "CONTYPE", "GPRS");
change = true;
}
if (strcmp(connParam.apn, apn) != 0) {
atBearerSettings(3, cid, "APN", apn);
change = true;
}
if (strcmp(connParam.user, user) != 0) {
atBearerSettings(3, cid, "USER", user);
change = true;
}
if (strcmp(connParam.pwd, pwd) != 0) {
atBearerSettings(3, cid, "PWD", pwd);
change = true;
}
if (change) {
atBearerSettings(5, 1);
getConnectionParam(cid);
}
}
struct ConnStatus IP::getConnectionStatus(unsigned char cid) {
atBearerSettings(2, cid);
return bearerProfile[cid-1].connStatus;
}
struct ConnParam IP::getConnectionParam(unsigned char cid) {
atBearerSettings(4, cid);
return bearerProfile[cid-1].connParam;
}
bool IP::openConnection(unsigned char cid) {
struct ConnStatus connStatus= getConnectionStatus(cid);
if (connStatus.status == 3) {
if (!gprs->isAttached()) return false;
if (!atBearerSettings(1, cid)) return false;
connStatus = getConnectionStatus(cid);
}
if (connStatus.status >= 2) return false;
return true;
}
bool IP::closeConnection(unsigned char cid) {
struct ConnStatus connStatus= getConnectionStatus(cid);
if (connStatus.status == 1) {
if (!atBearerSettings(0, cid)) return false;
connStatus = getConnectionStatus(cid);
}
if (connStatus.status <= 1) return false;
return true;
}
<|endoftext|> |
<commit_before><commit_msg>fixed ifdef typo<commit_after><|endoftext|> |
<commit_before><commit_msg>fixed assert<commit_after><|endoftext|> |
<commit_before><commit_msg>fixed bug that would grossly underestimate the TCP/IP overhead<commit_after><|endoftext|> |
<commit_before>/***************************************************************************************[System.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#include "../utils/System.h"
#if defined(__linux__)
#include <stdio.h>
#include <stdlib.h>
using namespace Minisat;
// TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and
// one for reading the current virtual memory size.
static inline int memReadStat(int field)
{
char name[256];
pid_t pid = getpid();
int value;
sprintf(name, "/proc/%d/statm", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
for (; field >= 0; field--)
if (fscanf(in, "%d", &value) != 1)
printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1);
fclose(in);
return value;
}
static inline int memReadPeak(void)
{
char name[256];
pid_t pid = getpid();
sprintf(name, "/proc/%d/status", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
// Find the correct line, beginning with "VmPeak:":
int peak_kb = 0;
while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1)
while (!feof(in) && fgetc(in) != '\n')
;
fclose(in);
return peak_kb;
}
double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }
double Minisat::memUsedPeak() {
double peak = memReadPeak() / 1024;
return peak == 0 ? memUsed() : peak; }
#elif defined(__FreeBSD__)
double Minisat::memUsed(void) {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return (double)ru.ru_maxrss / 1024; }
double MiniSat::memUsedPeak(void) { return memUsed(); }
#elif defined(__APPLE__)
#include <malloc/malloc.h>
double Minisat::memUsed(void) {
malloc_statistics_t t;
malloc_zone_statistics(NULL, &t);
return (double)t.max_size_in_use / (1024*1024); }
double Minisat::memUsedPeak(void) { return memUsed();}
#else
double Minisat::memUsed() {
return 0; }
#endif
<commit_msg>Patch from Khoo Yit Phang.<commit_after>/***************************************************************************************[System.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#include "../utils/System.h"
#if defined(__linux__)
#include <stdio.h>
#include <stdlib.h>
using namespace Minisat;
// TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and
// one for reading the current virtual memory size.
static inline int memReadStat(int field)
{
char name[256];
pid_t pid = getpid();
int value;
sprintf(name, "/proc/%d/statm", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
for (; field >= 0; field--)
if (fscanf(in, "%d", &value) != 1)
printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1);
fclose(in);
return value;
}
static inline int memReadPeak(void)
{
char name[256];
pid_t pid = getpid();
sprintf(name, "/proc/%d/status", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
// Find the correct line, beginning with "VmPeak:":
int peak_kb = 0;
while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1)
while (!feof(in) && fgetc(in) != '\n')
;
fclose(in);
return peak_kb;
}
double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }
double Minisat::memUsedPeak() {
double peak = memReadPeak() / 1024;
return peak == 0 ? memUsed() : peak; }
#elif defined(__FreeBSD__)
double Minisat::memUsed(void) {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return (double)ru.ru_maxrss / 1024; }
double Minisat::memUsedPeak(void) { return memUsed(); }
#elif defined(__APPLE__)
#include <malloc/malloc.h>
double Minisat::memUsed(void) {
malloc_statistics_t t;
malloc_zone_statistics(NULL, &t);
return (double)t.max_size_in_use / (1024*1024); }
double Minisat::memUsedPeak(void) { return memUsed();}
#else
double Minisat::memUsed() {
return 0; }
#endif
<|endoftext|> |
<commit_before><commit_msg>Properly serialize surjection proof in caching checker<commit_after><|endoftext|> |
<commit_before>/**
@file unix/filesystem.cpp
@author Tim Howard
@section LICENSE
Copyright (c) 2010-2011 Tim Howard
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <fcntl.h>
#include <duct/debug.hpp>
#include <duct/filesystem.hpp>
namespace duct {
// class DirStream implementation
DirStream::DirStream(const char* path) {
_path.append(path);
init();
}
DirStream::DirStream(const std::string& path) {
_path.append(path);
init();
}
DirStream::DirStream(const UnicodeString& path) {
path.toUTF8String(_path);
init();
}
DirStream::~DirStream() {
if (_inst) {
closedir(_inst);
_inst=NULL;
_entry=NULL;
}
}
bool DirStream::nextEntry() {
_entry=(void*)readdir(_inst);
return _entry!=NULL;
}
bool DirStream::nextEntry(UnicodeString& result) {
_entry=(void*)readdir(_inst);
if (_entry) {
result.setTo(UnicodeString(((struct dirent*)_entry)->d_name));
return true;
}
return false;
}
bool DirStream::entryName(UnicodeString& result) const {
if (_entry) {
result.setTo(UnicodeString(((struct dirent*)_entry)->d_name));
return true;
}
return false;
}
PathType DirStream::entryType() const {
if (_entry) {
std::string temp(_path);
temp.append(((struct dirent*)_entry)->d_name);
return FileSystem::pathType(temp);
} else {
return PATHTYPE_NONE;
}
}
bool DirStream::isOpen() const {
return _inst!=NULL;
}
bool DirStream::close() {
if (_inst) {
closedir(_inst);
_inst=NULL;
return true;
}
return false;
}
void DirStream::init() {
char c=_path[_path.length()-1];
if (c=='\\') {
_path.replace(_path.length()-1, 1, 1, '/');
} else if (c!='/') {
_path.append("/");
}
_inst=(void*)opendir(_path.c_str());
}
// FileSystem implementation
namespace FileSystem {
bool statPath(const char* path, struct stat* s) {
return stat(path, s)==0;
}
bool statPath(const std::string& path, struct stat* s) {
return stat(path.c_str(), s)==0;
}
bool statPath(const UnicodeString& path, struct stat* s) {
std::string str;
path.toUTF8String(str);
return stat(str.c_str(), s)==0;
}
PathType pathType(const char* path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
} else {
return PATHTYPE_NONE;
}
}
PathType pathType(const std::string& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
} else {
return PATHTYPE_NONE;
}
}
PathType pathType(const UnicodeString& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
} else {
return PATHTYPE_NONE;
}
}
bool dirExists(const char* path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISDIR(s.st_mode);
} else {
return false;
}
}
bool dirExists(const std::string& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISDIR(s.st_mode);
} else {
return false;
}
}
bool dirExists(const UnicodeString& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISDIR(s.st_mode);
} else {
return false;
}
}
bool fileExists(const char* path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode);
} else {
return false;
}
}
bool fileExists(const std::string& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode);
} else {
return false;
}
}
bool fileExists(const UnicodeString& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode);
} else {
return false;
}
}
// TODO structure creation
bool createDir(const char* path, bool structure) {
return mkdir(path, S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH)==0;
}
bool createDir(const std::string& path, bool structure) {
return createDir(path.c_str(), false);
}
bool createDir(const UnicodeString& path, bool structure) {
std::string str;
path.toUTF8String(str);
return createDir(str.c_str(), false);
}
bool createFile(const char* path, bool createpath) {
// TODO: dir/path extraction from file path
/*if (createpath && !dirExists()) {
createDir();
}*/
int fd=creat(path, 0);
if (fd!=-1) {
close(fd);
return true;
}
return false;
}
bool createFile(const std::string& path, bool createpath) {
return createFile(path.c_str(), createpath);
}
bool createFile(const UnicodeString& path, bool createpath) {
std::string str;
path.toUTF8String(str);
return createFile(str.c_str(), createpath);
}
bool deleteFile(const char* path) {
return remove(path)==0;
}
bool deleteFile(const std::string& path) {
return remove(path.c_str())==0;
}
bool deleteFile(const UnicodeString& path) {
std::string str;
path.toUTF8String(str);
return remove(str.c_str())==0;
}
bool deleteDir(const char* path) {
return rmdir(path)==0;
}
bool deleteDir(const std::string& path) {
return rmdir(path.c_str())==0;
}
bool deleteDir(const UnicodeString& path) {
std::string str;
path.toUTF8String(str);
return rmdir(str.c_str())==0;
}
} // namespace FileSystem
} // namespace duct
<commit_msg>Fixed FileSystem for Linux (mid-dev, borked it while testing Windows).<commit_after>/**
@file unix/filesystem.cpp
@author Tim Howard
@section LICENSE
Copyright (c) 2010-2011 Tim Howard
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <fcntl.h>
#include <duct/debug.hpp>
#include <duct/filesystem.hpp>
namespace duct {
// class DirStream implementation
DirStream::DirStream(const char* path) {
_path.append(path);
init();
}
DirStream::DirStream(const std::string& path) {
_path.append(path);
init();
}
DirStream::DirStream(const UnicodeString& path) {
path.toUTF8String(_path);
init();
}
DirStream::~DirStream() {
if (_dir) {
closedir(_dir);
_dir=NULL;
_entry=NULL;
}
}
bool DirStream::nextEntry() {
_entry=readdir(_dir);
return _entry!=NULL;
}
bool DirStream::nextEntry(UnicodeString& result) {
_entry=readdir(_dir);
if (_entry) {
result.setTo(UnicodeString(_entry->d_name));
return true;
}
return false;
}
bool DirStream::entryName(UnicodeString& result) const {
if (_entry) {
result.setTo(UnicodeString(_entry->d_name));
return true;
}
return false;
}
PathType DirStream::entryType() const {
if (_entry) {
std::string temp(_path);
temp.append(_entry->d_name);
return FileSystem::pathType(temp);
} else {
return PATHTYPE_NONE;
}
}
bool DirStream::isOpen() const {
return _dir!=NULL;
}
bool DirStream::close() {
if (_dir) {
closedir(_dir);
_dir=NULL;
return true;
}
return false;
}
void DirStream::init() {
char c=_path[_path.length()-1];
if (c=='\\') {
_path.replace(_path.length()-1, 1, 1, '/');
} else if (c!='/') {
_path.append("/");
}
_dir=opendir(_path.c_str());
}
// FileSystem implementation
namespace FileSystem {
bool statPath(const char* path, struct stat* s) {
return stat(path, s)==0;
}
bool statPath(const std::string& path, struct stat* s) {
return stat(path.c_str(), s)==0;
}
bool statPath(const UnicodeString& path, struct stat* s) {
std::string str;
path.toUTF8String(str);
return stat(str.c_str(), s)==0;
}
PathType pathType(const char* path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
} else {
return PATHTYPE_NONE;
}
}
PathType pathType(const std::string& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
} else {
return PATHTYPE_NONE;
}
}
PathType pathType(const UnicodeString& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode) ? PATHTYPE_FILE : (S_ISDIR(s.st_mode) ? PATHTYPE_DIR : PATHTYPE_NONE);
} else {
return PATHTYPE_NONE;
}
}
bool dirExists(const char* path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISDIR(s.st_mode);
} else {
return false;
}
}
bool dirExists(const std::string& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISDIR(s.st_mode);
} else {
return false;
}
}
bool dirExists(const UnicodeString& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISDIR(s.st_mode);
} else {
return false;
}
}
bool fileExists(const char* path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode);
} else {
return false;
}
}
bool fileExists(const std::string& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode);
} else {
return false;
}
}
bool fileExists(const UnicodeString& path) {
struct stat s;
if (statPath(path, &s)) {
return S_ISREG(s.st_mode);
} else {
return false;
}
}
// TODO structure creation
bool createDir(const char* path, bool structure) {
return mkdir(path, S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH)==0;
}
bool createDir(const std::string& path, bool structure) {
return createDir(path.c_str(), false);
}
bool createDir(const UnicodeString& path, bool structure) {
std::string str;
path.toUTF8String(str);
return createDir(str.c_str(), false);
}
bool createFile(const char* path, bool createpath) {
// TODO: dir/path extraction from file path
/*if (createpath && !dirExists()) {
createDir();
}*/
int fd=creat(path, 0);
if (fd!=-1) {
close(fd);
return true;
}
return false;
}
bool createFile(const std::string& path, bool createpath) {
return createFile(path.c_str(), createpath);
}
bool createFile(const UnicodeString& path, bool createpath) {
std::string str;
path.toUTF8String(str);
return createFile(str.c_str(), createpath);
}
bool deleteFile(const char* path) {
return remove(path)==0;
}
bool deleteFile(const std::string& path) {
return remove(path.c_str())==0;
}
bool deleteFile(const UnicodeString& path) {
std::string str;
path.toUTF8String(str);
return remove(str.c_str())==0;
}
bool deleteDir(const char* path) {
return rmdir(path)==0;
}
bool deleteDir(const std::string& path) {
return rmdir(path.c_str())==0;
}
bool deleteDir(const UnicodeString& path) {
std::string str;
path.toUTF8String(str);
return rmdir(str.c_str())==0;
}
} // namespace FileSystem
} // namespace duct
<|endoftext|> |
<commit_before>//===--- IncorrectRoundings.cpp - clang-tidy ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IncorrectRoundings.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace misc {
namespace {
AST_MATCHER(FloatingLiteral, floatHalf) {
const auto &literal = Node.getValue();
if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
return literal.convertToFloat() == 0.5f;
if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
return literal.convertToDouble() == 0.5;
return false;
}
} // namespace
void IncorrectRoundings::registerMatchers(MatchFinder *MatchFinder) {
// Match a floating literal with value 0.5.
auto FloatHalf = floatLiteral(floatHalf());
// Match a floating point expression.
auto FloatType = expr(hasType(realFloatingPointType()));
// Match a floating literal of 0.5 or a floating literal of 0.5 implicitly.
// cast to floating type.
auto FloatOrCastHalf =
anyOf(FloatHalf,
implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf))));
// Match if either the LHS or RHS is a floating literal of 0.5 or a floating
// literal of 0.5 and the other is of type double or vice versa.
auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)),
allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType)));
// Find expressions of cast to int of the sum of a floating point expression
// and 0.5.
MatchFinder->addMatcher(
implicitCastExpr(
hasImplicitDestinationType(isInteger()),
ignoringParenCasts(binaryOperator(hasOperatorName("+"), OneSideHalf)))
.bind("CastExpr"),
this);
}
void IncorrectRoundings::check(const MatchFinder::MatchResult &Result) {
const auto *CastExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>("CastExpr");
diag(CastExpr->getLocStart(),
"casting (double + 0.5) to integer leads to incorrect rounding; "
"consider using lround (#include <cmath>) instead");
}
} // namespace misc
} // namespace tidy
} // namespace clang
<commit_msg>Replace APFloatBase static fltSemantics data members with getter functions<commit_after>//===--- IncorrectRoundings.cpp - clang-tidy ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IncorrectRoundings.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace misc {
namespace {
AST_MATCHER(FloatingLiteral, floatHalf) {
const auto &literal = Node.getValue();
if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
return literal.convertToFloat() == 0.5f;
if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
return literal.convertToDouble() == 0.5;
return false;
}
} // namespace
void IncorrectRoundings::registerMatchers(MatchFinder *MatchFinder) {
// Match a floating literal with value 0.5.
auto FloatHalf = floatLiteral(floatHalf());
// Match a floating point expression.
auto FloatType = expr(hasType(realFloatingPointType()));
// Match a floating literal of 0.5 or a floating literal of 0.5 implicitly.
// cast to floating type.
auto FloatOrCastHalf =
anyOf(FloatHalf,
implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf))));
// Match if either the LHS or RHS is a floating literal of 0.5 or a floating
// literal of 0.5 and the other is of type double or vice versa.
auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)),
allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType)));
// Find expressions of cast to int of the sum of a floating point expression
// and 0.5.
MatchFinder->addMatcher(
implicitCastExpr(
hasImplicitDestinationType(isInteger()),
ignoringParenCasts(binaryOperator(hasOperatorName("+"), OneSideHalf)))
.bind("CastExpr"),
this);
}
void IncorrectRoundings::check(const MatchFinder::MatchResult &Result) {
const auto *CastExpr = Result.Nodes.getNodeAs<ImplicitCastExpr>("CastExpr");
diag(CastExpr->getLocStart(),
"casting (double + 0.5) to integer leads to incorrect rounding; "
"consider using lround (#include <cmath>) instead");
}
} // namespace misc
} // namespace tidy
} // namespace clang
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <SofaTest/Mapping_test.h>
#include <SofaTest/MultiMapping_test.h>
#include <sofa/defaulttype/VecTypes.h>
#include <Compliant/mapping/SafeDistanceMapping.h>
namespace sofa {
/** Test suite for SafeDistanceMapping
*/
template <typename Mapping>
struct SafeDistanceMappingTest : public Mapping_test<Mapping>
{
typedef SafeDistanceMappingTest self;
typedef Mapping_test<Mapping> base;
typedef sofa::defaulttype::Vec<3,SReal> Vec3;
Mapping* mapping;
SafeDistanceMappingTest() {
mapping = static_cast<Mapping*>(this->base::mapping);
}
bool test()
{
// we need to increase the error, the mapping is too much non-linear
// and the finite differences are too different from the analytic Jacobian
this->errorMax *= 200;
// mapping parameters
typename Mapping::pairs_type pairs(3);
pairs[0][0] = 0; pairs[0][1] = 1;
pairs[1][0] = 0; pairs[1][1] = 2;
pairs[2][0] = 0; pairs[2][1] = 2;
mapping->d_pairs.setValue(pairs);
helper::vector<SReal> restLengths(3);
restLengths[0] = 0;
restLengths[1] = 0;
restLengths[2] = 1;
mapping->d_restLengths.setValue(restLengths);
mapping->d_geometricStiffness.setValue(1); // exact
// parents
typename self::InVecCoord xin(3);
xin[0] = typename self::InCoord(0,0,0);
xin[1] = typename self::InCoord(325,23,-54);
xin[2] = typename self::InCoord(1e-5,-1e-5,1e-7);
typename self::OutVecCoord expected(5);
expected[0] = typename self::OutCoord(xin[1].norm());
expected[1] = typename self::OutCoord(xin[2][0]);
expected[2] = typename self::OutCoord(xin[2][1]);
expected[3] = typename self::OutCoord(xin[2][2]);
expected[4] = typename self::OutCoord(xin[2].norm()-restLengths[2]);
return this->runTest(xin, expected);
}
};
// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
component::mapping::SafeDistanceMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes; // the types to instanciate.
// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceMappingTest, DataTypes);
TYPED_TEST( SafeDistanceMappingTest, test )
{
ASSERT_TRUE( this->test() );
}
///////////////////////////
/** Test suite for SafeDistanceFromTargetMapping
*/
template <typename Mapping>
struct SafeDistanceFromTargetMappingTest : public Mapping_test<Mapping>
{
typedef SafeDistanceFromTargetMappingTest self;
typedef Mapping_test<Mapping> base;
typedef sofa::defaulttype::Vec<3,SReal> Vec3;
Mapping* mapping;
SafeDistanceFromTargetMappingTest() {
mapping = static_cast<Mapping*>(this->base::mapping);
}
bool test()
{
// we need to increase the error, the mapping is too much non-linear
// and the finite differences are too different from the analytic Jacobian
this->errorMax *= 200;
// mapping parameters
helper::vector<unsigned> indices(3);
indices[0] = 0;
indices[1] = 1;
indices[2] = 1;
mapping->d_indices.setValue(indices);
typename self::InVecCoord targets(3);
targets[0] = typename self::InCoord(0,0,0);
targets[1] = typename self::InCoord(0,0,0);
targets[2] = typename self::InCoord(0,0,0);
mapping->d_targetPositions.setValue(targets);
helper::vector<SReal> restLengths(3);
restLengths[0] = 0;
restLengths[1] = 0;
restLengths[2] = 1;
mapping->d_restLengths.setValue(restLengths);
mapping->d_geometricStiffness.setValue(1); // exact
// parents
typename self::InVecCoord xin(2);
xin[0] = typename self::InCoord(325,23,-54);
xin[1] = typename self::InCoord(1e-5,-1e-5,1e-7);
typename self::OutVecCoord expected(5);
expected[0] = typename self::OutCoord(xin[0].norm());
expected[1] = typename self::OutCoord(xin[1][0]);
expected[2] = typename self::OutCoord(xin[1][1]);
expected[3] = typename self::OutCoord(xin[1][2]);
expected[4] = typename self::OutCoord(xin[1].norm()-restLengths[2]);
return this->runTest(xin, expected);
}
};
// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
component::mapping::SafeDistanceFromTargetMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes2; // the types to instanciate.
// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceFromTargetMappingTest, DataTypes2);
TYPED_TEST( SafeDistanceFromTargetMappingTest, test )
{
ASSERT_TRUE( this->test() );
}
} // namespace sofa
<commit_msg>[Compliant] increasing SafeDistanceMappingTest threshold<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <SofaTest/Mapping_test.h>
#include <SofaTest/MultiMapping_test.h>
#include <sofa/defaulttype/VecTypes.h>
#include <Compliant/mapping/SafeDistanceMapping.h>
namespace sofa {
/** Test suite for SafeDistanceMapping
*/
template <typename Mapping>
struct SafeDistanceMappingTest : public Mapping_test<Mapping>
{
typedef SafeDistanceMappingTest self;
typedef Mapping_test<Mapping> base;
typedef sofa::defaulttype::Vec<3,SReal> Vec3;
Mapping* mapping;
SafeDistanceMappingTest() {
mapping = static_cast<Mapping*>(this->base::mapping);
}
bool test()
{
// we need to increase the error, the mapping is too much non-linear
// and the finite differences are too different from the analytic Jacobian
this->errorMax *= 300;
// mapping parameters
typename Mapping::pairs_type pairs(3);
pairs[0][0] = 0; pairs[0][1] = 1;
pairs[1][0] = 0; pairs[1][1] = 2;
pairs[2][0] = 0; pairs[2][1] = 2;
mapping->d_pairs.setValue(pairs);
helper::vector<SReal> restLengths(3);
restLengths[0] = 0;
restLengths[1] = 0;
restLengths[2] = 1;
mapping->d_restLengths.setValue(restLengths);
mapping->d_geometricStiffness.setValue(1); // exact
// parents
typename self::InVecCoord xin(3);
xin[0] = typename self::InCoord(0,0,0);
xin[1] = typename self::InCoord(325,23,-54);
xin[2] = typename self::InCoord(1e-5,-1e-5,1e-7);
typename self::OutVecCoord expected(5);
expected[0] = typename self::OutCoord(xin[1].norm());
expected[1] = typename self::OutCoord(xin[2][0]);
expected[2] = typename self::OutCoord(xin[2][1]);
expected[3] = typename self::OutCoord(xin[2][2]);
expected[4] = typename self::OutCoord(xin[2].norm()-restLengths[2]);
return this->runTest(xin, expected);
}
};
// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
component::mapping::SafeDistanceMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes; // the types to instanciate.
// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceMappingTest, DataTypes);
TYPED_TEST( SafeDistanceMappingTest, test )
{
ASSERT_TRUE( this->test() );
}
///////////////////////////
/** Test suite for SafeDistanceFromTargetMapping
*/
template <typename Mapping>
struct SafeDistanceFromTargetMappingTest : public Mapping_test<Mapping>
{
typedef SafeDistanceFromTargetMappingTest self;
typedef Mapping_test<Mapping> base;
typedef sofa::defaulttype::Vec<3,SReal> Vec3;
Mapping* mapping;
SafeDistanceFromTargetMappingTest() {
mapping = static_cast<Mapping*>(this->base::mapping);
}
bool test()
{
// we need to increase the error, the mapping is too much non-linear
// and the finite differences are too different from the analytic Jacobian
this->errorMax *= 300;
// mapping parameters
helper::vector<unsigned> indices(3);
indices[0] = 0;
indices[1] = 1;
indices[2] = 1;
mapping->d_indices.setValue(indices);
typename self::InVecCoord targets(3);
targets[0] = typename self::InCoord(0,0,0);
targets[1] = typename self::InCoord(0,0,0);
targets[2] = typename self::InCoord(0,0,0);
mapping->d_targetPositions.setValue(targets);
helper::vector<SReal> restLengths(3);
restLengths[0] = 0;
restLengths[1] = 0;
restLengths[2] = 1;
mapping->d_restLengths.setValue(restLengths);
mapping->d_geometricStiffness.setValue(1); // exact
// parents
typename self::InVecCoord xin(2);
xin[0] = typename self::InCoord(325,23,-54);
xin[1] = typename self::InCoord(1e-5,-1e-5,1e-7);
typename self::OutVecCoord expected(5);
expected[0] = typename self::OutCoord(xin[0].norm());
expected[1] = typename self::OutCoord(xin[1][0]);
expected[2] = typename self::OutCoord(xin[1][1]);
expected[3] = typename self::OutCoord(xin[1][2]);
expected[4] = typename self::OutCoord(xin[1].norm()-restLengths[2]);
return this->runTest(xin, expected);
}
};
// Define the list of types to instanciate. We do not necessarily need to test all combinations.
using testing::Types;
typedef Types<
component::mapping::SafeDistanceFromTargetMapping<defaulttype::Vec3Types, defaulttype::Vec1Types>
> DataTypes2; // the types to instanciate.
// Test suite for all the instanciations
TYPED_TEST_CASE(SafeDistanceFromTargetMappingTest, DataTypes2);
TYPED_TEST( SafeDistanceFromTargetMappingTest, test )
{
ASSERT_TRUE( this->test() );
}
} // namespace sofa
<|endoftext|> |
<commit_before>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2015, Daemon Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Daemon developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/
#include "common/System.h"
#include "common/String.h"
#include "Crypto.h"
#include <nettle/aes.h>
#include <nettle/base64.h>
#include <nettle/md5.h>
#include <nettle/sha2.h>
#include <nettle/version.h>
// Compatibility with old nettle versions
#if NETTLE_VERSION_MAJOR < 3
#ifndef AES256_KEY_SIZE
# define AES256_KEY_SIZE 32
#endif
typedef aes_ctx compat_aes256_ctx;
static void nettle_compat_aes256_set_encrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_encrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_set_decrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_decrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_encrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_encrypt(ctx, length, dst, src);
}
static void nettle_compat_aes256_decrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_decrypt(ctx, length, dst, src);
}
static int nettle_compat_base64_decode_update(base64_decode_ctx *ctx,
size_t *dst_length,
uint8_t *dst,
size_t src_length,
const uint8_t *src)
{
unsigned dst_length_uns = *dst_length;
nettle_base64_decode_update(ctx, &dst_length_uns, dst, src_length, src);
}
#undef aes256_set_encrypt_key
#define nettle_aes256_set_encrypt_key nettle_compat_aes256_set_encrypt_key
#define nettle_aes256_set_decrypt_key nettle_compat_aes256_set_decrypt_key
#define nettle_aes256_invert_key nettle_compat_aes256_invert_key
#define nettle_aes256_encrypt nettle_compat_aes256_encrypt
#define nettle_aes256_decrypt nettle_compat_aes256_decrypt
#define aes256_ctx compat_aes256_ctx
#define nettle_base64_decode_update nettle_compat_base64_decode_update
#endif // NETTLE_VERSION_MAJOR < 3
namespace Crypto {
Data RandomData( std::size_t bytes )
{
Data data( bytes );
Sys::GenRandomBytes(data.data(), data.size());
return data;
}
namespace Encoding {
/*
* Translates binary data into a hexadecimal string
*/
Data HexEncode( const Data& input )
{
std::ostringstream stream;
stream.setf(std::ios::hex, std::ios::basefield);
stream.fill('0');
for ( auto ch : input )
{
stream.width(2);
stream << int( ch );
}
auto string = stream.str();
return Data(string.begin(), string.end());
}
/*
* Translates a hexadecimal string into binary data
* PRE: input is a valid hexadecimal string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool HexDecode( const Data& input, Data& output )
{
if ( input.size() % 2 )
{
return false;
}
Data mid( input.size() / 2 );
for ( std::size_t i = 0; i < input.size(); i += 2 )
{
if ( !Str::cisxdigit( input[i] ) || !Str::cisxdigit( input[i+1] ) )
{
return false;
}
mid[ i / 2 ] = ( Str::GetHex( input[i] ) << 4 ) | Str::GetHex( input[i+1] );
}
output = mid;
return true;
}
/*
* Translates binary data into a base64 encoded string
*/
Data Base64Encode( const Data& input )
{
base64_encode_ctx ctx;
nettle_base64_encode_init( &ctx );
Data output( BASE64_ENCODE_LENGTH( input.size() ) + BASE64_ENCODE_FINAL_LENGTH );
int encoded_bytes = nettle_base64_encode_update(
&ctx, output.data(), input.size(), input.data()
);
encoded_bytes += nettle_base64_encode_final( &ctx, output.data() + encoded_bytes );
output.erase( output.begin() + encoded_bytes, output.end() );
return output;
}
/*
* Translates a base64 encoded string into binary data
* PRE: input is a valid Base64 string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool Base64Decode( const Data& input, Data& output )
{
base64_decode_ctx ctx;
nettle_base64_decode_init( &ctx );
Data temp( BASE64_DECODE_LENGTH( input.size() ) );
std::size_t decoded_bytes = 0;
if ( !nettle_base64_decode_update( &ctx, &decoded_bytes, temp.data(),
input.size(), input.data() ) )
{
return false;
}
if ( !nettle_base64_decode_final( &ctx ) )
{
return false;
}
temp.erase( temp.begin() + decoded_bytes, temp.end() );
output = temp;
return true;
}
} // namespace Encoding
namespace Hash {
Data Sha256( const Data& input )
{
sha256_ctx ctx;
nettle_sha256_init( &ctx );
nettle_sha256_update( &ctx, input.size(), input.data() );
Data output( SHA256_DIGEST_SIZE );
nettle_sha256_digest( &ctx, SHA256_DIGEST_SIZE, output.data() );
return output;
}
Data Md5( const Data& input )
{
md5_ctx ctx;
nettle_md5_init( &ctx );
nettle_md5_update( &ctx, input.size(), input.data() );
Data output( MD5_DIGEST_SIZE );
nettle_md5_digest( &ctx, MD5_DIGEST_SIZE, output.data() );
return output;
}
} // namespace Hash
/*
* Adds PKCS#7 padding to the data
*/
void AddPadding( Data& target, std::size_t block_size )
{
auto pad = block_size - target.size() % block_size;
target.resize( target.size() + pad, pad );
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long
* POST: output contains the encrypted data
* Notes: plain_text will be padded using the PKCS#7 algorthm,
* if the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Encrypt( Data plain_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE )
{
return false;
}
aes256_ctx ctx;
nettle_aes256_set_encrypt_key( &ctx, key.data() );
AddPadding( plain_text, AES_BLOCK_SIZE );
output.resize( plain_text.size(), 0 );
nettle_aes256_encrypt( &ctx, plain_text.size(),
output.data(), plain_text.data() );
nettle_aes256_decrypt( &ctx, plain_text.size(),
plain_text.data(), output.data() );
return true;
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long,
* cypher_text.size() is an integer multiple of the AES block size
* POST: output contains the decrypted data
* Note: If the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Decrypt( Data cypher_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE || cypher_text.size() % AES_BLOCK_SIZE )
{
return true;
}
aes256_ctx ctx;
nettle_aes256_set_decrypt_key( &ctx, key.data() );
output.resize( cypher_text.size(), 0 );
nettle_aes256_decrypt( &ctx, cypher_text.size(),
output.data(), cypher_text.data() );
return true;
}
} // namespace Crypto
<commit_msg>Use a different check to detect old Nettle versions<commit_after>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2015, Daemon Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Daemon developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/
#include "common/System.h"
#include "common/String.h"
#include "Crypto.h"
#include <nettle/aes.h>
#include <nettle/base64.h>
#include <nettle/md5.h>
#include <nettle/sha2.h>
#include <nettle/version.h>
// Compatibility with old nettle versions
#if !defined(AES256_KEY_SIZE)
#define AES256_KEY_SIZE 32
typedef aes_ctx compat_aes256_ctx;
static void nettle_compat_aes256_set_encrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_encrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_set_decrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_decrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_encrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_encrypt(ctx, length, dst, src);
}
static void nettle_compat_aes256_decrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_decrypt(ctx, length, dst, src);
}
static int nettle_compat_base64_decode_update(base64_decode_ctx *ctx,
size_t *dst_length,
uint8_t *dst,
size_t src_length,
const uint8_t *src)
{
unsigned dst_length_uns = *dst_length;
nettle_base64_decode_update(ctx, &dst_length_uns, dst, src_length, src);
}
#undef aes256_set_encrypt_key
#define nettle_aes256_set_encrypt_key nettle_compat_aes256_set_encrypt_key
#define nettle_aes256_set_decrypt_key nettle_compat_aes256_set_decrypt_key
#define nettle_aes256_invert_key nettle_compat_aes256_invert_key
#define nettle_aes256_encrypt nettle_compat_aes256_encrypt
#define nettle_aes256_decrypt nettle_compat_aes256_decrypt
#define aes256_ctx compat_aes256_ctx
#define nettle_base64_decode_update nettle_compat_base64_decode_update
#endif // NETTLE_VERSION_MAJOR < 3
namespace Crypto {
Data RandomData( std::size_t bytes )
{
Data data( bytes );
Sys::GenRandomBytes(data.data(), data.size());
return data;
}
namespace Encoding {
/*
* Translates binary data into a hexadecimal string
*/
Data HexEncode( const Data& input )
{
std::ostringstream stream;
stream.setf(std::ios::hex, std::ios::basefield);
stream.fill('0');
for ( auto ch : input )
{
stream.width(2);
stream << int( ch );
}
auto string = stream.str();
return Data(string.begin(), string.end());
}
/*
* Translates a hexadecimal string into binary data
* PRE: input is a valid hexadecimal string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool HexDecode( const Data& input, Data& output )
{
if ( input.size() % 2 )
{
return false;
}
Data mid( input.size() / 2 );
for ( std::size_t i = 0; i < input.size(); i += 2 )
{
if ( !Str::cisxdigit( input[i] ) || !Str::cisxdigit( input[i+1] ) )
{
return false;
}
mid[ i / 2 ] = ( Str::GetHex( input[i] ) << 4 ) | Str::GetHex( input[i+1] );
}
output = mid;
return true;
}
/*
* Translates binary data into a base64 encoded string
*/
Data Base64Encode( const Data& input )
{
base64_encode_ctx ctx;
nettle_base64_encode_init( &ctx );
Data output( BASE64_ENCODE_LENGTH( input.size() ) + BASE64_ENCODE_FINAL_LENGTH );
int encoded_bytes = nettle_base64_encode_update(
&ctx, output.data(), input.size(), input.data()
);
encoded_bytes += nettle_base64_encode_final( &ctx, output.data() + encoded_bytes );
output.erase( output.begin() + encoded_bytes, output.end() );
return output;
}
/*
* Translates a base64 encoded string into binary data
* PRE: input is a valid Base64 string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool Base64Decode( const Data& input, Data& output )
{
base64_decode_ctx ctx;
nettle_base64_decode_init( &ctx );
Data temp( BASE64_DECODE_LENGTH( input.size() ) );
std::size_t decoded_bytes = 0;
if ( !nettle_base64_decode_update( &ctx, &decoded_bytes, temp.data(),
input.size(), input.data() ) )
{
return false;
}
if ( !nettle_base64_decode_final( &ctx ) )
{
return false;
}
temp.erase( temp.begin() + decoded_bytes, temp.end() );
output = temp;
return true;
}
} // namespace Encoding
namespace Hash {
Data Sha256( const Data& input )
{
sha256_ctx ctx;
nettle_sha256_init( &ctx );
nettle_sha256_update( &ctx, input.size(), input.data() );
Data output( SHA256_DIGEST_SIZE );
nettle_sha256_digest( &ctx, SHA256_DIGEST_SIZE, output.data() );
return output;
}
Data Md5( const Data& input )
{
md5_ctx ctx;
nettle_md5_init( &ctx );
nettle_md5_update( &ctx, input.size(), input.data() );
Data output( MD5_DIGEST_SIZE );
nettle_md5_digest( &ctx, MD5_DIGEST_SIZE, output.data() );
return output;
}
} // namespace Hash
/*
* Adds PKCS#7 padding to the data
*/
void AddPadding( Data& target, std::size_t block_size )
{
auto pad = block_size - target.size() % block_size;
target.resize( target.size() + pad, pad );
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long
* POST: output contains the encrypted data
* Notes: plain_text will be padded using the PKCS#7 algorthm,
* if the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Encrypt( Data plain_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE )
{
return false;
}
aes256_ctx ctx;
nettle_aes256_set_encrypt_key( &ctx, key.data() );
AddPadding( plain_text, AES_BLOCK_SIZE );
output.resize( plain_text.size(), 0 );
nettle_aes256_encrypt( &ctx, plain_text.size(),
output.data(), plain_text.data() );
nettle_aes256_decrypt( &ctx, plain_text.size(),
plain_text.data(), output.data() );
return true;
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long,
* cypher_text.size() is an integer multiple of the AES block size
* POST: output contains the decrypted data
* Note: If the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Decrypt( Data cypher_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE || cypher_text.size() % AES_BLOCK_SIZE )
{
return true;
}
aes256_ctx ctx;
nettle_aes256_set_decrypt_key( &ctx, key.data() );
output.resize( cypher_text.size(), 0 );
nettle_aes256_decrypt( &ctx, cypher_text.size(),
output.data(), cypher_text.data() );
return true;
}
} // namespace Crypto
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: parsedFunction.C,v 1.4 2002/12/18 16:00:34 sturm Exp $
#include <BALL/MATHS/parsedFunction.h>
extern int parsedFunctionparse();
extern double parsedFunctionResult;
extern void parsedFunction_initBuffer(const char*);
extern void parsedFunction_delBuffer();
namespace BALL
{
HashMap<String, double*> *parsedFunctionConstants;
HashMap<String, double(*)(double)> *parsedFunctionFunctions;
template <typename arg>
ParsedFunction<arg>::ParsedFunction()
throw()
: constants_(),
functions_(),
expression_("")
{
initTable();
}
template <typename arg>
ParsedFunction<arg>::ParsedFunction(String expression)
throw()
: constants_(),
functions_(),
expression_(expression)
{
initTable();
}
/** Strange... gcc-3.0.1 needs this constructor as a non-template version... **/
template <>
ParsedFunction<float>::ParsedFunction(String expression)
throw()
: constants_(),
functions_(),
expression_(expression)
{
initTable();
}
template <typename arg>
ParsedFunction<arg>::ParsedFunction(const ParsedFunction& func)
throw()
{
constants_ = func.constants_;
functions_ = func.functions_;
expression_ = func.expression_;
initTable();
}
template <typename arg>
ParsedFunction<arg>::~ParsedFunction()
throw()
{
}
/** Strange... gcc-3.0.1 needs this destructor in a non-template version... **/
template <>
ParsedFunction<float>::~ParsedFunction()
throw()
{
}
template <typename arg>
double ParsedFunction<arg>::operator () (arg argument)
throw(Exception::ParseError)
{
constants_["X"] = (double) &argument;
parsedFunctionConstants = &constants_;
parsedFunctionFunctions = &functions_;
parsedFunction_initBuffer(expression_.c_str());
parsedFunctionparse();
parsedFunction_delBuffer();
return parsedFunctionResult;
}
template <>
double ParsedFunction<float>::operator () (float argument)
throw(Exception::ParseError)
{
double arg = argument;
constants_["X"] = &arg;
parsedFunctionConstants = &constants_;
parsedFunctionFunctions = &functions_;
parsedFunction_initBuffer(expression_.c_str());
parsedFunctionparse();
parsedFunction_delBuffer();
return parsedFunctionResult;
}
template <typename arg>
void ParsedFunction<arg>::initTable()
throw()
{
// initialize the functions table
functions_["sin"] = (double(*)(double))&sin;
functions_["cos"] = (double(*)(double))&cos;
functions_["asin"] = (double(*)(double))&asin;
functions_["acos"] = (double(*)(double))&acos;
functions_["tan"] = (double(*)(double))&tan;
functions_["atan"] = (double(*)(double))&atan;
functions_["ln"] = (double(*)(double))&log;
functions_["exp"] = (double(*)(double))&exp;
functions_[""] = 0;
}
}
<commit_msg>parsedFunction.C<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: parsedFunction.C,v 1.5 2002/12/20 21:00:57 anhi Exp $
#include <BALL/MATHS/parsedFunction.h>
extern int parsedFunctionparse();
extern double parsedFunctionResult;
extern void parsedFunction_initBuffer(const char*);
extern void parsedFunction_delBuffer();
namespace BALL
{
HashMap<String, double*> *parsedFunctionConstants;
HashMap<String, double(*)(double)> *parsedFunctionFunctions;
template <typename arg>
ParsedFunction<arg>::ParsedFunction()
throw()
: constants_(),
functions_(),
expression_("")
{
initTable();
}
template <typename arg>
ParsedFunction<arg>::ParsedFunction(const String& expression)
throw()
: constants_(),
functions_(),
expression_(expression)
{
initTable();
}
/* Strange... gcc-3.0.1 needs this constructor as a non-template version... */
template <>
ParsedFunction<float>::ParsedFunction(const String& expression)
throw()
: constants_(),
functions_(),
expression_(expression)
{
initTable();
}
template <typename arg>
ParsedFunction<arg>::ParsedFunction(const ParsedFunction& func)
throw()
{
constants_ = func.constants_;
functions_ = func.functions_;
expression_ = func.expression_;
initTable();
}
template <typename arg>
ParsedFunction<arg>::~ParsedFunction()
throw()
{
}
/** Strange... gcc-3.0.1 needs this destructor in a non-template version... **/
template <>
ParsedFunction<float>::~ParsedFunction()
throw()
{
}
template <typename arg>
double ParsedFunction<arg>::operator () (arg argument)
throw(Exception::ParseError)
{
constants_["X"] = (double) &argument;
parsedFunctionConstants = &constants_;
parsedFunctionFunctions = &functions_;
parsedFunction_initBuffer(expression_.c_str());
parsedFunctionparse();
parsedFunction_delBuffer();
return parsedFunctionResult;
}
template <>
double ParsedFunction<float>::operator () (float argument)
throw(Exception::ParseError)
{
double arg = argument;
constants_["X"] = &arg;
parsedFunctionConstants = &constants_;
parsedFunctionFunctions = &functions_;
parsedFunction_initBuffer(expression_.c_str());
parsedFunctionparse();
parsedFunction_delBuffer();
return parsedFunctionResult;
}
template <typename arg>
void ParsedFunction<arg>::initTable()
throw()
{
// initialize the functions table
functions_["sin"] = (double(*)(double))&sin;
functions_["cos"] = (double(*)(double))&cos;
functions_["asin"] = (double(*)(double))&asin;
functions_["acos"] = (double(*)(double))&acos;
functions_["tan"] = (double(*)(double))&tan;
functions_["atan"] = (double(*)(double))&atan;
functions_["ln"] = (double(*)(double))&log;
functions_["exp"] = (double(*)(double))&exp;
functions_[""] = 0;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/atom_api_clipboard.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
ui::ClipboardType Clipboard::GetClipboardType(mate::Arguments* args) {
std::string type;
if (args->GetNext(&type) && type == "selection")
return ui::CLIPBOARD_TYPE_SELECTION;
else
return ui::CLIPBOARD_TYPE_COPY_PASTE;
}
std::vector<base::string16> Clipboard::AvailableFormats(mate::Arguments* args) {
std::vector<base::string16> format_types;
bool ignore;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore);
return format_types;
}
bool Clipboard::Has(const std::string& format_string, mate::Arguments* args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
return clipboard->IsFormatAvailable(format, GetClipboardType(args));
}
std::string Clipboard::Read(const std::string& format_string) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
std::string data;
clipboard->ReadData(format, &data);
return data;
}
v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string,
mate::Arguments* args) {
std::string data = Read(format_string);
return node::Buffer::Copy(
args->isolate(), data.data(), data.length()).ToLocalChecked();
}
void Clipboard::WriteBuffer(const std::string& format,
const v8::Local<v8::Value> buffer,
mate::Arguments* args) {
if (!node::Buffer::HasInstance(buffer)) {
args->ThrowError("buffer must be a node Buffer");
return;
}
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteData(node::Buffer::Data(buffer), node::Buffer::Length(buffer),
ui::Clipboard::GetFormatType(format));
}
void Clipboard::Write(const mate::Dictionary& data, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
base::string16 text, html, bookmark;
gfx::Image image;
if (data.Get("text", &text)) {
writer.WriteText(text);
if (data.Get("bookmark", &bookmark))
writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text));
}
if (data.Get("rtf", &text)) {
std::string rtf = base::UTF16ToUTF8(text);
writer.WriteRTF(rtf);
}
if (data.Get("html", &html))
writer.WriteHTML(html, std::string());
if (data.Get("image", &image))
writer.WriteImage(image.AsBitmap());
}
base::string16 Clipboard::ReadText(mate::Arguments* args) {
base::string16 data;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
auto type = GetClipboardType(args);
if (clipboard->IsFormatAvailable(
ui::Clipboard::GetPlainTextWFormatType(), type)) {
clipboard->ReadText(type, &data);
} else if (clipboard->IsFormatAvailable(
ui::Clipboard::GetPlainTextFormatType(), type)) {
std::string result;
clipboard->ReadAsciiText(type, &result);
data = base::ASCIIToUTF16(result);
}
return data;
}
void Clipboard::WriteText(const base::string16& text, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteText(text);
}
base::string16 Clipboard::ReadRtf(mate::Arguments* args) {
std::string data;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadRTF(GetClipboardType(args), &data);
return base::UTF8ToUTF16(data);
}
void Clipboard::WriteRtf(const std::string& text, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteRTF(text);
}
base::string16 Clipboard::ReadHtml(mate::Arguments* args) {
base::string16 data;
base::string16 html;
std::string url;
uint32_t start;
uint32_t end;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end);
data = html.substr(start, end - start);
return data;
}
void Clipboard::WriteHtml(const base::string16& html, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteHTML(html, std::string());
}
v8::Local<v8::Value> Clipboard::ReadBookmark(mate::Arguments* args) {
base::string16 title;
std::string url;
mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate());
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadBookmark(&title, &url);
dict.Set("title", title);
dict.Set("url", url);
return dict.GetHandle();
}
void Clipboard::WriteBookmark(const base::string16& title,
const std::string& url,
mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteBookmark(title, url);
}
gfx::Image Clipboard::ReadImage(mate::Arguments* args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args));
return gfx::Image::CreateFrom1xBitmap(bitmap);
}
void Clipboard::WriteImage(const gfx::Image& image, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
SkBitmap bmp;
if (image.AsBitmap().deepCopyTo(&bmp)) {
writer.WriteImage(bmp);
} else {
writer.WriteImage(image.AsBitmap());
}
}
#if !defined(OS_MACOSX)
void Clipboard::WriteFindText(const base::string16& text) {}
base::string16 Clipboard::ReadFindText() { return base::string16(); }
#endif
void Clipboard::Clear(mate::Arguments* args) {
ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args));
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.SetMethod("availableFormats", &atom::api::Clipboard::AvailableFormats);
dict.SetMethod("has", &atom::api::Clipboard::Has);
dict.SetMethod("read", &atom::api::Clipboard::Read);
dict.SetMethod("write", &atom::api::Clipboard::Write);
dict.SetMethod("readText", &atom::api::Clipboard::ReadText);
dict.SetMethod("writeText", &atom::api::Clipboard::WriteText);
dict.SetMethod("readRTF", &atom::api::Clipboard::ReadRtf);
dict.SetMethod("writeRTF", &atom::api::Clipboard::WriteRtf);
dict.SetMethod("readHTML", &atom::api::Clipboard::ReadHtml);
dict.SetMethod("writeHTML", &atom::api::Clipboard::WriteHtml);
dict.SetMethod("readBookmark", &atom::api::Clipboard::ReadBookmark);
dict.SetMethod("writeBookmark", &atom::api::Clipboard::WriteBookmark);
dict.SetMethod("readImage", &atom::api::Clipboard::ReadImage);
dict.SetMethod("writeImage", &atom::api::Clipboard::WriteImage);
dict.SetMethod("readFindText", &atom::api::Clipboard::ReadFindText);
dict.SetMethod("writeFindText", &atom::api::Clipboard::WriteFindText);
dict.SetMethod("readBuffer", &atom::api::Clipboard::ReadBuffer);
dict.SetMethod("writeBuffer", &atom::api::Clipboard::WriteBuffer);
dict.SetMethod("clear", &atom::api::Clipboard::Clear);
// TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings
dict.SetMethod("readRtf", &atom::api::Clipboard::ReadRtf);
dict.SetMethod("writeRtf", &atom::api::Clipboard::WriteRtf);
dict.SetMethod("readHtml", &atom::api::Clipboard::ReadHtml);
dict.SetMethod("writeHtml", &atom::api::Clipboard::WriteHtml);
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_clipboard, Initialize)
<commit_msg>added comment to mention sk_tools_utils::copy_to<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/atom_api_clipboard.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
ui::ClipboardType Clipboard::GetClipboardType(mate::Arguments* args) {
std::string type;
if (args->GetNext(&type) && type == "selection")
return ui::CLIPBOARD_TYPE_SELECTION;
else
return ui::CLIPBOARD_TYPE_COPY_PASTE;
}
std::vector<base::string16> Clipboard::AvailableFormats(mate::Arguments* args) {
std::vector<base::string16> format_types;
bool ignore;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore);
return format_types;
}
bool Clipboard::Has(const std::string& format_string, mate::Arguments* args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
return clipboard->IsFormatAvailable(format, GetClipboardType(args));
}
std::string Clipboard::Read(const std::string& format_string) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
std::string data;
clipboard->ReadData(format, &data);
return data;
}
v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string,
mate::Arguments* args) {
std::string data = Read(format_string);
return node::Buffer::Copy(
args->isolate(), data.data(), data.length()).ToLocalChecked();
}
void Clipboard::WriteBuffer(const std::string& format,
const v8::Local<v8::Value> buffer,
mate::Arguments* args) {
if (!node::Buffer::HasInstance(buffer)) {
args->ThrowError("buffer must be a node Buffer");
return;
}
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteData(node::Buffer::Data(buffer), node::Buffer::Length(buffer),
ui::Clipboard::GetFormatType(format));
}
void Clipboard::Write(const mate::Dictionary& data, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
base::string16 text, html, bookmark;
gfx::Image image;
if (data.Get("text", &text)) {
writer.WriteText(text);
if (data.Get("bookmark", &bookmark))
writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text));
}
if (data.Get("rtf", &text)) {
std::string rtf = base::UTF16ToUTF8(text);
writer.WriteRTF(rtf);
}
if (data.Get("html", &html))
writer.WriteHTML(html, std::string());
if (data.Get("image", &image))
writer.WriteImage(image.AsBitmap());
}
base::string16 Clipboard::ReadText(mate::Arguments* args) {
base::string16 data;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
auto type = GetClipboardType(args);
if (clipboard->IsFormatAvailable(
ui::Clipboard::GetPlainTextWFormatType(), type)) {
clipboard->ReadText(type, &data);
} else if (clipboard->IsFormatAvailable(
ui::Clipboard::GetPlainTextFormatType(), type)) {
std::string result;
clipboard->ReadAsciiText(type, &result);
data = base::ASCIIToUTF16(result);
}
return data;
}
void Clipboard::WriteText(const base::string16& text, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteText(text);
}
base::string16 Clipboard::ReadRtf(mate::Arguments* args) {
std::string data;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadRTF(GetClipboardType(args), &data);
return base::UTF8ToUTF16(data);
}
void Clipboard::WriteRtf(const std::string& text, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteRTF(text);
}
base::string16 Clipboard::ReadHtml(mate::Arguments* args) {
base::string16 data;
base::string16 html;
std::string url;
uint32_t start;
uint32_t end;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end);
data = html.substr(start, end - start);
return data;
}
void Clipboard::WriteHtml(const base::string16& html, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteHTML(html, std::string());
}
v8::Local<v8::Value> Clipboard::ReadBookmark(mate::Arguments* args) {
base::string16 title;
std::string url;
mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate());
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadBookmark(&title, &url);
dict.Set("title", title);
dict.Set("url", url);
return dict.GetHandle();
}
void Clipboard::WriteBookmark(const base::string16& title,
const std::string& url,
mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteBookmark(title, url);
}
gfx::Image Clipboard::ReadImage(mate::Arguments* args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args));
return gfx::Image::CreateFrom1xBitmap(bitmap);
}
void Clipboard::WriteImage(const gfx::Image& image, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
SkBitmap bmp;
// TODO(ferreus): Replace with sk_tools_utils::copy_to (chrome60)
if (image.AsBitmap().deepCopyTo(&bmp)) {
writer.WriteImage(bmp);
} else {
writer.WriteImage(image.AsBitmap());
}
}
#if !defined(OS_MACOSX)
void Clipboard::WriteFindText(const base::string16& text) {}
base::string16 Clipboard::ReadFindText() { return base::string16(); }
#endif
void Clipboard::Clear(mate::Arguments* args) {
ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args));
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.SetMethod("availableFormats", &atom::api::Clipboard::AvailableFormats);
dict.SetMethod("has", &atom::api::Clipboard::Has);
dict.SetMethod("read", &atom::api::Clipboard::Read);
dict.SetMethod("write", &atom::api::Clipboard::Write);
dict.SetMethod("readText", &atom::api::Clipboard::ReadText);
dict.SetMethod("writeText", &atom::api::Clipboard::WriteText);
dict.SetMethod("readRTF", &atom::api::Clipboard::ReadRtf);
dict.SetMethod("writeRTF", &atom::api::Clipboard::WriteRtf);
dict.SetMethod("readHTML", &atom::api::Clipboard::ReadHtml);
dict.SetMethod("writeHTML", &atom::api::Clipboard::WriteHtml);
dict.SetMethod("readBookmark", &atom::api::Clipboard::ReadBookmark);
dict.SetMethod("writeBookmark", &atom::api::Clipboard::WriteBookmark);
dict.SetMethod("readImage", &atom::api::Clipboard::ReadImage);
dict.SetMethod("writeImage", &atom::api::Clipboard::WriteImage);
dict.SetMethod("readFindText", &atom::api::Clipboard::ReadFindText);
dict.SetMethod("writeFindText", &atom::api::Clipboard::WriteFindText);
dict.SetMethod("readBuffer", &atom::api::Clipboard::ReadBuffer);
dict.SetMethod("writeBuffer", &atom::api::Clipboard::WriteBuffer);
dict.SetMethod("clear", &atom::api::Clipboard::Clear);
// TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings
dict.SetMethod("readRtf", &atom::api::Clipboard::ReadRtf);
dict.SetMethod("writeRtf", &atom::api::Clipboard::WriteRtf);
dict.SetMethod("readHtml", &atom::api::Clipboard::ReadHtml);
dict.SetMethod("writeHtml", &atom::api::Clipboard::WriteHtml);
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_clipboard, Initialize)
<|endoftext|> |
<commit_before>// This class
#include <Internal/ParticleClasses/ParticleEmitter.hpp>
//#include <FluidManager.hpp> // Included for the sake of particle data. Kinda silly, really
#include <Internal/PhysicsModuleImplementation.hpp>
using namespace DirectX;
using namespace physx;
namespace DoremiEngine
{
namespace Physics
{
ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils)
: m_this(p_data), m_utils(p_utils), m_timeSinceLast(0)
{
m_nextIndex = 0;
m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT);
m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE);
m_utils.m_worldScene->addActor(*m_particleSystem);
// Might be necessary to set flag to collide with dynamics
// m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true);
m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); // Should not be here
}
ParticleEmitter::~ParticleEmitter() {}
void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; }
void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; }
void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); }
void ParticleEmitter::GetPositions(vector<XMFLOAT3>& o_positions)
{
// This is a bit harder than it really ought to be...
PxParticleReadData* readData = m_particleSystem->lockParticleReadData();
PxStrideIterator<const PxVec3> positions = readData->positionBuffer;
PxStrideIterator<const PxVec3> velocities = readData->velocityBuffer;
PxStrideIterator<const PxParticleFlags> flags = readData->flagsBuffer;
vector<XMFLOAT3> velocitiesVector;
vector<int> indicesOfParticlesToBeReleased;
uint32_t numParticles = readData->validParticleRange;
for(uint32_t i = 0; i < numParticles; i++)
{
// Check if particles are supposed to be removed
if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) // | PxParticleFlag::eVALID))
{
indicesOfParticlesToBeReleased.push_back(i);
}
else if(flags[i] & PxParticleFlag::eVALID)
{
o_positions.push_back(XMFLOAT3(positions[i].x, positions[i].y, positions[i].z));
}
}
readData->unlock();
if(indicesOfParticlesToBeReleased.size() != 0)
{
PxStrideIterator<const PxU32> inicesPX(reinterpret_cast<PxU32*>(&indicesOfParticlesToBeReleased[0]));
m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX);
}
}
void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; }
void ParticleEmitter::Update(float p_dt)
{
if(m_this.m_active)
{
// Update time since last particle wave was spawned
m_timeSinceLast += p_dt;
if(m_timeSinceLast > m_this.m_emissionRate)
{
m_timeSinceLast = 0;
vector<XMFLOAT3> velocities;
vector<XMFLOAT3> positions;
vector<int> indices;
/// Time for more particles!
/// These particles will be spawned in a sort of grid (atm)
for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++)
{
for(int y = -m_this.m_density; y < m_this.m_density * 2; y++)
{
// Calculate angles in local space
float xAngle = (x / m_this.m_density) * m_this.m_emissionAreaDimensions.x;
float yAngle = (y / m_this.m_density) * m_this.m_emissionAreaDimensions.y;
// Define standard target in local space
XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1));
XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0);
particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal);
// Move velocity vector into world space
XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction));
particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld);
// Multiply with pressure
particleVelocityVec *= m_this.m_launchPressure;
// Store in vector
XMFLOAT3 velocity;
XMStoreFloat3(&velocity, particleVelocityVec);
velocities.push_back(velocity);
// Add position (only emitts from the center of the emitter atm
float launchOffset = 0.1;
XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position);
positionVec += launchOffset * particleVelocityVec;
XMFLOAT3 position;
XMStoreFloat3(&position, positionVec);
positions.push_back(position);
// Add index (silly way just to make it work atm)
indices.push_back(m_nextIndex);
m_nextIndex++;
}
}
if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) // no point doing things if there's no new particles
{
// Cast into PhysX datatypes
PxVec3* positionsPX = reinterpret_cast<PxVec3*>(&positions[0]);
PxVec3* velocitiesPX = reinterpret_cast<PxVec3*>(&velocities[0]);
PxU32* indicesPX = reinterpret_cast<PxU32*>(&indices[0]);
// Create the particles
PxParticleCreationData newParticlesData;
newParticlesData.numParticles = positions.size();
newParticlesData.positionBuffer = PxStrideIterator<const PxVec3>(positionsPX);
newParticlesData.velocityBuffer = PxStrideIterator<const PxVec3>(velocitiesPX);
newParticlesData.indexBuffer = PxStrideIterator<const PxU32>(indicesPX);
m_particleSystem->createParticles(newParticlesData);
}
else
{
// No new particles. Do nothing
}
}
}
}
}
}<commit_msg>Fixed float warning in ParticleEmitter.cpp DoremiEngine/Physics/Source/ParticleClasses/ParticleEmitter.cpp<commit_after>// This class
#include <Internal/ParticleClasses/ParticleEmitter.hpp>
//#include <FluidManager.hpp> // Included for the sake of particle data. Kinda silly, really
#include <Internal/PhysicsModuleImplementation.hpp>
using namespace DirectX;
using namespace physx;
namespace DoremiEngine
{
namespace Physics
{
ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils)
: m_this(p_data), m_utils(p_utils), m_timeSinceLast(0)
{
m_nextIndex = 0;
m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT);
m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE);
m_utils.m_worldScene->addActor(*m_particleSystem);
// Might be necessary to set flag to collide with dynamics
// m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true);
m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); // Should not be here
}
ParticleEmitter::~ParticleEmitter() {}
void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; }
void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; }
void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); }
void ParticleEmitter::GetPositions(vector<XMFLOAT3>& o_positions)
{
// This is a bit harder than it really ought to be...
PxParticleReadData* readData = m_particleSystem->lockParticleReadData();
PxStrideIterator<const PxVec3> positions = readData->positionBuffer;
PxStrideIterator<const PxVec3> velocities = readData->velocityBuffer;
PxStrideIterator<const PxParticleFlags> flags = readData->flagsBuffer;
vector<XMFLOAT3> velocitiesVector;
vector<int> indicesOfParticlesToBeReleased;
uint32_t numParticles = readData->validParticleRange;
for(uint32_t i = 0; i < numParticles; i++)
{
// Check if particles are supposed to be removed
if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) // | PxParticleFlag::eVALID))
{
indicesOfParticlesToBeReleased.push_back(i);
}
else if(flags[i] & PxParticleFlag::eVALID)
{
o_positions.push_back(XMFLOAT3(positions[i].x, positions[i].y, positions[i].z));
}
}
readData->unlock();
if(indicesOfParticlesToBeReleased.size() != 0)
{
PxStrideIterator<const PxU32> inicesPX(reinterpret_cast<PxU32*>(&indicesOfParticlesToBeReleased[0]));
m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX);
}
}
void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; }
void ParticleEmitter::Update(float p_dt)
{
if(m_this.m_active)
{
// Update time since last particle wave was spawned
m_timeSinceLast += p_dt;
if(m_timeSinceLast > m_this.m_emissionRate)
{
m_timeSinceLast = 0;
vector<XMFLOAT3> velocities;
vector<XMFLOAT3> positions;
vector<int> indices;
/// Time for more particles!
/// These particles will be spawned in a sort of grid (atm)
for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++)
{
for(int y = -m_this.m_density; y < m_this.m_density * 2; y++)
{
// Calculate angles in local space
float xAngle = (x / m_this.m_density) * m_this.m_emissionAreaDimensions.x;
float yAngle = (y / m_this.m_density) * m_this.m_emissionAreaDimensions.y;
// Define standard target in local space
XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1));
XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0);
particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal);
// Move velocity vector into world space
XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction));
particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld);
// Multiply with pressure
particleVelocityVec *= m_this.m_launchPressure;
// Store in vector
XMFLOAT3 velocity;
XMStoreFloat3(&velocity, particleVelocityVec);
velocities.push_back(velocity);
// Add position (only emitts from the center of the emitter atm
float launchOffset = 0.1f;
XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position);
positionVec += launchOffset * particleVelocityVec;
XMFLOAT3 position;
XMStoreFloat3(&position, positionVec);
positions.push_back(position);
// Add index (silly way just to make it work atm)
indices.push_back(m_nextIndex);
m_nextIndex++;
}
}
if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) // no point doing things if there's no new particles
{
// Cast into PhysX datatypes
PxVec3* positionsPX = reinterpret_cast<PxVec3*>(&positions[0]);
PxVec3* velocitiesPX = reinterpret_cast<PxVec3*>(&velocities[0]);
PxU32* indicesPX = reinterpret_cast<PxU32*>(&indices[0]);
// Create the particles
PxParticleCreationData newParticlesData;
newParticlesData.numParticles = positions.size();
newParticlesData.positionBuffer = PxStrideIterator<const PxVec3>(positionsPX);
newParticlesData.velocityBuffer = PxStrideIterator<const PxVec3>(velocitiesPX);
newParticlesData.indexBuffer = PxStrideIterator<const PxU32>(indicesPX);
m_particleSystem->createParticles(newParticlesData);
}
else
{
// No new particles. Do nothing
}
}
}
}
}
}<|endoftext|> |
<commit_before>/* This is both a sort of unit test, and a demonstration of how to use deadlock
* prevention.
*
* Suggested compilation command:
* c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread
*/
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>
#include "locking-container.hpp"
//use this definition if you want the simple test
#define THREAD_TYPE thread_multi
//use this definition if you want the multi-lock test
//#define THREAD_TYPE thread_multi
//(probably better as arguments, but I'm too lazy right now)
#define THREADS 10
#define TIME 30
//(if you set either of these to 'false', the threads will gradually die off)
#define READ_BLOCK true
#define WRITE_BLOCK true
//the data being protected (initialize the 'int' to 'THREADS')
typedef locking_container <int> protected_int;
static protected_int my_data(THREADS);
//(used by 'thread_multi')
static protected_int my_data2;
static null_container multi_lock;
static void send_output(const char *format, ...);
static void *thread(void *nv);
static void *thread_multi(void *nv);
int main()
{
//create some threads
pthread_t threads[THREADS];
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("start %li\n", i);
threads[i] = pthread_t();
if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) {
send_output("error: %s\n", strerror(errno));
}
}
//wait for them to do some stuff
sleep(TIME);
//the threads exit when the value goes below 0
{
protected_int::proxy write = my_data.get();
//(no clean way to exit if the container can't be locked)
assert(write);
*write = -1;
} //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()')
sleep(3);
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("?join %li\n", i);
pthread_join(threads[i], NULL);
send_output("+join %li\n", i);
}
}
//a print function that ensures we have exclusive access to the output
static void send_output(const char *format, ...) {
//protect the output file while we're at it
typedef locking_container <FILE*, w_lock> protected_out;
//(this is local so that it can't be involved in a deadlock)
static protected_out stdout2(stdout);
va_list ap;
va_start(ap, format);
//NOTE: authorization isn't important here because it's not possible for the
//caller to lock another container while it holds a lock on 'stdout2';
//deadlocks aren't an issue with respect to 'stdout2'
protected_out::proxy write = stdout2.get();
if (!write) return;
vfprintf(*write, format, ap);
}
//a simple thread for repeatedly accessing the data
static void *thread(void *nv) {
//(cancelation can be messy...)
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
//get an authorization object, to prevent deadlocks
//NOTE: for the most part you should be able to use any authorization type
//with any lock type, but the behavior will be the stricter of the two
lock_auth_base::auth_type auth(protected_int::new_auth());
long n = (long) nv, counter = 0;
struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 };
nanosleep(&wait, NULL);
//loop through reading and writing forever
while (true) {
//read a bunch of times
for (int i = 0; i < THREADS + n; i++) {
send_output("?read %li\n", n);
protected_int::const_proxy read = my_data.get_auth_const(auth, READ_BLOCK);
if (!read) {
send_output("!read %li\n", n);
return NULL;
}
send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read);
send_output("@read %li %i\n", n, !!my_data.get_auth_const(auth, READ_BLOCK));
if (*read < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
//(sort of like a contest, to see how many times each thread reads its own number)
if (*read == n) ++counter;
nanosleep(&wait, NULL);
read.clear();
send_output("-read %li\n", n);
nanosleep(&wait, NULL);
}
//write once
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_auth(auth, WRITE_BLOCK);
if (!write) {
send_output("!write %li\n", n);
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
send_output("@write %li %i\n", n, !!my_data.get_auth(auth, WRITE_BLOCK));
if (*write < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
}
//a more complicated thread that requires deadlock prevention, but multiple write locks at once
static void *thread_multi(void *nv) {
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
//NOTE: multi-locking will work with either 'lock_auth <w_lock>' or
//'lock_auth <rw_lock>'; however, 'lock_auth <w_lock>' will prevent a thread
//from holding mutiple read locks at a time when that thread doesn't hold the
//multi-lock.
protected_int::auth_type auth(new lock_auth <rw_lock>);
long n = (long) nv, success = 0, failure = 0;
struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 };
nanosleep(&wait, NULL);
while (true) {
for (int i = 0; i < THREADS + n; i++) {
send_output("?read0 %li\n", n);
protected_int::const_proxy read0 = my_data.get_multi_const(multi_lock, auth);
if (!read0) {
send_output("!read0 %li\n", n);
return NULL;
}
send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0);
if (*read0 < 0) {
send_output("diff %li %i %i\n", n, success, -failure);
return NULL;
}
nanosleep(&wait, NULL);
//NOTE: if the auth. type is 'lock_auth <w_lock>', this second read lock
//will always fail because 'multi_lock' is already in use! (this is because
//'lock_auth <w_lock>' records the lock above as a write lock; when an
//auth. object holds a write lock, it can only obtain new read or write
//locks if the container to be locked has no other locks.)
send_output("?read1 %li\n", n);
protected_int::const_proxy read1 = my_data2.get_multi_const(multi_lock, auth);
if (!read1) {
//(track the number of successes vs. failures for 'read1')
++failure;
send_output("!read1 %li\n", n);
//NOTE: due to deadlock prevention, 'auth' will reject a lock if another
//thread is waiting for a write lock for 'multi_lock' because this
//thread already holds a read lock (on 'my_data'). (this could easily
//lead to a deadlock if 'get_multi_const' above blocked.) this isn't a
//catastrophic error, so we just skip the operation here.
} else {
++success;
send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1);
if (*read1 < 0) {
send_output("diff %li %i %i\n", n, success, -failure);
return NULL;
}
nanosleep(&wait, NULL);
read1.clear();
send_output("-read1 %li\n", n);
}
read0.clear();
send_output("-read0 %li\n", n);
nanosleep(&wait, NULL);
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_multi(multi_lock, auth);
if (!write) {
send_output("!write %li\n", n);
//(this thread has no locks at this point, so 'get_multi' above should
//simply block if another thread is waiting for (or has) a write lock on
//'multi_lock'. a NULL return is therefore an error.)
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
if (*write < 0) {
send_output("diff %li %i %i\n", n, success, -failure);
return NULL;
}
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
//get a write lock on 'multi_lock'. this blocks until all other locks have
//been released (provided they were obtained with 'get_multi' or
//'get_multi_const' using 'multi_lock). this is mostly a way to appease
//'auth', because it's preventing deadlocks.
//NOTE: the lock will be rejected without blocking if this thread holds a
//lock on another object, because a deadlock could otherwise happen!
send_output("?multi0 %li\n", n);
null_container::proxy multi = multi_lock.get_auth(auth);
if (!multi) {
send_output("!multi0 %li\n", n);
return NULL;
}
send_output("+multi0 %li\n", n);
//NOTE: even though this thread holds a write lock on 'multi_lock', it will
//still allow new read locks from this thread. this is why 'get_multi' can
//be used below.
//NOTE: even if the auth. type is 'lock_auth <w_lock>', this thread should
//be able to obtain multiple write locks, since the containers aren't being
//used by any other threads.
send_output("?multi1 %li\n", n);
protected_int::proxy write1 = my_data.get_multi(multi_lock, auth);
if (!write1) {
send_output("!multi1 %li\n", n);
return NULL;
}
send_output("+multi1 %li\n", n);
if (*write1 < 0) return NULL;
//NOTE: this second write lock is only possible because this thread's write
//lock on 'multi_lock' ensures that nothing else currently holds a lock on
//'my_data2'. in fact, that's the only purpose of using 'multi_lock'!
send_output("?multi2 %li\n", n);
protected_int::proxy write2 = my_data2.get_multi(multi_lock, auth);
if (!write2) {
send_output("!multi2 %li\n", n);
return NULL;
}
send_output("+multi2 %li\n", n);
//NOTE: since 'get_multi' keeps track of new locks on 'my_data' and
//'my_data2', the write lock on 'multi_lock' can be cleared. this allows
//other threads to access those objects as they become free again.
multi.clear();
send_output("-multi0 %li\n", n);
*write1 = *write2 = 100 + n;
nanosleep(&wait, NULL);
write2.clear();
send_output("-multi2 %li\n", n);
write1.clear();
send_output("-multi1 %li\n", n);
}
}
<commit_msg>removed forgotten testing code<commit_after>/* This is both a sort of unit test, and a demonstration of how to use deadlock
* prevention.
*
* Suggested compilation command:
* c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread
*/
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>
#include "locking-container.hpp"
//use this definition if you want the simple test
#define THREAD_TYPE thread
//use this definition if you want the multi-lock test
//#define THREAD_TYPE thread_multi
//(probably better as arguments, but I'm too lazy right now)
#define THREADS 10
#define TIME 30
//(if you set either of these to 'false', the threads will gradually die off)
#define READ_BLOCK true
#define WRITE_BLOCK true
//the data being protected (initialize the 'int' to 'THREADS')
typedef locking_container <int> protected_int;
static protected_int my_data(THREADS);
//(used by 'thread_multi')
static protected_int my_data2;
static null_container multi_lock;
static void send_output(const char *format, ...);
static void *thread(void *nv);
static void *thread_multi(void *nv);
int main()
{
//create some threads
pthread_t threads[THREADS];
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("start %li\n", i);
threads[i] = pthread_t();
if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) {
send_output("error: %s\n", strerror(errno));
}
}
//wait for them to do some stuff
sleep(TIME);
//the threads exit when the value goes below 0
{
protected_int::proxy write = my_data.get();
//(no clean way to exit if the container can't be locked)
assert(write);
*write = -1;
} //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()')
sleep(3);
for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) {
send_output("?join %li\n", i);
pthread_join(threads[i], NULL);
send_output("+join %li\n", i);
}
}
//a print function that ensures we have exclusive access to the output
static void send_output(const char *format, ...) {
//protect the output file while we're at it
typedef locking_container <FILE*, w_lock> protected_out;
//(this is local so that it can't be involved in a deadlock)
static protected_out stdout2(stdout);
va_list ap;
va_start(ap, format);
//NOTE: authorization isn't important here because it's not possible for the
//caller to lock another container while it holds a lock on 'stdout2';
//deadlocks aren't an issue with respect to 'stdout2'
protected_out::proxy write = stdout2.get();
if (!write) return;
vfprintf(*write, format, ap);
}
//a simple thread for repeatedly accessing the data
static void *thread(void *nv) {
//(cancelation can be messy...)
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
//get an authorization object, to prevent deadlocks
//NOTE: for the most part you should be able to use any authorization type
//with any lock type, but the behavior will be the stricter of the two
lock_auth_base::auth_type auth(protected_int::new_auth());
long n = (long) nv, counter = 0;
struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 };
nanosleep(&wait, NULL);
//loop through reading and writing forever
while (true) {
//read a bunch of times
for (int i = 0; i < THREADS + n; i++) {
send_output("?read %li\n", n);
protected_int::const_proxy read = my_data.get_auth_const(auth, READ_BLOCK);
if (!read) {
send_output("!read %li\n", n);
return NULL;
}
send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read);
send_output("@read %li %i\n", n, !!my_data.get_auth_const(auth, READ_BLOCK));
if (*read < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
//(sort of like a contest, to see how many times each thread reads its own number)
if (*read == n) ++counter;
nanosleep(&wait, NULL);
read.clear();
send_output("-read %li\n", n);
nanosleep(&wait, NULL);
}
//write once
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_auth(auth, WRITE_BLOCK);
if (!write) {
send_output("!write %li\n", n);
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
send_output("@write %li %i\n", n, !!my_data.get_auth(auth, WRITE_BLOCK));
if (*write < 0) {
send_output("counter %li %i\n", n, counter);
return NULL;
}
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
}
//a more complicated thread that requires deadlock prevention, but multiple write locks at once
static void *thread_multi(void *nv) {
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
//NOTE: multi-locking will work with either 'lock_auth <w_lock>' or
//'lock_auth <rw_lock>'; however, 'lock_auth <w_lock>' will prevent a thread
//from holding mutiple read locks at a time when that thread doesn't hold the
//multi-lock.
protected_int::auth_type auth(new lock_auth <rw_lock>);
long n = (long) nv, success = 0, failure = 0;
struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 };
nanosleep(&wait, NULL);
while (true) {
for (int i = 0; i < THREADS + n; i++) {
send_output("?read0 %li\n", n);
protected_int::const_proxy read0 = my_data.get_multi_const(multi_lock, auth);
if (!read0) {
send_output("!read0 %li\n", n);
return NULL;
}
send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0);
if (*read0 < 0) {
send_output("diff %li %i %i\n", n, success, -failure);
return NULL;
}
nanosleep(&wait, NULL);
//NOTE: if the auth. type is 'lock_auth <w_lock>', this second read lock
//will always fail because 'multi_lock' is already in use! (this is because
//'lock_auth <w_lock>' records the lock above as a write lock; when an
//auth. object holds a write lock, it can only obtain new read or write
//locks if the container to be locked has no other locks.)
send_output("?read1 %li\n", n);
protected_int::const_proxy read1 = my_data2.get_multi_const(multi_lock, auth);
if (!read1) {
//(track the number of successes vs. failures for 'read1')
++failure;
send_output("!read1 %li\n", n);
//NOTE: due to deadlock prevention, 'auth' will reject a lock if another
//thread is waiting for a write lock for 'multi_lock' because this
//thread already holds a read lock (on 'my_data'). (this could easily
//lead to a deadlock if 'get_multi_const' above blocked.) this isn't a
//catastrophic error, so we just skip the operation here.
} else {
++success;
send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1);
if (*read1 < 0) {
send_output("diff %li %i %i\n", n, success, -failure);
return NULL;
}
nanosleep(&wait, NULL);
read1.clear();
send_output("-read1 %li\n", n);
}
read0.clear();
send_output("-read0 %li\n", n);
nanosleep(&wait, NULL);
send_output("?write %li\n", n);
protected_int::proxy write = my_data.get_multi(multi_lock, auth);
if (!write) {
send_output("!write %li\n", n);
//(this thread has no locks at this point, so 'get_multi' above should
//simply block if another thread is waiting for (or has) a write lock on
//'multi_lock'. a NULL return is therefore an error.)
return NULL;
}
send_output("+write %li (%i)\n", n, write.last_lock_count());
if (*write < 0) {
send_output("diff %li %i %i\n", n, success, -failure);
return NULL;
}
*write = n;
nanosleep(&wait, NULL);
write.clear();
send_output("-write %li\n", n);
nanosleep(&wait, NULL);
}
//get a write lock on 'multi_lock'. this blocks until all other locks have
//been released (provided they were obtained with 'get_multi' or
//'get_multi_const' using 'multi_lock). this is mostly a way to appease
//'auth', because it's preventing deadlocks.
//NOTE: the lock will be rejected without blocking if this thread holds a
//lock on another object, because a deadlock could otherwise happen!
send_output("?multi0 %li\n", n);
null_container::proxy multi = multi_lock.get_auth(auth);
if (!multi) {
send_output("!multi0 %li\n", n);
return NULL;
}
send_output("+multi0 %li\n", n);
//NOTE: even though this thread holds a write lock on 'multi_lock', it will
//still allow new read locks from this thread. this is why 'get_multi' can
//be used below.
//NOTE: even if the auth. type is 'lock_auth <w_lock>', this thread should
//be able to obtain multiple write locks, since the containers aren't being
//used by any other threads.
send_output("?multi1 %li\n", n);
protected_int::proxy write1 = my_data.get_multi(multi_lock, auth);
if (!write1) {
send_output("!multi1 %li\n", n);
return NULL;
}
send_output("+multi1 %li\n", n);
if (*write1 < 0) return NULL;
//NOTE: this second write lock is only possible because this thread's write
//lock on 'multi_lock' ensures that nothing else currently holds a lock on
//'my_data2'. in fact, that's the only purpose of using 'multi_lock'!
send_output("?multi2 %li\n", n);
protected_int::proxy write2 = my_data2.get_multi(multi_lock, auth);
if (!write2) {
send_output("!multi2 %li\n", n);
return NULL;
}
send_output("+multi2 %li\n", n);
//NOTE: since 'get_multi' keeps track of new locks on 'my_data' and
//'my_data2', the write lock on 'multi_lock' can be cleared. this allows
//other threads to access those objects as they become free again.
multi.clear();
send_output("-multi0 %li\n", n);
*write1 = *write2 = 100 + n;
nanosleep(&wait, NULL);
write2.clear();
send_output("-multi2 %li\n", n);
write1.clear();
send_output("-multi1 %li\n", n);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cxt2ary.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2007-11-02 16:50:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_CPP_CTX2ARY_HXX
#define ADC_CPP_CTX2ARY_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/cpp/inpcontx.hxx>
#include <doc_deal.hxx>
#include "pev.hxx"
#include "fevnthdl.hxx"
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace loc
{
class File;
}
}
namespace cpp
{
/** @descr
This class provides information about the context of an
CodeEntity, which is going to be stored in the repository.
The information is used mainly by class ary::cpp::Gate.
Also it provides information for the parser about actual
state of several public variables.
@todo
Include events, which allow correct storing of inline
documentation after enum values, parameters,
base classes.
*/
class ContextForAry : public ary::cpp::InputContext,
public cpp::PeEnvironment,
public cpp::FileScope_EventHandler,
public DocuDealer
{
public:
// LIFECYCLE
ContextForAry(
ary::cpp::Gate & io_rAryGate );
virtual ~ContextForAry();
// OPERATIONS
void ResetResult() { aTokenResult.Reset(); }
// INQUIRY
const TokenProcessing_Result &
CurResult() const { return aTokenResult; }
// ACCESS
TokenProcessing_Result &
CurResult() { return aTokenResult; }
private:
// Interface ary::cpp::InputContext:
virtual ary::loc::File &
inq_CurFile() const;
virtual ary::cpp::Namespace &
inq_CurNamespace() const;
virtual ary::cpp::Class *
inq_CurClass() const;
virtual ary::cpp::Enum *
inq_CurEnum() const;
virtual Owner & inq_CurOwner() const;
virtual ary::cpp::E_Protection
inq_CurProtection() const;
// Interface PeEnvironment
virtual void do_SetTokenResult(
E_TokenDone i_eDone,
E_EnvStackAction i_eWhat2DoWithEnvStack,
ParseEnvironment * i_pParseEnv2Push );
virtual void do_OpenNamespace(
ary::cpp::Namespace &
io_rOpenedNamespace );
virtual void do_OpenExternC(
bool i_bOnlyForOneDeclaration );
virtual void do_OpenClass(
ary::cpp::Class & io_rOpenedClass );
virtual void do_OpenEnum(
ary::cpp::Enum & io_rOpenedEnum );
virtual void do_CloseBlock();
virtual void do_CloseClass();
virtual void do_CloseEnum();
virtual void do_SetCurProtection(
ary::cpp::E_Protection
i_eProtection );
virtual void do_OpenTemplate(
const StringVector &
i_rParameters );
virtual DYN StringVector *
do_Get_CurTemplateParameters();
virtual void do_Close_OpenTemplate();
virtual void do_Event_Class_FinishedBase(
const String & i_sBaseName );
virtual void do_Event_Store_Typedef(
ary::cpp::Typedef & io_rTypedef );
virtual void do_Event_Store_EnumValue(
ary::cpp::EnumValue &
io_rEnumValue );
virtual void do_Event_Store_CppDefinition(
ary::cpp::DefineEntity &
io_rDefinition );
virtual void do_Event_EnterFunction_ParameterList();
virtual void do_Event_Function_FinishedParameter(
const String & i_sParameterName );
virtual void do_Event_LeaveFunction_ParameterList();
virtual void do_Event_EnterFunction_Implementation();
virtual void do_Event_LeaveFunction_Implementation();
virtual void do_Event_Store_Function(
ary::cpp::Function &
io_rFunction );
virtual void do_Event_Store_Variable(
ary::cpp::Variable &
io_rVariable );
virtual void do_TakeDocu(
DYN ary::doc::OldCppDocu &
let_drInfo );
virtual void do_StartWaitingFor_Recovery();
virtual ary::cpp::Gate &
inq_AryGate() const;
virtual const ary::cpp::InputContext &
inq_Context() const;
virtual String inq_CurFileName() const;
virtual uintt inq_LineCount() const;
virtual bool inq_IsWaitingFor_Recovery() const;
virtual bool inq_IsExternC() const;
// Interface FileScope_EventHandler
virtual void do_SetCurFile(
ary::loc::File & io_rCurFile );
virtual void do_Event_IncrLineCount();
virtual void do_Event_SwBracketOpen();
virtual void do_Event_SwBracketClose();
virtual void do_Event_Semicolon();
// Local types
struct S_FileScopeInfo;
struct S_OwnerStack;
struct S_DocuDistributor;
struct S_RecoveryGuard;
// DATA
ary::cpp::Gate * pGate;
TokenProcessing_Result
aTokenResult;
Dyn<S_FileScopeInfo>
pFileScopeInfo;
Dyn<S_OwnerStack> pOwnerStack;
Dyn<S_DocuDistributor>
pDocuDistributor;
Dyn<S_RecoveryGuard>
pRecoveryGuard;
};
} // namespace cpp
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.22); FILE MERGED 2008/03/28 16:02:23 rt 1.4.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cxt2ary.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef ADC_CPP_CTX2ARY_HXX
#define ADC_CPP_CTX2ARY_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/cpp/inpcontx.hxx>
#include <doc_deal.hxx>
#include "pev.hxx"
#include "fevnthdl.hxx"
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace loc
{
class File;
}
}
namespace cpp
{
/** @descr
This class provides information about the context of an
CodeEntity, which is going to be stored in the repository.
The information is used mainly by class ary::cpp::Gate.
Also it provides information for the parser about actual
state of several public variables.
@todo
Include events, which allow correct storing of inline
documentation after enum values, parameters,
base classes.
*/
class ContextForAry : public ary::cpp::InputContext,
public cpp::PeEnvironment,
public cpp::FileScope_EventHandler,
public DocuDealer
{
public:
// LIFECYCLE
ContextForAry(
ary::cpp::Gate & io_rAryGate );
virtual ~ContextForAry();
// OPERATIONS
void ResetResult() { aTokenResult.Reset(); }
// INQUIRY
const TokenProcessing_Result &
CurResult() const { return aTokenResult; }
// ACCESS
TokenProcessing_Result &
CurResult() { return aTokenResult; }
private:
// Interface ary::cpp::InputContext:
virtual ary::loc::File &
inq_CurFile() const;
virtual ary::cpp::Namespace &
inq_CurNamespace() const;
virtual ary::cpp::Class *
inq_CurClass() const;
virtual ary::cpp::Enum *
inq_CurEnum() const;
virtual Owner & inq_CurOwner() const;
virtual ary::cpp::E_Protection
inq_CurProtection() const;
// Interface PeEnvironment
virtual void do_SetTokenResult(
E_TokenDone i_eDone,
E_EnvStackAction i_eWhat2DoWithEnvStack,
ParseEnvironment * i_pParseEnv2Push );
virtual void do_OpenNamespace(
ary::cpp::Namespace &
io_rOpenedNamespace );
virtual void do_OpenExternC(
bool i_bOnlyForOneDeclaration );
virtual void do_OpenClass(
ary::cpp::Class & io_rOpenedClass );
virtual void do_OpenEnum(
ary::cpp::Enum & io_rOpenedEnum );
virtual void do_CloseBlock();
virtual void do_CloseClass();
virtual void do_CloseEnum();
virtual void do_SetCurProtection(
ary::cpp::E_Protection
i_eProtection );
virtual void do_OpenTemplate(
const StringVector &
i_rParameters );
virtual DYN StringVector *
do_Get_CurTemplateParameters();
virtual void do_Close_OpenTemplate();
virtual void do_Event_Class_FinishedBase(
const String & i_sBaseName );
virtual void do_Event_Store_Typedef(
ary::cpp::Typedef & io_rTypedef );
virtual void do_Event_Store_EnumValue(
ary::cpp::EnumValue &
io_rEnumValue );
virtual void do_Event_Store_CppDefinition(
ary::cpp::DefineEntity &
io_rDefinition );
virtual void do_Event_EnterFunction_ParameterList();
virtual void do_Event_Function_FinishedParameter(
const String & i_sParameterName );
virtual void do_Event_LeaveFunction_ParameterList();
virtual void do_Event_EnterFunction_Implementation();
virtual void do_Event_LeaveFunction_Implementation();
virtual void do_Event_Store_Function(
ary::cpp::Function &
io_rFunction );
virtual void do_Event_Store_Variable(
ary::cpp::Variable &
io_rVariable );
virtual void do_TakeDocu(
DYN ary::doc::OldCppDocu &
let_drInfo );
virtual void do_StartWaitingFor_Recovery();
virtual ary::cpp::Gate &
inq_AryGate() const;
virtual const ary::cpp::InputContext &
inq_Context() const;
virtual String inq_CurFileName() const;
virtual uintt inq_LineCount() const;
virtual bool inq_IsWaitingFor_Recovery() const;
virtual bool inq_IsExternC() const;
// Interface FileScope_EventHandler
virtual void do_SetCurFile(
ary::loc::File & io_rCurFile );
virtual void do_Event_IncrLineCount();
virtual void do_Event_SwBracketOpen();
virtual void do_Event_SwBracketClose();
virtual void do_Event_Semicolon();
// Local types
struct S_FileScopeInfo;
struct S_OwnerStack;
struct S_DocuDistributor;
struct S_RecoveryGuard;
// DATA
ary::cpp::Gate * pGate;
TokenProcessing_Result
aTokenResult;
Dyn<S_FileScopeInfo>
pFileScopeInfo;
Dyn<S_OwnerStack> pOwnerStack;
Dyn<S_DocuDistributor>
pDocuDistributor;
Dyn<S_RecoveryGuard>
pRecoveryGuard;
};
} // namespace cpp
#endif
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <SDL/SDL.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
extern "C" int main(int argc, char** argv) {
printf("hello, world!\n");
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
#ifdef TEST_SDL_LOCK_OPTS
EM_ASM("SDL.defaults.copyOnLock = false; SDL.defaults.discardOnLock = true; SDL.defaults.opaqueFrontBuffer = false;");
#endif
if (SDL_MUSTLOCK(screen)) SDL_LockSurface(screen);
for (int i = 0; i < 256; i++) {
for (int j = 0; j < 256; j++) {
#ifdef TEST_SDL_LOCK_OPTS
// Alpha behaves like in the browser, so write proper opaque pixels.
int alpha = 255;
#else
// To emulate native behavior with blitting to screen, alpha component is ignored. Test that it is so by outputting
// data (and testing that it does get discarded)
int alpha = (i+j) % 255;
#endif
*((Uint32*)screen->pixels + i * 256 + j) = SDL_MapRGBA(screen->format, i, j, 255-i, alpha);
}
}
if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen);
SDL_Flip(screen);
printf("you should see a smoothly-colored square - no sharp lines but the square borders!\n");
printf("and here is some text that should be HTML-friendly: amp: |&| double-quote: |\"| quote: |'| less-than, greater-than, html-like tags: |<cheez></cheez>|\nanother line.\n");
SDL_Quit();
return 0;
}
<commit_msg>render test floor<commit_after>#include <stdio.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#define TILE_W 64
#define TILE_H 32
void project(float x, float y, float z, int* dx, int *dy) {
*dx = x * (TILE_W/2) - y * (TILE_W/2);
*dy = x * (TILE_H/2) + y * (TILE_H/2) - z;
}
extern "C" int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface *screen = SDL_SetVideoMode(1024,768, 32, SDL_SWSURFACE);
SDL_Surface *image = IMG_Load("./img/floor1.png");
if (!image)
{
printf("IMG_Load: %s\n", IMG_GetError());
return 0;
}
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
SDL_Rect dst;
dst.w = image->w;
dst.h = image->h;
project(x, y, 0, &dst.x, &dst.y);
dst.x += 512;
SDL_BlitSurface (image, NULL, screen, &dst);
}
}
SDL_Flip(screen);
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Some tests of Euler's Totient Function phi.
*
* Copyright (c) 2012 Christian Stigen Larsen
* http://csl.sublevel3.org
*
* Distributed under the BSD 3-clause license; see the file LICENSE.
*/
#include <iostream>
#include <inttypes.h>
#include <cassert>
#include "phi.h"
using namespace std;
void test1()
{
int n = phi<100>(12);
assert(n == 4);
}
void test2()
{
#define LIMIT1 1000000
cout << "Calculating " << 10*(LIMIT1) << " prime numbers" << endl;
for ( uint64_t n=0; n < LIMIT1; n += 56789 ) {
cout << "phi(" << n << ") = "
<< phi<10*LIMIT1>(n) << endl;
}
#define LIMIT2 10000000
cout << endl;
cout << "Calculating " << 10*(LIMIT2) << " prime numbers" << endl;
for ( uint64_t n=1000000; n < LIMIT2; n += 1122334/2 ) {
cout << "phi(" << n << ") = "
<< phi<10*LIMIT2>(n) << endl;
}
}
int main()
{
test1();
test2();
return 0;
}
<commit_msg>Faster test<commit_after>/*
* Some tests of Euler's Totient Function phi.
*
* Copyright (c) 2012 Christian Stigen Larsen
* http://csl.sublevel3.org
*
* Distributed under the BSD 3-clause license; see the file LICENSE.
*/
#include <iostream>
#include <inttypes.h>
#include <cassert>
#include "phi.h"
using namespace std;
void test1()
{
int n = phi<100>(12);
assert(n == 4);
}
void test2()
{
#define LIMIT 10000000
cout << "Calculating " << 10*(LIMIT) << " prime numbers" << endl;
for ( uint64_t n=0; n < LIMIT/10; n += 56789 ) {
cout << "phi(" << n << ") = "
<< phi<LIMIT>(n) << endl;
}
for ( uint64_t n=1000000; n < LIMIT; n += 1122334/2 ) {
cout << "phi(" << n << ") = "
<< phi<LIMIT>(n) << endl;
}
}
int main()
{
test1();
test2();
return 0;
}
<|endoftext|> |
<commit_before>/*
* nnet test
* 2016.06.06
* author:soma62jp
* */
#include "test.h"
using namespace std;
nnet::nnet(int inputnum,int hiddennum,int outputnum,int patternnum):
inputnum(inputnum)
,hiddennum(hiddennum)
,outputnum(outputnum)
,patternnum(patternnum)
,Eta(0.75)
,Alpha(0.8)
,ErrorEv(0.001)
,Rlow(-0.30)
,Rhigh(0.30)
,MaxGen(10000)
{
//this->inputnum=inputnum;
//this->hiddennum=hiddennum;
//this->outputnum=outputnum;
X_h = new double[hiddennum];
X_o = new double[outputnum];
bias_h = new double[hiddennum];
bias_o = new double[outputnum];
bias_h_prev = new double[hiddennum];
bias_o_prev = new double[outputnum];
// pattern*input
X_i = new double*[patternnum];
for(int i=0;i<patternnum;i++){
X_i[i] = new double[inputnum];
}
// pattern*output
T_signal = new double*[patternnum];
for(int i=0;i<patternnum;i++){
T_signal[i] = new double[outputnum];
}
// hidden*input
W_itoh = new double*[hiddennum];
for(int i=0;i<hiddennum;i++){
W_itoh[i] = new double[inputnum];
}
W_itoh_prev = new double*[hiddennum];
for(int i=0;i<hiddennum;i++){
W_itoh_prev[i] = new double[inputnum];
}
// output*hidden
W_htoo = new double*[outputnum];
for(int i=0;i<outputnum;i++){
W_htoo[i] = new double[hiddennum];
}
W_htoo_prev = new double*[outputnum];
for(int i=0;i<outputnum;i++){
W_htoo_prev[i] = new double[hiddennum];
}
//initialize parameter
srand((unsigned int)time(NULL));
for(int i=0;i<hiddennum;i++){
for(int j=0;j<inputnum;j++){
W_itoh[i][j]=urand();
}
}
for(int i=0;i<outputnum;i++){
for(int j=0;j<hiddennum;j++){
W_htoo[i][j]=urand();
}
}
for(int i=0;i<hiddennum;i++){
bias_h[i] = 0;
}
for(int i=0;i<outputnum;i++){
bias_o[i] = 0;
}
}
nnet::~nnet()
{
delete [] X_h;
delete [] X_o;
delete [] bias_h;
delete [] bias_o;
delete [] bias_h_prev;
delete [] bias_o_prev;
for( int i=0; i<patternnum; i++ ) {
delete[] X_i[i];
}
delete [] X_i;
for( int i=0; i<patternnum; i++ ) {
delete[] T_signal[i];
}
delete [] T_signal;
for( int i=0; i<hiddennum; i++ ) {
delete[] W_itoh[i];
}
delete [] W_itoh;
for( int i=0; i<hiddennum; i++ ) {
delete[] W_itoh_prev[i];
}
delete [] W_itoh_prev;
for( int i=0; i<outputnum; i++ ) {
delete [] W_htoo[i];
}
delete [] W_htoo;
for( int i=0; i<outputnum; i++ ) {
delete [] W_htoo_prev[i];
}
delete [] W_htoo_prev;
}
void nnet::foward_propagation(const int pnum)
{
int i,j;
double sum;
// 入力層ー>隠れ層
for(i=0;i<hiddennum;i++){
sum=0;
for(j=0;j<inputnum;j++){
// 重み×入力値
sum+=W_itoh[i][j]*X_i[pnum][j];
}
// 重み×入力値の総和にバイアス項を足してアクティベーション関数に通したものが中間層入力
X_h[i] = activationFunc(sum+bias_h[i]);
}
// 隠れ層ー>出力層
for(i=0;i<outputnum;i++){
sum=0;
for(j=0;j<hiddennum;j++){
// 重み×中間層入力
sum+=W_htoo[i][j]*X_h[j];
}
// 重み×中間層入力値の総和にバイアス項を足してアクティベーション関数に通したものが出力層
X_o[i]=activationFunc(sum+bias_o[i]);
}
}
void nnet::back_propagation(const int pnum)
{
int i,j;
double sum;
double *dwih = new double[hiddennum]; // 隠れ層での学習信号
double *dwho = new double[outputnum]; // 出力層での学習信号
// 出力層の学習信号から計算
for(i=0;i<outputnum;i++){
// 出力層での学習信号=(教師信号-出力) * f'(出力)
// f'(出力)はシグモイド関数の微分
dwho[i]=(T_signal[pnum][i]-X_o[i]) * activationFunc_diff(X_o[i]);
}
// 重みの変化量[隠れ層ー>出力層]を計算
// 隠れ層の学習信号を計算
for(i=0;i<hiddennum;i++){
sum=0;
for(j=0;j<outputnum;j++){
// 前回の重みの変化量[隠れ層->出力層] = η * 出力層での学習信号 * 隠れ層出力 * α * 前回の重みの変化量[隠れ層->出力層]
W_htoo_prev[j][i]=Eta*dwho[j]*X_h[i]+Alpha*W_htoo_prev[j][i];
// 重みの変化量[隠れ層ー>出力層] = 重みの変化量[隠れ層ー>出力層] + 前回の重みの変化量[隠れ層ー>出力層]
W_htoo[j][i]+=W_htoo_prev[j][i];
// 出力層での学習信号 * 重みの変化量[隠れ層ー>出力層]
sum += dwho[j]*W_htoo[j][i];
}
// 隠れ層での学習信号 = f'(隠れ層出力) * sum
dwih[i]=activationFunc_diff(X_h[i])*sum;
}
// 出力層のバイアス項を計算
for(i=0;i<outputnum;i++){
// 前回のバイアス項[出力層] = η * 出力層での学習信号 + α * 前回のバイアス項[出力層]
bias_o_prev[i] = Eta*dwho[i]+Alpha*bias_o_prev[i];
// 出力層バイアス項[出力層] = 出力層バイアス項[出力層] + 前回の出力層バイアス項[出力層]
bias_o[i]+=bias_o_prev[i];
}
// 重みの変化量[入力層ー>隠れ層]を計算
for(i=0;i<inputnum;i++){
for(j=0;j<hiddennum;j++){
// 前回の重みの変化量[入力層ー>隠れ層] = η * 隠れ層での学習信号 * 入力層出力 * α * 前回の重みの変化量[入力層ー>隠れ層]
W_itoh_prev[j][i]=Eta*dwih[j]*X_i[pnum][i]+Alpha*W_itoh_prev[j][i];
// 重みの変化量[入力層ー>隠れ層] = 重みの変化量[入力層ー>隠れ層] + 前回の重みの変化量[入力層ー>隠れ層]
W_itoh[j][i]+=W_itoh_prev[j][i];
}
}
// 隠れ層のバイアス項を計算
for(i=0;i<hiddennum;i++){
// 前回のバイアス項[隠れ層] = η * 隠れ層での学習信号 + α * 前回のバイアス項[隠れ層]
bias_h_prev[i]=Eta*dwih[i]+Alpha*bias_h_prev[i];
// 出力層バイアス項[隠れ層] = 出力層バイアス項[隠れ層] + 前回の出力層バイアス項[隠れ層]
bias_h[i]+=bias_h_prev[i];
}
delete dwih;
delete dwho;
}
void nnet::setInData(const int pnum,const int i,const double value)
{
if(pnum>=patternnum || i>=inputnum){
cout << "can't set Indata." << endl;
exit(1);
}
X_i[pnum][i] = value;
}
void nnet::setTeachData(const int pnum,const int i,const double value)
{
if(pnum>=patternnum || i>=outputnum){
cout << "can't set Teachdata." << endl;
exit(1);
}
T_signal[pnum][i] = value;
}
void nnet::setPredictData(const int i,const double value)
{
if(i>=inputnum){
cout << "can't set Predictdata." << endl;
exit(1);
}
X_i[patternnum-1][i] = value;
}
void nnet::train()
{
double verror;
int gen;
int i,j,ip;
gen = 0;
verror = 20.0;
while((verror > ErrorEv) && (gen < MaxGen))
{
gen++;
// foward and back propagation
for(i=0;i<patternnum;i++){
ip = patternnum * random();
foward_propagation(ip);
back_propagation(ip);
}
// error calc
verror = 0;
for(i=0;i<patternnum;i++){
foward_propagation(i);
for(j=0;j<outputnum;j++){
verror+=pow((T_signal[i][j] - X_o[j]) * 0.5 ,2.0);
}
}
verror /= (double)patternnum;
cout << verror << endl;
}
}
void nnet::predict()
{
int i;
foward_propagation(patternnum-1);
for(i=0;i<outputnum;i++){
cout << X_o[i] << endl;
}
}
double nnet::random()
{
double r;
int i;
i = rand();
if (i != 0)
i--;
r = (double)i / RAND_MAX;
return (r);
}
int main()
{
nnet net(2,2,1,4);
net.setInData(0,0,0);
net.setInData(0,1,0);
net.setTeachData(0,0,0);
net.setInData(1,0,1);
net.setInData(1,1,1);
net.setTeachData(1,0,0);
net.setInData(2,0,1);
net.setInData(2,1,0);
net.setTeachData(2,0,1);
net.setInData(3,0,0);
net.setInData(3,1,1);
net.setTeachData(3,0,1);
net.train();
cout << "-- Predict 00 --" << endl;
net.setPredictData(0,0);
net.setPredictData(1,0);
net.predict();
cout << "-- Predict 01 --" << endl;
net.setPredictData(0,0);
net.setPredictData(1,1);
net.predict();
cout << "-- Predict 10 --" << endl;
net.setPredictData(0,1);
net.setPredictData(1,0);
net.predict();
cout << "-- Predict 11 --" << endl;
net.setPredictData(0,1);
net.setPredictData(1,1);
net.predict();
}
<commit_msg>modifyed<commit_after>/*
* nnet test
* 2016.06.06
* author:soma62jp
* */
#include "test.h"
using namespace std;
nnet::nnet(int inputnum,int hiddennum,int outputnum,int patternnum):
inputnum(inputnum)
,hiddennum(hiddennum)
,outputnum(outputnum)
,patternnum(patternnum)
,Eta(0.75)
,Alpha(0.8)
,ErrorEv(0.001)
,Rlow(-0.30)
,Rhigh(0.30)
,MaxGen(10000)
{
//this->inputnum=inputnum;
//this->hiddennum=hiddennum;
//this->outputnum=outputnum;
X_h = new double[hiddennum];
X_o = new double[outputnum];
bias_h = new double[hiddennum];
bias_o = new double[outputnum];
bias_h_prev = new double[hiddennum];
bias_o_prev = new double[outputnum];
// pattern*input
X_i = new double*[patternnum];
for(int i=0;i<patternnum;i++){
X_i[i] = new double[inputnum];
}
// pattern*output
T_signal = new double*[patternnum];
for(int i=0;i<patternnum;i++){
T_signal[i] = new double[outputnum];
}
// hidden*input
W_itoh = new double*[hiddennum];
for(int i=0;i<hiddennum;i++){
W_itoh[i] = new double[inputnum];
}
W_itoh_prev = new double*[hiddennum];
for(int i=0;i<hiddennum;i++){
W_itoh_prev[i] = new double[inputnum];
}
// output*hidden
W_htoo = new double*[outputnum];
for(int i=0;i<outputnum;i++){
W_htoo[i] = new double[hiddennum];
}
W_htoo_prev = new double*[outputnum];
for(int i=0;i<outputnum;i++){
W_htoo_prev[i] = new double[hiddennum];
}
//initialize parameter
srand((unsigned int)time(NULL));
for(int i=0;i<hiddennum;i++){
for(int j=0;j<inputnum;j++){
W_itoh[i][j]=urand();
}
}
for(int i=0;i<outputnum;i++){
for(int j=0;j<hiddennum;j++){
W_htoo[i][j]=urand();
}
}
for(int i=0;i<hiddennum;i++){
bias_h[i] = 0;
}
for(int i=0;i<outputnum;i++){
bias_o[i] = 0;
}
}
nnet::~nnet()
{
delete [] X_h;
delete [] X_o;
delete [] bias_h;
delete [] bias_o;
delete [] bias_h_prev;
delete [] bias_o_prev;
for( int i=0; i<patternnum; i++ ) {
delete[] X_i[i];
}
delete [] X_i;
for( int i=0; i<patternnum; i++ ) {
delete[] T_signal[i];
}
delete [] T_signal;
for( int i=0; i<hiddennum; i++ ) {
delete[] W_itoh[i];
}
delete [] W_itoh;
for( int i=0; i<hiddennum; i++ ) {
delete[] W_itoh_prev[i];
}
delete [] W_itoh_prev;
for( int i=0; i<outputnum; i++ ) {
delete [] W_htoo[i];
}
delete [] W_htoo;
for( int i=0; i<outputnum; i++ ) {
delete [] W_htoo_prev[i];
}
delete [] W_htoo_prev;
}
void nnet::foward_propagation(const int pnum)
{
int i,j;
double sum;
// 入力層ー>隠れ層
for(i=0;i<hiddennum;i++){
sum=0;
for(j=0;j<inputnum;j++){
// 重み×入力値
sum+=W_itoh[i][j]*X_i[pnum][j];
}
// 重み×入力値の総和にバイアス項を足してアクティベーション関数に通したものが中間層入力
X_h[i] = activationFunc(sum+bias_h[i]);
}
// 隠れ層ー>出力層
for(i=0;i<outputnum;i++){
sum=0;
for(j=0;j<hiddennum;j++){
// 重み×中間層入力
sum+=W_htoo[i][j]*X_h[j];
}
// 重み×中間層入力値の総和にバイアス項を足してアクティベーション関数に通したものが出力層
X_o[i]=activationFunc(sum+bias_o[i]);
}
}
void nnet::back_propagation(const int pnum)
{
int i,j;
double sum;
double *dwih = new double[hiddennum]; // 隠れ層での学習信号
double *dwho = new double[outputnum]; // 出力層での学習信号
// 出力層の学習信号から計算
for(i=0;i<outputnum;i++){
// 出力層での学習信号=(教師信号-出力) * f'(出力)
// f'(出力)はシグモイド関数の微分
dwho[i]=(T_signal[pnum][i]-X_o[i]) * activationFunc_diff(X_o[i]);
}
// 重みの変化量[隠れ層ー>出力層]を計算
// 隠れ層の学習信号を計算
for(i=0;i<hiddennum;i++){
sum=0;
for(j=0;j<outputnum;j++){
// 前回の重みの変化量[隠れ層->出力層] = η * 出力層での学習信号 * 隠れ層出力 * α * 前回の重みの変化量[隠れ層->出力層]
W_htoo_prev[j][i]=Eta*dwho[j]*X_h[i]+Alpha*W_htoo_prev[j][i];
// 重みの変化量[隠れ層ー>出力層] = 重みの変化量[隠れ層ー>出力層] + 前回の重みの変化量[隠れ層ー>出力層]
W_htoo[j][i]+=W_htoo_prev[j][i];
// 出力層での学習信号 * 重みの変化量[隠れ層ー>出力層]
sum += dwho[j]*W_htoo[j][i];
}
// 隠れ層での学習信号 = f'(隠れ層出力) * sum
dwih[i]=activationFunc_diff(X_h[i])*sum;
}
// 出力層のバイアス項を計算
for(i=0;i<outputnum;i++){
// 前回のバイアス項[出力層] = η * 出力層での学習信号 + α * 前回のバイアス項[出力層]
bias_o_prev[i] = Eta*dwho[i]+Alpha*bias_o_prev[i];
// 出力層バイアス項[出力層] = 出力層バイアス項[出力層] + 前回の出力層バイアス項[出力層]
bias_o[i]+=bias_o_prev[i];
}
// 重みの変化量[入力層ー>隠れ層]を計算
for(i=0;i<inputnum;i++){
for(j=0;j<hiddennum;j++){
// 前回の重みの変化量[入力層ー>隠れ層] = η * 隠れ層での学習信号 * 入力層出力 * α * 前回の重みの変化量[入力層ー>隠れ層]
W_itoh_prev[j][i]=Eta*dwih[j]*X_i[pnum][i]+Alpha*W_itoh_prev[j][i];
// 重みの変化量[入力層ー>隠れ層] = 重みの変化量[入力層ー>隠れ層] + 前回の重みの変化量[入力層ー>隠れ層]
W_itoh[j][i]+=W_itoh_prev[j][i];
}
}
// 隠れ層のバイアス項を計算
for(i=0;i<hiddennum;i++){
// 前回のバイアス項[隠れ層] = η * 隠れ層での学習信号 + α * 前回のバイアス項[隠れ層]
bias_h_prev[i]=Eta*dwih[i]+Alpha*bias_h_prev[i];
// 出力層バイアス項[隠れ層] = 出力層バイアス項[隠れ層] + 前回の出力層バイアス項[隠れ層]
bias_h[i]+=bias_h_prev[i];
}
delete [] dwih;
delete [] dwho;
}
void nnet::setInData(const int pnum,const int i,const double value)
{
if(pnum>=patternnum || i>=inputnum){
cout << "can't set Indata." << endl;
exit(1);
}
X_i[pnum][i] = value;
}
void nnet::setTeachData(const int pnum,const int i,const double value)
{
if(pnum>=patternnum || i>=outputnum){
cout << "can't set Teachdata." << endl;
exit(1);
}
T_signal[pnum][i] = value;
}
void nnet::setPredictData(const int i,const double value)
{
if(i>=inputnum){
cout << "can't set Predictdata." << endl;
exit(1);
}
X_i[patternnum-1][i] = value;
}
void nnet::train()
{
double verror;
int gen;
int i,j,ip;
gen = 0;
verror = 20.0;
while((verror > ErrorEv) && (gen < MaxGen))
{
gen++;
// foward and back propagation
for(i=0;i<patternnum;i++){
ip = patternnum * random();
foward_propagation(ip);
back_propagation(ip);
}
// error calc
verror = 0;
for(i=0;i<patternnum;i++){
foward_propagation(i);
for(j=0;j<outputnum;j++){
verror+=pow((T_signal[i][j] - X_o[j]) * 0.5 ,2.0);
}
}
verror /= (double)patternnum;
cout << verror << endl;
}
}
void nnet::predict()
{
int i;
foward_propagation(patternnum-1);
for(i=0;i<outputnum;i++){
cout << X_o[i] << endl;
}
}
double nnet::random()
{
double r;
int i;
i = rand();
if (i != 0)
i--;
r = (double)i / RAND_MAX;
return (r);
}
int main()
{
nnet net(2,4,1,4);
net.setInData(0,0,0);
net.setInData(0,1,0);
net.setTeachData(0,0,0);
net.setInData(1,0,1);
net.setInData(1,1,1);
net.setTeachData(1,0,0);
net.setInData(2,0,1);
net.setInData(2,1,0);
net.setTeachData(2,0,1);
net.setInData(3,0,0);
net.setInData(3,1,1);
net.setTeachData(3,0,1);
net.train();
cout << "-- Predict 00 --" << endl;
net.setPredictData(0,0);
net.setPredictData(1,0);
net.predict();
cout << "-- Predict 01 --" << endl;
net.setPredictData(0,0);
net.setPredictData(1,1);
net.predict();
cout << "-- Predict 10 --" << endl;
net.setPredictData(0,1);
net.setPredictData(1,0);
net.predict();
cout << "-- Predict 11 --" << endl;
net.setPredictData(0,1);
net.setPredictData(1,1);
net.predict();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediawindow.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <cstdio>
#include <avmedia/mediawindow.hxx>
#include "mediawindow_impl.hxx"
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/pathoptions.hxx>
#include <sfx2/filedlghelper.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#define AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME 3.0
using namespace ::com::sun::star;
namespace avmedia {
// ---------------
// - MediaWindow -
// ---------------
MediaWindow::MediaWindow( Window* parent, bool bInternalMediaControl ) :
mpImpl( new priv::MediaWindowImpl( parent, this, bInternalMediaControl ) )
{
mpImpl->Show();
}
// -------------------------------------------------------------------------
MediaWindow::~MediaWindow()
{
mpImpl->cleanUp();
delete mpImpl;
mpImpl = NULL;
}
// -------------------------------------------------------------------------
void MediaWindow::setURL( const ::rtl::OUString& rURL )
{
if( mpImpl )
mpImpl->setURL( rURL );
}
// -------------------------------------------------------------------------
const ::rtl::OUString& MediaWindow::getURL() const
{
return mpImpl->getURL();
}
// -------------------------------------------------------------------------
bool MediaWindow::isValid() const
{
return( mpImpl != NULL && mpImpl->isValid() );
}
// -------------------------------------------------------------------------
void MediaWindow::MouseMove( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonDown( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonUp( const MouseEvent& /* rMEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyInput( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyUp( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::Command( const CommandEvent& /* rCEvt */ )
{
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::AcceptDrop( const AcceptDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::ExecuteDrop( const ExecuteDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
void MediaWindow::StartDrag( sal_Int8 /* nAction */, const Point& /* rPosPixel */ )
{
}
// -------------------------------------------------------------------------
bool MediaWindow::hasPreferredSize() const
{
return( mpImpl != NULL && mpImpl->hasPreferredSize() );
}
// -------------------------------------------------------------------------
Size MediaWindow::getPreferredSize() const
{
return mpImpl->getPreferredSize();
}
// -------------------------------------------------------------------------
void MediaWindow::setPosSize( const Rectangle& rNewRect )
{
if( mpImpl )
mpImpl->setPosSize( rNewRect );
}
// -------------------------------------------------------------------------
Rectangle MediaWindow::getPosSize() const
{
return Rectangle( mpImpl->GetPosPixel(), mpImpl->GetSizePixel() );
}
// -------------------------------------------------------------------------
void MediaWindow::setPointer( const Pointer& rPointer )
{
if( mpImpl )
mpImpl->setPointer( rPointer );
}
// -------------------------------------------------------------------------
const Pointer& MediaWindow::getPointer() const
{
return mpImpl->getPointer();
}
// -------------------------------------------------------------------------
bool MediaWindow::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
return( mpImpl != NULL && mpImpl->setZoom( eLevel ) );
}
// -------------------------------------------------------------------------
::com::sun::star::media::ZoomLevel MediaWindow::getZoom() const
{
return mpImpl->getZoom();
}
// -------------------------------------------------------------------------
bool MediaWindow::start()
{
return( mpImpl != NULL && mpImpl->start() );
}
// -------------------------------------------------------------------------
void MediaWindow::stop()
{
if( mpImpl )
mpImpl->stop();
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaying() const
{
return( mpImpl != NULL && mpImpl->isPlaying() );
}
// -------------------------------------------------------------------------
double MediaWindow::getDuration() const
{
return mpImpl->getDuration();
}
// -------------------------------------------------------------------------
void MediaWindow::setMediaTime( double fTime )
{
if( mpImpl )
mpImpl->setMediaTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getMediaTime() const
{
return mpImpl->getMediaTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setStopTime( double fTime )
{
if( mpImpl )
mpImpl->setStopTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getStopTime() const
{
return mpImpl->getStopTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setRate( double fRate )
{
if( mpImpl )
mpImpl->setRate( fRate );
}
// -------------------------------------------------------------------------
double MediaWindow::getRate() const
{
return mpImpl->getRate();
}
// -------------------------------------------------------------------------
void MediaWindow::setPlaybackLoop( bool bSet )
{
if( mpImpl )
mpImpl->setPlaybackLoop( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaybackLoop() const
{
return mpImpl->isPlaybackLoop();
}
// -------------------------------------------------------------------------
void MediaWindow::setMute( bool bSet )
{
if( mpImpl )
mpImpl->setMute( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isMute() const
{
return mpImpl->isMute();
}
// -------------------------------------------------------------------------
void MediaWindow::updateMediaItem( MediaItem& rItem ) const
{
if( mpImpl )
mpImpl->updateMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::executeMediaItem( const MediaItem& rItem )
{
if( mpImpl )
mpImpl->executeMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::show()
{
if( mpImpl )
mpImpl->Show();
}
// -------------------------------------------------------------------------
void MediaWindow::hide()
{
if( mpImpl )
mpImpl->Hide();
}
// -------------------------------------------------------------------------
void MediaWindow::enable()
{
if( mpImpl )
mpImpl->Enable();
}
// -------------------------------------------------------------------------
void MediaWindow::disable()
{
if( mpImpl )
mpImpl->Disable();
}
// -------------------------------------------------------------------------
Window* MediaWindow::getWindow() const
{
return mpImpl;
}
// -------------------------------------------------------------------------
void MediaWindow::getMediaFilters( FilterNameVector& rFilterNameVector )
{
static const char* pFilters[] = { "AIF Audio", "aif;aiff",
"AU Audio", "au",
"AVI", "avi",
"CD Audio", "cda",
"MIDI Audio", "mid;midi",
"MPEG Audio", "mp2;mp3;mpa",
"MPEG Video", "mpg;mpeg;mpv;mp4",
"Ogg bitstream", "ogg",
"Quicktime Video", "mov",
"Vivo Video", "viv",
"WAVE Audio", "wav" };
unsigned int i;
for( i = 0; i < ( sizeof( pFilters ) / sizeof( char* ) ); i += 2 )
{
rFilterNameVector.push_back( ::std::make_pair< ::rtl::OUString, ::rtl::OUString >(
::rtl::OUString::createFromAscii( pFilters[ i ] ),
::rtl::OUString::createFromAscii( pFilters[ i + 1 ] ) ) );
}
}
// -------------------------------------------------------------------------
bool MediaWindow::executeMediaURLDialog( Window* /* pParent */, ::rtl::OUString& rURL, bool bInsertDialog )
{
::sfx2::FileDialogHelper aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );
static const ::rtl::OUString aWildcard( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
FilterNameVector aFilters;
const ::rtl::OUString aSeparator( RTL_CONSTASCII_USTRINGPARAM( ";" ) );
::rtl::OUString aAllTypes;
aDlg.SetTitle( AVMEDIA_RESID( bInsertDialog ? AVMEDIA_STR_INSERTMEDIA_DLG : AVMEDIA_STR_OPENMEDIA_DLG ) );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; i < aFilters.size(); ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aAllTypes.getLength() )
aAllTypes += aSeparator;
( aAllTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
}
// add filter for all media types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_MEDIAFILES ), aAllTypes );
for( i = 0; i < aFilters.size(); ++i )
{
::rtl::OUString aTypes;
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aTypes.getLength() )
aTypes += aSeparator;
( aTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
// add single filters
aDlg.AddFilter( aFilters[ i ].first, aTypes );
}
// add filter for all types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_FILES ), String( RTL_CONSTASCII_USTRINGPARAM( "*.*" ) ) );
if( aDlg.Execute() == ERRCODE_NONE )
{
const INetURLObject aURL( aDlg.GetPath() );
rURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
}
else if( rURL.getLength() )
rURL = ::rtl::OUString();
return( rURL.getLength() > 0 );
}
// -------------------------------------------------------------------------
void MediaWindow::executeFormatErrorBox( Window* pParent )
{
ErrorBox aErrBox( pParent, AVMEDIA_RESID( AVMEDIA_ERR_URL ) );
aErrBox.Execute();
}
// -------------------------------------------------------------------------
bool MediaWindow::isMediaURL( const ::rtl::OUString& rURL, bool bDeep, Size* pPreferredSizePixel )
{
const INetURLObject aURL( rURL );
bool bRet = false;
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
{
if( bDeep || pPreferredSizePixel )
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
if( xFactory.is() )
{
try
{
fprintf(stderr, "-->%s uno reference \n\n",AVMEDIA_MANAGER_SERVICE_NAME);
uno::Reference< ::com::sun::star::media::XManager > xManager(
xFactory->createInstance( ::rtl::OUString::createFromAscii( AVMEDIA_MANAGER_SERVICE_NAME ) ),
uno::UNO_QUERY );
if( xManager.is() )
{
uno::Reference< media::XPlayer > xPlayer( xManager->createPlayer( aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) ) );
if( xPlayer.is() )
{
bRet = true;
if( pPreferredSizePixel )
{
const awt::Size aAwtSize( xPlayer->getPreferredPlayerWindowSize() );
pPreferredSizePixel->Width() = aAwtSize.Width;
pPreferredSizePixel->Height() = aAwtSize.Height;
}
}
}
}
catch( ... )
{
}
}
}
else
{
FilterNameVector aFilters;
const ::rtl::OUString aExt( aURL.getExtension() );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; ( i < aFilters.size() ) && !bRet; ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0 && !bRet; )
{
if( aExt.equalsIgnoreAsciiCase( aFilters[ i ].second.getToken( 0, ';', nIndex ) ) )
bRet = true;
}
}
}
}
return bRet;
}
// -------------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindow::createPlayer( const ::rtl::OUString& rURL )
{
return priv::MediaWindowImpl::createPlayer( rURL );
}
// -------------------------------------------------------------------------
uno::Reference< graphic::XGraphic > MediaWindow::grabFrame( const ::rtl::OUString& rURL,
bool bAllowToCreateReplacementGraphic,
double fMediaTime )
{
uno::Reference< media::XPlayer > xPlayer( createPlayer( rURL ) );
uno::Reference< graphic::XGraphic > xRet;
::std::auto_ptr< Graphic > apGraphic;
if( xPlayer.is() )
{
uno::Reference< media::XFrameGrabber > xGrabber( xPlayer->createFrameGrabber() );
if( xGrabber.is() )
{
if( AVMEDIA_FRAMEGRABBER_DEFAULTFRAME == fMediaTime )
fMediaTime = AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME;
if( fMediaTime >= xPlayer->getDuration() )
fMediaTime = ( xPlayer->getDuration() * 0.5 );
xRet = xGrabber->grabFrame( fMediaTime );
}
if( !xRet.is() && bAllowToCreateReplacementGraphic )
{
awt::Size aPrefSize( xPlayer->getPreferredPlayerWindowSize() );
if( !aPrefSize.Width && !aPrefSize.Height )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_AUDIOLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
}
}
if( !xRet.is() && !apGraphic.get() && bAllowToCreateReplacementGraphic )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_EMPTYLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
if( apGraphic.get() )
xRet = apGraphic->GetXGraphic();
return xRet;
}
} // namespace avemdia
<commit_msg>INTEGRATION: CWS hr51 (1.9.6); FILE MERGED 2008/06/06 14:14:11 hr 1.9.6.1: #i88947#: std namespace<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediawindow.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <cstdio>
#include <avmedia/mediawindow.hxx>
#include "mediawindow_impl.hxx"
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/pathoptions.hxx>
#include <sfx2/filedlghelper.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#define AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME 3.0
using namespace ::com::sun::star;
namespace avmedia {
// ---------------
// - MediaWindow -
// ---------------
MediaWindow::MediaWindow( Window* parent, bool bInternalMediaControl ) :
mpImpl( new priv::MediaWindowImpl( parent, this, bInternalMediaControl ) )
{
mpImpl->Show();
}
// -------------------------------------------------------------------------
MediaWindow::~MediaWindow()
{
mpImpl->cleanUp();
delete mpImpl;
mpImpl = NULL;
}
// -------------------------------------------------------------------------
void MediaWindow::setURL( const ::rtl::OUString& rURL )
{
if( mpImpl )
mpImpl->setURL( rURL );
}
// -------------------------------------------------------------------------
const ::rtl::OUString& MediaWindow::getURL() const
{
return mpImpl->getURL();
}
// -------------------------------------------------------------------------
bool MediaWindow::isValid() const
{
return( mpImpl != NULL && mpImpl->isValid() );
}
// -------------------------------------------------------------------------
void MediaWindow::MouseMove( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonDown( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonUp( const MouseEvent& /* rMEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyInput( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyUp( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::Command( const CommandEvent& /* rCEvt */ )
{
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::AcceptDrop( const AcceptDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::ExecuteDrop( const ExecuteDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
void MediaWindow::StartDrag( sal_Int8 /* nAction */, const Point& /* rPosPixel */ )
{
}
// -------------------------------------------------------------------------
bool MediaWindow::hasPreferredSize() const
{
return( mpImpl != NULL && mpImpl->hasPreferredSize() );
}
// -------------------------------------------------------------------------
Size MediaWindow::getPreferredSize() const
{
return mpImpl->getPreferredSize();
}
// -------------------------------------------------------------------------
void MediaWindow::setPosSize( const Rectangle& rNewRect )
{
if( mpImpl )
mpImpl->setPosSize( rNewRect );
}
// -------------------------------------------------------------------------
Rectangle MediaWindow::getPosSize() const
{
return Rectangle( mpImpl->GetPosPixel(), mpImpl->GetSizePixel() );
}
// -------------------------------------------------------------------------
void MediaWindow::setPointer( const Pointer& rPointer )
{
if( mpImpl )
mpImpl->setPointer( rPointer );
}
// -------------------------------------------------------------------------
const Pointer& MediaWindow::getPointer() const
{
return mpImpl->getPointer();
}
// -------------------------------------------------------------------------
bool MediaWindow::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
return( mpImpl != NULL && mpImpl->setZoom( eLevel ) );
}
// -------------------------------------------------------------------------
::com::sun::star::media::ZoomLevel MediaWindow::getZoom() const
{
return mpImpl->getZoom();
}
// -------------------------------------------------------------------------
bool MediaWindow::start()
{
return( mpImpl != NULL && mpImpl->start() );
}
// -------------------------------------------------------------------------
void MediaWindow::stop()
{
if( mpImpl )
mpImpl->stop();
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaying() const
{
return( mpImpl != NULL && mpImpl->isPlaying() );
}
// -------------------------------------------------------------------------
double MediaWindow::getDuration() const
{
return mpImpl->getDuration();
}
// -------------------------------------------------------------------------
void MediaWindow::setMediaTime( double fTime )
{
if( mpImpl )
mpImpl->setMediaTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getMediaTime() const
{
return mpImpl->getMediaTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setStopTime( double fTime )
{
if( mpImpl )
mpImpl->setStopTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getStopTime() const
{
return mpImpl->getStopTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setRate( double fRate )
{
if( mpImpl )
mpImpl->setRate( fRate );
}
// -------------------------------------------------------------------------
double MediaWindow::getRate() const
{
return mpImpl->getRate();
}
// -------------------------------------------------------------------------
void MediaWindow::setPlaybackLoop( bool bSet )
{
if( mpImpl )
mpImpl->setPlaybackLoop( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaybackLoop() const
{
return mpImpl->isPlaybackLoop();
}
// -------------------------------------------------------------------------
void MediaWindow::setMute( bool bSet )
{
if( mpImpl )
mpImpl->setMute( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isMute() const
{
return mpImpl->isMute();
}
// -------------------------------------------------------------------------
void MediaWindow::updateMediaItem( MediaItem& rItem ) const
{
if( mpImpl )
mpImpl->updateMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::executeMediaItem( const MediaItem& rItem )
{
if( mpImpl )
mpImpl->executeMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::show()
{
if( mpImpl )
mpImpl->Show();
}
// -------------------------------------------------------------------------
void MediaWindow::hide()
{
if( mpImpl )
mpImpl->Hide();
}
// -------------------------------------------------------------------------
void MediaWindow::enable()
{
if( mpImpl )
mpImpl->Enable();
}
// -------------------------------------------------------------------------
void MediaWindow::disable()
{
if( mpImpl )
mpImpl->Disable();
}
// -------------------------------------------------------------------------
Window* MediaWindow::getWindow() const
{
return mpImpl;
}
// -------------------------------------------------------------------------
void MediaWindow::getMediaFilters( FilterNameVector& rFilterNameVector )
{
static const char* pFilters[] = { "AIF Audio", "aif;aiff",
"AU Audio", "au",
"AVI", "avi",
"CD Audio", "cda",
"MIDI Audio", "mid;midi",
"MPEG Audio", "mp2;mp3;mpa",
"MPEG Video", "mpg;mpeg;mpv;mp4",
"Ogg bitstream", "ogg",
"Quicktime Video", "mov",
"Vivo Video", "viv",
"WAVE Audio", "wav" };
unsigned int i;
for( i = 0; i < ( sizeof( pFilters ) / sizeof( char* ) ); i += 2 )
{
rFilterNameVector.push_back( ::std::make_pair< ::rtl::OUString, ::rtl::OUString >(
::rtl::OUString::createFromAscii( pFilters[ i ] ),
::rtl::OUString::createFromAscii( pFilters[ i + 1 ] ) ) );
}
}
// -------------------------------------------------------------------------
bool MediaWindow::executeMediaURLDialog( Window* /* pParent */, ::rtl::OUString& rURL, bool bInsertDialog )
{
::sfx2::FileDialogHelper aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );
static const ::rtl::OUString aWildcard( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
FilterNameVector aFilters;
const ::rtl::OUString aSeparator( RTL_CONSTASCII_USTRINGPARAM( ";" ) );
::rtl::OUString aAllTypes;
aDlg.SetTitle( AVMEDIA_RESID( bInsertDialog ? AVMEDIA_STR_INSERTMEDIA_DLG : AVMEDIA_STR_OPENMEDIA_DLG ) );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; i < aFilters.size(); ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aAllTypes.getLength() )
aAllTypes += aSeparator;
( aAllTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
}
// add filter for all media types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_MEDIAFILES ), aAllTypes );
for( i = 0; i < aFilters.size(); ++i )
{
::rtl::OUString aTypes;
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aTypes.getLength() )
aTypes += aSeparator;
( aTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
// add single filters
aDlg.AddFilter( aFilters[ i ].first, aTypes );
}
// add filter for all types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_FILES ), String( RTL_CONSTASCII_USTRINGPARAM( "*.*" ) ) );
if( aDlg.Execute() == ERRCODE_NONE )
{
const INetURLObject aURL( aDlg.GetPath() );
rURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
}
else if( rURL.getLength() )
rURL = ::rtl::OUString();
return( rURL.getLength() > 0 );
}
// -------------------------------------------------------------------------
void MediaWindow::executeFormatErrorBox( Window* pParent )
{
ErrorBox aErrBox( pParent, AVMEDIA_RESID( AVMEDIA_ERR_URL ) );
aErrBox.Execute();
}
// -------------------------------------------------------------------------
bool MediaWindow::isMediaURL( const ::rtl::OUString& rURL, bool bDeep, Size* pPreferredSizePixel )
{
const INetURLObject aURL( rURL );
bool bRet = false;
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
{
if( bDeep || pPreferredSizePixel )
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
if( xFactory.is() )
{
try
{
std::fprintf(stderr, "-->%s uno reference \n\n",AVMEDIA_MANAGER_SERVICE_NAME);
uno::Reference< ::com::sun::star::media::XManager > xManager(
xFactory->createInstance( ::rtl::OUString::createFromAscii( AVMEDIA_MANAGER_SERVICE_NAME ) ),
uno::UNO_QUERY );
if( xManager.is() )
{
uno::Reference< media::XPlayer > xPlayer( xManager->createPlayer( aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) ) );
if( xPlayer.is() )
{
bRet = true;
if( pPreferredSizePixel )
{
const awt::Size aAwtSize( xPlayer->getPreferredPlayerWindowSize() );
pPreferredSizePixel->Width() = aAwtSize.Width;
pPreferredSizePixel->Height() = aAwtSize.Height;
}
}
}
}
catch( ... )
{
}
}
}
else
{
FilterNameVector aFilters;
const ::rtl::OUString aExt( aURL.getExtension() );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; ( i < aFilters.size() ) && !bRet; ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0 && !bRet; )
{
if( aExt.equalsIgnoreAsciiCase( aFilters[ i ].second.getToken( 0, ';', nIndex ) ) )
bRet = true;
}
}
}
}
return bRet;
}
// -------------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindow::createPlayer( const ::rtl::OUString& rURL )
{
return priv::MediaWindowImpl::createPlayer( rURL );
}
// -------------------------------------------------------------------------
uno::Reference< graphic::XGraphic > MediaWindow::grabFrame( const ::rtl::OUString& rURL,
bool bAllowToCreateReplacementGraphic,
double fMediaTime )
{
uno::Reference< media::XPlayer > xPlayer( createPlayer( rURL ) );
uno::Reference< graphic::XGraphic > xRet;
::std::auto_ptr< Graphic > apGraphic;
if( xPlayer.is() )
{
uno::Reference< media::XFrameGrabber > xGrabber( xPlayer->createFrameGrabber() );
if( xGrabber.is() )
{
if( AVMEDIA_FRAMEGRABBER_DEFAULTFRAME == fMediaTime )
fMediaTime = AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME;
if( fMediaTime >= xPlayer->getDuration() )
fMediaTime = ( xPlayer->getDuration() * 0.5 );
xRet = xGrabber->grabFrame( fMediaTime );
}
if( !xRet.is() && bAllowToCreateReplacementGraphic )
{
awt::Size aPrefSize( xPlayer->getPreferredPlayerWindowSize() );
if( !aPrefSize.Width && !aPrefSize.Height )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_AUDIOLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
}
}
if( !xRet.is() && !apGraphic.get() && bAllowToCreateReplacementGraphic )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_EMPTYLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
if( apGraphic.get() )
xRet = apGraphic->GetXGraphic();
return xRet;
}
} // namespace avemdia
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <ctime>
#include <stdint.h>
#include "libpopcnt.h"
int main(int argc, char** argv)
{
srand((unsigned int) time(0));
int max_size = 100000;
// Generate vectors with random data and compute the bit
// population count using 2 different algorithms and
// check that the results match
for (int size = 0; size < max_size; size++)
{
double percent = (100.0 * size) / max_size;
std::cout << "\rStatus: " << (int) percent << "%" << std::flush;
std::vector<uint8_t> data(size);
for (int i = 0; i < size; i++)
data[i] = (uint8_t) rand();
uint64_t bits = popcnt(&data[0], size);
uint64_t bits_verify = 0;
for (int i = 0; i < size; i++)
bits_verify += popcnt64(data[i]);
if (bits != bits_verify)
{
std::cerr << std::endl;
std::cerr << "libpopcnt test failed!" << std::endl;
return 1;
}
}
std::cout << "\rStatus: 100%" << std::flush;
std::cout << std::endl;
std::cout << "libpopcnt tested successfully!" << std::endl;
return 0;
}
<commit_msg>Rename popcnt64() to popcnt_u64()<commit_after>#include <iostream>
#include <vector>
#include <ctime>
#include <stdint.h>
#include "libpopcnt.h"
int main(int argc, char** argv)
{
srand((unsigned int) time(0));
int max_size = 100000;
// Generate vectors with random data and compute the bit
// population count using 2 different algorithms and
// check that the results match
for (int size = 0; size < max_size; size++)
{
double percent = (100.0 * size) / max_size;
std::cout << "\rStatus: " << (int) percent << "%" << std::flush;
std::vector<uint8_t> data(size);
for (int i = 0; i < size; i++)
data[i] = (uint8_t) rand();
uint64_t bits = popcnt(&data[0], size);
uint64_t bits_verify = 0;
for (int i = 0; i < size; i++)
bits_verify += popcnt_u64(data[i]);
if (bits != bits_verify)
{
std::cerr << std::endl;
std::cerr << "libpopcnt test failed!" << std::endl;
return 1;
}
}
std::cout << "\rStatus: 100%" << std::flush;
std::cout << std::endl;
std::cout << "libpopcnt tested successfully!" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <sys/socket.h>
#include <sys/un.h>
#include <json/json.h>
#include "data/Event.h"
#include "ipc/server/Json.h"
namespace blitzortung {
namespace ipc {
namespace server {
Json::Json(const unsigned int socket, const Process& process, const hardware::Pcb& hardware) :
Base(socket),
process_(process),
hardware_(hardware),
logger_("ipc.server.Json")
{
if (logger_.isDebugEnabled())
logger_.debugStream() << "initialize for socket " << socket;
}
std::string Json::respond(const std::string& input) {
json_object* jsonResult = json_object_new_object();
json_object* jsonObj = json_tokener_parse(input.c_str());
if (int(jsonObj) > 0) {
json_object* cmd_obj = json_object_object_get(jsonObj, "cmd");
if (cmd_obj != 0) {
const char* command = json_object_get_string(cmd_obj);
json_object_object_add(jsonResult, "command", json_object_new_string(command));
json_object* jsonHardware = json_object_new_object();
json_object_object_add(jsonHardware, "firmware", json_object_new_string(hardware_.getFirmwareVersion().c_str()));
json_object_object_add(jsonResult, "hardware", jsonHardware);
const hardware::gps::Base& gps = hardware_.getGps();
json_object* jsonGps = json_object_new_object();
char gpsStatus = gps.getStatus();
json_object_object_add(jsonGps, "longitude", json_object_new_double(gps.getLocation().getLongitude()));
json_object_object_add(jsonGps, "longitudeError", json_object_new_double(gps.getLocation().getLongitudeError()));
json_object_object_add(jsonGps, "latitude", json_object_new_double(gps.getLocation().getLatitude()));
json_object_object_add(jsonGps, "latitudeError", json_object_new_double(gps.getLocation().getLatitudeError()));
json_object_object_add(jsonGps, "altitude", json_object_new_int(gps.getLocation().getAltitude()));
json_object_object_add(jsonGps, "altitudeError", json_object_new_int(gps.getLocation().getAltitudeError()));
pt::ptime gpsTime = gps.getTime();
std::ostringstream oss;
gr::date_facet *datefacet = new gr::date_facet();
datefacet->format("%Y-%m-%d");
oss.imbue(std::locale(std::locale::classic(), datefacet));
oss << gpsTime.date();
json_object_object_add(jsonGps, "date", json_object_new_string(oss.str().c_str()));
oss.str("");
oss << gpsTime.time_of_day();
json_object_object_add(jsonGps, "time", json_object_new_string(oss.str().c_str()));
json_object_object_add(jsonGps, "ticksPerSecond", json_object_new_double(gps.getTicksPerSecond()));
json_object_object_add(jsonGps, "tickError", json_object_new_double(gps.getTickError()));
json_object_object_add(jsonGps, "status", json_object_new_string_len(&gpsStatus, 1));
json_object_object_add(jsonGps, "satelliteCount", json_object_new_int(gps.getSatelliteCount()));
json_object_object_add(jsonGps, "type", json_object_new_string(gps.getType().c_str()));
json_object_object_add(jsonHardware, "gps", jsonGps);
const hardware::comm::Base& comm = hardware_.getComm();
json_object* jsonComm = json_object_new_object();
json_object_object_add(jsonGps, "baudRate", json_object_new_int(comm.getBaudRate()));
json_object_object_add(jsonGps, "interfaceName", json_object_new_string(comm.getInterfaceName().c_str()));
json_object_object_add(jsonHardware, "comm", jsonComm);
json_object* jsonProcess = json_object_new_object();
json_object_object_add(jsonProcess, "numberOfSeconds", json_object_new_int(process_.getEventCountBuffer().getActualSize()));
json_object_object_add(jsonProcess, "numberOfEvents", json_object_new_int(process_.getEventCountBuffer().getSum()));
json_object_object_add(jsonProcess, "eventsPerSecond", json_object_new_double(process_.getEventCountBuffer().getAverage()));
json_object_object_add(jsonResult, "process", jsonProcess);
json_object_put(cmd_obj);
}
json_object_put(jsonObj);
} else {
std::string result = "could not parse command '" + input + "'";
json_object_object_add(jsonResult, "error", json_object_new_string(result.c_str()));
logger_.warnStream() << result;
}
std::string jsonString(json_object_to_json_string(jsonResult));
json_object_put(jsonResult);
return jsonString;
}
}
}
}
<commit_msg>fix json ipc<commit_after>#include <sys/socket.h>
#include <sys/un.h>
#include <json/json.h>
#include "data/Event.h"
#include "ipc/server/Json.h"
namespace blitzortung {
namespace ipc {
namespace server {
Json::Json(const unsigned int socket, const Process& process, const hardware::Pcb& hardware) :
Base(socket),
process_(process),
hardware_(hardware),
logger_("ipc.server.Json")
{
if (logger_.isDebugEnabled())
logger_.debugStream() << "initialize for socket " << socket;
}
std::string Json::respond(const std::string& input) {
json_object* jsonResult = json_object_new_object();
json_object* jsonObj = json_tokener_parse(input.c_str());
if (int(jsonObj) > 0) {
json_object* cmd_obj = json_object_object_get(jsonObj, "cmd");
if (cmd_obj != 0) {
const char* command = json_object_get_string(cmd_obj);
json_object_object_add(jsonResult, "command", json_object_new_string(command));
json_object* jsonHardware = json_object_new_object();
json_object_object_add(jsonHardware, "firmware", json_object_new_string(hardware_.getFirmwareVersion().c_str()));
json_object_object_add(jsonResult, "hardware", jsonHardware);
const hardware::gps::Base& gps = hardware_.getGps();
json_object* jsonGps = json_object_new_object();
char gpsStatus = gps.getStatus();
json_object_object_add(jsonGps, "longitude", json_object_new_double(gps.getLocation().getLongitude()));
json_object_object_add(jsonGps, "longitudeError", json_object_new_double(gps.getLocation().getLongitudeError()));
json_object_object_add(jsonGps, "latitude", json_object_new_double(gps.getLocation().getLatitude()));
json_object_object_add(jsonGps, "latitudeError", json_object_new_double(gps.getLocation().getLatitudeError()));
json_object_object_add(jsonGps, "altitude", json_object_new_int(gps.getLocation().getAltitude()));
json_object_object_add(jsonGps, "altitudeError", json_object_new_int(gps.getLocation().getAltitudeError()));
pt::ptime gpsTime = gps.getTime();
std::ostringstream oss;
gr::date_facet *datefacet = new gr::date_facet();
datefacet->format("%Y-%m-%d");
oss.imbue(std::locale(std::locale::classic(), datefacet));
oss << gpsTime.date();
json_object_object_add(jsonGps, "date", json_object_new_string(oss.str().c_str()));
oss.str("");
oss << gpsTime.time_of_day();
json_object_object_add(jsonGps, "time", json_object_new_string(oss.str().c_str()));
json_object_object_add(jsonGps, "ticksPerSecond", json_object_new_double(gps.getTicksPerSecond()));
json_object_object_add(jsonGps, "tickError", json_object_new_double(gps.getTickError()));
json_object_object_add(jsonGps, "status", json_object_new_string_len(&gpsStatus, 1));
json_object_object_add(jsonGps, "satelliteCount", json_object_new_int(gps.getSatelliteCount()));
json_object_object_add(jsonGps, "type", json_object_new_string(gps.getType().c_str()));
json_object_object_add(jsonHardware, "gps", jsonGps);
const hardware::comm::Base& comm = hardware_.getComm();
json_object* jsonComm = json_object_new_object();
json_object_object_add(jsonComm, "baudRate", json_object_new_int(comm.getBaudRate()));
json_object_object_add(jsonComm, "interfaceName", json_object_new_string(comm.getInterfaceName().c_str()));
json_object_object_add(jsonHardware, "comm", jsonComm);
json_object* jsonProcess = json_object_new_object();
json_object_object_add(jsonProcess, "numberOfSeconds", json_object_new_int(process_.getEventCountBuffer().getActualSize()));
json_object_object_add(jsonProcess, "numberOfEvents", json_object_new_int(process_.getEventCountBuffer().getSum()));
json_object_object_add(jsonProcess, "eventsPerSecond", json_object_new_double(process_.getEventCountBuffer().getAverage()));
json_object_object_add(jsonResult, "process", jsonProcess);
json_object_put(cmd_obj);
}
json_object_put(jsonObj);
} else {
std::string result = "could not parse command '" + input + "'";
json_object_object_add(jsonResult, "error", json_object_new_string(result.c_str()));
logger_.warnStream() << result;
}
std::string jsonString(json_object_to_json_string(jsonResult));
json_object_put(jsonResult);
return jsonString;
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__
#include <aleph/topology/Intersections.hh>
#include <algorithm>
#include <unordered_map>
#include <set>
#include <vector>
namespace aleph
{
namespace topology
{
/**
Stores coface relationships in a simplicial complex. Given a simplex
\f$\sigma\f$, the map contains all of its cofaces. Note that the map
will be updated upon every elementary collapse.
*/
template <class Simplex> using CofaceMap = std::unordered_map<Simplex, std::unordered_set<Simplex> >;
template <class Simplex> bool isPrincipal( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
return cofaces.at( s ).empty();
}
template <class Simplex> Simplex getFreeFace( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
if( !isPrincipal( cofaces, s ) )
return Simplex();
// Check whether a free face exists ----------------------------------
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
{
auto&& allCofaces = cofaces.at( *itFace );
if( allCofaces.size() == 1 && allCofaces.find( s ) != allCofaces.end() )
return *itFace;
}
return Simplex();
}
/**
Checks whether a simplex in a simplicial complex is principal, i.e.
whether it is not a proper face of any other simplex in K.
*/
template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
// Individual vertices cannot be considered to be principal because
// they do not have a free face.
if( s.dimension() == 0 )
return false;
bool principal = true;
auto itPair = K.range( s.dimension() + 1 );
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// This check assumes that the simplicial complex is valid, so it
// suffices to search faces in one dimension _below_ s. Note that
// the check only has to evaluate the *size* of the intersection,
// as this is sufficient to determine whether a simplex is a face
// of another simplex.
if( sizeOfIntersection(s,t) == s.size() )
principal = false;
}
return principal;
}
/**
Checks whether a simplex in a simplicial complex is admissible, i.e.
the simplex is *principal* and has at least one free face.
*/
template <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
if( !isPrincipal(s,K) )
return Simplex();
// Check whether a free face exists ----------------------------------
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::vector<bool> admissible( faces.size(), true );
std::size_t i = 0;
auto itPair = K.range( s.dimension() ); // valid range for searches, viz. *all*
// faces in "one dimension up"
for( auto&& face : faces )
{
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// We do not have to check for intersections with the original
// simplex from which we started---we already know that we are
// a face.
if( t != s )
{
if( sizeOfIntersection(face,t) == face.size() )
{
admissible[i] = false;
break;
}
}
}
++i;
}
auto pos = std::find( admissible.begin(), admissible.end(), true );
if( pos == admissible.end() )
return Simplex();
else
return faces.at( std::distance( admissible.begin(), pos ) );
}
/**
Calculates all principal faces of a given simplicial complex and
returns them.
*/
template <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::value_type;
auto L = K;
std::unordered_map<Simplex, Simplex> admissible;
// Step 1: determine free faces --------------------------------------
//
// This first checks which simplices have at least one free face,
// meaning that they may be potentially admissible.
for( auto it = L.begin(); it != L.end(); ++it )
{
if( it->dimension() == 0 )
continue;
// The range of the complex M is sufficient because we have
// already encountered all lower-dimensional simplices that
// precede the current one given by `it`.
//
// This complex will be used for testing free faces.
SimplicialComplex M( L.begin(), it );
// FIXME:
//
// In case of equal data values, the assignment from above does
// *not* work and will result in incorrect candidates.
M = L;
bool hasFreeFace = false;
Simplex freeFace = Simplex();
for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )
{
bool isFace = false;
for( auto&& simplex : M )
{
if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )
{
// The current face must *not* be a face of another simplex in
// the simplicial complex.
if( intersect( *itFace, simplex ) == *itFace )
{
isFace = true;
break;
}
}
}
hasFreeFace = !isFace;
if( hasFreeFace )
{
freeFace = *itFace;
break;
}
}
if( hasFreeFace )
admissible.insert( std::make_pair( *it, freeFace ) );
}
// Step 2: determine principality ------------------------------------
//
// All simplices that are faces of higher-dimensional simplices are
// now removed from the map of admissible simplices.
for( auto&& s : L )
{
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
admissible.erase( *itFace );
}
return admissible;
}
/**
Performs an iterated elementary simplicial collapse until *all* of the
admissible simplices have been collapsed. This leads to the *spine* of
the simplicial complex.
@see S. Matveev, "Algorithmic Topology and Classification of 3-Manifolds"
*/
template <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::value_type;
auto L = K;
// Step 1: obtain initial set of principal faces to start the process
// of collapsing the complex.
auto admissible = principalFaces( L );
// Step 2: collapse until no admissible simplices are left -----------
while( !admissible.empty() )
{
auto s = admissible.begin()->first;
auto t = admissible.begin()->second;
L.remove_without_validation( s );
L.remove_without_validation( t );
admissible.erase( s );
// New simplices ---------------------------------------------------
//
// Add new admissible simplices that may potentially have been
// spawned by the removal of s.
// 1. Add all faces of the principal simplex, as they may
// potentially become admissible again.
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&t, &L, &admissible] ( const Simplex& s )
{
// TODO: rename function
auto face = isAdmissible( s, L );
if( t != s && face )
admissible.insert( std::make_pair( s, face ) );
}
);
// 2. Add all faces othe free face, as they may now themselves
// become admissible.
faces.assign( t.begin_boundary(), t.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&L, &admissible] ( const Simplex& s )
{
// TODO: rename function
auto face = isAdmissible( s, L );
if( face )
admissible.insert( std::make_pair( s, face ) );
}
);
#if 0
// TODO: this check could be simplified by *storing* the free face
// along with the given simplex
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
{
auto t = *itFace;
if( isAdmissible( s, t, L ) )
{
L.remove_without_validation( s );
L.remove_without_validation( t );
admissible.erase( s );
// New simplices -----------------------------------------------
//
// Add new admissible simplices that may potentially have been
// spawned by the removal of s.
// 1. Add all faces of the principal simplex, as they may
// potentially become admissible again.
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&t, &L, &admissible] ( const Simplex& s )
{
if( t != s && isAdmissible( s, L ) )
admissible.insert( s );
}
);
// 2. Add all faces othe free face, as they may now themselves
// become admissible.
faces.assign( t.begin_boundary(), t.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&L, &admissible] ( const Simplex& s )
{
if( isAdmissible( s, L ) )
admissible.insert( s );
}
);
hasFreeFace = true;
break;
}
}
// The admissible simplex does not have a free face, so it must not
// be used.
if( !hasFreeFace )
admissible.erase( s );
#endif
// The heuristic above is incapable of detecting *all* principal
// faces of the complex because this may involve searching *all*
// co-faces. Instead, it is easier to fill up the admissible set
// here.
if( admissible.empty() )
admissible = principalFaces( L );
}
return L;
}
} // namespace topology
} // namespace aleph
#endif
<commit_msg>Creation of coface map<commit_after>#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__
#include <aleph/topology/Intersections.hh>
#include <algorithm>
#include <unordered_map>
#include <set>
#include <vector>
namespace aleph
{
namespace topology
{
/**
Stores coface relationships in a simplicial complex. Given a simplex
\f$\sigma\f$, the map contains all of its cofaces. Note that the map
will be updated upon every elementary collapse.
*/
template <class Simplex> using CofaceMap = std::unordered_map<Simplex, std::unordered_set<Simplex> >;
template <class SimplicialComplex> CofaceMap<typename SimplicialComplex::ValueType> buildCofaceMap( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::ValueType;
using CofaceMap = CofaceMap<Simplex>;
CofaceMap cofaces;
for( auto&& s : K )
{
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
cofaces[ *itFace ].insert( s );
}
return cofaces;
}
template <class Simplex> bool isPrincipal( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
return cofaces.at( s ).empty();
}
template <class Simplex> Simplex getFreeFace( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
if( !isPrincipal( cofaces, s ) )
return Simplex();
// Check whether a free face exists ----------------------------------
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
{
auto&& allCofaces = cofaces.at( *itFace );
if( allCofaces.size() == 1 && allCofaces.find( s ) != allCofaces.end() )
return *itFace;
}
return Simplex();
}
/**
Checks whether a simplex in a simplicial complex is principal, i.e.
whether it is not a proper face of any other simplex in K.
*/
template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
// Individual vertices cannot be considered to be principal because
// they do not have a free face.
if( s.dimension() == 0 )
return false;
bool principal = true;
auto itPair = K.range( s.dimension() + 1 );
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// This check assumes that the simplicial complex is valid, so it
// suffices to search faces in one dimension _below_ s. Note that
// the check only has to evaluate the *size* of the intersection,
// as this is sufficient to determine whether a simplex is a face
// of another simplex.
if( sizeOfIntersection(s,t) == s.size() )
principal = false;
}
return principal;
}
/**
Checks whether a simplex in a simplicial complex is admissible, i.e.
the simplex is *principal* and has at least one free face.
*/
template <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
if( !isPrincipal(s,K) )
return Simplex();
// Check whether a free face exists ----------------------------------
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::vector<bool> admissible( faces.size(), true );
std::size_t i = 0;
auto itPair = K.range( s.dimension() ); // valid range for searches, viz. *all*
// faces in "one dimension up"
for( auto&& face : faces )
{
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// We do not have to check for intersections with the original
// simplex from which we started---we already know that we are
// a face.
if( t != s )
{
if( sizeOfIntersection(face,t) == face.size() )
{
admissible[i] = false;
break;
}
}
}
++i;
}
auto pos = std::find( admissible.begin(), admissible.end(), true );
if( pos == admissible.end() )
return Simplex();
else
return faces.at( std::distance( admissible.begin(), pos ) );
}
/**
Calculates all principal faces of a given simplicial complex and
returns them.
*/
template <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::value_type;
auto L = K;
std::unordered_map<Simplex, Simplex> admissible;
// Step 1: determine free faces --------------------------------------
//
// This first checks which simplices have at least one free face,
// meaning that they may be potentially admissible.
for( auto it = L.begin(); it != L.end(); ++it )
{
if( it->dimension() == 0 )
continue;
// The range of the complex M is sufficient because we have
// already encountered all lower-dimensional simplices that
// precede the current one given by `it`.
//
// This complex will be used for testing free faces.
SimplicialComplex M( L.begin(), it );
// FIXME:
//
// In case of equal data values, the assignment from above does
// *not* work and will result in incorrect candidates.
M = L;
bool hasFreeFace = false;
Simplex freeFace = Simplex();
for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )
{
bool isFace = false;
for( auto&& simplex : M )
{
if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )
{
// The current face must *not* be a face of another simplex in
// the simplicial complex.
if( intersect( *itFace, simplex ) == *itFace )
{
isFace = true;
break;
}
}
}
hasFreeFace = !isFace;
if( hasFreeFace )
{
freeFace = *itFace;
break;
}
}
if( hasFreeFace )
admissible.insert( std::make_pair( *it, freeFace ) );
}
// Step 2: determine principality ------------------------------------
//
// All simplices that are faces of higher-dimensional simplices are
// now removed from the map of admissible simplices.
for( auto&& s : L )
{
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
admissible.erase( *itFace );
}
return admissible;
}
/**
Performs an iterated elementary simplicial collapse until *all* of the
admissible simplices have been collapsed. This leads to the *spine* of
the simplicial complex.
@see S. Matveev, "Algorithmic Topology and Classification of 3-Manifolds"
*/
template <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::value_type;
auto L = K;
// Step 1: obtain initial set of principal faces to start the process
// of collapsing the complex.
auto admissible = principalFaces( L );
// Step 2: collapse until no admissible simplices are left -----------
while( !admissible.empty() )
{
auto s = admissible.begin()->first;
auto t = admissible.begin()->second;
L.remove_without_validation( s );
L.remove_without_validation( t );
admissible.erase( s );
// New simplices ---------------------------------------------------
//
// Add new admissible simplices that may potentially have been
// spawned by the removal of s.
// 1. Add all faces of the principal simplex, as they may
// potentially become admissible again.
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&t, &L, &admissible] ( const Simplex& s )
{
// TODO: rename function
auto face = isAdmissible( s, L );
if( t != s && face )
admissible.insert( std::make_pair( s, face ) );
}
);
// 2. Add all faces othe free face, as they may now themselves
// become admissible.
faces.assign( t.begin_boundary(), t.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&L, &admissible] ( const Simplex& s )
{
// TODO: rename function
auto face = isAdmissible( s, L );
if( face )
admissible.insert( std::make_pair( s, face ) );
}
);
#if 0
// TODO: this check could be simplified by *storing* the free face
// along with the given simplex
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
{
auto t = *itFace;
if( isAdmissible( s, t, L ) )
{
L.remove_without_validation( s );
L.remove_without_validation( t );
admissible.erase( s );
// New simplices -----------------------------------------------
//
// Add new admissible simplices that may potentially have been
// spawned by the removal of s.
// 1. Add all faces of the principal simplex, as they may
// potentially become admissible again.
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&t, &L, &admissible] ( const Simplex& s )
{
if( t != s && isAdmissible( s, L ) )
admissible.insert( s );
}
);
// 2. Add all faces othe free face, as they may now themselves
// become admissible.
faces.assign( t.begin_boundary(), t.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&L, &admissible] ( const Simplex& s )
{
if( isAdmissible( s, L ) )
admissible.insert( s );
}
);
hasFreeFace = true;
break;
}
}
// The admissible simplex does not have a free face, so it must not
// be used.
if( !hasFreeFace )
admissible.erase( s );
#endif
// The heuristic above is incapable of detecting *all* principal
// faces of the complex because this may involve searching *all*
// co-faces. Instead, it is easier to fill up the admissible set
// here.
if( admissible.empty() )
admissible = principalFaces( L );
}
return L;
}
} // namespace topology
} // namespace aleph
#endif
<|endoftext|> |
<commit_before>#pragma once
/**
* The HeapAnalysis class wraps a Dsa-like analysis.
**/
#include "clam/config.h"
#include "crab/support/debug.hpp"
#include "llvm/IR/Value.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
// forward declarations
namespace llvm {
class Module;
class Function;
class Instruction;
class StringRef;
class CallInst;
} // namespace llvm
namespace clam {
////
// Dsa analysis for memory disambiguation
////
enum class heap_analysis_t {
// disable heap analysis
NONE,
// use context-insensitive sea-dsa
CI_SEA_DSA,
// use context-sensitive sea-dsa
CS_SEA_DSA
};
enum class region_type_t{
UNTYPED_REGION = 0,
BOOL_REGION = 1,
INT_REGION = 2,
PTR_REGION = 3
};
class RegionInfo {
region_type_t m_region_type;
// if PTR_REGION then bitwidth is the pointer size
// if INT_REGION or BOOL_REGION then bitwidth is the integer's
// bitwidth or 1.
unsigned m_bitwidth; // number of bits
// whether the region is coming from a "sequence" sea-dsa node
bool m_is_sequence;
// whether the region is possibly allocated in the heap
bool m_is_heap;
public:
RegionInfo(region_type_t t, unsigned b, bool is_seq, bool is_heap)
: m_region_type(t), m_bitwidth(b), m_is_sequence(is_seq), m_is_heap(is_heap) {}
RegionInfo(const RegionInfo &other) = default;
RegionInfo &operator=(const RegionInfo &other) = default;
bool operator==(const RegionInfo &o) {
// don't consider isSequence() or isHeap().
// We use this operation to compare a region between caller and callee.
return (getType() == o.getType() &&
getBitwidth() == o.getBitwidth());
}
bool containScalar() const {
return m_region_type == region_type_t::BOOL_REGION ||
m_region_type == region_type_t::INT_REGION;
}
bool containPointer() const {
return m_region_type == region_type_t::PTR_REGION;
}
// Return region's type: boolean, integer or pointer.
region_type_t getType() const { return m_region_type; }
// Return 1 if boolean region, size of the pointer if pointer
// region, or size of the integer if integer region. The bitwidth is
// in bits. Otherwise, it returns 0 if bitwdith cannot be
// determined.
unsigned getBitwidth() const { return m_bitwidth; }
// Whether the region corresponds to a "sequence" node
bool isSequence() const { return m_is_sequence;}
// Whether the region is potentially allocated via a malloc-like
// function.
bool isHeap() const { return m_is_heap;}
};
/**
* A region abstracts a Dsa node field to create a symbolic name.
**/
class Region {
public:
using RegionId = long unsigned int;
private:
// A region different from unknown should represent a consecutive
// sequence of bytes in memory that have compatible types and are
// accessed uniformly so the analysis can use it in a safe
// manner.
// Unique id
RegionId m_id;
// type of the region
RegionInfo m_info;
// whether the region contains a singleton value or not.
const llvm::Value *m_singleton;
public:
Region(RegionId id, RegionInfo info, const llvm::Value *singleton)
: m_id(id), m_info(info), m_singleton(singleton) {}
Region()
: m_id(0),
m_info(RegionInfo(region_type_t::UNTYPED_REGION, 0, false, false)),
m_singleton(nullptr) {}
Region(const Region &other) = default;
Region(Region &&other) = default;
Region &operator=(const Region &other) = default;
RegionId getId() const { return m_id; }
bool isUnknown() const { return (m_info.getType() == region_type_t::UNTYPED_REGION); }
const llvm::Value *getSingleton() const { return m_singleton; }
RegionInfo getRegionInfo() const { return m_info; }
bool operator<(const Region &o) const { return (m_id < o.m_id); }
bool operator==(const Region &o) const { return (m_id == o.m_id); }
void write(llvm::raw_ostream &o) const {
if (isUnknown()) {
o << "unknown";
} else {
o << "R_" << m_id << ":";
switch (getRegionInfo().getType()) {
case region_type_t::UNTYPED_REGION:
o << "U";
break;
case region_type_t::BOOL_REGION:
o << "B";
break;
case region_type_t::INT_REGION:
o << "I";
break;
case region_type_t::PTR_REGION:
o << "P";
break;
}
}
}
friend llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const Region &r) {
r.write(o);
return o;
}
};
inline llvm::raw_ostream &operator<<(llvm::raw_ostream &o,
std::vector<Region> s) {
o << "{";
for (typename std::vector<Region>::iterator it = s.begin(), et = s.end();
it != et;) {
o << *it;
++it;
if (it != et)
o << ",";
}
o << "}";
return o;
}
/* A convenient wrapper for a Dsa-like analysis */
class HeapAbstraction {
friend class Region;
public:
typedef std::vector<Region> RegionVec;
typedef typename Region::RegionId RegionId;
// Add a new value if a new HeapAbstraction subclass is created
// This is used to use static_cast.
enum class ClassId { DUMMY, SEA_DSA };
HeapAbstraction() {}
virtual ~HeapAbstraction() {}
virtual ClassId getClassId() const = 0;
virtual llvm::StringRef getName() const = 0;
// TODO: mark all these methods as const.
// fun is used to know in which function ptr lives.
// If not null, i is the instruction that uses ptr.
virtual Region getRegion(const llvm::Function &fun,
const llvm::Value &ptr) = 0;
/**======== These functions allow to purify functions ========**/
// Read-Only regions reachable by function parameters and globals
// but not returns
virtual RegionVec getOnlyReadRegions(const llvm::Function &) = 0;
// Written regions reachable by function parameters and globals but
// not returns
virtual RegionVec getModifiedRegions(const llvm::Function &) = 0;
// Regions that are reachable only from the return of the function
virtual RegionVec getNewRegions(const llvm::Function &) = 0;
// Read-only regions at the caller that are mapped to callee's
// formal parameters and globals.
virtual RegionVec getOnlyReadRegions(const llvm::CallInst &) = 0;
// Written regions at the caller that are mapped to callee's formal
// parameters and globals.
virtual RegionVec getModifiedRegions(const llvm::CallInst &) = 0;
// Regions at the caller that are mapped to those that are only
// reachable from callee's returns.
virtual RegionVec getNewRegions(const llvm::CallInst &) = 0;
};
} // namespace clam
<commit_msg>refactor(heap-abs): rename == and add write method to RegionInfo<commit_after>#pragma once
/**
* The HeapAnalysis class wraps a Dsa-like analysis.
**/
#include "clam/config.h"
#include "crab/support/debug.hpp"
#include "llvm/IR/Value.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
// forward declarations
namespace llvm {
class Module;
class Function;
class Instruction;
class StringRef;
class CallInst;
} // namespace llvm
namespace clam {
////
// Dsa analysis for memory disambiguation
////
enum class heap_analysis_t {
// disable heap analysis
NONE,
// use context-insensitive sea-dsa
CI_SEA_DSA,
// use context-sensitive sea-dsa
CS_SEA_DSA
};
enum class region_type_t{
UNTYPED_REGION = 0,
BOOL_REGION = 1,
INT_REGION = 2,
PTR_REGION = 3
};
class RegionInfo {
region_type_t m_region_type;
// if PTR_REGION then bitwidth is the pointer size
// if INT_REGION or BOOL_REGION then bitwidth is the integer's
// bitwidth or 1.
unsigned m_bitwidth; // number of bits
// whether the region is coming from a "sequence" sea-dsa node
bool m_is_sequence;
// whether the region is possibly allocated in the heap
bool m_is_heap;
public:
RegionInfo(region_type_t t, unsigned b, bool is_seq, bool is_heap)
: m_region_type(t), m_bitwidth(b), m_is_sequence(is_seq), m_is_heap(is_heap) {}
RegionInfo(const RegionInfo &other) = default;
RegionInfo &operator=(const RegionInfo &other) = default;
bool hasSameType(const RegionInfo &o) const {
return (getType() == o.getType() &&
getBitwidth() == o.getBitwidth());
}
bool containScalar() const {
return m_region_type == region_type_t::BOOL_REGION ||
m_region_type == region_type_t::INT_REGION;
}
bool containPointer() const {
return m_region_type == region_type_t::PTR_REGION;
}
// Return region's type: boolean, integer or pointer.
region_type_t getType() const { return m_region_type; }
// Return 1 if boolean region, size of the pointer if pointer
// region, or size of the integer if integer region. The bitwidth is
// in bits. Otherwise, it returns 0 if bitwdith cannot be
// determined.
unsigned getBitwidth() const { return m_bitwidth; }
// Whether the region corresponds to a "sequence" node
bool isSequence() const { return m_is_sequence;}
// Whether the region is potentially allocated via a malloc-like
// function.
bool isHeap() const { return m_is_heap;}
void write(llvm::raw_ostream &o) const {
switch (getType()) {
case region_type_t::UNTYPED_REGION:
o << "U";
break;
case region_type_t::BOOL_REGION:
o << "B";
break;
case region_type_t::INT_REGION:
o << "I" << ":" << getBitwidth();
break;
case region_type_t::PTR_REGION:
o << "P";
break;
}
}
friend llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const RegionInfo &rgnInfo) {
rgnInfo.write(o);
return o;
}
};
/**
* A region abstracts a Dsa node field to create a symbolic name.
**/
class Region {
public:
using RegionId = long unsigned int;
private:
// A region different from unknown should represent a consecutive
// sequence of bytes in memory that have compatible types and are
// accessed uniformly so the analysis can use it in a safe
// manner.
// Unique id
RegionId m_id;
// type of the region
RegionInfo m_info;
// whether the region contains a singleton value or not.
const llvm::Value *m_singleton;
public:
Region(RegionId id, RegionInfo info, const llvm::Value *singleton)
: m_id(id), m_info(info), m_singleton(singleton) {}
Region()
: m_id(0),
m_info(RegionInfo(region_type_t::UNTYPED_REGION, 0, false, false)),
m_singleton(nullptr) {}
Region(const Region &other) = default;
Region(Region &&other) = default;
Region &operator=(const Region &other) = default;
RegionId getId() const { return m_id; }
bool isUnknown() const { return (m_info.getType() == region_type_t::UNTYPED_REGION); }
const llvm::Value *getSingleton() const { return m_singleton; }
RegionInfo getRegionInfo() const { return m_info; }
bool operator<(const Region &o) const { return (m_id < o.m_id); }
bool operator==(const Region &o) const { return (m_id == o.m_id); }
void write(llvm::raw_ostream &o) const {
o << "R_" << m_id << ":" << getRegionInfo();
}
friend llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const Region &r) {
r.write(o);
return o;
}
};
inline llvm::raw_ostream &operator<<(llvm::raw_ostream &o,
std::vector<Region> s) {
o << "{";
for (typename std::vector<Region>::iterator it = s.begin(), et = s.end();
it != et;) {
o << *it;
++it;
if (it != et)
o << ",";
}
o << "}";
return o;
}
/* A convenient wrapper for a Dsa-like analysis */
class HeapAbstraction {
friend class Region;
public:
typedef std::vector<Region> RegionVec;
typedef typename Region::RegionId RegionId;
// Add a new value if a new HeapAbstraction subclass is created
// This is used to use static_cast.
enum class ClassId { DUMMY, SEA_DSA };
HeapAbstraction() {}
virtual ~HeapAbstraction() {}
virtual ClassId getClassId() const = 0;
virtual llvm::StringRef getName() const = 0;
// TODO: mark all these methods as const.
// fun is used to know in which function ptr lives.
// If not null, i is the instruction that uses ptr.
virtual Region getRegion(const llvm::Function &fun,
const llvm::Value &ptr) = 0;
/**======== These functions allow to purify functions ========**/
// Read-Only regions reachable by function parameters and globals
// but not returns
virtual RegionVec getOnlyReadRegions(const llvm::Function &) = 0;
// Written regions reachable by function parameters and globals but
// not returns
virtual RegionVec getModifiedRegions(const llvm::Function &) = 0;
// Regions that are reachable only from the return of the function
virtual RegionVec getNewRegions(const llvm::Function &) = 0;
// Read-only regions at the caller that are mapped to callee's
// formal parameters and globals.
virtual RegionVec getOnlyReadRegions(const llvm::CallInst &) = 0;
// Written regions at the caller that are mapped to callee's formal
// parameters and globals.
virtual RegionVec getModifiedRegions(const llvm::CallInst &) = 0;
// Regions at the caller that are mapped to those that are only
// reachable from callee's returns.
virtual RegionVec getNewRegions(const llvm::CallInst &) = 0;
};
} // namespace clam
<|endoftext|> |
<commit_before>#include "game.hpp"
bool Game::uciHandler(std::string str) {
std::vector<std::string> cmd = getStringArray(str);
if(cmd[0] == "isready") {
std::cout << "readyok" << std::endl;
} else if(cmd[0] == "position") {
gameHash.clear();
gameHash.resize(0);
hash_decrement = 0;
if(cmd[1] == "startpos") {
game_board.setFen(game_board.startpos_fen);
hash_decrement = 0;
hashAge = 0;
if(cmd.size() > 3) {
if(cmd[2] == "moves") {
for(unsigned int i = 3; i < cmd.size(); ++i) {
move(cmd[i]);
}
}
}
} else if(cmd[1] == "fen") {
std::string fen;
unsigned int pos = 2;
for(unsigned int i = 2; i < 8; ++i) {
fen += cmd[i];
if(i != cmd.size() - 1) {
fen.push_back(' ');
}
++pos;
}
game_board.setFen(fen);
if(cmd.size() > pos) {
if(cmd[pos] == "moves") {
for(unsigned int i = pos + 1; i < cmd.size(); ++i) {
move(cmd[i]);
}
}
}
}
} else if(cmd[0] == "go") {
if(cmd[1] == "depth") {
max_depth = std::stoi(cmd[2]);
goFixedDepth();
} else if(cmd[1] == "movetime") {
goFixedTime(std::stoi(cmd[2]), false);
} else if(cmd[1] == "infinite") {
max_depth = 99;
goFixedDepth();
} else {
wtime = 0, btime = 0;
winc = 0, binc = 0, movestogo = 0, movestogoEnable = false;
for(unsigned int i = 1; i < cmd.size(); ++i) {
if(cmd[i] == "wtime") {
wtime = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "btime") {
btime = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "winc") {
winc = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "binc") {
binc = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "movestogo") {
movestogoEnable = true;
movestogo = std::stoi(cmd[i+1]);
}
}
goTournament();
}
} else if(cmd[0] == "posmoves") {
MoveArray moves;
game_board.bitBoardMoveGenerator(moves, stress);
for(unsigned int i = 0; i < moves.count; ++i) {
std::cout << moves.moveArray[i].getMoveString();
std::cout << std::endl;
}
std::cout << game_board.getEvaluate() / PAWN_EV * 100 << std::endl;
std::cout << game_board.getFen() << std::endl;
std::cout << "inCheck (WHITE) : " << game_board.inCheck(WHITE) << std::endl;
std::cout << "inCheck (BLACK) : " << game_board.inCheck(BLACK) << std::endl;
std::cout << "color_hash: " << game_board.getColorHash() << std::endl;
} else if(cmd[0] == "move") {
move(cmd[1]);
} else if(cmd[0] == "quit") {
return false;
} else if(cmd[0] == "uci") {
idPrint();
option.print();
std::cout << "uciok" << std::endl;
} else if(cmd[0] == "bench") {
std::cout << "Benchmarking (15 sec)..." << std::endl;
game_board.stress = 0;
double st = clock();
while((clock() - st) / CLOCKS_PER_SEC < 15) {
for(unsigned int i = 0; i < 10000000; ++i) {
game_board.bitBoardMoveGenerator(moveArray[0], game_board.stress);
}
}
std::cout << (int64_t)(game_board.stress / ((clock() - st) / CLOCKS_PER_SEC)) / 10000 << " scores" << std::endl;
} else if(cmd[0] == "goback") {
game_board.goBack();
--hash_decrement;
} else if(cmd[0] == "perft") {
int k;
k = std::stoi(cmd[1]);
for(int i = 1; i <= k; ++i) {
combinations = 0;
double st = clock();
uint64_t count = perft(i);
std::cout << "Depth: " << i << "; count: " << combinations;
std::cout << "; speed: " << (int64_t)((double)count / (((double)clock() - (double)st) / (double)CLOCKS_PER_SEC)) << std::endl;
}
} else if(cmd[0] == "setoption" && cmd[1] == "name") {
if(cmd[2] == "nullmove" && cmd[3] == "value") {
if(cmd[4] == "true") {
option.nullMovePruningEnable = true;
} else if(cmd[4] == "false") {
option.nullMovePruningEnable = false;
}
} else if(cmd[2] == "checkExtensions" && cmd[3] == "value") {
if(cmd[4] == "true") {
option.checkExtensions = true;
} else if(cmd[4] == "false") {
option.checkExtensions = false;
}
} else if(cmd[2] == "Clear" && cmd[3] == "Hash") {
clearCash();
std::cout << "info hashfull 0" << std::endl;
} else if(cmd[2] == "Hash" && cmd[3] == "value") {
int hash_size = std::stoi(cmd[4]);
hash_size = std::min(hash_size, option.max_hash_size);
hash_size = std::max(hash_size, option.min_hash_size);
setHashSize(hash_size);
} else if(cmd[2] == "UCI_AnalyseMode" && cmd[3] == "value") {
if(cmd[4] == "true") {
option.UCI_AnalyseMode = true;
} else if(cmd[4] == "false") {
option.UCI_AnalyseMode = false;
}
}
}
return true;
}
void Game::idPrint() {
std::cout << "id name Zevra v1.7.1 r561 beta" << std::endl;
std::cout << "id author Oleg Smirnov @sovaz1997" << std::endl;
}<commit_msg>v1.7.1 Release<commit_after>#include "game.hpp"
bool Game::uciHandler(std::string str) {
std::vector<std::string> cmd = getStringArray(str);
if(cmd[0] == "isready") {
std::cout << "readyok" << std::endl;
} else if(cmd[0] == "position") {
gameHash.clear();
gameHash.resize(0);
hash_decrement = 0;
if(cmd[1] == "startpos") {
game_board.setFen(game_board.startpos_fen);
hash_decrement = 0;
hashAge = 0;
if(cmd.size() > 3) {
if(cmd[2] == "moves") {
for(unsigned int i = 3; i < cmd.size(); ++i) {
move(cmd[i]);
}
}
}
} else if(cmd[1] == "fen") {
std::string fen;
unsigned int pos = 2;
for(unsigned int i = 2; i < 8; ++i) {
fen += cmd[i];
if(i != cmd.size() - 1) {
fen.push_back(' ');
}
++pos;
}
game_board.setFen(fen);
if(cmd.size() > pos) {
if(cmd[pos] == "moves") {
for(unsigned int i = pos + 1; i < cmd.size(); ++i) {
move(cmd[i]);
}
}
}
}
} else if(cmd[0] == "go") {
if(cmd[1] == "depth") {
max_depth = std::stoi(cmd[2]);
goFixedDepth();
} else if(cmd[1] == "movetime") {
goFixedTime(std::stoi(cmd[2]), false);
} else if(cmd[1] == "infinite") {
max_depth = 99;
goFixedDepth();
} else {
wtime = 0, btime = 0;
winc = 0, binc = 0, movestogo = 0, movestogoEnable = false;
for(unsigned int i = 1; i < cmd.size(); ++i) {
if(cmd[i] == "wtime") {
wtime = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "btime") {
btime = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "winc") {
winc = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "binc") {
binc = std::stoi(cmd[i + 1]);
} else if(cmd[i] == "movestogo") {
movestogoEnable = true;
movestogo = std::stoi(cmd[i+1]);
}
}
goTournament();
}
} else if(cmd[0] == "posmoves") {
MoveArray moves;
game_board.bitBoardMoveGenerator(moves, stress);
for(unsigned int i = 0; i < moves.count; ++i) {
std::cout << moves.moveArray[i].getMoveString();
std::cout << std::endl;
}
std::cout << game_board.getEvaluate() / PAWN_EV * 100 << std::endl;
std::cout << game_board.getFen() << std::endl;
std::cout << "inCheck (WHITE) : " << game_board.inCheck(WHITE) << std::endl;
std::cout << "inCheck (BLACK) : " << game_board.inCheck(BLACK) << std::endl;
std::cout << "color_hash: " << game_board.getColorHash() << std::endl;
} else if(cmd[0] == "move") {
move(cmd[1]);
} else if(cmd[0] == "quit") {
return false;
} else if(cmd[0] == "uci") {
idPrint();
option.print();
std::cout << "uciok" << std::endl;
} else if(cmd[0] == "bench") {
std::cout << "Benchmarking (15 sec)..." << std::endl;
game_board.stress = 0;
double st = clock();
while((clock() - st) / CLOCKS_PER_SEC < 15) {
for(unsigned int i = 0; i < 10000000; ++i) {
game_board.bitBoardMoveGenerator(moveArray[0], game_board.stress);
}
}
std::cout << (int64_t)(game_board.stress / ((clock() - st) / CLOCKS_PER_SEC)) / 10000 << " scores" << std::endl;
} else if(cmd[0] == "goback") {
game_board.goBack();
--hash_decrement;
} else if(cmd[0] == "perft") {
int k;
k = std::stoi(cmd[1]);
for(int i = 1; i <= k; ++i) {
combinations = 0;
double st = clock();
uint64_t count = perft(i);
std::cout << "Depth: " << i << "; count: " << combinations;
std::cout << "; speed: " << (int64_t)((double)count / (((double)clock() - (double)st) / (double)CLOCKS_PER_SEC)) << std::endl;
}
} else if(cmd[0] == "setoption" && cmd[1] == "name") {
if(cmd[2] == "nullmove" && cmd[3] == "value") {
if(cmd[4] == "true") {
option.nullMovePruningEnable = true;
} else if(cmd[4] == "false") {
option.nullMovePruningEnable = false;
}
} else if(cmd[2] == "checkExtensions" && cmd[3] == "value") {
if(cmd[4] == "true") {
option.checkExtensions = true;
} else if(cmd[4] == "false") {
option.checkExtensions = false;
}
} else if(cmd[2] == "Clear" && cmd[3] == "Hash") {
clearCash();
std::cout << "info hashfull 0" << std::endl;
} else if(cmd[2] == "Hash" && cmd[3] == "value") {
int hash_size = std::stoi(cmd[4]);
hash_size = std::min(hash_size, option.max_hash_size);
hash_size = std::max(hash_size, option.min_hash_size);
setHashSize(hash_size);
} else if(cmd[2] == "UCI_AnalyseMode" && cmd[3] == "value") {
if(cmd[4] == "true") {
option.UCI_AnalyseMode = true;
} else if(cmd[4] == "false") {
option.UCI_AnalyseMode = false;
}
}
}
return true;
}
void Game::idPrint() {
std::cout << "id name Zevra v1.7.1 r563" << std::endl;
std::cout << "id author Oleg Smirnov @sovaz1997" << std::endl;
}<|endoftext|> |
<commit_before>#ifndef GAMELIB_EVENT_HPP
#define GAMELIB_EVENT_HPP
#include <memory>
#include "../Identifier.hpp"
namespace gamelib
{
typedef ID EventID;
constexpr EventID invalidEvent = invalidID;
typedef Identifiable BaseEvent; // Event Interface
typedef std::shared_ptr<BaseEvent> EventPtr;
// Wrapper (see Identifier.hpp)
template <ID id>
using Event = Identifier<id, BaseEvent>;
}
#endif
<commit_msg>Add function to BaseEvent to cast to a given type<commit_after>#ifndef GAMELIB_EVENT_HPP
#define GAMELIB_EVENT_HPP
#include <memory>
#include "../Identifier.hpp"
namespace gamelib
{
typedef ID EventID;
constexpr EventID invalidEvent = invalidID;
// typedef Identifiable BaseEvent; // Event Interface
class BaseEvent : public Identifiable
{
public:
virtual ~BaseEvent() {}
// Returns a pointer T*.
// Can be used to easily cast to the derived class.
template <class T>
const T* get() const
{
return static_cast<const T*>(this);
}
template <class T>
T* get()
{
return static_cast<T*>(this);
}
};
typedef std::shared_ptr<BaseEvent> EventPtr;
// Wrapper (see Identifier.hpp)
template <ID id>
using Event = Identifier<id, BaseEvent>;
}
#endif
<|endoftext|> |
<commit_before>/**
* @file postings_data.tcc
* @author Sean Massung
*/
#include <algorithm>
#include "index/postings_data.h"
namespace meta {
namespace index {
template <class PrimaryKey, class SecondaryKey>
postings_data<PrimaryKey, SecondaryKey>::postings_data(PrimaryKey p_id):
_p_id{p_id}
{ /* nothing */ }
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::merge_with(
postings_data & other)
{
auto searcher = [](const pair_t & p, const SecondaryKey & s) {
return p.first < s;
};
// O(n log n) now, could be O(n)
// if the primary_key doesn't exist, add onto back
uint64_t orig_length = _counts.size();
for(auto & p: other._counts)
{
auto it = std::lower_bound(_counts.begin(),
_counts.begin() + orig_length,
p.first,
searcher);
if(it == _counts.end() || it->first != p.first)
_counts.emplace_back(std::move(p));
else
it->second += p.second;
}
// sort _counts again to fix new elements added onto back
if (_counts.size() > orig_length) {
std::sort(_counts.begin(), _counts.end(),
[](const pair_t & a, const pair_t & b) {
return a.first < b.first;
}
);
}
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::increase_count(
SecondaryKey s_id, double amount)
{
auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id,
[](const pair_t & p, const SecondaryKey & s) {
return p.first < s;
}
);
if(it == _counts.end())
_counts.emplace_back(s_id, amount);
else if(it->first != s_id)
_counts.emplace(it, s_id, amount);
else
it->second += amount;
}
template <class PrimaryKey, class SecondaryKey>
double postings_data<PrimaryKey, SecondaryKey>::count(SecondaryKey s_id) const
{
auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id,
[](const pair_t & p, const SecondaryKey & s) {
return p.first < s;
}
);
if(it == _counts.end() || it->first != s_id)
return 0.0;
return it->second;
}
template <class PrimaryKey, class SecondaryKey>
const std::vector<std::pair<SecondaryKey, double>> &
postings_data<PrimaryKey, SecondaryKey>::counts() const
{
return _counts;
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::set_counts(const count_t & counts)
{
_counts = counts;
std::sort(_counts.begin(), _counts.end(),
[](const pair_t & a, const pair_t & b) {
return a.first < b.first;
}
);
}
template <class PrimaryKey, class SecondaryKey>
bool postings_data<PrimaryKey, SecondaryKey>::operator<(const postings_data & other) const
{
return primary_key() < other.primary_key();
}
template <class PrimaryKey, class SecondaryKey>
bool operator==(const postings_data<PrimaryKey, SecondaryKey> & lhs,
const postings_data<PrimaryKey, SecondaryKey> & rhs) {
return lhs.primary_key() == rhs.primary_key();
}
template <class PrimaryKey, class SecondaryKey>
PrimaryKey postings_data<PrimaryKey, SecondaryKey>::primary_key() const
{
return _p_id;
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::write_compressed(
io::compressed_file_writer & writer) const
{
count_t mutable_counts{_counts};
writer.write(mutable_counts[0].first);
writer.write(*reinterpret_cast<uint64_t*>(&mutable_counts[0].second));
// use gap encoding on the SecondaryKeys (we know they are integral types)
uint64_t cur_id = mutable_counts[0].first;
for(size_t i = 1; i < mutable_counts.size(); ++i)
{
uint64_t temp_id = mutable_counts[i].first;
mutable_counts[i].first = mutable_counts[i].first - cur_id;
cur_id = temp_id;
writer.write(mutable_counts[i].first);
if(std::is_same<PrimaryKey, term_id>::value
|| std::is_same<PrimaryKey, std::string>::value)
writer.write(static_cast<uint64_t>(mutable_counts[i].second));
else
writer.write(*reinterpret_cast<uint64_t*>(&mutable_counts[i].second));
}
// mark end of postings_data
writer.write(_delimiter);
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::read_compressed(
io::compressed_file_reader & reader)
{
_counts.clear();
uint64_t last_id = 0;
while(true)
{
uint64_t this_id = reader.next();
// have we reached a delimiter?
if(this_id == _delimiter)
break;
// we're using gap encoding
last_id += this_id;
SecondaryKey key{last_id};
uint64_t next = reader.next();
double count;
if(std::is_same<PrimaryKey, term_id>::value)
count = static_cast<double>(next);
else
count = *reinterpret_cast<double*>(&next);
_counts.emplace_back(key, count);
}
// compress vector to conserve memory (it shouldn't be modified again after
// this)
_counts.shrink_to_fit();
}
namespace {
template <class T>
uint64_t length(const T & elem,
typename std::enable_if<
std::is_same<T, std::string>::value
>::type * = nullptr) {
return elem.size();
}
template <class T>
uint64_t length(const T & elem,
typename std::enable_if<
!std::is_same<T, std::string>::value
>::type * = nullptr) {
return sizeof(elem);
}
}
template <class PrimaryKey, class SecondaryKey>
uint64_t postings_data<PrimaryKey, SecondaryKey>::bytes_used() const
{
return sizeof(pair_t) * _counts.size() + length(_p_id);
}
}
}
<commit_msg>Fix bug writing the first count of a postings_data in inverted indexes.<commit_after>/**
* @file postings_data.tcc
* @author Sean Massung
*/
#include <algorithm>
#include "index/postings_data.h"
namespace meta {
namespace index {
template <class PrimaryKey, class SecondaryKey>
postings_data<PrimaryKey, SecondaryKey>::postings_data(PrimaryKey p_id):
_p_id{p_id}
{ /* nothing */ }
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::merge_with(
postings_data & other)
{
auto searcher = [](const pair_t & p, const SecondaryKey & s) {
return p.first < s;
};
// O(n log n) now, could be O(n)
// if the primary_key doesn't exist, add onto back
uint64_t orig_length = _counts.size();
for(auto & p: other._counts)
{
auto it = std::lower_bound(_counts.begin(),
_counts.begin() + orig_length,
p.first,
searcher);
if(it == _counts.end() || it->first != p.first)
_counts.emplace_back(std::move(p));
else
it->second += p.second;
}
// sort _counts again to fix new elements added onto back
if (_counts.size() > orig_length) {
std::sort(_counts.begin(), _counts.end(),
[](const pair_t & a, const pair_t & b) {
return a.first < b.first;
}
);
}
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::increase_count(
SecondaryKey s_id, double amount)
{
auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id,
[](const pair_t & p, const SecondaryKey & s) {
return p.first < s;
}
);
if(it == _counts.end())
_counts.emplace_back(s_id, amount);
else if(it->first != s_id)
_counts.emplace(it, s_id, amount);
else
it->second += amount;
}
template <class PrimaryKey, class SecondaryKey>
double postings_data<PrimaryKey, SecondaryKey>::count(SecondaryKey s_id) const
{
auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id,
[](const pair_t & p, const SecondaryKey & s) {
return p.first < s;
}
);
if(it == _counts.end() || it->first != s_id)
return 0.0;
return it->second;
}
template <class PrimaryKey, class SecondaryKey>
const std::vector<std::pair<SecondaryKey, double>> &
postings_data<PrimaryKey, SecondaryKey>::counts() const
{
return _counts;
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::set_counts(const count_t & counts)
{
_counts = counts;
std::sort(_counts.begin(), _counts.end(),
[](const pair_t & a, const pair_t & b) {
return a.first < b.first;
}
);
}
template <class PrimaryKey, class SecondaryKey>
bool postings_data<PrimaryKey, SecondaryKey>::operator<(const postings_data & other) const
{
return primary_key() < other.primary_key();
}
template <class PrimaryKey, class SecondaryKey>
bool operator==(const postings_data<PrimaryKey, SecondaryKey> & lhs,
const postings_data<PrimaryKey, SecondaryKey> & rhs) {
return lhs.primary_key() == rhs.primary_key();
}
template <class PrimaryKey, class SecondaryKey>
PrimaryKey postings_data<PrimaryKey, SecondaryKey>::primary_key() const
{
return _p_id;
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::write_compressed(
io::compressed_file_writer & writer) const
{
count_t mutable_counts{_counts};
writer.write(mutable_counts[0].first);
if(std::is_same<PrimaryKey, term_id>::value
|| std::is_same<PrimaryKey, std::string>::value)
writer.write(static_cast<uint64_t>(mutable_counts[0].second));
else
writer.write(*reinterpret_cast<uint64_t*>(&mutable_counts[0].second));
// use gap encoding on the SecondaryKeys (we know they are integral types)
uint64_t cur_id = mutable_counts[0].first;
for(size_t i = 1; i < mutable_counts.size(); ++i)
{
uint64_t temp_id = mutable_counts[i].first;
mutable_counts[i].first = mutable_counts[i].first - cur_id;
cur_id = temp_id;
writer.write(mutable_counts[i].first);
if(std::is_same<PrimaryKey, term_id>::value
|| std::is_same<PrimaryKey, std::string>::value)
writer.write(static_cast<uint64_t>(mutable_counts[i].second));
else
writer.write(*reinterpret_cast<uint64_t*>(&mutable_counts[i].second));
}
// mark end of postings_data
writer.write(_delimiter);
}
template <class PrimaryKey, class SecondaryKey>
void postings_data<PrimaryKey, SecondaryKey>::read_compressed(
io::compressed_file_reader & reader)
{
_counts.clear();
uint64_t last_id = 0;
while(true)
{
uint64_t this_id = reader.next();
// have we reached a delimiter?
if(this_id == _delimiter)
break;
// we're using gap encoding
last_id += this_id;
SecondaryKey key{last_id};
uint64_t next = reader.next();
double count;
if(std::is_same<PrimaryKey, term_id>::value)
count = static_cast<double>(next);
else
count = *reinterpret_cast<double*>(&next);
_counts.emplace_back(key, count);
}
// compress vector to conserve memory (it shouldn't be modified again after
// this)
_counts.shrink_to_fit();
}
namespace {
template <class T>
uint64_t length(const T & elem,
typename std::enable_if<
std::is_same<T, std::string>::value
>::type * = nullptr) {
return elem.size();
}
template <class T>
uint64_t length(const T & elem,
typename std::enable_if<
!std::is_same<T, std::string>::value
>::type * = nullptr) {
return sizeof(elem);
}
}
template <class PrimaryKey, class SecondaryKey>
uint64_t postings_data<PrimaryKey, SecondaryKey>::bytes_used() const
{
return sizeof(pair_t) * _counts.size() + length(_p_id);
}
}
}
<|endoftext|> |
<commit_before>#include "rdo_studio/stdafx.h"
#include "rdo_studio/rdo_process/rdoprocess_project.h"
#include "rdo_studio/rdostudioapp.h"
#include "rdo_studio/rdo_process/rdoprocess_childfrm.h"
#include "rdo_studio/rdo_process/rdoprocess_docview.h"
#include "rdo_studio/rdo_process/rdoprocess_toolbar.h"
#include "rdo_studio/rdo_process/rp_misc/rdoprocess_pixmap.h"
#include "rdo_studio/rdo_process/rp_method/rdoprocess_object_flowchart.h"
#include "rdo_studio/rdo_process/rp_method/rdoprocess_method.h"
#include "rdo_studio/rdo_process/rp_misc/rdoprocess_xml.h"
#include "rdo_studio/rdostudiomodel.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// ----------------------------------------------------------------------------
// ---------- RPProjectMFC
// ----------------------------------------------------------------------------
RPProjectMFC::RPProjectMFC():
RPProject()
{
}
RPProjectMFC::~RPProjectMFC()
{
std::list< RPCtrlToolbarMFC* >::iterator it = toolbars.begin();
while ( it != toolbars.end() ) {
delete *it;
it++;
}
toolbars.clear();
}
std::ofstream& RPProjectMFC::log() const
{
return studioApp.log;
}
RPCtrlToolbar* RPProjectMFC::createToolBar( const rp::string& caption )
{
RPCtrlToolbarMFC* toolbar = new RPCtrlToolbarMFC( studioApp.mainFrame );
toolbars.push_back( toolbar );
studioApp.mainFrame->insertToolBar( &toolbar->toolbar );
toolbar->setCaption( caption );
return toolbar;
}
RPPixmap* RPProjectMFC::createBitmap( char* xpm[] )
{
return new RPPixmap( xpm );
}
/*
bool RPProjectMFC::lockResource( rpMethod::RPMethod* method )
{
RPMethodPlugin* plugin = studioApp.getMethodManager().find( method );
if ( plugin ) {
AfxSetResourceHandle( plugin->getLib() );
return true;
}
return false;
}
void RPProjectMFC::unlockResource()
{
AfxSetResourceHandle( studioApp.m_hInstance );
}
HWND RPProjectMFC::getMainWnd()
{
return AfxGetMainWnd()->m_hWnd;
}
*/
void RPProjectMFC::open()
{
try {
rp::RPXML xml_doc;
rp::RPXMLNode* project_node = xml_doc.open( "c:\\sample.xml" );
if ( project_node ) {
load( project_node );
}
} catch ( rp::RPXMLException& ex ) {
studioApp.mainFrame->MessageBox( ex.getError().c_str(), NULL, MB_ICONERROR );
}
}
void RPProjectMFC::save()
{
try {
rp::RPXML xml_doc;
rp::RPXMLNode* project_node = xml_doc.getDocument().makeChild( "project" );
save_child( project_node );
xml_doc.save( "c:\\sample.xml" );
} catch ( rp::RPXMLException& ex ) {
studioApp.mainFrame->MessageBox( ex.getError().c_str(), NULL, MB_ICONERROR );
}
}
void RPProjectMFC::load( rp::RPXMLNode* node )
{
rp::RPXMLNode* flowchart_node = NULL;
while ( flowchart_node = node->nextChild(flowchart_node) ) {
if ( flowchart_node->getName() == "flowchart" ) {
RPObjectFlowChart* flowobj = static_cast<RPObjectFlowChart*>(rpMethod::factory->getNewObject( flowchart_node->getAttribute("class"), rpMethod::project ));
flowobj->load( flowchart_node );
}
}
}
void RPProjectMFC::makeFlowChartWnd( RPObjectFlowChart* flowobj )
{
BOOL maximized = false;
studioApp.mainFrame->MDIGetActive( &maximized );
RPDoc* doc = static_cast<RPDoc*>(model->flowchartDocTemplate->OpenDocumentFile( NULL ));
RPChildFrame* mdi = static_cast<RPChildFrame*>(doc->getView()->GetParent());
mdi->SetIcon( flowobj->getMethod()->getPixmap()->getIcon(), true );
if ( maximized ) {
mdi->ShowWindow( SW_HIDE );
mdi->MDIRestore();
mdi->ShowWindow( SW_HIDE );
}
doc->getView()->makeFlowChartWnd( flowobj );
flowobj->setCorrectName( flowobj->getClassInfo()->getLabel() );
if ( maximized ) {
mdi->MDIMaximize();
}
/*
CDocument::SetTitle
CChildFrame::OnUpdateFrameTitle mdi
CFrameWnd::OnUpdateFrameTitle
AfxSetWindowText ( ) , .
CViewXXX CMDIChildWnd
*/
}
<commit_msg> - удалено лишнее<commit_after>#include "rdo_studio/stdafx.h"
#include "rdo_studio/rdo_process/rdoprocess_project.h"
#include "rdo_studio/rdostudioapp.h"
#include "rdo_studio/rdo_process/rdoprocess_childfrm.h"
#include "rdo_studio/rdo_process/rdoprocess_docview.h"
#include "rdo_studio/rdo_process/rdoprocess_toolbar.h"
#include "rdo_studio/rdo_process/rp_misc/rdoprocess_pixmap.h"
#include "rdo_studio/rdo_process/rp_method/rdoprocess_object_flowchart.h"
#include "rdo_studio/rdo_process/rp_method/rdoprocess_method.h"
#include "rdo_studio/rdo_process/rp_misc/rdoprocess_xml.h"
#include "rdo_studio/rdostudiomodel.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// ----------------------------------------------------------------------------
// ---------- RPProjectMFC
// ----------------------------------------------------------------------------
RPProjectMFC::RPProjectMFC():
RPProject()
{
}
RPProjectMFC::~RPProjectMFC()
{
std::list< RPCtrlToolbarMFC* >::iterator it = toolbars.begin();
while ( it != toolbars.end() ) {
delete *it;
it++;
}
toolbars.clear();
}
std::ofstream& RPProjectMFC::log() const
{
return studioApp.log;
}
RPCtrlToolbar* RPProjectMFC::createToolBar( const rp::string& caption )
{
RPCtrlToolbarMFC* toolbar = new RPCtrlToolbarMFC( studioApp.mainFrame );
toolbars.push_back( toolbar );
studioApp.mainFrame->insertToolBar( &toolbar->toolbar );
toolbar->setCaption( caption );
return toolbar;
}
RPPixmap* RPProjectMFC::createBitmap( char* xpm[] )
{
return new RPPixmap( xpm );
}
/*
bool RPProjectMFC::lockResource( rpMethod::RPMethod* method )
{
RPMethodPlugin* plugin = studioApp.getMethodManager().find( method );
if ( plugin ) {
AfxSetResourceHandle( plugin->getLib() );
return true;
}
return false;
}
void RPProjectMFC::unlockResource()
{
AfxSetResourceHandle( studioApp.m_hInstance );
}
HWND RPProjectMFC::getMainWnd()
{
return AfxGetMainWnd()->m_hWnd;
}
*/
void RPProjectMFC::open()
{
try {
rp::RPXML xml_doc;
rp::RPXMLNode* project_node = xml_doc.open( "c:\\sample.xml" );
if ( project_node ) {
load( project_node );
}
} catch ( rp::RPXMLException& ex ) {
studioApp.mainFrame->MessageBox( ex.getError().c_str(), NULL, MB_ICONERROR );
}
}
void RPProjectMFC::save()
{
try {
rp::RPXML xml_doc;
rp::RPXMLNode* project_node = xml_doc.getDocument().makeChild( "project" );
save_child( project_node );
xml_doc.save( "c:\\sample.xml" );
} catch ( rp::RPXMLException& ex ) {
studioApp.mainFrame->MessageBox( ex.getError().c_str(), NULL, MB_ICONERROR );
}
}
void RPProjectMFC::load( rp::RPXMLNode* node )
{
rp::RPXMLNode* flowchart_node = NULL;
while ( flowchart_node = node->nextChild(flowchart_node) ) {
if ( flowchart_node->getName() == "flowchart" ) {
RPObjectFlowChart* flowobj = static_cast<RPObjectFlowChart*>(rpMethod::factory->getNewObject( flowchart_node->getAttribute("class"), rpMethod::project ));
flowobj->load( flowchart_node );
}
}
}
void RPProjectMFC::makeFlowChartWnd( RPObjectFlowChart* flowobj )
{
/*
CDocument::SetTitle
CChildFrame::OnUpdateFrameTitle mdi
CFrameWnd::OnUpdateFrameTitle
AfxSetWindowText ( ) , .
CViewXXX CMDIChildWnd
*/
}
<|endoftext|> |
<commit_before>// MIT License
//
// Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <tacopie/utils/logger.hpp>
#include <tacopie/utils/thread_pool.hpp>
namespace tacopie {
namespace utils {
//!
//! ctor & dtor
//!
thread_pool::thread_pool(std::size_t nb_threads) {
__TACOPIE_LOG(debug, "create thread_pool");
set_nb_threads(nb_threads);
}
thread_pool::~thread_pool(void) {
__TACOPIE_LOG(debug, "destroy thread_pool");
stop();
}
//!
//! worker main loop
//!
void
thread_pool::run(void) {
__TACOPIE_LOG(debug, "start run() worker");
while (true) {
auto res = fetch_task_or_stop();
bool stopped = res.first;
task_t task = res.second;
//! if thread has been requested to stop, stop it here
if (stopped) {
break;
}
//! execute task
if (task) {
__TACOPIE_LOG(debug, "execute task");
try {
task();
}
catch (const std::exception&) {
__TACOPIE_LOG(warn, "uncatched exception propagated up to the threadpool.")
}
__TACOPIE_LOG(debug, "execution complete");
}
}
__TACOPIE_LOG(debug, "stop run() worker");
}
//!
//! stop the thread pool and wait for workers completion
//!
void
thread_pool::stop(void) {
if (!is_running()) { return; }
m_should_stop = true;
m_tasks_condvar.notify_all();
for (auto& worker : m_workers) { worker.join(); }
m_workers.clear();
__TACOPIE_LOG(debug, "thread_pool stopped");
}
//!
//! whether the thread_pool is running or not
//!
bool
thread_pool::is_running(void) const {
return !m_should_stop;
}
//!
//! whether the current thread should stop or not
//!
bool
thread_pool::should_stop(void) const {
return m_should_stop || m_nb_running_threads > m_max_nb_threads;
}
//!
//! retrieve a new task
//!
std::pair<bool, thread_pool::task_t>
thread_pool::fetch_task_or_stop(void) {
std::unique_lock<std::mutex> lock(m_tasks_mtx);
__TACOPIE_LOG(debug, "waiting to fetch task");
m_tasks_condvar.wait(lock, [&] { return should_stop() || !m_tasks.empty(); });
if (should_stop()) {
--m_nb_running_threads;
return {true, nullptr};
}
task_t task = std::move(m_tasks.front());
m_tasks.pop();
return {false, task};
}
//!
//! add tasks to thread pool
//!
void
thread_pool::add_task(const task_t& task) {
std::lock_guard<std::mutex> lock(m_tasks_mtx);
__TACOPIE_LOG(debug, "add task to thread_pool");
m_tasks.push(task);
m_tasks_condvar.notify_all();
}
thread_pool&
thread_pool::operator<<(const task_t& task) {
add_task(task);
return *this;
}
//!
//! adjust number of threads
//!
void
thread_pool::set_nb_threads(std::size_t nb_threads) {
m_max_nb_threads = nb_threads;
//! if we increased the number of threads, spawn them
while (m_nb_running_threads < m_max_nb_threads) {
++m_nb_running_threads;
m_workers.push_back(std::thread(std::bind(&thread_pool::run, this)));
}
//! otherwise, wake up threads to make them stop if necessary (until we get the right amount of threads)
if (m_nb_running_threads > m_max_nb_threads) {
m_tasks_condvar.notify_all();
}
}
} // namespace utils
} // namespace tacopie
<commit_msg>Update thread_pool.cpp, switch from notify_all to notify_one (#39)<commit_after>// MIT License
//
// Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <tacopie/utils/logger.hpp>
#include <tacopie/utils/thread_pool.hpp>
namespace tacopie {
namespace utils {
//!
//! ctor & dtor
//!
thread_pool::thread_pool(std::size_t nb_threads) {
__TACOPIE_LOG(debug, "create thread_pool");
set_nb_threads(nb_threads);
}
thread_pool::~thread_pool(void) {
__TACOPIE_LOG(debug, "destroy thread_pool");
stop();
}
//!
//! worker main loop
//!
void
thread_pool::run(void) {
__TACOPIE_LOG(debug, "start run() worker");
while (true) {
auto res = fetch_task_or_stop();
bool stopped = res.first;
task_t task = res.second;
//! if thread has been requested to stop, stop it here
if (stopped) {
break;
}
//! execute task
if (task) {
__TACOPIE_LOG(debug, "execute task");
try {
task();
}
catch (const std::exception&) {
__TACOPIE_LOG(warn, "uncatched exception propagated up to the threadpool.")
}
__TACOPIE_LOG(debug, "execution complete");
}
}
__TACOPIE_LOG(debug, "stop run() worker");
}
//!
//! stop the thread pool and wait for workers completion
//!
void
thread_pool::stop(void) {
if (!is_running()) { return; }
m_should_stop = true;
m_tasks_condvar.notify_all();
for (auto& worker : m_workers) { worker.join(); }
m_workers.clear();
__TACOPIE_LOG(debug, "thread_pool stopped");
}
//!
//! whether the thread_pool is running or not
//!
bool
thread_pool::is_running(void) const {
return !m_should_stop;
}
//!
//! whether the current thread should stop or not
//!
bool
thread_pool::should_stop(void) const {
return m_should_stop || m_nb_running_threads > m_max_nb_threads;
}
//!
//! retrieve a new task
//!
std::pair<bool, thread_pool::task_t>
thread_pool::fetch_task_or_stop(void) {
std::unique_lock<std::mutex> lock(m_tasks_mtx);
__TACOPIE_LOG(debug, "waiting to fetch task");
m_tasks_condvar.wait(lock, [&] { return should_stop() || !m_tasks.empty(); });
if (should_stop()) {
--m_nb_running_threads;
return {true, nullptr};
}
task_t task = std::move(m_tasks.front());
m_tasks.pop();
return {false, task};
}
//!
//! add tasks to thread pool
//!
void
thread_pool::add_task(const task_t& task) {
std::lock_guard<std::mutex> lock(m_tasks_mtx);
__TACOPIE_LOG(debug, "add task to thread_pool");
m_tasks.push(task);
m_tasks_condvar.notify_one();
}
thread_pool&
thread_pool::operator<<(const task_t& task) {
add_task(task);
return *this;
}
//!
//! adjust number of threads
//!
void
thread_pool::set_nb_threads(std::size_t nb_threads) {
m_max_nb_threads = nb_threads;
//! if we increased the number of threads, spawn them
while (m_nb_running_threads < m_max_nb_threads) {
++m_nb_running_threads;
m_workers.push_back(std::thread(std::bind(&thread_pool::run, this)));
}
//! otherwise, wake up threads to make them stop if necessary (until we get the right amount of threads)
if (m_nb_running_threads > m_max_nb_threads) {
m_tasks_condvar.notify_all();
}
}
} // namespace utils
} // namespace tacopie
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_CONFIG_ERROR_INCLUDED
#define MAPNIK_CONFIG_ERROR_INCLUDED
#include <iostream>
#include <sstream>
namespace mapnik {
class config_error : public std::exception
{
public:
config_error() {}
config_error( const std::string & what ) :
what_( what )
{
}
virtual ~config_error() throw() {};
virtual const char * what() const throw()
{
std::ostringstream os;
os << what_;
if ( ! context_.empty() )
{
os << std::endl << context_;
}
os << ".";
return os.str().c_str();
}
void append_context(const std::string & ctx) const
{
if ( ! context_.empty() )
{
context_ += " ";
}
context_ += ctx;
}
protected:
std::string what_;
mutable std::string context_;
};
}
#endif // MAPNIK_CONFIG_ERROR_INCLUDED
<commit_msg> - found and fixed another wild pointer<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_CONFIG_ERROR_INCLUDED
#define MAPNIK_CONFIG_ERROR_INCLUDED
#include <iostream>
#include <sstream>
namespace mapnik {
class config_error : public std::exception
{
public:
config_error() {}
config_error( const std::string & what ) :
what_( what )
{
}
virtual ~config_error() throw() {};
virtual const char * what() const throw()
{
return what_.c_str();
}
void append_context(const std::string & ctx) const
{
what_ += " " + ctx;
}
protected:
mutable std::string what_;
};
}
#endif // MAPNIK_CONFIG_ERROR_INCLUDED
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <guido.tack@monash.edu>
*/
/* 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/. */
#ifndef __MINIZINC_ASTITERATOR_HH__
#define __MINIZINC_ASTITERATOR_HH__
#include <minizinc/ast.hh>
#include <minizinc/hash.hh>
namespace MiniZinc {
/**
* \brief Bottom-up iterator for expressions
*/
template<class T>
class BottomUpIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Stack item
struct C {
/// Expression on the stack
Expression* _e;
/// Whether this expression has been visited before
bool _done;
/// If part of a generator expression, which one it is
int _gen_i;
/// Constructor
C(Expression* e) : _e(e), _done(false), _gen_i(-1) {}
/// Constructor for generator expression
C(Expression* e, int gen_i) : _e(e), _done(true), _gen_i(gen_i) {}
};
/// Push all elements of \a v onto \a stack
template<class E>
void pushVec(std::vector<C>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(C(v[i]));
}
public:
/// Constructor
BottomUpIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void bottomUp(T& t, Expression* e) {
BottomUpIterator<T>(t).run(e);
}
/**
* \brief Leaf iterator for expressions
*/
template<class T>
class TopDownIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Push all elements of \a v onto \a stack
template<class E>
static void pushVec(std::vector<Expression*>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(v[i]);
}
public:
/// Constructor
TopDownIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void topDown(T& t, Expression* e) {
TopDownIterator<T>(t).run(e);
}
/* IMPLEMENTATION */
template<class T> void
BottomUpIterator<T>::run(Expression* root) {
std::vector<C> stack;
if (_t.enter(root))
stack.push_back(C(root));
while (!stack.empty()) {
C& c = stack.back();
if (c._e==NULL) {
stack.pop_back();
continue;
}
if (c._done) {
switch (c._e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*c._e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*c._e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*c._e->template cast<SetLit>());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*c._e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*c._e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*c._e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*c._e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*c._e->template cast<ArrayLit>());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*c._e->template cast<ArrayAccess>());
break;
case Expression::E_COMP:
if (c._gen_i >= 0) {
_t.vComprehensionGenerator(*c._e->template cast<Comprehension>(), c._gen_i);
} else {
_t.vComprehension(*c._e->template cast<Comprehension>());
}
break;
case Expression::E_ITE:
_t.vITE(*c._e->template cast<ITE>());
break;
case Expression::E_BINOP:
_t.vBinOp(*c._e->template cast<BinOp>());
break;
case Expression::E_UNOP:
_t.vUnOp(*c._e->template cast<UnOp>());
break;
case Expression::E_CALL:
_t.vCall(*c._e->template cast<Call>());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*c._e->template cast<VarDecl>());
break;
case Expression::E_LET:
_t.vLet(*c._e->template cast<Let>());
break;
case Expression::E_TI:
_t.vTypeInst(*c._e->template cast<TypeInst>());
break;
case Expression::E_TIID:
_t.vTIId(*c._e->template cast<TIId>());
break;
}
_t.exit(c._e);
stack.pop_back();
} else {
c._done=true;
Expression* ce = c._e;
for (ExpressionSetIter it = ce->ann().begin(); it != ce->ann().end(); ++it) {
if (_t.enter(*it))
stack.push_back(C(*it));
}
if (_t.enter(ce)) {
switch (ce->eid()) {
case Expression::E_INTLIT:
case Expression::E_FLOATLIT:
case Expression::E_BOOLLIT:
case Expression::E_STRINGLIT:
case Expression::E_ANON:
case Expression::E_ID:
case Expression::E_TIID:
break;
case Expression::E_SETLIT:
pushVec(stack, ce->template cast<SetLit>()->v());
break;
case Expression::E_ARRAYLIT:
pushVec(stack, ce->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
pushVec(stack, ce->template cast<ArrayAccess>()->idx());
stack.push_back(C(ce->template cast<ArrayAccess>()->v()));
break;
case Expression::E_COMP:
{
Comprehension* comp = ce->template cast<Comprehension>();
stack.push_back(C(comp->e()));
stack.push_back(C(comp->where()));
for (unsigned int i=comp->n_generators(); i--; ) {
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(C(comp->decl(i, j)));
}
stack.push_back(C(comp,i));
stack.push_back(C(comp->in(i)));
}
}
break;
case Expression::E_ITE:
{
ITE* ite = ce->template cast<ITE>();
stack.push_back(C(ite->e_else()));
for (int i=0; i<ite->size(); i++) {
stack.push_back(C(ite->e_if(i)));
stack.push_back(C(ite->e_then(i)));
}
}
break;
case Expression::E_BINOP:
stack.push_back(C(ce->template cast<BinOp>()->rhs()));
stack.push_back(C(ce->template cast<BinOp>()->lhs()));
break;
case Expression::E_UNOP:
stack.push_back(C(ce->template cast<UnOp>()->e()));
break;
case Expression::E_CALL:
pushVec(stack, ce->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
stack.push_back(C(ce->template cast<VarDecl>()->e()));
stack.push_back(C(ce->template cast<VarDecl>()->ti()));
break;
case Expression::E_LET:
stack.push_back(C(ce->template cast<Let>()->in()));
pushVec(stack, ce->template cast<Let>()->let());
break;
case Expression::E_TI:
stack.push_back(C(ce->template cast<TypeInst>()->domain()));
pushVec(stack,ce->template cast<TypeInst>()->ranges());
break;
}
} else {
c._e = NULL;
}
}
}
}
template<class T> void
TopDownIterator<T>::run(Expression* root) {
std::vector<Expression*> stack;
if (_t.enter(root))
stack.push_back(root);
while (!stack.empty()) {
Expression* e = stack.back();
stack.pop_back();
if (e==NULL) {
continue;
}
switch (e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*e->template cast<SetLit>());
pushVec(stack, e->template cast<SetLit>()->v());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*e->template cast<ArrayLit>());
pushVec(stack, e->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*e->template cast<ArrayAccess>());
pushVec(stack, e->template cast<ArrayAccess>()->idx());
stack.push_back(e->template cast<ArrayAccess>()->v());
break;
case Expression::E_COMP:
_t.vComprehension(*e->template cast<Comprehension>());
{
Comprehension* comp = e->template cast<Comprehension>();
stack.push_back(comp->where());
for (unsigned int i=comp->n_generators(); i--; ) {
stack.push_back(comp->in(i));
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(comp->decl(i, j));
}
}
stack.push_back(comp->e());
}
break;
case Expression::E_ITE:
_t.vITE(*e->template cast<ITE>());
{
ITE* ite = e->template cast<ITE>();
stack.push_back(ite->e_else());
for (int i=0; i<ite->size(); i++) {
stack.push_back(ite->e_if(i));
stack.push_back(ite->e_then(i));
}
}
break;
case Expression::E_BINOP:
_t.vBinOp(*e->template cast<BinOp>());
stack.push_back(e->template cast<BinOp>()->rhs());
stack.push_back(e->template cast<BinOp>()->lhs());
break;
case Expression::E_UNOP:
_t.vUnOp(*e->template cast<UnOp>());
stack.push_back(e->template cast<UnOp>()->e());
break;
case Expression::E_CALL:
_t.vCall(*e->template cast<Call>());
pushVec(stack, e->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*e->template cast<VarDecl>());
stack.push_back(e->template cast<VarDecl>()->e());
stack.push_back(e->template cast<VarDecl>()->ti());
break;
case Expression::E_LET:
_t.vLet(*e->template cast<Let>());
stack.push_back(e->template cast<Let>()->in());
pushVec(stack, e->template cast<Let>()->let());
break;
case Expression::E_TI:
_t.vTypeInst(*e->template cast<TypeInst>());
stack.push_back(e->template cast<TypeInst>()->domain());
pushVec(stack,e->template cast<TypeInst>()->ranges());
break;
case Expression::E_TIID:
_t.vTIId(*e->template cast<TIId>());
break;
}
}
}
}
#endif
<commit_msg>Add enter method to top down iterator (was not used properly before)<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <guido.tack@monash.edu>
*/
/* 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/. */
#ifndef __MINIZINC_ASTITERATOR_HH__
#define __MINIZINC_ASTITERATOR_HH__
#include <minizinc/ast.hh>
#include <minizinc/hash.hh>
namespace MiniZinc {
/**
* \brief Bottom-up iterator for expressions
*/
template<class T>
class BottomUpIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Stack item
struct C {
/// Expression on the stack
Expression* _e;
/// Whether this expression has been visited before
bool _done;
/// If part of a generator expression, which one it is
int _gen_i;
/// Constructor
C(Expression* e) : _e(e), _done(false), _gen_i(-1) {}
/// Constructor for generator expression
C(Expression* e, int gen_i) : _e(e), _done(true), _gen_i(gen_i) {}
};
/// Push all elements of \a v onto \a stack
template<class E>
void pushVec(std::vector<C>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(C(v[i]));
}
public:
/// Constructor
BottomUpIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void bottomUp(T& t, Expression* e) {
BottomUpIterator<T>(t).run(e);
}
/**
* \brief Leaf iterator for expressions
*/
template<class T>
class TopDownIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Push all elements of \a v onto \a stack
template<class E>
static void pushVec(std::vector<Expression*>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(v[i]);
}
public:
/// Constructor
TopDownIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void topDown(T& t, Expression* e) {
TopDownIterator<T>(t).run(e);
}
/* IMPLEMENTATION */
template<class T> void
BottomUpIterator<T>::run(Expression* root) {
std::vector<C> stack;
if (_t.enter(root))
stack.push_back(C(root));
while (!stack.empty()) {
C& c = stack.back();
if (c._e==NULL) {
stack.pop_back();
continue;
}
if (c._done) {
switch (c._e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*c._e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*c._e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*c._e->template cast<SetLit>());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*c._e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*c._e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*c._e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*c._e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*c._e->template cast<ArrayLit>());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*c._e->template cast<ArrayAccess>());
break;
case Expression::E_COMP:
if (c._gen_i >= 0) {
_t.vComprehensionGenerator(*c._e->template cast<Comprehension>(), c._gen_i);
} else {
_t.vComprehension(*c._e->template cast<Comprehension>());
}
break;
case Expression::E_ITE:
_t.vITE(*c._e->template cast<ITE>());
break;
case Expression::E_BINOP:
_t.vBinOp(*c._e->template cast<BinOp>());
break;
case Expression::E_UNOP:
_t.vUnOp(*c._e->template cast<UnOp>());
break;
case Expression::E_CALL:
_t.vCall(*c._e->template cast<Call>());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*c._e->template cast<VarDecl>());
break;
case Expression::E_LET:
_t.vLet(*c._e->template cast<Let>());
break;
case Expression::E_TI:
_t.vTypeInst(*c._e->template cast<TypeInst>());
break;
case Expression::E_TIID:
_t.vTIId(*c._e->template cast<TIId>());
break;
}
_t.exit(c._e);
stack.pop_back();
} else {
c._done=true;
Expression* ce = c._e;
for (ExpressionSetIter it = ce->ann().begin(); it != ce->ann().end(); ++it) {
if (_t.enter(*it))
stack.push_back(C(*it));
}
if (_t.enter(ce)) {
switch (ce->eid()) {
case Expression::E_INTLIT:
case Expression::E_FLOATLIT:
case Expression::E_BOOLLIT:
case Expression::E_STRINGLIT:
case Expression::E_ANON:
case Expression::E_ID:
case Expression::E_TIID:
break;
case Expression::E_SETLIT:
pushVec(stack, ce->template cast<SetLit>()->v());
break;
case Expression::E_ARRAYLIT:
pushVec(stack, ce->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
pushVec(stack, ce->template cast<ArrayAccess>()->idx());
stack.push_back(C(ce->template cast<ArrayAccess>()->v()));
break;
case Expression::E_COMP:
{
Comprehension* comp = ce->template cast<Comprehension>();
stack.push_back(C(comp->e()));
stack.push_back(C(comp->where()));
for (unsigned int i=comp->n_generators(); i--; ) {
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(C(comp->decl(i, j)));
}
stack.push_back(C(comp,i));
stack.push_back(C(comp->in(i)));
}
}
break;
case Expression::E_ITE:
{
ITE* ite = ce->template cast<ITE>();
stack.push_back(C(ite->e_else()));
for (int i=0; i<ite->size(); i++) {
stack.push_back(C(ite->e_if(i)));
stack.push_back(C(ite->e_then(i)));
}
}
break;
case Expression::E_BINOP:
stack.push_back(C(ce->template cast<BinOp>()->rhs()));
stack.push_back(C(ce->template cast<BinOp>()->lhs()));
break;
case Expression::E_UNOP:
stack.push_back(C(ce->template cast<UnOp>()->e()));
break;
case Expression::E_CALL:
pushVec(stack, ce->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
stack.push_back(C(ce->template cast<VarDecl>()->e()));
stack.push_back(C(ce->template cast<VarDecl>()->ti()));
break;
case Expression::E_LET:
stack.push_back(C(ce->template cast<Let>()->in()));
pushVec(stack, ce->template cast<Let>()->let());
break;
case Expression::E_TI:
stack.push_back(C(ce->template cast<TypeInst>()->domain()));
pushVec(stack,ce->template cast<TypeInst>()->ranges());
break;
}
} else {
c._e = NULL;
}
}
}
}
template<class T> void
TopDownIterator<T>::run(Expression* root) {
std::vector<Expression*> stack;
if (_t.enter(root))
stack.push_back(root);
while (!stack.empty()) {
Expression* e = stack.back();
stack.pop_back();
if (e==NULL) {
continue;
}
if (!_t.enter(e))
continue;
switch (e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*e->template cast<SetLit>());
pushVec(stack, e->template cast<SetLit>()->v());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*e->template cast<ArrayLit>());
pushVec(stack, e->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*e->template cast<ArrayAccess>());
pushVec(stack, e->template cast<ArrayAccess>()->idx());
stack.push_back(e->template cast<ArrayAccess>()->v());
break;
case Expression::E_COMP:
_t.vComprehension(*e->template cast<Comprehension>());
{
Comprehension* comp = e->template cast<Comprehension>();
stack.push_back(comp->where());
for (unsigned int i=comp->n_generators(); i--; ) {
stack.push_back(comp->in(i));
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(comp->decl(i, j));
}
}
stack.push_back(comp->e());
}
break;
case Expression::E_ITE:
_t.vITE(*e->template cast<ITE>());
{
ITE* ite = e->template cast<ITE>();
stack.push_back(ite->e_else());
for (int i=0; i<ite->size(); i++) {
stack.push_back(ite->e_if(i));
stack.push_back(ite->e_then(i));
}
}
break;
case Expression::E_BINOP:
_t.vBinOp(*e->template cast<BinOp>());
stack.push_back(e->template cast<BinOp>()->rhs());
stack.push_back(e->template cast<BinOp>()->lhs());
break;
case Expression::E_UNOP:
_t.vUnOp(*e->template cast<UnOp>());
stack.push_back(e->template cast<UnOp>()->e());
break;
case Expression::E_CALL:
_t.vCall(*e->template cast<Call>());
pushVec(stack, e->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*e->template cast<VarDecl>());
stack.push_back(e->template cast<VarDecl>()->e());
stack.push_back(e->template cast<VarDecl>()->ti());
break;
case Expression::E_LET:
_t.vLet(*e->template cast<Let>());
stack.push_back(e->template cast<Let>()->in());
pushVec(stack, e->template cast<Let>()->let());
break;
case Expression::E_TI:
_t.vTypeInst(*e->template cast<TypeInst>());
stack.push_back(e->template cast<TypeInst>()->domain());
pushVec(stack,e->template cast<TypeInst>()->ranges());
break;
case Expression::E_TIID:
_t.vTIId(*e->template cast<TIId>());
break;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_
#define _Stroika_Foundation_DataExchange_OptionsFile_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Characters/Format.h"
#include "../Streams/BasicBinaryOutputStream.h"
namespace Stroika {
namespace Foundation {
namespace DataExchange {
/*
********************************************************************************
************************** DataExchange::OptionsFile ***************************
********************************************************************************
*/
template <typename T>
Optional<T> OptionsFile::Read ()
{
Optional<VariantValue> tmp = Read<VariantValue> ();
if (tmp.IsMissing ()) {
return Optional<T> ();
}
try {
return fMapper_.ToObject<T> (*tmp);
}
catch (const BadFormatException& bf) {
fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetReadFilePath_ ().c_str ()));
return Optional<T> ();
}
catch (...) {
// if this fails, its probably because somehow the data in the config file was bad.
// So at least log that, and continue without reading anything (as if empty file)
fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetReadFilePath_ ().c_str ()));
return Optional<T> ();
}
}
template <typename T>
T OptionsFile::Read (const T& defaultObj, ReadFlags readFlags)
{
Optional<T> eltRead = Read<T> ();
Optional<T> elt2Write; // only if needed
String msgAugment;
if (eltRead.IsMissing ()) {
if (readFlags == ReadFlags::eWriteIfChanged) {
elt2Write = defaultObj;
msgAugment = L" so defaults are more easily editable";
}
}
else {
if (readFlags == ReadFlags::eWriteIfChanged) {
if (elt2Write.IsMissing ()) {
// if filename differs - upgrading
if (GetReadFilePath_ () != GetWriteFilePath_ ()) {
elt2Write = eltRead;
msgAugment = L" in a new directory because upgrading the software has been upgraded";
}
}
if (elt2Write.IsMissing ()) {
try {
// See if re-persisting the item would change it.
// This is useful if your data model adds or removes fields. It updates the file contents written to the
// upgraded/latest form.
Memory::BLOB oldData = ReadRaw (); // @todo could have saved from previous Read<T>
Memory::BLOB newData;
{
Streams::BasicBinaryOutputStream outStream;
fWriter_.Write (fMapper_.FromObject (*eltRead), outStream);
// not sure needed? outStream.Flush();
newData = outStream.As<Memory::BLOB> ();
}
if (oldData != newData) {
elt2Write = eltRead;
msgAugment = L" because something changed (e.g. a default, or field added/removed).";
}
}
catch (...) {
fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetReadFilePath_ ().c_str ()));
}
}
}
}
if (elt2Write.IsPresent ()) {
fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing configuration file '%s'%s.", GetWriteFilePath_ ().c_str (), msgAugment.c_str ()));
try {
Write (*elt2Write);
}
catch (...) {
fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetWriteFilePath_ ().c_str ()));
}
return *elt2Write;
}
else if (eltRead.IsPresent ()) {
return *eltRead;
}
else {
return defaultObj;
}
}
template <typename T>
void OptionsFile::Write (const T& optionsObject)
{
Write<VariantValue> (fMapper_.FromObject<T> (optionsObject));
}
}
}
}
#endif /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/
<commit_msg>updated OptionsFile message<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_
#define _Stroika_Foundation_DataExchange_OptionsFile_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Characters/Format.h"
#include "../Streams/BasicBinaryOutputStream.h"
namespace Stroika {
namespace Foundation {
namespace DataExchange {
/*
********************************************************************************
************************** DataExchange::OptionsFile ***************************
********************************************************************************
*/
template <typename T>
Optional<T> OptionsFile::Read ()
{
Optional<VariantValue> tmp = Read<VariantValue> ();
if (tmp.IsMissing ()) {
return Optional<T> ();
}
try {
return fMapper_.ToObject<T> (*tmp);
}
catch (const BadFormatException& bf) {
fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetReadFilePath_ ().c_str ()));
return Optional<T> ();
}
catch (...) {
// if this fails, its probably because somehow the data in the config file was bad.
// So at least log that, and continue without reading anything (as if empty file)
fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetReadFilePath_ ().c_str ()));
return Optional<T> ();
}
}
template <typename T>
T OptionsFile::Read (const T& defaultObj, ReadFlags readFlags)
{
Optional<T> eltRead = Read<T> ();
Optional<T> elt2Write; // only if needed
String msgAugment;
if (eltRead.IsMissing ()) {
if (readFlags == ReadFlags::eWriteIfChanged) {
elt2Write = defaultObj;
msgAugment = L" so defaults are more easily editable";
}
}
else {
if (readFlags == ReadFlags::eWriteIfChanged) {
if (elt2Write.IsMissing ()) {
// if filename differs - upgrading
if (GetReadFilePath_ () != GetWriteFilePath_ ()) {
elt2Write = eltRead;
msgAugment = L" in a new directory because the software has been upgraded";
}
}
if (elt2Write.IsMissing ()) {
try {
// See if re-persisting the item would change it.
// This is useful if your data model adds or removes fields. It updates the file contents written to the
// upgraded/latest form.
Memory::BLOB oldData = ReadRaw (); // @todo could have saved from previous Read<T>
Memory::BLOB newData;
{
Streams::BasicBinaryOutputStream outStream;
fWriter_.Write (fMapper_.FromObject (*eltRead), outStream);
// not sure needed? outStream.Flush();
newData = outStream.As<Memory::BLOB> ();
}
if (oldData != newData) {
elt2Write = eltRead;
msgAugment = L" because something changed (e.g. a default, or field added/removed).";
}
}
catch (...) {
fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetReadFilePath_ ().c_str ()));
}
}
}
}
if (elt2Write.IsPresent ()) {
fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing configuration file '%s'%s.", GetWriteFilePath_ ().c_str (), msgAugment.c_str ()));
try {
Write (*elt2Write);
}
catch (...) {
fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetWriteFilePath_ ().c_str ()));
}
return *elt2Write;
}
else if (eltRead.IsPresent ()) {
return *eltRead;
}
else {
return defaultObj;
}
}
template <typename T>
void OptionsFile::Write (const T& optionsObject)
{
Write<VariantValue> (fMapper_.FromObject<T> (optionsObject));
}
}
}
}
#endif /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief TELNET サーバー・クラス @n
0xF0 [Sub-negotiaon End] 2次交渉終了 2次交渉パラメータの終了 @n
0xF1 [No Operation] オペレーションなし オペレーションなし。受信した側はこれを無視する @n
0xF2 [Data Mark] データマーク データ削除・リセット @n
0xF3 [Break] ブレーク ブレーク @n
0xF4 [Interrupt Process] プロセス中断 操作の一時中断・割り込み・停止 @n
0xF5 [Abort Output] 出力中止 出力を抑止する @n
0xF6 [Are You There] 相手確認 相手が動作しているかどうか確認する @n
0xF7 [Erase Character] 文字消去 最後の文字を消去する @n
0xF8 [Erase Line] 行消去 最後の行をすべて消去する @n
0xF9 [Go Ahead] 送信勧誘 送信するように受信側にうながす @n
0xFA [Sub-negotiation Begin] 2次交渉開始 2次交渉の開始 @n
0xFB WILL オプション希望 @n
0xFC WON'T オプション拒絶 @n
0xFD DO オプション実行要求 @n
0xFE DON'T オプション使用中止 @n
0xFF [Interpret as Command] コマンドとして解釈 telnetエスケープシーケンス @n
オプション・コード @n
0x00 [Transmit Binary] バイナリ転送 IAC以外の文字列はバイナリデータと解釈される @n
0x01 [Echo] エコー データのエコー @n
0x03 [Suppress Go Ahead] Go Ahead抑止 Go Aheadコマンドを使わないようにする @n
0x05 [Telnet Status Option] telnet状態オプション 相手側のtelnetオプションの状態を見られるようにする @n
0x06 [Telnet Timing Mark] telnetタイミングマーク 受信したデータが処理済ならばタイミングマークというデータを送る @n
0x18 [Terminal Type] ターミナルタイプ ターミナルタイプを交換可能にし、適切なターミナルタイプを設定する @n
0x22 [Telnet Line Mode] telnetラインモード 行単位で転送できるようにする
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "ethernet_server.hpp"
#include "common/fixed_fifo.hpp"
#define TELNETS_DEBUG
namespace net {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief telnet_server class テンプレート
@param[in] SEND_SIZE 送信、一時バッファサイズ
@param[in] RECV_SIZE 受信、一時バッファサイズ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t SEND_SIZE, uint32_t RECV_SIZE>
class telnet_server {
private:
// デバッグ以外で出力を無効にする
#ifdef TELNETS_DEBUG
typedef utils::format debug_format;
#else
typedef utils::null_format debug_format;
#endif
ethernet& eth_;
ethernet_server telnet_;
enum class task : uint8_t {
none,
begin,
wait,
main_loop,
disconnect_delay,
disconnect,
};
task task_;
char server_name_[32];
char user_[32];
char pass_[32];
uint32_t count_;
uint32_t disconnect_loop_;
typedef utils::fixed_fifo<char, SEND_SIZE> SEND_FIFO;
typedef utils::fixed_fifo<char, RECV_SIZE> RECV_FIFO;
SEND_FIFO send_;
RECV_FIFO recv_;
bool crlf_;
enum class esc_task : uint8_t {
none,
entry,
option,
second,
second_end,
};
esc_task esc_task_;
void write_()
{
char tmp[1024];
uint16_t l = 0;
while(send_.length() > 0) {
auto ch = send_.get();
tmp[l] = ch;
++l;
if(l >= sizeof(tmp)) {
telnet_.write(tmp, l);
l = 0;
}
}
if(l > 0) {
telnet_.write(tmp, l);
}
}
bool service_options_(char ch)
{
bool ret = true;
switch(esc_task_) {
case esc_task::entry:
if(ch == 0xFB || ch == 0xFC || ch == 0xFD || ch == 0xFE) {
esc_task_ = esc_task::option;
ret = false;
} else if(ch == 0xFA) { // 二次交渉開始
esc_task_ = esc_task::second;
ret = false;
}
break;
case esc_task::option:
esc_task_ = esc_task::none;
ret = false;
break;
case esc_task::second:
if(ch == 0xFF) {
esc_task_ = esc_task::second_end;
}
ret = false;
break;
case esc_task::second_end:
if(ch == 0xF0) {
esc_task_ = esc_task::none;
}
ret = false;
break;
case esc_task::none:
default:
if(ch == 0xFF) { // TELNET ESC シーケンス開始
esc_task_ = esc_task::entry;
ret = false;
}
break;
}
return ret;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] e イーサーネット・コンテキスト
@param[in] crlf LF コードを CR/LF に変換しない場合「false」
*/
//-----------------------------------------------------------------//
telnet_server(ethernet& e, bool crlf = true) : eth_(e), telnet_(e), task_(task::none),
server_name_{ 0 }, user_{ 0 }, pass_{ 0 },
count_(0), disconnect_loop_(0), crlf_(crlf),
esc_task_(esc_task::none)
{ }
//-----------------------------------------------------------------//
/*!
@brief スタート
@param[in] server_name サーバー名
@param[in] user ユーザー名
@param[in] pass パスワード
*/
//-----------------------------------------------------------------//
void start(const char* server_name, const char* user = nullptr, const char* pass = nullptr)
{
std::strncpy(server_name_, server_name, sizeof(server_name_) - 1);
if(user != nullptr) std::strncpy(user_, user, sizeof(user_) - 1);
if(pass != nullptr) std::strncpy(pass_, pass, sizeof(pass_) - 1);
count_ = 0;
disconnect_loop_ = 0;
esc_task_ = esc_task::none;
task_ = task::begin;
debug_format("TELNET Server: SEND_BUFF: %d, RECV_BUFF: %d\n") % SEND_SIZE % RECV_SIZE;
}
//-----------------------------------------------------------------//
/*!
@brief 接続の確認
@return 接続中なら「true」
*/
//-----------------------------------------------------------------//
bool probe() const { return task_ == task::main_loop; }
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] cycle サービス・サイクル(通常100Hz)
@param[in] port TELNET ポート番号(通常23番)
*/
//-----------------------------------------------------------------//
void service(uint32_t cycle, uint16_t port = 23)
{
switch(task_) {
case task::none:
break;
case task::begin:
telnet_.begin(port);
debug_format("Start TELNET Server: '%s' port(%d), fd(%d)\n")
% eth_.get_local_ip().c_str()
% static_cast<int>(telnet_.get_port()) % telnet_.get_cepid();
task_ = task::wait;
break;
case task::wait:
if(telnet_.connected()) {
debug_format("TELNET Server: New connected, from: %s\n") % telnet_.get_from_ip().c_str();
++count_;
task_ = task::main_loop;
}
break;
case task::main_loop:
if(telnet_.connected()) {
if(telnet_.available() > 0) { // リードデータがあるか?
char tmp[256];
int len = telnet_.read(tmp, sizeof(tmp));
if(len > 0) {
int l = 0;
// utils::format("Len: %d\n") % len;
while((recv_.size() - recv_.length()) > 2) {
char ch = tmp[l];
++l;
if(service_options_(ch)) {
/// putch(ch); // local echo
/// utils::format("%d: %02X\n") % l % static_cast<uint16_t>(ch);
recv_.put(ch);
}
if(l >= len) break;
}
}
}
write_();
} else {
task_ = task::disconnect_delay;
disconnect_loop_ = 10;
}
break;
case task::disconnect_delay:
if(disconnect_loop_ > 0) {
--disconnect_loop_;
} else {
task_ = task::disconnect;
}
break;
case task::disconnect:
default:
telnet_.stop();
debug_format("TELNET Server: disconnected\n");
task_ = task::begin;
break;
}
}
//-----------------------------------------------------------------//
/*!
@brief 出力
@param[in] ch 出力文字
*/
//-----------------------------------------------------------------//
void putch(char ch)
{
if(crlf_ && ch == '\n') {
putch('\r');
}
if(task_ == task::main_loop) {
if((send_.size() - send_.length()) <= 2) {
write_();
}
send_.put(ch);
// if(ch == '\r') {
// flush_();
// }
}
}
//-----------------------------------------------------------------//
/*!
@brief 出力
@param[in] str 出力文字列
*/
//-----------------------------------------------------------------//
void puts(const char* str)
{
if(str == nullptr) return;
char ch;
while((ch = *str++) != 0) {
putch(ch);
}
}
//-----------------------------------------------------------------//
/*!
@brief 入力文字数取得
@return 入力文字数
*/
//-----------------------------------------------------------------//
uint32_t length() const
{
return recv_.length();
}
//-----------------------------------------------------------------//
/*!
@brief 入力文字取得
@return 入力文字(入力文字が無い場合「0」が返る)
*/
//-----------------------------------------------------------------//
char getch()
{
if(recv_.length() > 0) {
return recv_.get();
} else {
utils::format("!!!!\n");
return 0;
}
}
};
}
<commit_msg>update: cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief TELNET サーバー・クラス @n
0xF0 [Sub-negotiaon End] 2次交渉終了 2次交渉パラメータの終了 @n
0xF1 [No Operation] オペレーションなし オペレーションなし。受信した側はこれを無視する @n
0xF2 [Data Mark] データマーク データ削除・リセット @n
0xF3 [Break] ブレーク ブレーク @n
0xF4 [Interrupt Process] プロセス中断 操作の一時中断・割り込み・停止 @n
0xF5 [Abort Output] 出力中止 出力を抑止する @n
0xF6 [Are You There] 相手確認 相手が動作しているかどうか確認する @n
0xF7 [Erase Character] 文字消去 最後の文字を消去する @n
0xF8 [Erase Line] 行消去 最後の行をすべて消去する @n
0xF9 [Go Ahead] 送信勧誘 送信するように受信側にうながす @n
0xFA [Sub-negotiation Begin] 2次交渉開始 2次交渉の開始 @n
0xFB WILL オプション希望 @n
0xFC WON'T オプション拒絶 @n
0xFD DO オプション実行要求 @n
0xFE DON'T オプション使用中止 @n
0xFF [Interpret as Command] コマンドとして解釈 telnetエスケープシーケンス @n
オプション・コード @n
0x00 [Transmit Binary] バイナリ転送 IAC以外の文字列はバイナリデータと解釈される @n
0x01 [Echo] エコー データのエコー @n
0x03 [Suppress Go Ahead] Go Ahead抑止 Go Aheadコマンドを使わないようにする @n
0x05 [Telnet Status Option] telnet状態オプション 相手側のtelnetオプションの状態を見られるようにする @n
0x06 [Telnet Timing Mark] telnetタイミングマーク 受信したデータが処理済ならばタイミングマークというデータを送る @n
0x18 [Terminal Type] ターミナルタイプ ターミナルタイプを交換可能にし、適切なターミナルタイプを設定する @n
0x22 [Telnet Line Mode] telnetラインモード 行単位で転送できるようにする
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "ethernet_server.hpp"
#include "common/fixed_fifo.hpp"
#define TELNETS_DEBUG
namespace net {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief telnet_server class テンプレート
@param[in] SEND_SIZE 送信、一時バッファサイズ
@param[in] RECV_SIZE 受信、一時バッファサイズ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t SEND_SIZE, uint32_t RECV_SIZE>
class telnet_server {
private:
// デバッグ以外で出力を無効にする
#ifdef TELNETS_DEBUG
typedef utils::format debug_format;
#else
typedef utils::null_format debug_format;
#endif
ethernet& eth_;
ethernet_server telnet_;
enum class task : uint8_t {
none,
begin,
wait,
main_loop,
disconnect_delay,
disconnect,
};
task task_;
char server_name_[32];
char user_[32];
char pass_[32];
uint32_t count_;
uint32_t disconnect_loop_;
typedef utils::fixed_fifo<char, SEND_SIZE> SEND_FIFO;
typedef utils::fixed_fifo<char, RECV_SIZE> RECV_FIFO;
SEND_FIFO send_;
RECV_FIFO recv_;
bool crlf_;
enum class esc_task : uint8_t {
none,
entry,
option,
second,
second_end,
};
esc_task esc_task_;
void write_()
{
char tmp[1024];
uint16_t l = 0;
while(send_.length() > 0) {
auto ch = send_.get();
tmp[l] = ch;
++l;
if(l >= sizeof(tmp)) {
telnet_.write(tmp, l);
l = 0;
}
}
if(l > 0) {
telnet_.write(tmp, l);
}
}
bool service_options_(char ch)
{
bool ret = true;
switch(esc_task_) {
case esc_task::entry:
if(ch == 0xFB || ch == 0xFC || ch == 0xFD || ch == 0xFE) {
esc_task_ = esc_task::option;
ret = false;
} else if(ch == 0xFA) { // 二次交渉開始
esc_task_ = esc_task::second;
ret = false;
}
break;
case esc_task::option:
esc_task_ = esc_task::none;
ret = false;
break;
case esc_task::second:
if(ch == 0xFF) {
esc_task_ = esc_task::second_end;
}
ret = false;
break;
case esc_task::second_end:
if(ch == 0xF0) {
esc_task_ = esc_task::none;
}
ret = false;
break;
case esc_task::none:
default:
if(ch == 0xFF) { // TELNET ESC シーケンス開始
esc_task_ = esc_task::entry;
ret = false;
}
break;
}
return ret;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] e イーサーネット・コンテキスト
@param[in] crlf LF コードを CR/LF に変換しない場合「false」
*/
//-----------------------------------------------------------------//
telnet_server(ethernet& e, bool crlf = true) : eth_(e), telnet_(e), task_(task::none),
server_name_{ 0 }, user_{ 0 }, pass_{ 0 },
count_(0), disconnect_loop_(0), crlf_(crlf),
esc_task_(esc_task::none)
{ }
//-----------------------------------------------------------------//
/*!
@brief スタート
@param[in] server_name サーバー名
@param[in] user ユーザー名
@param[in] pass パスワード
*/
//-----------------------------------------------------------------//
void start(const char* server_name, const char* user = nullptr, const char* pass = nullptr)
{
std::strncpy(server_name_, server_name, sizeof(server_name_) - 1);
if(user != nullptr) std::strncpy(user_, user, sizeof(user_) - 1);
if(pass != nullptr) std::strncpy(pass_, pass, sizeof(pass_) - 1);
count_ = 0;
disconnect_loop_ = 0;
esc_task_ = esc_task::none;
task_ = task::begin;
debug_format("TELNET Server: SEND_BUFF: %d, RECV_BUFF: %d\n") % SEND_SIZE % RECV_SIZE;
}
//-----------------------------------------------------------------//
/*!
@brief 接続の確認
@return 接続中なら「true」
*/
//-----------------------------------------------------------------//
bool probe() const { return task_ == task::main_loop; }
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] cycle サービス・サイクル(通常100Hz)
@param[in] port TELNET ポート番号(通常23番)
*/
//-----------------------------------------------------------------//
void service(uint32_t cycle, uint16_t port = 23)
{
switch(task_) {
case task::none:
break;
case task::begin:
telnet_.begin(port);
debug_format("Start TELNET Server: '%s' port(%d), fd(%d)\n")
% eth_.get_local_ip().c_str()
% static_cast<int>(telnet_.get_port()) % telnet_.get_cepid();
task_ = task::wait;
break;
case task::wait:
if(telnet_.connected()) {
debug_format("TELNET Server: New connected, from: %s\n")
% telnet_.get_from_ip().c_str();
++count_;
task_ = task::main_loop;
}
break;
case task::main_loop:
if(telnet_.connected()) {
if(telnet_.available() > 0) { // リードデータがあるか?
char tmp[256];
int len = telnet_.read(tmp, sizeof(tmp));
if(len > 0) {
int l = 0;
// utils::format("Len: %d\n") % len;
while((recv_.size() - recv_.length()) > 2) {
char ch = tmp[l];
++l;
if(service_options_(ch)) {
/// putch(ch); // local echo
/// utils::format("%d: %02X\n") % l % static_cast<uint16_t>(ch);
recv_.put(ch);
}
if(l >= len) break;
}
}
}
write_();
} else {
task_ = task::disconnect_delay;
disconnect_loop_ = 10;
}
break;
case task::disconnect_delay:
if(disconnect_loop_ > 0) {
--disconnect_loop_;
} else {
task_ = task::disconnect;
}
break;
case task::disconnect:
default:
telnet_.stop();
debug_format("TELNET Server: disconnected\n");
task_ = task::begin;
break;
}
}
//-----------------------------------------------------------------//
/*!
@brief 出力
@param[in] ch 出力文字
*/
//-----------------------------------------------------------------//
void putch(char ch)
{
if(crlf_ && ch == '\n') {
putch('\r');
}
if(task_ == task::main_loop) {
if((send_.size() - send_.length()) <= 2) {
write_();
}
send_.put(ch);
// if(ch == '\r') {
// flush_();
// }
}
}
//-----------------------------------------------------------------//
/*!
@brief 出力
@param[in] str 出力文字列
*/
//-----------------------------------------------------------------//
void puts(const char* str)
{
if(str == nullptr) return;
char ch;
while((ch = *str++) != 0) {
putch(ch);
}
}
//-----------------------------------------------------------------//
/*!
@brief 入力文字数取得
@return 入力文字数
*/
//-----------------------------------------------------------------//
uint32_t length() const
{
return recv_.length();
}
//-----------------------------------------------------------------//
/*!
@brief 入力文字取得
@return 入力文字(入力文字が無い場合「0」が返る)
*/
//-----------------------------------------------------------------//
char getch()
{
if(recv_.length() > 0) {
return recv_.get();
} else {
utils::format("!!!!\n");
return 0;
}
}
};
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplicationFactory.h"
#include "otbWrapperCompositeApplication.h"
namespace otb
{
namespace Wrapper
{
class BundleToPerfectSensor : public CompositeApplication
{
public:
/** Standard class typedefs. */
typedef BundleToPerfectSensor Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(BundleToPerfectSensor, otb::Wrapper::CompositeApplication);
private:
void DoInit() ITK_OVERRIDE
{
SetName("BundleToPerfectSensor");
SetDescription("Perform P+XS pansharpening");
// Documentation
SetDocName("Bundle to perfect sensor");
SetDocLongDescription("This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion (\"default mode\"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag(Tags::Pansharpening);
AddApplication("Superimpose", "superimpose", "Reproject XS onto Pan");
AddApplication("Pansharpening", "pansharp", "Fusion of XS and Pan");
ShareParameter("inp","superimpose.inr","Input PAN Image","Input panchromatic image.");
ShareParameter("inxs","superimpose.inm","Input XS Image","Input XS image.");
ShareParameter("out","pansharp.out");
ShareParameter("elev","superimpose.elev");
ShareParameter("mode","superimpose.mode");
ShareParameter("lms","superimpose.lms",
"Spacing of the deformation field",
"Spacing of the deformation field. Default is 10 times the PAN image spacing.");
ShareParameter("ram","superimpose.ram");
Connect("pansharp.inp","superimpose.inr");
Connect("pansharp.ram","superimpose.ram");
GetInternalApplication("superimpose")->SetParameterString("interpolator","bco");
GetInternalApplication("pansharp")->SetParameterString("method","rcs");
// Doc example parameter settings
SetDocExampleParameterValue("inp", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inxs", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "BundleToPerfectSensor.png uchar");
}
void DoUpdateParameters() ITK_OVERRIDE
{
UpdateInternalParameters("superimpose");
}
void DoExecute() ITK_OVERRIDE
{
ExecuteInternal("superimpose");
GetInternalApplication("pansharp")->SetParameterInputImage("inxs",
GetInternalApplication("superimpose")->GetParameterOutputImage("out"));
ExecuteInternal("pansharp");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::BundleToPerfectSensor)
<commit_msg>ENH: clean application in DoInit()<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplicationFactory.h"
#include "otbWrapperCompositeApplication.h"
namespace otb
{
namespace Wrapper
{
class BundleToPerfectSensor : public CompositeApplication
{
public:
/** Standard class typedefs. */
typedef BundleToPerfectSensor Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(BundleToPerfectSensor, otb::Wrapper::CompositeApplication);
private:
void DoInit() ITK_OVERRIDE
{
SetName("BundleToPerfectSensor");
SetDescription("Perform P+XS pansharpening");
// Documentation
SetDocName("Bundle to perfect sensor");
SetDocLongDescription("This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion (\"default mode\"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag(Tags::Pansharpening);
ClearApplications();
AddApplication("Superimpose", "superimpose", "Reproject XS onto Pan");
AddApplication("Pansharpening", "pansharp", "Fusion of XS and Pan");
ShareParameter("inp","superimpose.inr","Input PAN Image","Input panchromatic image.");
ShareParameter("inxs","superimpose.inm","Input XS Image","Input XS image.");
ShareParameter("out","pansharp.out");
ShareParameter("elev","superimpose.elev");
ShareParameter("mode","superimpose.mode");
ShareParameter("lms","superimpose.lms",
"Spacing of the deformation field",
"Spacing of the deformation field. Default is 10 times the PAN image spacing.");
ShareParameter("ram","superimpose.ram");
Connect("pansharp.inp","superimpose.inr");
Connect("pansharp.ram","superimpose.ram");
GetInternalApplication("superimpose")->SetParameterString("interpolator","bco");
GetInternalApplication("pansharp")->SetParameterString("method","rcs");
// Doc example parameter settings
SetDocExampleParameterValue("inp", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inxs", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "BundleToPerfectSensor.png uchar");
}
void DoUpdateParameters() ITK_OVERRIDE
{
UpdateInternalParameters("superimpose");
}
void DoExecute() ITK_OVERRIDE
{
ExecuteInternal("superimpose");
GetInternalApplication("pansharp")->SetParameterInputImage("inxs",
GetInternalApplication("superimpose")->GetParameterOutputImage("out"));
ExecuteInternal("pansharp");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::BundleToPerfectSensor)
<|endoftext|> |
<commit_before>/*!
\file string_utils.inl
\brief String utilities inline implementation
\author Ivan Shynkarenka
\date 15.05.2016
\copyright MIT License
*/
namespace CppCommon {
inline bool StringUtils::IsBlank(char ch)
{
return std::isspace(ch);
}
inline char StringUtils::ToLowerInternal(char ch)
{
return (char)std::tolower(ch);
}
inline char StringUtils::ToUpperInternal(char ch)
{
return (char)std::toupper(ch);
}
inline char StringUtils::ToLower(char ch)
{
return ToLowerInternal(ch);
}
inline char StringUtils::ToUpper(char ch)
{
return ToUpperInternal(ch);
}
inline std::string StringUtils::ToLower(std::string_view str)
{
std::string result(str);
Lower(result);
return result;
}
inline std::string StringUtils::ToUpper(std::string_view str)
{
std::string result(str);
Upper(result);
return result;
}
inline std::string& StringUtils::Lower(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), ToLowerInternal);
return str;
}
inline std::string& StringUtils::Upper(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), ToUpperInternal);
return str;
}
inline std::string& StringUtils::Trim(std::string& str)
{
return LTrim(RTrim(str));
}
inline bool StringUtils::Contains(std::string_view str, const char ch)
{
return (str.find(ch) != std::string::npos);
}
inline bool StringUtils::Contains(std::string_view str, const char* substr)
{
return (str.find(substr) != std::string::npos);
}
inline bool StringUtils::Contains(std::string_view str, std::string_view substr)
{
return (str.find(substr) != std::string::npos);
}
inline bool StringUtils::StartsWith(std::string_view str, std::string_view prefix)
{
return (str.size() >= prefix.size()) && (str.compare(0, prefix.size(), prefix) == 0);
}
inline bool StringUtils::EndsWith(std::string_view str, std::string_view suffix)
{
return (str.size() >= suffix.size()) && (str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0);
}
template <typename T>
inline std::string StringUtils::ToString(const T& value)
{
std::ostringstream ss;
ss << value;
return ss.str();
}
template <typename T>
inline T StringUtils::FromString(std::string_view str)
{
T result;
std::istringstream(str) >> result;
return result;
}
template <>
inline const char* StringUtils::FromString(std::string_view str)
{
return std::string(str).c_str();
}
template <>
inline std::string StringUtils::FromString(std::string_view str)
{
return std::string(str);
}
template <>
inline std::string_view StringUtils::FromString(std::string_view str)
{
return str;
}
template <>
inline bool StringUtils::FromString(std::string_view str)
{
std::string value = ToLower(str);
if ((value == "true") || (value == "yes") || (value == "on") || (value == "1"))
return true;
if ((value == "false") || (value == "no") || (value == "off") || (value == "0"))
return false;
assert("Invalid boolean value represented in string!");
return false;
}
} // namespace CppCommon
<commit_msg>update<commit_after>/*!
\file string_utils.inl
\brief String utilities inline implementation
\author Ivan Shynkarenka
\date 15.05.2016
\copyright MIT License
*/
namespace CppCommon {
inline bool StringUtils::IsBlank(char ch)
{
return std::isspace(ch);
}
inline char StringUtils::ToLowerInternal(char ch)
{
return (char)std::tolower(ch);
}
inline char StringUtils::ToUpperInternal(char ch)
{
return (char)std::toupper(ch);
}
inline char StringUtils::ToLower(char ch)
{
return ToLowerInternal(ch);
}
inline char StringUtils::ToUpper(char ch)
{
return ToUpperInternal(ch);
}
inline std::string StringUtils::ToLower(std::string_view str)
{
std::string result(str);
Lower(result);
return result;
}
inline std::string StringUtils::ToUpper(std::string_view str)
{
std::string result(str);
Upper(result);
return result;
}
inline std::string& StringUtils::Lower(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), ToLowerInternal);
return str;
}
inline std::string& StringUtils::Upper(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), ToUpperInternal);
return str;
}
inline std::string& StringUtils::Trim(std::string& str)
{
return LTrim(RTrim(str));
}
inline bool StringUtils::Contains(std::string_view str, const char ch)
{
return (str.find(ch) != std::string::npos);
}
inline bool StringUtils::Contains(std::string_view str, const char* substr)
{
return (str.find(substr) != std::string::npos);
}
inline bool StringUtils::Contains(std::string_view str, std::string_view substr)
{
return (str.find(substr) != std::string::npos);
}
inline bool StringUtils::StartsWith(std::string_view str, std::string_view prefix)
{
return (str.size() >= prefix.size()) && (str.compare(0, prefix.size(), prefix) == 0);
}
inline bool StringUtils::EndsWith(std::string_view str, std::string_view suffix)
{
return (str.size() >= suffix.size()) && (str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0);
}
template <typename T>
inline std::string StringUtils::ToString(const T& value)
{
std::ostringstream ss;
ss << value;
return ss.str();
}
template <typename T>
inline T StringUtils::FromString(std::string_view str)
{
T result;
std::istringstream(std::string(str)) >> result;
return result;
}
template <>
inline const char* StringUtils::FromString(std::string_view str)
{
return std::string(str).c_str();
}
template <>
inline std::string StringUtils::FromString(std::string_view str)
{
return std::string(str);
}
template <>
inline std::string_view StringUtils::FromString(std::string_view str)
{
return str;
}
template <>
inline bool StringUtils::FromString(std::string_view str)
{
std::string value = ToLower(str);
if ((value == "true") || (value == "yes") || (value == "on") || (value == "1"))
return true;
if ((value == "false") || (value == "no") || (value == "off") || (value == "0"))
return false;
assert("Invalid boolean value represented in string!");
return false;
}
} // namespace CppCommon
<|endoftext|> |
<commit_before>/**@file QueryCorrectionSubmanager.cpp
* @brief source file of Query Correction
* @author Jinglei Zhao&Jinli Liu
* @date 2009-08-21
* @details
* - Log
* - 2009.09.26 add new candidate generation
* - 2009.10.08 add new error model for english
* - 2009.11.27 add isEnglishWord() and isKoreanWord() to check if one word is mixure
* -2010.03.05 add log manager periodical worker.
*/
#include "Util.h"
#include "QueryCorrectionSubmanager.h"
#include <common/SFLogger.h>
#include <util/ustring/ustr_tool.h>
#include <boost/algorithm/string.hpp>
namespace
{
static const float SMOOTH = 0.000001;
static const float FACTOR = 0.05;
static const int UNIGRAM_FREQ_THRESHOLD = 3;
static const int BIGRAM_FREQ_THRESHOLD = 3;
static const int UNIGRAM_FACTOR = 10;
static const int BIGRAM_FACTOR = 1;
static const unsigned int CHINESE_CORRECTION_LENGTH = 8;
}
using namespace izenelib::util::ustring_tool;
namespace sf1r
{
_QueryCorrectionSubmanagerParam QueryCorrectionSubmanagerParam::param_;
QueryCorrectionSubmanager::QueryCorrectionSubmanager
(const string& path, const std::string& workingPath, bool enableEK, bool enableChn, int ed)
:path_(path), workingPath_(workingPath)
, enableEK_(enableEK), enableChn_(enableChn)
, activate_(false)
, cmgr_(path_+"/cn", workingPath_), ekmgr_(path, workingPath, ed)
, has_new_inject_(false)
{
initialize();
}
QueryCorrectionSubmanager& QueryCorrectionSubmanager::getInstance()
{
_QueryCorrectionSubmanagerParam& param =
QueryCorrectionSubmanagerParam::get();
static QueryCorrectionSubmanager qcManager(param.path_, param.workingPath_,
param.enableEK_, param.enableChn_);
return qcManager;
}
// bool QueryCorrectionSubmanager::stopHere(
// const izenelib::util::UString& queryUString)
// {
// bool is = true;
// std::vector<UString> queryTokens;
//
// string queryStr;
// queryUString.convertString(queryStr, UString::UTF_8);
// if (cmgr_.inPinyinDict(queryStr))
// return false;
//
// getTokensFromUString(UString::UTF_8,' ', queryUString, queryTokens);
// // Tokenize(queryUString, queryTokens);
//
// uint32_t chineseCount = 0;
// uint32_t ekCount = 0;
// for (size_t i = 0; i < queryUString.length(); i++)
// {
// if (queryUString.isChineseChar(i))
// {
// ++chineseCount;
// }
// else
// {
// ++ekCount;
// }
// }
// // if( !enableChn_ && chineseCount>0 ) return true;
// // if( !enableEK_ && ekCount>0 ) return true;
// if (chineseCount > CHINESE_CORRECTION_LENGTH)
// return true;
//
// vector<UString>::iterator it_token = queryTokens.begin();
// for (; it_token != queryTokens.end(); it_token++)
// {
// string str;
// it_token->convertString(str, izenelib::util::UString::UTF_8);
//
// //if it is one word in Chinese dictionary, Chinese
// //QueryCorrection is firstly processed.
// (*it_token).toLowerString();
// if (queryTokens.size() == 1 && cmgr_.inPinyinDict(str))
// {
// return false;
// }
// bool b1 = ekmgr_.inDict(*it_token);
// bool b2 = cmgr_.inChineseDict(str);
// if ( b2 )
// {
// return false;
// }
// else
// {
// if ( !b1 )
// is = false;
// }
//
// }
// return is;
// }
//Initialize some member variables
bool QueryCorrectionSubmanager::initialize()
{
std::cout<< "Start Speller construction!" << std::endl;
activate_ = true;
if (!boost::filesystem::exists(path_) || !boost::filesystem::is_directory(
path_))
{
std::string
msg =
"Initialize query correction failed, please ensure that you set the correct path in configuration file.";
sflog->error(SFL_MINE, msg.c_str());
activate_ = false;
return false;
}
if (enableEK_)
{
ekmgr_.initialize();
}
if (enableChn_)
{
if(!cmgr_.Load())
{
std::cerr<<"Load failed for Chinese query correction"<<std::endl;
activate_ = false;
return false;
}
}
{
boost::mutex::scoped_lock scopedLock(logMutex_);
if (enableEK_)
{
ekmgr_.warmUp();
}
}
//load inject
std::string inject_file = workingPath_+"/inject_data.txt";
std::vector<izenelib::util::UString> str_list;
std::ifstream ifs(inject_file.c_str());
std::string line;
while( getline(ifs, line) )
{
boost::algorithm::trim(line);
if(line.length()==0)
{
//do with str_list;
if(str_list.size()>=1)
{
std::string str_query;
str_list[0].convertString(str_query, izenelib::util::UString::UTF_8);
izenelib::util::UString result;
if(str_list.size()>=2)
{
result = str_list[1];
}
inject_data_.insert(std::make_pair(str_query, result));
}
str_list.resize(0);
continue;
}
str_list.push_back( izenelib::util::UString(line, izenelib::util::UString::UTF_8));
}
ifs.close();
std::cout << "End Speller construction!" << std::endl;
return true;
}
QueryCorrectionSubmanager::~QueryCorrectionSubmanager()
{
DLOG(INFO) << "... Query Correction module is destroyed" << std::endl;
}
bool QueryCorrectionSubmanager::getRefinedToken_(const std::string& collectionName, const izenelib::util::UString& token, izenelib::util::UString& result)
{
if (enableChn_)
{
std::vector<izenelib::util::UString> vec_result;
if ( cmgr_.GetResult(token, vec_result) )
{
if(vec_result.size()>0)
{
result = vec_result[0];
return true;
}
return false;
}
}
if (enableEK_)
{
if ( ekmgr_.getRefinedQuery(collectionName, token, result) )
{
if(result.length()>0)
{
return true;
}
else
{
return false;
}
}
}
return false;
}
//The public interface, when user input wrong query, given the correct refined query.
bool QueryCorrectionSubmanager::getRefinedQuery(const UString& queryUString,
UString& refinedQueryUString)
{
return getRefinedQuery("", queryUString, refinedQueryUString);
}
bool QueryCorrectionSubmanager::getRefinedQuery(
const std::string& collectionName, const UString& queryUString,
UString& refinedQueryUString)
{
// std::vector<izenelib::util::UString> vec_result;
// if ( cmgr_.GetResult(queryUString, vec_result) )
// {
// if(vec_result.size()>0)
// {
// refinedQueryUString = vec_result[0];
// return true;
// }
//
// }
// return false;
std::string str_query;
queryUString.convertString(str_query, izenelib::util::UString::UTF_8);
boost::algorithm::to_lower(str_query);
boost::unordered_map<std::string, izenelib::util::UString>::iterator it = inject_data_.find(str_query);
if(it!=inject_data_.end())
{
refinedQueryUString = it->second;
return true;
}
if (queryUString.empty() || !activate_)
{
return false;
}
if (!enableEK_ && !enableChn_)
{
return false;
}
CREATE_SCOPED_PROFILER(getRealRefinedQuery, "QueryCorrectionSubmanager",
"QueryCorrectionSubmanager :: getRealRefinedQuery");
// std::string sourceString( env.queryString_ );
typedef tokenizer<char_separator<char> > tokenizers;
char_separator<char> sep(QueryManager::seperatorString.c_str());//In order to omit ' punction.As we need to support words with suffix 's
std::string queryStr;
queryUString.convertString(queryStr, izenelib::util::UString::UTF_8);
tokenizers stringTokenizer(queryStr, sep);
// Tokenizing and apply query correction.
// izenelib::util::UString originalToken;
bool bRefined = false;
bool first = true;
for (tokenizers::iterator iter = stringTokenizer.begin(); iter
!= stringTokenizer.end(); iter++)
{
if (!first)
{
refinedQueryUString += ' ';
}
izenelib::util::UString token(*iter, izenelib::util::UString::UTF_8);
izenelib::util::UString refined_token;
if(getRefinedToken_(collectionName, token, refined_token) )
{
refinedQueryUString += refined_token;
bRefined = true;
}
else
{
refinedQueryUString += token;
}
first = false;
}
if(bRefined)
{
return true;
}
else
{
refinedQueryUString.clear();
return false;
}
// if (stopHere(queryUString) )
// {
// return false;
// }
}
bool QueryCorrectionSubmanager::getPinyin(
const izenelib::util::UString& hanzis, std::vector<
izenelib::util::UString>& pinyin)
{
// return cmgr_.getPinyin(hanzis, pinyin);
return false;
}
//
// bool QueryCorrectionSubmanager::pinyinSegment(const string& str,
// std::vector<string>& result)
// {
//
// std::vector<std::vector<string> > vpy;
// if ( !cmgr_.pinyinSegment(str, vpy) )
// {
// result.push_back(str);
// return true;
// }
//
// size_t minSize = 1000;
// for (size_t i=0; i<vpy.size(); i++)
// {
// if (vpy[i].size() < minSize)
// {
// minSize = vpy[i].size() ;
// result = vpy[i];
// }
// for (size_t j=0; j<vpy[i].size(); j++)
// cout<<vpy[i][j]<<" -> ";
// cout<<endl;
// }
// return true;
// }
//
//
bool QueryCorrectionSubmanager::isPinyin(const izenelib::util::UString& str)
{
// std::string tempString;
// str.convertString(tempString, izenelib::util::UString::UTF_8);
// return cmgr_.isPinyin(tempString);
return false;
}
//
void QueryCorrectionSubmanager::updateCogramAndDict(const std::list<std::pair<izenelib::util::UString, uint32_t> >& recentQueryList)
{
updateCogramAndDict("", recentQueryList);
}
void QueryCorrectionSubmanager::updateCogramAndDict(const std::string& collectionName, const std::list<std::pair<izenelib::util::UString, uint32_t> >& recentQueryList)
{
boost::mutex::scoped_lock scopedLock(logMutex_);
DLOG(INFO)<<"updateCogramAndDict..."<<endl;
const std::list < std :: pair < izenelib::util::UString, uint32_t> >& queryList = recentQueryList;
std::list < std :: pair < izenelib::util::UString, uint32_t> >::const_iterator lit;
//no collection independent
cmgr_.Update(queryList);
}
void QueryCorrectionSubmanager::Inject(const izenelib::util::UString& query, const izenelib::util::UString& result)
{
std::string str_query;
query.convertString(str_query, izenelib::util::UString::UTF_8);
boost::algorithm::trim(str_query);
if(str_query.empty()) return;
boost::algorithm::to_lower(str_query);
std::cout<<"Inject query correction : "<<str_query<<std::endl;
inject_data_.erase( str_query );
inject_data_.insert(std::make_pair( str_query, result) );
has_new_inject_ = true;
}
void QueryCorrectionSubmanager::FinishInject()
{
if(!has_new_inject_) return;
std::string inject_file = workingPath_+"/inject_data.txt";
if(boost::filesystem::exists( inject_file) )
{
boost::filesystem::remove_all( inject_file);
}
std::ofstream ofs(inject_file.c_str());
boost::unordered_map<std::string, izenelib::util::UString>::iterator it = inject_data_.begin();
while(it!= inject_data_.end())
{
std::string result;
it->second.convertString(result, izenelib::util::UString::UTF_8);
ofs<<it->first<<std::endl;
ofs<<result<<std::endl;
ofs<<std::endl;
++it;
}
ofs.close();
has_new_inject_ = false;
std::cout<<"Finish inject query correction."<<std::endl;
}
}/*namespace sf1r*/
<commit_msg>support pinyin autofill.<commit_after>/**@file QueryCorrectionSubmanager.cpp
* @brief source file of Query Correction
* @author Jinglei Zhao&Jinli Liu
* @date 2009-08-21
* @details
* - Log
* - 2009.09.26 add new candidate generation
* - 2009.10.08 add new error model for english
* - 2009.11.27 add isEnglishWord() and isKoreanWord() to check if one word is mixure
* -2010.03.05 add log manager periodical worker.
*/
#include "Util.h"
#include "QueryCorrectionSubmanager.h"
#include <common/SFLogger.h>
#include <util/ustring/ustr_tool.h>
#include <boost/algorithm/string.hpp>
namespace
{
static const float SMOOTH = 0.000001;
static const float FACTOR = 0.05;
static const int UNIGRAM_FREQ_THRESHOLD = 3;
static const int BIGRAM_FREQ_THRESHOLD = 3;
static const int UNIGRAM_FACTOR = 10;
static const int BIGRAM_FACTOR = 1;
static const unsigned int CHINESE_CORRECTION_LENGTH = 8;
}
using namespace izenelib::util::ustring_tool;
namespace sf1r
{
_QueryCorrectionSubmanagerParam QueryCorrectionSubmanagerParam::param_;
QueryCorrectionSubmanager::QueryCorrectionSubmanager
(const string& path, const std::string& workingPath, bool enableEK, bool enableChn, int ed)
:path_(path), workingPath_(workingPath)
, enableEK_(enableEK), enableChn_(enableChn)
, activate_(false)
, cmgr_(path_+"/cn", workingPath_), ekmgr_(path, workingPath, ed)
, has_new_inject_(false)
{
initialize();
}
QueryCorrectionSubmanager& QueryCorrectionSubmanager::getInstance()
{
_QueryCorrectionSubmanagerParam& param =
QueryCorrectionSubmanagerParam::get();
static QueryCorrectionSubmanager qcManager(param.path_, param.workingPath_,
param.enableEK_, param.enableChn_);
return qcManager;
}
// bool QueryCorrectionSubmanager::stopHere(
// const izenelib::util::UString& queryUString)
// {
// bool is = true;
// std::vector<UString> queryTokens;
//
// string queryStr;
// queryUString.convertString(queryStr, UString::UTF_8);
// if (cmgr_.inPinyinDict(queryStr))
// return false;
//
// getTokensFromUString(UString::UTF_8,' ', queryUString, queryTokens);
// // Tokenize(queryUString, queryTokens);
//
// uint32_t chineseCount = 0;
// uint32_t ekCount = 0;
// for (size_t i = 0; i < queryUString.length(); i++)
// {
// if (queryUString.isChineseChar(i))
// {
// ++chineseCount;
// }
// else
// {
// ++ekCount;
// }
// }
// // if( !enableChn_ && chineseCount>0 ) return true;
// // if( !enableEK_ && ekCount>0 ) return true;
// if (chineseCount > CHINESE_CORRECTION_LENGTH)
// return true;
//
// vector<UString>::iterator it_token = queryTokens.begin();
// for (; it_token != queryTokens.end(); it_token++)
// {
// string str;
// it_token->convertString(str, izenelib::util::UString::UTF_8);
//
// //if it is one word in Chinese dictionary, Chinese
// //QueryCorrection is firstly processed.
// (*it_token).toLowerString();
// if (queryTokens.size() == 1 && cmgr_.inPinyinDict(str))
// {
// return false;
// }
// bool b1 = ekmgr_.inDict(*it_token);
// bool b2 = cmgr_.inChineseDict(str);
// if ( b2 )
// {
// return false;
// }
// else
// {
// if ( !b1 )
// is = false;
// }
//
// }
// return is;
// }
//Initialize some member variables
bool QueryCorrectionSubmanager::initialize()
{
std::cout<< "Start Speller construction!" << std::endl;
activate_ = true;
if (!boost::filesystem::exists(path_) || !boost::filesystem::is_directory(
path_))
{
std::string
msg =
"Initialize query correction failed, please ensure that you set the correct path in configuration file.";
sflog->error(SFL_MINE, msg.c_str());
activate_ = false;
return false;
}
if (enableEK_)
{
ekmgr_.initialize();
}
if (enableChn_)
{
if(!cmgr_.Load())
{
std::cerr<<"Load failed for Chinese query correction"<<std::endl;
activate_ = false;
return false;
}
}
{
boost::mutex::scoped_lock scopedLock(logMutex_);
if (enableEK_)
{
ekmgr_.warmUp();
}
}
//load inject
std::string inject_file = workingPath_+"/inject_data.txt";
std::vector<izenelib::util::UString> str_list;
std::ifstream ifs(inject_file.c_str());
std::string line;
while( getline(ifs, line) )
{
boost::algorithm::trim(line);
if(line.length()==0)
{
//do with str_list;
if(str_list.size()>=1)
{
std::string str_query;
str_list[0].convertString(str_query, izenelib::util::UString::UTF_8);
izenelib::util::UString result;
if(str_list.size()>=2)
{
result = str_list[1];
}
inject_data_.insert(std::make_pair(str_query, result));
}
str_list.resize(0);
continue;
}
str_list.push_back( izenelib::util::UString(line, izenelib::util::UString::UTF_8));
}
ifs.close();
std::cout << "End Speller construction!" << std::endl;
return true;
}
QueryCorrectionSubmanager::~QueryCorrectionSubmanager()
{
DLOG(INFO) << "... Query Correction module is destroyed" << std::endl;
}
bool QueryCorrectionSubmanager::getRefinedToken_(const std::string& collectionName, const izenelib::util::UString& token, izenelib::util::UString& result)
{
if (enableChn_)
{
std::vector<izenelib::util::UString> vec_result;
if ( cmgr_.GetResult(token, vec_result) )
{
if(vec_result.size()>0)
{
result = vec_result[0];
return true;
}
return false;
}
}
if (enableEK_)
{
if ( ekmgr_.getRefinedQuery(collectionName, token, result) )
{
if(result.length()>0)
{
return true;
}
else
{
return false;
}
}
}
return false;
}
//The public interface, when user input wrong query, given the correct refined query.
bool QueryCorrectionSubmanager::getRefinedQuery(const UString& queryUString,
UString& refinedQueryUString)
{
return getRefinedQuery("", queryUString, refinedQueryUString);
}
bool QueryCorrectionSubmanager::getRefinedQuery(
const std::string& collectionName, const UString& queryUString,
UString& refinedQueryUString)
{
// std::vector<izenelib::util::UString> vec_result;
// if ( cmgr_.GetResult(queryUString, vec_result) )
// {
// if(vec_result.size()>0)
// {
// refinedQueryUString = vec_result[0];
// return true;
// }
//
// }
// return false;
std::string str_query;
queryUString.convertString(str_query, izenelib::util::UString::UTF_8);
boost::algorithm::to_lower(str_query);
boost::unordered_map<std::string, izenelib::util::UString>::iterator it = inject_data_.find(str_query);
if(it!=inject_data_.end())
{
refinedQueryUString = it->second;
return true;
}
if (queryUString.empty() || !activate_)
{
return false;
}
if (!enableEK_ && !enableChn_)
{
return false;
}
CREATE_SCOPED_PROFILER(getRealRefinedQuery, "QueryCorrectionSubmanager",
"QueryCorrectionSubmanager :: getRealRefinedQuery");
// std::string sourceString( env.queryString_ );
typedef tokenizer<char_separator<char> > tokenizers;
char_separator<char> sep(QueryManager::seperatorString.c_str());//In order to omit ' punction.As we need to support words with suffix 's
std::string queryStr;
queryUString.convertString(queryStr, izenelib::util::UString::UTF_8);
tokenizers stringTokenizer(queryStr, sep);
// Tokenizing and apply query correction.
// izenelib::util::UString originalToken;
bool bRefined = false;
bool first = true;
for (tokenizers::iterator iter = stringTokenizer.begin(); iter
!= stringTokenizer.end(); iter++)
{
if (!first)
{
refinedQueryUString += ' ';
}
izenelib::util::UString token(*iter, izenelib::util::UString::UTF_8);
izenelib::util::UString refined_token;
if(getRefinedToken_(collectionName, token, refined_token) )
{
refinedQueryUString += refined_token;
bRefined = true;
}
else
{
refinedQueryUString += token;
}
first = false;
}
if(bRefined)
{
return true;
}
else
{
refinedQueryUString.clear();
return false;
}
// if (stopHere(queryUString) )
// {
// return false;
// }
}
bool QueryCorrectionSubmanager::getPinyin(
const izenelib::util::UString& hanzis, std::vector<
izenelib::util::UString>& pinyin)
{
std::vector<std::string> result_list;
cmgr_.GetPinyin(hanzis, result_list);
for(uint32_t i=0;i<result_list.size();i++)
{
boost::algorithm::replace_all(result_list[i], ",", "");
pinyin.push_back( izenelib::util::UString(result_list[i], izenelib::util::UString::UTF_8) );
}
if(pinyin.size()>0) return true;
return false;
}
//
// bool QueryCorrectionSubmanager::pinyinSegment(const string& str,
// std::vector<string>& result)
// {
//
// std::vector<std::vector<string> > vpy;
// if ( !cmgr_.pinyinSegment(str, vpy) )
// {
// result.push_back(str);
// return true;
// }
//
// size_t minSize = 1000;
// for (size_t i=0; i<vpy.size(); i++)
// {
// if (vpy[i].size() < minSize)
// {
// minSize = vpy[i].size() ;
// result = vpy[i];
// }
// for (size_t j=0; j<vpy[i].size(); j++)
// cout<<vpy[i][j]<<" -> ";
// cout<<endl;
// }
// return true;
// }
//
//
bool QueryCorrectionSubmanager::isPinyin(const izenelib::util::UString& str)
{
// std::string tempString;
// str.convertString(tempString, izenelib::util::UString::UTF_8);
// return cmgr_.isPinyin(tempString);
return false;
}
//
void QueryCorrectionSubmanager::updateCogramAndDict(const std::list<std::pair<izenelib::util::UString, uint32_t> >& recentQueryList)
{
updateCogramAndDict("", recentQueryList);
}
void QueryCorrectionSubmanager::updateCogramAndDict(const std::string& collectionName, const std::list<std::pair<izenelib::util::UString, uint32_t> >& recentQueryList)
{
boost::mutex::scoped_lock scopedLock(logMutex_);
DLOG(INFO)<<"updateCogramAndDict..."<<endl;
const std::list < std :: pair < izenelib::util::UString, uint32_t> >& queryList = recentQueryList;
std::list < std :: pair < izenelib::util::UString, uint32_t> >::const_iterator lit;
//no collection independent
cmgr_.Update(queryList);
}
void QueryCorrectionSubmanager::Inject(const izenelib::util::UString& query, const izenelib::util::UString& result)
{
std::string str_query;
query.convertString(str_query, izenelib::util::UString::UTF_8);
boost::algorithm::trim(str_query);
if(str_query.empty()) return;
boost::algorithm::to_lower(str_query);
std::cout<<"Inject query correction : "<<str_query<<std::endl;
inject_data_.erase( str_query );
inject_data_.insert(std::make_pair( str_query, result) );
has_new_inject_ = true;
}
void QueryCorrectionSubmanager::FinishInject()
{
if(!has_new_inject_) return;
std::string inject_file = workingPath_+"/inject_data.txt";
if(boost::filesystem::exists( inject_file) )
{
boost::filesystem::remove_all( inject_file);
}
std::ofstream ofs(inject_file.c_str());
boost::unordered_map<std::string, izenelib::util::UString>::iterator it = inject_data_.begin();
while(it!= inject_data_.end())
{
std::string result;
it->second.convertString(result, izenelib::util::UString::UTF_8);
ofs<<it->first<<std::endl;
ofs<<result<<std::endl;
ofs<<std::endl;
++it;
}
ofs.close();
has_new_inject_ = false;
std::cout<<"Finish inject query correction."<<std::endl;
}
}/*namespace sf1r*/
<|endoftext|> |
<commit_before><commit_msg>add failing tests for DivModDown<commit_after><|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/odyssey/procedures/hwp/memory/lib/phy/ody_draminit_procedure.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
// EKB-Mirror-To: hostboot
///
/// @file ody_draminit_procedure.C
/// @brief Odyssey draminit procedure
/// @note Using a separate file as simulation might need a different draminit procedure for now
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/phy/ody_draminit_utils.H>
#include <lib/phy/ody_phy_utils.H>
#include <mss_odyssey_attribute_getters.H>
namespace mss
{
namespace ody
{
///
/// @brief Runs draminit
/// @param[in] i_target the target on which to operate
/// @return fapi2::FAPI2_RC_SUCCESS iff successful
/// @note Assumes PHY init has already been run
///
fapi2::ReturnCode draminit(const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target)
{
fapi2::ATTR_DRAMINIT_TRAINING_TIMEOUT_Type l_poll_count;
FAPI_TRY(mss::attr::get_draminit_training_timeout(i_target , l_poll_count));
// 1. Loads the IMEM Memory (instructions)
// TODO:ZEN:MST-1561 Create code to load IMEM, DMEM, and message block onto Synopsys PHY
// 2. Loads the DMEM Memory (data)
// TODO:ZEN:MST-1561 Create code to load IMEM, DMEM, and message block onto Synopsys PHY
// 3. Configures and loads the message block
// TODO:ZEN:MST-1561 Create code to load IMEM, DMEM, and message block onto Synopsys PHY
// 4. Initialize mailbox protocol and start training
FAPI_TRY(mss::ody::phy::init_mailbox_protocol(i_target));
FAPI_TRY(mss::ody::phy::start_training(i_target));
// 5. Processes and handles training messages (aka poll for completion)
FAPI_TRY (mss::ody::phy::poll_for_completion(i_target, l_poll_count));
// 6. Cleans up after training
FAPI_TRY(mss::ody::phy::cleanup_training(i_target));
// 7. Read the data structure and set attributes
// TODO:ZEN:MST-1567 Create code to process data from the Synopsys message block
// 8. Error handling
// TODO:ZEN:MST-1568 Add Odyssey draminit error processing
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Runs draminit
/// @param[in] i_target the target on which to operate
/// @return fapi2::FAPI2_RC_SUCCESS iff successful
/// @note Assumes PHY init has already been run
///
fapi2::ReturnCode draminit(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
for(const auto& l_port : mss::find_targets<fapi2::TARGET_TYPE_MEM_PORT>(i_target))
{
// Note: This will need to be updated to allow training to fail on one port but continue on the second
FAPI_TRY(draminit(l_port));
}
// Blame FIRs and unmask FIRs (done on the OCMB chip level)
// TODO:ZEN:MST-1530 Specialize unmask::after_draminit_training for Odyssey
fapi_try_exit:
return fapi2::current_err;
}
} // namespace ody
} // namespace mss
<commit_msg>Adds ODY draminit wrap<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/odyssey/procedures/hwp/memory/lib/phy/ody_draminit_procedure.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
// EKB-Mirror-To: hostboot
///
/// @file ody_draminit_procedure.C
/// @brief Odyssey draminit procedure
/// @note Using a separate file as simulation might need a different draminit procedure for now
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/phy/ody_draminit_utils.H>
#include <lib/phy/ody_phy_utils.H>
#include <mss_odyssey_attribute_getters.H>
#include <lib/phy/ody_draminit_procedure.H>
namespace mss
{
namespace ody
{
///
/// @brief Runs draminit
/// @param[in] i_target the target on which to operate
/// @return fapi2::FAPI2_RC_SUCCESS iff successful
/// @note Assumes PHY init has already been run
///
fapi2::ReturnCode draminit(const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target)
{
fapi2::ATTR_DRAMINIT_TRAINING_TIMEOUT_Type l_poll_count;
FAPI_TRY(mss::attr::get_draminit_training_timeout(i_target , l_poll_count));
// 1. Loads the IMEM Memory (instructions)
// TODO:ZEN:MST-1561 Create code to load IMEM, DMEM, and message block onto Synopsys PHY
// 2. Loads the DMEM Memory (data)
// TODO:ZEN:MST-1561 Create code to load IMEM, DMEM, and message block onto Synopsys PHY
// 3. Configures and loads the message block
// TODO:ZEN:MST-1561 Create code to load IMEM, DMEM, and message block onto Synopsys PHY
// 4. Initialize mailbox protocol and start training
FAPI_TRY(mss::ody::phy::init_mailbox_protocol(i_target));
FAPI_TRY(mss::ody::phy::start_training(i_target));
// 5. Processes and handles training messages (aka poll for completion)
FAPI_TRY (mss::ody::phy::poll_for_completion(i_target, l_poll_count));
// 6. Cleans up after training
FAPI_TRY(mss::ody::phy::cleanup_training(i_target));
// 7. Read the data structure and set attributes
// TODO:ZEN:MST-1567 Create code to process data from the Synopsys message block
// 8. Error handling
// TODO:ZEN:MST-1568 Add Odyssey draminit error processing
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Runs draminit
/// @param[in] i_target the target on which to operate
/// @return fapi2::FAPI2_RC_SUCCESS iff successful
/// @note Assumes PHY init has already been run
///
fapi2::ReturnCode draminit(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
for(const auto& l_port : mss::find_targets<fapi2::TARGET_TYPE_MEM_PORT>(i_target))
{
// Note: This will need to be updated to allow training to fail on one port but continue on the second
FAPI_TRY(draminit(l_port));
}
// Blame FIRs and unmask FIRs (done on the OCMB chip level)
// TODO:ZEN:MST-1530 Specialize unmask::after_draminit_training for Odyssey
fapi_try_exit:
return fapi2::current_err;
}
} // namespace ody
} // namespace mss
<|endoftext|> |
<commit_before>#include "../include/morton.h"
#include <iostream>
#include <iomanip>
using namespace std;
#define MAX 256
// Timer struct for easy timing
struct Timer {
clock_t Start;
clock_t Elapsed;
Timer(){
Elapsed = 0;
Start = clock();
}
void reset(){
Start = clock();
}
void resetTotal(){
Elapsed = 0;
}
void start(){
Start = clock();
}
void stop(){
clock_t End = clock();
Elapsed = Elapsed + (End - Start);
}
double getTotalTimeMs() const{
return ((double)Elapsed) / ((double)CLOCKS_PER_SEC / 1000.0f);
}
};
// Don't optimize this, since the loops themselves are useless - we're testing
#pragma optimize( "", off )
int main(int argc, char *argv[]) {
size_t total = MAX*MAX*MAX;
cout << "Running morton encoding / decoding tests ..." << endl;
cout << "+++ Encoding " << MAX << "^3 morton codes (" << total << " in total)" << endl;
Timer morton_LUT;
morton_LUT.reset();
morton_LUT.start();
for(size_t i = 0; i < MAX; i++){
for(size_t j = 0; j < MAX; j++){
for(size_t k = 0; k < MAX; k++){
mortonEncode_LUT(i,j,k);
}
}
}
morton_LUT.stop();
cout << "LUT-based method: " << morton_LUT.getTotalTimeMs() << " ms" << endl;
Timer morton_magicbits;
morton_magicbits.reset();
morton_magicbits.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
mortonEncode_magicbits(i, j, k);
}
}
}
morton_magicbits.stop();
cout << "Magic bits-based method: " << morton_magicbits.getTotalTimeMs() << " ms" << endl;
Timer morton_for;
morton_for.reset();
morton_for.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
mortonEncode_for(i, j, k);
}
}
}
morton_for.stop();
cout << "For-loop method: " << morton_for.getTotalTimeMs() << " ms" << endl;
cout << "+++ Decoding " << MAX << "^3 morton codes (" << total << " in total)" << endl;
Timer morton_decode_magicbits;
morton_decode_magicbits.reset();
morton_decode_magicbits.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
uint64_t s = mortonEncode_LUT(i, j, k);
if (i != mortonDecode_magicbits_X(s) || j != mortonDecode_magicbits_Y(s) || k != mortonDecode_magicbits_Z(s)){
cout << "Encode and decode don't match" << endl;
}
}
}
}
morton_decode_magicbits.stop();
cout << "Magicbits method: " << morton_decode_magicbits.getTotalTimeMs() - morton_LUT.getTotalTimeMs() << " ms" << endl;
Timer morton_decode_for;
morton_decode_for.reset();
morton_decode_for.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
uint64_t s = mortonEncode_LUT(i, j, k);
unsigned int x = 0;
unsigned int y = 0;
unsigned int z = 0;
mortonDecode_for(s, x, y, z);
if (i != x || j != y || k != z){
cout << "Encode and decode don't match" << endl;
}
}
}
}
morton_decode_for.stop();
cout << "For-loop method: " << morton_decode_for.getTotalTimeMs() - morton_LUT.getTotalTimeMs() << " ms" << endl;
}
<commit_msg>Changed comments<commit_after>#include "../include/morton.h"
#include <iostream>
#include <iomanip>
using namespace std;
#define MAX 256
// Timer struct for easy timing
struct Timer {
clock_t Start;
clock_t Elapsed;
Timer(){
Elapsed = 0;
Start = clock();
}
void reset(){
Start = clock();
}
void resetTotal(){
Elapsed = 0;
}
void start(){
Start = clock();
}
void stop(){
clock_t End = clock();
Elapsed = Elapsed + (End - Start);
}
double getTotalTimeMs() const{
return ((double)Elapsed) / ((double)CLOCKS_PER_SEC / 1000.0f);
}
};
// Don't optimize this, since the loops themselves are useless - we're testing
#pragma optimize( "", off )
int main(int argc, char *argv[]) {
size_t total = MAX*MAX*MAX;
cout << "Running morton encoding / decoding tests ..." << endl;
cout << "+++ Encoding " << MAX << "^3 morton codes (" << total << " in total)" << endl;
Timer morton_LUT;
morton_LUT.reset();
morton_LUT.start();
for(size_t i = 0; i < MAX; i++){
for(size_t j = 0; j < MAX; j++){
for(size_t k = 0; k < MAX; k++){
mortonEncode_LUT(i,j,k);
}
}
}
morton_LUT.stop();
cout << "LUT-based method: " << morton_LUT.getTotalTimeMs() << " ms" << endl;
Timer morton_magicbits;
morton_magicbits.reset();
morton_magicbits.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
mortonEncode_magicbits(i, j, k);
}
}
}
morton_magicbits.stop();
cout << "Magic bits-based method: " << morton_magicbits.getTotalTimeMs() << " ms" << endl;
Timer morton_for;
morton_for.reset();
morton_for.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
mortonEncode_for(i, j, k);
}
}
}
morton_for.stop();
cout << "For-loop method: " << morton_for.getTotalTimeMs() << " ms" << endl;
cout << "+++ Decoding " << MAX << "^3 morton codes (" << total << " in total)" << endl;
Timer morton_decode_magicbits;
morton_decode_magicbits.reset();
morton_decode_magicbits.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
uint64_t s = mortonEncode_LUT(i, j, k);
if (i != mortonDecode_magicbits_X(s) || j != mortonDecode_magicbits_Y(s) || k != mortonDecode_magicbits_Z(s)){
cout << "Encode and decode don't match" << endl;
}
}
}
}
morton_decode_magicbits.stop();
cout << "Magicbits method: " << morton_decode_magicbits.getTotalTimeMs() - morton_LUT.getTotalTimeMs() << " ms" << endl; // we subtract morton code generation time with LUT-based method
Timer morton_decode_for;
morton_decode_for.reset();
morton_decode_for.start();
for (size_t i = 0; i < MAX; i++){
for (size_t j = 0; j < MAX; j++){
for (size_t k = 0; k < MAX; k++){
uint64_t s = mortonEncode_LUT(i, j, k);
unsigned int x = 0;
unsigned int y = 0;
unsigned int z = 0;
mortonDecode_for(s, x, y, z);
if (i != x || j != y || k != z){
cout << "Encode and decode don't match" << endl;
}
}
}
}
morton_decode_for.stop();
cout << "For-loop method: " << morton_decode_for.getTotalTimeMs() - morton_LUT.getTotalTimeMs() << " ms" << endl; // we subtract morton code generation time with LUT method
}
<|endoftext|> |
<commit_before>/*
***************************************
* Asylum3D @ 2014-12-09
***************************************
*/
#ifndef __TEXPOOL_HPP__
#define __TEXPOOL_HPP__
/* Asylum Namespace */
namespace asy {
/***************/
/* TexPool Key */
/***************/
struct texpool_key
{
int32u hash;
const char* name;
};
/****************/
/* TexPool Unit */
/****************/
struct texpool_unit
{
size_t idx;
texpool_key key;
/* ====== */
void free ()
{
mem_free(this->key.name);
}
};
/***************/
/* TexPool Cmp */
/***************/
class texpool_cmp
{
public:
/* ======================== */
size_t hash (texpool_key* key)
{
key->hash = hash_crc32i_total(key->name, str_lenA(key->name));
return ((size_t)key->hash);
}
/* ========================================== */
bool match (texpool_key* key, texpool_unit* obj)
{
if (key->hash != obj->key.hash)
return (false);
if (str_cmpIA(key->name, obj->key.name) != 0)
return (false);
return (true);
}
};
/******************/
/* TexPool Rehash */
/******************/
class texpool_rehash
{
public:
/* ================================== */
bool doit (void* ctx, texpool_unit* obj)
{
table_c<texpool_unit, texpool_key, texpool_cmp>* tbl2;
tbl2 = (table_c<texpool_unit, texpool_key, texpool_cmp>*)ctx;
tbl2->insert(&obj->key, obj, false);
return (true);
}
};
/****************/
/* Texture Pool */
/****************/
template<class TTEX>
class texpool : public asylum
{
private:
size_t m_cnt;
array<TTEX> m_lst;
table_c<texpool_unit, texpool_key, texpool_cmp> m_tbl;
public:
/* ====== */
bool init ()
{
m_cnt = hash_count(0);
if (!m_tbl.init(m_cnt))
return (false);
m_lst.init();
return (true);
}
/* ====== */
void free ()
{
m_tbl.free();
m_lst.free();
}
public:
/* ============== */
size_t size () const
{
return (m_lst.size());
}
/* ======================= */
TTEX* get2 (size_t idx) const
{
return (m_lst.get(idx));
}
/* =========================== */
TTEX* get_safe (size_t idx) const
{
return (m_lst.get_safe(idx));
}
/* ============================ */
TTEX* get (const char* name) const
{
texpool_key key;
texpool_unit* unt;
key.name = name;
unt = m_tbl.get(&key);
if (unt != NULL)
return (m_lst.get(unt->idx));
return (NULL);
}
/* ======================================== */
TTEX* get (const char* name, const char* type)
{
texpool_key key;
texpool_unit* unt;
key.name = name;
unt = m_tbl.get(&key);
if (unt != NULL)
return (m_lst.get(unt->idx));
TTEX tex, *ret;
if (!tex.init(name, type))
return (NULL);
ret = m_lst.append(&tex);
if (ret == NULL) {
tex.free();
return (NULL);
}
size_t cnt;
texpool_unit tmp;
key.name = str_dupA(name);
if (key.name == NULL) {
m_lst.pop();
return (NULL);
}
mem_cpy(&tmp.key, &key, sizeof(key));
tmp.idx = m_lst.size() - 1;
if (m_tbl.insert(&key, &tmp, false) == NULL)
{
table_c<texpool_unit, texpool_key, texpool_cmp> tbl2;
cnt = hash_count(m_cnt + 1);
if (cnt == m_cnt || !tbl2.init(cnt)) {
mem_free(key.name);
m_lst.pop();
return (NULL);
}
m_tbl.traverse<texpool_rehash>(&tbl2);
m_tbl.setup(&tbl2);
m_cnt = cnt;
m_tbl.insert(&key, &tmp, false);
}
return (ret);
}
};
} /* namespace */
#endif /* __TEXPOOL_HPP__ */
<commit_msg>Asylum3D: 加载纹理时要传入主对象参数<commit_after>/*
***************************************
* Asylum3D @ 2014-12-09
***************************************
*/
#ifndef __TEXPOOL_HPP__
#define __TEXPOOL_HPP__
/* Asylum Namespace */
namespace asy {
/***************/
/* TexPool Key */
/***************/
struct texpool_key
{
int32u hash;
const char* name;
};
/****************/
/* TexPool Unit */
/****************/
struct texpool_unit
{
size_t idx;
texpool_key key;
/* ====== */
void free ()
{
mem_free(this->key.name);
}
};
/***************/
/* TexPool Cmp */
/***************/
class texpool_cmp
{
public:
/* ======================== */
size_t hash (texpool_key* key)
{
key->hash = hash_crc32i_total(key->name, str_lenA(key->name));
return ((size_t)key->hash);
}
/* ========================================== */
bool match (texpool_key* key, texpool_unit* obj)
{
if (key->hash != obj->key.hash)
return (false);
if (str_cmpIA(key->name, obj->key.name) != 0)
return (false);
return (true);
}
};
/******************/
/* TexPool Rehash */
/******************/
class texpool_rehash
{
public:
/* ================================== */
bool doit (void* ctx, texpool_unit* obj)
{
table_c<texpool_unit, texpool_key, texpool_cmp>* tbl2;
tbl2 = (table_c<texpool_unit, texpool_key, texpool_cmp>*)ctx;
tbl2->insert(&obj->key, obj, false);
return (true);
}
};
/****************/
/* Texture Pool */
/****************/
template<class TTEX, class TA3D>
class texpool : public asylum
{
private:
size_t m_cnt;
array<TTEX> m_lst;
table_c<texpool_unit, texpool_key, texpool_cmp> m_tbl;
public:
/* ====== */
bool init ()
{
m_cnt = hash_count(0);
if (!m_tbl.init(m_cnt))
return (false);
m_lst.init();
return (true);
}
/* ====== */
void free ()
{
m_tbl.free();
m_lst.free();
}
public:
/* ============== */
size_t size () const
{
return (m_lst.size());
}
/* ======================= */
TTEX* get2 (size_t idx) const
{
return (m_lst.get(idx));
}
/* =========================== */
TTEX* get_safe (size_t idx) const
{
return (m_lst.get_safe(idx));
}
/* ============================ */
TTEX* get (const char* name) const
{
texpool_key key;
texpool_unit* unt;
key.name = name;
unt = m_tbl.get(&key);
if (unt != NULL)
return (m_lst.get(unt->idx));
return (NULL);
}
/* ==================================================== */
TTEX* get (const char* name, const char* type, TA3D *main)
{
texpool_key key;
texpool_unit* unt;
key.name = name;
unt = m_tbl.get(&key);
if (unt != NULL)
return (m_lst.get(unt->idx));
TTEX tex, *ret;
if (!tex.init(name, type, main))
return (NULL);
ret = m_lst.append(&tex);
if (ret == NULL) {
tex.free();
return (NULL);
}
size_t cnt;
texpool_unit tmp;
key.name = str_dupA(name);
if (key.name == NULL) {
m_lst.pop();
return (NULL);
}
mem_cpy(&tmp.key, &key, sizeof(key));
tmp.idx = m_lst.size() - 1;
if (m_tbl.insert(&key, &tmp, false) == NULL)
{
table_c<texpool_unit, texpool_key, texpool_cmp> tbl2;
cnt = hash_count(m_cnt + 1);
if (cnt == m_cnt || !tbl2.init(cnt)) {
mem_free(key.name);
m_lst.pop();
return (NULL);
}
m_tbl.traverse<texpool_rehash>(&tbl2);
m_tbl.setup(&tbl2);
m_cnt = cnt;
m_tbl.insert(&key, &tmp, false);
}
return (ret);
}
};
} /* namespace */
#endif /* __TEXPOOL_HPP__ */
<|endoftext|> |
<commit_before>/*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2002 by the OpenSG Forum *
* *
* www.opensg.org *
* *
* contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
#define GL_GLEXT_PROTOTYPES
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib>
#include <cstdio>
#include <boost/bind.hpp>
#include "OSGConfig.h"
#include <OSGGL.h>
#include <OSGGLU.h>
#include <OSGGLEXT.h>
#include <OSGImage.h>
#include "OSGDrawActionBase.h"
#include "OSGDrawEnv.h"
#include "OSGTextureObjRefChunk.h"
//#define OSG_DUMP_TEX
OSG_USING_NAMESPACE
// Documentation for this class is emited in the
// OSGTextureObjRefChunkBase.cpp file.
// To modify it, please change the .fcd file (OSGTextureObjRefChunk.fcd) and
// regenerate the base file.
/***************************************************************************\
* Class variables *
\***************************************************************************/
/***************************************************************************\
* Class methods *
\***************************************************************************/
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
void TextureObjRefChunk::initMethod(InitPhase ePhase)
{
Inherited::initMethod(ePhase);
}
/***************************************************************************\
* Instance methods *
\***************************************************************************/
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
/*------------- constructors & destructors --------------------------------*/
TextureObjRefChunk::TextureObjRefChunk(void) :
Inherited()
{
}
TextureObjRefChunk::TextureObjRefChunk(const TextureObjRefChunk &source) :
Inherited(source)
{
}
TextureObjRefChunk::~TextureObjRefChunk(void)
{
}
/*------------------------- Chunk Class Access ---------------------------*/
/*------------------------------- Sync -----------------------------------*/
/*! React to field changes.
Note: this function also handles CubeTexture changes, make sure to keep
it consistent with the cubeTexture specifics
*/
void TextureObjRefChunk::changed(BitVector whichField, UInt32 origin)
{
Inherited::changed(whichField, origin);
}
bool TextureObjRefChunk::isTransparent(void) const
{
// Even if the texture has alpha, the Blending is makes the sorting
// important, thus textures per se are not transparent
return false;
}
/*----------------------------- onCreate --------------------------------*/
void TextureObjRefChunk::onCreate(const TextureObjRefChunk *source)
{
Inherited::onCreate(source);
}
void TextureObjRefChunk::onCreateAspect(const TextureObjRefChunk *createAspect,
const TextureObjRefChunk *source )
{
Inherited::onCreateAspect(createAspect, source);
}
/*------------------------------ Output ----------------------------------*/
void TextureObjRefChunk::dump( UInt32 OSG_CHECK_ARG(uiIndent),
const BitVector OSG_CHECK_ARG(bvFlags )) const
{
SLOG << "Dump TextureObjRefChunk NI" << std::endl;
}
/*------------------------------ State ------------------------------------*/
void TextureObjRefChunk::activate(DrawEnv *pEnv, UInt32 idx)
{
Window *pWin = pEnv->getWindow();
if(activateTexture(pWin, idx))
return; // trying to access too many textures
glBindTexture(this->getTarget(),
this->getGLId ());
pEnv->setActiveTexTarget(idx, this->getTarget());
glEnable(this->getTarget());
}
void TextureObjRefChunk::changeFrom(DrawEnv *pEnv,
StateChunk *old ,
UInt32 idx )
{
// change from me to me?
// this assumes I haven't changed in the meantime.
// is that a valid assumption?
if(old == this)
return;
Window *pWin = pEnv->getWindow();
if(activateTexture(pWin, idx))
return; // trying to access too many textures
glBindTexture(this->getTarget(),
this->getGLId ());
pEnv->setActiveTexTarget(idx, this->getTarget());
glEnable(this->getTarget());
}
void TextureObjRefChunk::deactivate(DrawEnv *pEnv, UInt32 idx)
{
Window *pWin = pEnv->getWindow();
if(activateTexture(pWin, idx))
return; // trying to access too many textures
glDisable(this->getTarget());
pEnv->setActiveTexTarget(idx, GL_NONE);
}
/*-------------------------- Comparison -----------------------------------*/
Real32 TextureObjRefChunk::switchCost(StateChunk *OSG_CHECK_ARG(chunk))
{
return 0;
}
bool TextureObjRefChunk::operator < (const StateChunk &other) const
{
return this < &other;
}
bool TextureObjRefChunk::operator == (const StateChunk &other) const
{
bool returnValue = false;
return returnValue;
}
bool TextureObjRefChunk::operator != (const StateChunk &other) const
{
return ! (*this == other);
}
<commit_msg>fixed : wrong-glid-mapping<commit_after>/*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2002 by the OpenSG Forum *
* *
* www.opensg.org *
* *
* contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
#define GL_GLEXT_PROTOTYPES
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib>
#include <cstdio>
#include <boost/bind.hpp>
#include "OSGConfig.h"
#include <OSGGL.h>
#include <OSGGLU.h>
#include <OSGGLEXT.h>
#include <OSGImage.h>
#include "OSGDrawActionBase.h"
#include "OSGDrawEnv.h"
#include "OSGTextureObjRefChunk.h"
//#define OSG_DUMP_TEX
OSG_USING_NAMESPACE
// Documentation for this class is emited in the
// OSGTextureObjRefChunkBase.cpp file.
// To modify it, please change the .fcd file (OSGTextureObjRefChunk.fcd) and
// regenerate the base file.
/***************************************************************************\
* Class variables *
\***************************************************************************/
/***************************************************************************\
* Class methods *
\***************************************************************************/
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
void TextureObjRefChunk::initMethod(InitPhase ePhase)
{
Inherited::initMethod(ePhase);
}
/***************************************************************************\
* Instance methods *
\***************************************************************************/
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
/*------------- constructors & destructors --------------------------------*/
TextureObjRefChunk::TextureObjRefChunk(void) :
Inherited()
{
}
TextureObjRefChunk::TextureObjRefChunk(const TextureObjRefChunk &source) :
Inherited(source)
{
}
TextureObjRefChunk::~TextureObjRefChunk(void)
{
}
/*------------------------- Chunk Class Access ---------------------------*/
/*------------------------------- Sync -----------------------------------*/
/*! React to field changes.
Note: this function also handles CubeTexture changes, make sure to keep
it consistent with the cubeTexture specifics
*/
void TextureObjRefChunk::changed(BitVector whichField, UInt32 origin)
{
Inherited::changed(whichField, origin);
}
bool TextureObjRefChunk::isTransparent(void) const
{
// Even if the texture has alpha, the Blending is makes the sorting
// important, thus textures per se are not transparent
return false;
}
/*----------------------------- onCreate --------------------------------*/
void TextureObjRefChunk::onCreate(const TextureObjRefChunk *source)
{
Inherited::onCreate(source);
}
void TextureObjRefChunk::onCreateAspect(const TextureObjRefChunk *createAspect,
const TextureObjRefChunk *source )
{
Inherited::onCreateAspect(createAspect, source);
}
/*------------------------------ Output ----------------------------------*/
void TextureObjRefChunk::dump( UInt32 OSG_CHECK_ARG(uiIndent),
const BitVector OSG_CHECK_ARG(bvFlags )) const
{
SLOG << "Dump TextureObjRefChunk NI" << std::endl;
}
/*------------------------------ State ------------------------------------*/
void TextureObjRefChunk::activate(DrawEnv *pEnv, UInt32 idx)
{
Window *pWin = pEnv->getWindow();
if(activateTexture(pWin, idx))
return; // trying to access too many textures
glBindTexture(this->getTarget(),
pWin->getGLObjectId(this->getGLId()));
pEnv->setActiveTexTarget(idx, this->getTarget());
glEnable(this->getTarget());
}
void TextureObjRefChunk::changeFrom(DrawEnv *pEnv,
StateChunk *old ,
UInt32 idx )
{
// change from me to me?
// this assumes I haven't changed in the meantime.
// is that a valid assumption?
if(old == this)
return;
Window *pWin = pEnv->getWindow();
if(activateTexture(pWin, idx))
return; // trying to access too many textures
glBindTexture(this->getTarget(),
pWin->getGLObjectId(this->getGLId()));
pEnv->setActiveTexTarget(idx, this->getTarget());
glEnable(this->getTarget());
}
void TextureObjRefChunk::deactivate(DrawEnv *pEnv, UInt32 idx)
{
Window *pWin = pEnv->getWindow();
if(activateTexture(pWin, idx))
return; // trying to access too many textures
glDisable(this->getTarget());
pEnv->setActiveTexTarget(idx, GL_NONE);
}
/*-------------------------- Comparison -----------------------------------*/
Real32 TextureObjRefChunk::switchCost(StateChunk *OSG_CHECK_ARG(chunk))
{
return 0;
}
bool TextureObjRefChunk::operator < (const StateChunk &other) const
{
return this < &other;
}
bool TextureObjRefChunk::operator == (const StateChunk &other) const
{
bool returnValue = false;
return returnValue;
}
bool TextureObjRefChunk::operator != (const StateChunk &other) const
{
return ! (*this == other);
}
<|endoftext|> |
<commit_before><commit_msg>compilo fixes<commit_after><|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc,
bool error_emitted)
{
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
if (error_emitted)
return result;
if (!array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
result->type = glsl_type::error_type;
}
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns 0 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array()) {
/* If the array is a variable dereference, it dereferences the
* whole array, by definition. Use this to get the variable.
*
* FINISHME: Should some methods for getting / setting / testing
* FINISHME: array access limits be added to ir_dereference?
*/
ir_variable *const v = array->whole_variable_referenced();
if ((v != NULL) && (unsigned(idx) > v->max_array_access)) {
v->max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(v->name, idx+1, loc, state);
}
}
} else if (array->type->is_array()) {
if (array->type->array_size() == 0) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
} else if (array->type->fields.array->is_interface()) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*/
if (array->type->element_type()->is_sampler()) {
if (!state->is_version(130, 100)) {
if (state->es_shader) {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is optional in %s",
state->get_version_string());
} else {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL 1.30 "
"and later");
}
} else {
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is forbidden in GLSL 1.30 and "
"later");
}
}
}
return result;
}
<commit_msg>glsl: Don't emit spurious errors for constant indexes of the wrong type<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc,
bool error_emitted)
{
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
if (error_emitted)
return result;
if (!array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
result->type = glsl_type::error_type;
}
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns 0 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array()) {
/* If the array is a variable dereference, it dereferences the
* whole array, by definition. Use this to get the variable.
*
* FINISHME: Should some methods for getting / setting / testing
* FINISHME: array access limits be added to ir_dereference?
*/
ir_variable *const v = array->whole_variable_referenced();
if ((v != NULL) && (unsigned(idx) > v->max_array_access)) {
v->max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(v->name, idx+1, loc, state);
}
}
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->array_size() == 0) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
} else if (array->type->fields.array->is_interface()) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*/
if (array->type->element_type()->is_sampler()) {
if (!state->is_version(130, 100)) {
if (state->es_shader) {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is optional in %s",
state->get_version_string());
} else {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL 1.30 "
"and later");
}
} else {
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is forbidden in GLSL 1.30 and "
"later");
}
}
}
return result;
}
<|endoftext|> |
<commit_before>//===-- driver.cpp - Swift Compiler Driver --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the swift compiler driver.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/DiagnosticEngine.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Driver/Compilation.h"
#include "swift/Driver/Driver.h"
#include "swift/Driver/Job.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
using namespace swift;
using namespace swift::driver;
std::string getExecutablePath(const char *FirstArg) {
void *P = (void *)(intptr_t)getExecutablePath;
return llvm::sys::fs::getMainExecutable(FirstArg, P);
}
extern int frontend_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr);
extern int transform_ir_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr);
int main(int argc_, const char **argv_) {
// Print a stack trace if we signal out.
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc_, argv_);
// Set up an object which will call llvm::llvm_shutdown() on exit.
llvm::llvm_shutdown_obj Y;
llvm::SmallVector<const char *, 256> argv;
llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
llvm::error_code EC = llvm::sys::Process::GetArgumentVector(argv,
llvm::ArrayRef<const char *>(argv_, argc_), ArgAllocator);
if (EC) {
llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
return 1;
}
// Handle integrated tools.
if (argv.size() > 1){
StringRef FirstArg(argv[1]);
if (FirstArg == "-frontend") {
return frontend_main(llvm::makeArrayRef(argv.data()+2,
argv.data()+argv.size()),
argv[0], (void *)(intptr_t)getExecutablePath);
} else if (FirstArg == "-transform-ir") {
return transform_ir_main(llvm::makeArrayRef(argv.data()+2,
argv.data()+argv.size()),
argv[0], (void *)(intptr_t)getExecutablePath);
}
}
std::string Path = getExecutablePath(argv[0]);
PrintingDiagnosticConsumer PDC;
SourceManager SM;
DiagnosticEngine Diags(SM);
Diags.addConsumer(PDC);
Driver TheDriver(Path, Diags);
llvm::InitializeAllTargets();
std::unique_ptr<Compilation> C = TheDriver.buildCompilation(argv);
// In the event of an unrecoverable error, BuildCompilation will exit early,
// so we can start with a 0 result code.
int ResultCode = 0;
if (C) {
ResultCode = C->performJobs();
}
return ResultCode;
}
<commit_msg>[driver] Updated main() to return 1 if there were any errors building the Compilation.<commit_after>//===-- driver.cpp - Swift Compiler Driver --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the swift compiler driver.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/DiagnosticEngine.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Driver/Compilation.h"
#include "swift/Driver/Driver.h"
#include "swift/Driver/Job.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
using namespace swift;
using namespace swift::driver;
std::string getExecutablePath(const char *FirstArg) {
void *P = (void *)(intptr_t)getExecutablePath;
return llvm::sys::fs::getMainExecutable(FirstArg, P);
}
extern int frontend_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr);
extern int transform_ir_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr);
int main(int argc_, const char **argv_) {
// Print a stack trace if we signal out.
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc_, argv_);
// Set up an object which will call llvm::llvm_shutdown() on exit.
llvm::llvm_shutdown_obj Y;
llvm::SmallVector<const char *, 256> argv;
llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
llvm::error_code EC = llvm::sys::Process::GetArgumentVector(argv,
llvm::ArrayRef<const char *>(argv_, argc_), ArgAllocator);
if (EC) {
llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
return 1;
}
// Handle integrated tools.
if (argv.size() > 1){
StringRef FirstArg(argv[1]);
if (FirstArg == "-frontend") {
return frontend_main(llvm::makeArrayRef(argv.data()+2,
argv.data()+argv.size()),
argv[0], (void *)(intptr_t)getExecutablePath);
} else if (FirstArg == "-transform-ir") {
return transform_ir_main(llvm::makeArrayRef(argv.data()+2,
argv.data()+argv.size()),
argv[0], (void *)(intptr_t)getExecutablePath);
}
}
std::string Path = getExecutablePath(argv[0]);
PrintingDiagnosticConsumer PDC;
SourceManager SM;
DiagnosticEngine Diags(SM);
Diags.addConsumer(PDC);
Driver TheDriver(Path, Diags);
llvm::InitializeAllTargets();
std::unique_ptr<Compilation> C = TheDriver.buildCompilation(argv);
if (Diags.hadAnyError())
return 1;
if (C) {
return C->performJobs();
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2008-2017 the MRtrix3 contributors.
*
* 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/.
*
* MRtrix 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.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "file/config.h"
#include "gui/opengl/gl.h"
#include "gui/mrview/mode/base.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
Base::Base (int flags) :
projection (window().glarea, window().font),
features (flags),
update_overlays (false),
visible (true) { }
Base::~Base ()
{
glarea()->setCursor (Cursor::crosshair);
}
const Projection* Base::get_current_projection () const { return &projection; }
void Base::paintGL ()
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
GL_CHECK_ERROR;
projection.set_viewport (window(), 0, 0, width(), height());
GL_CHECK_ERROR;
gl::Clear (gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
if (!image()) {
projection.setup_render_text();
projection.render_text (10, 10, "No image loaded");
projection.done_render_text();
goto done_painting;
}
GL_CHECK_ERROR;
if (!std::isfinite (focus().squaredNorm()) || !std::isfinite (target().squaredNorm()))
reset_view();
{
GL_CHECK_ERROR;
// call mode's draw method:
paint (projection);
gl::Disable (gl::MULTISAMPLE);
GL_CHECK_ERROR;
projection.setup_render_text();
if (window().show_voxel_info()) {
Eigen::Vector3f voxel (image()->transform().scanner2voxel.cast<float>() * focus());
ssize_t vox [] = { ssize_t(std::round (voxel[0])), ssize_t(std::round (voxel[1])), ssize_t(std::round (voxel[2])) };
std::string vox_str = printf ("voxel: [ %d %d %d ", vox[0], vox[1], vox[2]);
for (size_t n = 3; n < image()->header().ndim(); ++n)
vox_str += str(image()->image.index(n)) + " ";
vox_str += "]";
projection.render_text (printf ("position: [ %.4g %.4g %.4g ] mm", focus() [0], focus() [1], focus() [2]), LeftEdge | BottomEdge);
projection.render_text (vox_str, LeftEdge | BottomEdge, 1);
std::string value_str = "value: ";
cfloat value = image()->interpolate() ?
image()->trilinear_value (window().focus()) :
image()->nearest_neighbour_value (window().focus());
if (std::isfinite (std::abs (value)))
value_str += str(value);
else
value_str += "?";
projection.render_text (value_str, LeftEdge | BottomEdge, 2);
// Draw additional labels from tools
QList<QAction*> tools = window().tools()->actions();
for (size_t i = 0, line_num = 3, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
line_num += dock->tool->draw_tool_labels (LeftEdge | BottomEdge, line_num, projection);
}
}
GL_CHECK_ERROR;
if (window().show_comments()) {
for (size_t line = 0; line != image()->comments().size(); ++line)
projection.render_text (image()->comments()[line], LeftEdge | TopEdge, line);
}
projection.done_render_text();
GL_CHECK_ERROR;
if (window().show_colourbar()) {
auto &colourbar_renderer = window().colourbar_renderer;
colourbar_renderer.begin_render_colourbars (&projection, window().colourbar_position, 1);
colourbar_renderer.render (*image(), image()->scale_inverted());
colourbar_renderer.end_render_colourbars ();
QList<QAction*> tools = window().tools()->actions();
size_t num_tool_colourbars = 0;
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
num_tool_colourbars += dock->tool->visible_number_colourbars ();
}
colourbar_renderer.begin_render_colourbars (&projection, window().tools_colourbar_position, num_tool_colourbars);
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
dock->tool->draw_colourbars ();
}
colourbar_renderer.end_render_colourbars ();
}
GL_CHECK_ERROR;
}
done_painting:
update_overlays = false;
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void Base::paint (Projection&) { }
void Base::mouse_press_event () { }
void Base::mouse_release_event () { }
void Base::slice_move_event (float x)
{
const Projection* proj = get_current_projection();
if (!proj) return;
const auto &header = image()->header();
float increment = snap_to_image() ?
x * header.spacing (plane()) :
x * std::pow (header.spacing(0) * header.spacing(1) * header.spacing(2), 1/3.f);
move_in_out (increment, *proj);
move_target_to_focus_plane (*proj);
updateGL();
}
void Base::set_focus_event ()
{
const Projection* proj = get_current_projection();
if (!proj) return;
set_focus (proj->screen_to_model (window().mouse_position(), focus()));
updateGL();
}
void Base::contrast_event ()
{
image()->adjust_windowing (window().mouse_displacement());
window().on_scaling_changed();
updateGL();
}
void Base::pan_event ()
{
const Projection* proj = get_current_projection();
if (!proj) return;
set_target (target() - proj->screen_to_model_direction (window().mouse_displacement(), target()));
updateGL();
}
void Base::panthrough_event ()
{
const Projection* proj = get_current_projection();
if (!proj) return;
move_in_out_FOV (window().mouse_displacement().y(), *proj);
move_target_to_focus_plane (*proj);
updateGL();
}
void Base::setup_projection (const int axis, Projection& with_projection) const
{
const GL::mat4 M = snap_to_image() ? GL::mat4 (image()->transform().image2scanner.matrix()) : GL::mat4 (orientation());
setup_projection (adjust_projection_matrix (GL::transpose (M), axis), with_projection);
}
void Base::setup_projection (const Math::Versorf& V, Projection& with_projection) const
{
setup_projection (adjust_projection_matrix (GL::transpose (GL::mat4 (V))), with_projection);
}
void Base::setup_projection (const GL::mat4& M, Projection& with_projection) const
{
// info for projection:
const int w = with_projection.width(), h = with_projection.height();
const float fov = FOV() / (float)(w+h);
const float depth = std::sqrt ( Math::pow2 (image()->header().spacing(0) * image()->header().size(0))
+ Math::pow2 (image()->header().spacing(1) * image()->header().size(1))
+ Math::pow2 (image()->header().spacing(2) * image()->header().size(2)));
// set up projection & modelview matrices:
const GL::mat4 P = GL::ortho (-w*fov, w*fov, -h*fov, h*fov, -depth, depth);
const GL::mat4 MV = M * GL::translate (-target());
with_projection.set (MV, P);
}
Math::Versorf Base::get_tilt_rotation () const
{
const Projection* proj = get_current_projection();
if (!proj)
return Math::Versorf();
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
const Eigen::Vector3f x = proj->screen_to_model_direction (dpos, target());
const Eigen::Vector3f z = proj->screen_normal();
const Eigen::Vector3f v (x.cross (z).normalized());
float angle = -ROTATION_INC * std::sqrt (float (Math::pow2 (dpos.x()) + Math::pow2 (dpos.y())));
if (angle > Math::pi_2)
angle = Math::pi_2;
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
Math::Versorf Base::get_rotate_rotation () const
{
const Projection* proj = get_current_projection();
if (!proj)
return Math::Versorf();
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
Eigen::Vector3f x1 (window().mouse_position().x() - proj->x_position() - proj->width()/2,
window().mouse_position().y() - proj->y_position() - proj->height()/2,
0.0);
if (x1.norm() < 16.0f)
return Math::Versorf();
Eigen::Vector3f x0 (dpos.x() - x1[0], dpos.y() - x1[1], 0.0);
x1.normalize();
x0.normalize();
const Eigen::Vector3f n = x1.cross (x0);
const float angle = n[2];
Eigen::Vector3f v = (proj->screen_normal()).normalized();
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
void Base::tilt_event ()
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_tilt_rotation();
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::rotate_event ()
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_rotate_rotation();
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::reset_event ()
{
reset_view();
updateGL();
}
void Base::reset_view ()
{
if (!image()) return;
const Projection* proj = get_current_projection();
if (!proj) return;
float dim[] = {
float(image()->header().size (0) * image()->header().spacing (0)),
float(image()->header().size (1) * image()->header().spacing (1)),
float(image()->header().size (2) * image()->header().spacing (2))
};
if (dim[0] < dim[1] && dim[0] < dim[2])
set_plane (0);
else if (dim[1] < dim[0] && dim[1] < dim[2])
set_plane (1);
else
set_plane (2);
Eigen::Vector3f p (
std::floor ((image()->header().size(0)-1)/2.0f),
std::floor ((image()->header().size(1)-1)/2.0f),
std::floor ((image()->header().size(2)-1)/2.0f)
);
set_focus (image()->transform().voxel2scanner.cast<float>() * p);
set_target (focus());
reset_orientation();
int x, y;
image()->get_axes (plane(), x, y);
set_FOV (std::max (dim[x], dim[y]));
updateGL();
}
GL::mat4 Base::adjust_projection_matrix (const GL::mat4& Q, int proj) const
{
GL::mat4 M;
M(3,0) = M(3,1) = M(3,2) = M(0,3) = M(1,3) = M(2,3) = 0.0f;
M(3,3) = 1.0f;
if (proj == 0) { // sagittal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(1,n); // x: -y
M(1,n) = Q(2,n); // y: z
M(2,n) = -Q(0,n); // z: -x
}
}
else if (proj == 1) { // coronal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(2,n); // y: z
M(2,n) = Q(1,n); // z: y
}
}
else { // axial
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(1,n); // y: y
M(2,n) = -Q(2,n); // z: -z
}
}
return M;
}
}
}
}
}
#undef MODE
<commit_msg>mrview: pan_event: removed updateGL() which causes pan gestures to remain in state Qt::GestureUpdated, never reaching Qt::GestureFinished on macOS #761. no negative side effects - I think<commit_after>/* Copyright (c) 2008-2017 the MRtrix3 contributors.
*
* 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/.
*
* MRtrix 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.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "file/config.h"
#include "gui/opengl/gl.h"
#include "gui/mrview/mode/base.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
Base::Base (int flags) :
projection (window().glarea, window().font),
features (flags),
update_overlays (false),
visible (true) { }
Base::~Base ()
{
glarea()->setCursor (Cursor::crosshair);
}
const Projection* Base::get_current_projection () const { return &projection; }
void Base::paintGL ()
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
GL_CHECK_ERROR;
projection.set_viewport (window(), 0, 0, width(), height());
GL_CHECK_ERROR;
gl::Clear (gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
if (!image()) {
projection.setup_render_text();
projection.render_text (10, 10, "No image loaded");
projection.done_render_text();
goto done_painting;
}
GL_CHECK_ERROR;
if (!std::isfinite (focus().squaredNorm()) || !std::isfinite (target().squaredNorm()))
reset_view();
{
GL_CHECK_ERROR;
// call mode's draw method:
paint (projection);
gl::Disable (gl::MULTISAMPLE);
GL_CHECK_ERROR;
projection.setup_render_text();
if (window().show_voxel_info()) {
Eigen::Vector3f voxel (image()->transform().scanner2voxel.cast<float>() * focus());
ssize_t vox [] = { ssize_t(std::round (voxel[0])), ssize_t(std::round (voxel[1])), ssize_t(std::round (voxel[2])) };
std::string vox_str = printf ("voxel: [ %d %d %d ", vox[0], vox[1], vox[2]);
for (size_t n = 3; n < image()->header().ndim(); ++n)
vox_str += str(image()->image.index(n)) + " ";
vox_str += "]";
projection.render_text (printf ("position: [ %.4g %.4g %.4g ] mm", focus() [0], focus() [1], focus() [2]), LeftEdge | BottomEdge);
projection.render_text (vox_str, LeftEdge | BottomEdge, 1);
std::string value_str = "value: ";
cfloat value = image()->interpolate() ?
image()->trilinear_value (window().focus()) :
image()->nearest_neighbour_value (window().focus());
if (std::isfinite (std::abs (value)))
value_str += str(value);
else
value_str += "?";
projection.render_text (value_str, LeftEdge | BottomEdge, 2);
// Draw additional labels from tools
QList<QAction*> tools = window().tools()->actions();
for (size_t i = 0, line_num = 3, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
line_num += dock->tool->draw_tool_labels (LeftEdge | BottomEdge, line_num, projection);
}
}
GL_CHECK_ERROR;
if (window().show_comments()) {
for (size_t line = 0; line != image()->comments().size(); ++line)
projection.render_text (image()->comments()[line], LeftEdge | TopEdge, line);
}
projection.done_render_text();
GL_CHECK_ERROR;
if (window().show_colourbar()) {
auto &colourbar_renderer = window().colourbar_renderer;
colourbar_renderer.begin_render_colourbars (&projection, window().colourbar_position, 1);
colourbar_renderer.render (*image(), image()->scale_inverted());
colourbar_renderer.end_render_colourbars ();
QList<QAction*> tools = window().tools()->actions();
size_t num_tool_colourbars = 0;
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
num_tool_colourbars += dock->tool->visible_number_colourbars ();
}
colourbar_renderer.begin_render_colourbars (&projection, window().tools_colourbar_position, num_tool_colourbars);
for (size_t i = 0, N = tools.size(); i < N; ++i) {
Tool::Dock* dock = dynamic_cast<Tool::__Action__*>(tools[i])->dock;
if (dock)
dock->tool->draw_colourbars ();
}
colourbar_renderer.end_render_colourbars ();
}
GL_CHECK_ERROR;
}
done_painting:
update_overlays = false;
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void Base::paint (Projection&) { }
void Base::mouse_press_event () { }
void Base::mouse_release_event () { }
void Base::slice_move_event (float x)
{
const Projection* proj = get_current_projection();
if (!proj) return;
const auto &header = image()->header();
float increment = snap_to_image() ?
x * header.spacing (plane()) :
x * std::pow (header.spacing(0) * header.spacing(1) * header.spacing(2), 1/3.f);
move_in_out (increment, *proj);
move_target_to_focus_plane (*proj);
updateGL();
}
void Base::set_focus_event ()
{
const Projection* proj = get_current_projection();
if (!proj) return;
set_focus (proj->screen_to_model (window().mouse_position(), focus()));
updateGL();
}
void Base::contrast_event ()
{
image()->adjust_windowing (window().mouse_displacement());
window().on_scaling_changed();
updateGL();
}
void Base::pan_event ()
{
const Projection* proj = get_current_projection();
if (!proj) return;
set_target (target() - proj->screen_to_model_direction (window().mouse_displacement(), target()));
// updateGL(); # updateGL() causes pan gestures to remain in state Qt::GestureUpdated, never reaching Qt::GestureFinished on macOS
}
void Base::panthrough_event ()
{
const Projection* proj = get_current_projection();
if (!proj) return;
move_in_out_FOV (window().mouse_displacement().y(), *proj);
move_target_to_focus_plane (*proj);
updateGL();
}
void Base::setup_projection (const int axis, Projection& with_projection) const
{
const GL::mat4 M = snap_to_image() ? GL::mat4 (image()->transform().image2scanner.matrix()) : GL::mat4 (orientation());
setup_projection (adjust_projection_matrix (GL::transpose (M), axis), with_projection);
}
void Base::setup_projection (const Math::Versorf& V, Projection& with_projection) const
{
setup_projection (adjust_projection_matrix (GL::transpose (GL::mat4 (V))), with_projection);
}
void Base::setup_projection (const GL::mat4& M, Projection& with_projection) const
{
// info for projection:
const int w = with_projection.width(), h = with_projection.height();
const float fov = FOV() / (float)(w+h);
const float depth = std::sqrt ( Math::pow2 (image()->header().spacing(0) * image()->header().size(0))
+ Math::pow2 (image()->header().spacing(1) * image()->header().size(1))
+ Math::pow2 (image()->header().spacing(2) * image()->header().size(2)));
// set up projection & modelview matrices:
const GL::mat4 P = GL::ortho (-w*fov, w*fov, -h*fov, h*fov, -depth, depth);
const GL::mat4 MV = M * GL::translate (-target());
with_projection.set (MV, P);
}
Math::Versorf Base::get_tilt_rotation () const
{
const Projection* proj = get_current_projection();
if (!proj)
return Math::Versorf();
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
const Eigen::Vector3f x = proj->screen_to_model_direction (dpos, target());
const Eigen::Vector3f z = proj->screen_normal();
const Eigen::Vector3f v (x.cross (z).normalized());
float angle = -ROTATION_INC * std::sqrt (float (Math::pow2 (dpos.x()) + Math::pow2 (dpos.y())));
if (angle > Math::pi_2)
angle = Math::pi_2;
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
Math::Versorf Base::get_rotate_rotation () const
{
const Projection* proj = get_current_projection();
if (!proj)
return Math::Versorf();
QPoint dpos = window().mouse_displacement();
if (dpos.x() == 0 && dpos.y() == 0)
return Math::Versorf();
Eigen::Vector3f x1 (window().mouse_position().x() - proj->x_position() - proj->width()/2,
window().mouse_position().y() - proj->y_position() - proj->height()/2,
0.0);
if (x1.norm() < 16.0f)
return Math::Versorf();
Eigen::Vector3f x0 (dpos.x() - x1[0], dpos.y() - x1[1], 0.0);
x1.normalize();
x0.normalize();
const Eigen::Vector3f n = x1.cross (x0);
const float angle = n[2];
Eigen::Vector3f v = (proj->screen_normal()).normalized();
return Math::Versorf (Eigen::AngleAxisf (angle, v));
}
void Base::tilt_event ()
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_tilt_rotation();
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::rotate_event ()
{
if (snap_to_image())
window().set_snap_to_image (false);
const Math::Versorf rot = get_rotate_rotation();
if (!rot)
return;
Math::Versorf orient = rot * orientation();
set_orientation (orient);
updateGL();
}
void Base::reset_event ()
{
reset_view();
updateGL();
}
void Base::reset_view ()
{
if (!image()) return;
const Projection* proj = get_current_projection();
if (!proj) return;
float dim[] = {
float(image()->header().size (0) * image()->header().spacing (0)),
float(image()->header().size (1) * image()->header().spacing (1)),
float(image()->header().size (2) * image()->header().spacing (2))
};
if (dim[0] < dim[1] && dim[0] < dim[2])
set_plane (0);
else if (dim[1] < dim[0] && dim[1] < dim[2])
set_plane (1);
else
set_plane (2);
Eigen::Vector3f p (
std::floor ((image()->header().size(0)-1)/2.0f),
std::floor ((image()->header().size(1)-1)/2.0f),
std::floor ((image()->header().size(2)-1)/2.0f)
);
set_focus (image()->transform().voxel2scanner.cast<float>() * p);
set_target (focus());
reset_orientation();
int x, y;
image()->get_axes (plane(), x, y);
set_FOV (std::max (dim[x], dim[y]));
updateGL();
}
GL::mat4 Base::adjust_projection_matrix (const GL::mat4& Q, int proj) const
{
GL::mat4 M;
M(3,0) = M(3,1) = M(3,2) = M(0,3) = M(1,3) = M(2,3) = 0.0f;
M(3,3) = 1.0f;
if (proj == 0) { // sagittal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(1,n); // x: -y
M(1,n) = Q(2,n); // y: z
M(2,n) = -Q(0,n); // z: -x
}
}
else if (proj == 1) { // coronal
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(2,n); // y: z
M(2,n) = Q(1,n); // z: y
}
}
else { // axial
for (size_t n = 0; n < 3; n++) {
M(0,n) = -Q(0,n); // x: -x
M(1,n) = Q(1,n); // y: y
M(2,n) = -Q(2,n); // z: -z
}
}
return M;
}
}
}
}
}
#undef MODE
<|endoftext|> |
<commit_before><commit_msg>gui: check across all layers to determine rotation<commit_after><|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013-2014, Luke Goddard. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Luke Goddard nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "boost/test/test_tools.hpp"
#include "boost/test/results_reporter.hpp"
#include "boost/test/unit_test_suite.hpp"
#include "boost/test/output_test_stream.hpp"
#include "boost/test/unit_test_log.hpp"
#include "boost/test/framework.hpp"
#include "boost/test/detail/unit_test_parameters.hpp"
#include "GanderTest/LevenbergMarquardtTest.h"
#include "GanderTest/HomographyTest.h"
#include "GanderTest/AngleConversionTest.h"
#include "GanderTest/DecomposeRQ3x3Test.h"
#include "GanderTest/CommonTest.h"
#include "GanderTest/EnumHelperTest.h"
#include "GanderTest/BitTwiddlerTest.h"
using namespace boost::unit_test;
using boost::test_tools::output_test_stream;
using namespace Gander;
using namespace Gander::Test;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
test_suite* test = BOOST_TEST_SUITE( "Gander unit test" );
try
{
addLevenbergMarquardtTest(test);
addHomographyTest(test);
addDecomposeRQ3x3Test(test);
addAngleConversionTest(test);
addCommonTest(test);
addEnumHelperTest(test);
addBitTwiddlerTest(test);
}
catch (std::exception &ex)
{
std::cerr << "Failed to create test suite: " << ex.what() << std::endl;
throw;
}
return test;
}
<commit_msg>Made calls to the Tuple and Interface test cases.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013-2014, Luke Goddard. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Luke Goddard nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "boost/test/test_tools.hpp"
#include "boost/test/results_reporter.hpp"
#include "boost/test/unit_test_suite.hpp"
#include "boost/test/output_test_stream.hpp"
#include "boost/test/unit_test_log.hpp"
#include "boost/test/framework.hpp"
#include "boost/test/detail/unit_test_parameters.hpp"
#include "GanderTest/LevenbergMarquardtTest.h"
#include "GanderTest/HomographyTest.h"
#include "GanderTest/AngleConversionTest.h"
#include "GanderTest/DecomposeRQ3x3Test.h"
#include "GanderTest/CommonTest.h"
#include "GanderTest/EnumHelperTest.h"
#include "GanderTest/BitTwiddlerTest.h"
#include "GanderTest/TupleTest.h"
#include "GanderTest/InterfacesTest.h"
using namespace boost::unit_test;
using boost::test_tools::output_test_stream;
using namespace Gander;
using namespace Gander::Test;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
test_suite* test = BOOST_TEST_SUITE( "Gander unit test" );
try
{
addLevenbergMarquardtTest(test);
addHomographyTest(test);
addDecomposeRQ3x3Test(test);
addAngleConversionTest(test);
addCommonTest(test);
addEnumHelperTest(test);
addBitTwiddlerTest(test);
addTupleTest(test);
addInterfacesTest(test);
}
catch (std::exception &ex)
{
std::cerr << "Failed to create test suite: " << ex.what() << std::endl;
throw;
}
return test;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/CINImageWriter.h"
#include "IECore/MessageHandler.h"
#include "IECore/VectorTypedData.h"
#include "IECore/ByteOrder.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/FileNameParameter.h"
#include "IECore/DataConvert.h"
#include "IECore/ScaledDataConversion.h"
#include "IECore/CompoundDataConversion.h"
#include "IECore/LinearToCineonDataConversion.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/private/cineon.h"
#include "boost/format.hpp"
#include <fstream>
#include <time.h>
using namespace IECore;
using namespace std;
using namespace boost;
using namespace Imath;
const Writer::WriterDescription<CINImageWriter> CINImageWriter::m_writerDescription("cin");
CINImageWriter::CINImageWriter() :
ImageWriter("CINImageWriter", "Serializes images to the Kodak Cineon 10-bit log image format")
{
}
CINImageWriter::CINImageWriter( ObjectPtr image, const string &fileName ) :
ImageWriter("CINImageWriter", "Serializes images to the Kodak Cineon 10-bit log image format")
{
m_objectParameter->setValue( image );
m_fileNameParameter->setTypedValue( fileName );
}
CINImageWriter::~CINImageWriter()
{
}
struct CINImageWriter::ChannelConverter
{
typedef void ReturnType;
std::string m_channelName;
Box2i m_displayWindow;
Box2i m_dataWindow;
unsigned int m_bitShift;
std::vector<unsigned int> &m_imageBuffer;
ChannelConverter( const std::string &channelName, const Box2i &displayWindow, const Box2i &dataWindow, unsigned int bitShift, std::vector<unsigned int> &imageBuffer )
: m_channelName( channelName ), m_displayWindow( displayWindow ), m_dataWindow( dataWindow ), m_bitShift( bitShift ), m_imageBuffer( imageBuffer )
{
}
template<typename T>
ReturnType operator()( typename T::Ptr dataContainer )
{
assert( dataContainer );
const typename T::ValueType &data = dataContainer->readable();
CompoundDataConversion<
ScaledDataConversion<typename T::ValueType::value_type, float>,
LinearToCineonDataConversion<float, unsigned int>
> converter;
int displayWidth = m_displayWindow.size().x + 1;
int dataWidth = m_dataWindow.size().x + 1;
int dataY = 0;
for ( int y = m_dataWindow.min.y; y <= m_dataWindow.max.y; y++, dataY++ )
{
int dataOffset = dataY * dataWidth ;
assert( dataOffset >= 0 );
for ( int x = m_dataWindow.min.x; x <= m_dataWindow.max.x; x++, dataOffset++ )
{
int pixelIdx = ( y - m_displayWindow.min.y ) * displayWidth + ( x - m_displayWindow.min.x );
assert( pixelIdx >= 0 );
assert( pixelIdx < (int)m_imageBuffer.size() );
assert( dataOffset < (int)data.size() );
/// Perform the conversion, and set the appropriate bits in the "cell"
m_imageBuffer[ pixelIdx ] |= converter( data[dataOffset] ) << m_bitShift;
}
}
};
struct ErrorHandler
{
template<typename T, typename F>
void operator()( typename T::ConstPtr data, const F& functor )
{
assert( data );
throw InvalidArgumentException( ( boost::format( "CINImageWriter: Invalid data type \"%s\" for channel \"%s\"." ) % Object::typeNameFromTypeId( data->typeId() ) % functor.m_channelName ).str() );
}
};
};
void CINImageWriter::writeImage( const vector<string> &names, ConstImagePrimitivePtr image, const Box2i &dataWindow ) const
{
// write the cineon in the standard 10bit log format
std::ofstream out;
out.open(fileName().c_str());
if (!out.is_open())
{
throw IOException( "CINImageWriter: Could not open " + fileName() );
}
/// We'd like RGB to be at the front, in that order, because it seems that not all readers support the channel identifiers!
vector<string> desiredChannelOrder;
desiredChannelOrder.push_back( "R" );
desiredChannelOrder.push_back( "G" );
desiredChannelOrder.push_back( "B" );
vector<string> namesCopy = names;
vector<string> filteredNames;
for ( vector<string>::const_iterator it = desiredChannelOrder.begin(); it != desiredChannelOrder.end(); ++it )
{
vector<string>::iterator res = find( namesCopy.begin(), namesCopy.end(), *it );
if ( res != namesCopy.end() )
{
namesCopy.erase( res );
filteredNames.push_back( *it );
}
}
for ( vector<string>::const_iterator it = namesCopy.begin(); it != namesCopy.end(); ++it )
{
filteredNames.push_back( *it );
}
assert( names.size() == filteredNames.size() );
Box2i displayWindow = image->getDisplayWindow();
int displayWidth = 1 + displayWindow.size().x;
int displayHeight = 1 + displayWindow.size().y;
// build the header
FileInformation fi;
fi.magic = asBigEndian<>( 0x802a5fd7 );
fi.section_header_length = 0;
fi.industry_header_length = 0;
fi.variable_header_length = 0;
strcpy(fi.version, "V4.5");
strncpy( (char *) fi.file_name, fileName().c_str(), sizeof( fi.file_name ) );
// compute the current date and time
time_t t;
time(&t);
struct tm gmt;
localtime_r(&t, &gmt);
snprintf(fi.creation_date, sizeof( fi.creation_date ), "%04d-%02d-%02d", 1900 + gmt.tm_year, gmt.tm_mon, gmt.tm_mday);
snprintf(fi.creation_time, sizeof( fi.creation_time ), "%02d:%02d:%02d", gmt.tm_hour, gmt.tm_min, gmt.tm_sec);
ImageInformation ii;
ii.orientation = 0;
ii.channel_count = 0;
for (int c = 0; c < 8; ++c)
{
ImageInformationChannelInformation &ci = ii.channel_information[c];
ci.byte_0 = 0;
ci.byte_1 = 0;
ci.bpp = 10;
ci.pixels_per_line = 0;
ci.lines_per_image = 0;
}
// write the data
std::vector<unsigned int> imageBuffer( displayWidth*displayHeight, 0 );
vector<string>::const_iterator i = filteredNames.begin();
int offset = 0;
while (i != filteredNames.end())
{
if (!(*i == "R" || *i == "G" || *i == "B" || *i == "Y"))
{
msg( Msg::Warning, "CINImageWriter::write", format( "Channel \"%s\" was not encoded." ) % *i );
++i;
continue;
}
ImageInformationChannelInformation &ci = ii.channel_information[offset];
ci.byte_0 = 0;
if ( *i == "R" )
{
ci.byte_1 = 1;
}
else if ( *i == "G" )
{
ci.byte_1 = 2;
}
else if ( *i == "B" )
{
ci.byte_1 = 3;
}
else if ( *i == "Y" )
{
ci.byte_1 = 0;
}
ci.bpp = 10;
ci.pixels_per_line = asBigEndian<>( displayWidth );
ci.lines_per_image = asBigEndian<>( displayHeight );
/// \todo Document these constants
ci.min_data_value = 0.0;
ci.min_quantity = 0.0;
ci.max_data_value = 1023.0;
ci.max_quantity = 2.046;
ci.min_data_value = asBigEndian<>( ci.min_data_value );
ci.min_quantity = asBigEndian<>( ci.min_quantity );
ci.max_data_value = asBigEndian<>( ci.max_data_value );
ci.min_quantity = asBigEndian<>( ci.max_quantity );
int bpp = 10;
unsigned int shift = (32 - bpp) - (offset*bpp);
assert( image->variables.find( *i ) != image->variables.end() );
DataPtr dataContainer = image->variables.find( *i )->second.data;
assert( dataContainer );
ChannelConverter converter( *i, image->getDisplayWindow(), dataWindow, shift, imageBuffer );
despatchTypedData<
ChannelConverter,
TypeTraits::IsNumericVectorTypedData,
ChannelConverter::ErrorHandler
>( dataContainer, converter );
ii.channel_count ++;
++offset;
++i;
}
if ( ii.channel_count < 1 || ii.channel_count > 3 )
{
throw IOException( "CINImageWriter: Invalid number of channels" );
}
ImageDataFormatInformation idfi;
idfi.interleave = 0; // pixel interleave
idfi.packing = 5; // 32 bit left-aligned with 2 waste bits
idfi.data_signed = 0; // unsigned data
idfi.sense = 0; // positive image sense
idfi.eol_padding = 0; // no end-of-line padding
idfi.eoc_padding = 0; // no end-of-data padding
/// \todo Complete filling in this structure
ImageOriginationInformation ioi;
ioi.x_offset = 0; // could be dataWindow min.x
ioi.y_offset = 0; // could be dataWindow min.y
ioi.gamma = 0x7f800000;
ioi.gamma = asBigEndian<>(ioi.gamma);
// compute data offsets
fi.image_data_offset = 1024;
fi.image_data_offset = asBigEndian<>(fi.image_data_offset);
// file size is 1024 (header) + image data size
// image data size is 32 bits times width*height
fi.total_file_size = 1024 + sizeof( unsigned int ) * displayWidth * displayHeight;
fi.total_file_size = asBigEndian<>(fi.total_file_size);
out.write(reinterpret_cast<char *>(&fi), sizeof(fi));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ii), sizeof(ii));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&idfi), sizeof(idfi));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ioi), sizeof(ioi));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
// write the buffer
for (int i = 0; i < displayWidth*displayHeight; ++i)
{
imageBuffer[i] = asBigEndian<>(imageBuffer[i]);
out.write((const char *) (&imageBuffer[i]), sizeof(unsigned int));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
}
}
<commit_msg>Added assert and todo<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/CINImageWriter.h"
#include "IECore/MessageHandler.h"
#include "IECore/VectorTypedData.h"
#include "IECore/ByteOrder.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/FileNameParameter.h"
#include "IECore/DataConvert.h"
#include "IECore/ScaledDataConversion.h"
#include "IECore/CompoundDataConversion.h"
#include "IECore/LinearToCineonDataConversion.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/private/cineon.h"
#include "boost/format.hpp"
#include <fstream>
#include <time.h>
using namespace IECore;
using namespace std;
using namespace boost;
using namespace Imath;
const Writer::WriterDescription<CINImageWriter> CINImageWriter::m_writerDescription("cin");
CINImageWriter::CINImageWriter() :
ImageWriter("CINImageWriter", "Serializes images to the Kodak Cineon 10-bit log image format")
{
}
CINImageWriter::CINImageWriter( ObjectPtr image, const string &fileName ) :
ImageWriter("CINImageWriter", "Serializes images to the Kodak Cineon 10-bit log image format")
{
m_objectParameter->setValue( image );
m_fileNameParameter->setTypedValue( fileName );
}
CINImageWriter::~CINImageWriter()
{
}
struct CINImageWriter::ChannelConverter
{
typedef void ReturnType;
std::string m_channelName;
Box2i m_displayWindow;
Box2i m_dataWindow;
unsigned int m_bitShift;
std::vector<unsigned int> &m_imageBuffer;
ChannelConverter( const std::string &channelName, const Box2i &displayWindow, const Box2i &dataWindow, unsigned int bitShift, std::vector<unsigned int> &imageBuffer )
: m_channelName( channelName ), m_displayWindow( displayWindow ), m_dataWindow( dataWindow ), m_bitShift( bitShift ), m_imageBuffer( imageBuffer )
{
}
template<typename T>
ReturnType operator()( typename T::Ptr dataContainer )
{
assert( dataContainer );
const typename T::ValueType &data = dataContainer->readable();
CompoundDataConversion<
ScaledDataConversion<typename T::ValueType::value_type, float>,
LinearToCineonDataConversion<float, unsigned int>
> converter;
int displayWidth = m_displayWindow.size().x + 1;
int dataWidth = m_dataWindow.size().x + 1;
int dataY = 0;
for ( int y = m_dataWindow.min.y; y <= m_dataWindow.max.y; y++, dataY++ )
{
int dataOffset = dataY * dataWidth ;
assert( dataOffset >= 0 );
for ( int x = m_dataWindow.min.x; x <= m_dataWindow.max.x; x++, dataOffset++ )
{
int pixelIdx = ( y - m_displayWindow.min.y ) * displayWidth + ( x - m_displayWindow.min.x );
assert( pixelIdx >= 0 );
assert( pixelIdx < (int)m_imageBuffer.size() );
assert( dataOffset < (int)data.size() );
/// Perform the conversion, and set the appropriate bits in the "cell"
m_imageBuffer[ pixelIdx ] |= converter( data[dataOffset] ) << m_bitShift;
}
}
};
struct ErrorHandler
{
template<typename T, typename F>
void operator()( typename T::ConstPtr data, const F& functor )
{
assert( data );
throw InvalidArgumentException( ( boost::format( "CINImageWriter: Invalid data type \"%s\" for channel \"%s\"." ) % Object::typeNameFromTypeId( data->typeId() ) % functor.m_channelName ).str() );
}
};
};
void CINImageWriter::writeImage( const vector<string> &names, ConstImagePrimitivePtr image, const Box2i &dataWindow ) const
{
// write the cineon in the standard 10bit log format
std::ofstream out;
out.open(fileName().c_str());
if (!out.is_open())
{
throw IOException( "CINImageWriter: Could not open " + fileName() );
}
/// We'd like RGB to be at the front, in that order, because it seems that not all readers support the channel identifiers!
vector<string> desiredChannelOrder;
desiredChannelOrder.push_back( "R" );
desiredChannelOrder.push_back( "G" );
desiredChannelOrder.push_back( "B" );
vector<string> namesCopy = names;
vector<string> filteredNames;
for ( vector<string>::const_iterator it = desiredChannelOrder.begin(); it != desiredChannelOrder.end(); ++it )
{
vector<string>::iterator res = find( namesCopy.begin(), namesCopy.end(), *it );
if ( res != namesCopy.end() )
{
namesCopy.erase( res );
filteredNames.push_back( *it );
}
}
for ( vector<string>::const_iterator it = namesCopy.begin(); it != namesCopy.end(); ++it )
{
filteredNames.push_back( *it );
}
assert( names.size() == filteredNames.size() );
Box2i displayWindow = image->getDisplayWindow();
int displayWidth = 1 + displayWindow.size().x;
int displayHeight = 1 + displayWindow.size().y;
// build the header
FileInformation fi;
fi.magic = asBigEndian<>( 0x802a5fd7 );
fi.section_header_length = 0;
fi.industry_header_length = 0;
fi.variable_header_length = 0;
strcpy(fi.version, "V4.5");
strncpy( (char *) fi.file_name, fileName().c_str(), sizeof( fi.file_name ) );
// compute the current date and time
time_t t;
time(&t);
struct tm gmt;
localtime_r(&t, &gmt);
snprintf(fi.creation_date, sizeof( fi.creation_date ), "%04d-%02d-%02d", 1900 + gmt.tm_year, gmt.tm_mon, gmt.tm_mday);
snprintf(fi.creation_time, sizeof( fi.creation_time ), "%02d:%02d:%02d", gmt.tm_hour, gmt.tm_min, gmt.tm_sec);
ImageInformation ii;
ii.orientation = 0;
ii.channel_count = 0;
for (int c = 0; c < 8; ++c)
{
ImageInformationChannelInformation &ci = ii.channel_information[c];
ci.byte_0 = 0;
ci.byte_1 = 0;
ci.bpp = 10;
ci.pixels_per_line = 0;
ci.lines_per_image = 0;
}
// write the data
std::vector<unsigned int> imageBuffer( displayWidth*displayHeight, 0 );
vector<string>::const_iterator i = filteredNames.begin();
int offset = 0;
while (i != filteredNames.end())
{
if (!(*i == "R" || *i == "G" || *i == "B" || *i == "Y"))
{
msg( Msg::Warning, "CINImageWriter::write", format( "Channel \"%s\" was not encoded." ) % *i );
++i;
continue;
}
ImageInformationChannelInformation &ci = ii.channel_information[offset];
ci.byte_0 = 0;
if ( *i == "R" )
{
ci.byte_1 = 1;
}
else if ( *i == "G" )
{
ci.byte_1 = 2;
}
else if ( *i == "B" )
{
ci.byte_1 = 3;
}
else if ( *i == "Y" )
{
ci.byte_1 = 0;
}
ci.bpp = 10;
ci.pixels_per_line = asBigEndian<>( displayWidth );
ci.lines_per_image = asBigEndian<>( displayHeight );
/// \todo Document these constants
ci.min_data_value = 0.0;
ci.min_quantity = 0.0;
ci.max_data_value = 1023.0;
ci.max_quantity = 2.046;
ci.min_data_value = asBigEndian<>( ci.min_data_value );
ci.min_quantity = asBigEndian<>( ci.min_quantity );
ci.max_data_value = asBigEndian<>( ci.max_data_value );
ci.min_quantity = asBigEndian<>( ci.max_quantity );
int bpp = 10;
unsigned int shift = (32 - bpp) - (offset*bpp);
assert( image->variables.find( *i ) != image->variables.end() );
DataPtr dataContainer = image->variables.find( *i )->second.data;
assert( dataContainer );
ChannelConverter converter( *i, image->getDisplayWindow(), dataWindow, shift, imageBuffer );
despatchTypedData<
ChannelConverter,
TypeTraits::IsNumericVectorTypedData,
ChannelConverter::ErrorHandler
>( dataContainer, converter );
ii.channel_count ++;
++offset;
++i;
}
if ( ii.channel_count < 1 || ii.channel_count > 3 )
{
throw IOException( "CINImageWriter: Invalid number of channels" );
}
ImageDataFormatInformation idfi;
idfi.interleave = 0; // pixel interleave
idfi.packing = 5; // 32 bit left-aligned with 2 waste bits
idfi.data_signed = 0; // unsigned data
idfi.sense = 0; // positive image sense
idfi.eol_padding = 0; // no end-of-line padding
idfi.eoc_padding = 0; // no end-of-data padding
/// \todo Complete filling in this structure
ImageOriginationInformation ioi;
ioi.x_offset = 0; // could be dataWindow min.x
ioi.y_offset = 0; // could be dataWindow min.y
ioi.gamma = 0x7f800000;
ioi.gamma = asBigEndian<>(ioi.gamma);
// compute data offsets
fi.image_data_offset = 1024;
fi.image_data_offset = asBigEndian<>(fi.image_data_offset);
// file size is 1024 (header) + image data size
// image data size is 32 bits times width*height
fi.total_file_size = 1024 + sizeof( unsigned int ) * displayWidth * displayHeight;
fi.total_file_size = asBigEndian<>(fi.total_file_size);
out.write(reinterpret_cast<char *>(&fi), sizeof(fi));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ii), sizeof(ii));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&idfi), sizeof(idfi));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
out.write(reinterpret_cast<char *>(&ioi), sizeof(ioi));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
// write the buffer
for (int i = 0; i < displayWidth*displayHeight; ++i)
{
assert( i < (int)imageBuffer.size() );
imageBuffer[i] = asBigEndian<>(imageBuffer[i]);
/// \todo The following line has been seen to generate a valgrind warning that the system functions
/// called from within are attempting to access uninitialized data. Establish why.
out.write((const char *) (&imageBuffer[i]), sizeof(unsigned int));
if ( out.fail() )
{
throw IOException( "CINImageWriter: Error writing to " + fileName() );
}
}
}
<|endoftext|> |
<commit_before>/**
* @project identt
* @file src/http/NotFoundService.hpp
* @author S Roychowdhury <sroycode AT gmail DOT com>
* @version 1.0.0
*
* @section LICENSE
*
* Copyright (c) 2017 S Roychowdhury.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @section DESCRIPTION
*
* NotFoundService.hpp : NotFound Server Implementation
*
*/
#ifndef _IDENTT_HTTP_NOTFOUNDSERVICE_HPP_
#define _IDENTT_HTTP_NOTFOUNDSERVICE_HPP_
#include <http/ServiceBase.hpp>
namespace identt {
namespace http {
template <class HttpServerT>
class NotFoundService : protected identt::http::ServiceBase<HttpServerT> {
public:
/**
* NotFoundService : constructor
*
* @param context
* identt::utils::SharedTable::pointer stptr
*
* @param server
* HttpServerT server
*
* @param scope
* unsigned int scope check
*
* @return
* none
*/
NotFoundService(identt::utils::SharedTable::pointer stptr,
typename std::shared_ptr<HttpServerT> server,
unsigned int scope)
: identt::http::ServiceBase<HttpServerT>(IDENTT_SERVICE_SCOPE_HTTP | IDENTT_SERVICE_SCOPE_HTTPS)
{
if (!(this->myscope & scope)) return; // scope mismatch
server->default_resource["GET"] =
[this](typename HttpServerT::RespPtr response, typename HttpServerT::ReqPtr request) {
this->HttpErrorAction(response,request,404,"NOT FOUND");
};
server->default_resource["POST"] =
[this](typename HttpServerT::RespPtr response, typename HttpServerT::ReqPtr request) {
this->HttpErrorAction(response,request,404,"NOT FOUND");
};
}
private:
};
} // namespace http
} // namespace identt
#endif // _IDENTT_HTTP_NOTFOUNDSERVICE_HPP_
<commit_msg>changed the thirdparty building script<commit_after><|endoftext|> |
<commit_before>/**
* Copyright 2014-2015 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/vm/native-data.h"
#include "../../../bson.h"
#include "../../../mongodb.h"
#include "../../../utils.h"
#include "Command.h"
#include "Server.h"
#include "WriteConcern.h"
namespace HPHP {
const StaticString s_MongoDriverServer_className("MongoDB\\Driver\\Server");
Class* MongoDBDriverServerData::s_class = nullptr;
const StaticString MongoDBDriverServerData::s_className("MongoDBDriverServer");
const StaticString s_MongoDriverServer_host("host");
const StaticString s_MongoDriverServer_port("port");
const StaticString s_MongoDriverServer_type("type");
const StaticString s_MongoDriverServer_is_primary("is_primary");
const StaticString s_MongoDriverServer_is_secondary("is_secondary");
const StaticString s_MongoDriverServer_is_arbiter("is_arbiter");
const StaticString s_MongoDriverServer_hidden("hidden");
const StaticString s_MongoDriverServer_passive("passive");
const StaticString s_MongoDriverServer_is_hidden("is_hidden");
const StaticString s_MongoDriverServer_is_passive("is_passive");
const StaticString s_MongoDriverServer_tags("tags");
const StaticString s_MongoDriverServer_last_is_master("last_is_master");
const StaticString s_MongoDriverServer_round_trip_time("round_trip_time");
IMPLEMENT_GET_CLASS(MongoDBDriverServerData);
Array HHVM_METHOD(MongoDBDriverServer, __debugInfo)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
Array retval = Array::Create();
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
Variant v_last_is_master;
Array a_last_is_master;
retval.set(s_MongoDriverServer_host, sd->host.host);
retval.set(s_MongoDriverServer_port, sd->host.port);
retval.set(s_MongoDriverServer_type, sd->type);
retval.set(s_MongoDriverServer_is_primary, !!(sd->type == MONGOC_SERVER_RS_PRIMARY));
retval.set(s_MongoDriverServer_is_secondary, !!(sd->type == MONGOC_SERVER_RS_SECONDARY));
retval.set(s_MongoDriverServer_is_arbiter, !!(sd->type == MONGOC_SERVER_RS_ARBITER));
hippo_bson_conversion_options_t options = HIPPO_TYPEMAP_DEBUG_INITIALIZER;
BsonToVariantConverter convertor(bson_get_data(&sd->last_is_master), sd->last_is_master.len, options);
convertor.convert(&v_last_is_master);
a_last_is_master = v_last_is_master.toArray();
retval.set(s_MongoDriverServer_is_hidden, a_last_is_master.exists(s_MongoDriverServer_hidden) && !!a_last_is_master[s_MongoDriverServer_hidden].toBoolean());
retval.set(s_MongoDriverServer_is_passive, a_last_is_master.exists(s_MongoDriverServer_passive) && !!a_last_is_master[s_MongoDriverServer_passive].toBoolean());
retval.set(s_MongoDriverServer_last_is_master, a_last_is_master);
retval.set(s_MongoDriverServer_round_trip_time, sd->round_trip_time);
return retval;
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
String HHVM_METHOD(MongoDBDriverServer, getHost)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return String(sd->host.host);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
Array HHVM_METHOD(MongoDBDriverServer, getInfo)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
Variant v;
hippo_bson_conversion_options_t options = HIPPO_TYPEMAP_DEBUG_INITIALIZER;
BsonToVariantConverter convertor(bson_get_data(&sd->last_is_master), sd->last_is_master.len, options);
convertor.convert(&v);
return v.toArray();
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
int64_t HHVM_METHOD(MongoDBDriverServer, getLatency)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (int64_t) (sd->round_trip_time);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
int64_t HHVM_METHOD(MongoDBDriverServer, getPort)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (int64_t) (sd->host.port);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
Array HHVM_METHOD(MongoDBDriverServer, getTags)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
Variant v;
hippo_bson_conversion_options_t options = HIPPO_TYPEMAP_DEBUG_INITIALIZER;
BsonToVariantConverter convertor(bson_get_data(&sd->tags), sd->tags.len, options);
convertor.convert(&v);
return v.toArray();
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
int64_t HHVM_METHOD(MongoDBDriverServer, getType)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (int64_t) (sd->type);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isPrimary)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (bool) (sd->type == MONGOC_SERVER_RS_PRIMARY);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isSecondary)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (bool) (sd->type == MONGOC_SERVER_RS_SECONDARY);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isArbiter)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (bool) (sd->type == MONGOC_SERVER_RS_ARBITER);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isHidden)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
bson_iter_t iter;
return !!(bson_iter_init_find_case(&iter, &sd->last_is_master, "hidden") && bson_iter_as_bool(&iter));
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isPassive)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
bson_iter_t iter;
return !!(bson_iter_init_find_case(&iter, &sd->last_is_master, "passive") && bson_iter_as_bool(&iter));
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
Object HHVM_METHOD(MongoDBDriverServer, executeCommand, const String &db, const Object &command, const Variant &readPreference)
{
bson_t *bson;
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
auto zquery = command->o_get(String("command"), false, s_MongoDriverCommand_className);
VariantToBsonConverter converter(zquery, HIPPO_BSON_NO_FLAGS);
bson = bson_new();
converter.convert(bson);
return MongoDriver::Utils::doExecuteCommand(
db.c_str(),
data->m_client,
data->m_server_id,
bson,
readPreference
);
}
Object HHVM_METHOD(MongoDBDriverServer, executeQuery, const String &ns, const Object &query, const Variant &readPreference)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
return MongoDriver::Utils::doExecuteQuery(
ns,
data->m_client,
data->m_server_id,
query,
readPreference
);
}
Object HHVM_METHOD(MongoDBDriverServer, executeBulkWrite, const String &ns, const Object &bulk, const Variant &writeConcern)
{
const mongoc_write_concern_t *write_concern = NULL;
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
/* Deal with write concerns */
if (!writeConcern.isNull()) {
MongoDBDriverWriteConcernData* wc_data = Native::data<MongoDBDriverWriteConcernData>(writeConcern.toObject().get());
write_concern = wc_data->m_write_concern;
}
if (!write_concern) {
write_concern = mongoc_client_get_write_concern(data->m_client);
}
return MongoDriver::Utils::doExecuteBulkWrite(
ns,
data->m_client,
data->m_server_id,
bulk,
write_concern
);
}
}
<commit_msg>Extract adding of server information into its own function so we can reuse it<commit_after>/**
* Copyright 2014-2015 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/vm/native-data.h"
#include "../../../bson.h"
#include "../../../mongodb.h"
#include "../../../utils.h"
#include "Command.h"
#include "Server.h"
#include "WriteConcern.h"
namespace HPHP {
const StaticString s_MongoDriverServer_className("MongoDB\\Driver\\Server");
Class* MongoDBDriverServerData::s_class = nullptr;
const StaticString MongoDBDriverServerData::s_className("MongoDBDriverServer");
IMPLEMENT_GET_CLASS(MongoDBDriverServerData);
const StaticString
s_MongoDriverServer_host("host"),
s_MongoDriverServer_port("port"),
s_MongoDriverServer_type("type"),
s_MongoDriverServer_is_primary("is_primary"),
s_MongoDriverServer_is_secondary("is_secondary"),
s_MongoDriverServer_is_arbiter("is_arbiter"),
s_MongoDriverServer_hidden("hidden"),
s_MongoDriverServer_passive("passive"),
s_MongoDriverServer_is_hidden("is_hidden"),
s_MongoDriverServer_is_passive("is_passive"),
s_MongoDriverServer_tags("tags"),
s_MongoDriverServer_last_is_master("last_is_master"),
s_MongoDriverServer_round_trip_time("round_trip_time");
static bool mongodb_driver_add_server_debug(mongoc_server_description_t *sd, Array *retval)
{
Variant v_last_is_master;
Array a_last_is_master;
retval->set(s_MongoDriverServer_host, sd->host.host);
retval->set(s_MongoDriverServer_port, sd->host.port);
retval->set(s_MongoDriverServer_type, sd->type);
retval->set(s_MongoDriverServer_is_primary, !!(sd->type == MONGOC_SERVER_RS_PRIMARY));
retval->set(s_MongoDriverServer_is_secondary, !!(sd->type == MONGOC_SERVER_RS_SECONDARY));
retval->set(s_MongoDriverServer_is_arbiter, !!(sd->type == MONGOC_SERVER_RS_ARBITER));
hippo_bson_conversion_options_t options = HIPPO_TYPEMAP_DEBUG_INITIALIZER;
BsonToVariantConverter convertor(bson_get_data(&sd->last_is_master), sd->last_is_master.len, options);
convertor.convert(&v_last_is_master);
a_last_is_master = v_last_is_master.toArray();
retval->set(s_MongoDriverServer_is_hidden, a_last_is_master.exists(s_MongoDriverServer_hidden) && !!a_last_is_master[s_MongoDriverServer_hidden].toBoolean());
retval->set(s_MongoDriverServer_is_passive, a_last_is_master.exists(s_MongoDriverServer_passive) && !!a_last_is_master[s_MongoDriverServer_passive].toBoolean());
if (sd->tags.len) {
Variant v_tags;
hippo_bson_conversion_options_t options = HIPPO_TYPEMAP_DEBUG_INITIALIZER;
BsonToVariantConverter convertor(bson_get_data(&sd->tags), sd->tags.len, options);
convertor.convert(&v_tags);
retval->set(s_MongoDriverServer_tags, v_tags);
}
retval->set(s_MongoDriverServer_last_is_master, a_last_is_master);
retval->set(s_MongoDriverServer_round_trip_time, sd->round_trip_time);
return true;
}
Array HHVM_METHOD(MongoDBDriverServer, __debugInfo)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
Array retval = Array::Create();
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
mongodb_driver_add_server_debug(sd, &retval);
return retval;
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
String HHVM_METHOD(MongoDBDriverServer, getHost)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return String(sd->host.host);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
Array HHVM_METHOD(MongoDBDriverServer, getInfo)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
Variant v;
hippo_bson_conversion_options_t options = HIPPO_TYPEMAP_DEBUG_INITIALIZER;
BsonToVariantConverter convertor(bson_get_data(&sd->last_is_master), sd->last_is_master.len, options);
convertor.convert(&v);
return v.toArray();
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
int64_t HHVM_METHOD(MongoDBDriverServer, getLatency)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (int64_t) (sd->round_trip_time);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
int64_t HHVM_METHOD(MongoDBDriverServer, getPort)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (int64_t) (sd->host.port);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
Array HHVM_METHOD(MongoDBDriverServer, getTags)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
Variant v;
hippo_bson_conversion_options_t options = HIPPO_TYPEMAP_DEBUG_INITIALIZER;
BsonToVariantConverter convertor(bson_get_data(&sd->tags), sd->tags.len, options);
convertor.convert(&v);
return v.toArray();
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
int64_t HHVM_METHOD(MongoDBDriverServer, getType)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (int64_t) (sd->type);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isPrimary)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (bool) (sd->type == MONGOC_SERVER_RS_PRIMARY);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isSecondary)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (bool) (sd->type == MONGOC_SERVER_RS_SECONDARY);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isArbiter)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
return (bool) (sd->type == MONGOC_SERVER_RS_ARBITER);
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isHidden)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
bson_iter_t iter;
return !!(bson_iter_init_find_case(&iter, &sd->last_is_master, "hidden") && bson_iter_as_bool(&iter));
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
bool HHVM_METHOD(MongoDBDriverServer, isPassive)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
mongoc_server_description_t *sd;
if ((sd = mongoc_topology_description_server_by_id(&data->m_client->topology->description, data->m_server_id))) {
bson_iter_t iter;
return !!(bson_iter_init_find_case(&iter, &sd->last_is_master, "passive") && bson_iter_as_bool(&iter));
}
throw MongoDriver::Utils::CreateAndConstruct(MongoDriver::s_MongoDriverExceptionRuntimeException_className, HPHP::Variant("Failed to get server description, server likely gone"), HPHP::Variant((uint64_t) 0));
}
Object HHVM_METHOD(MongoDBDriverServer, executeCommand, const String &db, const Object &command, const Variant &readPreference)
{
bson_t *bson;
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
auto zquery = command->o_get(String("command"), false, s_MongoDriverCommand_className);
VariantToBsonConverter converter(zquery, HIPPO_BSON_NO_FLAGS);
bson = bson_new();
converter.convert(bson);
return MongoDriver::Utils::doExecuteCommand(
db.c_str(),
data->m_client,
data->m_server_id,
bson,
readPreference
);
}
Object HHVM_METHOD(MongoDBDriverServer, executeQuery, const String &ns, const Object &query, const Variant &readPreference)
{
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
return MongoDriver::Utils::doExecuteQuery(
ns,
data->m_client,
data->m_server_id,
query,
readPreference
);
}
Object HHVM_METHOD(MongoDBDriverServer, executeBulkWrite, const String &ns, const Object &bulk, const Variant &writeConcern)
{
const mongoc_write_concern_t *write_concern = NULL;
MongoDBDriverServerData* data = Native::data<MongoDBDriverServerData>(this_);
/* Deal with write concerns */
if (!writeConcern.isNull()) {
MongoDBDriverWriteConcernData* wc_data = Native::data<MongoDBDriverWriteConcernData>(writeConcern.toObject().get());
write_concern = wc_data->m_write_concern;
}
if (!write_concern) {
write_concern = mongoc_client_get_write_concern(data->m_client);
}
return MongoDriver::Utils::doExecuteBulkWrite(
ns,
data->m_client,
data->m_server_id,
bulk,
write_concern
);
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2018 Inria
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Daniel Carvalho
*/
#include "mem/cache/replacement_policies/random_rp.hh"
#include "base/random.hh"
#include "mem/cache/blk.hh"
RandomRP::RandomRP(const Params *p)
: BaseReplacementPolicy(p)
{
}
void
RandomRP::invalidate(const std::shared_ptr<ReplacementData>& replacement_data)
const
{
// Unprioritize replacement data victimization
std::static_pointer_cast<RandomReplData>(
replacement_data)->valid = false;
}
void
RandomRP::touch(const std::shared_ptr<ReplacementData>& replacement_data) const
{
}
void
RandomRP::reset(const std::shared_ptr<ReplacementData>& replacement_data) const
{
// Unprioritize replacement data victimization
std::static_pointer_cast<RandomReplData>(
replacement_data)->valid = true;
}
ReplaceableEntry*
RandomRP::getVictim(const ReplacementCandidates& candidates) const
{
// There must be at least one replacement candidate
assert(candidates.size() > 0);
// Choose one candidate at random
ReplaceableEntry* victim = candidates[random_mt.random<unsigned>(0,
candidates.size() - 1)];
// Visit all candidates to search for an invalid entry. If one is found,
// its eviction is prioritized
for (const auto& candidate : candidates) {
if (!std::static_pointer_cast<RandomReplData>(
candidate->replacementData)->valid) {
victim = candidate;
break;
}
}
return victim;
}
std::shared_ptr<ReplacementData>
RandomRP::instantiateEntry()
{
return std::shared_ptr<ReplacementData>(new ReplacementData());
}
RandomRP*
RandomRPParams::create()
{
return new RandomRP(this);
}
<commit_msg>mem-cache: Fix RandomReplData<commit_after>/**
* Copyright (c) 2018 Inria
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Daniel Carvalho
*/
#include "mem/cache/replacement_policies/random_rp.hh"
#include "base/random.hh"
#include "mem/cache/blk.hh"
RandomRP::RandomRP(const Params *p)
: BaseReplacementPolicy(p)
{
}
void
RandomRP::invalidate(const std::shared_ptr<ReplacementData>& replacement_data)
const
{
// Unprioritize replacement data victimization
std::static_pointer_cast<RandomReplData>(
replacement_data)->valid = false;
}
void
RandomRP::touch(const std::shared_ptr<ReplacementData>& replacement_data) const
{
}
void
RandomRP::reset(const std::shared_ptr<ReplacementData>& replacement_data) const
{
// Unprioritize replacement data victimization
std::static_pointer_cast<RandomReplData>(
replacement_data)->valid = true;
}
ReplaceableEntry*
RandomRP::getVictim(const ReplacementCandidates& candidates) const
{
// There must be at least one replacement candidate
assert(candidates.size() > 0);
// Choose one candidate at random
ReplaceableEntry* victim = candidates[random_mt.random<unsigned>(0,
candidates.size() - 1)];
// Visit all candidates to search for an invalid entry. If one is found,
// its eviction is prioritized
for (const auto& candidate : candidates) {
if (!std::static_pointer_cast<RandomReplData>(
candidate->replacementData)->valid) {
victim = candidate;
break;
}
}
return victim;
}
std::shared_ptr<ReplacementData>
RandomRP::instantiateEntry()
{
return std::shared_ptr<ReplacementData>(new RandomReplData());
}
RandomRP*
RandomRPParams::create()
{
return new RandomRP(this);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/socket.hpp"
#include <boost/bind.hpp>
#include <boost/mpl/max_element.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/sizeof.hpp>
#include <boost/mpl/transform_view.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/lexical_cast.hpp>
#include <libtorrent/io.hpp>
#include <libtorrent/invariant_check.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/find_data.hpp>
#include <libtorrent/kademlia/closest_nodes.hpp>
#include <libtorrent/kademlia/refresh.hpp>
#include <libtorrent/kademlia/node.hpp>
#include <libtorrent/kademlia/observer.hpp>
#include <libtorrent/hasher.hpp>
#include <fstream>
using boost::shared_ptr;
using boost::bind;
namespace libtorrent { namespace dht
{
namespace io = libtorrent::detail;
namespace mpl = boost::mpl;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DEFINE_LOG(rpc)
#endif
void intrusive_ptr_add_ref(observer const* o)
{
TORRENT_ASSERT(o->m_refs >= 0);
TORRENT_ASSERT(o != 0);
++o->m_refs;
}
void intrusive_ptr_release(observer const* o)
{
TORRENT_ASSERT(o->m_refs > 0);
TORRENT_ASSERT(o != 0);
if (--o->m_refs == 0)
{
boost::pool<>& p = o->pool_allocator;
o->~observer();
p.free(const_cast<observer*>(o));
}
}
node_id generate_id();
typedef mpl::vector<
closest_nodes_observer
, find_data_observer
, announce_observer
, get_peers_observer
, refresh_observer
, ping_observer
, null_observer
> observer_types;
typedef mpl::max_element<
mpl::transform_view<observer_types, mpl::sizeof_<mpl::_1> >
>::type max_observer_type_iter;
rpc_manager::rpc_manager(fun const& f, node_id const& our_id
, routing_table& table, send_fun const& sf)
: m_pool_allocator(sizeof(mpl::deref<max_observer_type_iter::base>::type))
, m_next_transaction_id(rand() % max_transactions)
, m_oldest_transaction_id(m_next_transaction_id)
, m_incoming(f)
, m_send(sf)
, m_our_id(our_id)
, m_table(table)
, m_timer(time_now())
, m_random_number(generate_id())
, m_destructing(false)
{
std::srand(time(0));
}
rpc_manager::~rpc_manager()
{
m_destructing = true;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Destructing";
#endif
std::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()
, bind(&observer::abort, _1));
for (transactions_t::iterator i = m_transactions.begin()
, end(m_transactions.end()); i != end; ++i)
{
if (*i) (*i)->abort();
}
}
#ifndef NDEBUG
void rpc_manager::check_invariant() const
{
TORRENT_ASSERT(m_oldest_transaction_id >= 0);
TORRENT_ASSERT(m_oldest_transaction_id < max_transactions);
TORRENT_ASSERT(m_next_transaction_id >= 0);
TORRENT_ASSERT(m_next_transaction_id < max_transactions);
TORRENT_ASSERT(!m_transactions[m_next_transaction_id]);
for (int i = (m_next_transaction_id + 1) % max_transactions;
i != m_oldest_transaction_id; i = (i + 1) % max_transactions)
{
TORRENT_ASSERT(!m_transactions[i]);
}
}
#endif
bool rpc_manager::incoming(msg const& m)
{
INVARIANT_CHECK;
if (m_destructing) return false;
if (m.reply)
{
// if we don't have the transaction id in our
// request list, ignore the packet
if (m.transaction_id.size() < 2)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with invalid transaction id size: "
<< m.transaction_id.size() << " from " << m.addr;
#endif
msg reply;
reply.reply = true;
reply.message_id = messages::error;
reply.error_code = 203; // Protocol error
reply.error_msg = "reply with invalid transaction id, size "
+ boost::lexical_cast<std::string>(m.transaction_id.size());
reply.addr = m.addr;
reply.transaction_id = "";
m_send(reply);
return false;
}
std::string::const_iterator i = m.transaction_id.begin();
int tid = io::read_uint16(i);
if (tid >= (int)m_transactions.size()
|| tid < 0)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with invalid transaction id: "
<< tid << " from " << m.addr;
#endif
msg reply;
reply.reply = true;
reply.message_id = messages::error;
reply.error_code = 203; // Protocol error
reply.error_msg = "reply with invalid transaction id";
reply.addr = m.addr;
reply.transaction_id = "";
m_send(reply);
return false;
}
observer_ptr o = m_transactions[tid];
if (!o)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with unknown transaction id: "
<< tid << " from " << m.addr << " (possibly timed out)";
#endif
return false;
}
if (m.addr != o->target_addr)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with incorrect address and valid transaction id: "
<< tid << " from " << m.addr;
#endif
return false;
}
#ifdef TORRENT_DHT_VERBOSE_LOGGING
std::ofstream reply_stats("libtorrent_logs/round_trip_ms.log", std::ios::app);
reply_stats << m.addr << "\t" << total_milliseconds(time_now() - o->sent)
<< std::endl;
#endif
o->reply(m);
m_transactions[tid] = 0;
if (m.piggy_backed_ping)
{
// there is a ping request piggy
// backed in this reply
msg ph;
ph.message_id = messages::ping;
ph.transaction_id = m.ping_transaction_id;
ph.addr = m.addr;
ph.reply = true;
reply(ph);
}
return m_table.node_seen(m.id, m.addr);
}
else
{
TORRENT_ASSERT(m.message_id != messages::error);
// this is an incoming request
m_incoming(m);
}
return false;
}
time_duration rpc_manager::tick()
{
INVARIANT_CHECK;
const int timeout_ms = 10 * 1000;
// look for observers that has timed out
if (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);
std::vector<observer_ptr > timeouts;
for (;m_next_transaction_id != m_oldest_transaction_id;
m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)
{
TORRENT_ASSERT(m_oldest_transaction_id >= 0);
TORRENT_ASSERT(m_oldest_transaction_id < max_transactions);
observer_ptr o = m_transactions[m_oldest_transaction_id];
if (!o) continue;
time_duration diff = o->sent + milliseconds(timeout_ms) - time_now();
if (diff > seconds(0))
{
if (diff < seconds(1)) return seconds(1);
return diff;
}
try
{
m_transactions[m_oldest_transaction_id] = 0;
timeouts.push_back(o);
} catch (std::exception) {}
}
std::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));
timeouts.clear();
// clear the aborted transactions, will likely
// generate new requests. We need to swap, since the
// destrutors may add more observers to the m_aborted_transactions
std::vector<observer_ptr >().swap(m_aborted_transactions);
return milliseconds(timeout_ms);
}
unsigned int rpc_manager::new_transaction_id(observer_ptr o)
{
INVARIANT_CHECK;
unsigned int tid = m_next_transaction_id;
m_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;
if (m_transactions[m_next_transaction_id])
{
// moving the observer into the set of aborted transactions
// it will prevent it from spawning new requests right now,
// since that would break the invariant
m_aborted_transactions.push_back(m_transactions[m_next_transaction_id]);
m_transactions[m_next_transaction_id] = 0;
TORRENT_ASSERT(m_oldest_transaction_id == m_next_transaction_id);
}
TORRENT_ASSERT(!m_transactions[tid]);
m_transactions[tid] = o;
if (m_oldest_transaction_id == m_next_transaction_id)
{
m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "WARNING: transaction limit reached! Too many concurrent"
" messages! limit: " << (int)max_transactions;
#endif
update_oldest_transaction_id();
}
return tid;
}
void rpc_manager::update_oldest_transaction_id()
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_oldest_transaction_id != m_next_transaction_id);
while (!m_transactions[m_oldest_transaction_id])
{
m_oldest_transaction_id = (m_oldest_transaction_id + 1)
% max_transactions;
if (m_oldest_transaction_id == m_next_transaction_id)
break;
}
}
void rpc_manager::invoke(int message_id, udp::endpoint target_addr
, observer_ptr o)
{
INVARIANT_CHECK;
if (m_destructing)
{
o->abort();
return;
}
msg m;
m.message_id = message_id;
m.reply = false;
m.id = m_our_id;
m.addr = target_addr;
TORRENT_ASSERT(!m_transactions[m_next_transaction_id]);
#ifndef NDEBUG
int potential_new_id = m_next_transaction_id;
#endif
try
{
m.transaction_id.clear();
std::back_insert_iterator<std::string> out(m.transaction_id);
io::write_uint16(m_next_transaction_id, out);
o->send(m);
o->sent = time_now();
o->target_addr = target_addr;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Invoking " << messages::ids[message_id]
<< " -> " << target_addr;
#endif
m_send(m);
new_transaction_id(o);
}
catch (std::exception& e)
{
// m_send may fail with "no route to host"
TORRENT_ASSERT(potential_new_id == m_next_transaction_id);
o->abort();
}
}
void rpc_manager::reply(msg& m)
{
INVARIANT_CHECK;
if (m_destructing) return;
TORRENT_ASSERT(m.reply);
m.piggy_backed_ping = false;
m.id = m_our_id;
m_send(m);
}
void rpc_manager::reply_with_ping(msg& m)
{
INVARIANT_CHECK;
if (m_destructing) return;
TORRENT_ASSERT(m.reply);
m.piggy_backed_ping = true;
m.id = m_our_id;
m.ping_transaction_id.clear();
std::back_insert_iterator<std::string> out(m.ping_transaction_id);
io::write_uint16(m_next_transaction_id, out);
observer_ptr o(new (allocator().malloc()) null_observer(allocator()));
TORRENT_ASSERT(!m_transactions[m_next_transaction_id]);
o->sent = time_now();
o->target_addr = m.addr;
m_send(m);
new_transaction_id(o);
}
} } // namespace libtorrent::dht
<commit_msg>updated dht verbose logging to try to catch #176<commit_after>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/socket.hpp"
#include <boost/bind.hpp>
#include <boost/mpl/max_element.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/sizeof.hpp>
#include <boost/mpl/transform_view.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/lexical_cast.hpp>
#include <libtorrent/io.hpp>
#include <libtorrent/invariant_check.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/find_data.hpp>
#include <libtorrent/kademlia/closest_nodes.hpp>
#include <libtorrent/kademlia/refresh.hpp>
#include <libtorrent/kademlia/node.hpp>
#include <libtorrent/kademlia/observer.hpp>
#include <libtorrent/hasher.hpp>
#include <fstream>
using boost::shared_ptr;
using boost::bind;
namespace libtorrent { namespace dht
{
namespace io = libtorrent::detail;
namespace mpl = boost::mpl;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DEFINE_LOG(rpc)
#endif
void intrusive_ptr_add_ref(observer const* o)
{
TORRENT_ASSERT(o->m_refs >= 0);
TORRENT_ASSERT(o != 0);
++o->m_refs;
}
void intrusive_ptr_release(observer const* o)
{
TORRENT_ASSERT(o->m_refs > 0);
TORRENT_ASSERT(o != 0);
if (--o->m_refs == 0)
{
boost::pool<>& p = o->pool_allocator;
o->~observer();
p.free(const_cast<observer*>(o));
}
}
node_id generate_id();
typedef mpl::vector<
closest_nodes_observer
, find_data_observer
, announce_observer
, get_peers_observer
, refresh_observer
, ping_observer
, null_observer
> observer_types;
typedef mpl::max_element<
mpl::transform_view<observer_types, mpl::sizeof_<mpl::_1> >
>::type max_observer_type_iter;
rpc_manager::rpc_manager(fun const& f, node_id const& our_id
, routing_table& table, send_fun const& sf)
: m_pool_allocator(sizeof(mpl::deref<max_observer_type_iter::base>::type))
, m_next_transaction_id(rand() % max_transactions)
, m_oldest_transaction_id(m_next_transaction_id)
, m_incoming(f)
, m_send(sf)
, m_our_id(our_id)
, m_table(table)
, m_timer(time_now())
, m_random_number(generate_id())
, m_destructing(false)
{
std::srand(time(0));
}
rpc_manager::~rpc_manager()
{
m_destructing = true;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Destructing";
#endif
std::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()
, bind(&observer::abort, _1));
for (transactions_t::iterator i = m_transactions.begin()
, end(m_transactions.end()); i != end; ++i)
{
if (*i) (*i)->abort();
}
}
#ifndef NDEBUG
void rpc_manager::check_invariant() const
{
TORRENT_ASSERT(m_oldest_transaction_id >= 0);
TORRENT_ASSERT(m_oldest_transaction_id < max_transactions);
TORRENT_ASSERT(m_next_transaction_id >= 0);
TORRENT_ASSERT(m_next_transaction_id < max_transactions);
TORRENT_ASSERT(!m_transactions[m_next_transaction_id]);
for (int i = (m_next_transaction_id + 1) % max_transactions;
i != m_oldest_transaction_id; i = (i + 1) % max_transactions)
{
TORRENT_ASSERT(!m_transactions[i]);
}
}
#endif
bool rpc_manager::incoming(msg const& m)
{
INVARIANT_CHECK;
if (m_destructing) return false;
if (m.reply)
{
// if we don't have the transaction id in our
// request list, ignore the packet
if (m.transaction_id.size() < 2)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with invalid transaction id size: "
<< m.transaction_id.size() << " from " << m.addr;
#endif
msg reply;
reply.reply = true;
reply.message_id = messages::error;
reply.error_code = 203; // Protocol error
reply.error_msg = "reply with invalid transaction id, size "
+ boost::lexical_cast<std::string>(m.transaction_id.size());
reply.addr = m.addr;
reply.transaction_id = "";
m_send(reply);
return false;
}
std::string::const_iterator i = m.transaction_id.begin();
int tid = io::read_uint16(i);
if (tid >= (int)m_transactions.size()
|| tid < 0)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with invalid transaction id: "
<< tid << " from " << m.addr;
#endif
msg reply;
reply.reply = true;
reply.message_id = messages::error;
reply.error_code = 203; // Protocol error
reply.error_msg = "reply with invalid transaction id";
reply.addr = m.addr;
reply.transaction_id = "";
m_send(reply);
return false;
}
observer_ptr o = m_transactions[tid];
if (!o)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with unknown transaction id: "
<< tid << " from " << m.addr << " (possibly timed out)";
#endif
return false;
}
if (m.addr != o->target_addr)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with incorrect address and valid transaction id: "
<< tid << " from " << m.addr;
#endif
return false;
}
#ifdef TORRENT_DHT_VERBOSE_LOGGING
std::ofstream reply_stats("libtorrent_logs/round_trip_ms.log", std::ios::app);
reply_stats << m.addr << "\t" << total_milliseconds(time_now() - o->sent)
<< std::endl;
#endif
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Reply with transaction id: "
<< tid << " from " << m.addr;
#endif
o->reply(m);
m_transactions[tid] = 0;
if (m.piggy_backed_ping)
{
// there is a ping request piggy
// backed in this reply
msg ph;
ph.message_id = messages::ping;
ph.transaction_id = m.ping_transaction_id;
ph.addr = m.addr;
ph.reply = true;
reply(ph);
}
return m_table.node_seen(m.id, m.addr);
}
else
{
TORRENT_ASSERT(m.message_id != messages::error);
// this is an incoming request
m_incoming(m);
}
return false;
}
time_duration rpc_manager::tick()
{
INVARIANT_CHECK;
const int timeout_ms = 10 * 1000;
// look for observers that has timed out
if (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);
std::vector<observer_ptr > timeouts;
for (;m_next_transaction_id != m_oldest_transaction_id;
m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)
{
TORRENT_ASSERT(m_oldest_transaction_id >= 0);
TORRENT_ASSERT(m_oldest_transaction_id < max_transactions);
observer_ptr o = m_transactions[m_oldest_transaction_id];
if (!o) continue;
time_duration diff = o->sent + milliseconds(timeout_ms) - time_now();
if (diff > seconds(0))
{
if (diff < seconds(1)) return seconds(1);
return diff;
}
try
{
m_transactions[m_oldest_transaction_id] = 0;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Timing out transaction id: "
<< m_oldest_transaction_id << " from " << o->target_addr;
#endif
timeouts.push_back(o);
} catch (std::exception) {}
}
std::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));
timeouts.clear();
// clear the aborted transactions, will likely
// generate new requests. We need to swap, since the
// destrutors may add more observers to the m_aborted_transactions
std::vector<observer_ptr >().swap(m_aborted_transactions);
return milliseconds(timeout_ms);
}
unsigned int rpc_manager::new_transaction_id(observer_ptr o)
{
INVARIANT_CHECK;
unsigned int tid = m_next_transaction_id;
m_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;
if (m_transactions[m_next_transaction_id])
{
// moving the observer into the set of aborted transactions
// it will prevent it from spawning new requests right now,
// since that would break the invariant
observer_ptr o = m_transactions[m_next_transaction_id];
m_aborted_transactions.push_back(o);
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "[new_transaction_id] Aborting message with transaction id: "
<< m_next_transaction_id << " sent to " << o->target_addr
<< " at " << o->sent;
#endif
m_transactions[m_next_transaction_id] = 0;
TORRENT_ASSERT(m_oldest_transaction_id == m_next_transaction_id);
}
TORRENT_ASSERT(!m_transactions[tid]);
m_transactions[tid] = o;
if (m_oldest_transaction_id == m_next_transaction_id)
{
m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "WARNING: transaction limit reached! Too many concurrent"
" messages! limit: " << (int)max_transactions;
#endif
update_oldest_transaction_id();
}
return tid;
}
void rpc_manager::update_oldest_transaction_id()
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_oldest_transaction_id != m_next_transaction_id);
while (!m_transactions[m_oldest_transaction_id])
{
m_oldest_transaction_id = (m_oldest_transaction_id + 1)
% max_transactions;
if (m_oldest_transaction_id == m_next_transaction_id)
break;
}
}
void rpc_manager::invoke(int message_id, udp::endpoint target_addr
, observer_ptr o)
{
INVARIANT_CHECK;
if (m_destructing)
{
o->abort();
return;
}
msg m;
m.message_id = message_id;
m.reply = false;
m.id = m_our_id;
m.addr = target_addr;
TORRENT_ASSERT(!m_transactions[m_next_transaction_id]);
#ifndef NDEBUG
int potential_new_id = m_next_transaction_id;
#endif
try
{
m.transaction_id.clear();
std::back_insert_iterator<std::string> out(m.transaction_id);
io::write_uint16(m_next_transaction_id, out);
o->send(m);
o->sent = time_now();
o->target_addr = target_addr;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(rpc) << "Invoking " << messages::ids[message_id]
<< " -> " << target_addr;
#endif
m_send(m);
new_transaction_id(o);
}
catch (std::exception& e)
{
// m_send may fail with "no route to host"
TORRENT_ASSERT(potential_new_id == m_next_transaction_id);
o->abort();
}
}
void rpc_manager::reply(msg& m)
{
INVARIANT_CHECK;
if (m_destructing) return;
TORRENT_ASSERT(m.reply);
m.piggy_backed_ping = false;
m.id = m_our_id;
m_send(m);
}
void rpc_manager::reply_with_ping(msg& m)
{
INVARIANT_CHECK;
if (m_destructing) return;
TORRENT_ASSERT(m.reply);
m.piggy_backed_ping = true;
m.id = m_our_id;
m.ping_transaction_id.clear();
std::back_insert_iterator<std::string> out(m.ping_transaction_id);
io::write_uint16(m_next_transaction_id, out);
observer_ptr o(new (allocator().malloc()) null_observer(allocator()));
TORRENT_ASSERT(!m_transactions[m_next_transaction_id]);
o->sent = time_now();
o->target_addr = m.addr;
m_send(m);
new_transaction_id(o);
}
} } // namespace libtorrent::dht
<|endoftext|> |
<commit_before>#include "utils/zmq.h"
#include <array>
void z_send(zmq::socket_t& socket, const std::string& str, int flags) {
zmq::message_t msg(str.size());
std::memcpy(msg.data(), str.c_str(), str.size());
socket.send(msg, flags);
}
void z_send(zmq::socket_t& socket, zmq::message_t& msg, int flags) {
socket.send(msg, flags);
}
std::string z_recv(zmq::socket_t& socket) {
zmq::message_t msg;
socket.recv(&msg);
return std::string(static_cast<char*>(msg.data()), msg.size());
}
LoadBalancer::LoadBalancer(zmq::context_t& context) : clients(context, ZMQ_ROUTER), workers(context, ZMQ_ROUTER) {}
void LoadBalancer::bind(const std::string& clients_socket_path, const std::string& workers_socket_path) {
clients.bind(clients_socket_path.c_str());
workers.bind(workers_socket_path.c_str());
}
void LoadBalancer::run() {
while (true) {
zmq_pollitem_t items[] = {{static_cast<void*>(workers), 0, ZMQ_POLLIN, 0},
{static_cast<void*>(clients), 0, ZMQ_POLLIN, 0}};
if (avalailable_worker.empty()) {
// we don't look for request from client if there is no worker for handling them
zmq::poll(items, 1, -1);
} else {
zmq::poll(items, 2, -1);
}
// handle worker
if (items[0].revents & ZMQ_POLLIN) {
// the first frame is the identifier of the worker: we add it to the available worker
avalailable_worker.push(z_recv(workers));
{
// Second frame is empty
std::string empty = z_recv(workers);
assert(empty.size() == 0);
}
// Third frame is READY or else a client reply address
std::string client_addr = z_recv(workers);
// If client reply, send resp back to the appropriate client
if (client_addr != "READY") {
{
// another empty frame
std::string empty = z_recv(workers);
assert(empty.size() == 0);
}
// the actual reply
zmq::message_t reply;
workers.recv(&reply);
z_send(clients, client_addr, ZMQ_SNDMORE);
z_send(clients, "", ZMQ_SNDMORE);
z_send(clients, reply);
}
}
// handle clients request
if (items[1].revents & ZMQ_POLLIN){
// The client request is a multi-part ZMQ message, we have to check every frame and be sure the multi-part message frame
// is composed as we wish, otherwise the multi-part message may be shifted unexpectedly.
// The multi-part ZMQ message should have 3 parts
// The first one is the ID of message
// The second one is an empty frame
// The third one is the real request
size_t more = 0;
size_t more_size = sizeof (more);
size_t nb_frames = 0;
// there is no copy/move constructor in message_t in v2.2, which is the verison used by Jenkins...
std::array<zmq::message_t, 3> frames{};
do {
zmq::message_t frame{};
clients.recv(&frame);
if (nb_frames < 3) {
frames[nb_frames].move(&frame);
}
// Are there more frames coming?
clients.getsockopt(ZMQ_RCVMORE, &more, &more_size);
nb_frames++;
} while (more);
if (nb_frames > 3 || frames[1].size() != 0 ) {
z_send(clients, "");
continue;
}
std::string worker_addr = avalailable_worker.top();
avalailable_worker.pop();
z_send(workers, worker_addr, ZMQ_SNDMORE);
z_send(workers, "", ZMQ_SNDMORE);
// frames[0] is the id of message
z_send(workers, frames[0], ZMQ_SNDMORE);
z_send(workers, "", ZMQ_SNDMORE);
// frames[2] is the request
z_send(workers, frames[2]);
}
}
}
<commit_msg>use at<commit_after>#include "utils/zmq.h"
#include <array>
void z_send(zmq::socket_t& socket, const std::string& str, int flags) {
zmq::message_t msg(str.size());
std::memcpy(msg.data(), str.c_str(), str.size());
socket.send(msg, flags);
}
void z_send(zmq::socket_t& socket, zmq::message_t& msg, int flags) {
socket.send(msg, flags);
}
std::string z_recv(zmq::socket_t& socket) {
zmq::message_t msg;
socket.recv(&msg);
return std::string(static_cast<char*>(msg.data()), msg.size());
}
LoadBalancer::LoadBalancer(zmq::context_t& context) : clients(context, ZMQ_ROUTER), workers(context, ZMQ_ROUTER) {}
void LoadBalancer::bind(const std::string& clients_socket_path, const std::string& workers_socket_path) {
clients.bind(clients_socket_path.c_str());
workers.bind(workers_socket_path.c_str());
}
void LoadBalancer::run() {
while (true) {
zmq_pollitem_t items[] = {{static_cast<void*>(workers), 0, ZMQ_POLLIN, 0},
{static_cast<void*>(clients), 0, ZMQ_POLLIN, 0}};
if (avalailable_worker.empty()) {
// we don't look for request from client if there is no worker for handling them
zmq::poll(items, 1, -1);
} else {
zmq::poll(items, 2, -1);
}
// handle worker
if (items[0].revents & ZMQ_POLLIN) {
// the first frame is the identifier of the worker: we add it to the available worker
avalailable_worker.push(z_recv(workers));
{
// Second frame is empty
std::string empty = z_recv(workers);
assert(empty.size() == 0);
}
// Third frame is READY or else a client reply address
std::string client_addr = z_recv(workers);
// If client reply, send resp back to the appropriate client
if (client_addr != "READY") {
{
// another empty frame
std::string empty = z_recv(workers);
assert(empty.size() == 0);
}
// the actual reply
zmq::message_t reply;
workers.recv(&reply);
z_send(clients, client_addr, ZMQ_SNDMORE);
z_send(clients, "", ZMQ_SNDMORE);
z_send(clients, reply);
}
}
// handle clients request
if (items[1].revents & ZMQ_POLLIN){
// The client request is a multi-part ZMQ message, we have to check every frame and be sure the multi-part message frame
// is composed as we wish, otherwise the multi-part message may be shifted unexpectedly.
// The multi-part ZMQ message should have 3 parts
// The first one is the ID of message
// The second one is an empty frame
// The third one is the real request
size_t more = 0;
size_t more_size = sizeof (more);
size_t nb_frames = 0;
// there is no copy/move constructor in message_t in v2.2, which is the verison used by Jenkins...
std::array<zmq::message_t, 3> frames{};
do {
zmq::message_t frame{};
clients.recv(&frame);
if (nb_frames < 3) {
frames[nb_frames].move(&frame);
}
// Are there more frames coming?
clients.getsockopt(ZMQ_RCVMORE, &more, &more_size);
nb_frames++;
} while (more);
if (nb_frames > 3 || frames.at(1).size() != 0 ) {
z_send(clients, "");
continue;
}
std::string worker_addr = avalailable_worker.top();
avalailable_worker.pop();
z_send(workers, worker_addr, ZMQ_SNDMORE);
z_send(workers, "", ZMQ_SNDMORE);
// frames[0] is the id of message
z_send(workers, frames[0], ZMQ_SNDMORE);
z_send(workers, "", ZMQ_SNDMORE);
// frames[2] is the request
z_send(workers, frames[2]);
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <imgui.h>
#define IMGUI_DEFINE_MATH_OPERATORS
#include <imgui_internal.h>
#include <cmath>
#include <vector>
#include <Video/ParticleSystemRenderer.hpp>
struct MyCurve {
std::string curve_name;
float maxTime = 1.0f;
ImVec2 value[10];
ImGuiID id;
int item = 0;
float value_you_care_about = 0.0f;
// Variables for controlling particle.
bool editVelocityX = false;
bool editVelocityY = false;
bool editVelocityZ = false;
};
class CurveEditor {
public:
CurveEditor();
~CurveEditor();
/// Show the editor.
void Show();
/// If editor is visible.
bool IsVisible() const;
/// Set visibility.
/**
* @param visible setting visibility on editor.
*/
void SetVisible(bool visible);
/// Adds a curve.
/**
* @param curve_name name of curve.
* @param uniqueId unique ID.
* @param item unique ID just set it to 0.
*/
void AddMyCurve(std::string& curve_name, ImGuiID uniqueId, int item);
/// Updates all curves.
/**
* @param deltaTime deltatime.
* @param totalTime total time for the curves.
*/
void UpdateCurves(float deltaTime, float totalTime);
/// Render the curve editor.
void RenderCurveEditor();
/// Get all curves.
/**
* @return All curves.
*/
const std::vector<MyCurve>& GetAllCurves() const;
private:
bool visible = false;
ImGuiID addedCurve = 0;
std::string curvename = "Default";
char curveBuf[10];
std::string editor_name;
std::vector<MyCurve> curves;
float time = 0.0f;
Video::ParticleSystemRenderer::EmitterSettings emitterSettings;
bool goBack = false;
bool play = false;
};<commit_msg>Add newline at end of file.<commit_after>#pragma once
#include <imgui.h>
#define IMGUI_DEFINE_MATH_OPERATORS
#include <imgui_internal.h>
#include <cmath>
#include <vector>
#include <Video/ParticleSystemRenderer.hpp>
struct MyCurve {
std::string curve_name;
float maxTime = 1.0f;
ImVec2 value[10];
ImGuiID id;
int item = 0;
float value_you_care_about = 0.0f;
// Variables for controlling particle.
bool editVelocityX = false;
bool editVelocityY = false;
bool editVelocityZ = false;
};
class CurveEditor {
public:
CurveEditor();
~CurveEditor();
/// Show the editor.
void Show();
/// If editor is visible.
bool IsVisible() const;
/// Set visibility.
/**
* @param visible setting visibility on editor.
*/
void SetVisible(bool visible);
/// Adds a curve.
/**
* @param curve_name name of curve.
* @param uniqueId unique ID.
* @param item unique ID just set it to 0.
*/
void AddMyCurve(std::string& curve_name, ImGuiID uniqueId, int item);
/// Updates all curves.
/**
* @param deltaTime deltatime.
* @param totalTime total time for the curves.
*/
void UpdateCurves(float deltaTime, float totalTime);
/// Render the curve editor.
void RenderCurveEditor();
/// Get all curves.
/**
* @return All curves.
*/
const std::vector<MyCurve>& GetAllCurves() const;
private:
bool visible = false;
ImGuiID addedCurve = 0;
std::string curvename = "Default";
char curveBuf[10];
std::string editor_name;
std::vector<MyCurve> curves;
float time = 0.0f;
Video::ParticleSystemRenderer::EmitterSettings emitterSettings;
bool goBack = false;
bool play = false;
};
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "qmljsscriptconsole.h"
#include "interactiveinterpreter.h"
#include "qmladapter.h"
#include "debuggerstringutils.h"
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/coreconstants.h>
#include <utils/statuslabel.h>
#include <QtGui/QMenu>
#include <QtGui/QTextBlock>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QToolButton>
namespace Debugger {
namespace Internal {
class QmlJSScriptConsolePrivate
{
public:
QmlJSScriptConsolePrivate()
: prompt(QLatin1String("> ")),
startOfEditableArea(-1),
lastKnownPosition(0),
inferiorStopped(false)
{
resetCache();
}
void resetCache();
void appendToHistory(const QString &script);
bool canEvaluateScript(const QString &script);
QWeakPointer<QmlAdapter> adapter;
QString prompt;
int startOfEditableArea;
int lastKnownPosition;
QStringList scriptHistory;
int scriptHistoryIndex;
InteractiveInterpreter interpreter;
bool inferiorStopped;
QList<QTextEdit::ExtraSelection> selections;
};
void QmlJSScriptConsolePrivate::resetCache()
{
scriptHistory.clear();
scriptHistory.append(QLatin1String(""));
scriptHistoryIndex = scriptHistory.count();
selections.clear();
}
void QmlJSScriptConsolePrivate::appendToHistory(const QString &script)
{
scriptHistoryIndex = scriptHistory.count();
scriptHistory.replace(scriptHistoryIndex - 1,script);
scriptHistory.append(QLatin1String(""));
scriptHistoryIndex = scriptHistory.count();
}
bool QmlJSScriptConsolePrivate::canEvaluateScript(const QString &script)
{
interpreter.clearText();
interpreter.appendText(script);
return interpreter.canEvaluate();
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsoleWidget
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsoleWidget::QmlJSScriptConsoleWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
vbox->setSpacing(0);
QWidget *statusbarContainer = new QWidget;
QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer);
hbox->setMargin(0);
hbox->setSpacing(0);
//Clear Button
QToolButton *clearButton = new QToolButton;
QAction *clearAction = new QAction(tr("Clear Console"), this);
clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE)));
clearButton->setDefaultAction(clearAction);
//Status Label
m_statusLabel = new Utils::StatusLabel;
hbox->addWidget(m_statusLabel, 20, Qt::AlignLeft);
hbox->addWidget(clearButton, 0, Qt::AlignRight);
m_console = new QmlJSScriptConsole;
connect(m_console, SIGNAL(evaluateExpression(QString)), this,
SIGNAL(evaluateExpression(QString)));
connect(m_console, SIGNAL(updateStatusMessage(const QString &, int)), m_statusLabel,
SLOT(showStatusMessage(const QString &, int)));
connect(clearAction, SIGNAL(triggered()), m_console, SLOT(clear()));
vbox->addWidget(statusbarContainer);
vbox->addWidget(m_console);
}
void QmlJSScriptConsoleWidget::setQmlAdapter(QmlAdapter *adapter)
{
m_console->setQmlAdapter(adapter);
}
void QmlJSScriptConsoleWidget::setInferiorStopped(bool inferiorStopped)
{
m_console->setInferiorStopped(inferiorStopped);
}
void QmlJSScriptConsoleWidget::appendResult(const QString &result)
{
m_console->appendResult(result);
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsole
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsole::QmlJSScriptConsole(QWidget *parent)
: QPlainTextEdit(parent),
d(new QmlJSScriptConsolePrivate())
{
connect(this, SIGNAL(cursorPositionChanged()), SLOT(onCursorPositionChanged()));
setFrameStyle(QFrame::NoFrame);
setUndoRedoEnabled(false);
setBackgroundVisible(false);
const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::instance()->fontSettings();
setFont(fs.font());
displayPrompt();
}
QmlJSScriptConsole::~QmlJSScriptConsole()
{
delete d;
}
void QmlJSScriptConsole::setPrompt(const QString &prompt)
{
d->prompt = prompt;
}
QString QmlJSScriptConsole::prompt() const
{
return d->prompt;
}
void QmlJSScriptConsole::setInferiorStopped(bool inferiorStopped)
{
d->inferiorStopped = inferiorStopped;
onSelectionChanged();
}
void QmlJSScriptConsole::setQmlAdapter(QmlAdapter *adapter)
{
d->adapter = adapter;
clear();
}
void QmlJSScriptConsole::appendResult(const QString &result)
{
QString currentScript = getCurrentScript();
d->appendToHistory(currentScript);
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(QLatin1String("\n"));
cur.insertText(result);
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(QLatin1String("\n"));
setTextCursor(cur);
displayPrompt();
QTextEdit::ExtraSelection sel;
QTextCharFormat resultFormat;
resultFormat.setForeground(QBrush(QColor(Qt::darkGray)));
QTextCursor c(document()->findBlockByNumber(cur.blockNumber()-1));
c.movePosition(QTextCursor::StartOfBlock);
c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
sel.format = resultFormat;
sel.cursor = c;
d->selections.append(sel);
setExtraSelections(d->selections);
}
void QmlJSScriptConsole::clear()
{
d->resetCache();
QPlainTextEdit::clear();
displayPrompt();
}
void QmlJSScriptConsole::onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State state)
{
QDeclarativeDebugExpressionQuery *query = qobject_cast<QDeclarativeDebugExpressionQuery *>(sender());
bool gotResult = false;
if (query && state != QDeclarativeDebugQuery::Error) {
QString result(query->result().toString());
if (result != QLatin1String("<undefined>")) {
appendResult(result);
gotResult = true;
}
}
if (!gotResult) {
QString currentScript = getCurrentScript();
if (d->canEvaluateScript(currentScript)) {
emit evaluateExpression(currentScript);
} else {
QPlainTextEdit::appendPlainText(QLatin1String(""));
moveCursor(QTextCursor::EndOfLine);
}
}
delete query;
}
void QmlJSScriptConsole::onSelectionChanged()
{
if (!d->adapter.isNull()) {
QString status;
if (!d->inferiorStopped) {
status.append(tr("Current Selected Object: "));
status.append(d->adapter.data()->currentSelectedDisplayName());
}
emit updateStatusMessage(status, 0);
}
}
void QmlJSScriptConsole::keyPressEvent(QKeyEvent *e)
{
bool keyConsumed = false;
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
if (isEditableArea()) {
handleReturnKey();
keyConsumed = true;
}
break;
case Qt::Key_Backspace: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if ((hasSelection && selectionStart < d->startOfEditableArea)
|| (!hasSelection && selectionStart == d->startOfEditableArea)) {
keyConsumed = true;
}
break;
}
case Qt::Key_Delete:
if (textCursor().selectionStart() < d->startOfEditableArea) {
keyConsumed = true;
}
break;
case Qt::Key_Tab:
case Qt::Key_Backtab:
keyConsumed = true;
break;
case Qt::Key_Left:
if (textCursor().position() == d->startOfEditableArea) {
keyConsumed = true;
} else if (e->modifiers() & Qt::ControlModifier && isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_Up:
if (isEditableArea()) {
handleUpKey();
keyConsumed = true;
}
break;
case Qt::Key_Down:
if (isEditableArea()) {
handleDownKey();
keyConsumed = true;
}
break;
case Qt::Key_Home:
if (isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_C:
case Qt::Key_Insert: {
//Fair to assume that for any selection beyond startOfEditableArea
//only copy function is allowed.
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
if (!(e->modifiers() & Qt::ControlModifier))
keyConsumed = true;
}
break;
}
default: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
keyConsumed = true;
}
break;
}
}
if (!keyConsumed)
QPlainTextEdit::keyPressEvent(e);
}
void QmlJSScriptConsole::contextMenuEvent(QContextMenuEvent *event)
{
QTextCursor cursor = textCursor();
Qt::TextInteractionFlags flags = textInteractionFlags();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
bool canBeEdited = true;
if (hasSelection && selectionStart < d->startOfEditableArea) {
canBeEdited = false;
}
QMenu *menu = new QMenu();
QAction *a;
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Cut"), this, SLOT(cut()));
a->setEnabled(cursor.hasSelection());
}
a = menu->addAction(tr("Copy"), this, SLOT(copy()));
a->setEnabled(cursor.hasSelection());
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Paste"), this, SLOT(paste()));
a->setEnabled(canPaste());
}
menu->addSeparator();
a = menu->addAction(tr("Select All"), this, SLOT(selectAll()));
a->setEnabled(!document()->isEmpty());
menu->addSeparator();
menu->addAction(tr("Clear"), this, SLOT(clear()));
menu->exec(event->globalPos());
delete menu;
}
void QmlJSScriptConsole::mouseReleaseEvent(QMouseEvent *e)
{
QPlainTextEdit::mouseReleaseEvent(e);
QTextCursor cursor = textCursor();
if (e->button() == Qt::LeftButton && !cursor.hasSelection() && !isEditableArea()) {
cursor.setPosition(d->lastKnownPosition);
setTextCursor(cursor);
}
}
void QmlJSScriptConsole::onCursorPositionChanged()
{
if (!isEditableArea()) {
setTextInteractionFlags(Qt::TextSelectableByMouse);
} else {
d->lastKnownPosition = textCursor().position();
setTextInteractionFlags(Qt::TextEditorInteraction);
}
}
void QmlJSScriptConsole::displayPrompt()
{
d->startOfEditableArea = textCursor().position() + d->prompt.length();
QTextCursor cur = textCursor();
cur.insertText(d->prompt);
cur.movePosition(QTextCursor::EndOfWord);
setTextCursor(cur);
}
void QmlJSScriptConsole::handleReturnKey()
{
QString currentScript = getCurrentScript();
bool evaluateScript = false;
//Check if string is only white spaces
if (currentScript.trimmed().isEmpty()) {
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(QLatin1String("\n"));
setTextCursor(cur);
displayPrompt();
evaluateScript = true;
}
if (!evaluateScript && !d->inferiorStopped) {
if (!d->adapter.isNull()) {
QDeclarativeEngineDebug *engineDebug = d->adapter.data()->engineDebugClient();
int id = d->adapter.data()->currentSelectedDebugId();
if (engineDebug && id != -1) {
QDeclarativeDebugExpressionQuery *query =
engineDebug->queryExpressionResult(id, currentScript, this);
connect(query, SIGNAL(stateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)),
this, SLOT(onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)));
evaluateScript = true;
}
}
}
if (!evaluateScript) {
if (d->canEvaluateScript(currentScript)) {
emit evaluateExpression(currentScript);
} else {
QPlainTextEdit::appendPlainText(QLatin1String(""));
moveCursor(QTextCursor::EndOfLine);
}
}
}
void QmlJSScriptConsole::handleUpKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex > 1)
d->scriptHistoryIndex--;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleDownKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex < d->scriptHistory.count())
d->scriptHistoryIndex++;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleHomeKey()
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
setTextCursor(cursor);
}
QString QmlJSScriptConsole::getCurrentScript() const
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor)) ;
QString script = cursor.selectedText();
cursor.clearSelection();
//remove trailing white space
int end = script.size() - 1;
while (end > 0 && script[end].isSpace())
end--;
return script.left(end + 1);
}
void QmlJSScriptConsole::replaceCurrentScript(const QString &script)
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor)) ;
cursor.deleteChar();
cursor.insertText(script);
setTextCursor(cursor);
}
bool QmlJSScriptConsole::isEditableArea() const
{
return textCursor().position() >= d->startOfEditableArea;
}
} //Internal
} //Debugger
<commit_msg>QmlScriptConsole: Bug Fixes<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "qmljsscriptconsole.h"
#include "interactiveinterpreter.h"
#include "qmladapter.h"
#include "debuggerstringutils.h"
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/coreconstants.h>
#include <utils/statuslabel.h>
#include <QtGui/QMenu>
#include <QtGui/QTextBlock>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QToolButton>
namespace Debugger {
namespace Internal {
class QmlJSScriptConsolePrivate
{
public:
QmlJSScriptConsolePrivate()
: prompt(_("> ")),
startOfEditableArea(-1),
lastKnownPosition(0),
inferiorStopped(false)
{
resetCache();
}
void resetCache();
void appendToHistory(const QString &script);
bool canEvaluateScript(const QString &script);
QWeakPointer<QmlAdapter> adapter;
QString prompt;
int startOfEditableArea;
int lastKnownPosition;
QStringList scriptHistory;
int scriptHistoryIndex;
InteractiveInterpreter interpreter;
bool inferiorStopped;
QList<QTextEdit::ExtraSelection> selections;
};
void QmlJSScriptConsolePrivate::resetCache()
{
scriptHistory.clear();
scriptHistory.append(QString());
scriptHistoryIndex = scriptHistory.count();
selections.clear();
}
void QmlJSScriptConsolePrivate::appendToHistory(const QString &script)
{
scriptHistoryIndex = scriptHistory.count();
scriptHistory.replace(scriptHistoryIndex - 1,script);
scriptHistory.append(QString());
scriptHistoryIndex = scriptHistory.count();
}
bool QmlJSScriptConsolePrivate::canEvaluateScript(const QString &script)
{
interpreter.clearText();
interpreter.appendText(script);
return interpreter.canEvaluate();
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsoleWidget
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsoleWidget::QmlJSScriptConsoleWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
vbox->setSpacing(0);
QWidget *statusbarContainer = new QWidget;
QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer);
hbox->setMargin(0);
hbox->setSpacing(0);
//Clear Button
QToolButton *clearButton = new QToolButton;
QAction *clearAction = new QAction(tr("Clear Console"), this);
clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE)));
clearButton->setDefaultAction(clearAction);
//Status Label
m_statusLabel = new Utils::StatusLabel;
hbox->addWidget(m_statusLabel, 20, Qt::AlignLeft);
hbox->addWidget(clearButton, 0, Qt::AlignRight);
m_console = new QmlJSScriptConsole;
connect(m_console, SIGNAL(evaluateExpression(QString)), this,
SIGNAL(evaluateExpression(QString)));
connect(m_console, SIGNAL(updateStatusMessage(const QString &, int)), m_statusLabel,
SLOT(showStatusMessage(const QString &, int)));
connect(clearAction, SIGNAL(triggered()), m_console, SLOT(clear()));
vbox->addWidget(statusbarContainer);
vbox->addWidget(m_console);
}
void QmlJSScriptConsoleWidget::setQmlAdapter(QmlAdapter *adapter)
{
m_console->setQmlAdapter(adapter);
}
void QmlJSScriptConsoleWidget::setInferiorStopped(bool inferiorStopped)
{
m_console->setInferiorStopped(inferiorStopped);
}
void QmlJSScriptConsoleWidget::appendResult(const QString &result)
{
m_console->appendResult(result);
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsole
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsole::QmlJSScriptConsole(QWidget *parent)
: QPlainTextEdit(parent),
d(new QmlJSScriptConsolePrivate())
{
connect(this, SIGNAL(cursorPositionChanged()), SLOT(onCursorPositionChanged()));
setFrameStyle(QFrame::NoFrame);
setUndoRedoEnabled(false);
setBackgroundVisible(false);
const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::instance()->fontSettings();
setFont(fs.font());
displayPrompt();
}
QmlJSScriptConsole::~QmlJSScriptConsole()
{
delete d;
}
void QmlJSScriptConsole::setPrompt(const QString &prompt)
{
d->prompt = prompt;
}
QString QmlJSScriptConsole::prompt() const
{
return d->prompt;
}
void QmlJSScriptConsole::setInferiorStopped(bool inferiorStopped)
{
d->inferiorStopped = inferiorStopped;
onSelectionChanged();
}
void QmlJSScriptConsole::setQmlAdapter(QmlAdapter *adapter)
{
d->adapter = adapter;
clear();
}
void QmlJSScriptConsole::appendResult(const QString &result)
{
QString currentScript = getCurrentScript();
d->appendToHistory(currentScript);
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(_("\n"));
cur.insertText(result);
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(_("\n"));
setTextCursor(cur);
displayPrompt();
QTextEdit::ExtraSelection sel;
QTextCharFormat resultFormat;
resultFormat.setForeground(QBrush(QColor(Qt::darkGray)));
QTextCursor c(document()->findBlockByNumber(cur.blockNumber()-1));
c.movePosition(QTextCursor::StartOfBlock);
c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
sel.format = resultFormat;
sel.cursor = c;
d->selections.append(sel);
setExtraSelections(d->selections);
}
void QmlJSScriptConsole::clear()
{
d->resetCache();
QPlainTextEdit::clear();
displayPrompt();
}
void QmlJSScriptConsole::onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State state)
{
QDeclarativeDebugExpressionQuery *query = qobject_cast<QDeclarativeDebugExpressionQuery *>(sender());
if (query && state != QDeclarativeDebugQuery::Error) {
QString result(query->result().toString());
if (result == _("<undefined>") && d->inferiorStopped) {
//don't give up. check if we can still evaluate using javascript engine
emit evaluateExpression(getCurrentScript());
} else {
appendResult(result);
}
} else {
QPlainTextEdit::appendPlainText(QString());
moveCursor(QTextCursor::EndOfLine);
}
delete query;
}
void QmlJSScriptConsole::onSelectionChanged()
{
if (!d->adapter.isNull()) {
QString status;
if (!d->inferiorStopped) {
status.append(tr("Current Selected Object: "));
status.append(d->adapter.data()->currentSelectedDisplayName());
}
emit updateStatusMessage(status, 0);
}
}
void QmlJSScriptConsole::keyPressEvent(QKeyEvent *e)
{
bool keyConsumed = false;
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
if (isEditableArea()) {
handleReturnKey();
keyConsumed = true;
}
break;
case Qt::Key_Backspace: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if ((hasSelection && selectionStart < d->startOfEditableArea)
|| (!hasSelection && selectionStart == d->startOfEditableArea)) {
keyConsumed = true;
}
break;
}
case Qt::Key_Delete:
if (textCursor().selectionStart() < d->startOfEditableArea) {
keyConsumed = true;
}
break;
case Qt::Key_Tab:
case Qt::Key_Backtab:
keyConsumed = true;
break;
case Qt::Key_Left:
if (textCursor().position() == d->startOfEditableArea) {
keyConsumed = true;
} else if (e->modifiers() & Qt::ControlModifier && isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_Up:
if (isEditableArea()) {
handleUpKey();
keyConsumed = true;
}
break;
case Qt::Key_Down:
if (isEditableArea()) {
handleDownKey();
keyConsumed = true;
}
break;
case Qt::Key_Home:
if (isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_C:
case Qt::Key_Insert: {
//Fair to assume that for any selection beyond startOfEditableArea
//only copy function is allowed.
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
if (!(e->modifiers() & Qt::ControlModifier))
keyConsumed = true;
}
break;
}
default: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
keyConsumed = true;
}
break;
}
}
if (!keyConsumed)
QPlainTextEdit::keyPressEvent(e);
}
void QmlJSScriptConsole::contextMenuEvent(QContextMenuEvent *event)
{
QTextCursor cursor = textCursor();
Qt::TextInteractionFlags flags = textInteractionFlags();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
bool canBeEdited = true;
if (hasSelection && selectionStart < d->startOfEditableArea) {
canBeEdited = false;
}
QMenu *menu = new QMenu();
QAction *a;
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Cut"), this, SLOT(cut()));
a->setEnabled(cursor.hasSelection());
}
a = menu->addAction(tr("Copy"), this, SLOT(copy()));
a->setEnabled(cursor.hasSelection());
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Paste"), this, SLOT(paste()));
a->setEnabled(canPaste());
}
menu->addSeparator();
a = menu->addAction(tr("Select All"), this, SLOT(selectAll()));
a->setEnabled(!document()->isEmpty());
menu->addSeparator();
menu->addAction(tr("Clear"), this, SLOT(clear()));
menu->exec(event->globalPos());
delete menu;
}
void QmlJSScriptConsole::mouseReleaseEvent(QMouseEvent *e)
{
QPlainTextEdit::mouseReleaseEvent(e);
QTextCursor cursor = textCursor();
if (e->button() == Qt::LeftButton && !cursor.hasSelection() && !isEditableArea()) {
cursor.setPosition(d->lastKnownPosition);
setTextCursor(cursor);
}
}
void QmlJSScriptConsole::onCursorPositionChanged()
{
if (!isEditableArea()) {
setTextInteractionFlags(Qt::TextSelectableByMouse);
} else {
d->lastKnownPosition = textCursor().position();
setTextInteractionFlags(Qt::TextEditorInteraction);
}
}
void QmlJSScriptConsole::displayPrompt()
{
d->startOfEditableArea = textCursor().position() + d->prompt.length();
QTextCursor cur = textCursor();
cur.insertText(d->prompt);
cur.movePosition(QTextCursor::EndOfWord);
setTextCursor(cur);
}
void QmlJSScriptConsole::handleReturnKey()
{
QString currentScript = getCurrentScript();
bool evaluateScript = false;
//Check if string is only white spaces
if (currentScript.trimmed().isEmpty()) {
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(_("\n"));
setTextCursor(cur);
displayPrompt();
evaluateScript = true;
}
if (!evaluateScript && !d->inferiorStopped) {
if (!d->adapter.isNull()) {
QDeclarativeEngineDebug *engineDebug = d->adapter.data()->engineDebugClient();
int id = d->adapter.data()->currentSelectedDebugId();
if (engineDebug && id != -1) {
QDeclarativeDebugExpressionQuery *query =
engineDebug->queryExpressionResult(id, currentScript, this);
connect(query, SIGNAL(stateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)),
this, SLOT(onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)));
evaluateScript = true;
}
}
}
if (!evaluateScript) {
if (d->canEvaluateScript(currentScript)) {
emit evaluateExpression(currentScript);
} else {
QPlainTextEdit::appendPlainText(QString());
moveCursor(QTextCursor::EndOfLine);
}
}
}
void QmlJSScriptConsole::handleUpKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex > 1)
d->scriptHistoryIndex--;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleDownKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex < d->scriptHistory.count())
d->scriptHistoryIndex++;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleHomeKey()
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
setTextCursor(cursor);
}
QString QmlJSScriptConsole::getCurrentScript() const
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor)) ;
QString script = cursor.selectedText();
cursor.clearSelection();
//remove trailing white space
int end = script.size() - 1;
while (end > 0 && script[end].isSpace())
end--;
return script.left(end + 1);
}
void QmlJSScriptConsole::replaceCurrentScript(const QString &script)
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor)) ;
cursor.deleteChar();
cursor.insertText(script);
setTextCursor(cursor);
}
bool QmlJSScriptConsole::isEditableArea() const
{
return textCursor().position() >= d->startOfEditableArea;
}
} //Internal
} //Debugger
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
* help_config.c
*
* Displays available options under grand unified configuration scheme
*
* Options whose flag bits are set to GUC_NO_SHOW_ALL, GUC_NOT_IN_SAMPLE,
* or GUC_DISALLOW_IN_FILE are not displayed, unless the user specifically
* requests that variable by name
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* src/backend/utils/misc/help_config.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <float.h>
#include <limits.h>
#include <unistd.h>
#include "utils/guc_tables.h"
#include "utils/help_config.h"
/*
* This union allows us to mix the numerous different types of structs
* that we are organizing.
*/
typedef union
{
struct config_generic generic;
struct config_bool bool;
struct config_real real;
struct config_int integer;
struct config_string string;
struct config_enum _enum;
} mixedStruct;
static void printMixedStruct(mixedStruct *structToPrint);
static bool displayStruct(mixedStruct *structToDisplay);
void
GucInfoMain(void)
{
struct config_generic **guc_vars;
int numOpts,
i;
/* Initialize the guc_variables[] array */
build_guc_variables();
guc_vars = get_guc_variables();
numOpts = GetNumConfigOptions();
for (i = 0; i < numOpts; i++)
{
mixedStruct *var = (mixedStruct *) guc_vars[i];
if (displayStruct(var))
printMixedStruct(var);
}
exit(0);
}
/*
* This function will return true if the struct passed to it
* should be displayed to the user.
*/
static bool
displayStruct(mixedStruct *structToDisplay)
{
return !(structToDisplay->generic.flags & (GUC_NO_SHOW_ALL |
GUC_NOT_IN_SAMPLE |
GUC_DISALLOW_IN_FILE));
}
/*
* This function prints out the generic struct passed to it. It will print out
* a different format, depending on what the user wants to see.
*/
static void
printMixedStruct(mixedStruct *structToPrint)
{
printf("%s\t%s\t%s\t",
structToPrint->generic.name,
GucContext_Names[structToPrint->generic.context],
_(config_group_names[structToPrint->generic.group]));
switch (structToPrint->generic.vartype)
{
case PGC_BOOL:
printf("BOOLEAN\t%s\t\t\t",
(structToPrint->bool.reset_val == 0) ?
"FALSE" : "TRUE");
break;
case PGC_INT:
printf("INTEGER\t%d\t%d\t%d\t",
structToPrint->integer.reset_val,
structToPrint->integer.min,
structToPrint->integer.max);
break;
case PGC_REAL:
printf("REAL\t%g\t%g\t%g\t",
structToPrint->real.reset_val,
structToPrint->real.min,
structToPrint->real.max);
break;
case PGC_STRING:
printf("STRING\t%s\t\t\t",
structToPrint->string.boot_val ? structToPrint->string.boot_val : "");
break;
case PGC_ENUM:
printf("ENUM\t%s\t\t\t",
config_enum_lookup_by_value(&structToPrint->_enum,
structToPrint->_enum.boot_val));
break;
default:
write_stderr("internal error: unrecognized run-time parameter type\n");
break;
}
printf("%s\t%s\n",
(structToPrint->generic.short_desc == NULL) ? "" : _(structToPrint->generic.short_desc),
(structToPrint->generic.long_desc == NULL) ? "" : _(structToPrint->generic.long_desc));
}
<commit_msg>change variable name bool to boolean<commit_after>/*-------------------------------------------------------------------------
* help_config.c
*
* Displays available options under grand unified configuration scheme
*
* Options whose flag bits are set to GUC_NO_SHOW_ALL, GUC_NOT_IN_SAMPLE,
* or GUC_DISALLOW_IN_FILE are not displayed, unless the user specifically
* requests that variable by name
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* src/backend/utils/misc/help_config.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <float.h>
#include <limits.h>
#include <unistd.h>
#include "utils/guc_tables.h"
#include "utils/help_config.h"
/*
* This union allows us to mix the numerous different types of structs
* that we are organizing.
*/
typedef union
{
struct config_generic generic;
struct config_bool boolean;
struct config_real real;
struct config_int integer;
struct config_string string;
struct config_enum _enum;
} mixedStruct;
static void printMixedStruct(mixedStruct *structToPrint);
static bool displayStruct(mixedStruct *structToDisplay);
void
GucInfoMain(void)
{
struct config_generic **guc_vars;
int numOpts,
i;
/* Initialize the guc_variables[] array */
build_guc_variables();
guc_vars = get_guc_variables();
numOpts = GetNumConfigOptions();
for (i = 0; i < numOpts; i++)
{
mixedStruct *var = (mixedStruct *) guc_vars[i];
if (displayStruct(var))
printMixedStruct(var);
}
exit(0);
}
/*
* This function will return true if the struct passed to it
* should be displayed to the user.
*/
static bool
displayStruct(mixedStruct *structToDisplay)
{
return !(structToDisplay->generic.flags & (GUC_NO_SHOW_ALL |
GUC_NOT_IN_SAMPLE |
GUC_DISALLOW_IN_FILE));
}
/*
* This function prints out the generic struct passed to it. It will print out
* a different format, depending on what the user wants to see.
*/
static void
printMixedStruct(mixedStruct *structToPrint)
{
printf("%s\t%s\t%s\t",
structToPrint->generic.name,
GucContext_Names[structToPrint->generic.context],
_(config_group_names[structToPrint->generic.group]));
switch (structToPrint->generic.vartype)
{
case PGC_BOOL:
printf("BOOLEAN\t%s\t\t\t",
(structToPrint->boolean.reset_val == 0) ?
"FALSE" : "TRUE");
break;
case PGC_INT:
printf("INTEGER\t%d\t%d\t%d\t",
structToPrint->integer.reset_val,
structToPrint->integer.min,
structToPrint->integer.max);
break;
case PGC_REAL:
printf("REAL\t%g\t%g\t%g\t",
structToPrint->real.reset_val,
structToPrint->real.min,
structToPrint->real.max);
break;
case PGC_STRING:
printf("STRING\t%s\t\t\t",
structToPrint->string.boot_val ? structToPrint->string.boot_val : "");
break;
case PGC_ENUM:
printf("ENUM\t%s\t\t\t",
config_enum_lookup_by_value(&structToPrint->_enum,
structToPrint->_enum.boot_val));
break;
default:
write_stderr("internal error: unrecognized run-time parameter type\n");
break;
}
printf("%s\t%s\n",
(structToPrint->generic.short_desc == NULL) ? "" : _(structToPrint->generic.short_desc),
(structToPrint->generic.long_desc == NULL) ? "" : _(structToPrint->generic.long_desc));
}
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, 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 as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero 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, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>
#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"
#include <sstream>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <openssl/err.h>
#include <openssl/pem.h>
using namespace std;
static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
static const char *APN_PORT = "2195";
static const char *GPN_ADDRESS = "android.googleapis.com";
static const char *GPN_PORT = "443";
static const char *WPPN_PORT = "80";
PushNotificationService::PushNotificationService(int maxQueueSize)
: mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
SSL_library_init();
SSL_load_error_strings();
}
PushNotificationService::~PushNotificationService() {
ERR_free_strings();
}
int PushNotificationService::sendPush(const std::shared_ptr<PushNotificationRequest> &pn) {
std::shared_ptr<PushNotificationClient> client = mClients[pn->getAppIdentifier()];
if (client == 0) {
if (pn->getType().compare(string("wp")) == 0) {
string wpClient = pn->getAppIdentifier();
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
LOGD("Creating PN client for %s", pn->getAppIdentifier().c_str());
mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx,
pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
client = mClients[wpClient];
} else {
LOGE("No push notification certificate for client %s", pn->getAppIdentifier().c_str());
return -1;
}
}
client->sendPush(pn);
return 0;
}
bool PushNotificationService::isIdle() {
map<string, std::shared_ptr<PushNotificationClient>>::const_iterator it;
for (it = mClients.begin(); it != mClients.end(); ++it) {
if (!it->second->isIdle()) {
return false;
}
}
return true;
}
void PushNotificationService::setupGenericClient(const url_t *url) {
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
mClients["generic"] = std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url),
mMaxQueueSize, false);
}
/* Utility function to convert ASN1_TIME to a printable string in a buffer */
static int ASN1_TIME_toString( const ASN1_TIME* time, char* buffer, uint32_t buff_length){
int write = 0;
BIO* bio = BIO_new(BIO_s_mem());
if (bio) {
if (ASN1_TIME_print(bio, time))
write = BIO_read(bio, buffer, buff_length-1);
BIO_free_all(bio);
}
buffer[write]='\0';
return write;
}
bool PushNotificationService::isCertExpired( const std::string &certPath ){
bool expired = true;
BIO* certbio = BIO_new(BIO_s_file());
int err = BIO_read_filename(certbio, certPath.c_str());
if( err == 0 ){
LOGE("BIO_read_filename failed for %s", certPath.c_str());
BIO_free_all(certbio);
return expired;
}
X509* cert = PEM_read_bio_X509(certbio, NULL, 0, 0);
if( !cert ){
char buf[128] = {};
unsigned long error = ERR_get_error();
ERR_error_string(error, buf);
LOGE("Couldn't parse certificate at %s : %s", certPath.c_str(), buf);
BIO_free_all(certbio);
return expired;
} else {
ASN1_TIME *notBefore = X509_get_notBefore(cert);
ASN1_TIME *notAfter = X509_get_notAfter(cert);
char beforeStr[128] = {};
char afterStr[128] = {};
int validDates = ( ASN1_TIME_toString(notBefore, beforeStr, 128) && ASN1_TIME_toString(notAfter, afterStr, 128));
if( X509_cmp_current_time(notBefore) <= 0 && X509_cmp_current_time(notAfter) >= 0 ) {
LOGD("Certificate %s has a valid expiration: %s.", certPath.c_str(), afterStr);
expired = false;
} else {
// the certificate has an expire or not before value that makes it not valid regarding the server's date.
if (validDates) {
LOGD("Certificate %s is expired or not yet valid! Not Before: %s, Not After: %s", certPath.c_str(),
beforeStr, afterStr);
} else {
LOGD("Certificate %s is expired or not yet valid!", certPath.c_str());
}
}
}
X509_free(cert);
BIO_free_all(certbio);
return expired;
}
int handle_verify_callback(X509_STORE_CTX* mCtx, void* ud) {
char subject_name[256];
X509 *cert = X509_STORE_CTX_get_current_cert(mCtx);
if (!cert) {
SLOGE << "No certificate found!";
return 0;
}
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
SLOGD << "Verifying " << subject_name;
int error = X509_STORE_CTX_get_error(mCtx);
if( error != 0 ){
switch (error) {
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_CRL_NOT_YET_VALID:
SLOGE << "Certificate for " << subject_name << " is not yet valid. Push won't work.";
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_CRL_HAS_EXPIRED:
SLOGE << "Certificate for " << subject_name << " is expired. Push won't work.";
break;
default:{
const char* errString = X509_verify_cert_error_string(error);
SLOGE << "Certificate for " << subject_name << " is invalid (reason: " << error << ": " << (errString ? errString:"unknown") << "). Push won't work.";
break;
}
}
}
return 0;
}
void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
struct dirent *dirent;
DIR *dirp;
dirp = opendir(certdir.c_str());
if (dirp == NULL) {
LOGE("Could not open push notification certificates directory (%s): %s", certdir.c_str(), strerror(errno));
return;
}
SLOGD << "Searching push notification client on dir [" << certdir << "]";
while (true) {
errno = 0;
if ((dirent = readdir(dirp)) == NULL) {
if (errno)
SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
break;
}
string cert = string(dirent->d_name);
// only consider files which end with .pem
string suffix = ".pem";
if (cert.compare(".") == 0 || cert.compare("..") == 0 ||
(cert.compare(cert.length() - suffix.length(), suffix.length(), suffix) != 0)) {
continue;
}
SSL_CTX* ctx = SSL_CTX_new(TLSv1_2_client_method());
if (!ctx) {
SLOGE << "Could not create ctx!";
ERR_print_errors_fp(stderr);
continue;
}
if (cafile.empty()) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
} else {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_cert_verify_callback(ctx, handle_verify_callback, NULL);
}
if(! SSL_CTX_load_verify_locations(ctx, cafile.empty()?NULL:cafile.c_str(), "/etc/ssl/certs")) {
SLOGE << "Error loading trust store";
ERR_print_errors_fp(stderr);
SSL_CTX_free(ctx);
continue;
}
string certpath = string(certdir) + "/" + cert;
if (!cert.empty()) {
int error = SSL_CTX_use_certificate_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
if (error != 1) {
LOGE("SSL_CTX_use_certificate_file for %s failed: %d", certpath.c_str(), error);
continue;
} else if ( isCertExpired(certpath) ){
LOGEN("Certificate %s is expired! You won't be able to use it for push notifications. Please update your certificate or remove it entirely.", certpath.c_str());
}
}
if (!certpath.empty()) {
int error = SSL_CTX_use_PrivateKey_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
if (error != 1 || SSL_CTX_check_private_key(ctx) != 1) {
SLOGE << "Private key does not match the certificate public key for " << certpath << ": " << error;
continue;
}
}
string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
const char *apn_server = (certName.find(".dev") != string::npos) ? APN_DEV_ADDRESS : APN_PROD_ADDRESS;
mClients[certName] = std::make_shared<PushNotificationClient>(cert, this, ctx, apn_server, APN_PORT, mMaxQueueSize, true);
SLOGD << "Adding ios push notification client [" << certName << "]";
}
closedir(dirp);
}
void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
map<string, string>::const_iterator it;
for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
string android_app_id = it->first;
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
mClients[android_app_id] = std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
SLOGD << "Adding android push notification client [" << android_app_id << "]";
}
}
<commit_msg>fix ssl version for apple production push notif server, that doesn't like TLS > 1.0<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, 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 as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero 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, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>
#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"
#include <sstream>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <openssl/err.h>
#include <openssl/pem.h>
using namespace std;
static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
static const char *APN_PORT = "2195";
static const char *GPN_ADDRESS = "android.googleapis.com";
static const char *GPN_PORT = "443";
static const char *WPPN_PORT = "80";
PushNotificationService::PushNotificationService(int maxQueueSize)
: mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
SSL_library_init();
SSL_load_error_strings();
}
PushNotificationService::~PushNotificationService() {
ERR_free_strings();
}
int PushNotificationService::sendPush(const std::shared_ptr<PushNotificationRequest> &pn) {
std::shared_ptr<PushNotificationClient> client = mClients[pn->getAppIdentifier()];
if (client == 0) {
if (pn->getType().compare(string("wp")) == 0) {
string wpClient = pn->getAppIdentifier();
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
LOGD("Creating PN client for %s", pn->getAppIdentifier().c_str());
mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx,
pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
client = mClients[wpClient];
} else {
LOGE("No push notification certificate for client %s", pn->getAppIdentifier().c_str());
return -1;
}
}
client->sendPush(pn);
return 0;
}
bool PushNotificationService::isIdle() {
map<string, std::shared_ptr<PushNotificationClient>>::const_iterator it;
for (it = mClients.begin(); it != mClients.end(); ++it) {
if (!it->second->isIdle()) {
return false;
}
}
return true;
}
void PushNotificationService::setupGenericClient(const url_t *url) {
SSL_CTX* ctx = SSL_CTX_new(TLSv1_client_method());
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
mClients["generic"] = std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url),
mMaxQueueSize, false);
}
/* Utility function to convert ASN1_TIME to a printable string in a buffer */
static int ASN1_TIME_toString( const ASN1_TIME* time, char* buffer, uint32_t buff_length){
int write = 0;
BIO* bio = BIO_new(BIO_s_mem());
if (bio) {
if (ASN1_TIME_print(bio, time))
write = BIO_read(bio, buffer, buff_length-1);
BIO_free_all(bio);
}
buffer[write]='\0';
return write;
}
bool PushNotificationService::isCertExpired( const std::string &certPath ){
bool expired = true;
BIO* certbio = BIO_new(BIO_s_file());
int err = BIO_read_filename(certbio, certPath.c_str());
if( err == 0 ){
LOGE("BIO_read_filename failed for %s", certPath.c_str());
BIO_free_all(certbio);
return expired;
}
X509* cert = PEM_read_bio_X509(certbio, NULL, 0, 0);
if( !cert ){
char buf[128] = {};
unsigned long error = ERR_get_error();
ERR_error_string(error, buf);
LOGE("Couldn't parse certificate at %s : %s", certPath.c_str(), buf);
BIO_free_all(certbio);
return expired;
} else {
ASN1_TIME *notBefore = X509_get_notBefore(cert);
ASN1_TIME *notAfter = X509_get_notAfter(cert);
char beforeStr[128] = {};
char afterStr[128] = {};
int validDates = ( ASN1_TIME_toString(notBefore, beforeStr, 128) && ASN1_TIME_toString(notAfter, afterStr, 128));
if( X509_cmp_current_time(notBefore) <= 0 && X509_cmp_current_time(notAfter) >= 0 ) {
LOGD("Certificate %s has a valid expiration: %s.", certPath.c_str(), afterStr);
expired = false;
} else {
// the certificate has an expire or not before value that makes it not valid regarding the server's date.
if (validDates) {
LOGD("Certificate %s is expired or not yet valid! Not Before: %s, Not After: %s", certPath.c_str(),
beforeStr, afterStr);
} else {
LOGD("Certificate %s is expired or not yet valid!", certPath.c_str());
}
}
}
X509_free(cert);
BIO_free_all(certbio);
return expired;
}
int handle_verify_callback(X509_STORE_CTX* mCtx, void* ud) {
char subject_name[256];
X509 *cert = X509_STORE_CTX_get_current_cert(mCtx);
if (!cert) {
SLOGE << "No certificate found!";
return 0;
}
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
SLOGD << "Verifying " << subject_name;
int error = X509_STORE_CTX_get_error(mCtx);
if( error != 0 ){
switch (error) {
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_CRL_NOT_YET_VALID:
SLOGE << "Certificate for " << subject_name << " is not yet valid. Push won't work.";
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_CRL_HAS_EXPIRED:
SLOGE << "Certificate for " << subject_name << " is expired. Push won't work.";
break;
default:{
const char* errString = X509_verify_cert_error_string(error);
SLOGE << "Certificate for " << subject_name << " is invalid (reason: " << error << ": " << (errString ? errString:"unknown") << "). Push won't work.";
break;
}
}
}
return 0;
}
void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
struct dirent *dirent;
DIR *dirp;
dirp = opendir(certdir.c_str());
if (dirp == NULL) {
LOGE("Could not open push notification certificates directory (%s): %s", certdir.c_str(), strerror(errno));
return;
}
SLOGD << "Searching push notification client on dir [" << certdir << "]";
while (true) {
errno = 0;
if ((dirent = readdir(dirp)) == NULL) {
if (errno)
SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
break;
}
string cert = string(dirent->d_name);
// only consider files which end with .pem
string suffix = ".pem";
if (cert.compare(".") == 0 || cert.compare("..") == 0 ||
(cert.compare(cert.length() - suffix.length(), suffix.length(), suffix) != 0)) {
continue;
}
/*March 2016: Yes Apple production push server doesn't support TLS > 1.0*/
SSL_CTX* ctx = SSL_CTX_new(TLSv1_client_method());
if (!ctx) {
SLOGE << "Could not create ctx!";
ERR_print_errors_fp(stderr);
continue;
}
if (cafile.empty()) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
} else {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_cert_verify_callback(ctx, handle_verify_callback, NULL);
}
if(! SSL_CTX_load_verify_locations(ctx, cafile.empty()?NULL:cafile.c_str(), "/etc/ssl/certs")) {
SLOGE << "Error loading trust store";
ERR_print_errors_fp(stderr);
SSL_CTX_free(ctx);
continue;
}
string certpath = string(certdir) + "/" + cert;
if (!cert.empty()) {
int error = SSL_CTX_use_certificate_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
if (error != 1) {
LOGE("SSL_CTX_use_certificate_file for %s failed: %d", certpath.c_str(), error);
continue;
} else if ( isCertExpired(certpath) ){
LOGEN("Certificate %s is expired! You won't be able to use it for push notifications. Please update your certificate or remove it entirely.", certpath.c_str());
}
}
if (!certpath.empty()) {
int error = SSL_CTX_use_PrivateKey_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
if (error != 1 || SSL_CTX_check_private_key(ctx) != 1) {
SLOGE << "Private key does not match the certificate public key for " << certpath << ": " << error;
continue;
}
}
string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
const char *apn_server = (certName.find(".dev") != string::npos) ? APN_DEV_ADDRESS : APN_PROD_ADDRESS;
mClients[certName] = std::make_shared<PushNotificationClient>(cert, this, ctx, apn_server, APN_PORT, mMaxQueueSize, true);
SLOGD << "Adding ios push notification client [" << certName << "]";
}
closedir(dirp);
}
void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
map<string, string>::const_iterator it;
for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
string android_app_id = it->first;
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
mClients[android_app_id] = std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
SLOGD << "Adding android push notification client [" << android_app_id << "]";
}
}
<|endoftext|> |
<commit_before>#include "command.h"
#include "debug.h"
#include "thread.h"
#include "dwi/tractography/rng.h"
#include "image.h"
using namespace MR;
using namespace App;
std::mutex mutex;
void usage ()
{
AUTHOR = "Joe Bloggs (joe.bloggs@acme.org)";
DESCRIPTION
+ "raise each voxel intensity to the given power (default: 2)";
ARGUMENTS
+ Argument ("in", "the input image.").type_image_in ()
+ Argument ("out", "the output image.").type_image_out ();
OPTIONS
+ Option ("power", "the power by which to raise each value (default: 1)")
+ Argument ("value").type_float()
+ Option ("noise", "the std. dev. of the noise to add to each value (default: 1)")
+ Argument ("value").type_float();
}
typedef float value_type;
using namespace DWI::Tractography;
//struct thread_func {
// void execute () {
// std::lock_guard<std::mutex> lock (mutex);
// std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
// }
//};
void run ()
{
auto input = Image<float>::open (argument[0]);
auto output = Image<float>::create (argument[1], input);
output.index(0) = input.index(0);
output.valid() = input.value();
// std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
// Thread::run (Thread::multi (thread_func()));
}
<commit_msg>change to bogus command to demonstrate issue with new syntax and assigning indices and values between images<commit_after>#include "command.h"
#include "debug.h"
#include "thread.h"
#include "dwi/tractography/rng.h"
#include "image.h"
using namespace MR;
using namespace App;
std::mutex mutex;
void usage ()
{
AUTHOR = "Joe Bloggs (joe.bloggs@acme.org)";
DESCRIPTION
+ "raise each voxel intensity to the given power (default: 2)";
ARGUMENTS
+ Argument ("in", "the input image.").type_image_in ()
+ Argument ("out", "the output image.").type_image_out ();
OPTIONS
+ Option ("power", "the power by which to raise each value (default: 1)")
+ Argument ("value").type_float()
+ Option ("noise", "the std. dev. of the noise to add to each value (default: 1)")
+ Argument ("value").type_float();
}
typedef float value_type;
using namespace DWI::Tractography;
//struct thread_func {
// void execute () {
// std::lock_guard<std::mutex> lock (mutex);
// std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
// }
//};
void run ()
{
auto input = Image<float>::open (argument[0]);
auto output = Image<float>::create (argument[1], input);
output.index(0) = input.index(0);
output.value() = input.value();
// std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
// Thread::run (Thread::multi (thread_func()));
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "oslops.h"
#include "oslexec_pvt.h"
#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {
/////////////////////////////////////////////////////////////////////////
// Notes on how messages work:
//
// The messages are stored in a ParamValueList in the ShadingContext.
// For simple types, just slurp them up into the PVL.
//
// Closures are tricky because of the memory management and that PVL's
// don't know anything about them. For those we allocate new closures
// in the context's closure_msgs vector, and just store their indices in
// the PVL.
//
// FIXME -- setmessage only stores message values, not derivs, so
// getmessage only retrieves the values and has zero derivs.
// We should come back and fix this later.
//
// FIXME -- I believe that if you try to set a message that is an array
// of closures, it will only store the first element. Also something to
// come back to, not an emergency at the moment.
//
// FIXME -- because we store closures by int index, there's an error
// condition if a shader does a setmessage with a closure, then does a
// getmessage of the same message name into int, or vice versa. Instead
// that should be a type mismatch and getmessage() should return 0.
// void setmessage (string name, ANY value).
DECLOP (OP_setmessage)
{
ASSERT (nargs == 2);
Symbol &Name (exec->sym (args[0]));
Symbol &Val (exec->sym (args[1]));
ASSERT (Name.typespec().is_string());
VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
ParamValueList &messages (exec->context()->messages());
std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());
bool varying = (Name.is_varying() || Val.is_varying() ||
! exec->all_points_on());
TypeDesc type = Val.typespec().simpletype();
if (Val.typespec().is_closure ())
type = TypeDesc::TypeInt; // Actually store closure indices only
size_t datasize = type.size();
ustring lastname; // Last message name that we matched
ParamValue *p = NULL; // Pointer to the PV for the message
for (int i = beginpoint; i < endpoint; ++i) {
if (runflags[i]) {
if (i == beginpoint || name[i] != lastname) {
// Different message than last time -- search anew
p = NULL;
for (size_t m = 0; m < messages.size() && !p; ++m)
if (messages[m].name() == name[i] &&
messages[m].type() == type)
p = &messages[m];
// If the message doesn't already exist, create it
if (! p) {
p = & messages.grow ();
p->init (name[i], type,
varying ? exec->npoints() : 1, NULL);
}
lastname = name[i];
}
// Copy the data
DASSERT (p != NULL);
char *msgdata = (char *)p->data() + varying*datasize*i;
if (Val.typespec().is_closure()) {
// Add the closure data to the end of the closure messages
closure_msgs.push_back (**(ClosureColor **)Val.data(i));
// and store its index in the PVL
*(int *)msgdata = (int)closure_msgs.size() - 1;
} else {
// Non-closure types, just memcpy
memcpy (msgdata, Val.data(i), datasize);
}
}
if (! varying)
break; // Non-uniform case can take early out
}
}
// int getmessage (string name, ANY value)
DECLOP (OP_getmessage)
{
ASSERT (nargs == 3);
Symbol &Result (exec->sym (args[0]));
Symbol &Name (exec->sym (args[1]));
Symbol &Val (exec->sym (args[2]));
ASSERT (Result.typespec().is_int() && Name.typespec().is_string());
bool varying = (Name.is_varying());
exec->adjust_varying (Result, varying);
exec->adjust_varying (Val, varying);
VaryingRef<int> result ((int *)Result.data(), Result.step());
VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
ParamValueList &messages (exec->context()->messages());
std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());
TypeDesc type = Val.typespec().simpletype();
if (Val.typespec().is_closure ())
type = TypeDesc::TypeInt; // Actually store closure indices only
size_t datasize = type.size();
ustring lastname; // Last message name that we matched
ParamValue *p = NULL; // Pointer to the PV for the message
for (int i = beginpoint; i < endpoint; ++i) {
if (runflags[i]) {
if (i == beginpoint || name[i] != lastname) {
// Different message than last time -- search anew
p = NULL;
for (size_t m = 0; m < messages.size() && !p; ++m)
if (messages[m].name() == name[i] &&
messages[m].type() == type)
p = &messages[m];
if (p && (! varying || Val.is_uniform()) && p->nvalues() > 1) {
// all the parameters to the function were uniform,
// but the message itself is varying, so adjust Val.
exec->adjust_varying (Val, true);
varying = true;
}
lastname = name[i];
}
if (p) {
result[i] = 1; // found
char *msgdata = (char *)p->data() + varying*datasize*i;
if (Val.typespec().is_closure()) {
// Retrieve the closure index from the PVL
int index = *(int *)msgdata;
ClosureColor *valclose = *(ClosureColor **) Val.data(i);
// then copy the closure (or clear it, if out of range)
if (index < (int)closure_msgs.size())
*valclose = closure_msgs.back();
else
valclose->clear ();
} else {
memcpy (Val.data(i), msgdata, datasize);
}
} else {
result[i] = 0; // not found
}
}
if (! varying)
break; // Non-uniform case can take early out
}
if (Val.has_derivs ())
exec->zero_derivs (Val);
}
}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<commit_msg>Fix bug in getmessage when all args are varying but the op occurs in a varying conditional.<commit_after>/*
Copyright (c) 2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "oslops.h"
#include "oslexec_pvt.h"
#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {
/////////////////////////////////////////////////////////////////////////
// Notes on how messages work:
//
// The messages are stored in a ParamValueList in the ShadingContext.
// For simple types, just slurp them up into the PVL.
//
// Closures are tricky because of the memory management and that PVL's
// don't know anything about them. For those we allocate new closures
// in the context's closure_msgs vector, and just store their indices in
// the PVL.
//
// FIXME -- setmessage only stores message values, not derivs, so
// getmessage only retrieves the values and has zero derivs.
// We should come back and fix this later.
//
// FIXME -- I believe that if you try to set a message that is an array
// of closures, it will only store the first element. Also something to
// come back to, not an emergency at the moment.
//
// FIXME -- because we store closures by int index, there's an error
// condition if a shader does a setmessage with a closure, then does a
// getmessage of the same message name into int, or vice versa. Instead
// that should be a type mismatch and getmessage() should return 0.
// void setmessage (string name, ANY value).
DECLOP (OP_setmessage)
{
ASSERT (nargs == 2);
Symbol &Name (exec->sym (args[0]));
Symbol &Val (exec->sym (args[1]));
ASSERT (Name.typespec().is_string());
VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
ParamValueList &messages (exec->context()->messages());
std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());
bool varying = (Name.is_varying() || Val.is_varying() ||
! exec->all_points_on());
TypeDesc type = Val.typespec().simpletype();
if (Val.typespec().is_closure ())
type = TypeDesc::TypeInt; // Actually store closure indices only
size_t datasize = type.size();
ustring lastname; // Last message name that we matched
ParamValue *p = NULL; // Pointer to the PV for the message
for (int i = beginpoint; i < endpoint; ++i) {
if (runflags[i]) {
if (i == beginpoint || name[i] != lastname) {
// Different message than last time -- search anew
p = NULL;
for (size_t m = 0; m < messages.size() && !p; ++m)
if (messages[m].name() == name[i] &&
messages[m].type() == type)
p = &messages[m];
// If the message doesn't already exist, create it
if (! p) {
p = & messages.grow ();
p->init (name[i], type,
varying ? exec->npoints() : 1, NULL);
}
lastname = name[i];
}
// Copy the data
DASSERT (p != NULL);
char *msgdata = (char *)p->data() + varying*datasize*i;
if (Val.typespec().is_closure()) {
// Add the closure data to the end of the closure messages
closure_msgs.push_back (**(ClosureColor **)Val.data(i));
// and store its index in the PVL
*(int *)msgdata = (int)closure_msgs.size() - 1;
} else {
// Non-closure types, just memcpy
memcpy (msgdata, Val.data(i), datasize);
}
}
if (! varying)
break; // Non-uniform case can take early out
}
}
// int getmessage (string name, ANY value)
DECLOP (OP_getmessage)
{
ASSERT (nargs == 3);
Symbol &Result (exec->sym (args[0]));
Symbol &Name (exec->sym (args[1]));
Symbol &Val (exec->sym (args[2]));
ASSERT (Result.typespec().is_int() && Name.typespec().is_string());
bool varying = (Name.is_varying());
exec->adjust_varying (Result, varying);
exec->adjust_varying (Val, varying);
varying |= Result.is_varying(); // adjust in case we're in a conditional
VaryingRef<int> result ((int *)Result.data(), Result.step());
VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
ParamValueList &messages (exec->context()->messages());
std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());
TypeDesc type = Val.typespec().simpletype();
if (Val.typespec().is_closure ())
type = TypeDesc::TypeInt; // Actually store closure indices only
size_t datasize = type.size();
ustring lastname; // Last message name that we matched
ParamValue *p = NULL; // Pointer to the PV for the message
for (int i = beginpoint; i < endpoint; ++i) {
if (runflags[i]) {
if (i == beginpoint || name[i] != lastname) {
// Different message than last time -- search anew
p = NULL;
for (size_t m = 0; m < messages.size() && !p; ++m)
if (messages[m].name() == name[i] &&
messages[m].type() == type)
p = &messages[m];
if (p && (! varying || Val.is_uniform()) && p->nvalues() > 1) {
// all the parameters to the function were uniform,
// but the message itself is varying, so adjust Val.
exec->adjust_varying (Val, true);
varying = true;
}
lastname = name[i];
}
if (p) {
result[i] = 1; // found
char *msgdata = (char *)p->data() + varying*datasize*i;
if (Val.typespec().is_closure()) {
// Retrieve the closure index from the PVL
int index = *(int *)msgdata;
ClosureColor *valclose = *(ClosureColor **) Val.data(i);
// then copy the closure (or clear it, if out of range)
if (index < (int)closure_msgs.size())
*valclose = closure_msgs.back();
else
valclose->clear ();
} else {
memcpy (Val.data(i), msgdata, datasize);
}
} else {
result[i] = 0; // not found
}
}
if (! varying)
break; // Non-uniform case can take early out
}
if (Val.has_derivs ())
exec->zero_derivs (Val);
}
}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009 Sony Pictures Imageworks, et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "oslops.h"
#include "oslexec_pvt.h"
#include "OpenImageIO/sysutil.h"
#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {
namespace { // anonymous
inline TextureOptions::Wrap
decode_wrap (ustring w)
{
if (w == Strings::black)
return TextureOptions::WrapBlack;
if (w == Strings::clamp)
return TextureOptions::WrapClamp;
if (w == Strings::periodic)
return TextureOptions::WrapPeriodic;
if (w == Strings::mirror)
return TextureOptions::WrapMirror;
return TextureOptions::WrapDefault;
}
}; // end anonymous namespace
DECLOP (OP_texture)
{
// Grab the required arguments: result, filename, s, t
DASSERT (nargs >= 4);
Symbol &Result (exec->sym (args[0]));
Symbol &Filename (exec->sym (args[1]));
DASSERT (Filename.typespec().is_string());
Symbol &S (exec->sym (args[2]));
Symbol &T (exec->sym (args[3]));
DASSERT (S.typespec().is_float() && T.typespec().is_float());
// Adjust the result's uniform/varying status
exec->adjust_varying (Result, true /* Assume texture always varies */);
// FIXME -- we should allow derivs of texture
if (Result.has_derivs ())
exec->zero_derivs (Result);
float zero = 0.0f;
VaryingRef<float> result ((float *)Result.data(), Result.step());
VaryingRef<float> s ((float *)S.data(), S.step());
VaryingRef<float> t ((float *)T.data(), T.step());
VaryingRef<ustring> filename ((ustring *)Filename.data(), Filename.step());
VaryingRef<ustring> swrap (NULL), twrap (NULL);
VaryingRef<int> firstchannel (NULL);
VaryingRef<float> alpha (NULL);
TextureSystem *texturesys = exec->texturesys ();
TextureOptions options;
options.firstchannel = 0;
options.nchannels = Result.typespec().simpletype().aggregate;
options.fill.init (&zero);
// Set up derivs
VaryingRef<float> dsdx, dsdy, dtdx, dtdy;
if (S.has_derivs()) {
dsdx.init ((float *)S.data() + 1, S.step());
dsdy.init ((float *)S.data() + 2, S.step());
} else {
dsdx.init (&zero);
dsdy.init (&zero);
}
if (T.has_derivs()) {
dtdx.init ((float *)T.data() + 1, T.step());
dtdy.init ((float *)T.data() + 2, T.step());
} else {
dtdx.init (&zero);
dtdy.init (&zero);
}
// Parse all the optional arguments
for (int a = 4; a < nargs; ++a) {
Symbol &Name (exec->sym (args[a]));
DASSERT (Name.typespec().is_string() &&
"optional texture token must be a string");
DASSERT (a+1 < nargs && "malformed argument list for texture");
if (Name.is_varying()) {
exec->warning ("optional texture argument is a varying string! Seems pretty fishy.");
}
++a; // advance to next argument
Symbol &Val (exec->sym (args[a]));
TypeDesc valtype = Val.typespec().simpletype ();
ustring name = * (ustring *) Name.data();
if (name == Strings::width && valtype == TypeDesc::FLOAT) {
options.swidth.init ((float *)Val.data(), Val.step());
options.twidth.init ((float *)Val.data(), Val.step());
} else if (name == Strings::swidth && valtype == TypeDesc::FLOAT) {
options.swidth.init ((float *)Val.data(), Val.step());
} else if (name == Strings::twidth && valtype == TypeDesc::FLOAT) {
options.twidth.init ((float *)Val.data(), Val.step());
} else if (name == Strings::blur && valtype == TypeDesc::FLOAT) {
options.sblur.init ((float *)Val.data(), Val.step());
options.tblur.init ((float *)Val.data(), Val.step());
} else if (name == Strings::sblur && valtype == TypeDesc::FLOAT) {
options.sblur.init ((float *)Val.data(), Val.step());
} else if (name == Strings::tblur && valtype == TypeDesc::FLOAT) {
options.tblur.init ((float *)Val.data(), Val.step());
} else if (name == Strings::wrap && valtype == TypeDesc::STRING) {
swrap.init ((ustring *)Val.data(), Val.step());
twrap.init ((ustring *)Val.data(), Val.step());
} else if (name == Strings::swrap && valtype == TypeDesc::STRING) {
swrap.init ((ustring *)Val.data(), Val.step());
} else if (name == Strings::twrap && valtype == TypeDesc::STRING) {
twrap.init ((ustring *)Val.data(), Val.step());
} else if (name == Strings::firstchannel && valtype == TypeDesc::INT) {
firstchannel.init ((int *)Val.data(), Val.step());
} else if (name == Strings::fill && valtype == TypeDesc::FLOAT) {
options.fill.init ((float *)Val.data(), Val.step());
} else if (name == Strings::alpha && valtype == TypeDesc::FLOAT) {
exec->adjust_varying (Val, true);
alpha.init ((float *)Val.data(), Val.step());
} else {
exec->error ("Unknown texture optional argument: \"%s\", <%s>",
name.c_str(), valtype.c_str());
}
}
if (alpha)
options.nchannels += 1;
float *r = &result[0];
bool tempresult = false;
if (Result.has_derivs() || alpha) {
tempresult = true;
r = ALLOCA (float, endpoint*options.nchannels);
}
for (int i = beginpoint; i < endpoint; ++i) {
// FIXME -- this calls texture system separately for each point!
// We really want to batch it into groups that share the same texture
// filename.
if (runflags[i]) {
if (swrap)
options.swrap = decode_wrap (swrap[i]);
if (twrap)
options.twrap = decode_wrap (twrap[i]);
if (firstchannel)
options.firstchannel = firstchannel[i];
bool ok = texturesys->texture (filename[i], options,
runflags, i /*beginpoint*/, i+1 /*endpoint*/,
s, t, dsdx, dtdx, dsdy, dtdy,
r);
if (! ok) {
std::string err = texturesys->geterror ();
if (err.length())
exec->error ("%s", err.c_str());
}
}
}
if (tempresult) {
// We need to re-copy results back to the right destinations.
int resultchans = Result.typespec().simpletype().aggregate;
for (int i = beginpoint; i < endpoint; ++i) {
if (runflags[i])
for (int c = 0; c < resultchans; ++c)
(&result[i])[c] = r[i*options.nchannels+c];
}
if (alpha) {
for (int i = beginpoint; i < endpoint; ++i)
if (runflags[i])
alpha[i] = r[i*options.nchannels+resultchans];
}
}
}
}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<commit_msg>Add texture derivatives (trac#22)<commit_after>/*
Copyright (c) 2009 Sony Pictures Imageworks, et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "oslops.h"
#include "oslexec_pvt.h"
#include "OpenImageIO/sysutil.h"
#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {
namespace { // anonymous
inline TextureOptions::Wrap
decode_wrap (ustring w)
{
if (w == Strings::black)
return TextureOptions::WrapBlack;
if (w == Strings::clamp)
return TextureOptions::WrapClamp;
if (w == Strings::periodic)
return TextureOptions::WrapPeriodic;
if (w == Strings::mirror)
return TextureOptions::WrapMirror;
return TextureOptions::WrapDefault;
}
}; // end anonymous namespace
DECLOP (OP_texture)
{
// Grab the required arguments: result, filename, s, t
DASSERT (nargs >= 4);
Symbol &Result (exec->sym (args[0]));
Symbol &Filename (exec->sym (args[1]));
DASSERT (Filename.typespec().is_string());
Symbol &S (exec->sym (args[2]));
Symbol &T (exec->sym (args[3]));
DASSERT (S.typespec().is_float() && T.typespec().is_float());
// Adjust the result's uniform/varying status
exec->adjust_varying (Result, true /* Assume texture always varies */);
float zero = 0.0f;
VaryingRef<float> result ((float *)Result.data(), Result.step());
VaryingRef<float> s ((float *)S.data(), S.step());
VaryingRef<float> t ((float *)T.data(), T.step());
VaryingRef<ustring> filename ((ustring *)Filename.data(), Filename.step());
VaryingRef<ustring> swrap (NULL), twrap (NULL);
VaryingRef<int> firstchannel (NULL);
VaryingRef<float> alpha (NULL);
Symbol* Alpha = NULL;
TextureSystem *texturesys = exec->texturesys ();
TextureOptions options;
options.firstchannel = 0;
options.nchannels = Result.typespec().simpletype().aggregate;
options.fill.init (&zero);
// Set up derivs
VaryingRef<float> dsdx, dsdy, dtdx, dtdy;
if (S.has_derivs()) {
dsdx.init ((float *)S.data() + 1, S.step());
dsdy.init ((float *)S.data() + 2, S.step());
} else {
dsdx.init (&zero);
dsdy.init (&zero);
}
if (T.has_derivs()) {
dtdx.init ((float *)T.data() + 1, T.step());
dtdy.init ((float *)T.data() + 2, T.step());
} else {
dtdx.init (&zero);
dtdy.init (&zero);
}
// Parse all the optional arguments
for (int a = 4; a < nargs; ++a) {
Symbol &Name (exec->sym (args[a]));
DASSERT (Name.typespec().is_string() &&
"optional texture token must be a string");
DASSERT (a+1 < nargs && "malformed argument list for texture");
if (Name.is_varying()) {
exec->warning ("optional texture argument is a varying string! Seems pretty fishy.");
}
++a; // advance to next argument
Symbol &Val (exec->sym (args[a]));
TypeDesc valtype = Val.typespec().simpletype ();
ustring name = * (ustring *) Name.data();
if (name == Strings::width && valtype == TypeDesc::FLOAT) {
options.swidth.init ((float *)Val.data(), Val.step());
options.twidth.init ((float *)Val.data(), Val.step());
} else if (name == Strings::swidth && valtype == TypeDesc::FLOAT) {
options.swidth.init ((float *)Val.data(), Val.step());
} else if (name == Strings::twidth && valtype == TypeDesc::FLOAT) {
options.twidth.init ((float *)Val.data(), Val.step());
} else if (name == Strings::blur && valtype == TypeDesc::FLOAT) {
options.sblur.init ((float *)Val.data(), Val.step());
options.tblur.init ((float *)Val.data(), Val.step());
} else if (name == Strings::sblur && valtype == TypeDesc::FLOAT) {
options.sblur.init ((float *)Val.data(), Val.step());
} else if (name == Strings::tblur && valtype == TypeDesc::FLOAT) {
options.tblur.init ((float *)Val.data(), Val.step());
} else if (name == Strings::wrap && valtype == TypeDesc::STRING) {
swrap.init ((ustring *)Val.data(), Val.step());
twrap.init ((ustring *)Val.data(), Val.step());
} else if (name == Strings::swrap && valtype == TypeDesc::STRING) {
swrap.init ((ustring *)Val.data(), Val.step());
} else if (name == Strings::twrap && valtype == TypeDesc::STRING) {
twrap.init ((ustring *)Val.data(), Val.step());
} else if (name == Strings::firstchannel && valtype == TypeDesc::INT) {
firstchannel.init ((int *)Val.data(), Val.step());
} else if (name == Strings::fill && valtype == TypeDesc::FLOAT) {
options.fill.init ((float *)Val.data(), Val.step());
} else if (name == Strings::alpha && valtype == TypeDesc::FLOAT) {
exec->adjust_varying (Val, true);
alpha.init ((float *)Val.data(), Val.step());
Alpha = &Val;
} else {
exec->error ("Unknown texture optional argument: \"%s\", <%s>",
name.c_str(), valtype.c_str());
}
}
if (alpha)
options.nchannels += 1;
float *r = &result[0];
bool tempresult = false;
if (Result.has_derivs() || alpha) {
tempresult = true;
r = ALLOCA (float, endpoint*options.nchannels);
// allocate some space to track the derivatives of the result
// NOTE: even though OIIO doesn't need derivatives from S and T to
// compute the gradients, we need them on the OSL side to be able to
// rotate the gradients via the chain rule
if (S.has_derivs() && T.has_derivs()) {
options.dresultds = ALLOCA (float, endpoint*options.nchannels);
options.dresultdt = ALLOCA (float, endpoint*options.nchannels);
} else {
// we won't be able to provide derivatives properly
if (Result.has_derivs())
exec->zero_derivs(Result);
if (Alpha && Alpha->has_derivs())
exec->zero_derivs(*Alpha);
}
}
for (int i = beginpoint; i < endpoint; ++i) {
// FIXME -- this calls texture system separately for each point!
// We really want to batch it into groups that share the same texture
// filename.
if (runflags[i]) {
if (swrap)
options.swrap = decode_wrap (swrap[i]);
if (twrap)
options.twrap = decode_wrap (twrap[i]);
if (firstchannel)
options.firstchannel = firstchannel[i];
bool ok = texturesys->texture (filename[i], options,
runflags, i /*beginpoint*/, i+1 /*endpoint*/,
s, t, dsdx, dtdx, dsdy, dtdy,
r);
if (! ok) {
std::string err = texturesys->geterror ();
if (err.length())
exec->error ("%s", err.c_str());
}
}
}
if (tempresult) {
// We need to re-copy results back to the right destinations.
int resultchans = Result.typespec().simpletype().aggregate;
for (int i = beginpoint; i < endpoint; ++i) {
if (runflags[i])
for (int c = 0; c < resultchans; ++c)
(&result[i])[c] = r[i*options.nchannels+c];
}
if (alpha) {
for (int i = beginpoint; i < endpoint; ++i)
if (runflags[i])
alpha[i] = r[i*options.nchannels+resultchans];
}
// now figure out derivatives (as needed)
// we use the multi-variate chain rule:
// dTdx = dTds * dsdx + dTdt * dtdx
// dTdy = dTds * dsdy + dTdt * dtdy
if (options.dresultds) {
for (int i = beginpoint; i < endpoint; ++i) {
if (runflags[i]) {
for (int c = 0; c < resultchans; ++c) {
(&result[i])[1 * resultchans + c] = options.dresultds[i*options.nchannels+c] * dsdx[i] + options.dresultdt[i*options.nchannels+c] * dtdx[i];
(&result[i])[2 * resultchans + c] = options.dresultds[i*options.nchannels+c] * dsdy[i] + options.dresultdt[i*options.nchannels+c] * dtdy[i];
}
if (alpha) {
(&alpha[i])[1] = options.dresultds[i*options.nchannels+resultchans] * dsdx[i] + options.dresultdt[i*options.nchannels+resultchans] * dtdx[i];
(&alpha[i])[2] = options.dresultds[i*options.nchannels+resultchans] * dsdy[i] + options.dresultdt[i*options.nchannels+resultchans] * dtdy[i];
}
}
}
}
}
}
}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<|endoftext|> |
<commit_before>
/*
* This file is part of cryptopp-bindings-api.
*
* (c) Stephen Berquet <stephen.berquet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "api_mac_abstract.h"
NAMESPACE_BEGIN(CryptoppApi)
MacAbstract::MacAbstract()
: m_mac(NULL)
, m_name(NULL)
{
}
const char *MacAbstract::getName() const
{
return m_name;
}
void MacAbstract::setCryptoppObject(CryptoPP::MessageAuthenticationCode *mac)
{
m_mac = mac;
}
bool MacAbstract::isValidKeyLength(size_t length) const
{
return m_mac->IsValidKeyLength(length);
}
void MacAbstract::setKey(const byte *key, const size_t keyLength)
{
SymmetricKeyAbstract::setKey(key, keyLength);
m_mac->SetKey(key, keyLength);
}
void MacAbstract::setName(const std::string name)
{
m_name = const_cast<char*>(name.c_str());
}
const char *BlockCipherAbstract::getName() const
{
return m_name;
}
size_t MacAbstract::getDigestSize() const
{
return m_mac->DigestSize();
}
size_t MacAbstract::getBlockSize() const
{
return m_mac->BlockSize();
}
void MacAbstract::calculateDigest(byte *input, size_t inputLength, byte *output)
{
m_mac->CalculateDigest(output, input, inputLength);
}
void MacAbstract::update(byte *input, size_t inputLength)
{
m_mac->Update(input, inputLength);
}
void MacAbstract::finalize(byte *output)
{
m_mac->Final(output);
}
void MacAbstract::restart()
{
m_mac->Restart();
}
NAMESPACE_END
<commit_msg>mac abstract: removed unnecessary method<commit_after>
/*
* This file is part of cryptopp-bindings-api.
*
* (c) Stephen Berquet <stephen.berquet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "api_mac_abstract.h"
NAMESPACE_BEGIN(CryptoppApi)
MacAbstract::MacAbstract()
: m_mac(NULL)
, m_name(NULL)
{
}
const char *MacAbstract::getName() const
{
return m_name;
}
void MacAbstract::setCryptoppObject(CryptoPP::MessageAuthenticationCode *mac)
{
m_mac = mac;
}
bool MacAbstract::isValidKeyLength(size_t length) const
{
return m_mac->IsValidKeyLength(length);
}
void MacAbstract::setKey(const byte *key, const size_t keyLength)
{
SymmetricKeyAbstract::setKey(key, keyLength);
m_mac->SetKey(key, keyLength);
}
void MacAbstract::setName(const std::string name)
{
m_name = const_cast<char*>(name.c_str());
}
size_t MacAbstract::getDigestSize() const
{
return m_mac->DigestSize();
}
size_t MacAbstract::getBlockSize() const
{
return m_mac->BlockSize();
}
void MacAbstract::calculateDigest(byte *input, size_t inputLength, byte *output)
{
m_mac->CalculateDigest(output, input, inputLength);
}
void MacAbstract::update(byte *input, size_t inputLength)
{
m_mac->Update(input, inputLength);
}
void MacAbstract::finalize(byte *output)
{
m_mac->Final(output);
}
void MacAbstract::restart()
{
m_mac->Restart();
}
NAMESPACE_END
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <google/dense_hash_set>
#include <locale>
#include <list>
#include <iostream>
#include <string>
#include <re2/re2.h>
#include "smart_git.h"
#include "timer.h"
using google::dense_hash_set;
using re2::RE2;
using re2::StringPiece;
using namespace std;
#define CHUNK_SIZE (1 << 20)
struct search_file {
string path;
const char *ref;
git_oid oid;
};
struct chunk_file {
search_file *file;
unsigned int left;
unsigned int right;
};
#define CHUNK_MAGIC 0xC407FADE
struct chunk {
int size;
unsigned magic;
vector<chunk_file> files;
char data[0];
chunk()
: size(0), magic(CHUNK_MAGIC), files() {
}
void add_chunk_file(search_file *sf, const StringPiece &line) {
unsigned l = line.data() - data;
unsigned r = l + line.size();
if (files.empty() || files.back().file != sf) {
files.push_back(chunk_file());
chunk_file &cf = files.back();
cf.file = sf;
cf.left = l;
cf.right = r;
} else {
chunk_file &cf = files.back();
cf.left = min(l, cf.left);
cf.right = max(r, cf.right);
}
}
};
#define CHUNK_SPACE (CHUNK_SIZE - (sizeof(chunk)))
chunk *alloc_chunk() {
void *p;
if (posix_memalign(&p, CHUNK_SIZE, CHUNK_SIZE) != 0)
return NULL;
return new(p) chunk;
};
class chunk_allocator {
public:
chunk_allocator() : current_() {
new_chunk();
}
char *alloc(size_t len) {
assert(len < CHUNK_SPACE);
if ((current_->size + len) > CHUNK_SPACE)
new_chunk();
char *out = current_->data + current_->size;
current_->size += len;
return out;
}
list<chunk*>::iterator begin () {
return chunks_.begin();
}
typename list<chunk*>::iterator end () {
return chunks_.end();
}
chunk *current_chunk() {
return current_;
}
protected:
void new_chunk() {
current_ = alloc_chunk();
chunks_.push_back(current_);
}
list<chunk*> chunks_;
chunk *current_;
};
/*
* We special-case data() == NULL to provide an "empty" element for
* dense_hash_set.
*
* StringPiece::operator== will consider a zero-length string equal to a
* zero-length string with a NULL data().
*/
struct eqstr {
bool operator()(const StringPiece& lhs, const StringPiece& rhs) const {
if (lhs.data() == NULL && rhs.data() == NULL)
return true;
if (lhs.data() == NULL || rhs.data() == NULL)
return false;
return lhs == rhs;
}
};
struct hashstr {
locale loc;
size_t operator()(const StringPiece &str) const {
const collate<char> &coll = use_facet<collate<char> >(loc);
return coll.hash(str.data(), str.data() + str.size());
}
};
const StringPiece empty_string(NULL, 0);
typedef dense_hash_set<StringPiece, hashstr, eqstr> string_hash;
class code_counter {
public:
code_counter(git_repository *repo)
: repo_(repo), stats_()
{
lines_.set_empty_key(empty_string);
}
void walk_ref(const char *ref) {
smart_object<git_commit> commit;
smart_object<git_tree> tree;
resolve_ref(commit, ref);
git_commit_tree(tree, commit);
walk_tree(ref, "", tree);
}
void dump_stats() {
printf("Bytes: %ld (dedup: %ld)\n", stats_.bytes, stats_.dedup_bytes);
printf("Lines: %ld (dedup: %ld)\n", stats_.lines, stats_.dedup_lines);
}
bool match(RE2& pat) {
list<chunk*>::iterator it;
StringPiece match;
int matches = 0;
for (it = alloc_.begin(); it != alloc_.end(); it++) {
StringPiece str((*it)->data, (*it)->size);
int pos = 0;
while (pos < str.size()) {
if (!pat.Match(str, pos, str.size(), RE2::UNANCHORED, &match, 1))
break;
assert(memchr(match.data(), '\n', match.size()) == NULL);
StringPiece line = find_line(str, match);
print_match(line);
pos = line.size() + line.data() - str.data();
if (++matches == 10)
return true;
}
}
return matches > 0;
}
protected:
void print_match (const StringPiece& line) {
chunk *c = find_chunk(line.data());
unsigned int off = line.data() - c->data;
int lno;
int matches = 0;
for(vector<chunk_file>::iterator it = c->files.begin();
it != c->files.end(); it++) {
if (off >= it->left && off < it->right) {
lno = try_match(line, it->file);
if (lno > 0) {
printf("%s:%s:%d: %.*s\n",
it->file->ref,
it->file->path.c_str(),
lno,
line.size(), line.data());
if (++matches == 10)
break;
}
}
}
}
int try_match(const StringPiece &line, search_file *sf) {
smart_object<git_blob> blob;
git_blob_lookup(blob, repo_, &sf->oid);
int pos;
StringPiece search(static_cast<const char*>(git_blob_rawcontent(blob)),
git_blob_rawsize(blob));
pos = search.find(line);
if (pos == StringPiece::npos) {
return 0;
}
return 1 + count(search.data(), search.data() + pos, '\n');
}
StringPiece find_line(const StringPiece& chunk, const StringPiece& match) {
const char *start, *end;
assert(match.data() >= chunk.data());
assert(match.data() < chunk.data() + chunk.size());
assert(match.size() < (chunk.size() - (match.data() - chunk.data())));
start = static_cast<const char*>
(memrchr(chunk.data(), '\n', match.data() - chunk.data()));
if (start == NULL)
start = chunk.data();
else
start++;
end = static_cast<const char*>
(memchr(match.data() + match.size(), '\n',
chunk.size() - (match.data() - chunk.data()) - match.size()));
if (end == NULL)
end = chunk.data() + chunk.size();
return StringPiece(start, end - start);
}
void walk_tree(const char *ref, const string& pfx, git_tree *tree) {
string path;
int entries = git_tree_entrycount(tree);
int i;
for (i = 0; i < entries; i++) {
const git_tree_entry *ent = git_tree_entry_byindex(tree, i);
path = pfx + git_tree_entry_name(ent);
smart_object<git_object> obj;
git_tree_entry_2object(obj, repo_, ent);
if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {
walk_tree(ref, path + "/", obj);
} else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {
update_stats(ref, path, obj);
}
}
}
chunk* find_chunk(const char *p) {
chunk *out = reinterpret_cast<chunk*>
(reinterpret_cast<uintptr_t>(p) & ~(CHUNK_SIZE - 1));
assert(out->magic == CHUNK_MAGIC);
return out;
}
void update_stats(const char *ref, const string& path, git_blob *blob) {
size_t len = git_blob_rawsize(blob);
const char *p = static_cast<const char*>(git_blob_rawcontent(blob));
const char *end = p + len;
const char *f;
string_hash::iterator it;
search_file *sf = new search_file;
sf->path = path;
sf->ref = ref;
git_oid_cpy(&sf->oid, git_object_id(reinterpret_cast<git_object*>(blob)));
chunk *c;
StringPiece line;
while ((f = static_cast<const char*>(memchr(p, '\n', end - p))) != 0) {
it = lines_.find(StringPiece(p, f - p));
if (it == lines_.end()) {
stats_.dedup_bytes += (f - p) + 1;
stats_.dedup_lines ++;
// Include the trailing '\n' in the chunk buffer
char *alloc = alloc_.alloc(f - p + 1);
memcpy(alloc, p, f - p + 1);
line = StringPiece(alloc, f - p);
lines_.insert(line);
c = alloc_.current_chunk();
} else {
line = *it;
c = find_chunk(line.data());
}
c->add_chunk_file(sf, line);
p = f + 1;
stats_.lines++;
}
stats_.bytes += len;
}
void resolve_ref(smart_object<git_commit> &out, const char *refname) {
git_reference *ref;
const git_oid *oid;
git_oid tmp;
smart_object<git_object> obj;
if (git_oid_fromstr(&tmp, refname) == GIT_SUCCESS) {
git_object_lookup(obj, repo_, &tmp, GIT_OBJ_ANY);
} else {
git_reference_lookup(&ref, repo_, refname);
git_reference_resolve(&ref, ref);
oid = git_reference_oid(ref);
git_object_lookup(obj, repo_, oid, GIT_OBJ_ANY);
}
if (git_object_type(obj) == GIT_OBJ_TAG) {
git_tag_target(out, obj);
} else {
out = obj.release();
}
}
git_repository *repo_;
string_hash lines_;
struct {
unsigned long bytes, dedup_bytes;
unsigned long lines, dedup_lines;
} stats_;
chunk_allocator alloc_;
};
int main(int argc, char **argv) {
git_repository *repo;
git_repository_open(&repo, ".git");
code_counter counter(repo);
for (int i = 1; i < argc; i++) {
timer tm;
struct timeval elapsed;
printf("Walking %s...", argv[i]);
fflush(stdout);
counter.walk_ref(argv[i]);
elapsed = tm.elapsed();
printf(" done in %d.%06ds\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
counter.dump_stats();
RE2::Options opts;
opts.set_never_nl(true);
opts.set_one_line(false);
opts.set_posix_syntax(true);
while (true) {
printf("regex> ");
string line;
getline(cin, line);
if (cin.eof())
break;
RE2 re(line, opts);
if (re.ok()) {
timer tm;
struct timeval elapsed;
if (!counter.match(re)) {
printf("no match\n");
}
elapsed = tm.elapsed();
printf("Match completed in %d.%06ds.\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
}
return 0;
}
<commit_msg>Shrink CHUNK_SIZE.<commit_after>#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <google/dense_hash_set>
#include <locale>
#include <list>
#include <iostream>
#include <string>
#include <re2/re2.h>
#include "smart_git.h"
#include "timer.h"
using google::dense_hash_set;
using re2::RE2;
using re2::StringPiece;
using namespace std;
#define CHUNK_SIZE (1 << 16)
struct search_file {
string path;
const char *ref;
git_oid oid;
};
struct chunk_file {
search_file *file;
unsigned int left;
unsigned int right;
};
#define CHUNK_MAGIC 0xC407FADE
struct chunk {
int size;
unsigned magic;
vector<chunk_file> files;
char data[0];
chunk()
: size(0), magic(CHUNK_MAGIC), files() {
}
void add_chunk_file(search_file *sf, const StringPiece &line) {
unsigned l = line.data() - data;
unsigned r = l + line.size();
if (files.empty() || files.back().file != sf) {
files.push_back(chunk_file());
chunk_file &cf = files.back();
cf.file = sf;
cf.left = l;
cf.right = r;
} else {
chunk_file &cf = files.back();
cf.left = min(l, cf.left);
cf.right = max(r, cf.right);
}
}
};
#define CHUNK_SPACE (CHUNK_SIZE - (sizeof(chunk)))
chunk *alloc_chunk() {
void *p;
if (posix_memalign(&p, CHUNK_SIZE, CHUNK_SIZE) != 0)
return NULL;
return new(p) chunk;
};
class chunk_allocator {
public:
chunk_allocator() : current_() {
new_chunk();
}
char *alloc(size_t len) {
assert(len < CHUNK_SPACE);
if ((current_->size + len) > CHUNK_SPACE)
new_chunk();
char *out = current_->data + current_->size;
current_->size += len;
return out;
}
list<chunk*>::iterator begin () {
return chunks_.begin();
}
typename list<chunk*>::iterator end () {
return chunks_.end();
}
chunk *current_chunk() {
return current_;
}
protected:
void new_chunk() {
current_ = alloc_chunk();
chunks_.push_back(current_);
}
list<chunk*> chunks_;
chunk *current_;
};
/*
* We special-case data() == NULL to provide an "empty" element for
* dense_hash_set.
*
* StringPiece::operator== will consider a zero-length string equal to a
* zero-length string with a NULL data().
*/
struct eqstr {
bool operator()(const StringPiece& lhs, const StringPiece& rhs) const {
if (lhs.data() == NULL && rhs.data() == NULL)
return true;
if (lhs.data() == NULL || rhs.data() == NULL)
return false;
return lhs == rhs;
}
};
struct hashstr {
locale loc;
size_t operator()(const StringPiece &str) const {
const collate<char> &coll = use_facet<collate<char> >(loc);
return coll.hash(str.data(), str.data() + str.size());
}
};
const StringPiece empty_string(NULL, 0);
typedef dense_hash_set<StringPiece, hashstr, eqstr> string_hash;
class code_counter {
public:
code_counter(git_repository *repo)
: repo_(repo), stats_()
{
lines_.set_empty_key(empty_string);
}
void walk_ref(const char *ref) {
smart_object<git_commit> commit;
smart_object<git_tree> tree;
resolve_ref(commit, ref);
git_commit_tree(tree, commit);
walk_tree(ref, "", tree);
}
void dump_stats() {
printf("Bytes: %ld (dedup: %ld)\n", stats_.bytes, stats_.dedup_bytes);
printf("Lines: %ld (dedup: %ld)\n", stats_.lines, stats_.dedup_lines);
}
bool match(RE2& pat) {
list<chunk*>::iterator it;
StringPiece match;
int matches = 0;
for (it = alloc_.begin(); it != alloc_.end(); it++) {
StringPiece str((*it)->data, (*it)->size);
int pos = 0;
while (pos < str.size()) {
if (!pat.Match(str, pos, str.size(), RE2::UNANCHORED, &match, 1))
break;
assert(memchr(match.data(), '\n', match.size()) == NULL);
StringPiece line = find_line(str, match);
print_match(line);
pos = line.size() + line.data() - str.data();
if (++matches == 10)
return true;
}
}
return matches > 0;
}
protected:
void print_match (const StringPiece& line) {
chunk *c = find_chunk(line.data());
unsigned int off = line.data() - c->data;
int lno;
int matches = 0;
for(vector<chunk_file>::iterator it = c->files.begin();
it != c->files.end(); it++) {
if (off >= it->left && off < it->right) {
lno = try_match(line, it->file);
if (lno > 0) {
printf("%s:%s:%d: %.*s\n",
it->file->ref,
it->file->path.c_str(),
lno,
line.size(), line.data());
if (++matches == 10)
break;
}
}
}
}
int try_match(const StringPiece &line, search_file *sf) {
smart_object<git_blob> blob;
git_blob_lookup(blob, repo_, &sf->oid);
int pos;
StringPiece search(static_cast<const char*>(git_blob_rawcontent(blob)),
git_blob_rawsize(blob));
pos = search.find(line);
if (pos == StringPiece::npos) {
return 0;
}
return 1 + count(search.data(), search.data() + pos, '\n');
}
StringPiece find_line(const StringPiece& chunk, const StringPiece& match) {
const char *start, *end;
assert(match.data() >= chunk.data());
assert(match.data() < chunk.data() + chunk.size());
assert(match.size() < (chunk.size() - (match.data() - chunk.data())));
start = static_cast<const char*>
(memrchr(chunk.data(), '\n', match.data() - chunk.data()));
if (start == NULL)
start = chunk.data();
else
start++;
end = static_cast<const char*>
(memchr(match.data() + match.size(), '\n',
chunk.size() - (match.data() - chunk.data()) - match.size()));
if (end == NULL)
end = chunk.data() + chunk.size();
return StringPiece(start, end - start);
}
void walk_tree(const char *ref, const string& pfx, git_tree *tree) {
string path;
int entries = git_tree_entrycount(tree);
int i;
for (i = 0; i < entries; i++) {
const git_tree_entry *ent = git_tree_entry_byindex(tree, i);
path = pfx + git_tree_entry_name(ent);
smart_object<git_object> obj;
git_tree_entry_2object(obj, repo_, ent);
if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {
walk_tree(ref, path + "/", obj);
} else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {
update_stats(ref, path, obj);
}
}
}
chunk* find_chunk(const char *p) {
chunk *out = reinterpret_cast<chunk*>
(reinterpret_cast<uintptr_t>(p) & ~(CHUNK_SIZE - 1));
assert(out->magic == CHUNK_MAGIC);
return out;
}
void update_stats(const char *ref, const string& path, git_blob *blob) {
size_t len = git_blob_rawsize(blob);
const char *p = static_cast<const char*>(git_blob_rawcontent(blob));
const char *end = p + len;
const char *f;
string_hash::iterator it;
search_file *sf = new search_file;
sf->path = path;
sf->ref = ref;
git_oid_cpy(&sf->oid, git_object_id(reinterpret_cast<git_object*>(blob)));
chunk *c;
StringPiece line;
while ((f = static_cast<const char*>(memchr(p, '\n', end - p))) != 0) {
it = lines_.find(StringPiece(p, f - p));
if (it == lines_.end()) {
stats_.dedup_bytes += (f - p) + 1;
stats_.dedup_lines ++;
// Include the trailing '\n' in the chunk buffer
char *alloc = alloc_.alloc(f - p + 1);
memcpy(alloc, p, f - p + 1);
line = StringPiece(alloc, f - p);
lines_.insert(line);
c = alloc_.current_chunk();
} else {
line = *it;
c = find_chunk(line.data());
}
c->add_chunk_file(sf, line);
p = f + 1;
stats_.lines++;
}
stats_.bytes += len;
}
void resolve_ref(smart_object<git_commit> &out, const char *refname) {
git_reference *ref;
const git_oid *oid;
git_oid tmp;
smart_object<git_object> obj;
if (git_oid_fromstr(&tmp, refname) == GIT_SUCCESS) {
git_object_lookup(obj, repo_, &tmp, GIT_OBJ_ANY);
} else {
git_reference_lookup(&ref, repo_, refname);
git_reference_resolve(&ref, ref);
oid = git_reference_oid(ref);
git_object_lookup(obj, repo_, oid, GIT_OBJ_ANY);
}
if (git_object_type(obj) == GIT_OBJ_TAG) {
git_tag_target(out, obj);
} else {
out = obj.release();
}
}
git_repository *repo_;
string_hash lines_;
struct {
unsigned long bytes, dedup_bytes;
unsigned long lines, dedup_lines;
} stats_;
chunk_allocator alloc_;
};
int main(int argc, char **argv) {
git_repository *repo;
git_repository_open(&repo, ".git");
code_counter counter(repo);
for (int i = 1; i < argc; i++) {
timer tm;
struct timeval elapsed;
printf("Walking %s...", argv[i]);
fflush(stdout);
counter.walk_ref(argv[i]);
elapsed = tm.elapsed();
printf(" done in %d.%06ds\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
counter.dump_stats();
RE2::Options opts;
opts.set_never_nl(true);
opts.set_one_line(false);
opts.set_posix_syntax(true);
while (true) {
printf("regex> ");
string line;
getline(cin, line);
if (cin.eof())
break;
RE2 re(line, opts);
if (re.ok()) {
timer tm;
struct timeval elapsed;
if (!counter.match(re)) {
printf("no match\n");
}
elapsed = tm.elapsed();
printf("Match completed in %d.%06ds.\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
}
return 0;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#include "Basics/win-utils.h"
#endif
#include "Scheduler.h"
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
#include "Basics/MutexLocker.h"
#include "Basics/StringUtils.h"
#include "Basics/Thread.h"
#include "Logger/Logger.h"
#include "Rest/GeneralResponse.h"
#include "Scheduler/JobQueue.h"
#include "Scheduler/Task.h"
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
// -----------------------------------------------------------------------------
// --SECTION-- SchedulerManagerThread
// -----------------------------------------------------------------------------
namespace {
class SchedulerManagerThread : public Thread {
public:
SchedulerManagerThread(Scheduler* scheduler, boost::asio::io_service* service)
: Thread("SchedulerManager"), _scheduler(scheduler), _service(service) {}
~SchedulerManagerThread() { shutdown(); }
public:
void run() {
while (!_scheduler->isStopping()) {
try {
_service->run_one();
_scheduler->deleteOldThreads();
} catch (...) {
LOG_TOPIC(ERR, Logger::THREADS)
<< "manager loop caught an error, restarting";
}
}
_scheduler->threadDone(this);
}
private:
Scheduler* _scheduler;
boost::asio::io_service* _service;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- SchedulerThread
// -----------------------------------------------------------------------------
namespace {
class SchedulerThread : public Thread {
public:
SchedulerThread(Scheduler* scheduler, boost::asio::io_service* service)
: Thread("Scheduler"), _scheduler(scheduler), _service(service) {}
~SchedulerThread() { shutdown(); }
public:
void run() {
_scheduler->incRunning();
LOG_TOPIC(DEBUG, Logger::THREADS) << "running (" << _scheduler->infoStatus()
<< ")";
auto start = std::chrono::steady_clock::now();
try {
static size_t EVERY_LOOP = 1000;
static double MIN_SECONDS = 30;
size_t counter = 0;
while (!_scheduler->isStopping()) {
_service->run_one();
if (++counter > EVERY_LOOP) {
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> diff = now - start;
if (diff.count() > MIN_SECONDS) {
if (_scheduler->stopThread()) {
auto n = _scheduler->decRunning();
if (n <= 2) {
_scheduler->incRunning();
} else {
break;
}
}
start = std::chrono::steady_clock::now();
}
}
}
LOG_TOPIC(DEBUG, Logger::THREADS) << "stopped ("
<< _scheduler->infoStatus() << ")";
} catch (...) {
LOG_TOPIC(ERR, Logger::THREADS)
<< "scheduler loop caught an error, restarting";
_scheduler->decRunning();
_scheduler->startNewThread();
}
_scheduler->threadDone(this);
}
private:
Scheduler* _scheduler;
boost::asio::io_service* _service;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- Scheduler
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
Scheduler::Scheduler(size_t nrThreads, size_t maxQueueSize)
: _nrThreads(nrThreads),
_maxQueueSize(maxQueueSize),
_stopping(false),
_nrBusy(0),
_nrWorking(0),
_nrBlocked(0),
_nrRunning(0),
_nrMinimal(0),
_nrMaximal(0),
_nrRealMaximum(0),
_lastThreadWarning(0) {
// setup signal handlers
initializeSignalHandlers();
}
Scheduler::~Scheduler() { deleteOldThreads(); }
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
bool Scheduler::start(ConditionVariable* cv) {
// start the I/O
startIoService();
// initialize thread handling
if (_nrMaximal <= 0) {
_nrMaximal = _nrThreads;
}
if (_nrRealMaximum <= 0) {
_nrRealMaximum = 4 * _nrMaximal;
}
for (size_t i = 0; i < 2; ++i) {
startNewThread();
}
startManagerThread();
startRebalancer();
// initialize the queue handling
_jobQueue.reset(new JobQueue(_maxQueueSize, _ioService.get()));
_jobQueue->start();
// done
LOG(TRACE) << "all scheduler threads are up and running";
return true;
}
void Scheduler::startIoService() {
_ioService.reset(new boost::asio::io_service());
_serviceGuard.reset(new boost::asio::io_service::work(*_ioService));
_managerService.reset(new boost::asio::io_service());
_managerGuard.reset(new boost::asio::io_service::work(*_managerService));
}
void Scheduler::startRebalancer() {
std::chrono::milliseconds interval(500);
_threadManager.reset(new boost::asio::steady_timer(*_managerService));
_threadHandler = [this, interval](const boost::system::error_code& error) {
if (error || isStopping()) {
return;
}
rebalanceThreads();
_threadManager->expires_from_now(interval);
_threadManager->async_wait(_threadHandler);
};
_threadManager->expires_from_now(interval);
_threadManager->async_wait(_threadHandler);
_lastThreadWarning.store(TRI_microtime());
}
void Scheduler::startManagerThread() {
MUTEX_LOCKER(guard, _threadsLock);
auto thread = new SchedulerManagerThread(this, _managerService.get());
_threads.emplace(thread);
thread->start();
}
void Scheduler::startNewThread() {
MUTEX_LOCKER(guard, _threadsLock);
auto thread = new SchedulerThread(this, _ioService.get());
_threads.emplace(thread);
thread->start();
}
bool Scheduler::stopThread() {
if (_nrRunning <= _nrMinimal) {
return false;
}
if (_nrRunning >= 3) {
int64_t low = ((_nrRunning <= 4) ? 0 : (_nrRunning * 1 / 4)) - _nrBlocked;
if (_nrBusy <= low && _nrWorking <= low) {
return true;
}
}
return false;
}
void Scheduler::threadDone(Thread* thread) {
MUTEX_LOCKER(guard, _threadsLock);
_threads.erase(thread);
_deadThreads.insert(thread);
}
void Scheduler::deleteOldThreads() {
// delete old thread objects
std::unordered_set<Thread*> deadThreads;
{
MUTEX_LOCKER(guard, _threadsLock);
if (_deadThreads.empty()) {
return;
}
deadThreads.swap(_deadThreads);
}
for (auto thread : deadThreads) {
try {
delete thread;
} catch (...) {
LOG_TOPIC(ERR, Logger::THREADS) << "cannot delete thread";
}
}
}
void Scheduler::rebalanceThreads() {
static double const MIN_WARN_INTERVAL = 10;
static double const MIN_ERR_INTERVAL = 300;
int64_t high = (_nrRunning <= 4) ? 1 : (_nrRunning * 11 / 16);
int64_t working = (_nrBusy > _nrWorking) ? _nrBusy : _nrWorking;
LOG_TOPIC(DEBUG, Logger::THREADS) << "rebalancing threads, high: " << high
<< ", working: " << working << " ("
<< infoStatus() << ")";
if (working >= high) {
if (_nrRunning < _nrMaximal + _nrBlocked &&
_nrRunning < _nrRealMaximal) { // added by Max 22.12.2016
// otherwise we exceed the total maximum
startNewThread();
return;
}
}
if (working >= _nrMaximal + _nrBlocked || _nrRunning < _nrMinimal) {
double ltw = _lastThreadWarning.load();
double now = TRI_microtime();
if (_nrRunning >= _nrRealMaximum) {
if (ltw - now > MIN_ERR_INTERVAL) {
LOG_TOPIC(ERR, Logger::THREADS) << "too many threads (" << infoStatus()
<< ")";
_lastThreadWarning.store(now);
}
} else {
if (_nrRunning >= _nrRealMaximum * 3 / 4) {
if (ltw - now > MIN_WARN_INTERVAL) {
LOG_TOPIC(WARN, Logger::THREADS)
<< "number of threads is reaching a critical limit ("
<< infoStatus() << ")";
_lastThreadWarning.store(now);
}
}
LOG_TOPIC(DEBUG, Logger::THREADS) << "overloading threads ("
<< infoStatus() << ")";
startNewThread();
}
}
}
void Scheduler::beginShutdown() {
if (_stopping) {
return;
}
_jobQueue->beginShutdown();
_threadManager.reset();
_managerGuard.reset();
_managerService->stop();
_serviceGuard.reset();
_ioService->stop();
// set the flag AFTER stopping the threads
_stopping = true;
}
void Scheduler::shutdown() {
bool done = false;
while (!done) {
MUTEX_LOCKER(guard, _threadsLock);
done = _threads.empty();
}
deleteOldThreads();
_managerService.reset();
_ioService.reset();
}
void Scheduler::initializeSignalHandlers() {
#ifdef _WIN32
// Windows does not support POSIX signal handling
#else
struct sigaction action;
memset(&action, 0, sizeof(action));
sigfillset(&action.sa_mask);
// ignore broken pipes
action.sa_handler = SIG_IGN;
int res = sigaction(SIGPIPE, &action, 0);
if (res < 0) {
LOG(ERR) << "cannot initialize signal handlers for pipe";
}
#endif
}
<commit_msg>Fix compilation.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#include "Basics/win-utils.h"
#endif
#include "Scheduler.h"
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
#include "Basics/MutexLocker.h"
#include "Basics/StringUtils.h"
#include "Basics/Thread.h"
#include "Logger/Logger.h"
#include "Rest/GeneralResponse.h"
#include "Scheduler/JobQueue.h"
#include "Scheduler/Task.h"
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
// -----------------------------------------------------------------------------
// --SECTION-- SchedulerManagerThread
// -----------------------------------------------------------------------------
namespace {
class SchedulerManagerThread : public Thread {
public:
SchedulerManagerThread(Scheduler* scheduler, boost::asio::io_service* service)
: Thread("SchedulerManager"), _scheduler(scheduler), _service(service) {}
~SchedulerManagerThread() { shutdown(); }
public:
void run() {
while (!_scheduler->isStopping()) {
try {
_service->run_one();
_scheduler->deleteOldThreads();
} catch (...) {
LOG_TOPIC(ERR, Logger::THREADS)
<< "manager loop caught an error, restarting";
}
}
_scheduler->threadDone(this);
}
private:
Scheduler* _scheduler;
boost::asio::io_service* _service;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- SchedulerThread
// -----------------------------------------------------------------------------
namespace {
class SchedulerThread : public Thread {
public:
SchedulerThread(Scheduler* scheduler, boost::asio::io_service* service)
: Thread("Scheduler"), _scheduler(scheduler), _service(service) {}
~SchedulerThread() { shutdown(); }
public:
void run() {
_scheduler->incRunning();
LOG_TOPIC(DEBUG, Logger::THREADS) << "running (" << _scheduler->infoStatus()
<< ")";
auto start = std::chrono::steady_clock::now();
try {
static size_t EVERY_LOOP = 1000;
static double MIN_SECONDS = 30;
size_t counter = 0;
while (!_scheduler->isStopping()) {
_service->run_one();
if (++counter > EVERY_LOOP) {
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> diff = now - start;
if (diff.count() > MIN_SECONDS) {
if (_scheduler->stopThread()) {
auto n = _scheduler->decRunning();
if (n <= 2) {
_scheduler->incRunning();
} else {
break;
}
}
start = std::chrono::steady_clock::now();
}
}
}
LOG_TOPIC(DEBUG, Logger::THREADS) << "stopped ("
<< _scheduler->infoStatus() << ")";
} catch (...) {
LOG_TOPIC(ERR, Logger::THREADS)
<< "scheduler loop caught an error, restarting";
_scheduler->decRunning();
_scheduler->startNewThread();
}
_scheduler->threadDone(this);
}
private:
Scheduler* _scheduler;
boost::asio::io_service* _service;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- Scheduler
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
Scheduler::Scheduler(size_t nrThreads, size_t maxQueueSize)
: _nrThreads(nrThreads),
_maxQueueSize(maxQueueSize),
_stopping(false),
_nrBusy(0),
_nrWorking(0),
_nrBlocked(0),
_nrRunning(0),
_nrMinimal(0),
_nrMaximal(0),
_nrRealMaximum(0),
_lastThreadWarning(0) {
// setup signal handlers
initializeSignalHandlers();
}
Scheduler::~Scheduler() { deleteOldThreads(); }
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
bool Scheduler::start(ConditionVariable* cv) {
// start the I/O
startIoService();
// initialize thread handling
if (_nrMaximal <= 0) {
_nrMaximal = _nrThreads;
}
if (_nrRealMaximum <= 0) {
_nrRealMaximum = 4 * _nrMaximal;
}
for (size_t i = 0; i < 2; ++i) {
startNewThread();
}
startManagerThread();
startRebalancer();
// initialize the queue handling
_jobQueue.reset(new JobQueue(_maxQueueSize, _ioService.get()));
_jobQueue->start();
// done
LOG(TRACE) << "all scheduler threads are up and running";
return true;
}
void Scheduler::startIoService() {
_ioService.reset(new boost::asio::io_service());
_serviceGuard.reset(new boost::asio::io_service::work(*_ioService));
_managerService.reset(new boost::asio::io_service());
_managerGuard.reset(new boost::asio::io_service::work(*_managerService));
}
void Scheduler::startRebalancer() {
std::chrono::milliseconds interval(500);
_threadManager.reset(new boost::asio::steady_timer(*_managerService));
_threadHandler = [this, interval](const boost::system::error_code& error) {
if (error || isStopping()) {
return;
}
rebalanceThreads();
_threadManager->expires_from_now(interval);
_threadManager->async_wait(_threadHandler);
};
_threadManager->expires_from_now(interval);
_threadManager->async_wait(_threadHandler);
_lastThreadWarning.store(TRI_microtime());
}
void Scheduler::startManagerThread() {
MUTEX_LOCKER(guard, _threadsLock);
auto thread = new SchedulerManagerThread(this, _managerService.get());
_threads.emplace(thread);
thread->start();
}
void Scheduler::startNewThread() {
MUTEX_LOCKER(guard, _threadsLock);
auto thread = new SchedulerThread(this, _ioService.get());
_threads.emplace(thread);
thread->start();
}
bool Scheduler::stopThread() {
if (_nrRunning <= _nrMinimal) {
return false;
}
if (_nrRunning >= 3) {
int64_t low = ((_nrRunning <= 4) ? 0 : (_nrRunning * 1 / 4)) - _nrBlocked;
if (_nrBusy <= low && _nrWorking <= low) {
return true;
}
}
return false;
}
void Scheduler::threadDone(Thread* thread) {
MUTEX_LOCKER(guard, _threadsLock);
_threads.erase(thread);
_deadThreads.insert(thread);
}
void Scheduler::deleteOldThreads() {
// delete old thread objects
std::unordered_set<Thread*> deadThreads;
{
MUTEX_LOCKER(guard, _threadsLock);
if (_deadThreads.empty()) {
return;
}
deadThreads.swap(_deadThreads);
}
for (auto thread : deadThreads) {
try {
delete thread;
} catch (...) {
LOG_TOPIC(ERR, Logger::THREADS) << "cannot delete thread";
}
}
}
void Scheduler::rebalanceThreads() {
static double const MIN_WARN_INTERVAL = 10;
static double const MIN_ERR_INTERVAL = 300;
int64_t high = (_nrRunning <= 4) ? 1 : (_nrRunning * 11 / 16);
int64_t working = (_nrBusy > _nrWorking) ? _nrBusy : _nrWorking;
LOG_TOPIC(DEBUG, Logger::THREADS) << "rebalancing threads, high: " << high
<< ", working: " << working << " ("
<< infoStatus() << ")";
if (working >= high) {
if (_nrRunning < _nrMaximal + _nrBlocked &&
_nrRunning < _nrRealMaximum) { // added by Max 22.12.2016
// otherwise we exceed the total maximum
startNewThread();
return;
}
}
if (working >= _nrMaximal + _nrBlocked || _nrRunning < _nrMinimal) {
double ltw = _lastThreadWarning.load();
double now = TRI_microtime();
if (_nrRunning >= _nrRealMaximum) {
if (ltw - now > MIN_ERR_INTERVAL) {
LOG_TOPIC(ERR, Logger::THREADS) << "too many threads (" << infoStatus()
<< ")";
_lastThreadWarning.store(now);
}
} else {
if (_nrRunning >= _nrRealMaximum * 3 / 4) {
if (ltw - now > MIN_WARN_INTERVAL) {
LOG_TOPIC(WARN, Logger::THREADS)
<< "number of threads is reaching a critical limit ("
<< infoStatus() << ")";
_lastThreadWarning.store(now);
}
}
LOG_TOPIC(DEBUG, Logger::THREADS) << "overloading threads ("
<< infoStatus() << ")";
startNewThread();
}
}
}
void Scheduler::beginShutdown() {
if (_stopping) {
return;
}
_jobQueue->beginShutdown();
_threadManager.reset();
_managerGuard.reset();
_managerService->stop();
_serviceGuard.reset();
_ioService->stop();
// set the flag AFTER stopping the threads
_stopping = true;
}
void Scheduler::shutdown() {
bool done = false;
while (!done) {
MUTEX_LOCKER(guard, _threadsLock);
done = _threads.empty();
}
deleteOldThreads();
_managerService.reset();
_ioService.reset();
}
void Scheduler::initializeSignalHandlers() {
#ifdef _WIN32
// Windows does not support POSIX signal handling
#else
struct sigaction action;
memset(&action, 0, sizeof(action));
sigfillset(&action.sa_mask);
// ignore broken pipes
action.sa_handler = SIG_IGN;
int res = sigaction(SIGPIPE, &action, 0);
if (res < 0) {
LOG(ERR) << "cannot initialize signal handlers for pipe";
}
#endif
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <utility>
#include <stdexcept>
#include <string.h>
#include <algorithm>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include "kms++.h"
#ifndef DRM_CLIENT_CAP_ATOMIC
#define DRM_CLIENT_CAP_ATOMIC 3
#endif
using namespace std;
namespace kms
{
Card::Card()
{
const char *card = "/dev/dri/card0";
int fd = open(card, O_RDWR | O_CLOEXEC);
if (fd < 0)
throw invalid_argument(string(strerror(errno)) + " opening " +
card);
m_fd = fd;
int r;
r = drmSetMaster(fd);
m_master = r == 0;
r = drmSetClientCap(m_fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
m_has_universal_planes = r == 0;
if (getenv("LIBKMSXX_DISABLE_ATOMIC") == 0) {
r = drmSetClientCap(m_fd, DRM_CLIENT_CAP_ATOMIC, 1);
m_has_atomic = r == 0;
} else {
m_has_atomic = false;
}
uint64_t has_dumb;
r = drmGetCap(fd, DRM_CAP_DUMB_BUFFER, &has_dumb);
if (r || !has_dumb)
throw invalid_argument("Dumb buffers not available");
auto res = drmModeGetResources(m_fd);
if (!res)
throw invalid_argument("Can't get card resources");
for (int i = 0; i < res->count_connectors; ++i) {
uint32_t id = res->connectors[i];
m_obmap[id] = new Connector(*this, id, i);
}
for (int i = 0; i < res->count_crtcs; ++i) {
uint32_t id = res->crtcs[i];
m_obmap[id] = new Crtc(*this, id, i);
}
for (int i = 0; i < res->count_encoders; ++i) {
uint32_t id = res->encoders[i];
m_obmap[id] = new Encoder(*this, id);
}
drmModeFreeResources(res);
auto planeRes = drmModeGetPlaneResources(m_fd);
for (uint i = 0; i < planeRes->count_planes; ++i) {
uint32_t id = planeRes->planes[i];
m_obmap[id] = new Plane(*this, id);
}
drmModeFreePlaneResources(planeRes);
// collect all possible props
for (auto ob : get_objects()) {
auto props = drmModeObjectGetProperties(m_fd, ob->id(), ob->object_type());
if (props == nullptr)
continue;
for (unsigned i = 0; i < props->count_props; ++i) {
uint32_t prop_id = props->props[i];
if (m_obmap.find(prop_id) == m_obmap.end())
m_obmap[prop_id] = new Property(*this, prop_id);
}
drmModeFreeObjectProperties(props);
}
for (auto pair : m_obmap)
pair.second->setup();
}
Card::~Card()
{
for (auto pair : m_obmap)
delete pair.second;
close(m_fd);
}
template <class T> static void print_obs(const map<uint32_t, DrmObject*>& obmap)
{
for (auto pair : obmap) {
auto ob = pair.second;
if (dynamic_cast<T*>(ob)) {
ob->print_short();
//ob->print_props();
}
}
}
void Card::print_short() const
{
print_obs<Connector>(m_obmap);
print_obs<Encoder>(m_obmap);
print_obs<Crtc>(m_obmap);
print_obs<Plane>(m_obmap);
}
Property* Card::get_prop(const char *name) const
{
for (auto pair : m_obmap) {
auto prop = dynamic_cast<Property*>(pair.second);
if (!prop)
continue;
if (strcmp(name, prop->name()) == 0)
return prop;
}
throw invalid_argument(string("Card property ") + name + " not found");
}
Connector* Card::get_first_connected_connector() const
{
for(auto pair : m_obmap) {
auto c = dynamic_cast<Connector*>(pair.second);
if (c && c->connected())
return c;
}
throw invalid_argument("no connected connectors");
}
DrmObject* Card::get_object(uint32_t id) const
{
return m_obmap.at(id);
}
vector<Connector*> Card::get_connectors() const
{
vector<Connector*> v;
for(auto pair : m_obmap) {
auto p = dynamic_cast<Connector*>(pair.second);
if (p)
v.push_back(p);
}
return v;
}
vector<Plane*> Card::get_planes() const
{
vector<Plane*> v;
for(auto pair : m_obmap) {
auto p = dynamic_cast<Plane*>(pair.second);
if (p)
v.push_back(p);
}
return v;
}
vector<DrmObject*> Card::get_objects() const
{
vector<DrmObject*> v;
for(auto pair : m_obmap)
v.push_back(pair.second);
return v;
}
Crtc* Card::get_crtc_by_index(uint32_t idx) const
{
for(auto pair : m_obmap) {
auto crtc = dynamic_cast<Crtc*>(pair.second);
if (crtc && crtc->idx() == idx)
return crtc;
}
throw invalid_argument(string("Crtc #") + to_string(idx) + "not found");
}
Crtc* Card::get_crtc(uint32_t id) const { return dynamic_cast<Crtc*>(get_object(id)); }
Encoder* Card::get_encoder(uint32_t id) const { return dynamic_cast<Encoder*>(get_object(id)); }
Property* Card::get_prop(uint32_t id) const { return dynamic_cast<Property*>(get_object(id)); }
std::vector<kms::Pipeline> Card::get_connected_pipelines()
{
vector<Pipeline> outputs;
for (auto conn : get_connectors())
{
if (conn->connected() == false)
continue;
Crtc* crtc = conn->get_current_crtc();
if (!crtc) {
for (auto possible : conn->get_possible_crtcs()) {
if (find_if(outputs.begin(), outputs.end(), [possible](Pipeline out) { return out.crtc == possible; }) == outputs.end()) {
crtc = possible;
break;
}
}
}
if (!crtc)
throw invalid_argument(string("Connector #") +
to_string(conn->idx()) +
" has no possible crtcs");
outputs.push_back(Pipeline { crtc, conn });
}
return outputs;
}
}
<commit_msg>Allow disabling universal planes with LIBKMSXX_DISABLE_UNIVERSAL_PLANES<commit_after>#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <utility>
#include <stdexcept>
#include <string.h>
#include <algorithm>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include "kms++.h"
#ifndef DRM_CLIENT_CAP_ATOMIC
#define DRM_CLIENT_CAP_ATOMIC 3
#endif
using namespace std;
namespace kms
{
Card::Card()
{
const char *card = "/dev/dri/card0";
int fd = open(card, O_RDWR | O_CLOEXEC);
if (fd < 0)
throw invalid_argument(string(strerror(errno)) + " opening " +
card);
m_fd = fd;
int r;
r = drmSetMaster(fd);
m_master = r == 0;
if (getenv("LIBKMSXX_DISABLE_UNIVERSAL_PLANES") == 0) {
r = drmSetClientCap(m_fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
m_has_universal_planes = r == 0;
} else {
m_has_universal_planes = false;
}
if (getenv("LIBKMSXX_DISABLE_ATOMIC") == 0) {
r = drmSetClientCap(m_fd, DRM_CLIENT_CAP_ATOMIC, 1);
m_has_atomic = r == 0;
} else {
m_has_atomic = false;
}
uint64_t has_dumb;
r = drmGetCap(fd, DRM_CAP_DUMB_BUFFER, &has_dumb);
if (r || !has_dumb)
throw invalid_argument("Dumb buffers not available");
auto res = drmModeGetResources(m_fd);
if (!res)
throw invalid_argument("Can't get card resources");
for (int i = 0; i < res->count_connectors; ++i) {
uint32_t id = res->connectors[i];
m_obmap[id] = new Connector(*this, id, i);
}
for (int i = 0; i < res->count_crtcs; ++i) {
uint32_t id = res->crtcs[i];
m_obmap[id] = new Crtc(*this, id, i);
}
for (int i = 0; i < res->count_encoders; ++i) {
uint32_t id = res->encoders[i];
m_obmap[id] = new Encoder(*this, id);
}
drmModeFreeResources(res);
auto planeRes = drmModeGetPlaneResources(m_fd);
for (uint i = 0; i < planeRes->count_planes; ++i) {
uint32_t id = planeRes->planes[i];
m_obmap[id] = new Plane(*this, id);
}
drmModeFreePlaneResources(planeRes);
// collect all possible props
for (auto ob : get_objects()) {
auto props = drmModeObjectGetProperties(m_fd, ob->id(), ob->object_type());
if (props == nullptr)
continue;
for (unsigned i = 0; i < props->count_props; ++i) {
uint32_t prop_id = props->props[i];
if (m_obmap.find(prop_id) == m_obmap.end())
m_obmap[prop_id] = new Property(*this, prop_id);
}
drmModeFreeObjectProperties(props);
}
for (auto pair : m_obmap)
pair.second->setup();
}
Card::~Card()
{
for (auto pair : m_obmap)
delete pair.second;
close(m_fd);
}
template <class T> static void print_obs(const map<uint32_t, DrmObject*>& obmap)
{
for (auto pair : obmap) {
auto ob = pair.second;
if (dynamic_cast<T*>(ob)) {
ob->print_short();
//ob->print_props();
}
}
}
void Card::print_short() const
{
print_obs<Connector>(m_obmap);
print_obs<Encoder>(m_obmap);
print_obs<Crtc>(m_obmap);
print_obs<Plane>(m_obmap);
}
Property* Card::get_prop(const char *name) const
{
for (auto pair : m_obmap) {
auto prop = dynamic_cast<Property*>(pair.second);
if (!prop)
continue;
if (strcmp(name, prop->name()) == 0)
return prop;
}
throw invalid_argument(string("Card property ") + name + " not found");
}
Connector* Card::get_first_connected_connector() const
{
for(auto pair : m_obmap) {
auto c = dynamic_cast<Connector*>(pair.second);
if (c && c->connected())
return c;
}
throw invalid_argument("no connected connectors");
}
DrmObject* Card::get_object(uint32_t id) const
{
return m_obmap.at(id);
}
vector<Connector*> Card::get_connectors() const
{
vector<Connector*> v;
for(auto pair : m_obmap) {
auto p = dynamic_cast<Connector*>(pair.second);
if (p)
v.push_back(p);
}
return v;
}
vector<Plane*> Card::get_planes() const
{
vector<Plane*> v;
for(auto pair : m_obmap) {
auto p = dynamic_cast<Plane*>(pair.second);
if (p)
v.push_back(p);
}
return v;
}
vector<DrmObject*> Card::get_objects() const
{
vector<DrmObject*> v;
for(auto pair : m_obmap)
v.push_back(pair.second);
return v;
}
Crtc* Card::get_crtc_by_index(uint32_t idx) const
{
for(auto pair : m_obmap) {
auto crtc = dynamic_cast<Crtc*>(pair.second);
if (crtc && crtc->idx() == idx)
return crtc;
}
throw invalid_argument(string("Crtc #") + to_string(idx) + "not found");
}
Crtc* Card::get_crtc(uint32_t id) const { return dynamic_cast<Crtc*>(get_object(id)); }
Encoder* Card::get_encoder(uint32_t id) const { return dynamic_cast<Encoder*>(get_object(id)); }
Property* Card::get_prop(uint32_t id) const { return dynamic_cast<Property*>(get_object(id)); }
std::vector<kms::Pipeline> Card::get_connected_pipelines()
{
vector<Pipeline> outputs;
for (auto conn : get_connectors())
{
if (conn->connected() == false)
continue;
Crtc* crtc = conn->get_current_crtc();
if (!crtc) {
for (auto possible : conn->get_possible_crtcs()) {
if (find_if(outputs.begin(), outputs.end(), [possible](Pipeline out) { return out.crtc == possible; }) == outputs.end()) {
crtc = possible;
break;
}
}
}
if (!crtc)
throw invalid_argument(string("Connector #") +
to_string(conn->idx()) +
" has no possible crtcs");
outputs.push_back(Pipeline { crtc, conn });
}
return outputs;
}
}
<|endoftext|> |
<commit_before>/* LibMary - C++ library for high-performance network servers
Copyright (C) 2011 Dmitry Shatrov
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <libmary/types.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <libmary/exception.h>
#include <libmary/posix.h>
#include <libmary/io.h>
#include <libmary/native_file.h>
#include <libmary/buffered_output_stream.h>
#include <libmary/log.h>
#include <libmary/util_str.h>
namespace M {
#if 0
void posix_throw_errno ()
{
// switch (errno) {
// }
exc_throw (PosixException (errno));
exc_push ();
#if 0
// TODO Convert posix errors to libmary.
exc_throw (InternalException (InternalException::UnknownError));
#endif
}
#endif
void libMary_posixInit ()
{
// Calling tzset() for localtime_r() to behave correctly.
tzset ();
outs = new NativeFile (STDOUT_FILENO);
errs = new NativeFile (STDERR_FILENO);
static BufferedOutputStream logs_buffered (errs, 4096);
logs = &logs_buffered;
if (!updateTime ())
logE_ (_func, exc->toString());
// Blocking SIGPIPE for write()/writev().
{
// logD_ (_func, "blocking SIGPIPE");
struct sigaction act;
memset (&act, 0, sizeof (act));
act.sa_handler = SIG_IGN;
// TODO -1 on error
sigemptyset (&act.sa_mask);
// TODO -1 on error
sigaddset (&act.sa_mask, SIGPIPE);
if (sigaction (SIGPIPE, &act, NULL) == -1)
logE_ (_func, "sigaction() failed: ", errnoString (errno));
}
#if 0
{
struct sigaction sa;
zeroMemory (&sa, sizeof sa);
sa.sa_handler = sigchld_handler;
sigemptyset (&sa.sa_mask);
/* I'd like to have a non-restarting signal
* to test MyNC libraries for correct handling of EINTR.
sa.sa_flags = SA_RESTART;
*/
// TODO sigaddset?
sa.sa_flags = 0;
if (sigaction (SIGCHLD, &sa, NULL) == -1) {
printError ("sigthread_func: (fatal) sigaction");
_exit (-1);
}
}
#endif
}
}
<commit_msg>prevent 'logs' from being destroyed when the server exits<commit_after>/* LibMary - C++ library for high-performance network servers
Copyright (C) 2011 Dmitry Shatrov
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <libmary/types.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <libmary/exception.h>
#include <libmary/posix.h>
#include <libmary/io.h>
#include <libmary/native_file.h>
#include <libmary/buffered_output_stream.h>
#include <libmary/log.h>
#include <libmary/util_str.h>
namespace M {
#if 0
void posix_throw_errno ()
{
// switch (errno) {
// }
exc_throw (PosixException (errno));
exc_push ();
#if 0
// TODO Convert posix errors to libmary.
exc_throw (InternalException (InternalException::UnknownError));
#endif
}
#endif
void libMary_posixInit ()
{
// Calling tzset() for localtime_r() to behave correctly.
tzset ();
outs = new NativeFile (STDOUT_FILENO);
errs = new NativeFile (STDERR_FILENO);
#if 0
static BufferedOutputStream logs_buffered (errs, 4096);
logs = &logs_buffered;
#endif
// Allocating on heap to avoid problems with deinitialization order
// of static data.
logs = new BufferedOutputStream (errs, 4096);
if (!updateTime ())
logE_ (_func, exc->toString());
// Blocking SIGPIPE for write()/writev().
{
// logD_ (_func, "blocking SIGPIPE");
struct sigaction act;
memset (&act, 0, sizeof (act));
act.sa_handler = SIG_IGN;
// TODO -1 on error
sigemptyset (&act.sa_mask);
// TODO -1 on error
sigaddset (&act.sa_mask, SIGPIPE);
if (sigaction (SIGPIPE, &act, NULL) == -1)
logE_ (_func, "sigaction() failed: ", errnoString (errno));
}
#if 0
{
struct sigaction sa;
zeroMemory (&sa, sizeof sa);
sa.sa_handler = sigchld_handler;
sigemptyset (&sa.sa_mask);
/* I'd like to have a non-restarting signal
* to test MyNC libraries for correct handling of EINTR.
sa.sa_flags = SA_RESTART;
*/
// TODO sigaddset?
sa.sa_flags = 0;
if (sigaction (SIGCHLD, &sa, NULL) == -1) {
printError ("sigthread_func: (fatal) sigaction");
_exit (-1);
}
}
#endif
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "TestingEnvironment.hpp"
#include <GL/glx.h>
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, int, const int*);
namespace Diligent
{
namespace Testing
{
NativeWindow TestingEnvironment::CreateNativeWindow()
{
auto* display = XOpenDisplay(0);
// clang-format off
static int visual_attribs[] =
{
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_DOUBLEBUFFER, true,
// The largest available total RGBA color buffer size (sum of GLX_RED_SIZE,
// GLX_GREEN_SIZE, GLX_BLUE_SIZE, and GLX_ALPHA_SIZE) of at least the minimum
// size specified for each color component is preferred.
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
// The largest available depth buffer of at least GLX_DEPTH_SIZE size is preferred
GLX_DEPTH_SIZE, 24,
//GLX_SAMPLE_BUFFERS, 1,
GLX_SAMPLES, 1,
None
};
// clang-format on
int fbcount = 0;
GLXFBConfig* fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount);
if (!fbc)
{
LOG_ERROR_AND_THROW("Failed to retrieve a framebuffer config");
}
XVisualInfo* vi = glXGetVisualFromFBConfig(display, fbc[0]);
XSetWindowAttributes swa;
swa.colormap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone);
swa.border_pixel = 0;
swa.event_mask =
StructureNotifyMask |
ExposureMask |
KeyPressMask |
KeyReleaseMask |
ButtonPressMask |
ButtonReleaseMask |
PointerMotionMask;
auto win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, 1024, 768, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa);
if (!win)
{
LOG_ERROR_AND_THROW("Failed to create window.");
}
{
auto SizeHints = XAllocSizeHints();
SizeHints->flags = PMinSize;
SizeHints->min_width = 320;
SizeHints->min_height = 240;
XSetWMNormalHints(display, win, SizeHints);
XFree(SizeHints);
}
XMapWindow(display, win);
glXCreateContextAttribsARBProc glXCreateContextAttribsARB = nullptr;
{
// Create an oldstyle context first, to get the correct function pointer for glXCreateContextAttribsARB
GLXContext ctx_old = glXCreateContext(display, vi, 0, GL_TRUE);
glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
glXMakeCurrent(display, None, NULL);
glXDestroyContext(display, ctx_old);
}
if (glXCreateContextAttribsARB == nullptr)
{
LOG_ERROR_AND_THROW("glXCreateContextAttribsARB entry point not found. Aborting.");
}
int Flags = GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
#ifdef _DEBUG
Flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
#endif
int major_version = 4;
int minor_version = 3;
// clang-format off
static int context_attribs[] =
{
GLX_CONTEXT_MAJOR_VERSION_ARB, major_version,
GLX_CONTEXT_MINOR_VERSION_ARB, minor_version,
GLX_CONTEXT_FLAGS_ARB, Flags,
None
};
// clang-format on
GLXContext ctx = glXCreateContextAttribsARB(display, fbc[0], NULL, 1, context_attribs);
if (!ctx)
{
LOG_ERROR_AND_THROW("Failed to create GL context.");
}
XFree(fbc);
glXMakeCurrent(display, win, ctx);
struct TestingEnvironmentLinuxData : PlatformData
{
TestingEnvironmentLinuxData(NativeWindow _LinuxWnd) :
LinuxWnd{_LinuxWnd}
{
}
virtual ~TestingEnvironmentLinuxData()
{
auto ctx = glXGetCurrentContext();
auto* display = reinterpret_cast<Display*>(LinuxWnd.pDisplay);
glXMakeCurrent(display, None, NULL);
glXDestroyContext(display, ctx);
XDestroyWindow(display, LinuxWnd.WindowId);
XCloseDisplay(display);
}
NativeWindow LinuxWnd;
};
NativeWindow LinuxWnd;
LinuxWnd.pDisplay = display;
LinuxWnd.WindowId = win;
m_pPlatformData.reset(new TestingEnvironmentLinuxData{LinuxWnd});
return LinuxWnd;
}
} // namespace Testing
} // namespace Diligent
<commit_msg>Fixed minor issue with non-explicit ctor<commit_after>/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "TestingEnvironment.hpp"
#include <GL/glx.h>
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, int, const int*);
namespace Diligent
{
namespace Testing
{
NativeWindow TestingEnvironment::CreateNativeWindow()
{
auto* display = XOpenDisplay(0);
// clang-format off
static int visual_attribs[] =
{
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_DOUBLEBUFFER, true,
// The largest available total RGBA color buffer size (sum of GLX_RED_SIZE,
// GLX_GREEN_SIZE, GLX_BLUE_SIZE, and GLX_ALPHA_SIZE) of at least the minimum
// size specified for each color component is preferred.
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
// The largest available depth buffer of at least GLX_DEPTH_SIZE size is preferred
GLX_DEPTH_SIZE, 24,
//GLX_SAMPLE_BUFFERS, 1,
GLX_SAMPLES, 1,
None
};
// clang-format on
int fbcount = 0;
GLXFBConfig* fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount);
if (!fbc)
{
LOG_ERROR_AND_THROW("Failed to retrieve a framebuffer config");
}
XVisualInfo* vi = glXGetVisualFromFBConfig(display, fbc[0]);
XSetWindowAttributes swa;
swa.colormap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone);
swa.border_pixel = 0;
swa.event_mask =
StructureNotifyMask |
ExposureMask |
KeyPressMask |
KeyReleaseMask |
ButtonPressMask |
ButtonReleaseMask |
PointerMotionMask;
auto win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, 1024, 768, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa);
if (!win)
{
LOG_ERROR_AND_THROW("Failed to create window.");
}
{
auto SizeHints = XAllocSizeHints();
SizeHints->flags = PMinSize;
SizeHints->min_width = 320;
SizeHints->min_height = 240;
XSetWMNormalHints(display, win, SizeHints);
XFree(SizeHints);
}
XMapWindow(display, win);
glXCreateContextAttribsARBProc glXCreateContextAttribsARB = nullptr;
{
// Create an oldstyle context first, to get the correct function pointer for glXCreateContextAttribsARB
GLXContext ctx_old = glXCreateContext(display, vi, 0, GL_TRUE);
glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
glXMakeCurrent(display, None, NULL);
glXDestroyContext(display, ctx_old);
}
if (glXCreateContextAttribsARB == nullptr)
{
LOG_ERROR_AND_THROW("glXCreateContextAttribsARB entry point not found. Aborting.");
}
int Flags = GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
#ifdef _DEBUG
Flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
#endif
int major_version = 4;
int minor_version = 3;
// clang-format off
static int context_attribs[] =
{
GLX_CONTEXT_MAJOR_VERSION_ARB, major_version,
GLX_CONTEXT_MINOR_VERSION_ARB, minor_version,
GLX_CONTEXT_FLAGS_ARB, Flags,
None
};
// clang-format on
GLXContext ctx = glXCreateContextAttribsARB(display, fbc[0], NULL, 1, context_attribs);
if (!ctx)
{
LOG_ERROR_AND_THROW("Failed to create GL context.");
}
XFree(fbc);
glXMakeCurrent(display, win, ctx);
struct TestingEnvironmentLinuxData : PlatformData
{
explicit TestingEnvironmentLinuxData(NativeWindow _LinuxWnd) :
LinuxWnd{_LinuxWnd}
{
}
virtual ~TestingEnvironmentLinuxData()
{
auto ctx = glXGetCurrentContext();
auto* display = reinterpret_cast<Display*>(LinuxWnd.pDisplay);
glXMakeCurrent(display, None, NULL);
glXDestroyContext(display, ctx);
XDestroyWindow(display, LinuxWnd.WindowId);
XCloseDisplay(display);
}
NativeWindow LinuxWnd;
};
NativeWindow LinuxWnd;
LinuxWnd.pDisplay = display;
LinuxWnd.WindowId = win;
m_pPlatformData.reset(new TestingEnvironmentLinuxData{LinuxWnd});
return LinuxWnd;
}
} // namespace Testing
} // namespace Diligent
<|endoftext|> |
<commit_before>#include "ui_lua.h"
#include <lua\lua.hpp>
#include <util\lua_table.h>
#include "image_mgr.h"
#include "script_mgr.h"
#include "soundbuf_mgr.h"
#include "string_mgr.h"
#include "ui_button.h"
#include "ui_label.h"
#include "ui_line.h"
#include "ui_panel.h"
#include "ui_progressbar.h"
#include "ui_window.h"
#include "util_lua.h"
#include "util_sprite.h"
void RegisterUICreators()
{
ScriptManager& scriptMgr = ScriptManager::GetInstance();
scriptMgr.RegisterFunc("Button", Button);
scriptMgr.RegisterFunc("Label", Label);
scriptMgr.RegisterFunc("Line", Line);
scriptMgr.RegisterFunc("Panel", Panel);
scriptMgr.RegisterFunc("Progressbar", Progressbar);
scriptMgr.RegisterFunc("Widget", Widget);
scriptMgr.RegisterFunc("Window", Window_);
}
namespace
{
void SetName(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "name"))
{
std::string name = util::GetField_String(L, "name");
widget->SetName(name);
}
}
void SetTopLeftWidthHeight(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "top") && util::HasField(L, "left"))
{
float left = util::GetField_Number(L, "left");
float top = util::GetField_Number(L, "top");
widget->SetTopLeft(Vector2f(left, top));
}
if (util::HasField(L, "width") && util::HasField(L, "height"))
{
float width = util::GetField_Number(L, "width");
float height = util::GetField_Number(L, "height");
widget->SetWidthHeight(Vector2f(width, height));
}
}
void SetAnim(lua_State* L, UIWidget* widget, std::string widgetAnimKey, std::string luaAnimFieldKey)
{
if (util::HasField(L, luaAnimFieldKey.c_str()))
{
std::string imgKey = util::GetField_String(L, luaAnimFieldKey);
if (!imgKey.empty())
{
Animation anim;
Image& img = ImageManager::GetInstance().GetImage(imgKey);
SetImage(anim, img);
widget->SetAnim(widgetAnimKey, anim);
}
}
}
void SetTooltip(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "tooltipStringKey"))
{
std::string tooltipStringKey = util::GetField_String(L, "tooltipStringKey");
if (!tooltipStringKey.empty())
{
String& str = StringManager::GetInstance().GetString(tooltipStringKey);
widget->SetTooltip(str);
}
}
if (util::HasField(L, "tooltipTopleft"))
{
lua_getfield(L, -1, "tooltipTopleft");
Vector2f topleft;
SetVector2f(L, topleft);
lua_pop(L, 1);
widget->SetTooltipTopLeft(topleft);
}
if (util::HasField(L, "useRelativeTooltipTopleft"))
{
bool useRelativeTooltipTopleft = util::GetField_Boolean(L, "useRelativeTooltipTopleft");
widget->SetUseRelativeTooltipTopLeft(useRelativeTooltipTopleft);
}
}
void SetTextUserData(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "textUserData"))
{
std::string textUserData = util::GetField_String(L, "textUserData");
if (!textUserData.empty())
widget->SetTextUserData(textUserData);
}
}
void SetPressedSoundKey(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "pressedSoundKey"))
widget->SetPressedSoundKey(util::GetField_String(L, "pressedSoundKey"));
}
void AddWidget(lua_State* L, UIWidget* widget)
{
lua_pushnil(L);
while (lua_next(L, -2) != 0)
{
if (lua_islightuserdata(L, -1))
{
UIWidget* subWidget = static_cast<UIWidget*>(lua_touserdata(L, -1));
widget->AddWidget(subWidget, subWidget->GetName());
}
lua_pop(L, 1);
}
}
void SetButton(lua_State* L, UIButton* btn)
{
SetName(L, btn);
SetTopLeftWidthHeight(L, btn);
SetAnim(L, btn, UIButton::NORMAL_ANIM_, "normalAnim");
SetAnim(L, btn, UIButton::HOVERED_ANIM_, "hoveredAnim");
SetAnim(L, btn, UIButton::PRESSED_ANIM_, "pressedAnim");
SetAnim(L, btn, UIButton::DISABLED_ANIM_, "disabledAnim");
AddWidget(L, btn);
}
}
int Button(lua_State* L)
{
UIButton* btn = new UIButton;
SetName(L, btn);
SetTopLeftWidthHeight(L, btn);
SetTooltip(L, btn);
SetAnim(L, btn, UIButton::NORMAL_ANIM_, "normalAnim");
SetAnim(L, btn, UIButton::HOVERED_ANIM_, "hoveredAnim");
SetAnim(L, btn, UIButton::PRESSED_ANIM_, "pressedAnim");
SetAnim(L, btn, UIButton::DISABLED_ANIM_, "disabledAnim");
SetTextUserData(L, btn);
SetPressedSoundKey(L, btn);
AddWidget(L, btn);
lua_pushlightuserdata(L, btn);
return 1;
}
int Label(lua_State* L)
{
UILabel* label = new UILabel;
SetName(L, label);
SetTopLeftWidthHeight(L, label);
SetTooltip(L, label);
SetTextUserData(L, label);
SetPressedSoundKey(L, label);
if (util::HasField(L, "hoveredStyle"))
{
int style = util::GetField_Number(L, "hoveredStyle");
label->SetHoveredStyle(style);
}
if (util::HasField(L, "stringKey"))
{
std::string stringKey = util::GetField_String(L, "stringKey");
if (!stringKey.empty())
label->SetString(StringManager::GetInstance().GetString(stringKey));
}
if (util::HasField(L, "color"))
{
String& str = label->GetString();
Color& color = const_cast<Color&>(str.GetColor());
lua_getfield(L, -1, "color");
SetColor(L, color);
lua_pop(L, 1);
}
lua_pushlightuserdata(L, label);
return 1;
}
int Line(lua_State* L)
{
UILine* line = new UILine;
SetName(L, line);
SetTopLeftWidthHeight(L, line);
SetTooltip(L, line);
SetTextUserData(L, line);
lua_pushlightuserdata(L, line);
return 1;
}
int Panel(lua_State* L)
{
UIPanel* panel = new UIPanel;
SetName(L, panel);
SetTopLeftWidthHeight(L, panel);
SetTooltip(L, panel);
SetAnim(L, panel, UIPanel::NORMAL_ANIM_, "normalAnim");
SetAnim(L, panel, UIPanel::DISABLED_ANIM_, "disabledAnim");
SetTextUserData(L, panel);
AddWidget(L, panel);
lua_pushlightuserdata(L, panel);
return 1;
}
int Progressbar(lua_State* L)
{
UIProgressbar* progressbar = new UIProgressbar;
SetName(L, progressbar);
SetTopLeftWidthHeight(L, progressbar);
SetTooltip(L, progressbar);
SetAnim(L, progressbar, UIProgressbar::BOTTOM_ANIM_, "bottomAnim");
SetAnim(L, progressbar, UIProgressbar::MID_ANIM_, "midAnim");
SetAnim(L, progressbar, UIProgressbar::TOP_ANIM_, "topAnim");
SetTextUserData(L, progressbar);
AddWidget(L, progressbar);
lua_pushlightuserdata(L, progressbar);
return 1;
}
int Window_( lua_State* L )
{
UIWindow* window = new UIWindow;
SetName(L, window);
SetTopLeftWidthHeight(L, window);
SetTooltip(L, window);
SetAnim(L, window, UIPanel::NORMAL_ANIM_, "normalAnim");
SetAnim(L, window, UIPanel::DISABLED_ANIM_, "disabledAnim");
SetTextUserData(L, window);
AddWidget(L, window);
// ùرհť
if (util::HasField(L, "closeBtn"))
{
lua_pushstring(L, "closeBtn");
lua_gettable(L, -2);
if (lua_istable(L, -1))
SetButton(L, window->GetCloseButton());
lua_pop(L, 1);
}
lua_pushlightuserdata(L, window);
return 1;
}
int Widget(lua_State* L)
{
UIWindow* widget = new UIWindow;
SetName(L, widget);
SetTextUserData(L, widget);
AddWidget(L, widget);
lua_pushlightuserdata(L, widget);
return 1;
}
<commit_msg>Fixed bug in int Widget(lua_State* L).<commit_after>#include "ui_lua.h"
#include <lua\lua.hpp>
#include <util\lua_table.h>
#include "image_mgr.h"
#include "script_mgr.h"
#include "soundbuf_mgr.h"
#include "string_mgr.h"
#include "ui_button.h"
#include "ui_label.h"
#include "ui_line.h"
#include "ui_panel.h"
#include "ui_progressbar.h"
#include "ui_window.h"
#include "util_lua.h"
#include "util_sprite.h"
void RegisterUICreators()
{
ScriptManager& scriptMgr = ScriptManager::GetInstance();
scriptMgr.RegisterFunc("Button", Button);
scriptMgr.RegisterFunc("Label", Label);
scriptMgr.RegisterFunc("Line", Line);
scriptMgr.RegisterFunc("Panel", Panel);
scriptMgr.RegisterFunc("Progressbar", Progressbar);
scriptMgr.RegisterFunc("Widget", Widget);
scriptMgr.RegisterFunc("Window", Window_);
}
namespace
{
void SetName(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "name"))
{
std::string name = util::GetField_String(L, "name");
widget->SetName(name);
}
}
void SetTopLeftWidthHeight(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "top") && util::HasField(L, "left"))
{
float left = util::GetField_Number(L, "left");
float top = util::GetField_Number(L, "top");
widget->SetTopLeft(Vector2f(left, top));
}
if (util::HasField(L, "width") && util::HasField(L, "height"))
{
float width = util::GetField_Number(L, "width");
float height = util::GetField_Number(L, "height");
widget->SetWidthHeight(Vector2f(width, height));
}
}
void SetAnim(lua_State* L, UIWidget* widget, std::string widgetAnimKey, std::string luaAnimFieldKey)
{
if (util::HasField(L, luaAnimFieldKey.c_str()))
{
std::string imgKey = util::GetField_String(L, luaAnimFieldKey);
if (!imgKey.empty())
{
Animation anim;
Image& img = ImageManager::GetInstance().GetImage(imgKey);
SetImage(anim, img);
widget->SetAnim(widgetAnimKey, anim);
}
}
}
void SetTooltip(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "tooltipStringKey"))
{
std::string tooltipStringKey = util::GetField_String(L, "tooltipStringKey");
if (!tooltipStringKey.empty())
{
String& str = StringManager::GetInstance().GetString(tooltipStringKey);
widget->SetTooltip(str);
}
}
if (util::HasField(L, "tooltipTopleft"))
{
lua_getfield(L, -1, "tooltipTopleft");
Vector2f topleft;
SetVector2f(L, topleft);
lua_pop(L, 1);
widget->SetTooltipTopLeft(topleft);
}
if (util::HasField(L, "useRelativeTooltipTopleft"))
{
bool useRelativeTooltipTopleft = util::GetField_Boolean(L, "useRelativeTooltipTopleft");
widget->SetUseRelativeTooltipTopLeft(useRelativeTooltipTopleft);
}
}
void SetTextUserData(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "textUserData"))
{
std::string textUserData = util::GetField_String(L, "textUserData");
if (!textUserData.empty())
widget->SetTextUserData(textUserData);
}
}
void SetPressedSoundKey(lua_State* L, UIWidget* widget)
{
if (util::HasField(L, "pressedSoundKey"))
widget->SetPressedSoundKey(util::GetField_String(L, "pressedSoundKey"));
}
void AddWidget(lua_State* L, UIWidget* widget)
{
lua_pushnil(L);
while (lua_next(L, -2) != 0)
{
if (lua_islightuserdata(L, -1))
{
UIWidget* subWidget = static_cast<UIWidget*>(lua_touserdata(L, -1));
widget->AddWidget(subWidget, subWidget->GetName());
}
lua_pop(L, 1);
}
}
void SetButton(lua_State* L, UIButton* btn)
{
SetName(L, btn);
SetTopLeftWidthHeight(L, btn);
SetAnim(L, btn, UIButton::NORMAL_ANIM_, "normalAnim");
SetAnim(L, btn, UIButton::HOVERED_ANIM_, "hoveredAnim");
SetAnim(L, btn, UIButton::PRESSED_ANIM_, "pressedAnim");
SetAnim(L, btn, UIButton::DISABLED_ANIM_, "disabledAnim");
AddWidget(L, btn);
}
}
int Button(lua_State* L)
{
UIButton* btn = new UIButton;
SetName(L, btn);
SetTopLeftWidthHeight(L, btn);
SetTooltip(L, btn);
SetAnim(L, btn, UIButton::NORMAL_ANIM_, "normalAnim");
SetAnim(L, btn, UIButton::HOVERED_ANIM_, "hoveredAnim");
SetAnim(L, btn, UIButton::PRESSED_ANIM_, "pressedAnim");
SetAnim(L, btn, UIButton::DISABLED_ANIM_, "disabledAnim");
SetTextUserData(L, btn);
SetPressedSoundKey(L, btn);
AddWidget(L, btn);
lua_pushlightuserdata(L, btn);
return 1;
}
int Label(lua_State* L)
{
UILabel* label = new UILabel;
SetName(L, label);
SetTopLeftWidthHeight(L, label);
SetTooltip(L, label);
SetTextUserData(L, label);
SetPressedSoundKey(L, label);
if (util::HasField(L, "hoveredStyle"))
{
int style = util::GetField_Number(L, "hoveredStyle");
label->SetHoveredStyle(style);
}
if (util::HasField(L, "stringKey"))
{
std::string stringKey = util::GetField_String(L, "stringKey");
if (!stringKey.empty())
label->SetString(StringManager::GetInstance().GetString(stringKey));
}
if (util::HasField(L, "color"))
{
String& str = label->GetString();
Color& color = const_cast<Color&>(str.GetColor());
lua_getfield(L, -1, "color");
SetColor(L, color);
lua_pop(L, 1);
}
lua_pushlightuserdata(L, label);
return 1;
}
int Line(lua_State* L)
{
UILine* line = new UILine;
SetName(L, line);
SetTopLeftWidthHeight(L, line);
SetTooltip(L, line);
SetTextUserData(L, line);
lua_pushlightuserdata(L, line);
return 1;
}
int Panel(lua_State* L)
{
UIPanel* panel = new UIPanel;
SetName(L, panel);
SetTopLeftWidthHeight(L, panel);
SetTooltip(L, panel);
SetAnim(L, panel, UIPanel::NORMAL_ANIM_, "normalAnim");
SetAnim(L, panel, UIPanel::DISABLED_ANIM_, "disabledAnim");
SetTextUserData(L, panel);
AddWidget(L, panel);
lua_pushlightuserdata(L, panel);
return 1;
}
int Progressbar(lua_State* L)
{
UIProgressbar* progressbar = new UIProgressbar;
SetName(L, progressbar);
SetTopLeftWidthHeight(L, progressbar);
SetTooltip(L, progressbar);
SetAnim(L, progressbar, UIProgressbar::BOTTOM_ANIM_, "bottomAnim");
SetAnim(L, progressbar, UIProgressbar::MID_ANIM_, "midAnim");
SetAnim(L, progressbar, UIProgressbar::TOP_ANIM_, "topAnim");
SetTextUserData(L, progressbar);
AddWidget(L, progressbar);
lua_pushlightuserdata(L, progressbar);
return 1;
}
int Window_( lua_State* L )
{
UIWindow* window = new UIWindow;
SetName(L, window);
SetTopLeftWidthHeight(L, window);
SetTooltip(L, window);
SetAnim(L, window, UIPanel::NORMAL_ANIM_, "normalAnim");
SetAnim(L, window, UIPanel::DISABLED_ANIM_, "disabledAnim");
SetTextUserData(L, window);
AddWidget(L, window);
// ùرհť
if (util::HasField(L, "closeBtn"))
{
lua_pushstring(L, "closeBtn");
lua_gettable(L, -2);
if (lua_istable(L, -1))
SetButton(L, window->GetCloseButton());
lua_pop(L, 1);
}
lua_pushlightuserdata(L, window);
return 1;
}
int Widget(lua_State* L)
{
UIWidget* widget = new UIWidget;
SetName(L, widget);
SetTextUserData(L, widget);
AddWidget(L, widget);
lua_pushlightuserdata(L, widget);
return 1;
}
<|endoftext|> |
<commit_before>#ifndef INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#define INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#include <string>
#include <boost/call_traits.hpp>
#include <ackward/core/ExceptionTranslator.hpp>
#include <ackward/core/Object.hpp>
namespace ackward {
namespace core {
/** Property<T> is a value-like C++ interface to an underlying Python
property. It provides a C++ API for properties which is similar to
what you get in Python.
\rst
General use is like this::
class MyClass {
public:
Property<int> myProperty;
};
...
MyClass c;
c.myProperty = 3;
int x = c.myProperty;
\endrst
*/
template <typename T>
class Property : private Object
{
public:
typedef T value_type;
/** Construct a new property.
@param obj The underlying Python object.
@param pythonName The name of the property on `obj`.
*/
Property(boost::python::object obj,
const std::string& pythonName) :
Object (obj),
pythonName_ (pythonName)
{}
/** Get the underlying property value.
*/
operator value_type ()
{
try {
return boost::python::extract<value_type>(
obj().attr(pythonName_));
} TRANSLATE_PYTHON_EXCEPTION();
}
/** Assign to the underlying property.
@param v The value to assign.
@returns This object.
*/
Property<value_type>& operator=(typename boost::call_traits<value_type>::const_reference v)
{
try {
obj().attr(pythonName_) = v;
} TRANSLATE_PYTHON_EXCEPTION();
return *this;
}
using Object::obj;
private:
std::string pythonName_;
};
}
}
#endif
<commit_msg>Added ostream operator support to Property.<commit_after>#ifndef INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#define INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#include <iostream>
#include <string>
#include <boost/call_traits.hpp>
#include <ackward/core/ExceptionTranslator.hpp>
#include <ackward/core/Object.hpp>
namespace ackward {
namespace core {
/** Property<T> is a value-like C++ interface to an underlying Python
property. It provides a C++ API for properties which is similar to
what you get in Python.
\rst
General use is like this::
class MyClass {
public:
Property<int> myProperty;
};
...
MyClass c;
c.myProperty = 3;
int x = c.myProperty;
\endrst
*/
template <typename T>
class Property : private Object
{
public:
typedef T value_type;
/** Construct a new property.
@param obj The underlying Python object.
@param pythonName The name of the property on `obj`.
*/
Property(boost::python::object obj,
const std::string& pythonName) :
Object (obj),
pythonName_ (pythonName)
{}
/** Get the underlying property value.
*/
operator value_type () const
{
try {
return boost::python::extract<value_type>(
obj().attr(pythonName_.c_str()));
} TRANSLATE_PYTHON_EXCEPTION();
}
/** Assign to the underlying property.
@param v The value to assign.
@returns This object.
*/
Property<value_type>& operator=(typename boost::call_traits<value_type>::const_reference v)
{
try {
obj().attr(pythonName_.c_str()) = v;
} TRANSLATE_PYTHON_EXCEPTION();
return *this;
}
using Object::obj;
private:
std::string pythonName_;
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const Property<T>& p)
{
os << static_cast<T>(p);
return os;
}
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dx_winstuff.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _DXCANVAS_WINSTUFF_HXX
#define _DXCANVAS_WINSTUFF_HXX
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <basegfx/numeric/ftools.hxx>
#ifdef _WINDOWS_
#error someone else included <windows.h>
#endif
// Enabling Direct3D Debug Information Further more, with registry key
// \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\D3D9Debugging\\EnableCreationStack
// set to 1, sets a backtrace each time an object is created to the
// following global variable: LPCWSTR CreationCallStack
#if OSL_DEBUG_LEVEL > 0
# define D3D_DEBUG_INFO
#endif
#ifndef DIRECTX_VERSION
#error please define for which directx version we should compile
#endif
#if defined _MSC_VER
#pragma warning(push,1)
#endif
#define BOOL win32BOOL
#define INT32 win32INT32
#define UINT32 win32UINT32
#define GradientStyle_RECT win32GradientStyle_RECT
#define Polygon win32Polygon
#define PolyPolygon win32PolyPolygon
#undef WB_LEFT
#undef WB_RIGHT
#define WIN32_LEAN_AND_MEAN
#include <windows.h> // TODO(Q1): extract minimal set of required headers for gdiplus
#if DIRECTX_VERSION < 0x0900
#include <multimon.h>
// Be compatible with directdraw 3.0. Lets see how far this takes us
#define DIRECTDRAW_VERSION 0x0300
#include <ddraw.h>
// Be compatible with direct3d 5.0. Lets see how far this takes us
#define DIRECT3D_VERSION 0x0500
#define D3D_OVERLOADS
#include <d3d.h>
typedef IDirectDrawSurface surface_type;
#else
#include <d3d9.h>
#include <d3dx9.h>
#include <dxerr9.h>
typedef IDirect3DSurface9 surface_type;
#endif
#undef DrawText
#ifdef __MINGW32__
using ::std::max;
using ::std::min;
#endif
#include <gdiplus.h>
#ifdef min
# undef min
#endif
#ifdef max
# undef max
#endif
namespace dxcanvas
{
// some shared pointer typedefs to Gdiplus objects
typedef ::boost::shared_ptr< Gdiplus::Graphics > GraphicsSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::GraphicsPath > GraphicsPathSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Bitmap > BitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::CachedBitmap > CachedBitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Font > FontSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Brush > BrushSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::TextureBrush > TextureBrushSharedPtr;
/** COM object RAII wrapper
This template wraps a Windows COM object, transparently
handling lifetime issues the C++ way (i.e. releasing the
reference when the object is destroyed)
*/
template< typename T > class COMReference
{
public:
typedef T Wrappee;
COMReference() :
mp( NULL )
{
}
/** Create from raw pointer
@attention This constructor assumes the interface is
already acquired (unless p is NULL), no additional AddRef
is called here.
This caters e.g. for all DirectX factory methods, which
return the created interfaces pre-acquired, into a raw
pointer. Simply pass the pointer to this class, but don't
call Release manually on it!
@example IDirectDrawSurface* pSurface;
pDD->CreateSurface(&aSurfaceDesc, &pSurface, NULL);
mpSurface = COMReference< IDirectDrawSurface >(pSurface);
*/
explicit COMReference( T* p ) :
mp( p )
{
}
COMReference( const COMReference& rNew ) :
mp( NULL )
{
if( rNew.mp == NULL )
return;
rNew.mp->AddRef(); // do that _before_ assigning the
// pointer. Just in case...
mp = rNew.mp;
}
COMReference& operator=( const COMReference& rRHS )
{
COMReference aTmp(rRHS);
::std::swap( mp, aTmp.mp );
return *this;
}
~COMReference()
{
reset();
}
int reset()
{
int refcount = 0;
if( mp )
refcount = mp->Release();
mp = NULL;
return refcount;
}
bool is() const { return mp != NULL; }
T* get() const { return mp; }
T* operator->() const { return mp; }
T& operator*() const { return *mp; }
private:
T* mp;
};
// get_pointer() enables boost::mem_fn to recognize COMReference
template<class T> inline T * get_pointer(COMReference<T> const& p)
{
return p.get();
}
}
#if defined _MSC_VER
#pragma warning(pop)
#endif
#undef DELETE
#undef BOOL
#undef INT32
#undef UINT32
#undef PolyPolygon
#endif /* _DXCANVAS_WINSTUFF_HXX */
<commit_msg>impress181: #i107614#: fixed build error, dxerr9.h has been renamed to dxerr.h in the latest DirectX SDK from August 2009<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dx_winstuff.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _DXCANVAS_WINSTUFF_HXX
#define _DXCANVAS_WINSTUFF_HXX
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <basegfx/numeric/ftools.hxx>
#ifdef _WINDOWS_
#error someone else included <windows.h>
#endif
// Enabling Direct3D Debug Information Further more, with registry key
// \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\D3D9Debugging\\EnableCreationStack
// set to 1, sets a backtrace each time an object is created to the
// following global variable: LPCWSTR CreationCallStack
#if OSL_DEBUG_LEVEL > 0
# define D3D_DEBUG_INFO
#endif
#ifndef DIRECTX_VERSION
#error please define for which directx version we should compile
#endif
#if defined _MSC_VER
#pragma warning(push,1)
#endif
#define BOOL win32BOOL
#define INT32 win32INT32
#define UINT32 win32UINT32
#define GradientStyle_RECT win32GradientStyle_RECT
#define Polygon win32Polygon
#define PolyPolygon win32PolyPolygon
#undef WB_LEFT
#undef WB_RIGHT
#define WIN32_LEAN_AND_MEAN
#include <windows.h> // TODO(Q1): extract minimal set of required headers for gdiplus
#if DIRECTX_VERSION < 0x0900
#include <multimon.h>
// Be compatible with directdraw 3.0. Lets see how far this takes us
#define DIRECTDRAW_VERSION 0x0300
#include <ddraw.h>
// Be compatible with direct3d 5.0. Lets see how far this takes us
#define DIRECT3D_VERSION 0x0500
#define D3D_OVERLOADS
#include <d3d.h>
typedef IDirectDrawSurface surface_type;
#else
#include <d3d9.h>
#include <d3dx9.h>
// #include <dxerr9.h> #i107614# removing include, it has been changed in the latest sdk fron August2009 from dxerr9.h into dxerr.h
typedef IDirect3DSurface9 surface_type;
#endif
#undef DrawText
#ifdef __MINGW32__
using ::std::max;
using ::std::min;
#endif
#include <gdiplus.h>
#ifdef min
# undef min
#endif
#ifdef max
# undef max
#endif
namespace dxcanvas
{
// some shared pointer typedefs to Gdiplus objects
typedef ::boost::shared_ptr< Gdiplus::Graphics > GraphicsSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::GraphicsPath > GraphicsPathSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Bitmap > BitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::CachedBitmap > CachedBitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Font > FontSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Brush > BrushSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::TextureBrush > TextureBrushSharedPtr;
/** COM object RAII wrapper
This template wraps a Windows COM object, transparently
handling lifetime issues the C++ way (i.e. releasing the
reference when the object is destroyed)
*/
template< typename T > class COMReference
{
public:
typedef T Wrappee;
COMReference() :
mp( NULL )
{
}
/** Create from raw pointer
@attention This constructor assumes the interface is
already acquired (unless p is NULL), no additional AddRef
is called here.
This caters e.g. for all DirectX factory methods, which
return the created interfaces pre-acquired, into a raw
pointer. Simply pass the pointer to this class, but don't
call Release manually on it!
@example IDirectDrawSurface* pSurface;
pDD->CreateSurface(&aSurfaceDesc, &pSurface, NULL);
mpSurface = COMReference< IDirectDrawSurface >(pSurface);
*/
explicit COMReference( T* p ) :
mp( p )
{
}
COMReference( const COMReference& rNew ) :
mp( NULL )
{
if( rNew.mp == NULL )
return;
rNew.mp->AddRef(); // do that _before_ assigning the
// pointer. Just in case...
mp = rNew.mp;
}
COMReference& operator=( const COMReference& rRHS )
{
COMReference aTmp(rRHS);
::std::swap( mp, aTmp.mp );
return *this;
}
~COMReference()
{
reset();
}
int reset()
{
int refcount = 0;
if( mp )
refcount = mp->Release();
mp = NULL;
return refcount;
}
bool is() const { return mp != NULL; }
T* get() const { return mp; }
T* operator->() const { return mp; }
T& operator*() const { return *mp; }
private:
T* mp;
};
// get_pointer() enables boost::mem_fn to recognize COMReference
template<class T> inline T * get_pointer(COMReference<T> const& p)
{
return p.get();
}
}
#if defined _MSC_VER
#pragma warning(pop)
#endif
#undef DELETE
#undef BOOL
#undef INT32
#undef UINT32
#undef PolyPolygon
#endif /* _DXCANVAS_WINSTUFF_HXX */
<|endoftext|> |
<commit_before>#ifdef CHANNEL_MKL
#include "Tools/Exception/exception.hpp"
#include "Noise_MKL.hpp"
using namespace aff3ct::tools;
template <typename R>
Noise_MKL<R>
::Noise_MKL(const int seed)
: Noise<R>(), stream_state(nullptr), is_stream_alloc(false)
{
this->set_seed(seed);
}
template <typename R>
Noise_MKL<R>
::~Noise_MKL()
{
if (is_stream_alloc)
vslDeleteStream(&stream_state);
}
template <typename R>
void Noise_MKL<R>
::set_seed(const int seed)
{
if (is_stream_alloc) vslDeleteStream(&stream_state);
//vslNewStream(&stream_state, VSL_BRNG_MT2203, seed);
vslNewStream(&stream_state, VSL_BRNG_SFMT19937, seed);
is_stream_alloc = true;
}
template <typename R>
void Noise_MKL<R>
::generate(R *noise, const unsigned length, const R sigma, const R mu)
{
throw runtime_error(__FILE__, __LINE__, __func__, "Adding white Gaussian noise is impossible on this data type.");
}
namespace aff3ct
{
namespace tools
{
template <>
void Noise_MKL<float>
::generate(float *noise, const unsigned length, const float sigma, const R mu)
{
vsRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2,
stream_state,
length,
noise,
mu,
sigma);
/*
vsRngGaussian(VSL_RNG_METHOD_GAUSSIAN_ICDF,
stream_state,
length,
noise,
mu,
sigma);
*/
}
}
}
namespace aff3ct
{
namespace tools
{
template <>
void Noise_MKL<double>
::generate(double *noise, const unsigned length, const double sigma, const R mu)
{
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2,
stream_state,
length,
noise,
mu,
sigma);
/*
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_ICDF,
stream_state,
length,
noise,
mu,
sigma);
*/
}
}
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::tools::Noise_MKL<R_32>;
template class aff3ct::tools::Noise_MKL<R_64>;
#else
template class aff3ct::tools::Noise_MKL<R>;
#endif
// ==================================================================================== explicit template instantiation
#endif
<commit_msg>Fix Noise MKL algo specialized generate functions<commit_after>#ifdef CHANNEL_MKL
#include "Tools/Exception/exception.hpp"
#include "Noise_MKL.hpp"
using namespace aff3ct::tools;
template <typename R>
Noise_MKL<R>
::Noise_MKL(const int seed)
: Noise<R>(), stream_state(nullptr), is_stream_alloc(false)
{
this->set_seed(seed);
}
template <typename R>
Noise_MKL<R>
::~Noise_MKL()
{
if (is_stream_alloc)
vslDeleteStream(&stream_state);
}
template <typename R>
void Noise_MKL<R>
::set_seed(const int seed)
{
if (is_stream_alloc) vslDeleteStream(&stream_state);
//vslNewStream(&stream_state, VSL_BRNG_MT2203, seed);
vslNewStream(&stream_state, VSL_BRNG_SFMT19937, seed);
is_stream_alloc = true;
}
template <typename R>
void Noise_MKL<R>
::generate(R *noise, const unsigned length, const R sigma, const R mu)
{
throw runtime_error(__FILE__, __LINE__, __func__, "Adding white Gaussian noise is impossible on this data type.");
}
namespace aff3ct
{
namespace tools
{
template <>
void Noise_MKL<float>
::generate(float *noise, const unsigned length, const float sigma, const float mu)
{
vsRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2,
stream_state,
length,
noise,
mu,
sigma);
/*
vsRngGaussian(VSL_RNG_METHOD_GAUSSIAN_ICDF,
stream_state,
length,
noise,
mu,
sigma);
*/
}
}
}
namespace aff3ct
{
namespace tools
{
template <>
void Noise_MKL<double>
::generate(double *noise, const unsigned length, const double sigma, const double mu)
{
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2,
stream_state,
length,
noise,
mu,
sigma);
/*
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_ICDF,
stream_state,
length,
noise,
mu,
sigma);
*/
}
}
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::tools::Noise_MKL<R_32>;
template class aff3ct::tools::Noise_MKL<R_64>;
#else
template class aff3ct::tools::Noise_MKL<R>;
#endif
// ==================================================================================== explicit template instantiation
#endif
<|endoftext|> |
<commit_before><commit_msg>move log_entry_v4 out of unnamed namespace to make validate-reflection test happy<commit_after><|endoftext|> |
<commit_before><commit_msg>[linalg] allow matrix rows to come in non-sorted order.<commit_after><|endoftext|> |
<commit_before>#include "Chan.h"
#include "znc.h"
#include "User.h"
#include "Utils.h"
void CChan::Reset() {
m_bWhoDone = false;
m_bIsOn = false;
m_bIsOp = false;
m_bIsVoice = false;
m_uOpCount = 0;
m_uVoiceCount = 0;
m_uModes = 0;
m_uLimit = 0;
m_uClientRequests = 0;
ClearNicks();
}
void CChan::Joined() {
}
void CChan::Cycle() const {
if (AutoCycle()) {
m_pUser->PutIRC("PART " + GetName() + "\r\nJOIN " + GetName() + " " + GetKey());
}
}
void CChan::JoinUser() {
if (!IsOn()) {
IncClientRequests();
m_pUser->PutIRC("JOIN " + GetName());
return;
}
m_pUser->PutUser(":" + m_pUser->GetIRCNick().GetNickMask() + " JOIN :" + GetName());
if (!GetTopic().empty()) {
m_pUser->PutUser(":" + m_pUser->GetIRCServer() + " 332 " + m_pUser->GetIRCNick().GetNick() + " " + GetName() + " :" + GetTopic());
m_pUser->PutUser(":" + m_pUser->GetIRCServer() + " 333 " + m_pUser->GetIRCNick().GetNick() + " " + GetName() + " " + GetTopicOwner() + " " + CUtils::ToString(GetTopicDate()));
}
string sPre = ":" + m_pUser->GetIRCServer() + " 353 " + m_pUser->GetIRCNick().GetNick() + " = " + GetName() + " :";
string sLine = sPre;
for (map<string,CNick*>::iterator a = m_msNicks.begin(); a != m_msNicks.end(); a++) {
if (a->second->IsOp()) {
sLine += "@";
} else if (a->second->IsVoice()) {
sLine += "+";
}
sLine += a->first;
if (sLine.size() >= 490 || a == (--m_msNicks.end())) {
m_pUser->PutUser(sLine);
sLine = sPre;
} else {
sLine += " ";
}
}
m_pUser->PutUser(":" + m_pUser->GetIRCServer() + " 366 " + m_pUser->GetIRCNick().GetNick() + " " + GetName() + " :End of /NAMES list.");
//m_pUser->PutIRC("NAMES " + GetName());
//m_pUser->PutIRC("TOPIC " + GetName());
SendBuffer();
m_bDetached = false;
}
void CChan::SendBuffer() {
if (m_pUser->IsUserAttached()) {
const vector<string>& vsBuffer = GetBuffer();
if (vsBuffer.size()) {
m_pUser->PutUser(":***!znc@znc.com PRIVMSG " + GetName() + " :Buffer Playback...");
for (unsigned int a = 0; a < vsBuffer.size(); a++) {
m_pUser->PutUser(vsBuffer[a]);
}
if (!KeepBuffer()) {
ClearBuffer();
}
m_pUser->PutUser(":***!znc@znc.com PRIVMSG " + GetName() + " :Playback Complete.");
}
}
}
void CChan::DetachUser() {
m_pUser->PutUser(":" + m_pUser->GetIRCNick().GetNickMask() + " PART " + GetName());
m_bDetached = true;
}
string CChan::GetModeString() const {
string sRet;
if (m_uModes & Secret) { sRet += "s"; }
if (m_uModes & Private) { sRet += "p"; }
if (m_uModes & OpTopic) { sRet += "t"; }
if (m_uModes & InviteOnly) { sRet += "i"; }
if (m_uModes & NoMessages) { sRet += "n"; }
if (m_uModes & Moderated) { sRet += "m"; }
if (m_uLimit) { sRet += "l"; }
if (m_uModes & Key) { sRet += "k"; }
return (sRet.empty()) ? sRet : ("+" + sRet);
}
void CChan::SetModes(const string& sModes) {
m_uModes = 0;
m_uLimit = 0;
m_sKey = "";
ModeChange(sModes);
}
void CChan::IncClientRequests() {
m_uClientRequests++;
}
bool CChan::DecClientRequests() {
if (!m_uClientRequests) {
return false;
}
m_uClientRequests--;
return true;
}
bool CChan::Who() {
if (m_bWhoDone) {
return false;
}
m_pUser->PutIRC("WHO " + GetName());
return true;
}
void CChan::OnWho(const string& sNick, const string& sIdent, const string& sHost) {
CNick* pNick = FindNick(sNick);
if (pNick) {
pNick->SetIdent(sIdent);
pNick->SetHost(sHost);
}
}
void CChan::ModeChange(const string& sModes, const string& sOpNick) {
string sModeArg = CUtils::Token(sModes, 0);
string sArgs = CUtils::Token(sModes, 1, true);
bool bAdd = true;
#ifdef _MODULES
CNick* pNick = FindNick(sOpNick);
if (pNick) {
m_pUser->GetModules().OnRawMode(*pNick, *this, sModeArg, sArgs);
}
#endif
for (unsigned int a = 0; a < sModeArg.size(); a++) {
switch (sModeArg[a]) {
case '+': bAdd = true; break;
case '-': bAdd = false; break;
case 's': if (bAdd) { m_uModes |= Secret; } else { m_uModes &= ~Secret; } break;
case 'p': if (bAdd) { m_uModes |= Private; } else { m_uModes &= ~Private; } break;
case 'm': if (bAdd) { m_uModes |= Moderated; } else { m_uModes &= ~Moderated; } break;
case 'i': if (bAdd) { m_uModes |= InviteOnly; } else { m_uModes &= ~InviteOnly; } break;
case 'n': if (bAdd) { m_uModes |= NoMessages; } else { m_uModes &= ~NoMessages; } break;
case 't': if (bAdd) { m_uModes |= OpTopic; } else { m_uModes &= ~OpTopic; } break;
case 'l': if (bAdd) { m_uLimit = strtoul(GetModeArg(sArgs).c_str(), NULL, 10); } else { m_uLimit = 0; } break;
case 'k': if (bAdd) { m_uModes |= Key; SetKey(GetModeArg(sArgs)); } else { m_uModes &= ~Key; GetModeArg(sArgs); } break;
case 'o': OnOp(sOpNick, GetModeArg(sArgs), bAdd); break;
case 'v': OnVoice(sOpNick, GetModeArg(sArgs), bAdd); break;
case 'b': // Don't do anything with bans yet
case 'e': // Don't do anything with excepts yet
default: GetModeArg(sArgs); // Pop off an arg, assume new modes will have an argument
}
}
}
string CChan::GetModeArg(string& sArgs) const {
string sRet = sArgs.substr(0, sArgs.find(' '));
sArgs = (sRet.size() < sArgs.size()) ? sArgs.substr(sRet.size() +1) : "";
return sRet;
}
void CChan::ClearNicks() {
for (map<string,CNick*>::iterator a = m_msNicks.begin(); a != m_msNicks.end(); a++) {
delete a->second;
}
m_msNicks.clear();
}
int CChan::AddNicks(const string& sNicks) {
if (IsOn()) {
return 0;
}
int iRet = 0;
string sCurNick;
for (unsigned int a = 0; a < sNicks.size(); a++) {
switch (sNicks[a]) {
case ' ':
if (AddNick(sCurNick)) {
iRet++;
}
sCurNick = "";
break;
default:
sCurNick += sNicks[a];
break;
}
}
if (!sCurNick.empty()) {
if (AddNick(sCurNick)) {
iRet++;
}
}
return iRet;
}
bool CChan::AddNick(const string& sNick) {
const char* p = sNick.c_str();
bool bIsOp = false;
bool bIsVoice = false;
switch (*p) {
case '\0':
return false;
case '@':
bIsOp = true;
case '+':
if (!*++p) {
return false;
}
bIsVoice = !bIsOp;
}
CNick* pNick = FindNick(p);
if (!pNick) {
pNick = new CNick(p);
}
if ((bIsOp) && (!pNick->IsOp())) {
IncOpCount();
pNick->SetOp(true);
if (strcasecmp(pNick->GetNick().c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetOpped(true);
}
} else if ((bIsVoice) && (!pNick->IsVoice())) {
IncVoiceCount();
pNick->SetVoice(true);
if (strcasecmp(pNick->GetNick().c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetVoiced(true);
}
}
m_msNicks[pNick->GetNick()] = pNick;
return true;
}
bool CChan::RemNick(const string& sNick) {
map<string,CNick*>::iterator it = m_msNicks.find(sNick);
if (it == m_msNicks.end()) {
return false;
}
if (it->second->IsOp()) {
DecOpCount();
}
if (it->second->IsVoice()) {
DecVoiceCount();
}
delete it->second;
m_msNicks.erase(it);
CNick* pNick = m_msNicks.begin()->second;
if ((m_msNicks.size() == 1) && (!pNick->IsOp()) && (strcasecmp(pNick->GetNick().c_str(), m_pUser->GetCurNick().c_str()) == 0)) {
Cycle();
}
return true;
}
bool CChan::ChangeNick(const string& sOldNick, const string& sNewNick) {
map<string,CNick*>::iterator it = m_msNicks.find(sOldNick);
if (it == m_msNicks.end()) {
return false;
}
// Rename this nick
it->second->SetNick(sNewNick);
// Insert a new element into the map then erase the old one, do this to change the key
m_msNicks[sNewNick] = it->second;
m_msNicks.erase(it);
return true;
}
void CChan::OnOp(const string& sOpNick, const string& sNick, bool bOpped) {
CNick* pNick = FindNick(sNick);
if (pNick) {
bool bNoChange = (pNick->IsOp() == bOpped);
#ifdef _MODULES
CNick* pOpNick = FindNick(sOpNick);
if (pOpNick) {
if (bOpped) {
m_pUser->GetModules().OnOp(*pOpNick, *pNick, *this, bNoChange);
} else {
m_pUser->GetModules().OnDeop(*pOpNick, *pNick, *this, bNoChange);
}
}
#endif
if (strcasecmp(sNick.c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetOpped(bOpped);
}
if (bNoChange) {
// If no change, return
return;
}
pNick->SetOp(bOpped);
(bOpped) ? IncOpCount() : DecOpCount();
}
}
void CChan::OnVoice(const string& sOpNick, const string& sNick, bool bVoiced) {
CNick* pNick = FindNick(sNick);
if (pNick) {
bool bNoChange = (pNick->IsVoice() == bVoiced);
#ifdef _MODULES
CNick* pOpNick = FindNick(sOpNick);
if (pOpNick) {
if (bVoiced) {
m_pUser->GetModules().OnVoice(*pOpNick, *pNick, *this, bNoChange);
} else {
m_pUser->GetModules().OnDevoice(*pOpNick, *pNick, *this, bNoChange);
}
}
#endif
if (strcasecmp(sNick.c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetVoiced(bVoiced);
}
if (bNoChange) {
// If no change, return
return;
}
pNick->SetVoice(bVoiced);
(bVoiced) ? IncVoiceCount() : DecVoiceCount();
}
}
CNick* CChan::FindNick(const string& sNick) const {
map<string,CNick*>::const_iterator it = m_msNicks.find(sNick);
return (it != m_msNicks.end()) ? it->second : NULL;
}
int CChan::AddBuffer(const string& sLine) {
// Todo: revisit the buffering
if (!m_uBufferCount) {
return 0;
}
if (m_vsBuffer.size() >= m_uBufferCount) {
m_vsBuffer.erase(m_vsBuffer.begin());
}
m_vsBuffer.push_back(sLine);
return m_vsBuffer.size();
}
void CChan::ClearBuffer() {
m_vsBuffer.clear();
}
<commit_msg>Moved AutoCycle() check to the caller instead of inside of Cycle()<commit_after>#include "Chan.h"
#include "znc.h"
#include "User.h"
#include "Utils.h"
void CChan::Reset() {
m_bWhoDone = false;
m_bIsOn = false;
m_bIsOp = false;
m_bIsVoice = false;
m_uOpCount = 0;
m_uVoiceCount = 0;
m_uModes = 0;
m_uLimit = 0;
m_uClientRequests = 0;
ClearNicks();
}
void CChan::Joined() {
}
void CChan::Cycle() const {
m_pUser->PutIRC("PART " + GetName() + "\r\nJOIN " + GetName() + " " + GetKey());
}
void CChan::JoinUser() {
if (!IsOn()) {
IncClientRequests();
m_pUser->PutIRC("JOIN " + GetName());
return;
}
m_pUser->PutUser(":" + m_pUser->GetIRCNick().GetNickMask() + " JOIN :" + GetName());
if (!GetTopic().empty()) {
m_pUser->PutUser(":" + m_pUser->GetIRCServer() + " 332 " + m_pUser->GetIRCNick().GetNick() + " " + GetName() + " :" + GetTopic());
m_pUser->PutUser(":" + m_pUser->GetIRCServer() + " 333 " + m_pUser->GetIRCNick().GetNick() + " " + GetName() + " " + GetTopicOwner() + " " + CUtils::ToString(GetTopicDate()));
}
string sPre = ":" + m_pUser->GetIRCServer() + " 353 " + m_pUser->GetIRCNick().GetNick() + " = " + GetName() + " :";
string sLine = sPre;
for (map<string,CNick*>::iterator a = m_msNicks.begin(); a != m_msNicks.end(); a++) {
if (a->second->IsOp()) {
sLine += "@";
} else if (a->second->IsVoice()) {
sLine += "+";
}
sLine += a->first;
if (sLine.size() >= 490 || a == (--m_msNicks.end())) {
m_pUser->PutUser(sLine);
sLine = sPre;
} else {
sLine += " ";
}
}
m_pUser->PutUser(":" + m_pUser->GetIRCServer() + " 366 " + m_pUser->GetIRCNick().GetNick() + " " + GetName() + " :End of /NAMES list.");
//m_pUser->PutIRC("NAMES " + GetName());
//m_pUser->PutIRC("TOPIC " + GetName());
SendBuffer();
m_bDetached = false;
}
void CChan::SendBuffer() {
if (m_pUser->IsUserAttached()) {
const vector<string>& vsBuffer = GetBuffer();
if (vsBuffer.size()) {
m_pUser->PutUser(":***!znc@znc.com PRIVMSG " + GetName() + " :Buffer Playback...");
for (unsigned int a = 0; a < vsBuffer.size(); a++) {
m_pUser->PutUser(vsBuffer[a]);
}
if (!KeepBuffer()) {
ClearBuffer();
}
m_pUser->PutUser(":***!znc@znc.com PRIVMSG " + GetName() + " :Playback Complete.");
}
}
}
void CChan::DetachUser() {
m_pUser->PutUser(":" + m_pUser->GetIRCNick().GetNickMask() + " PART " + GetName());
m_bDetached = true;
}
string CChan::GetModeString() const {
string sRet;
if (m_uModes & Secret) { sRet += "s"; }
if (m_uModes & Private) { sRet += "p"; }
if (m_uModes & OpTopic) { sRet += "t"; }
if (m_uModes & InviteOnly) { sRet += "i"; }
if (m_uModes & NoMessages) { sRet += "n"; }
if (m_uModes & Moderated) { sRet += "m"; }
if (m_uLimit) { sRet += "l"; }
if (m_uModes & Key) { sRet += "k"; }
return (sRet.empty()) ? sRet : ("+" + sRet);
}
void CChan::SetModes(const string& sModes) {
m_uModes = 0;
m_uLimit = 0;
m_sKey = "";
ModeChange(sModes);
}
void CChan::IncClientRequests() {
m_uClientRequests++;
}
bool CChan::DecClientRequests() {
if (!m_uClientRequests) {
return false;
}
m_uClientRequests--;
return true;
}
bool CChan::Who() {
if (m_bWhoDone) {
return false;
}
m_pUser->PutIRC("WHO " + GetName());
return true;
}
void CChan::OnWho(const string& sNick, const string& sIdent, const string& sHost) {
CNick* pNick = FindNick(sNick);
if (pNick) {
pNick->SetIdent(sIdent);
pNick->SetHost(sHost);
}
}
void CChan::ModeChange(const string& sModes, const string& sOpNick) {
string sModeArg = CUtils::Token(sModes, 0);
string sArgs = CUtils::Token(sModes, 1, true);
bool bAdd = true;
#ifdef _MODULES
CNick* pNick = FindNick(sOpNick);
if (pNick) {
m_pUser->GetModules().OnRawMode(*pNick, *this, sModeArg, sArgs);
}
#endif
for (unsigned int a = 0; a < sModeArg.size(); a++) {
switch (sModeArg[a]) {
case '+': bAdd = true; break;
case '-': bAdd = false; break;
case 's': if (bAdd) { m_uModes |= Secret; } else { m_uModes &= ~Secret; } break;
case 'p': if (bAdd) { m_uModes |= Private; } else { m_uModes &= ~Private; } break;
case 'm': if (bAdd) { m_uModes |= Moderated; } else { m_uModes &= ~Moderated; } break;
case 'i': if (bAdd) { m_uModes |= InviteOnly; } else { m_uModes &= ~InviteOnly; } break;
case 'n': if (bAdd) { m_uModes |= NoMessages; } else { m_uModes &= ~NoMessages; } break;
case 't': if (bAdd) { m_uModes |= OpTopic; } else { m_uModes &= ~OpTopic; } break;
case 'l': if (bAdd) { m_uLimit = strtoul(GetModeArg(sArgs).c_str(), NULL, 10); } else { m_uLimit = 0; } break;
case 'k': if (bAdd) { m_uModes |= Key; SetKey(GetModeArg(sArgs)); } else { m_uModes &= ~Key; GetModeArg(sArgs); } break;
case 'o': OnOp(sOpNick, GetModeArg(sArgs), bAdd); break;
case 'v': OnVoice(sOpNick, GetModeArg(sArgs), bAdd); break;
case 'b': // Don't do anything with bans yet
case 'e': // Don't do anything with excepts yet
default: GetModeArg(sArgs); // Pop off an arg, assume new modes will have an argument
}
}
}
string CChan::GetModeArg(string& sArgs) const {
string sRet = sArgs.substr(0, sArgs.find(' '));
sArgs = (sRet.size() < sArgs.size()) ? sArgs.substr(sRet.size() +1) : "";
return sRet;
}
void CChan::ClearNicks() {
for (map<string,CNick*>::iterator a = m_msNicks.begin(); a != m_msNicks.end(); a++) {
delete a->second;
}
m_msNicks.clear();
}
int CChan::AddNicks(const string& sNicks) {
if (IsOn()) {
return 0;
}
int iRet = 0;
string sCurNick;
for (unsigned int a = 0; a < sNicks.size(); a++) {
switch (sNicks[a]) {
case ' ':
if (AddNick(sCurNick)) {
iRet++;
}
sCurNick = "";
break;
default:
sCurNick += sNicks[a];
break;
}
}
if (!sCurNick.empty()) {
if (AddNick(sCurNick)) {
iRet++;
}
}
return iRet;
}
bool CChan::AddNick(const string& sNick) {
const char* p = sNick.c_str();
bool bIsOp = false;
bool bIsVoice = false;
switch (*p) {
case '\0':
return false;
case '@':
bIsOp = true;
case '+':
if (!*++p) {
return false;
}
bIsVoice = !bIsOp;
}
CNick* pNick = FindNick(p);
if (!pNick) {
pNick = new CNick(p);
}
if ((bIsOp) && (!pNick->IsOp())) {
IncOpCount();
pNick->SetOp(true);
if (strcasecmp(pNick->GetNick().c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetOpped(true);
}
} else if ((bIsVoice) && (!pNick->IsVoice())) {
IncVoiceCount();
pNick->SetVoice(true);
if (strcasecmp(pNick->GetNick().c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetVoiced(true);
}
}
m_msNicks[pNick->GetNick()] = pNick;
return true;
}
bool CChan::RemNick(const string& sNick) {
map<string,CNick*>::iterator it = m_msNicks.find(sNick);
if (it == m_msNicks.end()) {
return false;
}
if (it->second->IsOp()) {
DecOpCount();
}
if (it->second->IsVoice()) {
DecVoiceCount();
}
delete it->second;
m_msNicks.erase(it);
CNick* pNick = m_msNicks.begin()->second;
if ((m_msNicks.size() == 1) && (!pNick->IsOp()) && (strcasecmp(pNick->GetNick().c_str(), m_pUser->GetCurNick().c_str()) == 0)) {
if (AutoCycle()) {
Cycle();
}
}
return true;
}
bool CChan::ChangeNick(const string& sOldNick, const string& sNewNick) {
map<string,CNick*>::iterator it = m_msNicks.find(sOldNick);
if (it == m_msNicks.end()) {
return false;
}
// Rename this nick
it->second->SetNick(sNewNick);
// Insert a new element into the map then erase the old one, do this to change the key
m_msNicks[sNewNick] = it->second;
m_msNicks.erase(it);
return true;
}
void CChan::OnOp(const string& sOpNick, const string& sNick, bool bOpped) {
CNick* pNick = FindNick(sNick);
if (pNick) {
bool bNoChange = (pNick->IsOp() == bOpped);
#ifdef _MODULES
CNick* pOpNick = FindNick(sOpNick);
if (pOpNick) {
if (bOpped) {
m_pUser->GetModules().OnOp(*pOpNick, *pNick, *this, bNoChange);
} else {
m_pUser->GetModules().OnDeop(*pOpNick, *pNick, *this, bNoChange);
}
}
#endif
if (strcasecmp(sNick.c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetOpped(bOpped);
}
if (bNoChange) {
// If no change, return
return;
}
pNick->SetOp(bOpped);
(bOpped) ? IncOpCount() : DecOpCount();
}
}
void CChan::OnVoice(const string& sOpNick, const string& sNick, bool bVoiced) {
CNick* pNick = FindNick(sNick);
if (pNick) {
bool bNoChange = (pNick->IsVoice() == bVoiced);
#ifdef _MODULES
CNick* pOpNick = FindNick(sOpNick);
if (pOpNick) {
if (bVoiced) {
m_pUser->GetModules().OnVoice(*pOpNick, *pNick, *this, bNoChange);
} else {
m_pUser->GetModules().OnDevoice(*pOpNick, *pNick, *this, bNoChange);
}
}
#endif
if (strcasecmp(sNick.c_str(), m_pUser->GetCurNick().c_str()) == 0) {
SetVoiced(bVoiced);
}
if (bNoChange) {
// If no change, return
return;
}
pNick->SetVoice(bVoiced);
(bVoiced) ? IncVoiceCount() : DecVoiceCount();
}
}
CNick* CChan::FindNick(const string& sNick) const {
map<string,CNick*>::const_iterator it = m_msNicks.find(sNick);
return (it != m_msNicks.end()) ? it->second : NULL;
}
int CChan::AddBuffer(const string& sLine) {
// Todo: revisit the buffering
if (!m_uBufferCount) {
return 0;
}
if (m_vsBuffer.size() >= m_uBufferCount) {
m_vsBuffer.erase(m_vsBuffer.begin());
}
m_vsBuffer.push_back(sLine);
return m_vsBuffer.size();
}
void CChan::ClearBuffer() {
m_vsBuffer.clear();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006-2020 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "algorithmfactory.h"
#include "essentiamath.h"
#include "noveltycurve.h"
using namespace std;
namespace essentia {
namespace standard {
const char* NoveltyCurve::name = "NoveltyCurve";
const char* NoveltyCurve::category = "Rhythm";
const char* NoveltyCurve::description = DOC("This algorithm computes the \"novelty curve\" (Grosche & Müller, 2009) onset detection function. The algorithm expects as an input a frame-wise sequence of frequency-bands energies or spectrum magnitudes as originally proposed in [1] (see FrequencyBands and Spectrum algorithms). Novelty in each band (or frequency bin) is computed as a derivative between log-compressed energy (magnitude) values in consequent frames. The overall novelty value is then computed as a weighted sum that can be configured using 'weightCurve' parameter. The resulting novelty curve can be used for beat tracking and onset detection (see BpmHistogram and Onsets).\n"
"\n"
"Notes:\n"
"- Recommended frame/hop size for spectrum computation is 2048/1024 samples (44.1 kHz sampling rate) [2].\n"
"- Log compression is applied with C=1000 as in [1].\n"
"- Frequency bands energies (see FrequencyBands) as well as bin magnitudes for the whole spectrum can be used as an input. The implementation for the original algorithm [2] works with spectrum bin magnitudes for which novelty functions are computed separately and are then summarized into bands.\n"
"- In the case if 'weightCurve' is set to 'hybrid' a complex combination of flat, quadratic, linear and inverse quadratic weight curves is used. It was reported to improve performance of beat tracking in some informal in-house experiments (Note: this information is probably outdated).\n"
"\n"
"References:\n"
" [1] P. Grosche and M. Müller, \"A mid-level representation for capturing\n"
" dominant tempo and pulse information in music recordings,\" in\n"
" International Society for Music Information Retrieval Conference\n"
" (ISMIR’09), 2009, pp. 189–194.\n"
" [2] Tempogram Toolbox (Matlab implementation),\n"
" http://resources.mpi-inf.mpg.de/MIR/tempogramtoolbox\n");
vector<Real> NoveltyCurve::weightCurve(int size, WeightType type) {
vector<Real> result(size, 0.0);
int halfSize = size/2;
int sqrHalfSize = halfSize*halfSize;
int sqrSize = size*size;
// NB:some of these curves have a +1 so we don't reach zero!!
switch(type) {
case FLAT:
fill(result.begin(), result.end(), Real(1.0));
break;
case TRIANGLE:
for (int i=0; i<halfSize; i++) {
result[i] = result[size-1-i] = i+1;
}
if ((size&1) == 1) result[halfSize] = size/2; // for odd sizes
break;
case INVERSE_TRIANGLE:
for (int i=0; i<halfSize; i++) {
result[i] = result[size-1-i] = halfSize-i;
}
break;
case PARABOLA:
for (int i=0; i<halfSize; i++) {
result[i] = result[size-1-i] = (halfSize-i)*(halfSize-i);
}
break;
case INVERSE_PARABOLA:
for (int i=0; i<halfSize; i++) {
result[i] = sqrHalfSize - (halfSize-i)*(halfSize-i)+1;
result[size-1-i] = result[i];
}
if ((size&1) == 1) result[halfSize] = halfSize; // for odd sizes
break;
case LINEAR:
for (int i=0; i<size; i++) result[i] = i+1;
break;
case QUADRATIC:
for (int i=0; i<size; i++) result[i] = i*i+1;
break;
case INVERSE_QUADRATIC:
for (int i=0; i<size; i++) result[i] = sqrSize - i*i;
break;
case SUPPLIED:
result = parameter("weightCurve").toVectorReal();
if (int(result.size()) != size) {
throw EssentiaException("NoveltyCurve::weightCurve, the size of the supplied weights must be the same as the number of the frequency bands", size);
}
break;
default:
throw EssentiaException("Weighting Curve type not known");
}
//Real max = *max_element(result.begin(), result.end());
//if (max == 0) throw EssentiaException("Weighting curves has null maximum");
//for (int i=0; i<size; i++) result[i] /= max;
return result;
}
/**
* Compute the novelty curve for a single variable (energy band, spectrum bin, ...).
* Resulting output vector size is equal to the input vector. The first value is always set
* to 0 because for it the derivative cannot be defined.
*/
vector<Real> NoveltyCurve::noveltyFunction(const vector<Real>& spec, Real C, int meanSize) {
int size = spec.size();
int dsize = size - 1;
vector<Real> logSpec(size, 0.0), novelty(dsize, 0.0);
for (int i=0; i<size; i++) logSpec[i] = log10(1 + C*spec[i]);
// differentiate log spec and keep only positive variations
for (int i=1; i<size; i++) {
Real d = logSpec[i] - logSpec[i-1];
if (d>0) novelty[i-1] = d;
}
// subtract local mean
for (int i=0; i<dsize; i++) {
int start = i - meanSize/2, end = i + meanSize/2;
// TODO: decide on which option to choose
// Nico adjust
//start = max(start, 0);
//end = min(end, size-1);
// Edu adjust
if (start<0 && end>=dsize) {start=0; end=dsize;}
else {
if (start<0) { start=0; end=meanSize;}
if (end>=dsize) { end=dsize; start=dsize-meanSize;}
}
Real m = essentia::mean(novelty, start, end);
if (novelty[i] < m) novelty[i]=0.0;
else novelty[i] -= m;
}
if (_normalize) {
Real maxValue = *max_element(novelty.begin(), novelty.end());
if (maxValue != 0) {
vector<Real>::iterator it = novelty.begin();
for (;it!=novelty.end(); ++it) *it /= maxValue;
}
}
Algorithm * mavg = AlgorithmFactory::create("MovingAverage", "size", meanSize);
vector<Real> novelty_ma;
mavg->input("signal").set(novelty);
mavg->output("signal").set(novelty_ma);
mavg->compute();
delete mavg;
return novelty_ma;
}
void NoveltyCurve::configure() {
string type = parameter("weightCurveType").toString();
if (type == "flat") _type = FLAT;
else if (type == "triangle") _type = TRIANGLE;
else if (type == "inverse_triangle") _type = INVERSE_TRIANGLE;
else if (type == "parabola") _type = PARABOLA;
else if (type == "inverse_parabola") _type = INVERSE_PARABOLA;
else if (type == "linear") _type = LINEAR;
else if (type == "quadratic") _type = QUADRATIC;
else if (type == "inverse_quadratic") _type = INVERSE_QUADRATIC;
else if (type == "supplied") _type = SUPPLIED;
else if (type == "hybrid") _type = HYBRID;
_frameRate = parameter("frameRate").toReal();
_normalize = parameter("normalize").toBool();
}
void NoveltyCurve::compute() {
const vector<vector<Real> >& frequencyBands = _frequencyBands.get();
vector<Real>& novelty = _novelty.get();
if (frequencyBands.empty())
throw EssentiaException("NoveltyCurve::compute, cannot compute from an empty input matrix");
int nFrames = frequencyBands.size();
int nBands = (int)frequencyBands[0].size();
//vector<Real> weights = weightCurve(nBands);
novelty.resize(nFrames-1);
fill(novelty.begin(), novelty.end(), Real(0.0));
vector<vector<Real> > t_frequencyBands = essentia::transpose(frequencyBands); // [bands x frames]
vector<vector<Real> > noveltyBands(nBands);
int meanSize = int(0.1 * _frameRate); // integral number of frames in 2*0.05 second
// compute novelty for each sub-band
meanSize += (meanSize % 2); // force even size // TODO: why?
for (int bandIdx=0; bandIdx<nBands; bandIdx++) {
noveltyBands[bandIdx] = noveltyFunction(t_frequencyBands[bandIdx], 1000, meanSize);
}
//sum novelty on all bands (weighted) to get a single novelty value per frame
noveltyBands = essentia::transpose(noveltyBands); // back to [frames x bands]
// TODO: weight curves should be pre-computed in configure() method
if (_type == HYBRID) {
// EAylon: By trial-&-error I found that combining weightings (flat, quadratic,
// linear and inverse quadratic) was giving better results.
vector<Real> aweights = weightCurve(nBands, FLAT);
vector<Real> bweights = weightCurve(nBands, QUADRATIC);
vector<Real> cweights = weightCurve(nBands, LINEAR);
vector<Real> dweights = weightCurve(nBands, INVERSE_QUADRATIC);
vector<Real> bnovelty(nFrames-1, 0.0);
vector<Real> cnovelty(nFrames-1, 0.0);
vector<Real> dnovelty(nFrames-1, 0.0);
for (int frameIdx=0; frameIdx<nFrames-1; frameIdx++) { // noveltyBands is a derivative whose size is nframes-1
for (int bandIdx=0; bandIdx<nBands; bandIdx++) {
novelty[frameIdx] += aweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
bnovelty[frameIdx] += bweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
cnovelty[frameIdx] += cweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
dnovelty[frameIdx] += dweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
}
}
for (int frameIdx=0; frameIdx<nFrames-1; frameIdx++) {
// TODO why multiplication instead of sum (or mean)?
novelty[frameIdx] *= bnovelty[frameIdx];
novelty[frameIdx] *= cnovelty[frameIdx];
novelty[frameIdx] *= dnovelty[frameIdx];
}
}
else {
// TODO weight curve should be pre-computed in configure() method
vector<Real> weights = weightCurve(nBands, _type);
for (int frameIdx=0; frameIdx<nFrames-1; frameIdx++) {
for (int bandIdx=0; bandIdx<nBands; bandIdx++) {
novelty[frameIdx] += weights[bandIdx] * noveltyBands[frameIdx][bandIdx];
}
}
}
// smoothing
Algorithm * mavg = AlgorithmFactory::create("MovingAverage", "size", meanSize);
vector<Real> novelty_ma;
mavg->input("signal").set(novelty);
mavg->output("signal").set(novelty_ma);
mavg->compute();
delete mavg;
novelty.assign(novelty_ma.begin(), novelty_ma.end());
}
void NoveltyCurve::reset() {
Algorithm::reset();
}
} // namespace standard
} // namespace essentia
#include "poolstorage.h"
#include "algorithmfactory.h"
namespace essentia {
namespace streaming {
const char* NoveltyCurve::name = standard::NoveltyCurve::name;
const char* NoveltyCurve::description = standard::NoveltyCurve::description;
NoveltyCurve::NoveltyCurve() : AlgorithmComposite() {
_noveltyCurve = standard::AlgorithmFactory::create("NoveltyCurve");
_poolStorage = new PoolStorage<vector<Real> >(&_pool, "internal.frequencyBands");
declareInput(_frequencyBands, 1, "frequencyBands", "the frequency bands");
declareOutput(_novelty, 0, "novelty", "the novelty curve as a single vector");
_frequencyBands >> _poolStorage->input("data"); // attach input proxy
// Need to set the buffer type to multiple frames as all the values
// are output all at once
_novelty.setBufferType(BufferUsage::forMultipleFrames);
}
NoveltyCurve::~NoveltyCurve() {
delete _noveltyCurve;
delete _poolStorage;
}
void NoveltyCurve::reset() {
AlgorithmComposite::reset();
_noveltyCurve->reset();
}
AlgorithmStatus NoveltyCurve::process() {
if (!shouldStop()) return PASS;
vector<Real> novelty;
_noveltyCurve->input("frequencyBands").set(_pool.value<vector<vector<Real> > >("internal.frequencyBands"));
_noveltyCurve->output("novelty").set(novelty);
_noveltyCurve->compute();
for (size_t i=0; i<novelty.size(); ++i) {
_novelty.push(novelty[i]);
}
return FINISHED;
}
} // namespace streaming
} // namespace essentia<commit_msg>Fix DOC formatting for NoveltyCurve<commit_after>/*
* Copyright (C) 2006-2020 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "algorithmfactory.h"
#include "essentiamath.h"
#include "noveltycurve.h"
using namespace std;
namespace essentia {
namespace standard {
const char* NoveltyCurve::name = "NoveltyCurve";
const char* NoveltyCurve::category = "Rhythm";
const char* NoveltyCurve::description = DOC("This algorithm computes the \"novelty curve\" (Grosche & Müller, 2009) onset detection function. The algorithm expects as an input a frame-wise sequence of frequency-bands energies or spectrum magnitudes as originally proposed in [1] (see FrequencyBands and Spectrum algorithms). Novelty in each band (or frequency bin) is computed as a derivative between log-compressed energy (magnitude) values in consequent frames. The overall novelty value is then computed as a weighted sum that can be configured using 'weightCurve' parameter. The resulting novelty curve can be used for beat tracking and onset detection (see BpmHistogram and Onsets).\n"
"\n"
"Notes:\n"
"\n"
"- Recommended frame/hop size for spectrum computation is 2048/1024 samples (44.1 kHz sampling rate) [2].\n"
"- Log compression is applied with C=1000 as in [1].\n"
"- Frequency bands energies (see FrequencyBands) as well as bin magnitudes for the whole spectrum can be used as an input. The implementation for the original algorithm [2] works with spectrum bin magnitudes for which novelty functions are computed separately and are then summarized into bands.\n"
"- In the case if 'weightCurve' is set to 'hybrid' a complex combination of flat, quadratic, linear and inverse quadratic weight curves is used. It was reported to improve performance of beat tracking in some informal in-house experiments (Note: this information is probably outdated).\n"
"\n"
"References:\n"
"\n"
"1. Grosche, P. & Müller, M. (2009). A mid-level representation for capturing "
"dominant tempo and pulse information in music recordings. "
"International Society for Music Information Retrieval Conference (ISMIR 2009).\n"
"\n"
"2. Tempogram Toolbox (Matlab implementation), "
"http://resources.mpi%2Dinf.mpg.de/MIR/tempogramtoolbox\n\n");
vector<Real> NoveltyCurve::weightCurve(int size, WeightType type) {
vector<Real> result(size, 0.0);
int halfSize = size/2;
int sqrHalfSize = halfSize*halfSize;
int sqrSize = size*size;
// NB:some of these curves have a +1 so we don't reach zero!!
switch(type) {
case FLAT:
fill(result.begin(), result.end(), Real(1.0));
break;
case TRIANGLE:
for (int i=0; i<halfSize; i++) {
result[i] = result[size-1-i] = i+1;
}
if ((size&1) == 1) result[halfSize] = size/2; // for odd sizes
break;
case INVERSE_TRIANGLE:
for (int i=0; i<halfSize; i++) {
result[i] = result[size-1-i] = halfSize-i;
}
break;
case PARABOLA:
for (int i=0; i<halfSize; i++) {
result[i] = result[size-1-i] = (halfSize-i)*(halfSize-i);
}
break;
case INVERSE_PARABOLA:
for (int i=0; i<halfSize; i++) {
result[i] = sqrHalfSize - (halfSize-i)*(halfSize-i)+1;
result[size-1-i] = result[i];
}
if ((size&1) == 1) result[halfSize] = halfSize; // for odd sizes
break;
case LINEAR:
for (int i=0; i<size; i++) result[i] = i+1;
break;
case QUADRATIC:
for (int i=0; i<size; i++) result[i] = i*i+1;
break;
case INVERSE_QUADRATIC:
for (int i=0; i<size; i++) result[i] = sqrSize - i*i;
break;
case SUPPLIED:
result = parameter("weightCurve").toVectorReal();
if (int(result.size()) != size) {
throw EssentiaException("NoveltyCurve::weightCurve, the size of the supplied weights must be the same as the number of the frequency bands", size);
}
break;
default:
throw EssentiaException("Weighting Curve type not known");
}
//Real max = *max_element(result.begin(), result.end());
//if (max == 0) throw EssentiaException("Weighting curves has null maximum");
//for (int i=0; i<size; i++) result[i] /= max;
return result;
}
/**
* Compute the novelty curve for a single variable (energy band, spectrum bin, ...).
* Resulting output vector size is equal to the input vector. The first value is always set
* to 0 because for it the derivative cannot be defined.
*/
vector<Real> NoveltyCurve::noveltyFunction(const vector<Real>& spec, Real C, int meanSize) {
int size = spec.size();
int dsize = size - 1;
vector<Real> logSpec(size, 0.0), novelty(dsize, 0.0);
for (int i=0; i<size; i++) logSpec[i] = log10(1 + C*spec[i]);
// differentiate log spec and keep only positive variations
for (int i=1; i<size; i++) {
Real d = logSpec[i] - logSpec[i-1];
if (d>0) novelty[i-1] = d;
}
// subtract local mean
for (int i=0; i<dsize; i++) {
int start = i - meanSize/2, end = i + meanSize/2;
// TODO: decide on which option to choose
// Nico adjust
//start = max(start, 0);
//end = min(end, size-1);
// Edu adjust
if (start<0 && end>=dsize) {start=0; end=dsize;}
else {
if (start<0) { start=0; end=meanSize;}
if (end>=dsize) { end=dsize; start=dsize-meanSize;}
}
Real m = essentia::mean(novelty, start, end);
if (novelty[i] < m) novelty[i]=0.0;
else novelty[i] -= m;
}
if (_normalize) {
Real maxValue = *max_element(novelty.begin(), novelty.end());
if (maxValue != 0) {
vector<Real>::iterator it = novelty.begin();
for (;it!=novelty.end(); ++it) *it /= maxValue;
}
}
Algorithm * mavg = AlgorithmFactory::create("MovingAverage", "size", meanSize);
vector<Real> novelty_ma;
mavg->input("signal").set(novelty);
mavg->output("signal").set(novelty_ma);
mavg->compute();
delete mavg;
return novelty_ma;
}
void NoveltyCurve::configure() {
string type = parameter("weightCurveType").toString();
if (type == "flat") _type = FLAT;
else if (type == "triangle") _type = TRIANGLE;
else if (type == "inverse_triangle") _type = INVERSE_TRIANGLE;
else if (type == "parabola") _type = PARABOLA;
else if (type == "inverse_parabola") _type = INVERSE_PARABOLA;
else if (type == "linear") _type = LINEAR;
else if (type == "quadratic") _type = QUADRATIC;
else if (type == "inverse_quadratic") _type = INVERSE_QUADRATIC;
else if (type == "supplied") _type = SUPPLIED;
else if (type == "hybrid") _type = HYBRID;
_frameRate = parameter("frameRate").toReal();
_normalize = parameter("normalize").toBool();
}
void NoveltyCurve::compute() {
const vector<vector<Real> >& frequencyBands = _frequencyBands.get();
vector<Real>& novelty = _novelty.get();
if (frequencyBands.empty())
throw EssentiaException("NoveltyCurve::compute, cannot compute from an empty input matrix");
int nFrames = frequencyBands.size();
int nBands = (int)frequencyBands[0].size();
//vector<Real> weights = weightCurve(nBands);
novelty.resize(nFrames-1);
fill(novelty.begin(), novelty.end(), Real(0.0));
vector<vector<Real> > t_frequencyBands = essentia::transpose(frequencyBands); // [bands x frames]
vector<vector<Real> > noveltyBands(nBands);
int meanSize = int(0.1 * _frameRate); // integral number of frames in 2*0.05 second
// compute novelty for each sub-band
meanSize += (meanSize % 2); // force even size // TODO: why?
for (int bandIdx=0; bandIdx<nBands; bandIdx++) {
noveltyBands[bandIdx] = noveltyFunction(t_frequencyBands[bandIdx], 1000, meanSize);
}
//sum novelty on all bands (weighted) to get a single novelty value per frame
noveltyBands = essentia::transpose(noveltyBands); // back to [frames x bands]
// TODO: weight curves should be pre-computed in configure() method
if (_type == HYBRID) {
// EAylon: By trial-&-error I found that combining weightings (flat, quadratic,
// linear and inverse quadratic) was giving better results.
vector<Real> aweights = weightCurve(nBands, FLAT);
vector<Real> bweights = weightCurve(nBands, QUADRATIC);
vector<Real> cweights = weightCurve(nBands, LINEAR);
vector<Real> dweights = weightCurve(nBands, INVERSE_QUADRATIC);
vector<Real> bnovelty(nFrames-1, 0.0);
vector<Real> cnovelty(nFrames-1, 0.0);
vector<Real> dnovelty(nFrames-1, 0.0);
for (int frameIdx=0; frameIdx<nFrames-1; frameIdx++) { // noveltyBands is a derivative whose size is nframes-1
for (int bandIdx=0; bandIdx<nBands; bandIdx++) {
novelty[frameIdx] += aweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
bnovelty[frameIdx] += bweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
cnovelty[frameIdx] += cweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
dnovelty[frameIdx] += dweights[bandIdx] * noveltyBands[frameIdx][bandIdx];
}
}
for (int frameIdx=0; frameIdx<nFrames-1; frameIdx++) {
// TODO why multiplication instead of sum (or mean)?
novelty[frameIdx] *= bnovelty[frameIdx];
novelty[frameIdx] *= cnovelty[frameIdx];
novelty[frameIdx] *= dnovelty[frameIdx];
}
}
else {
// TODO weight curve should be pre-computed in configure() method
vector<Real> weights = weightCurve(nBands, _type);
for (int frameIdx=0; frameIdx<nFrames-1; frameIdx++) {
for (int bandIdx=0; bandIdx<nBands; bandIdx++) {
novelty[frameIdx] += weights[bandIdx] * noveltyBands[frameIdx][bandIdx];
}
}
}
// smoothing
Algorithm * mavg = AlgorithmFactory::create("MovingAverage", "size", meanSize);
vector<Real> novelty_ma;
mavg->input("signal").set(novelty);
mavg->output("signal").set(novelty_ma);
mavg->compute();
delete mavg;
novelty.assign(novelty_ma.begin(), novelty_ma.end());
}
void NoveltyCurve::reset() {
Algorithm::reset();
}
} // namespace standard
} // namespace essentia
#include "poolstorage.h"
#include "algorithmfactory.h"
namespace essentia {
namespace streaming {
const char* NoveltyCurve::name = standard::NoveltyCurve::name;
const char* NoveltyCurve::description = standard::NoveltyCurve::description;
NoveltyCurve::NoveltyCurve() : AlgorithmComposite() {
_noveltyCurve = standard::AlgorithmFactory::create("NoveltyCurve");
_poolStorage = new PoolStorage<vector<Real> >(&_pool, "internal.frequencyBands");
declareInput(_frequencyBands, 1, "frequencyBands", "the frequency bands");
declareOutput(_novelty, 0, "novelty", "the novelty curve as a single vector");
_frequencyBands >> _poolStorage->input("data"); // attach input proxy
// Need to set the buffer type to multiple frames as all the values
// are output all at once
_novelty.setBufferType(BufferUsage::forMultipleFrames);
}
NoveltyCurve::~NoveltyCurve() {
delete _noveltyCurve;
delete _poolStorage;
}
void NoveltyCurve::reset() {
AlgorithmComposite::reset();
_noveltyCurve->reset();
}
AlgorithmStatus NoveltyCurve::process() {
if (!shouldStop()) return PASS;
vector<Real> novelty;
_noveltyCurve->input("frequencyBands").set(_pool.value<vector<vector<Real> > >("internal.frequencyBands"));
_noveltyCurve->output("novelty").set(novelty);
_noveltyCurve->compute();
for (size_t i=0; i<novelty.size(); ++i) {
_novelty.push(novelty[i]);
}
return FINISHED;
}
} // namespace streaming
} // namespace essentia
<|endoftext|> |
<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// 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 https://mozilla.org/MPL/2.0/.
#include "Datasheet.hpp"
#include <string>
#include <algorithm>
#include <boost/algorithm/string/predicate.hpp>
namespace aliceVision {
namespace sensorDB {
bool Datasheet::operator==(const Datasheet& other) const
{
std::string brandA = _brand;
std::string brandB = other._brand;
std::transform(brandA.begin(), brandA.end(), brandA.begin(), ::tolower); //tolower
std::transform(brandB.begin(), brandB.end(), brandB.begin(), ::tolower); //tolower
brandA.erase(std::remove_if(brandA.begin(), brandA.end(), ::ispunct), brandA.end()); //remove punctuation
brandB.erase(std::remove_if(brandB.begin(), brandB.end(), ::ispunct), brandB.end()); //remove punctuation
if(brandA == brandB)
{
std::string modelA = _model;
std::string modelB = other._model;
std::transform(modelA.begin(), modelA.end(), modelA.begin(), ::tolower); //tolower
std::transform(modelB.begin(), modelB.end(), modelB.begin(), ::tolower); //tolower
modelA.erase(std::remove_if(modelA.begin(), modelA.end(), ::ispunct), modelA.end()); //remove punctuation
modelB.erase(std::remove_if(modelB.begin(), modelB.end(), ::ispunct), modelB.end()); //remove punctuation
if((modelA == modelB) ||
(boost::algorithm::ends_with(modelA, modelB)) ||
(boost::algorithm::ends_with(modelB, modelA)))
return true;
}
return false;
}
} // namespace sensorDB
} // namespace aliceVision
<commit_msg>[sensorDB] Use boost `to_lower` instead of `transform`<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// 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 https://mozilla.org/MPL/2.0/.
#include "Datasheet.hpp"
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
namespace aliceVision {
namespace sensorDB {
bool Datasheet::operator==(const Datasheet& other) const
{
std::string brandA = _brand;
std::string brandB = other._brand;
boost::algorithm::to_lower(brandA);
boost::algorithm::to_lower(brandB);
brandA.erase(std::remove_if(brandA.begin(), brandA.end(), ::ispunct), brandA.end()); //remove punctuation
brandB.erase(std::remove_if(brandB.begin(), brandB.end(), ::ispunct), brandB.end()); //remove punctuation
if(brandA == brandB)
{
std::string modelA = _model;
std::string modelB = other._model;
boost::algorithm::to_lower(modelA);
boost::algorithm::to_lower(modelB);
modelA.erase(std::remove_if(modelA.begin(), modelA.end(), ::ispunct), modelA.end()); //remove punctuation
modelB.erase(std::remove_if(modelB.begin(), modelB.end(), ::ispunct), modelB.end()); //remove punctuation
if((modelA == modelB) ||
(boost::algorithm::ends_with(modelA, modelB)) ||
(boost::algorithm::ends_with(modelB, modelA)))
return true;
}
return false;
}
} // namespace sensorDB
} // namespace aliceVision
<|endoftext|> |
<commit_before>#include "espresso_core.h"
int main(int argc, char** argv) {
handle_cmd_args(argc, argv);
load_persistent_metadata(argv[METADATA_FILE]);
// TODO: open filesystem data for when you need it
// filepath is argv[FILESYSTEM]
printf("persistent metadata on %s has been loaded, ", argv[NAME_ID]);
printf("opening espresso node to network connections\n");
// register espresso callback functions in network layer
register_read_data_callback(read_data);
register_write_data_callback(write_data);
register_delete_data_callback(delete_data);
// the svc_main_loop function lives in network core and
// calls registered espresso functions as it receives the rpcs
svc_main_loop(argc, argv);
return 0;
}
ssize_t read_data (int fd, int file_id, int stripe_id, int chunk_num, int offset, void *buf, int count) {
printf("read_data called, espresso_core\n");
return read_chunk(fd, file_id, stripe_id, chunk_num, offset, buf, count);
}
ssize_t write_data (int fd, int file_id, int stripe_id, int chunk_num, int offset, void *buf, int count) {
return write_chunk(fd, file_id, stripe_id, chunk_num, offset, buf, count);
}
int delete_data (int fd, int file_id, int stripe_id, int chunk_num) {
printf("delete_data called, espresso_core\n");
return delete_chunk(fd, file_id, stripe_id, chunk_num);
}
void load_persistent_metadata(char* metadata_path) {
printf("loading metadata from: %s\n", metadata_path);
// TODO: load metadata
}
void handle_cmd_args(int argc, char** argv) {
if (argc == NUM_EXPECTED_ARGS) {
}
else {
fprintf(stderr, "%s exiting: invalid command line arguments provided", argv[0]);
fprintf(stderr, "\nUsage: %s <id> <persistent metadata path> <data path>\n", argv[0]);
exit(-1);
}
}
<commit_msg>changed #defined names in espresso_core<commit_after>#include "espresso_core.h"
int main(int argc, char** argv) {
handle_cmd_args(argc, argv);
load_persistent_metadata(argv[METADATA]);
// TODO: open filesystem data for when you need it
// filepath is argv[FILESYSTEM]
printf("persistent metadata on %s has been loaded, ", argv[NAME]);
printf("opening espresso node to network connections\n");
// register espresso callback functions in network layer
register_read_data_callback(read_data);
register_write_data_callback(write_data);
register_delete_data_callback(delete_data);
// the svc_main_loop function lives in network core and
// calls registered espresso functions as it receives the rpcs
svc_main_loop(argc, argv);
return 0;
}
ssize_t read_data (int fd, int file_id, int stripe_id, int chunk_num, int offset, void *buf, int count) {
printf("read_data called, espresso_core\n");
return read_chunk(fd, file_id, stripe_id, chunk_num, offset, buf, count);
}
ssize_t write_data (int fd, int file_id, int stripe_id, int chunk_num, int offset, void *buf, int count) {
return write_chunk(fd, file_id, stripe_id, chunk_num, offset, buf, count);
}
int delete_data (int fd, int file_id, int stripe_id, int chunk_num) {
printf("delete_data called, espresso_core\n");
return delete_chunk(fd, file_id, stripe_id, chunk_num);
}
void load_persistent_metadata(char* metadata_path) {
printf("loading metadata from: %s\n", metadata_path);
// TODO: load metadata
}
void handle_cmd_args(int argc, char** argv) {
if (argc == NUM_EXPECTED_ARGS) {
}
else {
fprintf(stderr, "%s exiting: invalid command line arguments provided", argv[0]);
fprintf(stderr, "\nUsage: %s <id> <persistent metadata path> <data path>\n", argv[0]);
exit(-1);
}
}
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* libtest
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <stdexcept>
#ifndef __PRETTY_FUNCTION__
#define __PRETTY_FUNCTION__ __func__
#endif
#define LIBYATL_DEFAULT_PARAM __FILE__, __LINE__, __PRETTY_FUNCTION__
namespace libtest {
class fatal : std::runtime_error
{
public:
fatal(const char *file, int line, const char *func, const char *format, ...);
const char* what() const throw()
{
return _error_message;
}
// The following are just for unittesting the exception class
static bool is_disabled();
static bool disable();
static bool enable();
static uint32_t disabled_counter();
static void increment_disabled_counter();
private:
char _error_message[BUFSIZ];
};
} // namespace libtest
#define fatal_message(__mesg) libtest::fatal(LIBYATL_DEFAULT_PARAM, __mesg)
<commit_msg>Update of libtest.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* libtest
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <stdexcept>
#ifndef __PRETTY_FUNCTION__
#define __PRETTY_FUNCTION__ __func__
#endif
#define LIBYATL_DEFAULT_PARAM __FILE__, __LINE__, __PRETTY_FUNCTION__
namespace libtest {
class fatal : std::runtime_error
{
public:
fatal(const char *file, int line, const char *func, const char *format, ...);
const char* what() const throw()
{
return _error_message;
}
// The following are just for unittesting the exception class
static bool is_disabled();
static bool disable();
static bool enable();
static uint32_t disabled_counter();
static void increment_disabled_counter();
private:
char _error_message[BUFSIZ];
};
} // namespace libtest
#define fatal_message(__mesg) libtest::fatal(LIBYATL_DEFAULT_PARAM, __mesg)
#define fatal_assert(__assert) if((__assert)) {} else { libtest::fatal(LIBYATL_DEFAULT_PARAM, #__assert); }
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* Main file for the io board application on the Tiva Launchpad board.
*
* @author Balazs Racz
* @date 5 Jun 2015
*/
#define LOGLEVEL INFO
#include <algorithm>
#include "os/os.h"
#include "nmranet_config.h"
#include "openlcb/SimpleStack.hxx"
#include "openlcb/ConfiguredConsumer.hxx"
#include "openlcb/MultiConfiguredConsumer.hxx"
#include "openlcb/ConfiguredProducer.hxx"
#include "utils/gc_format.h"
#include "freertos_drivers/ti/TivaGPIO.hxx"
#include "freertos_drivers/ti/TivaCpuLoad.hxx"
#include "freertos_drivers/common/BlinkerGPIO.hxx"
#include "freertos_drivers/common/PersistentGPIO.hxx"
#include "freertos_drivers/common/BenchmarkCan.hxx"
#include "config.hxx"
#include "hardware.hxx"
// Writes all log data to stderr.
#include "utils/TcpLogging.hxx"
BenchmarkCan benchmark_can("/dev/fakecan0");
// These preprocessor symbols are used to select which physical connections
// will be enabled in the main(). See @ref appl_main below.
//#define SNIFF_ON_SERIAL
//#define SNIFF_ON_USB
//#define HAVE_PHYSICAL_CAN_PORT
// Changes the default behavior by adding a newline after each gridconnect
// packet. Makes it easier for debugging the raw device.
OVERRIDE_CONST(gc_generate_newlines, 1);
// Specifies how much RAM (in bytes) we allocate to the stack of the main
// thread. Useful tuning parameter in case the application runs out of memory.
OVERRIDE_CONST(main_thread_stack_size, 2500);
// Specifies the 48-bit OpenLCB node identifier. This must be unique for every
// hardware manufactured, so in production this should be replaced by some
// easily incrementable method.
extern const openlcb::NodeID NODE_ID = 0x050101011804ULL;
// Sets up a comprehensive OpenLCB stack for a single virtual node. This stack
// contains everything needed for a usual peripheral node -- all
// CAN-bus-specific components, a virtual node, PIP, SNIP, Memory configuration
// protocol, ACDI, CDI, a bunch of memory spaces, etc.
openlcb::SimpleCanStack stack(NODE_ID);
SerialLoggingServer log_server(stack.service(), "/dev/ser0");
TivaCpuLoad<TivaCpuLoadDefHw> load_monitor;
#include "freertos_drivers/common/cpu_profile.hxx"
DEFINE_CPU_PROFILE_INTERRUPT_HANDLER(timer4a_interrupt_handler);
class BenchmarkDriver : public StateFlowBase
{
public:
BenchmarkDriver()
: StateFlowBase(stack.service())
{
start_flow(STATE(log_and_wait));
}
private:
Action log_and_wait() {
if (!SW1_Pin::get()) {
return call_immediately(STATE(do_benchmark));
}
return sleep_and_call(&timer_, MSEC_TO_NSEC(100), STATE(log_and_wait));
}
Action do_benchmark() {
struct can_frame frame;
LOG(INFO, "Starting benchmark.");
HHASSERT(0 == gc_format_parse("X195B4123N0501010118FF0123", &frame));
startTime_ = OSTime::get_monotonic();
benchmark_can.start_benchmark(&frame, COUNT);
enable_profiling = 1;
return sleep_and_call(
&timer_, MSEC_TO_NSEC(100), STATE(check_benchmark_state));
}
Action check_benchmark_state() {
unsigned count = 1;
auto end_time = benchmark_can.get_timestamp(&count);
if (!count) {
enable_profiling = 0;
float spd = COUNT;
float time = (end_time - startTime_);
time /= 1e9;
spd /= time;
LOG(INFO, "Benchmark done. Time %d msec, speed %d pkt/sec",
static_cast<int>((end_time - startTime_ + 500000) / 1000000),
static_cast<int>(spd));
return call_immediately(STATE(log_and_wait));
} else {
LOG(INFO, "benchmark: %u pkt left", count);
}
return sleep_and_call(
&timer_, MSEC_TO_NSEC(100), STATE(check_benchmark_state));
}
static constexpr unsigned COUNT = 10000;
long long startTime_;
StateFlowTimer timer_{this};
} benchmark_driver;
class CpuLoadLog : public StateFlowBase
{
public:
CpuLoadLog()
: StateFlowBase(stack.service())
{
start_flow(STATE(log_and_wait));
}
private:
Action log_and_wait()
{
auto *l = CpuLoad::instance();
LOG(INFO, "Load: avg %3d max streak %d max of 16 %d", l->get_load(),
l->get_max_consecutive(), l->get_peak_over_16_counts());
l->clear_max_consecutive();
l->clear_peak_over_16_counts();
vector<pair<unsigned, string*> > per_task_ticks;
unsigned c = l->get_utilization_delta(&per_task_ticks);
std::sort(per_task_ticks.begin(), per_task_ticks.end(), std::greater<>());
string details;
for (volatile auto it : per_task_ticks) {
int perc = it.first * 1000 / c;
details += StringPrintf(" | %d.%d:", perc / 10, perc % 10);
details += *it.second;
}
log_output((char*)details.data(), details.size());
auto k = l->new_key();
if (k > 300) {
char* name = pcTaskGetName((TaskHandle_t)k);
l->set_key_description(k, name);
} else {
l->set_key_description(k, StringPrintf("irq-%u", k));
}
return sleep_and_call(&timer_, MSEC_TO_NSEC(2000), STATE(log_and_wait));
}
StateFlowTimer timer_{this};
} load_logger;
// ConfigDef comes from config.hxx and is specific to the particular device and
// target. It defines the layout of the configuration memory space and is also
// used to generate the cdi.xml file. Here we instantiate the configuration
// layout. The argument of offset zero is ignored and will be removed later.
openlcb::ConfigDef cfg(0);
// Defines weak constants used by the stack to tell it which device contains
// the volatile configuration information. This device name appears in
// HwInit.cxx that creates the device drivers.
extern const char *const openlcb::CONFIG_FILENAME = "/dev/eeprom";
// The size of the memory space to export over the above device.
extern const size_t openlcb::CONFIG_FILE_SIZE =
cfg.seg().size() + cfg.seg().offset();
static_assert(openlcb::CONFIG_FILE_SIZE <= 300, "Need to adjust eeprom size");
// The SNIP user-changeable information in also stored in the above eeprom
// device. In general this could come from different eeprom segments, but it is
// simpler to keep them together.
extern const char *const openlcb::SNIP_DYNAMIC_FILENAME =
openlcb::CONFIG_FILENAME;
// Defines the GPIO ports used for the producers and the consumers.
// Defines the GPIO ports used for the producers and the consumers.
// The first LED is driven by the blinker device from BlinkerGPIO.hxx. WE just
// create an alias for symmetry.
typedef BLINKER_Pin XLED_B1_Pin;
// Instantiates the actual producer and consumer objects for the given GPIO
// pins from above. The ConfiguredConsumer class takes care of most of the
// complicated setup and operation requirements. We need to give it the virtual
// node pointer, the configuration configuration from the CDI definition, and
// the hardware pin definition. The virtual node pointer comes from the stack
// object. The configuration structure comes from the CDI definition object,
// segment 'seg', in which there is a repeated group 'consumers', and we assign
// the individual entries to the individual consumers. Each consumer gets its
// own GPIO pin.
openlcb::ConfiguredConsumer consumer_1(
stack.node(), cfg.seg().consumers().entry<0>(), LED_B1_Pin());
openlcb::ConfiguredConsumer consumer_2(
stack.node(), cfg.seg().consumers().entry<1>(), LED_B2_Pin());
openlcb::ConfiguredConsumer consumer_3(
stack.node(), cfg.seg().consumers().entry<2>(), LED_B3_Pin());
openlcb::ConfiguredConsumer consumer_4(
stack.node(), cfg.seg().consumers().entry<3>(), LED_B4_Pin());
// Similar syntax for the producers.
openlcb::ConfiguredProducer producer_sw1(
stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin());
openlcb::ConfiguredProducer producer_sw2(
stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin());
// The producers need to be polled repeatedly for changes and to execute the
// debouncing algorithm. This class instantiates a refreshloop and adds the two
// producers to it.
openlcb::RefreshLoop loop(
stack.node(), {producer_sw1.polling(), producer_sw2.polling()});
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
stack.check_version_and_factory_reset(
cfg.seg().internal_config(), openlcb::CANONICAL_VERSION, false);
stack.add_can_port_select("/dev/fakecan0");
// This command donates the main thread to the operation of the
// stack. Alternatively the stack could be started in a separate stack and
// then application-specific business logic could be executed ion a busy
// loop in the main thread.
stack.loop_executor();
return 0;
}
<commit_msg>Fixes compilation for the 129 performance benchmark.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* Main file for the io board application on the Tiva Launchpad board.
*
* @author Balazs Racz
* @date 5 Jun 2015
*/
#define LOGLEVEL INFO
#include <algorithm>
#include "os/os.h"
#include "nmranet_config.h"
#include "openlcb/SimpleStack.hxx"
#include "openlcb/ConfiguredConsumer.hxx"
#include "openlcb/MultiConfiguredConsumer.hxx"
#include "openlcb/ConfiguredProducer.hxx"
#include "utils/gc_format.h"
#include "freertos_drivers/ti/TivaGPIO.hxx"
#include "freertos_drivers/ti/TivaCpuLoad.hxx"
#include "freertos_drivers/common/BlinkerGPIO.hxx"
#include "freertos_drivers/common/PersistentGPIO.hxx"
#include "freertos_drivers/common/BenchmarkCan.hxx"
#include "config.hxx"
#include "hardware.hxx"
// Writes all log data to stderr.
#include "utils/TcpLogging.hxx"
BenchmarkCan benchmark_can("/dev/fakecan0");
// These preprocessor symbols are used to select which physical connections
// will be enabled in the main(). See @ref appl_main below.
//#define SNIFF_ON_SERIAL
//#define SNIFF_ON_USB
//#define HAVE_PHYSICAL_CAN_PORT
// Changes the default behavior by adding a newline after each gridconnect
// packet. Makes it easier for debugging the raw device.
OVERRIDE_CONST(gc_generate_newlines, 1);
// Specifies how much RAM (in bytes) we allocate to the stack of the main
// thread. Useful tuning parameter in case the application runs out of memory.
OVERRIDE_CONST(main_thread_stack_size, 2500);
// Specifies the 48-bit OpenLCB node identifier. This must be unique for every
// hardware manufactured, so in production this should be replaced by some
// easily incrementable method.
extern const openlcb::NodeID NODE_ID = 0x050101011804ULL;
// Sets up a comprehensive OpenLCB stack for a single virtual node. This stack
// contains everything needed for a usual peripheral node -- all
// CAN-bus-specific components, a virtual node, PIP, SNIP, Memory configuration
// protocol, ACDI, CDI, a bunch of memory spaces, etc.
openlcb::SimpleCanStack stack(NODE_ID);
SerialLoggingServer log_server(stack.service(), "/dev/ser0");
TivaCpuLoad<TivaCpuLoadDefHw> load_monitor;
#include "freertos_drivers/common/cpu_profile.hxx"
DEFINE_CPU_PROFILE_INTERRUPT_HANDLER(timer4a_interrupt_handler,
MAP_TimerIntClear(TIMER4_BASE, TIMER_TIMA_TIMEOUT));
class BenchmarkDriver : public StateFlowBase
{
public:
BenchmarkDriver()
: StateFlowBase(stack.service())
{
start_flow(STATE(log_and_wait));
}
private:
Action log_and_wait() {
if (!SW1_Pin::get()) {
return call_immediately(STATE(do_benchmark));
}
return sleep_and_call(&timer_, MSEC_TO_NSEC(100), STATE(log_and_wait));
}
Action do_benchmark() {
struct can_frame frame;
LOG(INFO, "Starting benchmark.");
auto ret = gc_format_parse("X195B4123N0501010118FF0123", &frame);
HASSERT(0 == ret);
startTime_ = OSTime::get_monotonic();
benchmark_can.start_benchmark(&frame, COUNT);
enable_profiling = 1;
return sleep_and_call(
&timer_, MSEC_TO_NSEC(100), STATE(check_benchmark_state));
}
Action check_benchmark_state() {
unsigned count = 1;
auto end_time = benchmark_can.get_timestamp(&count);
if (!count) {
enable_profiling = 0;
float spd = COUNT;
float time = (end_time - startTime_);
time /= 1e9;
spd /= time;
LOG(INFO, "Benchmark done. Time %d msec, speed %d pkt/sec",
static_cast<int>((end_time - startTime_ + 500000) / 1000000),
static_cast<int>(spd));
return call_immediately(STATE(log_and_wait));
} else {
LOG(INFO, "benchmark: %u pkt left", count);
}
return sleep_and_call(
&timer_, MSEC_TO_NSEC(100), STATE(check_benchmark_state));
}
static constexpr unsigned COUNT = 10000;
long long startTime_;
StateFlowTimer timer_{this};
} benchmark_driver;
CpuLoadLog load_logger(stack.service());
// ConfigDef comes from config.hxx and is specific to the particular device and
// target. It defines the layout of the configuration memory space and is also
// used to generate the cdi.xml file. Here we instantiate the configuration
// layout. The argument of offset zero is ignored and will be removed later.
openlcb::ConfigDef cfg(0);
// Defines weak constants used by the stack to tell it which device contains
// the volatile configuration information. This device name appears in
// HwInit.cxx that creates the device drivers.
extern const char *const openlcb::CONFIG_FILENAME = "/dev/eeprom";
// The size of the memory space to export over the above device.
extern const size_t openlcb::CONFIG_FILE_SIZE =
cfg.seg().size() + cfg.seg().offset();
static_assert(openlcb::CONFIG_FILE_SIZE <= 300, "Need to adjust eeprom size");
// The SNIP user-changeable information in also stored in the above eeprom
// device. In general this could come from different eeprom segments, but it is
// simpler to keep them together.
extern const char *const openlcb::SNIP_DYNAMIC_FILENAME =
openlcb::CONFIG_FILENAME;
// Defines the GPIO ports used for the producers and the consumers.
// Defines the GPIO ports used for the producers and the consumers.
// The first LED is driven by the blinker device from BlinkerGPIO.hxx. WE just
// create an alias for symmetry.
typedef BLINKER_Pin XLED_B1_Pin;
// Instantiates the actual producer and consumer objects for the given GPIO
// pins from above. The ConfiguredConsumer class takes care of most of the
// complicated setup and operation requirements. We need to give it the virtual
// node pointer, the configuration configuration from the CDI definition, and
// the hardware pin definition. The virtual node pointer comes from the stack
// object. The configuration structure comes from the CDI definition object,
// segment 'seg', in which there is a repeated group 'consumers', and we assign
// the individual entries to the individual consumers. Each consumer gets its
// own GPIO pin.
openlcb::ConfiguredConsumer consumer_1(
stack.node(), cfg.seg().consumers().entry<0>(), LED_B1_Pin());
openlcb::ConfiguredConsumer consumer_2(
stack.node(), cfg.seg().consumers().entry<1>(), LED_B2_Pin());
openlcb::ConfiguredConsumer consumer_3(
stack.node(), cfg.seg().consumers().entry<2>(), LED_B3_Pin());
openlcb::ConfiguredConsumer consumer_4(
stack.node(), cfg.seg().consumers().entry<3>(), LED_B4_Pin());
// Similar syntax for the producers.
openlcb::ConfiguredProducer producer_sw1(
stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin());
openlcb::ConfiguredProducer producer_sw2(
stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin());
// The producers need to be polled repeatedly for changes and to execute the
// debouncing algorithm. This class instantiates a refreshloop and adds the two
// producers to it.
openlcb::RefreshLoop loop(
stack.node(), {producer_sw1.polling(), producer_sw2.polling()});
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
stack.check_version_and_factory_reset(
cfg.seg().internal_config(), openlcb::CANONICAL_VERSION, false);
stack.add_can_port_select("/dev/fakecan0");
// This command donates the main thread to the operation of the
// stack. Alternatively the stack could be started in a separate stack and
// then application-specific business logic could be executed ion a busy
// loop in the main thread.
stack.loop_executor();
return 0;
}
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file brainflowboard.cpp
* @author Andrey Parfenov <a1994ndrey@gmail.com>
* @version dev
* @date February, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Andrey Parfenov. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Contains the definition of the BrainFlowBoard class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <QMessageBox>
#include "data_filter.h"
#include "brainflowboard.h"
#include "FormFiles/brainflowsetupwidget.h"
#include "FormFiles/brainflowstreamingwidget.h"
#include <fiff/fiff_info.h>
#include <scMeas/realtimemultisamplearray.h>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace BRAINFLOWBOARDPLUGIN;
using namespace SCSHAREDLIB;
using namespace SCMEASLIB;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
BrainFlowBoard::BrainFlowBoard()
: m_pBoardShim(NULL)
, m_pChannels(NULL)
, m_iBoardId((int)BoardIds::SYNTHETIC_BOARD)
, m_bIsRunning(false)
, m_pOutput(NULL)
, m_iSamplingFreq(0)
, m_sStreamerParams("")
, m_iNumberChannels(0)
, m_pFiffInfo(QSharedPointer<FiffInfo>::create())
{
m_pShowSettingsAction = new QAction(QIcon(":/images/options.png"), tr("Streaming Settings"),this);
m_pShowSettingsAction->setStatusTip(tr("Streaming Settings"));
connect(m_pShowSettingsAction, &QAction::triggered, this, &BrainFlowBoard::showSettings);
addPluginAction(m_pShowSettingsAction);
m_pOutput = PluginOutputData<RealTimeMultiSampleArray>::create(this, "BrainFlowBoard", "BrainFlow Board Output");
m_outputConnectors.append(m_pOutput);
}
//*************************************************************************************************************
BrainFlowBoard::~BrainFlowBoard()
{
releaseSession(false);
}
//*************************************************************************************************************
void BrainFlowBoard::showSettings()
{
BrainFlowStreamingWidget *widget = new BrainFlowStreamingWidget(this);
widget->show();
}
//*************************************************************************************************************
QSharedPointer<IPlugin> BrainFlowBoard::clone() const
{
QSharedPointer<BrainFlowBoard> pClone(new BrainFlowBoard());
return pClone;
}
//*************************************************************************************************************
void BrainFlowBoard::init()
{
BoardShim::set_log_file((char *)"brainflow_log.txt");
BoardShim::enable_dev_board_logger();
}
//*************************************************************************************************************
void BrainFlowBoard::unload()
{
}
//*************************************************************************************************************
void BrainFlowBoard::setUpFiffInfo()
{
//
//Clear old fiff info data
//
m_pFiffInfo->clear();
//
//Set number of channels, sampling frequency and high/-lowpass
//
m_pFiffInfo->nchan = m_iNumberChannels;
m_pFiffInfo->sfreq = m_iSamplingFreq;
m_pFiffInfo->highpass = 0.001f;
m_pFiffInfo->lowpass = m_iSamplingFreq/2;
//
//Set up the channel info
//
QStringList QSLChNames;
m_pFiffInfo->chs.clear();
for(int i = 0; i < m_pFiffInfo->nchan; ++i)
{
//Create information for each channel
QString sChType;
FiffChInfo fChInfo;
//Set channel name
sChType = QString("Ch ");
if(i<10) {
sChType.append("00");
}
if(i>=10 && i<100) {
sChType.append("0");
}
fChInfo.ch_name = sChType.append(sChType.number(i));
//Set channel type
fChInfo.kind = FIFFV_EEG_CH;
//Set logno
fChInfo.logNo = i;
//Set coord frame
fChInfo.coord_frame = FIFFV_COORD_HEAD;
//Set unit
fChInfo.unit = FIFF_UNIT_V;
//Set EEG electrode location - Convert from mm to m
fChInfo.eeg_loc(0,0) = 0;
fChInfo.eeg_loc(1,0) = 0;
fChInfo.eeg_loc(2,0) = 0;
//Set EEG electrode direction - Convert from mm to m
fChInfo.eeg_loc(0,1) = 0;
fChInfo.eeg_loc(1,1) = 0;
fChInfo.eeg_loc(2,1) = 0;
//Also write the eeg electrode locations into the meg loc variable (mne_ex_read_raw() matlab function wants this)
fChInfo.chpos.r0(0) = 0;
fChInfo.chpos.r0(1) = 0;
fChInfo.chpos.r0(2) = 0;
fChInfo.chpos.ex(0) = 1;
fChInfo.chpos.ex(1) = 0;
fChInfo.chpos.ex(2) = 0;
fChInfo.chpos.ey(0) = 0;
fChInfo.chpos.ey(1) = 1;
fChInfo.chpos.ey(2) = 0;
fChInfo.chpos.ez(0) = 0;
fChInfo.chpos.ez(1) = 0;
fChInfo.chpos.ez(2) = 1;
// //Digital input channel
// if(i == m_pFiffInfo->nchan-1)
// {
// //Set channel type
// fChInfo.kind = FIFFV_STIM_CH;
// sChType = QString("STIM");
// fChInfo.ch_name = sChType;
// }
QSLChNames << sChType;
m_pFiffInfo->chs.append(fChInfo);
}
//Set channel names in fiff_info_base
m_pFiffInfo->ch_names = QSLChNames;
//
//Set head projection
//
m_pFiffInfo->dev_head_t.from = FIFFV_COORD_DEVICE;
m_pFiffInfo->dev_head_t.to = FIFFV_COORD_HEAD;
m_pFiffInfo->ctf_head_t.from = FIFFV_COORD_DEVICE;
m_pFiffInfo->ctf_head_t.to = FIFFV_COORD_HEAD;
}
//*************************************************************************************************************
bool BrainFlowBoard::start()
{
if (!m_pBoardShim)
{
QMessageBox msgBox;
msgBox.setText("Configure streaming session before run!");
msgBox.exec();
return false;
}
try {
m_pBoardShim->start_stream(m_iSamplingFreq * 100, (char*)m_sStreamerParams.c_str());
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
QMessageBox msgBox;
msgBox.setText("Failed to start streaming.");
msgBox.exec();
return false;
}
m_bIsRunning = true;
QThread::start();
return true;
}
//*************************************************************************************************************
bool BrainFlowBoard::stop()
{
try {
m_pBoardShim->stop_stream();
m_bIsRunning = false;
m_pOutput->data()->clear();
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
return false;
}
return true;
}
//*************************************************************************************************************
IPlugin::PluginType BrainFlowBoard::getType() const
{
return _ISensor;
}
//*************************************************************************************************************
QString BrainFlowBoard::getName() const
{
return "BrainFlow Board Plugin";
}
//*************************************************************************************************************
QWidget* BrainFlowBoard::setupWidget()
{
BrainFlowSetupWidget* widget = new BrainFlowSetupWidget(this);
return widget;
}
//*************************************************************************************************************
void BrainFlowBoard::prepareSession(BrainFlowInputParams params,
std::string streamerParams,
int boardId,
int dataType,
int vertScale)
{
if (m_pBoardShim)
{
QMessageBox msgBox;
msgBox.setText("Streaming session already prepared.");
msgBox.exec();
return;
}
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, "Vert Scale is %d %d", vertScale);
QMessageBox msgBox;
m_iBoardId = boardId;
m_sStreamerParams = streamerParams;
try {
switch (dataType)
{
case 0:
m_pChannels = BoardShim::get_eeg_channels(boardId, &m_iNumberChannels);
break;
case 1:
m_pChannels = BoardShim::get_emg_channels(boardId, &m_iNumberChannels);
break;
case 2:
m_pChannels = BoardShim::get_ecg_channels(boardId, &m_iNumberChannels);
break;
case 3:
m_pChannels = BoardShim::get_eog_channels(boardId, &m_iNumberChannels);
break;
case 4:
m_pChannels = BoardShim::get_eda_channels(boardId, &m_iNumberChannels);
break;
default:
throw BrainFlowException ("unsupported data type", UNSUPPORTED_BOARD_ERROR);
break;
}
m_iSamplingFreq = BoardShim::get_sampling_rate(boardId);
m_pBoardShim = new BoardShim(m_iBoardId, params);
m_pBoardShim->prepare_session();
setUpFiffInfo();
m_pOutput->data()->initFromFiffInfo(m_pFiffInfo);
m_pOutput->data()->setMultiArraySize(1);
msgBox.setText("Streaming session is ready");
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
msgBox.setText("Invalid parameters. Check logs for details.");
delete[] m_pChannels;
delete m_pBoardShim;
m_pChannels = NULL;
m_pBoardShim = NULL;
m_iNumberChannels = 0;
}
msgBox.exec();
}
//*************************************************************************************************************
void BrainFlowBoard::configureBoard(std::string config)
{
QMessageBox msgBox;
if (!m_pBoardShim)
{
msgBox.setText("Prepare Session first.");
return;
}
else
{
try {
m_pBoardShim->config_board((char *)config.c_str());
msgBox.setText("Configured.");
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
msgBox.setText("Failed to Configure.");
}
}
msgBox.exec();
}
//*************************************************************************************************************
void BrainFlowBoard::run()
{
int iMinSamples = 10;
unsigned long lSamplingPeriod = (unsigned long)(1000000.0 / m_iSamplingFreq) * iMinSamples;
int numRows = BoardShim::get_num_rows(m_iBoardId);
double **data = NULL;
int dataCount = 0;
while(m_bIsRunning)
{
usleep(lSamplingPeriod);
data = m_pBoardShim->get_board_data (&dataCount);
if (dataCount == 0)
{
continue;
}
Eigen::MatrixXd matrix (m_iNumberChannels, dataCount);
for (int j = 0; j < m_iNumberChannels; j++)
{
for (int i = 0; i < dataCount; i++)
{
matrix(j, i) = data[m_pChannels[j]][i];
}
}
m_pOutput->data()->setValue(matrix);
for (int i = 0; i < numRows; i++)
{
delete[] data[i];
}
delete[] data;
}
}
//*************************************************************************************************************
void BrainFlowBoard::releaseSession(bool useQmessage)
{
if (m_pBoardShim)
{
try {
m_pBoardShim->release_session();
} catch (...) {
}
}
delete m_pBoardShim;
delete[] m_pChannels;
for (int i = 0; i < m_iNumberChannels; i++)
{
m_outputConnectors.pop_back();
}
m_pBoardShim = NULL;
m_pChannels = NULL;
m_iBoardId = (int)BoardIds::SYNTHETIC_BOARD;
m_bIsRunning = false;
m_pOutput = NULL;
m_iSamplingFreq = 0;
m_sStreamerParams = "";
m_iNumberChannels = 0;
if (useQmessage)
{
QMessageBox msgBox;
msgBox.setText("Released.");
msgBox.exec();
}
}
<commit_msg>Add using namespace<commit_after>//=============================================================================================================
/**
* @file brainflowboard.cpp
* @author Andrey Parfenov <a1994ndrey@gmail.com>
* @version dev
* @date February, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Andrey Parfenov. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Contains the definition of the BrainFlowBoard class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <QMessageBox>
#include "data_filter.h"
#include "brainflowboard.h"
#include "FormFiles/brainflowsetupwidget.h"
#include "FormFiles/brainflowstreamingwidget.h"
#include <fiff/fiff_info.h>
#include <scMeas/realtimemultisamplearray.h>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace BRAINFLOWBOARDPLUGIN;
using namespace SCSHAREDLIB;
using namespace SCMEASLIB;
using namespace FIFFLIB;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
BrainFlowBoard::BrainFlowBoard()
: m_pBoardShim(NULL)
, m_pChannels(NULL)
, m_iBoardId((int)BoardIds::SYNTHETIC_BOARD)
, m_bIsRunning(false)
, m_pOutput(NULL)
, m_iSamplingFreq(0)
, m_sStreamerParams("")
, m_iNumberChannels(0)
, m_pFiffInfo(QSharedPointer<FiffInfo>::create())
{
m_pShowSettingsAction = new QAction(QIcon(":/images/options.png"), tr("Streaming Settings"),this);
m_pShowSettingsAction->setStatusTip(tr("Streaming Settings"));
connect(m_pShowSettingsAction, &QAction::triggered, this, &BrainFlowBoard::showSettings);
addPluginAction(m_pShowSettingsAction);
m_pOutput = PluginOutputData<RealTimeMultiSampleArray>::create(this, "BrainFlowBoard", "BrainFlow Board Output");
m_outputConnectors.append(m_pOutput);
}
//*************************************************************************************************************
BrainFlowBoard::~BrainFlowBoard()
{
releaseSession(false);
}
//*************************************************************************************************************
void BrainFlowBoard::showSettings()
{
BrainFlowStreamingWidget *widget = new BrainFlowStreamingWidget(this);
widget->show();
}
//*************************************************************************************************************
QSharedPointer<IPlugin> BrainFlowBoard::clone() const
{
QSharedPointer<BrainFlowBoard> pClone(new BrainFlowBoard());
return pClone;
}
//*************************************************************************************************************
void BrainFlowBoard::init()
{
BoardShim::set_log_file((char *)"brainflow_log.txt");
BoardShim::enable_dev_board_logger();
}
//*************************************************************************************************************
void BrainFlowBoard::unload()
{
}
//*************************************************************************************************************
void BrainFlowBoard::setUpFiffInfo()
{
//
//Clear old fiff info data
//
m_pFiffInfo->clear();
//
//Set number of channels, sampling frequency and high/-lowpass
//
m_pFiffInfo->nchan = m_iNumberChannels;
m_pFiffInfo->sfreq = m_iSamplingFreq;
m_pFiffInfo->highpass = 0.001f;
m_pFiffInfo->lowpass = m_iSamplingFreq/2;
//
//Set up the channel info
//
QStringList QSLChNames;
m_pFiffInfo->chs.clear();
for(int i = 0; i < m_pFiffInfo->nchan; ++i)
{
//Create information for each channel
QString sChType;
FiffChInfo fChInfo;
//Set channel name
sChType = QString("Ch ");
if(i<10) {
sChType.append("00");
}
if(i>=10 && i<100) {
sChType.append("0");
}
fChInfo.ch_name = sChType.append(sChType.number(i));
//Set channel type
fChInfo.kind = FIFFV_EEG_CH;
//Set logno
fChInfo.logNo = i;
//Set coord frame
fChInfo.coord_frame = FIFFV_COORD_HEAD;
//Set unit
fChInfo.unit = FIFF_UNIT_V;
//Set EEG electrode location - Convert from mm to m
fChInfo.eeg_loc(0,0) = 0;
fChInfo.eeg_loc(1,0) = 0;
fChInfo.eeg_loc(2,0) = 0;
//Set EEG electrode direction - Convert from mm to m
fChInfo.eeg_loc(0,1) = 0;
fChInfo.eeg_loc(1,1) = 0;
fChInfo.eeg_loc(2,1) = 0;
//Also write the eeg electrode locations into the meg loc variable (mne_ex_read_raw() matlab function wants this)
fChInfo.chpos.r0(0) = 0;
fChInfo.chpos.r0(1) = 0;
fChInfo.chpos.r0(2) = 0;
fChInfo.chpos.ex(0) = 1;
fChInfo.chpos.ex(1) = 0;
fChInfo.chpos.ex(2) = 0;
fChInfo.chpos.ey(0) = 0;
fChInfo.chpos.ey(1) = 1;
fChInfo.chpos.ey(2) = 0;
fChInfo.chpos.ez(0) = 0;
fChInfo.chpos.ez(1) = 0;
fChInfo.chpos.ez(2) = 1;
// //Digital input channel
// if(i == m_pFiffInfo->nchan-1)
// {
// //Set channel type
// fChInfo.kind = FIFFV_STIM_CH;
// sChType = QString("STIM");
// fChInfo.ch_name = sChType;
// }
QSLChNames << sChType;
m_pFiffInfo->chs.append(fChInfo);
}
//Set channel names in fiff_info_base
m_pFiffInfo->ch_names = QSLChNames;
//
//Set head projection
//
m_pFiffInfo->dev_head_t.from = FIFFV_COORD_DEVICE;
m_pFiffInfo->dev_head_t.to = FIFFV_COORD_HEAD;
m_pFiffInfo->ctf_head_t.from = FIFFV_COORD_DEVICE;
m_pFiffInfo->ctf_head_t.to = FIFFV_COORD_HEAD;
}
//*************************************************************************************************************
bool BrainFlowBoard::start()
{
if (!m_pBoardShim)
{
QMessageBox msgBox;
msgBox.setText("Configure streaming session before run!");
msgBox.exec();
return false;
}
try {
m_pBoardShim->start_stream(m_iSamplingFreq * 100, (char*)m_sStreamerParams.c_str());
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
QMessageBox msgBox;
msgBox.setText("Failed to start streaming.");
msgBox.exec();
return false;
}
m_bIsRunning = true;
QThread::start();
return true;
}
//*************************************************************************************************************
bool BrainFlowBoard::stop()
{
try {
m_pBoardShim->stop_stream();
m_bIsRunning = false;
m_pOutput->data()->clear();
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
return false;
}
return true;
}
//*************************************************************************************************************
IPlugin::PluginType BrainFlowBoard::getType() const
{
return _ISensor;
}
//*************************************************************************************************************
QString BrainFlowBoard::getName() const
{
return "BrainFlow Board Plugin";
}
//*************************************************************************************************************
QWidget* BrainFlowBoard::setupWidget()
{
BrainFlowSetupWidget* widget = new BrainFlowSetupWidget(this);
return widget;
}
//*************************************************************************************************************
void BrainFlowBoard::prepareSession(BrainFlowInputParams params,
std::string streamerParams,
int boardId,
int dataType,
int vertScale)
{
if (m_pBoardShim)
{
QMessageBox msgBox;
msgBox.setText("Streaming session already prepared.");
msgBox.exec();
return;
}
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, "Vert Scale is %d %d", vertScale);
QMessageBox msgBox;
m_iBoardId = boardId;
m_sStreamerParams = streamerParams;
try {
switch (dataType)
{
case 0:
m_pChannels = BoardShim::get_eeg_channels(boardId, &m_iNumberChannels);
break;
case 1:
m_pChannels = BoardShim::get_emg_channels(boardId, &m_iNumberChannels);
break;
case 2:
m_pChannels = BoardShim::get_ecg_channels(boardId, &m_iNumberChannels);
break;
case 3:
m_pChannels = BoardShim::get_eog_channels(boardId, &m_iNumberChannels);
break;
case 4:
m_pChannels = BoardShim::get_eda_channels(boardId, &m_iNumberChannels);
break;
default:
throw BrainFlowException ("unsupported data type", UNSUPPORTED_BOARD_ERROR);
break;
}
m_iSamplingFreq = BoardShim::get_sampling_rate(boardId);
m_pBoardShim = new BoardShim(m_iBoardId, params);
m_pBoardShim->prepare_session();
setUpFiffInfo();
m_pOutput->data()->initFromFiffInfo(m_pFiffInfo);
m_pOutput->data()->setMultiArraySize(1);
msgBox.setText("Streaming session is ready");
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
msgBox.setText("Invalid parameters. Check logs for details.");
delete[] m_pChannels;
delete m_pBoardShim;
m_pChannels = NULL;
m_pBoardShim = NULL;
m_iNumberChannels = 0;
}
msgBox.exec();
}
//*************************************************************************************************************
void BrainFlowBoard::configureBoard(std::string config)
{
QMessageBox msgBox;
if (!m_pBoardShim)
{
msgBox.setText("Prepare Session first.");
return;
}
else
{
try {
m_pBoardShim->config_board((char *)config.c_str());
msgBox.setText("Configured.");
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
msgBox.setText("Failed to Configure.");
}
}
msgBox.exec();
}
//*************************************************************************************************************
void BrainFlowBoard::run()
{
int iMinSamples = 10;
unsigned long lSamplingPeriod = (unsigned long)(1000000.0 / m_iSamplingFreq) * iMinSamples;
int numRows = BoardShim::get_num_rows(m_iBoardId);
double **data = NULL;
int dataCount = 0;
while(m_bIsRunning)
{
usleep(lSamplingPeriod);
data = m_pBoardShim->get_board_data (&dataCount);
if (dataCount == 0)
{
continue;
}
Eigen::MatrixXd matrix (m_iNumberChannels, dataCount);
for (int j = 0; j < m_iNumberChannels; j++)
{
for (int i = 0; i < dataCount; i++)
{
matrix(j, i) = data[m_pChannels[j]][i];
}
}
m_pOutput->data()->setValue(matrix);
for (int i = 0; i < numRows; i++)
{
delete[] data[i];
}
delete[] data;
}
}
//*************************************************************************************************************
void BrainFlowBoard::releaseSession(bool useQmessage)
{
if (m_pBoardShim)
{
try {
m_pBoardShim->release_session();
} catch (...) {
}
}
delete m_pBoardShim;
delete[] m_pChannels;
for (int i = 0; i < m_iNumberChannels; i++)
{
m_outputConnectors.pop_back();
}
m_pBoardShim = NULL;
m_pChannels = NULL;
m_iBoardId = (int)BoardIds::SYNTHETIC_BOARD;
m_bIsRunning = false;
m_pOutput = NULL;
m_iSamplingFreq = 0;
m_sStreamerParams = "";
m_iNumberChannels = 0;
if (useQmessage)
{
QMessageBox msgBox;
msgBox.setText("Released.");
msgBox.exec();
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <boost/mpl/size.hpp>
#include <boost/mpl/unique.hpp>
#include <boost/mpl/vector.hpp>
namespace blackhole {
/// Metafunction, that detects whether a parameter pack has duplicate items.
template<typename... Args>
struct unique :
public std::conditional<
sizeof...(Args) == boost::mpl::size<
typename boost::mpl::unique<
boost::mpl::vector<Args...>,
std::is_same<boost::mpl::_1, boost::mpl::_2>
>::type
>::value,
std::true_type,
std::false_type
>::type
{};
} // namespace blackhole
<commit_msg>[GCC 4.4] Fuck you. Workaround variadic pack expansion.<commit_after>#pragma once
#include <type_traits>
#include <boost/mpl/size.hpp>
#include <boost/mpl/unique.hpp>
#include <boost/mpl/vector.hpp>
namespace blackhole {
/// General definition of the helper class
template<typename... Args> struct from_variadic;
/// This one handles the case when no types passed.
template<>
struct from_variadic<> {
typedef boost::mpl::vector<> type;
};
/// This one is a specialization for the case when only one type is passed.
template<typename T>
struct from_variadic<T> {
typedef boost::mpl::vector<T> type;
};
/*!
* This specialization does the actual job.
* It splits the whole pack into 2 parts: one with single type T and the rest
* of types Args.
* As soon as it is done T is added to an mpl::vector.
*/
template<typename T, typename... Args>
struct from_variadic<T, Args...> {
typedef typename boost::mpl::push_front<
typename from_variadic<Args...>::type,
T
>::type type;
};
/// Metafunction, that detects whether a parameter pack has duplicate items.
template<typename... Args>
struct unique :
public std::conditional<
sizeof...(Args) == boost::mpl::size<
typename boost::mpl::unique<
typename from_variadic<Args...>::type,
std::is_same<boost::mpl::_1, boost::mpl::_2>
>::type
>::value,
std::true_type,
std::false_type
>::type
{};
} // namespace blackhole
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <boost/mpl/size.hpp>
#include <boost/mpl/unique.hpp>
#include <boost/mpl/vector.hpp>
namespace blackhole {
/// Metafunction, that determines whether a parameter pack has duplicate items.
template<typename... Args>
struct unique :
public std::conditional<
sizeof...(Args) == boost::mpl::size<
typename boost::mpl::unique<
boost::mpl::vector<Args...>,
std::is_same<boost::mpl::_1, boost::mpl::_2>
>::type
>::value,
std::true_type,
std::false_type
>::type
{};
} // namespace blackhole
<commit_msg>[Code Style] Wording.<commit_after>#pragma once
#include <type_traits>
#include <boost/mpl/size.hpp>
#include <boost/mpl/unique.hpp>
#include <boost/mpl/vector.hpp>
namespace blackhole {
/// Metafunction, that detects whether a parameter pack has duplicate items.
template<typename... Args>
struct unique :
public std::conditional<
sizeof...(Args) == boost::mpl::size<
typename boost::mpl::unique<
boost::mpl::vector<Args...>,
std::is_same<boost::mpl::_1, boost::mpl::_2>
>::type
>::value,
std::true_type,
std::false_type
>::type
{};
} // namespace blackhole
<|endoftext|> |
<commit_before>/*
* THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit
* COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED.
*
* THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
* https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md
*/
#include "chronotext/path/FollowablePath.h"
#include "chronotext/utils/MathUtils.h"
#include "chronotext/utils/Utils.h"
using namespace ci;
using namespace std;
namespace chronotext
{
FollowablePath::FollowablePath(Mode mode, int capacity)
:
mode(mode)
{
if (capacity > 0)
{
points.reserve(capacity);
len.reserve(capacity);
}
}
FollowablePath::FollowablePath(const vector<Vec2f> &points, Mode mode)
:
mode(mode)
{
add(points);
}
FollowablePath::FollowablePath(DataSourceRef source, Mode mode)
:
mode(mode)
{
read(source);
}
void FollowablePath::read(DataSourceRef source)
{
auto stream = source->createStream();
int newPointsSize;
stream->readLittle(&newPointsSize);
extendCapacity(newPointsSize);
// ---
Vec2f point;
for (int i = 0; i < newPointsSize; i++)
{
stream->readLittle(&point.x);
stream->readLittle(&point.y);
add(point);
}
}
void FollowablePath::write(DataTargetRef target)
{
auto stream = target->getStream();
stream->writeLittle(size());
for (auto &point : points)
{
stream->writeLittle(point.x);
stream->writeLittle(point.y);
}
}
void FollowablePath::add(const vector<Vec2f> &newPoints)
{
extendCapacity(newPoints.size());
for (auto &point : newPoints)
{
add(point);
}
}
void FollowablePath::add(const ci::Vec2f &point)
{
if (!points.empty())
{
Vec2f delta = point - points.back();
if (delta != Vec2f::zero())
{
len.push_back(len.back() + delta.length());
}
else
{
return;
}
}
else
{
len.push_back(0);
}
points.push_back(point);
}
void FollowablePath::clear()
{
points.clear();
len.clear();
}
int FollowablePath::size() const
{
return points.size();
}
bool FollowablePath::empty() const
{
return points.empty();
}
float FollowablePath::getLength() const
{
if (!points.empty())
{
return len.back();
}
else
{
return 0;
}
}
Rectf FollowablePath::getBounds() const
{
float minX = numeric_limits<float>::max();
float minY = numeric_limits<float>::max();
float maxX = numeric_limits<float>::min();
float maxY = numeric_limits<float>::min();
for (auto &point : points)
{
if (point.x < minX) minX = point.x;
if (point.y < minY) minY = point.y;
if (point.x > maxX) maxX = point.x;
if (point.y > maxY) maxY = point.y;
}
return Rectf(minX, minY, maxX, maxY);
}
void FollowablePath::close()
{
if (size() > 2)
{
if (points.front() != points.back())
{
add(points.front());
}
}
}
FollowablePath::Value FollowablePath::pos2Value(float pos) const
{
float length = len.back();
if (mode == MODE_LOOP || mode == MODE_MODULO)
{
pos = boundf(pos, length);
}
else
{
if (pos <= 0)
{
if (mode == MODE_BOUNDED)
{
pos = 0;
}
}
else if (pos >= length)
{
if (mode == MODE_BOUNDED)
{
pos = length;
}
}
}
int index = search(len, pos, 1, size());
auto p0 = points[index];
auto p1 = points[index + 1];
float ratio = (pos - len[index]) / (len[index + 1] - len[index]);
FollowablePath::Value value;
value.point = p0 + (p1 - p0) * ratio;
value.angle = math<float>::atan2(p1.y - p0.y, p1.x - p0.x);
value.position = pos;
return value;
}
Vec2f FollowablePath::pos2Point(float pos) const
{
float length = len.back();
if (mode == MODE_LOOP || mode == MODE_MODULO)
{
pos = boundf(pos, length);
}
else
{
if (pos <= 0)
{
if (mode == MODE_BOUNDED)
{
return points.front();
}
}
else if (pos >= length)
{
if (mode == MODE_BOUNDED)
{
return points.back();
}
}
}
int index = search(len, pos, 1, size());
auto p0 = points[index];
auto p1 = points[index + 1];
float ratio = (pos - len[index]) / (len[index + 1] - len[index]);
return p0 + (p1 - p0) * ratio;
}
float FollowablePath::pos2Angle(float pos) const
{
float length = len.back();
if (mode == MODE_LOOP || mode == MODE_MODULO)
{
pos = boundf(pos, length);
}
else
{
if (pos <= 0)
{
if (mode == MODE_BOUNDED)
{
pos = 0;
}
}
else if (pos >= length)
{
if (mode == MODE_BOUNDED)
{
pos = length;
}
}
}
int index = search(len, pos, 1, size());
auto p0 = points[index];
auto p1 = points[index + 1];
return math<float>::atan2(p1.y - p0.y, p1.x - p0.x);
}
float FollowablePath::pos2SampledAngle(float pos, float sampleSize) const
{
Vec2f gradient = pos2Gradient(pos, sampleSize);
/*
* WE USE AN EPSILON VALUE TO AVOID
* DEGENERATED RESULTS IN SOME EXTREME CASES
* (E.G. CLOSE TO 180 DEGREE DIFF. BETWEEN TWO SEGMENTS)
*/
if (gradient.lengthSquared() > 1.0)
{
return math<float>::atan2(gradient.y, gradient.x);
}
else
{
return pos2Angle(pos);
}
}
Vec2f FollowablePath::pos2Gradient(float pos, float sampleSize) const
{
Vec2f pm = pos2Point(pos - sampleSize * 0.5f);
Vec2f pp = pos2Point(pos + sampleSize * 0.5f);
return (pp - pm) * 0.5f;
}
/*
* RETURNS false IF CLOSEST POINT IS FARTHER THAN threshold DISTANCE
*
* REFERENCE: "Minimum Distance between a Point and a Line" BY Paul Bourke
* http://paulbourke.net/geometry/pointlineplane/
*/
bool FollowablePath::findClosestPoint(const Vec2f &point, float threshold, FollowablePath::ClosePoint &res) const
{
float min = threshold * threshold; // BECAUSE IT IS MORE EFFICIENT TO WORK WITH MAGNIFIED DISTANCES
int index = -1;
int _size = size();
Vec2f _point;
float _len;
for (int i = 0; i < _size; i++)
{
int i0, i1;
if (i == _size - 1)
{
i0 = i - 1;
i1 = i;
}
else
{
i0 = i;
i1 = i + 1;
}
auto p0 = points[i0];
auto p1 = points[i1];
Vec2f delta = p1 - p0;
float l = len[i1] - len[i0];
float u = delta.dot(point - p0) / (l * l);
if (u >= 0 && u <= 1)
{
Vec2f p = p0 + u * delta;
float mag = (p - point).lengthSquared();
if (mag < min)
{
min = mag;
index = i0;
_point = p;
_len = len[index] + u * l;
}
}
else
{
float mag0 = (p0 - point).lengthSquared();
float mag1 = (p1 - point).lengthSquared();
if ((mag0 < min) && (mag0 < mag1))
{
min = mag0;
index = i0;
_point = points[i0];
_len = len[index];
}
else if ((mag1 < min) && (mag1 < mag0))
{
min = mag1;
index = i1;
_point = points[i1];
_len = len[index];
}
}
}
if (index != -1)
{
res.point = _point;
res.position = _len;
res.distance = math<float>::sqrt(min);
return true;
}
return false;
}
/*
* segmentIndex MUST BE < size
*
* REFERENCE: "Minimum Distance between a Point and a Line" BY Paul Bourke
* http://paulbourke.net/geometry/pointlineplane/
*/
FollowablePath::ClosePoint FollowablePath::closestPointFromSegment(const Vec2f &point, int segmentIndex) const
{
FollowablePath::ClosePoint res;
int i0 = segmentIndex;
int i1 = segmentIndex + 1;
auto p0 = points[i0];
auto p1 = points[i1];
Vec2f delta = p1 - p0;
float l = len[i1] - len[i0];
float u = delta.dot(point - p0) / (l * l);
if (u >= 0 && u <= 1)
{
Vec2f p = p0 + u * delta;
float mag = (p - point).lengthSquared();
res.point = p;
res.position = len[i0] + u * l;
res.distance = math<float>::sqrt(mag);
}
else
{
float mag0 = (p0 - point).lengthSquared();
float mag1 = (p1 - point).lengthSquared();
if (mag0 < mag1)
{
res.point = p0;
res.position = len[i0];
res.distance = math<float>::sqrt(mag0);
}
else
{
res.point = p1;
res.position = len[i1];
res.distance = math<float>::sqrt(mag1);
}
}
return res;
}
void FollowablePath::extendCapacity(int amount)
{
int newCapacity = size() + amount;
points.reserve(newCapacity);
len.reserve(newCapacity);
}
}
<commit_msg>COSMETICS<commit_after>/*
* THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit
* COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED.
*
* THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
* https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md
*/
#include "chronotext/path/FollowablePath.h"
#include "chronotext/utils/MathUtils.h"
#include "chronotext/utils/Utils.h"
using namespace ci;
using namespace std;
namespace chronotext
{
FollowablePath::FollowablePath(Mode mode, int capacity)
:
mode(mode)
{
if (capacity > 0)
{
extendCapacity(capacity);
}
}
FollowablePath::FollowablePath(const vector<Vec2f> &points, Mode mode)
:
mode(mode)
{
add(points);
}
FollowablePath::FollowablePath(DataSourceRef source, Mode mode)
:
mode(mode)
{
read(source);
}
void FollowablePath::read(DataSourceRef source)
{
auto stream = source->createStream();
int newPointsSize;
stream->readLittle(&newPointsSize);
extendCapacity(newPointsSize);
// ---
Vec2f point;
for (int i = 0; i < newPointsSize; i++)
{
stream->readLittle(&point.x);
stream->readLittle(&point.y);
add(point);
}
}
void FollowablePath::write(DataTargetRef target)
{
auto stream = target->getStream();
stream->writeLittle(size());
for (auto &point : points)
{
stream->writeLittle(point.x);
stream->writeLittle(point.y);
}
}
void FollowablePath::add(const vector<Vec2f> &newPoints)
{
extendCapacity(newPoints.size());
for (auto &point : newPoints)
{
add(point);
}
}
void FollowablePath::add(const ci::Vec2f &point)
{
if (!points.empty())
{
Vec2f delta = point - points.back();
if (delta != Vec2f::zero())
{
len.push_back(len.back() + delta.length());
}
else
{
return;
}
}
else
{
len.push_back(0);
}
points.push_back(point);
}
void FollowablePath::clear()
{
points.clear();
len.clear();
}
int FollowablePath::size() const
{
return points.size();
}
bool FollowablePath::empty() const
{
return points.empty();
}
float FollowablePath::getLength() const
{
if (!points.empty())
{
return len.back();
}
else
{
return 0;
}
}
Rectf FollowablePath::getBounds() const
{
float minX = numeric_limits<float>::max();
float minY = numeric_limits<float>::max();
float maxX = numeric_limits<float>::min();
float maxY = numeric_limits<float>::min();
for (auto &point : points)
{
if (point.x < minX) minX = point.x;
if (point.y < minY) minY = point.y;
if (point.x > maxX) maxX = point.x;
if (point.y > maxY) maxY = point.y;
}
return Rectf(minX, minY, maxX, maxY);
}
void FollowablePath::close()
{
if (size() > 2)
{
if (points.front() != points.back())
{
add(points.front());
}
}
}
FollowablePath::Value FollowablePath::pos2Value(float pos) const
{
float length = len.back();
if (mode == MODE_LOOP || mode == MODE_MODULO)
{
pos = boundf(pos, length);
}
else
{
if (pos <= 0)
{
if (mode == MODE_BOUNDED)
{
pos = 0;
}
}
else if (pos >= length)
{
if (mode == MODE_BOUNDED)
{
pos = length;
}
}
}
int index = search(len, pos, 1, size());
auto p0 = points[index];
auto p1 = points[index + 1];
float ratio = (pos - len[index]) / (len[index + 1] - len[index]);
FollowablePath::Value value;
value.point = p0 + (p1 - p0) * ratio;
value.angle = math<float>::atan2(p1.y - p0.y, p1.x - p0.x);
value.position = pos;
return value;
}
Vec2f FollowablePath::pos2Point(float pos) const
{
float length = len.back();
if (mode == MODE_LOOP || mode == MODE_MODULO)
{
pos = boundf(pos, length);
}
else
{
if (pos <= 0)
{
if (mode == MODE_BOUNDED)
{
return points.front();
}
}
else if (pos >= length)
{
if (mode == MODE_BOUNDED)
{
return points.back();
}
}
}
int index = search(len, pos, 1, size());
auto p0 = points[index];
auto p1 = points[index + 1];
float ratio = (pos - len[index]) / (len[index + 1] - len[index]);
return p0 + (p1 - p0) * ratio;
}
float FollowablePath::pos2Angle(float pos) const
{
float length = len.back();
if (mode == MODE_LOOP || mode == MODE_MODULO)
{
pos = boundf(pos, length);
}
else
{
if (pos <= 0)
{
if (mode == MODE_BOUNDED)
{
pos = 0;
}
}
else if (pos >= length)
{
if (mode == MODE_BOUNDED)
{
pos = length;
}
}
}
int index = search(len, pos, 1, size());
auto p0 = points[index];
auto p1 = points[index + 1];
return math<float>::atan2(p1.y - p0.y, p1.x - p0.x);
}
float FollowablePath::pos2SampledAngle(float pos, float sampleSize) const
{
Vec2f gradient = pos2Gradient(pos, sampleSize);
/*
* WE USE AN EPSILON VALUE TO AVOID
* DEGENERATED RESULTS IN SOME EXTREME CASES
* (E.G. CLOSE TO 180 DEGREE DIFF. BETWEEN TWO SEGMENTS)
*/
if (gradient.lengthSquared() > 1.0)
{
return math<float>::atan2(gradient.y, gradient.x);
}
else
{
return pos2Angle(pos);
}
}
Vec2f FollowablePath::pos2Gradient(float pos, float sampleSize) const
{
Vec2f pm = pos2Point(pos - sampleSize * 0.5f);
Vec2f pp = pos2Point(pos + sampleSize * 0.5f);
return (pp - pm) * 0.5f;
}
/*
* RETURNS false IF CLOSEST POINT IS FARTHER THAN threshold DISTANCE
*
* REFERENCE: "Minimum Distance between a Point and a Line" BY Paul Bourke
* http://paulbourke.net/geometry/pointlineplane/
*/
bool FollowablePath::findClosestPoint(const Vec2f &point, float threshold, FollowablePath::ClosePoint &res) const
{
float min = threshold * threshold; // BECAUSE IT IS MORE EFFICIENT TO WORK WITH MAGNIFIED DISTANCES
int index = -1;
int _size = size();
Vec2f _point;
float _len;
for (int i = 0; i < _size; i++)
{
int i0, i1;
if (i == _size - 1)
{
i0 = i - 1;
i1 = i;
}
else
{
i0 = i;
i1 = i + 1;
}
auto p0 = points[i0];
auto p1 = points[i1];
Vec2f delta = p1 - p0;
float l = len[i1] - len[i0];
float u = delta.dot(point - p0) / (l * l);
if (u >= 0 && u <= 1)
{
Vec2f p = p0 + u * delta;
float mag = (p - point).lengthSquared();
if (mag < min)
{
min = mag;
index = i0;
_point = p;
_len = len[index] + u * l;
}
}
else
{
float mag0 = (p0 - point).lengthSquared();
float mag1 = (p1 - point).lengthSquared();
if ((mag0 < min) && (mag0 < mag1))
{
min = mag0;
index = i0;
_point = points[i0];
_len = len[index];
}
else if ((mag1 < min) && (mag1 < mag0))
{
min = mag1;
index = i1;
_point = points[i1];
_len = len[index];
}
}
}
if (index != -1)
{
res.point = _point;
res.position = _len;
res.distance = math<float>::sqrt(min);
return true;
}
return false;
}
/*
* segmentIndex MUST BE < size
*
* REFERENCE: "Minimum Distance between a Point and a Line" BY Paul Bourke
* http://paulbourke.net/geometry/pointlineplane/
*/
FollowablePath::ClosePoint FollowablePath::closestPointFromSegment(const Vec2f &point, int segmentIndex) const
{
FollowablePath::ClosePoint res;
int i0 = segmentIndex;
int i1 = segmentIndex + 1;
auto p0 = points[i0];
auto p1 = points[i1];
Vec2f delta = p1 - p0;
float l = len[i1] - len[i0];
float u = delta.dot(point - p0) / (l * l);
if (u >= 0 && u <= 1)
{
Vec2f p = p0 + u * delta;
float mag = (p - point).lengthSquared();
res.point = p;
res.position = len[i0] + u * l;
res.distance = math<float>::sqrt(mag);
}
else
{
float mag0 = (p0 - point).lengthSquared();
float mag1 = (p1 - point).lengthSquared();
if (mag0 < mag1)
{
res.point = p0;
res.position = len[i0];
res.distance = math<float>::sqrt(mag0);
}
else
{
res.point = p1;
res.position = len[i1];
res.distance = math<float>::sqrt(mag1);
}
}
return res;
}
void FollowablePath::extendCapacity(int amount)
{
int newCapacity = size() + amount;
points.reserve(newCapacity);
len.reserve(newCapacity);
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MockLinkMissionItemHandler.h"
#include "MockLink.h"
#include <QDebug>
QGC_LOGGING_CATEGORY(MockLinkMissionItemHandlerLog, "MockLinkMissionItemHandlerLog")
MockLinkMissionItemHandler::MockLinkMissionItemHandler(MockLink* mockLink, MAVLinkProtocol* mavlinkProtocol)
: _mockLink(mockLink)
, _missionItemResponseTimer(NULL)
, _failureMode(FailNone)
, _sendHomePositionOnEmptyList(false)
, _mavlinkProtocol(mavlinkProtocol)
, _failReadRequestListFirstResponse(true)
, _failReadRequest1FirstResponse(true)
, _failWriteMissionCountFirstResponse(true)
{
Q_ASSERT(mockLink);
}
MockLinkMissionItemHandler::~MockLinkMissionItemHandler()
{
}
void MockLinkMissionItemHandler::_startMissionItemResponseTimer(void)
{
if (!_missionItemResponseTimer) {
_missionItemResponseTimer = new QTimer();
connect(_missionItemResponseTimer, &QTimer::timeout, this, &MockLinkMissionItemHandler::_missionItemResponseTimeout);
}
_missionItemResponseTimer->start(500);
}
bool MockLinkMissionItemHandler::handleMessage(const mavlink_message_t& msg)
{
switch (msg.msgid) {
case MAVLINK_MSG_ID_MISSION_REQUEST_LIST:
_handleMissionRequestList(msg);
break;
case MAVLINK_MSG_ID_MISSION_REQUEST:
_handleMissionRequest(msg);
break;
case MAVLINK_MSG_ID_MISSION_ITEM:
_handleMissionItem(msg);
break;
case MAVLINK_MSG_ID_MISSION_COUNT:
_handleMissionCount(msg);
break;
case MAVLINK_MSG_ID_MISSION_ACK:
// Acks are received back for each MISSION_ITEM message
break;
case MAVLINK_MSG_ID_MISSION_SET_CURRENT:
// Sets the currently active mission item
break;
case MAVLINK_MSG_ID_MISSION_CLEAR_ALL:
// Delete all mission items
_missionItems.clear();
break;
default:
return false;
}
return true;
}
void MockLinkMissionItemHandler::_handleMissionRequestList(const mavlink_message_t& msg)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequestList read sequence";
_failReadRequest1FirstResponse = true;
if (_failureMode == FailReadRequestListNoResponse) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequestList not responding due to failure mode FailReadRequestListNoResponse";
} else if (_failureMode == FailReadRequestListFirstResponse && _failReadRequestListFirstResponse) {
_failReadRequestListFirstResponse = false;
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequestList not responding due to failure mode FailReadRequestListFirstResponse";
} else {
mavlink_mission_request_list_t request;
_failReadRequestListFirstResponse = true;
mavlink_msg_mission_request_list_decode(&msg, &request);
Q_ASSERT(request.target_system == _mockLink->vehicleId());
_requestType = (MAV_MISSION_TYPE)request.mission_type;
int itemCount;
switch (_requestType) {
case MAV_MISSION_TYPE_MISSION:
itemCount = _missionItems.count();
if (itemCount == 0 && _sendHomePositionOnEmptyList) {
itemCount = 1;
}
break;
case MAV_MISSION_TYPE_FENCE:
itemCount = _fenceItems.count();
break;
case MAV_MISSION_TYPE_RALLY:
itemCount = _rallyItems.count();
break;
default:
Q_ASSERT(false);
}
mavlink_message_t responseMsg;
mavlink_msg_mission_count_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&responseMsg, // Outgoing message
msg.sysid, // Target is original sender
msg.compid, // Target is original sender
itemCount, // Number of mission items
_requestType);
_mockLink->respondWithMavlinkMessage(responseMsg);
}
}
void MockLinkMissionItemHandler::_handleMissionRequest(const mavlink_message_t& msg)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest read sequence";
mavlink_mission_request_t request;
mavlink_msg_mission_request_decode(&msg, &request);
Q_ASSERT(request.target_system == _mockLink->vehicleId());
if (_failureMode == FailReadRequest0NoResponse && request.seq == 0) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest not responding due to failure mode FailReadRequest0NoResponse";
} else if (_failureMode == FailReadRequest1NoResponse && request.seq == 1) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest not responding due to failure mode FailReadRequest1NoResponse";
} else if (_failureMode == FailReadRequest1FirstResponse && request.seq == 1 && _failReadRequest1FirstResponse) {
_failReadRequest1FirstResponse = false;
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest not responding due to failure mode FailReadRequest1FirstResponse";
} else {
// FIXME: Track whether all items are requested, or requested in sequence
if ((_failureMode == FailReadRequest0IncorrectSequence && request.seq == 0) ||
(_failureMode == FailReadRequest1IncorrectSequence && request.seq == 1)) {
// Send back the incorrect sequence number
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest sending bad sequence number";
request.seq++;
}
if ((_failureMode == FailReadRequest0ErrorAck && request.seq == 0) ||
(_failureMode == FailReadRequest1ErrorAck && request.seq == 1)) {
_sendAck(MAV_MISSION_ERROR);
} else {
mavlink_mission_item_t item;
mavlink_message_t responseMsg;
switch (request.mission_type) {
case MAV_MISSION_TYPE_MISSION:
if (_missionItems.count() == 0 && _sendHomePositionOnEmptyList) {
item.frame = MAV_FRAME_GLOBAL_RELATIVE_ALT;
item.command = MAV_CMD_NAV_WAYPOINT;
item.current = false;
item.autocontinue = true;
item.param1 = item.param2 = item.param3 = item.param4 = item.x = item.y = item.z = 0;
} else {
item = _missionItems[request.seq];
}
break;
case MAV_MISSION_TYPE_FENCE:
item = _fenceItems[request.seq];
break;
case MAV_MISSION_TYPE_RALLY:
item = _rallyItems[request.seq];
break;
default:
Q_ASSERT(false);
}
mavlink_msg_mission_item_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&responseMsg, // Outgoing message
msg.sysid, // Target is original sender
msg.compid, // Target is original sender
request.seq, // Index of mission item being sent
item.frame,
item.command,
item.current,
item.autocontinue,
item.param1, item.param2, item.param3, item.param4,
item.x, item.y, item.z,
_requestType);
_mockLink->respondWithMavlinkMessage(responseMsg);
}
}
}
void MockLinkMissionItemHandler::_handleMissionCount(const mavlink_message_t& msg)
{
mavlink_mission_count_t missionCount;
mavlink_msg_mission_count_decode(&msg, &missionCount);
Q_ASSERT(missionCount.target_system == _mockLink->vehicleId());
_requestType = (MAV_MISSION_TYPE)missionCount.mission_type;
_writeSequenceCount = missionCount.count;
Q_ASSERT(_writeSequenceCount >= 0);
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionCount write sequence _writeSequenceCount:" << _writeSequenceCount;
switch (missionCount.mission_type) {
case MAV_MISSION_TYPE_MISSION:
_missionItems.clear();
break;
case MAV_MISSION_TYPE_FENCE:
_fenceItems.clear();
break;
case MAV_MISSION_TYPE_RALLY:
_rallyItems.clear();
break;
}
if (_writeSequenceCount == 0) {
_sendAck(MAV_MISSION_ACCEPTED);
} else {
if (_failureMode == FailWriteMissionCountNoResponse) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionCount not responding due to failure mode FailWriteMissionCountNoResponse";
return;
}
if (_failureMode == FailWriteMissionCountFirstResponse && _failWriteMissionCountFirstResponse) {
_failWriteMissionCountFirstResponse = false;
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionCount not responding due to failure mode FailWriteMissionCountNoResponse";
return;
}
_failWriteMissionCountFirstResponse = true;
_writeSequenceIndex = 0;
_requestNextMissionItem(_writeSequenceIndex);
}
}
void MockLinkMissionItemHandler::_requestNextMissionItem(int sequenceNumber)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem write sequence sequenceNumber:" << sequenceNumber << "_failureMode:" << _failureMode;
if (_failureMode == FailWriteRequest1NoResponse && sequenceNumber == 1) {
qCDebug(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem not responding due to failure mode FailWriteRequest1NoResponse";
} else {
if (sequenceNumber >= _writeSequenceCount) {
qCWarning(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem requested seqeuence number > write count sequenceNumber::_writeSequenceCount" << sequenceNumber << _writeSequenceCount;
return;
}
if ((_failureMode == FailWriteRequest0IncorrectSequence && sequenceNumber == 0) ||
(_failureMode == FailWriteRequest1IncorrectSequence && sequenceNumber == 1)) {
sequenceNumber ++;
}
if ((_failureMode == FailWriteRequest0ErrorAck && sequenceNumber == 0) ||
(_failureMode == FailWriteRequest1ErrorAck && sequenceNumber == 1)) {
qCDebug(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem sending ack error due to failure mode";
_sendAck(MAV_MISSION_ERROR);
} else {
mavlink_message_t message;
mavlink_msg_mission_request_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&message,
_mavlinkProtocol->getSystemId(),
_mavlinkProtocol->getComponentId(),
sequenceNumber,
_requestType);
_mockLink->respondWithMavlinkMessage(message);
// If response with Mission Item doesn't come before timer fires it's an error
_startMissionItemResponseTimer();
}
}
}
void MockLinkMissionItemHandler::_sendAck(MAV_MISSION_RESULT ackType)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_sendAck write sequence complete ackType:" << ackType;
mavlink_message_t message;
mavlink_msg_mission_ack_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&message,
_mavlinkProtocol->getSystemId(),
_mavlinkProtocol->getComponentId(),
ackType,
_requestType);
_mockLink->respondWithMavlinkMessage(message);
}
void MockLinkMissionItemHandler::_handleMissionItem(const mavlink_message_t& msg)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionItem write sequence";
_missionItemResponseTimer->stop();
mavlink_mission_item_t missionItem;
mavlink_msg_mission_item_decode(&msg, &missionItem);
Q_ASSERT(missionItem.target_system == _mockLink->vehicleId());
switch (missionItem.mission_type) {
case MAV_MISSION_TYPE_MISSION:
_missionItems[missionItem.seq] = missionItem;
break;
case MAV_MISSION_TYPE_FENCE:
_fenceItems[missionItem.seq] = missionItem;
break;
case MAV_MISSION_TYPE_RALLY:
_rallyItems[missionItem.seq] = missionItem;
break;
}
_writeSequenceIndex++;
if (_writeSequenceIndex < _writeSequenceCount) {
if (_failureMode == FailWriteFinalAckMissingRequests && _writeSequenceIndex == 3) {
// Send MAV_MISSION_ACCPETED ack too early
_sendAck(MAV_MISSION_ACCEPTED);
} else {
_requestNextMissionItem(_writeSequenceIndex);
}
} else {
if (_failureMode != FailWriteFinalAckNoResponse) {
MAV_MISSION_RESULT ack = MAV_MISSION_ACCEPTED;
if (_failureMode == FailWriteFinalAckErrorAck) {
ack = MAV_MISSION_ERROR;
}
_sendAck(ack);
}
}
}
void MockLinkMissionItemHandler::_missionItemResponseTimeout(void)
{
qWarning() << "Timeout waiting for next MISSION_ITEM";
Q_ASSERT(false);
}
void MockLinkMissionItemHandler::sendUnexpectedMissionAck(MAV_MISSION_RESULT ackType)
{
_sendAck(ackType);
}
void MockLinkMissionItemHandler::sendUnexpectedMissionItem(void)
{
// FIXME: NYI
Q_ASSERT(false);
}
void MockLinkMissionItemHandler::sendUnexpectedMissionRequest(void)
{
// FIXME: NYI
Q_ASSERT(false);
}
void MockLinkMissionItemHandler::setMissionItemFailureMode(FailureMode_t failureMode)
{
_failureMode = failureMode;
}
void MockLinkMissionItemHandler::shutdown(void)
{
if (_missionItemResponseTimer) {
delete _missionItemResponseTimer;
}
}
<commit_msg>Fix CLEAR_ALL<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MockLinkMissionItemHandler.h"
#include "MockLink.h"
#include <QDebug>
QGC_LOGGING_CATEGORY(MockLinkMissionItemHandlerLog, "MockLinkMissionItemHandlerLog")
MockLinkMissionItemHandler::MockLinkMissionItemHandler(MockLink* mockLink, MAVLinkProtocol* mavlinkProtocol)
: _mockLink(mockLink)
, _missionItemResponseTimer(NULL)
, _failureMode(FailNone)
, _sendHomePositionOnEmptyList(false)
, _mavlinkProtocol(mavlinkProtocol)
, _failReadRequestListFirstResponse(true)
, _failReadRequest1FirstResponse(true)
, _failWriteMissionCountFirstResponse(true)
{
Q_ASSERT(mockLink);
}
MockLinkMissionItemHandler::~MockLinkMissionItemHandler()
{
}
void MockLinkMissionItemHandler::_startMissionItemResponseTimer(void)
{
if (!_missionItemResponseTimer) {
_missionItemResponseTimer = new QTimer();
connect(_missionItemResponseTimer, &QTimer::timeout, this, &MockLinkMissionItemHandler::_missionItemResponseTimeout);
}
_missionItemResponseTimer->start(500);
}
bool MockLinkMissionItemHandler::handleMessage(const mavlink_message_t& msg)
{
switch (msg.msgid) {
case MAVLINK_MSG_ID_MISSION_REQUEST_LIST:
_handleMissionRequestList(msg);
break;
case MAVLINK_MSG_ID_MISSION_REQUEST:
_handleMissionRequest(msg);
break;
case MAVLINK_MSG_ID_MISSION_ITEM:
_handleMissionItem(msg);
break;
case MAVLINK_MSG_ID_MISSION_COUNT:
_handleMissionCount(msg);
break;
case MAVLINK_MSG_ID_MISSION_ACK:
// Acks are received back for each MISSION_ITEM message
break;
case MAVLINK_MSG_ID_MISSION_SET_CURRENT:
// Sets the currently active mission item
break;
case MAVLINK_MSG_ID_MISSION_CLEAR_ALL:
// Delete all plan items
_missionItems.clear();
_fenceItems.clear();
_rallyItems.clear();
_sendAck(MAV_MISSION_ACCEPTED);
break;
default:
return false;
}
return true;
}
void MockLinkMissionItemHandler::_handleMissionRequestList(const mavlink_message_t& msg)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequestList read sequence";
_failReadRequest1FirstResponse = true;
if (_failureMode == FailReadRequestListNoResponse) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequestList not responding due to failure mode FailReadRequestListNoResponse";
} else if (_failureMode == FailReadRequestListFirstResponse && _failReadRequestListFirstResponse) {
_failReadRequestListFirstResponse = false;
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequestList not responding due to failure mode FailReadRequestListFirstResponse";
} else {
mavlink_mission_request_list_t request;
_failReadRequestListFirstResponse = true;
mavlink_msg_mission_request_list_decode(&msg, &request);
Q_ASSERT(request.target_system == _mockLink->vehicleId());
_requestType = (MAV_MISSION_TYPE)request.mission_type;
int itemCount;
switch (_requestType) {
case MAV_MISSION_TYPE_MISSION:
itemCount = _missionItems.count();
if (itemCount == 0 && _sendHomePositionOnEmptyList) {
itemCount = 1;
}
break;
case MAV_MISSION_TYPE_FENCE:
itemCount = _fenceItems.count();
break;
case MAV_MISSION_TYPE_RALLY:
itemCount = _rallyItems.count();
break;
default:
Q_ASSERT(false);
}
mavlink_message_t responseMsg;
mavlink_msg_mission_count_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&responseMsg, // Outgoing message
msg.sysid, // Target is original sender
msg.compid, // Target is original sender
itemCount, // Number of mission items
_requestType);
_mockLink->respondWithMavlinkMessage(responseMsg);
}
}
void MockLinkMissionItemHandler::_handleMissionRequest(const mavlink_message_t& msg)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest read sequence";
mavlink_mission_request_t request;
mavlink_msg_mission_request_decode(&msg, &request);
Q_ASSERT(request.target_system == _mockLink->vehicleId());
if (_failureMode == FailReadRequest0NoResponse && request.seq == 0) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest not responding due to failure mode FailReadRequest0NoResponse";
} else if (_failureMode == FailReadRequest1NoResponse && request.seq == 1) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest not responding due to failure mode FailReadRequest1NoResponse";
} else if (_failureMode == FailReadRequest1FirstResponse && request.seq == 1 && _failReadRequest1FirstResponse) {
_failReadRequest1FirstResponse = false;
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest not responding due to failure mode FailReadRequest1FirstResponse";
} else {
// FIXME: Track whether all items are requested, or requested in sequence
if ((_failureMode == FailReadRequest0IncorrectSequence && request.seq == 0) ||
(_failureMode == FailReadRequest1IncorrectSequence && request.seq == 1)) {
// Send back the incorrect sequence number
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionRequest sending bad sequence number";
request.seq++;
}
if ((_failureMode == FailReadRequest0ErrorAck && request.seq == 0) ||
(_failureMode == FailReadRequest1ErrorAck && request.seq == 1)) {
_sendAck(MAV_MISSION_ERROR);
} else {
mavlink_mission_item_t item;
mavlink_message_t responseMsg;
switch (request.mission_type) {
case MAV_MISSION_TYPE_MISSION:
if (_missionItems.count() == 0 && _sendHomePositionOnEmptyList) {
item.frame = MAV_FRAME_GLOBAL_RELATIVE_ALT;
item.command = MAV_CMD_NAV_WAYPOINT;
item.current = false;
item.autocontinue = true;
item.param1 = item.param2 = item.param3 = item.param4 = item.x = item.y = item.z = 0;
} else {
item = _missionItems[request.seq];
}
break;
case MAV_MISSION_TYPE_FENCE:
item = _fenceItems[request.seq];
break;
case MAV_MISSION_TYPE_RALLY:
item = _rallyItems[request.seq];
break;
default:
Q_ASSERT(false);
}
mavlink_msg_mission_item_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&responseMsg, // Outgoing message
msg.sysid, // Target is original sender
msg.compid, // Target is original sender
request.seq, // Index of mission item being sent
item.frame,
item.command,
item.current,
item.autocontinue,
item.param1, item.param2, item.param3, item.param4,
item.x, item.y, item.z,
_requestType);
_mockLink->respondWithMavlinkMessage(responseMsg);
}
}
}
void MockLinkMissionItemHandler::_handleMissionCount(const mavlink_message_t& msg)
{
mavlink_mission_count_t missionCount;
mavlink_msg_mission_count_decode(&msg, &missionCount);
Q_ASSERT(missionCount.target_system == _mockLink->vehicleId());
_requestType = (MAV_MISSION_TYPE)missionCount.mission_type;
_writeSequenceCount = missionCount.count;
Q_ASSERT(_writeSequenceCount >= 0);
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionCount write sequence _writeSequenceCount:" << _writeSequenceCount;
switch (missionCount.mission_type) {
case MAV_MISSION_TYPE_MISSION:
_missionItems.clear();
break;
case MAV_MISSION_TYPE_FENCE:
_fenceItems.clear();
break;
case MAV_MISSION_TYPE_RALLY:
_rallyItems.clear();
break;
}
if (_writeSequenceCount == 0) {
_sendAck(MAV_MISSION_ACCEPTED);
} else {
if (_failureMode == FailWriteMissionCountNoResponse) {
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionCount not responding due to failure mode FailWriteMissionCountNoResponse";
return;
}
if (_failureMode == FailWriteMissionCountFirstResponse && _failWriteMissionCountFirstResponse) {
_failWriteMissionCountFirstResponse = false;
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionCount not responding due to failure mode FailWriteMissionCountNoResponse";
return;
}
_failWriteMissionCountFirstResponse = true;
_writeSequenceIndex = 0;
_requestNextMissionItem(_writeSequenceIndex);
}
}
void MockLinkMissionItemHandler::_requestNextMissionItem(int sequenceNumber)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem write sequence sequenceNumber:" << sequenceNumber << "_failureMode:" << _failureMode;
if (_failureMode == FailWriteRequest1NoResponse && sequenceNumber == 1) {
qCDebug(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem not responding due to failure mode FailWriteRequest1NoResponse";
} else {
if (sequenceNumber >= _writeSequenceCount) {
qCWarning(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem requested seqeuence number > write count sequenceNumber::_writeSequenceCount" << sequenceNumber << _writeSequenceCount;
return;
}
if ((_failureMode == FailWriteRequest0IncorrectSequence && sequenceNumber == 0) ||
(_failureMode == FailWriteRequest1IncorrectSequence && sequenceNumber == 1)) {
sequenceNumber ++;
}
if ((_failureMode == FailWriteRequest0ErrorAck && sequenceNumber == 0) ||
(_failureMode == FailWriteRequest1ErrorAck && sequenceNumber == 1)) {
qCDebug(MockLinkMissionItemHandlerLog) << "_requestNextMissionItem sending ack error due to failure mode";
_sendAck(MAV_MISSION_ERROR);
} else {
mavlink_message_t message;
mavlink_msg_mission_request_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&message,
_mavlinkProtocol->getSystemId(),
_mavlinkProtocol->getComponentId(),
sequenceNumber,
_requestType);
_mockLink->respondWithMavlinkMessage(message);
// If response with Mission Item doesn't come before timer fires it's an error
_startMissionItemResponseTimer();
}
}
}
void MockLinkMissionItemHandler::_sendAck(MAV_MISSION_RESULT ackType)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_sendAck write sequence complete ackType:" << ackType;
mavlink_message_t message;
mavlink_msg_mission_ack_pack_chan(_mockLink->vehicleId(),
MAV_COMP_ID_MISSIONPLANNER,
_mockLink->mavlinkChannel(),
&message,
_mavlinkProtocol->getSystemId(),
_mavlinkProtocol->getComponentId(),
ackType,
_requestType);
_mockLink->respondWithMavlinkMessage(message);
}
void MockLinkMissionItemHandler::_handleMissionItem(const mavlink_message_t& msg)
{
qCDebug(MockLinkMissionItemHandlerLog) << "_handleMissionItem write sequence";
_missionItemResponseTimer->stop();
mavlink_mission_item_t missionItem;
mavlink_msg_mission_item_decode(&msg, &missionItem);
Q_ASSERT(missionItem.target_system == _mockLink->vehicleId());
switch (missionItem.mission_type) {
case MAV_MISSION_TYPE_MISSION:
_missionItems[missionItem.seq] = missionItem;
break;
case MAV_MISSION_TYPE_FENCE:
_fenceItems[missionItem.seq] = missionItem;
break;
case MAV_MISSION_TYPE_RALLY:
_rallyItems[missionItem.seq] = missionItem;
break;
}
_writeSequenceIndex++;
if (_writeSequenceIndex < _writeSequenceCount) {
if (_failureMode == FailWriteFinalAckMissingRequests && _writeSequenceIndex == 3) {
// Send MAV_MISSION_ACCPETED ack too early
_sendAck(MAV_MISSION_ACCEPTED);
} else {
_requestNextMissionItem(_writeSequenceIndex);
}
} else {
if (_failureMode != FailWriteFinalAckNoResponse) {
MAV_MISSION_RESULT ack = MAV_MISSION_ACCEPTED;
if (_failureMode == FailWriteFinalAckErrorAck) {
ack = MAV_MISSION_ERROR;
}
_sendAck(ack);
}
}
}
void MockLinkMissionItemHandler::_missionItemResponseTimeout(void)
{
qWarning() << "Timeout waiting for next MISSION_ITEM";
Q_ASSERT(false);
}
void MockLinkMissionItemHandler::sendUnexpectedMissionAck(MAV_MISSION_RESULT ackType)
{
_sendAck(ackType);
}
void MockLinkMissionItemHandler::sendUnexpectedMissionItem(void)
{
// FIXME: NYI
Q_ASSERT(false);
}
void MockLinkMissionItemHandler::sendUnexpectedMissionRequest(void)
{
// FIXME: NYI
Q_ASSERT(false);
}
void MockLinkMissionItemHandler::setMissionItemFailureMode(FailureMode_t failureMode)
{
_failureMode = failureMode;
}
void MockLinkMissionItemHandler::shutdown(void)
{
if (_missionItemResponseTimer) {
delete _missionItemResponseTimer;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.