<commit_before>/// \file TClingUtilsTest.cxx
///
/// \brief The file contain unit tests which test the TClingUtils.h
///
/// \author Vassil Vassilev <vvasilev@cern.ch>
///
/// \date Aug, 2019
///
/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <TClingUtils.h>

#include <ROOT/FoundationUtils.hxx>

#include "gtest/gtest.h"

#include <fstream>

TEST(TClingUtilsTests, GetRealPath)
{
#ifndef R__WIN32
   // Create a file in the current folder
   std::string cwd = ROOT::FoundationUtils::GetCurrentDir();

   ASSERT_FALSE(cwd.empty());

   std::ofstream file;
   file.open("./realfile1", std::ios::out);
   file.close();
   file.open("./realfile2", std::ios::out);
   file.close();
   // Create symlinks
   symlink("./realfile1", "symlink_realfile1");
   symlink((cwd + "realfile2").c_str(), "symlink_realfile2");

   // Recursive symlinks
   symlink("./symlink_realfile1", "symlink1_symlink_realfile1");
   symlink((cwd + "symlink_realfile2").c_str(), "symlink1_symlink_realfile2");

   symlink("./symlink_realfile2", "symlink2_symlink_realfile2");
   symlink((cwd + "symlink_realfile1").c_str(), "symlink2_symlink_realfile1");

   symlink((cwd + ".//.///symlink_realfile1").c_str(), "symlink3_symlink_realfile1");

   using namespace ROOT::TMetaUtils;
   std::string realfile1 = GetRealPath("./realfile1");
   std::string realfile2 = GetRealPath("./realfile2");
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink1_symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink2_symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink3_symlink_realfile1"));

   ASSERT_TRUE(realfile2 == GetRealPath("./realfile2"));
   ASSERT_TRUE(realfile2 == GetRealPath("./symlink_realfile2"));
   ASSERT_TRUE(realfile2 == GetRealPath("./symlink1_symlink_realfile2"));
   ASSERT_TRUE(realfile2 == GetRealPath("./symlink2_symlink_realfile2"));

   std::remove("./symlink3_symlink_realfile1");
   std::remove("./symlink2_symlink_realfile2");
   std::remove("./symlink2_symlink_realfile1");
   std::remove("./symlink1_symlink_realfile2");
   std::remove("./symlink1_symlink_realfile1");
   std::remove("./symlink_realfile1");
   std::remove("./symlink_realfile2");
   std::remove("./realfile1");
   std::remove("./realfile2");
#endif // not R__WIN32
}
<commit_msg>[clingutil] Fix "result unused" warning on symlink.<commit_after>/// \file TClingUtilsTest.cxx
///
/// \brief The file contain unit tests which test the TClingUtils.h
///
/// \author Vassil Vassilev <vvasilev@cern.ch>
///
/// \date Aug, 2019
///
/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <TClingUtils.h>

#include <ROOT/FoundationUtils.hxx>

#include "gtest/gtest.h"

#include <fstream>

