<commit_before>#include "ros/ros.h"
#include <linux/input.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
#include <vector>

#include "evdev_teleport/EvdevEvent.h"
#include "evdev_teleport/EvdevEvents.h"

const char* DEVICE_PATH_PARAM = "device_path";
const double SLEEP_DURATION = 0.0001; // seconds

int main(int argc, char** argv) {

  /* initialize ros */

  ros::init(argc, argv, "evdev_teleport_sender");

  ros::NodeHandle n("~");

  /* open the device */

  std::string device_path;
  int device_fd;

  if (n.getParam(DEVICE_PATH_PARAM, device_path)) {
    ROS_INFO("Using device: %s", device_path.c_str());
    n.deleteParam(DEVICE_PATH_PARAM);
  } else {
    ROS_ERROR("Private parameter 'device_path' must be set");
    ros::shutdown();
    exit(EXIT_FAILURE);
  }

  if ((device_fd = open(device_path.c_str(), O_RDONLY | O_NONBLOCK)) < 0) {
    perror("opening the file you specified");
    ros::shutdown();
    exit(EXIT_FAILURE);
  }

  /* advertise the topic */

  ros::Publisher evdev_pub =
    n.advertise<evdev_teleport::EvdevEvents>("/evdev_teleport/event", 1);

  /* begin relaying from the device to the topic */

  evdev_teleport::EvdevEvents events_msg;

  while(ros::ok()) {
    struct input_event ev;
    struct input_event *event_data = &ev;
    evdev_teleport::EvdevEvent event_msg;

    int num_read = read(device_fd, event_data, sizeof(ev));

    if (sizeof(ev) != num_read) {
      ros::Duration(SLEEP_DURATION).sleep();
      continue;
    }

    if (event_data->type == EV_SYN) {
      if (!events_msg.events.empty()) {
        evdev_pub.publish(events_msg);
        events_msg.events.clear();
      }
      ros::spinOnce();
      continue;
    }

    event_msg.type = event_data->type;
    event_msg.code = event_data->code;
    event_msg.value = event_data->value;
    events_msg.events.push_back(event_msg);

    ROS_DEBUG(
      "got type: %d code: %d value: %d\n",
      event_msg.type, event_msg.code, event_msg.value
    );
  }
}
<commit_msg>poll() version of evdev_teleport sender<commit_after>#include "ros/ros.h"
#include <linux/input.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <string>
#include <vector>

#include "evdev_teleport/EvdevEvent.h"
#include "evdev_teleport/EvdevEvents.h"

const char* DEVICE_PATH_PARAM = "device_path";

int main(int argc, char** argv) {

  /* initialize ros */

  ros::init(argc, argv, "evdev_teleport_sender");

  ros::NodeHandle n("~");

  /* open the device */

  std::string device_path;
  int device_fd;

  if (n.getParam(DEVICE_PATH_PARAM, device_path)) {
    ROS_INFO("Using device: %s", device_path.c_str());
    n.deleteParam(DEVICE_PATH_PARAM);
  } else {
    ROS_ERROR("Private parameter 'device_path' must be set");
    ros::shutdown();
    exit(EXIT_FAILURE);
  }

  if ((device_fd = open(device_path.c_str(), O_RDONLY | O_NONBLOCK)) < 0) {
    perror("opening the file you specified");
    ros::shutdown();
    exit(EXIT_FAILURE);
  }

  /* set up fd polling */

  struct pollfd poll_fd;
  memset(&poll_fd, 0, sizeof(poll_fd));
  poll_fd.fd = device_fd;
  poll_fd.events = POLLIN;

  /* advertise the topic */

  ros::Publisher evdev_pub =
    n.advertise<evdev_teleport::EvdevEvents>("/evdev_teleport/event", 1);

  /* begin relaying from the device to the topic */

  evdev_teleport::EvdevEvents events_msg;

  while(ros::ok()) {
    struct input_event ev;
    struct input_event *event_data = &ev;
    evdev_teleport::EvdevEvent event_msg;

    /* read an event */

    int status = poll(&poll_fd, 1, -1);
    if (status == 1) {
      // device is ready to read
      int num_read = read(device_fd, event_data, sizeof(ev));

      if (num_read != sizeof(ev)) {
        ROS_ERROR("Error getting next event");
        ros::shutdown();
        exit(EXIT_FAILURE);
      }

    } else {
      // an error has occurred
      perror("polling device");
      ros::shutdown();
      exit(EXIT_FAILURE);
    }

    /* handle the event */

    if (event_data->type == EV_SYN) {
      // only publish when a syn event is read
      if (!events_msg.events.empty()) {
        evdev_pub.publish(events_msg);
        events_msg.events.clear();
      }
      ros::spinOnce();
      continue;
    }

    // non-syn events are aggregated
    event_msg.type = event_data->type;
    event_msg.code = event_data->code;
    event_msg.value = event_data->value;
    events_msg.events.push_back(event_msg);

    ROS_DEBUG(
      "got type: %d code: %d value: %d\n",
      event_msg.type, event_msg.code, event_msg.value
    );
  }
}
<|endoftext|>


<commit_before>/*
Copyright 2016 Colin Girling

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.
*/

#ifndef OCL_GUARD_TEST_TESTSTRING_HPP
#define OCL_GUARD_TEST_TESTSTRING_HPP

#include "TestMemoryUtility.hpp"
#include "TestStringUtility.hpp"
#include <cstddef>
#include <cstdlib>
#include <cstring>

namespace ocl
{

/*
 * String class for test harness, with an interface complete enough for general usage.
 */

class TestString
{
public:
    typedef TestStringUtility::size_type size_type;

public:
    TestString(char const* str = NULL)
        : m_length(0)
        , m_string(NULL)
    {
        if (str != NULL)
            TestStringUtility::UnsafeAllocateCopy(m_string, m_length, str);
    }

    TestString(char ch, size_type len)
        : m_length(len)
        , m_string(NULL)
    {
        if (len > 0)
        {
            TestStringUtility::Allocate(m_string, len);
            if (m_string != NULL)
                TestStringUtility::UnsafeFill(m_string, ch, len);
            else
                m_length = 0;
        }
    }

    TestString(TestString const& str)
        : m_length(0)
        , m_string(NULL)
    {
        TestStringUtility::SafeAllocateCopy(m_string, m_length, str.m_string, str.m_length);
    }

    ~TestString()
    {
        TestStringUtility::FastFree(m_string);
    }

    TestString& operator =(char const* str)
    {
        if ((str == NULL) || (*str == '\0'))
            Clear();
        else
            TestStringUtility::SafeReallocCopy(m_string, m_length, str);
        return *this;
    }

    TestString& operator =(TestString const& str)
    {
        TestStringUtility::SafeReallocCopy(m_string,
                                           m_length,
                                           str.m_string,
                                           str.m_length);

        return *this;
    }

    TestString& operator +=(char const* str)
    {
        Append(str);
        return *this;
    }

    TestString& operator +=(TestString const& str)
    {
        Append(str);
        return *this;
    }

    char operator [](size_type index) const
    {
        return ((m_string != NULL) && (index < m_length)) ? m_string[index] : '\0';
    }

    char& operator [](size_type index)
    {
        static char spare = '\0';
        return ((m_string != NULL) && (index < m_length)) ? m_string[index] : spare;
    }

    operator char const*() const throw()
    {
        return Ptr();
    }

    bool operator ==(char const* str) const
    {
        if (m_string == NULL)
            return str == NULL;
        return ::strcmp(m_string, str) == 0;
    }

    bool operator ==(TestString const& str) const
    {
        if (m_string == NULL)
            return str.m_string == NULL;
        return ::strcmp(m_string, str.Ptr()) == 0;
    }

public:
    char const* Ptr() const throw()
    {
        return m_string != NULL ? m_string : "";
    }

    size_type GetLength() const throw()
    {
        return m_length;
    }

    bool IsEmpty() const throw()
    {
        return m_string == NULL;
    }

    void Clear()
    {
        TestStringUtility::FastFree(m_string);
        m_string = NULL;
        m_length = 0;
    }

    bool Find(char ch, size_type& pos, size_type start = 0) const
    {
        if (m_string != NULL)
            return TestStringUtility::UnsafeFind(m_string, ch, pos, start);
        return false;
    }

    /// Extract a partial string, and optionally remove the partial string
    /// from this string.
    void GetSubString(TestString& sub_str,
                      size_type start,
                      size_type count,
                      bool remove = false)
    {
        sub_str.Clear();
        TestStringUtility::SafeReallocCopy(sub_str.m_string,
                                           sub_str.m_length,
                                           m_string + start,
                                           count);
        if (remove)
        {
            if (sub_str.m_length < m_length)
            {
                size_type chars_remaining = m_length - sub_str.m_length;
                ::memmove(m_string, m_string + sub_str.m_length, chars_remaining);
                *(m_string + chars_remaining) = '\0';
                m_length = chars_remaining;
            }
            else
                Clear();
        }
    }

    /// Replace the current sting with str.
    void Assign(char const* str)
    {
        TestStringUtility::SafeReallocCopy(m_string, m_length, str);
    }

    /// Replace the current sting with str.
    void Assign(TestString const& str)
    {
        TestStringUtility::SafeReallocCopy(m_string, m_length, str.m_string);
    }

    /// Move str into this string.
    void Move(char*& str, size_type len)
    {
        TestStringUtility::FastFree(m_string);
        m_string = str;
        m_length = len;
        str = NULL;
    }

