<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "ElemAttribute.hpp"

#include <sax/AttributeList.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>

#include <DOMSupport/DOMServices.hpp>

#include "AVT.hpp"
#include "Constants.hpp"
#include "StylesheetConstructionContext.hpp"
#include "StylesheetExecutionContext.hpp"

ElemAttribute::ElemAttribute(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber) :
	ElemTemplateElement(constructionContext,
						stylesheetTree,
						lineNumber,
						columnNumber,
						Constants::ELEMNAME_ATTRIBUTE),
	m_pNameAVT(0),
	m_pNamespaceAVT(0)
{
	const unsigned int	nAttrs = atts.getLength();

	for(unsigned int i = 0; i < nAttrs; i++)
	{
		const XalanDOMChar*	const	aname = atts.getName(i);

		if(equals(aname, Constants::ATTRNAME_NAME))
		{
			m_pNameAVT = new AVT(aname, atts.getType(i), atts.getValue(i),
				*this, constructionContext);
		}
		else if(equals(aname,Constants::ATTRNAME_NAMESPACE))
		{
			m_pNamespaceAVT = new AVT(aname, atts.getType(i), atts.getValue(i),
				*this, constructionContext);
		}
		else if(!(isAttrOK(aname, atts, i, constructionContext) ||
			processSpaceAttr(aname, atts, i)))
		{
			constructionContext.error(Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING + " has an illegal attribute: " + aname);
		}
	}

	if(0 == m_pNameAVT)
	{
#if defined(XALAN_CANNOT_DELETE_CONST)
		delete (AVT*)m_pNamespaceAVT;
#else
		delete m_pNamespaceAVT;
#endif

		constructionContext.error(Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING + " must have a name attribute.");
	}

}

ElemAttribute::~ElemAttribute()
{
#if defined(XALAN_CANNOT_DELETE_CONST)
	delete (AVT*)m_pNameAVT;

	delete (AVT*)m_pNamespaceAVT;
#else
	delete m_pNameAVT;

	delete m_pNamespaceAVT;
#endif
}

const XalanDOMString&
ElemAttribute::getElementName() const
{
	return Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING;
}

void
ElemAttribute::execute(StylesheetExecutionContext&		executionContext) const
{
	assert(m_pNameAVT != 0);

	ElemTemplateElement::execute(executionContext);

	StylesheetExecutionContext::GetAndReleaseCachedString	attrNameGuard(executionContext);

	XalanDOMString&		attrName = attrNameGuard.get();

	XalanNode* sourceNode = executionContext.getCurrentNode();

	m_pNameAVT->evaluate(attrName, sourceNode, *this, executionContext);

	if(!isEmpty(attrName))
	{
		// save original attribute name
		StylesheetExecutionContext::GetAndReleaseCachedString	origAttrNameGuard(executionContext);

		XalanDOMString&		origAttrName = origAttrNameGuard.get();

		assign(origAttrName, attrName);

		const unsigned int		origAttrNameLength = length(origAttrName);

		unsigned int			indexOfNSSep = 0;

		StylesheetExecutionContext::GetAndReleaseCachedString	attrNameSpaceGuard(executionContext);

		XalanDOMString&		attrNameSpace = attrNameSpaceGuard.get();

		if(0 != m_pNamespaceAVT)
		{
			m_pNamespaceAVT->evaluate(attrNameSpace, sourceNode, *this, executionContext);

			if(isEmpty(attrNameSpace))
			{
				indexOfNSSep = origAttrNameLength;
			}
			else
			{
				indexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);

				// See if the namespace already exists.  If it does, we'll get the
				// prefix that was used when it was declared.
				const XalanDOMString*  const	prefix =
					executionContext.getResultPrefixForNamespace(attrNameSpace);

				if(prefix != 0)
				{
					assert(length(*prefix) != 0);

					if(indexOfNSSep < origAttrNameLength)
					{
						reserve(
							attrName,
							length(attrName) - (indexOfNSSep + 1) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);

						assign(attrName, substring(attrName, indexOfNSSep + 1));
					}
					else
					{
						reserve(
							attrName,
							length(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);
					}

					insert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);
					insert(attrName, 0, *prefix);
				}
				else
				{
					StylesheetExecutionContext::GetAndReleaseCachedString	newPrefixGuard(executionContext);

					XalanDOMString&		newPrefix = newPrefixGuard.get();

					// If the prefix on the QName is xmlns, we cannot use it.
					const bool			fPrefixIsXMLNS =
						startsWith(origAttrName, DOMServices::s_XMLNamespaceWithSeparator);

					// If there's a prefix, and it's not xmlns, then use
					// the prefix that's provided.
					if(indexOfNSSep < origAttrNameLength &&
					    fPrefixIsXMLNS == false)
					{
						newPrefix = substring(origAttrName, 0, indexOfNSSep);
					}
					else
					{
						// If there's a prefix, and it's xmlns, then strip it
						// off...
						if (fPrefixIsXMLNS == true)
						{
							assign(attrName, substring(attrName, indexOfNSSep + 1));
						}

						// Get a new, unique namespace prefix...
						executionContext.getUniqueNamespaceValue(newPrefix);

						// Reserve some space in the string.
						reserve(
							attrName,
							length(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(newPrefix) + 1);

						insert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);
						insert(attrName, 0, newPrefix);
					}

					// OK, now we have to generate a namespace declaration...
					StylesheetExecutionContext::GetAndReleaseCachedString	nsDeclGuard(executionContext);

					XalanDOMString&		nsDecl = nsDeclGuard.get();

					reserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(newPrefix) + 1);

					assign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);

					append(nsDecl, newPrefix);

					// Add the namespace declaration...
					executionContext.addResultAttribute(nsDecl, attrNameSpace);
				}
			}
		}
      // Note we are using original attribute name for these tests.
		else if(executionContext.isElementPending() == true &&
				!equals(origAttrName, DOMServices::s_XMLNamespace))
		{
			// Don't try to create a namespace declaration for anything that
			// starts with xml:
			if (startsWith(origAttrName, DOMServices::s_XMLString) == true)
			{
				// This just fakes out the test below.  It would be better if
				// we had a better way of testing this...
				indexOfNSSep = origAttrNameLength;
			}
			else
			{
				// make sure that if a prefix is specified on the attribute name, it is valid
				indexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);

				if(indexOfNSSep < origAttrNameLength)
				{
					StylesheetExecutionContext::GetAndReleaseCachedString	nsprefixGuard(executionContext);

					XalanDOMString&		nsprefix = nsprefixGuard.get();

					nsprefix = substring(origAttrName, 0, indexOfNSSep);

					const XalanDOMString* const		theNamespace =
						getNamespaceForPrefix(nsprefix);

					if (theNamespace != 0)
					{
						assign(attrNameSpace, *theNamespace);
					}

					if (isEmpty(attrNameSpace))
					{
						// Could not resolve prefix
						executionContext.warn("Warning: Could not resolve prefix " + nsprefix, sourceNode, this);
					}
					else
					{
						// Check to see if there's already a namespace declaration in scope...
						const XalanDOMString* const		prefix =
							executionContext.getResultPrefixForNamespace(attrNameSpace);

						if (prefix == 0)
						{
							// We need to generate a namespace declaration...
							StylesheetExecutionContext::GetAndReleaseCachedString	nsDeclGuard(executionContext);

							XalanDOMString&		nsDecl = nsDeclGuard.get();

							reserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(nsprefix) + 1);

							assign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);

							append(nsDecl, nsprefix);

							// Add the namespace declaration...
							executionContext.addResultAttribute(nsDecl, attrNameSpace);
						}
					}
				}
			}
		}
		else
		{
			executionContext.warn("Warning: Trying to add attribute after element child has been added, ignoring...", sourceNode, this);
		}

		// If there was no namespace, or the namespace was resolved, process
		// the result attribute.
		if (indexOfNSSep == origAttrNameLength || !isEmpty(attrNameSpace))
		{
			StylesheetExecutionContext::GetAndReleaseCachedString	theResult(executionContext);

			childrenToString(
					executionContext,
					theResult.get());

			executionContext.addResultAttribute(attrName, theResult.get());
		}
	}
}

bool
ElemAttribute::childTypeAllowed(int		xslToken) const
{
	bool	fResult = false;

	switch(xslToken)
	{
		// char-instructions
	case Constants::ELEMNAME_TEXTLITERALRESULT:
	case Constants::ELEMNAME_APPLY_TEMPLATES:
	case Constants::ELEMNAME_APPLY_IMPORTS:
	case Constants::ELEMNAME_CALLTEMPLATE:
	case Constants::ELEMNAME_FOREACH:
	case Constants::ELEMNAME_VALUEOF:
	case Constants::ELEMNAME_COPY_OF:
	case Constants::ELEMNAME_NUMBER:
	case Constants::ELEMNAME_CHOOSE:
	case Constants::ELEMNAME_IF:
	case Constants::ELEMNAME_TEXT:
	case Constants::ELEMNAME_COPY:
	case Constants::ELEMNAME_VARIABLE:
	case Constants::ELEMNAME_MESSAGE:
		// instructions
		// case Constants.ELEMNAME_PI:
		// case Constants.ELEMNAME_COMMENT:
		// case Constants.ELEMNAME_ELEMENT:
		// case Constants.ELEMNAME_ATTRIBUTE:
		fResult = true;
		break;

	default:
		break;
	}

	return fResult;
}
<commit_msg>Generate a new prefix for xsl:attribute if that prefix is already mapped to a different namespace.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "ElemAttribute.hpp"

#include <sax/AttributeList.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>