TEST(TClingUtilsTests, GetRealPath)
{
#ifndef R__WIN32
   // Create a file in the current folder
   std::string cwd = ROOT::FoundationUtils::GetCurrentDir();

   ASSERT_FALSE(cwd.empty());

   std::ofstream file;
   file.open("./realfile1", std::ios::out);
   file.close();
   file.open("./realfile2", std::ios::out);
   file.close();
   // Create symlinks
   ASSERT_GE(symlink("./realfile1", "symlink_realfile1"), 0);
   ASSERT_GE(symlink((cwd + "realfile2").c_str(), "symlink_realfile2"), 0);

   // Recursive symlinks
   ASSERT_GE(symlink("./symlink_realfile1", "symlink1_symlink_realfile1"), 0);
   ASSERT_GE(symlink((cwd + "symlink_realfile2").c_str(), "symlink1_symlink_realfile2"), 0);

   ASSERT_GE(symlink("./symlink_realfile2", "symlink2_symlink_realfile2"), 0);
   ASSERT_GE(symlink((cwd + "symlink_realfile1").c_str(), "symlink2_symlink_realfile1"), 0);

   ASSERT_GE(symlink((cwd + ".//.///symlink_realfile1").c_str(), "symlink3_symlink_realfile1"), 0);

   using namespace ROOT::TMetaUtils;
   std::string realfile1 = GetRealPath("./realfile1");
   std::string realfile2 = GetRealPath("./realfile2");
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink1_symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink2_symlink_realfile1"));
   ASSERT_TRUE(realfile1 == GetRealPath("./symlink3_symlink_realfile1"));

   ASSERT_TRUE(realfile2 == GetRealPath("./realfile2"));
   ASSERT_TRUE(realfile2 == GetRealPath("./symlink_realfile2"));
   ASSERT_TRUE(realfile2 == GetRealPath("./symlink1_symlink_realfile2"));
   ASSERT_TRUE(realfile2 == GetRealPath("./symlink2_symlink_realfile2"));

   std::remove("./symlink3_symlink_realfile1");
   std::remove("./symlink2_symlink_realfile2");
   std::remove("./symlink2_symlink_realfile1");
   std::remove("./symlink1_symlink_realfile2");
   std::remove("./symlink1_symlink_realfile1");
   std::remove("./symlink_realfile1");
   std::remove("./symlink_realfile2");
   std::remove("./realfile1");
   std::remove("./realfile2");
#endif // not R__WIN32
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Timo Savola
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "api.h"
#include "tap.hpp"

#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <set>

#include "buffer.hpp"
#include "peer.hpp"

using namespace tap;

struct TapMarshalHeader {
	TapKey size;
	TapKey type_id;
	TapKey key;
} TAP_PACKED;

struct TapMarshalVisitor {
	static bool Visit(const void *ptr, void *arg) throw ()
	{
		return reinterpret_cast<TapMarshalVisitor *> (arg)->visit(ptr);
	}

	TapMarshalVisitor(TapPeer *peer, TapBuffer *buffer) throw ():
		peer(peer),
		buffer(buffer)
	{
	}

	bool visit(const void *ptr) throw ()
	{
		if (seen.find(ptr) != seen.end())
			return true;

		seen.insert(ptr);

		const TapType *type = tap_object_type(ptr);
		TapKey key = 0;

		auto i = peer->key_states.find(ptr);
		if (i != peer->key_states.end()) {
			if (i->second.dirty) {
				key = i->second.key;
				i->second.dirty = false;
			}
		} else {
			key = peer->insert(ptr, false);
		}

		if (key) {
			size_t marshal_size = type->marshal_size(type, ptr, peer);
			size_t extent_size = sizeof (TapMarshalHeader) + marshal_size;

			auto header = reinterpret_cast<TapMarshalHeader *> (
					buffer->extend(extent_size));
			if (header == NULL)
				return false;

			header->size = Port(extent_size);
			header->type_id = Port(type->id);
			header->key = Port(key);

			if (!type->marshal(type, ptr, peer, header + 1, marshal_size))
				return false;
		}

		return type->traverse(type, ptr, Visit, this);
	}

	TapPeer *const peer;
	TapBuffer *const buffer;
	std::set<const void *> seen;
};

bool tap_marshal(TapPeer *peer, TapBuffer *buffer, const void *ptr)
{
	TapMarshalVisitor visitor(peer, buffer);
	return visitor.visit(ptr);
}

static void *tap_unmarshal_pass1(TapPeer *peer, const void *data,
                                 size_t size) throw ()
{
	void *root_ptr = NULL;

	while (size >= sizeof (TapMarshalHeader)) {
		auto header = reinterpret_cast<const TapMarshalHeader *> (data);
		uint32_t item_size = Port(header->size);
		uint32_t item_type_id = Port(header->type_id);
		TapKey item_key = Port(header->key);

		if (item_size > size) {
			std::fprintf(stderr, "unmarshal: header size out of bounds\n");
			return NULL;
		}
		size_t marshal_size = item_size - sizeof (TapMarshalHeader);
		const void *marshal_data = header + 1;

		auto i = peer->instance.system.types.find(item_type_id);
		if (i == peer->instance.system.types.end()) {
			std::fprintf(stderr, "unmarshal: object type id is unknown\n");
			return NULL;
		}
		const TapType *type = i->second;

		void *ptr;

		auto j = peer->objects.find(item_key);
		if (j != peer->objects.end()) {
			ptr = j->second;
			type->destroy(type, ptr);

			peer->key_states[ptr].dirty = false;
		} else {
			ptr = type->unmarshal_alloc(type, marshal_data, marshal_size);
			if (ptr == NULL) {
				std::fprintf(stderr, "unmarshal: allocation failed\n");
				return NULL;
			}

			peer->key_states[ptr] = TapPeer::KeyState(item_key, false);
			peer->objects[item_key] = ptr;
		}

		if (root_ptr == NULL)
			root_ptr = ptr;

		data = reinterpret_cast<const char *> (data) + item_size;
		size -= item_size;
	}

	if (size > 0) {
		std::fprintf(stderr,
		             "unmarshal: trailing garbage or truncated data\n");
		return NULL;
	}

	return root_ptr;
}

static bool tap_unmarshal_pass2(TapPeer *peer, const void *data,
                                size_t size) throw ()
{
	while (size >= sizeof (TapMarshalHeader)) {
		auto header = reinterpret_cast<const TapMarshalHeader *> (data);
		uint32_t item_size = Port(header->size);
		TapKey item_key = Port(header->key);

		size_t marshal_size = item_size - sizeof (TapMarshalHeader);
		const void *marshal_data = header + 1;
		void *ptr = peer->objects.find(item_key)->second;
		const TapType *type = tap_object_type(ptr);

		if (!type->unmarshal(type, ptr, peer, marshal_data, marshal_size))
			return false;

		data = reinterpret_cast<const char *> (data) + item_size;
		size -= item_size;
	}

	return true;
}

void *tap_unmarshal(TapPeer *peer, const void *data, size_t size)
{
	void *ptr = tap_unmarshal_pass1(peer, data, size);

	if (ptr && !tap_unmarshal_pass2(peer, data, size))
		ptr = NULL;

	return ptr;
}
<commit_msg>TapKey fix<commit_after>/*
 * Copyright (c) 2013, Timo Savola
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "api.h"
#include "tap.hpp"

#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <set>

#include "buffer.hpp"
#include "peer.hpp"

using namespace tap;

struct TapMarshalHeader {
	uint32_t size;
	uint32_t type_id;
	TapKey key;
} TAP_PACKED;

struct TapMarshalVisitor {
	static bool Visit(const void *ptr, void *arg) throw ()
	{
		return reinterpret_cast<TapMarshalVisitor *> (arg)->visit(ptr);
	}

	TapMarshalVisitor(TapPeer *peer, TapBuffer *buffer) throw ():
		peer(peer),
		buffer(buffer)
	{
	}

	bool visit(const void *ptr) throw ()
	{
		if (seen.find(ptr) != seen.end())
			return true;

		seen.insert(ptr);

		const TapType *type = tap_object_type(ptr);
		TapKey key = 0;

		auto i = peer->key_states.find(ptr);
		if (i != peer->key_states.end()) {
			if (i->second.dirty) {
				key = i->second.key;
				i->second.dirty = false;
			}
		} else {
			key = peer->insert(ptr, false);
		}

		if (key) {
			size_t marshal_size = type->marshal_size(type, ptr, peer);
			size_t extent_size = sizeof (TapMarshalHeader) + marshal_size;

			auto header = reinterpret_cast<TapMarshalHeader *> (
					buffer->extend(extent_size));
			if (header == NULL)
				return false;

			header->size = Port(extent_size);
			header->type_id = Port(type->id);
			header->key = Port(key);

			if (!type->marshal(type, ptr, peer, header + 1, marshal_size))
				return false;
		}

		return type->traverse(type, ptr, Visit, this);
	}

	TapPeer *const peer;
	TapBuffer *const buffer;
	std::set<const void *> seen;
};

bool tap_marshal(TapPeer *peer, TapBuffer *buffer, const void *ptr)
{
	TapMarshalVisitor visitor(peer, buffer);
	return visitor.visit(ptr);
}

static void *tap_unmarshal_pass1(TapPeer *peer, const void *data,
                                 size_t size) throw ()
{
	void *root_ptr = NULL;

	while (size >= sizeof (TapMarshalHeader)) {
		auto header = reinterpret_cast<const TapMarshalHeader *> (data);
		uint32_t item_size = Port(header->size);
		uint32_t item_type_id = Port(header->type_id);
		TapKey item_key = Port(header->key);

		if (item_size > size) {
			std::fprintf(stderr, "unmarshal: header size out of bounds\n");
			return NULL;
		}
		size_t marshal_size = item_size - sizeof (TapMarshalHeader);
		const void *marshal_data = header + 1;

		auto i = peer->instance.system.types.find(item_type_id);
		if (i == peer->instance.system.types.end()) {
			std::fprintf(stderr, "unmarshal: object type id is unknown\n");
			return NULL;
		}
		const TapType *type = i->second;

		void *ptr;

		auto j = peer->objects.find(item_key);
		if (j != peer->objects.end()) {
			ptr = j->second;
			type->destroy(type, ptr);

			peer->key_states[ptr].dirty = false;
		} else {
			ptr = type->unmarshal_alloc(type, marshal_data, marshal_size);
			if (ptr == NULL) {
				std::fprintf(stderr, "unmarshal: allocation failed\n");
				return NULL;
			}

			peer->key_states[ptr] = TapPeer::KeyState(item_key, false);
			peer->objects[item_key] = ptr;
		}

		if (root_ptr == NULL)
			root_ptr = ptr;

		data = reinterpret_cast<const char *> (data) + item_size;
		size -= item_size;
	}

	if (size > 0) {
		std::fprintf(stderr,
		             "unmarshal: trailing garbage or truncated data\n");
		return NULL;
	}

	return root_ptr;
}

static bool tap_unmarshal_pass2(TapPeer *peer, const void *data,
                                size_t size) throw ()
{
	while (size >= sizeof (TapMarshalHeader)) {
		auto header = reinterpret_cast<const TapMarshalHeader *> (data);
		uint32_t item_size = Port(header->size);
		TapKey item_key = Port(header->key);

		size_t marshal_size = item_size - sizeof (TapMarshalHeader);
		const void *marshal_data = header + 1;
		void *ptr = peer->objects.find(item_key)->second;
		const TapType *type = tap_object_type(ptr);

		if (!type->unmarshal(type, ptr, peer, marshal_data, marshal_size))
			return false;

		data = reinterpret_cast<const char *> (data) + item_size;
		size -= item_size;
	}

	return true;
}

void *tap_unmarshal(TapPeer *peer, const void *data, size_t size)
{
	void *ptr = tap_unmarshal_pass1(peer, data, size);

	if (ptr && !tap_unmarshal_pass2(peer, data, size))
		ptr = NULL;

	return ptr;
}
<|endoftext|>


<commit_before>#include "editparams.h"
#include "ui_editparams.h"

#include <QSpinBox>
#include <QLineEdit>
#include <QDoubleSpinBox>
#include <QMessageBox>
#include <QPushButton>

EditParams::EditParams(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::EditParams),
    catTab(NULL),
	module(NULL)
{
	m_ui->setupUi(this);

	connect(m_ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
}

EditParams::~EditParams()
{
    delete m_ui;
}

void EditParams::setModule(ppk_module* module)
{
	//Set up the tab widget before rendering into it
	if(catTab!=NULL)
		delete catTab;
	catTab = new QTabWidget(this);
	m_ui->mainLayout->insertWidget(1, catTab);

	//Change the module name
	this->module = module;
	m_ui->lbl_modulename->setText(QString::fromUtf8(module->display_name));
	m_ui->lbl_textintro->setText(tr("Edit settings of the \nmodule %0").arg(QString::fromUtf8(module->display_name)));

	//Show the available parameters
	const ppk_proto_param** list=ppk_module_available_parameters(module->id);
	if(list)
	{
		int i=0;
		while(list[i]!=NULL)
		{
			if(!categories.contains(QString::fromUtf8(list[i]->group->display_name)))
				addCategory(catTab, list[i]->group);

			addParam(catTab, categories[QString::fromUtf8(list[i]->group->display_name)], list[i]);

			i++;
		}
	}
}

void EditParams::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
	   m_ui->retranslateUi(this);
	   break;
    default:
	   break;
    }
}

void EditParams::buttonBoxClicked(QAbstractButton* bbox)
{
	QDialogButtonBox::StandardButton button=m_ui->buttonBox->standardButton(bbox);

	if(button==QDialogButtonBox::RestoreDefaults)
	{
		for(int i=0;i<fields.size();i++)
			fields[i]->reset();
	}
	else if(button==QDialogButtonBox::Cancel)
		close();
	else if(button==QDialogButtonBox::Save)
	{
		saveParam();
		accept();
	}
}

/*
  Parameter listing functions
  */

QString EditParams::createNameString(const ppk_proto_param* pparam)
{
	QVariant default_value;

	switch(cvariant_get_type(pparam->default_value))
	{
		case cvariant_string:
			default_value=QString::fromUtf8(cvariant_get_string(pparam->default_value));
			break;

		case cvariant_int:
			default_value=cvariant_get_int(pparam->default_value);
			break;

		case cvariant_float:
			default_value=cvariant_get_float(pparam->default_value);
			break;

		default:
			return tr("Unknown");
	}

	return QString::fromUtf8("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
%1 (Default: '%2')
").arg(QString::fromUtf8(pparam->name)).arg(default_value.toString());
}

#include "form_fields/qtextfield.h"
#include "form_fields/qspinfield.h"
#include "form_fields/qdoublespinfield.h"

QAbstractFormField* EditParams::abstractFormFieldFromParamProto(QWidget* parent, const ppk_proto_param* pparam)
{
	//Get Param's value
	cvariant c_value=ppk_module_get_param("AskForPass_Qt", pparam->name);

	//Create the widget
	switch(pparam->expected_type)
	{
		case cvariant_none:
		{
			break;
		}

		case cvariant_string:
		{
			QString default_value=QString::fromUtf8(cvariant_get_string(pparam->default_value));
			QString value;
			if(cvariant_not_null(c_value))
				value=QString::fromUtf8(cvariant_get_string(c_value));
			else
				value=default_value;

			QTextField* lineEdit = new QTextField(parent);
			lineEdit->setDefaultValue(default_value);
			lineEdit->setValue(value);
			return (QAbstractFormField*)lineEdit;
		}

		case cvariant_int:
		{
			int default_value=cvariant_get_int(pparam->default_value);
			int value;
			if(cvariant_not_null(c_value))
				value=cvariant_get_int(c_value);
			else
				value=default_value;

			QSpinField* spinBox = new QSpinField(parent);
			spinBox->setDefaultValue(default_value);
			spinBox->setValue(value);
			return (QAbstractFormField*)spinBox;
		}

		case cvariant_float:
		{
			double default_value=cvariant_get_float(pparam->default_value);
			double value;
			if(cvariant_not_null(c_value))
				value=cvariant_get_float(c_value);
			else
				value=default_value;

			QDoubleSpinField* doubleSpinBox = new QDoubleSpinField(parent);
			doubleSpinBox->setDefaultValue(default_value);
			doubleSpinBox->setValue(value);
			return (QAbstractFormField*)doubleSpinBox;
		}
	}

	return NULL;
}

void EditParams::addParam(QWidget* parent, QGridLayout* layout, const ppk_proto_param* pparam)
{
	if(!layout)
	{
		qDebug("EditParams::addParam: Tried to add a param to a NULL tab widget !\n");
		return;
	}

	QAbstractFormField* field=abstractFormFieldFromParamProto(parent, pparam);
	if(field)
	{
		field->setFieldName(QString::fromUtf8(pparam->name));
		field->setHelpText(QString::fromUtf8(pparam->help_text));

		int line=layout->rowCount();

		QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
		sizePolicy.setHorizontalStretch(0);
		sizePolicy.setVerticalStretch(0);
		sizePolicy.setHeightForWidth(field->widget()->sizePolicy().hasHeightForWidth());
		field->widget()->setSizePolicy(sizePolicy);
		field->widget()->setToolTip(QString::fromUtf8(pparam->help_text));
		layout->addWidget(field->widget(), line, 1, 1, 1);

		QLabel* nameParamLbl = new QLabel(createNameString(pparam), parent);
		nameParamLbl->setToolTip(QString::fromUtf8(pparam->help_text));
		nameParamLbl->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed);
		layout->addWidget(nameParamLbl, line, 0, 1, 1);

		QPushButton* helpParamBtn = new QPushButton(tr("?"), parent);
		helpParamBtn->setObjectName(QString::fromUtf8("helpParamBtn"));
		QSizePolicy sizePolicy1(QSizePolicy::Maximum, QSizePolicy::Fixed);
		sizePolicy1.setHorizontalStretch(0);
		sizePolicy1.setVerticalStretch(0);
		sizePolicy1.setHeightForWidth(helpParamBtn->sizePolicy().hasHeightForWidth());
		helpParamBtn->setSizePolicy(sizePolicy1);
		helpParamBtn->setMaximumSize(QSize(40, 16777215));
		helpParamBtn->setToolTip(QString::fromUtf8(pparam->help_text));
		layout->addWidget(helpParamBtn, line, 2, 1, 1);

		QDialogButtonBox* rstParamBtn = new QDialogButtonBox(parent);
		rstParamBtn->setObjectName(QString::fromUtf8("rstParamBtn"));
		sizePolicy1.setHeightForWidth(rstParamBtn->sizePolicy().hasHeightForWidth());
		rstParamBtn->setSizePolicy(sizePolicy1);
		rstParamBtn->setStandardButtons(QDialogButtonBox::Reset);
		rstParamBtn->setToolTip(tr("Reset to the default value"));
		layout->addWidget(rstParamBtn, line, 3, 1, 1);

		//Add the field to the field vector
		fields.push_back(field);

		connect(helpParamBtn, SIGNAL(clicked()), field, SLOT(showHelpText()));
		connect(rstParamBtn, SIGNAL(clicked(QAbstractButton*)), field, SLOT(reset()));
	}
}

QWidget* EditParams::addCategory(QTabWidget* catTab, const ppk_settings_group* categ)
{
	if(categ)
	{
		if(!categories.contains(QString::fromUtf8(categ->display_name)))
		{
			QWidget* tab = new QWidget(catTab);
			/*int pos=*/catTab->addTab(tab, QString::fromUtf8(categ->display_name));

			categories[QString::fromUtf8(categ->display_name)]=new QGridLayout(tab);

			return tab;
		}
		else
		{
			qDebug("EditParams::addCategory: Trying to add an already existing category(%s) !\n", categ->display_name);
			return NULL;
		}
	}
	else
	{
		qDebug("EditParams::addCategory: categ==NULL !\n");
		return NULL;
	}
}

void EditParams::saveParam()
{
	for(int i=0;i<fields.size();i++)
	{
		QString name=fields[i]->fieldName();
		QVariant fieldValue=fields[i]->value();
		QVariant fieldDefaultValue=fields[i]->defaultValue();

		cvariant new_value=cvariant_null();
		switch(fields[i]->value().type())
		{
			case QVariant::Double:
			{
				new_value=cvariant_from_float(fieldValue.toDouble());
				break;
			}
			case QVariant::Int:
			{
				new_value=cvariant_from_int(fieldValue.toInt());
				break;
			}
			case QVariant::String:
			{
				new_value=cvariant_from_string_copy(fieldValue.toString().toUtf8().data(), fieldValue.toString().size()+1);
				break;
			}
			default:
				continue;
		}

		//Compare the current value to the currently stored
		cvariant cur_value=ppk_module_get_param(module->id, qPrintable(name));

		//If there is an already existing key, replace it. or if we changed the default value
		if(cvariant_not_null(cur_value) || fieldValue!=fieldDefaultValue)
			ppk_module_save_param(module->id, qPrintable(name), new_value);
	}
}
<commit_msg>util qt: woooops, I had left an hardcoded module name<commit_after>#include "editparams.h"
#include "ui_editparams.h"

#include <QSpinBox>
#include <QLineEdit>
#include <QDoubleSpinBox>
#include <QMessageBox>
#include <QPushButton>

EditParams::EditParams(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::EditParams),
    catTab(NULL),
	module(NULL)
{
	m_ui->setupUi(this);

	connect(m_ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
}

EditParams::~EditParams()
{
    delete m_ui;
}

void EditParams::setModule(ppk_module* module)
{
	//Set up the tab widget before rendering into it
	if(catTab!=NULL)
		delete catTab;
	catTab = new QTabWidget(this);
	m_ui->mainLayout->insertWidget(1, catTab);

	//Change the module name
	this->module = module;
	m_ui->lbl_modulename->setText(QString::fromUtf8(module->display_name));
	m_ui->lbl_textintro->setText(tr("Edit settings of the \nmodule %0").arg(QString::fromUtf8(module->display_name)));

	//Show the available parameters
	const ppk_proto_param** list=ppk_module_available_parameters(module->id);
	if(list)
	{
		int i=0;
		while(list[i]!=NULL)
		{
			if(!categories.contains(QString::fromUtf8(list[i]->group->display_name)))
				addCategory(catTab, list[i]->group);

			addParam(catTab, categories[QString::fromUtf8(list[i]->group->display_name)], list[i]);

			i++;
		}
	}
}

void EditParams::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
	   m_ui->retranslateUi(this);
	   break;
    default:
	   break;
    }
}

