<commit_before>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"

//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif

using namespace MathLib;

class CSysControlLocal : public CSysControl
{
public:
	CSysControlLocal();
	virtual ~CSysControlLocal();

	virtual void Init();	//角色要初始化，着色器要初始化，
	virtual void Update(float ifps);
	virtual void Shutdown();

	virtual int GetState(int state);		//鼠标状态，键盘状态，人物状态，子弹状态等等。
	virtual int ClearState(int state);

	virtual float GetMouseDX();
	virtual float GetMouseDY();

	virtual void SetMouseGrab(int g);		//设置是否显示鼠标
	virtual int GetMouseGrab();			//获取鼠标状态，是显示呢还是不显示的状态。

	virtual void SetControlMode(ControlMode mode);			//控制模式
	virtual ControlMode GetControlMode() const;				//获取控制模式

private:
	void Update_Mouse(float ifps);
	void Update_Keyboard(float ifps);
	void Update_XPad360(float ifps);

	CControlsApp        *m_pControlsApp;		//控制游戏中移动
	CControlsXPad360    *m_pControlsXPad360;
	ControlMode         m_nControlMode;			//控制模式

	int                 m_nOldMouseX;			//上一个鼠标坐标X
	int                 m_nOldMouseY;			//上一个鼠标坐标Y

	CObjectGui          *m_pTest3DUI;
	CWidgetLabel        *m_pTestMessageLabel;

};

CSysControlLocal::CSysControlLocal()
{

}
CSysControlLocal::~CSysControlLocal()
{

}

void CSysControlLocal::Init()
{
	m_pControlsApp = new CControlsApp;
	m_pControlsXPad360 = new CControlsXPad360(0);

	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);

	SetControlMode(CONTROL_KEYBORAD_MOUSE);

	m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
	m_pTest3DUI->SetMouseShow(0);
	m_pTest3DUI->SetBackground(1);
	m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));

	m_pTest3DUI->SetScreenSize(800, 400);
	m_pTest3DUI->SetControlDistance(1000.0f);
	m_pTest3DUI->CreateMaterial("gui_base");	 //show in game

	m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel->SetFontSize(80);		//设置字体大小
	m_pTestMessageLabel->SetFontOutline(1);		//设置字体轮廓
	m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");

	void CSysControlLocal::Update(float ifps)
	{
		Update_Mouse(ifps);
		Update_Keyboard(ifps);
		Update_XPad360(ifps);
	}

	m_nOldMouseX = 0;
	m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);
	delete m_pControlsApp;
	m_pControlsApp = NULL;
	delete m_pControlsXPad360;
	m_pControlsXPad360 = NULL;
	delete m_pTestMessageLabel;
	m_pTestMessageLabel = NULL;
	delete m_pTest3DUI;
	m_pTest3DUI = NULL;

}

int CSysControlLocal::GetState(int state)
{

	return m_pControlsApp->GetState(state);
}

int CSysControlLocal::ClearState(int state)
{
	return m_pControlsApp->ClearState(state);
}

float CSysControlLocal::GetMouseDX()
{
	return m_pControlsApp->GetMouseDX();
}

float CSysControlLocal::GetMouseDY()
{
	return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
	g_Engine.pApp->SetMouseGrab(g);
	g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
	return g_Engine.pApp->GetMouseGrab();
}

void CSysControlLocal::SetControlMode(ControlMode mode)
{
	m_nControlMode = mode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
	float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大，鼠标移动越快
	float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小，鼠标移动越慢

	m_pControlsApp->SetMouseDX(dx);
	m_pControlsApp->SetMouseDY(dy);

	if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
	{
		g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
	}

	m_nOldMouseX = g_Engine.pApp->GetMouseX();
	m_nOldMouseY = g_Engine.pApp->GetMouseY();
}

