<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "logging/flags.hpp"

mesos::internal::logging::Flags::Flags()
{
  add(&Flags::quiet,
      "quiet",
      "Disable logging to stderr",
      false);

  add(&Flags::logging_level,
      "logging_level",
      "Log message at or above this level.\n"
      "Possible values: `INFO`, `WARNING`, `ERROR`.\n"
      "If `--quiet` is specified, this will only affect the logs\n"
      "written to `--log_dir`, if specified.",
      "INFO");

  add(&Flags::log_dir,
      "log_dir",
      "Location to put log files.  By default, nothing is written to disk.\n"
      "Does not affect logging to stderr.\n"
      "If specified, the log file will appear in the Mesos WebUI."
      "NOTE: 3rd party log messages (e.g. ZooKeeper) are\n"
      "only written to stderr!");

  add(&Flags::logbufsecs,
      "logbufsecs",
      "Maximum number of seconds that logs may be buffered for.\n"
      "By default, logs are flushed immediately.",
      0);

  add(&Flags::initialize_driver_logging,
      "initialize_driver_logging",
      "Whether the master/agent should initialize Google logging for the\n"
      "Mesos scheduler and executor drivers, in same way as described here.\n"
      "The scheduler/executor drivers have separate logs and do not get\n"
      "written to the master/agent logs.\n\n"
      "This option has no effect when using the HTTP scheduler/executor APIs.\n"
      "By default, this option is true.",
      true);

  add(&Flags::external_log_file,
      "external_log_file",
      "Location of the externally managed log file.  Mesos does not write to\n"
      "this file directly and merely exposes it in the WebUI and HTTP API.\n"
      "This is only useful when logging to stderr in combination with an\n"
      "external logging mechanism, like syslog or journald.\n\n"
      "This option is meaningless when specified along with `--quiet`.\n\n"
      "This option takes precedence over `--log_dir` in the WebUI.\n"
      "However, logs will still be written to the `--log_dir` if\n"
      "that option is specified.");
}
<commit_msg>Fixed newline for `--log_dir` flag usage message.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "logging/flags.hpp"

mesos::internal::logging::Flags::Flags()
{
  add(&Flags::quiet,
      "quiet",
      "Disable logging to stderr",
      false);

  add(&Flags::logging_level,
      "logging_level",
      "Log message at or above this level.\n"
      "Possible values: `INFO`, `WARNING`, `ERROR`.\n"
      "If `--quiet` is specified, this will only affect the logs\n"
      "written to `--log_dir`, if specified.",
      "INFO");

  add(&Flags::log_dir,
      "log_dir",
      "Location to put log files.  By default, nothing is written to disk.\n"
      "Does not affect logging to stderr.\n"
      "If specified, the log file will appear in the Mesos WebUI.\n"
      "NOTE: 3rd party log messages (e.g. ZooKeeper) are\n"
      "only written to stderr!");

  add(&Flags::logbufsecs,
      "logbufsecs",
      "Maximum number of seconds that logs may be buffered for.\n"
      "By default, logs are flushed immediately.",
      0);

  add(&Flags::initialize_driver_logging,
      "initialize_driver_logging",
      "Whether the master/agent should initialize Google logging for the\n"
      "Mesos scheduler and executor drivers, in same way as described here.\n"
      "The scheduler/executor drivers have separate logs and do not get\n"
      "written to the master/agent logs.\n\n"
      "This option has no effect when using the HTTP scheduler/executor APIs.\n"
      "By default, this option is true.",
      true);

  add(&Flags::external_log_file,
      "external_log_file",
      "Location of the externally managed log file.  Mesos does not write to\n"
      "this file directly and merely exposes it in the WebUI and HTTP API.\n"
      "This is only useful when logging to stderr in combination with an\n"
      "external logging mechanism, like syslog or journald.\n\n"
      "This option is meaningless when specified along with `--quiet`.\n\n"
      "This option takes precedence over `--log_dir` in the WebUI.\n"
      "However, logs will still be written to the `--log_dir` if\n"
      "that option is specified.");
}
<|endoftext|>


<commit_before>#include "Number.h"
#include "BigFix/DataRef.h"
#include "BigFix/Error.h"

namespace BigFix
{

uint64_t ReadLittleEndian( DataRef data )
{
  uint64_t number = 0;

  for ( size_t i = data.Length(); i != 0; i-- )
  {
    number *= 256;
    number += data.Start()[i - 1];
  }

  return number;
}

void WriteLittleEndian( uint64_t number, uint8_t* buffer, size_t length )
{
  for ( size_t i = 0; i != length; i++ )
  {
    buffer[i] = number % 256;
    number /= 256;
  }
}

static bool IsAsciiDigit( uint8_t c )
{
  return '0' <= c && c <= '9';
}

template < class T >
T ReadAsciiNumber( DataRef data )
{
  T number = 0;

  for ( size_t i = 0; i < data.Length(); i++ )
  {
    uint8_t c = data.Start()[i];

    if ( !IsAsciiDigit( c ) )
      throw Error( "Invalid ascii number" );

    number *= 10;
    number += c - '0';
  }

  return number;
}

template uint8_t ReadAsciiNumber<uint8_t>( DataRef );
template int32_t ReadAsciiNumber<int32_t>( DataRef );
template uint32_t ReadAsciiNumber<uint32_t>( DataRef );

}
<commit_msg>Just use the normal subscript<commit_after>#include "Number.h"
#include "BigFix/DataRef.h"
#include "BigFix/Error.h"

namespace BigFix
{

uint64_t ReadLittleEndian( DataRef data )
{
  uint64_t number = 0;

  for ( size_t i = data.Length(); i != 0; i-- )
  {
    number *= 256;
    number += data[i - 1];
  }

  return number;
}

void WriteLittleEndian( uint64_t number, uint8_t* buffer, size_t length )
{
  for ( size_t i = 0; i != length; i++ )
  {
    buffer[i] = number % 256;
    number /= 256;
  }
}

static bool IsAsciiDigit( uint8_t c )
{
  return '0' <= c && c <= '9';
}

template < class T >
T ReadAsciiNumber( DataRef data )
{
  T number = 0;

  for ( size_t i = 0; i < data.Length(); i++ )
  {
    uint8_t c = data[i];

    if ( !IsAsciiDigit( c ) )
      throw Error( "Invalid ascii number" );

    number *= 10;
    number += c - '0';
  }

  return number;
}

template uint8_t ReadAsciiNumber<uint8_t>( DataRef );
template int32_t ReadAsciiNumber<int32_t>( DataRef );
template uint32_t ReadAsciiNumber<uint32_t>( DataRef );

}
<|endoftext|>


<commit_before>/* Copyright 2019 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.
==============================================================================*/
#if GOOGLE_CUDA

#define EIGEN_USE_GPU

#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "tensorflow_addons/custom_ops/image/cc/kernels/adjust_hsv_in_yiq_op.h"

namespace tensorflow {
namespace addons {

namespace {

template <typename T>
inline se::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory, uint64 size) {
  se::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory), size * sizeof(T));
  se::DeviceMemory<T> typed(wrapped);
  return typed;
}
}  // namespace

namespace internal {

__global__ void compute_transformation_matrix_cuda(const float* const delta_h,
                                                   const float* const scale_s,
                                                   const float* const scale_v,
                                                   float* const matrix,
                                                   const int matrix_size) {
  if (matrix_size == kChannelSize * kChannelSize) {
    compute_transformation_matrix<kChannelSize * kChannelSize>(
        *delta_h, *scale_s, *scale_v, matrix);
  }
}
}  // namespace internal

namespace functor {

void AdjustHsvInYiqGPU::operator()(OpKernelContext* ctx, int channel_count,
                                   const Tensor* const input,
                                   const float* const delta_h,
                                   const float* const scale_s,
                                   const float* const scale_v,
                                   Tensor* const output) {
  const uint64 m = channel_count;
  const uint64 k = kChannelSize;
  const uint64 n = kChannelSize;
  auto* cu_stream = ctx->eigen_device<GPUDevice>().stream();
  OP_REQUIRES(ctx, cu_stream, errors::Internal("No GPU stream available."));
  Tensor transformation_matrix;
  OP_REQUIRES_OK(ctx, ctx->allocate_temp(
                          DT_FLOAT, TensorShape({kChannelSize * kChannelSize}),
                          &transformation_matrix));
  // TODO(huangyp): It takes about 3.5 us to compute transformation_matrix
  // with one thread. Improve its performance if necessary.
  TF_CHECK_OK(CudaLaunchKernel(internal::compute_transformation_matrix_cuda, 1,
                               1, 0, cu_stream, delta_h, scale_s, scale_v,
                               transformation_matrix.flat<float>().data(),
                               transformation_matrix.flat<float>().size()));
  // Call cuBlas C = A * B directly.
  auto no_transpose = se::blas::Transpose::kNoTranspose;
  auto a_ptr =
      AsDeviceMemory(input->flat<float>().data(), input->flat<float>().size());
  auto b_ptr = AsDeviceMemory(transformation_matrix.flat<float>().data(),
                              transformation_matrix.flat<float>().size());
  auto c_ptr = AsDeviceMemory(output->flat<float>().data(),
                              output->flat<float>().size());
  auto* stream = ctx->op_device_context()->stream();
  OP_REQUIRES(ctx, stream, errors::Internal("No GPU stream available."));
  // TODO(huangyp): share/use autotune cublas algorithms in Matmul.op.
  bool blas_launch_status =
      stream
          ->ThenBlasGemm(no_transpose, no_transpose, n, m, k, 1.0f, b_ptr, n,
                         a_ptr, k, 0.0f, &c_ptr, n)
          .ok();
  if (!blas_launch_status) {
    ctx->SetStatus(errors::Internal("Blas SGEMM launch failed : m=", m,
                                    ", n=", n, ", k=", k));
  }
}
}  // namespace functor
}  // end namespace addons
}  // namespace tensorflow