void EditParams::buttonBoxClicked(QAbstractButton* bbox)
{
	QDialogButtonBox::StandardButton button=m_ui->buttonBox->standardButton(bbox);

	if(button==QDialogButtonBox::RestoreDefaults)
	{
		for(int i=0;i<fields.size();i++)
			fields[i]->reset();
	}
	else if(button==QDialogButtonBox::Cancel)
		close();
	else if(button==QDialogButtonBox::Save)
	{
		saveParam();
		accept();
	}
}

/*
  Parameter listing functions
  */

QString EditParams::createNameString(const ppk_proto_param* pparam)
{
	QVariant default_value;

	switch(cvariant_get_type(pparam->default_value))
	{
		case cvariant_string:
			default_value=QString::fromUtf8(cvariant_get_string(pparam->default_value));
			break;

		case cvariant_int:
			default_value=cvariant_get_int(pparam->default_value);
			break;

		case cvariant_float:
			default_value=cvariant_get_float(pparam->default_value);
			break;

		default:
			return tr("Unknown");
	}

	return QString::fromUtf8("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
%1 (Default: '%2')
").arg(QString::fromUtf8(pparam->name)).arg(default_value.toString());
}

#include "form_fields/qtextfield.h"
#include "form_fields/qspinfield.h"
#include "form_fields/qdoublespinfield.h"

QAbstractFormField* EditParams::abstractFormFieldFromParamProto(QWidget* parent, const ppk_proto_param* pparam)
{
	//Get Param's value
	cvariant c_value=ppk_module_get_param(module->id, pparam->name);

	//Create the widget
	switch(pparam->expected_type)
	{
		case cvariant_none:
		{
			break;
		}

		case cvariant_string:
		{
			QString default_value=QString::fromUtf8(cvariant_get_string(pparam->default_value));
			QString value;
			if(cvariant_not_null(c_value))
				value=QString::fromUtf8(cvariant_get_string(c_value));
			else
				value=default_value;

			QTextField* lineEdit = new QTextField(parent);
			lineEdit->setDefaultValue(default_value);
			lineEdit->setValue(value);
			return (QAbstractFormField*)lineEdit;
		}

		case cvariant_int:
		{
			int default_value=cvariant_get_int(pparam->default_value);
			int value;
			if(cvariant_not_null(c_value))
				value=cvariant_get_int(c_value);
			else
				value=default_value;

			QSpinField* spinBox = new QSpinField(parent);
			spinBox->setDefaultValue(default_value);
			spinBox->setValue(value);
			return (QAbstractFormField*)spinBox;
		}

		case cvariant_float:
		{
			double default_value=cvariant_get_float(pparam->default_value);
			double value;
			if(cvariant_not_null(c_value))
				value=cvariant_get_float(c_value);
			else
				value=default_value;

			QDoubleSpinField* doubleSpinBox = new QDoubleSpinField(parent);
			doubleSpinBox->setDefaultValue(default_value);
			doubleSpinBox->setValue(value);
			return (QAbstractFormField*)doubleSpinBox;
		}
	}

	return NULL;
}

void EditParams::addParam(QWidget* parent, QGridLayout* layout, const ppk_proto_param* pparam)
{
	if(!layout)
	{
		qDebug("EditParams::addParam: Tried to add a param to a NULL tab widget !\n");
		return;
	}

	QAbstractFormField* field=abstractFormFieldFromParamProto(parent, pparam);
	if(field)
	{
		field->setFieldName(QString::fromUtf8(pparam->name));
		field->setHelpText(QString::fromUtf8(pparam->help_text));

		int line=layout->rowCount();

		QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
		sizePolicy.setHorizontalStretch(0);
		sizePolicy.setVerticalStretch(0);
		sizePolicy.setHeightForWidth(field->widget()->sizePolicy().hasHeightForWidth());
		field->widget()->setSizePolicy(sizePolicy);
		field->widget()->setToolTip(QString::fromUtf8(pparam->help_text));
		layout->addWidget(field->widget(), line, 1, 1, 1);

		QLabel* nameParamLbl = new QLabel(createNameString(pparam), parent);
		nameParamLbl->setToolTip(QString::fromUtf8(pparam->help_text));
		nameParamLbl->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed);
		layout->addWidget(nameParamLbl, line, 0, 1, 1);

		QPushButton* helpParamBtn = new QPushButton(tr("?"), parent);
		helpParamBtn->setObjectName(QString::fromUtf8("helpParamBtn"));
		QSizePolicy sizePolicy1(QSizePolicy::Maximum, QSizePolicy::Fixed);
		sizePolicy1.setHorizontalStretch(0);
		sizePolicy1.setVerticalStretch(0);
		sizePolicy1.setHeightForWidth(helpParamBtn->sizePolicy().hasHeightForWidth());
		helpParamBtn->setSizePolicy(sizePolicy1);
		helpParamBtn->setMaximumSize(QSize(40, 16777215));
		helpParamBtn->setToolTip(QString::fromUtf8(pparam->help_text));
		layout->addWidget(helpParamBtn, line, 2, 1, 1);

		QDialogButtonBox* rstParamBtn = new QDialogButtonBox(parent);
		rstParamBtn->setObjectName(QString::fromUtf8("rstParamBtn"));
		sizePolicy1.setHeightForWidth(rstParamBtn->sizePolicy().hasHeightForWidth());
		rstParamBtn->setSizePolicy(sizePolicy1);
		rstParamBtn->setStandardButtons(QDialogButtonBox::Reset);
		rstParamBtn->setToolTip(tr("Reset to the default value"));
		layout->addWidget(rstParamBtn, line, 3, 1, 1);

		//Add the field to the field vector
		fields.push_back(field);

		connect(helpParamBtn, SIGNAL(clicked()), field, SLOT(showHelpText()));
		connect(rstParamBtn, SIGNAL(clicked(QAbstractButton*)), field, SLOT(reset()));
	}
}