#include <DOMSupport/DOMServices.hpp>

#include "AVT.hpp"
#include "Constants.hpp"
#include "StylesheetConstructionContext.hpp"
#include "StylesheetExecutionContext.hpp"

ElemAttribute::ElemAttribute(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber) :
	ElemTemplateElement(constructionContext,
						stylesheetTree,
						lineNumber,
						columnNumber,
						Constants::ELEMNAME_ATTRIBUTE),
	m_pNameAVT(0),
	m_pNamespaceAVT(0)
{
	const unsigned int	nAttrs = atts.getLength();

	for(unsigned int i = 0; i < nAttrs; i++)
	{
		const XalanDOMChar*	const	aname = atts.getName(i);

		if(equals(aname, Constants::ATTRNAME_NAME))
		{
			m_pNameAVT = new AVT(aname, atts.getType(i), atts.getValue(i),
				*this, constructionContext);
		}
		else if(equals(aname,Constants::ATTRNAME_NAMESPACE))
		{
			m_pNamespaceAVT = new AVT(aname, atts.getType(i), atts.getValue(i),
				*this, constructionContext);
		}
		else if(!(isAttrOK(aname, atts, i, constructionContext) ||
			processSpaceAttr(aname, atts, i)))
		{
			constructionContext.error(Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING + " has an illegal attribute: " + aname);
		}
	}

	if(0 == m_pNameAVT)
	{
#if defined(XALAN_CANNOT_DELETE_CONST)
		delete (AVT*)m_pNamespaceAVT;
#else
		delete m_pNamespaceAVT;
#endif

		constructionContext.error(Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING + " must have a name attribute.");
	}

}

ElemAttribute::~ElemAttribute()
{
#if defined(XALAN_CANNOT_DELETE_CONST)
	delete (AVT*)m_pNameAVT;

	delete (AVT*)m_pNamespaceAVT;
#else
	delete m_pNameAVT;

	delete m_pNamespaceAVT;
#endif
}

const XalanDOMString&
ElemAttribute::getElementName() const
{
	return Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING;
}

void
ElemAttribute::execute(StylesheetExecutionContext&		executionContext) const
{
	assert(m_pNameAVT != 0);

	ElemTemplateElement::execute(executionContext);

	StylesheetExecutionContext::GetAndReleaseCachedString	attrNameGuard(executionContext);

	XalanDOMString&		attrName = attrNameGuard.get();

	XalanNode* sourceNode = executionContext.getCurrentNode();

	m_pNameAVT->evaluate(attrName, sourceNode, *this, executionContext);

	if(!isEmpty(attrName))
	{
		// save original attribute name
		StylesheetExecutionContext::GetAndReleaseCachedString	origAttrNameGuard(executionContext);

		XalanDOMString&		origAttrName = origAttrNameGuard.get();

		assign(origAttrName, attrName);

		const unsigned int		origAttrNameLength = length(origAttrName);

		unsigned int			indexOfNSSep = 0;

		StylesheetExecutionContext::GetAndReleaseCachedString	attrNameSpaceGuard(executionContext);

		XalanDOMString&		attrNameSpace = attrNameSpaceGuard.get();

		if(0 != m_pNamespaceAVT)
		{
			m_pNamespaceAVT->evaluate(attrNameSpace, sourceNode, *this, executionContext);

			if(isEmpty(attrNameSpace))
			{
				indexOfNSSep = origAttrNameLength;
			}
			else
			{
				indexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);

				// See if the namespace already exists.  If it does, we'll get the
				// prefix that was used when it was declared.
				const XalanDOMString*  const	prefix =
					executionContext.getResultPrefixForNamespace(attrNameSpace);

				if(prefix != 0)
				{
					assert(length(*prefix) != 0);

					if(indexOfNSSep < origAttrNameLength)
					{
						reserve(
							attrName,
							length(attrName) - (indexOfNSSep + 1) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);

						assign(attrName, substring(attrName, indexOfNSSep + 1));
					}
					else
					{
						reserve(
							attrName,
							length(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);
					}

					insert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);
					insert(attrName, 0, *prefix);
				}
				else
				{
					StylesheetExecutionContext::GetAndReleaseCachedString	newPrefixGuard(executionContext);

					XalanDOMString&		newPrefix = newPrefixGuard.get();

					// If the prefix on the QName is xmlns, we cannot use it.
					const bool			fPrefixIsXMLNS =
						startsWith(origAttrName, DOMServices::s_XMLNamespaceWithSeparator);

					// If there's a prefix, and it's not xmlns, then use
					// the prefix that's provided.
					if(indexOfNSSep < origAttrNameLength &&
					    fPrefixIsXMLNS == false)
					{
						newPrefix = substring(origAttrName, 0, indexOfNSSep);

						// OK, make sure that the prefix provided maps to
						// the same namespace as the one the user requested...
						const XalanDOMString* const	theNamespace =
							executionContext.getResultNamespaceForPrefix(newPrefix);

						if (theNamespace != 0 &&
							equals(*theNamespace, attrNameSpace) == false)
						{
							// It doesn't, so we'll need to manufacture a
							// prefix.
							clear(newPrefix);

							// Strip the user-supplied prefix from the name...
							attrName = substring(origAttrName, indexOfNSSep + 1);
						}
					}

					if (length(newPrefix) == 0)
					{
						// If there's a prefix, and it's xmlns, then strip it
						// off...
						if (fPrefixIsXMLNS == true)
						{
							assign(attrName, substring(attrName, indexOfNSSep + 1));
						}

						// Get a new, unique namespace prefix...
						executionContext.getUniqueNamespaceValue(newPrefix);

						// Reserve some space in the string.
						reserve(
							attrName,
							length(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(newPrefix) + 1);

						insert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);
						insert(attrName, 0, newPrefix);
					}

					// OK, now we have to generate a namespace declaration...
					StylesheetExecutionContext::GetAndReleaseCachedString	nsDeclGuard(executionContext);

					XalanDOMString&		nsDecl = nsDeclGuard.get();

					reserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(newPrefix) + 1);

					assign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);

					append(nsDecl, newPrefix);

					// Add the namespace declaration...
					executionContext.addResultAttribute(nsDecl, attrNameSpace);
				}
			}
		}
      // Note we are using original attribute name for these tests.
		else if(executionContext.isElementPending() == true &&
				!equals(origAttrName, DOMServices::s_XMLNamespace))
		{
			// Don't try to create a namespace declaration for anything that
			// starts with xml:
			if (startsWith(origAttrName, DOMServices::s_XMLString) == true)
			{
				// This just fakes out the test below.  It would be better if
				// we had a better way of testing this...
				indexOfNSSep = origAttrNameLength;
			}
			else
			{
				// make sure that if a prefix is specified on the attribute name, it is valid
				indexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);

				if(indexOfNSSep < origAttrNameLength)
				{
					StylesheetExecutionContext::GetAndReleaseCachedString	nsprefixGuard(executionContext);

					XalanDOMString&		nsprefix = nsprefixGuard.get();

					nsprefix = substring(origAttrName, 0, indexOfNSSep);

					const XalanDOMString* const		theNamespace =
						getNamespaceForPrefix(nsprefix);

					if (theNamespace != 0)
					{
						assign(attrNameSpace, *theNamespace);
					}

					if (isEmpty(attrNameSpace))
					{
						// Could not resolve prefix
						executionContext.warn("Warning: Could not resolve prefix " + nsprefix, sourceNode, this);
					}
					else
					{
						// Check to see if there's already a namespace declaration in scope...
						const XalanDOMString* const		prefix =
							executionContext.getResultPrefixForNamespace(attrNameSpace);

						if (prefix == 0)
						{
							// We need to generate a namespace declaration...
							StylesheetExecutionContext::GetAndReleaseCachedString	nsDeclGuard(executionContext);

							XalanDOMString&		nsDecl = nsDeclGuard.get();

							reserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(nsprefix) + 1);

							assign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);

							append(nsDecl, nsprefix);

							// Add the namespace declaration...
							executionContext.addResultAttribute(nsDecl, attrNameSpace);
						}
					}
				}
			}
		}
		else
		{
			executionContext.warn("Warning: Trying to add attribute after element child has been added, ignoring...", sourceNode, this);
		}

		// If there was no namespace, or the namespace was resolved, process
		// the result attribute.
		if (indexOfNSSep == origAttrNameLength || !isEmpty(attrNameSpace))
		{
			StylesheetExecutionContext::GetAndReleaseCachedString	theResult(executionContext);

			childrenToString(
					executionContext,
					theResult.get());

			executionContext.addResultAttribute(attrName, theResult.get());
		}
	}
}

bool
ElemAttribute::childTypeAllowed(int		xslToken) const
{
	bool	fResult = false;

	switch(xslToken)
	{
		// char-instructions
	case Constants::ELEMNAME_TEXTLITERALRESULT:
	case Constants::ELEMNAME_APPLY_TEMPLATES:
	case Constants::ELEMNAME_APPLY_IMPORTS:
	case Constants::ELEMNAME_CALLTEMPLATE:
	case Constants::ELEMNAME_FOREACH:
	case Constants::ELEMNAME_VALUEOF:
	case Constants::ELEMNAME_COPY_OF:
	case Constants::ELEMNAME_NUMBER:
	case Constants::ELEMNAME_CHOOSE:
	case Constants::ELEMNAME_IF:
	case Constants::ELEMNAME_TEXT:
	case Constants::ELEMNAME_COPY:
	case Constants::ELEMNAME_VARIABLE:
	case Constants::ELEMNAME_MESSAGE:
		// instructions
		// case Constants.ELEMNAME_PI:
		// case Constants.ELEMNAME_COMMENT:
		// case Constants.ELEMNAME_ELEMENT:
		// case Constants.ELEMNAME_ATTRIBUTE:
		fResult = true;
		break;

	default:
		break;
	}

	return fResult;
}
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Julian Ganz
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#ifndef CMOH_ATTRIBUTE_HPP__
#define CMOH_ATTRIBUTE_HPP__

