<commit_before>#include "./texture_mapper_manager.h"
#include "./utils/memory.h"
#include "./placement/cuda_texture_mapper.h"
#include "./placement/distance_transform.h"
#include "./placement/occupancy.h"
#include "./placement/apollonius.h"
#include "./utils/image_persister.h"

TextureMapperManager::TextureMapperManager(int bufferSize)
  : bufferSize(bufferSize)
{
}

TextureMapperManager::~TextureMapperManager()
{
  cleanup();
}

void TextureMapperManager::initialize(
    Graphics::Gl *gl, std::shared_ptr<Graphics::FrameBufferObject> fbo)
{
  occupancyTexture = std::make_shared<Graphics::StandardTexture2d>(
      bufferSize, bufferSize, GL_R32F);
  occupancyTexture->initialize(gl);

  distanceTransformTexture = std::make_shared<Graphics::StandardTexture2d>(
      bufferSize, bufferSize, GL_R32F);
  distanceTransformTexture->initialize(gl);

  apolloniusTexture = std::make_shared<Graphics::StandardTexture2d>(
      bufferSize, bufferSize, GL_RGBA32F);
  apolloniusTexture->initialize(gl);

  initializeMappers(fbo);
}

void TextureMapperManager::resize(int width, int height)
{
  this->width = width;
  this->height = height;
}

void TextureMapperManager::update()
{
  occupancy->runKernel();

  if (saveOccupancyInNextFrame)
  {
    saveOccupancyInNextFrame = false;
    occupancyTexture->save("occupancy.tga");
  }

  distanceTransform->run();

  if (saveDistanceTransformInNextFrame)
  {
    saveDistanceTransformInNextFrame = false;
    distanceTransformTexture->save("distanceTransform.tga");
  }

  if (saveApolloniusInNextFrame)
  {
    saveApolloniusInNextFrame = false;
    apolloniusTexture->save("apollonius.tga");
  }
}

void TextureMapperManager::bindOccupancyTexture()
{
  occupancyTexture->bind();
}

void TextureMapperManager::bindDistanceTransform()
{
  distanceTransformTexture->bind();
}

void TextureMapperManager::bindApollonius()
{
  apolloniusTexture->bind();
}

std::shared_ptr<CudaTextureMapper>
TextureMapperManager::getOccupancyTextureMapper()
{
  return occupancyTextureMapper;
}

std::shared_ptr<CudaTextureMapper>
TextureMapperManager::getDistanceTransformTextureMapper()
{
  return distanceTransformTextureMapper;
}

std::shared_ptr<CudaTextureMapper>
TextureMapperManager::getApolloniusTextureMapper()
{
  return apolloniusTextureMapper;
}

void TextureMapperManager::cleanup()
{
  occupancy.release();
  distanceTransform.release();

  colorTextureMapper.reset();
  positionsTextureMapper.reset();
  occupancyTextureMapper.reset();
  distanceTransformTextureMapper.reset();
  apolloniusTextureMapper.reset();
}

void TextureMapperManager::saveOccupancy()
{
  saveOccupancyInNextFrame = true;
}

void TextureMapperManager::saveDistanceTransform()
{
  saveDistanceTransformInNextFrame = true;
}

void TextureMapperManager::saveApollonius()
{
  saveApolloniusInNextFrame = true;
}

void TextureMapperManager::initializeMappers(
    std::shared_ptr<Graphics::FrameBufferObject> fbo)
{
  colorTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteMapper(fbo->getRenderTextureId(), width,
                                               height));

  positionsTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadOnlyMapper(fbo->getPositionTextureId(),
                                              width, height));

  distanceTransformTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteDiscardMapper(
          distanceTransformTexture->getId(),
          distanceTransformTexture->getWidth(),
          distanceTransformTexture->getHeight()));

  occupancyTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteDiscardMapper(
          occupancyTexture->getId(), occupancyTexture->getWidth(),
          occupancyTexture->getHeight()));

  apolloniusTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteDiscardMapper(
          apolloniusTexture->getId(), apolloniusTexture->getWidth(),
          apolloniusTexture->getHeight()));

  occupancy = std::make_unique<Occupancy>(positionsTextureMapper,
                                          occupancyTextureMapper);

  distanceTransform = std::make_unique<DistanceTransform>(
      occupancyTextureMapper, distanceTransformTextureMapper);
}

<commit_msg>Use tiff as texture format for buffer textures.<commit_after>#include "./texture_mapper_manager.h"
#include "./utils/memory.h"
#include "./placement/cuda_texture_mapper.h"
#include "./placement/distance_transform.h"
#include "./placement/occupancy.h"
#include "./placement/apollonius.h"
#include "./utils/image_persister.h"

TextureMapperManager::TextureMapperManager(int bufferSize)
  : bufferSize(bufferSize)
{
}

TextureMapperManager::~TextureMapperManager()
{
  cleanup();
}

void TextureMapperManager::initialize(
    Graphics::Gl *gl, std::shared_ptr<Graphics::FrameBufferObject> fbo)
{
  occupancyTexture = std::make_shared<Graphics::StandardTexture2d>(
      bufferSize, bufferSize, GL_R32F);
  occupancyTexture->initialize(gl);

  distanceTransformTexture = std::make_shared<Graphics::StandardTexture2d>(
      bufferSize, bufferSize, GL_R32F);
  distanceTransformTexture->initialize(gl);

  apolloniusTexture = std::make_shared<Graphics::StandardTexture2d>(
      bufferSize, bufferSize, GL_RGBA32F);
  apolloniusTexture->initialize(gl);

  initializeMappers(fbo);
}

void TextureMapperManager::resize(int width, int height)
{
  this->width = width;
  this->height = height;
}

void TextureMapperManager::update()
{
  occupancy->runKernel();

  if (saveOccupancyInNextFrame)
  {
    saveOccupancyInNextFrame = false;
    occupancyTexture->save("occupancy.tiff");
  }

  distanceTransform->run();

  if (saveDistanceTransformInNextFrame)
  {
    saveDistanceTransformInNextFrame = false;
    distanceTransformTexture->save("distanceTransform.tiff");
  }

  if (saveApolloniusInNextFrame)
  {
    saveApolloniusInNextFrame = false;
    apolloniusTexture->save("apollonius.tiff");
  }
}

void TextureMapperManager::bindOccupancyTexture()
{
  occupancyTexture->bind();
}

void TextureMapperManager::bindDistanceTransform()
{
  distanceTransformTexture->bind();
}

void TextureMapperManager::bindApollonius()
{
  apolloniusTexture->bind();
}

std::shared_ptr<CudaTextureMapper>
TextureMapperManager::getOccupancyTextureMapper()
{
  return occupancyTextureMapper;
}

std::shared_ptr<CudaTextureMapper>
TextureMapperManager::getDistanceTransformTextureMapper()
{
  return distanceTransformTextureMapper;
}

std::shared_ptr<CudaTextureMapper>
TextureMapperManager::getApolloniusTextureMapper()
{
  return apolloniusTextureMapper;
}

void TextureMapperManager::cleanup()
{
  occupancy.release();
  distanceTransform.release();

  colorTextureMapper.reset();
  positionsTextureMapper.reset();
  occupancyTextureMapper.reset();
  distanceTransformTextureMapper.reset();
  apolloniusTextureMapper.reset();
}

void TextureMapperManager::saveOccupancy()
{
  saveOccupancyInNextFrame = true;
}

void TextureMapperManager::saveDistanceTransform()
{
  saveDistanceTransformInNextFrame = true;
}

void TextureMapperManager::saveApollonius()
{
  saveApolloniusInNextFrame = true;
}

void TextureMapperManager::initializeMappers(
    std::shared_ptr<Graphics::FrameBufferObject> fbo)
{
  colorTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteMapper(fbo->getRenderTextureId(), width,
                                               height));

  positionsTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadOnlyMapper(fbo->getPositionTextureId(),
                                              width, height));

  distanceTransformTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteDiscardMapper(
          distanceTransformTexture->getId(),
          distanceTransformTexture->getWidth(),
          distanceTransformTexture->getHeight()));

  occupancyTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteDiscardMapper(
          occupancyTexture->getId(), occupancyTexture->getWidth(),
          occupancyTexture->getHeight()));

  apolloniusTextureMapper = std::shared_ptr<CudaTextureMapper>(
      CudaTextureMapper::createReadWriteDiscardMapper(
          apolloniusTexture->getId(), apolloniusTexture->getWidth(),
          apolloniusTexture->getHeight()));

  occupancy = std::make_unique<Occupancy>(positionsTextureMapper,
                                          occupancyTextureMapper);

  distanceTransform = std::make_unique<DistanceTransform>(
      occupancyTextureMapper, distanceTransformTextureMapper);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/
#include <iostream>

#ifdef __APPLE__
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif

#ifdef __ANDROID__
#include <android/log.h>
#endif

#include <tightdb/util/terminate.hpp>

using namespace std;