QWidget* EditParams::addCategory(QTabWidget* catTab, const ppk_settings_group* categ)
{
	if(categ)
	{
		if(!categories.contains(QString::fromUtf8(categ->display_name)))
		{
			QWidget* tab = new QWidget(catTab);
			/*int pos=*/catTab->addTab(tab, QString::fromUtf8(categ->display_name));

			categories[QString::fromUtf8(categ->display_name)]=new QGridLayout(tab);

			return tab;
		}
		else
		{
			qDebug("EditParams::addCategory: Trying to add an already existing category(%s) !\n", categ->display_name);
			return NULL;
		}
	}
	else
	{
		qDebug("EditParams::addCategory: categ==NULL !\n");
		return NULL;
	}
}

void EditParams::saveParam()
{
	for(int i=0;i<fields.size();i++)
	{
		QString name=fields[i]->fieldName();
		QVariant fieldValue=fields[i]->value();
		QVariant fieldDefaultValue=fields[i]->defaultValue();

		cvariant new_value=cvariant_null();
		switch(fields[i]->value().type())
		{
			case QVariant::Double:
			{
				new_value=cvariant_from_float(fieldValue.toDouble());
				break;
			}
			case QVariant::Int:
			{
				new_value=cvariant_from_int(fieldValue.toInt());
				break;
			}
			case QVariant::String:
			{
				new_value=cvariant_from_string_copy(fieldValue.toString().toUtf8().data(), fieldValue.toString().size()+1);
				break;
			}
			default:
				continue;
		}

		//Compare the current value to the currently stored
		cvariant cur_value=ppk_module_get_param(module->id, qPrintable(name));

		//If there is an already existing key, replace it. or if we changed the default value
		if(cvariant_not_null(cur_value) || fieldValue!=fieldDefaultValue)
			ppk_module_save_param(module->id, qPrintable(name), new_value);
	}
}
<|endoftext|>


<commit_before><commit_msg>Lines authored by mhorowitz<commit_after><|endoftext|>


<commit_before>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <fstream>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/DOM/Node.h>
#include <Poco/DOM/NamedNodeMap.h>
#include <Poco/DOM/DOMWriter.h>
#include <Poco/SAX/InputSource.h>
#pragma warning(push, 3)
	#include <Poco/FileStream.h>
	#include <Poco/File.h>
#pragma warning(pop)
#include "ColladaMassager.hpp"
#include "../../internal/Exception.hpp"

namespace AssimpWorker {