#endif  // GOOGLE_CUDA
<commit_msg>use AsDeviceMemory from StreamExecutorUtil (#1851)<commit_after>/* Copyright 2019 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.
==============================================================================*/
#if GOOGLE_CUDA

#define EIGEN_USE_GPU

#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "tensorflow/core/util/stream_executor_util.h"
#include "tensorflow_addons/custom_ops/image/cc/kernels/adjust_hsv_in_yiq_op.h"

namespace tensorflow {
namespace addons {
namespace internal {

__global__ void compute_transformation_matrix_cuda(const float* const delta_h,
                                                   const float* const scale_s,
                                                   const float* const scale_v,
                                                   float* const matrix,
                                                   const int matrix_size) {
  if (matrix_size == kChannelSize * kChannelSize) {
    compute_transformation_matrix<kChannelSize * kChannelSize>(
        *delta_h, *scale_s, *scale_v, matrix);
  }
}
}  // namespace internal

namespace functor {

void AdjustHsvInYiqGPU::operator()(OpKernelContext* ctx, int channel_count,
                                   const Tensor* const input,
                                   const float* const delta_h,
                                   const float* const scale_s,
                                   const float* const scale_v,
                                   Tensor* const output) {
  const uint64 m = channel_count;
  const uint64 k = kChannelSize;
  const uint64 n = kChannelSize;
  auto* cu_stream = ctx->eigen_device<GPUDevice>().stream();
  OP_REQUIRES(ctx, cu_stream, errors::Internal("No GPU stream available."));
  Tensor transformation_matrix;
  OP_REQUIRES_OK(ctx, ctx->allocate_temp(
                          DT_FLOAT, TensorShape({kChannelSize * kChannelSize}),
                          &transformation_matrix));
  // TODO(huangyp): It takes about 3.5 us to compute transformation_matrix
  // with one thread. Improve its performance if necessary.
  TF_CHECK_OK(CudaLaunchKernel(internal::compute_transformation_matrix_cuda, 1,
                               1, 0, cu_stream, delta_h, scale_s, scale_v,
                               transformation_matrix.flat<float>().data(),
                               transformation_matrix.flat<float>().size()));
  // Call cuBlas C = A * B directly.
  auto no_transpose = se::blas::Transpose::kNoTranspose;
  auto a_ptr = StreamExecutorUtil::AsDeviceMemory<float>(*input);
  auto b_ptr = StreamExecutorUtil::AsDeviceMemory<float>(transformation_matrix);
  auto c_ptr = StreamExecutorUtil::AsDeviceMemory<float>(*output);
  auto* stream = ctx->op_device_context()->stream();
  OP_REQUIRES(ctx, stream, errors::Internal("No GPU stream available."));
  // TODO(huangyp): share/use autotune cublas algorithms in Matmul.op.
  bool blas_launch_status =
      stream
          ->ThenBlasGemm(no_transpose, no_transpose, n, m, k, 1.0f, b_ptr, n,
                         a_ptr, k, 0.0f, &c_ptr, n)
          .ok();
  if (!blas_launch_status) {
    ctx->SetStatus(errors::Internal("Blas SGEMM launch failed : m=", m,
                                    ", n=", n, ", k=", k));
  }
}
}  // namespace functor
}  // end namespace addons
}  // namespace tensorflow

#endif  // GOOGLE_CUDA
<|endoftext|>


<commit_before>#ifdef ENABLE_MPI

#include <stddef.h>

#include "Tools/Display/bash_tools.h"

#include "Monitor_reduction_mpi.hpp"

struct monitor_vals
{
	int n_be;
	int n_fe;
	unsigned long long n_fra;
};

void MPI_SUM_monitor_vals_func(void *in, void *inout, int *len, MPI_Datatype *datatype)
{
	auto    in_cvt = static_cast<monitor_vals*>(in   );
	auto inout_cvt = static_cast<monitor_vals*>(inout);

	for (auto i = 0; i < *len; i++)
	{
		inout_cvt[i].n_be  += in_cvt[i].n_be;
		inout_cvt[i].n_fe  += in_cvt[i].n_fe;
		inout_cvt[i].n_fra += in_cvt[i].n_fra;
	}
}

template <typename B>
Monitor_reduction_mpi<B>
::Monitor_reduction_mpi(const int& K, const int& N, const int& max_fe,
                        std::vector<Monitor<B>*>& error_analyzers,
                        const std::thread::id master_thread_id,
                        const std::chrono::nanoseconds d_mpi_comm_frequency,
                        const int& n_frames,
                        const std::string name)
: Monitor_reduction<B>(K, N, max_fe, error_analyzers, n_frames, name),
  master_thread_id(master_thread_id),
  is_fe_limit_achieved(false),
  t_last_mpi_comm(std::chrono::steady_clock::now()),
  d_mpi_comm_frequency(d_mpi_comm_frequency)
{
	int blen[3];
	MPI_Aint displacements[3];
	MPI_Datatype oldtypes[3];

	blen[0] = 1; displacements[0] = offsetof(monitor_vals, n_be);  oldtypes[0] = MPI_INT;
	blen[1] = 1; displacements[1] = offsetof(monitor_vals, n_fe);  oldtypes[1] = MPI_INT;
	blen[2] = 1; displacements[2] = offsetof(monitor_vals, n_fra); oldtypes[2] = MPI_UNSIGNED_LONG_LONG;

	if (auto ret = MPI_Type_create_struct(3, blen, displacements, oldtypes, &MPI_monitor_vals))
	{
		std::cerr << bold_red("(EE) MPI_Type_create_struct returned \"") << bold_red(std::to_string(ret))
		          << bold_red("\", exiting.") << std::endl;
		std::exit(-1);
	}

	if (auto ret = MPI_Type_commit(&MPI_monitor_vals))
	{
		std::cerr << bold_red("(EE) MPI_Type_commit returned \"") << bold_red(std::to_string(ret))
		          << bold_red("\", exiting.") << std::endl;
		std::exit(-1);
	}

	if (auto ret = MPI_Op_create(MPI_SUM_monitor_vals_func, true, &MPI_SUM_monitor_vals))
	{
		std::cerr << bold_red("(EE) MPI_Op_create returned \"") << bold_red(std::to_string(ret))
		          << bold_red("\", exiting.") << std::endl;
		std::exit(-1);
	}
}

template <typename B>
Monitor_reduction_mpi<B>
::~Monitor_reduction_mpi()
{
}

template <typename B>
bool Monitor_reduction_mpi<B>
::fe_limit_achieved()
{
	// only the master thread can do this
	if (std::this_thread::get_id() == this->master_thread_id &&
	    ((std::chrono::steady_clock::now() - t_last_mpi_comm) >= d_mpi_comm_frequency))
	{
		monitor_vals mvals_recv;
		monitor_vals mvals_send = { this->get_n_be()           - this->n_bit_errors,
		                            this->get_n_fe()           - this->n_frame_errors,
		                            this->get_n_analyzed_fra() - this->n_analyzed_frames };

		MPI_Allreduce(&mvals_send, &mvals_recv, 1, MPI_monitor_vals, MPI_SUM_monitor_vals, MPI_COMM_WORLD);

		this->n_bit_errors      = mvals_recv.n_be  - mvals_send.n_be;
		this->n_frame_errors    = mvals_recv.n_fe  - mvals_send.n_fe;
		this->n_analyzed_frames = mvals_recv.n_fra - mvals_send.n_fra;

		t_last_mpi_comm = std::chrono::steady_clock::now();

		is_fe_limit_achieved = this->get_n_fe() >= this->get_fe_limit();
	}

	return is_fe_limit_achieved;
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Monitor_reduction_mpi<B_8>;
template class Monitor_reduction_mpi<B_16>;
template class Monitor_reduction_mpi<B_32>;
template class Monitor_reduction_mpi<B_64>;
#else
template class Monitor_reduction_mpi<B>;
#endif
// ==================================================================================== explicit template instantiation

#endif
<commit_msg>Fix a possible dead lock.<commit_after>#ifdef ENABLE_MPI

#include <stddef.h>

#include "Tools/Display/bash_tools.h"

#include "Monitor_reduction_mpi.hpp"

struct monitor_vals
{
	int n_be;
	int n_fe;
	unsigned long long n_fra;
};

void MPI_SUM_monitor_vals_func(void *in, void *inout, int *len, MPI_Datatype *datatype)
{
	auto    in_cvt = static_cast<monitor_vals*>(in   );
	auto inout_cvt = static_cast<monitor_vals*>(inout);

	for (auto i = 0; i < *len; i++)
	{
		inout_cvt[i].n_be  += in_cvt[i].n_be;
		inout_cvt[i].n_fe  += in_cvt[i].n_fe;
		inout_cvt[i].n_fra += in_cvt[i].n_fra;
	}
}

template <typename B>
Monitor_reduction_mpi<B>
::Monitor_reduction_mpi(const int& K, const int& N, const int& max_fe,
                        std::vector<Monitor<B>*>& error_analyzers,
                        const std::thread::id master_thread_id,
                        const std::chrono::nanoseconds d_mpi_comm_frequency,
                        const int& n_frames,
                        const std::string name)
: Monitor_reduction<B>(K, N, max_fe, error_analyzers, n_frames, name),
  master_thread_id(master_thread_id),
  is_fe_limit_achieved(false),
  t_last_mpi_comm(std::chrono::steady_clock::now()),
  d_mpi_comm_frequency(d_mpi_comm_frequency)
{
	int blen[3];
	MPI_Aint displacements[3];
	MPI_Datatype oldtypes[3];

	blen[0] = 1; displacements[0] = offsetof(monitor_vals, n_be);  oldtypes[0] = MPI_INT;
	blen[1] = 1; displacements[1] = offsetof(monitor_vals, n_fe);  oldtypes[1] = MPI_INT;
	blen[2] = 1; displacements[2] = offsetof(monitor_vals, n_fra); oldtypes[2] = MPI_UNSIGNED_LONG_LONG;

	if (auto ret = MPI_Type_create_struct(3, blen, displacements, oldtypes, &MPI_monitor_vals))
	{
		std::cerr << bold_red("(EE) MPI_Type_create_struct returned \"") << bold_red(std::to_string(ret))
		          << bold_red("\", exiting.") << std::endl;
		std::exit(-1);
	}

	if (auto ret = MPI_Type_commit(&MPI_monitor_vals))
	{
		std::cerr << bold_red("(EE) MPI_Type_commit returned \"") << bold_red(std::to_string(ret))
		          << bold_red("\", exiting.") << std::endl;
		std::exit(-1);
	}

	if (auto ret = MPI_Op_create(MPI_SUM_monitor_vals_func, true, &MPI_SUM_monitor_vals))
	{
		std::cerr << bold_red("(EE) MPI_Op_create returned \"") << bold_red(std::to_string(ret))
		          << bold_red("\", exiting.") << std::endl;
		std::exit(-1);
	}
}

template <typename B>
Monitor_reduction_mpi<B>
::~Monitor_reduction_mpi()
{
}

template <typename B>
bool Monitor_reduction_mpi<B>
::fe_limit_achieved()
{
	// only the master thread can do this
	if (std::this_thread::get_id() == this->master_thread_id &&
	    ((std::chrono::steady_clock::now() - t_last_mpi_comm) >= d_mpi_comm_frequency))
	{
		monitor_vals mvals_recv;
		monitor_vals mvals_send = { this->get_n_be()           - this->n_bit_errors,
		                            this->get_n_fe()           - this->n_frame_errors,
		                            this->get_n_analyzed_fra() - this->n_analyzed_frames };

		MPI_Allreduce(&mvals_send, &mvals_recv, 1, MPI_monitor_vals, MPI_SUM_monitor_vals, MPI_COMM_WORLD);

		this->n_bit_errors      = mvals_recv.n_be  - mvals_send.n_be;
		this->n_frame_errors    = mvals_recv.n_fe  - mvals_send.n_fe;
		this->n_analyzed_frames = mvals_recv.n_fra - mvals_send.n_fra;

		t_last_mpi_comm = std::chrono::steady_clock::now();

		is_fe_limit_achieved = mvals_recv.n_fe >= this->get_fe_limit();
	}

	return is_fe_limit_achieved;
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Monitor_reduction_mpi<B_8>;
template class Monitor_reduction_mpi<B_16>;
template class Monitor_reduction_mpi<B_32>;
template class Monitor_reduction_mpi<B_64>;
#else
template class Monitor_reduction_mpi<B>;
#endif
// ==================================================================================== explicit template instantiation

#endif
<|endoftext|>


<commit_before>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2013 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh is distributed in the hope that it will be useful,              *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

//== INCLUDES =================================================================

#ifdef _MSC_VER
#  pragma warning(disable: 4267 4311)
#endif

#include <iostream>
#include <fstream>

#include <qapplication.h>
#include <qdatetime.h>

#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/MeshIO.hh>

#include <OpenMesh/Apps/Decimating/DecimaterViewerWidget.hh>

//== IMPLEMENTATION ==========================================================

//-----------------------------------------------------------------------------

void DecimaterViewerWidget::keyPressEvent(QKeyEvent* _event)
{
  switch (_event->key())
  {
    case Key_H:
      std::cout << "Press '+' to increase the number of decimating steps\n"
                << "Press '-' to decrease the number of decimating steps\n"
                << "Press 'd' to perform the set number of decimating steps\n"
                << "Press 'S' to save the mesh to 'result.off'\n"
                << "Press 'q' or 'Esc' quit the application" << std::endl;
      break;
    case Key_D:
    {
      int rc;
      if ( (rc=decimater_->decimate(steps_)) )
      {
        decimater_->mesh().garbage_collection();
        std::cout << rc << " vertices removed!\n";
        updateGL();
      }
      else
        std::cout << "Decimation failed\n";
      break;
    }

    case Key_Plus:
      ++steps_;
      steps_ = std::min( steps_ , (size_t)( mesh_.n_vertices() / 10 ) );
      updateGL();
      std::cout << "# decimating steps increased to " << steps_ << std::endl;
      break;

    case Key_Minus:
      --steps_;
      steps_ = std::max( steps_ , size_t(1) );
      updateGL();
      std::cout << "# decimating steps increased to " << steps_ << std::endl;
      break;

    case Key_S:
    {
      OpenMesh::IO::Options opt;

      opt += OpenMesh::IO::Options::Binary;

      if (OpenMesh::IO::write_mesh( mesh(), "result.off", opt ))
        std::cout << "mesh saved in 'result.off'\n";
    }
    break;

    case Key_Q:
    case Key_Escape:
      qApp->quit();
      break;
    default:
      this->inherited_t::keyPressEvent(_event);
      break;
  }
}

void DecimaterViewerWidget::animate( void )
{
//    updateGL();
//    timer_->start(300, true);
}

//=============================================================================
<commit_msg>cppcheck: Missing break<commit_after>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2013 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh is distributed in the hope that it will be useful,              *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

//== INCLUDES =================================================================

#ifdef _MSC_VER
#  pragma warning(disable: 4267 4311)
#endif

#include <iostream>
#include <fstream>

#include <qapplication.h>
#include <qdatetime.h>

#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/MeshIO.hh>

#include <OpenMesh/Apps/Decimating/DecimaterViewerWidget.hh>

//== IMPLEMENTATION ==========================================================

//-----------------------------------------------------------------------------

void DecimaterViewerWidget::keyPressEvent(QKeyEvent* _event)
{
  switch (_event->key())
  {
    case Key_H:
      std::cout << "Press '+' to increase the number of decimating steps\n"
                << "Press '-' to decrease the number of decimating steps\n"
                << "Press 'd' to perform the set number of decimating steps\n"
                << "Press 'S' to save the mesh to 'result.off'\n"
                << "Press 'q' or 'Esc' quit the application" << std::endl;
      break;
    case Key_D:
    {
      int rc;
      if ( (rc=decimater_->decimate(steps_)) )
      {
        decimater_->mesh().garbage_collection();
        std::cout << rc << " vertices removed!\n";
        updateGL();
      }
      else
        std::cout << "Decimation failed\n";
      break;
    }

    case Key_Plus:
      ++steps_;
      steps_ = std::min( steps_ , (size_t)( mesh_.n_vertices() / 10 ) );
      updateGL();
      std::cout << "# decimating steps increased to " << steps_ << std::endl;
      break;

    case Key_Minus:
      --steps_;
      steps_ = std::max( steps_ , size_t(1) );
      updateGL();
      std::cout << "# decimating steps increased to " << steps_ << std::endl;
      break;

    case Key_S:
    {
      OpenMesh::IO::Options opt;

      opt += OpenMesh::IO::Options::Binary;

      if (OpenMesh::IO::write_mesh( mesh(), "result.off", opt ))
        std::cout << "mesh saved in 'result.off'\n";
    }
    break;

    case Key_Q:
      qApp->quit();
      break;
    case Key_Escape:
      qApp->quit();
      break;
    default:
      this->inherited_t::keyPressEvent(_event);
      break;
  }
}

void DecimaterViewerWidget::animate( void )
{
//    updateGL();
//    timer_->start(300, true);
}

//=============================================================================
<|endoftext|>


<commit_before>#ifndef ARGUMENT_TYPE_FILE_SYSTEM_HPP_
#define ARGUMENT_TYPE_FILE_SYSTEM_HPP_

#include <string>
#include <iostream>
#include <stdexcept>

#include "Tools/system_functions.h"
#include "Tools/version.h"

#include "../Argument_type_limited.hpp"

namespace aff3ct
{
namespace tools
{

enum class openmode : uint8_t {read, write, read_write};

template <typename Read_F>
std::string modify_path(const std::string& val)
{
	std::string binary_path = get_binary_path();
	if (!binary_path.empty())
	{
		std::string basedir, filename;
		split_path(binary_path, basedir, filename);

		std::string aff3ct_version = aff3ct::version();
		if (!aff3ct_version.empty() && aff3ct_version[0] == 'v')
			aff3ct_version.erase(0, 1); // rm the 'v'

		std::vector<std::string> paths = {
			"../../",
			"../../../",
			"../share/aff3ct-" + aff3ct_version + "/",
			"../../share/aff3ct-" + aff3ct_version + "/",
			"/usr/share/aff3ct-" + aff3ct_version + "/",
			"/usr/share/aff3ct-" + aff3ct_version + "/",
			"/usr/local/share/aff3ct-" + aff3ct_version + "/",
			"../share/aff3ct/",
			"../../share/aff3ct/",
			"/usr/share/aff3ct/",
			"/usr/local/share/aff3ct/",
		};

		for (auto &path : paths)
		{
			std::string full_path = (path[0] != '/') ? basedir + "/" : "";
			full_path += path + val;
#if defined(_WIN32) || defined(_WIN64)
			if (path[0] == '/')
				continue;
			std::replace(full_path.begin(), full_path.end(), '/', '\\');
#endif
			if (Read_F::check(full_path))
				return full_path;
		}
	}

	return "";
}

std::string openmode_to_string(const openmode& mode);

struct Is_file
{
	static bool check(const std::string& filename);
};

struct Is_folder
{
	static bool check(const std::string& foldername);
};

struct Is_path
{
	static bool check(const std::string& path);
};

struct No_check
{
	static bool check(const std::string&);
};

template <typename T = std::string, typename Read_F = No_check, typename Write_F = No_check, typename RW_F = No_check, typename... Ranges>
class File_system_type : public Argument_type_limited<T,Ranges...>
{
protected:
	const std::string name;
	const openmode    mode;

public:
	template <typename r, typename... R>
	explicit File_system_type(const std::string& name, const openmode& mode, const r* range, const R*... ranges)
	: Argument_type_limited<T,Ranges...>(generate_title(name, mode), range, ranges...), name(name), mode(mode)
	{ }

	explicit File_system_type(const std::string& name, const openmode& mode)
	: Argument_type_limited<T,Ranges...>(generate_title(name, mode)), name(name), mode(mode)
	{ }

	virtual ~File_system_type() {};

	virtual File_system_type<T, Read_F, Write_F, RW_F, Ranges...>* clone() const
	{
		auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges...>(name, mode);

		return dynamic_cast<File_system_type<T, Read_F, Write_F, RW_F, Ranges...>*>(this->clone_ranges(clone));
	}

	template <typename... NewRanges>
	File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>* clone(NewRanges*... new_ranges)
	{
		auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>(name, mode);

		this->clone_ranges(clone);

		clone->add_ranges(new_ranges...);

		return clone;
	}

	static std::string generate_title(const std::string& name, const openmode& mode)
	{
		return name + " [" + openmode_to_string(mode) + "]";
	}

	virtual T convert(const std::string& val) const
	{
		return val;
	}

	virtual void check(const std::string& val) const
	{
		auto str_val = this->convert(val);

		if (str_val.empty())
			throw std::runtime_error("shall be a " + name + " name");

		switch(mode)
		{
			case openmode::read :
				if(!Read_F::check(str_val))
					if (modify_path<Read_F>(str_val).empty())
						throw std::runtime_error("does not name an existing " + name);
				break;

			case openmode::write :
				if(!Write_F::check(str_val))
					throw std::runtime_error("does not name a " + name);
				break;

			case openmode::read_write : // nothing to check
				if(!RW_F::check(str_val))
					throw std::runtime_error("does not name a " + name);
				break;
		}

		this->check_ranges(str_val);
	}
};

}
}

#include "File.hpp"
#include "Folder.hpp"
#include "Path.hpp"

#endif /* ARGUMENT_TYPE_FILE_SYSTEM_HPP_ */<commit_msg>Print debug infos.<commit_after>#ifndef ARGUMENT_TYPE_FILE_SYSTEM_HPP_
#define ARGUMENT_TYPE_FILE_SYSTEM_HPP_

#include <string>
#include <iostream>
#include <stdexcept>

#include "Tools/system_functions.h"
#include "Tools/version.h"

#include "../Argument_type_limited.hpp"

namespace aff3ct
{
namespace tools
{

enum class openmode : uint8_t {read, write, read_write};

template <typename Read_F>
std::string modify_path(const std::string& val)
{
	std::string binary_path = get_binary_path();
	if (!binary_path.empty())
	{
		std::string basedir, filename;
		split_path(binary_path, basedir, filename);

		std::cout << "# (DBG) binary_path = '" << binary_path << "'" << std::endl;
		std::cout << "# (DBG) basedir     = '" << basedir     << "'" << std::endl;
		std::cout << "# (DBG) filename    = '" << filename    << "'" << std::endl;

		std::string aff3ct_version = aff3ct::version();
		if (!aff3ct_version.empty() && aff3ct_version[0] == 'v')
			aff3ct_version.erase(0, 1); // rm the 'v'

		std::vector<std::string> paths = {
			"../../",
			"../../../",
			"../share/aff3ct-" + aff3ct_version + "/",
			"../../share/aff3ct-" + aff3ct_version + "/",
			"/usr/share/aff3ct-" + aff3ct_version + "/",
			"/usr/share/aff3ct-" + aff3ct_version + "/",
			"/usr/local/share/aff3ct-" + aff3ct_version + "/",
			"../share/aff3ct/",
			"../../share/aff3ct/",
			"/usr/share/aff3ct/",
			"/usr/local/share/aff3ct/",
		};

		for (auto &path : paths)
		{
			std::string full_path = (path[0] != '/') ? basedir + "/" : "";
			full_path += path + val;
#if defined(_WIN32) || defined(_WIN64)
			if (path[0] == '/')
				continue;
			std::replace(full_path.begin(), full_path.end(), '/', '\\');
#endif
			if (Read_F::check(full_path))
				return full_path;
		}
	}

	return "";
}

std::string openmode_to_string(const openmode& mode);

struct Is_file
{
	static bool check(const std::string& filename);
};

struct Is_folder
{
	static bool check(const std::string& foldername);
};

struct Is_path
{
	static bool check(const std::string& path);
};

struct No_check
{
	static bool check(const std::string&);
};

template <typename T = std::string, typename Read_F = No_check, typename Write_F = No_check, typename RW_F = No_check, typename... Ranges>
class File_system_type : public Argument_type_limited<T,Ranges...>
{
protected:
	const std::string name;
	const openmode    mode;

public:
	template <typename r, typename... R>
	explicit File_system_type(const std::string& name, const openmode& mode, const r* range, const R*... ranges)
	: Argument_type_limited<T,Ranges...>(generate_title(name, mode), range, ranges...), name(name), mode(mode)
	{ }

	explicit File_system_type(const std::string& name, const openmode& mode)
	: Argument_type_limited<T,Ranges...>(generate_title(name, mode)), name(name), mode(mode)
	{ }

	virtual ~File_system_type() {};

	virtual File_system_type<T, Read_F, Write_F, RW_F, Ranges...>* clone() const
	{
		auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges...>(name, mode);

		return dynamic_cast<File_system_type<T, Read_F, Write_F, RW_F, Ranges...>*>(this->clone_ranges(clone));
	}

	template <typename... NewRanges>
	File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>* clone(NewRanges*... new_ranges)
	{
		auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>(name, mode);

		this->clone_ranges(clone);

		clone->add_ranges(new_ranges...);

		return clone;
	}

	static std::string generate_title(const std::string& name, const openmode& mode)
	{
		return name + " [" + openmode_to_string(mode) + "]";
	}

	virtual T convert(const std::string& val) const
	{
		return val;
	}

	virtual void check(const std::string& val) const
	{
		auto str_val = this->convert(val);

		if (str_val.empty())
			throw std::runtime_error("shall be a " + name + " name");

		switch(mode)
		{
			case openmode::read :
				if(!Read_F::check(str_val))
					if (modify_path<Read_F>(str_val).empty())
						throw std::runtime_error("does not name an existing " + name);
				break;

			case openmode::write :
				if(!Write_F::check(str_val))
					throw std::runtime_error("does not name a " + name);
				break;

			case openmode::read_write : // nothing to check
				if(!RW_F::check(str_val))
					throw std::runtime_error("does not name a " + name);
				break;
		}

		this->check_ranges(str_val);
	}
};

}
}

#include "File.hpp"
#include "Folder.hpp"
#include "Path.hpp"

#endif /* ARGUMENT_TYPE_FILE_SYSTEM_HPP_ */<|endoftext|>


<commit_before>#include <readline/readline.h>
#include <readline/history.h>
#include <iostream>
#include <cctype>
#include <sstream>
#include <ctime>
#include "../parser/stmt.h"
#include "../../parser.tab.h"
#include "evaluator.h"

typedef struct yy_buffer_state *YY_BUFFER_STATE;

extern YY_BUFFER_STATE yy_scan_string (const char *yy_str  );
extern void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
extern void yy_delete_buffer (YY_BUFFER_STATE b  );
extern int yyparse ();

using namespace std;

BufferManager BufferManager;
IndexManager IndexManager(&BufferManager);
catalog_manager catm(".");
RecordManager RecordManager;

string base_addr = ".";

void system_init() {
    cout << "System Initialized!" << endl;

    RecordManager.Init(&BufferManager, &catm, &IndexManager);

}

int main() {

    system_init();

    int ii = 10;
    time_t *start_time = nullptr, *end_time;

    while(ii < 1200) {
        if ( stmt_queue.empty() ) {
            if (start_time != nullptr) {
                cout << difftime(*end_time, *start_time) << " seconds used." << endl;
            }
            time(end_time);
            char * line = readline(">>> ");
            time(start_time);
            add_history(line);

            int len = strlen(line);
            char *tmp = new char[len + 2];
            strcpy(tmp, line);
            tmp[len + 1] = 0;

            YY_BUFFER_STATE my_string_buffer = yy_scan_string(tmp);
            yy_switch_to_buffer( my_string_buffer );
            yyparse();
            yy_delete_buffer( my_string_buffer );

            delete[] tmp;
        }

        try {
            while( !stmt_queue.empty() ) {

                switch( stmt_queue.front().first ) {
                    case stmt_type::_create_table_stmt:
                        xyzsql_process_create_table();
                        break;
                    case stmt_type::_create_index_stmt:
                        xyzsql_process_create_index();
                        break;
                    case stmt_type::_select_stmt:
                        xyzsql_process_select();
                        break;
                    case stmt_type::_insert_stmt:
                        xyzsql_process_insert();
                        break;
                    case stmt_type::_delete_stmt:
                        xyzsql_process_delete();
                        break;
                    case stmt_type::_drop_table_stmt:
                        xyzsql_process_drop_table();
                        break;
                    case stmt_type::_drop_index_stmt:
                        xyzsql_process_drop_index();
                        break;
                    case stmt_type::_transaction_stmt:
                        xyzsql_process_transaction();
                        break;
                    case stmt_type::_commit_stmt:
                        xyzsql_process_commit();
                        break;
                    case stmt_type::_rollback_stmt:
                        xyzsql_process_rollback();
                        break;
                    case stmt_type::_quit_stmt:
                        xyzsql_exit();
                        break;
                    case stmt_type::_exefile_stmt:
                        xyzsql_batch();
                        break;
                    default: xyzsql_unknown_stmt();
                }

                if ( stmt_queue.front().second != nullptr)
                    delete stmt_queue.front().second;
                stmt_queue.pop();

                ii++;
            }

        } catch( exception &t ) {
            cout << t.what() << endl;
            stmt_queue.pop();
        }
    }

    xyzsql_finalize();

    return 0;
}

<commit_msg>Perfect time measurement module.<commit_after>#include <readline/readline.h>
#include <readline/history.h>
#include <iostream>
#include <cctype>
#include <sstream>
#include <ctime>
#include "../parser/stmt.h"
#include "../../parser.tab.h"
#include "evaluator.h"

typedef struct yy_buffer_state *YY_BUFFER_STATE;

extern YY_BUFFER_STATE yy_scan_string (const char *yy_str  );
extern void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
extern void yy_delete_buffer (YY_BUFFER_STATE b  );
extern int yyparse ();

using namespace std;

BufferManager BufferManager;
IndexManager IndexManager(&BufferManager);
catalog_manager catm(".");
RecordManager RecordManager;

string base_addr = ".";

void system_init() {
    cout << "System Initialized!" << endl;

    RecordManager.Init(&BufferManager, &catm, &IndexManager);

}

int main() {

    system_init();

    int ii = 10;
    clock_t start_time = 0, end_time;

    while(ii < 1200) {
        if ( stmt_queue.empty() ) {
            end_time = clock();
            if (start_time != 0 ) {
                cout << (end_time - start_time) * 1000 / CLOCKS_PER_SEC << " ms used. " << end_time - start_time << endl;
            }
            char * line = readline(">>> ");
            add_history(line);
            start_time = clock();

            int len = strlen(line);
            char *tmp = new char[len + 2];
            strcpy(tmp, line);
            tmp[len + 1] = 0;

            YY_BUFFER_STATE my_string_buffer = yy_scan_string(tmp);
            yy_switch_to_buffer( my_string_buffer );
            yyparse();
            yy_delete_buffer( my_string_buffer );

            delete[] tmp;
        }

        try {
            while( !stmt_queue.empty() ) {

                switch( stmt_queue.front().first ) {
                    case stmt_type::_create_table_stmt:
                        xyzsql_process_create_table();
                        break;
                    case stmt_type::_create_index_stmt:
                        xyzsql_process_create_index();
                        break;
                    case stmt_type::_select_stmt:
                        xyzsql_process_select();
                        break;
                    case stmt_type::_insert_stmt:
                        xyzsql_process_insert();
                        break;
                    case stmt_type::_delete_stmt:
                        xyzsql_process_delete();
                        break;
                    case stmt_type::_drop_table_stmt:
                        xyzsql_process_drop_table();
                        break;
                    case stmt_type::_drop_index_stmt:
                        xyzsql_process_drop_index();
                        break;
                    case stmt_type::_transaction_stmt:
                        xyzsql_process_transaction();
                        break;
                    case stmt_type::_commit_stmt:
                        xyzsql_process_commit();
                        break;
                    case stmt_type::_rollback_stmt:
                        xyzsql_process_rollback();
                        break;
                    case stmt_type::_quit_stmt:
                        xyzsql_exit();
                        break;
                    case stmt_type::_exefile_stmt:
                        xyzsql_batch();
                        break;
                    default: xyzsql_unknown_stmt();
                }

                if ( stmt_queue.front().second != nullptr)
                    delete stmt_queue.front().second;
                stmt_queue.pop();

                ii++;
            }

        } catch( exception &t ) {
            cout << t.what() << endl;
            stmt_queue.pop();
        }
    }

    xyzsql_finalize();

    return 0;
}

<|endoftext|>


<commit_before>/*
 * C++ wrappers for the libevent callback.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef EVENT_CALLBACK_HXX
#define EVENT_CALLBACK_HXX

#include <event.h>

template<class T, void (T::*member)()>
struct SimpleEventCallback {
    static void Callback(gcc_unused evutil_socket_t fd,
                         gcc_unused short events,
                         void *ctx) {
        T &t = *(T *)ctx;
        (t.*member)();
    }
};

/* need C++ N3601 to do this without macros */
#define MakeSimpleEventCallback(T, C) SimpleEventCallback<T, &T::C>::Callback

#endif
<commit_msg>event/Callback: add missing include<commit_after>/*
 * C++ wrappers for the libevent callback.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef EVENT_CALLBACK_HXX
#define EVENT_CALLBACK_HXX

#include <inline/compiler.h>

#include <event.h>

template<class T, void (T::*member)()>
struct SimpleEventCallback {
    static void Callback(gcc_unused evutil_socket_t fd,
                         gcc_unused short events,
                         void *ctx) {
        T &t = *(T *)ctx;
        (t.*member)();
    }
};

/* need C++ N3601 to do this without macros */
#define MakeSimpleEventCallback(T, C) SimpleEventCallback<T, &T::C>::Callback

#endif
<|endoftext|>


<commit_before>//
// Created by Dawid Drozd aka Gelldur on 6/30/16.
//

#include "Fail.h"

#include <exception>

#include <log.h>

Fail::Fail(const char* fileName, const char* functionName, int lineNumber)
		: _lineNumber(lineNumber)
		, _fileName(fileName)
		, _functionName(functionName)
{
	auto srcPosition = _fileName.rfind("/src/");
	if (srcPosition != std::string::npos)
	{
		_fileName.erase(0, srcPosition);
	}
	_stream << _fileName << " " << _fileName << ":" << _lineNumber << " ";
}

void Fail::report()
{
	auto message = _stream.str();
	ILOG("Fail: %s", message.c_str());
	throw std::runtime_error(message);
}
<commit_msg>Fix GCC 4.9 include<commit_after>//
// Created by Dawid Drozd aka Gelldur on 6/30/16.
//

#include "Fail.h"

#include <stdexcept>

#include <log.h>

Fail::Fail(const char* fileName, const char* functionName, int lineNumber)
		: _lineNumber(lineNumber)
		, _fileName(fileName)
		, _functionName(functionName)
{
	auto srcPosition = _fileName.rfind("/src/");
	if (srcPosition != std::string::npos)
	{
		_fileName.erase(0, srcPosition);
	}
	_stream << _fileName << " " << _fileName << ":" << _lineNumber << " ";
}

void Fail::report()
{
	auto message = _stream.str();
	ILOG("Fail: %s", message.c_str());
	throw std::runtime_error(message);
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/file/BaseTagFS.hpp>

#include <nix/NDArray.hpp>
#include <nix/file/DataArrayFS.hpp>
#include <nix/file/BlockFS.hpp>
#include <nix/file/FeatureFS.hpp>

namespace bfs= boost::filesystem;

namespace nix {
namespace file {

BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
                     const std::string &loc)
    : EntityWithSourcesFS(file, block, loc)
{
    createSubFolders(file);
}

BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
                     const std::string &loc, const std::string &id, const std::string &type, const std::string &name)
    : BaseTagFS(file, block, loc, id, type, name, util::getTime())
{
}

BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
                     const std::string &loc, const std::string &id, const std::string &type, const std::string &name, time_t time)
    : EntityWithSourcesFS(file, block, loc, id, type, name, time)
{
    createSubFolders(file);
}

void BaseTagFS::createSubFolders(const std::shared_ptr<base::IFile> &file) {
    bfs::path refs("references");
    bfs::path feats("features");
    bfs::path p(location());

    refs_group = Directory(p / refs, file->fileMode());
    feature_group = Directory(p / feats, file->fileMode());
}

//--------------------------------------------------
// Methods concerning references.
//--------------------------------------------------

bool BaseTagFS::hasReference(const std::string &name_or_id) const {
    std::string id = name_or_id;

    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
        id = block()->getDataArray(name_or_id)->id();
    }

    return refs_group.hasObject(id);
}

ndsize_t BaseTagFS::referenceCount() const {
    return refs_group.subdirCount();
}

std::shared_ptr<base::IDataArray>  BaseTagFS::getReference(const std::string &name_or_id) const {
    std::shared_ptr<base::IDataArray> da;

    std::string id = name_or_id;
    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
        id = block()->getDataArray(name_or_id)->id();
    }

    if (hasReference(id)) {
        boost::optional<bfs::path> path = refs_group.findByNameOrAttribute("name", name_or_id);
        if (path) {
            return std::make_shared<DataArrayFS>(file(), block(), path->string());
        }
    }
    return da;
}

std::shared_ptr<base::IDataArray>  BaseTagFS::getReference(size_t index) const {
    if(index > referenceCount()) {
        throw OutOfBounds("No reference at given index", index);
    }
    bfs::path p = refs_group.sub_dir_by_index(index);
    return std::make_shared<DataArrayFS>(file(), block(), p.string());
}

void BaseTagFS::addReference(const std::string &name_or_id) {
    if (name_or_id.empty())
        throw EmptyString("addReference");

    if (!block()->hasDataArray(name_or_id))
        throw std::runtime_error("BaseTagFS::addReference: DataArray not found in block!");

    auto target = std::dynamic_pointer_cast<DataArrayFS>(block()->getDataArray(name_or_id));
    refs_group.createDirectoryLink(target->location(), target->id());
}

bool BaseTagFS::removeReference(const std::string &name_or_id) {
    return refs_group.removeObjectByNameOrAttribute("name", name_or_id);
}

void BaseTagFS::references(const std::vector<DataArray> &refs_new) {
    // extract vectors of names from vectors of new & old references
    std::vector<std::string> names_new(refs_new.size());
    transform(refs_new.begin(), refs_new.end(), names_new.begin(), util::toName<DataArray>);
    //FIXME: issue 473
    std::vector<DataArray> refs_old(static_cast<size_t>(referenceCount()));
    for (size_t i = 0; i < refs_old.size(); i++) refs_old[i] = getReference(i);
    std::vector<std::string> names_old(refs_old.size());
    std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<DataArray>);

    // sort them
    std::sort(names_new.begin(), names_new.end());
    std::sort(names_new.begin(), names_new.end());

    // get names only in names_new (add), names only in names_old (remove) & ignore rest
    std::vector<std::string> names_add;
    std::vector<std::string> names_rem;
    std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),
                        std::inserter(names_add, names_add.begin()));
    std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),
                        std::inserter(names_rem, names_rem.begin()));

    // check if all new references exist & add sources
    auto blck = std::dynamic_pointer_cast<BlockFS>(block());
    for (auto name : names_add) {
        if (!blck->hasDataArray(name))
            throw std::runtime_error("One or more data arrays do not exist in this block!");
        addReference(blck->getDataArray(name)->id());
    }
    // remove references
    for (auto name : names_rem) {
        if (!blck->hasDataArray(name))
            removeReference(blck->getDataArray(name)->id());
    }
}

