<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ecc/fw_mark_store.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>Adding ECC syndrome register access functions<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ecc/fw_mark_store.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 fw_mark_store.H
/// @brief Subroutines for the MC firmware mark store registers
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_FW_MARK_STORE_H_
#define _MSS_FW_MARK_STORE_H_

#include <fapi2.H>
#include <lib/mcbist/address.H>
#include <lib/utils/scom.H>
#include <lib/ecc/ecc_traits.H>
#include <lib/shared/mss_const.H>

namespace mss
{

namespace ecc
{

namespace fwms
{

///
/// @brief Read Firmware Mark Store (FWMS) register
/// @tparam R master rank number
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t R, fapi2::TargetType T, typename TT = eccTraits<T> >
inline fapi2::ReturnCode read_rank( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    static_assert((R < MAX_MRANK_PER_PORT), "Master rank index failed range check");
    FAPI_TRY( mss::getScom(i_target, (TT::FIRMWARE_MS0_REG + R), o_data) );
    FAPI_INF("read_rank<%d>: 0x%016lx", R, o_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 0 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank0( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<0>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 1 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank1( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<1>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 2 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank2( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<2>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 3 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank3( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<3>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 4 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank4( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<4>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 5 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank5( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<5>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 6 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank6( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<6>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) rank 7 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read_rank7( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    return ( read_rank<7>(i_target, o_data) );
}

///
/// @brief Read Firmware Mark Store (FWMS) register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_rank the master rank index
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode read( const fapi2::Target<T>& i_target,
                               const uint64_t i_rank,
                               fapi2::buffer<uint64_t>& o_data )
{
    switch (i_rank)
    {
        case(0):
            return ( read_rank0(i_target, o_data) );

        case(1):
            return ( read_rank1(i_target, o_data) );

        case(2):
            return ( read_rank2(i_target, o_data) );

        case(3):
            return ( read_rank3(i_target, o_data) );

        case(4):
            return ( read_rank4(i_target, o_data) );

        case(5):
            return ( read_rank5(i_target, o_data) );

        case(6):
            return ( read_rank6(i_target, o_data) );

        case(7):
            return ( read_rank7(i_target, o_data) );

        default:
            return fapi2::FAPI2_RC_INVALID_PARAMETER;
    }
}

///
/// @brief Write Firmware Mark Store (FWMS) register
/// @tparam R master rank number
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t R, fapi2::TargetType T, typename TT = eccTraits<T> >
inline fapi2::ReturnCode write_rank( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    static_assert((R < MAX_MRANK_PER_PORT), "Master rank index failed range check");
    FAPI_TRY( mss::putScom(i_target, (TT::FIRMWARE_MS0_REG + R), i_data) );
    FAPI_INF("write_rank<%d>: 0x%016lx", R, i_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 0 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank0( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<0>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 1 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank1( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<1>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 2 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank2( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<2>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 3 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank3( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<3>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 4 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank4( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<4>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 5 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank5( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<5>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 6 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank6( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<6>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) rank 7 register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write_rank7( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    return ( write_rank<7>(i_target, i_data) );
}

///
/// @brief Write Firmware Mark Store (FWMS) register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_rank the master rank index
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T >
inline fapi2::ReturnCode write( const fapi2::Target<T>& i_target,
                                const uint64_t i_rank,
                                const fapi2::buffer<uint64_t>& i_data )
{
    switch (i_rank)
    {
        case(0):
            return ( write_rank0(i_target, i_data) );

        case(1):
            return ( write_rank1(i_target, i_data) );

        case(2):
            return ( write_rank2(i_target, i_data) );

        case(3):
            return ( write_rank3(i_target, i_data) );

        case(4):
            return ( write_rank4(i_target, i_data) );

        case(5):
            return ( write_rank5(i_target, i_data) );

        case(6):
            return ( write_rank6(i_target, i_data) );

        case(7):
            return ( write_rank7(i_target, i_data) );

        default:
            return fapi2::FAPI2_RC_INVALID_PARAMETER;
    }
}

///
/// @brief set_mark
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in, out] io_data the register value
/// @param[in] i_value the value of the field
/// @note FWMS0_MARK: mark (Galois field code)
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void set_mark( fapi2::buffer<uint64_t>& io_data, const uint64_t i_value )
{
    io_data.insertFromRight<TT::FIRMWARE_MS_MARK, TT::FIRMWARE_MS_MARK_LEN>(i_value);
    FAPI_INF("set_mark: 0x%02lx", i_value);
}

///
/// @brief get_mark
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_data the register value
/// @param[out] o_value the value of the field
/// @note FWMS0_MARK: mark (Galois field code)
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void get_mark( const fapi2::buffer<uint64_t>& i_data, uint64_t& o_value )
{
    i_data.extractToRight<TT::FIRMWARE_MS_MARK, TT::FIRMWARE_MS_MARK_LEN>(o_value);
    FAPI_INF("get_mark: 0x%02lx", o_value);
}

///
/// @brief set_type
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in, out] io_data the register value
/// @param[in] i_value the value of the field
/// @note FWMS0_TYPE: mark type
/// @note Dial enums:
/// @note SYMBOL=>0b1
/// @note CHIP=>0b0
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void set_type( fapi2::buffer<uint64_t>& io_data, const uint64_t i_value )
{
    io_data.writeBit<TT::FIRMWARE_MS_TYPE>(i_value);
    FAPI_INF("set_type: 0x%01lx", i_value);
}

///
/// @brief get_type
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_data the register value
/// @param[out] o_value the value of the field
/// @note FWMS0_TYPE: mark type
/// @note Dial enums:
/// @note SYMBOL=>0b1
/// @note CHIP=>0b0
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void get_type( const fapi2::buffer<uint64_t>& i_data, uint64_t& o_value )
{
    o_value = i_data.getBit<TT::FIRMWARE_MS_TYPE>();
    FAPI_INF("get_type: 0x%01lx", o_value);
}

///
/// @brief set_region
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in, out] io_data the register value
/// @param[in] i_value the value of the field
/// @note FWMS0_REGION: Selects mark region (address range to which mark applies)
/// @note Dial enums:
/// @note DISABLED=>0b000
/// @note RESERVED=>0b001
/// @note BANK=>0b010
/// @note BANKGROUP=>0b011
/// @note SRANK=>0b100
/// @note MRANK=>0b101
/// @note DIMM=>0b110
/// @note UNIVERSAL=>0b111
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void set_region( fapi2::buffer<uint64_t>& io_data, const uint64_t i_value )
{
    io_data.insertFromRight<TT::FIRMWARE_MS_REGION, TT::FIRMWARE_MS_REGION_LEN>(i_value);
    FAPI_INF("set_region: 0x%02lx", i_value);
}

///
/// @brief get_region
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_data the register value
/// @param[out] o_value the value of the field
/// @note FWMS0_REGION: Selects mark region (address range to which mark applies)
/// @note Dial enums:
/// @note DISABLED=>0b000
/// @note RESERVED=>0b001
/// @note BANK=>0b010
/// @note BANKGROUP=>0b011
/// @note SRANK=>0b100
/// @note MRANK=>0b101
/// @note DIMM=>0b110
/// @note UNIVERSAL=>0b111
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void get_region( const fapi2::buffer<uint64_t>& i_data, uint64_t& o_value )
{
    i_data.extractToRight<TT::FIRMWARE_MS_REGION, TT::FIRMWARE_MS_REGION_LEN>(o_value);
    FAPI_INF("get_region: 0x%02lx", o_value);
}

///
/// @brief set_address
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in, out] io_data the register value
/// @param[in] i_address mcbist::address form of address field
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void set_address( fapi2::buffer<uint64_t>& io_data, const mcbist::address& i_address)
{
    // construct fwms::address from mcbist::address
    const auto l_addr = address<T>(i_address);
    io_data.insert<TT::FIRMWARE_MS_ADDRESS, TT::FIRMWARE_MS_ADDRESS_LEN, TT::FIRMWARE_MS_ADDRESS>(l_addr);
    FAPI_INF("set_address: 0x%016lx", uint64_t(l_addr));
}

///
/// @brief get_address
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_data the register value
/// @param[out] o_address mcbist::address form of address field
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void get_address( const fapi2::buffer<uint64_t>& i_data, mcbist::address& o_address )
{
    // construct fwms::address from i_data
    const auto l_addr = address<T>(uint64_t(i_data));
    // construct mcbist::address from fwms::address
    o_address = mcbist::address(l_addr);
    FAPI_INF("get_address: 0x%016lx", uint64_t(l_addr));
}

///
/// @brief set_exit_1
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in, out] io_data the register value
/// @param[in] i_state mss::YES or mss::NO - desired state
/// @note FWMS0_EXIT_1: When set, bypass-enabled reads using this mark will use exit 1
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void set_exit_1( fapi2::buffer<uint64_t>& io_data, const mss::states i_state )
{
    io_data.writeBit<TT::FIRMWARE_MS_EXIT1>(i_state);
    FAPI_INF("set_exit_1: 0x%01lx", i_state);
}

///
/// @brief get_exit_1
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_data the register value
/// @param[out] o_state mss::YES or mss::NO - representing the state of the field
/// @note FWMS0_EXIT_1: When set, bypass-enabled reads using this mark will use exit 1
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void get_exit_1( const fapi2::buffer<uint64_t>& i_data, mss::states& o_state )
{
    o_state = (i_data.getBit<TT::FIRMWARE_MS_EXIT1>() == false) ? mss::NO : mss::YES;
    FAPI_INF("get_exit_1: 0x%01lx", o_state);
}

} // close namespace fwms

} // close namespace ecc

} // close namespace mss

#endif
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2015 Daniel Mansfield

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef CREATURE_HPP
#define CREATURE_HPP

#include "entity.hpp"
#include "inventory.hpp"
#include "weapon.hpp"
#include "armour.hpp"

#include <string>
#include <fstream>
#include "JsonBox.h"

class Creature : public Entity
{
	public:

	// Name of the creature and the name of its class, if it has one
	// Class may be Fighter, Rogue etc
	std::string name;
	std::string className;

	// Creature stats. Reasonable values are in parentheses
	int health;		// Current hit points (10-1000+)
	int maxHealth;	// Maximum hit points (10-1000+)
	int str;		// Strength. Determines damage in battle (1-100)
	int end;		// Endurance. Determines maximum health (1-100)
	int dex;		// Dexterity. Determines speed in battle (1-100)
	double hitRate;	// Modifier to hit chance. (1-150)

	// Current level of the creature. Determines the amount of experience
	// that it gives to the victor when defeated (see Battle class for more)
	// and the amount of experience required to level up again. Upon
	// levelling up the creature will gain stat improvements.
	// 1-50 is reasonable
	unsigned int level;

	// Current experience. 0-1M is reasonable, see the levelup() function
	// for a decent scale
	unsigned int exp;

	// Items that the creature possesses
	Inventory inventory;

	// Currently equipped weapon. Used as a pointer to an atlas entry,
	// but not necessary. nullptr denotes that no weapon is equipped
	Weapon* equippedWeapon;

	// Armour currently equipped into each slot
	Armour* equippedArmour[Armour::Slot::N];

	Creature(std::string id, std::string name, int health, int str, int end, int dex, double hitRate,
		unsigned int level = 1, std::string className = "") : Entity(id)
	{
		this->name = name;
		this->health = health;
		this->maxHealth = health;
		this->str = str;
		this->end = end;
		this->dex = dex;
		this->hitRate = hitRate;
		this->className = className;
		this->equippedArmour[Armour::Slot::HEAD] = nullptr;
		this->equippedArmour[Armour::Slot::TORSO] = nullptr;
		this->equippedArmour[Armour::Slot::LEGS] = nullptr;
		this->equippedWeapon = nullptr;
		this->level = level;
		this->exp = 0;
	}

	Creature() : Entity("nullid")
	{
		this->equippedArmour[Armour::Slot::HEAD] = nullptr;
		this->equippedArmour[Armour::Slot::TORSO] = nullptr;
		this->equippedArmour[Armour::Slot::LEGS] = nullptr;
		this->equippedWeapon = nullptr;
		this->level = 1;
		this->exp = 0;
	}

	// Equip a weapon by setting the equipped weapon pointer. Currently
	// a pointless function (simple enough to be rewritten each time)
	// but handy if dual wielding is ever added, or shields etc
	void equipWeapon(Weapon* weapon)
	{
		this->equippedWeapon = weapon;

		return;
	}

	// Equip the armour into it's correct slot. A slightly more useful
	// function!
	void equipArmour(Armour* armour)
	{
		this->equippedArmour[(int)armour->slot] = armour;

		return;
	}

	// Calculates the experience required to reach a certain level,
	// *in total*. Really this is class specific and not object specific
	unsigned int expToLevel(unsigned int level)
	{
		// Exp to level x = 128*x^2
		return 128 * level * level;
	}

	// Level the creature to the next level if it has enough experience
	// to do so, returning true if it could level up and false otherwise.
	bool levelUp()
	{
		// We want the experience to the next level, not the current level
		if(this->exp >= expToLevel(this->level+1))
		{
			// Advance to the next level
			++level;

			// Variables to keep track of stat changes. Neater than
			// having a bunch of stat increases all over the place,
			// and removes the issue of the next level's stats affecting
			// themselves (increasing endurance then increasing health
			// based on the boosted instead of the original value, for
			// example
			unsigned int healthBoost = 0;
			unsigned int strBoost = 0;
			unsigned int endBoost = 0;
			unsigned int dexBoost = 0;

			// Give a large boost to health every third level
			if(level % 3 == 0)
			{
				// Randomly increase health, but always give a sizeable
				// chunk proportional to the creature's endurance
				healthBoost = 10 + (rand() % 4) + this->end / 4;
			}
			else
			{
				// Just increase health by a small amount
				healthBoost = this->end / 4;
			}
			// If the creature is a fighter, then favour strength and
			// endurance boosts over dexterity, but increase dexterity
			// 50% of the time too
			if(this->className == "Fighter")
			{
				strBoost = 1;
				endBoost = 1;
				if(rand() % 2 == 0) dexBoost = 1;
			}
			// Same as for fighter but favour dexterity and endurance
			// instead. Rogue's favour endurance too in order to keep
			// them at roughly the same capability
			else if(this->className == "Rogue")
			{
				endBoost = 1;
				dexBoost = 1;
				if(rand() % 2 == 0) strBoost = 1;
			}

			// Adjust all of the variables accordingly
			this->maxHealth += healthBoost;
			this->str += strBoost;
			this->end += endBoost;
			this->dex += dexBoost;

			// Tell the user that they grew a level, what the boosts where
			// and what their stats are now
			std::cout << this->name << " grew to level " << level << "!\n";
			std::cout << "Health +" << healthBoost << " -> " << this->maxHealth << std::endl;
			std::cout << "Str +" << strBoost << " -> " << this->str << std::endl;
			std::cout << "End +" << endBoost << " -> " << this->end << std::endl;
			std::cout << "Dex +" << dexBoost << " -> " << this->dex<< std::endl;
			std::cout << "----------------\n";

			return true;
		}
		return false;
	}

	// Save the creature's data to a JSON file named according to the name
	// of the creature
	void save()
	{
		JsonBox::Object o;
		o["name"] = JsonBox::Value(this->name);
		o["className"] = JsonBox::Value(this->className);
		o["health"] = JsonBox::Value(this->health);
		o["maxHealth"] = JsonBox::Value(this->maxHealth);
		o["str"] = JsonBox::Value(this->str);
		o["end"] = JsonBox::Value(this->end);
		o["dex"] = JsonBox::Value(this->dex);
		o["hitRate"] = JsonBox::Value(this->hitRate);
		o["level"] = JsonBox::Value(int(this->level));
		o["exp"] = JsonBox::Value(int(this->exp));
		o["inventory"] = JsonBox::Value(this->inventory.to_json());
		o["equipped_weapon"] = JsonBox::Value(this->equippedWeapon == nullptr ? "nullptr" : this->equippedWeapon->id);
		JsonBox::Array a;
		for(auto armour : this->equippedArmour)
		{
			a.push_back(armour == nullptr ? "nullptr" : armour->id);
		}
		o["equipped_armour"] = a;
		JsonBox::Value v(o);
		v.writeToFile(this->name + ".json");

		return;
	}

	// Attempt to load the creature's data from the given JSON file
	bool load(std::string name,
		std::map<std::string, Item>& itemAtlas,
		std::map<std::string, Weapon>& weaponAtlas,
		std::map<std::string, Armour>& armourAtlas)
	{
		// Check for existence then open using JsonBox if it exists
		std::ifstream f((name + ".json").c_str());
		if(f.good())
		{
			f.close();
			JsonBox::Value v;
			v.loadFromFile(name + ".json");
			JsonBox::Object o = v.getObject();
			this->name = o["name"].getString();;
			this->className = o["className"].getString();
			this->health = o["health"].getInteger();
			this->maxHealth = o["maxHealth"].getInteger();
			this->str = o["str"].getInteger();
			this->end = o["end"].getInteger();
			this->dex = o["dex"].getInteger();
			this->hitRate = o["hitRate"].getDouble();
			this->level = o["level"].getInteger();
			this->exp = o["exp"].getInteger();
			this->inventory = Inventory(o["inventory"], itemAtlas, weaponAtlas, armourAtlas);

			std::string equippedWeaponName = o["equipped_weapon"].getString();
			this->equippedWeapon = equippedWeaponName == "nullptr" ? nullptr : &weaponAtlas[equippedWeaponName];

			JsonBox::Array a = o["equipped_amour"].getArray();
			for(int i = 0; i < a.size(); ++i)
			{
				std::string equippedArmourName = a[i].getString();
				this->equippedArmour[i] = equippedArmourName == "nullptr" ? nullptr : &armourAtlas[equippedArmourName];
			}

			return true;
		}
		else
		{
			f.close();
			return false;
		}
	}
};

#endif /* CREATURE_HPP */
<commit_msg>Made optional constructor arguments optional in JSON<commit_after>/*
The MIT License (MIT)

Copyright (c) 2015 Daniel Mansfield

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef CREATURE_HPP
#define CREATURE_HPP

#include "entity.hpp"
#include "inventory.hpp"
#include "weapon.hpp"
#include "armour.hpp"

#include <string>
#include <fstream>
#include "JsonBox.h"

class Creature : public Entity
{
	public:

	// Name of the creature and the name of its class, if it has one
	// Class may be Fighter, Rogue etc
	std::string name;
	std::string className;

	// Creature stats. Reasonable values are in parentheses
	int health;		// Current hit points (10-1000+)
	int maxHealth;	// Maximum hit points (10-1000+)
	int str;		// Strength. Determines damage in battle (1-100)
	int end;		// Endurance. Determines maximum health (1-100)
	int dex;		// Dexterity. Determines speed in battle (1-100)
	double hitRate;	// Modifier to hit chance. (1-150)

	// Current level of the creature. Determines the amount of experience
	// that it gives to the victor when defeated (see Battle class for more)
	// and the amount of experience required to level up again. Upon
	// levelling up the creature will gain stat improvements.
	// 1-50 is reasonable
	unsigned int level;

	// Current experience. 0-1M is reasonable, see the levelup() function
	// for a decent scale
	unsigned int exp;

	// Items that the creature possesses
	Inventory inventory;

	// Currently equipped weapon. Used as a pointer to an atlas entry,
	// but not necessary. nullptr denotes that no weapon is equipped
	Weapon* equippedWeapon;

	// Armour currently equipped into each slot
	Armour* equippedArmour[Armour::Slot::N];

	Creature(std::string id, std::string name, int health, int str, int end, int dex, double hitRate,
		unsigned int level = 1, std::string className = "") : Entity(id)
	{
		this->name = name;
		this->health = health;
		this->maxHealth = health;
		this->str = str;
		this->end = end;
		this->dex = dex;
		this->hitRate = hitRate;
		this->className = className;
		this->equippedArmour[Armour::Slot::HEAD] = nullptr;
		this->equippedArmour[Armour::Slot::TORSO] = nullptr;
		this->equippedArmour[Armour::Slot::LEGS] = nullptr;
		this->equippedWeapon = nullptr;
		this->level = level;
		this->exp = 0;
	}

	Creature() : Entity("nullid")
	{
		this->equippedArmour[Armour::Slot::HEAD] = nullptr;
		this->equippedArmour[Armour::Slot::TORSO] = nullptr;
		this->equippedArmour[Armour::Slot::LEGS] = nullptr;
		this->equippedWeapon = nullptr;
		this->level = 1;
		this->exp = 0;
	}

	// Equip a weapon by setting the equipped weapon pointer. Currently
	// a pointless function (simple enough to be rewritten each time)
	// but handy if dual wielding is ever added, or shields etc
	void equipWeapon(Weapon* weapon)
	{
		this->equippedWeapon = weapon;

		return;
	}

	// Equip the armour into it's correct slot. A slightly more useful
	// function!
	void equipArmour(Armour* armour)
	{
		this->equippedArmour[(int)armour->slot] = armour;

		return;
	}

	// Calculates the experience required to reach a certain level,
	// *in total*. Really this is class specific and not object specific
	unsigned int expToLevel(unsigned int level)
	{
		// Exp to level x = 128*x^2
		return 128 * level * level;
	}

	// Level the creature to the next level if it has enough experience
	// to do so, returning true if it could level up and false otherwise.
	bool levelUp()
	{
		// We want the experience to the next level, not the current level
		if(this->exp >= expToLevel(this->level+1))
		{
			// Advance to the next level
			++level;

			// Variables to keep track of stat changes. Neater than
			// having a bunch of stat increases all over the place,
			// and removes the issue of the next level's stats affecting
			// themselves (increasing endurance then increasing health
			// based on the boosted instead of the original value, for
			// example
			unsigned int healthBoost = 0;
			unsigned int strBoost = 0;
			unsigned int endBoost = 0;
			unsigned int dexBoost = 0;

			// Give a large boost to health every third level
			if(level % 3 == 0)
			{
				// Randomly increase health, but always give a sizeable
				// chunk proportional to the creature's endurance
				healthBoost = 10 + (rand() % 4) + this->end / 4;
			}
			else
			{
				// Just increase health by a small amount
				healthBoost = this->end / 4;
			}
			// If the creature is a fighter, then favour strength and
			// endurance boosts over dexterity, but increase dexterity
			// 50% of the time too
			if(this->className == "Fighter")
			{
				strBoost = 1;
				endBoost = 1;
				if(rand() % 2 == 0) dexBoost = 1;
			}
			// Same as for fighter but favour dexterity and endurance
			// instead. Rogue's favour endurance too in order to keep
			// them at roughly the same capability
			else if(this->className == "Rogue")
			{
				endBoost = 1;
				dexBoost = 1;
				if(rand() % 2 == 0) strBoost = 1;
			}

			// Adjust all of the variables accordingly
			this->maxHealth += healthBoost;
			this->str += strBoost;
			this->end += endBoost;
			this->dex += dexBoost;

			// Tell the user that they grew a level, what the boosts where
			// and what their stats are now
			std::cout << this->name << " grew to level " << level << "!\n";
			std::cout << "Health +" << healthBoost << " -> " << this->maxHealth << std::endl;
			std::cout << "Str +" << strBoost << " -> " << this->str << std::endl;
			std::cout << "End +" << endBoost << " -> " << this->end << std::endl;
			std::cout << "Dex +" << dexBoost << " -> " << this->dex<< std::endl;
			std::cout << "----------------\n";

			return true;
		}
		return false;
	}

	// Save the creature's data to a JSON file named according to the name
	// of the creature
	void save()
	{
		JsonBox::Object o;
		o["name"] = JsonBox::Value(this->name);
		o["className"] = JsonBox::Value(this->className);
		o["health"] = JsonBox::Value(this->health);
		o["maxHealth"] = JsonBox::Value(this->maxHealth);
		o["str"] = JsonBox::Value(this->str);
		o["end"] = JsonBox::Value(this->end);
		o["dex"] = JsonBox::Value(this->dex);
		o["hitRate"] = JsonBox::Value(this->hitRate);
		o["level"] = JsonBox::Value(int(this->level));
		o["exp"] = JsonBox::Value(int(this->exp));
		o["inventory"] = JsonBox::Value(this->inventory.to_json());
		o["equipped_weapon"] = JsonBox::Value(this->equippedWeapon == nullptr ? "nullptr" : this->equippedWeapon->id);
		JsonBox::Array a;
		for(auto armour : this->equippedArmour)
		{
			a.push_back(armour == nullptr ? "nullptr" : armour->id);
		}
		o["equipped_armour"] = a;
		JsonBox::Value v(o);
		v.writeToFile(this->name + ".json");

		return;
	}

	// Attempt to load the creature's data from the given JSON file
	bool load(std::string name,
		std::map<std::string, Item>& itemAtlas,
		std::map<std::string, Weapon>& weaponAtlas,
		std::map<std::string, Armour>& armourAtlas)
	{
		// Check for existence then open using JsonBox if it exists
		std::ifstream f((name + ".json").c_str());
		if(f.good())
		{
			f.close();
			JsonBox::Value v;
			v.loadFromFile(name + ".json");
			JsonBox::Object o = v.getObject();
			this->name = o["name"].getString();
			// Set className if it exists
			if(o.find("className") != o.end())
			{
				this->className = o["className"].getString();
			}
			else
			{
				this->className = "";
			}
			this->health = o["health"].getInteger();
			if(o.find("maxHealth") != o.end())
			{
				this->maxHealth = o["maxHealth"].getInteger();
			}
			else
			{
				this->maxHealth = this->health;
			}
			this->str = o["str"].getInteger();
			this->end = o["end"].getInteger();
			this->dex = o["dex"].getInteger();
			this->hitRate = o["hitRate"].getDouble();
			this->level = o["level"].getInteger();
			if(o.find("exp") != o.end())
			{
				this->exp = o["exp"].getInteger();
			}
			else
			{
				this->exp = 0;
			}
			if(o.find("inventory") != o.end())
			{
				this->inventory = Inventory(o["inventory"], itemAtlas, weaponAtlas, armourAtlas);
			}
			if(o.find("equipped_weapon") != o.end())
			{
				std::string equippedWeaponName = o["equipped_weapon"].getString();
				this->equippedWeapon = equippedWeaponName == "nullptr" ? nullptr : &weaponAtlas[equippedWeaponName];
			}
			if(o.find("equipped_armour") != o.end())
			{
				JsonBox::Array a = o["equipped_amour"].getArray();
				for(int i = 0; i < a.size(); ++i)
				{
					std::string equippedArmourName = a[i].getString();
					this->equippedArmour[i] = equippedArmourName == "nullptr" ? nullptr : &armourAtlas[equippedArmourName];
				}
			}
			return true;
		}
		else
		{
			f.close();
			return false;
		}
	}
};

#endif /* CREATURE_HPP */
<|endoftext|>


<commit_before>#include "dbg_path.h"
#include <deque>
#include <algorithm>

namespace vscode
{
	fs::path path_uncomplete(const fs::path& path, const fs::path& base, std::error_code& ec)
	{
		fs::path npath = path_normalize(path);
		fs::path nbase = path_normalize(base);
		if (npath == nbase)
			return L"./";
		fs::path from_path, from_base, output;
		fs::path::iterator path_it = npath.begin(), path_end = npath.end();
		fs::path::iterator base_it = nbase.begin(), base_end = nbase.end();

		if ((path_it == path_end) || (base_it == base_end))
		{
			ec = std::make_error_code(std::errc::not_a_directory);
			return npath;
		}

#ifdef WIN32
		if (*path_it != *base_it)
			return npath;
		++path_it, ++base_it;
#endif

		while (true) {
			if ((path_it == path_end) || (base_it == base_end) || (*path_it != *base_it)) {
				for (; base_it != base_end; ++base_it) {
					if (*base_it == L".")
						continue;
					else if (*base_it == L"/")
						continue;

					output /= L"../";
				}
				fs::path::iterator path_it_start = path_it;
				for (; path_it != path_end; ++path_it) {

					if (path_it != path_it_start)
						output /= L"/";

					if (*path_it == L".")
						continue;
					if (*path_it == L"/")
						continue;

					output /= *path_it;
				}

				break;
			}
			from_path /= fs::path(*path_it);
			from_base /= fs::path(*base_it);
			++path_it, ++base_it;
		}

		return output;
	}

	fs::path path_normalize(const fs::path& p)
	{
		fs::path result = p.root_path();
		std::deque<std::wstring> stack;
		for (auto e : p.relative_path()) {
			if (e == L".." && !stack.empty() && stack.back() != L"..") {
				stack.pop_back();
			}
			else if (e != L".") {
#if _MSC_VER >= 1900
				stack.push_back(e.wstring());
#else
				stack.push_back(e);
#endif
			}
		}
		for (auto e : stack) {
			result /= e;
		}
		std::wstring ret = result.wstring();
		std::wstring tmp;
		tmp.resize(ret.size());
		std::transform(ret.begin(), ret.end(), tmp.begin(), tolower);
		return tmp;
	}

	bool path_is_subpath(const fs::path& path, const fs::path& base)
	{
		fs::path npath = path_normalize(path);
		fs::path::iterator path_it = npath.begin(), path_end = npath.end();
		fs::path::iterator base_it = base.begin(), base_end = base.end();

		for (;;)
		{
			if (base_it == base_end) {
				return true;
			}
			if (path_it == path_end) {
				return false;
			}
			if (*path_it != *base_it) {
				return false;
			}
			++path_it;
			++base_it;
		}
		return false;
	}
}
<commit_msg>修正一个错误<commit_after>#include "dbg_path.h"
#include <deque>
#include <algorithm>

namespace vscode
{
	fs::path path_uncomplete(const fs::path& path, const fs::path& base, std::error_code& ec)
	{
		fs::path npath = path_normalize(path);
		fs::path nbase = path_normalize(base);
		if (npath == nbase)
			return L"./";
		fs::path from_path, from_base, output;
		fs::path::iterator path_it = npath.begin(), path_end = npath.end();
		fs::path::iterator base_it = nbase.begin(), base_end = nbase.end();

		if ((path_it == path_end) || (base_it == base_end))
		{
			ec = std::make_error_code(std::errc::not_a_directory);
			return npath;
		}

#ifdef WIN32
		if (*path_it != *base_it)
			return npath;
		++path_it, ++base_it;
#endif

		while (true) {
			if ((path_it == path_end) || (base_it == base_end) || (*path_it != *base_it)) {
				for (; base_it != base_end; ++base_it) {
					if (*base_it == L".")
						continue;
					else if (*base_it == L"/")
						continue;

					output /= L"../";
				}
				fs::path::iterator path_it_start = path_it;
				for (; path_it != path_end; ++path_it) {

					if (path_it != path_it_start)
						output /= L"/";

					if (*path_it == L".")
						continue;
					if (*path_it == L"/")
						continue;

					output /= *path_it;
				}

				break;
			}
			from_path /= fs::path(*path_it);
			from_base /= fs::path(*base_it);
			++path_it, ++base_it;
		}

		return output;
	}

	fs::path path_normalize(const fs::path& p)
	{
		fs::path result = p.root_path();
		std::deque<std::wstring> stack;
		for (auto e : p.relative_path()) {
			if (e == L".." && !stack.empty() && stack.back() != L"..") {
				stack.pop_back();
			}
			else if (e != L".") {
#if _MSC_VER >= 1900
				stack.push_back(e.wstring());
#else
				stack.push_back(e);
#endif
			}
		}
		for (auto e : stack) {
			result /= e;
		}
		std::wstring ret = result.wstring();
		std::wstring tmp;
		tmp.resize(ret.size());
		std::transform(ret.begin(), ret.end(), tmp.begin(), towlower);
		return tmp;
	}

	bool path_is_subpath(const fs::path& path, const fs::path& base)
	{
		fs::path npath = path_normalize(path);
		fs::path::iterator path_it = npath.begin(), path_end = npath.end();
		fs::path::iterator base_it = base.begin(), base_end = base.end();

		for (;;)
		{
			if (base_it == base_end) {
				return true;
			}
			if (path_it == path_end) {
				return false;
			}
			if (*path_it != *base_it) {
				return false;
			}
			++path_it;
			++base_it;
		}
		return false;
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: salstd.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2004-01-06 14:25:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SALSTD_HXX
#define _SALSTD_HXX

// -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SV_SV_H
#include <sv.h>
#endif

// -=-= X-Lib forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef _SVUNX_H
typedef unsigned long       Pixel;
typedef unsigned long       XID;
typedef unsigned long       XLIB_Time;
typedef unsigned long       XtIntervalId;

typedef XID                 Colormap;
typedef XID                 Drawable;
typedef XID                 Pixmap;
typedef XID                 XLIB_Cursor;
typedef XID                 XLIB_Font;
typedef XID                 XLIB_Window;

typedef struct  _XDisplay   Display;
typedef struct  _XGC       *GC;
typedef struct  _XImage     XImage;
typedef struct  _XRegion   *XLIB_Region;

typedef union   _XEvent     XEvent;

typedef struct  _XConfigureEvent    XConfigureEvent;
typedef struct  _XReparentEvent     XReparentEvent;
typedef struct  _XClientMessageEvent        XClientMessageEvent;
typedef struct  _XErrorEvent        XErrorEvent;

struct  Screen;
struct  Visual;
struct  XColormapEvent;
struct  XFocusChangeEvent;
struct  XFontStruct;
struct  XKeyEvent;
struct  XPropertyEvent;
struct  XTextItem;
struct  XWindowChanges;

#define None    0L
#endif

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.546); FILE MERGED 2005/09/05 14:45:30 rt 1.3.546.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salstd.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:47:04 $
 *
 *  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 _SALSTD_HXX
#define _SALSTD_HXX

// -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SV_SV_H
#include <sv.h>
#endif

// -=-= X-Lib forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef _SVUNX_H
typedef unsigned long       Pixel;
typedef unsigned long       XID;
typedef unsigned long       XLIB_Time;
typedef unsigned long       XtIntervalId;

typedef XID                 Colormap;
typedef XID                 Drawable;
typedef XID                 Pixmap;
typedef XID                 XLIB_Cursor;
typedef XID                 XLIB_Font;
typedef XID                 XLIB_Window;

typedef struct  _XDisplay   Display;
typedef struct  _XGC       *GC;
typedef struct  _XImage     XImage;
typedef struct  _XRegion   *XLIB_Region;

typedef union   _XEvent     XEvent;

typedef struct  _XConfigureEvent    XConfigureEvent;
typedef struct  _XReparentEvent     XReparentEvent;
typedef struct  _XClientMessageEvent        XClientMessageEvent;
typedef struct  _XErrorEvent        XErrorEvent;

struct  Screen;
struct  Visual;
struct  XColormapEvent;
struct  XFocusChangeEvent;
struct  XFontStruct;
struct  XKeyEvent;
struct  XPropertyEvent;
struct  XTextItem;
struct  XWindowChanges;

#define None    0L
#endif

#endif

<|endoftext|>


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

#ifndef FASTA_IO_HPP_
#define FASTA_IO_HPP_

#include <string>
#include <vector>
#include <iostream>

namespace fastq_io {
int ReadRecode(std::istream &istream, std::string &header,
		std::string &sequence, std::string &quality);
int WriteRecode(std::ostream &ostream, const std::string &header,
		const std::string &sequence, std::string &quality);

}

#endif /* FASTA_IO_HPP_ */
<commit_msg>Update fastq_io.hpp<commit_after>/*
 * fasta_io.hpp
 *
 *   Copyright (c) 2013, Shuji Suzuki
 *   All rights reserved.
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *   1. Redistributions of source code must retain the above Copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above Copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 *   PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *   HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 *   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#ifndef FASTQ_IO_HPP_
#define FASTQ_IO_HPP_

#include <string>
#include <vector>
#include <iostream>

namespace fastq_io {
int ReadRecode(std::istream &istream, std::string &header,
		std::string &sequence, std::string &quality);
int WriteRecode(std::ostream &ostream, const std::string &header,
		const std::string &sequence, std::string &quality);

}

#endif /* FASTQ_IO_HPP_ */
<|endoftext|>


<commit_before>#ifndef FUNCTION_HXX_
#define FUNCTION_HXX_

#include <string>

namespace tglng {
  class Interpreter;

  /**
   * A Function is a special command (or command variant) which is dynamically
   * invokable. In particular, it must fulfil the following properties:
   * + It must be immutable, having no state other than the interpreter in
   *   which it runs.
   * + It must have a fixed arity.
   * + It can only take strings as arguments.
   *
   * The arity of a Function is expressed as
   *   numoutputs <- numinputs
   * Where numinputs and numoutputs are non-negative integers. Note in
   * particular that a Function may return multiple values.
   *
   * Symbolically, a certain type of Function (ie, based on the task it is
   * expected to perform) is written as
   *   (output0, output1) <- (input0, input1)
   */
  class Function {
  public:
    /**
     * The function pointer type which performs a Function's actual work.
     *
     * The callee need not worry about the size of the arrays; it may assume
     * they are the correct size.
     *
     * @param out An array of output strings, assumed to be equal in size to
     * this Function's outputArity. The contents of these strings is undefined
     * when the Function is executed. The callee may alter them arbitrarily,
     * leaving the desired result in each when returning successfully.
     * @param in An array of input strings, assumed to be equal in size to this
     * Function's inputArity.
     * @param interp The Interpreter in which the Function is being run.
     * @return Whether the function succeeded.
     */
    typedef bool (*exec_t)(std::wstring& out, const std::wstring& in,
                           Interpreter&);

    /**
     * The number of output arguments this Function takes.
     */
    unsigned outputArity;

    /**
     * The number of input arguments this Function takes.
     */
    unsigned inputArity;

    /**
     * Call to invoke the Function.
     *
     * @see Function::exec_t
     */
    exec_t exec;

    /**
     * Constructs an invalid Function.
     */
    Function()
    : outputArity(0), inputArity(0), exec(NULL)
    { }

    /**
     * Constructs a Function with the given parms.
     *
     * @param outputArity_ The number of output arguments this Function will
     * take.
     * @param inputArity_ The number of input arguments this Function will take.
     * @param exec_ The implementation of this Function.
     */
    Function(unsigned outputArity_, unsigned inputArity_, exec_t exec_)
    : outputArity(outputArity_), inputArity(inputArity_), exec(exec_)
    { }

    /**
     * Checks whether this Function matches the given arity, in output,input
     * order.
     *
     * @param outputArity The number of output arguments the caller expects.
     * @param inputArity The number of input arguments the caller expects.
     * @return Whether the actual arity matches the expected.
     */
    bool matches(unsigned outputArity, unsigned inputArity) const {
      return this->outputArity == outputArity && this->inputArity == inputArity;
    }

    /**
     * Checks whether this Function is "compatible" with the given expected
     * arity, in output,input order.
     *
     * A Function is compatible with an arity if the actual number of arguments
     * is less than or equal to the expected number of arguments for both
     * inputs. This means that a "compatible" Function may ignore some of its
     * inputs, and may not alter some of its outputs. This means that a caller
     * which uses this behaviour should set the outputs to something reasonable
     * before calling the function.
     */
    bool compatible(unsigned outputArity, unsigned inputArity) const {
      return this->outputArity <= outputArity && this->inputArity <= inputArity;
    }
  };
}

#endif /* FUNCTION_HXX_ */
<commit_msg>Correct argument types in Function::exec_t.<commit_after>#ifndef FUNCTION_HXX_
#define FUNCTION_HXX_

#include <string>

namespace tglng {
  class Interpreter;

  /**
   * A Function is a special command (or command variant) which is dynamically
   * invokable. In particular, it must fulfil the following properties:
   * + It must be immutable, having no state other than the interpreter in
   *   which it runs.
   * + It must have a fixed arity.
   * + It can only take strings as arguments.
   *
   * The arity of a Function is expressed as
   *   numoutputs <- numinputs
   * Where numinputs and numoutputs are non-negative integers. Note in
   * particular that a Function may return multiple values.
   *
   * Symbolically, a certain type of Function (ie, based on the task it is
   * expected to perform) is written as
   *   (output0, output1) <- (input0, input1)
   */
  class Function {
  public:
    /**
     * The function pointer type which performs a Function's actual work.
     *
     * The callee need not worry about the size of the arrays; it may assume
     * they are the correct size.
     *
     * @param out An array of output strings, assumed to be equal in size to
     * this Function's outputArity. The contents of these strings is undefined
     * when the Function is executed. The callee may alter them arbitrarily,
     * leaving the desired result in each when returning successfully.
     * @param in An array of input strings, assumed to be equal in size to this
     * Function's inputArity.
     * @param interp The Interpreter in which the Function is being run.
     * @return Whether the function succeeded.
     */
    typedef bool (*exec_t)(std::wstring* out, const std::wstring* in,
                           Interpreter&);

    /**
     * The number of output arguments this Function takes.
     */
    unsigned outputArity;

    /**
     * The number of input arguments this Function takes.
     */
    unsigned inputArity;

    /**
     * Call to invoke the Function.
     *
     * @see Function::exec_t
     */
    exec_t exec;

    /**
     * Constructs an invalid Function.
     */
    Function()
    : outputArity(0), inputArity(0), exec(NULL)
    { }

    /**
     * Constructs a Function with the given parms.
     *
     * @param outputArity_ The number of output arguments this Function will
     * take.
     * @param inputArity_ The number of input arguments this Function will take.
     * @param exec_ The implementation of this Function.
     */
    Function(unsigned outputArity_, unsigned inputArity_, exec_t exec_)
    : outputArity(outputArity_), inputArity(inputArity_), exec(exec_)
    { }

    /**
     * Checks whether this Function matches the given arity, in output,input
     * order.
     *
     * @param outputArity The number of output arguments the caller expects.
     * @param inputArity The number of input arguments the caller expects.
     * @return Whether the actual arity matches the expected.
     */
    bool matches(unsigned outputArity, unsigned inputArity) const {
      return this->outputArity == outputArity && this->inputArity == inputArity;
    }

    /**
     * Checks whether this Function is "compatible" with the given expected
     * arity, in output,input order.
     *
     * A Function is compatible with an arity if the actual number of arguments
     * is less than or equal to the expected number of arguments for both
     * inputs. This means that a "compatible" Function may ignore some of its
     * inputs, and may not alter some of its outputs. This means that a caller
     * which uses this behaviour should set the outputs to something reasonable
     * before calling the function.
     */
    bool compatible(unsigned outputArity, unsigned inputArity) const {
      return this->outputArity <= outputArity && this->inputArity <= inputArity;
    }
  };
}

#endif /* FUNCTION_HXX_ */
<|endoftext|>


<commit_before>#include "../include/generator.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

generator::generator(string s1, string s2, string s3, string s4, string s5, string s6, string s7)
{
	sTemplates = s1;
	sTemp = s2;
	sMake = s3;
	sShow = s4;
	sClass = s5;
	sTestName = s6;
	sTestDate = s7;
}
MyDir::dirlist generator::getAllTests(string sPath)
{
	MyDir::dirlist _dirlist = MyDir::getAllSubdirs(sPath);
	ifstream testfile;
	MyDir::dirlist availableTests;
	for(int i = 0; i < _dirlist.size(); i++) //check all directories for available tests
	{
		testfile.open(sPath + "/" + _dirlist[i] + "/test");
		if(!testfile.is_open())
		{
			cout << "can't open " << _dirlist[i] << endl;
			continue;
		}
		testfile.close();
		availableTests.push_back(sPath + "/" + _dirlist[i]);
	}
	return availableTests;
}
void generator::showAvailableTests(string sPath)
{
	ifstream templatefile;
	templatefile.open(sTemplates + "/templatebase/test");
	if(!templatefile.is_open())
	{
		cout << "can't open templatebase/test";
		throw 0;
	}
	MyDir::dirlist availableTests = getAllTests(sPath);
	generateTest(availableTests, sTemp + "/testgenerator");
	createNamesTex(sTemp + "/testgenerator", true);
	string s = "cd " + sTemp + "/testgenerator;" + sMake + " " + sTemp + "/testgenerator/main.tex";
	command::exec(s.c_str());
	command::threadexec((sShow + " " + sTemp + "/testgenerator/main.pdf&").c_str());
}
void generator::generateTestFromSelectionString(string sPath, string sSelect, string sSavePath)
{
	vector<int> iSelectedNumbers;
	vector<string> strs;
	boost::split(strs, sSelect, boost::is_any_of(","));
	for(int i = 0; i < strs.size(); i++)
		iSelectedNumbers.push_back(boost::lexical_cast<int>(strs[i]) - 1);
	MyDir::dirlist selectedTests;
	MyDir::dirlist availableTests = getAllTests(sPath);
	for(int i = 0; i < iSelectedNumbers.size(); i++)
		selectedTests.push_back(availableTests[iSelectedNumbers[i]]);
	generateTest(selectedTests, sSavePath);
	createNamesTex(sSavePath, false);
	string s = "cd " + sSavePath + ";" + sMake + " " + "main.tex";
	command::exec(s.c_str());
	command::threadexec((sShow + " " + sSavePath + "/main.pdf&").c_str());

}

void generator::createNamesTex(string sPath, bool bOverview)
{
	ofstream file(sPath + "/names.tex");
	if(!file.is_open())
	{
		cout << "can't write names.tex" << endl;
		throw 0;
	}
	file << "\\newcommand{\\myclassname}[0]{" << (bOverview ? "" : sClass) << "}" << endl;
	file << "\\newcommand{\\mytitle}[0]{" << (bOverview ? "" : sTestName) << "}" << endl;
	file << "\\newcommand{\\testdate}[0]{" << (bOverview ? "" : sTestDate) << "}" << endl;
	file.close();
}

void generator::createFromOneExercise(string s)
{
	generator::dirlist list;
	list.push_back(s);
	generator::generateTest(list, sTemp + "/testgenerator");
	createNamesTex(sTemp + "/testgenerator", true);
	s = "cd " + sTemp + "/testgenerator;" + sMake + " " + "main.tex";
	command::printoutput(command::exec(s.c_str()));
	command::threadexec((sShow + " " + sTemp + "/testgenerator/main.pdf&").c_str());
}
void generator::generateTest(generator::dirlist _dirlist, string sSavePath)
{
	string line;
	ofstream generatedtest;
	MyDir::createDir(sSavePath);
	generatedtest.open(sSavePath + "/main.tex", ios::trunc);
	if(!generatedtest.is_open())
	{
		cout << "can't write main.tex" << endl;
		throw 0;
	}
	ifstream templatefile;
	templatefile.open(sTemplates + "/templatebase/test");
	if(!templatefile.is_open())
	{
		cout << "can't open templatebase/test";
		throw 0;
	}

	while(true)//writing generated test until content
	{
		getline(templatefile, line);
		if(line == "#CONTENT")
			break;
		generatedtest << line << endl;
	}

	ifstream testfile;
	int iTestNr = 1;
	for(int i = 0; i < _dirlist.size(); i++)
	{
		testfile.open(_dirlist[i] + "/test");
		if(!testfile.is_open())
			cout << "can'r open " << _dirlist[i] << "/test" << endl;
		vector<string> testcontent;
		while(getline(testfile, line))
			testcontent.push_back(line);
		cout << "testcontent size " << testcontent.size() << endl;
		char cSubtask = 'a';
		bool bSubtasks = false;
		bool bInMulticol = false;
		int iBE;
		for(int j = 1; j < testcontent.size(); j++)
			if(testcontent[j][0] == '#')
			{
				bSubtasks = true;
				break;
			}

		for(int j = 0; j < testcontent.size(); j++)
		{
			if(testcontent[j][0] == '#')
			{
				generatedtest << "\\hline" << endl;
				vector<string> strs;
				boost::split(strs, testcontent[j], boost::is_any_of("#"));
				if(cSubtask == 'a')
					generatedtest << iTestNr;
				if(strs.size() > 2)
					generatedtest << "&\\multicolumn{2}{p{14cm}|}{" << strs[2] << "}&&\\\\" << endl << "\\hline";
				generatedtest  << "&" << (bSubtasks ? cSubtask : ' ') << (bSubtasks ? ")&" : "&");
				cout << strs[1] << endl;
				iBE = boost::lexical_cast<int>(strs[1]);
				cSubtask++;
			}
			else
			{
				if((testcontent[j - 1][0] != '#') && testcontent[j][0] != '.')
					generatedtest << "\\newline ";
				if(testcontent[j][0] == '.') // no newline on code
					testcontent[j][0] = ' ';
				generatedtest  << testcontent[j];
			}
			cout << j << endl;
			if(j + 1 == testcontent.size() || testcontent[j + 1][0] == '#')
			{
				generatedtest << "&" << iBE << "&" << (j + 2 == testcontent.size() ? " " : "\\\\") << endl;
			}
		}
		generatedtest << "\\hline" << endl;
		iTestNr++;
		MyDir::copyImages(_dirlist[i] + "/img", sSavePath + "/img");
		testfile.close();
	}
	while(getline(templatefile, line))
		generatedtest << line << endl;
	generatedtest.close();
	ofstream makefile;
	makefile.open(sSavePath + "/makefile");
	makefile << "#testgenerator" << endl << "new:" << endl << "\t" << sMake << " main.tex" << endl;
}
<commit_msg>all multiline support<commit_after>#include "../include/generator.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

generator::generator(string s1, string s2, string s3, string s4, string s5, string s6, string s7)
{
	sTemplates = s1;
	sTemp = s2;
	sMake = s3;
	sShow = s4;
	sClass = s5;
	sTestName = s6;
	sTestDate = s7;
}
MyDir::dirlist generator::getAllTests(string sPath)
{
	MyDir::dirlist _dirlist = MyDir::getAllSubdirs(sPath);
	ifstream testfile;
	MyDir::dirlist availableTests;
	for(int i = 0; i < _dirlist.size(); i++) //check all directories for available tests
	{
		testfile.open(sPath + "/" + _dirlist[i] + "/test");
		if(!testfile.is_open())
		{
			cout << "can't open " << _dirlist[i] << endl;
			continue;
		}
		testfile.close();
		availableTests.push_back(sPath + "/" + _dirlist[i]);
	}
	return availableTests;
}
void generator::showAvailableTests(string sPath)
{
	ifstream templatefile;
	templatefile.open(sTemplates + "/templatebase/test");
	if(!templatefile.is_open())
	{
		cout << "can't open templatebase/test";
		throw 0;
	}
	MyDir::dirlist availableTests = getAllTests(sPath);
	generateTest(availableTests, sTemp + "/testgenerator");
	createNamesTex(sTemp + "/testgenerator", true);
	string s = "cd " + sTemp + "/testgenerator;" + sMake + " " + sTemp + "/testgenerator/main.tex";
	command::exec(s.c_str());
	command::threadexec((sShow + " " + sTemp + "/testgenerator/main.pdf&").c_str());
}
void generator::generateTestFromSelectionString(string sPath, string sSelect, string sSavePath)
{
	vector<int> iSelectedNumbers;
	vector<string> strs;
	boost::split(strs, sSelect, boost::is_any_of(","));
	for(int i = 0; i < strs.size(); i++)
		iSelectedNumbers.push_back(boost::lexical_cast<int>(strs[i]) - 1);
	MyDir::dirlist selectedTests;
	MyDir::dirlist availableTests = getAllTests(sPath);
	for(int i = 0; i < iSelectedNumbers.size(); i++)
		selectedTests.push_back(availableTests[iSelectedNumbers[i]]);
	generateTest(selectedTests, sSavePath);
	createNamesTex(sSavePath, false);
	string s = "cd " + sSavePath + ";" + sMake + " " + "main.tex";
	command::exec(s.c_str());
	command::threadexec((sShow + " " + sSavePath + "/main.pdf&").c_str());

}

void generator::createNamesTex(string sPath, bool bOverview)
{
	ofstream file(sPath + "/names.tex");
	if(!file.is_open())
	{
		cout << "can't write names.tex" << endl;
		throw 0;
	}
	file << "\\newcommand{\\myclassname}[0]{" << (bOverview ? "" : sClass) << "}" << endl;
	file << "\\newcommand{\\mytitle}[0]{" << (bOverview ? "" : sTestName) << "}" << endl;
	file << "\\newcommand{\\testdate}[0]{" << (bOverview ? "" : sTestDate) << "}" << endl;
	file.close();
}

void generator::createFromOneExercise(string s)
{
	generator::dirlist list;
	list.push_back(s);
	generator::generateTest(list, sTemp + "/testgenerator");
	createNamesTex(sTemp + "/testgenerator", true);
	s = "cd " + sTemp + "/testgenerator;" + sMake + " " + "main.tex";
	command::printoutput(command::exec(s.c_str()));
	command::threadexec((sShow + " " + sTemp + "/testgenerator/main.pdf&").c_str());
}
void generator::generateTest(generator::dirlist _dirlist, string sSavePath)
{
	string line;
	ofstream generatedtest;
	MyDir::createDir(sSavePath);
	generatedtest.open(sSavePath + "/main.tex", ios::trunc);
	if(!generatedtest.is_open())
	{
		cout << "can't write main.tex" << endl;
		throw 0;
	}
	ifstream templatefile;
	templatefile.open(sTemplates + "/templatebase/test");
	if(!templatefile.is_open())
	{
		cout << "can't open templatebase/test";
		throw 0;
	}

	while(true)//writing generated test until content
	{
		getline(templatefile, line);
		if(line == "#CONTENT")
			break;
		generatedtest << line << endl;
	}

	ifstream testfile;
	int iTestNr = 1;
	for(int i = 0; i < _dirlist.size(); i++)
	{
		testfile.open(_dirlist[i] + "/test");
		if(!testfile.is_open())
			cout << "can'r open " << _dirlist[i] << "/test" << endl;
		vector<string> testcontent;
		while(getline(testfile, line))
		{
			if(line[0] == '.')
			{
				line[0] = ' ';
				testcontent[testcontent.size() - 1] += line;
			}
			else
				testcontent.push_back(line);
		}
		cout << "testcontent size " << testcontent.size() << endl;
		char cSubtask = 'a';
		bool bSubtasks = false;
		bool bInMulticol = false;
		int iBE;
		for(int j = 1; j < testcontent.size(); j++)
			if(testcontent[j][0] == '#')
			{
				bSubtasks = true;
				break;
			}

		for(int j = 0; j < testcontent.size(); j++)
		{
			if(testcontent[j][0] == '#')
			{
				generatedtest << "\\hline" << endl;
				vector<string> strs;
				boost::split(strs, testcontent[j], boost::is_any_of("#"));
				if(cSubtask == 'a')
					generatedtest << iTestNr;
				if(strs.size() > 2)
					generatedtest << "&\\multicolumn{2}{p{14cm}|}{" << strs[2] << "}&&\\\\" << endl << "\\hline";
				generatedtest  << "&" << (bSubtasks ? cSubtask : ' ') << (bSubtasks ? ")&" : "&");
				cout << strs[1] << endl;
				iBE = boost::lexical_cast<int>(strs[1]);
				cSubtask++;
			}
			else
			{
				if((testcontent[j - 1][0] != '#'))
					generatedtest << "\\newline ";
				generatedtest  << testcontent[j];
			}
			cout << j << endl;
			if(j + 1 == testcontent.size() || testcontent[j + 1][0] == '#')
			{
				generatedtest << "&" << iBE << "&" << (j + 2 == testcontent.size() ? " " : "\\\\") << endl;
			}
		}
		generatedtest << "\\hline" << endl;
		iTestNr++;
		MyDir::copyImages(_dirlist[i] + "/img", sSavePath + "/img");
		testfile.close();
	}
	while(getline(templatefile, line))
		generatedtest << line << endl;
	generatedtest.close();
	ofstream makefile;
	makefile.open(sSavePath + "/makefile");
	makefile << "#testgenerator" << endl << "new:" << endl << "\t" << sMake << " main.tex" << endl;
}
<|endoftext|>


<commit_before>#include "geometry.h"
#include <cmath>
#include <cstdio>

const double epsilon = 0.0001;

bool insideInterval(double x, double a, double b) {
    return x >= a && x <= b;
}

bool intersects(Point line1, Point line2, Point center, double radius, double height) {
    Point start = line1 - center;
    Point direction = line2 - line1;
    start = Point(start.x / radius, start.y / radius, start.z / height);
    direction = Point(direction.x / radius, direction.y / radius, direction.z / height);
    double t0, t1;
    double a = direction.x * direction.x + direction.y * direction.y;
    double b = 2 * start.x * direction.x + 2 * start.y * direction.y;
    double c = start.x * start.x + start.y * start.y - 1;

    double b24ac = b * b - 4 * a * c;
    if (b24ac < 0)
        return false;

    double sqb24ac = sqrt(b24ac);
    t0 = (-b + sqb24ac) / (2 * a);
    t1 = (-b - sqb24ac) / (2 * a);
    if (t0 > t1) {
        double tmp = t0;
        t0 = t1;
        t1 = tmp;
    }

    float y0 = start.z + t0 * direction.z;
    float y1 = start.z + t1 * direction.z;

    if (y0 < -1) {
        if (y1 < -1)
            return false;
        else {
            // hit the cap
            float th = t0 + (t1 - t0) * (y0 + 1) / (y0 - y1);
            if (th <= -epsilon)
                return false;
            return true;
        }
    } else if (y0 >= -1 && y0 <= 1) {
        // hit the cylinder bit
        // check if on the segment
        if (!insideInterval(t0, 0, 1))
            return false;
        if (t0 < -epsilon)
            return false;
        return true;
    } else if (y0 > 1) {
        if (y1 > 1)
            return false;
        else {
            // hit the cap
            float th = t0 + (t1 - t0) * (y0 - 1) / (y0 - y1);
            if (th <= 0)
                return false;
            return true;
        }
    }
    return false;
}
<commit_msg>Use double everywhere.<commit_after>#include "geometry.h"
#include <cmath>
#include <cstdio>

const double epsilon = 0.0001;

bool insideInterval(double x, double a, double b) {
    return x >= a && x <= b;
}

bool intersects(Point line1, Point line2, Point center, double radius, double height) {
    Point start = line1 - center;
    Point direction = line2 - line1;
    start = Point(start.x / radius, start.y / radius, start.z / height);
    direction = Point(direction.x / radius, direction.y / radius, direction.z / height);
    double t0, t1;
    double a = direction.x * direction.x + direction.y * direction.y;
    double b = 2 * start.x * direction.x + 2 * start.y * direction.y;
    double c = start.x * start.x + start.y * start.y - 1;

    double b24ac = b * b - 4 * a * c;
    if (b24ac < 0)
        return false;

    double sqb24ac = sqrt(b24ac);
    t0 = (-b + sqb24ac) / (2 * a);
    t1 = (-b - sqb24ac) / (2 * a);
    if (t0 > t1) {
        double tmp = t0;
        t0 = t1;
        t1 = tmp;
    }

    double y0 = start.z + t0 * direction.z;
    double y1 = start.z + t1 * direction.z;

    if (y0 < -1) {
        if (y1 < -1)
            return false;
        else {
            // hit the cap
            double th = t0 + (t1 - t0) * (y0 + 1) / (y0 - y1);
            if (th <= -epsilon)
                return false;
            return true;
        }
    } else if (y0 >= -1 && y0 <= 1) {
        // hit the cylinder bit
        // check if on the segment
        if (!insideInterval(t0, 0, 1))
            return false;
        if (t0 < -epsilon)
            return false;
        return true;
    } else if (y0 > 1) {
        if (y1 > 1)
            return false;
        else {
            // hit the cap
            double th = t0 + (t1 - t0) * (y0 - 1) / (y0 - y1);
            if (th <= 0)
                return false;
            return true;
        }
    }
    return false;
}
<|endoftext|>


<commit_before>#include "graphics.h"
#include "romfile.h"
#include <QPixmap>

QImage *banks = 0;
uint numBanks = 0;

void loadCHRBanks(ROMFile& rom) {
    if (banks)
        delete[] banks;

    numBanks = rom.getNumCHRBanks();
    banks = new QImage[numBanks];
    for (uint i = 0; i < numBanks; i++)
        banks[i] = rom.readCHRBank(i);
}

// get single CHR bank with applied palette
// (TODO: the palette thing)
QImage getCHRBank(uint bank, uint pal) {
    if (banks) {
        QImage newBank(banks[bank % numBanks]);
        // test: save bank to image
        newBank.save(QString("bank%1.png").arg(bank));
        // apply palette here eventually
        return newBank;
    } else return QImage();
}
<commit_msg>get rid of debug image output<commit_after>#include "graphics.h"
#include "romfile.h"
#include <QPixmap>

QImage *banks = 0;
uint numBanks = 0;

void loadCHRBanks(ROMFile& rom) {
    if (banks)
        delete[] banks;

    numBanks = rom.getNumCHRBanks();
    banks = new QImage[numBanks];
    for (uint i = 0; i < numBanks; i++)
        banks[i] = rom.readCHRBank(i);
}

// get single CHR bank with applied palette
// (TODO: the palette thing)
QImage getCHRBank(uint bank, uint pal) {
    if (banks) {
        QImage newBank(banks[bank % numBanks]);

        // apply palette here eventually
        return newBank;
    } else return QImage();
}
<|endoftext|>


<commit_before><commit_msg>fs34b: added some diagnostics, so next time a bug like #i117507# happens<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2006-2010 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "datetime.h"

#include <zorba/item_factory.h>
#include <zorba/singleton_item_sequence.h>

#include <time.h>
#include <sys/timeb.h>
#ifdef UNIX
#include <sys/time.h>
#endif

namespace zorba { namespace datetimemodule {

void
compute_date_time(
    struct ::tm&    gmtm,
    long&           timezone,
    unsigned short& millitm)
{
#if defined (WIN32)
  struct _timeb timebuffer;
  _ftime_s( &timebuffer );
  localtime_s(&gmtm, &timebuffer.time); //thread safe localtime on Windows
#else
  struct timeb timebuffer;
  ftime( &timebuffer );
  localtime_r(&timebuffer.time, &gmtm); //thread safe localtime on Linux
#endif

  int lSummerTimeShift = 0;
  if (gmtm.tm_isdst != 0)
    lSummerTimeShift = 3600;

  timezone = -timebuffer.timezone * 60 + lSummerTimeShift; // in seconds
  millitm = timebuffer.millitm;
}

/******************************************************************************
 *****************************************************************************/
zorba::ItemSequence_t
CurrentDateTimeFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  struct ::tm    gmtm;
  long           lTimezone;
  unsigned short lMilliTm;

  compute_date_time(gmtm, lTimezone, lMilliTm);

  zorba::Item lDateTime =
    Zorba::getInstance(0)->getItemFactory()->createDateTime(
      (short)(gmtm.tm_year + 1900), (short)(gmtm.tm_mon + 1), (short)gmtm.tm_mday, (short)gmtm.tm_hour,
      (short)gmtm.tm_min, gmtm.tm_sec + lMilliTm/1000.0, (short)(lTimezone/3600));

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lDateTime));
}

/******************************************************************************
 *****************************************************************************/
zorba::ItemSequence_t
CurrentDateFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  struct ::tm    gmtm;
  long           lTimezone;
  unsigned short lMilliTm;

  compute_date_time(gmtm, lTimezone, lMilliTm);

  zorba::Item lDateTime =
    Zorba::getInstance(0)->getItemFactory()->createDate(
      gmtm.tm_year + 1900, gmtm.tm_mon + 1, gmtm.tm_mday);

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lDateTime));
}

/******************************************************************************
 *****************************************************************************/
zorba::ItemSequence_t
CurrentTimeFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  struct ::tm    gmtm;
  long           lTimezone;
  unsigned short lMilliTm;

  compute_date_time(gmtm, lTimezone, lMilliTm);

  zorba::Item lDateTime =
    Zorba::getInstance(0)->getItemFactory()->createTime(
      (short)gmtm.tm_hour, (short)gmtm.tm_min, gmtm.tm_sec + lMilliTm/1000.0, (short)(lTimezone/3600));

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lDateTime));
}

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

zorba::ItemSequence_t
TimestampFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  zorba::Item lMillis;
#if WIN32
  time_t t0;
  time(&t0);
  lMillis = Zorba::getInstance(0)->getItemFactory()->createLong(t0*1000);
#else
  timeval tv;
  gettimeofday(&tv, 0);
  long long millis = tv.tv_sec;
  millis = millis * 1000 + tv.tv_usec/1000;
  lMillis = Zorba::getInstance(0)->getItemFactory()->createLong(millis);
#endif

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lMillis));
}

/******************************************************************************
 *****************************************************************************/
zorba::ExternalFunction*
DateTimeModule::getExternalFunction(const zorba::String& aLocalname)
{
  zorba::ExternalFunction*& lFunc = theFunctions[aLocalname];
  if (!lFunc) {
    if (aLocalname == "current-dateTime") {
      lFunc = new CurrentDateTimeFunction(this);
    } else if (aLocalname == "current-date") {
      lFunc = new CurrentDateFunction(this);
    } else if (aLocalname == "current-time") {
      lFunc = new CurrentTimeFunction(this);
    } else if (aLocalname == "timestamp") {
      lFunc = new TimestampFunction(this);
    }
  }
  return lFunc;
}

/******************************************************************************
 *****************************************************************************/
DateTimeModule::~DateTimeModule()
{
  for (FuncMap_t::const_iterator lIter = theFunctions.begin();
       lIter != theFunctions.end(); ++lIter) {
    delete lIter->second;
  }
  theFunctions.clear();
}

/******************************************************************************
 *****************************************************************************/
void
DateTimeModule::destroy()
{
  if (!dynamic_cast<DateTimeModule*>(this)) {
    return;
  }
  delete this;
}

} /* namespace datetimemodule */ } /* namespace zorba */

