<commit_before>// $Id$
//
//  Copyright (C) 2004-2008 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#include "RingInfo.h"
#include <RDGeneral/Invariant.h>
#include <algorithm>

namespace RDKit{
  bool RingInfo::isAtomInRingOfSize(unsigned int idx,unsigned int size) const {
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_atomMembers.size() ){
      return std::find(d_atomMembers[idx].begin(),d_atomMembers[idx].end(),
                       static_cast<int>(size))!=d_atomMembers[idx].end();
    } else {
      return false;
    }
  }
  unsigned int RingInfo::minAtomRingSize(unsigned int idx) const {
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_atomMembers.size() && d_atomMembers[idx].size() ){
      return *std::min_element(d_atomMembers[idx].begin(),d_atomMembers[idx].end());
    } else {
      return 0;
    }
  }
  unsigned int RingInfo::numAtomRings(unsigned int idx) const {
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_atomMembers.size() ){
      return d_atomMembers[idx].size();
    } else {
      return 0;
    }
  }
  bool RingInfo::isBondInRingOfSize(unsigned int idx,unsigned int size) const {
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_bondMembers.size() ){
      return std::find(d_bondMembers[idx].begin(),
                       d_bondMembers[idx].end(),
                       static_cast<int>(size))!=d_bondMembers[idx].end();
    } else {
      return false;
    }

  }
  unsigned int RingInfo::minBondRingSize(unsigned int idx) const {
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_bondMembers.size() && d_bondMembers[idx].size() ){
      return *std::min_element(d_bondMembers[idx].begin(),d_bondMembers[idx].end());
    } else {
      return 0;
    }

  }
  unsigned int RingInfo::numBondRings(unsigned int idx) const {
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_bondMembers.size() ){
      return d_bondMembers[idx].size();
    } else {
      return 0;
    }
  }

  unsigned int RingInfo::numRings() const {
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(d_atomRings.size()==d_bondRings.size(),"length mismatch");
    return d_atomRings.size();
  }

  unsigned int RingInfo::addRing(const INT_VECT &atomIndices,const INT_VECT &bondIndices){
    PRECONDITION(df_init,"not initialized");
    PRECONDITION(atomIndices.size()==bondIndices.size(),"length mismatch");
    int sz = atomIndices.size();
    for(INT_VECT::const_iterator i=atomIndices.begin();
	i<atomIndices.end(); i++){
      if( *i>=static_cast<int>(d_atomMembers.size()) ) d_atomMembers.resize((*i)+1);
      d_atomMembers[*i].push_back(sz);
    }
    for(INT_VECT::const_iterator i=bondIndices.begin();
	i<bondIndices.end(); i++){
      if( *i>=static_cast<int>(d_bondMembers.size()) ) d_bondMembers.resize((*i)+1);
      d_bondMembers[*i].push_back(sz);
    }
    d_atomRings.push_back(atomIndices);
    d_bondRings.push_back(bondIndices);
    POSTCONDITION(d_atomRings.size()==d_bondRings.size(),"length mismatch");
    return d_atomRings.size();
  }

  void RingInfo::initialize() {
    PRECONDITION(!df_init,"already initialized");
    df_init=true;
  };
  void RingInfo::reset(){
    df_init=false;
    d_atomMembers.clear();
    d_bondMembers.clear();
    d_atomRings.clear();
    d_bondRings.clear();
  }
  void RingInfo::preallocate(unsigned int numAtoms,unsigned int numBonds){
    d_atomMembers.resize(numAtoms);
    d_bondMembers.resize(numBonds);
  }
}
<commit_msg>make the "not initialized" error message moderately more informative<commit_after>// $Id$
//
//  Copyright (C) 2004-2008 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#include "RingInfo.h"
#include <RDGeneral/Invariant.h>
#include <algorithm>

namespace RDKit{
  bool RingInfo::isAtomInRingOfSize(unsigned int idx,unsigned int size) const {
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_atomMembers.size() ){
      return std::find(d_atomMembers[idx].begin(),d_atomMembers[idx].end(),
                       static_cast<int>(size))!=d_atomMembers[idx].end();
    } else {
      return false;
    }
  }
  unsigned int RingInfo::minAtomRingSize(unsigned int idx) const {
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_atomMembers.size() && d_atomMembers[idx].size() ){
      return *std::min_element(d_atomMembers[idx].begin(),d_atomMembers[idx].end());
    } else {
      return 0;
    }
  }
  unsigned int RingInfo::numAtomRings(unsigned int idx) const {
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_atomMembers.size() ){
      return d_atomMembers[idx].size();
    } else {
      return 0;
    }
  }
  bool RingInfo::isBondInRingOfSize(unsigned int idx,unsigned int size) const {
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_bondMembers.size() ){
      return std::find(d_bondMembers[idx].begin(),
                       d_bondMembers[idx].end(),
                       static_cast<int>(size))!=d_bondMembers[idx].end();
    } else {
      return false;
    }

  }
  unsigned int RingInfo::minBondRingSize(unsigned int idx) const {
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_bondMembers.size() && d_bondMembers[idx].size() ){
      return *std::min_element(d_bondMembers[idx].begin(),d_bondMembers[idx].end());
    } else {
      return 0;
    }

  }
  unsigned int RingInfo::numBondRings(unsigned int idx) const {
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(idx>=0,"bad index");
    if( idx < d_bondMembers.size() ){
      return d_bondMembers[idx].size();
    } else {
      return 0;
    }
  }

  unsigned int RingInfo::numRings() const {
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(d_atomRings.size()==d_bondRings.size(),"length mismatch");
    return d_atomRings.size();
  }

  unsigned int RingInfo::addRing(const INT_VECT &atomIndices,const INT_VECT &bondIndices){
    PRECONDITION(df_init,"RingInfo not initialized");
    PRECONDITION(atomIndices.size()==bondIndices.size(),"length mismatch");
    int sz = atomIndices.size();
    for(INT_VECT::const_iterator i=atomIndices.begin();
	i<atomIndices.end(); i++){
      if( *i>=static_cast<int>(d_atomMembers.size()) ) d_atomMembers.resize((*i)+1);
      d_atomMembers[*i].push_back(sz);
    }
    for(INT_VECT::const_iterator i=bondIndices.begin();
	i<bondIndices.end(); i++){
      if( *i>=static_cast<int>(d_bondMembers.size()) ) d_bondMembers.resize((*i)+1);
      d_bondMembers[*i].push_back(sz);
    }
    d_atomRings.push_back(atomIndices);
    d_bondRings.push_back(bondIndices);
    POSTCONDITION(d_atomRings.size()==d_bondRings.size(),"length mismatch");
    return d_atomRings.size();
  }

  void RingInfo::initialize() {
    PRECONDITION(!df_init,"already initialized");
    df_init=true;
  };
  void RingInfo::reset(){
    df_init=false;
    d_atomMembers.clear();
    d_bondMembers.clear();
    d_atomRings.clear();
    d_bondRings.clear();
  }
  void RingInfo::preallocate(unsigned int numAtoms,unsigned int numBonds){
    d_atomMembers.resize(numAtoms);
    d_bondMembers.resize(numBonds);
  }
}
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h"

#include <string>

#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/stream_executor/stream.h"
#include "tensorflow/stream_executor/stream_executor_internal.h"

static void ReportInternalError(tensorflow::OpKernelContext *ctx,
                                const std::string msg) {
  if (ctx == nullptr) {
    LOG(WARNING) << msg << "\n";
    return;
  }
  ctx->CtxFailureWithWarning(
      tensorflow::Status{tensorflow::error::INTERNAL, msg});
}

#if GOOGLE_CUDA
using GPUResult = CUresult;
#endif
#if TENSORFLOW_USE_ROCM
using GPUResult = hipError_t;
#endif

void GPUReportIfError(GPUResult result, tensorflow::OpKernelContext *ctx,
                      const char *expr_str) {
  if (!result) return;

#if GOOGLE_CUDA
  const char *name = nullptr;
  cuGetErrorName(result, &name);
#endif
#if TENSORFLOW_USE_ROCM
  const char *name = hipGetErrorName(result);
#endif

  if (!name) name = "<unknown>";
  std::string msg = absl::StrCat("'", expr_str, "' failed with '", name, "'");
  ReportInternalError(ctx, msg);
}