void CSysControlLocal::Update_Keyboard(float ifps)		//键盘按键响应wsad
{

	if (g_Engine.pInput->IsKeyDown('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	if (g_Engine.pInput->IsKeyDown('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	if (g_Engine.pInput->IsKeyDown('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	if (g_Engine.pInput->IsKeyDown('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);

	if (g_Engine.pInput->IsKeyUp('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
	else if (g_Engine.pInput->IsKeyUp('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);

	if (g_Engine.pInput->IsKeyUp('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
	else if (g_Engine.pInput->IsKeyUp('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	if (g_Engine.pInput->IsKeyDown(' '))		//空格跳跃
		m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
	else
		m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
	m_pControlsXPad360->UpdateEvents();
	CUtilStr strMessage;
	strMessage = CUtilStr("测试3D UI\n"),
	strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";

	strMessage += CUtilStr::Format("\n手柄测试\n");
	strMessage += CUtilStr::Format("LeftX:  %5.2f\n", m_pControlsXPad360->GetLeftX());
	strMessage += CUtilStr::Format("LeftY:  %5.2f\n", m_pControlsXPad360->GetLeftY());
	strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
	strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
	strMessage += "\nTriggers:\n";
	strMessage += CUtilStr::Format("Left:   %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
	strMessage += CUtilStr::Format("Right:  %5.2f\n", m_pControlsXPad360->GetRightTrigger());

	strMessage += CUtilStr::Format("\nButtons:\n");
	for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)
	{
		strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i));
	}
	m_pTestMessageLabel->SetText(strMessage.Get());

	const float fPadThreshold = 0.5f;
	if (m_pControlsXPad360->GetLeftX() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
	else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	}
	if (m_pControlsXPad360->GetLeftY() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	else if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
	}
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"

//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif

using namespace MathLib;

class CSysControlLocal : public CSysControl
{
public:
	CSysControlLocal();
	virtual ~CSysControlLocal();

	virtual void Init();	//角色要初始化，着色器要初始化，
	virtual void Update(float ifps);
	virtual void Shutdown();

	virtual int GetState(int state);		//鼠标状态，键盘状态，人物状态，子弹状态等等。
	virtual int ClearState(int state);

	virtual float GetMouseDX();
	virtual float GetMouseDY();

	virtual void SetMouseGrab(int g);		//设置是否显示鼠标
	virtual int GetMouseGrab();			//获取鼠标状态，是显示呢还是不显示的状态。

	virtual void SetControlMode(ControlMode mode);			//控制模式
	virtual ControlMode GetControlMode() const;				//获取控制模式

private:
	void Update_Mouse(float ifps);
	void Update_Keyboard(float ifps);
	void Update_XPad360(float ifps);

	CControlsApp        *m_pControlsApp;		//控制游戏中移动
	CControlsXPad360    *m_pControlsXPad360;
	ControlMode         m_nControlMode;			//控制模式

	int                 m_nOldMouseX;			//上一个鼠标坐标X
	int                 m_nOldMouseY;			//上一个鼠标坐标Y

	CObjectGui          *m_pTest3DUI;
	CWidgetLabel        *m_pTestMessageLabel;

};

CSysControlLocal::CSysControlLocal()
{

}
CSysControlLocal::~CSysControlLocal()
{

}

void CSysControlLocal::Init()
{
	m_pControlsApp = new CControlsApp;
	m_pControlsXPad360 = new CControlsXPad360(0);

	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);

	SetControlMode(CONTROL_KEYBORAD_MOUSE);

	m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
	m_pTest3DUI->SetMouseShow(0);
	m_pTest3DUI->SetBackground(1);
	m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));

	m_pTest3DUI->SetScreenSize(800, 400);
	m_pTest3DUI->SetControlDistance(1000.0f);
	m_pTest3DUI->CreateMaterial("gui_base");	 //show in game

	m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel->SetFontSize(80);		//设置字体大小
	m_pTestMessageLabel->SetFontOutline(1);		//设置字体轮廓
	m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");

	void CSysControlLocal::Update(float ifps)
	{
		Update_Mouse(ifps);
		Update_Keyboard(ifps);
		Update_XPad360(ifps);
	}

	m_nOldMouseX = 0;
	m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);
	delete m_pControlsApp;
	m_pControlsApp = NULL;
	delete m_pControlsXPad360;
	m_pControlsXPad360 = NULL;
	delete m_pTestMessageLabel;
	m_pTestMessageLabel = NULL;
	delete m_pTest3DUI;
	m_pTest3DUI = NULL;

}

int CSysControlLocal::GetState(int state)
{

	return m_pControlsApp->GetState(state);
}

int CSysControlLocal::ClearState(int state)
{
	return m_pControlsApp->ClearState(state);
}

float CSysControlLocal::GetMouseDX()
{
	return m_pControlsApp->GetMouseDX();
}

float CSysControlLocal::GetMouseDY()
{
	return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
	g_Engine.pApp->SetMouseGrab(g);
	g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
	return g_Engine.pApp->GetMouseGrab();
}

void CSysControlLocal::SetControlMode(ControlMode mode)
{
	m_nControlMode = mode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
	float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大，鼠标移动越快
	float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小，鼠标移动越慢

	m_pControlsApp->SetMouseDX(dx);
	m_pControlsApp->SetMouseDY(dy);

	if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
	{
		g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
	}

	m_nOldMouseX = g_Engine.pApp->GetMouseX();
	m_nOldMouseY = g_Engine.pApp->GetMouseY();
}

void CSysControlLocal::Update_Keyboard(float ifps)		//键盘按键响应wsad
{

	if (g_Engine.pInput->IsKeyDown('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	if (g_Engine.pInput->IsKeyDown('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	if (g_Engine.pInput->IsKeyDown('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	if (g_Engine.pInput->IsKeyDown('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);

	if (g_Engine.pInput->IsKeyUp('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
	else if (g_Engine.pInput->IsKeyUp('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);

	if (g_Engine.pInput->IsKeyUp('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
	else if (g_Engine.pInput->IsKeyUp('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	if (g_Engine.pInput->IsKeyDown(' '))		//空格跳跃
		m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
	else
		m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
	m_pControlsXPad360->UpdateEvents();
	CUtilStr strMessage;
	strMessage = CUtilStr("测试3D UI\n"),
	strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";

	strMessage += CUtilStr::Format("\n手柄测试\n");
	strMessage += CUtilStr::Format("LeftX:  %5.2f\n", m_pControlsXPad360->GetLeftX());
	strMessage += CUtilStr::Format("LeftY:  %5.2f\n", m_pControlsXPad360->GetLeftY());
	strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
	strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
	strMessage += "\nTriggers:\n";
	strMessage += CUtilStr::Format("Left:   %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
	strMessage += CUtilStr::Format("Right:  %5.2f\n", m_pControlsXPad360->GetRightTrigger());

	strMessage += CUtilStr::Format("\nButtons:\n");
	for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)
	{
		strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i));
	}
	m_pTestMessageLabel->SetText(strMessage.Get());

	const float fPadThreshold = 0.5f;
	if (m_pControlsXPad360->GetLeftX() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
	else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	}
	if (m_pControlsXPad360->GetLeftY() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	else if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
	}
	if (m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_LEFT) || m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_RIGHT))
		m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
	else
		m_pControlsApp->SetState(CControls::STATE_JUMP, 0);

}<|endoftext|>


<commit_before><commit_msg>Switched httpserver.cpp to use RAII wrapped libevents.<commit_after><|endoftext|>


<commit_before>#include "parse_json.hh"
#include "lightweight_nn_streamers.hh"

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <cassert>
#include <string>

#include <iostream>

namespace {
  using namespace boost::property_tree;
  using namespace lwt;
  lwt::Activation get_activation(const std::string&);
  lwt::Architecture get_architecture(const std::string&);
  void add_dense_info(LayerConfig& lc, const ptree& pt);
}

namespace lwt {

  JSONConfig parse_json(std::istream& json)
  {
    boost::property_tree::ptree pt;
    boost::property_tree::read_json(json, pt);

    JSONConfig cfg;
    for (const auto& v: pt.get_child("inputs")) {
      std::string name = v.second.get<std::string>("name");
      auto offset = v.second.get<double>("offset");
      auto scale = v.second.get<double>("scale");
      Input input{name, offset, scale};
      cfg.inputs.push_back(input);
    }
    for (const auto& v: pt.get_child("layers")) {
      LayerConfig layer;
      layer.activation = get_activation(
        v.second.get<std::string>("activation"));
      layer.architecture = get_architecture(
        v.second.get<std::string>("architecture"));
      // todo: make this weights stuff happen in another function
      for (const auto& wt: v.second.get_child("weights")) {
        layer.weights.push_back(wt.second.get_value<double>());
      }
      for (const auto& bs: v.second.get_child("bias")) {
        layer.bias.push_back(bs.second.get_value<double>());
      }
      // todo: add maxout_tensor filler
      cfg.layers.push_back(layer);
    }
    for (const auto& v: pt.get_child("outputs"))
    {
      assert(v.first.empty()); // array elements have no names
      cfg.outputs.push_back(v.second.data());
    }
    const std::string dname = "defaults";
    if (pt.count(dname)) {
      for (const auto& def: pt.get_child(dname)) {
        cfg.defaults.emplace(def.first, def.second.get_value<double>());
      }
    }
    return cfg;
  }

}

namespace {
  lwt::Activation get_activation(const std::string& str) {
    using namespace lwt;
    if (str == "linear") return Activation::LINEAR;
    if (str == "sigmoid") return Activation::SIGMOID;
    if (str == "rectified") return Activation::RECTIFIED;
    if (str == "softmax") return Activation::SOFTMAX;
    throw std::logic_error("activation function " + str + " not recognized");
  }
  lwt::Architecture get_architecture(const std::string& str) {
    using namespace lwt;
    if (str == "dense") return Architecture::DENSE;
    if (str == "maxout") return Architecture::MAXOUT;
    throw std::logic_error("architecture " + str + " not recognized");
  }
  void add_dense_info(LayerConfig& lc, const ptree& pt) {

  }
}
<commit_msg>Maxout seems to be working<commit_after>#include "parse_json.hh"
#include "lightweight_nn_streamers.hh"

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <cassert>
#include <string>

#include <iostream>

namespace {
  using namespace boost::property_tree;
  using namespace lwt;
  lwt::Activation get_activation(const std::string&);
  lwt::Architecture get_architecture(const std::string&);
  void add_dense_info(LayerConfig& lc, const ptree::value_type& pt);
  void add_maxout_info(LayerConfig& lc, const ptree::value_type& pt);
}

namespace lwt {

  JSONConfig parse_json(std::istream& json)
  {
    boost::property_tree::ptree pt;
    boost::property_tree::read_json(json, pt);

    JSONConfig cfg;
    for (const auto& v: pt.get_child("inputs")) {
      std::string name = v.second.get<std::string>("name");
      auto offset = v.second.get<double>("offset");
      auto scale = v.second.get<double>("scale");
      Input input{name, offset, scale};
      cfg.inputs.push_back(input);
    }
    for (const auto& v: pt.get_child("layers")) {
      LayerConfig layer;
      layer.activation = get_activation(
        v.second.get<std::string>("activation"));
      layer.architecture = get_architecture(
        v.second.get<std::string>("architecture"));

      if (layer.architecture == Architecture::DENSE) {
        add_dense_info(layer, v);
      } else if (layer.architecture == Architecture::MAXOUT) {
        add_maxout_info(layer, v);
      }
      cfg.layers.push_back(layer);
    }
    for (const auto& v: pt.get_child("outputs"))
    {
      assert(v.first.empty()); // array elements have no names
      cfg.outputs.push_back(v.second.data());
    }
    const std::string dname = "defaults";
    if (pt.count(dname)) {
      for (const auto& def: pt.get_child(dname)) {
        cfg.defaults.emplace(def.first, def.second.get_value<double>());
      }
    }
    return cfg;
  }

}

namespace {
  lwt::Activation get_activation(const std::string& str) {
    using namespace lwt;
    if (str == "linear") return Activation::LINEAR;
    if (str == "sigmoid") return Activation::SIGMOID;
    if (str == "rectified") return Activation::RECTIFIED;
    if (str == "softmax") return Activation::SOFTMAX;
    throw std::logic_error("activation function " + str + " not recognized");
  }

  lwt::Architecture get_architecture(const std::string& str) {
    using namespace lwt;
    if (str == "dense") return Architecture::DENSE;
    if (str == "maxout") return Architecture::MAXOUT;
    throw std::logic_error("architecture " + str + " not recognized");
  }

  void add_dense_info(LayerConfig& layer, const ptree::value_type& v) {
    for (const auto& wt: v.second.get_child("weights")) {
      layer.weights.push_back(wt.second.get_value<double>());
    }
    for (const auto& bs: v.second.get_child("bias")) {
      layer.bias.push_back(bs.second.get_value<double>());
    }
  }

  void add_maxout_info(LayerConfig& layer, const ptree::value_type& v) {
    for (const auto& mat: v.second.get_child("weights")) {
      layer.maxout_tensor.push_back(std::vector<double>());
      for (const auto& wt: mat.second) {
        layer.maxout_tensor.back().push_back(wt.second.get_value<double>());
      }
    }
  }

}
<|endoftext|>


<commit_before><commit_msg>Replace boost::ptr_vector with std::vector<std::unique_ptr><commit_after><|endoftext|>


<commit_before><commit_msg>taken care of the case where a root node is also a leaf<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include "version.h"
#include "parser.h"
using namespace lean;

int main() {
    std::cout << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ")\n";
    frontend f;
    return parse_commands(f, std::cin) ? 0 : 1;
}
<commit_msg>Add support for reading input files from the command line.<commit_after>#include <iostream>
#include <fstream>
#include "version.h"
#include "parser.h"
using namespace lean;

int main(int argc, char ** argv) {
    std::cout << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ")\n";
    frontend f;
    if (argc == 1) {
        return parse_commands(f, std::cin) ? 0 : 1;
    } else {
        bool ok = true;
        for (int i = 1; i < argc; i++) {
            std::ifstream in(argv[i]);
            if (!parse_commands(f, in))
                ok = false;
        }
        return ok ? 0 : 1;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: optload.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-20 12:39:39 $
 *
 *  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 _OPTLOAD_HXX
#define _OPTLOAD_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SVX_STRARRAY_HXX
#include <svx/strarray.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVX_CHECKLBX_HXX //autogen
#include <svx/checklbx.hxx>
#endif
#ifndef _SWLBOX_HXX
#include <swlbox.hxx>
#endif
#ifndef _CAPTION_HXX
#include <caption.hxx>
#endif

class SwFldMgr;
class SvLBoxEntry;
class SwWrtShell;

/*-----------------31.08.96 10.09-------------------

--------------------------------------------------*/

class SwLoadOptPage : public SfxTabPage
{
private:
    FixedLine   aUpdateFL;
    FixedText   aLinkFT;
    RadioButton aAlwaysRB;
    RadioButton aRequestRB;
    RadioButton aNeverRB;

    FixedText   aFieldFT;
    CheckBox    aAutoUpdateFields;
    CheckBox    aAutoUpdateCharts;

    FixedLine   aSettingsFL;
    FixedText   aMetricFT;
    ListBox     aMetricLB;
    FixedText   aTabFT;
    MetricField aTabMF;

    SwWrtShell* pWrtShell;
    sal_Bool    bHTMLMode;
    UINT16      nLastTab;
    sal_Int32   nOldLinkMode;

    DECL_LINK(CaptionHdl, PushButton*);
    DECL_LINK(MetricHdl, ListBox*);
    DECL_LINK(UpdateHdl, CheckBox* );

public:
    SwLoadOptPage( Window* pParent, const SfxItemSet& rSet );
    ~SwLoadOptPage();

    static SfxTabPage*  Create( Window* pParent,
                                const SfxItemSet& rAttrSet);

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
};

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/
class SwCaptionOptDlg : public SfxSingleTabDialog
{
public:
     SwCaptionOptDlg(Window* pParent, const SfxItemSet& rSet);
    ~SwCaptionOptDlg();
};
/* -----------------23.10.98 13:19-------------------
 *
 * --------------------------------------------------*/

class CaptionComboBox : public SwComboBox
{
protected:
    virtual void KeyInput( const KeyEvent& );

public:
    CaptionComboBox( Window* pParent, const ResId& rResId)
        : SwComboBox(pParent, rResId)
    {}
};

/*-----------------31.08.96 10.09-------------------

--------------------------------------------------*/

class SwCaptionPreview : public Window
{
private:
    String          maText;
    Point           maDrawPos;
public:
                    SwCaptionPreview( Window* pParent, const ResId& rResId );
    void            SetPreviewText( const String& rText );
    virtual void    Paint( const Rectangle& rRect );
};

class SwCaptionOptPage : public SfxTabPage
{
private:
    FixedText       aCheckFT;
    SvxCheckListBox aCheckLB;

    FixedLine       aSettingsGroupFL;
    FixedText       aCategoryText;
    CaptionComboBox aCategoryBox;
    FixedText       aFormatText;
    ListBox         aFormatBox;
    FixedText       aTextText;
    Edit            aTextEdit;
    FixedText       aPosText;
    ListBox         aPosBox;

    FixedLine       aNumCaptFL;
    FixedText       aFtLevel;
    ListBox         aLbLevel;
    FixedText       aFtDelim;
    Edit            aEdDelim;

    FixedLine       aCategoryFL;
    FixedText       aCharStyleFT;
    ListBox         aCharStyleLB;
    CheckBox        aApplyBorderCB;

    SwCaptionPreview    aPreview;

    String          sSWTable;
    String          sSWFrame;
    String          sSWGraphic;
    String          sOLE;

    String          sIllustration;
    String          sTable;
    String          sText;
    String          sDrawing;

    String          sBegin;
    String          sEnd;
    String          sAbove;
    String          sBelow;

    String          sNone;

    SwFldMgr        *pMgr;
    USHORT          eType;
    BOOL            bHTMLMode;

    DECL_LINK( SelectHdl, ListBox *pLB = 0 );
    DECL_LINK( ModifyHdl, Edit *pEdt = 0 );
    DECL_LINK( ShowEntryHdl, SvxCheckListBox *pLB = 0 );
    DECL_LINK( SaveEntryHdl, SvxCheckListBox *pLB = 0 );

    void                DelUserData();
    void                SetOptions( const USHORT nPos,
                                    const SwCapObjType eType,
                                    const SvGlobalName *pOleId = 0);
    void                SaveEntry( SvLBoxEntry* pEntry );
    void                DrawSample();

public:
                        SwCaptionOptPage( Window* pParent,
                                         const SfxItemSet& rSet );
                        ~SwCaptionOptPage();

    static SfxTabPage*  Create( Window* pParent,
                                const SfxItemSet& rAttrSet);

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.580); FILE MERGED 2005/09/05 13:45:30 rt 1.8.580.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optload.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:55:14 $
 *
 *  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 _OPTLOAD_HXX
#define _OPTLOAD_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SVX_STRARRAY_HXX
#include <svx/strarray.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVX_CHECKLBX_HXX //autogen
#include <svx/checklbx.hxx>
#endif
#ifndef _SWLBOX_HXX
#include <swlbox.hxx>
#endif
#ifndef _CAPTION_HXX
#include <caption.hxx>
#endif

class SwFldMgr;
class SvLBoxEntry;
class SwWrtShell;

/*-----------------31.08.96 10.09-------------------

--------------------------------------------------*/

class SwLoadOptPage : public SfxTabPage
{
private:
    FixedLine   aUpdateFL;
    FixedText   aLinkFT;
    RadioButton aAlwaysRB;
    RadioButton aRequestRB;
    RadioButton aNeverRB;

    FixedText   aFieldFT;
    CheckBox    aAutoUpdateFields;
    CheckBox    aAutoUpdateCharts;

    FixedLine   aSettingsFL;
    FixedText   aMetricFT;
    ListBox     aMetricLB;
    FixedText   aTabFT;
    MetricField aTabMF;

    SwWrtShell* pWrtShell;
    sal_Bool    bHTMLMode;
    UINT16      nLastTab;
    sal_Int32   nOldLinkMode;

    DECL_LINK(CaptionHdl, PushButton*);
    DECL_LINK(MetricHdl, ListBox*);
    DECL_LINK(UpdateHdl, CheckBox* );

public:
    SwLoadOptPage( Window* pParent, const SfxItemSet& rSet );
    ~SwLoadOptPage();

    static SfxTabPage*  Create( Window* pParent,
                                const SfxItemSet& rAttrSet);

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
};

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/
class SwCaptionOptDlg : public SfxSingleTabDialog
{
public:
     SwCaptionOptDlg(Window* pParent, const SfxItemSet& rSet);
    ~SwCaptionOptDlg();
};
/* -----------------23.10.98 13:19-------------------
 *
 * --------------------------------------------------*/

class CaptionComboBox : public SwComboBox
{
protected:
    virtual void KeyInput( const KeyEvent& );

public:
    CaptionComboBox( Window* pParent, const ResId& rResId)
        : SwComboBox(pParent, rResId)
    {}
};

/*-----------------31.08.96 10.09-------------------

--------------------------------------------------*/

class SwCaptionPreview : public Window
{
private:
    String          maText;
    Point           maDrawPos;
public:
                    SwCaptionPreview( Window* pParent, const ResId& rResId );
    void            SetPreviewText( const String& rText );
    virtual void    Paint( const Rectangle& rRect );
};

class SwCaptionOptPage : public SfxTabPage
{
private:
    FixedText       aCheckFT;
    SvxCheckListBox aCheckLB;

    FixedLine       aSettingsGroupFL;
    FixedText       aCategoryText;
    CaptionComboBox aCategoryBox;
    FixedText       aFormatText;
    ListBox         aFormatBox;
    FixedText       aTextText;
    Edit            aTextEdit;
    FixedText       aPosText;
    ListBox         aPosBox;

    FixedLine       aNumCaptFL;
    FixedText       aFtLevel;
    ListBox         aLbLevel;
    FixedText       aFtDelim;
    Edit            aEdDelim;

    FixedLine       aCategoryFL;
    FixedText       aCharStyleFT;
    ListBox         aCharStyleLB;
    CheckBox        aApplyBorderCB;

    SwCaptionPreview    aPreview;

    String          sSWTable;
    String          sSWFrame;
    String          sSWGraphic;
    String          sOLE;

    String          sIllustration;
    String          sTable;
    String          sText;
    String          sDrawing;

    String          sBegin;
    String          sEnd;
    String          sAbove;
    String          sBelow;

    String          sNone;

    SwFldMgr        *pMgr;
    USHORT          eType;
    BOOL            bHTMLMode;

    DECL_LINK( SelectHdl, ListBox *pLB = 0 );
    DECL_LINK( ModifyHdl, Edit *pEdt = 0 );
    DECL_LINK( ShowEntryHdl, SvxCheckListBox *pLB = 0 );
    DECL_LINK( SaveEntryHdl, SvxCheckListBox *pLB = 0 );

    void                DelUserData();
    void                SetOptions( const USHORT nPos,
                                    const SwCapObjType eType,
                                    const SvGlobalName *pOleId = 0);
    void                SaveEntry( SvLBoxEntry* pEntry );
    void                DrawSample();

public:
                        SwCaptionOptPage( Window* pParent,
                                         const SfxItemSet& rSet );
                        ~SwCaptionOptPage();

    static SfxTabPage*  Create( Window* pParent,
                                const SfxItemSet& rAttrSet);

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
};

#endif

<|endoftext|>


<commit_before>#include "yaml-cpp/yaml.h"  // IWYU pragma: keep

#include "gtest/gtest.h"

namespace YAML {
namespace {
TEST(LoadNodeTest, Reassign) {
  Node node = Load("foo");
  node = Node();
}

TEST(LoadNodeTest, FallbackValues) {
  Node node = Load("foo: bar\nx: 2");
  EXPECT_EQ("bar", node["foo"].as<std::string>());
  EXPECT_EQ("bar", node["foo"].as<std::string>("hello"));
  EXPECT_EQ("hello", node["baz"].as<std::string>("hello"));
  EXPECT_EQ(2, node["x"].as<int>());
  EXPECT_EQ(2, node["x"].as<int>(5));
  EXPECT_EQ(5, node["y"].as<int>(5));
}

TEST(LoadNodeTest, NumericConversion) {
  Node node = Load("[1.5, 1, .nan, .inf, -.inf, 0x15, 015]");
  EXPECT_EQ(1.5f, node[0].as<float>());
  EXPECT_EQ(1.5, node[0].as<double>());
  EXPECT_THROW(node[0].as<int>(), TypedBadConversion<int>);
  EXPECT_EQ(1, node[1].as<int>());
  EXPECT_EQ(1.0f, node[1].as<float>());
  EXPECT_NE(node[2].as<float>(), node[2].as<float>());
  EXPECT_EQ(std::numeric_limits<float>::infinity(), node[3].as<float>());
  EXPECT_EQ(-std::numeric_limits<float>::infinity(), node[4].as<float>());
  EXPECT_EQ(21, node[5].as<int>());
  EXPECT_EQ(13, node[6].as<int>());
}

TEST(LoadNodeTest, Binary) {
  Node node = Load(
      "[!!binary \"SGVsbG8sIFdvcmxkIQ==\", !!binary "
      "\"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS"
      "B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG"
      "x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi"
      "B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG"
      "dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS"
      "4K\"]");
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>("Hello, World!"), 13),
            node[0].as<Binary>());
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node[1].as<Binary>());
}

TEST(LoadNodeTest, BinaryWithWhitespaces) {
  Node node = Load(
      "binaryText: !binary |-\n"
      "  TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS\n"
      "  B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG\n"
      "  x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi\n"
      "  B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG\n"
      "  dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS\n"
      "  4K");
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node["binaryText"].as<Binary>());
}

TEST(LoadNodeTest, IterateSequence) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 4);
    int x = seq[i++];
    EXPECT_EQ(x, it->as<int>());
  }
  EXPECT_EQ(4, i);
}

TEST(LoadNodeTest, IterateMap) {
  Node node = Load("{a: A, b: B, c: C}");
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 3);
    i++;
    EXPECT_EQ(it->second.as<char>(), it->first.as<char>() + 'A' - 'a');
  }
  EXPECT_EQ(3, i);
}

#ifdef BOOST_FOREACH
TEST(LoadNodeTest, ForEach) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  BOOST_FOREACH (const Node& item, node) {
    int x = seq[i++];
    EXPECT_EQ(x, item.as<int>());
  }
}

TEST(LoadNodeTest, ForEachMap) {
  Node node = Load("{a: A, b: B, c: C}");
  BOOST_FOREACH (const const_iterator::value_type& p, node) {
    EXPECT_EQ(p.second.as<char>(), p.first.as<char>() + 'A' - 'a');
  }
}
#endif

TEST(LoadNodeTest, CloneScalar) {
  Node node = Load("!foo monkey");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(clone.as<std::string>(), node.as<std::string>());
  EXPECT_EQ(clone.Tag(), node.Tag());
}

TEST(LoadNodeTest, CloneSeq) {
  Node node = Load("[1, 3, 5, 7]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  for (std::size_t i = 0; i < node.size(); i++) {
    EXPECT_EQ(clone[i].as<int>(), node[i].as<int>());
  }
}

TEST(LoadNodeTest, CloneMap) {
  Node node = Load("{foo: bar}");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Map, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone["foo"].as<std::string>(), node["foo"].as<std::string>());
}

TEST(LoadNodeTest, CloneAlias) {
  Node node = Load("&foo [*foo]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone[0], clone);
}

TEST(LoadNodeTest, ForceInsertIntoMap) {
  Node node;
  node["a"] = "b";
  node.force_insert("x", "y");
  node.force_insert("a", 5);
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(NodeType::Map, node.Type());
  bool ab = false;
  bool a5 = false;
  bool xy = false;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    if (it->first.as<std::string>() == "a") {
      if (it->second.as<std::string>() == "b")
        ab = true;
      else if (it->second.as<std::string>() == "5")
        a5 = true;
    } else if (it->first.as<std::string>() == "x" &&
               it->second.as<std::string>() == "y")
      xy = true;
  }
  EXPECT_TRUE(ab);
  EXPECT_TRUE(a5);
  EXPECT_TRUE(xy);
}

TEST(LoadNodeTest, ResetNode) {
  Node node = Load("[1, 2, 3]");
  EXPECT_TRUE(!node.IsNull());
  Node other = node;
  node.reset();
  EXPECT_TRUE(node.IsNull());
  EXPECT_TRUE(!other.IsNull());
  node.reset(other);
  EXPECT_TRUE(!node.IsNull());
  EXPECT_EQ(node, other);
}

TEST(LoadNodeTest, EmptyString) {
  Node node = Load("\"\"");
  EXPECT_TRUE(!node.IsNull());
}

TEST(LoadNodeTest, DereferenceIteratorError) {
  Node node = Load("[{a: b}, 1, 2]");
  EXPECT_THROW(node.begin()->first.as<int>(), InvalidNode);
  EXPECT_EQ(true, (*node.begin()).IsMap());
  EXPECT_EQ(true, node.begin()->IsMap());
  EXPECT_THROW((*node.begin()->begin()).Type(), InvalidNode);
  EXPECT_THROW(node.begin()->begin()->Type(), InvalidNode);
}

TEST(NodeTest, EmitEmptyNode) {
  Node node;
  Emitter emitter;
  emitter << node;
  EXPECT_EQ("", std::string(emitter.c_str()));
}

TEST(NodeTest, ParseNodeStyle) {
  EXPECT_EQ(EmitterStyle::Flow, Load("[1, 2, 3]").Style());
  EXPECT_EQ(EmitterStyle::Flow, Load("{foo: bar}").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("- foo\n- bar").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("foo: bar").Style());
}

struct ParserExceptionTestCase {
  std::string name;
  std::string input;
  std::string expected_exception;
};

TEST(NodeTest, IncompleteJson) {
  std::vector<ParserExceptionTestCase> tests = {
      {"JSON map without value", "{\"access\"", ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map with colon but no value", "{\"access\":",
       ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map with unclosed value quote", "{\"access\":\"",
       ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map without end brace", "{\"access\":\"abc\"",
       ErrorMsg::END_OF_MAP_FLOW},
  };
  for (const ParserExceptionTestCase test : tests) {
    try {
      Load(test.input);
      FAIL() << "Expected exception " << test.expected_exception << " for "
             << test.name << ", input: " << test.input;
    } catch (const ParserException& e) {
      EXPECT_EQ(test.expected_exception, e.msg);
    }
  }
}

TEST(NodeTest, LoadTildeAsNull) {
  Node node = Load("~");
  ASSERT_TRUE(node.IsNull());
}

TEST(NodeTest, LoadTagWithParenthesis) {
    Node node = Load("!Complex(Tag) foo");
    EXPECT_EQ(node.Tag(), "!Complex(Tag)");
    EXPECT_EQ(node.as<std::string>(), "foo");
}

TEST(NodeTest, LoadTagWithNullScalar) {
  Node node = Load("!2");
  EXPECT_TRUE(node.IsNull());
}

}  // namespace
}  // namespace YAML
<commit_msg>Add IsNull() check in test after reassignment (#814)<commit_after>#include "yaml-cpp/yaml.h"  // IWYU pragma: keep

#include "gtest/gtest.h"

namespace YAML {
namespace {
TEST(LoadNodeTest, Reassign) {
  Node node = Load("foo");
  node = Node();
  EXPECT_TRUE(node.IsNull());
}

TEST(LoadNodeTest, FallbackValues) {
  Node node = Load("foo: bar\nx: 2");
  EXPECT_EQ("bar", node["foo"].as<std::string>());
  EXPECT_EQ("bar", node["foo"].as<std::string>("hello"));
  EXPECT_EQ("hello", node["baz"].as<std::string>("hello"));
  EXPECT_EQ(2, node["x"].as<int>());
  EXPECT_EQ(2, node["x"].as<int>(5));
  EXPECT_EQ(5, node["y"].as<int>(5));
}

TEST(LoadNodeTest, NumericConversion) {
  Node node = Load("[1.5, 1, .nan, .inf, -.inf, 0x15, 015]");
  EXPECT_EQ(1.5f, node[0].as<float>());
  EXPECT_EQ(1.5, node[0].as<double>());
  EXPECT_THROW(node[0].as<int>(), TypedBadConversion<int>);
  EXPECT_EQ(1, node[1].as<int>());
  EXPECT_EQ(1.0f, node[1].as<float>());
  EXPECT_NE(node[2].as<float>(), node[2].as<float>());
  EXPECT_EQ(std::numeric_limits<float>::infinity(), node[3].as<float>());
  EXPECT_EQ(-std::numeric_limits<float>::infinity(), node[4].as<float>());
  EXPECT_EQ(21, node[5].as<int>());
  EXPECT_EQ(13, node[6].as<int>());
}

TEST(LoadNodeTest, Binary) {
  Node node = Load(
      "[!!binary \"SGVsbG8sIFdvcmxkIQ==\", !!binary "
      "\"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS"
      "B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG"
      "x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi"
      "B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG"
      "dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS"
      "4K\"]");
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>("Hello, World!"), 13),
            node[0].as<Binary>());
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node[1].as<Binary>());
}

TEST(LoadNodeTest, BinaryWithWhitespaces) {
  Node node = Load(
      "binaryText: !binary |-\n"
      "  TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS\n"
      "  B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG\n"
      "  x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi\n"
      "  B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG\n"
      "  dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS\n"
      "  4K");
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node["binaryText"].as<Binary>());
}

TEST(LoadNodeTest, IterateSequence) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 4);
    int x = seq[i++];
    EXPECT_EQ(x, it->as<int>());
  }
  EXPECT_EQ(4, i);
}

TEST(LoadNodeTest, IterateMap) {
  Node node = Load("{a: A, b: B, c: C}");
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 3);
    i++;
    EXPECT_EQ(it->second.as<char>(), it->first.as<char>() + 'A' - 'a');
  }
  EXPECT_EQ(3, i);
}

#ifdef BOOST_FOREACH
TEST(LoadNodeTest, ForEach) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  BOOST_FOREACH (const Node& item, node) {
    int x = seq[i++];
    EXPECT_EQ(x, item.as<int>());
  }
}