#ifdef WIN32
#  define DLL_EXPORT __declspec(dllexport)
#else
#  define DLL_EXPORT __attribute__ ((visibility("default")))
#endif

extern "C" DLL_EXPORT zorba::ExternalModule* createModule() {
  return new zorba::datetimemodule::DateTimeModule();
}
<commit_msg>Fixing warnings in Windows build.<commit_after>/*
 * Copyright 2006-2010 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "datetime.h"

#include <zorba/item_factory.h>
#include <zorba/singleton_item_sequence.h>

#include <time.h>
#include <sys/timeb.h>
#ifdef UNIX
#include <sys/time.h>
#endif

namespace zorba { namespace datetimemodule {

void
compute_date_time(
    struct ::tm&    gmtm,
    long&           timezone,
    unsigned short& millitm)
{
#if defined (WIN32)
  struct _timeb timebuffer;
  _ftime_s( &timebuffer );
  localtime_s(&gmtm, &timebuffer.time); //thread safe localtime on Windows
#else
  struct timeb timebuffer;
  ftime( &timebuffer );
  localtime_r(&timebuffer.time, &gmtm); //thread safe localtime on Linux
#endif

  int lSummerTimeShift = 0;
  if (gmtm.tm_isdst != 0)
    lSummerTimeShift = 3600;

  timezone = -timebuffer.timezone * 60 + lSummerTimeShift; // in seconds
  millitm = timebuffer.millitm;
}

/******************************************************************************
 *****************************************************************************/