#define GPU_REPORT_IF_ERROR_WITH_CTX(expr, ctx) \
  GPUReportIfError(expr, ctx, #expr)
#define GPU_REPORT_IF_ERROR(expr) GPU_REPORT_IF_ERROR_WITH_CTX(expr, nullptr)

// Implement the GPU module cache and share what can be shared.

namespace mlir {
namespace kernel_gen {
namespace tf_framework {

GPURuntimeCache::~GPURuntimeCache() {
  tensorflow::mutex_lock lock(mu_);
  for (auto it : gpu_module_by_data_ptr_) {
#if GOOGLE_CUDA
    GPU_REPORT_IF_ERROR(cuModuleUnload(it.second));
#endif
#if TENSORFLOW_USE_ROCM
    GPU_REPORT_IF_ERROR(hipModuleUnload(it.second));
#endif
  }
}

tensorflow::Status GPURuntimeCache::Create(GPURuntimeCache **dst) {
  *dst = new GPURuntimeCache;
  return tensorflow::Status::OK();
}

std::string GPURuntimeCache::DebugString() const { return "GPU runtime cache"; }

GPURuntimeCache::GPUModule GPURuntimeCache::LookupOrLoadModule(void *data) {
  tensorflow::mutex_lock lock(mu_);
  GPUModule &module = gpu_module_by_data_ptr_[data];

#if GOOGLE_CUDA
  if (!module) GPU_REPORT_IF_ERROR(cuModuleLoadData(&module, data));
#endif
#if TENSORFLOW_USE_ROCM
  if (!module) GPU_REPORT_IF_ERROR(hipModuleLoadData(&module, data));
#endif

  return module;
}

// Implements a C wrapper around the TensorFlow runtime and CUDA (or ROCm)
// library that allows launching a kernel on the current device and stream from
// a binary blob for the module and function name.
// The wrapper uses intptr_t instead of CUDA's unsigned int (or ROCm's unsigned
// int) to match the type of MLIR's index type. This avoids the need for casts
// in the generated MLIR code.
extern "C" void _mlir_ciface_tf_launch_kernel(void *ctx, void *module_blob,
                                              char *kernel_name, intptr_t gridX,
                                              intptr_t gridY, intptr_t gridZ,
                                              intptr_t blockX, intptr_t blockY,
                                              intptr_t blockZ, void **params) {
  // For empty grids, we don't need to do anything.
  if (!gridX || !gridY || !gridZ) return;

  // Get the GPU module cache.
  auto *op_kernel_ctx = static_cast<tensorflow::OpKernelContext *>(ctx);
  auto *rm = op_kernel_ctx->resource_manager();
  if (rm == nullptr) {
    ReportInternalError(op_kernel_ctx, "expected resource_manager");
    return;
  }
  GPURuntimeCache *cache = nullptr;
  OP_REQUIRES_OK(op_kernel_ctx, rm->LookupOrCreate<GPURuntimeCache>(
                                    rm->default_container(),
                                    GPURuntimeCache::kDefaultResourceName,
                                    &cache, GPURuntimeCache::Create));
  assert(cache != nullptr && "cache creation must not fail");
  tensorflow::core::ScopedUnref ref(cache);

  // Get the GPU module.
  stream_executor::Stream *se_stream =
      op_kernel_ctx->op_device_context()->stream();
  void *stream = se_stream->implementation()->GpuStreamHack();
  GPURuntimeCache::GPUModule module = cache->LookupOrLoadModule(module_blob);

#if GOOGLE_CUDA
  CUfunction function;
  GPU_REPORT_IF_ERROR_WITH_CTX(
      cuModuleGetFunction(&function, module, kernel_name), op_kernel_ctx);
  GPU_REPORT_IF_ERROR_WITH_CTX(
      cuLaunchKernel(function, gridX, gridY, gridZ, blockX, blockY, blockZ,
                     /*sharedMemBytes=*/0, reinterpret_cast<CUstream>(stream),
                     params, nullptr),
      op_kernel_ctx);
#endif
#if TENSORFLOW_USE_ROCM
  hipFunction_t function;
  GPU_REPORT_IF_ERROR_WITH_CTX(
      hipModuleGetFunction(&function, module, kernel_name), op_kernel_ctx);
  GPU_REPORT_IF_ERROR_WITH_CTX(
      hipModuleLaunchKernel(
          function, gridX, gridY, gridZ, blockX, blockY, blockZ,
          /*sharedMemBytes=*/0, reinterpret_cast<hipStream_t>(stream), params,
          nullptr),
      op_kernel_ctx);
#endif
}

}  // namespace tf_framework
}  // namespace kernel_gen
}  // namespace mlir
<commit_msg>[MLIR][KernelGen] Share similar code between Cuda and Rocm error handling<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h"

#include <string>

#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/stream_executor/stream.h"
#include "tensorflow/stream_executor/stream_executor_internal.h"

static void ReportInternalError(tensorflow::OpKernelContext *ctx,
                                const std::string msg) {
  if (ctx == nullptr) {
    LOG(WARNING) << msg << "\n";
    return;
  }
  ctx->CtxFailureWithWarning(
      tensorflow::Status{tensorflow::error::INTERNAL, msg});
}

#define CUDA_REPORT_IF_ERROR_WITH_CTX(expr, context)                          \
  [](CUresult result, tensorflow::OpKernelContext *ctx) {                     \
    if (!result) return;                                                      \
    const char *name = nullptr;                                               \
    cuGetErrorName(result, &name);                                            \
    if (!name) name = "<unknown>";                                            \
    std::string msg = absl::StrCat("'", #expr, "' failed with '", name, "'"); \
    if (ctx != nullptr) {                                                     \
      ctx->CtxFailureWithWarning(                                             \
          tensorflow::Status{tensorflow::error::INTERNAL, msg});              \
    } else {                                                                  \
      LOG(WARNING) << msg << "\n";                                            \
    }                                                                         \
  }(expr, context)

#define CUDA_REPORT_IF_ERROR(expr) CUDA_REPORT_IF_ERROR_WITH_CTX(expr, nullptr)

#define HIP_REPORT_IF_ERROR_WITH_CTX(expr, context)                           \
  [](hipError_t result, tensorflow::OpKernelContext *ctx) {                   \
    if (!result) return;                                                      \
    const char *name = hipGetErrorName(result);                               \
    if (!name) name = "<unknown>";                                            \
    std::string msg = absl::StrCat("'", #expr, "' failed with '", name, "'"); \
    if (ctx != nullptr) {                                                     \
      ctx->CtxFailureWithWarning(                                             \
          tensorflow::Status{tensorflow::error::INTERNAL, msg});              \
    } else {                                                                  \
      LOG(WARNING) << msg << "\n";                                            \
    }                                                                         \
  }(expr, context)

#define HIP_REPORT_IF_ERROR(expr) HIP_REPORT_IF_ERROR_WITH_CTX(expr, nullptr)

// Implement the GPU module cache and share what can be shared.

namespace mlir {
namespace kernel_gen {
namespace tf_framework {

GPURuntimeCache::~GPURuntimeCache() {
  tensorflow::mutex_lock lock(mu_);
  for (auto it : gpu_module_by_data_ptr_) {
#if GOOGLE_CUDA
    CUDA_REPORT_IF_ERROR(cuModuleUnload(it.second));
#endif
#if TENSORFLOW_USE_ROCM
    HIP_REPORT_IF_ERROR(hipModuleUnload(it.second));
#endif
  }
}

tensorflow::Status GPURuntimeCache::Create(GPURuntimeCache **dst) {
  *dst = new GPURuntimeCache;
  return tensorflow::Status::OK();
}

std::string GPURuntimeCache::DebugString() const { return "GPU runtime cache"; }

GPURuntimeCache::GPUModule GPURuntimeCache::LookupOrLoadModule(void *data) {
  tensorflow::mutex_lock lock(mu_);
  GPUModule &module = gpu_module_by_data_ptr_[data];

#if GOOGLE_CUDA
  if (!module) CUDA_REPORT_IF_ERROR(cuModuleLoadData(&module, data));
#endif
#if TENSORFLOW_USE_ROCM
  if (!module) HIP_REPORT_IF_ERROR(hipModuleLoadData(&module, data));
#endif

  return module;
}

// Implements a C wrapper around the TensorFlow runtime and CUDA (or ROCm)
// library that allows launching a kernel on the current device and stream from
// a binary blob for the module and function name.
// The wrapper uses intptr_t instead of CUDA's unsigned int (or ROCm's unsigned
// int) to match the type of MLIR's index type. This avoids the need for casts
// in the generated MLIR code.
extern "C" void _mlir_ciface_tf_launch_kernel(void *ctx, void *module_blob,
                                              char *kernel_name, intptr_t gridX,
                                              intptr_t gridY, intptr_t gridZ,
                                              intptr_t blockX, intptr_t blockY,
                                              intptr_t blockZ, void **params) {
  // For empty grids, we don't need to do anything.
  if (!gridX || !gridY || !gridZ) return;

  // Get the GPU module cache.
  auto *op_kernel_ctx = static_cast<tensorflow::OpKernelContext *>(ctx);
  auto *rm = op_kernel_ctx->resource_manager();
  if (rm == nullptr) {
    ReportInternalError(op_kernel_ctx, "expected resource_manager");
    return;
  }
  GPURuntimeCache *cache = nullptr;
  OP_REQUIRES_OK(op_kernel_ctx, rm->LookupOrCreate<GPURuntimeCache>(
                                    rm->default_container(),
                                    GPURuntimeCache::kDefaultResourceName,
                                    &cache, GPURuntimeCache::Create));
  assert(cache != nullptr && "cache creation must not fail");
  tensorflow::core::ScopedUnref ref(cache);

  // Get the GPU module.
  stream_executor::Stream *se_stream =
      op_kernel_ctx->op_device_context()->stream();
  void *stream = se_stream->implementation()->GpuStreamHack();
  GPURuntimeCache::GPUModule module = cache->LookupOrLoadModule(module_blob);

#if GOOGLE_CUDA
  CUfunction function;
  CUDA_REPORT_IF_ERROR_WITH_CTX(
      cuModuleGetFunction(&function, module, kernel_name), op_kernel_ctx);
  CUDA_REPORT_IF_ERROR_WITH_CTX(
      cuLaunchKernel(function, gridX, gridY, gridZ, blockX, blockY, blockZ,
                     /*sharedMemBytes=*/0, reinterpret_cast<CUstream>(stream),
                     params, nullptr),
      op_kernel_ctx);
#endif
#if TENSORFLOW_USE_ROCM
  hipFunction_t function;
  HIP_REPORT_IF_ERROR_WITH_CTX(
      hipModuleGetFunction(&function, module, kernel_name), op_kernel_ctx);
  HIP_REPORT_IF_ERROR_WITH_CTX(
      hipModuleLaunchKernel(
          function, gridX, gridY, gridZ, blockX, blockY, blockZ,
          /*sharedMemBytes=*/0, reinterpret_cast<hipStream_t>(stream), params,
          nullptr),
      op_kernel_ctx);
#endif
}

}  // namespace tf_framework
}  // namespace kernel_gen
}  // namespace mlir
<|endoftext|>


<commit_before>/*
 * ssl_context_service.cpp
 *
 *  Created on: Aug 21, 2015
 *      Author: zmij
 */

#include <tip/ssl_context_service.hpp>
#include <boost/filesystem.hpp>

namespace tip {
namespace ssl {

ssl_context_service::io_service::id ssl_context_service::id;

struct ssl_context_service::impl {
	context_type context_;

	impl() : context_(context_type::sslv23)
	{
	}

	void
	load_verify_files(path_type const& p)
	{
		namespace fs = boost::filesystem;
		if (fs::exists(p)) {
			if (fs::is_directory(p)) {
				fs::directory_iterator f(p);
				fs::directory_iterator eod;
				for (; f != eod; ++f) {
					if (fs::is_regular_file(*f)) {
						context_.load_verify_file(f->path().native());
					}
				}
			} else if (fs::is_regular_file(p)) {
				context_.load_verify_file(p.native());
			}
		}
	}

	void
	load_default_verify_path()
	{
	    context_.set_default_verify_paths();
	}
};

ssl_context_service::ssl_context_service(io_service& svc) : base_type(svc), pimpl_(new impl)
{
}

ssl_context_service::~ssl_context_service()
{
}

ssl_context_service::context_type&
ssl_context_service::context()
{
	return pimpl_->context_;
}

ssl_context_service::context_type const&
ssl_context_service::context() const
{
	return pimpl_->context_;
}

void
ssl_context_service::load_verify_files(path_type const& p)
{
	pimpl_->load_verify_files(p);
}

void
ssl_context_service::load_default_verify_path()
{
    pimpl_->load_default_verify_path();
}

void
ssl_context_service::shutdown_service()
{
}

} /* namespace ssl */
} /* namespace tip */
<commit_msg>Use tls1.2 instead of ssl3<commit_after>/*
 * ssl_context_service.cpp
 *
 *  Created on: Aug 21, 2015
 *      Author: zmij
 */

#include <tip/ssl_context_service.hpp>
#include <boost/filesystem.hpp>

namespace tip {
namespace ssl {

ssl_context_service::io_service::id ssl_context_service::id;

struct ssl_context_service::impl {
	context_type context_;

	impl() : context_(context_type::tlsv12)
	{
	    using ssl_context       = ::boost::asio::ssl::context;
	    context_.set_options(
            ssl_context::default_workarounds |
            ssl_context::no_sslv2 |
            ssl_context::single_dh_use
        );
	}

	void
	load_verify_files(path_type const& p)
	{
		namespace fs = boost::filesystem;
		if (fs::exists(p)) {
			if (fs::is_directory(p)) {
				fs::directory_iterator f(p);
				fs::directory_iterator eod;
				for (; f != eod; ++f) {
					if (fs::is_regular_file(*f)) {
						context_.load_verify_file(f->path().native());
					}
				}
			} else if (fs::is_regular_file(p)) {
				context_.load_verify_file(p.native());
			}
		}
	}

	void
	load_default_verify_path()
	{
	    context_.set_default_verify_paths();
	}
};

ssl_context_service::ssl_context_service(io_service& svc) : base_type(svc), pimpl_(new impl)
{
}

ssl_context_service::~ssl_context_service()
{
}

ssl_context_service::context_type&
ssl_context_service::context()
{
	return pimpl_->context_;
}

ssl_context_service::context_type const&
ssl_context_service::context() const
{
	return pimpl_->context_;
}

void
ssl_context_service::load_verify_files(path_type const& p)
{
	pimpl_->load_verify_files(p);
}

void
ssl_context_service::load_default_verify_path()
{
    pimpl_->load_default_verify_path();
}

void
ssl_context_service::shutdown_service()
{
}

} /* namespace ssl */
} /* namespace tip */
<|endoftext|>


<commit_before>/**
 * @file treeproc.cpp
 * @brief Node tree processor
 *
 * (c) 2013-2014 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "mega/treeproc.h"
#include "mega/megaclient.h"
#include "mega/logging.h"

namespace mega {
// create share keys
TreeProcShareKeys::TreeProcShareKeys(Node* n)
{
    sn = n;
}

void TreeProcShareKeys::proc(MegaClient*, Node* n)
{
    snk.add(n, sn, sn != NULL);
}

void TreeProcShareKeys::get(Command* c)
{
    snk.get(c);
}

void TreeProcForeignKeys::proc(MegaClient* client, Node* n)
{
    if (n->foreignkey)
    {
        client->nodekeyrewrite.push_back(n->nodehandle);

        n->foreignkey = false;
    }
}

// total disk space / node count
TreeProcDU::TreeProcDU()
{
    numbytes = 0;
    numfiles = 0;
    numfolders = 0;
}

void TreeProcDU::proc(MegaClient*, Node* n)
{
    if (n->type == FILENODE)
    {
        numbytes += n->size;
        numfiles++;
    }
    else
    {
        numfolders++;
    }
}

// mark node as removed and notify
void TreeProcDel::proc(MegaClient* client, Node* n)
{
    n->changed.removed = true;
    n->tag = client->reqtag;
    client->notifynode(n);
    if (n->owner != client->me)
    {
        client->useralerts.noteSharedNode(n->owner, n->type, 0, NULL);
    }
}

void TreeProcApplyKey::proc(MegaClient *client, Node *n)
{
    if (n->attrstring)
    {
        n->applykey();
        if (!n->attrstring)
        {
            n->changed.attrs = true;
            client->notifynode(n);
        }
    }
}

#ifdef ENABLE_SYNC
// stop sync get
void TreeProcDelSyncGet::proc(MegaClient*, Node* n)
{
    if (n->syncget)
    {
        delete n->syncget;
        n->syncget = NULL;
    }
}

LocalTreeProcMove::LocalTreeProcMove(Sync* sync, bool recreate)
{
    this->newsync = sync;
    this->recreate = recreate;
    nc = 0;
}

void LocalTreeProcMove::proc(MegaClient*, LocalNode* localnode)
{
    if (newsync != localnode->sync)
    {
        localnode->sync->statecachedel(localnode);
        localnode->sync = newsync;
        newsync->statecacheadd(localnode);
    }

    if (recreate)
    {
        localnode->created = false;
        localnode->node.reset();
    }

    nc++;
}

void LocalTreeProcUpdateTransfers::proc(MegaClient *client, LocalNode *localnode)
{
    if (localnode->transfer && !localnode->transfer->localfilename.empty())
    {
        LOG_debug << "Updating transfer path";
        localnode->prepare(*client->fsaccess);
    }
}

void LocalTreeProcUnlinkNodes::proc(MegaClient *, LocalNode *localnode)
{
    localnode->node.reset();
}

#endif
} // namespace
<commit_msg>Fix the wrong value for UserAlerts::RemovedSharedNode::itemsNumber<commit_after>/**
 * @file treeproc.cpp
 * @brief Node tree processor
 *
 * (c) 2013-2014 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "mega/treeproc.h"
#include "mega/megaclient.h"
#include "mega/logging.h"

namespace mega {
// create share keys
TreeProcShareKeys::TreeProcShareKeys(Node* n)
{
    sn = n;
}

void TreeProcShareKeys::proc(MegaClient*, Node* n)
{
    snk.add(n, sn, sn != NULL);
}

void TreeProcShareKeys::get(Command* c)
{
    snk.get(c);
}

void TreeProcForeignKeys::proc(MegaClient* client, Node* n)
{
    if (n->foreignkey)
    {
        client->nodekeyrewrite.push_back(n->nodehandle);

        n->foreignkey = false;
    }
}

// total disk space / node count
TreeProcDU::TreeProcDU()
{
    numbytes = 0;
    numfiles = 0;
    numfolders = 0;
}

void TreeProcDU::proc(MegaClient*, Node* n)
{
    if (n->type == FILENODE)
    {
        numbytes += n->size;
        numfiles++;
    }
    else
    {
        numfolders++;
    }
}

// mark node as removed and notify
void TreeProcDel::proc(MegaClient* client, Node* n)
{
    n->changed.removed = true;
    n->tag = client->reqtag;
    client->notifynode(n);
    if (n->owner != client->me)
    {
        client->useralerts.noteSharedNode(n->owner, n->type, 0, n);
    }
}

void TreeProcApplyKey::proc(MegaClient *client, Node *n)
{
    if (n->attrstring)
    {
        n->applykey();
        if (!n->attrstring)
        {
            n->changed.attrs = true;
            client->notifynode(n);
        }
    }
}

#ifdef ENABLE_SYNC
// stop sync get
void TreeProcDelSyncGet::proc(MegaClient*, Node* n)
{
    if (n->syncget)
    {
        delete n->syncget;
        n->syncget = NULL;
    }
}

LocalTreeProcMove::LocalTreeProcMove(Sync* sync, bool recreate)
{
    this->newsync = sync;
    this->recreate = recreate;
    nc = 0;
}

void LocalTreeProcMove::proc(MegaClient*, LocalNode* localnode)
{
    if (newsync != localnode->sync)
    {
        localnode->sync->statecachedel(localnode);
        localnode->sync = newsync;
        newsync->statecacheadd(localnode);
    }

    if (recreate)
    {
        localnode->created = false;
        localnode->node.reset();
    }

    nc++;
}

void LocalTreeProcUpdateTransfers::proc(MegaClient *client, LocalNode *localnode)
{
    if (localnode->transfer && !localnode->transfer->localfilename.empty())
    {
        LOG_debug << "Updating transfer path";
        localnode->prepare(*client->fsaccess);
    }
}

void LocalTreeProcUnlinkNodes::proc(MegaClient *, LocalNode *localnode)
{
    localnode->node.reset();
}

#endif
} // namespace
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkGDCMImageIO.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm 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 "itkGDCMImageIO.h"
#include "gdcmFile.h"
#include "gdcmHeaderHelper.h"
#include <fstream>

namespace itk
{

GDCMImageIO::GDCMImageIO()
{
//  this->SetNumberOfDimensions(2); //default
  m_ByteOrder = LittleEndian; //default
  m_FileType = Binary;  //default...always true
  m_RescaleSlope = 1.0;
  m_RescaleIntercept = 0.0;
  m_GdcmHeader = NULL;
}

GDCMImageIO::~GDCMImageIO()
{
  //delete m_GdcmHeader;
}

bool GDCMImageIO::OpenGDCMFileForReading(std::ifstream& os,
                                         const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for reading
  itkDebugMacro(<< "Initialize: opening file " << filename);

  // Actually open the file
  os.open( filename, std::ios::in | std::ios::binary );

  if ( os.fail() )
    {
    return false;
    }

  return true;
}

bool GDCMImageIO::OpenGDCMFileForWriting(std::ofstream& os,
                                         const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for writing
  itkDebugMacro(<< "Initialize: opening file " << filename);

#ifdef __sgi
  // Create the file. This is required on some older sgi's
  std::ofstream tFile(filename,std::ios::out);
  tFile.close();
#endif

  // Actually open the file
  os.open( filename, std::ios::out | std::ios::binary );

  if( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for writing: " << filename);
    return false;
    }

  return true;
}

// This method will only test if the header looks like a
//GDCM image file.
bool GDCMImageIO::CanReadFile(const char* filename)
{
  std::ifstream file;
  char buffer[256];
  std::string fname(filename);

  if(  fname == "" )
    {
    itkDebugMacro(<<"No filename specified.");
    return false;
    }

  bool extensionFound = false;
  std::string::size_type sprPos = fname.rfind(".dcm");  //acr nema ??
  if ((sprPos != std::string::npos)
      && (sprPos == fname.length() - 4))
    {
    extensionFound = true;
    }

  if( !extensionFound )
    {
    itkDebugMacro(<<"The filename extension is not recognized");
    return false;
    }

  //Check for file existence:
  if ( ! this->OpenGDCMFileForReading(file, filename))
    {
    return false;
    }

  // Check to see if its a valid dicom file gdcm is able to parse:
  //We are parsing the header one time here:

  gdcmHeader GdcmHeader( filename );
  if (!m_GdcmHeader->IsReadable())
    {
    itkExceptionMacro("Gdcm cannot parse file " << filename );
    return false;
    }

  //For later : For 2d stack dicom:
  //we should not mix insoncistent on pixel type
  //GdcmHeader.GetPixelType();
  //we should not mix insoncistent on image size
  //GdcmHeader.GetXSize(); GdcmHeader.GetYSize(); GdcmHeader.GetZSize();
  //spacing:
  //GdcmHeader.GetXSpacing(); GdcmHeader.GetYSpacing(); ...
  //GdcmHeader.GetXOrigin() ...

  return true;
}

void GDCMImageIO::Read(void* buffer)
{
  std::ifstream file;

  //read header information file:
  this->InternalReadImageInformation(file);

  //Should I handle differently dicom lut ?
  //GdcmHeader.HasLUT()

  if( !this->ReadBufferAsBinary( file, buffer, this->GetImageSizeInBytes()) )
    {
    itkExceptionMacro(<<"Read failed: Wanted "
                      << this->GetImageSizeInBytes()
                      << " bytes, but read "
                      << file.gcount() << " bytes.");
    }

  m_GdcmHeader = new gdcmHeader( m_FileName.c_str() );

  gdcmFile GdcmFile(m_FileName);
  size_t size = GdcmFile.GetImageDataSize();
  //== this->GetImageSizeInComponents()
  unsigned char *Source = (unsigned char*)GdcmFile.GetImageData();
  memcpy((void*)buffer, (void*)Source, size);

  //closing files:
  file.close();
}

void GDCMImageIO::InternalReadImageInformation(std::ifstream& file)
{
  //read header
  if ( ! this->OpenGDCMFileForReading(file, m_FileName.c_str()) )
    {
    itkExceptionMacro(<< "Cannot read requested file");
    }

  gdcmHeaderHelper *GdcmHeader = new gdcmHeaderHelper(m_FileName.c_str());

  // We don't need to positionate the Endian related stuff (by using
  // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
  // since the reading of the file is done by gdcm.
  // But we do need to set up the data type for downstream filters:

  std::string type = GdcmHeader->GetPixelType();
  if( type == "8U")
    {
    SetPixelType(UCHAR);
    SetComponentType(UCHAR);
    }
  else if( type == "8S")
    {
    SetPixelType(CHAR);
    SetComponentType(CHAR);
    }
  else if( type == "16U")
    {
    SetPixelType(USHORT);
    SetComponentType(USHORT);
    }
  else if( type == "16S")
    {
    SetPixelType(SHORT);
    SetComponentType(SHORT);
    }
  else if( type == "32U")
    {
    SetPixelType(UINT);
    SetComponentType(UINT);
    }
  else if( type == "32S")
    {
    SetPixelType(INT);
    SetComponentType(INT);
    }
  else if ( type == "FD" )
    {
    //64 bits Double image
    SetPixelType(DOUBLE);
    SetComponentType(DOUBLE);
    }
  else
    {
    itkExceptionMacro(<<"Unrecognized type:" << type);
    }

  // set values in case we don't find them
  this->SetNumberOfDimensions(2);
  m_Dimensions[0] = GdcmHeader->GetXSize();
  m_Dimensions[1] = GdcmHeader->GetYSize();
  //m_Dimensions[2] = GdcmHeader->GetZSize();
  m_Dimensions[2] = 0;

  m_Spacing[0] = GdcmHeader->GetXSpacing();
  m_Spacing[1] = GdcmHeader->GetYSpacing();
  //  m_Spacing[2] = GdcmHeader->GetZSpacing();
  m_Spacing[2] = 0;

  m_Origin[0] = GdcmHeader->GetXOrigin();
  m_Origin[1] = GdcmHeader->GetYOrigin();
  m_Origin[2] = GdcmHeader->GetZOrigin();

  //For grayscale image :
  m_RescaleSlope = GdcmHeader->GetRescaleSlope();
  m_RescaleIntercept = GdcmHeader->GetRescaleIntercept();

}

void GDCMImageIO::ReadImageInformation()
{
  std::ifstream file;
  this->InternalReadImageInformation(file);
}

bool GDCMImageIO::CanWriteFile( const char* name )
{
  std::string filename = name;

  if(  filename == "" )
    {
    itkDebugMacro(<<"No filename specified.");
    return false;
    }

  bool extensionFound = false;
  std::string::size_type sprPos = filename.rfind(".dcm");
  if ((sprPos != std::string::npos)
      && (sprPos == filename.length() - 4))
    {
    extensionFound = true;
    }

  if( !extensionFound )
    {
    itkDebugMacro(<<"The filename extension is not recognized");
    return false;
    }

  return true;
}

void GDCMImageIO::WriteImageInformation()
{
}

void GDCMImageIO::Write(const void* buffer)
{
  std::ofstream file;
  if ( ! this->OpenGDCMFileForWriting(file, m_FileName.c_str()) )
    {
    return;
    }

  const unsigned long numberOfBytes = this->GetImageSizeInBytes();

  gdcmFile *GdcmFile = new gdcmFile( m_GdcmHeader );
  GdcmFile->SetImageData((void*)buffer, numberOfBytes );
  GdcmFile->WriteDcmExplVR(m_FileName);

  file.close();
}

void GDCMImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "RescaleSlope: " << m_RescaleSlope << "\n";
  os << indent << "RescaleIntercept: " << m_RescaleIntercept << "\n";
}

} // end namespace itk
<commit_msg>BUG: Need to reallocate m_Origin<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkGDCMImageIO.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm 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 "itkGDCMImageIO.h"
#include "gdcmFile.h"
#include "gdcmHeaderHelper.h"
#include <fstream>

namespace itk
{

GDCMImageIO::GDCMImageIO()
{
//  this->SetNumberOfDimensions(2); //default
  m_ByteOrder = LittleEndian; //default
  m_FileType = Binary;  //default...always true
  m_RescaleSlope = 1.0;
  m_RescaleIntercept = 0.0;
  m_GdcmHeader = NULL;
}

GDCMImageIO::~GDCMImageIO()
{
  //delete m_GdcmHeader;
}

bool GDCMImageIO::OpenGDCMFileForReading(std::ifstream& os,
                                         const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for reading
  itkDebugMacro(<< "Initialize: opening file " << filename);

  // Actually open the file
  os.open( filename, std::ios::in | std::ios::binary );

  if ( os.fail() )
    {
    return false;
    }

  return true;
}

bool GDCMImageIO::OpenGDCMFileForWriting(std::ofstream& os,
                                         const char* filename)

{
  // Make sure that we have a file to
  if ( filename == "" )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    return false;
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for writing
  itkDebugMacro(<< "Initialize: opening file " << filename);

#ifdef __sgi
  // Create the file. This is required on some older sgi's
  std::ofstream tFile(filename,std::ios::out);
  tFile.close();
#endif

  // Actually open the file
  os.open( filename, std::ios::out | std::ios::binary );

  if( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for writing: " << filename);
    return false;
    }

  return true;
}

// This method will only test if the header looks like a
//GDCM image file.
bool GDCMImageIO::CanReadFile(const char* filename)
{
  std::ifstream file;
  char buffer[256];
  std::string fname(filename);

  if(  fname == "" )
    {
    itkDebugMacro(<<"No filename specified.");
    return false;
    }

  bool extensionFound = false;
  std::string::size_type sprPos = fname.rfind(".dcm");  //acr nema ??
  if ((sprPos != std::string::npos)
      && (sprPos == fname.length() - 4))
    {
    extensionFound = true;
    }

  if( !extensionFound )
    {
    itkDebugMacro(<<"The filename extension is not recognized");
    return false;
    }

  //Check for file existence:
  if ( ! this->OpenGDCMFileForReading(file, filename))
    {
    return false;
    }

  // Check to see if its a valid dicom file gdcm is able to parse:
  //We are parsing the header one time here:

  gdcmHeader GdcmHeader( filename );
  if (!m_GdcmHeader->IsReadable())
    {
    itkExceptionMacro("Gdcm cannot parse file " << filename );
    return false;
    }

  //For later : For 2d stack dicom:
  //we should not mix insoncistent on pixel type
  //GdcmHeader.GetPixelType();
  //we should not mix insoncistent on image size
  //GdcmHeader.GetXSize(); GdcmHeader.GetYSize(); GdcmHeader.GetZSize();
  //spacing:
  //GdcmHeader.GetXSpacing(); GdcmHeader.GetYSpacing(); ...
  //GdcmHeader.GetXOrigin() ...

  return true;
}

void GDCMImageIO::Read(void* buffer)
{
  std::ifstream file;

  //read header information file:
  this->InternalReadImageInformation(file);

  //Should I handle differently dicom lut ?
  //GdcmHeader.HasLUT()

  if( !this->ReadBufferAsBinary( file, buffer, this->GetImageSizeInBytes()) )
    {
    itkExceptionMacro(<<"Read failed: Wanted "
                      << this->GetImageSizeInBytes()
                      << " bytes, but read "
                      << file.gcount() << " bytes.");
    }

  m_GdcmHeader = new gdcmHeader( m_FileName.c_str() );

  gdcmFile GdcmFile(m_FileName);
  size_t size = GdcmFile.GetImageDataSize();
  //== this->GetImageSizeInComponents()
  unsigned char *Source = (unsigned char*)GdcmFile.GetImageData();
  memcpy((void*)buffer, (void*)Source, size);

  //closing files:
  file.close();
}

void GDCMImageIO::InternalReadImageInformation(std::ifstream& file)
{
  //read header
  if ( ! this->OpenGDCMFileForReading(file, m_FileName.c_str()) )
    {
    itkExceptionMacro(<< "Cannot read requested file");
    }

  gdcmHeaderHelper *GdcmHeader = new gdcmHeaderHelper(m_FileName.c_str());

  // We don't need to positionate the Endian related stuff (by using
  // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
  // since the reading of the file is done by gdcm.
  // But we do need to set up the data type for downstream filters:

  std::string type = GdcmHeader->GetPixelType();
  if( type == "8U")
    {
    SetPixelType(UCHAR);
    SetComponentType(UCHAR);
    }
  else if( type == "8S")
    {
    SetPixelType(CHAR);
    SetComponentType(CHAR);
    }
  else if( type == "16U")
    {
    SetPixelType(USHORT);
    SetComponentType(USHORT);
    }
  else if( type == "16S")
    {
    SetPixelType(SHORT);
    SetComponentType(SHORT);
    }
  else if( type == "32U")
    {
    SetPixelType(UINT);
    SetComponentType(UINT);
    }
  else if( type == "32S")
    {
    SetPixelType(INT);
    SetComponentType(INT);
    }
  else if ( type == "FD" )
    {
    //64 bits Double image
    SetPixelType(DOUBLE);
    SetComponentType(DOUBLE);
    }
  else
    {
    itkExceptionMacro(<<"Unrecognized type:" << type);
    }

  // set values in case we don't find them
  this->SetNumberOfDimensions(2);
  m_Dimensions[0] = GdcmHeader->GetXSize();
  m_Dimensions[1] = GdcmHeader->GetYSize();
  //m_Dimensions[2] = GdcmHeader->GetZSize();
  m_Dimensions[2] = 0;

  m_Spacing[0] = GdcmHeader->GetXSpacing();
  m_Spacing[1] = GdcmHeader->GetYSpacing();
  // I have to figure out how to find the dimension (2 or 3) of the DICOM image:
  // m_Spacing[2] = GdcmHeader->GetZSpacing();
  m_Spacing[2] = 0;

  m_Origin.resize(3); //very important
  // Since SetNumberOfDimensions only reallocate for dim == 2
  m_Origin[0] = GdcmHeader->GetXOrigin();
  m_Origin[1] = GdcmHeader->GetYOrigin();
  m_Origin[2] = GdcmHeader->GetZOrigin();

  //For grayscale image :
  m_RescaleSlope = GdcmHeader->GetRescaleSlope();
  m_RescaleIntercept = GdcmHeader->GetRescaleIntercept();

}

void GDCMImageIO::ReadImageInformation()
{
  std::ifstream file;
  this->InternalReadImageInformation(file);
}

bool GDCMImageIO::CanWriteFile( const char* name )
{
  std::string filename = name;

  if(  filename == "" )
    {
    itkDebugMacro(<<"No filename specified.");
    return false;
    }

  bool extensionFound = false;
  std::string::size_type sprPos = filename.rfind(".dcm");
  if ((sprPos != std::string::npos)
      && (sprPos == filename.length() - 4))
    {
    extensionFound = true;
    }

  if( !extensionFound )
    {
    itkDebugMacro(<<"The filename extension is not recognized");
    return false;
    }

  return true;
}

void GDCMImageIO::WriteImageInformation()
{
}

void GDCMImageIO::Write(const void* buffer)
{
  std::ofstream file;
  if ( ! this->OpenGDCMFileForWriting(file, m_FileName.c_str()) )
    {
    return;
    }

  const unsigned long numberOfBytes = this->GetImageSizeInBytes();

  gdcmFile *GdcmFile = new gdcmFile( m_GdcmHeader );
  GdcmFile->SetImageData((void*)buffer, numberOfBytes );
  GdcmFile->WriteDcmExplVR(m_FileName);

  file.close();
}

void GDCMImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "RescaleSlope: " << m_RescaleSlope << "\n";
  os << indent << "RescaleIntercept: " << m_RescaleIntercept << "\n";
}

} // end namespace itk
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * 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 license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/cli/console.h>
#include <eventql/util/inspect.h>

namespace eventql {
namespace cli {

void Console::run() {
  iputs("hello world", 1);
}

} // namespace cli
} // namespace eventql

<commit_msg>readline example<commit_after>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * 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 license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/cli/console.h>
#include <eventql/util/inspect.h>

namespace eventql {
namespace cli {

extern "C" {
extern char *readline(char *prompt);
}

void Console::run() {
  char *p;

  while ((p = readline("evql> ")) != NULL) {
    puts(p);
    free(p);
  }
}

} // namespace cli
} // namespace eventql

<|endoftext|>


<commit_before>// Tests trace pc guard coverage collection.
//
// REQUIRES: has_sancovcc,stable-runtime
// XFAIL: tsan,darwin,powerpc64,s390x
//
// RUN: DIR=%t_workdir
// RUN: rm -rf $DIR
// RUN: mkdir -p $DIR
// RUN: cd $DIR
// RUN: %clangxx -O0 -fsanitize-coverage=trace-pc-guard %s -ldl -o %t
// RUN: %env_tool_opts=coverage=1 %t 2>&1 | FileCheck %s
// RUN: %sancovcc  -covered-functions -strip_path_prefix=TestCases/ *.sancov %t 2>&1 | \
// RUN:   FileCheck --check-prefix=CHECK-SANCOV %s
// RUN: %env_tool_opts=coverage=0 %t 2>&1 | FileCheck --check-prefix=CHECK-NOCOV %s
// RUN: rm -rf $DIR
// Make some room to stabilize line numbers
//
//
//
#include <stdio.h>

int foo() {
  fprintf(stderr, "foo\n");
  return 1;
}

int main() {
  fprintf(stderr, "main\n");
  foo();
  foo();
}

// CHECK: main
// CHECK-NEXT: foo
// CHECK-NEXT: foo
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard.{{.*}}.sancov 2 PCs written
//
// CHECK-SANCOV: sanitizer_coverage_trace_pc_guard.cc:22 foo
// CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard.cc:27 main
//
// CHECK-NOCOV-NOT: SanitizerCoverage
<commit_msg>Remove XFAIL from the sanitizer guard test for darwin<commit_after>// Tests trace pc guard coverage collection.
//
// REQUIRES: has_sancovcc,stable-runtime
// UNSUPPORTED: i386-darwin
// XFAIL: tsan,powerpc64,s390x
//
// RUN: DIR=%t_workdir
// RUN: rm -rf $DIR
// RUN: mkdir -p $DIR
// RUN: cd $DIR
// RUN: %clangxx -O0 -fsanitize-coverage=trace-pc-guard %s -ldl -o %t
// RUN: %env_tool_opts=coverage=1 %t 2>&1 | FileCheck %s
// RUN: %sancovcc  -covered-functions -strip_path_prefix=TestCases/ *.sancov %t 2>&1 | \
// RUN:   FileCheck --check-prefix=CHECK-SANCOV %s
// RUN: %env_tool_opts=coverage=0 %t 2>&1 | FileCheck --check-prefix=CHECK-NOCOV %s
// RUN: rm -rf $DIR
// Make some room to stabilize line numbers
//
//
//
#include <stdio.h>

int foo() {
  fprintf(stderr, "foo\n");
  return 1;
}

int main() {
  fprintf(stderr, "main\n");
  foo();
  foo();
}

// CHECK: main
// CHECK-NEXT: foo
// CHECK-NEXT: foo
// CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard.{{.*}}.sancov 2 PCs written
//
// CHECK-SANCOV: sanitizer_coverage_trace_pc_guard.cc:23 foo
// CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard.cc:28 main
//
// CHECK-NOCOV-NOT: SanitizerCoverage
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013-2015, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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 Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include <algorithm> // std::generate
#include <iostream>
#include <vector>

#include "nupic/algorithms/Anomaly.hpp"
#include "nupic/algorithms/Cells4.hpp"  //TODO use TM instead
#include "nupic/algorithms/SpatialPooler.hpp"
#include "nupic/encoders/ScalarEncoder.hpp"

#include "nupic/os/Timer.hpp"
#include "nupic/utils/VectorHelpers.hpp"
#include "nupic/utils/Random.hpp"

namespace examples {

using namespace std;
using namespace nupic;
using namespace nupic::utils;
using nupic::ScalarEncoder;
using nupic::algorithms::spatial_pooler::SpatialPooler;
using nupic::algorithms::Cells4::Cells4;
using nupic::algorithms::anomaly::Anomaly;
using nupic::algorithms::anomaly::AnomalyMode;

// work-load
void run() {
  const UInt COLS = 2048; // number of columns in SP, TP
  const UInt DIM_INPUT = 10000;
  const UInt CELLS = 10; // cells per column in TP
  const UInt EPOCHS = 1000; // number of iterations (calls to SP/TP compute() )
  std::cout << "starting test. DIM_INPUT=" << DIM_INPUT
  		<< ", DIM=" << COLS << ", CELLS=" << CELLS << std::endl;
  std::cout << "EPOCHS = " << EPOCHS << std::endl;

  // initialize SP, TP, Anomaly, AnomalyLikelihood
  ScalarEncoder enc(133, -100.0, 100.0, DIM_INPUT, 0.0, 0.0, false);
  SpatialPooler sp(vector<UInt>{DIM_INPUT}, vector<UInt>{COLS});
  Cells4 tp(COLS, CELLS, 12, 8, 15, 5, .5f, .8f, 1.0f, .1f, .1f, 0.0f,
            false, 42, true, false);
  Anomaly an(5, AnomalyMode::LIKELIHOOD);

  // data for processing input
  vector<UInt> input(DIM_INPUT);
  vector<UInt> outSP(COLS); // active array, output of SP/TP
  vector<UInt> outTP(tp.nCells());
  vector<Real> rIn(COLS); // input for TP (must be Reals)
  vector<Real> rOut(tp.nCells());
  Real res = 0.0; //for anomaly:
  vector<UInt> prevPred_(outSP.size());
  Random rnd;

  // Start a stopwatch timer
  printf("starting:  %d iterations.", EPOCHS);
  Timer stopwatch(true);

  //run
  for (UInt e = 0; e < EPOCHS; e++) {
    //Input
//    generate(input.begin(), input.end(), [&] () { return rnd.getUInt32(2); });
    const Real r = rnd.getUInt32(100) - rnd.getUInt32(100)*rnd.getReal64(); //rnd from range -100..100

    //Encode
    enc.encodeIntoArray(r, input.data());

    //SP
    fill(outSP.begin(), outSP.end(), 0);
    sp.compute(input.data(), true, outSP.data());
    sp.stripUnlearnedColumns(outSP.data());

    //TP
    rIn = VectorHelpers::castVectorType<UInt, Real>(outSP);
    tp.compute(rIn.data(), rOut.data(), true, true);
    outTP = VectorHelpers::castVectorType<Real, UInt>(rOut);

    //Anomaly
    res = an.compute(outSP /*active*/, prevPred_ /*prev predicted*/);
    prevPred_ = outTP; //to be used as predicted T-1
    cout << res << " ";

    // print
    if (e == EPOCHS - 1) {
      cout << "Epoch = " << e << endl;
      VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(outSP), ",", "SP= ");
      VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(VectorHelpers::cellsToColumns(outTP, CELLS)), ",", "TP= ");
      NTA_CHECK(outSP[69] == 0) << "A value in SP computed incorrectly";
      NTA_CHECK(outTP[42] == 0) << "Incorrect value in TP";
    }
  }

  stopwatch.stop();
  const size_t timeTotal = stopwatch.getElapsed();
  cout << "Total elapsed time = " << timeTotal << " seconds" << endl;