TEST(LoadNodeTest, ForEachMap) {
  Node node = Load("{a: A, b: B, c: C}");
  BOOST_FOREACH (const const_iterator::value_type& p, node) {
    EXPECT_EQ(p.second.as<char>(), p.first.as<char>() + 'A' - 'a');
  }
}
#endif

TEST(LoadNodeTest, CloneScalar) {
  Node node = Load("!foo monkey");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(clone.as<std::string>(), node.as<std::string>());
  EXPECT_EQ(clone.Tag(), node.Tag());
}

TEST(LoadNodeTest, CloneSeq) {
  Node node = Load("[1, 3, 5, 7]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  for (std::size_t i = 0; i < node.size(); i++) {
    EXPECT_EQ(clone[i].as<int>(), node[i].as<int>());
  }
}

TEST(LoadNodeTest, CloneMap) {
  Node node = Load("{foo: bar}");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Map, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone["foo"].as<std::string>(), node["foo"].as<std::string>());
}

TEST(LoadNodeTest, CloneAlias) {
  Node node = Load("&foo [*foo]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone[0], clone);
}

TEST(LoadNodeTest, ForceInsertIntoMap) {
  Node node;
  node["a"] = "b";
  node.force_insert("x", "y");
  node.force_insert("a", 5);
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(NodeType::Map, node.Type());
  bool ab = false;
  bool a5 = false;
  bool xy = false;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    if (it->first.as<std::string>() == "a") {
      if (it->second.as<std::string>() == "b")
        ab = true;
      else if (it->second.as<std::string>() == "5")
        a5 = true;
    } else if (it->first.as<std::string>() == "x" &&
               it->second.as<std::string>() == "y")
      xy = true;
  }
  EXPECT_TRUE(ab);
  EXPECT_TRUE(a5);
  EXPECT_TRUE(xy);
}