// std includes
#include <type_traits>
#include <utility>

// local includes
#include <cmoh/accessors/attribute/by_method.hpp>
#include <cmoh/accessors/attribute/by_offset.hpp>

namespace cmoh {

/**
 * Attribute declaration utility
 *
 * Using this template, a programmer may declare attributes she wants to make
 * accessible to the cmoh system. Use like:
 *
 *     enum attributes {foo, bar};
 *     using foo_attr = cmoh::attribute<attributes, foo, int>;
 *     using bar_attr = cmoh::attribute<attributes, bar, int>;
 *
 * The attributes themselves are not bound to a C++ type. Attributes do,
 * however, provide the `accessor()` static method for creating appropriate
 * types of accessors for accessing attributes in objects of a specific C++
 * type. These accessors provide a method for getting the attribute's value and
 * may provide a method for setting the attribute:
 *
 *     type get(object_type const& obj) const;
 *     void set(object_type& obj, type&& value);
 *
 * Attributes may be grouped together in namespaces or stucts, each representing
 * an interface.
 */
template <
    typename KeyType, ///< type of the key used to identify the attribute
    KeyType Key, ///< identifier of the attribute
    typename Type ///< type of the attribute value
>
struct attribute {
    typedef KeyType key_type;
    typedef typename std::remove_cv<Type>::type type;
    static constexpr bool is_const = std::is_const<Type>::value;

    static constexpr const key_type key = Key;

    /**
     * Get an accessor for the attribute
     *
     * This methos creates a new accessor using the facilities passed to it.
     * That accessor may be used to access the attribute in a concrete C++
     * struct or class of type `ObjType`.
     */
    template <
        typename ObjType, ///< type of the class or struct with the attribute
        typename Value = type, ///< type of the value in the concrete C++ type
        typename... Args ///< arguments forwarded to the factory
    >
    static
    constexpr
    decltype(accessors::attribute::make_accessor<attribute, ObjType, Value>(
        std::declval<Args>()...
    ))
    accessor(
        Args&&... args
    ) {
        return accessors::attribute::make_accessor<attribute, ObjType, Value>(
            std::forward<Args>(args)...
        );
    }

    /**
     * Move an argument if it is linked to the current attribute
     *
     * This utility evaluates to a rvalue reference if the template parameter
     * passed is the current attribute and to a const lvalue reference
     * otherwise.
     */
    template <
        typename Attribute
    >
    using move_if_same = typename std::conditional<
        std::is_same<Attribute, attribute>::value,
        typename Attribute::type&&,
        typename Attribute::type const&
    >::type;

    /**
     * From a number of values, select the value for the current attribute
     *
     * Using this static method, one can select the value for a specific
     * attribute from a sequence of parameters passed to a function or
     * method.
     *
     * Like `std::forward()`, `select()` is designed to be used within a method
     * or function call, e.g.:
     *
     *     foo(attr1::select<attr1, attr2, attr3>('x', "bar", 42))
     *
     */
    template <
        typename Attribute,
        typename ...Attributes
    >
    static
    constexpr
    typename std::enable_if<
        !std::is_same<Attribute, attribute>::value,
        type&&
    >::type
    select(
        typename Attribute::type const& arg0,
        move_if_same<Attributes>... args
    ) {
        return std::forward<type>(select<Attributes...>(
            std::forward<move_if_same<Attributes>>(args)...
        ));
    }

    // overload for the current attribute
    template <
        typename Attribute,
        typename ...Attributes
    >
    static
    constexpr
    typename std::enable_if<
        std::is_same<Attribute, attribute>::value,
        type&&
    >::type
    select(
        type&& arg0,
        typename Attributes::type const&... args
    ) {
        return std::forward<type>(arg0);
    }
};
}

#endif
<commit_msg>Use enum values for static constants in attributes<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Julian Ganz
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#ifndef CMOH_ATTRIBUTE_HPP__
#define CMOH_ATTRIBUTE_HPP__

// std includes
#include <type_traits>
#include <utility>

// local includes
#include <cmoh/accessors/attribute/by_method.hpp>
#include <cmoh/accessors/attribute/by_offset.hpp>

namespace cmoh {

/**
 * Attribute declaration utility
 *
 * Using this template, a programmer may declare attributes she wants to make
 * accessible to the cmoh system. Use like:
 *
 *     enum attributes {foo, bar};
 *     using foo_attr = cmoh::attribute<attributes, foo, int>;
 *     using bar_attr = cmoh::attribute<attributes, bar, int>;
 *
 * The attributes themselves are not bound to a C++ type. Attributes do,
 * however, provide the `accessor()` static method for creating appropriate
 * types of accessors for accessing attributes in objects of a specific C++
 * type. These accessors provide a method for getting the attribute's value and
 * may provide a method for setting the attribute:
 *
 *     type get(object_type const& obj) const;
 *     void set(object_type& obj, type&& value);
 *
 * Attributes may be grouped together in namespaces or stucts, each representing
 * an interface.
 */
template <
    typename KeyType, ///< type of the key used to identify the attribute
    KeyType Key, ///< identifier of the attribute
    typename Type ///< type of the attribute value
>
struct attribute {
    typedef KeyType key_type;
    typedef typename std::remove_cv<Type>::type type;
    enum : bool {is_const = std::is_const<Type>::value};

    static constexpr const key_type key = Key;

    /**
     * Get an accessor for the attribute
     *
     * This methos creates a new accessor using the facilities passed to it.
     * That accessor may be used to access the attribute in a concrete C++
     * struct or class of type `ObjType`.
     */
    template <
        typename ObjType, ///< type of the class or struct with the attribute
        typename Value = type, ///< type of the value in the concrete C++ type
        typename... Args ///< arguments forwarded to the factory
    >
    static
    constexpr
    decltype(accessors::attribute::make_accessor<attribute, ObjType, Value>(
        std::declval<Args>()...
    ))
    accessor(
        Args&&... args
    ) {
        return accessors::attribute::make_accessor<attribute, ObjType, Value>(
            std::forward<Args>(args)...
        );
    }

    /**
     * Move an argument if it is linked to the current attribute
     *
     * This utility evaluates to a rvalue reference if the template parameter
     * passed is the current attribute and to a const lvalue reference
     * otherwise.
     */
    template <
        typename Attribute
    >
    using move_if_same = typename std::conditional<
        std::is_same<Attribute, attribute>::value,
        typename Attribute::type&&,
        typename Attribute::type const&
    >::type;

    /**
     * From a number of values, select the value for the current attribute
     *
     * Using this static method, one can select the value for a specific
     * attribute from a sequence of parameters passed to a function or
     * method.
     *
     * Like `std::forward()`, `select()` is designed to be used within a method
     * or function call, e.g.:
     *
     *     foo(attr1::select<attr1, attr2, attr3>('x', "bar", 42))
     *
     */
    template <
        typename Attribute,
        typename ...Attributes
    >
    static
    constexpr
    typename std::enable_if<
        !std::is_same<Attribute, attribute>::value,
        type&&
    >::type
    select(
        typename Attribute::type const& arg0,
        move_if_same<Attributes>... args
    ) {
        return std::forward<type>(select<Attributes...>(
            std::forward<move_if_same<Attributes>>(args)...
        ));
    }

    // overload for the current attribute
    template <
        typename Attribute,
        typename ...Attributes
    >
    static
    constexpr
    typename std::enable_if<
        std::is_same<Attribute, attribute>::value,
        type&&
    >::type
    select(
        type&& arg0,
        typename Attributes::type const&... args
    ) {
        return std::forward<type>(arg0);
    }
};
}

#endif
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
 *                     University of Southern California
 *    Jan Issac (jan.issac@gmail.com)
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY 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 OWNER 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.
 *
 */

/**
 * @date 05/25/2014
 * @author Jan Issac (jan.issac@gmail.com)
 * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * Max-Planck-Institute for Intelligent Systems,
 *  University of Southern California (USC)
 */

#ifndef FAST_FILTERING_DISTRIBUTIONS_INTERFACES_SAMPLING_HPP
#define FAST_FILTERING_DISTRIBUTIONS_INTERFACES_SAMPLING_HPP

namespace ff
{

template <typename Vector>
class Sampling
{
public:
    virtual ~Sampling() {}

    virtual Vector Sample() = 0;
};

}

#endif
<commit_msg>Added sampling interface docs<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
 *                     University of Southern California
 *    Jan Issac (jan.issac@gmail.com)
 *
 *
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY 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 OWNER 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.
 *
 */

/**
 * @date 05/25/2014
 * @author Jan Issac (jan.issac@gmail.com)
 * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * Max-Planck-Institute for Intelligent Systems,
 *  University of Southern California (USC)
 */

#ifndef FAST_FILTERING_DISTRIBUTIONS_INTERFACES_SAMPLING_HPP
#define FAST_FILTERING_DISTRIBUTIONS_INTERFACES_SAMPLING_HPP

namespace ff
{

/**
 * \interface Sampling
 * \brief Distribution sampling interface
 *
 * \tparam Vector   Sample variable type
 */
template <typename Vector>
class Sampling
{
public:
    /**
     * @return A random sample of the underlying distribution
     */
    virtual Vector Sample() = 0;