#ifdef NDEBUG
  const size_t CI_avg_time = 45; //sec
  NTA_CHECK(timeTotal <= CI_avg_time) << //we'll see how stable the time result in CI is, if usable
	  "HelloSPTP test slower than expected! (" << timeTotal << ",should be "<< CI_avg_time;
#endif
}
} //-ns
<commit_msg>Hotgym: silence output<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013-2015, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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 Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include <algorithm> // std::generate
#include <iostream>
#include <vector>

#include "nupic/algorithms/Anomaly.hpp"
#include "nupic/algorithms/Cells4.hpp"  //TODO use TM instead
#include "nupic/algorithms/SpatialPooler.hpp"
#include "nupic/encoders/ScalarEncoder.hpp"

#include "nupic/os/Timer.hpp"
#include "nupic/utils/VectorHelpers.hpp"
#include "nupic/utils/Random.hpp"

namespace examples {

using namespace std;
using namespace nupic;
using namespace nupic::utils;
using nupic::ScalarEncoder;
using nupic::algorithms::spatial_pooler::SpatialPooler;
using nupic::algorithms::Cells4::Cells4;
using nupic::algorithms::anomaly::Anomaly;
using nupic::algorithms::anomaly::AnomalyMode;

// work-load
void run() {
  const UInt COLS = 2048; // number of columns in SP, TP
  const UInt DIM_INPUT = 10000;
  const UInt CELLS = 10; // cells per column in TP
  const UInt EPOCHS = 1000; // number of iterations (calls to SP/TP compute() )
  std::cout << "starting test. DIM_INPUT=" << DIM_INPUT
  		<< ", DIM=" << COLS << ", CELLS=" << CELLS << std::endl;
  std::cout << "EPOCHS = " << EPOCHS << std::endl;

  // initialize SP, TP, Anomaly, AnomalyLikelihood
  ScalarEncoder enc(133, -100.0, 100.0, DIM_INPUT, 0.0, 0.0, false);
  SpatialPooler sp(vector<UInt>{DIM_INPUT}, vector<UInt>{COLS});
  Cells4 tp(COLS, CELLS, 12, 8, 15, 5, .5f, .8f, 1.0f, .1f, .1f, 0.0f,
            false, 42, true, false);
  Anomaly an(5, AnomalyMode::LIKELIHOOD);

  // data for processing input
  vector<UInt> input(DIM_INPUT);
  vector<UInt> outSP(COLS); // active array, output of SP/TP
  vector<UInt> outTP(tp.nCells());
  vector<Real> rIn(COLS); // input for TP (must be Reals)
  vector<Real> rOut(tp.nCells());
  Real res = 0.0; //for anomaly:
  vector<UInt> prevPred_(outSP.size());
  Random rnd;

  // Start a stopwatch timer
  printf("starting:  %d iterations.", EPOCHS);
  Timer stopwatch(true);

  //run
  for (UInt e = 0; e < EPOCHS; e++) {
    //Input
//    generate(input.begin(), input.end(), [&] () { return rnd.getUInt32(2); });
    const Real r = rnd.getUInt32(100) - rnd.getUInt32(100)*rnd.getReal64(); //rnd from range -100..100

    //Encode
    enc.encodeIntoArray(r, input.data());

    //SP
    fill(outSP.begin(), outSP.end(), 0);
    sp.compute(input.data(), true, outSP.data());
    sp.stripUnlearnedColumns(outSP.data());

    //TP
    rIn = VectorHelpers::castVectorType<UInt, Real>(outSP);
    tp.compute(rIn.data(), rOut.data(), true, true);
    outTP = VectorHelpers::castVectorType<Real, UInt>(rOut);

    //Anomaly
    res = an.compute(outSP /*active*/, prevPred_ /*prev predicted*/);
    prevPred_ = outTP; //to be used as predicted T-1

    // print
    if (e == EPOCHS - 1) {
      cout << "Epoch = " << e << endl;
      cout << "Anomaly = " << res << endl;
      VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(outSP), ",", "SP= ");
      VectorHelpers::print_vector(VectorHelpers::binaryToSparse<UInt>(VectorHelpers::cellsToColumns(outTP, CELLS)), ",", "TP= ");
      NTA_CHECK(outSP[69] == 0) << "A value in SP computed incorrectly";
      NTA_CHECK(outTP[42] == 0) << "Incorrect value in TP";
    }
  }

