<commit_before>#include "pd_view.h"
#include "pd_backend.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <scintilla/include/Scintilla.h>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

struct SourceCodeData
{
    char filename[4096];
    int line;
    bool requestFiles;
    bool hasFiles;
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* readFileFromDisk(const char* file, size_t* size)
{
    FILE* f = fopen(file, "rb");
    uint8_t* data = 0;
    size_t s = 0, t = 0;

    *size = 0;

    if (!f)
        return 0;

    // TODO: Use fstat here?

    fseek(f, 0, SEEK_END);
    long ts = ftell(f);

    if (ts < 0)
        goto end;

    s = (size_t)ts;

    data = (uint8_t*)malloc(s + 16);

    if (!data)
        goto end;

    fseek(f, 0, SEEK_SET);

    t = fread(data, s, 1, f);
    (void)t;

    data[s] = 0;

    *size = s;

    end:

    fclose(f);

    return data;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
    (void)serviceFunc;
    (void)uiFuncs;
    SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData));
    memset(userData, 0, sizeof(SourceCodeData));

    userData->requestFiles = false;
    userData->hasFiles = false;

    // TODO: Temp testing code

    //parseFile(&userData->file, "examples/crashing_native/crash2.c");

    return userData;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void destroyInstance(void* userData)
{
    free(userData);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void setExceptionLocation(PDUI* uiFuncs, PDSCInterface* sourceFuncs, SourceCodeData* data, PDReader* inEvents)
{
    const char* filename;
    uint32_t line;

    // TODO: How to show this? Tell user to switch to disassembly view?

    if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound)
        return;

    if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound)
        return;

    if (strcmp(filename, data->filename))
    {
        size_t size = 0;
        void* fileData = readFileFromDisk(filename, &size);

        printf("reading file to buffer %s\n", filename);

        (void)uiFuncs;

        PDUI_setTitle(uiFuncs, filename);

        if (fileData)
		{
            PDUI_SCSendCommand(sourceFuncs, SCI_CLEARALL, 0, 0);
            PDUI_SCSendCommand(sourceFuncs, SCI_ADDTEXT, size, (intptr_t)fileData);
		}
        else
		{
            printf("Sourcecode_plugin: Unable to load %s\n", filename);
		}

        free(fileData);

        strncpy(data->filename, filename, sizeof(data->filename));
        data->filename[sizeof(data->filename) - 1] = 0;
    }

    PDUI_SCSendCommand(sourceFuncs, SCI_GOTOLINE, (uintptr_t)line, 0);

    data->line = (int)line;

    //if (strcmp(filename, data->filename))
    // PDUI_setTitle(uiFuncs, filename);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void updateKeyboard(SourceCodeData* data, PDUI* uiFuncs)
{
    (void)data;
    (void)uiFuncs;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void toggleBreakpointCurrentLine(SourceCodeData* data, PDWriter* writer)
{
    (void)data;
    (void)writer;
    /*
       // TODO: Currenty we don't handly if we set breakpoints on a line we can't

       PDWrite_eventBegin(writer, PDEventType_setBreakpoint);
       PDWrite_string(writer, "filename", data->file.filename);
       PDWrite_u32(writer, "line", (unsigned int)data->cursorPos + 1);
       PDWrite_eventEnd(writer);

       data->file.lines[data->cursorPos].breakpoint = !data->file.lines[data->cursorPos].breakpoint;
     */
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
    uint32_t event;

    (void)uiFuncs;

    SourceCodeData* data = (SourceCodeData*)userData;
    PDSCInterface* sourceFuncs = uiFuncs->scInputText("test", 800, 700, 0, 0);

    while ((event = PDRead_getEvent(inEvents)) != 0)
    {
        switch (event)
        {
            case PDEventType_setExceptionLocation:
            {
                setExceptionLocation(uiFuncs, sourceFuncs, data, inEvents);
                data->requestFiles = true;
                break;
            }

            case PDEventType_toggleBreakpointCurrentLine:
            {
                toggleBreakpointCurrentLine(data, writer);
                break;
            }

			case PDEventType_setSourceFiles:
			{
				// TODO: Store the files

                data->hasFiles = true;
				break;
			}
        }
    }

    updateKeyboard(data, uiFuncs);

    PDUI_SCUpdate(sourceFuncs);
    PDUI_SCDraw(sourceFuncs);

    //showInUI(data, uiFuncs);

    PDWrite_eventBegin(writer, PDEventType_getExceptionLocation);
    PDWrite_eventEnd(writer);

    if (!data->hasFiles && data->requestFiles)
	{
		printf("requesting files\n");
		PDWrite_eventBegin(writer, PDEventType_getSourceFiles);
		PDWrite_eventEnd(writer);
	}

    return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static PDViewPlugin plugin =
{
    "Source Code View",
    createInstance,
    destroyInstance,
    update,
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

extern "C"
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
    {
        registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
    }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

<commit_msg>Test of adding fast open shortcut<commit_after>#include "pd_view.h"
#include "pd_backend.h"
#include "pd_host.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <scintilla/include/Scintilla.h>

static const char* s_pluginName = "Source Code View";

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

struct SourceCodeData
{
    char filename[4096];
    int line;
    bool requestFiles;
    bool hasFiles;
    uint32_t fastOpenKey;
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static PDSettingsFuncs* s_settings = 0;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* readFileFromDisk(const char* file, size_t* size)
{
    FILE* f = fopen(file, "rb");
    uint8_t* data = 0;
    size_t s = 0, t = 0;

    *size = 0;

    if (!f)
        return 0;

    // TODO: Use fstat here?

    fseek(f, 0, SEEK_END);
    long ts = ftell(f);

    if (ts < 0)
        goto end;

    s = (size_t)ts;

    data = (uint8_t*)malloc(s + 16);

    if (!data)
        goto end;

    fseek(f, 0, SEEK_SET);

    t = fread(data, s, 1, f);
    (void)t;

    data[s] = 0;

    *size = s;

    end:

    fclose(f);

    return data;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
    (void)serviceFunc;
    (void)uiFuncs;
    SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData));
    memset(userData, 0, sizeof(SourceCodeData));

	s_settings = (PDSettingsFuncs*)serviceFunc(PDSETTINGS_GLOBAL);

	userData->fastOpenKey = s_settings->getShortcut(s_pluginName, "fast_open");

	printf("fastOpenKey 0x%x\n", userData->fastOpenKey);

    userData->requestFiles = false;
    userData->hasFiles = false;

    return userData;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void destroyInstance(void* userData)
{
    free(userData);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void setExceptionLocation(PDUI* uiFuncs, PDSCInterface* sourceFuncs, SourceCodeData* data, PDReader* inEvents)
{
    const char* filename;
    uint32_t line;

    // TODO: How to show this? Tell user to switch to disassembly view?

    if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound)
        return;

    if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound)
        return;

    if (strcmp(filename, data->filename))
    {
        size_t size = 0;
        void* fileData = readFileFromDisk(filename, &size);

        printf("reading file to buffer %s\n", filename);

        (void)uiFuncs;

        PDUI_setTitle(uiFuncs, filename);

        if (fileData)
		{
            PDUI_SCSendCommand(sourceFuncs, SCI_CLEARALL, 0, 0);
            PDUI_SCSendCommand(sourceFuncs, SCI_ADDTEXT, size, (intptr_t)fileData);
		}
        else
		{
            printf("Sourcecode_plugin: Unable to load %s\n", filename);
		}

        free(fileData);

        strncpy(data->filename, filename, sizeof(data->filename));
        data->filename[sizeof(data->filename) - 1] = 0;
    }

    PDUI_SCSendCommand(sourceFuncs, SCI_GOTOLINE, (uintptr_t)line, 0);

    data->line = (int)line;

    //if (strcmp(filename, data->filename))
    // PDUI_setTitle(uiFuncs, filename);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void updateKeyboard(SourceCodeData* data, PDUI* uiFuncs)
{
    (void)data;
    (void)uiFuncs;

    if (uiFuncs->isKeyDownId(data->fastOpenKey, 0))
	{
		printf("do fast open\n");
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void toggleBreakpointCurrentLine(SourceCodeData* data, PDWriter* writer)
{
    (void)data;
    (void)writer;
    /*
       // TODO: Currenty we don't handly if we set breakpoints on a line we can't

       PDWrite_eventBegin(writer, PDEventType_setBreakpoint);
       PDWrite_string(writer, "filename", data->file.filename);
       PDWrite_u32(writer, "line", (unsigned int)data->cursorPos + 1);
       PDWrite_eventEnd(writer);

       data->file.lines[data->cursorPos].breakpoint = !data->file.lines[data->cursorPos].breakpoint;
     */
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
    uint32_t event;

    (void)uiFuncs;

    SourceCodeData* data = (SourceCodeData*)userData;
    PDSCInterface* sourceFuncs = uiFuncs->scInputText("test", 800, 700, 0, 0);

    while ((event = PDRead_getEvent(inEvents)) != 0)
    {
        switch (event)
        {
            case PDEventType_setExceptionLocation:
            {
                setExceptionLocation(uiFuncs, sourceFuncs, data, inEvents);
                data->requestFiles = true;
                break;
            }

            case PDEventType_toggleBreakpointCurrentLine:
            {
                toggleBreakpointCurrentLine(data, writer);
                break;
            }

			case PDEventType_setSourceFiles:
			{
				// TODO: Store the files

                data->hasFiles = true;
				break;
			}
        }
    }

    updateKeyboard(data, uiFuncs);

    PDUI_SCUpdate(sourceFuncs);
    PDUI_SCDraw(sourceFuncs);

    //showInUI(data, uiFuncs);

    PDWrite_eventBegin(writer, PDEventType_getExceptionLocation);
    PDWrite_eventEnd(writer);

    if (!data->hasFiles && data->requestFiles)
	{
		printf("requesting files\n");
		PDWrite_eventBegin(writer, PDEventType_getSourceFiles);
		PDWrite_eventEnd(writer);
	}

    return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static PDViewPlugin plugin =
{
	"Source Code View",
    createInstance,
    destroyInstance,
    update,
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

extern "C"
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
	registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"

#include <gflags/gflags.h>

#include <mutex>

#include "xenia/base/main.h"
#include "xenia/base/math.h"
#include "xenia/base/threading.h"

DEFINE_bool(fast_stdout, false,
            "Don't lock around stdout/stderr. May introduce weirdness.");
DEFINE_bool(flush_stdout, true, "Flush stdout after each log line.");
DEFINE_bool(log_filenames, false,
            "Log filenames/line numbers in log statements.");

namespace xe {

std::mutex log_lock;

void format_log_line(char* buffer, size_t buffer_count, const char* file_path,
                     const uint32_t line_number, const char level_char,
                     const char* fmt, va_list args) {
  char* buffer_ptr;
  if (FLAGS_log_filenames) {
    // Strip out just the filename from the path.
    const char* filename = strrchr(file_path, xe::path_separator);
    if (filename) {
      // Slash - skip over it.
      filename++;
    } else {
      // No slash, entire thing is filename.
      filename = file_path;
    }

    // Format string - add a trailing newline if required.
    const char* outfmt = "%c> %.2X %s:%d: ";
    buffer_ptr = buffer + snprintf(buffer, buffer_count - 1, outfmt, level_char,
                                   xe::threading::current_thread_id(), filename,
                                   line_number);
  } else {
    buffer_ptr = buffer;
    *(buffer_ptr++) = level_char;
    *(buffer_ptr++) = '>';
    *(buffer_ptr++) = ' ';
    buffer_ptr +=
        sprintf(buffer_ptr, "%.4X", xe::threading::current_thread_id());
    *(buffer_ptr++) = ' ';
  }

  // Scribble args into the print buffer.
  buffer_ptr = buffer_ptr + vsnprintf(buffer_ptr,
                                      buffer_count - (buffer_ptr - buffer) - 1,
                                      fmt, args);

  // Add a trailing newline.
  if (buffer_ptr[-1] != '\n') {
    buffer_ptr[0] = '\n';
    buffer_ptr[1] = 0;
  }
}

thread_local char log_buffer[2048];

void log_line(const char* file_path, const uint32_t line_number,
              const char level_char, const char* fmt, ...) {
  // SCOPE_profile_cpu_i("emu", "log_line");

  va_list args;
  va_start(args, fmt);
  format_log_line(log_buffer, xe::countof(log_buffer), file_path, line_number,
                  level_char, fmt, args);
  va_end(args);

  if (!FLAGS_fast_stdout) {
    log_lock.lock();
  }
#if 0  // defined(OutputDebugString)
  OutputDebugStringA(log_buffer);
#else
  fprintf(stdout, "%s", log_buffer);
  if (FLAGS_flush_stdout) {
    fflush(stdout);
  }
#endif  // OutputDebugString
  if (!FLAGS_fast_stdout) {
    log_lock.unlock();
  }
}

void handle_fatal(const char* file_path, const uint32_t line_number,
                  const char* fmt, ...) {
  char buffer[2048];
  va_list args;
  va_start(args, fmt);
  format_log_line(buffer, xe::countof(buffer), file_path, line_number, 'X', fmt,
                  args);
  va_end(args);

  if (!FLAGS_fast_stdout) {
    log_lock.lock();
  }
#if defined(OutputDebugString)
  OutputDebugStringA(buffer);
#else
  fprintf(stderr, "%s", buffer);
  fflush(stderr);
#endif  // OutputDebugString
  if (!FLAGS_fast_stdout) {
    log_lock.unlock();
  }

#if XE_PLATFORM_WIN32
  if (!xe::has_console_attached()) {
    MessageBoxA(NULL, buffer, "Xenia Error",
                MB_OK | MB_ICONERROR | MB_APPLMODAL | MB_SETFOREGROUND);
  }
#endif  // WIN32

  exit(1);
}

}  // namespace xe
<commit_msg>Make the log buffer stupid large.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"

#include <gflags/gflags.h>

#include <mutex>

#include "xenia/base/main.h"
#include "xenia/base/math.h"
#include "xenia/base/threading.h"

DEFINE_bool(fast_stdout, false,
            "Don't lock around stdout/stderr. May introduce weirdness.");
DEFINE_bool(flush_stdout, true, "Flush stdout after each log line.");
DEFINE_bool(log_filenames, false,
            "Log filenames/line numbers in log statements.");

namespace xe {

std::mutex log_lock;

void format_log_line(char* buffer, size_t buffer_count, const char* file_path,
                     const uint32_t line_number, const char level_char,
                     const char* fmt, va_list args) {
  char* buffer_ptr;
  if (FLAGS_log_filenames) {
    // Strip out just the filename from the path.
    const char* filename = strrchr(file_path, xe::path_separator);
    if (filename) {
      // Slash - skip over it.
      filename++;
    } else {
      // No slash, entire thing is filename.
      filename = file_path;
    }

    // Format string - add a trailing newline if required.
    const char* outfmt = "%c> %.2X %s:%d: ";
    buffer_ptr = buffer + snprintf(buffer, buffer_count - 1, outfmt, level_char,
                                   xe::threading::current_thread_id(), filename,
                                   line_number);
  } else {
    buffer_ptr = buffer;
    *(buffer_ptr++) = level_char;
    *(buffer_ptr++) = '>';
    *(buffer_ptr++) = ' ';
    buffer_ptr +=
        sprintf(buffer_ptr, "%.4X", xe::threading::current_thread_id());
    *(buffer_ptr++) = ' ';
  }

  // Scribble args into the print buffer.
  buffer_ptr = buffer_ptr + vsnprintf(buffer_ptr,
                                      buffer_count - (buffer_ptr - buffer) - 1,
                                      fmt, args);

  // Add a trailing newline.
  if (buffer_ptr[-1] != '\n') {
    buffer_ptr[0] = '\n';
    buffer_ptr[1] = 0;
  }
}

thread_local char log_buffer[16 * 1024];

void log_line(const char* file_path, const uint32_t line_number,
              const char level_char, const char* fmt, ...) {
  // SCOPE_profile_cpu_i("emu", "log_line");

  va_list args;
  va_start(args, fmt);
  format_log_line(log_buffer, xe::countof(log_buffer), file_path, line_number,
                  level_char, fmt, args);
  va_end(args);

  if (!FLAGS_fast_stdout) {
    log_lock.lock();
  }
#if 0  // defined(OutputDebugString)
  OutputDebugStringA(log_buffer);
#else
  fprintf(stdout, "%s", log_buffer);
  if (FLAGS_flush_stdout) {
    fflush(stdout);
  }
#endif  // OutputDebugString
  if (!FLAGS_fast_stdout) {
    log_lock.unlock();
  }
}

void handle_fatal(const char* file_path, const uint32_t line_number,
                  const char* fmt, ...) {
  char buffer[2048];
  va_list args;
  va_start(args, fmt);
  format_log_line(buffer, xe::countof(buffer), file_path, line_number, 'X', fmt,
                  args);
  va_end(args);

  if (!FLAGS_fast_stdout) {
    log_lock.lock();
  }
#if defined(OutputDebugString)
  OutputDebugStringA(buffer);
#else
  fprintf(stderr, "%s", buffer);
  fflush(stderr);
#endif  // OutputDebugString
  if (!FLAGS_fast_stdout) {
    log_lock.unlock();
  }

#if XE_PLATFORM_WIN32
  if (!xe::has_console_attached()) {
    MessageBoxA(NULL, buffer, "Xenia Error",
                MB_OK | MB_ICONERROR | MB_APPLMODAL | MB_SETFOREGROUND);
  }
#endif  // WIN32

  exit(1);
}

}  // namespace xe
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle 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. */
#define GLOG_NO_ABBREVIATED_SEVERITIES

#include "paddle/fluid/memory/detail/system_allocator.h"

#ifdef _WIN32
#include <malloc.h>
#include <windows.h>  // VirtualLock/VirtualUnlock
#else
#include <sys/mman.h>  // for mlock and munlock
#endif
#include <stdlib.h>   // for malloc and free
#include <algorithm>  // for std::max

#include "gflags/gflags.h"
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/platform/cpu_info.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/gpu_info.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif

DECLARE_bool(use_pinned_memory);
DECLARE_double(fraction_of_gpu_memory_to_use);
DECLARE_uint64(initial_gpu_memory_in_mb);
DECLARE_uint64(reallocate_gpu_memory_in_mb);

namespace paddle {
namespace memory {
namespace detail {

void* AlignedMalloc(size_t size) {
  void* p = nullptr;
  size_t alignment = 32ul;
#ifdef PADDLE_WITH_MKLDNN
  // refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp
  // memory alignment
  alignment = 4096ul;
#endif
#ifdef _WIN32
  p = _aligned_malloc(size, alignment);
#else
  PADDLE_ENFORCE_EQ(posix_memalign(&p, alignment, size), 0, "Alloc %ld error!",
                    size);
#endif
  PADDLE_ENFORCE_NOT_NULL(p, "Fail to allocate CPU memory: size = %d .", size);
  return p;
}

void* CPUAllocator::Alloc(size_t* index, size_t size) {
  // According to http://www.cplusplus.com/reference/cstdlib/malloc/,
  // malloc might not return nullptr if size is zero, but the returned
  // pointer shall not be dereferenced -- so we make it nullptr.
  if (size <= 0) return nullptr;

  *index = 0;  // unlock memory

  void* p = AlignedMalloc(size);

  if (p != nullptr) {
    if (FLAGS_use_pinned_memory) {
      *index = 1;
#ifdef _WIN32
      VirtualLock(p, size);
#else
      mlock(p, size);  // lock memory
#endif
    }
  }

  return p;
}

void CPUAllocator::Free(void* p, size_t size, size_t index) {
  if (p != nullptr && index == 1) {
#ifdef _WIN32
    VirtualUnlock(p, size);
#else
    munlock(p, size);
#endif
  }
#ifdef _WIN32
  _aligned_free(p);
#else
  free(p);
#endif
}

bool CPUAllocator::UseGpu() const { return false; }

#ifdef PADDLE_WITH_CUDA

void* GPUAllocator::Alloc(size_t* index, size_t size) {
  // CUDA documentation doesn't explain if cudaMalloc returns nullptr
  // if size is 0.  We just make sure it does.
  if (size <= 0) return nullptr;

  paddle::platform::CUDADeviceGuard guard(gpu_id_);

  void* p;
  cudaError_t result = cudaMalloc(&p, size);

  if (result == cudaSuccess) {
    *index = 0;
    gpu_alloc_size_ += size;
    return p;
  } else {
    PADDLE_THROW_BAD_ALLOC(
        "Cannot malloc " + std::to_string(size / 1024.0 / 1024.0) +
        " MB GPU memory. Please shrink "
        "FLAGS_fraction_of_gpu_memory_to_use or "
        "FLAGS_initial_gpu_memory_in_mb or "
        "FLAGS_reallocate_gpu_memory_in_mb"
        "environment variable to a lower value. " +
        "Current FLAGS_fraction_of_gpu_memory_to_use value is " +
        std::to_string(FLAGS_fraction_of_gpu_memory_to_use) +
        ". Current FLAGS_initial_gpu_memory_in_mb value is " +
        std::to_string(FLAGS_initial_gpu_memory_in_mb) +
        ". Current FLAGS_reallocate_gpu_memory_in_mb value is " +
        std::to_string(FLAGS_reallocate_gpu_memory_in_mb));
  }
}

void GPUAllocator::Free(void* p, size_t size, size_t index) {
  cudaError_t err;
  PADDLE_ENFORCE_EQ(index, 0);
  PADDLE_ENFORCE_GE(gpu_alloc_size_, size);
  gpu_alloc_size_ -= size;
  err = cudaFree(p);

  // Purposefully allow cudaErrorCudartUnloading, because
  // that is returned if you ever call cudaFree after the
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
  // cudaFree succeeds.
  if (err != cudaErrorCudartUnloading) {
    PADDLE_ENFORCE(err, "cudaFree{Host} failed in GPUAllocator::Free.");
  }
}

bool GPUAllocator::UseGpu() const { return true; }

// PINNED memory allows direct DMA transfers by the GPU to and from system
// memory. It’s locked to a physical address.
void* CUDAPinnedAllocator::Alloc(size_t* index, size_t size) {
  if (size <= 0) return nullptr;

  // NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size
  // of host pinned allocation. Allocates too much would reduce
  // the amount of memory available to the underlying system for paging.
  size_t usable =
      paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_;

  if (size > usable) {
    LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0
                 << " MB pinned memory."
                 << ", available " << usable / 1024.0 / 1024.0 << " MB";
    return nullptr;
  }

  void* p;
  // PINNED memory is visible to all CUDA contexts.
  cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable);

  if (result == cudaSuccess) {
    *index = 1;  // PINNED memory
    cuda_pinnd_alloc_size_ += size;
    return p;
  } else {
    LOG(WARNING) << "cudaHostAlloc failed.";
    return nullptr;
  }

  return nullptr;
}

void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) {
  cudaError_t err;
  PADDLE_ENFORCE_EQ(index, 1);

  PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_, size);
  cuda_pinnd_alloc_size_ -= size;
  err = cudaFreeHost(p);

  // Purposefully allow cudaErrorCudartUnloading, because
  // that is returned if you ever call cudaFreeHost after the
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
  // cudaFreeHost succeeds.
  if (err != cudaErrorCudartUnloading) {
    PADDLE_ENFORCE(err, "cudaFreeHost failed in GPUPinnedAllocator::Free.");
  }
}

bool CUDAPinnedAllocator::UseGpu() const { return false; }

#endif

}  // namespace detail
}  // namespace memory
}  // namespace paddle
<commit_msg>fix typo of allocator, test=develop (#19578)<commit_after>/* Copyright (c) 2016 PaddlePaddle 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. */
#define GLOG_NO_ABBREVIATED_SEVERITIES

#include "paddle/fluid/memory/detail/system_allocator.h"

#ifdef _WIN32
#include <malloc.h>
#include <windows.h>  // VirtualLock/VirtualUnlock
#else
#include <sys/mman.h>  // for mlock and munlock
#endif
#include <stdlib.h>   // for malloc and free
#include <algorithm>  // for std::max

#include "gflags/gflags.h"
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/platform/cpu_info.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/gpu_info.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif

DECLARE_bool(use_pinned_memory);
DECLARE_double(fraction_of_gpu_memory_to_use);
DECLARE_uint64(initial_gpu_memory_in_mb);
DECLARE_uint64(reallocate_gpu_memory_in_mb);

namespace paddle {
namespace memory {
namespace detail {

void* AlignedMalloc(size_t size) {
  void* p = nullptr;
  size_t alignment = 32ul;
#ifdef PADDLE_WITH_MKLDNN
  // refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp
  // memory alignment
  alignment = 4096ul;
#endif
#ifdef _WIN32
  p = _aligned_malloc(size, alignment);
#else
  PADDLE_ENFORCE_EQ(posix_memalign(&p, alignment, size), 0, "Alloc %ld error!",
                    size);
#endif
  PADDLE_ENFORCE_NOT_NULL(p, "Fail to allocate CPU memory: size = %d .", size);
  return p;
}

void* CPUAllocator::Alloc(size_t* index, size_t size) {
  // According to http://www.cplusplus.com/reference/cstdlib/malloc/,
  // malloc might not return nullptr if size is zero, but the returned
  // pointer shall not be dereferenced -- so we make it nullptr.
  if (size <= 0) return nullptr;

  *index = 0;  // unlock memory

  void* p = AlignedMalloc(size);

  if (p != nullptr) {
    if (FLAGS_use_pinned_memory) {
      *index = 1;
#ifdef _WIN32
      VirtualLock(p, size);
#else
      mlock(p, size);  // lock memory
#endif
    }
  }

  return p;
}

void CPUAllocator::Free(void* p, size_t size, size_t index) {
  if (p != nullptr && index == 1) {
#ifdef _WIN32
    VirtualUnlock(p, size);
#else
    munlock(p, size);
#endif
  }
#ifdef _WIN32
  _aligned_free(p);
#else
  free(p);
#endif
}

bool CPUAllocator::UseGpu() const { return false; }

#ifdef PADDLE_WITH_CUDA

void* GPUAllocator::Alloc(size_t* index, size_t size) {
  // CUDA documentation doesn't explain if cudaMalloc returns nullptr
  // if size is 0.  We just make sure it does.
  if (size <= 0) return nullptr;

  paddle::platform::CUDADeviceGuard guard(gpu_id_);

  void* p;
  cudaError_t result = cudaMalloc(&p, size);

  if (result == cudaSuccess) {
    *index = 0;
    gpu_alloc_size_ += size;
    return p;
  } else {
    PADDLE_THROW_BAD_ALLOC(
        "Cannot malloc " + std::to_string(size / 1024.0 / 1024.0) +
        " MB GPU memory. Please shrink "
        "FLAGS_fraction_of_gpu_memory_to_use or "
        "FLAGS_initial_gpu_memory_in_mb or "
        "FLAGS_reallocate_gpu_memory_in_mb "
        "environment variable to a lower value. " +
        "Current FLAGS_fraction_of_gpu_memory_to_use value is " +
        std::to_string(FLAGS_fraction_of_gpu_memory_to_use) +
        ". Current FLAGS_initial_gpu_memory_in_mb value is " +
        std::to_string(FLAGS_initial_gpu_memory_in_mb) +
        ". Current FLAGS_reallocate_gpu_memory_in_mb value is " +
        std::to_string(FLAGS_reallocate_gpu_memory_in_mb));
  }
}

void GPUAllocator::Free(void* p, size_t size, size_t index) {
  cudaError_t err;
  PADDLE_ENFORCE_EQ(index, 0);
  PADDLE_ENFORCE_GE(gpu_alloc_size_, size);
  gpu_alloc_size_ -= size;
  err = cudaFree(p);

  // Purposefully allow cudaErrorCudartUnloading, because
  // that is returned if you ever call cudaFree after the
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
  // cudaFree succeeds.
  if (err != cudaErrorCudartUnloading) {
    PADDLE_ENFORCE(err, "cudaFree{Host} failed in GPUAllocator::Free.");
  }
}

bool GPUAllocator::UseGpu() const { return true; }

// PINNED memory allows direct DMA transfers by the GPU to and from system
// memory. It’s locked to a physical address.
void* CUDAPinnedAllocator::Alloc(size_t* index, size_t size) {
  if (size <= 0) return nullptr;

  // NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size
  // of host pinned allocation. Allocates too much would reduce
  // the amount of memory available to the underlying system for paging.
  size_t usable =
      paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_;

  if (size > usable) {
    LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0
                 << " MB pinned memory."
                 << ", available " << usable / 1024.0 / 1024.0 << " MB";
    return nullptr;
  }

  void* p;
  // PINNED memory is visible to all CUDA contexts.
  cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable);

  if (result == cudaSuccess) {
    *index = 1;  // PINNED memory
    cuda_pinnd_alloc_size_ += size;
    return p;
  } else {
    LOG(WARNING) << "cudaHostAlloc failed.";
    return nullptr;
  }

  return nullptr;
}

void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) {
  cudaError_t err;
  PADDLE_ENFORCE_EQ(index, 1);

  PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_, size);
  cuda_pinnd_alloc_size_ -= size;
  err = cudaFreeHost(p);

  // Purposefully allow cudaErrorCudartUnloading, because
  // that is returned if you ever call cudaFreeHost after the
  // driver has already shutdown. This happens only if the
  // process is terminating, in which case we don't care if
  // cudaFreeHost succeeds.
  if (err != cudaErrorCudartUnloading) {
    PADDLE_ENFORCE(err, "cudaFreeHost failed in GPUPinnedAllocator::Free.");
  }
}

bool CUDAPinnedAllocator::UseGpu() const { return false; }

#endif

}  // namespace detail
}  // namespace memory
}  // namespace paddle
<|endoftext|>


<commit_before>#include "recordserializer.hh"
#include "registrardb-redis.hh"
#include "common.hh"

#include <algorithm>

#include "configmanager.hh"

#include <hiredis/hiredis.h>

#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_wait.h>

#include <memory>

using namespace std;

bool sUseSyslog;

struct DumpListener : public RegistrarDbListener {

private:
	su_root_t* root;

private:
	void su_break(){
		if( root ){
			su_root_break(root);
		}
	}

public:
	bool listenerError = false;

public:
	DumpListener(su_root_t* _root) : RegistrarDbListener(), root(_root) {}

	virtual void onRecordFound(Record *record) {
		if (record) cout << *record           << endl;
		else        cout << "No record found" << endl;
		su_break();
	}
	virtual void onError() {
		SLOGE << "Connection error, aborting" <<  endl;
		listenerError = true;
		su_break();
	}
	virtual void onInvalid() {
		SLOGW << "Invalid" << endl;
		listenerError = true;
		su_break();
	}
};

struct CTArgs {
	bool debug;
	RedisParameters redis;
	string serializer;
	string url;

	static void usage(const char *app) {
		CTArgs args;
		cout << app << " -t host[" << args.redis.domain << "] "
			<< "-p port[" << args.redis.port << "] "
			<< "--debug "
			<< "-a auth "
			<< "-s serializer[" << args.serializer << "] "
			<< "sip_uri " << endl;
	}

	CTArgs() {
		debug = false;
		redis.port=6379;
		redis.timeout = 2000;
		redis.domain = "sip";
		serializer = "protobuf";
	}

	void parse(int argc, char **argv) {
		#define EQ0(i, name) (strcmp(name, argv[ i ]) == 0)
		#define EQ1(i, name) (strcmp(name, argv[ i ]) == 0 && argc > i)
		for (int i = 1; i < argc; ++i) {
			if (EQ0(i, "--debug")) {
				debug = true;
			} else if (EQ0(i, "--help") || EQ0(i, "-h")) {
				usage(*argv);
				exit(0);
			} else if (EQ1(i, "-p")) {
				redis.port = atoi(argv[++i]);
			} else if (EQ1(i, "-t")) {
				redis.domain = argv[++i];
			} else if (EQ1(i, "-a")) {
				redis.auth = argv[++i];
			} else if (EQ1(i, "-s")) {
				serializer = argv[++i];
				if (serializer != "protobuf" && serializer != "c" && serializer != "json") {
					cerr << "invalid serializer : " << serializer << endl;
					exit(-1);
				}
			} else {
				url = argv[i++];
				if (argc > i) {
					cerr << "? arg" << i << " " << argv[i] << endl;
					usage(*argv);
					exit(-1);
				}
			}
		}
		if (url.empty()) {
			cerr << "specify aor" << endl;
			usage(*argv);
			exit(-1);
		}
	}
};

static void timerfunc(su_root_magic_t *magic, su_timer_t *t, Agent *arg){
	arg->idle();
}

int main(int argc, char **argv) {
	su_home_t home;
	su_root_t* root;
	sUseSyslog = false;
	shared_ptr<Agent> agent;
	CTArgs args; args.parse(argc, argv);

	flexisip::log::preinit(sUseSyslog, args.debug);
	flexisip::log::initLogs(sUseSyslog, args.debug);
	flexisip::log::updateFilter("%Severity% >= debug");

	Record::sLineFieldNames = {"line"};
	Record::sMaxContacts = 10;

	su_home_init(&home);
	root = su_root_create(NULL);
	agent      = make_shared<Agent>(root);

	auto serializer  = unique_ptr<RecordSerializer>(RecordSerializer::create(args.serializer));
	auto registrardb = new RegistrarDbRedisAsync("localhost", root, serializer.get(), args.redis);
	auto url = url_format(&home,args.url.c_str());
	auto listener = make_shared<DumpListener>(root);

	registrardb->fetch(url, listener);

	su_timer_t* timer = su_timer_create(su_root_task(root),5000);
	if( !listener->listenerError ){
		su_timer_set_for_ever(timer,(su_timer_f)timerfunc,agent.get());
		su_root_run(root);
	}

	agent.reset();

	su_timer_destroy(timer);
	su_root_destroy(root);
	su_home_destroy(&home);
}

<commit_msg>Fix class member initialization<commit_after>#include "recordserializer.hh"
#include "registrardb-redis.hh"
#include "common.hh"

#include <algorithm>

#include "configmanager.hh"

#include <hiredis/hiredis.h>

#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_wait.h>

#include <memory>

using namespace std;

bool sUseSyslog;

struct DumpListener : public RegistrarDbListener {

private:
	su_root_t* root;

private:
	void su_break(){
		if( root ){
			su_root_break(root);
		}
	}

public:
	bool listenerError;

public:
	DumpListener(su_root_t* _root) : RegistrarDbListener(), root(_root), listenerError(false) {}

	virtual void onRecordFound(Record *record) {
		if (record) cout << *record           << endl;
		else        cout << "No record found" << endl;
		su_break();
	}
	virtual void onError() {
		SLOGE << "Connection error, aborting" <<  endl;
		listenerError = true;
		su_break();
	}
	virtual void onInvalid() {
		SLOGW << "Invalid" << endl;
		listenerError = true;
		su_break();
	}
};

struct CTArgs {
	bool debug;
	RedisParameters redis;
	string serializer;
	string url;

	static void usage(const char *app) {
		CTArgs args;
		cout << app << " -t host[" << args.redis.domain << "] "
			<< "-p port[" << args.redis.port << "] "
			<< "--debug "
			<< "-a auth "
			<< "-s serializer[" << args.serializer << "] "
			<< "sip_uri " << endl;
	}

	CTArgs() {
		debug = false;
		redis.port=6379;
		redis.timeout = 2000;
		redis.domain = "sip";
		serializer = "protobuf";
	}

	void parse(int argc, char **argv) {
		#define EQ0(i, name) (strcmp(name, argv[ i ]) == 0)
		#define EQ1(i, name) (strcmp(name, argv[ i ]) == 0 && argc > i)
		for (int i = 1; i < argc; ++i) {
			if (EQ0(i, "--debug")) {
				debug = true;
			} else if (EQ0(i, "--help") || EQ0(i, "-h")) {
				usage(*argv);
				exit(0);
			} else if (EQ1(i, "-p")) {
				redis.port = atoi(argv[++i]);
			} else if (EQ1(i, "-t")) {
				redis.domain = argv[++i];
			} else if (EQ1(i, "-a")) {
				redis.auth = argv[++i];
			} else if (EQ1(i, "-s")) {
				serializer = argv[++i];
				if (serializer != "protobuf" && serializer != "c" && serializer != "json") {
					cerr << "invalid serializer : " << serializer << endl;
					exit(-1);
				}
			} else {
				url = argv[i++];
				if (argc > i) {
					cerr << "? arg" << i << " " << argv[i] << endl;
					usage(*argv);
					exit(-1);
				}
			}
		}
		if (url.empty()) {
			cerr << "specify aor" << endl;
			usage(*argv);
			exit(-1);
		}
	}
};

static void timerfunc(su_root_magic_t *magic, su_timer_t *t, Agent *arg){
	arg->idle();
}

int main(int argc, char **argv) {
	su_home_t home;
	su_root_t* root;
	sUseSyslog = false;
	shared_ptr<Agent> agent;
	CTArgs args; args.parse(argc, argv);

	flexisip::log::preinit(sUseSyslog, args.debug);
	flexisip::log::initLogs(sUseSyslog, args.debug);
	flexisip::log::updateFilter("%Severity% >= debug");

	Record::sLineFieldNames = {"line"};
	Record::sMaxContacts = 10;

	su_home_init(&home);
	root = su_root_create(NULL);
	agent      = make_shared<Agent>(root);

	auto serializer  = unique_ptr<RecordSerializer>(RecordSerializer::create(args.serializer));
	auto registrardb = new RegistrarDbRedisAsync("localhost", root, serializer.get(), args.redis);
	auto url = url_format(&home,args.url.c_str());
	auto listener = make_shared<DumpListener>(root);

	registrardb->fetch(url, listener);

	su_timer_t* timer = su_timer_create(su_root_task(root),5000);
	if( !listener->listenerError ){
		su_timer_set_for_ever(timer,(su_timer_f)timerfunc,agent.get());
		su_root_run(root);
	}

	agent.reset();

	su_timer_destroy(timer);
	su_root_destroy(root);
	su_home_destroy(&home);
}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_LOG_HPP
#define STAN_MATH_REV_FUN_LOG_HPP

#include <stan/math/prim/fun/log.hpp>
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/abs.hpp>
#include <stan/math/rev/fun/arg.hpp>
#include <stan/math/rev/fun/atan2.hpp>
#include <stan/math/rev/fun/cos.hpp>
#include <stan/math/rev/fun/is_inf.hpp>
#include <stan/math/rev/fun/is_nan.hpp>
#include <stan/math/rev/fun/sqrt.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * Return the natural log of the specified variable (cmath).
 *
 * The derivative is defined by
 *
 * \f$\frac{d}{dx} \log x = \frac{1}{x}\f$.
 *
   \f[
   \mbox{log}(x) =
   \begin{cases}
     \textrm{NaN} & \mbox{if } x < 0\\
     \ln(x) & \mbox{if } x \geq 0 \\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
   \f]

   \f[
   \frac{\partial\, \mbox{log}(x)}{\partial x} =
   \begin{cases}
     \textrm{NaN} & \mbox{if } x < 0\\
     \frac{1}{x} & \mbox{if } x\geq 0 \\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
   \f]
 *
 * @tparam T Arithmetic or a type inheriting from `EigenBase`.
 * @param a Variable whose log is taken.
 * @return Natural log of variable.
 */
template <typename T, require_stan_scalar_or_eigen_t<T>* = nullptr>
inline auto log(const var_value<T>& a) {
  return make_callback_var(log(a.val()), [a](auto& vi) mutable {
    as_array_or_scalar(a.adj())
        += as_array_or_scalar(vi.adj()) / as_array_or_scalar(a.val());
  });
}

/**
 * Return the natural logarithm (base e) of the specified complex argument.
 *
 * @param z complex argument
 * @return natural logarithm of argument
 */
inline std::complex<var> log(const std::complex<var>& z) {
  return internal::complex_log(z);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>fix for apply scalar unary<commit_after>#ifndef STAN_MATH_REV_FUN_LOG_HPP
#define STAN_MATH_REV_FUN_LOG_HPP

#include <stan/math/prim/fun/log.hpp>
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/functor/apply_scalar_unary.hpp>
#include <stan/math/rev/fun/abs.hpp>
#include <stan/math/rev/fun/arg.hpp>
#include <stan/math/rev/fun/atan2.hpp>
#include <stan/math/rev/fun/cos.hpp>
#include <stan/math/rev/fun/is_inf.hpp>
#include <stan/math/rev/fun/is_nan.hpp>
#include <stan/math/rev/fun/sqrt.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * Return the natural log of the specified variable (cmath).
 *
 * The derivative is defined by
 *
 * \f$\frac{d}{dx} \log x = \frac{1}{x}\f$.
 *
   \f[
   \mbox{log}(x) =
   \begin{cases}
     \textrm{NaN} & \mbox{if } x < 0\\
     \ln(x) & \mbox{if } x \geq 0 \\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
   \f]

   \f[
   \frac{\partial\, \mbox{log}(x)}{\partial x} =
   \begin{cases}
     \textrm{NaN} & \mbox{if } x < 0\\
     \frac{1}{x} & \mbox{if } x\geq 0 \\[6pt]
     \textrm{NaN} & \mbox{if } x = \textrm{NaN}
   \end{cases}
   \f]
 *
 * @tparam T Arithmetic or a type inheriting from `EigenBase`.
 * @param a Variable whose log is taken.
 * @return Natural log of variable.
 */
template <typename T, require_stan_scalar_or_eigen_t<T>* = nullptr>
inline auto log(const var_value<T>& a) {
  return make_callback_var(log(a.val()), [a](auto& vi) mutable {
    as_array_or_scalar(a.adj())
        += as_array_or_scalar(vi.adj()) / as_array_or_scalar(a.val());
  });
}

/**
 * Return the natural logarithm (base e) of the specified complex argument.
 *
 * @param z complex argument
 * @return natural logarithm of argument
 */
inline std::complex<var> log(const std::complex<var>& z) {
  return internal::complex_log(z);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: applicat.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: fme $ $Date: 2001-08-16 09:14:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef APPLICAT_HXX
#define APPLICAT_HXX

class SvxErrorHandler;

#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif

/**************************************************************************/
/*
**
**  MACRO DEFINITION
**
**/

#define SMDLL   1

#define APPLICATIONNAME      "smath3"

/**************************************************************************/
/*
**
**  CLASS DEFINITION
**
**/

#ifdef WIN
#define RELEASE     "WIN304"
#endif

#ifdef PM2
#define RELEASE     "PM304"
#endif

#ifdef MAC
#define RELEASE     "MAC304"
#endif

#ifdef WNT
#define RELEASE     "WNT304"
#endif

#ifdef UNX
#define RELEASE     "UNX304"
#endif

#ifndef SMDLL
class SmResId : public ResId
{
public:
    SmResId(USHORT nId) :
        ResId(nId)
    {
    }

};

#endif

#ifndef _DLL_
class SmDLL;

class SmApplicat: public SfxApplication
{
protected:
    SvxErrorHandler     *pSvxErrorHandler;

    virtual void        OpenClients();

    // initialization / deinitialization
    virtual void        Init();
    virtual void        Exit();

public:
    void Main();

    SmApplicat() :
        SfxApplication("iso")
    {
    }

};

#endif
#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.456); FILE MERGED 2005/09/05 17:37:21 rt 1.3.456.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: applicat.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 14:57:06 $
 *
 *  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 APPLICAT_HXX
#define APPLICAT_HXX

class SvxErrorHandler;

#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif

/**************************************************************************/
/*
**
**  MACRO DEFINITION
**
**/

#define SMDLL   1

#define APPLICATIONNAME      "smath3"

/**************************************************************************/
/*
**
**  CLASS DEFINITION
**
**/

#ifdef WIN
#define RELEASE     "WIN304"
#endif

#ifdef PM2
#define RELEASE     "PM304"
#endif

#ifdef MAC
#define RELEASE     "MAC304"
#endif

#ifdef WNT
#define RELEASE     "WNT304"
#endif

#ifdef UNX
#define RELEASE     "UNX304"
#endif

#ifndef SMDLL
class SmResId : public ResId
{
public:
    SmResId(USHORT nId) :
        ResId(nId)
    {
    }

};

#endif

#ifndef _DLL_
class SmDLL;

class SmApplicat: public SfxApplication
{
protected:
    SvxErrorHandler     *pSvxErrorHandler;

    virtual void        OpenClients();

    // initialization / deinitialization
    virtual void        Init();
    virtual void        Exit();

public:
    void Main();

    SmApplicat() :
        SfxApplication("iso")
    {
    }

};

#endif
#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef APPLICAT_HXX
#define APPLICAT_HXX

class SvxErrorHandler;

#include <sfx2/app.hxx>

/**************************************************************************/
/*
**
**  MACRO DEFINITION
**
**/

#define SMDLL   1

#define APPLICATIONNAME      "smath3"

/**************************************************************************/
/*
**
**  CLASS DEFINITION
**
**/

#ifdef PM2
#define RELEASE     "PM304"
#endif

#ifdef WNT
#define RELEASE     "WNT304"
#endif

#ifdef UNX
#define RELEASE     "UNX304"
#endif

#ifndef SMDLL
class SmResId : public ResId
{
public:
    SmResId(USHORT nId) :
        ResId(nId)
    {
    }

};

#endif

#ifndef _DLL_
class SmDLL;

class SmApplicat: public SfxApplication
{
protected:
    SvxErrorHandler     *pSvxErrorHandler;

    virtual void        OpenClients();

    // initialization / deinitialization
    virtual void        Init();
    virtual void        Exit();

public:
    void Main();

    SmApplicat() :
        SfxApplication("iso")
    {
    }

};

#endif
#endif

<commit_msg>CWS gnumake3: some more fixes for windows and svx; remove superfluous code in starmath that still used old _DLL_ define<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef APPLICAT_HXX
#define APPLICAT_HXX

class SvxErrorHandler;

#include <sfx2/app.hxx>

/**************************************************************************/
/*
**
**  MACRO DEFINITION
**
**/

#define SMDLL   1

#define APPLICATIONNAME      "smath3"

/**************************************************************************/
/*
**
**  CLASS DEFINITION
**
**/

#ifdef PM2
#define RELEASE     "PM304"
#endif

#ifdef WNT
#define RELEASE     "WNT304"
#endif

#ifdef UNX
#define RELEASE     "UNX304"
#endif

#ifndef SMDLL
class SmResId : public ResId
{
public:
    SmResId(USHORT nId) :
        ResId(nId)
    {
    }

};

#endif

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: document.hxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-19 08:51:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DOCUMENT_HXX
#define DOCUMENT_HXX

#define SMDLL   1

#ifndef _SVSTOR_HXX //autogen
#include <so3/svstor.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFX_INTERNO_HXX //autogen
#include <sfx2/interno.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif

#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif

class SmNode;
class SmSymSetManager;
class SfxPrinter;
class Printer;

#ifndef SO2_DECL_SVSTORAGESTREAM_DEFINED
#define SO2_DECL_SVSTORAGESTREAM_DEFINED
SO2_DECL_REF(SvStorageStream)
#endif

#define HINT_DATACHANGED    1004

#define SM30BIDENT   ((ULONG)0x534D3033L)
#define SM30IDENT    ((ULONG)0x30334d53L)
#define SM304AIDENT  ((ULONG)0x34303330L)
#define SM30VERSION  ((ULONG)0x00010000L)
#define SM50VERSION  ((ULONG)0x00010001L)   //Unterschied zur SM30VERSION ist
                                            //der neue Border im Format.

#define FRMIDENT    ((ULONG)0x03031963L)
#define FRMVERSION  ((ULONG)0x00010001L)

#define STAROFFICE_XML  "StarOffice XML (Math)"
#define MATHML_XML      "MathML XML (Math)"

/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
 * ==========================================================================
 *
 * Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
 * das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
 * grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
 * einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
 * im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
 * Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
 * (etwa waehrend des Paints).
 * Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
 * oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
 * fuer die der Access auch Friend der DocShell ist.
*/

class SmDocShell;
class EditEngine;
class EditEngineItemPool;

class SmPrinterAccess
{
    Printer* pPrinter;
    OutputDevice* pRefDev;
public:
    SmPrinterAccess( SmDocShell &rDocShell );
    ~SmPrinterAccess();
    Printer* GetPrinter()  { return pPrinter; }
    OutputDevice* GetRefDev()  { return pRefDev; }
};

////////////////////////////////////////////////////////////

class SmDocShell : public SfxObjectShell, public SfxInPlaceObject,
                    public SfxListener
{
    friend class SmPrinterAccess;

    String              aText;
    SmFormat            aFormat;
    SmParser            aInterpreter;
    SvStorageStreamRef  aDocStream;
    String              aAccText;
    SmSymSetManager    *pSymSetMgr;
    SmNode             *pTree;
    SvInPlaceMenuBar   *pMenuBar;
    SfxMenuBarManager  *pMenuMgr;
    SfxItemPool        *pEditEngineItemPool;
    EditEngine         *pEditEngine;
    SfxPrinter         *pPrinter;       //Siehe Kommentar zum SmPrinter Access!
    Printer            *pTmpPrinter;    //ebenfalls
    long                nLeftBorder,
                        nRightBorder,
                        nTopBorder,
                        nBottomBorder;
    USHORT              nModifyCount;
    BOOL                bIsFormulaArranged;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
                        const SfxHint& rHint, const TypeId& rHintType);

    void        RestartFocusTimer ();

    BOOL        Try3x( SvStorage *pStor, StreamMode eMode);
    BOOL        Try2x( SvStorage *pStor, StreamMode eMode);
    BOOL        WriteAsMathType3( SfxMedium& );

    virtual void        Draw(OutputDevice *pDevice,
                             const JobSetup & rSetup,
                             USHORT nAspect = ASPECT_CONTENT);

    virtual void        FillClass(SvGlobalName* pClassName,
                                  ULONG*  pFormat,
                                  String* pAppName,
                                  String* pFullTypeName,
                                  String* pShortTypeName,
                                  long    nFileFormat = SOFFICE_FILEFORMAT_CURRENT) const;

    virtual BOOL        SetData( const String& rData );
    virtual ULONG       GetMiscStatus() const;
    virtual void        OnDocumentPrinterChanged( Printer * );
    virtual BOOL        InitNew(SvStorage *);
    virtual BOOL        Load(SvStorage *);
    virtual BOOL        Insert(SvStorage *);
            void        ImplSave(  SvStorageStreamRef xStrm  );
    virtual BOOL        Save();
    virtual BOOL        SaveAs( SvStorage *pNewStor );
    virtual BOOL        ConvertTo( SfxMedium &rMedium );
    virtual BOOL        SaveCompleted( SvStorage *pNewStor );
    virtual void        HandsOff();

    Printer             *GetPrt();
    OutputDevice*       GetRefDev();

    // used to convert the formula text between different office versions
    void                ConvertText( String &rText, SmConvert eConv );

    BOOL                IsFormulaArranged() const { return bIsFormulaArranged; }
    void                SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }
    void                ArrangeFormula();

    virtual BOOL        ConvertFrom(SfxMedium &rMedium);
            BOOL        InsertFrom(SfxMedium &rMedium);

    BOOL                ImportSM20File(SvStream *pStream);

    void                UpdateText();

public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1);
    SFX_DECL_OBJECTFACTORY(SmDocShell);

                SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    virtual     ~SmDocShell();

    void        LoadSymbols();
    void        SaveSymbols();

    //Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
    //und fuer die Kommunikation mit dem SFX!
    //Alle internen Verwendungen des Printers sollten ausschlieslich uber
    //den SmPrinterAccess funktionieren.
    BOOL        HasPrinter()    { return 0 != pPrinter; }
    SfxPrinter *GetPrinter()    { GetPrt(); return pPrinter; }
    void        SetPrinter( SfxPrinter * );

    const String &GetTitle() const;
    const String &GetComment() const;

    void        SetText(const String& rBuffer);
    String&     GetText() { return (aText); }
    void        SetFormat(SmFormat& rFormat);
    SmFormat&   GetFormat() { return (aFormat); }

    void            Parse();
    SmParser &      GetParser() { return aInterpreter; }
    const SmNode *  GetFormulaTree() const  { return pTree; }
    void            SetFormulaTree(SmNode *&rTree) { pTree = rTree; }

    String          GetAccessibleText();

    EditEngine &    GetEditEngine();
    SfxItemPool &   GetEditEngineItemPool();

    SmSymSetManager &       GetSymSetManager();
    const SmSymSetManager & GetSymSetManager() const
    {
        return ((SmDocShell *) this)->GetSymSetManager();
    }

    void        Draw(OutputDevice &rDev, Point &rPosition);
    Size        GetSize();

    void        Resize();

    virtual     SfxUndoManager *GetUndoManager ();

    virtual     SfxItemPool& GetPool();

    void        Execute( SfxRequest& rReq );
    void        GetState(SfxItemSet &);

    virtual void SetVisArea (const Rectangle & rVisArea);
    virtual void UIActivate (BOOL bActivate);

    virtual void SetModified(BOOL bModified);
};

#endif

<commit_msg>INTEGRATION: CWS mav09 (1.18.74); FILE MERGED 2004/08/12 17:09:38 mav 1.18.74.5: #i27773# introduce version back 2004/04/29 11:05:05 mba 1.18.74.4: #i27773#: remove so3 2004/04/14 13:24:37 mba 1.18.74.3: #i27773#: remove so3; new storage API 2004/04/14 12:45:30 mba 1.18.74.2: #i27773#: remove so3; new storage API 2004/04/14 12:29:40 mba 1.18.74.1: #i27773#: remove so3; new storage API<commit_after>/*************************************************************************
 *
 *  $RCSfile: document.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 18:02:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DOCUMENT_HXX
#define DOCUMENT_HXX

#define SMDLL   1

#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif

#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif

#include <vcl/jobset.hxx>

class SmNode;
class SmSymSetManager;
class SfxPrinter;
class Printer;

#define HINT_DATACHANGED    1004

#define SM30BIDENT   ((ULONG)0x534D3033L)
#define SM30IDENT    ((ULONG)0x30334d53L)
#define SM304AIDENT  ((ULONG)0x34303330L)
#define SM30VERSION  ((ULONG)0x00010000L)
#define SM50VERSION  ((ULONG)0x00010001L)   //Unterschied zur SM30VERSION ist
                                            //der neue Border im Format.

#define FRMIDENT    ((ULONG)0x03031963L)
#define FRMVERSION  ((ULONG)0x00010001L)

#define STAROFFICE_XML  "StarOffice XML (Math)"
#define MATHML_XML      "MathML XML (Math)"

/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
 * ==========================================================================
 *
 * Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
 * das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
 * grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
 * einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
 * im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
 * Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
 * (etwa waehrend des Paints).
 * Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
 * oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
 * fuer die der Access auch Friend der DocShell ist.
*/

class SmDocShell;
class EditEngine;
class EditEngineItemPool;

class SmPrinterAccess
{
    Printer* pPrinter;
    OutputDevice* pRefDev;
public:
    SmPrinterAccess( SmDocShell &rDocShell );
    ~SmPrinterAccess();
    Printer* GetPrinter()  { return pPrinter; }
    OutputDevice* GetRefDev()  { return pRefDev; }
};

////////////////////////////////////////////////////////////

class SmDocShell : public SfxObjectShell, public SfxListener
{
    friend class SmPrinterAccess;

    String              aText;
    SmFormat            aFormat;
    SmParser            aInterpreter;
    String              aAccText;
    SmSymSetManager    *pSymSetMgr;
    SmNode             *pTree;
    SfxMenuBarManager  *pMenuMgr;
    SfxItemPool        *pEditEngineItemPool;
    EditEngine         *pEditEngine;
    SfxPrinter         *pPrinter;       //Siehe Kommentar zum SmPrinter Access!
    Printer            *pTmpPrinter;    //ebenfalls
    long                nLeftBorder,
                        nRightBorder,
                        nTopBorder,
                        nBottomBorder;
    USHORT              nModifyCount;
    BOOL                bIsFormulaArranged;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
                        const SfxHint& rHint, const TypeId& rHintType);

    void        RestartFocusTimer ();

    BOOL        Try3x( SvStorage *pStor, StreamMode eMode);
    BOOL        Try2x( SvStorage *pStor, StreamMode eMode);
    BOOL        WriteAsMathType3( SfxMedium& );

    virtual void        Draw(OutputDevice *pDevice,
                             const JobSetup & rSetup,
                             USHORT nAspect = ASPECT_CONTENT);

    virtual void        FillClass(SvGlobalName* pClassName,
                                  ULONG*  pFormat,
                                  String* pAppName,
                                  String* pFullTypeName,
                                  String* pShortTypeName,
                                  sal_Int32 nFileFormat ) const;

    virtual BOOL        SetData( const String& rData );
    virtual ULONG       GetMiscStatus() const;
    virtual void        OnDocumentPrinterChanged( Printer * );
    virtual sal_Bool    InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    virtual BOOL        Load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    virtual BOOL        Insert( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
            void        ImplSave(  SvStorageStreamRef xStrm  );
    virtual BOOL        Save();
    virtual BOOL        SaveAs( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    virtual BOOL        ConvertTo( SfxMedium &rMedium );
    virtual BOOL        SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    Printer             *GetPrt();
    OutputDevice*       GetRefDev();

    // used to convert the formula text between different office versions
    void                ConvertText( String &rText, SmConvert eConv );

    BOOL                IsFormulaArranged() const { return bIsFormulaArranged; }
    void                SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }
    void                ArrangeFormula();

    virtual BOOL        ConvertFrom(SfxMedium &rMedium);
            BOOL        InsertFrom(SfxMedium &rMedium);

    BOOL                ImportSM20File(SvStream *pStream);

    void                UpdateText();

public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1);
    SFX_DECL_OBJECTFACTORY();

                SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    virtual     ~SmDocShell();

    void        LoadSymbols();
    void        SaveSymbols();

    //Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
    //und fuer die Kommunikation mit dem SFX!
    //Alle internen Verwendungen des Printers sollten ausschlieslich uber
    //den SmPrinterAccess funktionieren.
    BOOL        HasPrinter()    { return 0 != pPrinter; }
    SfxPrinter *GetPrinter()    { GetPrt(); return pPrinter; }
    void        SetPrinter( SfxPrinter * );

    const String &GetTitle() const;
    const String &GetComment() const;

    void        SetText(const String& rBuffer);
    String&     GetText() { return (aText); }
    void        SetFormat(SmFormat& rFormat);
    SmFormat&   GetFormat() { return (aFormat); }

    void            Parse();
    SmParser &      GetParser() { return aInterpreter; }
    const SmNode *  GetFormulaTree() const  { return pTree; }
    void            SetFormulaTree(SmNode *&rTree) { pTree = rTree; }

    String          GetAccessibleText();

    EditEngine &    GetEditEngine();
    SfxItemPool &   GetEditEngineItemPool();

    SmSymSetManager &       GetSymSetManager();
    const SmSymSetManager & GetSymSetManager() const
    {
        return ((SmDocShell *) this)->GetSymSetManager();
    }

    void        Draw(OutputDevice &rDev, Point &rPosition);
    Size        GetSize();

    void        Resize();

    virtual     SfxUndoManager *GetUndoManager ();

    virtual     SfxItemPool& GetPool();

    void        Execute( SfxRequest& rReq );
    void        GetState(SfxItemSet &);

    virtual void SetVisArea (const Rectangle & rVisArea);
    virtual void UIActivate (BOOL bActivate);

    virtual void SetModified(BOOL bModified);
};