    /**
     * \brief Overridable default destructor
     */
    virtual ~Sampling() { }
};

}

#endif
<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief int type definition and macros
	Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/

#if defined(_MSC_VER) && (MSC_VER <= 1500) && !defined(CYBOZU_DEFINED_INTXX)
	#define CYBOZU_DEFINED_INTXX
	typedef __int64 int64_t;
	typedef unsigned __int64 uint64_t;
	typedef unsigned int uint32_t;
	typedef int int32_t;
	typedef unsigned short uint16_t;
	typedef short int16_t;
	typedef unsigned char uint8_t;
	typedef signed char int8_t;
#else
	#include <stdint.h>
#endif

#ifdef _MSC_VER
	#ifndef CYBOZU_DEFINED_SSIZE_T
		#define CYBOZU_DEFINED_SSIZE_T
		#ifdef _WIN64
			typedef int64_t ssize_t;
		#else
			typedef int32_t ssize_t;
		#endif
	#endif
#else
	#include <unistd.h> // for ssize_t
#endif

#ifndef CYBOZU_ALIGN
	#ifdef _MSC_VER
		#define CYBOZU_ALIGN(x) __declspec(align(x))
	#else
		#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
	#endif
#endif
#ifndef CYBOZU_FORCE_INLINE
	#ifdef _MSC_VER
		#define CYBOZU_FORCE_INLINE __forceinline
	#else
		#define CYBOZU_FORCE_INLINE __attribute__((always_inline))
	#endif
#endif
#ifndef CYBOZU_UNUSED
	#ifdef __GNUC__
		#define CYBOZU_UNUSED __attribute__((unused))
	#else
		#define CYBOZU_UNUSED
	#endif
#endif
#ifndef CYBOZU_ALLOCA
	#ifdef _MSC_VER
		#include <malloc.h>
		#define CYBOZU_ALLOCA(x) _malloca(x)
	#else
		#define CYBOZU_ALLOCA_(x) __builtin_alloca(x)
	#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
	#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
	#if defined(_MSC_VER) && (_MSC_VER < 1900)
		#define CYBOZU_SNPRINTF(x, len, ...) (void)_snprintf_s(x, len, len - 1, __VA_ARGS__)
	#else
		#define CYBOZU_SNPRINTF(x, len, ...) (void)snprintf(x, len, __VA_ARGS__)
	#endif
#endif

#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2

#ifdef __GNUC__
	#define CYBOZU_GNUC_PREREQ(major, minor) ((__GNUC__) * 100 + (__GNUC_MINOR__) >= (major) * 100 + (minor))
#else
	#define CYBOZU_GNUC_PREREQ(major, minor) 0
#endif

#if (__cplusplus >= 201103) || (_MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
	#if defined(_MSC_VER) && (_MSC_VER <= 1600)
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
	#else
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
	#endif
#elif CYBOZU_GNUC_PREREQ(4, 5) || (CYBOZU_GNUC_PREREQ(4, 2) && __GLIBCXX__ >= 20070719) || defined(__INTEL_COMPILER) || (__clang_major__ >= 3)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif

#ifdef CYBOZU_USE_BOOST
	#define CYBOZU_NAMESPACE_STD boost
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#elif (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1) && !defined(__APPLE__)
	#define CYBOZU_NAMESPACE_STD std::tr1
	#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
	#define CYBOZU_NAMESPACE_TR1_END }
#else
	#define CYBOZU_NAMESPACE_STD std
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#endif

#ifndef CYBOZU_OS_BIT
	#if defined(_WIN64) || defined(__x86_64__)
		#define CYBOZU_OS_BIT 64
	#else
		#define CYBOZU_OS_BIT 32
	#endif
#endif

#ifndef CYBOZU_HOST
	#define CYBOZU_HOST_UNKNOWN 0
	#define CYBOZU_HOST_INTEL 1
	#define CYBOZU_HOST_ARM 2
	#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
		#define CYBOZU_HOST CYBOZU_HOST_INTEL
	#elif defined(__arm__)
		#define CYBOZU_HOST CYBOZU_HOST_ARM
	#else
		#define CYBOZU_HOST CYBOZU_HOST_UNKNOWN
	#endif
#endif

#ifndef CYBOZU_ENDIAN
	#define CYBOZU_ENDIAN_UNKNOWN 0
	#define CYBOZU_ENDIAN_LITTLE 1
	#define CYBOZU_ENDIAN_BIG 2
	#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#elif (CYBOZU_HOST == CYBOZU_HOST_ARM) && defined(__ARM_EABI__)
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#else
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
	#endif
#endif

namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<commit_msg>add detection of aarch64 little endian<commit_after>#pragma once
/**
	@file
	@brief int type definition and macros
	Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/

#if defined(_MSC_VER) && (MSC_VER <= 1500) && !defined(CYBOZU_DEFINED_INTXX)
	#define CYBOZU_DEFINED_INTXX
	typedef __int64 int64_t;
	typedef unsigned __int64 uint64_t;
	typedef unsigned int uint32_t;
	typedef int int32_t;
	typedef unsigned short uint16_t;
	typedef short int16_t;
	typedef unsigned char uint8_t;
	typedef signed char int8_t;
#else
	#include <stdint.h>
#endif

#ifdef _MSC_VER
	#ifndef CYBOZU_DEFINED_SSIZE_T
		#define CYBOZU_DEFINED_SSIZE_T
		#ifdef _WIN64
			typedef int64_t ssize_t;
		#else
			typedef int32_t ssize_t;
		#endif
	#endif
#else
	#include <unistd.h> // for ssize_t
#endif

#ifndef CYBOZU_ALIGN
	#ifdef _MSC_VER
		#define CYBOZU_ALIGN(x) __declspec(align(x))
	#else
		#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
	#endif
#endif
#ifndef CYBOZU_FORCE_INLINE
	#ifdef _MSC_VER
		#define CYBOZU_FORCE_INLINE __forceinline
	#else
		#define CYBOZU_FORCE_INLINE __attribute__((always_inline))
	#endif
#endif
#ifndef CYBOZU_UNUSED
	#ifdef __GNUC__
		#define CYBOZU_UNUSED __attribute__((unused))
	#else
		#define CYBOZU_UNUSED
	#endif
#endif
#ifndef CYBOZU_ALLOCA
	#ifdef _MSC_VER
		#include <malloc.h>
		#define CYBOZU_ALLOCA(x) _malloca(x)
	#else
		#define CYBOZU_ALLOCA_(x) __builtin_alloca(x)
	#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
	#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
	#if defined(_MSC_VER) && (_MSC_VER < 1900)
		#define CYBOZU_SNPRINTF(x, len, ...) (void)_snprintf_s(x, len, len - 1, __VA_ARGS__)
	#else
		#define CYBOZU_SNPRINTF(x, len, ...) (void)snprintf(x, len, __VA_ARGS__)
	#endif
#endif

#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2

#ifdef __GNUC__
	#define CYBOZU_GNUC_PREREQ(major, minor) ((__GNUC__) * 100 + (__GNUC_MINOR__) >= (major) * 100 + (minor))
#else
	#define CYBOZU_GNUC_PREREQ(major, minor) 0
#endif

#if (__cplusplus >= 201103) || (_MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
	#if defined(_MSC_VER) && (_MSC_VER <= 1600)
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
	#else
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
	#endif
#elif CYBOZU_GNUC_PREREQ(4, 5) || (CYBOZU_GNUC_PREREQ(4, 2) && __GLIBCXX__ >= 20070719) || defined(__INTEL_COMPILER) || (__clang_major__ >= 3)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif

#ifdef CYBOZU_USE_BOOST
	#define CYBOZU_NAMESPACE_STD boost
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#elif (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1) && !defined(__APPLE__)
	#define CYBOZU_NAMESPACE_STD std::tr1
	#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
	#define CYBOZU_NAMESPACE_TR1_END }
#else
	#define CYBOZU_NAMESPACE_STD std
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#endif

#ifndef CYBOZU_OS_BIT
	#if defined(_WIN64) || defined(__x86_64__) || defined(__AARCH64EL__)
		#define CYBOZU_OS_BIT 64
	#else
		#define CYBOZU_OS_BIT 32
	#endif
#endif

#ifndef CYBOZU_HOST
	#define CYBOZU_HOST_UNKNOWN 0
	#define CYBOZU_HOST_INTEL 1
	#define CYBOZU_HOST_ARM 2
	#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
		#define CYBOZU_HOST CYBOZU_HOST_INTEL
	#elif defined(__arm__) || defined(__AARCH64EL__)
		#define CYBOZU_HOST CYBOZU_HOST_ARM
	#else
		#define CYBOZU_HOST CYBOZU_HOST_UNKNOWN
	#endif
#endif

#ifndef CYBOZU_ENDIAN
	#define CYBOZU_ENDIAN_UNKNOWN 0
	#define CYBOZU_ENDIAN_LITTLE 1
	#define CYBOZU_ENDIAN_BIG 2
	#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#elif (CYBOZU_HOST == CYBOZU_HOST_ARM) && (defined(__ARM_EABI__) || defined(__AARCH64EL__))
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#else
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
	#endif
#endif

namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<|endoftext|>


<commit_before>/* This file is part of Zanshin Todo.

   Copyright 2010 Mario Bensi <mbensi@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "actionlistcombobox.h"
#include "combomodel.h"

#include <QtCore/QEvent>
#include <QtGui/QAbstractItemView>

ActionListComboBox::ActionListComboBox(bool isFiltered, QWidget *parent)
    : QComboBox(parent), m_isReleaseEvent(false)
{
    if (isFiltered) {
        view()->viewport()->installEventFilter(this);
    }
}

bool ActionListComboBox::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonRelease && object==view()->viewport()) {
        m_isReleaseEvent = true;
    }
    return QComboBox::eventFilter(object,event);
}

void ActionListComboBox::showPopup()
{
    QComboBox::showPopup();

    int width = 0;
    const int itemCount = count();
    const int iconWidth = iconSize().width() + 4;
    const QFontMetrics &fm = fontMetrics();

    for (int i = 0; i < itemCount; ++i) {
        const int textWidth = fm.width(itemText(i));
        if (itemIcon(i).isNull()) {
            width = (qMax(width, textWidth));
        } else {
            width = (qMax(width, textWidth + iconWidth));
        }
    }

    QStyleOptionComboBox opt;
    initStyleOption(&opt);
    QSize tmp(width, 0);
    tmp = style()->sizeFromContents(QStyle::CT_ComboBox, &opt, tmp, this);
    width = tmp.width();

    if (width>view()->width()) {
        QSize size = view()->parentWidget()->size();
        size.setWidth(width + 10);
        view()->parentWidget()->resize(size);
    }
}

void ActionListComboBox::hidePopup()
{
    if (m_isReleaseEvent) {
        m_isReleaseEvent = false;
        return;
    }
    QComboBox::hidePopup();
}

void ActionListComboBox::showItem(const QModelIndex &index)
{
    if (!index.isValid()) {
        ComboModel *comboModel = static_cast<ComboModel*>(model());
        setEditText(comboModel->selectedItems().join(", "));
    }
}
<commit_msg>Better positioning strategy for the popup when it overflows on the right of the screen. Also cap the width to half the screen size to avoid ridiculously large popups.<commit_after>/* This file is part of Zanshin Todo.

   Copyright 2010 Mario Bensi <mbensi@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "actionlistcombobox.h"
#include "combomodel.h"

#include <QtCore/QEvent>
#include <QtGui/QAbstractItemView>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>

ActionListComboBox::ActionListComboBox(bool isFiltered, QWidget *parent)
    : QComboBox(parent), m_isReleaseEvent(false)
{
    if (isFiltered) {
        view()->viewport()->installEventFilter(this);
    }
}

bool ActionListComboBox::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonRelease && object==view()->viewport()) {
        m_isReleaseEvent = true;
    }
    return QComboBox::eventFilter(object,event);
}

void ActionListComboBox::showPopup()
{
    QComboBox::showPopup();

    int width = 0;
    const int itemCount = count();
    const int iconWidth = iconSize().width() + 4;
    const QFontMetrics &fm = fontMetrics();

    for (int i = 0; i < itemCount; ++i) {
        const int textWidth = fm.width(itemText(i));
        if (itemIcon(i).isNull()) {
            width = (qMax(width, textWidth));
        } else {
            width = (qMax(width, textWidth + iconWidth));
        }
    }

    QStyleOptionComboBox opt;
    initStyleOption(&opt);
    QSize tmp(width, 0);
    tmp = style()->sizeFromContents(QStyle::CT_ComboBox, &opt, tmp, this);
    width = tmp.width();

    const int screenWidth = QApplication::desktop()->width();
    if ( width>screenWidth/2 ) {
        width = screenWidth/2;
    }

    if (width>view()->width()) {
        QSize size = view()->parentWidget()->size();
        size.setWidth(width + 10);
        view()->parentWidget()->resize(size);
    }

    const int viewRight = view()->parentWidget()->mapToGlobal(view()->parentWidget()->rect().bottomRight()).x();
    const int dx = screenWidth - viewRight;

    if (dx<0) {
        const int x = view()->parentWidget()->geometry().x() + dx;
        const int y = view()->parentWidget()->geometry().y();
        view()->parentWidget()->move( x, y );
    }
}

void ActionListComboBox::hidePopup()
{
    if (m_isReleaseEvent) {
        m_isReleaseEvent = false;
        return;
    }
    QComboBox::hidePopup();
}

void ActionListComboBox::showItem(const QModelIndex &index)
{
    if (!index.isValid()) {
        ComboModel *comboModel = static_cast<ComboModel*>(model());
        setEditText(comboModel->selectedItems().join(", "));
    }
}
<|endoftext|>


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

/*!
 * \file dbn_detail.hpp
 * \brief DBN implementation details
 */