  stopwatch.stop();
  const size_t timeTotal = stopwatch.getElapsed();
  cout << "Total elapsed time = " << timeTotal << " seconds" << endl;
#ifdef NDEBUG
  const size_t CI_avg_time = 45; //sec
  NTA_CHECK(timeTotal <= CI_avg_time) << //we'll see how stable the time result in CI is, if usable
	  "HelloSPTP test slower than expected! (" << timeTotal << ",should be "<< CI_avg_time;
#endif
}
} //-ns
<|endoftext|>


<commit_before>//  Copyright (c) 2014, Kyle Wilson
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation
//  and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
//  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//  The views and conclusions contained in the software and documentation are those
//  of the authors and should not be interpreted as representing official policies,
//  either expressed or implied, of the FreeBSD Project.

// Copyright (c) 2014 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/multiview/translation_averaging_common.hpp"
#include "openMVG/multiview/translation_averaging_solver.hpp"

#include "ceres/ceres.h"

#include <vector>
#include <set>
#include <map>

using ceres::AutoDiffCostFunction;
using ceres::CostFunction;
using ceres::Problem;
using ceres::Solver;
using ceres::Solve;
using ceres::HuberLoss;

struct ChordFunctor {
  ChordFunctor(const double *direction, double weight)
    : u_(direction), w_(weight){}