	ColladaMassager::ColladaMassager(const Poco::URI& uri) :
		idToNameMap(),
		parentIDToExternalURL(),
		uri(uri),
		xmlDocument(),
		idCounter(0),
		alreadyMassagedMyFile(false)
	{
		needToPurge = uri.getFragment() != "";
	}

	ColladaMassager::~ColladaMassager(){
		return;
	}

	void ColladaMassager::massage() {
		if (alreadyMassagedMyFile){
			return;
		}
		try
		{
			readXML();
			handleExternalReferences();
			purgeAllNodes();
			writePurgedXML();
			alreadyMassagedMyFile = true;
		}
		catch (const std::exception& e) {
			std::cout << "Exception while trying to purge names from Collada file: Error #" << e.what() << std::endl;
		}
	}

	void ColladaMassager::readXML(){
		std::ifstream amlStream(uri.getPath());
		Poco::XML::InputSource amlFileSource(amlStream);
		Poco::XML::DOMParser parser;
		parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
		xmlDocument = parser.parse(&amlFileSource);
		amlStream.close();
	}

	void ColladaMassager::handleExternalReferences(){
		Poco::XML::NodeList* nodes = xmlDocument->getElementsByTagName("instance_node");
		for (int i = 0; i < nodes->length(); ++i) {
			Poco::XML::Node* node = nodes->item(i);
			Poco::XML::Node* urlNode = node->attributes()->getNamedItem("url");
			if (urlNode == NULL){
				continue;
			}
			std::string url = urlNode->getNodeValue();
			if (url.at(0) == '#'){
				continue;
			}
			Poco::XML::Node* parent = node->parentNode();
			Poco::XML::Node* parentIdNode = parent->attributes()->getNamedItem("id");
			std::string id;
			if (parentIdNode != NULL){
				id = parentIdNode->getNodeValue();
			} else {
				id = "generated_" + idCounter;
				idCounter++;
				Poco::XML::Node* idNode = xmlDocument->createElement("id");
				idNode->setNodeValue(id);
				parent->attributes()->setNamedItem(idNode);
			}
			parentIDToExternalURL.insert(std::make_pair(id, url));
			node->attributes()->removeNamedItem("url");
		}
	}

	std::map<std::string, std::string>& ColladaMassager::getExternalReferences(){
		return parentIDToExternalURL;
	}

	void ColladaMassager::purgeAllNodes(){
		Poco::XML::NodeList* nodes = xmlDocument->getElementsByTagName("node");
		for (int i = 0; i < nodes->length(); ++i) {
			purgeNode(nodes->item(i));
		}
	}

	void ColladaMassager::forceUnitMeter() {
		Poco::XML::NodeList* unitNodes = xmlDocument->getElementsByTagName("unit");
		for (int i = 0; i < unitNodes->length(); i++) {
			Poco::XML::Node* meterNode = unitNodes->item(i)->attributes()->getNamedItem("meter");
			Poco::XML::Node* nameNode = unitNodes->item(i)->attributes()->getNamedItem("name");

			if (meterNode->getNodeValue() != "1" || nameNode->getNodeValue() != "m") {
				convertTransformsToMeter(meterNode);
			}
			meterNode->setNodeValue("1");
			nameNode->setNodeValue("m");
		}
	}
	void ColladaMassager::purgeNode(Poco::XML::Node* node){
		Poco::XML::Node* nameNode = node->attributes()->getNamedItem("name");
		Poco::XML::Node* idNode = node->attributes()->getNamedItem("id");
		if (nameNode == NULL || idNode == NULL) {
			return;
		}
		std::string name = nameNode->getNodeValue();
		std::string id = idNode->getNodeValue();
		idToNameMap.insert(std::make_pair(id, name));
		node->attributes()->removeNamedItem("name");
	}

	void ColladaMassager::writePurgedXML(){
		//we remove something from the content and write into the same file,
		//leading to some leftover garbage at the end of the file
		//to remove the garbage: remove and recreate the file
		Poco::File file(uri.getPath());
		file.remove();
		file.createFile();
		Poco::FileStream ofs(uri.getPath(), std::ios::in);
		Poco::XML::DOMWriter writer;
		writer.writeNode(ofs, xmlDocument);
		ofs.flush();
		ofs.close();
	}

	std::string ColladaMassager::getNameForId(const std::string& id) {
		auto it = idToNameMap.find(id);
		if (it == idToNameMap.end()){
			throw Exception("Did not find id in map: " + id);
		}
		return it->second;
	}

	void ColladaMassager::restoreOriginalNames(aiNode* node) {
		node->mName = getNameForId(node->mName.C_Str());
		for (int i = 0; i < node->mNumChildren; i++){
			restoreOriginalNames(node->mChildren[i]);
		}
	}

	void ColladaMassager::restoreOriginalNames(ATLAS::Model::Folder& folder) {
		const std::string colladaID = folder.getName();
		std::string colladaName;
		try{
			colladaName = getNameForId(colladaID);
		}catch (Exception ex){
			colladaName = colladaID;
		}
		folder.addAttribute("colladaID", colladaID);
		folder.setName(colladaName);
		for (ATLAS::Model::Folder& child : folder.getChildren()){
			restoreOriginalNames(child);
		}
	}
}
<commit_msg>removed some leftovers from a no longer convert-matrix-function<commit_after>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <fstream>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/DOM/Node.h>
#include <Poco/DOM/NamedNodeMap.h>
#include <Poco/DOM/DOMWriter.h>
#include <Poco/SAX/InputSource.h>
#pragma warning(push, 3)
	#include <Poco/FileStream.h>
	#include <Poco/File.h>
#pragma warning(pop)
#include "ColladaMassager.hpp"
#include "../../internal/Exception.hpp"

namespace AssimpWorker {

	ColladaMassager::ColladaMassager(const Poco::URI& uri) :
		idToNameMap(),
		parentIDToExternalURL(),
		uri(uri),
		xmlDocument(),
		idCounter(0),
		alreadyMassagedMyFile(false)
	{
		needToPurge = uri.getFragment() != "";
	}

	ColladaMassager::~ColladaMassager(){
		return;
	}

	void ColladaMassager::massage() {
		if (alreadyMassagedMyFile){
			return;
		}
		try
		{
			readXML();
			handleExternalReferences();
			purgeAllNodes();
			writePurgedXML();
			alreadyMassagedMyFile = true;
		}
		catch (const std::exception& e) {
			std::cout << "Exception while trying to purge names from Collada file: Error #" << e.what() << std::endl;
		}
	}

	void ColladaMassager::readXML(){
		std::ifstream amlStream(uri.getPath());
		Poco::XML::InputSource amlFileSource(amlStream);
		Poco::XML::DOMParser parser;
		parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
		xmlDocument = parser.parse(&amlFileSource);
		amlStream.close();
	}

	void ColladaMassager::handleExternalReferences(){
		Poco::XML::NodeList* nodes = xmlDocument->getElementsByTagName("instance_node");
		for (int i = 0; i < nodes->length(); ++i) {
			Poco::XML::Node* node = nodes->item(i);
			Poco::XML::Node* urlNode = node->attributes()->getNamedItem("url");
			if (urlNode == NULL){
				continue;
			}
			std::string url = urlNode->getNodeValue();
			if (url.at(0) == '#'){
				continue;
			}
			Poco::XML::Node* parent = node->parentNode();
			Poco::XML::Node* parentIdNode = parent->attributes()->getNamedItem("id");
			std::string id;
			if (parentIdNode != NULL){
				id = parentIdNode->getNodeValue();
			} else {
				id = "generated_" + idCounter;
				idCounter++;
				Poco::XML::Node* idNode = xmlDocument->createElement("id");
				idNode->setNodeValue(id);
				parent->attributes()->setNamedItem(idNode);
			}
			parentIDToExternalURL.insert(std::make_pair(id, url));
			node->attributes()->removeNamedItem("url");
		}
	}

	std::map<std::string, std::string>& ColladaMassager::getExternalReferences(){
		return parentIDToExternalURL;
	}

	void ColladaMassager::purgeAllNodes(){
		Poco::XML::NodeList* nodes = xmlDocument->getElementsByTagName("node");
		for (int i = 0; i < nodes->length(); ++i) {
			purgeNode(nodes->item(i));
		}
	}