#endif

<|endoftext|>


<commit_before>/**
 * Copyright  (C)  2013 CoDyCo Project
 * Author: Silvio Traversaro
 * website: http://www.codyco.eu
 */

#include "kdl_codyco/treepartition.hpp"
#include <kdl/joint.hpp>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
#include "kdl_codyco/utils.hpp"
#include "kdl_codyco/config.h"

namespace KDL {
namespace CoDyCo {
    /*
    int TreePart::getLocalPartIndex(const std::string part_name)
    {
        std::map<std::string,int>::const_iterator it_si = name_map.find(part_name);

        if( it_si == name_map.end() ) { return -1; }

        int part_id = it_si->second;

        std::map<int,int>::const_iterator it_ii = ID_map.find(part_id);

        if( it_ii == ID_map.end() ) { return -1; }

        int part_local_index = it_ii->second;

        return part_local_index;
    }*/

    TreePart::TreePart(): part_id(-1), part_name("TreePartError"), dof_id(0), links_id(0)
    {
    }

    TreePart::TreePart(int _part_id, std::string _part_name): part_id(_part_id), part_name(_part_name), dof_id(0), links_id(0)
    {
    }

    TreePart::TreePart(int _part_id, std::string _part_name, std::vector<int> _dof_id, std::vector<int> _links_id): part_id(_part_id), part_name(_part_name), dof_id(_dof_id), links_id(_links_id)
    {
    }