//--------------------------------------------------
// Methods concerning features.
//--------------------------------------------------

bool BaseTagFS::hasFeature(const std::string &name_or_id) const {
    return !feature_group.findByNameOrAttribute("entity_id", name_or_id)->empty();
}

ndsize_t BaseTagFS::featureCount() const {
    return feature_group.subdirCount();
}

std::shared_ptr<base::IFeature> BaseTagFS::getFeature(const std::string &name_or_id) const {
    std::shared_ptr<base::IFeature> feature;
    boost::optional<bfs::path> p = feature_group.findByNameOrAttribute("name", name_or_id);
    if (p) {
        return std::make_shared<FeatureFS>(file(), block(), p->string());
    }
    return feature;
}

std::shared_ptr<base::IFeature>  BaseTagFS::getFeature(size_t index) const {
    if (index >= featureCount()) {
        throw OutOfBounds("Trying to access a feature with an invalid index!");
    }
    bfs::path id = feature_group.sub_dir_by_index(index);
    return getFeature(id.filename().string());
}

std::shared_ptr<base::IFeature>  BaseTagFS::createFeature(const std::string &name_or_id, LinkType link_type) {
    if(!block()->hasDataArray(name_or_id)) {
        throw std::runtime_error("DataArray not found in Block!");
    }
    std::string rep_id = util::createId();
    DataArray a = block()->getDataArray(name_or_id);
    return std::make_shared<FeatureFS>(file(), block(), feature_group.location(), rep_id, a, link_type);
}