#pragma once

namespace dll {

namespace dbn_detail {

// extract_weight

/*!
 * \brief Extrac the weight type from the set of the layers of the DBN
 */
template <size_t I, typename DBN, typename Enable = void>
struct extract_weight_t;

/*!
 * \copydoc extract_weight_t
 */
template <size_t I, typename DBN>
struct extract_weight_t<I, DBN, std::enable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    /*!
     * \brief The extracted weight type
     */
    using type = typename extract_weight_t<I + 1, DBN>::type;
};

/*!
 * \copydoc extract_weight_t
 */
template <size_t I, typename DBN>
struct extract_weight_t<I, DBN, cpp::disable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    /*!
     * \brief The extracted weight type
     */
    using type = typename DBN::template layer_type<I>::weight;
};

// test that a layer has the correct weight type

template <size_t I, typename DBN, typename T, typename Enable = void>
struct weight_type_same;

template <size_t I, typename DBN, typename T>
struct weight_type_same<I, DBN, T, std::enable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    /*!
     * \brief Boolean flag indicating if the weight type of the two
     * layers is the same
     */
    static constexpr bool value = true;
};

template <size_t I, typename DBN, typename T>
struct weight_type_same<I, DBN, T, cpp::disable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    using type = typename DBN::template layer_type<I>::weight;

    /*!
     * \brief Boolean flag indicating if the weight type of the two
     * layers is the same
     */
    static constexpr bool value = std::is_same_v<T, type>;
};

// validate the weight type of the layers

template <size_t I, typename DBN, typename T, typename Enable = void>
struct validate_weight_type_impl;

template <size_t I, typename DBN, typename T>
struct validate_weight_type_impl< I, DBN, T, std::enable_if_t<(I == DBN::layers_t::size - 1)> > {
    static constexpr bool value = weight_type_same<I, DBN, T>::value;
};

template <size_t I, typename DBN, typename T>
struct validate_weight_type_impl< I, DBN, T, std::enable_if_t<(I < DBN::layers_t::size - 1)> > {
    static constexpr bool value = weight_type_same<I, DBN, T>::value && validate_weight_type_impl<I + 1, DBN, T>::value;
};

template <typename DBN, typename T>
struct validate_weight_type {
    static constexpr bool value = validate_weight_type_impl<0, DBN, T>::value;
};

// Compute the distance between two iterators, only if random_access

template <typename Iterator>
size_t fast_distance(Iterator& first, Iterator& last) {
    if constexpr (std::is_same_v<typename std::iterator_traits<Iterator>::iterator_category, std::random_access_iterator_tag>) {
        return std::distance(first, last);
    } else {
        return 0;
    }
}

template <typename D, size_t N, typename T>
struct for_each_impl;

template <typename D, size_t... I>
struct for_each_impl<D, 1, std::index_sequence<I...>> {
    D& dbn;

    for_each_impl(D& dbn)
            : dbn(dbn) {}

    template <typename Functor>
    void for_each_layer(Functor&& functor) {
        functor(dbn.template layer_get<0>());
    }

    template <typename Functor>
    void for_each_layer_i(Functor&& functor) {
        functor(dbn.template layer_get<0>(), 0);
    }

    template <typename Functor>
    void for_each_layer_pair([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }

    template <typename Functor>
    void for_each_layer_pair_i([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }

    template <typename Functor>
    void for_each_layer_rpair([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }

    template <typename Functor>
    void for_each_layer_rpair_i([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }
};

template <typename D, size_t N, size_t... I>
struct for_each_impl<D, N, std::index_sequence<I...>> {
    D& dbn;

    for_each_impl(D& dbn)
            : dbn(dbn) {}

    template <typename Functor>
    void for_each_layer(Functor&& functor) {
        (functor(dbn.template layer_get<I>()), ...);
    }

    template <typename Functor>
    void for_each_layer_i(Functor&& functor) {
        (functor(I, dbn.template layer_get<I>()), ...);
    }

    template <typename Functor>
    void for_each_layer_pair(Functor&& functor) {
        (functor(dbn.template layer_get<I>(), dbn.template layer_get<I + 1>()), ...);
    }

    template <typename Functor>
    void for_each_layer_pair_i(Functor&& functor) {
        (functor(I, dbn.template layer_get<I>(), dbn.template layer_get<I + 1>()), ...);
    }

    template <typename Functor>
    void for_each_layer_rpair(Functor&& functor) {
        (functor(dbn.template layer_get<D::layers - I - 2>(), dbn.template layer_get<D::layers - I - 1>()), ...);
    }

    template <typename Functor>
    void for_each_layer_rpair_i(Functor&& functor) {
        (functor(D::layers - I - 2, dbn.template layer_get<D::layers - I - 2>(), dbn.template layer_get<D::layers - I - 1>()), ...);
    }
};

} //end of namespace dbn_detail

} //end of namespace dll
<commit_msg>Fix bug in layer iteration<commit_after>//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file dbn_detail.hpp
 * \brief DBN implementation details
 */

#pragma once

namespace dll {

namespace dbn_detail {

// extract_weight

/*!
 * \brief Extrac the weight type from the set of the layers of the DBN
 */
template <size_t I, typename DBN, typename Enable = void>
struct extract_weight_t;

/*!
 * \copydoc extract_weight_t
 */
template <size_t I, typename DBN>
struct extract_weight_t<I, DBN, std::enable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    /*!
     * \brief The extracted weight type
     */
    using type = typename extract_weight_t<I + 1, DBN>::type;
};

/*!
 * \copydoc extract_weight_t
 */
template <size_t I, typename DBN>
struct extract_weight_t<I, DBN, cpp::disable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    /*!
     * \brief The extracted weight type
     */
    using type = typename DBN::template layer_type<I>::weight;
};

// test that a layer has the correct weight type

template <size_t I, typename DBN, typename T, typename Enable = void>
struct weight_type_same;

template <size_t I, typename DBN, typename T>
struct weight_type_same<I, DBN, T, std::enable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    /*!
     * \brief Boolean flag indicating if the weight type of the two
     * layers is the same
     */
    static constexpr bool value = true;
};

template <size_t I, typename DBN, typename T>
struct weight_type_same<I, DBN, T, cpp::disable_if_t<layer_traits<typename DBN::template layer_type<I>>::has_same_type()>> {
    using type = typename DBN::template layer_type<I>::weight;