    TreePart::~TreePart()
    {
    }

    TreePart& TreePart::operator=(const TreePart& x)
    {
        if ( this != &x ) {
            this->part_id = x.part_id;
            this->part_name = x.part_name;
            this->dof_id = x.dof_id;
            this->links_id = x.links_id;
        }
        return *this;
    }

    int TreePart::getNrOfLinks() const
    {
        return links_id.size();
    }

    int TreePart::getNrOfDOFs() const
    {
        return dof_id.size();
    }

    std::string TreePart::getPartName() const
    {
        return part_name;
    }

    int TreePart::getPartID() const
    {
        return part_id;
    }

    std::string TreePart::toString() const
    {
        std::stringstream ss;
        ss << "TreePart: " << part_id << " " << part_name << std::endl;
        ss << "Links: " << std::endl;
        for(int link = 0; link < getNrOfLinks(); link++ ) {
            ss << "Local link " << link << " is global link " << links_id[link] << std::endl;
        }
        ss << "Joints: " << std::endl;
        for(int joint = 0; joint < getNrOfDOFs(); joint++ ) {
            ss << "Local dof id " << joint << " is global dof " << dof_id[joint] << std::endl;
        }
        return ss.str();
    }

    TreePartition::TreePartition()
    {
    }

    TreePartition::~TreePartition()
    {
    }