bool BaseTagFS::deleteFeature(const std::string &name_or_id) {
    return feature_group.removeObjectByNameOrAttribute("name", name_or_id);
}

BaseTagFS::~BaseTagFS() {}

} // ns nix::file
} // ns nix<commit_msg>fix  issue 473 in BaseTagFS<commit_after>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/file/BaseTagFS.hpp>

#include <nix/NDArray.hpp>
#include <nix/file/DataArrayFS.hpp>
#include <nix/file/BlockFS.hpp>
#include <nix/file/FeatureFS.hpp>

namespace bfs= boost::filesystem;

namespace nix {
namespace file {

BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
                     const std::string &loc)
    : EntityWithSourcesFS(file, block, loc)
{
    createSubFolders(file);
}

BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
                     const std::string &loc, const std::string &id, const std::string &type, const std::string &name)
    : BaseTagFS(file, block, loc, id, type, name, util::getTime())
{
}

BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
                     const std::string &loc, const std::string &id, const std::string &type, const std::string &name, time_t time)
    : EntityWithSourcesFS(file, block, loc, id, type, name, time)
{
    createSubFolders(file);
}

void BaseTagFS::createSubFolders(const std::shared_ptr<base::IFile> &file) {
    bfs::path refs("references");
    bfs::path feats("features");
    bfs::path p(location());

    refs_group = Directory(p / refs, file->fileMode());
    feature_group = Directory(p / feats, file->fileMode());
}