	void ColladaMassager::forceUnitMeter() {
		Poco::XML::NodeList* unitNodes = xmlDocument->getElementsByTagName("unit");
		for (int i = 0; i < unitNodes->length(); i++) {
			Poco::XML::Node* meterNode = unitNodes->item(i)->attributes()->getNamedItem("meter");
			Poco::XML::Node* nameNode = unitNodes->item(i)->attributes()->getNamedItem("name");

			meterNode->setNodeValue("1");
			nameNode->setNodeValue("m");
		}
	}
	void ColladaMassager::purgeNode(Poco::XML::Node* node){
		Poco::XML::Node* nameNode = node->attributes()->getNamedItem("name");
		Poco::XML::Node* idNode = node->attributes()->getNamedItem("id");
		if (nameNode == NULL || idNode == NULL) {
			return;
		}
		std::string name = nameNode->getNodeValue();
		std::string id = idNode->getNodeValue();
		idToNameMap.insert(std::make_pair(id, name));
		node->attributes()->removeNamedItem("name");
	}

	void ColladaMassager::writePurgedXML(){
		//we remove something from the content and write into the same file,
		//leading to some leftover garbage at the end of the file
		//to remove the garbage: remove and recreate the file
		Poco::File file(uri.getPath());
		file.remove();
		file.createFile();
		Poco::FileStream ofs(uri.getPath(), std::ios::in);
		Poco::XML::DOMWriter writer;
		writer.writeNode(ofs, xmlDocument);
		ofs.flush();
		ofs.close();
	}

	std::string ColladaMassager::getNameForId(const std::string& id) {
		auto it = idToNameMap.find(id);
		if (it == idToNameMap.end()){
			throw Exception("Did not find id in map: " + id);
		}
		return it->second;
	}

	void ColladaMassager::restoreOriginalNames(aiNode* node) {
		node->mName = getNameForId(node->mName.C_Str());
		for (int i = 0; i < node->mNumChildren; i++){
			restoreOriginalNames(node->mChildren[i]);
		}
	}

	void ColladaMassager::restoreOriginalNames(ATLAS::Model::Folder& folder) {
		const std::string colladaID = folder.getName();
		std::string colladaName;
		try{
			colladaName = getNameForId(colladaID);
		}catch (Exception ex){
			colladaName = colladaID;
		}
		folder.addAttribute("colladaID", colladaID);
		folder.setName(colladaName);
		for (ATLAS::Model::Folder& child : folder.getChildren()){
			restoreOriginalNames(child);
		}
	}
}
<|endoftext|>


<commit_before>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#pragma once

#include "Poco/URI.h"
#include <Poco/DOM/AutoPtr.h>
#include <Poco/DOM/Document.h>
#include <map>
#include <assimp/scene.h>
#include <atlas/model/Folder.hpp>

namespace AssimpWorker {

	class ColladaMassager
	{
	public:
		ColladaMassager(const Poco::URI& colladaPath);

		~ColladaMassager();

		void readXML();
		void massage();
		void restoreOriginalNames(aiNode* node);
		void restoreOriginalNames(ATLAS::Model::Folder& folder);

		std::vector<std::pair<std::string, std::string>>& getExternalReferences();
		const float getCurrentUnit();
		const std::string getUpAxis();
		void forceUnitMeter();

	private:
		std::map<std::string, std::string> idToNameMap;
		Poco::URI uri;
		Poco::XML::AutoPtr<Poco::XML::Document> xmlDocument;
		bool needToPurge;
		std::vector<std::pair<std::string, std::string>> parentIDToExternalURL;
		int idCounter;
		bool alreadyMassagedMyFile;
		void readUpAxis();
		void handleExternalReferences();
		void purgeAllNodes();
		void purgeNode(Poco::XML::Node* node);
		void writePurgedXML();
		std::string getNameForId(const std::string& id);
		float localScaleBeforeMassage;
		std::string upAxis;
	};

} // End namespace AssimpWorker

<commit_msg>Re-order members<commit_after>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#pragma once

#include "Poco/URI.h"
#include <Poco/DOM/AutoPtr.h>
#include <Poco/DOM/Document.h>
#include <map>
#include <assimp/scene.h>
#include <atlas/model/Folder.hpp>

namespace AssimpWorker {

	class ColladaMassager
	{
	public:
		ColladaMassager(const Poco::URI& colladaPath);

		~ColladaMassager();

		void readXML();
		void massage();
		void restoreOriginalNames(aiNode* node);
		void restoreOriginalNames(ATLAS::Model::Folder& folder);

		std::vector<std::pair<std::string, std::string>>& getExternalReferences();
		const float getCurrentUnit();
		const std::string getUpAxis();
		void forceUnitMeter();

	private:
		std::map<std::string, std::string> idToNameMap;
		Poco::URI uri;
		Poco::XML::AutoPtr<Poco::XML::Document> xmlDocument;
		bool needToPurge;
		std::vector<std::pair<std::string, std::string>> parentIDToExternalURL;
		int idCounter;
		bool alreadyMassagedMyFile;
		float localScaleBeforeMassage;
		std::string upAxis;

		void readUpAxis();
		void handleExternalReferences();
		void purgeAllNodes();
		void purgeNode(Poco::XML::Node* node);
		void writePurgedXML();
		std::string getNameForId(const std::string& id);
	};

} // End namespace AssimpWorker

<|endoftext|>


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

/*
 * This is mostly a compilation test to ensure that RBM is accepting
 * enough input types
 */

#include <numeric>
#include <vector>
#include <list>
#include <deque>

#include "catch.hpp"

#include "cpp_utils/data.hpp"

#include "dll/rbm.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

namespace {

using rbm_float = dll::rbm_desc<
        28 * 28, 100,
        dll::weight_type<float>,
        dll::batch_size<25>>::layer_t;

} // end of anonymous namespace