zorba::ItemSequence_t
CurrentDateTimeFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  struct ::tm    gmtm;
  long           lTimezone;
  unsigned short lMilliTm;

  compute_date_time(gmtm, lTimezone, lMilliTm);

  zorba::Item lDateTime =
    Zorba::getInstance(0)->getItemFactory()->createDateTime(
      static_cast<short>(gmtm.tm_year + 1900),
      static_cast<short>(gmtm.tm_mon + 1),
      static_cast<short>(gmtm.tm_mday),
      static_cast<short>(gmtm.tm_hour),
      static_cast<short>(gmtm.tm_min),
      gmtm.tm_sec + lMilliTm/1000.0,
      static_cast<short>(lTimezone/3600)
    );

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lDateTime));
}

/******************************************************************************
 *****************************************************************************/
zorba::ItemSequence_t
CurrentDateFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  struct ::tm    gmtm;
  long           lTimezone;
  unsigned short lMilliTm;

  compute_date_time(gmtm, lTimezone, lMilliTm);

  zorba::Item lDateTime =
    Zorba::getInstance(0)->getItemFactory()->createDate(
      static_cast<short>(gmtm.tm_year + 1900),
      static_cast<short>(gmtm.tm_mon + 1),
      static_cast<short>(gmtm.tm_mday)
    );

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lDateTime));
}