TEST(LoadNodeTest, ResetNode) {
  Node node = Load("[1, 2, 3]");
  EXPECT_TRUE(!node.IsNull());
  Node other = node;
  node.reset();
  EXPECT_TRUE(node.IsNull());
  EXPECT_TRUE(!other.IsNull());
  node.reset(other);
  EXPECT_TRUE(!node.IsNull());
  EXPECT_EQ(node, other);
}

TEST(LoadNodeTest, EmptyString) {
  Node node = Load("\"\"");
  EXPECT_TRUE(!node.IsNull());
}

TEST(LoadNodeTest, DereferenceIteratorError) {
  Node node = Load("[{a: b}, 1, 2]");
  EXPECT_THROW(node.begin()->first.as<int>(), InvalidNode);
  EXPECT_EQ(true, (*node.begin()).IsMap());
  EXPECT_EQ(true, node.begin()->IsMap());
  EXPECT_THROW((*node.begin()->begin()).Type(), InvalidNode);
  EXPECT_THROW(node.begin()->begin()->Type(), InvalidNode);
}

TEST(NodeTest, EmitEmptyNode) {
  Node node;
  Emitter emitter;
  emitter << node;
  EXPECT_EQ("", std::string(emitter.c_str()));
}

TEST(NodeTest, ParseNodeStyle) {
  EXPECT_EQ(EmitterStyle::Flow, Load("[1, 2, 3]").Style());
  EXPECT_EQ(EmitterStyle::Flow, Load("{foo: bar}").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("- foo\n- bar").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("foo: bar").Style());
}