//--------------------------------------------------
// Methods concerning references.
//--------------------------------------------------

bool BaseTagFS::hasReference(const std::string &name_or_id) const {
    std::string id = name_or_id;

    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
        id = block()->getDataArray(name_or_id)->id();
    }

    return refs_group.hasObject(id);
}

ndsize_t BaseTagFS::referenceCount() const {
    return refs_group.subdirCount();
}

std::shared_ptr<base::IDataArray>  BaseTagFS::getReference(const std::string &name_or_id) const {
    std::shared_ptr<base::IDataArray> da;

    std::string id = name_or_id;
    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
        id = block()->getDataArray(name_or_id)->id();
    }

    if (hasReference(id)) {
        boost::optional<bfs::path> path = refs_group.findByNameOrAttribute("name", name_or_id);
        if (path) {
            return std::make_shared<DataArrayFS>(file(), block(), path->string());
        }
    }
    return da;
}

std::shared_ptr<base::IDataArray>  BaseTagFS::getReference(size_t index) const {
    if(index > referenceCount()) {
        throw OutOfBounds("No reference at given index", index);
    }
    bfs::path p = refs_group.sub_dir_by_index(index);
    return std::make_shared<DataArrayFS>(file(), block(), p.string());
}

void BaseTagFS::addReference(const std::string &name_or_id) {
    if (name_or_id.empty())
        throw EmptyString("addReference");

    if (!block()->hasDataArray(name_or_id))
        throw std::runtime_error("BaseTagFS::addReference: DataArray not found in block!");

    auto target = std::dynamic_pointer_cast<DataArrayFS>(block()->getDataArray(name_or_id));
    refs_group.createDirectoryLink(target->location(), target->id());
}