/******************************************************************************
 *****************************************************************************/
zorba::ItemSequence_t
CurrentTimeFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  struct ::tm    gmtm;
  long           lTimezone;
  unsigned short lMilliTm;

  compute_date_time(gmtm, lTimezone, lMilliTm);

  zorba::Item lDateTime =
    Zorba::getInstance(0)->getItemFactory()->createTime(
      static_cast<short>(gmtm.tm_hour),
      static_cast<short>(gmtm.tm_min),
      gmtm.tm_sec + lMilliTm/1000.0,
      static_cast<short>(lTimezone/3600)
    );

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lDateTime));
}

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

zorba::ItemSequence_t
TimestampFunction::evaluate(
  const Arguments_t& aArgs,
  const zorba::StaticContext* aSctx,
  const zorba::DynamicContext* aDctx) const
{
  zorba::Item lMillis;
#if WIN32
  time_t t0;
  time(&t0);
  lMillis = Zorba::getInstance(0)->getItemFactory()->createLong(t0*1000);
#else
  timeval tv;
  gettimeofday(&tv, 0);
  long long millis = tv.tv_sec;
  millis = millis * 1000 + tv.tv_usec/1000;
  lMillis = Zorba::getInstance(0)->getItemFactory()->createLong(millis);
#endif

  return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lMillis));
}