struct ParserExceptionTestCase {
  std::string name;
  std::string input;
  std::string expected_exception;
};

TEST(NodeTest, IncompleteJson) {
  std::vector<ParserExceptionTestCase> tests = {
      {"JSON map without value", "{\"access\"", ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map with colon but no value", "{\"access\":",
       ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map with unclosed value quote", "{\"access\":\"",
       ErrorMsg::END_OF_MAP_FLOW},
      {"JSON map without end brace", "{\"access\":\"abc\"",
       ErrorMsg::END_OF_MAP_FLOW},
  };
  for (const ParserExceptionTestCase test : tests) {
    try {
      Load(test.input);
      FAIL() << "Expected exception " << test.expected_exception << " for "
             << test.name << ", input: " << test.input;
    } catch (const ParserException& e) {
      EXPECT_EQ(test.expected_exception, e.msg);
    }
  }
}

TEST(NodeTest, LoadTildeAsNull) {
  Node node = Load("~");
  ASSERT_TRUE(node.IsNull());
}

TEST(NodeTest, LoadTagWithParenthesis) {
    Node node = Load("!Complex(Tag) foo");
    EXPECT_EQ(node.Tag(), "!Complex(Tag)");
    EXPECT_EQ(node.as<std::string>(), "foo");
}

TEST(NodeTest, LoadTagWithNullScalar) {
  Node node = Load("!2");
  EXPECT_TRUE(node.IsNull());
}

}  // namespace
}  // namespace YAML
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Ref.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 02:48:17 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#ifndef _CONNECTIVITY_JAVA_SQL_REF_HXX_
#include "java/sql/Ref.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Ref
//**************************************************************