    TreePartition::TreePartition(const Tree & tree)
    {
        int nrOfDOFs = tree.getNrOfJoints();
        int nrOfLinks = tree.getNrOfSegments();

        TreePart tree_part(0,"default_part");

        SegmentMap::const_iterator root = tree.getRootSegment();

        /** \todo remove this assumption */
        assert(GetTreeElementChildren(root->second).size() != 0);
//        SegmentMap::const_iterator root_child = root->second.children[0];

         //This should be coherent with the behaviour of UndirectedTree
        if( !isBaseLinkFake(tree) )
        {
            nrOfLinks++;
        }

        for(int i=0; i <nrOfDOFs; i++ )
        {
            tree_part.addDOF(i);
        }

        for(int i=0; i <nrOfLinks; i++ )
        {
            tree_part.addLink(i);
        }

        addPart(tree_part);
    }

    bool TreePartition::addPart(TreePart & tree_part)
    {
        int part_index = parts.size();
        parts.push_back(tree_part);
        ID_map.insert(std::make_pair(tree_part.getPartID(),part_index));
        name_map.insert(std::make_pair(tree_part.getPartName(),part_index));
        return true;
    }

    TreePart TreePartition::getPart(int id) const
    {
        int local_index;

        std::map<int,int>::const_iterator it = ID_map.find(id);

        if( it == ID_map.end() ) {
            return TreePart();
        }

        local_index = it->second;

        return parts[local_index];
    }