namespace tightdb {
namespace util {

#ifdef __APPLE__
void nslog(const char *message) {
    CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, message, kCFStringEncodingMacRoman);
    CFShow(str);
    CFRelease(str);
}
#endif

TIGHTDB_NORETURN void abort() TIGHTDB_NOEXCEPT
{
    std::abort();
}

TIGHTDB_NORETURN void terminate(string message, const char* file, long line) TIGHTDB_NOEXCEPT
{
    const char *support_message = "Please send the log and Realm files to help@realm.io.";
    cerr << file << ":" << line << ": " << message << endl;

#if defined __APPLE__
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char** strs = backtrace_symbols(callstack, frames);
    for (int i = 0; i < frames; ++i) {
        cerr << strs[i] << endl;
        nslog(strs[i]);
    }
    free(strs);
    nslog(support_message);
#elif defined __ANDROID__
    __android_log_print(ANDROID_LOG_ERROR, "TIGHTDB", support_message);
#else
    cerr << support_message << endl;
#endif
    abort();
}

} // namespace util
} // namespace tightdb
<commit_msg>Update wording in log message<commit_after>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/
#include <iostream>

#ifdef __APPLE__
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif

#ifdef __ANDROID__
#include <android/log.h>
#endif

#include <tightdb/util/terminate.hpp>

using namespace std;

namespace tightdb {
namespace util {

#ifdef __APPLE__
void nslog(const char *message) {
    CFStringRef str = CFStringCreateWithCString(kCFAllocatorDefault, message, kCFStringEncodingMacRoman);
    CFShow(str);
    CFRelease(str);
}
#endif

TIGHTDB_NORETURN void abort() TIGHTDB_NOEXCEPT
{
    std::abort();
}

TIGHTDB_NORETURN void terminate(string message, const char* file, long line) TIGHTDB_NOEXCEPT
{
    const char *support_message = "IMPORTANT: if you see this error, please send this log to help@realm.io.";
    cerr << file << ":" << line << ": " << message << endl;

#if defined __APPLE__
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char** strs = backtrace_symbols(callstack, frames);
    for (int i = 0; i < frames; ++i) {
        cerr << strs[i] << endl;
        nslog(strs[i]);
    }
    free(strs);
    nslog(support_message);
#elif defined __ANDROID__
    __android_log_print(ANDROID_LOG_ERROR, "TIGHTDB", support_message);
#else
    cerr << support_message << endl;
#endif
    abort();
}

} // namespace util
} // namespace tightdb
<|endoftext|>


<commit_before>// -*-Mode: C++;-*- // technically C99

// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

#include <iostream>
using std::cerr;
using std::endl;

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <streambuf>
#include <new>
#include <vector>

#include <string.h>
#include <unistd.h>

#include <string.h>

#include <include/gpu-binary.h>
#include "hpcstruct.hpp"
#include <lib/prof-lean/hpcio.h>
#include <lib/prof-lean/cpuset_hwthreads.h>
#include <lib/support/realpath.h>
#include <lib/support/FileUtil.hpp>
#include <lib/support/IOUtil.hpp>

#include <lib/support/RealPathMgr.hpp>

using namespace std;

// Function prototypes
static void create_structs_directory ( string &structs_dir);
static void open_makefile ( string &makefile_name, fstream &makefile);
static void verify_measurements_directory(string &measurements_dir);

// Contents of Makefile to be generated for the directory
static const char* analysis_makefile =
#include "pmake.h"
;

//
// For a measurements directory, write a Makefile and launch hpcstruct
// to analyze CPU and GPU binaries associated with the measurements
//

void
doMeasurementsDir
(
 Args &args,
 struct stat *sb
)
{
  std::string measurements_dir = RealPath(args.in_filenm.c_str());

  verify_measurements_directory(measurements_dir);

  //
  // Put hpctoolkit on PATH
  //
  char *path = getenv("PATH");
  string new_path = string(HPCTOOLKIT_INSTALL_PREFIX) + "/bin" + ":" + path;

  // Assume that nvdisasm is on the user's path; if not BAnal will complain

  setenv("PATH", new_path.c_str(), 1);

  // Construct full paths for hpcproftt and hpcstruct
  //
  string hpcproftt_path = string(HPCTOOLKIT_INSTALL_PREFIX)
    + "/libexec/hpctoolkit/hpcproftt";

  string hpcstruct_path = string(HPCTOOLKIT_INSTALL_PREFIX)
    + "/bin/hpcstruct";

  //
  // Write Makefile and launch analysis.
  //
  string structs_dir = measurements_dir + "/structs";
  create_structs_directory(structs_dir);

  string makefile_name = structs_dir + "/Makefile";

  fstream makefile;
  open_makefile(makefile_name, makefile);

  // Figure out how many threads and jobs are to be used
  unsigned int pthreads;
  unsigned int jobs;

  if (args.jobs == 0) { // not specified
    // Set the default: half the number of CPUs
    unsigned int hwthreads = cpuset_hwthreads();
    jobs = std::max(hwthreads/2, 1U);
    pthreads = std::min(jobs, 16U);
  } else {
    jobs = args.jobs;
    pthreads = jobs;
  }

  string cache_path;

  // Initialize the structure cache, if specified
  //
  if (!args.nocache) {
    char *cpath = NULL;

    // Find or create the actual cache directory
    try {
      cpath = setup_cache_dir(args.cache_directory.c_str(), &args);
    } catch(const Diagnostics::FatalException &e) {
      exit(1);
    };

    // How can cpath still be NULL???
    if (cpath) {
      cache_path = cpath;
      //
      // check that the cache is writable
      //
      if (!hpcstruct_cache_writable(cpath)) {
	DIAG_EMsg("hpcstruct cache directory " << cpath << " not writable");
	exit(1);
      }
    }
  }

  string gpucfg = args.compute_gpu_cfg ? "yes" : "no";

  // two threads per small binary unless concurrency is 1
  int small_jobs = (jobs >= 2) ? jobs / 2 : jobs;
  int small_threads = (jobs == 1) ? 1 : 2;

  // Write the header with definitions to the makefile
  makefile << "MEAS_DIR =  "    << measurements_dir << "\n"
 	   << "GPUBIN_CFG = "   << gpucfg << "\n"
	   << "CPU_ANALYZE = "  << args.analyze_cpu_binaries << "\n"
	   << "GPU_ANALYZE = "  << args.analyze_gpu_binaries << "\n"
	   << "PAR_SIZE = "     << args.parallel_analysis_threshold << "\n"
	   << "JOBS = "         << jobs << "\n"
	   << "SJOBS = "        << small_jobs << "\n"
	   << "STHREADS = "     << small_threads << "\n"
	   << "LJOBS = "        << jobs/pthreads << "\n"
	   << "LTHREADS = "     << pthreads << "\n"
	   << "PROFTT = "       << hpcproftt_path << "\n"
	   << "STRUCT= "        << hpcstruct_path << "\n";

  if (!cache_path.empty()) {
    makefile << "CACHE= "       << cache_path << "\n";
  } else {
    makefile << "CACHE= " << "\n";
  }

  makefile << analysis_makefile << endl;

  makefile.close();

  // Construct the make command to invoke it
  string make_cmd = string("make -C ") + structs_dir + " -k --silent "
      + " --no-print-directory all";

  // Describe the parallelism and concurrency used
  cout << "NOTE: Using a pool of " << jobs << " threads to analyze binaries in a measurement directory" << endl;
  cout << "NOTE: Analyzing each large binary of >= " << args.parallel_analysis_threshold << " bytes in parallel using " << pthreads
       << " threads" << endl;
  cout << "NOTE: Analyzing each small binary using " << small_threads <<
    " thread" << ((small_threads > 1) ? "s" : "") <<  "\n" << endl;

  // Run the make command
  //
  if (system(make_cmd.c_str()) != 0) {
    DIAG_EMsg("Running make to generate hpcstruct files for measurement directory failed.");
    exit(1);
  }

  // Write a blank line
  std::cout << std::endl;

  // and exit
  exit(0);
}

// Routine to verify that given measurements directory
// (1) is readable
// (2) contains measurement files
//
// It is invoked for a measurement-directory invocation, and for a single-binary
//    invocation with a "-M" argument
// It is never invoked for a single binary without the "-M" argument
//

void
verify_measurements_directory
(
  string &measurements_dir
)
{
  DIR *dir = opendir(measurements_dir.c_str());

  if (dir != NULL) {
    struct dirent *ent;
    bool has_hpcrun = false;
    while ((ent = readdir(dir)) != NULL) {
      string file_name(ent->d_name);
      if (file_name.find(".hpcrun") != string::npos) {
        has_hpcrun = true;
	break;
      }
    }
    closedir(dir);
    if (!has_hpcrun) {
      DIAG_EMsg("Measurements directory " << measurements_dir <<
                "does not contain any .hpcrun measurement files ");
      exit(1);
    }
  } else {
    DIAG_EMsg("Unable to open measurements directory " << measurements_dir
              << ": " << strerror(errno));
    exit(1);
  }
}

#if 0
// check if measurements directory contains a GPU binary
static bool
check_gpubin
(
  string &measurements_dir
)
{
  bool has_gpubin = false;

  string gpubin_dir = measurements_dir + "/" GPU_BINARY_DIRECTORY;

  DIR *dir = opendir(gpubin_dir.c_str());
  if (dir != NULL) {
    struct dirent *ent;
    while ((ent = readdir(dir)) != NULL) {
      string file_name(ent->d_name);
      if (file_name.find(GPU_BINARY_SUFFIX) != string::npos) {
        has_gpubin = true;
        break;
      }
    }
    closedir(dir);
  }

  return has_gpubin;
}
#endif

// Invoked for a measurements-directory handling to ensure
//  that it has a subdirectory for structure files
static void
create_structs_directory
(
  string &structs_dir
)
{
  int result_dir = mkdir(structs_dir.c_str(), 0755);

  if (result_dir != 0 && errno != EEXIST) {
    DIAG_EMsg("Unable to create results directory " << structs_dir
              << ": " << strerror(errno));
    exit(1);
  }
}