jclass java_sql_Ref::theClass = 0;
java_sql_Ref::java_sql_Ref( JNIEnv * pEnv, jobject myObj )
: java_lang_Object( pEnv, myObj )
{
    SDBThreadAttach::addRef();
}
java_sql_Ref::~java_sql_Ref()
{
    SDBThreadAttach::releaseRef();
}

jclass java_sql_Ref::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/sql/Ref" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_Ref::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

::rtl::OUString SAL_CALL java_sql_Ref::getBaseTypeName(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    ::rtl::OUString aStr;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/String;";
        static const char * cMethodName = "getBaseTypeName";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
            aStr = JavaString2String(t.pEnv,out);
            // und aufraeumen
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return  aStr;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.9.216); FILE MERGED 2008/04/01 10:53:05 thb 1.9.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:42 rt 1.9.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: Ref.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "java/sql/Ref.hxx"
#include "java/tools.hxx"
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Ref
//**************************************************************

jclass java_sql_Ref::theClass = 0;
java_sql_Ref::java_sql_Ref( JNIEnv * pEnv, jobject myObj )
: java_lang_Object( pEnv, myObj )
{
    SDBThreadAttach::addRef();
}
java_sql_Ref::~java_sql_Ref()
{
    SDBThreadAttach::releaseRef();
}

jclass java_sql_Ref::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/sql/Ref" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_Ref::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

::rtl::OUString SAL_CALL java_sql_Ref::getBaseTypeName(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    ::rtl::OUString aStr;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/String;";
        static const char * cMethodName = "getBaseTypeName";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
            aStr = JavaString2String(t.pEnv,out);
            // und aufraeumen
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return  aStr;
}

<|endoftext|>


<commit_before>/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 14:05:18
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef tuple<int, int, int, int, int> state; // x, y, dir, a, b

int A, B;
int h, w;
string c[100];

queue<state> Q;

bool valid(int x, int y, int a, int b)
{
  return (a <= A && b <= B && c[x][y] == '.');
}

int main()
{
  cin >> A >> B;
  cin >> h >> w;
  for (auto i = 0; i < h; i++)
  {
    cin >> c[i];
  }
  Q.push(state(1, 1, 0, 0, 0));
  while (!Q.empty())
  {
    int now_x = get<0>(Q.front());
    int now_y = get<1>(Q.front());
    int now_dir = get<2>(Q.front());
    int now_a = get<3>(Q.front());
    int now_b = get<4>(Q.front());
    #if DEBUG == 1
    cerr << "(" << now_x << ", " << now_y << "), "
         << now_dir << ", "
         << "(" << now_a << ", " << now_b << ")" << endl;
    #endif
    Q.pop();
    if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)
    {
      cout << "Yes" << endl;
      return 0;
    }
    else
    {
      int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};
      int new_a[3] = {now_a + 1, now_a, now_a};
      int new_b[3] = {now_b, now_b + 1, now_b};
      for (auto k = 0; k < 3; k++)
      {
        int new_x = now_x + dx[new_dir[k]];
        int new_y = now_y + dy[new_dir[k]];
        if (valid(new_x, new_y, new_a[k], new_b[k]))
        {
          Q.push(state(new_x, new_y, new_dir[k], new_a[k], new_b[k]));
        }
      }
    }
  }
  cout << "No" << endl;
}<commit_msg>submit B.cpp to 'B - 駆け抜けろ！埼大山車部！！' (maximum-cup-2018) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 14:05:18
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef tuple<int, int, int, int, int> state; // x, y, dir, a, b

int A, B;
int h, w;
string c[100];

stack<state> S;

bool valid(int x, int y, int a, int b)
{
  return (a <= A && b <= B && c[x][y] == '.');
}

int main()
{
  cin >> A >> B;
  cin >> h >> w;
  for (auto i = 0; i < h; i++)
  {
    cin >> c[i];
  }
  S.push(state(1, 1, 0, 0, 0));
  while (!S.empty())
  {
    int now_x = get<0>(S.top());
    int now_y = get<1>(S.top());
    int now_dir = get<2>(S.top());
    int now_a = get<3>(S.top());
    int now_b = get<4>(S.top());
    #if DEBUG == 1
    cerr << "(" << now_x << ", " << now_y << "), "
         << now_dir << ", "
         << "(" << now_a << ", " << now_b << ")" << endl;
    #endif
    S.pop();
    if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)
    {
      cout << "Yes" << endl;
      return 0;
    }
    else
    {
      int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};
      int new_a[3] = {now_a + 1, now_a, now_a};
      int new_b[3] = {now_b, now_b + 1, now_b};
      for (auto k = 0; k < 3; k++)
      {
        int new_x = now_x + dx[new_dir[k]];
        int new_y = now_y + dy[new_dir[k]];
        if (valid(new_x, new_y, new_a[k], new_b[k]))
        {
          S.push(state(new_x, new_y, new_dir[k], new_a[k], new_b[k]));
        }
      }
    }
  }
  cout << "No" << endl;
}<|endoftext|>


<commit_before>#include "Bits.h"
using namespace std;

/**
 * Create a new object of Bits. 'data' will be set to NULL.
 * 'position' and 'max_position' will be set to 0.
 */
Bits::Bits(){
	this->data = NULL;
	this->position = 0;
	this->max_position = 0;
}

/**
 * Destroying the Bits object will call 'unload()'.
 */
Bits::~Bits(){
	this->unload();
}

/**
 * Read data from file.
 * @param fname The path/name of the file.
 * @param mode Optional, open mode. Default is "rb".
 * @return True if data was successfully readen, otherwise false.
 */
bool Bits::fromFile(char *fname, ios_base::openmode mode){
	bool state = false;
	streampos size;
	ifstream file(fname, mode);

	if(fname == NULL){
		goto err;
	}

	if(file.is_open()){
		file.seekg(0, ios::end);
		size = file.tellg();

		if(size == -1){
			goto err;
		}

		this->data = (unsigned char *)malloc(size);
		if(this->data == NULL){
			goto err;
		}

		this->position = 0;
		this->max_position = size;

		file.seekg(0, ios::beg);
		file.read((char *)data, size);
		file.close();

		state = true;
	}

	err:

	return state;
}

/**
 * Write data to file.
 * @param fname The path/name of the file.
 * @param mode Optional, open mode. Default is "wb".
 * @return True if data was successfully written, otherwise false.
 */
bool Bits::toFile(char *fname, const char *mode){

}

/**
 * Load a memory chunk of data, the size of N bytes.
 * @param chunk A  pointer to the data to be loaded.
 * @param size Number of bytes to load.
 * @return True on success, false otherwise.
 */
bool Bits::fromMem(unsigned char *chunk, int64_t size){
	if(chunk == NULL){
		return false;
	}else{
		this->data = chunk;
		this->position = 0;
		this->max_position = size;
		return true;
	}
}

/**
 * Unload whatever was loaded (if anything was loaded at all).
 * That means that 'data' will be set to NULL.
 * Also, 'position' and 'max_position' will be set to 0.
 */
void Bits::unload(){
	this->data = NULL;
	this->position = 0;
	this->max_position = 0;
}

/**
 * Read N bytes starting from the current position of the data.
 * The current position will be changed to <current position> + n.
 * @param n Number of bytes to read.
 * @param reverse If set to true (default is false) the data will be returned byte-reversed.
 * @return The data that was readen or NULL if something failed.
 */
unsigned char *Bits::read(int64_t n, bool reverse){
	if(!this->canMoveForward(n)){
		return NULL;
	}

	unsigned char *tmp = (unsigned char *) malloc(n);

	if(!tmp){
		return NULL;
	}

	if(reverse){
		for(int64_t i = n - 1; i >= 0; i--){
			tmp[n - (i + 1)] = this->data[this->position + i];
		}
		this->position += n;
	}else{
		for(int64_t i = 0; i < n; i++){
			tmp[i] = this->data[this->position];
			this->position++;
		}
	}

	return tmp;
}

/**
 * Read N bytes starting from the current position of the data, without changing the position.
 * @param n Number of bytes to read.
 * @param reverse If set to true (default is false) the data will be returned byte-reversed.
 * @return The data that was readen or NULL if something failed.
 */