    TreePart TreePartition::getPart(const std::string & part_name) const
    {
        int local_index;

        std::map<std::string,int>::const_iterator it = name_map.find(part_name);

        if( it == name_map.end() ) {
            return TreePart();
        }

        local_index = it->second;

        return parts[local_index];
    }

    int TreePartition::getPartIDfromPartName(const std::string & part_name) const
    {
       int local_index;

        std::map<std::string,int>::const_iterator it = name_map.find(part_name);

        if( it == name_map.end() ) {
            return -1;
        }

        local_index = it->second;

        return parts[local_index].getPartID();
    }

    int TreePartition::getPartIDfromLink(int link_id) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
                if( parts[i].getGlobalLinkIndex(j) == link_id ) {
                    return parts[i].getPartID();
                }
            }
        }
        return -1;
    }

    int TreePartition::getPartIDfromDOF(int dof_id) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
                if( parts[i].getGlobalDOFIndex(j) == dof_id ) {
                    return parts[i].getPartID();
                }
            }
        }
        return -1;
    }

    int TreePartition::getGlobalLinkIndex(int part_ID, int local_link_index) const
    {
        int local_index;

        std::map<int,int>::const_iterator it = ID_map.find(part_ID);

        if( it == ID_map.end() ) {
            return -1;
        }

        local_index = it->second;

        if( local_link_index >= parts[local_index].getNrOfLinks() || local_link_index < 0 ) return -2;

        return parts[local_index].getGlobalLinkIndex(local_link_index);
    }

    int TreePartition::getGlobalDOFIndex(int part_ID, int local_DOF_index) const
    {
        int local_index;

        std::map<int,int>::const_iterator it = ID_map.find(part_ID);

        if( it == ID_map.end() ) {
            return -1;
        }

        local_index = it->second;

        return parts[local_index].getGlobalDOFIndex(local_DOF_index);
    }

    int TreePartition::getLocalLinkIndex(int global_link_index) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
                if( parts[i].getGlobalLinkIndex(j) == global_link_index ) {
                    return j;
                }
            }
        }
        return -1;
    }

    int TreePartition::getLocalDOFIndex(int global_dof_index) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
                if( parts[i].getGlobalDOFIndex(j) == global_dof_index) {
                    return j;
                }
            }
        }
        return -1;
    }

    /**
    * Check if the TreePartition is a valid partition for the
    * given Tree (and optionally the given TreeSerialization )
    *
    */
    bool TreePartition::is_consistent(const Tree & tree ) const
    {
        return is_consistent(tree,TreeSerialization(tree));
    }

    bool TreePartition::is_consistent(const Tree & tree, TreeSerialization tree_serialization) const
    {
        if( !tree_serialization.is_consistent(tree) ) return false;

        int total_links = 0;

        for(int i=0; i < (int)parts.size(); i++ ) {
            TreePart part = parts[i];
            if( part.getNrOfLinks() <= 0 ) return false;
            total_links +=  part.getNrOfLinks();
        }

        if( total_links != (int)tree.getNrOfSegments() ) return false;

        if( ID_map.size() != parts.size() ) { return false; }
        if( name_map.size() != parts.size() ) { return false; }

        /**
         * \todo add link/joint id level serialization
         */

        return true;
    }

    /**
     * \todo add efficient way of returning vector<int>
     *
     */
    std::vector<int> TreePartition::getPartLinkIDs(const std::string & part_name) const
    {
        //\todo error checking
        TreePart part = getPart(part_name);
        return part.getLinkIDs();
    }

    /**
     * \todo add efficient way of returning vector<int>
     *
     */
    std::vector<int> TreePartition::getPartDOFIDs(const std::string & part_name) const
    {
        std::vector<int> ret;
        #ifndef NDEBUG
        //std::cout << "getPartDOFIDs(" << part_name <<")" << std::endl;
        #endif
        TreePart part = getPart(part_name);
        ret = part.getDOFIDs();
        #ifndef NDEBUG
        //std::cout << part.toString() << std::endl;
        //std::cout << "has " << ret.size() << " DOFs " << std::endl;
        #endif
        return ret;
    }

    std::string TreePartition::toString() const
    {
        std::stringstream ss;
        for(int i=0; i < (int)parts.size(); i++ ) {
            ss << parts[i].toString() << std::endl;
            int part_id = parts[i].getPartID();
            std::map<int,int>::const_iterator it = ID_map.find(part_id);
            int local_vector_index = it->second;
            ss << "Part with ID " << parts[i].getPartID() << " has index in local part vector" << local_vector_index << std::endl;
        }
        return ss.str();
    }
}
}
<commit_msg>Added assertion in treepartition method<commit_after>/**
 * Copyright  (C)  2013 CoDyCo Project
 * Author: Silvio Traversaro
 * website: http://www.codyco.eu
 */