// fast_rbm<float> <- std::vector<float>
TEST_CASE("rbm/types/1", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<float>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::list<float>
TEST_CASE("rbm/types/2", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<float>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    // mnist reader does not support std::list (with reason)
    std::vector<std::list<float>> training_images;
    training_images.reserve(dataset.training_images.size());
    for(auto& image : dataset.training_images){
        training_images.emplace_back(image.begin(), image.end());
    }

    REQUIRE(rbm.train(training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(training_images, training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::deque<float>
TEST_CASE("rbm/types/3", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::deque<float>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::vector<double>
TEST_CASE("rbm/types/4", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<double>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::list<double>
TEST_CASE("rbm/types/5", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<double>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    // mnist reader does not support std::list (with reason)
    std::vector<std::list<double>> training_images;
    training_images.reserve(dataset.training_images.size());
    for(auto& image : dataset.training_images){
        training_images.emplace_back(image.begin(), image.end());
    }

    REQUIRE(rbm.train(training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(training_images, training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::deque<double>
TEST_CASE("rbm/types/6", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::deque<double>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::dyn_matrix<float, 1>
TEST_CASE("rbm/types/7", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::fast_dyn_matrix<float, 1>
TEST_CASE("rbm/types/8", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::dyn_matrix<double, 1>
TEST_CASE("rbm/types/9", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<double, 1>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::fast_dyn_matrix<double, 1>
TEST_CASE("rbm/types/10", "[types]") {
    rbm_float rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 28 * 28>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}
<commit_msg>Test more RBM types<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*
 * This is mostly a compilation test to ensure that RBM is accepting
 * enough input types
 */

#include <numeric>
#include <vector>
#include <list>
#include <deque>

#include "catch.hpp"
#include "template_test.hpp"

#include "cpp_utils/data.hpp"

#include "dll/rbm.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

namespace {

using rbm_float = dll::rbm_desc<
        28 * 28, 100,
        dll::weight_type<float>,
        dll::batch_size<25>>::layer_t;

using rbm_double = dll::rbm_desc<
        28 * 28, 100,
        dll::weight_type<double>,
        dll::batch_size<25>>::layer_t;

} // end of anonymous namespace

// fast_rbm<float> <- std::vector<float>
TEMPLATE_TEST_CASE_2("rbm/types/1", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<float>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::list<float>
TEMPLATE_TEST_CASE_2("rbm/types/2", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<float>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    // mnist reader does not support std::list (with reason)
    std::vector<std::list<float>> training_images;
    training_images.reserve(dataset.training_images.size());
    for(auto& image : dataset.training_images){
        training_images.emplace_back(image.begin(), image.end());
    }

    REQUIRE(rbm.train(training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(training_images, training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::deque<float>
TEMPLATE_TEST_CASE_2("rbm/types/3", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::deque<float>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::vector<double>
TEMPLATE_TEST_CASE_2("rbm/types/4", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<double>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::list<double>
TEMPLATE_TEST_CASE_2("rbm/types/5", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::vector<double>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    // mnist reader does not support std::list (with reason)
    std::vector<std::list<double>> training_images;
    training_images.reserve(dataset.training_images.size());
    for(auto& image : dataset.training_images){
        training_images.emplace_back(image.begin(), image.end());
    }

    REQUIRE(rbm.train(training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(training_images, training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- std::deque<double>
TEMPLATE_TEST_CASE_2("rbm/types/6", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, std::deque<double>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::dyn_matrix<float, 1>
TEMPLATE_TEST_CASE_2("rbm/types/7", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::fast_dyn_matrix<float, 1>
TEMPLATE_TEST_CASE_2("rbm/types/8", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::dyn_matrix<double, 1>
TEMPLATE_TEST_CASE_2("rbm/types/9", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<double, 1>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}

// fast_rbm<float> <- etl::fast_dyn_matrix<double, 1>
TEMPLATE_TEST_CASE_2("rbm/types/10", "[types]", RBM, rbm_float, rbm_double) {
    RBM rbm;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 28 * 28>>(100);
    mnist::binarize_dataset(dataset);

    auto& sample = dataset.training_images[1];

    REQUIRE(rbm.train(dataset.training_images, 20) < 0.1);
    REQUIRE(rbm.reconstruction_error(sample) < 0.1);
    REQUIRE(rbm.train_denoising(dataset.training_images, dataset.training_images, 20) < 1.0);

    auto a = rbm.activate_hidden(sample);
    auto b = rbm.features(sample);

    REQUIRE(rbm.free_energy(sample) < 0.0);
    REQUIRE(rbm.energy(sample, a) > 0.0);
    REQUIRE(rbm.energy(sample, b) > 0.0);
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2016 Volker Krause <vkrause@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This program 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 Library General Public
    License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "repository.h"
#include "definition.h"

#include <QDebug>
#include <QDirIterator>
#include <QFileInfo>
#include <QStandardPaths>

using namespace SyntaxHighlighting;

namespace SyntaxHighlighting {
class RepositoryPrivate
{
public:
    void load(Repository *repo);
    void loadFolder(Repository *repo, const QString &path);
    void addDefinition(const Definition &def);

    QHash<QString, Definition> m_defs;
};
}

Repository::Repository() :
    d(new RepositoryPrivate)
{
    d->load(this);
}

Repository::~Repository()
{
}

Definition Repository::definitionForName(const QString& defName) const
{
    auto def = d->m_defs.value(defName);
    if (def.isValid())
        def.load();
    return def;
}

Definition Repository::definitionForFileName(const QString& fileName) const
{
    QFileInfo fi(fileName);
    const auto ext = fi.suffix();

    for (auto it = d->m_defs.constBegin(); it != d->m_defs.constEnd(); ++it) {
        auto def = it.value();
        // FIXME: this is way too simple, there are other patterns too, see KateWildcardMatcher
        if (def.extensions().contains(QLatin1String("*.") + ext)) {
            def.load();
            return def; // TODO order results by priority
        }
    }

    return Definition();
}

QVector<Definition> Repository::definitions() const
{
    QVector<Definition> defs;
    defs.reserve(d->m_defs.size());
    for (auto it = d->m_defs.constBegin(); it != d->m_defs.constEnd(); ++it)
        defs.push_back(it.value());
    return defs;
}

void RepositoryPrivate::load(Repository *repo)
{
    foreach (const auto &dir, QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation)) {
        loadFolder(repo, dir + QStringLiteral("/KateSyntax"));
    }
    loadFolder(repo, QStringLiteral(":/syntaxhighlighting/syntax"));
}

void RepositoryPrivate::loadFolder(Repository *repo, const QString &path)
{
    QDirIterator it(path);
    while (it.hasNext()) {
        Definition def;
        def.setRepository(repo);
        if (def.loadMetaData(it.next()))
            addDefinition(def);
    }
}

void RepositoryPrivate::addDefinition(const Definition &def)
{
    const auto it = m_defs.constFind(def.name());
    if (it == m_defs.constEnd()) {
        m_defs.insert(def.name(), def);
        return;
    }

    if (it.value().version() >= def.version())
        return;
    m_defs.insert(def.name(), def);
}
<commit_msg>Sort definition vector by section/name<commit_after>/*
    Copyright (C) 2016 Volker Krause <vkrause@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This program 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 Library General Public
    License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "repository.h"
#include "definition.h"

#include <QDebug>
#include <QDirIterator>
#include <QFileInfo>
#include <QStandardPaths>

using namespace SyntaxHighlighting;

namespace SyntaxHighlighting {
class RepositoryPrivate
{
public:
    void load(Repository *repo);
    void loadFolder(Repository *repo, const QString &path);
    void addDefinition(const Definition &def);

    QHash<QString, Definition> m_defs;
    QVector<Definition> m_sortedDefs;
};
}

Repository::Repository() :
    d(new RepositoryPrivate)
{
    d->load(this);
}

Repository::~Repository()
{
}

Definition Repository::definitionForName(const QString& defName) const
{
    auto def = d->m_defs.value(defName);
    if (def.isValid())
        def.load();
    return def;
}

Definition Repository::definitionForFileName(const QString& fileName) const
{
    QFileInfo fi(fileName);
    const auto ext = fi.suffix();

    for (auto it = d->m_defs.constBegin(); it != d->m_defs.constEnd(); ++it) {
        auto def = it.value();
        // FIXME: this is way too simple, there are other patterns too, see KateWildcardMatcher
        if (def.extensions().contains(QLatin1String("*.") + ext)) {
            def.load();
            return def; // TODO order results by priority
        }
    }

    return Definition();
}

QVector<Definition> Repository::definitions() const
{
    return d->m_sortedDefs;
}

void RepositoryPrivate::load(Repository *repo)
{
    foreach (const auto &dir, QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation)) {
        loadFolder(repo, dir + QStringLiteral("/KateSyntax"));
    }
    loadFolder(repo, QStringLiteral(":/syntaxhighlighting/syntax"));

    m_sortedDefs.reserve(m_defs.size());
    for (auto it = m_defs.constBegin(); it != m_defs.constEnd(); ++it)
        m_sortedDefs.push_back(it.value());
    std::sort(m_sortedDefs.begin(), m_sortedDefs.end(), [](const Definition &left, const Definition &right) {
        auto comparison = left.translatedSection().compare(right.translatedSection(), Qt::CaseInsensitive);
        if (comparison == 0)
            comparison = left.translatedName().compare(right.translatedName(), Qt::CaseInsensitive);
        return comparison < 0;
    });
}

void RepositoryPrivate::loadFolder(Repository *repo, const QString &path)
{
    QDirIterator it(path);
    while (it.hasNext()) {
        Definition def;
        def.setRepository(repo);
        if (def.loadMetaData(it.next()))
            addDefinition(def);
    }
}

void RepositoryPrivate::addDefinition(const Definition &def)
{
    const auto it = m_defs.constFind(def.name());
    if (it == m_defs.constEnd()) {
        m_defs.insert(def.name(), def);
        return;
    }

    if (it.value().version() >= def.version())
        return;
    m_defs.insert(def.name(), def);
}
<|endoftext|>


<commit_before>/*
 *            Copyright 2009-2012 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      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.
 *
 */

#include "votca/ctp/gaussian.h"
#include "votca/ctp/segment.h"
#include <stdio.h>
#include <iomanip>
#include <boost/filesystem.hpp>
#include <sys/stat.h>

using namespace std;

namespace votca { namespace ctp {

Gaussian::Gaussian( tools::Property *opt ) {

    string key = "package";

    string _name = opt->get(key+".name").as<string> ();

    if ( _name != "gaussian" ) {
        cerr << "Tried to use " << _name << " package. ";
        throw std::runtime_error( "Package is not supported.");
    }

    _executable =       opt->get(key + ".executable").as<string> ();
    _functional =       opt->get(key + ".functional").as<string> ();
    _basis_set =        opt->get(key + ".basisset").as<string> ();
    _charge =           opt->get(key + ".charge").as<int> ();
    _spin =             opt->get(key + ".spin").as<int> ();
    _options =          opt->get(key + ".options").as<string> ();
    _memory =           opt->get(key + ".memory").as<string> ();
    _threads =          opt->get(key + ".threads").as<int> ();
    _checkpointfile =   opt->get(key + ".checkpoint").as<string> ();
    _scratch =          opt->get(key + ".scratch").as<string> ();

};

Gaussian::~Gaussian() {
}

/**
 * Prepares the com file from a vector of segments
 */
bool Gaussian::WriteInputFile( Segment *seg ) {

    vector< Atom* > ::iterator ait;

    int qmatoms = 0;

    vector< Atom* > _atoms;
    _atoms  = seg-> Atoms();

    ofstream _com_file;

    string _com_file_name_full = _run_dir + "/" + _com_file_name;

    _com_file.open ( _com_file_name_full.c_str() );
    // header
    if ( _checkpointfile.size() != 0 ) {
        _com_file << "%chk = " << _checkpointfile << endl;
    }

    if ( _memory.size() != 0 ) {
        _com_file << "%mem = " << _memory << endl ;
    }

    if ( _threads != 0 ) {
         _com_file << "%nprocshared = "  << _threads << endl;
    }

    if ( _functional.size() != 0 and _basis_set.size() != 0 ) {
        _com_file <<  "# " <<  _functional << "/" <<  _basis_set;
    }

    if ( _options.size() != 0 ) {
        _com_file <<  "  " << _options << endl ;
    }

    _com_file << endl << seg->getName() << endl << endl;
    _com_file << setw(2) << _charge << setw(2) << _spin << endl;

    for (ait = _atoms.begin(); ait < _atoms.end(); ++ait) {

        if ((*ait)->HasQMPart() == false) { continue; }

        vec     pos = (*ait)->getQMPos();
        string  name = (*ait)->getElement();

        //fprintf(out, "%2s %4.7f %4.7f %4.7f \n"
        _com_file << setw(3) << name.c_str()
                  << setw(12) << setprecision(5) << pos.getX()*10
                  << setw(12) << setprecision(5) << pos.getY()*10
                  << setw(12) << setprecision(5) << pos.getZ()*10
                  << endl;
    }

    _com_file << endl;
    _com_file.close();
}

bool Gaussian::WriteShellScript() {
    ofstream _shell_file;

    string _shell_file_name_full = _run_dir + "/" + _shell_file_name;

    _shell_file.open ( _shell_file_name_full.c_str() );

    _shell_file << "#!/bin/tcsh" << endl ;
    _shell_file << "mkdir -p " << _scratch << endl;
    _shell_file << "setenv GAUSS_SCRDIR " << _scratch << endl;
    _shell_file << "cd " << _run_dir << endl;
    _shell_file << _executable << " " << _com_file_name << endl;
    _shell_file.close();
}

/**
 * Runs the Gaussian job
 */
bool Gaussian::Run()
{
    //boost::filesystem::path _current_path = boost::filesystem::current_path();

    //boost::filesystem::path p( filename );
    //boost::filesystem::path dir = p.parent_path();
    //boost::filesystem::path file = p.filename();

    //chdir( (dir.string()).c_str() );
    //mkdir ( "temp", S_IRWXU|S_IRGRP|S_IXGRP ) ;

    //cout << endl << "... ... Running " << _executable << " package." << endl ;
    //execlp( _executable.c_str(), _executable.c_str(), (file.string()).c_str(), NULL );
    //cout << filename << endl ;

    //system( _executable.c_str(), _executable.c_str(), filename.c_str(), NULL );

    //execlp( _executable.c_str(), _executable.c_str(), filename.c_str(), NULL );

    printf ("... ... Checking if processor is available ... ");
    if (system(NULL)) puts ("Ok"); else exit (EXIT_FAILURE);

    string _command  = _executable + " " + _com_file_name.c_str();
    printf ( _command.c_str() );
    int i = system ( _command.c_str() );
    printf ("The value returned was: %d.\n",i);

    //rmdir ( "temp" );

    //chdir( (_current_path.string()).c_str() );
}

}}
<commit_msg>change of folders<commit_after>/*
 *            Copyright 2009-2012 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      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.
 *
 */

#include "votca/ctp/gaussian.h"
#include "votca/ctp/segment.h"
#include <stdio.h>
#include <iomanip>
#include <boost/filesystem.hpp>
#include <sys/stat.h>

using namespace std;

namespace votca { namespace ctp {

Gaussian::Gaussian( tools::Property *opt ) {

    string key = "package";

    string _name = opt->get(key+".name").as<string> ();

    if ( _name != "gaussian" ) {
        cerr << "Tried to use " << _name << " package. ";
        throw std::runtime_error( "Package is not supported.");
    }

    _executable =       opt->get(key + ".executable").as<string> ();
    _functional =       opt->get(key + ".functional").as<string> ();
    _basis_set =        opt->get(key + ".basisset").as<string> ();
    _charge =           opt->get(key + ".charge").as<int> ();
    _spin =             opt->get(key + ".spin").as<int> ();
    _options =          opt->get(key + ".options").as<string> ();
    _memory =           opt->get(key + ".memory").as<string> ();
    _threads =          opt->get(key + ".threads").as<int> ();
    _checkpointfile =   opt->get(key + ".checkpoint").as<string> ();
    _scratch =          opt->get(key + ".scratch").as<string> ();

};

Gaussian::~Gaussian() {
}

/**
 * Prepares the com file from a vector of segments
 */
bool Gaussian::WriteInputFile( Segment *seg ) {

    vector< Atom* > ::iterator ait;

    int qmatoms = 0;

    vector< Atom* > _atoms;
    _atoms  = seg-> Atoms();

    ofstream _com_file;

    string _com_file_name_full = _run_dir + "/" + _com_file_name;

    _com_file.open ( _com_file_name_full.c_str() );
    // header
    if ( _checkpointfile.size() != 0 ) {
        _com_file << "%chk = " << _checkpointfile << endl;
    }

    if ( _memory.size() != 0 ) {
        _com_file << "%mem = " << _memory << endl ;
    }

    if ( _threads != 0 ) {
         _com_file << "%nprocshared = "  << _threads << endl;
    }

    if ( _functional.size() != 0 and _basis_set.size() != 0 ) {
        _com_file <<  "# " <<  _functional << "/" <<  _basis_set;
    }

    if ( _options.size() != 0 ) {
        _com_file <<  "  " << _options << endl ;
    }

    _com_file << endl << seg->getName() << endl << endl;
    _com_file << setw(2) << _charge << setw(2) << _spin << endl;

    for (ait = _atoms.begin(); ait < _atoms.end(); ++ait) {

        if ((*ait)->HasQMPart() == false) { continue; }

        vec     pos = (*ait)->getQMPos();
        string  name = (*ait)->getElement();

        //fprintf(out, "%2s %4.7f %4.7f %4.7f \n"
        _com_file << setw(3) << name.c_str()
                  << setw(12) << setprecision(5) << pos.getX()*10
                  << setw(12) << setprecision(5) << pos.getY()*10
                  << setw(12) << setprecision(5) << pos.getZ()*10
                  << endl;
    }

    _com_file << endl;
    _com_file.close();
}

bool Gaussian::WriteShellScript() {
    ofstream _shell_file;

    string _shell_file_name_full = _run_dir + "/" + _shell_file_name;

    _shell_file.open ( _shell_file_name_full.c_str() );

    _shell_file << "#!/bin/tcsh" << endl ;
    _shell_file << "mkdir -p " << _scratch << endl;
    _shell_file << "setenv GAUSS_SCRDIR " << _scratch << endl;
    _shell_file << _executable << " " << _com_file_name << endl;
    _shell_file.close();
}

/**
 * Runs the Gaussian job
 */
bool Gaussian::Run()
{
    //boost::filesystem::path _current_path = boost::filesystem::current_path();

    //boost::filesystem::path p( filename );
    //boost::filesystem::path dir = p.parent_path();
    //boost::filesystem::path file = p.filename();

    //chdir( (dir.string()).c_str() );
    //mkdir ( "temp", S_IRWXU|S_IRGRP|S_IXGRP ) ;

    //cout << endl << "... ... Running " << _executable << " package." << endl ;
    //execlp( _executable.c_str(), _executable.c_str(), (file.string()).c_str(), NULL );
    //cout << filename << endl ;

    //system( _executable.c_str(), _executable.c_str(), filename.c_str(), NULL );

    //execlp( _executable.c_str(), _executable.c_str(), filename.c_str(), NULL );

    printf ("... ... Checking if processor is available ... ");
    if (system(NULL)) puts ("Ok"); else exit (EXIT_FAILURE);

    string _command  = "cd " + _run_dir + "; "
                             + _executable + " "
                             + _com_file_name.c_str();
    printf ( _command.c_str() );
    int i = system ( _command.c_str() );
    printf ("The value returned was: %d.\n",i);

    //rmdir ( "temp" );

    //chdir( (_current_path.string()).c_str() );
}

}}
<|endoftext|>