unsigned char *Bits::peek(int64_t n, bool reverse){
	if(!this->canMoveForward(n)){
		return NULL;
	}

	int64_t tmppos = this->position;
	unsigned char *tmp = this->read(n, reverse);
	this->position = tmppos;

	return tmp;
}

/**
 * Write N bytes of data read from chunk, starting from the current position of the data.
 * The current position will be changed to <current position> + n.
 * @param chunk The data we want to write.
 * @param n Number of bytes we want to write from the chunk.
 * @param patch If set to false (default is true) data will be inserted without replacing, instead of patching.
 * @return True on success, false otherwise.
 */
bool Bits::write(unsigned char *chunk, int64_t n, bool patch){
	if(patch && this->canMoveForward(n)){

		memcpy(this->data + this->position, chunk, n);

	}else if(!patch){

		unsigned char *newdata = (unsigned char*)malloc(this->max_position + n);

		//Copy from position 0 to current position
		memcpy(newdata, this->data, this->position);

		//Insert new data
		memcpy(newdata + this->position, chunk, n);

		//Finish copying until the end
		memcpy(newdata + this->position + n, this->data + this->position, this->max_position - this->position);

		try{
			//free(this->data);
		}catch(...){
			//Oops...
		}

		this->data = newdata;
		this->max_position += n;

	}else{

		return false;

	}

	this->position += n;
	return true;
}

/**
 * Seek N bytes in the currently loaded data.
 * If N is negative, the position will be decreased.
 * If the operation exceeds the minimum or maximum position, false will be returned.
 * @param n Number of bytes to seek.
 * @return True is the operation was successful, false otherwise.
 */
bool Bits::seek(int64_t n){
	if(
			(n >= 0 && this->canMoveForward(n)) ||
			(n <= 0 && this->canMoveBackwards(n))
	){
		this->position += n;
		return true;
	}else{
		return false;
	}
}

/**
 * Find the nearest match to a given pattern in the data behind the current position.
 * The current position will remain unchanged.
 * @param pattern The byte(s) pattern we are looking for.
 * @param n The number of bytes the pattern is long.
 * @return Position/offset or -1 if nothing was found.
 */
int64_t Bits::findPrevious(unsigned char *pattern, int64_t n){
	int64_t res = -1, tmppos = this->position;

	while(this->canMoveBackwards()){;
		if(!this->canMoveForward(n)){
			this->seek(-1);
			continue;
		}

		bool c1 = memcmp(this->data + this->position, pattern, n);
		if(c1 == 0){
			res = this->position;
			break;
		}else{
			this->seek(-1);
		}
	}

	this->position = tmppos;
	return res;
}

/**
 * Find the nearest match to a given pattern in the data starting at the current position.
 * This, effectively, means that if you search something which is already right next
 * to the current position you'll keep "finding" it forever and ever. Just use "seek" or
 * "setPosition" to go to <current position> + 1 and continue searching from there.
 * The current position will remain unchanged.
 * @param pattern The byte(s) pattern we are looking for.
 * @param n The number of bytes the pattern is long.
 * @return Position/offset or -1 if nothing was found.
 */
int64_t Bits::findNext(unsigned char *pattern, int64_t n){
	int64_t res = -1, tmppos = this->position;

	while(this->canMoveForward(n)){
		bool c1 = memcmp(this->data + this->position, pattern, n);
		if(c1 == 0){
			res = this->position;
			break;
		}else{
			this->seek(1);
		}
	}

	this->position = tmppos;
	return res;
}

/**
 * Test if a bit in the next to be read byte is set.
 * Keep in mind that the bit 0 is the least significant, while bit 8 is the most significant.
 * Example: In 00000010, all bits are set to 0, except bit 1 (that is, the second bit).
 * @param bit The Nth bit to test.
 * @return True if the bit is set, false otherwise.
 */
bool Bits::testBit(unsigned int bit){
	if(!this->canMoveForward() || bit > 7){
		return false;
	}

	uint8_t byte = (uint8_t) *this->peek(1);
	return byte & (1 << bit);
}

/**
 * Test a bit to 1 in the next to be read byte.
 * Keep in mind that the bit 0 is the least significant, while bit 8 is the most significant.
 * Example: In 00000010, all bits are set to 0, except bit 1 (that is, the second bit).
 * @param bit The Nth bit to set.
 * @return True if the bit is set, false otherwise.
 */
bool Bits::setBit(unsigned int bit){
	if(!this->canMoveForward() || bit > 7){
		return false;
	}

	uint8_t byte = (uint8_t) *this->peek(1);
	byte |= 1 << bit;
	this->write(&byte, 1);
	this->position--;

	return true;
}

bool Bits::unsetBit(unsigned int bit){
	if(!this->canMoveForward() || bit > 7){
		return false;
	}

	uint8_t byte = (uint8_t) *this->peek(1);
	byte &= ~(1 << bit);
	this->write(&byte, 1);
	this->position--;

	return true;
}

bool Bits::toggleBit(unsigned int bit){
	if(this->testBit(bit)){
		return this->unsetBit(bit);
	}else{
		return this->setBit(bit);
	}
}

/**
 * Print N bytes starting from the current position, in a hexadecimal representation.
 * @param n Number of bytes to print.
 */
void Bits::printHex(int64_t n){
	for(int64_t i = 0; i < n && this->canMoveForward(); i++){
		cout << hex << (int) *this->read(1);
	}
}

/**
 * Print N bytes starting from the current position, each byte in it's bits representation.
 * @param n Number of bytes to print.
 */
void Bits::printBits(int64_t n){
	for(int64_t i = 0; i < n && this->canMoveForward(); i++){
		cout << bitset<8>(*this->read(1));
	}
}

/**
 * Get a pointer to the data managed by Bits
 * @return A pointer to the data managed by Bits.
 */
unsigned char *Bits::getData(){
	return this->data;
}

/**
 * Getter for the current position.
 * @return The current position.
 */
int64_t Bits::getPosition(){
	return this->position;
}

/**
 * Set the current position.
 * @param The position that is desired.
 */
bool Bits::setPosition(int64_t pos){
	if(this->max_position >= pos){
		this->position = pos;
		return true;
	}else{
		return false;
	}
}

/**
 * Getter for the maximum position. we can go.
 * @return The maximum position we can go.
 */
int64_t Bits::getMaxPosition(){
	return this->max_position;
}

/******************************************************************************/

bool Bits::canMoveBackwards(int64_t n){
	if(this->position == 0 || this->position < n){
		return false;
	}

	return (this->position + n) >= 0;
}

bool Bits::canMoveForward(int64_t n){
	return (this->position + n) <= this->max_position;
}<commit_msg>WIP toFile()<commit_after>#include "Bits.h"
using namespace std;

/**
 * Create a new object of Bits. 'data' will be set to NULL.
 * 'position' and 'max_position' will be set to 0.
 */
Bits::Bits(){
	this->data = NULL;
	this->position = 0;
	this->max_position = 0;
}

/**
 * Destroying the Bits object will call 'unload()'.
 */
Bits::~Bits(){
	this->unload();
}

/**
 * Read data from file.
 * @param fname The path/name of the file.
 * @param mode Optional, open mode. Default is "rb".
 * @return True if data was successfully readen, otherwise false.
 */
bool Bits::fromFile(char *fname, ios_base::openmode mode){
	bool state = false;
	streampos size;
	ifstream file(fname, mode);

	if(fname == NULL){
		goto err;
	}

	if(file.is_open()){
		file.seekg(0, ios::end);
		size = file.tellg();

		if(size == -1){
			goto err;
		}

		this->data = (unsigned char *)malloc(size);
		if(this->data == NULL){
			goto err;
		}

		this->position = 0;
		this->max_position = size;

		file.seekg(0, ios::beg);
		file.read((char *)data, size);
		file.close();

		state = true;
	}

	err:

	return state;
}

/**
 * Write data to file.
 * @param fname The path/name of the file.
 * @param offset An offset from which should start the dumping. Default is 0.
 * @param size The size (in bytes) of the data to be written. Default is the length of the data holded by the object, if offset is 0, otherwise it will be calculated if not passed.
 * @param mode Optional, open mode. Default is "wb".
 * @return True if data was successfully written, otherwise false.
 */
bool Bits::toFile(char *fname, int64_t offset, int64_t size, ios_base::openmode mode){
	if(fname == NULL){
		goto err;
	}

	if(offset > this->max_position || offset < 0){
		goto err;
	}

	if(offset == 0 && size == -1){
		size = this->max_position;
	}else if(offset > 0 && size == -1){
		size = this->max_position - offset;
	}

	if(this->max_position - offset > size){
		goto err;
	}

	//TODO: DUMP!

	err:

	return false;
}