  const double *u_; // local estimate of the translation direction
  const double w_;  // weight

  // Residual computation (3x1: a residual along each unit axis)
  template <typename T>
  bool operator()(const T* const x0, const T* const x1, T* residual) const
  {
    // compute ||x1 - x0||_2
    T norm = sqrt((x1[0]-x0[0])*(x1[0]-x0[0]) +
      (x1[1]-x0[1])*(x1[1]-x0[1]) +
      (x1[2]-x0[2])*(x1[2]-x0[2]));
    residual[0] = w_*((x1[0]-x0[0]) / norm - T(u_[0]));
    residual[1] = w_*((x1[1]-x0[1]) / norm - T(u_[1]));
    residual[2] = w_*((x1[2]-x0[2]) / norm - T(u_[2]));
    return true;
  }
};

void reindex_problem(int* edges, int num_edges, std::vector<int> &reindex_lookup);

bool solve_translations_problem(
  const int* edges,
  const double* poses,
  const double* weights,
  int num_edges,
  double loss_width,
  double* X,
  double function_tolerance,
  double parameter_tolerance,
  int max_iterations)
{
  // seed the random number generator
  std::srand( std::time( NULL ) );

  // re index the edges to be a sequential set
  std::vector<int> _edges(edges, edges+2*num_edges);
  std::vector<int> reindex_lookup;
  reindex_problem(&_edges[0], num_edges, reindex_lookup);
  const int num_nodes = reindex_lookup.size();

  // Init with a random guess solution
  double *x = new double[3*num_nodes];
  for (int i=0; i<3*num_nodes; ++i)
    x[i] = (double)rand() / RAND_MAX;

  // add the parameter blocks (a 3-vector for each node)
  Problem problem;
  for (int i=0; i<num_nodes; ++i)
    problem.AddParameterBlock(x+3*i, 3);

  // set the residual function (chordal distance for each edge)
  for (int i=0; i<num_edges; ++i) {
    CostFunction* cost_function =
      new AutoDiffCostFunction<ChordFunctor, 3, 3, 3>(
      new ChordFunctor(poses+3*i, weights[i]));

    if (loss_width == 0.0) {
      // No robust loss function
      problem.AddResidualBlock(cost_function, NULL, x+3*_edges[2*i+0], x+3*_edges[2*i+1]);
    } else {
      problem.AddResidualBlock(cost_function, new ceres::HuberLoss(loss_width), x+3*_edges[2*i+0], x+3*_edges[2*i+1]);
    }
  }

  // Fix first camera in {0,0,0}: fix the translation ambiguity
  x[0] = x[1] = x[2] = 0.0;
  problem.SetParameterBlockConstant(x);

  // solve
  Solver::Options options;
#ifdef USE_OPENMP
  options.num_threads = omp_get_max_threads();
  options.num_linear_solver_threads = omp_get_max_threads();
#endif // USE_OPENMP
  //options.minimizer_progress_to_stdout = true;
  options.max_num_iterations = max_iterations;
  options.function_tolerance = function_tolerance;
  options.parameter_tolerance = parameter_tolerance;
  options.linear_solver_type = ceres::ITERATIVE_SCHUR;
  options.preconditioner_type = ceres::SCHUR_JACOBI;

  Solver::Summary summary;
  Solve(options, &problem, &summary);

  std::cout << summary.FullReport() << "\n";

  if (summary.IsSolutionUsable())
  {
    // undo the re indexing
    for (int i=0; i<num_nodes; ++i) {
      const int j = reindex_lookup[i];
      X[3*j+0] = x[3*i+0];
      X[3*j+1] = x[3*i+1];
      X[3*j+2] = x[3*i+2];
    }
  }
  return summary.IsSolutionUsable();
}