bool BaseTagFS::removeReference(const std::string &name_or_id) {
    return refs_group.removeObjectByNameOrAttribute("name", name_or_id);
}

void BaseTagFS::references(const std::vector<DataArray> &refs_new) {
    // extract vectors of names from vectors of new & old references
    std::vector<std::string> names_new(refs_new.size());
    transform(refs_new.begin(), refs_new.end(), names_new.begin(), util::toName<DataArray>);

    size_t count = nix::check::fits_in_size_t(referenceCount(), "referenceCount() failed! count > than size_t!");
    std::vector<DataArray> refs_old(count);
    for (size_t i = 0; i < refs_old.size(); i++){
        refs_old[i] = getReference(i);
    }

    std::vector<std::string> names_old(refs_old.size());
    std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<DataArray>);

    // sort them
    std::sort(names_new.begin(), names_new.end());
    std::sort(names_new.begin(), names_new.end());

    // get names only in names_new (add), names only in names_old (remove) & ignore rest
    std::vector<std::string> names_add;
    std::vector<std::string> names_rem;
    std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),
                        std::inserter(names_add, names_add.begin()));
    std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),
                        std::inserter(names_rem, names_rem.begin()));

    // check if all new references exist & add sources
    auto blck = std::dynamic_pointer_cast<BlockFS>(block());
    for (auto name : names_add) {
        if (!blck->hasDataArray(name))
            throw std::runtime_error("One or more data arrays do not exist in this block!");
        addReference(blck->getDataArray(name)->id());
    }
    // remove references
    for (auto name : names_rem) {
        if (!blck->hasDataArray(name))
            removeReference(blck->getDataArray(name)->id());
    }
}