/******************************************************************************
 *****************************************************************************/
zorba::ExternalFunction*
DateTimeModule::getExternalFunction(const zorba::String& aLocalname)
{
  zorba::ExternalFunction*& lFunc = theFunctions[aLocalname];
  if (!lFunc) {
    if (aLocalname == "current-dateTime") {
      lFunc = new CurrentDateTimeFunction(this);
    } else if (aLocalname == "current-date") {
      lFunc = new CurrentDateFunction(this);
    } else if (aLocalname == "current-time") {
      lFunc = new CurrentTimeFunction(this);
    } else if (aLocalname == "timestamp") {
      lFunc = new TimestampFunction(this);
    }
  }
  return lFunc;
}

/******************************************************************************
 *****************************************************************************/
DateTimeModule::~DateTimeModule()
{
  for (FuncMap_t::const_iterator lIter = theFunctions.begin();
       lIter != theFunctions.end(); ++lIter) {
    delete lIter->second;
  }
  theFunctions.clear();
}

/******************************************************************************
 *****************************************************************************/
void
DateTimeModule::destroy()
{
  if (!dynamic_cast<DateTimeModule*>(this)) {
    return;
  }
  delete this;
}

} /* namespace datetimemodule */ } /* namespace zorba */

#ifdef WIN32
#  define DLL_EXPORT __declspec(dllexport)
#else
#  define DLL_EXPORT __attribute__ ((visibility("default")))
#endif

extern "C" DLL_EXPORT zorba::ExternalModule* createModule() {
  return new zorba::datetimemodule::DateTimeModule();
}
<|endoftext|>