void
reindex_problem(int* edges, int num_edges, std::vector<int> &reindex_lookup)
{
  // get the unique set of nodes
  std::set<int> nodes;
  for (int i=0; i<2*num_edges; ++i)
    nodes.insert(edges[i]);

  reindex_lookup.clear();
  reindex_lookup.reserve(nodes.size());

  std::map<int, int> reindexing_key;
  // iterator through them and assign a new Id to each vertex
  std::set<int>::const_iterator it;
  int n=0;
  for (it = nodes.begin(); it != nodes.end(); ++it, ++n) {
    reindex_lookup.push_back(*it);
    reindexing_key[*it] = n;
  }

  // now renumber the edges
  for (int i=0; i<2*num_edges; ++i)
    edges[i]  = reindexing_key[edges[i]];
}
<commit_msg>Fix a memory leak.<commit_after>//  Copyright (c) 2014, Kyle Wilson
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation
//  and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
//  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//  The views and conclusions contained in the software and documentation are those
//  of the authors and should not be interpreted as representing official policies,
//  either expressed or implied, of the FreeBSD Project.

// Copyright (c) 2014 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/multiview/translation_averaging_common.hpp"
#include "openMVG/multiview/translation_averaging_solver.hpp"

#include "ceres/ceres.h"

#include <vector>
#include <set>
#include <map>

using ceres::AutoDiffCostFunction;
using ceres::CostFunction;
using ceres::Problem;
using ceres::Solver;
using ceres::Solve;
using ceres::HuberLoss;

struct ChordFunctor {
  ChordFunctor(const double *direction, double weight)
    : u_(direction), w_(weight){}

  const double *u_; // local estimate of the translation direction
  const double w_;  // weight

  // Residual computation (3x1: a residual along each unit axis)
  template <typename T>
  bool operator()(const T* const x0, const T* const x1, T* residual) const
  {
    // compute ||x1 - x0||_2
    T norm = sqrt((x1[0]-x0[0])*(x1[0]-x0[0]) +
      (x1[1]-x0[1])*(x1[1]-x0[1]) +
      (x1[2]-x0[2])*(x1[2]-x0[2]));
    residual[0] = w_*((x1[0]-x0[0]) / norm - T(u_[0]));
    residual[1] = w_*((x1[1]-x0[1]) / norm - T(u_[1]));
    residual[2] = w_*((x1[2]-x0[2]) / norm - T(u_[2]));
    return true;
  }
};

void reindex_problem(int* edges, int num_edges, std::vector<int> &reindex_lookup);