//--------------------------------------------------
// Methods concerning features.
//--------------------------------------------------

bool BaseTagFS::hasFeature(const std::string &name_or_id) const {
    return !feature_group.findByNameOrAttribute("entity_id", name_or_id)->empty();
}

ndsize_t BaseTagFS::featureCount() const {
    return feature_group.subdirCount();
}

std::shared_ptr<base::IFeature> BaseTagFS::getFeature(const std::string &name_or_id) const {
    std::shared_ptr<base::IFeature> feature;
    boost::optional<bfs::path> p = feature_group.findByNameOrAttribute("name", name_or_id);
    if (p) {
        return std::make_shared<FeatureFS>(file(), block(), p->string());
    }
    return feature;
}

std::shared_ptr<base::IFeature>  BaseTagFS::getFeature(size_t index) const {
    if (index >= featureCount()) {
        throw OutOfBounds("Trying to access a feature with an invalid index!");
    }
    bfs::path id = feature_group.sub_dir_by_index(index);
    return getFeature(id.filename().string());
}

std::shared_ptr<base::IFeature>  BaseTagFS::createFeature(const std::string &name_or_id, LinkType link_type) {
    if(!block()->hasDataArray(name_or_id)) {
        throw std::runtime_error("DataArray not found in Block!");
    }
    std::string rep_id = util::createId();
    DataArray a = block()->getDataArray(name_or_id);
    return std::make_shared<FeatureFS>(file(), block(), feature_group.location(), rep_id, a, link_type);
}

bool BaseTagFS::deleteFeature(const std::string &name_or_id) {
    return feature_group.removeObjectByNameOrAttribute("name", name_or_id);
}

BaseTagFS::~BaseTagFS() {}

} // ns nix::file
} // ns nix<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/utility/test.h"
#include "foundation/utility/unzipper.h"

// Boost headers
#include "boost/filesystem.hpp"

// Standard headers
#include <set>
#include <vector>
#include <iostream>

using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;

TEST_SUITE(Foundation_Utility_Unzipper)
{
    const string valid_project = "unit tests/inputs/test_packed_project_valid.appleseedz";
    const string invalid_project = "unit tests/inputs/test_packed_project_invalid.appleseedz";

    set<string> recursive_ls(bf::path dir)
    {
        set<string> files;

        // A default constructed directory_iterator acts as the end iterator
        bf::directory_iterator end_iter;
        for (bf::directory_iterator dir_itr(dir); dir_itr != end_iter; ++dir_itr)
        {
            const bf::path current_path = dir_itr->path();

            if (bf::is_directory(current_path))
            {
                const string dirname = current_path.filename().string();
                const set<string> files_in_subdir = recursive_ls(current_path);

                for (set<string>::iterator it = files_in_subdir.begin(); it != files_in_subdir.end(); ++it)
                    files.insert(dirname + "/" + *it);
            }
            else
                files.insert(current_path.filename().string());
        }

        return files;
    }

    TEST_CASE(UnzipTest)
    {
        const string unpacked_dir = valid_project + ".unpacked";

        try
        {
            unzip(valid_project, unpacked_dir);

            EXPECT_EQ(true, bf::exists(bf::path(unpacked_dir)));
            EXPECT_EQ(false, bf::is_empty(bf::path(unpacked_dir)));

            const string expected_files[] =
            {
                "01 - lambertiannrdf - arealight.appleseed",
                "geometry/sphere.obj",
                "geometry/Box002.binarymesh",
                "geometry/GeoSphere001.binarymesh",
                "geometry/dirpole reference sphere.obj",
                "geometry/Box001.binarymesh",
                "geometry/plane.obj",
                "geometry/Sphere002.binarymesh",
                "geometry/Plane002.binarymesh",
                "geometry/cube.obj",
                "geometry/Plane001.binarymesh"
            };

            const set<string> actual_files = recursive_ls(bf::path(unpacked_dir));

            for (size_t i = 0; i < 11; ++i)
            {
                EXPECT_EQ(1, actual_files.count(expected_files[i]));
            }

            bf::remove_all(bf::path(unpacked_dir));
        }
        catch (exception e)
        {
            bf::remove_all(bf::path(unpacked_dir));
            throw e;
        }
    }

    TEST_CASE(FilesnamesWithExtensionTest)
    {
        const string extension = ".appleseed";

        const vector<string> appleseed_files_4 = get_filenames_with_extension_from_zip(invalid_project, extension);
        const vector<string> appleseed_files_1 = get_filenames_with_extension_from_zip(valid_project, extension);

        EXPECT_EQ(4, appleseed_files_4.size());
        EXPECT_EQ(1, appleseed_files_1.size());

        EXPECT_EQ("01 - lambertiannrdf - arealight.appleseed", appleseed_files_1[0]);
    }
}
<commit_msg>Split FilesnamesWithExtensionTest test on two<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/utility/test.h"
#include "foundation/utility/unzipper.h"

// Boost headers
#include "boost/filesystem.hpp"

// Standard headers
#include <set>
#include <vector>
#include <iostream>

using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;