#include "kdl_codyco/treepartition.hpp"
#include <kdl/joint.hpp>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
#include "kdl_codyco/utils.hpp"
#include "kdl_codyco/config.h"

namespace KDL {
namespace CoDyCo {
    /*
    int TreePart::getLocalPartIndex(const std::string part_name)
    {
        std::map<std::string,int>::const_iterator it_si = name_map.find(part_name);

        if( it_si == name_map.end() ) { return -1; }

        int part_id = it_si->second;

        std::map<int,int>::const_iterator it_ii = ID_map.find(part_id);

        if( it_ii == ID_map.end() ) { return -1; }

        int part_local_index = it_ii->second;

        return part_local_index;
    }*/

    TreePart::TreePart(): part_id(-1), part_name("TreePartError"), dof_id(0), links_id(0)
    {
    }

    TreePart::TreePart(int _part_id, std::string _part_name): part_id(_part_id), part_name(_part_name), dof_id(0), links_id(0)
    {
    }

    TreePart::TreePart(int _part_id, std::string _part_name, std::vector<int> _dof_id, std::vector<int> _links_id): part_id(_part_id), part_name(_part_name), dof_id(_dof_id), links_id(_links_id)
    {
    }

    TreePart::~TreePart()
    {
    }

    TreePart& TreePart::operator=(const TreePart& x)
    {
        if ( this != &x ) {
            this->part_id = x.part_id;
            this->part_name = x.part_name;
            this->dof_id = x.dof_id;
            this->links_id = x.links_id;
        }
        return *this;
    }

