<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
<commit_msg>Change SEQ timings, SEQ ODT, WC config and DQS polarity<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file workarounds/dp16.H
/// @brief Workarounds for the DP16 logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Steven Glancy <sglancy@usi.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_WORKAROUNDS_DP16_H_
#define _MSS_WORKAROUNDS_DP16_H_

#include <fapi2.H>

namespace mss
{

namespace workarounds
{

namespace dp16
{

///
/// @brief DQS polarity workaround
/// For Monza DDR port 2, one pair of DQS P/N is swapped polarity.  Not in DDR port 6
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed. It is specific to the Monza module, but can be called for all modules as it
/// will enforce its requirements internally
///
fapi2::ReturnCode dqs_polarity( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target );

} // close namespace dp16
} // close namespace workarounds
} // close namespace mss

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: HStorage.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:03:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CONNECTIVITY_HSQLDB_STORAGE_HXX
#define CONNECTIVITY_HSQLDB_STORAGE_HXX

#ifndef _CPPUHELPER_COMPBASE6_HXX_
#include <cppuhelper/compbase6.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif

#define DECLARE_SERVICE_INFO_STATIC()   \
    DECLARE_SERVICE_INFO(); \
    static ::rtl::OUString SAL_CALL getImplementationName_Static(  ) throw (::com::sun::star::uno::RuntimeException);   \
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static(  ) throw(::com::sun::star::uno::RuntimeException);  \
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >    \
        SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&)    \

namespace connectivity
{
    namespace hsqldb
    {
        typedef ::cppu::WeakComponentImplHelper6<   ::com::sun::star::io::XStream
                                        ,   ::com::sun::star::io::XInputStream
                                        ,   ::com::sun::star::io::XOutputStream
                                        ,   ::com::sun::star::io::XSeekable
                                        ,   ::com::sun::star::lang::XInitialization
                                        ,   ::com::sun::star::lang::XServiceInfo>   OStorage_Base;
        class OStorage : public ::comphelper::OBaseMutex
                        ,public OStorage_Base
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >            m_xServiceFactory;
            ::com::sun::star::uno::Reference< ::com::sun::star::document::XDocumentSubStorageSupplier>  m_xDS;

            ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage>    m_xStorge;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream >       m_xStream;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >  m_xIn;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > m_xOut;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable >     m_xSeek;

            OStorage();                         // never implemented
            OStorage(const OStorage&);          // never implemented
            int operator= (const OStorage&);    // never implemented

            OStorage(
                const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);
        protected:
            /** this function is called upon disposing the component
            */
            virtual void SAL_CALL disposing();
        public:
            // ::com::sun::star::lang::XServiceInfo
            DECLARE_SERVICE_INFO_STATIC();

            // XInitialization
            virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

            // XStream
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream(  ) throw (::com::sun::star::uno::RuntimeException);