// Open the Makefile to create it.
static void
open_makefile
(
  string &makefile_name,
  fstream &makefile
)
{
  makefile.open(makefile_name, fstream::out | fstream::trunc);

  if (! makefile.is_open()) {
    DIAG_EMsg("Unable to write file: " << makefile_name);
    exit(1);
  }
}

<commit_msg>Inserted a necessary blank in the error message for no .hpcrun measurement files.<commit_after>// -*-Mode: C++;-*- // technically C99

// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

#include <iostream>
using std::cerr;
using std::endl;

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <streambuf>
#include <new>
#include <vector>

#include <string.h>
#include <unistd.h>

#include <string.h>

#include <include/gpu-binary.h>
#include "hpcstruct.hpp"
#include <lib/prof-lean/hpcio.h>
#include <lib/prof-lean/cpuset_hwthreads.h>
#include <lib/support/realpath.h>
#include <lib/support/FileUtil.hpp>
#include <lib/support/IOUtil.hpp>

#include <lib/support/RealPathMgr.hpp>

using namespace std;

// Function prototypes
static void create_structs_directory ( string &structs_dir);
static void open_makefile ( string &makefile_name, fstream &makefile);
static void verify_measurements_directory(string &measurements_dir);

// Contents of Makefile to be generated for the directory
static const char* analysis_makefile =
#include "pmake.h"
;

//
// For a measurements directory, write a Makefile and launch hpcstruct
// to analyze CPU and GPU binaries associated with the measurements
//

void
doMeasurementsDir
(
 Args &args,
 struct stat *sb
)
{
  std::string measurements_dir = RealPath(args.in_filenm.c_str());

  verify_measurements_directory(measurements_dir);

  //
  // Put hpctoolkit on PATH
  //
  char *path = getenv("PATH");
  string new_path = string(HPCTOOLKIT_INSTALL_PREFIX) + "/bin" + ":" + path;

  // Assume that nvdisasm is on the user's path; if not BAnal will complain

  setenv("PATH", new_path.c_str(), 1);

  // Construct full paths for hpcproftt and hpcstruct
  //
  string hpcproftt_path = string(HPCTOOLKIT_INSTALL_PREFIX)
    + "/libexec/hpctoolkit/hpcproftt";

  string hpcstruct_path = string(HPCTOOLKIT_INSTALL_PREFIX)
    + "/bin/hpcstruct";

  //
  // Write Makefile and launch analysis.
  //
  string structs_dir = measurements_dir + "/structs";
  create_structs_directory(structs_dir);

  string makefile_name = structs_dir + "/Makefile";

  fstream makefile;
  open_makefile(makefile_name, makefile);

  // Figure out how many threads and jobs are to be used
  unsigned int pthreads;
  unsigned int jobs;

  if (args.jobs == 0) { // not specified
    // Set the default: half the number of CPUs
    unsigned int hwthreads = cpuset_hwthreads();
    jobs = std::max(hwthreads/2, 1U);
    pthreads = std::min(jobs, 16U);
  } else {
    jobs = args.jobs;
    pthreads = jobs;
  }

  string cache_path;

  // Initialize the structure cache, if specified
  //
  if (!args.nocache) {
    char *cpath = NULL;

    // Find or create the actual cache directory
    try {
      cpath = setup_cache_dir(args.cache_directory.c_str(), &args);
    } catch(const Diagnostics::FatalException &e) {
      exit(1);
    };

    // How can cpath still be NULL???
    if (cpath) {
      cache_path = cpath;
      //
      // check that the cache is writable
      //
      if (!hpcstruct_cache_writable(cpath)) {
	DIAG_EMsg("hpcstruct cache directory " << cpath << " not writable");
	exit(1);
      }
    }
  }

  string gpucfg = args.compute_gpu_cfg ? "yes" : "no";

  // two threads per small binary unless concurrency is 1
  int small_jobs = (jobs >= 2) ? jobs / 2 : jobs;
  int small_threads = (jobs == 1) ? 1 : 2;

  // Write the header with definitions to the makefile
  makefile << "MEAS_DIR =  "    << measurements_dir << "\n"
 	   << "GPUBIN_CFG = "   << gpucfg << "\n"
	   << "CPU_ANALYZE = "  << args.analyze_cpu_binaries << "\n"
	   << "GPU_ANALYZE = "  << args.analyze_gpu_binaries << "\n"
	   << "PAR_SIZE = "     << args.parallel_analysis_threshold << "\n"
	   << "JOBS = "         << jobs << "\n"
	   << "SJOBS = "        << small_jobs << "\n"
	   << "STHREADS = "     << small_threads << "\n"
	   << "LJOBS = "        << jobs/pthreads << "\n"
	   << "LTHREADS = "     << pthreads << "\n"
	   << "PROFTT = "       << hpcproftt_path << "\n"
	   << "STRUCT= "        << hpcstruct_path << "\n";

  if (!cache_path.empty()) {
    makefile << "CACHE= "       << cache_path << "\n";
  } else {
    makefile << "CACHE= " << "\n";
  }

  makefile << analysis_makefile << endl;

  makefile.close();

  // Construct the make command to invoke it
  string make_cmd = string("make -C ") + structs_dir + " -k --silent "
      + " --no-print-directory all";

  // Describe the parallelism and concurrency used
  cout << "NOTE: Using a pool of " << jobs << " threads to analyze binaries in a measurement directory" << endl;
  cout << "NOTE: Analyzing each large binary of >= " << args.parallel_analysis_threshold << " bytes in parallel using " << pthreads
       << " threads" << endl;
  cout << "NOTE: Analyzing each small binary using " << small_threads <<
    " thread" << ((small_threads > 1) ? "s" : "") <<  "\n" << endl;

  // Run the make command
  //
  if (system(make_cmd.c_str()) != 0) {
    DIAG_EMsg("Running make to generate hpcstruct files for measurement directory failed.");
    exit(1);
  }

  // Write a blank line
  std::cout << std::endl;

  // and exit
  exit(0);
}

// Routine to verify that given measurements directory
// (1) is readable
// (2) contains measurement files
//
// It is invoked for a measurement-directory invocation, and for a single-binary
//    invocation with a "-M" argument
// It is never invoked for a single binary without the "-M" argument
//

void
verify_measurements_directory
(
  string &measurements_dir
)
{
  DIR *dir = opendir(measurements_dir.c_str());

  if (dir != NULL) {
    struct dirent *ent;
    bool has_hpcrun = false;
    while ((ent = readdir(dir)) != NULL) {
      string file_name(ent->d_name);
      if (file_name.find(".hpcrun") != string::npos) {
        has_hpcrun = true;
	break;
      }
    }
    closedir(dir);
    if (!has_hpcrun) {
      DIAG_EMsg("Measurements directory " << measurements_dir <<
                " does not contain any .hpcrun measurement files ");
      exit(1);
    }
  } else {
    DIAG_EMsg("Unable to open measurements directory " << measurements_dir
              << ": " << strerror(errno));
    exit(1);
  }
}

#if 0
// check if measurements directory contains a GPU binary
static bool
check_gpubin
(
  string &measurements_dir
)
{
  bool has_gpubin = false;

  string gpubin_dir = measurements_dir + "/" GPU_BINARY_DIRECTORY;

  DIR *dir = opendir(gpubin_dir.c_str());
  if (dir != NULL) {
    struct dirent *ent;
    while ((ent = readdir(dir)) != NULL) {
      string file_name(ent->d_name);
      if (file_name.find(GPU_BINARY_SUFFIX) != string::npos) {
        has_gpubin = true;
        break;
      }
    }
    closedir(dir);
  }

  return has_gpubin;
}
#endif

// Invoked for a measurements-directory handling to ensure
//  that it has a subdirectory for structure files
static void
create_structs_directory
(
  string &structs_dir
)
{
  int result_dir = mkdir(structs_dir.c_str(), 0755);

  if (result_dir != 0 && errno != EEXIST) {
    DIAG_EMsg("Unable to create results directory " << structs_dir
              << ": " << strerror(errno));
    exit(1);
  }
}

// Open the Makefile to create it.
static void
open_makefile
(
  string &makefile_name,
  fstream &makefile
)
{
  makefile.open(makefile_name, fstream::out | fstream::trunc);

  if (! makefile.is_open()) {
    DIAG_EMsg("Unable to write file: " << makefile_name);
    exit(1);
  }
}

<|endoftext|>


<commit_before>/* Copyright (c) 2010-2012, AOYAMA Kazuharu
 * All rights reserved.
 *
 * This software may be used and distributed according to the terms of
 * the New BSD License, which is incorporated herein by reference.
 */

#include <TSqlORMapper>
#include <TCriteria>
#include "tsessionsqlobjectstore.h"
#include "tsessionobject.h"

/*!
  \class TSessionSqlObjectStore
  \brief The TSessionSqlObjectStore class stores HTTP sessions into database
         system using object-relational mapping tool.
  \sa TSessionObject
*/

/* create table session ( id varchar(50) primary key, data blob, updated_at datetime ); */

bool TSessionSqlObjectStore::store(TSession &session)
{
    TSqlORMapper<TSessionObject> mapper;
    TCriteria cri(TSessionObject::Id, TSql::Equal, session.id());
    TSessionObject so = mapper.findFirst(cri);

    QDataStream ds(&so.data, QIODevice::WriteOnly);
    ds << *static_cast<const QVariantMap *>(&session);

    if (so.isEmpty()) {
        so.id = session.id();
        return so.create();
    }
    return so.update();
}