    int TreePart::getNrOfLinks() const
    {
        return links_id.size();
    }

    int TreePart::getNrOfDOFs() const
    {
        return dof_id.size();
    }

    std::string TreePart::getPartName() const
    {
        return part_name;
    }

    int TreePart::getPartID() const
    {
        return part_id;
    }

    std::string TreePart::toString() const
    {
        std::stringstream ss;
        ss << "TreePart: " << part_id << " " << part_name << std::endl;
        ss << "Links: " << std::endl;
        for(int link = 0; link < getNrOfLinks(); link++ ) {
            ss << "Local link " << link << " is global link " << links_id[link] << std::endl;
        }
        ss << "Joints: " << std::endl;
        for(int joint = 0; joint < getNrOfDOFs(); joint++ ) {
            ss << "Local dof id " << joint << " is global dof " << dof_id[joint] << std::endl;
        }
        return ss.str();
    }

    TreePartition::TreePartition()
    {
    }

    TreePartition::~TreePartition()
    {
    }

    TreePartition::TreePartition(const Tree & tree)
    {
        int nrOfDOFs = tree.getNrOfJoints();
        int nrOfLinks = tree.getNrOfSegments();

        TreePart tree_part(0,"default_part");

        SegmentMap::const_iterator root = tree.getRootSegment();

        /** \todo remove this assumption */
        assert(GetTreeElementChildren(root->second).size() != 0);
//        SegmentMap::const_iterator root_child = root->second.children[0];

         //This should be coherent with the behaviour of UndirectedTree
        if( !isBaseLinkFake(tree) )
        {
            nrOfLinks++;
        }

        for(int i=0; i <nrOfDOFs; i++ )
        {
            tree_part.addDOF(i);
        }

        for(int i=0; i <nrOfLinks; i++ )
        {
            tree_part.addLink(i);
        }

        addPart(tree_part);
    }