            // XInputStream
            virtual ::sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nMaxBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL skipBytes( ::sal_Int32 nBytesToSkip ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int32 SAL_CALL available(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL closeInput(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

            // XOutputStream
            virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL flush(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL closeOutput(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

            // XSeekable
            virtual void SAL_CALL seek( ::sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int64 SAL_CALL getPosition(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int64 SAL_CALL getLength(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        };
    }
// .......................................................................
} // connectivity
// .......................................................................
#endif // CONNECTIVITY_HSQLDB_STORAGE_HXX

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

#include <cppuhelper/compbase6.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include "connectivity/CommonTools.hxx"
#include <comphelper/broadcasthelper.hxx>

#define DECLARE_SERVICE_INFO_STATIC()   \
    DECLARE_SERVICE_INFO(); \
    static ::rtl::OUString SAL_CALL getImplementationName_Static(  ) throw (::com::sun::star::uno::RuntimeException);   \
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static(  ) throw(::com::sun::star::uno::RuntimeException);  \
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >    \
        SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&)    \

namespace connectivity
{
    namespace hsqldb
    {
        typedef ::cppu::WeakComponentImplHelper6<   ::com::sun::star::io::XStream
                                        ,   ::com::sun::star::io::XInputStream
                                        ,   ::com::sun::star::io::XOutputStream
                                        ,   ::com::sun::star::io::XSeekable
                                        ,   ::com::sun::star::lang::XInitialization
                                        ,   ::com::sun::star::lang::XServiceInfo>   OStorage_Base;
        class OStorage : public ::comphelper::OBaseMutex
                        ,public OStorage_Base
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >            m_xServiceFactory;
            ::com::sun::star::uno::Reference< ::com::sun::star::document::XDocumentSubStorageSupplier>  m_xDS;

            ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage>    m_xStorge;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream >       m_xStream;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >  m_xIn;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > m_xOut;
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable >     m_xSeek;

            OStorage();                         // never implemented
            OStorage(const OStorage&);          // never implemented
            int operator= (const OStorage&);    // never implemented

            OStorage(
                const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);
        protected:
            /** this function is called upon disposing the component
            */
            virtual void SAL_CALL disposing();
        public:
            // ::com::sun::star::lang::XServiceInfo
            DECLARE_SERVICE_INFO_STATIC();

            // XInitialization
            virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

            // XStream
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream(  ) throw (::com::sun::star::uno::RuntimeException);

            // XInputStream
            virtual ::sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nMaxBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL skipBytes( ::sal_Int32 nBytesToSkip ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int32 SAL_CALL available(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL closeInput(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

            // XOutputStream
            virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL flush(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL closeOutput(  ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

            // XSeekable
            virtual void SAL_CALL seek( ::sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int64 SAL_CALL getPosition(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
            virtual ::sal_Int64 SAL_CALL getLength(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        };
    }
// .......................................................................
} // connectivity
// .......................................................................
#endif // CONNECTIVITY_HSQLDB_STORAGE_HXX

<|endoftext|>


<commit_before>/*
** Copyright 2014-2015 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/

#include <orange/FunctionStmt.h>
#include <orange/generator.h>
#include <orange/IfStmts.h>

FunctionStmt::FunctionStmt(std::string name, ParamList parameters, SymTable* symtab) : Block(symtab) {
	m_name = name;
	m_parameters = parameters;
}

FunctionStmt::FunctionStmt(std::string name, AnyType* type, ParamList parameters, SymTable* symtab) : Block(symtab) {
	m_name = name;
	m_type = type;
	m_parameters = parameters;
}

std::string FunctionStmt::getClonesFullSignature(ArgList args) {
	std::string ret_name = m_name + "_";
	for (auto arg : args) {
		AnyType* type = arg->getType();

		if (type->isIntegerTy()) {
			int width = type->getIntegerBitWidth();
			switch (width) {
				case 1:
					ret_name += "T";
					break;
				case 8:
					ret_name += (type->isSigned() ? "b" : "B");
					break;
				case 16:
					ret_name += (type->isSigned() ? "s" : "S");
					break;
				case 32:
					ret_name += (type->isSigned() ? "i" : "I");
					break;
				case 64:
					ret_name += (type->isSigned() ? "l" : "L");
					break;
				default:
					ret_name += "?";
					break;
			}
		} else if (type->isFloatTy()) {
			ret_name += "f";
		} else if (type->isDoubleTy()) {
			ret_name += "F";
		}

		for (int i = 0; i < type->getPointerLength(); i++) {
			ret_name += "p";
		}
	}

	return ret_name;
}

FunctionStmt* FunctionStmt::createGenericClone(ArgList args) {
	// If we're not a generic, we shouldn't be trying to make a clone.
	if (isGeneric() == false) {
		return nullptr;
	}

	if (args.size() != m_parameters.size()) {
		throw CompilerMessage(*this, "Mismatched number of arguments while calling " + m_name + "!");
	}

	std::string cloned_name = getClonesFullSignature(args);

	// Does a clone with that name already exist? If so, return that clone.
	for (auto clone : m_clones) {
		if (clone->m_name == cloned_name) {
			return clone;
		}
	}

	// Create paramlist from args
	ParamList cloned_params;

	for (int i = 0; i < args.size(); i++) {
		VarExpr* curParam = m_parameters[i];
		VarExpr* newParam = new VarExpr(curParam->name(), args[i]->getType());
		cloned_params.push_back(newParam);
	}

	// Otherwise, create that clone here, add it to the list, and return it.
	FunctionStmt* clone;

	if (m_type) {
		clone = new FunctionStmt(cloned_name, m_type, cloned_params, symtab()->clone());
	} else {
		clone = new FunctionStmt(cloned_name, cloned_params, symtab()->clone());
	}

	for (auto stmt : m_statements) {
		auto clonedStmt = stmt->clone();
		clone->addStatement(clonedStmt);

		// if the stmt is a block, set its parent to the clone's symtab IFF
		// their symtab's parent is the one for our current function statement
		if (Block* block = dynamic_cast<Block*>(clonedStmt)) {
			if (block->symtab()->parent()->ID() == symtab()->ID()) {
				block->symtab()->setParent(clone->symtab());
			}
		}

		if (IfStmts* ifStmts = dynamic_cast<IfStmts*>(clonedStmt)) {
			for (auto block : ifStmts->blocks()) {
				block->symtab()->setParent(clone->symtab());
			}
		}
	}

	m_clones.push_back(clone);
	return clone;
}

AnyType* FunctionStmt::getType() {
	AnyType *ret = m_type;

	// This should not happen; getType() should only be called against clones.
	if (isGeneric()) {
		throw CompilerMessage(*this, "Cannot get type of a generic function.");
	}

	GE::runner()->pushBlock(this);

	// Here, invalid type means that it needs to be redefined for this function.
	bool invalidType = (m_type == nullptr || m_type->isVoidTy() || m_type->isIDTy());
	if (invalidType && m_looking == false) {
		// Set m_looking to true so we don't recursively try to get the type of FunctionStmt
		m_looking = true;

		// If we don't have an explicit type set, we have to determine it from our body and nested bodies.
		AnyType* foundRet = searchForReturn();
		ret = foundRet ? foundRet : ASTNode::getType();
		m_type = ret;
		m_looking = false;
	}

	GE::runner()->popBlock();

	return ret;
}

Value* FunctionStmt::Codegen() {
	// Check to see if we're a generic function.
	// If we are, we only should generate our clones since we're incomplete.
	if (isGeneric()) {
		for (auto clone : m_clones) {
			clone->Codegen();
		}

		return nullptr;
	}

	// Push ourselves onto the stack first.
	GE::runner()->pushBlock(this);

	// Create a list of types that serve as our function's arguments
	std::vector<Type*> Args;

	for (auto param : m_parameters) {
		Args.push_back(param->getLLVMType());
	}

	// Create the function itself, and set it as our AST value.
	FunctionType* funcType = FunctionType::get(getLLVMType(), Args, m_isVarArg);
	Function* generatedFunc = Function::Create(funcType, m_linkageType, m_name, GE::module());
	m_value = generatedFunc;

	// TODO: Set argument names, if any (generatedFunc->arg_begin, setName on iterator)
	auto arg_it = generatedFunc->arg_begin();
	for (unsigned int i = 0; i < Args.size(); i++, arg_it++) {
		arg_it->setName(m_parameters[i]->name());
	}

	// Before generating, we need to get the current insert block so we don't lose our place.
	auto oldInsertBlock = GE::builder()->GetInsertBlock();

	// Create basic block and set our insertion point to it.
	BasicBlock *funcBody = BasicBlock::Create(GE::runner()->context(), "entry", generatedFunc);
	BasicBlock *funcEnd = BasicBlock::Create(GE::runner()->context(), "exit", generatedFunc);
	GE::builder()->SetInsertPoint(funcBody);

	// Set up values for children statements to use.
	Value *retVal = nullptr;
	if (getType()->isVoidTy() == false) {
		retVal = GE::builder()->CreateAlloca(getLLVMType(), nullptr, "return");
		m_retVal = retVal;
	}

	m_blockEnd = funcEnd;

	// Create our paramters.
	arg_it = generatedFunc->arg_begin();
	for (int i = 0; i < Args.size(); i++, arg_it++) {
		Value *paramV = GE::builder()->CreateAlloca(arg_it->getType());
		GE::builder()->CreateStore(arg_it, paramV);
		m_parameters[i]->setValueTo(paramV);
	}

	// Generate the body, which will add code to our new insert block
	generateStatements();

	// If our body has a return statement, then we don't have to do anything else here.
	// If we don't have a return statement or a terminator (current block doesn't have a return):
	//		- Are we a main function? If we are, force return 0.
	//		- Are we an auto return? If not, throw an error about a missing return of type for function
	// We only want to check for a return statement in the direct body; no nested bodies. The reason for this is that
	// if we _need_ a return type, it _needs_ to be in the main body.
	if (hasReturn() == false && GE::builder()->GetInsertBlock()->getTerminator() == nullptr) {
		if (isRoot()) {
			GE::builder()->CreateStore(ConstantInt::getSigned(funcType->getReturnType(), 0), m_retVal);
		} else if (m_type != nullptr) {
			throw CompilerMessage(*this, "Missing return type; expected a " + m_type->string());
		}

		// Jump to the end now.
		GE::builder()->CreateBr(m_blockEnd);
	}

	GE::builder()->SetInsertPoint(m_blockEnd);

	// Let's return from the function now; returning our value if we have one (e.g., we're not a void func)
	if (retVal != nullptr) {
		GE::builder()->CreateRet(GE::builder()->CreateLoad(retVal));
	} else {
		GE::builder()->CreateRetVoid();
	}

	// Optimize our function.
	GE::sharedEngine()->functionOptimizer()->run(*generatedFunc);

	// Finally, restore our insert block, pop our block and return our function
	GE::builder()->SetInsertPoint(oldInsertBlock);
	GE::runner()->popBlock();
	return m_value;
}

ASTNode* FunctionStmt::clone() {
	ParamList clonedParams;

	for (auto param : m_parameters) {
		clonedParams.push_back((VarExpr*)param->clone());
	}

	FunctionStmt* clonedFunc = nullptr;

	if (m_type) {
		clonedFunc = new FunctionStmt(m_name, m_type, clonedParams, symtab()->clone());
	} else {
		clonedFunc = new FunctionStmt(m_name, clonedParams, symtab()->clone());
	}

	for (auto stmt : m_statements) {
		auto clonedStmt = stmt->clone();
		clonedFunc->addStatement(clonedStmt);

		// if the stmt is a block, set its parent to the clone's symtab IFF
		// their symtab's parent is the one for our current function statement
		if (Block* block = dynamic_cast<Block*>(clonedStmt)) {
			if (block->symtab()->parent()->ID() == symtab()->ID()) {
				block->symtab()->setParent(clonedFunc->symtab());
			}
		}

		if (IfStmts* ifStmts = dynamic_cast<IfStmts*>(clonedStmt)) {
			for (auto block : ifStmts->blocks()) {
				block->symtab()->setParent(clonedFunc->symtab());
			}
		}
	}

	return clonedFunc;
}

std::string FunctionStmt::string() {
	std::stringstream ss;

	GE::runner()->pushBlock(this);

	ss << m_name << ":" << std::endl;

	for (ASTNode *s : m_statements) {
		if (s == nullptr) continue;
		ss << "\t" << s->string() << std::endl;
	}

	GE::runner()->popBlock();
	return ss.str();
}

bool FunctionStmt::isGeneric() const {
	for (auto param : m_parameters) {
		// *DON'T* use getType() here! that searches up the symtab tree. we only want
		// the deepest level here.
		if (param->type() == nullptr || param->type()->isVoidTy()) {
			return true;
		}
	}

	return false;
}

void FunctionStmt::resolve() {
	if (m_resolved) return;
	// Don't set m_resolved here; let Block::resolve do it.

	// If we don't exist in the parent symtab, add us as a reference.
	// If the parent doesn't exist, we're in the global block, so
	// nothing could call is anyway.
	if (symtab()->parent() != nullptr) {
		bool added = symtab()->parent()->create(m_name, this);
		if (added == false) {
			throw std::runtime_error("Can't create function " + m_name + ". Something with that name already exists!");
		}
	}

	// Add us to our own symtab so we can do recursion.
	bool added = symtab()->create(m_name, this);
	if (added == false) {
		throw std::runtime_error("Can't create function " + m_name + ". Something with that name already exists!");
	}

	// Add us as a structure.
	symtab()->setStructure(this);

	if (isGeneric()) {
		// We don't actually want to resolve our parameters or body since as a generic function, they will never
		// be used. Instead, let's just resolve our clones here.
		for (auto clone : m_clones) {
			clone->resolve();
		}

		m_resolved = true;
		return;
	}

	// Push our symtab into the stack and add our parameters to the symbol table.
	GE::runner()->pushBlock(this);

	for (auto param : m_parameters) param->create();

	GE::runner()->popBlock();

	Block::resolve();
}
<commit_msg>Changed FunctionStmt to not throw an error when the return type is not null, but is a VoidTy.<commit_after>/*
** Copyright 2014-2015 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/

#include <orange/FunctionStmt.h>
#include <orange/generator.h>
#include <orange/IfStmts.h>

FunctionStmt::FunctionStmt(std::string name, ParamList parameters, SymTable* symtab) : Block(symtab) {
	m_name = name;
	m_parameters = parameters;
}

FunctionStmt::FunctionStmt(std::string name, AnyType* type, ParamList parameters, SymTable* symtab) : Block(symtab) {
	m_name = name;
	m_type = type;
	m_parameters = parameters;
}

std::string FunctionStmt::getClonesFullSignature(ArgList args) {
	std::string ret_name = m_name + "_";
	for (auto arg : args) {
		AnyType* type = arg->getType();

		if (type->isIntegerTy()) {
			int width = type->getIntegerBitWidth();
			switch (width) {
				case 1:
					ret_name += "T";
					break;
				case 8:
					ret_name += (type->isSigned() ? "b" : "B");
					break;
				case 16:
					ret_name += (type->isSigned() ? "s" : "S");
					break;
				case 32:
					ret_name += (type->isSigned() ? "i" : "I");
					break;
				case 64:
					ret_name += (type->isSigned() ? "l" : "L");
					break;
				default:
					ret_name += "?";
					break;
			}
		} else if (type->isFloatTy()) {
			ret_name += "f";
		} else if (type->isDoubleTy()) {
			ret_name += "F";
		}

		for (int i = 0; i < type->getPointerLength(); i++) {
			ret_name += "p";
		}
	}

	return ret_name;
}

FunctionStmt* FunctionStmt::createGenericClone(ArgList args) {
	// If we're not a generic, we shouldn't be trying to make a clone.
	if (isGeneric() == false) {
		return nullptr;
	}

	if (args.size() != m_parameters.size()) {
		throw CompilerMessage(*this, "Mismatched number of arguments while calling " + m_name + "!");
	}

	std::string cloned_name = getClonesFullSignature(args);

	// Does a clone with that name already exist? If so, return that clone.
	for (auto clone : m_clones) {
		if (clone->m_name == cloned_name) {
			return clone;
		}
	}

	// Create paramlist from args
	ParamList cloned_params;

	for (int i = 0; i < args.size(); i++) {
		VarExpr* curParam = m_parameters[i];
		VarExpr* newParam = new VarExpr(curParam->name(), args[i]->getType());
		cloned_params.push_back(newParam);
	}

	// Otherwise, create that clone here, add it to the list, and return it.
	FunctionStmt* clone;

	if (m_type) {
		clone = new FunctionStmt(cloned_name, m_type, cloned_params, symtab()->clone());
	} else {
		clone = new FunctionStmt(cloned_name, cloned_params, symtab()->clone());
	}

	for (auto stmt : m_statements) {
		auto clonedStmt = stmt->clone();
		clone->addStatement(clonedStmt);

		// if the stmt is a block, set its parent to the clone's symtab IFF
		// their symtab's parent is the one for our current function statement
		if (Block* block = dynamic_cast<Block*>(clonedStmt)) {
			if (block->symtab()->parent()->ID() == symtab()->ID()) {
				block->symtab()->setParent(clone->symtab());
			}
		}

		if (IfStmts* ifStmts = dynamic_cast<IfStmts*>(clonedStmt)) {
			for (auto block : ifStmts->blocks()) {
				block->symtab()->setParent(clone->symtab());
			}
		}
	}

	m_clones.push_back(clone);
	return clone;
}

AnyType* FunctionStmt::getType() {
	AnyType *ret = m_type;

	// This should not happen; getType() should only be called against clones.
	if (isGeneric()) {
		throw CompilerMessage(*this, "Cannot get type of a generic function.");
	}

	GE::runner()->pushBlock(this);

	// Here, invalid type means that it needs to be redefined for this function.
	bool invalidType = (m_type == nullptr || m_type->isVoidTy() || m_type->isIDTy());
	if (invalidType && m_looking == false) {
		// Set m_looking to true so we don't recursively try to get the type of FunctionStmt
		m_looking = true;

		// If we don't have an explicit type set, we have to determine it from our body and nested bodies.
		AnyType* foundRet = searchForReturn();
		ret = foundRet ? foundRet : ASTNode::getType();
		m_type = ret;
		m_looking = false;
	}

	GE::runner()->popBlock();

	return ret;
}

Value* FunctionStmt::Codegen() {
	// Check to see if we're a generic function.
	// If we are, we only should generate our clones since we're incomplete.
	if (isGeneric()) {
		for (auto clone : m_clones) {
			clone->Codegen();
		}

		return nullptr;
	}

	// Push ourselves onto the stack first.
	GE::runner()->pushBlock(this);

	// Create a list of types that serve as our function's arguments
	std::vector<Type*> Args;

	for (auto param : m_parameters) {
		Args.push_back(param->getLLVMType());
	}

	// Create the function itself, and set it as our AST value.
	FunctionType* funcType = FunctionType::get(getLLVMType(), Args, m_isVarArg);
	Function* generatedFunc = Function::Create(funcType, m_linkageType, m_name, GE::module());
	m_value = generatedFunc;

	// TODO: Set argument names, if any (generatedFunc->arg_begin, setName on iterator)
	auto arg_it = generatedFunc->arg_begin();
	for (unsigned int i = 0; i < Args.size(); i++, arg_it++) {
		arg_it->setName(m_parameters[i]->name());
	}

	// Before generating, we need to get the current insert block so we don't lose our place.
	auto oldInsertBlock = GE::builder()->GetInsertBlock();

	// Create basic block and set our insertion point to it.
	BasicBlock *funcBody = BasicBlock::Create(GE::runner()->context(), "entry", generatedFunc);
	BasicBlock *funcEnd = BasicBlock::Create(GE::runner()->context(), "exit", generatedFunc);
	GE::builder()->SetInsertPoint(funcBody);

	// Set up values for children statements to use.
	Value *retVal = nullptr;
	if (getType()->isVoidTy() == false) {
		retVal = GE::builder()->CreateAlloca(getLLVMType(), nullptr, "return");
		m_retVal = retVal;
	}

	m_blockEnd = funcEnd;

	// Create our paramters.
	arg_it = generatedFunc->arg_begin();
	for (int i = 0; i < Args.size(); i++, arg_it++) {
		Value *paramV = GE::builder()->CreateAlloca(arg_it->getType());
		GE::builder()->CreateStore(arg_it, paramV);
		m_parameters[i]->setValueTo(paramV);
	}

	// Generate the body, which will add code to our new insert block
	generateStatements();

	// If our body has a return statement, then we don't have to do anything else here.
	// If we don't have a return statement or a terminator (current block doesn't have a return):
	//		- Are we a main function? If we are, force return 0.
	//		- Are we an auto return? If not, throw an error about a missing return of type for function
	// We only want to check for a return statement in the direct body; no nested bodies. The reason for this is that
	// if we _need_ a return type, it _needs_ to be in the main body.
	if (hasReturn() == false && GE::builder()->GetInsertBlock()->getTerminator() == nullptr) {
		if (isRoot()) {
			GE::builder()->CreateStore(ConstantInt::getSigned(funcType->getReturnType(), 0), m_retVal);
		} else if (m_type != nullptr && m_type->isVoidTy() == false) {
			throw CompilerMessage(*this, "Missing return type; expected a " + m_type->string());
		}

		// Jump to the end now.
		GE::builder()->CreateBr(m_blockEnd);
	}

	GE::builder()->SetInsertPoint(m_blockEnd);

	// Let's return from the function now; returning our value if we have one (e.g., we're not a void func)
	if (retVal != nullptr) {
		GE::builder()->CreateRet(GE::builder()->CreateLoad(retVal));
	} else {
		GE::builder()->CreateRetVoid();
	}

	// Optimize our function.
	GE::sharedEngine()->functionOptimizer()->run(*generatedFunc);

	// Finally, restore our insert block, pop our block and return our function
	GE::builder()->SetInsertPoint(oldInsertBlock);
	GE::runner()->popBlock();
	return m_value;
}

ASTNode* FunctionStmt::clone() {
	ParamList clonedParams;

	for (auto param : m_parameters) {
		clonedParams.push_back((VarExpr*)param->clone());
	}

	FunctionStmt* clonedFunc = nullptr;

	if (m_type) {
		clonedFunc = new FunctionStmt(m_name, m_type, clonedParams, symtab()->clone());
	} else {
		clonedFunc = new FunctionStmt(m_name, clonedParams, symtab()->clone());
	}

	for (auto stmt : m_statements) {
		auto clonedStmt = stmt->clone();
		clonedFunc->addStatement(clonedStmt);

		// if the stmt is a block, set its parent to the clone's symtab IFF
		// their symtab's parent is the one for our current function statement
		if (Block* block = dynamic_cast<Block*>(clonedStmt)) {
			if (block->symtab()->parent()->ID() == symtab()->ID()) {
				block->symtab()->setParent(clonedFunc->symtab());
			}
		}

		if (IfStmts* ifStmts = dynamic_cast<IfStmts*>(clonedStmt)) {
			for (auto block : ifStmts->blocks()) {
				block->symtab()->setParent(clonedFunc->symtab());
			}
		}
	}

	return clonedFunc;
}

std::string FunctionStmt::string() {
	std::stringstream ss;

	GE::runner()->pushBlock(this);

	ss << m_name << ":" << std::endl;

	for (ASTNode *s : m_statements) {
		if (s == nullptr) continue;
		ss << "\t" << s->string() << std::endl;
	}

	GE::runner()->popBlock();
	return ss.str();
}

bool FunctionStmt::isGeneric() const {
	for (auto param : m_parameters) {
		// *DON'T* use getType() here! that searches up the symtab tree. we only want
		// the deepest level here.
		if (param->type() == nullptr || param->type()->isVoidTy()) {
			return true;
		}
	}

	return false;
}

void FunctionStmt::resolve() {
	if (m_resolved) return;
	// Don't set m_resolved here; let Block::resolve do it.

	// If we don't exist in the parent symtab, add us as a reference.
	// If the parent doesn't exist, we're in the global block, so
	// nothing could call is anyway.
	if (symtab()->parent() != nullptr) {
		bool added = symtab()->parent()->create(m_name, this);
		if (added == false) {
			throw std::runtime_error("Can't create function " + m_name + ". Something with that name already exists!");
		}
	}

	// Add us to our own symtab so we can do recursion.
	bool added = symtab()->create(m_name, this);
	if (added == false) {
		throw std::runtime_error("Can't create function " + m_name + ". Something with that name already exists!");
	}

	// Add us as a structure.
	symtab()->setStructure(this);

	if (isGeneric()) {
		// We don't actually want to resolve our parameters or body since as a generic function, they will never
		// be used. Instead, let's just resolve our clones here.
		for (auto clone : m_clones) {
			clone->resolve();
		}

		m_resolved = true;
		return;
	}

	// Push our symtab into the stack and add our parameters to the symbol table.
	GE::runner()->pushBlock(this);

	for (auto param : m_parameters) param->create();

	GE::runner()->popBlock();

	Block::resolve();
}
<|endoftext|>


<commit_before>#include <fftw3.h>
#include "common.h"
#include "metrix.h"

// Very simple. Only for even sizes.
// And for even sizes fftshift and ifftshift coinside.
template<int N> void fft_center(complexd data[N][N]){
  bool flip = false;
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      if (flip) data[i][j] = std::complex<double>(-data[i][j].real(), -data[i][j].imag());
      flip = !flip;
    }
  }
}

template<int N> void fftshift_even(complexd data[N][N]){
  complexd tmp;
  for (int i = 0; i < N/2; i++) {
    for (int j = 0; j < N/2; j++) {
       tmp = data[i+N/2][j+N/2];
       data[i+N/2][j+N/2] = data[i][j];
       data[i][j] = tmp;
    }
  }
}

#define dp reinterpret_cast<fftw_complex*>(&data[0][0])
template<int N> void __fft_inplace(complexd data[N][N]){
  fft_center<N>(data);
  fftw_plan p = fftw_plan_dft_2d(N, N, dp, dp, FFTW_FORWARD, FFTW_ESTIMATE);
  fftw_execute(p);
  fftw_destroy_plan(p);
  // Temporarily disable the shifting of the result because
  // of slowness
  // fftshift_even<N>(data);
}

extern "C"
void fft_inplace_even(complexd data[GRID_SIZE][GRID_SIZE]){
  __fft_inplace<GRID_SIZE>(data);
}
<commit_msg>Forgot to move comment.<commit_after>#include <fftw3.h>
#include "common.h"
#include "metrix.h"

template<int N> void fft_center(complexd data[N][N]){
  bool flip = false;
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      if (flip) data[i][j] = std::complex<double>(-data[i][j].real(), -data[i][j].imag());
      flip = !flip;
    }
  }
}

// Very simple. Only for even sizes.
// And for even sizes fftshift and ifftshift coinside.
template<int N> void fftshift_even(complexd data[N][N]){
  complexd tmp;
  for (int i = 0; i < N/2; i++) {
    for (int j = 0; j < N/2; j++) {
       tmp = data[i+N/2][j+N/2];
       data[i+N/2][j+N/2] = data[i][j];
       data[i][j] = tmp;
    }
  }
}

#define dp reinterpret_cast<fftw_complex*>(&data[0][0])
template<int N> void __fft_inplace(complexd data[N][N]){
  fft_center<N>(data);
  fftw_plan p = fftw_plan_dft_2d(N, N, dp, dp, FFTW_FORWARD, FFTW_ESTIMATE);
  fftw_execute(p);
  fftw_destroy_plan(p);
  // Temporarily disable the shifting of the result because
  // of slowness
  // fftshift_even<N>(data);
}

extern "C"
void fft_inplace_even(complexd data[GRID_SIZE][GRID_SIZE]){
  __fft_inplace<GRID_SIZE>(data);
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright (C) 2015 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <map>

namespace utils {

/**
 * Histogram that can be constructed from streaming of data.
 *
 * The algorithm is taken from following paper:
 * Yael Ben-Haim and Elad Tom-Tov, "A Streaming Parallel Decision Tree Algorithm" (2010)
 * http://jmlr.csail.mit.edu/papers/volume11/ben-haim10a/ben-haim10a.pdf
 */
struct streaming_histogram {
    // TreeMap to hold bins of histogram.
    std::map<double, uint64_t> bin;

    // maximum bin size for this histogram
    uint32_t max_bin_size;

    /**
     * Creates a new histogram with max bin size of maxBinSize
     * @param maxBinSize maximum number of bins this histogram can have
     */
    streaming_histogram(int max_bin_size_p = 0) {
        max_bin_size = max_bin_size_p;
    }

    streaming_histogram(int max_bin_size_p, std::map<double, uint64_t>&& bin_p)
    {
        max_bin_size = max_bin_size_p;
        bin = std::move(bin_p);
    }

    /**
     * Adds new point p to this histogram.
     * @param p
     */
    void update(double p)
    {
        update(p, 1);
    }

    /**
     * Adds new point p with value m to this histogram.
     * @param p
     * @param m
     */
    void update(double p, uint64_t m) {
        auto it = bin.find(p);
        if (it != bin.end()) {
            bin[p] = it->second + m;
        } else {
            bin[p] = m;
            // if bin size exceeds maximum bin size then trim down to max size
            while (bin.size() > max_bin_size) {
                // find points p1, p2 which have smallest difference
                auto it = bin.begin();
                double p1 = it->first;
                it++;
                double p2 = it->first;
                it++;
                double smallestDiff = p2 - p1;
                double q1 = p1, q2 = p2;
                while(it != bin.end()) {
                    p1 = p2;
                    p2 = it->first;
                    it++;
                    double diff = p2 - p1;
                    if (diff < smallestDiff)
                    {
                        smallestDiff = diff;
                        q1 = p1;
                        q2 = p2;
                    }
                }
                // merge those two
                uint64_t k1 = bin.at(q1);
                uint64_t k2 = bin.at(q2);
                bin.erase(q1);
                bin.erase(q2);
                bin.insert({(q1 * k1 + q2 * k2) / (k1 + k2), k1 + k2});
            }
        }
    }

    /**
     * Merges given histogram with this histogram.
     *
     * @param other histogram to merge
     */
    void merge(streaming_histogram& other)
    {
        if (!other.bin.size())
            return;

        for (auto& it : other.bin) {
            update(it.first, it.second);
        }
    }

    /**
     * Calculates estimated number of points in interval [-inf,b].
     *
     * @param b upper bound of a interval to calculate sum
     * @return estimated number of points in a interval [-inf,b].
     */
    double sum(double b) const {
        double sum = 0;
        // find the points pi, pnext which satisfy pi <= b < pnext
        auto pnext = bin.upper_bound(b);
        if (pnext == bin.end()) {
            // if b is greater than any key in this histogram,
            // just count all appearance and return
            for (auto& e : bin) {
                sum += e.second;
            }
        }
        else
        {
            // return key-value mapping associated with the greatest key less than or equal to the given key
            auto pi = bin.lower_bound(b);
            if (pi == bin.end() || (pi == bin.begin() && b < pi->first)) {
                return 0;
            }
            if (pi->first != b) {
                --pi;
            }

            // calculate estimated count mb for point b
            double weight = (b - pi->first) / (pnext->first - pi->first);
            double mb = pi->second + (int64_t(pnext->second) - int64_t(pi->second)) * weight;
            sum += (pi->second + mb) * weight / 2;

            sum += pi->second / 2.0;
            // iterate through portion of map whose keys are less than pi->first
            auto it_end = bin.lower_bound(pi->first);
            for (auto it = bin.begin(); it != it_end; it++) {
                sum += it->second;
            }
        }
        return sum;
    }

    // FIXME: convert Java code below.
#if 0
    public Map<Double, Long> getAsMap()
    {
        return Collections.unmodifiableMap(bin);
    }

    public static class StreamingHistogramSerializer implements ISerializer<StreamingHistogram>
    {
        public void serialize(StreamingHistogram histogram, DataOutputPlus out) throws IOException
        {
            out.writeInt(histogram.maxBinSize);
            Map<Double, Long> entries = histogram.getAsMap();
            out.writeInt(entries.size());
            for (Map.Entry<Double, Long> entry : entries.entrySet())
            {
                out.writeDouble(entry.getKey());
                out.writeLong(entry.getValue());
            }
        }

        public StreamingHistogram deserialize(DataInput in) throws IOException
        {
            int maxBinSize = in.readInt();
            int size = in.readInt();
            Map<Double, Long> tmp = new HashMap<>(size);
            for (int i = 0; i < size; i++)
            {
                tmp.put(in.readDouble(), in.readLong());
            }

            return new StreamingHistogram(maxBinSize, tmp);
        }

        public long serializedSize(StreamingHistogram histogram, TypeSizes typeSizes)
        {
            long size = typeSizes.sizeof(histogram.maxBinSize);
            Map<Double, Long> entries = histogram.getAsMap();
            size += typeSizes.sizeof(entries.size());
            // size of entries = size * (8(double) + 8(long))
            size += entries.size() * (8 + 8);
            return size;
        }
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o)
            return true;

        if (!(o instanceof StreamingHistogram))
            return false;

        StreamingHistogram that = (StreamingHistogram) o;
        return maxBinSize == that.maxBinSize && bin.equals(that.bin);
    }

    @Override
    public int hashCode()
    {
        return Objects.hashCode(bin.hashCode(), maxBinSize);
    }
#endif
};

}
<commit_msg>streaming_histogram: fix coding style<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright (C) 2015 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <map>

namespace utils {

/**
 * Histogram that can be constructed from streaming of data.
 *
 * The algorithm is taken from following paper:
 * Yael Ben-Haim and Elad Tom-Tov, "A Streaming Parallel Decision Tree Algorithm" (2010)
 * http://jmlr.csail.mit.edu/papers/volume11/ben-haim10a/ben-haim10a.pdf
 */
struct streaming_histogram {
    // TreeMap to hold bins of histogram.
    std::map<double, uint64_t> bin;

    // maximum bin size for this histogram
    uint32_t max_bin_size;

    /**
     * Creates a new histogram with max bin size of maxBinSize
     * @param maxBinSize maximum number of bins this histogram can have
     */
    streaming_histogram(int max_bin_size = 0)
        : max_bin_size(max_bin_size) {
    }

    streaming_histogram(int max_bin_size, std::map<double, uint64_t>&& bin)
        : bin(std::move(bin))
        , max_bin_size(max_bin_size) {
    }

    /**
     * Adds new point p to this histogram.
     * @param p
     */
    void update(double p) {
        update(p, 1);
    }

    /**
     * Adds new point p with value m to this histogram.
     * @param p
     * @param m
     */
    void update(double p, uint64_t m) {
        auto it = bin.find(p);
        if (it != bin.end()) {
            bin[p] = it->second + m;
        } else {
            bin[p] = m;
            // if bin size exceeds maximum bin size then trim down to max size
            while (bin.size() > max_bin_size) {
                // find points p1, p2 which have smallest difference
                auto it = bin.begin();
                double p1 = it->first;
                it++;
                double p2 = it->first;
                it++;
                double smallestDiff = p2 - p1;
                double q1 = p1, q2 = p2;
                while(it != bin.end()) {
                    p1 = p2;
                    p2 = it->first;
                    it++;
                    double diff = p2 - p1;
                    if (diff < smallestDiff)
                    {
                        smallestDiff = diff;
                        q1 = p1;
                        q2 = p2;
                    }
                }
                // merge those two
                uint64_t k1 = bin.at(q1);
                uint64_t k2 = bin.at(q2);
                bin.erase(q1);
                bin.erase(q2);
                bin.insert({(q1 * k1 + q2 * k2) / (k1 + k2), k1 + k2});
            }
        }
    }

    /**
     * Merges given histogram with this histogram.
     *
     * @param other histogram to merge
     */
    void merge(streaming_histogram& other) {
        if (!other.bin.size()) {
            return;
        }

        for (auto& it : other.bin) {
            update(it.first, it.second);
        }
    }

    /**
     * Calculates estimated number of points in interval [-inf,b].
     *
     * @param b upper bound of a interval to calculate sum
     * @return estimated number of points in a interval [-inf,b].
     */
    double sum(double b) const {
        double sum = 0;
        // find the points pi, pnext which satisfy pi <= b < pnext
        auto pnext = bin.upper_bound(b);
        if (pnext == bin.end()) {
            // if b is greater than any key in this histogram,
            // just count all appearance and return
            for (auto& e : bin) {
                sum += e.second;
            }
        } else {
            // return key-value mapping associated with the greatest key less than or equal to the given key
            auto pi = bin.lower_bound(b);
            if (pi == bin.end() || (pi == bin.begin() && b < pi->first)) {
                return 0;
            }
            if (pi->first != b) {
                --pi;
            }

            // calculate estimated count mb for point b
            double weight = (b - pi->first) / (pnext->first - pi->first);
            double mb = pi->second + (int64_t(pnext->second) - int64_t(pi->second)) * weight;
            sum += (pi->second + mb) * weight / 2;

            sum += pi->second / 2.0;
            // iterate through portion of map whose keys are less than pi->first
            auto it_end = bin.lower_bound(pi->first);
            for (auto it = bin.begin(); it != it_end; it++) {
                sum += it->second;
            }
        }
        return sum;
    }

    // FIXME: convert Java code below.
#if 0
    public Map<Double, Long> getAsMap()
    {
        return Collections.unmodifiableMap(bin);
    }

    public static class StreamingHistogramSerializer implements ISerializer<StreamingHistogram>
    {
        public void serialize(StreamingHistogram histogram, DataOutputPlus out) throws IOException
        {
            out.writeInt(histogram.maxBinSize);
            Map<Double, Long> entries = histogram.getAsMap();
            out.writeInt(entries.size());
            for (Map.Entry<Double, Long> entry : entries.entrySet())
            {
                out.writeDouble(entry.getKey());
                out.writeLong(entry.getValue());
            }
        }

        public StreamingHistogram deserialize(DataInput in) throws IOException
        {
            int maxBinSize = in.readInt();
            int size = in.readInt();
            Map<Double, Long> tmp = new HashMap<>(size);
            for (int i = 0; i < size; i++)
            {
                tmp.put(in.readDouble(), in.readLong());
            }

            return new StreamingHistogram(maxBinSize, tmp);
        }

        public long serializedSize(StreamingHistogram histogram, TypeSizes typeSizes)
        {
            long size = typeSizes.sizeof(histogram.maxBinSize);
            Map<Double, Long> entries = histogram.getAsMap();
            size += typeSizes.sizeof(entries.size());
            // size of entries = size * (8(double) + 8(long))
            size += entries.size() * (8 + 8);
            return size;
        }
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o)
            return true;

        if (!(o instanceof StreamingHistogram))
            return false;

        StreamingHistogram that = (StreamingHistogram) o;
        return maxBinSize == that.maxBinSize && bin.equals(that.bin);
    }

    @Override
    public int hashCode()
    {
        return Objects.hashCode(bin.hashCode(), maxBinSize);
    }
#endif
};

}
<|endoftext|>


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

#ifndef _SV_IMPIMAGETREE_HXX
#define _SV_IMPIMAGETREE_HXX

#include <memory>

#ifndef _COMPHELPER_SINGLETONREF_HXX_
#include <salhelper/singletonref.hxx>
#endif
#include <com/sun/star/uno/Reference.hxx>

// ----------------
// -ImplImageTree -
// ----------------

class BitmapEx;
namespace com { namespace sun { namespace star { namespace packages { namespace zip { class XZipFileAccess; } } } } }
namespace com { namespace sun { namespace star { namespace container { class XNameAccess; } } } }
namespace com { namespace sun { namespace star { namespace beans { class XPropertySet; } } } }
namespace com { namespace sun { namespace star { namespace ucb { class XSimpleFileAccess; } } } }
namespace com { namespace sun { namespace star { namespace io { class XInputStream; } } } }

class ImplImageTree
{
public:

                    ImplImageTree();
                    ~ImplImageTree();

    bool            loadImage( const ::rtl::OUString& rName,
                               const ::rtl::OUString& rSymbolsStyle,
                               BitmapEx& rReturn,
                               bool bSearchLanguageDependent = false );
    void            addUserImage( const ::rtl::OUString& rName, const BitmapEx& rReturn );

    static void     cleanup();

private:

    ::com::sun::star::uno::Reference< ::com::sun::star::packages::zip::XZipFileAccess > mxZipAcc;
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >        mxNameAcc;
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >           mxPathSettings;
    ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >        mxFileAccess;
    bool                                                                                mbInit;
    ::rtl::OUString                                                                     maSymbolsStyle;

    bool                    implInit();
    ::rtl::OUString         implGetZipFileURL( bool bWithStyle = true ) const;
    const ::rtl::OUString&  implGetUserDirURL() const;
    ::rtl::OUString         implGetUserFileURL( const ::rtl::OUString& rName ) const;
    void                    implCheckUserCache();
    bool                    implLoadFromStream( SvStream& rIStm, const ::rtl::OUString& rFileName, BitmapEx& rReturn );
    ::std::auto_ptr< SvStream > implGetStream( const ::com::sun::star::uno::Reference<
                                                        ::com::sun::star::io::XInputStream >& rxIStm ) const;
    void                    implUpdateSymbolsStyle( const ::rtl::OUString& rSymbolsStyle );
};

typedef ::salhelper::SingletonRef< ImplImageTree > ImplImageTreeSingletonRef;

#endif // _SV_IMPIMAGETREE_HXX
<commit_msg>INTEGRATION: CWS iconupdate04 (1.2.204); FILE MERGED 2008/04/10 06:35:38 ka 1.2.204.2: #i87567#: allow usage of multilayer icon themes 2008/04/08 15:34:54 ka 1.2.204.1: multilayer image handling<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: impimagetree.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SV_IMPIMAGETREE_HXX
#define _SV_IMPIMAGETREE_HXX

#include <memory>

#ifndef _COMPHELPER_SINGLETONREF_HXX_
#include <salhelper/singletonref.hxx>
#endif
#include <com/sun/star/uno/Reference.hxx>

// ----------------
// -ImplImageTree -
// ----------------

class BitmapEx;
namespace com { namespace sun { namespace star { namespace packages { namespace zip { class XZipFileAccess; } } } } }
namespace com { namespace sun { namespace star { namespace container { class XNameAccess; } } } }
namespace com { namespace sun { namespace star { namespace beans { class XPropertySet; } } } }
namespace com { namespace sun { namespace star { namespace ucb { class XSimpleFileAccess; } } } }
namespace com { namespace sun { namespace star { namespace io { class XInputStream; } } } }

// -------------------
// - ImplZipAccessor -
// -------------------

class ImplZipAccessor
{
private:

    ::std::vector< ::rtl::OUString >                                                                     maURLVector;
    ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >                         mxFileAccess;
    ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::packages::zip::XZipFileAccess > > maZipAccVector;
    ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > >        maNameAccVector;

public:

                                ImplZipAccessor();
                                ~ImplZipAccessor();

    void                        Update( const ::rtl::OUString& rSymbolsStyle );
    void                        Clear();
    bool                        HasEntries() const;

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > GetByName( const ::rtl::OUString& rName ) const;
};

// -----------------
// - ImplImageTree -
// -----------------

class ImplImageTree
{
public:

                    ImplImageTree();
                    ~ImplImageTree();

    bool            loadImage( const ::rtl::OUString& rName,
                               const ::rtl::OUString& rSymbolsStyle,
                               BitmapEx& rReturn,
                               bool bSearchLanguageDependent = false );
    void            addUserImage( const ::rtl::OUString& rName, const BitmapEx& rReturn );

    static void     cleanup();

private:

    ImplZipAccessor                                                                     maZipAcc;
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >           mxPathSettings;
    ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >        mxFileAccess;
    bool                                                                                mbInit;
    ::rtl::OUString                                                                     maSymbolsStyle;

    bool                    implInit();
    const ::rtl::OUString&  implGetUserDirURL() const;
    ::rtl::OUString         implGetUserFileURL( const ::rtl::OUString& rName ) const;
    void                    implCheckUserCache();
    bool                    implLoadFromStream( SvStream& rIStm, const ::rtl::OUString& rFileName, BitmapEx& rReturn );
    ::std::auto_ptr< SvStream > implGetStream( const ::com::sun::star::uno::Reference<
                                                        ::com::sun::star::io::XInputStream >& rxIStm ) const;
    void                    implUpdateSymbolsStyle( const ::rtl::OUString& rSymbolsStyle );
};

typedef ::salhelper::SingletonRef< ImplImageTree > ImplImageTreeSingletonRef;

#endif // _SV_IMPIMAGETREE_HXX
<|endoftext|>


<commit_before><commit_msg>fdo#74124 bilinear scaling with blending for some formats<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabdlg.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-19 16:48:35 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SV_FIXED_HXX
#include <fixed.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _SV_TABDLG_HXX
#include <tabdlg.hxx>
#endif
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif

// =======================================================================

void TabDialog::ImplInitTabDialogData()
{
    mpFixedLine     = NULL;
    mpViewWindow    = NULL;
    meViewAlign     = WINDOWALIGN_LEFT;
    mbPosControls   = TRUE;
}

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

void TabDialog::ImplPosControls()
{
    Size        aCtrlSize( IMPL_MINSIZE_BUTTON_WIDTH, IMPL_MINSIZE_BUTTON_HEIGHT );
    long        nDownCtrl = 0;
    long        nOffY = 0;
    TabControl* pTabControl = NULL;

    Window* pChild = GetWindow( WINDOW_FIRSTCHILD );
    while ( pChild )
    {
        if ( pChild->IsVisible() && (pChild != mpViewWindow) )
        {
            if ( pChild->GetType() == WINDOW_TABCONTROL )
                pTabControl = (TabControl*)pChild;
            else if ( pTabControl )
            {
                long nTxtWidth = pChild->GetCtrlTextWidth( pChild->GetText() );
                nTxtWidth += IMPL_EXTRA_BUTTON_WIDTH;
                if ( nTxtWidth > aCtrlSize.Width() )
                    aCtrlSize.Width() = nTxtWidth;
                long nTxtHeight = pChild->GetTextHeight();
                nTxtHeight += IMPL_EXTRA_BUTTON_HEIGHT;
                if ( nTxtHeight > aCtrlSize.Height() )
                    aCtrlSize.Height() = nTxtHeight;
                nDownCtrl++;
            }
            else
            {
                long nHeight = pChild->GetSizePixel().Height();
                if ( nHeight > nOffY )
                    nOffY = nHeight;
            }
        }

        pChild = pChild->GetWindow( WINDOW_NEXT );
    }

    // Haben wir ueberhaupt ein TabControl
    if ( pTabControl )
    {
        // Offset bei weiteren Controls um einen weiteren Abstand anpassen
        if ( nOffY )
            nOffY += IMPL_DIALOG_BAR_OFFSET*2 + 2;

        Point   aTabOffset( IMPL_DIALOG_OFFSET, IMPL_DIALOG_OFFSET+nOffY );
        Size    aTabSize = pTabControl->GetSizePixel();
        Size    aDlgSize( aTabSize.Width() + IMPL_DIALOG_OFFSET*2,
                          aTabSize.Height() + IMPL_DIALOG_OFFSET*2 + nOffY );
        long    nBtnEx = 0;

        // Preview-Fenster beruecksichtigen und die Groessen/Offsets anpassen
        if ( mpViewWindow && mpViewWindow->IsVisible() )
        {
            long    nViewOffX = 0;
            long    nViewOffY = 0;
            long    nViewWidth = 0;
            long    nViewHeight = 0;
            USHORT  nViewPosFlags = WINDOW_POSSIZE_POS;
            Size    aViewSize = mpViewWindow->GetSizePixel();
            if (  meViewAlign == WINDOWALIGN_TOP )
            {
                nViewOffX       = aTabOffset.X();
                nViewOffY       = nOffY+IMPL_DIALOG_OFFSET;
                nViewWidth      = aTabSize.Width();
                nViewPosFlags  |= WINDOW_POSSIZE_WIDTH;
                aTabOffset.Y() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
                aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
            }
            else if (  meViewAlign == WINDOWALIGN_BOTTOM )
            {
                nViewOffX       = aTabOffset.X();
                nViewOffY       = aTabOffset.Y()+aTabSize.Height()+IMPL_DIALOG_OFFSET;
                nViewWidth      = aTabSize.Width();
                nViewPosFlags  |= WINDOW_POSSIZE_WIDTH;
                aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
            }
            else if (  meViewAlign == WINDOWALIGN_RIGHT )
            {
                nViewOffX       = aTabOffset.X()+aTabSize.Width()+IMPL_DIALOG_OFFSET;
                nViewOffY       = aTabOffset.Y();
                nViewHeight     = aTabSize.Height();
                nViewPosFlags  |= WINDOW_POSSIZE_HEIGHT;
                aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
                nBtnEx          = aViewSize.Width()+IMPL_DIALOG_OFFSET;
            }
            else // meViewAlign == WINDOWALIGN_LEFT
            {
                nViewOffX       = IMPL_DIALOG_OFFSET;
                nViewOffY       = aTabOffset.Y();
                nViewHeight     = aTabSize.Height();
                nViewPosFlags  |= WINDOW_POSSIZE_HEIGHT;
                aTabOffset.X() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
                aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
                nBtnEx          = aViewSize.Width()+IMPL_DIALOG_OFFSET;
            }

            mpViewWindow->SetPosSizePixel( nViewOffX, nViewOffY,
                                           nViewWidth, nViewHeight,
                                           nViewPosFlags );
        }

        // Positionierung vornehmen
        pTabControl->SetPosPixel( aTabOffset );

        // Alle anderen Childs positionieren
        BOOL bTabCtrl   = FALSE;
        int  nLines     = 0;
        long nX;
        long nY         = aDlgSize.Height();
        long nTopX      = IMPL_DIALOG_OFFSET;

        // Unter Windows 95 werden die Buttons rechtsbuendig angeordnet
        nX = IMPL_DIALOG_OFFSET;
        long nCtrlBarWidth = ((aCtrlSize.Width()+IMPL_DIALOG_OFFSET)*nDownCtrl)-IMPL_DIALOG_OFFSET;
        if ( nCtrlBarWidth <= (aTabSize.Width()+nBtnEx) )
            nX = (aTabSize.Width()+nBtnEx) - nCtrlBarWidth + IMPL_DIALOG_OFFSET;

        Window* pChild2 = GetWindow( WINDOW_FIRSTCHILD );
        while ( pChild2 )
        {
            if ( pChild2->IsVisible() && (pChild2 != mpViewWindow) )
            {
                if ( pChild2 == pTabControl )
                    bTabCtrl = TRUE;
                else if ( bTabCtrl )
                {
                    if ( !nLines )
                        nLines = 1;

                    if ( nX+aCtrlSize.Width()-IMPL_DIALOG_OFFSET > (aTabSize.Width()+nBtnEx) )
                    {
                        nY += aCtrlSize.Height()+IMPL_DIALOG_OFFSET;
                        nX  = IMPL_DIALOG_OFFSET;
                        nLines++;
                    }

                    pChild2->SetPosSizePixel( Point( nX, nY ), aCtrlSize );
                    nX += aCtrlSize.Width()+IMPL_DIALOG_OFFSET;
                }
                else
                {
                    Size aChildSize = pChild2->GetSizePixel();
                    pChild2->SetPosPixel( Point( nTopX, (nOffY-aChildSize.Height())/2 ) );
                    nTopX += aChildSize.Width()+2;
                }
            }

            pChild2 = pChild2->GetWindow( WINDOW_NEXT );
        }

        aDlgSize.Height() += nLines * (aCtrlSize.Height()+IMPL_DIALOG_OFFSET);
        SetOutputSizePixel( aDlgSize );
    }

    // Offset merken
    if ( nOffY )
    {
        Size aDlgSize = GetOutputSizePixel();
        if ( !mpFixedLine )
            mpFixedLine = new FixedLine( this );
        mpFixedLine->SetPosSizePixel( Point( 0, nOffY ),
                                      Size( aDlgSize.Width(), 2 ) );
        mpFixedLine->Show();
    }

    mbPosControls = FALSE;
}

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

TabDialog::TabDialog( Window* pParent, WinBits nStyle ) :
    Dialog( WINDOW_TABDIALOG )
{
    ImplInitTabDialogData();
    ImplInit( pParent, nStyle );
}

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

TabDialog::TabDialog( Window* pParent, const ResId& rResId ) :
    Dialog( WINDOW_TABDIALOG )
{
    ImplInitTabDialogData();
    rResId.SetRT( RSC_TABDIALOG );
    ImplInit( pParent, ImplInitRes( rResId ) );
    ImplLoadRes( rResId );
}

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

TabDialog::~TabDialog()
{
    if ( mpFixedLine )
        delete mpFixedLine;
}

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

void TabDialog::Resize()
{
// !!! In the future the controls should be automaticly rearrange
// !!! if the window is resized
// !!! if ( !IsRollUp() )
// !!!      ImplPosControls();
}

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

void TabDialog::StateChanged( StateChangedType nType )
{
    if ( nType == STATE_CHANGE_INITSHOW )
    {
        // Calculate the Layout only for the initialized state
        if ( mbPosControls )
            ImplPosControls();
    }
    Dialog::StateChanged( nType );
}

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

void TabDialog::AdjustLayout()
{
    ImplPosControls();
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.60); FILE MERGED 2006/09/01 17:57:56 kaib 1.6.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabdlg.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 12:22:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _SV_FIXED_HXX
#include <fixed.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _SV_TABDLG_HXX
#include <tabdlg.hxx>
#endif
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif

// =======================================================================

void TabDialog::ImplInitTabDialogData()
{
    mpFixedLine     = NULL;
    mpViewWindow    = NULL;
    meViewAlign     = WINDOWALIGN_LEFT;
    mbPosControls   = TRUE;
}

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

void TabDialog::ImplPosControls()
{
    Size        aCtrlSize( IMPL_MINSIZE_BUTTON_WIDTH, IMPL_MINSIZE_BUTTON_HEIGHT );
    long        nDownCtrl = 0;
    long        nOffY = 0;
    TabControl* pTabControl = NULL;

    Window* pChild = GetWindow( WINDOW_FIRSTCHILD );
    while ( pChild )
    {
        if ( pChild->IsVisible() && (pChild != mpViewWindow) )
        {
            if ( pChild->GetType() == WINDOW_TABCONTROL )
                pTabControl = (TabControl*)pChild;
            else if ( pTabControl )
            {
                long nTxtWidth = pChild->GetCtrlTextWidth( pChild->GetText() );
                nTxtWidth += IMPL_EXTRA_BUTTON_WIDTH;
                if ( nTxtWidth > aCtrlSize.Width() )
                    aCtrlSize.Width() = nTxtWidth;
                long nTxtHeight = pChild->GetTextHeight();
                nTxtHeight += IMPL_EXTRA_BUTTON_HEIGHT;
                if ( nTxtHeight > aCtrlSize.Height() )
                    aCtrlSize.Height() = nTxtHeight;
                nDownCtrl++;
            }
            else
            {
                long nHeight = pChild->GetSizePixel().Height();
                if ( nHeight > nOffY )
                    nOffY = nHeight;
            }
        }

        pChild = pChild->GetWindow( WINDOW_NEXT );
    }

    // Haben wir ueberhaupt ein TabControl
    if ( pTabControl )
    {
        // Offset bei weiteren Controls um einen weiteren Abstand anpassen
        if ( nOffY )
            nOffY += IMPL_DIALOG_BAR_OFFSET*2 + 2;

        Point   aTabOffset( IMPL_DIALOG_OFFSET, IMPL_DIALOG_OFFSET+nOffY );
        Size    aTabSize = pTabControl->GetSizePixel();
        Size    aDlgSize( aTabSize.Width() + IMPL_DIALOG_OFFSET*2,
                          aTabSize.Height() + IMPL_DIALOG_OFFSET*2 + nOffY );
        long    nBtnEx = 0;

        // Preview-Fenster beruecksichtigen und die Groessen/Offsets anpassen
        if ( mpViewWindow && mpViewWindow->IsVisible() )
        {
            long    nViewOffX = 0;
            long    nViewOffY = 0;
            long    nViewWidth = 0;
            long    nViewHeight = 0;
            USHORT  nViewPosFlags = WINDOW_POSSIZE_POS;
            Size    aViewSize = mpViewWindow->GetSizePixel();
            if (  meViewAlign == WINDOWALIGN_TOP )
            {
                nViewOffX       = aTabOffset.X();
                nViewOffY       = nOffY+IMPL_DIALOG_OFFSET;
                nViewWidth      = aTabSize.Width();
                nViewPosFlags  |= WINDOW_POSSIZE_WIDTH;
                aTabOffset.Y() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
                aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
            }
            else if (  meViewAlign == WINDOWALIGN_BOTTOM )
            {
                nViewOffX       = aTabOffset.X();
                nViewOffY       = aTabOffset.Y()+aTabSize.Height()+IMPL_DIALOG_OFFSET;
                nViewWidth      = aTabSize.Width();
                nViewPosFlags  |= WINDOW_POSSIZE_WIDTH;
                aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
            }
            else if (  meViewAlign == WINDOWALIGN_RIGHT )
            {
                nViewOffX       = aTabOffset.X()+aTabSize.Width()+IMPL_DIALOG_OFFSET;
                nViewOffY       = aTabOffset.Y();
                nViewHeight     = aTabSize.Height();
                nViewPosFlags  |= WINDOW_POSSIZE_HEIGHT;
                aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
                nBtnEx          = aViewSize.Width()+IMPL_DIALOG_OFFSET;
            }
            else // meViewAlign == WINDOWALIGN_LEFT
            {
                nViewOffX       = IMPL_DIALOG_OFFSET;
                nViewOffY       = aTabOffset.Y();
                nViewHeight     = aTabSize.Height();
                nViewPosFlags  |= WINDOW_POSSIZE_HEIGHT;
                aTabOffset.X() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
                aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
                nBtnEx          = aViewSize.Width()+IMPL_DIALOG_OFFSET;
            }

            mpViewWindow->SetPosSizePixel( nViewOffX, nViewOffY,
                                           nViewWidth, nViewHeight,
                                           nViewPosFlags );
        }

        // Positionierung vornehmen
        pTabControl->SetPosPixel( aTabOffset );

        // Alle anderen Childs positionieren
        BOOL bTabCtrl   = FALSE;
        int  nLines     = 0;
        long nX;
        long nY         = aDlgSize.Height();
        long nTopX      = IMPL_DIALOG_OFFSET;

        // Unter Windows 95 werden die Buttons rechtsbuendig angeordnet
        nX = IMPL_DIALOG_OFFSET;
        long nCtrlBarWidth = ((aCtrlSize.Width()+IMPL_DIALOG_OFFSET)*nDownCtrl)-IMPL_DIALOG_OFFSET;
        if ( nCtrlBarWidth <= (aTabSize.Width()+nBtnEx) )
            nX = (aTabSize.Width()+nBtnEx) - nCtrlBarWidth + IMPL_DIALOG_OFFSET;

        Window* pChild2 = GetWindow( WINDOW_FIRSTCHILD );
        while ( pChild2 )
        {
            if ( pChild2->IsVisible() && (pChild2 != mpViewWindow) )
            {
                if ( pChild2 == pTabControl )
                    bTabCtrl = TRUE;
                else if ( bTabCtrl )
                {
                    if ( !nLines )
                        nLines = 1;

                    if ( nX+aCtrlSize.Width()-IMPL_DIALOG_OFFSET > (aTabSize.Width()+nBtnEx) )
                    {
                        nY += aCtrlSize.Height()+IMPL_DIALOG_OFFSET;
                        nX  = IMPL_DIALOG_OFFSET;
                        nLines++;
                    }

                    pChild2->SetPosSizePixel( Point( nX, nY ), aCtrlSize );
                    nX += aCtrlSize.Width()+IMPL_DIALOG_OFFSET;
                }
                else
                {
                    Size aChildSize = pChild2->GetSizePixel();
                    pChild2->SetPosPixel( Point( nTopX, (nOffY-aChildSize.Height())/2 ) );
                    nTopX += aChildSize.Width()+2;
                }
            }

            pChild2 = pChild2->GetWindow( WINDOW_NEXT );
        }

        aDlgSize.Height() += nLines * (aCtrlSize.Height()+IMPL_DIALOG_OFFSET);
        SetOutputSizePixel( aDlgSize );
    }

    // Offset merken
    if ( nOffY )
    {
        Size aDlgSize = GetOutputSizePixel();
        if ( !mpFixedLine )
            mpFixedLine = new FixedLine( this );
        mpFixedLine->SetPosSizePixel( Point( 0, nOffY ),
                                      Size( aDlgSize.Width(), 2 ) );
        mpFixedLine->Show();
    }

    mbPosControls = FALSE;
}

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

TabDialog::TabDialog( Window* pParent, WinBits nStyle ) :
    Dialog( WINDOW_TABDIALOG )
{
    ImplInitTabDialogData();
    ImplInit( pParent, nStyle );
}

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

TabDialog::TabDialog( Window* pParent, const ResId& rResId ) :
    Dialog( WINDOW_TABDIALOG )
{
    ImplInitTabDialogData();
    rResId.SetRT( RSC_TABDIALOG );
    ImplInit( pParent, ImplInitRes( rResId ) );
    ImplLoadRes( rResId );
}

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

TabDialog::~TabDialog()
{
    if ( mpFixedLine )
        delete mpFixedLine;
}

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

void TabDialog::Resize()
{
// !!! In the future the controls should be automaticly rearrange
// !!! if the window is resized
// !!! if ( !IsRollUp() )
// !!!      ImplPosControls();
}

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

void TabDialog::StateChanged( StateChangedType nType )
{
    if ( nType == STATE_CHANGE_INITSHOW )
    {
        // Calculate the Layout only for the initialized state
        if ( mbPosControls )
            ImplPosControls();
    }
    Dialog::StateChanged( nType );
}

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

void TabDialog::AdjustLayout()
{
    ImplPosControls();
}
<|endoftext|>


<commit_before><commit_msg>typo in comment<commit_after><|endoftext|>


<commit_before>#ifndef VIENNAGRID_CONFIG_OTHERS_HPP
#define VIENNAGRID_CONFIG_OTHERS_HPP

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include "viennagrid/topology/quadrilateral.hpp"
#include "viennagrid/topology/hexahedron.hpp"

/** @file others.hpp
    @brief Provides default configuration classes for hypercube domains
*/

namespace viennagrid
{
  namespace config
  {
    /** @brief Predefined configuration class for two-dimensional hypercube cells (quadrilaterals) in a 2d geometry using Cartesian coordinates. */
    struct quadrilateral_2d
    {
      typedef double                                numeric_type;
      typedef viennagrid::cartesian_cs<2>           coordinate_system_tag;
      typedef viennagrid::quadrilateral_tag         cell_tag;
    };

    /** @brief Predefined configuration class for two-dimensional hypercube cells (quadrilaterals) in a 3d geometry using Cartesian coordinates. */
    struct quadrilateral_3d
    {
      typedef double                                numeric_type;
      typedef viennagrid::cartesian_cs<3>           coordinate_system_tag;
      typedef viennagrid::quadrilateral_tag         cell_tag;
    };

    /** @brief Predefined configuration class for three-dimensional hypercube cells (hexahedra) in a 3d geometry using Cartesian coordinates. */
    struct hexahedral_3d
    {
      typedef double                                numeric_type;
      typedef viennagrid::cartesian_cs<3>           coordinate_system_tag;
      typedef viennagrid::hexahedron_tag            cell_tag;
    };
  }
}

#endif
<commit_msg>added polygon_2d config<commit_after>#ifndef VIENNAGRID_CONFIG_OTHERS_HPP
#define VIENNAGRID_CONFIG_OTHERS_HPP

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include "viennagrid/topology/quadrilateral.hpp"
#include "viennagrid/topology/hexahedron.hpp"
#include "viennagrid/topology/polygon.hpp"

/** @file others.hpp
    @brief Provides default configuration classes for hypercube domains
*/

namespace viennagrid
{
  namespace config
  {
    /** @brief Predefined configuration class for two-dimensional hypercube cells (quadrilaterals) in a 2d geometry using Cartesian coordinates. */
    struct quadrilateral_2d
    {
      typedef double                                numeric_type;
      typedef viennagrid::cartesian_cs<2>           coordinate_system_tag;
      typedef viennagrid::quadrilateral_tag         cell_tag;
    };

    /** @brief Predefined configuration class for two-dimensional polygon cells in a 2d geometry using Cartesian coordinates. */
    struct polygon_2d
    {
      typedef double                                numeric_type;
      typedef viennagrid::cartesian_cs<2>           coordinate_system_tag;
      typedef viennagrid::polygon_tag               cell_tag;
    };

    /** @brief Predefined configuration class for two-dimensional hypercube cells (quadrilaterals) in a 3d geometry using Cartesian coordinates. */
    struct quadrilateral_3d
    {
      typedef double                                numeric_type;
      typedef viennagrid::cartesian_cs<3>           coordinate_system_tag;
      typedef viennagrid::quadrilateral_tag         cell_tag;
    };

    /** @brief Predefined configuration class for three-dimensional hypercube cells (hexahedra) in a 3d geometry using Cartesian coordinates. */
    struct hexahedral_3d
    {
      typedef double                                numeric_type;
      typedef viennagrid::cartesian_cs<3>           coordinate_system_tag;
      typedef viennagrid::hexahedron_tag            cell_tag;
    };
  }
}

#endif
<|endoftext|>