TSession TSessionSqlObjectStore::find(const QByteArray &id, const QDateTime &modified)
{
    TSqlORMapper<TSessionObject> mapper;
    TCriteria cri;
    cri.add(TSessionObject::Id, TSql::Equal, id);
    cri.add(TSessionObject::UpdatedAt, TSql::GreaterEqual, modified);

    TSessionObject sess = mapper.findFirst(cri);
    if (sess.isEmpty())
        return TSession();

    TSession result(id);
    QDataStream ds(&sess.data, QIODevice::ReadOnly);
    ds >> *static_cast<QVariantMap *>(&result);
    return result;
}

bool TSessionSqlObjectStore::remove(const QDateTime &garbageExpiration)
{
    TSqlORMapper<TSessionObject> mapper;
    TCriteria cri(TSessionObject::UpdatedAt, TSql::LessThan, garbageExpiration);
    int cnt = mapper.removeAll(cri);
    return (cnt >= 0);
}

bool TSessionSqlObjectStore::remove(const QByteArray &id)
{
    TSqlORMapper<TSessionObject> mapper;
    int cnt = mapper.removeAll(TCriteria(TSessionObject::Id, id));
    return (cnt > 0);
}
<commit_msg>trimmed white spaces of end of line.<commit_after>/* Copyright (c) 2010-2012, AOYAMA Kazuharu
 * All rights reserved.
 *
 * This software may be used and distributed according to the terms of
 * the New BSD License, which is incorporated herein by reference.
 */

#include <TSqlORMapper>
#include <TCriteria>
#include "tsessionsqlobjectstore.h"
#include "tsessionobject.h"

/*!
  \class TSessionSqlObjectStore
  \brief The TSessionSqlObjectStore class stores HTTP sessions into database
         system using object-relational mapping tool.
  \sa TSessionObject
*/

/* create table session ( id varchar(50) primary key, data blob, updated_at datetime ); */

bool TSessionSqlObjectStore::store(TSession &session)
{
    TSqlORMapper<TSessionObject> mapper;
    TCriteria cri(TSessionObject::Id, TSql::Equal, session.id());
    TSessionObject so = mapper.findFirst(cri);

    QDataStream ds(&so.data, QIODevice::WriteOnly);
    ds << *static_cast<const QVariantMap *>(&session);

    if (so.isEmpty()) {
        so.id = session.id();
        return so.create();
    }
    return so.update();
}

TSession TSessionSqlObjectStore::find(const QByteArray &id, const QDateTime &modified)
{
    TSqlORMapper<TSessionObject> mapper;
    TCriteria cri;
    cri.add(TSessionObject::Id, TSql::Equal, id);
    cri.add(TSessionObject::UpdatedAt, TSql::GreaterEqual, modified);

    TSessionObject sess = mapper.findFirst(cri);
    if (sess.isEmpty())
        return TSession();

    TSession result(id);
    QDataStream ds(&sess.data, QIODevice::ReadOnly);
    ds >> *static_cast<QVariantMap *>(&result);
    return result;
}

bool TSessionSqlObjectStore::remove(const QDateTime &garbageExpiration)
{
    TSqlORMapper<TSessionObject> mapper;
    TCriteria cri(TSessionObject::UpdatedAt, TSql::LessThan, garbageExpiration);
    int cnt = mapper.removeAll(cri);
    return (cnt >= 0);
}

bool TSessionSqlObjectStore::remove(const QByteArray &id)
{
    TSqlORMapper<TSessionObject> mapper;
    int cnt = mapper.removeAll(TCriteria(TSessionObject::Id, id));
    return (cnt > 0);
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 * logger.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/backend/logging/logger.cpp
 *
 *-------------------------------------------------------------------------
 */

#include "backend/logging/logger.h"

namespace peloton {
namespace logging {

/**
 * @brief Run logging_MainLoop to receive log record and flush
 */
void Logger::logging_MainLoop(void){
  proxy->logging_MainLoop();
}

/**
 * @brief Run logging_MainLoop to receive log record and flush
 */
void Logger::log(LogRecord record){
  proxy->log(record);
}

/**
 * @brief Run logging_MainLoop to receive log record and flush
 */
void Logger::flush(void){
  proxy->flush();
}

}  // namespace logging
}  // namespace peloton

<commit_msg>Minor refactoring<commit_after>/*-------------------------------------------------------------------------
 *
 * logger.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/backend/logging/logger.cpp
 *
 *-------------------------------------------------------------------------
 */

#include "backend/logging/logger.h"

namespace peloton {
namespace logging {

/**
 * @brief Run logging_MainLoop
 */
void Logger::logging_MainLoop(void){
  proxy->logging_MainLoop();
}

/**
 * @brief Run log
 * @param record
 */
void Logger::log(LogRecord record){
  proxy->log(record);
}

/**
 * @brief Run flush
 */
void Logger::flush(void){
  proxy->flush();
}

}  // namespace logging
}  // namespace peloton

<|endoftext|>


<commit_before>class myKernel: public kernel_Base {
public:
    virtual double kernel_Func(Point r0, Point r1){
        double r =  sqrt((r0.x-r1.x)*(r0.x-r1.x) + (r0.y-r1.y)*(r0.y-r1.y));
        double t0;         //implement your own kernel on the next line
          t0 = exp(pow(r,1.0/4.0)*(-1.0/3.0E1));
        return t0;
    }
};
<commit_msg>bug fixed<commit_after>class myKernel: public kernel_Base {
public:
    virtual double kernel_Func(Point r0, Point r1){
        double r =  sqrt((r0.x-r1.x)*(r0.x-r1.x) + (r0.y-r1.y)*(r0.y-r1.y));
        double t0;         //implement your own kernel on the next line
          t0 = exp(-r*r);
        if (isinf(t0)|| isnan(t0))
           return 0;
        else
        return t0;
    }
};
<|endoftext|>


<commit_before>/*
 * player.cpp
 *
 *  Created on: Mar 28, 2016
 *      Author: Tumblr
 */

#include "player.h"

Player::Player()
	:life { 10 },
	 mana { 0 } {
	// TODO Auto-generated constructor stub

}

Player::~Player() {
	// TODO Auto-generated destructor stub
}

bool Player::select_deck(Deck selected) {
	deck = selected;
	return true;
}

bool Player::draw_card() {
    if(deck.size() <= 0) {
        while(discard.size() > 0) {
            deck.add_card(discard.draw_card());
		}

        deck.shuffle();
    }

	Card* temp = deck.draw_card();
	if(temp == nullptr) return false;
	hand.add_card(temp);

    return true;
}

/*
 * Move the card in the players
 * hand at the given index into the board
 * deck.
 */
bool Player::cast(size_t cardIndex) {
	if(cardIndex >= hand.size()) return false;
	Card* temp = hand.get_card(cardIndex);
	if(temp == nullptr) return false;
	mana -= temp->get_cost();
	board.add_card(temp);
    return true;
}
<commit_msg>Added Player method comments<commit_after>/*
 * player.cpp
 *
 *  Created on: Mar 28, 2016
 *      Author: Tumblr
 */

#include "player.h"

/*
 * Default Player constructor
 */
Player::Player()
	:life { 10 },
	 mana { 0 } {
	// TODO Auto-generated constructor stub

}

/*
 * Default Player destructor
 */
Player::~Player() {
	// TODO Auto-generated destructor stub
}

/*
 * Set's the players deck to the selected deck
 */
bool Player::select_deck(Deck selected) {
	deck = selected;
	return true;
}

/*
 * Moves a card from the players deck to the players
 * hand.
 */
bool Player::draw_card() {
    if(deck.size() <= 0) {
        while(discard.size() > 0) {
            deck.add_card(discard.draw_card());
		}

        deck.shuffle();
    }

	Card* temp = deck.draw_card();
	if(temp == nullptr) return false;
	hand.add_card(temp);

    return true;
}

/*
 * Move the card in the players
 * hand at the given index into the board
 * deck.
 */
bool Player::cast(size_t cardIndex) {
	if(cardIndex >= hand.size()) return false;
	Card* temp = hand.get_card(cardIndex);
	if(temp == nullptr) return false;
	mana -= temp->get_cost();
	board.add_card(temp);
    return true;
}
<|endoftext|>


<commit_before>/*
 * This File is part of Davix, The IO library for HTTP based protocols
 * Copyright (C) 2013  Adrien Devresse <adrien.devresse@cern.ch>, CERN
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
*/

#ifndef DAVIX_TYPES_HPP
#define DAVIX_TYPES_HPP

#include <string>
#include <iostream>
#include <vector>
#include <stack>
#include <deque>
#include <typeinfo>
#include <algorithm>
#include <functional>

#include <stdint.h>
#include <sys/types.h>

#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>

#ifndef __DAVIX_INSIDE__
#error "Only davix.hpp should be included."
#endif

// type decl
#ifndef DAVIX_EXPORT
#define DAVIX_EXPORT __attribute__((visibility("default")))
#endif

struct Davix_context;
struct Davix_error;

// alias
typedef struct Davix_context* davix_sess_t;
typedef struct Davix_error* davix_error_t;
typedef struct davix_file_desc_s* davix_file_desc_t;
typedef struct davix_auth_st* davix_auth_t;
typedef struct davix_request_params* davix_params_t;

namespace Davix{
    // Davix namespace declaration
    typedef std::vector< std::pair <std::string, std::string> > HeaderVec;

} // Davix

// detect CXX11 support
#if ( (__cplusplus > 199711L) \
     || (defined (DAVIX_FORCE_CXX11)) \
     || (defined __GXX_EXPERIMENTAL_CXX0X__) )