    bool TreePartition::addPart(TreePart & tree_part)
    {
        int part_index = parts.size();
        parts.push_back(tree_part);
        ID_map.insert(std::make_pair(tree_part.getPartID(),part_index));
        name_map.insert(std::make_pair(tree_part.getPartName(),part_index));
        return true;
    }

    TreePart TreePartition::getPart(int id) const
    {
        int local_index;

        std::map<int,int>::const_iterator it = ID_map.find(id);

        if( it == ID_map.end() ) {
            return TreePart();
        }

        local_index = it->second;

        return parts[local_index];
    }

    TreePart TreePartition::getPart(const std::string & part_name) const
    {
        int local_index;

        std::map<std::string,int>::const_iterator it = name_map.find(part_name);

        if( it == name_map.end() ) {
            return TreePart();
        }

        local_index = it->second;

        return parts[local_index];
    }

    int TreePartition::getPartIDfromPartName(const std::string & part_name) const
    {
       int local_index;

        std::map<std::string,int>::const_iterator it = name_map.find(part_name);

        if( it == name_map.end() ) {
            return -1;
        }

        local_index = it->second;

        return parts[local_index].getPartID();
    }

    int TreePartition::getPartIDfromLink(int link_id) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
                if( parts[i].getGlobalLinkIndex(j) == link_id ) {
                    return parts[i].getPartID();
                }
            }
        }
        return -1;
    }

    int TreePartition::getPartIDfromDOF(int dof_id) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
                if( parts[i].getGlobalDOFIndex(j) == dof_id ) {
                    return parts[i].getPartID();
                }
            }
        }
        return -1;
    }

    int TreePartition::getGlobalLinkIndex(int part_ID, int local_link_index) const
    {
        int local_index;

        std::map<int,int>::const_iterator it = ID_map.find(part_ID);

        if( it == ID_map.end() ) {
            return -1;
        }

        local_index = it->second;

        if( local_link_index >= parts[local_index].getNrOfLinks() || local_link_index < 0 ) return -2;

        return parts[local_index].getGlobalLinkIndex(local_link_index);
    }

    int TreePartition::getGlobalDOFIndex(int part_ID, int local_DOF_index) const
    {
        int local_index;

        assert(ID_map.size() == parts.size());
        std::map<int,int>::const_iterator it = ID_map.find(part_ID);

        if( it == ID_map.end() ) {
            return -1;
        }

        local_index = it->second;

        return parts[local_index].getGlobalDOFIndex(local_DOF_index);
    }

    int TreePartition::getLocalLinkIndex(int global_link_index) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
                if( parts[i].getGlobalLinkIndex(j) == global_link_index ) {
                    return j;
                }
            }
        }
        return -1;
    }

    int TreePartition::getLocalDOFIndex(int global_dof_index) const
    {
        for(int i=0; i < (int)parts.size(); i++ ) {
            for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
                if( parts[i].getGlobalDOFIndex(j) == global_dof_index) {
                    return j;
                }
            }
        }
        return -1;
    }

    /**
    * Check if the TreePartition is a valid partition for the
    * given Tree (and optionally the given TreeSerialization )
    *
    */
    bool TreePartition::is_consistent(const Tree & tree ) const
    {
        return is_consistent(tree,TreeSerialization(tree));
    }

    bool TreePartition::is_consistent(const Tree & tree, TreeSerialization tree_serialization) const
    {
        if( !tree_serialization.is_consistent(tree) ) return false;

        int total_links = 0;

        for(int i=0; i < (int)parts.size(); i++ ) {
            TreePart part = parts[i];
            if( part.getNrOfLinks() <= 0 ) return false;
            total_links +=  part.getNrOfLinks();
        }

        if( total_links != (int)tree.getNrOfSegments() ) return false;

        if( ID_map.size() != parts.size() ) { return false; }
        if( name_map.size() != parts.size() ) { return false; }

        /**
         * \todo add link/joint id level serialization
         */

        return true;
    }

    /**
     * \todo add efficient way of returning vector<int>
     *
     */
    std::vector<int> TreePartition::getPartLinkIDs(const std::string & part_name) const
    {
        //\todo error checking
        TreePart part = getPart(part_name);
        return part.getLinkIDs();
    }

    /**
     * \todo add efficient way of returning vector<int>
     *
     */
    std::vector<int> TreePartition::getPartDOFIDs(const std::string & part_name) const
    {
        std::vector<int> ret;
        #ifndef NDEBUG
        //std::cout << "getPartDOFIDs(" << part_name <<")" << std::endl;
        #endif
        TreePart part = getPart(part_name);
        ret = part.getDOFIDs();
        #ifndef NDEBUG
        //std::cout << part.toString() << std::endl;
        //std::cout << "has " << ret.size() << " DOFs " << std::endl;
        #endif
        return ret;
    }

    std::string TreePartition::toString() const
    {
        std::stringstream ss;
        for(int i=0; i < (int)parts.size(); i++ ) {
            ss << parts[i].toString() << std::endl;
            int part_id = parts[i].getPartID();
            std::map<int,int>::const_iterator it = ID_map.find(part_id);
            int local_vector_index = it->second;
            ss << "Part with ID " << parts[i].getPartID() << " has index in local part vector" << local_vector_index << std::endl;
        }
        return ss.str();
    }
}
}
<|endoftext|>