    /*!
     * \brief Boolean flag indicating if the weight type of the two
     * layers is the same
     */
    static constexpr bool value = std::is_same_v<T, type>;
};

// validate the weight type of the layers

template <size_t I, typename DBN, typename T, typename Enable = void>
struct validate_weight_type_impl;

template <size_t I, typename DBN, typename T>
struct validate_weight_type_impl< I, DBN, T, std::enable_if_t<(I == DBN::layers_t::size - 1)> > {
    static constexpr bool value = weight_type_same<I, DBN, T>::value;
};

template <size_t I, typename DBN, typename T>
struct validate_weight_type_impl< I, DBN, T, std::enable_if_t<(I < DBN::layers_t::size - 1)> > {
    static constexpr bool value = weight_type_same<I, DBN, T>::value && validate_weight_type_impl<I + 1, DBN, T>::value;
};

template <typename DBN, typename T>
struct validate_weight_type {
    static constexpr bool value = validate_weight_type_impl<0, DBN, T>::value;
};

// Compute the distance between two iterators, only if random_access

template <typename Iterator>
size_t fast_distance(Iterator& first, Iterator& last) {
    if constexpr (std::is_same_v<typename std::iterator_traits<Iterator>::iterator_category, std::random_access_iterator_tag>) {
        return std::distance(first, last);
    } else {
        return 0;
    }
}

template <typename D, size_t N, typename T>
struct for_each_impl;

template <typename D, size_t... I>
struct for_each_impl<D, 1, std::index_sequence<I...>> {
    D& dbn;

    for_each_impl(D& dbn)
            : dbn(dbn) {}

    template <typename Functor>
    void for_each_layer(Functor&& functor) {
        functor(dbn.template layer_get<0>());
    }

    template <typename Functor>
    void for_each_layer_i(Functor&& functor) {
        functor(0, dbn.template layer_get<0>());
    }

    template <typename Functor>
    void for_each_layer_pair([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }

    template <typename Functor>
    void for_each_layer_pair_i([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }

    template <typename Functor>
    void for_each_layer_rpair([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }

    template <typename Functor>
    void for_each_layer_rpair_i([[maybe_unused]] Functor&& functor) {
        // Nothing to do here
    }
};

template <typename D, size_t N, size_t... I>
struct for_each_impl<D, N, std::index_sequence<I...>> {
    D& dbn;

    for_each_impl(D& dbn)
            : dbn(dbn) {}

    template <typename Functor>
    void for_each_layer(Functor&& functor) {
        (functor(dbn.template layer_get<I>()), ...);
    }

    template <typename Functor>
    void for_each_layer_i(Functor&& functor) {
        (functor(I, dbn.template layer_get<I>()), ...);
    }

    template <typename Functor>
    void for_each_layer_pair(Functor&& functor) {
        (functor(dbn.template layer_get<I>(), dbn.template layer_get<I + 1>()), ...);
    }

    template <typename Functor>
    void for_each_layer_pair_i(Functor&& functor) {
        (functor(I, dbn.template layer_get<I>(), dbn.template layer_get<I + 1>()), ...);
    }

    template <typename Functor>
    void for_each_layer_rpair(Functor&& functor) {
        (functor(dbn.template layer_get<D::layers - I - 2>(), dbn.template layer_get<D::layers - I - 1>()), ...);
    }

    template <typename Functor>
    void for_each_layer_rpair_i(Functor&& functor) {
        (functor(D::layers - I - 2, dbn.template layer_get<D::layers - I - 2>(), dbn.template layer_get<D::layers - I - 1>()), ...);
    }
};

} //end of namespace dbn_detail

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


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

#ifndef DLL_RBM_COMMON_HPP
#define DLL_RBM_COMMON_HPP

#include "rbm_traits.hpp"

namespace dll {

template<typename RBM>
struct rbm_trainer;

namespace rbm_detail {

template<typename RBM>
static void store(std::ostream& os, const RBM& rbm){
    binary_write_all(os, rbm.w);
    binary_write_all(os, rbm.b);
    binary_write_all(os, rbm.c);
}

template<typename RBM>
static void load(std::istream& is, RBM& rbm){
    binary_load_all(is, rbm.w);
    binary_load_all(is, rbm.b);
    binary_load_all(is, rbm.c);
}

template<typename Samples, typename RBM>
void init_weights(const Samples& training_data, RBM& rbm){
    //Initialize the visible biases to log(pi/(1-pi))
    for(size_t i = 0; i < num_visible(rbm); ++i){
        auto count = std::count_if(training_data.begin(), training_data.end(),
            [i](auto& a){return a[i] == 1; });

        auto pi = static_cast<double>(count) / training_data.size();
        pi += 0.0001;
        rbm.c(i) = log(pi / (1.0 - pi));

        dll_assert(std::isfinite(rbm.c(i)), "NaN verify");
    }
}

template<typename RBM, typename V, typename H, enable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight energy(const RBM& rbm, const V& v, const H& h){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //E(v,h) = -sum(ai*vi) - sum(bj*hj) -sum(vi*hj*wij)

        auto mid_term = 0.0;

        //TODO Simplify that
        for(size_t i = 0; i < num_visible(rbm); ++i){
            for(size_t j = 0; j < num_hidden(rbm); ++j){
                mid_term += rbm.w(i, j) * v(i) * h(j);
            }
        }

        return -etl::dot(rbm.c, v) - etl::dot(rbm.b, h) - mid_term;
    } else {
        return 0.0;
    }
}

template<typename RBM, typename V, typename H, disable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight energy(const RBM& rbm, const V& v, const H& h){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //E(v,h) = -sum(ai*vi) - sum(bj*hj) -sum(vi*hj*wij)

        auto visible_term = 0.0;
        auto hidden_term = 0.0;

        for(size_t i = 0; i < num_visible(rbm); ++i){
            visible_term = rbm.c(i) * v[i];
        }

        for(size_t j = 0; j < num_hidden(rbm); ++j){
            hidden_term = rbm.b(j) * h[j];
        }

        auto mid_term = 0.0;

        //TODO Simplify that
        for(size_t i = 0; i < num_visible(rbm); ++i){
            for(size_t j = 0; j < num_hidden(rbm); ++j){
                mid_term += rbm.w(i, j) * v(i) * h(j);
            }
        }

        return -visible_term - hidden_term - mid_term;
    } else {
        return 0.0;
    }
}

template<typename RBM, typename V, enable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight free_energy(const RBM& rbm, const V& v){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //F(v) = -sum(ai*vi) - sum(log(1 + e^(xj)))
        //xj = input to hidden neuron j

        using namespace etl;

        std::cout << rbm_traits<RBM>::is_dynamic() << std::endl;

        static fast_matrix<typename RBM::weight, 1, RBM::num_hidden> t;

        auto x = rbm.b + mmul(reshape<1, RBM::desc::num_visible>(v), rbm.w, t);

        return -dot(rbm.c, v) - sum(log(1.0 + exp(x)));
    } else {
        return 0.0;
    }
}

template<typename RBM, typename V, disable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight free_energy(const RBM& rbm, const V& v){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //F(v) = -sum(ai*vi) - sum(log(1 + e^(xj)))
        //xj = input to hidden neuron j

        auto visible_term = 0.0;

        for(size_t i = 0; i < num_visible(rbm); ++i){
            visible_term = rbm.c(i) * v[i];
        }

        auto mid_term = 0.0;

        for(size_t j = 0; j < num_hidden(rbm); ++j){
            auto x = rbm.b(j);
            for(size_t i = 0; i < num_visible(rbm); ++i){
                x += v[i] * rbm.w(i,j);
            }

            mid_term += std::log(1.0 + std::exp(x));
        }

        return -visible_term - mid_term;
    } else {
        return 0.0;
    }
}

template<typename Sample, typename RBM>
void reconstruct(const Sample& items, RBM& rbm){
    dll_assert(items.size() == num_visible, "The size of the training sample must match visible units");

    stop_watch<> watch;

    //Set the state of the visible units
    rbm.v1 = items;

    rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1);
    rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s);
    rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s);

    std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl;
}

template<typename RBM>
void display_weights(RBM& rbm){
    for(size_t j = 0; j < num_hidden(rbm); ++j){
        for(size_t i = 0; i < num_visible(rbm); ++i){
            std::cout << rbm.w(i, j) << " ";
        }
        std::cout << std::endl;
    }
}

template<typename RBM>
void display_weights(RBM& rbm, size_t matrix){
    for(size_t j = 0; j < num_hidden(rbm); ++j){
        for(size_t i = 0; i < num_visible(rbm);){
            for(size_t m = 0; m < matrix; ++m){
                std::cout << rbm.w(i++, j) << " ";
            }
            std::cout << std::endl;
        }
    }
}