#define DAVIX_CX11_SUPPORT
#endif

// enable TR1 for non CX11 compilation
#ifndef DAVIX_CX11_SUPPORT

#include <tr1/functional>

// bind tr1 to std for old compiler without CXX11
namespace std{
    using namespace std::tr1;
}
#endif

// Disable all non C++03 features
//#define DAVIX_STD_CXX03

// Davix Large File Support
#if  ( __WORDSIZE == 32 ) || \
        ( SIZE_MAX ==  (4294967295U) ) || \
        ( defined __WIN32 )

typedef uint64_t dav_off_t;
typedef uint64_t dav_size_t;
typedef int64_t dav_ssize_t;
#else
typedef off_t dav_off_t;
typedef size_t dav_size_t;
typedef ssize_t dav_ssize_t;
#endif

// block size
#define DAVIX_BLOCK_SIZE 4096
#define DAVIX_MAX_BLOCK_SIZE 16777216

//
// davix preproc facilities
//
#undef DAVIX_C_DECL_BEGIN
#undef DAVIX_C_DECL_END
#ifdef __cplusplus
#define DAVIX_C_DECL_BEGIN \
        extern "C" {
#define DAVIX_C_DECL_END }
#else
#define DAVIX_C_DECL_BEGIN  // void
#define DAVIX_C_DECL_END    // void
#endif

/// @class NonCopyable
/// @brief Simple NonCopyableProtector
class NonCopyable{
protected:
   NonCopyable() {}
    ~NonCopyable() {}
private:  // emphasize the following members are private
   NonCopyable( const NonCopyable& );
   const NonCopyable& operator=( const NonCopyable& );
};

#endif // DAVIX_TYPES_HPP
<commit_msg>Remove the need of tr1/functional or C++11 to compile against davix, the flag DAVIX_STD_CXX03 allows to compile in standard C++03 mode<commit_after>/*
 * This File is part of Davix, The IO library for HTTP based protocols
 * Copyright (C) 2013  Adrien Devresse <adrien.devresse@cern.ch>, CERN
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
*/

#ifndef DAVIX_TYPES_HPP
#define DAVIX_TYPES_HPP

#include <string>
#include <iostream>
#include <vector>
#include <stack>
#include <deque>
#include <typeinfo>
#include <algorithm>
#include <functional>

#include <stdint.h>
#include <sys/types.h>

#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>

#ifndef __DAVIX_INSIDE__
#error "Only davix.hpp should be included."
#endif

// type decl
#ifndef DAVIX_EXPORT
#define DAVIX_EXPORT __attribute__((visibility("default")))
#endif

struct Davix_context;
struct Davix_error;

// alias
typedef struct Davix_context* davix_sess_t;
typedef struct Davix_error* davix_error_t;
typedef struct davix_file_desc_s* davix_file_desc_t;
typedef struct davix_auth_st* davix_auth_t;
typedef struct davix_request_params* davix_params_t;

namespace Davix{
    // Davix namespace declaration
    typedef std::vector< std::pair <std::string, std::string> > HeaderVec;

} // Davix

// detect CXX11 support
#if ( (__cplusplus > 199711L) \
     || (defined (DAVIX_FORCE_CXX11)) \
     || (defined __GXX_EXPERIMENTAL_CXX0X__) )
#define DAVIX_CX11_SUPPORT
#endif

// enable TR1 for non CX11 compilation
#if (!(defined DAVIX_CX11_SUPPORT) && !(defined DAVIX_STD_CXX03))

#include <tr1/functional>

// bind tr1 to std for old compiler without CXX11
namespace std{
    using namespace std::tr1;
}
#endif

// Disable all non C++03 features
//#define DAVIX_STD_CXX03

// Davix Large File Support
#if  ( __WORDSIZE == 32 ) || \
        ( SIZE_MAX ==  (4294967295U) ) || \
        ( defined __WIN32 )

typedef uint64_t dav_off_t;
typedef uint64_t dav_size_t;
typedef int64_t dav_ssize_t;
#else
typedef off_t dav_off_t;
typedef size_t dav_size_t;
typedef ssize_t dav_ssize_t;
#endif

// block size
#define DAVIX_BLOCK_SIZE 4096
#define DAVIX_MAX_BLOCK_SIZE 16777216