bool solve_translations_problem(
  const int* edges,
  const double* poses,
  const double* weights,
  int num_edges,
  double loss_width,
  double* X,
  double function_tolerance,
  double parameter_tolerance,
  int max_iterations)
{
  // seed the random number generator
  std::srand( std::time( NULL ) );

  // re index the edges to be a sequential set
  std::vector<int> _edges(edges, edges+2*num_edges);
  std::vector<int> reindex_lookup;
  reindex_problem(&_edges[0], num_edges, reindex_lookup);
  const int num_nodes = reindex_lookup.size();

  // Init with a random guess solution
  double *x = new double[3*num_nodes];
  for (int i=0; i<3*num_nodes; ++i)
    x[i] = (double)rand() / RAND_MAX;

  // add the parameter blocks (a 3-vector for each node)
  Problem problem;
  for (int i=0; i<num_nodes; ++i)
    problem.AddParameterBlock(x+3*i, 3);

  // set the residual function (chordal distance for each edge)
  for (int i=0; i<num_edges; ++i) {
    CostFunction* cost_function =
      new AutoDiffCostFunction<ChordFunctor, 3, 3, 3>(
      new ChordFunctor(poses+3*i, weights[i]));

    if (loss_width == 0.0) {
      // No robust loss function
      problem.AddResidualBlock(cost_function, NULL, x+3*_edges[2*i+0], x+3*_edges[2*i+1]);
    } else {
      problem.AddResidualBlock(cost_function, new ceres::HuberLoss(loss_width), x+3*_edges[2*i+0], x+3*_edges[2*i+1]);
    }
  }

  // Fix first camera in {0,0,0}: fix the translation ambiguity
  x[0] = x[1] = x[2] = 0.0;
  problem.SetParameterBlockConstant(x);

  // solve
  Solver::Options options;
#ifdef USE_OPENMP
  options.num_threads = omp_get_max_threads();
  options.num_linear_solver_threads = omp_get_max_threads();
#endif // USE_OPENMP
  //options.minimizer_progress_to_stdout = true;
  options.max_num_iterations = max_iterations;
  options.function_tolerance = function_tolerance;
  options.parameter_tolerance = parameter_tolerance;
  options.linear_solver_type = ceres::ITERATIVE_SCHUR;
  options.preconditioner_type = ceres::SCHUR_JACOBI;

  Solver::Summary summary;
  Solve(options, &problem, &summary);

  std::cout << summary.FullReport() << "\n";

  if (summary.IsSolutionUsable())
  {
    // undo the re indexing
    for (int i=0; i<num_nodes; ++i) {
      const int j = reindex_lookup[i];
      X[3*j+0] = x[3*i+0];
      X[3*j+1] = x[3*i+1];
      X[3*j+2] = x[3*i+2];
    }
  }
  delete [] x;
  return summary.IsSolutionUsable();
}

void
reindex_problem(int* edges, int num_edges, std::vector<int> &reindex_lookup)
{
  // get the unique set of nodes
  std::set<int> nodes;
  for (int i=0; i<2*num_edges; ++i)
    nodes.insert(edges[i]);

  reindex_lookup.clear();
  reindex_lookup.reserve(nodes.size());

  std::map<int, int> reindexing_key;
  // iterator through them and assign a new Id to each vertex
  std::set<int>::const_iterator it;
  int n=0;
  for (it = nodes.begin(); it != nodes.end(); ++it, ++n) {
    reindex_lookup.push_back(*it);
    reindexing_key[*it] = n;
  }

  // now renumber the edges
  for (int i=0; i<2*num_edges; ++i)
    edges[i]  = reindexing_key[edges[i]];
}
<|endoftext|>


<commit_before>#include "helpers.h"

namespace node_leveldb {

leveldb::Options JsToOptions(Handle<Value> val) {
  HandleScope scope;
  Local<Object> obj = Object::Cast(*val);
  leveldb::Options options;
  if (obj->Has(String::New("create_if_missing"))) {
    options.create_if_missing = obj->Get(String::New("create_if_missing"))->BooleanValue();
  }
  if (obj->Has(String::New("error_if_exists"))) {
    options.error_if_exists = obj->Get(String::New("error_if_exists"))->BooleanValue();
  }
  if (obj->Has(String::New("paranoid_checks"))) {
    options.paranoid_checks = obj->Get(String::New("paranoid_checks"))->BooleanValue();
  }
  if (obj->Has(String::New("write_buffer_size"))) {
    options.write_buffer_size = obj->Get(String::New("write_buffer_size"))->Int32Value();
  }
  if (obj->Has(String::New("max_open_files"))) {
    options.max_open_files = obj->Get(String::New("max_open_files"))->Int32Value();
  }
  if (obj->Has(String::New("block_size"))) {
    options.block_size = obj->Get(String::New("block_size"))->Int32Value();
  }
  if (obj->Has(String::New("block_restart_interval"))) {
    options.block_restart_interval = obj->Get(String::New("block_restart_interval"))->Int32Value();
  }
  return options;
}

leveldb::ReadOptions JsToReadOptions(Handle<Value> val) {
  HandleScope scope;
  leveldb::ReadOptions options;
  Local<Object> obj = Object::Cast(*val);
  if (obj->Has(String::New("verify_checksums"))) {
    options.verify_checksums = obj->Get(String::New("verify_checksums"))->BooleanValue();
  }
  if (obj->Has(String::New("fill_cache"))) {
    options.fill_cache = obj->Get(String::New("fill_cache"))->BooleanValue();
  }
  return options;
}

leveldb::WriteOptions JsToWriteOptions(Handle<Value> val) {
  HandleScope scope;
  leveldb::WriteOptions options;
  Local<Object> obj = Object::Cast(*val);
  if (obj->Has(String::New("sync"))) {
    options.sync = obj->Get(String::New("sync"))->BooleanValue();
  }
  return options;
}

leveldb::Slice JsToSlice(Handle<Value> val, std::vector<std::string> *strings) {
  HandleScope scope;
  if (val->IsString() && strings != NULL) {
    std::string str(*String::Utf8Value(val));
    strings->push_back(str);
    return leveldb::Slice(str.data(), str.length());
  }
  else if (Buffer::HasInstance(val)) {
    Local<Object> obj = Object::Cast(*val);
    return leveldb::Slice(BufferData(obj), BufferLength(obj));
  }
  else {
    return leveldb::Slice();
  }
}

Handle<Value> processStatus(leveldb::Status status) {
  if (status.ok()) return String::New(status.ToString().c_str());
  return ThrowException(Exception::Error(String::New(status.ToString().c_str())));
}

Local<Object> Bufferize(std::string value) {
    int length = value.length();
    Buffer *slowBuffer = Buffer::New(length);
    memcpy(BufferData(slowBuffer), value.c_str(), length);
    Local<Function> bufferConstructor = Local<Function>::Cast(Context::GetCurrent()->Global()->Get(String::New("Buffer")));
    Handle<Value> constructorArgs[3] = { slowBuffer->handle_, Integer::New(length), Integer::New(0) };

    return bufferConstructor->NewInstance(3, constructorArgs);
}

char* BufferData(Buffer *b) {
  return Buffer::Data(b->handle_);
}

size_t BufferLength(Buffer *b) {
  return Buffer::Length(b->handle_);
}

char* BufferData(Handle<Object> buf_obj) {
  return Buffer::Data(buf_obj);
}

size_t BufferLength(Handle<Object> buf_obj) {
  return Buffer::Length(buf_obj);
}

} // node_leveldb
<commit_msg>Fixed segfault where global was gc'ed during call to String::New().<commit_after>#include "helpers.h"

namespace node_leveldb {

leveldb::Options JsToOptions(Handle<Value> val) {
  HandleScope scope;
  Local<Object> obj = Object::Cast(*val);
  leveldb::Options options;
  if (obj->Has(String::New("create_if_missing"))) {
    options.create_if_missing = obj->Get(String::New("create_if_missing"))->BooleanValue();
  }
  if (obj->Has(String::New("error_if_exists"))) {
    options.error_if_exists = obj->Get(String::New("error_if_exists"))->BooleanValue();
  }
  if (obj->Has(String::New("paranoid_checks"))) {
    options.paranoid_checks = obj->Get(String::New("paranoid_checks"))->BooleanValue();
  }
  if (obj->Has(String::New("write_buffer_size"))) {
    options.write_buffer_size = obj->Get(String::New("write_buffer_size"))->Int32Value();
  }
  if (obj->Has(String::New("max_open_files"))) {
    options.max_open_files = obj->Get(String::New("max_open_files"))->Int32Value();
  }
  if (obj->Has(String::New("block_size"))) {
    options.block_size = obj->Get(String::New("block_size"))->Int32Value();
  }
  if (obj->Has(String::New("block_restart_interval"))) {
    options.block_restart_interval = obj->Get(String::New("block_restart_interval"))->Int32Value();
  }
  return options;
}

leveldb::ReadOptions JsToReadOptions(Handle<Value> val) {
  HandleScope scope;
  leveldb::ReadOptions options;
  Local<Object> obj = Object::Cast(*val);
  if (obj->Has(String::New("verify_checksums"))) {
    options.verify_checksums = obj->Get(String::New("verify_checksums"))->BooleanValue();
  }
  if (obj->Has(String::New("fill_cache"))) {
    options.fill_cache = obj->Get(String::New("fill_cache"))->BooleanValue();
  }
  return options;
}

leveldb::WriteOptions JsToWriteOptions(Handle<Value> val) {
  HandleScope scope;
  leveldb::WriteOptions options;
  Local<Object> obj = Object::Cast(*val);
  if (obj->Has(String::New("sync"))) {
    options.sync = obj->Get(String::New("sync"))->BooleanValue();
  }
  return options;
}

leveldb::Slice JsToSlice(Handle<Value> val, std::vector<std::string> *strings) {
  HandleScope scope;
  if (val->IsString() && strings != NULL) {
    std::string str(*String::Utf8Value(val));
    strings->push_back(str);
    return leveldb::Slice(str.data(), str.length());
  }
  else if (Buffer::HasInstance(val)) {
    Local<Object> obj = Object::Cast(*val);
    return leveldb::Slice(BufferData(obj), BufferLength(obj));
  }
  else {
    return leveldb::Slice();
  }
}

Handle<Value> processStatus(leveldb::Status status) {
  if (status.ok()) return String::New(status.ToString().c_str());
  return ThrowException(Exception::Error(String::New(status.ToString().c_str())));
}

Local<Object> Bufferize(std::string value) {
  HandleScope scope;

  int length = value.length();
  Buffer *slowBuffer = Buffer::New(length);
  memcpy(Buffer::Data(slowBuffer), value.c_str(), length);

  Local<Object> global = v8::Context::GetCurrent()->Global();
  Local<Value> bv = global->Get(String::NewSymbol("Buffer"));
  assert(bv->IsFunction());
  Local<Function> b = Local<Function>::Cast(bv);
  Handle<Value> argv[3] = { slowBuffer->handle_, Integer::New(length), Integer::New(0) };
  Local<Object> instance = b->NewInstance(3, argv);

  return scope.Close(instance);
}

char* BufferData(Buffer *b) {
  return Buffer::Data(b->handle_);
}

size_t BufferLength(Buffer *b) {
  return Buffer::Length(b->handle_);
}

char* BufferData(Handle<Object> buf_obj) {
  return Buffer::Data(buf_obj);
}

size_t BufferLength(Handle<Object> buf_obj) {
  return Buffer::Length(buf_obj);
}

} // node_leveldb
<|endoftext|>


<commit_before>/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/

/* rev for v2.3 by JGG */

#include <globals.h>
#include <stdio.h>
#include <assert.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rtdefs.h"

extern "C" {
extern int get_last_input_index(void);       /* defined in rtinput.c */
}

#define INCHANS_DISCREPANCY_WARNING "\
WARNING: The bus config for this instrument specifies %d input channels, \n\
but its input source has %d channels.\n"