template<typename RBM>
void display_visible_units(RBM& rbm){
    std::cout << "Visible  Value" << std::endl;

    for(size_t i = 0; i < num_visible(rbm); ++i){
        printf("%-8lu %d\n", i, rbm.v2_s(i));
    }
}

template<typename RBM>
void display_visible_units(RBM& rbm, size_t matrix){
    for(size_t i = 0; i < matrix; ++i){
        for(size_t j = 0; j < matrix; ++j){
            std::cout << rbm.v2_s(i * matrix + j) << " ";
        }
        std::cout << std::endl;
    }
}

template<typename RBM>
void display_hidden_units(RBM& rbm){
    std::cout << "Hidden Value" << std::endl;

    for(size_t j = 0; j < num_hidden(rbm); ++j){
        printf("%-8lu %d\n", j, rbm.h2_s(j));
    }
}

} //end of rbm_detail

} //end of dbn namespace

#endif<commit_msg>Remove unwanted message<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DLL_RBM_COMMON_HPP
#define DLL_RBM_COMMON_HPP

#include "rbm_traits.hpp"

namespace dll {

template<typename RBM>
struct rbm_trainer;

namespace rbm_detail {

template<typename RBM>
static void store(std::ostream& os, const RBM& rbm){
    binary_write_all(os, rbm.w);
    binary_write_all(os, rbm.b);
    binary_write_all(os, rbm.c);
}

template<typename RBM>
static void load(std::istream& is, RBM& rbm){
    binary_load_all(is, rbm.w);
    binary_load_all(is, rbm.b);
    binary_load_all(is, rbm.c);
}

template<typename Samples, typename RBM>
void init_weights(const Samples& training_data, RBM& rbm){
    //Initialize the visible biases to log(pi/(1-pi))
    for(size_t i = 0; i < num_visible(rbm); ++i){
        auto count = std::count_if(training_data.begin(), training_data.end(),
            [i](auto& a){return a[i] == 1; });

        auto pi = static_cast<double>(count) / training_data.size();
        pi += 0.0001;
        rbm.c(i) = log(pi / (1.0 - pi));

        dll_assert(std::isfinite(rbm.c(i)), "NaN verify");
    }
}

template<typename RBM, typename V, typename H, enable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight energy(const RBM& rbm, const V& v, const H& h){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //E(v,h) = -sum(ai*vi) - sum(bj*hj) -sum(vi*hj*wij)

        auto mid_term = 0.0;

        //TODO Simplify that
        for(size_t i = 0; i < num_visible(rbm); ++i){
            for(size_t j = 0; j < num_hidden(rbm); ++j){
                mid_term += rbm.w(i, j) * v(i) * h(j);
            }
        }

        return -etl::dot(rbm.c, v) - etl::dot(rbm.b, h) - mid_term;
    } else {
        return 0.0;
    }
}

template<typename RBM, typename V, typename H, disable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight energy(const RBM& rbm, const V& v, const H& h){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //E(v,h) = -sum(ai*vi) - sum(bj*hj) -sum(vi*hj*wij)

        auto visible_term = 0.0;
        auto hidden_term = 0.0;

        for(size_t i = 0; i < num_visible(rbm); ++i){
            visible_term = rbm.c(i) * v[i];
        }

        for(size_t j = 0; j < num_hidden(rbm); ++j){
            hidden_term = rbm.b(j) * h[j];
        }

        auto mid_term = 0.0;

        //TODO Simplify that
        for(size_t i = 0; i < num_visible(rbm); ++i){
            for(size_t j = 0; j < num_hidden(rbm); ++j){
                mid_term += rbm.w(i, j) * v(i) * h(j);
            }
        }

        return -visible_term - hidden_term - mid_term;
    } else {
        return 0.0;
    }
}

template<typename RBM, typename V, enable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight free_energy(const RBM& rbm, const V& v){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //F(v) = -sum(ai*vi) - sum(log(1 + e^(xj)))
        //xj = input to hidden neuron j

        using namespace etl;

        static fast_matrix<typename RBM::weight, 1, RBM::num_hidden> t;

        auto x = rbm.b + mmul(reshape<1, RBM::desc::num_visible>(v), rbm.w, t);

        return -dot(rbm.c, v) - sum(log(1.0 + exp(x)));
    } else {
        return 0.0;
    }
}

template<typename RBM, typename V, disable_if_u<etl::is_etl_expr<V>::value> = ::detail::dummy>
typename RBM::weight free_energy(const RBM& rbm, const V& v){
    if(RBM::desc::visible_unit == unit_type::BINARY && RBM::desc::hidden_unit == unit_type::BINARY){
        //Definition according to G. Hinton
        //F(v) = -sum(ai*vi) - sum(log(1 + e^(xj)))
        //xj = input to hidden neuron j

        auto visible_term = 0.0;

        for(size_t i = 0; i < num_visible(rbm); ++i){
            visible_term = rbm.c(i) * v[i];
        }

        auto mid_term = 0.0;

        for(size_t j = 0; j < num_hidden(rbm); ++j){
            auto x = rbm.b(j);
            for(size_t i = 0; i < num_visible(rbm); ++i){
                x += v[i] * rbm.w(i,j);
            }

            mid_term += std::log(1.0 + std::exp(x));
        }

        return -visible_term - mid_term;
    } else {
        return 0.0;
    }
}

template<typename Sample, typename RBM>
void reconstruct(const Sample& items, RBM& rbm){
    dll_assert(items.size() == num_visible, "The size of the training sample must match visible units");

    stop_watch<> watch;

    //Set the state of the visible units
    rbm.v1 = items;

    rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1);
    rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s);
    rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s);

    std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl;
}

template<typename RBM>
void display_weights(RBM& rbm){
    for(size_t j = 0; j < num_hidden(rbm); ++j){
        for(size_t i = 0; i < num_visible(rbm); ++i){
            std::cout << rbm.w(i, j) << " ";
        }
        std::cout << std::endl;
    }
}

template<typename RBM>
void display_weights(RBM& rbm, size_t matrix){
    for(size_t j = 0; j < num_hidden(rbm); ++j){
        for(size_t i = 0; i < num_visible(rbm);){
            for(size_t m = 0; m < matrix; ++m){
                std::cout << rbm.w(i++, j) << " ";
            }
            std::cout << std::endl;
        }
    }
}

template<typename RBM>
void display_visible_units(RBM& rbm){
    std::cout << "Visible  Value" << std::endl;

    for(size_t i = 0; i < num_visible(rbm); ++i){
        printf("%-8lu %d\n", i, rbm.v2_s(i));
    }
}

template<typename RBM>
void display_visible_units(RBM& rbm, size_t matrix){
    for(size_t i = 0; i < matrix; ++i){
        for(size_t j = 0; j < matrix; ++j){
            std::cout << rbm.v2_s(i * matrix + j) << " ";
        }
        std::cout << std::endl;
    }
}

template<typename RBM>
void display_hidden_units(RBM& rbm){
    std::cout << "Hidden Value" << std::endl;

    for(size_t j = 0; j < num_hidden(rbm); ++j){
        printf("%-8lu %d\n", j, rbm.h2_s(j));
    }
}

} //end of rbm_detail

} //end of dbn namespace

#endif<|endoftext|>


<commit_before>/*
 *   Copyright (c) 2012 - 2015 Kulykov Oleh <info@resident.name>
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 */

#include "../include/REInt24.h"

#if defined(HAVE_RECORE_CONFIG_H)
#include "recore_config.h"
#endif

#include <string.h>

REInt24::REInt24()
{
	memset(_data, 0, 3);
}

REInt24::REInt24(const REInt32 v)
{
	this->set(v);
}

REInt24::REInt24(const REInt24 & v)
{
	this->set(v);
}

REInt32 REInt24::get() const
{
	if (_data[2] & 0x80)
	{
		return (0xff << 24) | (_data[2] << 16) | (_data[1] << 8) | (_data[0] << 0);
	}
	else
	{
		return (_data[2] << 16) | (_data[1] << 8) | (_data[0] << 0);
	}
}

REInt24 & REInt24::set(const REInt24 & v)
{
	memcpy(_data, v._data, 3);
	return (*this);
}

REInt24 & REInt24::set(const REInt32 v)
{
	memcpy(_data, &v, 3);
	return (*this);
}

REInt24 & REInt24::operator=(const REInt24 & v)
{
	return this->set(v);
}

REInt24 & REInt24::operator=(const REInt32 v)
{
	return this->set(v);
}

REInt24 REInt24::operator+(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r += v2;

	return REInt24(r);
}

REInt24 REInt24::operator-(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r -= v2;

	return REInt24(r);
}

REInt24 REInt24::operator*(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r *= v2;

	return REInt24(r);
}

REInt24 REInt24::operator/(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r /= v2;

	return REInt24(r);
}

REInt24 REInt24::operator+(const REInt32 v) const
{
	REInt32 r = this->get();
	r += v;

	return REInt24(r);
}

REInt24 REInt24::operator-(const REInt32 v) const
{
	REInt32 r = this->get();
	r -= v;

	return REInt24(r);
}

REInt24 REInt24::operator*(const REInt32 v) const
{
	REInt32 r = this->get();
	r *= v;

	return REInt24(r);
}

REInt24 REInt24::operator/(const REInt32 v) const
{
	REInt32 r = this->get();
	r /= v;

	return REInt24(r);
}

REInt24 & REInt24::operator+=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r += v2;

	return this->set(r);
}