TEST_SUITE(Foundation_Utility_Unzipper)
{
    const string valid_project = "unit tests/inputs/test_packed_project_valid.appleseedz";
    const string invalid_project = "unit tests/inputs/test_packed_project_invalid.appleseedz";

    set<string> recursive_ls(bf::path dir)
    {
        set<string> files;

        // A default constructed directory_iterator acts as the end iterator
        bf::directory_iterator end_iter;
        for (bf::directory_iterator dir_itr(dir); dir_itr != end_iter; ++dir_itr)
        {
            const bf::path current_path = dir_itr->path();

            if (bf::is_directory(current_path))
            {
                const string dirname = current_path.filename().string();
                const set<string> files_in_subdir = recursive_ls(current_path);

                for (set<string>::iterator it = files_in_subdir.begin(); it != files_in_subdir.end(); ++it)
                    files.insert(dirname + "/" + *it);
            }
            else
                files.insert(current_path.filename().string());
        }

        return files;
    }

    TEST_CASE(UnzipTest)
    {
        const string unpacked_dir = valid_project + ".unpacked";

        try
        {
            unzip(valid_project, unpacked_dir);

            EXPECT_EQ(true, bf::exists(bf::path(unpacked_dir)));
            EXPECT_EQ(false, bf::is_empty(bf::path(unpacked_dir)));

            const string expected_files[] =
            {
                "01 - lambertiannrdf - arealight.appleseed",
                "geometry/sphere.obj",
                "geometry/Box002.binarymesh",
                "geometry/GeoSphere001.binarymesh",
                "geometry/dirpole reference sphere.obj",
                "geometry/Box001.binarymesh",
                "geometry/plane.obj",
                "geometry/Sphere002.binarymesh",
                "geometry/Plane002.binarymesh",
                "geometry/cube.obj",
                "geometry/Plane001.binarymesh"
            };

            const set<string> actual_files = recursive_ls(bf::path(unpacked_dir));

            for (size_t i = 0; i < 11; ++i)
            {
                EXPECT_EQ(1, actual_files.count(expected_files[i]));
            }

            bf::remove_all(bf::path(unpacked_dir));
        }
        catch (exception e)
        {
            bf::remove_all(bf::path(unpacked_dir));
            throw e;
        }
    }

    TEST_CASE(FilesnamesWithExtensionOneFile)
    {
        const string extension = ".appleseed";
        const vector<string> appleseed_files_1 = get_filenames_with_extension_from_zip(valid_project, extension);

        EXPECT_EQ(1, appleseed_files_1.size());
        EXPECT_EQ("01 - lambertiannrdf - arealight.appleseed", appleseed_files_1[0]);
    }

    TEST_CASE(FilesnamesWithExtensionSeveralFiles)
    {
        const string extension = ".appleseed";
        const vector<string> appleseed_files_4 = get_filenames_with_extension_from_zip(invalid_project, extension);

        EXPECT_EQ(4, appleseed_files_4.size());
    }
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <gtest/gtest.h>

#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Testing/Utils/SCIRunUnitTests.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;

namespace
{
void runTest(int basis, int expectedMatrixRows, int expectedMatrixColumns, const std::string& expectedMatrixString = "")
{
  std::cout << "Basis # " << basis << std::endl;
  FieldInformation lfi("LatVolMesh", basis, "double");

  size_type sizex = 2, sizey = 3, sizez = 4;
  Point minb(-1.0, -1.0, -1.0);
  Point maxb(1.0, 1.0, 1.0);
  MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
  FieldHandle ofh = CreateField(lfi,mesh);
  ofh->vfield()->clear_all_values();

  GetFieldBoundaryAlgo algo;

  FieldHandle boundary;
  MatrixHandle mapping;
  algo.run(ofh, boundary, mapping);

  ASSERT_TRUE(boundary.get() != nullptr);

  /// @todo: need assertions on boundary field

  if (basis != -1)
  {
    ASSERT_TRUE(mapping.get() != nullptr);
    EXPECT_EQ(expectedMatrixRows, mapping->nrows());
    EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
    std::ostringstream ostr;
    ostr << *mapping;
    //std::cout << "expected\n" << expectedMatrixString << std::endl;
    //std::cout << "actual\n" << ostr.str() << std::endl;
    EXPECT_EQ(expectedMatrixString, ostr.str());
  }
}

const std::string matrixCells =
  "1 0 0 0 0 0 \n"
  "1 0 0 0 0 0 \n"
  "1 0 0 0 0 0 \n"
  "1 0 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 0 1 0 0 0 \n"
  "0 0 1 0 0 0 \n"
  "0 0 1 0 0 0 \n"
  "0 0 0 1 0 0 \n"
  "0 0 0 1 0 0 \n"
  "0 0 0 1 0 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 0 1 \n"
  "0 0 0 0 0 1 \n"
  "0 0 0 0 0 1 \n"
  "0 0 0 0 0 1 \n";

const std::string matrixNodes =
  "1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \n";
}

TEST(GetFieldBoundaryTest, LatVolBoundary)
{
  runTest(0, 22, 6, matrixCells);
  runTest(-1, 0, 0);
  runTest(1, 24, 24, matrixNodes);

  /*
  EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
  EXPECT_EQ(0, info.dataMin);
  EXPECT_EQ(0, info.dataMax);
  EXPECT_EQ(0, info.numdata_);
  EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
  EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
  EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}

TEST(GetFieldBoundaryTest, CanLogErrorMessage)
{
  GetFieldBoundaryAlgo algo;

  FieldHandle input, output;
  MatrixHandle mapping;

  EXPECT_FALSE(algo.run(input, output, mapping));

  EXPECT_FALSE(algo.run(input, output));
}<commit_msg>Fix yet another Eigen matrix string debug diff<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <gtest/gtest.h>

#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Testing/Utils/SCIRunUnitTests.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;

namespace
{
void runTest(int basis, int expectedMatrixRows, int expectedMatrixColumns, const std::string& expectedMatrixString = "")
{
  std::cout << "Basis # " << basis << std::endl;
  FieldInformation lfi("LatVolMesh", basis, "double");

  size_type sizex = 2, sizey = 3, sizez = 4;
  Point minb(-1.0, -1.0, -1.0);
  Point maxb(1.0, 1.0, 1.0);
  MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
  FieldHandle ofh = CreateField(lfi,mesh);
  ofh->vfield()->clear_all_values();

  GetFieldBoundaryAlgo algo;

  FieldHandle boundary;
  MatrixHandle mapping;
  algo.run(ofh, boundary, mapping);

  ASSERT_TRUE(boundary.get() != nullptr);

  /// @todo: need assertions on boundary field

  if (basis != -1)
  {
    ASSERT_TRUE(mapping != nullptr);
    EXPECT_EQ(expectedMatrixRows, mapping->nrows());
    EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
    EXPECT_EQ(expectedMatrixString, matrix_to_string(*matrix_convert::to_dense(mapping)));
  }
}

const std::string matrixCells =
  "1 0 0 0 0 0 \n"
  "1 0 0 0 0 0 \n"
  "1 0 0 0 0 0 \n"
  "1 0 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 1 0 0 0 0 \n"
  "0 0 1 0 0 0 \n"
  "0 0 1 0 0 0 \n"
  "0 0 1 0 0 0 \n"
  "0 0 0 1 0 0 \n"
  "0 0 0 1 0 0 \n"
  "0 0 0 1 0 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 1 0 \n"
  "0 0 0 0 0 1 \n"
  "0 0 0 0 0 1 \n"
  "0 0 0 0 0 1 \n"
  "0 0 0 0 0 1 \n";

const std::string matrixNodes =
  "1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n"
  "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \n";
}

TEST(GetFieldBoundaryTest, LatVolBoundary)
{
  runTest(0, 22, 6, matrixCells);
  runTest(-1, 0, 0);
  runTest(1, 24, 24, matrixNodes);

  /*
  EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
  EXPECT_EQ(0, info.dataMin);
  EXPECT_EQ(0, info.dataMax);
  EXPECT_EQ(0, info.numdata_);
  EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
  EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
  EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}

TEST(GetFieldBoundaryTest, CanLogErrorMessage)
{
  GetFieldBoundaryAlgo algo;

  FieldHandle input, output;
  MatrixHandle mapping;

  EXPECT_FALSE(algo.run(input, output, mapping));

  EXPECT_FALSE(algo.run(input, output));
}<|endoftext|>


<commit_before>/*!
 * \author ddubois
 * \date 03-Sep-18.
 */

#include <future>

#include "nova_renderer.hpp"

#include "platform.hpp"
#include "util/logger.hpp"
#include "glslang/MachineIndependent/Initialize.h"
#include "loading/shaderpack/shaderpack_loading.hpp"

#if _WIN32
#include "render_engine/dx12/dx12_render_engine.hpp"
#endif

#include "render_engine/vulkan/vulkan_render_engine.hpp"

namespace nova {
    nova_renderer *nova_renderer::instance;

    nova_renderer::nova_renderer(const settings_options &settings) :
		render_settings(settings), task_scheduler(16, ttl::empty_queue_behavior::YIELD) {

        switch(settings.api) {
        case graphics_api::dx12:
            #if _WIN32
            engine = std::make_unique<dx12_render_engine>(render_settings, &task_scheduler);
            break;
            #endif
        case graphics_api::vulkan:
            engine = std::make_unique<vulkan_render_engine>(render_settings, &task_scheduler);
        }

        NOVA_LOG(DEBUG) << "Opened window";
    }

	nova_settings &nova_renderer::get_settings() {
        return render_settings;
    }

    void nova_renderer::execute_frame() {
		frame_done_future.get();
        frame_done_future = task_scheduler.add_task([](ttl::task_scheduler* task_scheduler, render_engine* engine) { engine->render_frame(); }, engine.get());
    }

    void nova_renderer::load_shaderpack(const std::string &shaderpack_name) {
        glslang::InitializeProcess();

        std::future<shaderpack_data> shaderpack_data = load_shaderpack_data(fs::path(shaderpack_name), task_scheduler);
		shaderpack_data.wait();

        engine->set_shaderpack(shaderpack_data.get());
		NOVA_LOG(INFO) << "Shaderpack " << shaderpack_name << " loaded successfully";
    }

    render_engine *nova_renderer::get_engine() const {
        return engine.get();
    }

    nova_renderer *nova_renderer::get_instance() {
        return instance;
    }

    void nova_renderer::deinitialize() {
        delete instance;
    }

	ttl::task_scheduler &nova_renderer::get_task_scheduler() {
        return task_scheduler;
    }
}  // namespace nova
<commit_msg>Commit before removing threading<commit_after>/*!
 * \author ddubois
 * \date 03-Sep-18.
 */

#include <future>

#include "nova_renderer.hpp"

#include "platform.hpp"
#include "util/logger.hpp"
#include "glslang/MachineIndependent/Initialize.h"
#include "loading/shaderpack/shaderpack_loading.hpp"

#if _WIN32
#include "render_engine/dx12/dx12_render_engine.hpp"
#endif

#include "render_engine/vulkan/vulkan_render_engine.hpp"

namespace nova {
    nova_renderer *nova_renderer::instance;

    nova_renderer::nova_renderer(const settings_options &settings) :
		render_settings(settings), task_scheduler(16, ttl::empty_queue_behavior::YIELD) {

        switch(settings.api) {
        case graphics_api::dx12:
            #if _WIN32
            engine = std::make_unique<dx12_render_engine>(render_settings, &task_scheduler);
            break;
            #endif
        case graphics_api::vulkan:
            engine = std::make_unique<vulkan_render_engine>(render_settings, &task_scheduler);
        }

        NOVA_LOG(DEBUG) << "Opened window";
    }

	nova_settings &nova_renderer::get_settings() {
        return render_settings;
    }

    void nova_renderer::execute_frame() {
		frame_done_future.wait();
		frame_done_future.get();
		try {
			frame_done_future = task_scheduler.add_task([](ttl::task_scheduler* task_scheduler, render_engine* engine) { engine->render_frame(); }, engine.get());

		} catch(const std::exception& e) {
			NOVA_LOG(ERROR) << "Could not execute frame: " << e.what();
		}
    }

    void nova_renderer::load_shaderpack(const std::string &shaderpack_name) {
        glslang::InitializeProcess();

        std::future<shaderpack_data> shaderpack_data = load_shaderpack_data(fs::path(shaderpack_name), task_scheduler);
		shaderpack_data.wait();

        engine->set_shaderpack(shaderpack_data.get());
		NOVA_LOG(INFO) << "Shaderpack " << shaderpack_name << " loaded successfully";
    }

    render_engine *nova_renderer::get_engine() const {
        return engine.get();
    }

    nova_renderer *nova_renderer::get_instance() {
        return instance;
    }

    void nova_renderer::deinitialize() {
        delete instance;
    }

	ttl::task_scheduler &nova_renderer::get_task_scheduler() {
        return task_scheduler;
    }
}  // namespace nova
<|endoftext|>