/* ----------------------------------------------------------- rtsetinput --- */
/* Instruments call this to set their input file pointer (like setnote in cmix).
   Returns 0 if ok, -1 if error.
*/
int
rtsetinput(float start_time, Instrument *inst)
{
   if (inst->bus_config->auxin_count > 0) {
      if (start_time != 0.0) {
         fprintf(stderr, "inskip must be 0 when reading from an aux bus.\n");
         exit(1);
      }
   }

   if (inst->bus_config->in_count > 0) {
      int src_chans;
      int index = get_last_input_index();

      if (index < 0 || inputFileTable[index].fd < 1) {
         fprintf(stderr, "No input source open for this instrument!\n");
         return -1;
      }

      /* File or audio device was opened in rtinput(). Here we store the
         index into the inputFileTable for the file or device.
      */
      inst->fdIndex = index;

      /* Fill in relevant data members of instrument class. */
      inst->inputsr = inputFileTable[index].srate;

      src_chans = inputFileTable[index].chans;

      if (inst->inputchans != src_chans) {
         fprintf(stderr, INCHANS_DISCREPANCY_WARNING, inst->inputchans,
                                                                  src_chans);
      }

      if (inputFileTable[index].is_audio_dev) {
         if (start_time != 0.0) {
            fprintf(stderr, "inskip must be 0 when reading from the real-time "
                            "audio device.\n");
            exit(1);
         }
      }
      else {
         int datum_size, inskip;

         inst->sfile_on = 1;

         inskip = (int) (start_time * inst->inputsr);

         /* sndlib always uses 2 for datum size, even if the actual size is
            different. However, we don't use sndlib to read float files, so
            their datum size is the real thing.
         */
         if (inputFileTable[index].is_float_format)
            datum_size = sizeof(float);
         else
            datum_size = 2;

         /* Offset is measured from the header size determined in rtinput(). */
         inst->fileOffset = inputFileTable[index].data_location
                            + (inskip * inst->inputchans * datum_size);

         if (start_time >= inputFileTable[index].dur)
            fprintf(stderr, "WARNING: Attempt to read past end of input "
                            "file: %s\n", inputFileTable[index].filename);
      }

      /* Increment the reference count for this file. */
      inputFileTable[index].refcount++;
   }

   return 0;
}

<commit_msg>Catch invalid input to rtsetinput().<commit_after>/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/

/* rev for v2.3 by JGG */

#include <globals.h>
#include <stdio.h>
#include <assert.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rtdefs.h"

extern "C" {
extern int get_last_input_index(void);       /* defined in rtinput.c */
}

#define INCHANS_DISCREPANCY_WARNING "\
WARNING: The bus config for this instrument specifies %d input channels, \n\
but its input source has %d channels.\n"

/* ----------------------------------------------------------- rtsetinput --- */
/* Instruments call this to set their input file pointer (like setnote in cmix).
   Returns 0 if ok, -1 if error.
*/
int
rtsetinput(float start_time, Instrument *inst)
{
   int auxin_count = inst->bus_config->auxin_count;
   int in_count = inst->bus_config->in_count;

   if (auxin_count == 0 && in_count == 0) {
      fprintf(stderr, "This instrument requires input from either an in bus"
                      "or an aux bus.\n Change this with bus_config().\n");
      exit(1);
   }

   if (auxin_count > 0) {
      if (start_time != 0.0) {
         fprintf(stderr, "inskip must be 0 when reading from an aux bus.\n");
         exit(1);
      }
   }

   if (in_count > 0) {
      int src_chans;
      int index = get_last_input_index();

      if (index < 0 || inputFileTable[index].fd < 1) {
         fprintf(stderr, "No input source open for this instrument!\n");
         return -1;
      }

      /* File or audio device was opened in rtinput(). Here we store the
         index into the inputFileTable for the file or device.
      */
      inst->fdIndex = index;

      /* Fill in relevant data members of instrument class. */
      inst->inputsr = inputFileTable[index].srate;

      src_chans = inputFileTable[index].chans;

      if (inst->inputchans != src_chans) {
         fprintf(stderr, INCHANS_DISCREPANCY_WARNING, inst->inputchans,
                                                                  src_chans);
      }

      if (inputFileTable[index].is_audio_dev) {
         if (start_time != 0.0) {
            fprintf(stderr, "inskip must be 0 when reading from the real-time "
                            "audio device.\n");
            exit(1);
         }
      }
      else {
         int datum_size, inskip;

         inst->sfile_on = 1;

         inskip = (int) (start_time * inst->inputsr);

         /* sndlib always uses 2 for datum size, even if the actual size is
            different. However, we don't use sndlib to read float files, so
            their datum size is the real thing.
         */
         if (inputFileTable[index].is_float_format)
            datum_size = sizeof(float);
         else
            datum_size = 2;

         /* Offset is measured from the header size determined in rtinput(). */
         inst->fileOffset = inputFileTable[index].data_location
                            + (inskip * inst->inputchans * datum_size);

         if (start_time >= inputFileTable[index].dur)
            fprintf(stderr, "WARNING: Attempt to read past end of input "
                            "file: %s\n", inputFileTable[index].filename);
      }

      /* Increment the reference count for this file. */
      inputFileTable[index].refcount++;
   }

   return 0;
}

<|endoftext|>


<commit_before>/*
 * This is code from the Simple Pseudo-random Number Generators
 * Contact : http://craig.mcqueen.id.au
 * Copyright : 2010 Craig McQueen
 *
 * Available on GitHub https://github.com/cmcqueen/simplerandom
 */

#include "simplerandom.hpp"
#include <stddef.h>

#ifndef UINT32_C
#define UINT32_C(val) val##ui32
#endif

void simplerandom_cong_seed(SimpleRandomCong_t * p_cong, uint32_t seed);
void simplerandom_cong_mix(SimpleRandomCong_t * p_cong, const uint32_t * p_data, size_t num_data);
uint32_t simplerandom_cong_next(SimpleRandomCong_t * p_cong);

SimpleRandom::SimpleRandom(uint32_t seed)
{
    this->internal = new SimpleRandomCong_t();
}

SimpleRandom::~SimpleRandom()
{
    delete this->internal;
}

uint32_t SimpleRandom::next()
{
    return simplerandom_cong_next(this->internal);
}

uint32_t SimpleRandom::maximum()
{
    return 2 >> 32 - 1;
}

size_t simplerandom_cong_num_seeds(const SimpleRandomCong_t * p_cong)
{
    (const void *)p_cong;   /* We only use this parameter for type checking. */

    return 1u;
}

size_t simplerandom_cong_seed_array(SimpleRandomCong_t * p_cong, const uint32_t * p_seeds, size_t num_seeds, bool mix_extras)
{
    uint32_t    seed = 0;
    size_t      num_seeds_used = 0;

    if (num_seeds >= 1u && p_seeds != NULL)
    {
        seed = p_seeds[0];
        num_seeds_used = 1u;
    }
    simplerandom_cong_seed(p_cong, seed);

    if (mix_extras && p_seeds != NULL)
    {
        simplerandom_cong_mix(p_cong, p_seeds + num_seeds_used, num_seeds - num_seeds_used);
        num_seeds_used = num_seeds;
    }
    return num_seeds_used;
}

void simplerandom_cong_seed(SimpleRandomCong_t * p_cong, uint32_t seed)
{
    p_cong->cong = seed;
    /* No sanitize is needed because for Cong, all state values are valid. */
}

void simplerandom_cong_sanitize(SimpleRandomCong_t * p_cong)
{
    /* All state values are valid for Cong. No sanitizing needed. */
    (const void *) p_cong;
}

uint32_t simplerandom_cong_next(SimpleRandomCong_t * p_cong)
{
    uint32_t    cong;

    cong = UINT32_C(69069) * p_cong->cong + 12345u;
    p_cong->cong = cong;

    return cong;
}

void simplerandom_cong_mix(SimpleRandomCong_t * p_cong, const uint32_t * p_data, size_t num_data)
{
    if (p_data != NULL)
    {
        while (num_data)
        {
            --num_data;
            p_cong->cong ^= *p_data++;
            simplerandom_cong_sanitize(p_cong);
            simplerandom_cong_next(p_cong);
        }
    }
}
<commit_msg>Fixing the simplerandom::maximum<commit_after>/*
 * This is code from the Simple Pseudo-random Number Generators
 * Contact : http://craig.mcqueen.id.au
 * Copyright : 2010 Craig McQueen
 *
 * Available on GitHub https://github.com/cmcqueen/simplerandom
 */

#include "simplerandom.hpp"
#include <stddef.h>

#ifndef UINT32_C
#define UINT32_C(val) val##ui32
#endif

void simplerandom_cong_seed(SimpleRandomCong_t * p_cong, uint32_t seed);
void simplerandom_cong_mix(SimpleRandomCong_t * p_cong, const uint32_t * p_data, size_t num_data);
uint32_t simplerandom_cong_next(SimpleRandomCong_t * p_cong);

SimpleRandom::SimpleRandom(uint32_t seed)
{
    this->internal = new SimpleRandomCong_t();
}

SimpleRandom::~SimpleRandom()
{
    delete this->internal;
}

uint32_t SimpleRandom::next()
{
    return simplerandom_cong_next(this->internal);
}

uint32_t SimpleRandom::maximum()
{
    return 4294967295;
}

size_t simplerandom_cong_num_seeds(const SimpleRandomCong_t * p_cong)
{
    (const void *)p_cong;   /* We only use this parameter for type checking. */

    return 1u;
}

size_t simplerandom_cong_seed_array(SimpleRandomCong_t * p_cong, const uint32_t * p_seeds, size_t num_seeds, bool mix_extras)
{
    uint32_t    seed = 0;
    size_t      num_seeds_used = 0;

    if (num_seeds >= 1u && p_seeds != NULL)
    {
        seed = p_seeds[0];
        num_seeds_used = 1u;
    }
    simplerandom_cong_seed(p_cong, seed);

    if (mix_extras && p_seeds != NULL)
    {
        simplerandom_cong_mix(p_cong, p_seeds + num_seeds_used, num_seeds - num_seeds_used);
        num_seeds_used = num_seeds;
    }
    return num_seeds_used;
}

void simplerandom_cong_seed(SimpleRandomCong_t * p_cong, uint32_t seed)
{
    p_cong->cong = seed;
    /* No sanitize is needed because for Cong, all state values are valid. */
}

void simplerandom_cong_sanitize(SimpleRandomCong_t * p_cong)
{
    /* All state values are valid for Cong. No sanitizing needed. */
    (const void *) p_cong;
}

uint32_t simplerandom_cong_next(SimpleRandomCong_t * p_cong)
{
    uint32_t    cong;

    cong = UINT32_C(69069) * p_cong->cong + 12345u;
    p_cong->cong = cong;

    return cong;
}

void simplerandom_cong_mix(SimpleRandomCong_t * p_cong, const uint32_t * p_data, size_t num_data)
{
    if (p_data != NULL)
    {
        while (num_data)
        {
            --num_data;
            p_cong->cong ^= *p_data++;
            simplerandom_cong_sanitize(p_cong);
            simplerandom_cong_next(p_cong);
        }
    }
}
<|endoftext|>