REInt24 & REInt24::operator-=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r -= v2;

	return this->set(r);
}

REInt24 & REInt24::operator*=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r *= v2;

	return this->set(r);
}

REInt24 & REInt24::operator/=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r /= v2;

	return this->set(r);
}

REInt24 & REInt24::operator+=(const REInt32 v)
{
	REInt32 r = this->get();
	r += v;

	return this->set(r);
}

REInt24 & REInt24::operator-=(const REInt32 v)
{
	REInt32 r = this->get();
	r -= v;

	return this->set(r);
}

REInt24 & REInt24::operator*=(const REInt32 v)
{
	REInt32 r = this->get();
	r *= v;

	return this->set(r);
}

REInt24 & REInt24::operator/=(const REInt32 v)
{
	REInt32 r = this->get();
	r /= v;

	return this->set(r);
}

REInt24 REInt24::operator>>(const REInt32 v) const
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 >> v;

	return REInt24(r);
}

REInt24 REInt24::operator<<(const REInt32 v) const
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 << v;

	return REInt24(r);
}

REInt24 & REInt24::operator>>=(const REInt32 v)
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 >> v;

	return this->set(r);
}

REInt24 & REInt24::operator<<=(const REInt32 v)
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 << v;

	return this->set(r);
}

REInt24 REInt24::operator-()
{
	const REInt32 v1 = this->get();

	return REInt24(-v1);
}

bool REInt24::operator==(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 == v2);
}

bool REInt24::operator!=(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 != v2);
}

bool REInt24::operator>=(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 >= v2);
}

bool REInt24::operator<=(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 <= v2);
}

bool REInt24::operator>(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 > v2);
}

bool REInt24::operator<(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 < v2);
}

bool REInt24::operator==(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 == v);
}

bool REInt24::operator!=(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 != v);
}

bool REInt24::operator>=(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 >= v);
}

bool REInt24::operator<=(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 <= v);
}

bool REInt24::operator>(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 > v);
}

bool REInt24::operator<(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 < v);
}

<commit_msg>Int24 all operators stored in each constant<commit_after>/*
 *   Copyright (c) 2012 - 2015 Kulykov Oleh <info@resident.name>
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 */

#include "../include/REInt24.h"

#if defined(HAVE_RECORE_CONFIG_H)
#include "recore_config.h"
#endif

#include <string.h>

REInt24::REInt24()
{
	memset(_data, 0, 3);
}

REInt24::REInt24(const REInt32 v)
{
	this->set(v);
}

REInt24::REInt24(const REInt24 & v)
{
	this->set(v);
}

REInt32 REInt24::get() const
{
	if (_data[2] & 0x80)
	{
		return (0xff << 24) | (_data[2] << 16) | (_data[1] << 8) | (_data[0] << 0);
	}
	else
	{
		return (_data[2] << 16) | (_data[1] << 8) | (_data[0] << 0);
	}
}

REInt24 & REInt24::set(const REInt24 & v)
{
	memcpy(_data, v._data, 3);
	return (*this);
}

REInt24 & REInt24::set(const REInt32 v)
{
	memcpy(_data, &v, 3);
	return (*this);
}

REInt24 & REInt24::operator=(const REInt24 & v)
{
	return this->set(v);
}

REInt24 & REInt24::operator=(const REInt32 v)
{
	return this->set(v);
}

REInt24 REInt24::operator+(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r += v2;

	return REInt24(r);
}

REInt24 REInt24::operator-(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r -= v2;

	return REInt24(r);
}

REInt24 REInt24::operator*(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r *= v2;

	return REInt24(r);
}

REInt24 REInt24::operator/(const REInt24 & v) const
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r /= v2;

	return REInt24(r);
}

REInt24 REInt24::operator+(const REInt32 v) const
{
	REInt32 r = this->get();
	r += v;

	return REInt24(r);
}

REInt24 REInt24::operator-(const REInt32 v) const
{
	REInt32 r = this->get();
	r -= v;

	return REInt24(r);
}

REInt24 REInt24::operator*(const REInt32 v) const
{
	REInt32 r = this->get();
	r *= v;

	return REInt24(r);
}

REInt24 REInt24::operator/(const REInt32 v) const
{
	REInt32 r = this->get();
	r /= v;

	return REInt24(r);
}

REInt24 & REInt24::operator+=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r += v2;

	return this->set(r);
}

REInt24 & REInt24::operator-=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r -= v2;

	return this->set(r);
}

REInt24 & REInt24::operator*=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r *= v2;

	return this->set(r);
}

REInt24 & REInt24::operator/=(const REInt24 & v)
{
	REInt32 r = this->get();
	const REInt32 v2 = v.get();
	r /= v2;

	return this->set(r);
}

REInt24 & REInt24::operator+=(const REInt32 v)
{
	REInt32 r = this->get();
	r += v;

	return this->set(r);
}

REInt24 & REInt24::operator-=(const REInt32 v)
{
	REInt32 r = this->get();
	r -= v;

	return this->set(r);
}

REInt24 & REInt24::operator*=(const REInt32 v)
{
	REInt32 r = this->get();
	r *= v;

	return this->set(r);
}

REInt24 & REInt24::operator/=(const REInt32 v)
{
	REInt32 r = this->get();
	r /= v;

	return this->set(r);
}

REInt24 REInt24::operator>>(const REInt32 v) const
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 >> v;

	return REInt24(r);
}

REInt24 REInt24::operator<<(const REInt32 v) const
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 << v;

	return REInt24(r);
}

REInt24 & REInt24::operator>>=(const REInt32 v)
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 >> v;

	return this->set(r);
}

REInt24 & REInt24::operator<<=(const REInt32 v)
{
	const REInt32 v1 = this->get();
	const REInt32 r = v1 << v;

	return this->set(r);
}

REInt24 REInt24::operator-()
{
	REInt32 r = this->get();
	r = -r;

	return REInt24(r);
}

bool REInt24::operator==(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 == v2);
}

bool REInt24::operator!=(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 != v2);
}

bool REInt24::operator>=(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 >= v2);
}

bool REInt24::operator<=(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 <= v2);
}

bool REInt24::operator>(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 > v2);
}

bool REInt24::operator<(const REInt24 & v) const
{
	const REInt32 v1 = this->get();
	const REInt32 v2 = v.get();

	return (v1 < v2);
}

bool REInt24::operator==(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 == v);
}

bool REInt24::operator!=(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 != v);
}

bool REInt24::operator>=(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 >= v);
}

bool REInt24::operator<=(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 <= v);
}

bool REInt24::operator>(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 > v);
}

bool REInt24::operator<(const REInt32 v) const
{
	const REInt32 v1 = this->get();

	return (v1 < v);
}

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: factory.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef FACTORY_HPP
#define FACTORY_HPP

// mapnik
#include <mapnik/utils.hpp>
// stl
#include <stdexcept>
#include <map>

namespace mapnik {
template <typename key_type,
          typename product_type>
class default_factory_error
{
public:
    struct factory_exception : public std::exception
    {
        const char* what() const throw()
        {
            return "uknown object type";
        }
    };
    static product_type* on_unknown_type(const key_type&)
    {
        return 0;
    }
};

template
<
typename product_type,
typename key_type,
typename product_creator=product_type* (*)(),
template <typename,typename> class factory_error_policy=default_factory_error
>
class factory : public singleton<factory <product_type,
                                          key_type,
                                          product_creator,factory_error_policy> >,
                factory_error_policy <key_type,product_type>
{
private:
    typedef std::map<key_type,product_creator> product_map;
    product_map map_;
public:

    bool register_product(const key_type& key,product_creator creator)
    {
        return map_.insert(typename product_map::value_type(key,creator)).second;
    }

    bool unregister_product(const key_type& key)
    {
        return map_.erase(key)==1;
    }

    product_type* create_object(const key_type& key,const std::string& file)
    {
        typename product_map::const_iterator pos=map_.find(key);
        if (pos!=map_.end())
        {
            return (pos->second)(file);
        }
        return on_unknown_type(key);
    }
};
}

#endif //FACTORY_HPP
<commit_msg>+ fixed clang++ issue<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: factory.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef FACTORY_HPP
#define FACTORY_HPP

// mapnik
#include <mapnik/utils.hpp>
// stl
#include <stdexcept>
#include <map>

namespace mapnik {
template <typename key_type,
          typename product_type>
class default_factory_error
{
public:
    struct factory_exception : public std::exception
    {
        const char* what() const throw()
        {
            return "uknown object type";
        }
    };
    static product_type* on_unknown_type(const key_type&)
    {
        return 0;
    }
};

template
<
typename product_type,
typename key_type,
typename product_creator=product_type* (*)(),
template <typename,typename> class factory_error_policy=default_factory_error
>
class factory : public singleton<factory <product_type,
                                          key_type,
                                          product_creator,factory_error_policy> >,
                factory_error_policy <key_type,product_type>
{
private:
    typedef std::map<key_type,product_creator> product_map;
    product_map map_;
public:

    bool register_product(const key_type& key,product_creator creator)
    {
        return map_.insert(typename product_map::value_type(key,creator)).second;
    }

    bool unregister_product(const key_type& key)
    {
        return map_.erase(key)==1;
    }

    product_type* create_object(const key_type& key,const std::string& file)
    {
        typename product_map::const_iterator pos=map_.find(key);
        if (pos!=map_.end())
        {
            return (pos->second)(file);
        }
        return factory_error_policy<key_type,product_type>::on_unknown_type(key);
    }
};
}

#endif //FACTORY_HPP
<|endoftext|>