/**
 * Load a memory chunk of data, the size of N bytes.
 * @param chunk A pointer to the data to be loaded.
 * @param size Number of bytes to load.
 * @return True on success, false otherwise.
 */
bool Bits::fromMem(unsigned char *chunk, int64_t size){
	if(chunk == NULL){
		return false;
	}else{
		this->data = chunk;
		this->position = 0;
		this->max_position = size;
		return true;
	}
}

/**
 * Unload whatever was loaded (if anything was loaded at all).
 * That means that 'data' will be set to NULL.
 * Also, 'position' and 'max_position' will be set to 0.
 */
void Bits::unload(){
	this->data = NULL;
	this->position = 0;
	this->max_position = 0;
}

/**
 * Read N bytes starting from the current position of the data.
 * The current position will be changed to <current position> + n.
 * @param n Number of bytes to read.
 * @param reverse If set to true (default is false) the data will be returned byte-reversed.
 * @return The data that was readen or NULL if something failed.
 */
unsigned char *Bits::read(int64_t n, bool reverse){
	if(!this->canMoveForward(n)){
		return NULL;
	}

	unsigned char *tmp = (unsigned char *) malloc(n);

	if(!tmp){
		return NULL;
	}

	if(reverse){
		for(int64_t i = n - 1; i >= 0; i--){
			tmp[n - (i + 1)] = this->data[this->position + i];
		}
		this->position += n;
	}else{
		for(int64_t i = 0; i < n; i++){
			tmp[i] = this->data[this->position];
			this->position++;
		}
	}

	return tmp;
}

/**
 * Read N bytes starting from the current position of the data, without changing the position.
 * @param n Number of bytes to read.
 * @param reverse If set to true (default is false) the data will be returned byte-reversed.
 * @return The data that was readen or NULL if something failed.
 */
unsigned char *Bits::peek(int64_t n, bool reverse){
	if(!this->canMoveForward(n)){
		return NULL;
	}

	int64_t tmppos = this->position;
	unsigned char *tmp = this->read(n, reverse);
	this->position = tmppos;

	return tmp;
}

/**
 * Write N bytes of data read from chunk, starting from the current position of the data.
 * The current position will be changed to <current position> + n.
 * @param chunk The data we want to write.
 * @param n Number of bytes we want to write from the chunk.
 * @param patch If set to false (default is true) data will be inserted without replacing, instead of patching.
 * @return True on success, false otherwise.
 */
bool Bits::write(unsigned char *chunk, int64_t n, bool patch){
	if(patch && this->canMoveForward(n)){

		memcpy(this->data + this->position, chunk, n);

	}else if(!patch){

		unsigned char *newdata = (unsigned char*)malloc(this->max_position + n);

		//Copy from position 0 to current position
		memcpy(newdata, this->data, this->position);

		//Insert new data
		memcpy(newdata + this->position, chunk, n);

		//Finish copying until the end
		memcpy(newdata + this->position + n, this->data + this->position, this->max_position - this->position);

		try{
			//free(this->data);
		}catch(...){
			//Oops...
		}

		this->data = newdata;
		this->max_position += n;

	}else{

		return false;

	}

	this->position += n;
	return true;
}

/**
 * Seek N bytes in the currently loaded data.
 * If N is negative, the position will be decreased.
 * If the operation exceeds the minimum or maximum position, false will be returned.
 * @param n Number of bytes to seek.
 * @return True is the operation was successful, false otherwise.
 */
bool Bits::seek(int64_t n){
	if(
			(n >= 0 && this->canMoveForward(n)) ||
			(n <= 0 && this->canMoveBackwards(n))
	){
		this->position += n;
		return true;
	}else{
		return false;
	}
}

/**
 * Find the nearest match to a given pattern in the data behind the current position.
 * The current position will remain unchanged.
 * @param pattern The byte(s) pattern we are looking for.
 * @param n The number of bytes the pattern is long.
 * @return Position/offset or -1 if nothing was found.
 */
int64_t Bits::findPrevious(unsigned char *pattern, int64_t n){
	int64_t res = -1, tmppos = this->position;

	while(this->canMoveBackwards()){;
		if(!this->canMoveForward(n)){
			this->seek(-1);
			continue;
		}

		bool c1 = memcmp(this->data + this->position, pattern, n);
		if(c1 == 0){
			res = this->position;
			break;
		}else{
			this->seek(-1);
		}
	}

	this->position = tmppos;
	return res;
}

/**
 * Find the nearest match to a given pattern in the data starting at the current position.
 * This, effectively, means that if you search something which is already right next
 * to the current position you'll keep "finding" it forever and ever. Just use "seek" or
 * "setPosition" to go to <current position> + 1 and continue searching from there.
 * The current position will remain unchanged.
 * @param pattern The byte(s) pattern we are looking for.
 * @param n The number of bytes the pattern is long.
 * @return Position/offset or -1 if nothing was found.
 */
int64_t Bits::findNext(unsigned char *pattern, int64_t n){
	int64_t res = -1, tmppos = this->position;

	while(this->canMoveForward(n)){
		bool c1 = memcmp(this->data + this->position, pattern, n);
		if(c1 == 0){
			res = this->position;
			break;
		}else{
			this->seek(1);
		}
	}

	this->position = tmppos;
	return res;
}

/**
 * Test if a bit in the next to be read byte is set.
 * Keep in mind that the bit 0 is the least significant, while bit 8 is the most significant.
 * Example: In 00000010, all bits are set to 0, except bit 1 (that is, the second bit).
 * @param bit The Nth bit to test.
 * @return True if the bit is set, false otherwise.
 */
bool Bits::testBit(unsigned int bit){
	if(!this->canMoveForward() || bit > 7){
		return false;
	}

	uint8_t byte = (uint8_t) *this->peek(1);
	return byte & (1 << bit);
}

/**
 * Test a bit to 1 in the next to be read byte.
 * Keep in mind that the bit 0 is the least significant, while bit 8 is the most significant.
 * Example: In 00000010, all bits are set to 0, except bit 1 (that is, the second bit).
 * @param bit The Nth bit to set.
 * @return True if the bit is set, false otherwise.
 */
bool Bits::setBit(unsigned int bit){
	if(!this->canMoveForward() || bit > 7){
		return false;
	}

	uint8_t byte = (uint8_t) *this->peek(1);
	byte |= 1 << bit;
	this->write(&byte, 1);
	this->position--;

	return true;
}

bool Bits::unsetBit(unsigned int bit){
	if(!this->canMoveForward() || bit > 7){
		return false;
	}

	uint8_t byte = (uint8_t) *this->peek(1);
	byte &= ~(1 << bit);
	this->write(&byte, 1);
	this->position--;

	return true;
}

bool Bits::toggleBit(unsigned int bit){
	if(this->testBit(bit)){
		return this->unsetBit(bit);
	}else{
		return this->setBit(bit);
	}
}

/**
 * Print N bytes starting from the current position, in a hexadecimal representation.
 * @param n Number of bytes to print.
 */
void Bits::printHex(int64_t n){
	for(int64_t i = 0; i < n && this->canMoveForward(); i++){
		cout << hex << (int) *this->read(1);
	}
}

/**
 * Print N bytes starting from the current position, each byte in it's bits representation.
 * @param n Number of bytes to print.
 */
void Bits::printBits(int64_t n){
	for(int64_t i = 0; i < n && this->canMoveForward(); i++){
		cout << bitset<8>(*this->read(1));
	}
}

/**
 * Get a pointer to the data managed by Bits
 * @return A pointer to the data managed by Bits.
 */
unsigned char *Bits::getData(){
	return this->data;
}

/**
 * Getter for the current position.
 * @return The current position.
 */
int64_t Bits::getPosition(){
	return this->position;
}

/**
 * Set the current position.
 * @param The position that is desired.
 */
bool Bits::setPosition(int64_t pos){
	if(this->max_position >= pos){
		this->position = pos;
		return true;
	}else{
		return false;
	}
}

/**
 * Getter for the maximum position. we can go.
 * @return The maximum position we can go.
 */
int64_t Bits::getMaxPosition(){
	return this->max_position;
}

/******************************************************************************/

bool Bits::canMoveBackwards(int64_t n){
	if(this->position == 0 || this->position < n){
		return false;
	}

	return (this->position + n) >= 0;
}

bool Bits::canMoveForward(int64_t n){
	return (this->position + n) <= this->max_position;
}<|endoftext|>