//
// davix preproc facilities
//
#undef DAVIX_C_DECL_BEGIN
#undef DAVIX_C_DECL_END
#ifdef __cplusplus
#define DAVIX_C_DECL_BEGIN \
        extern "C" {
#define DAVIX_C_DECL_END }
#else
#define DAVIX_C_DECL_BEGIN  // void
#define DAVIX_C_DECL_END    // void
#endif

/// @class NonCopyable
/// @brief Simple NonCopyableProtector
class NonCopyable{
protected:
   NonCopyable() {}
    ~NonCopyable() {}
private:  // emphasize the following members are private
   NonCopyable( const NonCopyable& );
   const NonCopyable& operator=( const NonCopyable& );
};

#endif // DAVIX_TYPES_HPP
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "dll/neural_layer.hpp"

namespace dll {

/*!
 * \brief Standard convolutional layer of neural network.
 */
template <typename Desc>
struct deconv_layer final : neural_layer<deconv_layer<Desc>, Desc> {
    using desc      = Desc;
    using weight    = typename desc::weight;
    using this_type = deconv_layer<desc>;
    using base_type = neural_layer<this_type, desc>;

    static constexpr const std::size_t NV1 = desc::NV1; ///< The first dimension of the visible units
    static constexpr const std::size_t NV2 = desc::NV2; ///< The second dimension of the visible units
    static constexpr const std::size_t NW1 = desc::NW1; ///< The first dimension of the hidden units
    static constexpr const std::size_t NW2 = desc::NW2; ///< The second dimension of the hidden units
    static constexpr const std::size_t NC  = desc::NC;  ///< The number of input channels
    static constexpr const std::size_t K   = desc::K;   ///< The number of filters

    static constexpr const std::size_t NH1 = NV1 + NW1 - 1; //By definition
    static constexpr const std::size_t NH2 = NV2 + NW2 - 1; //By definition

    static constexpr const function activation_function = desc::activation_function;

    using input_one_t  = etl::fast_dyn_matrix<weight, NC, NV1, NV2>;
    using output_one_t = etl::fast_dyn_matrix<weight, K, NH1, NH2>;
    using input_t      = std::vector<input_one_t>;
    using output_t     = std::vector<output_one_t>;

    using w_type = etl::fast_matrix<weight, NC, K, NW1, NW2>;
    using b_type = etl::fast_matrix<weight, K>;

    //Weights and biases
    w_type w; //!< Weights
    b_type b; //!< Hidden biases

    //Backup weights and biases
    std::unique_ptr<w_type> bak_w; //!< Backup Weights
    std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases

    /*!
     * \brief Initialize a conv layer with basic weights.
     */
    deconv_layer() : base_type() {
        //Initialize the weights and biases following Lecun approach
        //to initialization [lecun-98b]

        w = etl::normal_generator<weight>() * std::sqrt(2.0 / double(NC * NV1 * NV2));

        if (activation_function == function::RELU) {
            b = 0.01;
        } else {
            b = etl::normal_generator<weight>() * std::sqrt(2.0 / double(NC * NV1 * NV2));
        }
    }

    static constexpr std::size_t input_size() noexcept {
        return NC * NV1 * NV2;
    }

    static constexpr std::size_t output_size() noexcept {
        return K * NH1 * NH2;
    }

    static constexpr std::size_t parameters() noexcept {
        return K * NW1 * NW2;
    }

    static std::string to_short_string() {
        char buffer[1024];
        snprintf(buffer, 1024, "Deconv: %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", NC, NV1, NV2, K, NW1, NW2, to_string(activation_function).c_str(), K, NH1, NH2);
        return {buffer};
    }

    void activate_hidden(output_one_t& output, const input_one_t& v) const {
        auto b_rep = etl::force_temporary(etl::rep<NH1, NH2>(b));

        etl::reshape<1, K, NH1, NH2>(output) = etl::conv_4d_full_flipped(etl::reshape<1, NC, NV1, NV2>(v), w);

        output = f_activate<activation_function>(b_rep + output);
    }

    template <typename V>
    void activate_hidden(output_one_t& output, const V& v) const {
        decltype(auto) converted = converter_one<V, input_one_t>::convert(*this, v);
        activate_hidden(output, converted);
    }

    template <typename H1, typename V>
    void batch_activate_hidden(H1&& output, const V& v) const {
        output = etl::conv_4d_full_flipped(v, w);

        static constexpr const auto batch_size = etl::decay_traits<H1>::template dim<0>();

        auto b_rep = etl::force_temporary(etl::rep_l<batch_size>(etl::rep<NH1, NH2>(b)));

        output = f_activate<activation_function>(b_rep + output);
    }

    template <typename Input>
    output_one_t prepare_one_output() const {
        return {};
    }

    template <typename Input>
    static output_t prepare_output(std::size_t samples) {
        return output_t{samples};
    }

    template<typename DRBM>
    static void dyn_init(DRBM& dyn){
        cpp_unused(dyn);
        //dyn.init_layer(NC, NV1, NV2, K, NH1, NH2);
    }

    template<typename C>
    void adapt_errors(C& context) const {
        if(activation_function != function::IDENTITY){
            context.errors = f_derivative<activation_function>(context.output) >> context.errors;
        }
    }

    template<typename H, typename C>
    void backward_batch(H&& output, C& context) const {
        cpp_unused(output);
        cpp_unused(context);
        //output = etl::conv_4d_full_flipped(context.errors, w);
    }

    template<typename C>
    void compute_gradients(C& context) const {
        cpp_unused(context);
        //context.w_grad = conv_4d_valid_filter_flipped(context.input, context.errors);
        //context.b_grad = etl::mean_r(etl::sum_l(context.errors));
    }
};

//Allow odr-use of the constexpr static members

template <typename Desc>
const std::size_t deconv_layer<Desc>::NV1;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NV2;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NH1;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NH2;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NC;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NW1;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NW2;

template <typename Desc>
const std::size_t deconv_layer<Desc>::K;

} //end of dll namespace
<commit_msg>Complete (a bit) deconv layer<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "dll/neural_layer.hpp"

namespace dll {

/*!
 * \brief Standard convolutional layer of neural network.
 */
template <typename Desc>
struct deconv_layer final : neural_layer<deconv_layer<Desc>, Desc> {
    using desc      = Desc;
    using weight    = typename desc::weight;
    using this_type = deconv_layer<desc>;
    using base_type = neural_layer<this_type, desc>;

    static constexpr const std::size_t NV1 = desc::NV1; ///< The first dimension of the visible units
    static constexpr const std::size_t NV2 = desc::NV2; ///< The second dimension of the visible units
    static constexpr const std::size_t NW1 = desc::NW1; ///< The first dimension of the hidden units
    static constexpr const std::size_t NW2 = desc::NW2; ///< The second dimension of the hidden units
    static constexpr const std::size_t NC  = desc::NC;  ///< The number of input channels
    static constexpr const std::size_t K   = desc::K;   ///< The number of filters

    static constexpr const std::size_t NH1 = NV1 + NW1 - 1; //By definition
    static constexpr const std::size_t NH2 = NV2 + NW2 - 1; //By definition

    static constexpr const function activation_function = desc::activation_function;

    using input_one_t  = etl::fast_dyn_matrix<weight, NC, NV1, NV2>;
    using output_one_t = etl::fast_dyn_matrix<weight, K, NH1, NH2>;
    using input_t      = std::vector<input_one_t>;
    using output_t     = std::vector<output_one_t>;

    using w_type = etl::fast_matrix<weight, NC, K, NW1, NW2>;
    using b_type = etl::fast_matrix<weight, K>;

    //Weights and biases
    w_type w; //!< Weights
    b_type b; //!< Hidden biases

    //Backup weights and biases
    std::unique_ptr<w_type> bak_w; //!< Backup Weights
    std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases

    /*!
     * \brief Initialize a conv layer with basic weights.
     */
    deconv_layer() : base_type() {
        //Initialize the weights and biases following Lecun approach
        //to initialization [lecun-98b]

        w = etl::normal_generator<weight>() * std::sqrt(2.0 / double(NC * NV1 * NV2));

        if (activation_function == function::RELU) {
            b = 0.01;
        } else {
            b = etl::normal_generator<weight>() * std::sqrt(2.0 / double(NC * NV1 * NV2));
        }
    }

    static constexpr std::size_t input_size() noexcept {
        return NC * NV1 * NV2;
    }

    static constexpr std::size_t output_size() noexcept {
        return K * NH1 * NH2;
    }

    static constexpr std::size_t parameters() noexcept {
        return K * NW1 * NW2;
    }

    static std::string to_short_string() {
        char buffer[1024];
        snprintf(buffer, 1024, "Deconv: %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", NC, NV1, NV2, K, NW1, NW2, to_string(activation_function).c_str(), K, NH1, NH2);
        return {buffer};
    }

    void activate_hidden(output_one_t& output, const input_one_t& v) const {
        auto b_rep = etl::force_temporary(etl::rep<NH1, NH2>(b));

        etl::reshape<1, K, NH1, NH2>(output) = etl::conv_4d_full_flipped(etl::reshape<1, NC, NV1, NV2>(v), w);

        output = f_activate<activation_function>(b_rep + output);
    }

    template <typename V>
    void activate_hidden(output_one_t& output, const V& v) const {
        decltype(auto) converted = converter_one<V, input_one_t>::convert(*this, v);
        activate_hidden(output, converted);
    }

    template <typename H1, typename V>
    void batch_activate_hidden(H1&& output, const V& v) const {
        output = etl::conv_4d_full_flipped(v, w);

        static constexpr const auto batch_size = etl::decay_traits<H1>::template dim<0>();

        auto b_rep = etl::force_temporary(etl::rep_l<batch_size>(etl::rep<NH1, NH2>(b)));

        output = f_activate<activation_function>(b_rep + output);
    }

    template <typename Input>
    output_one_t prepare_one_output() const {
        return {};
    }

    template <typename Input>
    static output_t prepare_output(std::size_t samples) {
        return output_t{samples};
    }

    template<typename DRBM>
    static void dyn_init(DRBM& dyn){
        cpp_unused(dyn);
        //dyn.init_layer(NC, NV1, NV2, K, NH1, NH2);
    }

    template<typename C>
    void adapt_errors(C& context) const {
        if(activation_function != function::IDENTITY){
            context.errors = f_derivative<activation_function>(context.output) >> context.errors;
        }
    }

    template<typename H, typename C>
    void backward_batch(H&& output, C& context) const {
        output = etl::conv_4d_valid_flipped(context.errors, w);
    }

    template<typename C>
    void compute_gradients(C& context) const {
        //context.w_grad = conv_4d_valid_filter(context.errors, context.input);
        context.b_grad = etl::mean_r(etl::sum_l(context.errors));
    }
};

//Allow odr-use of the constexpr static members

template <typename Desc>
const std::size_t deconv_layer<Desc>::NV1;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NV2;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NH1;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NH2;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NC;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NW1;

template <typename Desc>
const std::size_t deconv_layer<Desc>::NW2;

template <typename Desc>
const std::size_t deconv_layer<Desc>::K;

} //end of dll namespace
<|endoftext|>


<commit_before>#pragma once

#include "constants.hpp"
#include "filesystem.hpp"
#include "local_datagram/client_manager.hpp"
#include "logger.hpp"
#include "session.hpp"
#include "shared_instance_provider.hpp"
#include "types.hpp"
#include <unistd.h>
#include <vector>

namespace krbn {
class grabber_client final : public shared_instance_provider<grabber_client> {
public:
  // Signals

  // Note: These signals are fired on local_datagram::client's thread.

  boost::signals2::signal<void(void)> connected;
  boost::signals2::signal<void(const boost::system::error_code&)> connect_failed;
  boost::signals2::signal<void(void)> closed;

  // Methods

  grabber_client(const grabber_client&) = delete;

  grabber_client(void) {
  }

  void start(void) {
    std::lock_guard<std::mutex> lock(client_manager_mutex_);

    client_manager_ = nullptr;

    auto socket_file_path = constants::get_grabber_socket_file_path();
    std::chrono::milliseconds heartbeat_interval(3000);
    std::chrono::milliseconds reconnect_interval(1000);

    client_manager_ = std::make_unique<local_datagram::client_manager>(socket_file_path,
                                                                       heartbeat_interval,
                                                                       reconnect_interval);

    client_manager_->connected.connect([this](void) {
      logger::get_logger().info("grabber_client is connected.");

      connected();
    });

    client_manager_->connect_failed.connect([this](auto&& error_code) {
      connect_failed(error_code);
    });

    client_manager_->closed.connect([this](void) {
      logger::get_logger().info("grabber_client is closed.");

      closed();
    });

    client_manager_->start();
  }

  void grabbable_state_changed(grabbable_state grabbable_state) const {
    operation_type_grabbable_state_changed_struct s;
    s.grabbable_state = grabbable_state;

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void connect(void) const {
    operation_type_connect_struct s;
    s.pid = getpid();

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void system_preferences_updated(const system_preferences& system_preferences) const {
    operation_type_system_preferences_updated_struct s;
    s.system_preferences = system_preferences;

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void frontmost_application_changed(const std::string& bundle_identifier,
                                     const std::string& file_path) const {
    operation_type_frontmost_application_changed_struct s;

    strlcpy(s.bundle_identifier,
            bundle_identifier.c_str(),
            sizeof(s.bundle_identifier));

    strlcpy(s.file_path,
            file_path.c_str(),
            sizeof(s.file_path));

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void input_source_changed(const input_source_identifiers& input_source_identifiers) const {
    operation_type_input_source_changed_struct s;

    if (auto& v = input_source_identifiers.get_language()) {
      strlcpy(s.language,
              v->c_str(),
              sizeof(s.language));
    }

    if (auto& v = input_source_identifiers.get_input_source_id()) {
      strlcpy(s.input_source_id,
              v->c_str(),
              sizeof(s.input_source_id));
    }

    if (auto& v = input_source_identifiers.get_input_mode_id()) {
      strlcpy(s.input_mode_id,
              v->c_str(),
              sizeof(s.input_mode_id));
    }

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

private:
  void async_send(const uint8_t* _Nonnull p, size_t length) const {
    std::lock_guard<std::mutex> lock(client_manager_mutex_);

    if (client_manager_) {
      if (auto client = client_manager_->get_client()) {
        client->async_send(p, length);
      }
    }
  }

  std::unique_ptr<local_datagram::client_manager> client_manager_;
  mutable std::mutex client_manager_mutex_;
};
} // namespace krbn
<commit_msg>add grabber_client::stop<commit_after>#pragma once

#include "constants.hpp"
#include "filesystem.hpp"
#include "local_datagram/client_manager.hpp"
#include "logger.hpp"
#include "session.hpp"
#include "shared_instance_provider.hpp"
#include "types.hpp"
#include <unistd.h>
#include <vector>

namespace krbn {
class grabber_client final : public shared_instance_provider<grabber_client> {
public:
  // Signals

  // Note: These signals are fired on local_datagram::client's thread.

  boost::signals2::signal<void(void)> connected;
  boost::signals2::signal<void(const boost::system::error_code&)> connect_failed;
  boost::signals2::signal<void(void)> closed;

  // Methods

  grabber_client(const grabber_client&) = delete;

  grabber_client(void) : started_(false) {
  }

  void start(void) {
    std::lock_guard<std::mutex> lock(client_manager_mutex_);

    if (started_) {
      return;
    }

    started_ = true;

    client_manager_ = nullptr;

    auto socket_file_path = constants::get_grabber_socket_file_path();
    std::chrono::milliseconds heartbeat_interval(3000);
    std::chrono::milliseconds reconnect_interval(1000);

    client_manager_ = std::make_unique<local_datagram::client_manager>(socket_file_path,
                                                                       heartbeat_interval,
                                                                       reconnect_interval);

    client_manager_->connected.connect([this](void) {
      logger::get_logger().info("grabber_client is connected.");

      connected();
    });

    client_manager_->connect_failed.connect([this](auto&& error_code) {
      connect_failed(error_code);
    });

    client_manager_->closed.connect([this](void) {
      logger::get_logger().info("grabber_client is closed.");

      closed();
    });

    client_manager_->start();
  }

  void stop(void) {
    std::lock_guard<std::mutex> lock(client_manager_mutex_);

    started_ = false;

    client_manager_ = nullptr;
  }

  void grabbable_state_changed(grabbable_state grabbable_state) const {
    operation_type_grabbable_state_changed_struct s;
    s.grabbable_state = grabbable_state;

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void connect(void) const {
    operation_type_connect_struct s;
    s.pid = getpid();

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void system_preferences_updated(const system_preferences& system_preferences) const {
    operation_type_system_preferences_updated_struct s;
    s.system_preferences = system_preferences;

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void frontmost_application_changed(const std::string& bundle_identifier,
                                     const std::string& file_path) const {
    operation_type_frontmost_application_changed_struct s;

    strlcpy(s.bundle_identifier,
            bundle_identifier.c_str(),
            sizeof(s.bundle_identifier));

    strlcpy(s.file_path,
            file_path.c_str(),
            sizeof(s.file_path));

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void input_source_changed(const input_source_identifiers& input_source_identifiers) const {
    operation_type_input_source_changed_struct s;

    if (auto& v = input_source_identifiers.get_language()) {
      strlcpy(s.language,
              v->c_str(),
              sizeof(s.language));
    }

    if (auto& v = input_source_identifiers.get_input_source_id()) {
      strlcpy(s.input_source_id,
              v->c_str(),
              sizeof(s.input_source_id));
    }

    if (auto& v = input_source_identifiers.get_input_mode_id()) {
      strlcpy(s.input_mode_id,
              v->c_str(),
              sizeof(s.input_mode_id));
    }

    async_send(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

private:
  void async_send(const uint8_t* _Nonnull p, size_t length) const {
    std::lock_guard<std::mutex> lock(client_manager_mutex_);

    if (client_manager_) {
      if (auto client = client_manager_->get_client()) {
        client->async_send(p, length);
      }
    }
  }

  bool started_;

  std::unique_ptr<local_datagram::client_manager> client_manager_;
  mutable std::mutex client_manager_mutex_;
};
} // namespace krbn
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SchXMLExportHelper.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 13:21:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _XMLOFF_SCH_XMLEXPORTHELPER_HXX_
#define _XMLOFF_SCH_XMLEXPORTHELPER_HXX_

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef INCLUDED_XMLOFF_DLLAPI_H
#include "xmloff/dllapi.h"
#endif

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _UNIVERSALL_REFERENCE_HXX
#include <xmloff/uniref.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XSTRINGMAPPING_HPP_
#include <com/sun/star/util/XStringMapping.hpp>
#endif

#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif

#include "queue"

namespace com { namespace sun { namespace star {
    namespace chart {
        class XDiagram;
        class XChartDocument;
        class XChartDataArray;
        struct ChartSeriesAddress;
    }
    namespace drawing {
        class XShape;
        class XShapes;
    }
    namespace task {
        class XStatusIndicator;
    }
    namespace frame {
        class XModel;
    }
    namespace xml {
        namespace sax {
            class XAttributeList;
}}}}}

class SvXMLAutoStylePoolP;
class XMLChartExportPropertyMapper;
class SvXMLExport;
class XMLPropertyHandlerFactory;

/** With this class you can export a <chart:chart> element containing
    its data as <table:table> element or without internal table. In
    the latter case you have to provide a table address mapper if the
    cell addressing set at the document is not in XML format.
 */
class XMLOFF_DLLPUBLIC SchXMLExportHelper : public UniRefBase
{
private:
    SvXMLExport& mrExport;
    SvXMLAutoStylePoolP& mrAutoStylePool;
    UniReference< XMLPropertyHandlerFactory > mxPropertyHandlerFactory;
    UniReference< XMLPropertySetMapper > mxPropertySetMapper;
    UniReference< XMLChartExportPropertyMapper > mxExpPropMapper;
    com::sun::star::uno::Reference< com::sun::star::util::XStringMapping > mxTableAddressMapper;

    rtl::OUString msTableName;
    rtl::OUStringBuffer msStringBuffer;
    rtl::OUString msString;
    sal_Int32 mnSeriesCount;
    sal_Int32 mnSeriesLength;
    sal_Int32 mnDomainAxes;
    sal_Bool mbHasSeriesLabels, mbHasCategoryLabels;
    sal_Bool mbRowSourceColumns;

    rtl::OUString msChartAddress;
    rtl::OUString msTableNumberList;

    rtl::OUString msCLSID;

    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > mxAdditionalShapes;

    /** first parseDocument: collect autostyles and store names in this queue
        second parseDocument: export content and use names from this queue
     */
    ::std::queue< ::rtl::OUString > maAutoStyleNameQueue;
    SAL_DLLPRIVATE void CollectAutoStyle(
        const std::vector< XMLPropertyState >& aStates );
    SAL_DLLPRIVATE void AddAutoStyleAttribute(
        const std::vector< XMLPropertyState >& aStates );

    SAL_DLLPRIVATE SvXMLAutoStylePoolP& GetAutoStylePoolP()
    { return mrAutoStylePool; }

    /// if bExportContent is false the auto-styles are collected
    SAL_DLLPRIVATE void parseDocument( com::sun::star::uno::Reference<
                            com::sun::star::chart::XChartDocument >& rChartDoc,
                        sal_Bool bExportContent,
                        sal_Bool bIncludeTable = sal_False );
    SAL_DLLPRIVATE void exportTable( com::sun::star::uno::Reference<
                          com::sun::star::chart::XChartDataArray >& rData );
    SAL_DLLPRIVATE void exportPlotArea( com::sun::star::uno::Reference< com::sun::star::chart::XDiagram > xDiagram,
                         sal_Bool bExportContent,
                         sal_Bool bIncludeTable );
    SAL_DLLPRIVATE void exportAxes( com::sun::star::uno::Reference< com::sun::star::chart::XDiagram > xDiagram,
                     sal_Bool bExportContent );

    /// add svg position as attribute for current element
    SAL_DLLPRIVATE void addPosition( com::sun::star::uno::Reference< com::sun::star::drawing::XShape > xShape );
    /// add svg size as attribute for current element
    SAL_DLLPRIVATE void addSize( com::sun::star::uno::Reference< com::sun::star::drawing::XShape > xShape );
    /// fills the member msString with the appropriate String (i.e. "A3")
    SAL_DLLPRIVATE void getCellAddress( sal_Int32 nCol, sal_Int32 nRow );
    /// interchanges rows and columns of the sequence given
    SAL_DLLPRIVATE void swapDataArray( com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< double > >& rSequence );
    /// exports a string as a paragraph element
    SAL_DLLPRIVATE void exportText( const ::rtl::OUString& rText, bool bConvertTabsLFs = false );

    SAL_DLLPRIVATE SchXMLExportHelper(SchXMLExportHelper &); // not defined
    SAL_DLLPRIVATE void operator =(SchXMLExportHelper &); // not defined

public:
    SchXMLExportHelper( SvXMLExport& rExport,
                        SvXMLAutoStylePoolP& rASPool );

    virtual ~SchXMLExportHelper();

    // auto-styles
    /// parse chart and collect all auto-styles used in current pool
    void collectAutoStyles( com::sun::star::uno::Reference<
                            com::sun::star::chart::XChartDocument > rChartDoc );
    /// write the styles collected into the current pool as <style:style> elements
    void exportAutoStyles();

    // content
    /** set the string mapper that is used to convert the application format
        for cell addresses and cell range addresses into XML format

        If the mapper is set it is automatically used for conversion
        @deprecated
      */
    void setTableAddressMapper( com::sun::star::uno::Reference<
                                    com::sun::star::util::XStringMapping > xMapper )
        { mxTableAddressMapper = xMapper; }
    /** export the <chart:chart> element corresponding to rChartDoc
        if bIncludeTable is true, the chart data is exported as <table:table>
        element (inside the chart element).

        Otherwise the external references stored in the chart document are used
        for writing the corresponding attributes at series

        All attributes contained in xAttrList are written at the chart element,
        which ist the outer element of a chart. So these attributes can easily
        be parsed again by the container
     */
    void exportChart( com::sun::star::uno::Reference<
                          com::sun::star::chart::XChartDocument > rChartDoc,
                      sal_Bool bIncludeTable );

    /// returns the string corresponding to the current FileFormat CLSID for Chart
    const rtl::OUString& getChartCLSID();

    UniReference< XMLPropertySetMapper > GetPropertySetMapper() const { return mxPropertySetMapper; }

    void SetChartRangeAddress( const ::rtl::OUString& rAddress )
        { msChartAddress = rAddress; }
    void SetTableNumberList( const ::rtl::OUString& rList )
        { msTableNumberList = rList; }
};

#endif  // _XMLOFF_SCH_XMLEXPORTHELPER_HXX_
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.14); FILE MERGED 2007/04/25 08:13:04 bm 1.2.14.1: saved changes done in file on branch before move here from ..<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SchXMLExportHelper.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 16:03:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _XMLOFF_SCH_XMLEXPORTHELPER_HXX_
#define _XMLOFF_SCH_XMLEXPORTHELPER_HXX_

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef INCLUDED_XMLOFF_DLLAPI_H
#include "xmloff/dllapi.h"
#endif

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _UNIVERSALL_REFERENCE_HXX
#include <xmloff/uniref.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XSTRINGMAPPING_HPP_
#include <com/sun/star/util/XStringMapping.hpp>
#endif

#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif

#include <queue>
#include <vector>

namespace com { namespace sun { namespace star {
    namespace chart {
        class XDiagram;
        class XChartDocument;
        class XChartDataArray;
        struct ChartSeriesAddress;
    }
    namespace chart2 {
        class XDiagram;
        class XChartDocument;
        class XDataSeries;
        namespace data
        {
            class XDataProvider;
            class XDataSequence;
        }
    }
    namespace drawing {
        class XShape;
        class XShapes;
    }
    namespace task {
        class XStatusIndicator;
    }
    namespace frame {
        class XModel;
    }
    namespace xml {
        namespace sax {
            class XAttributeList;
}}}}}

class SvXMLAutoStylePoolP;
class XMLChartExportPropertyMapper;
class SvXMLExport;
class XMLPropertyHandlerFactory;

/** With this class you can export a <chart:chart> element containing
    its data as <table:table> element or without internal table. In
    the latter case you have to provide a table address mapper if the
    cell addressing set at the document is not in XML format.
 */
class XMLOFF_DLLPUBLIC SchXMLExportHelper : public UniRefBase
{
public:
    // first: data sequence for label, second: data sequence for values.
    typedef ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSequence >,
            ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSequence > > tLabelValuesDataPair;
    typedef ::std::vector< tLabelValuesDataPair > tDataSequenceCont;

private:
    SvXMLExport& mrExport;
    SvXMLAutoStylePoolP& mrAutoStylePool;
    UniReference< XMLPropertyHandlerFactory > mxPropertyHandlerFactory;
    UniReference< XMLPropertySetMapper > mxPropertySetMapper;
    UniReference< XMLChartExportPropertyMapper > mxExpPropMapper;

    rtl::OUString msTableName;
    rtl::OUStringBuffer msStringBuffer;
    rtl::OUString msString;

    // members filled by InitRangeSegmentationProperties (retrieved from DataProvider)
    sal_Bool mbHasSeriesLabels;
    sal_Bool mbHasCategoryLabels; //if the categories are only automatically generated this will be false
    sal_Bool mbRowSourceColumns;
    rtl::OUString msChartAddress;
    rtl::OUString msTableNumberList;
    ::com::sun::star::uno::Sequence< sal_Int32 > maSequenceMapping;

    rtl::OUString msCLSID;

    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > mxAdditionalShapes;

    tDataSequenceCont m_aDataSequencesToExport;

    /** first parseDocument: collect autostyles and store names in this queue
        second parseDocument: export content and use names from this queue
     */
    ::std::queue< ::rtl::OUString > maAutoStyleNameQueue;
    SAL_DLLPRIVATE void CollectAutoStyle(
        const std::vector< XMLPropertyState >& aStates );
    SAL_DLLPRIVATE void AddAutoStyleAttribute(
        const std::vector< XMLPropertyState >& aStates );

    SAL_DLLPRIVATE SvXMLAutoStylePoolP& GetAutoStylePoolP()
    { return mrAutoStylePool; }

    /// if bExportContent is false the auto-styles are collected
    SAL_DLLPRIVATE void parseDocument( com::sun::star::uno::Reference<
                            com::sun::star::chart::XChartDocument >& rChartDoc,
                        sal_Bool bExportContent,
                        sal_Bool bIncludeTable = sal_False );
    SAL_DLLPRIVATE void exportTable();
    SAL_DLLPRIVATE void exportPlotArea(
        com::sun::star::uno::Reference< com::sun::star::chart::XDiagram > xDiagram,
        com::sun::star::uno::Reference< com::sun::star::chart2::XDiagram > xNewDiagram,
        sal_Bool bExportContent,
        sal_Bool bIncludeTable );
    SAL_DLLPRIVATE void exportAxes( const com::sun::star::uno::Reference< com::sun::star::chart::XDiagram > & xDiagram,
                                    const com::sun::star::uno::Reference< com::sun::star::chart2::XDiagram > & xNewDiagram,
                                    sal_Bool bExportContent );

    SAL_DLLPRIVATE void exportSeries(
        const com::sun::star::uno::Reference< com::sun::star::chart2::XDiagram > & xNewDiagram,
        sal_Bool bExportContent,
        sal_Bool bHasTwoYAxes );
    SAL_DLLPRIVATE void exportCandleStickSeries(
        const ::com::sun::star::uno::Sequence<
            ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XDataSeries > > & aSeriesSeq,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram > & xDiagram,
        sal_Bool bJapaneseCandleSticks,
        sal_Bool bExportContent );
    SAL_DLLPRIVATE void exportDataPoints(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > & xSeriesProperties,
        sal_Int32 nSeriesLength,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram > & xDiagram,
        sal_Bool bExportContent );

    /// add svg position as attribute for current element
    SAL_DLLPRIVATE void addPosition( com::sun::star::uno::Reference< com::sun::star::drawing::XShape > xShape );
    /// add svg size as attribute for current element
    SAL_DLLPRIVATE void addSize( com::sun::star::uno::Reference< com::sun::star::drawing::XShape > xShape );
    /// fills the member msString with the appropriate String (i.e. "A3")
    SAL_DLLPRIVATE void getCellAddress( sal_Int32 nCol, sal_Int32 nRow );
    /// interchanges rows and columns of the sequence given
    SAL_DLLPRIVATE void swapDataArray( com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< double > >& rSequence );
    /// exports a string as a paragraph element
    SAL_DLLPRIVATE void exportText( const ::rtl::OUString& rText, bool bConvertTabsLFs = false );

    SAL_DLLPRIVATE SchXMLExportHelper(SchXMLExportHelper &); // not defined
    SAL_DLLPRIVATE void operator =(SchXMLExportHelper &); // not defined

public:
    SchXMLExportHelper( SvXMLExport& rExport,
                        SvXMLAutoStylePoolP& rASPool );

    virtual ~SchXMLExportHelper();

    // auto-styles
    /// parse chart and collect all auto-styles used in current pool
    void collectAutoStyles( com::sun::star::uno::Reference<
                            com::sun::star::chart::XChartDocument > rChartDoc );
    /// write the styles collected into the current pool as <style:style> elements
    void exportAutoStyles();

    /** export the <chart:chart> element corresponding to rChartDoc
        if bIncludeTable is true, the chart data is exported as <table:table>
        element (inside the chart element).

        Otherwise the external references stored in the chart document are used
        for writing the corresponding attributes at series

        All attributes contained in xAttrList are written at the chart element,
        which ist the outer element of a chart. So these attributes can easily
        be parsed again by the container
     */
    void exportChart( com::sun::star::uno::Reference<
                          com::sun::star::chart::XChartDocument > rChartDoc,
                      sal_Bool bIncludeTable );

    /// returns the string corresponding to the current FileFormat CLSID for Chart
    const rtl::OUString& getChartCLSID();

    UniReference< XMLPropertySetMapper > GetPropertySetMapper() const { return mxPropertySetMapper; }

    void SetChartRangeAddress( const ::rtl::OUString& rAddress )
        { msChartAddress = rAddress; }
    void SetTableNumberList( const ::rtl::OUString& rList )
        { msTableNumberList = rList; }

    void InitRangeSegmentationProperties(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XChartDocument > & xChartDoc );

    // if no data provider exists by, now the model (as XChild) is asked for its
    // parent which creates the data provider that is finally set at the chart
    // document
    static ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataProvider >
        GetDataProvider( const ::com::sun::star::uno::Reference<
                             ::com::sun::star::chart2::XChartDocument > & xChartDoc );
};

#endif  // _XMLOFF_SCH_XMLEXPORTHELPER_HXX_
<|endoftext|>