    void Prepend(char const* str)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             str,
                                             privateSafeLength(str),
                                             m_string,
                                             m_length);
    }

    void Append(char const* str)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             m_string,
                                             m_length,
                                             str,
                                             privateSafeLength(str));
    }

    void Append(char const* str, size_type count)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             m_string,
                                             m_length,
                                             str,
                                             count);
    }

    void Append(TestString const& str)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             m_string,
                                             m_length,
                                             str.m_string,
                                             str.m_length);
    }

    /// Append a boolean converted to a "true" ot "false" string.
    void Append(bool value)
    {
        char const* str = value ? "true" : "false";
        Append(str);
    }

    /// Append a single character.
    void Append(char value)
    {
        char str[2];
        str[0] = value;
        str[1] = '\0';
        Append(str);
    }

    /// Append number of characters.
    void Append(char value, size_type count)
    {
        if (count > 0)
        {
            char* str = NULL;
            TestStringUtility::Allocate(str, count);
            if (str != NULL)
            {
                char* start = str;
                for (char* str_end = str + count; str < str_end; ++str)
                    *str = value;
                Append(start, count);
                TestStringUtility::FastFree(start);
            }
            else
                Append(value);
        }
    }

    /// Append number of characters then a string value.
    void Append(char ch, size_type count, char const* value, size_type len)
    {
        if (count > 0)
        {
            char* str = NULL;
            TestStringUtility::Allocate(str, count + len);
            if (str != NULL)
            {
                char* start = str;
                for (char* str_end = str + count; str < str_end; ++str)
                    *str = ch;
                ::memcpy(str, value, len + 1);
                Append(start, count + len);
                TestStringUtility::FastFree(start);
            }
            else
                Append(ch);
        }
        else
            Append(value, len);
    }

    void Append(signed char value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned char value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(signed short value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned short value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(signed int value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned int value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(signed long value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned long value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

private:
    template<typename T>
    void privateAppendValue(T value, size_type pad)
    {
        size_type length = 0;
        char* str = TestStringUtility::GetString(value, length);
        if (str != NULL)
        {
            if (IsEmpty() && (pad == 0))
                Move(str, length);
            else
            {
                if (pad > length)
                    Append('0', pad - length, str, length);
                else
                    Append(str, length);
                TestStringUtility::FastFree(str);
            }
        }
    }

    size_type privateSafeLength(char const* str)
    {
        return TestStringUtility::SafeLength(str);
    }

private:
    size_type m_length;
    char* m_string;
};

} // namespace ocl

#endif // OCL_GUARD_TEST_TESTSTRING_HPP
<commit_msg>Updated assignment operator to clear instead of copy empty string for TestString class.<commit_after>/*
Copyright 2016 Colin Girling

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.
*/

#ifndef OCL_GUARD_TEST_TESTSTRING_HPP
#define OCL_GUARD_TEST_TESTSTRING_HPP

#include "TestMemoryUtility.hpp"
#include "TestStringUtility.hpp"
#include <cstddef>
#include <cstdlib>
#include <cstring>

namespace ocl
{

/*
 * String class for test harness, with an interface complete enough for general usage.
 */

class TestString
{
public:
    typedef TestStringUtility::size_type size_type;

public:
    TestString(char const* str = NULL)
        : m_length(0)
        , m_string(NULL)
    {
        if (str != NULL)
            TestStringUtility::UnsafeAllocateCopy(m_string, m_length, str);
    }

    TestString(char ch, size_type len)
        : m_length(len)
        , m_string(NULL)
    {
        if (len > 0)
        {
            TestStringUtility::Allocate(m_string, len);
            if (m_string != NULL)
                TestStringUtility::UnsafeFill(m_string, ch, len);
            else
                m_length = 0;
        }
    }

    TestString(TestString const& str)
        : m_length(0)
        , m_string(NULL)
    {
        TestStringUtility::SafeAllocateCopy(m_string, m_length, str.m_string, str.m_length);
    }

    ~TestString()
    {
        TestStringUtility::FastFree(m_string);
    }

    TestString& operator =(char const* str)
    {
        if ((str != NULL) && (*str != '\0'))
            TestStringUtility::SafeReallocCopy(m_string, m_length, str);
        else
            Clear();
        return *this;
    }

    TestString& operator =(TestString const& str)
    {
        if ((str.m_string != NULL) && (*str.m_string != '\0') && (str.m_length > 0))
        {
            TestStringUtility::SafeReallocCopy(m_string,
                                               m_length,
                                               str.m_string,
                                               str.m_length);
        }
        else
            Clear();

        return *this;
    }

    TestString& operator +=(char const* str)
    {
        Append(str);
        return *this;
    }

    TestString& operator +=(TestString const& str)
    {
        Append(str);
        return *this;
    }

    char operator [](size_type index) const
    {
        return ((m_string != NULL) && (index < m_length)) ? m_string[index] : '\0';
    }

    char& operator [](size_type index)
    {
        static char spare = '\0';
        return ((m_string != NULL) && (index < m_length)) ? m_string[index] : spare;
    }

    operator char const*() const throw()
    {
        return Ptr();
    }

    bool operator ==(char const* str) const
    {
        if (m_string == NULL)
            return str == NULL;
        return ::strcmp(m_string, str) == 0;
    }

    bool operator ==(TestString const& str) const
    {
        if (m_string == NULL)
            return str.m_string == NULL;
        return ::strcmp(m_string, str.Ptr()) == 0;
    }

public:
    char const* Ptr() const throw()
    {
        return m_string != NULL ? m_string : "";
    }

    size_type GetLength() const throw()
    {
        return m_length;
    }

    bool IsEmpty() const throw()
    {
        return m_string == NULL;
    }

    void Clear()
    {
        TestStringUtility::FastFree(m_string);
        m_string = NULL;
        m_length = 0;
    }

    bool Find(char ch, size_type& pos, size_type start = 0) const
    {
        if (m_string != NULL)
            return TestStringUtility::UnsafeFind(m_string, ch, pos, start);
        return false;
    }

    /// Extract a partial string, and optionally remove the partial string
    /// from this string.
    void GetSubString(TestString& sub_str,
                      size_type start,
                      size_type count,
                      bool remove = false)
    {
        sub_str.Clear();
        TestStringUtility::SafeReallocCopy(sub_str.m_string,
                                           sub_str.m_length,
                                           m_string + start,
                                           count);
        if (remove)
        {
            if (sub_str.m_length < m_length)
            {
                size_type chars_remaining = m_length - sub_str.m_length;
                ::memmove(m_string, m_string + sub_str.m_length, chars_remaining);
                *(m_string + chars_remaining) = '\0';
                m_length = chars_remaining;
            }
            else
                Clear();
        }
    }

    /// Replace the current sting with str.
    void Assign(char const* str)
    {
        TestStringUtility::SafeReallocCopy(m_string, m_length, str);
    }

    /// Replace the current sting with str.
    void Assign(TestString const& str)
    {
        TestStringUtility::SafeReallocCopy(m_string, m_length, str.m_string);
    }

    /// Move str into this string.
    void Move(char*& str, size_type len)
    {
        TestStringUtility::FastFree(m_string);
        m_string = str;
        m_length = len;
        str = NULL;
    }

    void Prepend(char const* str)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             str,
                                             privateSafeLength(str),
                                             m_string,
                                             m_length);
    }

    void Append(char const* str)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             m_string,
                                             m_length,
                                             str,
                                             privateSafeLength(str));
    }

    void Append(char const* str, size_type count)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             m_string,
                                             m_length,
                                             str,
                                             count);
    }

    void Append(TestString const& str)
    {
        TestStringUtility::SafeReallocAppend(m_string,
                                             m_length,
                                             m_string,
                                             m_length,
                                             str.m_string,
                                             str.m_length);
    }

    /// Append a boolean converted to a "true" ot "false" string.
    void Append(bool value)
    {
        char const* str = value ? "true" : "false";
        Append(str);
    }

    /// Append a single character.
    void Append(char value)
    {
        char str[2];
        str[0] = value;
        str[1] = '\0';
        Append(str);
    }

    /// Append number of characters.
    void Append(char value, size_type count)
    {
        if (count > 0)
        {
            char* str = NULL;
            TestStringUtility::Allocate(str, count);
            if (str != NULL)
            {
                char* start = str;
                for (char* str_end = str + count; str < str_end; ++str)
                    *str = value;
                Append(start, count);
                TestStringUtility::FastFree(start);
            }
            else
                Append(value);
        }
    }

    /// Append number of characters then a string value.
    void Append(char ch, size_type count, char const* value, size_type len)
    {
        if (count > 0)
        {
            char* str = NULL;
            TestStringUtility::Allocate(str, count + len);
            if (str != NULL)
            {
                char* start = str;
                for (char* str_end = str + count; str < str_end; ++str)
                    *str = ch;
                ::memcpy(str, value, len + 1);
                Append(start, count + len);
                TestStringUtility::FastFree(start);
            }
            else
                Append(ch);
        }
        else
            Append(value, len);
    }

    void Append(signed char value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned char value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(signed short value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned short value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(signed int value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned int value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(signed long value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

    void Append(unsigned long value, size_type pad = 0)
    {
        privateAppendValue(value, pad);
    }

private:
    template<typename T>
    void privateAppendValue(T value, size_type pad)
    {
        size_type length = 0;
        char* str = TestStringUtility::GetString(value, length);
        if (str != NULL)
        {
            if (IsEmpty() && (pad == 0))
                Move(str, length);
            else
            {
                if (pad > length)
                    Append('0', pad - length, str, length);
                else
                    Append(str, length);
                TestStringUtility::FastFree(str);
            }
        }
    }

    size_type privateSafeLength(char const* str)
    {
        return TestStringUtility::SafeLength(str);
    }

private:
    size_type m_length;
    char* m_string;
};

} // namespace ocl

#endif // OCL_GUARD_TEST_TESTSTRING_HPP
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <fstream>
#ifdef ACTIONMONITOR_CS_PLUGIN

#include <os/ipclistener.h>
#include "csvirtualmachine.h"

CsVirtualMachine::CsVirtualMachine() :
  PowershellVirtualMachine()
{
}

CsVirtualMachine::~CsVirtualMachine()
{
}

/**
 * \brief Check if a given file extension is used by this API or not.
 * \param file the file we are checking
 * \return bool true|false if the given extension is powershell or not.
 */
bool CsVirtualMachine::IsExt(const MYODD_STRING& file)
{
  return myodd::files::IsExtension(file, _T("CS"));
}

/**
 * \brief create the full command line argument that will be passed to powershell
 * \param action the action we are working with
 * \param dllFullPath the full path of the dll
 * \param pluginPath the path to the plugin
 * \param uuid the unique id
 */
MYODD_STRING CsVirtualMachine::GetCommandLineArguments(
  const ActiveAction& action,
  const std::wstring& dllFullPath,
  const std::wstring& pluginPath,
  const std::wstring& uuid
)
{
  // the command is our class name.
  auto className = action.Command();

  // we want to create the powershell script
  auto script = myodd::strings::Format(

    L"# Press a key\n"
    L"function __amPressKey()\n"
    L"{\n"
    L"  #press key\n"
    L"  Write-Host -NoNewLine 'Press any key to continue...';\n"
    L"  $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');\n"
    L"}\n"
    L"\n"

    L"# Include the dll, (so the c# can access it)\n"
    L"Add-Type -Path \"%s\"\n"
    L"\n"

    L"# Create the Action monitor object to pass to the c# code\n"
    L"$am = New-Object Am.Core \"%s\"\n"
    L"\n"

    L"try {\n"
    L"  # Load the code.\n"
    L"  $code = [IO.File]::ReadAllText(\"%s\")\n"
    L"  \n"

    L"  # Pas it the common assemblies\n"
    L"  $assem = (\n"
    L"    \"System\",\n"
    L"    \"System.Core\",\n"
    L"    \"System.Xml.Linq\",\n"
    L"    \"System.Data.DataSetExtensions\",\n"
    L"    \"Microsoft.CSharp\",\n"
    L"    \"System.Data\",\n"
    L"    \"System.Net.Http\",\n"
    L"    \"System.Xml\",\n"
    L"    \"%s\"\n"
    L"  )\n"
    L"\n"
    L"  # Putting it all together\n"
    L"  Add-Type -TypeDefinition $code -ReferencedAssemblies $assem -Language CSharp\n"
    L"  $plugin = New-Object Am.%s $am\n"
    L"  [void]($plugin.Go())\n"
    L"\n"
    L"} catch {\n"
    L"  # Give the error message\n"
    L"  $ErrorMessage = $_.Exception.Message\n"
    L"\n"
    L"  $fullMessage = \"There was an error in script '%s', The error message was \"\"$ErrorMessage\"\"\"\n"
    L"  [void]($am.Log( 2, $fullMessage ))\n"
    L"  Write-Warning $fullMessage\n"
    L"  # And then wait\n"
    L"  __amPressKey;\n"
    L"}\n"
    , dllFullPath.c_str()   // create object
    , uuid.c_str()          // unique id
    , pluginPath.c_str()    // the code itself.
    , dllFullPath.c_str()   // assemblies
    , className.c_str()     // the class name
    , pluginPath.c_str()    // the code itself, (for the error).
  );

  std::wstring file;
  myodd::files::GetFullTempFileName(file, L"file", L"ps1");
  std::wofstream myfile;
  myfile.open(file.c_str());
  myfile << script.c_str();
  myfile.close();

  // The simply execute the
  return myodd::strings::Format(
    _T("-command \"&{$policy = Get-ExecutionPolicy; Set-ExecutionPolicy RemoteSigned -Force; Add-Type -Path '%s'; . '%s';Set-ExecutionPolicy $policy -Force; }\""),
    dllFullPath.c_str(),
    file.c_str()
  );
}
#endif /*ACTIONMONITOR_CS_PLUGIN*/<commit_msg>Added a couple more assemblies ... still testing<commit_after>#include "stdafx.h"
#include <fstream>
#ifdef ACTIONMONITOR_CS_PLUGIN

#include <os/ipclistener.h>
#include "csvirtualmachine.h"

CsVirtualMachine::CsVirtualMachine() :
  PowershellVirtualMachine()
{
}

CsVirtualMachine::~CsVirtualMachine()
{
}

/**
 * \brief Check if a given file extension is used by this API or not.
 * \param file the file we are checking
 * \return bool true|false if the given extension is powershell or not.
 */
bool CsVirtualMachine::IsExt(const MYODD_STRING& file)
{
  return myodd::files::IsExtension(file, _T("CS"));
}

/**
 * \brief create the full command line argument that will be passed to powershell
 * \param action the action we are working with
 * \param dllFullPath the full path of the dll
 * \param pluginPath the path to the plugin
 * \param uuid the unique id
 */
MYODD_STRING CsVirtualMachine::GetCommandLineArguments(
  const ActiveAction& action,
  const std::wstring& dllFullPath,
  const std::wstring& pluginPath,
  const std::wstring& uuid
)
{
  // the command is our class name.
  auto className = action.Command();

  // we want to create the powershell script
  auto script = myodd::strings::Format(

    L"# Press a key\n"
    L"function __amPressKey()\n"
    L"{\n"
    L"  #press key\n"
    L"  Write-Host -NoNewLine 'Press any key to continue...';\n"
    L"  $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');\n"
    L"}\n"
    L"\n"

    L"# Include the dll, (so the c# can access it)\n"
    L"Add-Type -Path \"%s\"\n"
    L"\n"

    L"# Create the Action monitor object to pass to the c# code\n"
    L"$am = New-Object Am.Core \"%s\"\n"
    L"\n"

    L"try {\n"
    L"  # Load the code.\n"
    L"  $code = [IO.File]::ReadAllText(\"%s\")\n"
    L"  \n"

    L"  # Pas it the common assemblies\n"
    L"  $assem = (\n"
    L"    \"System\",\n"
    L"    \"System.Core\",\n"
    L"    \"System.Collections.Generic\",\n"
    L"    \"System.Linq\",\n"
    L"    \"System.Text\",\n"
    L"    \"System.Threading.Tasks\",\n"
    L"    \"System.Data\",\n"
    L"    \"System.Net.Http\",\n"
    L"    \"System.Xml\",\n"
    L"    \"System.Xml.Linq\",\n"
    L"    \"System.Data.DataSetExtensions\",\n"
    L"    \"Microsoft.CSharp\",\n"
    L"    \"%s\"\n"
    L"  )\n"
    L"\n"
    L"  # Putting it all together\n"
    L"  Add-Type -TypeDefinition $code -ReferencedAssemblies $assem -Language CSharp\n"
    L"  $plugin = New-Object Am.%s $am\n"
    L"  [void]($plugin.Go())\n"
    L"\n"
    L"} catch {\n"
    L"  # Give the error message\n"
    L"  $ErrorMessage = $_.Exception.Message\n"
    L"\n"
    L"  $fullMessage = \"There was an error in script '%s', The error message was \"\"$ErrorMessage\"\"\"\n"
    L"  [void]($am.Log( 2, $fullMessage ))\n"
    L"  Write-Warning $fullMessage\n"
    L"  # And then wait\n"
    L"  __amPressKey;\n"
    L"}\n"
    , dllFullPath.c_str()   // create object
    , uuid.c_str()          // unique id
    , pluginPath.c_str()    // the code itself.
    , dllFullPath.c_str()   // assemblies
    , className.c_str()     // the class name
    , pluginPath.c_str()    // the code itself, (for the error).
  );

  std::wstring file;
  myodd::files::GetFullTempFileName(file, L"file", L"ps1");
  std::wofstream myfile;
  myfile.open(file.c_str());
  myfile << script.c_str();
  myfile.close();

  // The simply execute the
  return myodd::strings::Format(
    _T("-command \"&{$policy = Get-ExecutionPolicy; Set-ExecutionPolicy RemoteSigned -Force; Add-Type -Path '%s'; . '%s';Set-ExecutionPolicy $policy -Force; }\""),
    dllFullPath.c_str(),
    file.c_str()
  );
}
#endif /*ACTIONMONITOR_CS_PLUGIN*/<|endoftext|>


<commit_before>//===-- clang-doc/HTMLGeneratorTest.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "ClangDocTest.h"
#include "Generators.h"
#include "Representation.h"
#include "gtest/gtest.h"

namespace clang {
namespace doc {

std::unique_ptr<Generator> getHTMLGenerator() {
  auto G = doc::findGeneratorByName("html");
  if (!G)
    return nullptr;
  return std::move(G.get());
}

ClangDocContext
getClangDocContext(std::vector<std::string> UserStylesheets = {}) {
  ClangDocContext CDCtx;
  CDCtx.UserStylesheets = {UserStylesheets.begin(), UserStylesheets.end()};
  CDCtx.UserStylesheets.insert(
      CDCtx.UserStylesheets.begin(),
      "../share/clang/clang-doc-default-stylesheet.css");
  return CDCtx;
}

TEST(HTMLGeneratorTest, emitNamespaceHTML) {
  NamespaceInfo I;
  I.Name = "Namespace";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.ChildNamespaces.emplace_back(EmptySID, "ChildNamespace",
                                 InfoType::IT_namespace);
  I.ChildRecords.emplace_back(EmptySID, "ChildStruct", InfoType::IT_record);
  I.ChildFunctions.emplace_back();
  I.ChildFunctions.back().Name = "OneFunction";
  I.ChildEnums.emplace_back();
  I.ChildEnums.back().Name = "OneEnum";

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext({"user-provided-stylesheet.css"});
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title>namespace Namespace</title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>
<link rel="stylesheet" href="user-provided-stylesheet.css"/>

namespace Namespace

Namespaces

ChildNamespace

Records

ChildStruct

Functions

OneFunction

OneFunction()

Enums

enum OneEnum

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitRecordHTML) {
  RecordInfo I;
  I.Name = "r";
  I.Path = "X/Y/Z";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.Loc.emplace_back(12, llvm::SmallString<16>{"test.cpp"});

  SmallString<16> PathTo;
  llvm::sys::path::native("path/to", PathTo);
  I.Members.emplace_back("int", "X/Y", "X", AccessSpecifier::AS_private);
  I.TagType = TagTypeKind::TTK_Class;
  I.Parents.emplace_back(EmptySID, "F", InfoType::IT_record, PathTo);
  I.VirtualParents.emplace_back(EmptySID, "G", InfoType::IT_record);

  I.ChildRecords.emplace_back(EmptySID, "ChildStruct", InfoType::IT_record);
  I.ChildFunctions.emplace_back();
  I.ChildFunctions.back().Name = "OneFunction";
  I.ChildEnums.emplace_back();
  I.ChildEnums.back().Name = "OneEnum";

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  SmallString<16> PathToF;
  llvm::sys::path::native("../../../path/to/F.html", PathToF);
  SmallString<16> PathToInt;
  llvm::sys::path::native("../int.html", PathToInt);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title>class r</title>
<link rel="stylesheet" href="../../../clang-doc-default-stylesheet.css"/>

class r

Defined at line 10 of test.cpp

    Inherits from
    F
    , G

Members

      private
      int
       X

Records

ChildStruct

Functions

OneFunction

OneFunction()

Enums

enum OneEnum

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitFunctionHTML) {
  FunctionInfo I;
  I.Name = "f";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.Loc.emplace_back(12, llvm::SmallString<16>{"test.cpp"});

  SmallString<16> PathTo;
  llvm::sys::path::native("path/to", PathTo);
  I.ReturnType = TypeInfo(EmptySID, "float", InfoType::IT_default, PathTo);
  I.Params.emplace_back("int", PathTo, "P");
  I.IsMethod = true;
  I.Parent = Reference(EmptySID, "Parent", InfoType::IT_record);

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  SmallString<16> PathToFloat;
  llvm::sys::path::native("path/to/float.html", PathToFloat);
  SmallString<16> PathToInt;
  llvm::sys::path::native("path/to/int.html", PathToInt);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title></title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>

f

    float
     f(
    int
     P)

Defined at line 10 of test.cpp

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitEnumHTML) {
  EnumInfo I;
  I.Name = "e";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.Loc.emplace_back(12, llvm::SmallString<16>{"test.cpp"});

  I.Members.emplace_back("X");
  I.Scoped = true;

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title></title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>

enum class e

X

Defined at line 10 of test.cpp

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitCommentHTML) {
  FunctionInfo I;
  I.Name = "f";
  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.ReturnType = TypeInfo(EmptySID, "void", InfoType::IT_default);
  I.Params.emplace_back("int", "I");
  I.Params.emplace_back("int", "J");

  CommentInfo Top;
  Top.Kind = "FullComment";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *BlankLine = Top.Children.back().get();
  BlankLine->Kind = "ParagraphComment";
  BlankLine->Children.emplace_back(llvm::make_unique<CommentInfo>());
  BlankLine->Children.back()->Kind = "TextComment";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *Brief = Top.Children.back().get();
  Brief->Kind = "ParagraphComment";
  Brief->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Brief->Children.back()->Kind = "TextComment";
  Brief->Children.back()->Name = "ParagraphComment";
  Brief->Children.back()->Text = " Brief description.";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *Extended = Top.Children.back().get();
  Extended->Kind = "ParagraphComment";
  Extended->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Extended->Children.back()->Kind = "TextComment";
  Extended->Children.back()->Text = " Extended description that";
  Extended->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Extended->Children.back()->Kind = "TextComment";
  Extended->Children.back()->Text = " continues onto the next line.";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *Entities = Top.Children.back().get();
  Entities->Kind = "ParagraphComment";
  Entities->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Entities->Children.back()->Kind = "TextComment";
  Entities->Children.back()->Name = "ParagraphComment";
  Entities->Children.back()->Text =
      " Comment with html entities: &, <, >, \", \'.";

  I.Description.emplace_back(std::move(Top));

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title></title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>

f

void f(int I, int J)

Defined at line 10 of test.cpp

 Brief description.

 Extended description that continues onto the next line.

 Comment with html entities: &, <, >, ", '.

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

} // namespace doc
} // namespace clang
<commit_msg>[clang-doc] Fix failing tests on Windows<commit_after>//===-- clang-doc/HTMLGeneratorTest.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "ClangDocTest.h"
#include "Generators.h"
#include "Representation.h"
#include "gtest/gtest.h"

namespace clang {
namespace doc {

std::unique_ptr<Generator> getHTMLGenerator() {
  auto G = doc::findGeneratorByName("html");
  if (!G)
    return nullptr;
  return std::move(G.get());
}

ClangDocContext
getClangDocContext(std::vector<std::string> UserStylesheets = {}) {
  ClangDocContext CDCtx;
  CDCtx.UserStylesheets = {UserStylesheets.begin(), UserStylesheets.end()};
  CDCtx.UserStylesheets.insert(
      CDCtx.UserStylesheets.begin(),
      "../share/clang/clang-doc-default-stylesheet.css");
  return CDCtx;
}

TEST(HTMLGeneratorTest, emitNamespaceHTML) {
  NamespaceInfo I;
  I.Name = "Namespace";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.ChildNamespaces.emplace_back(EmptySID, "ChildNamespace",
                                 InfoType::IT_namespace);
  I.ChildRecords.emplace_back(EmptySID, "ChildStruct", InfoType::IT_record);
  I.ChildFunctions.emplace_back();
  I.ChildFunctions.back().Name = "OneFunction";
  I.ChildEnums.emplace_back();
  I.ChildEnums.back().Name = "OneEnum";

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext({"user-provided-stylesheet.css"});
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title>namespace Namespace</title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>
<link rel="stylesheet" href="user-provided-stylesheet.css"/>

namespace Namespace

Namespaces

ChildNamespace

Records

ChildStruct

Functions

OneFunction

OneFunction()

Enums

enum OneEnum

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitRecordHTML) {
  RecordInfo I;
  I.Name = "r";
  I.Path = "X/Y/Z";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.Loc.emplace_back(12, llvm::SmallString<16>{"test.cpp"});

  SmallString<16> PathTo;
  llvm::sys::path::native("path/to", PathTo);
  I.Members.emplace_back("int", "X/Y", "X", AccessSpecifier::AS_private);
  I.TagType = TagTypeKind::TTK_Class;
  I.Parents.emplace_back(EmptySID, "F", InfoType::IT_record, PathTo);
  I.VirtualParents.emplace_back(EmptySID, "G", InfoType::IT_record);

  I.ChildRecords.emplace_back(EmptySID, "ChildStruct", InfoType::IT_record);
  I.ChildFunctions.emplace_back();
  I.ChildFunctions.back().Name = "OneFunction";
  I.ChildEnums.emplace_back();
  I.ChildEnums.back().Name = "OneEnum";

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  SmallString<16> PathToF;
  llvm::sys::path::native("../../../path/to/F.html", PathToF);
  SmallString<16> PathToInt;
  llvm::sys::path::native("../int.html", PathToInt);
  SmallString<16> PathToSylesheet;
  llvm::sys::path::native("../../../clang-doc-default-stylesheet.css",
                          PathToSylesheet);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title>class r</title>
<link rel="stylesheet" href=")raw" +
                         std::string(PathToSylesheet.str()) +
                         R"raw("/>

class r

Defined at line 10 of test.cpp

    Inherits from
    F
    , G

Members

      private
      int
       X

Records

ChildStruct

Functions

OneFunction

OneFunction()

Enums

enum OneEnum

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitFunctionHTML) {
  FunctionInfo I;
  I.Name = "f";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.Loc.emplace_back(12, llvm::SmallString<16>{"test.cpp"});

  SmallString<16> PathTo;
  llvm::sys::path::native("path/to", PathTo);
  I.ReturnType = TypeInfo(EmptySID, "float", InfoType::IT_default, PathTo);
  I.Params.emplace_back("int", PathTo, "P");
  I.IsMethod = true;
  I.Parent = Reference(EmptySID, "Parent", InfoType::IT_record);

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  SmallString<16> PathToFloat;
  llvm::sys::path::native("path/to/float.html", PathToFloat);
  SmallString<16> PathToInt;
  llvm::sys::path::native("path/to/int.html", PathToInt);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title></title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>

f

    float
     f(
    int
     P)

Defined at line 10 of test.cpp

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitEnumHTML) {
  EnumInfo I;
  I.Name = "e";
  I.Namespace.emplace_back(EmptySID, "A", InfoType::IT_namespace);

  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.Loc.emplace_back(12, llvm::SmallString<16>{"test.cpp"});

  I.Members.emplace_back("X");
  I.Scoped = true;

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title></title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>

enum class e

X

Defined at line 10 of test.cpp

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

TEST(HTMLGeneratorTest, emitCommentHTML) {
  FunctionInfo I;
  I.Name = "f";
  I.DefLoc = Location(10, llvm::SmallString<16>{"test.cpp"});
  I.ReturnType = TypeInfo(EmptySID, "void", InfoType::IT_default);
  I.Params.emplace_back("int", "I");
  I.Params.emplace_back("int", "J");

  CommentInfo Top;
  Top.Kind = "FullComment";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *BlankLine = Top.Children.back().get();
  BlankLine->Kind = "ParagraphComment";
  BlankLine->Children.emplace_back(llvm::make_unique<CommentInfo>());
  BlankLine->Children.back()->Kind = "TextComment";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *Brief = Top.Children.back().get();
  Brief->Kind = "ParagraphComment";
  Brief->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Brief->Children.back()->Kind = "TextComment";
  Brief->Children.back()->Name = "ParagraphComment";
  Brief->Children.back()->Text = " Brief description.";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *Extended = Top.Children.back().get();
  Extended->Kind = "ParagraphComment";
  Extended->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Extended->Children.back()->Kind = "TextComment";
  Extended->Children.back()->Text = " Extended description that";
  Extended->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Extended->Children.back()->Kind = "TextComment";
  Extended->Children.back()->Text = " continues onto the next line.";

  Top.Children.emplace_back(llvm::make_unique<CommentInfo>());
  CommentInfo *Entities = Top.Children.back().get();
  Entities->Kind = "ParagraphComment";
  Entities->Children.emplace_back(llvm::make_unique<CommentInfo>());
  Entities->Children.back()->Kind = "TextComment";
  Entities->Children.back()->Name = "ParagraphComment";
  Entities->Children.back()->Text =
      " Comment with html entities: &, <, >, \", \'.";

  I.Description.emplace_back(std::move(Top));

  auto G = getHTMLGenerator();
  assert(G);
  std::string Buffer;
  llvm::raw_string_ostream Actual(Buffer);
  ClangDocContext CDCtx = getClangDocContext();
  auto Err = G->generateDocForInfo(&I, Actual, CDCtx);
  assert(!Err);
  std::string Expected = R"raw(<!DOCTYPE html>
<meta charset="utf-8"/>
<title></title>
<link rel="stylesheet" href="clang-doc-default-stylesheet.css"/>

f

void f(int I, int J)

Defined at line 10 of test.cpp

 Brief description.

 Extended description that continues onto the next line.

 Comment with html entities: &, <, >, ", '.

)raw";

  EXPECT_EQ(Expected, Actual.str());
}

} // namespace doc
} // namespace clang
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: hints.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 10:10:21 $
 *
 *  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 SC_HINTS_HXX
#define SC_HINTS_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif

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

class ScPaintHint : public SfxHint
{
    ScRange     aRange;
    USHORT      nParts;
    BOOL        bPrint;     //  Flag, ob auch Druck/Vorschau betroffen ist

public:
                    TYPEINFO();
                    ScPaintHint();
                    ScPaintHint( const ScRange& rRng, USHORT nPaint = PAINT_ALL );
                    ~ScPaintHint();

    void            SetPrintFlag(BOOL bSet) { bPrint = bSet; }

    const ScRange&  GetRange() const        { return aRange; }
    SCCOL           GetStartCol() const     { return aRange.aStart.Col(); }
    SCROW           GetStartRow() const     { return aRange.aStart.Row(); }
    SCTAB           GetStartTab() const     { return aRange.aStart.Tab(); }
    SCCOL           GetEndCol() const       { return aRange.aEnd.Col(); }
    SCROW           GetEndRow() const       { return aRange.aEnd.Row(); }
    SCTAB           GetEndTab() const       { return aRange.aEnd.Tab(); }
    USHORT          GetParts() const        { return nParts; }
    BOOL            GetPrintFlag() const    { return bPrint; }
};

class ScUpdateRefHint : public SfxHint
{
    UpdateRefMode   eUpdateRefMode;
    ScRange         aRange;
    SCsCOL          nDx;
    SCsROW          nDy;
    SCsTAB          nDz;

public:
                    TYPEINFO();

                    ScUpdateRefHint( UpdateRefMode eMode, const ScRange& rR,
                                        SCsCOL nX, SCsROW nY, SCsTAB nZ );
                    ~ScUpdateRefHint();

    UpdateRefMode   GetMode() const         { return eUpdateRefMode; }
    const ScRange&  GetRange() const        { return aRange; }
    SCsCOL          GetDx() const           { return nDx; }
    SCsROW          GetDy() const           { return nDy; }
    SCsTAB          GetDz() const           { return nDz; }
};

#define SC_POINTERCHANGED_NUMFMT    1

class ScPointerChangedHint : public SfxHint
{
    USHORT          nFlags;

public:
                    TYPEINFO();

                    ScPointerChangedHint( USHORT nF );
                    ~ScPointerChangedHint();

    USHORT          GetFlags() const            { return nFlags; }
};

//! move ScLinkRefreshedHint to a different file?

#define SC_LINKREFTYPE_NONE     0
#define SC_LINKREFTYPE_SHEET    1
#define SC_LINKREFTYPE_AREA     2
#define SC_LINKREFTYPE_DDE      3

class ScLinkRefreshedHint : public SfxHint
{
    USHORT      nLinkType;  // SC_LINKREFTYPE_...
    String      aUrl;       // used for sheet links
    String      aDdeAppl;   // used for dde links:
    String      aDdeTopic;
    String      aDdeItem;
    BYTE        nDdeMode;
    ScAddress   aDestPos;   // used to identify area links
                            //! also use source data for area links?

public:
                    TYPEINFO();
                    ScLinkRefreshedHint();
                    ~ScLinkRefreshedHint();

    void            SetSheetLink( const String& rSourceUrl );
    void            SetDdeLink( const String& rA, const String& rT, const String& rI, BYTE nM );
    void            SetAreaLink( const ScAddress& rPos );

    USHORT              GetLinkType() const { return nLinkType; }
    const String&       GetUrl() const      { return aUrl; }
    const String&       GetDdeAppl() const  { return aDdeAppl; }
    const String&       GetDdeTopic() const { return aDdeTopic; }
    const String&       GetDdeItem() const  { return aDdeItem; }
    BYTE                GetDdeMode() const  { return nDdeMode; }
    const ScAddress&    GetDestPos() const  { return aDestPos; }
};

//! move ScAutoStyleHint to a different file?

class ScAutoStyleHint : public SfxHint
{
    ScRange     aRange;
    String      aStyle1;
    String      aStyle2;
    ULONG       nTimeout;

public:
                    TYPEINFO();
                    ScAutoStyleHint( const ScRange& rR, const String& rSt1,
                                        ULONG nT, const String& rSt2 );
                    ~ScAutoStyleHint();

    const ScRange&  GetRange() const    { return aRange; }
    const String&   GetStyle1() const   { return aStyle1; }
    UINT32          GetTimeout() const  { return nTimeout; }
    const String&   GetStyle2() const   { return aStyle2; }
};

class ScDBRangeRefreshedHint : public SfxHint
{
    ScImportParam   aParam;

public:
                    TYPEINFO();
                    ScDBRangeRefreshedHint( const ScImportParam& rP );
                    ~ScDBRangeRefreshedHint();

    const ScImportParam&  GetImportParam() const    { return aParam; }
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.452); FILE MERGED 2005/09/05 15:00:48 rt 1.3.452.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hints.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:42:23 $
 *
 *  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 SC_HINTS_HXX
#define SC_HINTS_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif

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

class ScPaintHint : public SfxHint
{
    ScRange     aRange;
    USHORT      nParts;
    BOOL        bPrint;     //  Flag, ob auch Druck/Vorschau betroffen ist

public:
                    TYPEINFO();
                    ScPaintHint();
                    ScPaintHint( const ScRange& rRng, USHORT nPaint = PAINT_ALL );
                    ~ScPaintHint();

    void            SetPrintFlag(BOOL bSet) { bPrint = bSet; }

    const ScRange&  GetRange() const        { return aRange; }
    SCCOL           GetStartCol() const     { return aRange.aStart.Col(); }
    SCROW           GetStartRow() const     { return aRange.aStart.Row(); }
    SCTAB           GetStartTab() const     { return aRange.aStart.Tab(); }
    SCCOL           GetEndCol() const       { return aRange.aEnd.Col(); }
    SCROW           GetEndRow() const       { return aRange.aEnd.Row(); }
    SCTAB           GetEndTab() const       { return aRange.aEnd.Tab(); }
    USHORT          GetParts() const        { return nParts; }
    BOOL            GetPrintFlag() const    { return bPrint; }
};

class ScUpdateRefHint : public SfxHint
{
    UpdateRefMode   eUpdateRefMode;
    ScRange         aRange;
    SCsCOL          nDx;
    SCsROW          nDy;
    SCsTAB          nDz;

public:
                    TYPEINFO();

                    ScUpdateRefHint( UpdateRefMode eMode, const ScRange& rR,
                                        SCsCOL nX, SCsROW nY, SCsTAB nZ );
                    ~ScUpdateRefHint();

    UpdateRefMode   GetMode() const         { return eUpdateRefMode; }
    const ScRange&  GetRange() const        { return aRange; }
    SCsCOL          GetDx() const           { return nDx; }
    SCsROW          GetDy() const           { return nDy; }
    SCsTAB          GetDz() const           { return nDz; }
};

#define SC_POINTERCHANGED_NUMFMT    1

class ScPointerChangedHint : public SfxHint
{
    USHORT          nFlags;

public:
                    TYPEINFO();

                    ScPointerChangedHint( USHORT nF );
                    ~ScPointerChangedHint();

    USHORT          GetFlags() const            { return nFlags; }
};

//! move ScLinkRefreshedHint to a different file?

#define SC_LINKREFTYPE_NONE     0
#define SC_LINKREFTYPE_SHEET    1
#define SC_LINKREFTYPE_AREA     2
#define SC_LINKREFTYPE_DDE      3

class ScLinkRefreshedHint : public SfxHint
{
    USHORT      nLinkType;  // SC_LINKREFTYPE_...
    String      aUrl;       // used for sheet links
    String      aDdeAppl;   // used for dde links:
    String      aDdeTopic;
    String      aDdeItem;
    BYTE        nDdeMode;
    ScAddress   aDestPos;   // used to identify area links
                            //! also use source data for area links?

public:
                    TYPEINFO();
                    ScLinkRefreshedHint();
                    ~ScLinkRefreshedHint();

    void            SetSheetLink( const String& rSourceUrl );
    void            SetDdeLink( const String& rA, const String& rT, const String& rI, BYTE nM );
    void            SetAreaLink( const ScAddress& rPos );

    USHORT              GetLinkType() const { return nLinkType; }
    const String&       GetUrl() const      { return aUrl; }
    const String&       GetDdeAppl() const  { return aDdeAppl; }
    const String&       GetDdeTopic() const { return aDdeTopic; }
    const String&       GetDdeItem() const  { return aDdeItem; }
    BYTE                GetDdeMode() const  { return nDdeMode; }
    const ScAddress&    GetDestPos() const  { return aDestPos; }
};

//! move ScAutoStyleHint to a different file?

class ScAutoStyleHint : public SfxHint
{
    ScRange     aRange;
    String      aStyle1;
    String      aStyle2;
    ULONG       nTimeout;

public:
                    TYPEINFO();
                    ScAutoStyleHint( const ScRange& rR, const String& rSt1,
                                        ULONG nT, const String& rSt2 );
                    ~ScAutoStyleHint();

    const ScRange&  GetRange() const    { return aRange; }
    const String&   GetStyle1() const   { return aStyle1; }
    UINT32          GetTimeout() const  { return nTimeout; }
    const String&   GetStyle2() const   { return aStyle2; }
};

class ScDBRangeRefreshedHint : public SfxHint
{
    ScImportParam   aParam;

public:
                    TYPEINFO();
                    ScDBRangeRefreshedHint( const ScImportParam& rP );
                    ~ScDBRangeRefreshedHint();

    const ScImportParam&  GetImportParam() const    { return aParam; }
};

#endif
<|endoftext|>


<commit_before>#include <cxxtest/TestSuite.h>
#include <typeinfo>
#include "dicek/vector.hpp"

class VectorTest : public CxxTest::TestSuite {
public:
    using vector3d = dicek::math::vector<3,double>;

    void testDIM( void )
    {
        static_assert( vector3d::DIM == 3, "vector<3,double>::DIM is not 3" );
        TSM_ASSERT_EQUALS( "vector<3,double>::DIM is not 3", 3, ( vector3d::DIM ) );
    }

    void test_real_type( void )
    {
        static_assert( std::is_same< vector3d::real_type, double>::value, "vector3d::real_type is not double" );
        TSM_ASSERT( "vector3d::real_type is not double", typeid( vector3d::real_type ) == typeid( double ) );
    }

    void test_default_constructor( void )
    {
        vector3d v;
        TSM_ASSERT_EQUALS( "Not zero", v[ 0 ], 0 );
        TSM_ASSERT_EQUALS( "Not zero", v[ 1 ], 0 );
        TSM_ASSERT_EQUALS( "Not zero", v[ 2 ], 0 );
    }

    void test_at( void )
    {
        vector3d v;
        v.at( 0 ) = 5;
        v.at( 1 ) = 7;
        v.at( 2 ) = 11;

        TSM_ASSERT_EQUALS( "at(0) is not 5", v.at( 0 ), 5 );
        TSM_ASSERT_EQUALS( "at(1) is not 7", v.at( 1 ), 7 );
        TSM_ASSERT_EQUALS( "at(2) is not 11", v.at( 2 ), 11 );
    }

    void test_at_const( void )
    {
        vector3d v;
        v.at( 0 ) = 13;
        v.at( 1 ) = 17;
        v.at( 2 ) = 19;

        const auto& ref = v;

        TSM_ASSERT_EQUALS( "at(0) is not 13", ref.at( 0 ), 13 );
        TSM_ASSERT_EQUALS( "at(1) is not 17", ref.at( 1 ), 17 );
        TSM_ASSERT_EQUALS( "at(2) is not 19", ref.at( 2 ), 19 );
    }

    void test_at_throw( void )
    {
        vector3d v;
        TSM_ASSERT_THROWS( "Exception not thrown", v.at( 3 ), std::out_of_range );
        TSM_ASSERT_THROWS( "Exception not thrown", const_cast<const decltype( v )&>( v ).at( 3 ), std::out_of_range );
    }

    void test_operator_square_bracket( void )
    {
        vector3d v;
        v[ 0 ] = 5;
        v[ 1 ] = 7;
        v[ 2 ] = 11;

        TSM_ASSERT_EQUALS( "operator[](0) is not 5", v[ 0 ], 5 );
        TSM_ASSERT_EQUALS( "operator[](1) is not 7", v[ 1 ], 7 );
        TSM_ASSERT_EQUALS( "operator[](2) is not 11", v[ 2 ], 11 );
    }

    void test_operator_square_bracket_const( void )
    {
        vector3d v;
        v[ 0 ] = 13;
        v[ 1 ] = 17;
        v[ 2 ] = 19;

        const auto& ref = v;

        TSM_ASSERT_EQUALS( "operator[](0) is not 13", ref[ 0 ], 13 );
        TSM_ASSERT_EQUALS( "operator[](1) is not 17", ref[ 1 ], 17 );
        TSM_ASSERT_EQUALS( "operator[](2) is not 19", ref[ 2 ], 19 );
    }

    void test_operator_add( void )
    {
        vector3d v, w;
        v[ 0 ] = 1;
        v[ 1 ] = 2;
        v[ 2 ] = 3;

        w[ 0 ] = 10;
        w[ 1 ] = 20;
        w[ 2 ] = 30;

        const auto& _v = v;
        const auto& _w = w;

        vector3d x = _v + _w;
        vector3d y = _w + _v;

        TSM_ASSERT_EQUALS( "operator+ is not 11", x[ 0 ], 11 );
        TSM_ASSERT_EQUALS( "operator+ is not 22", x[ 1 ], 22 );
        TSM_ASSERT_EQUALS( "operator+ is not 33", x[ 2 ], 33 );

        TSM_ASSERT_EQUALS( "operator+ is not 11", y[ 0 ], 11 );
        TSM_ASSERT_EQUALS( "operator+ is not 22", y[ 1 ], 22 );
        TSM_ASSERT_EQUALS( "operator+ is not 33", y[ 2 ], 33 );
    }
};
<commit_msg>Add whitespace<commit_after>#include <cxxtest/TestSuite.h>
#include <typeinfo>
#include "dicek/vector.hpp"

class VectorTest : public CxxTest::TestSuite {
public:
    using vector3d = dicek::math::vector<3, double>;

    void testDIM( void )
    {
        static_assert( vector3d::DIM == 3, "vector<3,double>::DIM is not 3" );
        TSM_ASSERT_EQUALS( "vector<3,double>::DIM is not 3", 3, ( vector3d::DIM ) );
    }

    void test_real_type( void )
    {
        static_assert( std::is_same< vector3d::real_type, double>::value, "vector3d::real_type is not double" );
        TSM_ASSERT( "vector3d::real_type is not double", typeid( vector3d::real_type ) == typeid( double ) );
    }

    void test_default_constructor( void )
    {
        vector3d v;
        TSM_ASSERT_EQUALS( "Not zero", v[ 0 ], 0 );
        TSM_ASSERT_EQUALS( "Not zero", v[ 1 ], 0 );
        TSM_ASSERT_EQUALS( "Not zero", v[ 2 ], 0 );
    }

    void test_at( void )
    {
        vector3d v;
        v.at( 0 ) = 5;
        v.at( 1 ) = 7;
        v.at( 2 ) = 11;

        TSM_ASSERT_EQUALS( "at(0) is not 5", v.at( 0 ), 5 );
        TSM_ASSERT_EQUALS( "at(1) is not 7", v.at( 1 ), 7 );
        TSM_ASSERT_EQUALS( "at(2) is not 11", v.at( 2 ), 11 );
    }

    void test_at_const( void )
    {
        vector3d v;
        v.at( 0 ) = 13;
        v.at( 1 ) = 17;
        v.at( 2 ) = 19;

        const auto& ref = v;

        TSM_ASSERT_EQUALS( "at(0) is not 13", ref.at( 0 ), 13 );
        TSM_ASSERT_EQUALS( "at(1) is not 17", ref.at( 1 ), 17 );
        TSM_ASSERT_EQUALS( "at(2) is not 19", ref.at( 2 ), 19 );
    }

    void test_at_throw( void )
    {
        vector3d v;
        TSM_ASSERT_THROWS( "Exception not thrown", v.at( 3 ), std::out_of_range );
        TSM_ASSERT_THROWS( "Exception not thrown", const_cast<const decltype( v )&>( v ).at( 3 ), std::out_of_range );
    }

    void test_operator_square_bracket( void )
    {
        vector3d v;
        v[ 0 ] = 5;
        v[ 1 ] = 7;
        v[ 2 ] = 11;

        TSM_ASSERT_EQUALS( "operator[](0) is not 5", v[ 0 ], 5 );
        TSM_ASSERT_EQUALS( "operator[](1) is not 7", v[ 1 ], 7 );
        TSM_ASSERT_EQUALS( "operator[](2) is not 11", v[ 2 ], 11 );
    }

    void test_operator_square_bracket_const( void )
    {
        vector3d v;
        v[ 0 ] = 13;
        v[ 1 ] = 17;
        v[ 2 ] = 19;

        const auto& ref = v;

        TSM_ASSERT_EQUALS( "operator[](0) is not 13", ref[ 0 ], 13 );
        TSM_ASSERT_EQUALS( "operator[](1) is not 17", ref[ 1 ], 17 );
        TSM_ASSERT_EQUALS( "operator[](2) is not 19", ref[ 2 ], 19 );
    }

    void test_operator_add( void )
    {
        vector3d v, w;
        v[ 0 ] = 1;
        v[ 1 ] = 2;
        v[ 2 ] = 3;

        w[ 0 ] = 10;
        w[ 1 ] = 20;
        w[ 2 ] = 30;

        const auto& _v = v;
        const auto& _w = w;

        vector3d x = _v + _w;
        vector3d y = _w + _v;

        TSM_ASSERT_EQUALS( "operator+ is not 11", x[ 0 ], 11 );
        TSM_ASSERT_EQUALS( "operator+ is not 22", x[ 1 ], 22 );
        TSM_ASSERT_EQUALS( "operator+ is not 33", x[ 2 ], 33 );

        TSM_ASSERT_EQUALS( "operator+ is not 11", y[ 0 ], x[ 0 ] );
        TSM_ASSERT_EQUALS( "operator+ is not 22", y[ 1 ], x[ 1 ] );
        TSM_ASSERT_EQUALS( "operator+ is not 33", y[ 2 ], x[ 2 ] );
    }
};
<|endoftext|>


<commit_before>#include "board.h"
#include "eventblock.h"
#include "subjectblock.h"
#include "cornerblock.h"

Board::Board()
{
    boards = new Block*[36];

	boards[0] = new CornerBlock;

	static_cast<SubjectBlock*>boards[1] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[2] = new SUbjectBlock;
	static_cast<SubjectBlock*>boards[3] = new SUbjectBlock;

	static_cast<SubjectBlock*>boards[4] = new SubjectBlock;
	//
	static_cast<SubjectBlock*>boards[6] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[7] = new SubjectBlock;

	boards[8] = new EventBlock;

	boards[9] = new CornerBlock;

	static_cast<SubjectBlock*>boards[10] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[11] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[12] = new SubjectBlock;

	boards[13] = new EventBlock;

	static_cast<SubjectBlock*>boards[14] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[15] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[16] = new SubjectBlock;

	//

	boards[18] = new CornerBlock;

	static_cast<SubjectBlock*>boards[19] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[20] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[21] = new SubjectBlock;

	boards[22] = new EventBlock;

	static_cast<SubjectBlock*>boards[23] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[24] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[25] = new SubjectBlock;

	//

	boards[27] = new CornerBlock;

	//

	static_cast<SubjectBlock*>boards[29] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[30] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[31] = new SubjectBlock;

	boards[32] = new EventBlock;

	static_cast<SubjectBlock*>boards[33] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[34] = new SubjectBlock;
	static_cast<SubjectBlock*>boards[35] = new SubjectBlock;

}

void Board::enter(Player* player)
{
	int position = player->getPosition();
    boards[position]->enter(player);
}
<commit_msg>Fix board<commit_after>#include "board.h"
#include "eventblock.h"
#include "subjectblock.h"
#include "cornerblock.h"

Board::Board()
{
    boards = new Block*[36];

	boards[0] = new CornerBlock;

	boards[1] = new SubjectBlock;
	boards[2] = new SUbjectBlock;
	boards[3] = new SUbjectBlock;

	boards[4] = new SubjectBlock;
	// 관광지
	boards[6] = new SubjectBlock;
	boards[7] = new SubjectBlock;

	boards[8] = new EventBlock;

	boards[9] = new CornerBlock;

	boards[10] = new SubjectBlock;
	boards[11] = new SubjectBlock;
	boards[12] = new SubjectBlock;

	boards[13] = new EventBlock;

	boards[14] = new SubjectBlock;
	boards[15] = new SubjectBlock;
	boards[16] = new SubjectBlock;

	// 관광지
	boards[18] = new CornerBlock;

	boards[19] = new SubjectBlock;
	boards[20] = new SubjectBlock;
	boards[21] = new SubjectBlock;

	boards[22] = new EventBlock;

	boards[23] = new SubjectBlock;
	boards[24] = new SubjectBlock;
	boards[25] = new SubjectBlock;

	// 관광지

	boards[27] = new CornerBlock;

	// 관광지

	boards[29] = new SubjectBlock;
	boards[30] = new SubjectBlock;
	boards[31] = new SubjectBlock;

	boards[32] = new EventBlock;

	boards[33] = new SubjectBlock;
	boards[34] = new SubjectBlock;
	boards[35] = new SubjectBlock;

}

void Board::enter(Player* player)
{
	int position = player->getPosition();
    boards[position]->enter(player);
}
<|endoftext|>


<commit_before>#include "Grid.hpp"

#include <cassert>
#include <stdexcept>
#include <algorithm>
#include <array>

#include "Util.hpp"
#include "TileLogic.hpp"
#include "Types.hpp"

using namespace jakway_antf;

namespace
{
#ifdef DEBUG
    void assertGridIsRectangular(std::deque<std::deque<bool>*>& tiles)
    {
        //sanity check
        assert(!tiles.empty());

        //check the grid is rectangular and not jagged
        //i.e. all sublists are the same size
        //note that the number of sublists does not have to be equal to the number of columns
        for(std::deque<bool>* thisSubList : tiles)
        {
            for(std::deque<bool>* otherSubList : tiles)
            {
                assert(!otherSubList->empty());
                assert(thisSubList->size() == otherSubList->size());
            }
        }
    }
#endif
}

POS_TYPE Grid::getWidth()
{
    return tiles.front()->size();
}

POS_TYPE Grid::getHeight()
{
    return tiles.size();
}

POS_TYPE Grid::getSize()
{
    return getWidth() * getHeight();
}

void Grid::expandGrid()
{
    //check the grid is the right shape before and after we modify it
#ifdef DEBUG
    assertGridIsRectangular(tiles);
#endif
    const POS_TYPE newWidth = getWidth() + 2;

    //add 1 tile to the beginning of each sublist (prepending a column)
    //add 1 tile to the end of each sublist (appending a column)
    for(std::deque<bool>* thisSubList : tiles)
    {
        thisSubList->push_front(TILE_DEAD);
        thisSubList->push_back(TILE_DEAD);
    }

    //add 1 row to the beginning of the tiles list (prepending a row)
    //add 1 row to the end of the tiles list (appending a column)
    std::deque<bool> *firstList = new std::deque<bool>(newWidth, TILE_DEAD),
        *lastList = new std::deque<bool>(newWidth, TILE_DEAD);
    tiles.push_front(firstList);
    tiles.push_back(lastList);

#ifdef DEBUG
    //check the size is correct
    assertGridIsRectangular(tiles);
#endif
}

/**
 * should this be renamed to liveEdges()?
 */
bool Grid::touchingEdges()
{
    //check top edge for live tiles
    std::deque<bool>* topSubList = tiles.front();
    for(bool thisBool : *topSubList)
    {
        if(thisBool == TILE_ALIVE)
            return true;
    }

    //check bottom edge for live tiles
    std::deque<bool>* bottomSubList = tiles.back();
    for(bool thisBool : *bottomSubList)
    {
        if(thisBool == TILE_ALIVE)
            return true;
    }

    //check the left and right edges
    for(std::deque<bool>* thisSubList : tiles)
    {
        if(thisSubList->front() == TILE_ALIVE || thisSubList->back() == TILE_ALIVE)
            return true;
    }

    //if we haven't found any live tiles yet, there arent any in the edges
    return false;
}

Grid::Grid(const Grid& other)
{
    //TODO: IMPLEMENT
}

Grid::Grid(const POS_TYPE width, const POS_TYPE height)
{
    //making i the same type is easier
    for(POS_TYPE i = 0; i < height; i++)
    {
        //don't have to loop to add items to the list
        //this list CTOR will insert <width> number of bools all at once
        std::deque<bool>* subList = new std::deque<bool>(width, TILE_DEAD);
        //insert the sublist
        tiles.push_back(subList);
    }
}

Grid::~Grid()
{
    for(std::deque<bool>* thisSubList : tiles)
    {
        delete thisSubList;
    }
}

void Grid::runGeneration()
{
    if(touchingEdges())
        expandGrid();

    assert(!touchingEdges());

    //XXX -- TODO: implement runGeneration
    //XXX -- TODO: instead of making changes in-place, change the method signature to return a unique_ptr<Grid> -- a new pointer to a grid
    //make all changes to the new grid so that the generation only calculates which tiles live based on ALREADY ALIVE tiles, otherwise you're modifying a tiles' neighbor right before you check if it will live.  THIS IS A BUG!
    assert(false); //XXX
    for(auto gridIt = begin(); gridIt != end(); gridIt++)
    {
        const bool isAlive = *gridIt;
        unsigned int numLiveNeighbors = gridIt.getNumLiveNeighbors();

        //change the tile based on if it will live
        *gridIt = TileLogic::WillBeAlive(isAlive, numLiveNeighbors);

    }
}

/**
 * return the selected row (corresponding to x) that contains the passed y value
 * will throw if out of bounds
 */
std::deque<bool>* Grid::getRow(POS_TYPE x, POS_TYPE y)
{
    //subtract 1 because y is zero-indexed
    if(tiles.size()-1 < y)
    {
       throw std::out_of_range("y is greater than the number of rows!");
    }

    std::deque<bool>* selectedRow = tiles.at(y);
    //subtract 1 because x is zero-indexed
    if(selectedRow->size()-1 < x)
    {
       throw std::out_of_range("x is greater than the number of columns!");
    }
    return selectedRow;
}

void Grid::setTile(POS_TYPE x, POS_TYPE y, bool alive)
{
    std::deque<bool>* selectedRow = getRow(x, y);

    //we've found the tile, modify it
    (*selectedRow)[x] = alive;
}

bool Grid::getTile(POS_TYPE x, POS_TYPE y)
{
    std::deque<bool>* selectedRow = getRow(x, y);
    return (*selectedRow)[x];
}

/**
 * returns true if the tile is alive
 * returns false if the tile is dead or if the tile is outside the grid
 */
bool Grid::getTileIfValid(const POS_TYPE x, const POS_TYPE y)
{
    //POS_TYPE is unsigned, can never be less than 0
    if(x >= getWidth())
        return TILE_DEAD;
    if(y >= getHeight())
        return TILE_DEAD;

    try
    {
        return getTile(x, y);
    }
    //don't catch other exceptions--might be completely unrelated and make debugging very painful
    catch(std::out_of_range& e)
    {
        return false;
    }
}

/**
 * set every tile in the grid to TILE_DEAD
 */
void Grid::clearGrid()
{
    /**
     * could make this easier by writing a custom iterator for Grid
     */
    for(POS_TYPE x = 0; x < getWidth(); x++)
    {
        for(POS_TYPE y = 0; y < getHeight(); y++)
        {
            setTile(x, y, TILE_DEAD);
        }
    }

    assert(!touchingEdges());
}

//********************************
//GRID ITERATOR
//********************************

/**
 * this does the heavy lifting of the iterator
 * get the bool at GridIterator::pos or throw std::out_of_range if pos is invalid
 */
bool* Grid::GridIterator::getTile()
{
    if(xpos > grid->getWidth())
    {
        throw std::out_of_range("Exception in GridIterator: x out of range in getTile()!");
    }
    if(ypos > grid->getHeight())
    {
        throw std::out_of_range("Exception in GridIterator: y out of range in getTile()!");
    }

    //use grid->getRow instead of getRow because we need a pointer to the actual bool in the grid so we can modify it if necessary
    //grid->getTile returns the bool value, which can't be modified
    std::deque<bool>* row = grid->getRow(xpos, ypos);
    return &row->at(xpos);
}

/**
 * prefix increment operator
 */
Grid::GridIterator& Grid::GridIterator::operator++()
{
    //increment x then check if it went off the edge
    //if so, move it back to the leftmost side of the grid and shift to the next row
    xpos++;
    if(xpos >= grid->getWidth())
    {
        xpos = 0;
        ypos++;
    }

    return *this;
}

/**
 * postfix increment operator
 */
Grid::GridIterator Grid::GridIterator::operator++(int)
{
    GridIterator tmp(*this);
    operator++();
    return tmp;
}

/**
 * only true if both iterators point to the same Grid and are at the same position
 * this intentionally is NOT a deep equality test because we want to make sure that if 2 iterators are equal they can modify the same grid
 */
bool Grid::GridIterator::operator==(const GridIterator& other)
{
    return other.grid == grid && other.xpos == xpos && other.ypos == ypos;
}

bool Grid::GridIterator::operator!=(const GridIterator& other)
{
    //implement in terms of ==
    return !(*this == other);
}

bool& Grid::GridIterator::operator*()
{
    return *getTile();
}

unsigned int Grid::GridIterator::getNumLiveNeighbors()
{
    //every tile has 8 neighbors
    std::array<bool, NUM_NEIGHBORS> neighbors;
    neighbors.fill(false);

    //get a list of this tile's neighbors
    auto neighborPosArray = TileLogic::GetNeighbors(getX(), getY());
    assert(neighbors.size() == neighborPosArray.size());

    //check which neighbors are alive
    auto aliveIt = neighbors.begin();
    std::for_each(neighborPosArray.begin(), neighborPosArray.end(), [&aliveIt, this](std::array<POS_TYPE, 2> pos)
        {
            *aliveIt = this->grid->getTileIfValid(pos.front(), pos.back());
        });

    //count them
    unsigned int numLiveNeighbors = 0;
    std::for_each(neighbors.begin(), neighbors.end(), [&numLiveNeighbors](bool alive)
        {
            if(alive)
            {
                numLiveNeighbors++;
            }
        });

    return numLiveNeighbors;
}

POS_TYPE Grid::GridIterator::getX()
{
    return xpos;
}

POS_TYPE Grid::GridIterator::getY()
{
    return ypos;
}

Grid::iterator Grid::begin()
{
    return Grid::GridIterator(this, 0, 0);
}

/**
 * returns an iterator pointing to the off-the-end element (i.e. returns the iterator that would follow the last valid iterator)
 * should NOT be dereferenced
 */
Grid::iterator Grid::end()
{
    //return xpos == 0, ypos == height because incrementing the last valid iterator will set xpos = 0 and increment ypos
    //because xpos and ypos are 0-indexed, the ypos just after the last valid iterator is getHeight()
    return Grid::GridIterator(this, 0, getHeight());
}
<commit_msg>wrote an anonymous Tile class<commit_after>#include "Grid.hpp"

#include <cassert>
#include <stdexcept>
#include <algorithm>
#include <array>

#include "Util.hpp"
#include "TileLogic.hpp"
#include "Types.hpp"

using namespace jakway_antf;

namespace
{
#ifdef DEBUG
    void assertGridIsRectangular(std::deque<std::deque<bool>*>& tiles)
    {
        //sanity check
        assert(!tiles.empty());

        //check the grid is rectangular and not jagged
        //i.e. all sublists are the same size
        //note that the number of sublists does not have to be equal to the number of columns
        for(std::deque<bool>* thisSubList : tiles)
        {
            for(std::deque<bool>* otherSubList : tiles)
            {
                assert(!otherSubList->empty());
                assert(thisSubList->size() == otherSubList->size());
            }
        }
    }
#endif
}

POS_TYPE Grid::getWidth()
{
    return tiles.front()->size();
}

POS_TYPE Grid::getHeight()
{
    return tiles.size();
}

POS_TYPE Grid::getSize()
{
    return getWidth() * getHeight();
}

void Grid::expandGrid()
{
    //check the grid is the right shape before and after we modify it
#ifdef DEBUG
    assertGridIsRectangular(tiles);
#endif
    const POS_TYPE newWidth = getWidth() + 2;

    //add 1 tile to the beginning of each sublist (prepending a column)
    //add 1 tile to the end of each sublist (appending a column)
    for(std::deque<bool>* thisSubList : tiles)
    {
        thisSubList->push_front(TILE_DEAD);
        thisSubList->push_back(TILE_DEAD);
    }

    //add 1 row to the beginning of the tiles list (prepending a row)
    //add 1 row to the end of the tiles list (appending a column)
    std::deque<bool> *firstList = new std::deque<bool>(newWidth, TILE_DEAD),
        *lastList = new std::deque<bool>(newWidth, TILE_DEAD);
    tiles.push_front(firstList);
    tiles.push_back(lastList);

#ifdef DEBUG
    //check the size is correct
    assertGridIsRectangular(tiles);
#endif
}

/**
 * should this be renamed to liveEdges()?
 */
bool Grid::touchingEdges()
{
    //check top edge for live tiles
    std::deque<bool>* topSubList = tiles.front();
    for(bool thisBool : *topSubList)
    {
        if(thisBool == TILE_ALIVE)
            return true;
    }

    //check bottom edge for live tiles
    std::deque<bool>* bottomSubList = tiles.back();
    for(bool thisBool : *bottomSubList)
    {
        if(thisBool == TILE_ALIVE)
            return true;
    }

    //check the left and right edges
    for(std::deque<bool>* thisSubList : tiles)
    {
        if(thisSubList->front() == TILE_ALIVE || thisSubList->back() == TILE_ALIVE)
            return true;
    }

    //if we haven't found any live tiles yet, there arent any in the edges
    return false;
}

Grid::Grid(const Grid& other)
{
    //TODO: IMPLEMENT
}

Grid::Grid(const POS_TYPE width, const POS_TYPE height)
{
    //making i the same type is easier
    for(POS_TYPE i = 0; i < height; i++)
    {
        //don't have to loop to add items to the list
        //this list CTOR will insert <width> number of bools all at once
        std::deque<bool>* subList = new std::deque<bool>(width, TILE_DEAD);
        //insert the sublist
        tiles.push_back(subList);
    }
}

Grid::~Grid()
{
    for(std::deque<bool>* thisSubList : tiles)
    {
        delete thisSubList;
    }
}

namespace
{
    /**
     * a barebones immutable Tile class
     */
    class Tile
    {
    private:
        const POS_TYPE x, y;
        const bool alive;
    public:
        Tile(const POS_TYPE pX, const POS_TYPE pY, const bool pAlive)
            : x(pX), y(pY), alive(pAlive) {}

        POS_TYPE getX()
        { return x; }
        POS_TYPE getY()
        { return y; }
        bool isAlive()
        { return alive; }
    };
}

void Grid::runGeneration()
{
    if(touchingEdges())
        expandGrid();

    assert(!touchingEdges());

    //XXX -- TODO: implement runGeneration
    //XXX -- TODO: instead of making changes in-place, change the method signature to return a unique_ptr<Grid> -- a new pointer to a grid
    //make all changes to the new grid so that the generation only calculates which tiles live based on ALREADY ALIVE tiles, otherwise you're modifying a tiles' neighbor right before you check if it will live.  THIS IS A BUG!
    assert(false); //XXX
    for(auto gridIt = begin(); gridIt != end(); gridIt++)
    {
        const bool isAlive = *gridIt;
        unsigned int numLiveNeighbors = gridIt.getNumLiveNeighbors();

        //change the tile based on if it will live
        *gridIt = TileLogic::WillBeAlive(isAlive, numLiveNeighbors);

    }
}

/**
 * return the selected row (corresponding to x) that contains the passed y value
 * will throw if out of bounds
 */
std::deque<bool>* Grid::getRow(POS_TYPE x, POS_TYPE y)
{
    //subtract 1 because y is zero-indexed
    if(tiles.size()-1 < y)
    {
       throw std::out_of_range("y is greater than the number of rows!");
    }

    std::deque<bool>* selectedRow = tiles.at(y);
    //subtract 1 because x is zero-indexed
    if(selectedRow->size()-1 < x)
    {
       throw std::out_of_range("x is greater than the number of columns!");
    }
    return selectedRow;
}

void Grid::setTile(POS_TYPE x, POS_TYPE y, bool alive)
{
    std::deque<bool>* selectedRow = getRow(x, y);

    //we've found the tile, modify it
    (*selectedRow)[x] = alive;
}

bool Grid::getTile(POS_TYPE x, POS_TYPE y)
{
    std::deque<bool>* selectedRow = getRow(x, y);
    return (*selectedRow)[x];
}

/**
 * returns true if the tile is alive
 * returns false if the tile is dead or if the tile is outside the grid
 */
bool Grid::getTileIfValid(const POS_TYPE x, const POS_TYPE y)
{
    //POS_TYPE is unsigned, can never be less than 0
    if(x >= getWidth())
        return TILE_DEAD;
    if(y >= getHeight())
        return TILE_DEAD;

    try
    {
        return getTile(x, y);
    }
    //don't catch other exceptions--might be completely unrelated and make debugging very painful
    catch(std::out_of_range& e)
    {
        return false;
    }
}

/**
 * set every tile in the grid to TILE_DEAD
 */
void Grid::clearGrid()
{
    /**
     * could make this easier by writing a custom iterator for Grid
     */
    for(POS_TYPE x = 0; x < getWidth(); x++)
    {
        for(POS_TYPE y = 0; y < getHeight(); y++)
        {
            setTile(x, y, TILE_DEAD);
        }
    }

    assert(!touchingEdges());
}

//********************************
//GRID ITERATOR
//********************************

/**
 * this does the heavy lifting of the iterator
 * get the bool at GridIterator::pos or throw std::out_of_range if pos is invalid
 */
bool* Grid::GridIterator::getTile()
{
    if(xpos > grid->getWidth())
    {
        throw std::out_of_range("Exception in GridIterator: x out of range in getTile()!");
    }
    if(ypos > grid->getHeight())
    {
        throw std::out_of_range("Exception in GridIterator: y out of range in getTile()!");
    }

    //use grid->getRow instead of getRow because we need a pointer to the actual bool in the grid so we can modify it if necessary
    //grid->getTile returns the bool value, which can't be modified
    std::deque<bool>* row = grid->getRow(xpos, ypos);
    return &row->at(xpos);
}

/**
 * prefix increment operator
 */
Grid::GridIterator& Grid::GridIterator::operator++()
{
    //increment x then check if it went off the edge
    //if so, move it back to the leftmost side of the grid and shift to the next row
    xpos++;
    if(xpos >= grid->getWidth())
    {
        xpos = 0;
        ypos++;
    }

    return *this;
}

/**
 * postfix increment operator
 */
Grid::GridIterator Grid::GridIterator::operator++(int)
{
    GridIterator tmp(*this);
    operator++();
    return tmp;
}

/**
 * only true if both iterators point to the same Grid and are at the same position
 * this intentionally is NOT a deep equality test because we want to make sure that if 2 iterators are equal they can modify the same grid
 */
bool Grid::GridIterator::operator==(const GridIterator& other)
{
    return other.grid == grid && other.xpos == xpos && other.ypos == ypos;
}

bool Grid::GridIterator::operator!=(const GridIterator& other)
{
    //implement in terms of ==
    return !(*this == other);
}

bool& Grid::GridIterator::operator*()
{
    return *getTile();
}

unsigned int Grid::GridIterator::getNumLiveNeighbors()
{
    //every tile has 8 neighbors
    std::array<bool, NUM_NEIGHBORS> neighbors;
    neighbors.fill(false);

    //get a list of this tile's neighbors
    auto neighborPosArray = TileLogic::GetNeighbors(getX(), getY());
    assert(neighbors.size() == neighborPosArray.size());

    //check which neighbors are alive
    auto aliveIt = neighbors.begin();
    std::for_each(neighborPosArray.begin(), neighborPosArray.end(), [&aliveIt, this](std::array<POS_TYPE, 2> pos)
        {
            *aliveIt = this->grid->getTileIfValid(pos.front(), pos.back());
        });

    //count them
    unsigned int numLiveNeighbors = 0;
    std::for_each(neighbors.begin(), neighbors.end(), [&numLiveNeighbors](bool alive)
        {
            if(alive)
            {
                numLiveNeighbors++;
            }
        });

    return numLiveNeighbors;
}

POS_TYPE Grid::GridIterator::getX()
{
    return xpos;
}

POS_TYPE Grid::GridIterator::getY()
{
    return ypos;
}

Grid::iterator Grid::begin()
{
    return Grid::GridIterator(this, 0, 0);
}

/**
 * returns an iterator pointing to the off-the-end element (i.e. returns the iterator that would follow the last valid iterator)
 * should NOT be dereferenced
 */
Grid::iterator Grid::end()
{
    //return xpos == 0, ypos == height because incrementing the last valid iterator will set xpos = 0 and increment ypos
    //because xpos and ypos are 0-indexed, the ypos just after the last valid iterator is getHeight()
    return Grid::GridIterator(this, 0, getHeight());
}
<|endoftext|>