<commit_before>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/bitcoin/error.hpp>

#include <boost/system/error_code.hpp>
#include <bitcoin/bitcoin/compat.hpp>

using namespace bc;

class error_category_impl
  : public std::error_category
{
public:
    virtual const char* name() const BC_NOEXCEPT;
    virtual std::string message(int ev) const BC_NOEXCEPT;
    virtual std::error_condition default_error_condition(int ev)
        const BC_NOEXCEPT;
};

static const error_category_impl& get_error_category_instance()
{
    static error_category_impl instance;
    return instance;
}

const char* error_category_impl::name() const BC_NOEXCEPT
{
    return "bitcoin";
}

std::string error_category_impl::message(int ev) const BC_NOEXCEPT
{
    // This text mapping may change without notice.
    switch (ev)
    {
        case error::success:
            return "success";

        // network errors
        case error::service_stopped:
            return "connection terminated";
        case error::operation_failed:
            return "operation failed";

        // blockchain errors
        case error::not_found:
            return "object does not exist";
        case error::duplicate:
            return "matching previous object found";
        case error::unspent_output:
            return "unspent output";
        case error::unsupported_payment_type:
            return "unsupport payment type";

        // network errors (more)
        case error::resolve_failed:
            return "resolving hostname failed";
        case error::network_unreachable:
            return "unable to reach remote host";
        case error::address_in_use:
            return "address already in use";
        case error::listen_failed:
            return "incoming connection failed";
        case error::accept_failed:
            return "connection acceptance failed";
        case error::bad_stream:
            return "bad data stream";
        case error::channel_timeout:
            return "connection timed out";

        // transaction pool
        case error::blockchain_reorganized:
            return "transactions invalidated by blockchain reorganization";
        case error::pool_filled:
            return "forced removal of old transaction from pool overflow";

        // validate tx
        case error::coinbase_transaction:
            return "coinbase transaction disallowed in memory pool";
        case error::is_not_standard:
            return "transaction is not standard";
        case error::double_spend:
            return "double spend of input";
        case error::input_not_found:
            return "spent input not found";

        // check_transaction()
        case error::empty_transaction:
            return "transaction inputs or outputs are empty";
        case error::output_value_overflow:
            return "output value outside valid range";
        case error::invalid_coinbase_script_size:
            return "coinbase script is too small or large";
        case error::previous_output_null:
            return "non-coinbase transaction has input with null previous output";

        // validate block
        case error::previous_block_invalid:
            return "previous block failed to validate";

        // check_block()
        case error::size_limits:
            return "size limits failed";
        case error::proof_of_work:
            return "proof of work failed";
        case error::futuristic_timestamp:
            return "timestamp too far in the future";
        case error::first_not_coinbase:
            return "first transaction is not a coinbase";
        case error::extra_coinbases:
            return "more than one coinbase";
        case error::too_many_sigs:
            return "too many script signatures";
        case error::merkle_mismatch:
            return "merkle root mismatch";

        // accept_block()
        case error::incorrect_proof_of_work:
            return "proof of work does not match bits field";
        case error::timestamp_too_early:
            return "block timestamp is too early";
        case error::non_final_transaction:
            return "block contains a non-final transaction";
        case error::checkpoints_failed:
            return "block hash rejected by checkpoint lockins";
        case error::old_version_block:
            return "block version one rejected at current height";
        case error::coinbase_height_mismatch:
            return "block height mismatch in coinbase";

        // connect_block()
        case error::duplicate_or_spent:
            return "duplicate transaction with unspent outputs";
        case error::validate_inputs_failed:
            return "validation of inputs failed";
        case error::fees_out_of_range:
            return "fees are out of range";
        case error::coinbase_too_large:
            return "coinbase value is too large";

        // file system errors
        case error::file_system:
            return "file system error";

        // unknown errors
        case error::unknown:
        default:
            return "unknown error";
    }
}

std::error_condition error_category_impl::default_error_condition(int ev)
    const BC_NOEXCEPT
{
    switch (ev)
    {
        // validate tx
        case error::coinbase_transaction:
        case error::is_not_standard:
        case error::double_spend:
        case error::input_not_found:

        // check_transaction()
        case error::empty_transaction:
        case error::output_value_overflow:
        case error::invalid_coinbase_script_size:
        case error::previous_output_null:

        // validate block
        case error::previous_block_invalid:

        // check_block()
        case error::size_limits:
        case error::proof_of_work:
        case error::futuristic_timestamp:
        case error::first_not_coinbase:
        case error::extra_coinbases:
        case error::too_many_sigs:
        case error::merkle_mismatch:

        // accept_block()
        case error::incorrect_proof_of_work:
        case error::timestamp_too_early:
        case error::non_final_transaction:
        case error::checkpoints_failed:
        case error::old_version_block:
        case error::coinbase_height_mismatch:

        // connect_block()
        case error::duplicate_or_spent:
        case error::validate_inputs_failed:
        case error::fees_out_of_range:
        case error::coinbase_too_large:
            return error::validate_failed;

        // transaction pool
        case error::blockchain_reorganized:
        case error::pool_filled:
            return error::forced_removal;

        default:
            return std::error_condition(ev, *this);
    }
}

namespace libbitcoin {
namespace error {

    std::error_code make_error_code(error_code_t e)
    {
        return std::error_code(e, get_error_category_instance());
    }

    std::error_condition make_error_condition(error_condition_t e)
    {
        return std::error_condition(e, get_error_category_instance());
    }

    error_code_t boost_to_error_code(const boost::system::error_code& ec)
    {
        const static int windows_connection_reset_by_peer = 10054;
        namespace boost_error = boost::system::errc;
        switch (ec.value())
        {
            case boost_error::success:
                return error::success;

            // network errors
            case windows_connection_reset_by_peer:
            case boost_error::connection_aborted:
            case boost_error::connection_refused:
            case boost_error::connection_reset:
            case boost_error::not_connected:
            case boost_error::operation_canceled:
                return error::service_stopped;

            case boost_error::operation_not_permitted:
            case boost_error::operation_not_supported:
            case boost_error::owner_dead:
            case boost_error::permission_denied:
                return error::operation_failed;

            case boost_error::address_family_not_supported:
            case boost_error::address_not_available:
            case boost_error::bad_address:
            case boost_error::destination_address_required:
                return error::resolve_failed;

            case boost_error::broken_pipe:
            case boost_error::host_unreachable:
            case boost_error::network_down:
            case boost_error::network_reset:
            case boost_error::network_unreachable:
            case boost_error::no_link:
            case boost_error::no_protocol_option:
            case boost_error::no_such_file_or_directory:
            case boost_error::not_a_socket:
            case boost_error::protocol_not_supported:
            case boost_error::wrong_protocol_type:
                return error::network_unreachable;

            case boost_error::address_in_use:
            case boost_error::already_connected:
            case boost_error::connection_already_in_progress:
            case boost_error::operation_in_progress:
                return error::address_in_use;

            case boost_error::bad_message:
            case boost_error::illegal_byte_sequence:
            case boost_error::io_error:
            case boost_error::message_size:
            case boost_error::no_message_available:
            case boost_error::no_message:
            case boost_error::no_stream_resources:
            case boost_error::not_a_stream:
            case boost_error::protocol_error:
                return error::bad_stream;

            case boost_error::stream_timeout:
            case boost_error::timed_out:
                return error::channel_timeout;

            // file system errors
            case boost_error::cross_device_link:
            case boost_error::bad_file_descriptor:
            case boost_error::device_or_resource_busy:
            case boost_error::directory_not_empty:
            case boost_error::executable_format_error:
            case boost_error::file_exists:
            case boost_error::file_too_large:
            case boost_error::filename_too_long:
            case boost_error::invalid_seek:
            case boost_error::is_a_directory:
            case boost_error::no_space_on_device:
            case boost_error::no_such_device:
            case boost_error::no_such_device_or_address:
            case boost_error::read_only_file_system:
            case boost_error::resource_unavailable_try_again:
            case boost_error::text_file_busy:
            case boost_error::too_many_files_open:
            case boost_error::too_many_files_open_in_system:
            case boost_error::too_many_links:
            case boost_error::too_many_symbolic_link_levels:
                return error::file_system;

            // unknown errors
            case boost_error::argument_list_too_long:
            case boost_error::argument_out_of_domain:
            case boost_error::function_not_supported:
            case boost_error::identifier_removed:
            case boost_error::inappropriate_io_control_operation:
            case boost_error::interrupted:
            case boost_error::invalid_argument:
            case boost_error::no_buffer_space:
            case boost_error::no_child_process:
            case boost_error::no_lock_available:
            case boost_error::no_such_process:
            case boost_error::not_a_directory:
            case boost_error::not_enough_memory:

            // This is the same value as operation_not_supported
            // in gcc, so excluded to prevent case break.
            //case boost_error::operation_would_block:
            // case boost_error::not_supported:

            // This is the same value as resource_unavailable_try_again
            // except in MSVC, so excluded to prevent case break.
            //case boost_error::operation_would_block:

            case boost_error::resource_deadlock_would_occur:
            case boost_error::result_out_of_range:
            case boost_error::state_not_recoverable:
            case boost_error::value_too_large:
            default:
                return error::unknown;
        }
    }

} // namespace error
} // namespace libbitcoin
<commit_msg>Add another boost/windows error code.<commit_after>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/bitcoin/error.hpp>

#include <boost/system/error_code.hpp>
#include <bitcoin/bitcoin/compat.hpp>

using namespace bc;

class error_category_impl
  : public std::error_category
{
public:
    virtual const char* name() const BC_NOEXCEPT;
    virtual std::string message(int ev) const BC_NOEXCEPT;
    virtual std::error_condition default_error_condition(int ev)
        const BC_NOEXCEPT;
};

static const error_category_impl& get_error_category_instance()
{
    static error_category_impl instance;
    return instance;
}

const char* error_category_impl::name() const BC_NOEXCEPT
{
    return "bitcoin";
}

std::string error_category_impl::message(int ev) const BC_NOEXCEPT
{
    // This text mapping may change without notice.
    switch (ev)
    {
        case error::success:
            return "success";

        // network errors
        case error::service_stopped:
            return "connection terminated";
        case error::operation_failed:
            return "operation failed";

        // blockchain errors
        case error::not_found:
            return "object does not exist";
        case error::duplicate:
            return "matching previous object found";
        case error::unspent_output:
            return "unspent output";
        case error::unsupported_payment_type:
            return "unsupport payment type";

        // network errors (more)
        case error::resolve_failed:
            return "resolving hostname failed";
        case error::network_unreachable:
            return "unable to reach remote host";
        case error::address_in_use:
            return "address already in use";
        case error::listen_failed:
            return "incoming connection failed";
        case error::accept_failed:
            return "connection acceptance failed";
        case error::bad_stream:
            return "bad data stream";
        case error::channel_timeout:
            return "connection timed out";

        // transaction pool
        case error::blockchain_reorganized:
            return "transactions invalidated by blockchain reorganization";
        case error::pool_filled:
            return "forced removal of old transaction from pool overflow";

        // validate tx
        case error::coinbase_transaction:
            return "coinbase transaction disallowed in memory pool";
        case error::is_not_standard:
            return "transaction is not standard";
        case error::double_spend:
            return "double spend of input";
        case error::input_not_found:
            return "spent input not found";

        // check_transaction()
        case error::empty_transaction:
            return "transaction inputs or outputs are empty";
        case error::output_value_overflow:
            return "output value outside valid range";
        case error::invalid_coinbase_script_size:
            return "coinbase script is too small or large";
        case error::previous_output_null:
            return "non-coinbase transaction has input with null previous output";

        // validate block
        case error::previous_block_invalid:
            return "previous block failed to validate";

        // check_block()
        case error::size_limits:
            return "size limits failed";
        case error::proof_of_work:
            return "proof of work failed";
        case error::futuristic_timestamp:
            return "timestamp too far in the future";
        case error::first_not_coinbase:
            return "first transaction is not a coinbase";
        case error::extra_coinbases:
            return "more than one coinbase";
        case error::too_many_sigs:
            return "too many script signatures";
        case error::merkle_mismatch:
            return "merkle root mismatch";

        // accept_block()
        case error::incorrect_proof_of_work:
            return "proof of work does not match bits field";
        case error::timestamp_too_early:
            return "block timestamp is too early";
        case error::non_final_transaction:
            return "block contains a non-final transaction";
        case error::checkpoints_failed:
            return "block hash rejected by checkpoint lockins";
        case error::old_version_block:
            return "block version one rejected at current height";
        case error::coinbase_height_mismatch:
            return "block height mismatch in coinbase";

        // connect_block()
        case error::duplicate_or_spent:
            return "duplicate transaction with unspent outputs";
        case error::validate_inputs_failed:
            return "validation of inputs failed";
        case error::fees_out_of_range:
            return "fees are out of range";
        case error::coinbase_too_large:
            return "coinbase value is too large";

        // file system errors
        case error::file_system:
            return "file system error";

        // unknown errors
        case error::unknown:
        default:
            return "unknown error";
    }
}

std::error_condition error_category_impl::default_error_condition(int ev)
    const BC_NOEXCEPT
{
    switch (ev)
    {
        // validate tx
        case error::coinbase_transaction:
        case error::is_not_standard:
        case error::double_spend:
        case error::input_not_found:

        // check_transaction()
        case error::empty_transaction:
        case error::output_value_overflow:
        case error::invalid_coinbase_script_size:
        case error::previous_output_null:

        // validate block
        case error::previous_block_invalid:

        // check_block()
        case error::size_limits:
        case error::proof_of_work:
        case error::futuristic_timestamp:
        case error::first_not_coinbase:
        case error::extra_coinbases:
        case error::too_many_sigs:
        case error::merkle_mismatch:

        // accept_block()
        case error::incorrect_proof_of_work:
        case error::timestamp_too_early:
        case error::non_final_transaction:
        case error::checkpoints_failed:
        case error::old_version_block:
        case error::coinbase_height_mismatch:

        // connect_block()
        case error::duplicate_or_spent:
        case error::validate_inputs_failed:
        case error::fees_out_of_range:
        case error::coinbase_too_large:
            return error::validate_failed;

        // transaction pool
        case error::blockchain_reorganized:
        case error::pool_filled:
            return error::forced_removal;

        default:
            return std::error_condition(ev, *this);
    }
}

namespace libbitcoin {
namespace error {

    std::error_code make_error_code(error_code_t e)
    {
        return std::error_code(e, get_error_category_instance());
    }

    std::error_condition make_error_condition(error_condition_t e)
    {
        return std::error_condition(e, get_error_category_instance());
    }

    error_code_t boost_to_error_code(const boost::system::error_code& ec)
    {
        enum windows_error
        {
            connection_aborted_by_host_system = 10053,
            connection_reset_by_peer = 10054
        };

        namespace boost_error = boost::system::errc;
        switch (ec.value())
        {
            case boost_error::success:
                return error::success;

            // network errors
            case windows_error::connection_aborted_by_host_system:
            case windows_error::connection_reset_by_peer:
            case boost_error::connection_aborted:
            case boost_error::connection_refused:
            case boost_error::connection_reset:
            case boost_error::not_connected:
            case boost_error::operation_canceled:
                return error::service_stopped;

            case boost_error::operation_not_permitted:
            case boost_error::operation_not_supported:
            case boost_error::owner_dead:
            case boost_error::permission_denied:
                return error::operation_failed;

            case boost_error::address_family_not_supported:
            case boost_error::address_not_available:
            case boost_error::bad_address:
            case boost_error::destination_address_required:
                return error::resolve_failed;

            case boost_error::broken_pipe:
            case boost_error::host_unreachable:
            case boost_error::network_down:
            case boost_error::network_reset:
            case boost_error::network_unreachable:
            case boost_error::no_link:
            case boost_error::no_protocol_option:
            case boost_error::no_such_file_or_directory:
            case boost_error::not_a_socket:
            case boost_error::protocol_not_supported:
            case boost_error::wrong_protocol_type:
                return error::network_unreachable;

            case boost_error::address_in_use:
            case boost_error::already_connected:
            case boost_error::connection_already_in_progress:
            case boost_error::operation_in_progress:
                return error::address_in_use;

            case boost_error::bad_message:
            case boost_error::illegal_byte_sequence:
            case boost_error::io_error:
            case boost_error::message_size:
            case boost_error::no_message_available:
            case boost_error::no_message:
            case boost_error::no_stream_resources:
            case boost_error::not_a_stream:
            case boost_error::protocol_error:
                return error::bad_stream;

            case boost_error::stream_timeout:
            case boost_error::timed_out:
                return error::channel_timeout;

            // file system errors
            case boost_error::cross_device_link:
            case boost_error::bad_file_descriptor:
            case boost_error::device_or_resource_busy:
            case boost_error::directory_not_empty:
            case boost_error::executable_format_error:
            case boost_error::file_exists:
            case boost_error::file_too_large:
            case boost_error::filename_too_long:
            case boost_error::invalid_seek:
            case boost_error::is_a_directory:
            case boost_error::no_space_on_device:
            case boost_error::no_such_device:
            case boost_error::no_such_device_or_address:
            case boost_error::read_only_file_system:
            case boost_error::resource_unavailable_try_again:
            case boost_error::text_file_busy:
            case boost_error::too_many_files_open:
            case boost_error::too_many_files_open_in_system:
            case boost_error::too_many_links:
            case boost_error::too_many_symbolic_link_levels:
                return error::file_system;

            // unknown errors
            case boost_error::argument_list_too_long:
            case boost_error::argument_out_of_domain:
            case boost_error::function_not_supported:
            case boost_error::identifier_removed:
            case boost_error::inappropriate_io_control_operation:
            case boost_error::interrupted:
            case boost_error::invalid_argument:
            case boost_error::no_buffer_space:
            case boost_error::no_child_process:
            case boost_error::no_lock_available:
            case boost_error::no_such_process:
            case boost_error::not_a_directory:
            case boost_error::not_enough_memory:

            // This is the same value as operation_not_supported
            // in gcc, so excluded to prevent case break.
            //case boost_error::operation_would_block:
            // case boost_error::not_supported:

            // This is the same value as resource_unavailable_try_again
            // except in MSVC, so excluded to prevent case break.
            //case boost_error::operation_would_block:

            case boost_error::resource_deadlock_would_occur:
            case boost_error::result_out_of_range:
            case boost_error::state_not_recoverable:
            case boost_error::value_too_large:
            default:
                return error::unknown;
        }
    }

} // namespace error
} // namespace libbitcoin
<|endoftext|>


<commit_before>#include "NavarroSeq.h"
#include <string>
#include <math.h>
#include <unordered_set>
#include <stdio.h>
#include <vector>

using namespace std;

string NavarroSeq::compress(string s)
{
	size_t n = s.size();
	size_t i,r;

	unordered_set<char> unique_chars;
	for (i=0; i<n; i++) {
		unique_chars.insert(s.at(i));
	}
	r = unique_chars.size();

	size_t u = floor(0.5*log((double) n)/log((double) r));
	printf("n = %i; r = %i; u = %i\n", (int)n, (int)r, (int)u);

	//example enumeration (while it's still fresh on my mind) :

	vector<vector<unsigned int> > combinations = get_all_combinations(unique_chars.size(), u);
	printf ("Vector size is %u\n", (unsigned int) combinations.size());

	// get a chunk of u characters
	// make a vector of length r containing numbers of each character

	// I
	// R
	// E tables
	// F mapping

	return "Hello World!";
}

string NavarroSeq::decompress(string s)
{
	return "Hello again, world!";
}

char NavarroSeq::access(string s, int index)
{
	return 4;
}

unsigned int NavarroSeq::rank(string s, char c, int index)
{
	return 14;
}

unsigned int NavarroSeq::select(string s, char c, int index)
{
	return 55;
}

vector<vector<unsigned int> > NavarroSeq::get_all_combinations(size_t r, size_t u) // r is alphabet size; u is block size
{
	unsigned int i;
	vector<vector<unsigned int> > combinations; // store a list of all combinations

	for (i = 0; i<r; i++)
	{
		/*
		* Create a vector of counts for each character
		* Vector of length r
		* values[0] has counts for alphabet[0], values[1] for alphabet[1]...
		*/
		vector<unsigned int> values (r,0);
		values.at(i)++; // Set initial count to current character
		enumerate(values, combinations, i, r, u-1); // add all enumerations with this prefix
	}
	return combinations;
}

void NavarroSeq::enumerate(vector<unsigned int>& values, vector<vector<unsigned int> >& combos, unsigned int min, unsigned int r, unsigned int u)
{
	if (u <= 0) //We already have a sequence of length u
	{
		combos.push_back(values); // Add it to the list
		return;
	}
	else
	{
		unsigned int i;
		for (i = min; i<r; i++) // iterate through all possible characters >= prefix
		{
			values.at(i)++;
			enumerate(values, combos, i, r, u-1);
		}
	}
}

int main() {
	// test sequence
	NavarroSeq::compress("abbabaababbababcabbabaababbababcabbabaababbababcabbabaababbababcabbabaababbababcabc");
	return 0;
}<commit_msg>fixed vector copying bug in combination enumeration.<commit_after>#include "NavarroSeq.h"
#include <string>
#include <math.h>
#include <unordered_set>
#include <stdio.h>
#include <vector>

using namespace std;

string NavarroSeq::compress(string s)
{
	size_t n = s.size();
	size_t i,r;

	unordered_set<char> unique_chars;
	for (i=0; i<n; i++) {
		unique_chars.insert(s.at(i));
	}
	r = unique_chars.size();

	size_t u = floor(0.5*log((double) n)/log((double) r));
	printf("n = %i; r = %i; u = %i\n", (int)n, (int)r, (int)u);

	//example enumeration (while it's still fresh on my mind) :

	vector<vector<unsigned int> > combinations = get_all_combinations(unique_chars.size(), u);
	printf ("Vector size is %u\n", (unsigned int) combinations.size());

	unsigned int myindex, count = 0;
	for(vector<vector<unsigned int> >::iterator it = combinations.begin(); it != combinations.end(); ++it) {
		printf ("%u: (", myindex);
		for (count=0; count<it->size(); count++) {
			printf("%u",it->at(count));
			if (count != it->size() - 1) printf(",");
		}
		printf(")\n");
		myindex++;
	}

	// get a chunk of u characters
	// make a vector of length r containing numbers of each character

	// I
	// R
	// E tables
	// F mapping

	return "Hello World!";
}

string NavarroSeq::decompress(string s)
{
	return "Hello again, world!";
}

char NavarroSeq::access(string s, int index)
{
	return 4;
}

unsigned int NavarroSeq::rank(string s, char c, int index)
{
	return 14;
}

unsigned int NavarroSeq::select(string s, char c, int index)
{
	return 55;
}

vector<vector<unsigned int> > NavarroSeq::get_all_combinations(size_t r, size_t u) // r is alphabet size; u is block size
{
	unsigned int i;
	vector<vector<unsigned int> > combinations; // store a list of all combinations

	for (i = 0; i<r; i++)
	{
		/*
		* Create a vector of counts for each character
		* Vector of length r
		* values[0] has counts for alphabet[0], values[1] for alphabet[1]...
		*/
		vector<unsigned int> values (r,0);
		values.at(i)++; // Set initial count to current character
		printf("Calling enumerate on (");
		for (int count=0; count<values.size(); count++) {
			printf("%u",values.at(count));
			if (count != values.size() - 1) printf(",");
		}
		printf("): min = %u, r = %u, u = %u\n", i, (unsigned int)r, (unsigned int)u-1);
		enumerate(values, combinations, i, r, u-1); // add all enumerations with this prefix
	}
	return combinations;
}

void NavarroSeq::enumerate(vector<unsigned int>& values, vector<vector<unsigned int> >& combos, unsigned int min, unsigned int r, unsigned int u)
{
	if (u <= 0) //We already have a sequence of length u
	{
		combos.push_back(values); // Add it to the list
		printf("pushing back: (");
		for (int count=0; count<values.size(); count++) {
			printf("%u",values.at(count));
			if (count != values.size() - 1) printf(",");
		}
		printf(")\n");
		return;
	}
	else
	{
		unsigned int i;
		for (i = min; i<r; i++) // iterate through all possible characters >= prefix
		{
			vector<unsigned int> values_copy (values);
			values_copy.at(i)++;
			printf("Calling enumerate recursively on (");
			for (int count=0; count<values.size(); count++) {
				printf("%u",values_copy.at(count));
				if (count != values_copy.size() - 1) printf(",");
			}
			printf("): min = %u, r = %u, u = %u\n", i, (unsigned int)r, (unsigned int)u-1);
			enumerate(values_copy, combos, i, r, u-1);
		}
	}
}

int main() {
	// test sequence
	NavarroSeq::compress("abbabaababbababcabbabaababbababcabbabaababbababcabbabaababbababcabbabaababbababcabc");
	return 0;
}<|endoftext|>


<commit_before>// Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ctime>

#include <ArgumentList.hpp>
#include <Exceptions.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>

typedef float dataType;
const string typeName("float");

// Common parameters
const unsigned int nrSeconds = 1;
const unsigned int nrBeams = 1;
const unsigned int nrStations = 64;

int main(int argc, char *argv[]) {
  bool localMem = false;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	unsigned int nrSamplesPerBlock = 0;
	unsigned int nrDMsPerBlock = 0;
	unsigned int nrSamplesPerThread = 0;
	unsigned int nrDMsPerThread = 0;
	unsigned int secondsToBuffer = 0;
	long long unsigned int wrongSamples= 0;
	AstroData::Observation< dataType > observation("DedispersionTest", typeName);

	try {
    isa::utils::ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    localMem = args.getSwitch("-local");

		nrSamplesPerBlock = args.getSwitchArgument< unsigned int >("-sb");
		nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db");
		nrSamplesPerThread = args.getSwitchArgument< unsigned int >("-st");
		nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt");

		observation.setMinFreq(args.getSwitchArgument< float >("-min_freq"));
		observation.setChannelBandwidth(args.getSwitchArgument< float >("-channel_bandwidth"));
		observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
		observation.setNrChannels(args.getSwitchArgument< unsigned int >("-channels"));
		observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
		observation.setFirstDM(args.getSwitchArgument< float >("-dm_first"));
		observation.setDMStep(args.getSwitchArgument< float >("-dm_step"));
		observation.setMaxFreq(observation.getMinFreq() + (observation.getChannelBandwidth() * (observation.getNrChannels() - 1)));
	} catch  ( isa::Exceptions::SwitchNotFound &err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }catch ( std::exception &err ) {
    std::cerr << "Usage: " << argv[0] << " -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
		return 1;
	}

	// Remaining parameters
	observation.setNrSeconds(nrSeconds);
	observation.setNrBeams(nrStations);
	observation.setNrStations(nrBeams);

	// Initialize OpenCL
	cl::Context * clContext = new cl::Context();
	std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
	std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
	std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();

  isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
  std::vector< unsigned int > * shifts = PulsarSearch::getShifts(observation);

  observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]);

	// Allocate memory
  cl::Buffer shifts_d;
  std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel());
  cl::Buffer dispersedData_d;
  std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
  cl::Buffer dedispersedData_d;
  std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
  try {
    shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(unsigned int), NULL, NULL);
    dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), NULL, NULL);
    dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), NULL, NULL);
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

	srand(time(NULL));
	for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
		for ( unsigned int sample = 0; sample < (secondsToBuffer * observation.getNrSamplesPerSecond()); sample++ ) {
      dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10);
		}
	}

  // Copy data structures to device
  try {
    clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(unsigned int), reinterpret_cast< void * >(shifts->data()), NULL, NULL);
    clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), NULL, NULL);
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

	// Generate kernel
  std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, nrSamplesPerBlock, nrDMsPerBlock, nrSamplesPerThread, nrDMsPerThread, typeName, observation, *shifts);
  cl::Kernel * kernel;
  std::cout << *code << std::endl;
	try {
    kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -cl-uniform-work-group-size -Werror", *clContext, clDevices->at(clDeviceID));
	} catch ( isa::Exceptions::OpenCLError &err ) {
    std::cerr << err.what() << std::endl;
		return 1;
	}

  // Run OpenCL kernel and CPU control
  try {
    cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / nrSamplesPerThread, observation.getNrDMs() / nrDMsPerThread);
    cl::NDRange local(nrSamplesPerBlock, nrDMsPerBlock);

    kernel->setArg(0, dispersedData_d);
    kernel->setArg(1, dedispersedData_d);
    kernel->setArg(2, shifts_d);
    clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local);
    PulsarSearch::dedispersion(observation, dispersedData, controlData, shifts);
    clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data()));
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

	for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
      if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) {
        wrongSamples++;
			}
		}
	}

  std::cout << std::endl;
  std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl;
  std::cout << std::endl;

	return 0;
}

<commit_msg>Using the type specifier for PulsarSearch templates.<commit_after>// Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ctime>

#include <ArgumentList.hpp>
#include <Exceptions.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>

typedef float dataType;
const string typeName("float");

// Common parameters
const unsigned int nrSeconds = 1;
const unsigned int nrBeams = 1;
const unsigned int nrStations = 64;

int main(int argc, char *argv[]) {
  bool localMem = false;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	unsigned int nrSamplesPerBlock = 0;
	unsigned int nrDMsPerBlock = 0;
	unsigned int nrSamplesPerThread = 0;
	unsigned int nrDMsPerThread = 0;
	unsigned int secondsToBuffer = 0;
	long long unsigned int wrongSamples= 0;
	AstroData::Observation< dataType > observation("DedispersionTest", typeName);

	try {
    isa::utils::ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    localMem = args.getSwitch("-local");

		nrSamplesPerBlock = args.getSwitchArgument< unsigned int >("-sb");
		nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db");
		nrSamplesPerThread = args.getSwitchArgument< unsigned int >("-st");
		nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt");

		observation.setMinFreq(args.getSwitchArgument< float >("-min_freq"));
		observation.setChannelBandwidth(args.getSwitchArgument< float >("-channel_bandwidth"));
		observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
		observation.setNrChannels(args.getSwitchArgument< unsigned int >("-channels"));
		observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
		observation.setFirstDM(args.getSwitchArgument< float >("-dm_first"));
		observation.setDMStep(args.getSwitchArgument< float >("-dm_step"));
		observation.setMaxFreq(observation.getMinFreq() + (observation.getChannelBandwidth() * (observation.getNrChannels() - 1)));
	} catch  ( isa::Exceptions::SwitchNotFound &err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }catch ( std::exception &err ) {
    std::cerr << "Usage: " << argv[0] << " -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
		return 1;
	}

	// Remaining parameters
	observation.setNrSeconds(nrSeconds);
	observation.setNrBeams(nrStations);
	observation.setNrStations(nrBeams);

	// Initialize OpenCL
	cl::Context * clContext = new cl::Context();
	std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
	std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
	std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();

  isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
  std::vector< unsigned int > * shifts = PulsarSearch::getShifts(observation);

  observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]);

	// Allocate memory
  cl::Buffer shifts_d;
  std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel());
  cl::Buffer dispersedData_d;
  std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
  cl::Buffer dedispersedData_d;
  std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
  try {
    shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(unsigned int), NULL, NULL);
    dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), NULL, NULL);
    dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), NULL, NULL);
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

	srand(time(NULL));
	for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
		for ( unsigned int sample = 0; sample < (secondsToBuffer * observation.getNrSamplesPerSecond()); sample++ ) {
      dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10);
		}
	}

  // Copy data structures to device
  try {
    clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(unsigned int), reinterpret_cast< void * >(shifts->data()), NULL, NULL);
    clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), NULL, NULL);
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

	// Generate kernel
  std::string * code = PulsarSearch::getDedispersionOpenCL< dataType >(localMem, nrSamplesPerBlock, nrDMsPerBlock, nrSamplesPerThread, nrDMsPerThread, typeName, observation, *shifts);
  cl::Kernel * kernel;
  std::cout << *code << std::endl;
	try {
    kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -cl-uniform-work-group-size -Werror", *clContext, clDevices->at(clDeviceID));
	} catch ( isa::Exceptions::OpenCLError &err ) {
    std::cerr << err.what() << std::endl;
		return 1;
	}

  // Run OpenCL kernel and CPU control
  try {
    cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / nrSamplesPerThread, observation.getNrDMs() / nrDMsPerThread);
    cl::NDRange local(nrSamplesPerBlock, nrDMsPerBlock);

    kernel->setArg(0, dispersedData_d);
    kernel->setArg(1, dedispersedData_d);
    kernel->setArg(2, shifts_d);
    clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local);
    PulsarSearch::dedispersion< dataType >(observation, dispersedData, controlData, shifts);
    clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data()));
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

	for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
      if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) {
        wrongSamples++;
			}
		}
	}

  std::cout << std::endl;
  std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl;
  std::cout << std::endl;

	return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright © 2017 Mozilla Foundation
 *
 * This program is made available under an ISC-style license.  See the
 * accompanying file LICENSE for details.
 */

#include "gtest/gtest.h"
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <atomic>
#include "cubeb/cubeb.h"
#include "common.h"

#define SAMPLE_FREQUENCY 48000
#if (defined(_WIN32) || defined(__WIN32__))
#define STREAM_FORMAT CUBEB_SAMPLE_FLOAT32LE
#else
#define STREAM_FORMAT CUBEB_SAMPLE_S16LE
#endif

std::atomic<bool> load_callback{ false };

long data_cb(cubeb_stream * stream, void * user, const void * inputbuffer, void * outputbuffer, long nframes)
{
  if (load_callback) {
    printf("Sleeping...\n");
    delay(100000);
    printf("Sleeping done\n");
  }
  return nframes;
}

void state_cb(cubeb_stream * stream, void * /*user*/, cubeb_state state)
{
  assert(stream);

  switch (state) {
  case CUBEB_STATE_STARTED:
    printf("stream started\n"); break;
  case CUBEB_STATE_STOPPED:
    printf("stream stopped\n"); break;
  case CUBEB_STATE_DRAINED:
    assert(false && "this test is not supposed to drain"); break;
  case CUBEB_STATE_ERROR:
    printf("stream error\n"); break;
  default:
    assert(false && "this test is not supposed to have a weird state"); break;
  }
}

TEST(cubeb, overload_callback)
{
  cubeb * ctx;
  cubeb_stream * stream;
  cubeb_stream_params output_params;
  int r;
  uint32_t latency_frames = 0;

  r = cubeb_init(&ctx, "Cubeb callback overload", NULL);
  ASSERT_EQ(r, CUBEB_OK);

  output_params.format = STREAM_FORMAT;
  output_params.rate = 48000;
  output_params.channels = 2;
  output_params.layout = CUBEB_LAYOUT_STEREO;

  r = cubeb_get_min_latency(ctx, output_params, &latency_frames);
  ASSERT_EQ(r, CUBEB_OK);

  r = cubeb_stream_init(ctx, &stream, "Cubeb",
                        NULL, NULL, NULL, &output_params,
                        latency_frames, data_cb, state_cb, NULL);
  ASSERT_EQ(r, CUBEB_OK);

  cubeb_stream_start(stream);
  delay(500);
  // This causes the callback to sleep for a large number of seconds.
  load_callback = true;
  delay(500);
  cubeb_stream_stop(stream);

  cubeb_stream_destroy(stream);
  cubeb_destroy(ctx);
}
<commit_msg>Replace assert by gtest assertion<commit_after>/*
 * Copyright © 2017 Mozilla Foundation
 *
 * This program is made available under an ISC-style license.  See the
 * accompanying file LICENSE for details.
 */

#include "gtest/gtest.h"
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <atomic>
#include "cubeb/cubeb.h"
#include "common.h"

#define SAMPLE_FREQUENCY 48000
#if (defined(_WIN32) || defined(__WIN32__))
#define STREAM_FORMAT CUBEB_SAMPLE_FLOAT32LE
#else
#define STREAM_FORMAT CUBEB_SAMPLE_S16LE
#endif

std::atomic<bool> load_callback{ false };

long data_cb(cubeb_stream * stream, void * user, const void * inputbuffer, void * outputbuffer, long nframes)
{
  if (load_callback) {
    printf("Sleeping...\n");
    delay(100000);
    printf("Sleeping done\n");
  }
  return nframes;
}

void state_cb(cubeb_stream * stream, void * /*user*/, cubeb_state state)
{
  ASSERT_TRUE(!!stream);

  switch (state) {
  case CUBEB_STATE_STARTED:
    printf("stream started\n"); break;
  case CUBEB_STATE_STOPPED:
    printf("stream stopped\n"); break;
  case CUBEB_STATE_DRAINED:
    FAIL() << "this test is not supposed to drain"; break;
  case CUBEB_STATE_ERROR:
    printf("stream error\n"); break;
  default:
    FAIL() << "this test is not supposed to have a weird state"; break;
  }
}

TEST(cubeb, overload_callback)
{
  cubeb * ctx;
  cubeb_stream * stream;
  cubeb_stream_params output_params;
  int r;
  uint32_t latency_frames = 0;

  r = cubeb_init(&ctx, "Cubeb callback overload", NULL);
  ASSERT_EQ(r, CUBEB_OK);

  output_params.format = STREAM_FORMAT;
  output_params.rate = 48000;
  output_params.channels = 2;
  output_params.layout = CUBEB_LAYOUT_STEREO;

  r = cubeb_get_min_latency(ctx, output_params, &latency_frames);
  ASSERT_EQ(r, CUBEB_OK);

  r = cubeb_stream_init(ctx, &stream, "Cubeb",
                        NULL, NULL, NULL, &output_params,
                        latency_frames, data_cb, state_cb, NULL);
  ASSERT_EQ(r, CUBEB_OK);

  cubeb_stream_start(stream);
  delay(500);
  // This causes the callback to sleep for a large number of seconds.
  load_callback = true;
  delay(500);
  cubeb_stream_stop(stream);

  cubeb_stream_destroy(stream);
  cubeb_destroy(ctx);
}
<|endoftext|>


<commit_before>//
// Name: MapServerDlg.cpp
//
// Copyright (c) 2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "MapServerDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
	#pragma hdrstop
#endif

#include "MapServerDlg.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// MapServerDlg.cpp
//----------------------------------------------------------------------------

// WDR: event table for MapServerDlg.cpp

BEGIN_EVENT_TABLE(MapServerDlg,AutoDialog)
	EVT_COMBOBOX( ID_BASE_URL, MapServerDlg::OnBaseUrlText )
	EVT_TEXT( ID_BASE_URL, MapServerDlg::OnBaseUrlText )
	EVT_TEXT( ID_WIDTH, MapServerDlg::OnSize )
	EVT_TEXT( ID_HEIGHT, MapServerDlg::OnSize )
	EVT_CHOICE( ID_CHOICE_FORMAT, MapServerDlg::OnFormat )
	EVT_CHOICE( ID_CHOICE_LAYERS, MapServerDlg::OnLayer )
	EVT_BUTTON( ID_QUERY_LAYERS, MapServerDlg::OnQueryLayers )
END_EVENT_TABLE()

MapServerDlg::MapServerDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	m_iFormat = 0;
	m_bSetting = false;
	MapServerDialogFunc( this, TRUE );
}

// WDR: handler implementations for MapServerDlg.cpp

void MapServerDlg::OnQueryLayers( wxCommandEvent &event )
{

}

void MapServerDlg::OnLayer( wxCommandEvent &event )
{
	if (m_bSetting)
		return;

	TransferDataFromWindow();
	UpdateURL();
}

void MapServerDlg::OnFormat( wxCommandEvent &event )
{
	if (m_bSetting)
		return;

	TransferDataFromWindow();
	UpdateURL();
}

void MapServerDlg::OnInitDialog(wxInitDialogEvent& event)
{
	m_iXSize = 1024;
	m_iYSize = 1024;

	AddNumValidator(ID_WIDTH, &m_iXSize);
	AddNumValidator(ID_HEIGHT, &m_iYSize);

	AddValidator(ID_QUERY, &m_query);
	AddValidator(ID_CHOICE_FORMAT, &m_iFormat);

	GetBaseUrl()->Append(_("http://wmt.jpl.nasa.gov/cgi-bin/wmt.cgi"));
	GetBaseUrl()->Append(_("http://globe.digitalearth.gov/viz-bin/wmt.cgi"));
	GetBaseUrl()->Append(_("http://grid.cr.usgs.gov/cgi-bin/mapserver/elsalvador"));
	GetBaseUrl()->Append(_("http://www.cubewerx.com/demo/cubeserv/cubeserv.cgi"));
	GetBaseUrl()->Append(_("http://demo.cubewerx.com/demo/cubexplor/cubexplor.cgi"));
	GetBaseUrl()->SetSelection(0);

	GetLayers()->Append(_("<none>"));
	GetLayers()->SetSelection(0);

	GetFormat()->Append(_("JPEG"));
	GetFormat()->Append(_("PNG"));
	GetFormat()->SetSelection(0);

	wxWindow::OnInitDialog(event);
}

void MapServerDlg::OnSize( wxCommandEvent &event )
{
	if (m_bSetting)
		return;

	TransferDataFromWindow();
	UpdateURL();
}

void MapServerDlg::OnBaseUrlText( wxCommandEvent &event )
{
	UpdateURL();
}

void MapServerDlg::UpdateURL()
{
	wxString2 val = GetBaseUrl()->GetValue();

	vtString url = val.mb_str(), str;

	url += "?WMTVER=1.0.0&REQUEST=map";
	url += "&LAYERS=africa";
	url += "&STYLES=&SRS=EPSG:4326";

	str.Format("&BBOX=%lf,%lf,%lf,%lf", m_area.left, m_area.bottom, m_area.right, m_area.top);
	url += str;

	str.Format("&WIDTH=%d&HEIGHT=%d", m_iXSize, m_iYSize);
	url += str;
	if (m_iFormat == 0)
		url += "&FORMAT=JPEG";
	else
		url += "&FORMAT=PNG";
	url += "&TRANSPARENT=TRUE&EXCEPTIONS=WMS_XML&";

	m_query = url;

	m_bSetting = true;
	TransferDataToWindow();
	m_bSetting = false;
}

<commit_msg>more dev<commit_after>//
// Name: MapServerDlg.cpp
//
// Copyright (c) 2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "MapServerDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
	#pragma hdrstop
#endif

#include "MapServerDlg.h"
#include "Vtdata/WFSClient.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// MapServerDlg.cpp
//----------------------------------------------------------------------------

// WDR: event table for MapServerDlg.cpp

BEGIN_EVENT_TABLE(MapServerDlg,AutoDialog)
	EVT_COMBOBOX( ID_BASE_URL, MapServerDlg::OnBaseUrlText )
	EVT_TEXT( ID_BASE_URL, MapServerDlg::OnBaseUrlText )
	EVT_TEXT( ID_WIDTH, MapServerDlg::OnSize )
	EVT_TEXT( ID_HEIGHT, MapServerDlg::OnSize )
	EVT_CHOICE( ID_CHOICE_FORMAT, MapServerDlg::OnFormat )
	EVT_CHOICE( ID_CHOICE_LAYERS, MapServerDlg::OnLayer )
	EVT_BUTTON( ID_QUERY_LAYERS, MapServerDlg::OnQueryLayers )
END_EVENT_TABLE()

MapServerDlg::MapServerDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	m_iFormat = 0;
	m_bSetting = false;
	MapServerDialogFunc( this, TRUE );
}

// WDR: handler implementations for MapServerDlg.cpp

void MapServerDlg::OnQueryLayers( wxCommandEvent &event )
{
	WFSLayerArray layers;
	wxString2 val = GetBaseUrl()->GetValue();
	vtString url = val.mb_str();
	bool success = GetLayersFromWMS(url, layers);
	if (!success)
		return;

	GetLayers()->Clear();
	int num = layers.size();
	if (num == 0)
		GetLayers()->Append(_("<none>"));
	else
	{
		for (int i = 0; i < num; i++)
		{
			vtString str;
			vtTagArray *tags = layers[i];
#if 0
			// this shows all data of all tags
			for (int j = 0; j < tags->NumTags(); j++)
			{
				str += "\'";
				str += tags->GetTag(j)->name;
				str += "\' \'";
				str += tags->GetTag(j)->value;
				str += "\' ";
			}
			GetLayers()->Append(wxString2(str));
#else
			vtTag *tag = tags->FindTag("Name");
			if (!tag)
				continue;
			str += tag->value;
/*		  tag = tags->FindTag("Title");
			if (tag && tag->value != str)
			{
				str += "(";
				str += tag->value;
				str += ")";
			}*/
			GetLayers()->Append(wxString2(str));
#endif
		}
	}
	GetLayers()->SetSelection(0);
}

void MapServerDlg::OnLayer( wxCommandEvent &event )
{
	if (m_bSetting)
		return;

	TransferDataFromWindow();
	UpdateURL();
}

void MapServerDlg::OnFormat( wxCommandEvent &event )
{
	if (m_bSetting)
		return;

	TransferDataFromWindow();
	UpdateURL();
}

void MapServerDlg::OnInitDialog(wxInitDialogEvent& event)
{
	m_iXSize = 1024;
	m_iYSize = 1024;

	AddNumValidator(ID_WIDTH, &m_iXSize);
	AddNumValidator(ID_HEIGHT, &m_iYSize);

	AddValidator(ID_QUERY, &m_query);
	AddValidator(ID_CHOICE_FORMAT, &m_iFormat);

	GetBaseUrl()->Append(_("http://wmt.jpl.nasa.gov/cgi-bin/wmt.cgi"));
	GetBaseUrl()->Append(_("http://globe.digitalearth.gov/viz-bin/wmt.cgi"));
	GetBaseUrl()->Append(_("http://grid.cr.usgs.gov/cgi-bin/mapserver/elsalvador"));
	GetBaseUrl()->Append(_("http://www.cubewerx.com/demo/cubeserv/cubeserv.cgi"));
	GetBaseUrl()->Append(_("http://demo.cubewerx.com/demo/cubexplor/cubexplor.cgi"));
	GetBaseUrl()->SetSelection(0);

	GetLayers()->Append(_("<none>"));
	GetLayers()->SetSelection(0);

	GetFormat()->Append(_("JPEG"));
	GetFormat()->Append(_("PNG"));
	GetFormat()->SetSelection(0);

	wxWindow::OnInitDialog(event);
}

void MapServerDlg::OnSize( wxCommandEvent &event )
{
	if (m_bSetting)
		return;

	TransferDataFromWindow();
	UpdateURL();
}

void MapServerDlg::OnBaseUrlText( wxCommandEvent &event )
{
	UpdateURL();
}

void MapServerDlg::UpdateURL()
{
	wxString2 urlvalue = GetBaseUrl()->GetValue();
	vtString url = urlvalue.mb_str(), str;

	wxString2 layervalue = GetLayers()->GetString(GetLayers()->GetSelection());

	url += "?WMTVER=1.0.0&REQUEST=map";
	url += "&LAYERS=";
	url += layervalue.mb_str();
	url += "&STYLES=&SRS=EPSG:4326";	// 4326 = WGS84

	str.Format("&BBOX=%lf,%lf,%lf,%lf", m_area.left, m_area.bottom, m_area.right, m_area.top);
	url += str;

	str.Format("&WIDTH=%d&HEIGHT=%d", m_iXSize, m_iYSize);
	url += str;
	if (m_iFormat == 0)
		url += "&FORMAT=JPEG";
	else
		url += "&FORMAT=PNG";
	url += "&TRANSPARENT=TRUE&EXCEPTIONS=WMS_XML&";

	m_query = url;

	m_bSetting = true;
	TransferDataToWindow();
	m_bSetting = false;
}

<|endoftext|>


<commit_before>#include <LuaContext.hpp>
#include <gtest/gtest.h>

TEST(CustomTypes, ReadWrite) {
	struct Object {
		int value;
    };

    LuaContext context;
    context.writeVariable("obj", Object{5});
	EXPECT_EQ(5, context.readVariable<Object>("obj").value);
}

TEST(CustomTypes, MemberFunctions) {
	struct Object {
		void  increment() { ++value; }
		int value;
    };

    LuaContext context;
    context.registerFunction("increment", &Object::increment);

    context.writeVariable("obj", Object{10});
    context.executeCode("obj:increment()");

	EXPECT_EQ(11, context.readVariable<Object>("obj").value);
}

TEST(CustomTypes, ConstVolatileMemberFunctions) {
	struct Object {
		int foo() { return 1; }
		int fooC() const { return 2; }
		int fooV() volatile { return 3; }
		int fooCV() const volatile { return 4; }
    };

    LuaContext context;
    context.registerFunction("foo", &Object::foo);
    context.registerFunction("fooC", &Object::fooC);
    context.registerFunction("fooV", &Object::fooV);
    context.registerFunction("fooCV", &Object::fooCV);

    context.writeVariable("obj", Object{});

    EXPECT_EQ(1, context.executeCode<int>("return obj:foo()"));
    EXPECT_EQ(2, context.executeCode<int>("return obj:fooC()"));
    EXPECT_EQ(3, context.executeCode<int>("return obj:fooV()"));
    EXPECT_EQ(4, context.executeCode<int>("return obj:fooCV()"));
}

TEST(CustomTypes, Members) {
	struct Object {
		int value;
    };

    LuaContext context;
    context.registerMember("value", &Object::value);

    context.writeVariable("obj", Object{10});
    context.executeCode("obj.value = obj.value + 5");

	EXPECT_EQ(15, context.readVariable<Object>("obj").value);
}

TEST(CustomTypes, CustomMemberFunctions) {
	struct Object {
		Object(int v) : value(v) {}
		int value;
    };

    LuaContext context;
	context.registerFunction<void (Object::*)()>("increment", [](Object& obj) { ++obj.value; });
	context.registerFunction<Object, int (int)>("add", [](Object& obj, int x) { obj.value += x; return obj.value; });

	context.writeVariable("obj1", Object{10});
	Object obj{10};
	context.writeVariable("obj2", &obj);
	context.writeVariable("obj3", std::make_shared<Object>(10));

	context.executeCode("obj1:increment()");
	context.executeCode("obj2:increment()");
	context.executeCode("obj3:increment()");

	EXPECT_EQ(11, context.readVariable<Object>("obj1").value);
	EXPECT_EQ(11, context.readVariable<Object*>("obj2")->value);
	EXPECT_EQ(11, context.readVariable<std::shared_ptr<Object>>("obj3")->value);

	EXPECT_EQ(14, context.executeCode<int>("return obj1:add(3)"));
	EXPECT_EQ(14, context.executeCode<int>("return obj2:add(3)"));
	EXPECT_EQ(14, context.executeCode<int>("return obj3:add(3)"));
}

TEST(CustomTypes, CustomMembers) {
	struct Object {};

    LuaContext context;
	context.registerMember<int (Object::*)>("value",
		[](const Object& obj) { return 2; },
		[](Object& obj, int val) {}
	);

    context.writeVariable("obj", Object{});
    EXPECT_EQ(2, context.executeCode<int>("return obj.value"));
}

TEST(CustomTypes, Unregistering) {
	struct Object {
		int  foo() { return 2; }
    };

    LuaContext context;
    context.writeVariable("obj", Object{});
	EXPECT_ANY_THROW(context.executeCode("return obj:foo()"));

    context.registerFunction("foo", &Object::foo);
    EXPECT_EQ(2, context.executeCode<int>("return obj:foo()"));

	context.unregisterFunction<Object>("foo");
	EXPECT_ANY_THROW(context.executeCode("return obj:foo()"));
}
<commit_msg>Added test for custom function objects for register member functions<commit_after>#include <LuaContext.hpp>
#include <gtest/gtest.h>

TEST(CustomTypes, ReadWrite) {
	struct Object {
		int value;
    };

    LuaContext context;
    context.writeVariable("obj", Object{5});
	EXPECT_EQ(5, context.readVariable<Object>("obj").value);
}

TEST(CustomTypes, MemberFunctions) {
	struct Object {
		void  increment() { ++value; }
		int value;
    };

    LuaContext context;
    context.registerFunction("increment", &Object::increment);

    context.writeVariable("obj", Object{10});
    context.executeCode("obj:increment()");

	EXPECT_EQ(11, context.readVariable<Object>("obj").value);
}

TEST(CustomTypes, ConstVolatileMemberFunctions) {
	struct Object {
		int foo() { return 1; }
		int fooC() const { return 2; }
		int fooV() volatile { return 3; }
		int fooCV() const volatile { return 4; }
    };

    LuaContext context;
    context.registerFunction("foo", &Object::foo);
    context.registerFunction("fooC", &Object::fooC);
    context.registerFunction("fooV", &Object::fooV);
    context.registerFunction("fooCV", &Object::fooCV);

    context.writeVariable("obj", Object{});

    EXPECT_EQ(1, context.executeCode<int>("return obj:foo()"));
    EXPECT_EQ(2, context.executeCode<int>("return obj:fooC()"));
    EXPECT_EQ(3, context.executeCode<int>("return obj:fooV()"));
    EXPECT_EQ(4, context.executeCode<int>("return obj:fooCV()"));
}

TEST(CustomTypes, Members) {
	struct Object {
		int value;
    };

    LuaContext context;
    context.registerMember("value", &Object::value);

    context.writeVariable("obj", Object{10});
    context.executeCode("obj.value = obj.value + 5");

	EXPECT_EQ(15, context.readVariable<Object>("obj").value);
}

TEST(CustomTypes, CustomMemberFunctions) {
	struct Object {
		Object(int v) : value(v) {}
		int value;
    };

    LuaContext context;
	context.registerFunction<void (Object::*)()>("increment", [](Object& obj) { ++obj.value; });
	context.registerFunction<Object, int (int)>("add", [](Object& obj, int x) { obj.value += x; return obj.value; });

	context.writeVariable("obj1", Object{10});
	Object obj{10};
	context.writeVariable("obj2", &obj);
	context.writeVariable("obj3", std::make_shared<Object>(10));

	context.executeCode("obj1:increment()");
	context.executeCode("obj2:increment()");
	context.executeCode("obj3:increment()");

	EXPECT_EQ(11, context.readVariable<Object>("obj1").value);
	EXPECT_EQ(11, context.readVariable<Object*>("obj2")->value);
	EXPECT_EQ(11, context.readVariable<std::shared_ptr<Object>>("obj3")->value);

	EXPECT_EQ(14, context.executeCode<int>("return obj1:add(3)"));
	EXPECT_EQ(14, context.executeCode<int>("return obj2:add(3)"));
	EXPECT_EQ(14, context.executeCode<int>("return obj3:add(3)"));
}

TEST(CustomTypes, CustomMemberFunctionsCustomFunctionObject) {
	struct Object {
		Object(int v) : value(v) {}
		int value;
	};

	struct ObjectIncrementer {
		void operator()(Object& obj) const { ++obj.value; }
	};

	LuaContext context;
	context.registerFunction<void (Object::*)()>("increment1", ObjectIncrementer{});
	context.registerFunction<Object, void ()>("increment2", ObjectIncrementer{});

	context.writeVariable("obj1", Object{ 10 });
	Object obj{ 10 };
	context.writeVariable("obj2", &obj);
	context.writeVariable("obj3", std::make_shared<Object>(10));

	context.executeCode("obj1:increment1()");
	context.executeCode("obj1:increment2()");
	context.executeCode("obj2:increment1()");
	context.executeCode("obj2:increment2()");
	context.executeCode("obj3:increment1()");
	context.executeCode("obj3:increment2()");

	EXPECT_EQ(12, context.readVariable<Object>("obj1").value);
	EXPECT_EQ(12, context.readVariable<Object*>("obj2")->value);
	EXPECT_EQ(12, context.readVariable<std::shared_ptr<Object>>("obj3")->value);
}

TEST(CustomTypes, CustomMembers) {
	struct Object {};

    LuaContext context;
	context.registerMember<int (Object::*)>("value",
		[](const Object& obj) { return 2; },
		[](Object& obj, int val) {}
	);

    context.writeVariable("obj", Object{});
    EXPECT_EQ(2, context.executeCode<int>("return obj.value"));
}

TEST(CustomTypes, Unregistering) {
	struct Object {
		int  foo() { return 2; }
    };

    LuaContext context;
    context.writeVariable("obj", Object{});
	EXPECT_ANY_THROW(context.executeCode("return obj:foo()"));

    context.registerFunction("foo", &Object::foo);
    EXPECT_EQ(2, context.executeCode<int>("return obj:foo()"));

	context.unregisterFunction<Object>("foo");
	EXPECT_ANY_THROW(context.executeCode("return obj:foo()"));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: functiondescription.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 02:31:50 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "functiondescription.hxx"

#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"

namespace css = com::sun::star;

using stoc::registry_tdprovider::FunctionDescription;

FunctionDescription::FunctionDescription(
    css::uno::Reference< css::container::XHierarchicalNameAccess > const &
        manager,
    com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
    sal_uInt16 index):
    m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}

FunctionDescription::~FunctionDescription() {}

css::uno::Sequence<
    css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
    {
        osl::MutexGuard guard(m_mutex);
        if (m_exceptionsInit) {
            return m_exceptions;
        }
    }
    typereg::Reader reader(getReader());
    sal_uInt16 n = reader.getMethodExceptionCount(m_index);
    css::uno::Sequence<
        css::uno::Reference< css::reflection::XCompoundTypeDescription > >
            exceptions(n);
    for (sal_uInt16 i = 0; i < n; ++i) {
        rtl::OUString name(
            reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
        css::uno::Any any;
        try {
            any = m_manager->getByHierarchicalName(name);
        } catch (css::container::NoSuchElementException & e) {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.container.NoSuchElementException: "))
                 + e.Message),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        if (!(any >>= exceptions[i])
            || exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
        {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
                 + name),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        OSL_ASSERT(exceptions[i].is());
    }
    osl::MutexGuard guard(m_mutex);
    if (!m_exceptionsInit) {
        m_exceptions = exceptions;
        m_exceptionsInit;
    }
    return m_exceptions;
}

typereg::Reader FunctionDescription::getReader() const {
    return typereg::Reader(
        m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.58); FILE MERGED 2005/09/05 17:11:02 rt 1.3.58.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: functiondescription.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:02:47 $
 *
 *  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
 *
 ************************************************************************/

#include "functiondescription.hxx"

#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"

namespace css = com::sun::star;

using stoc::registry_tdprovider::FunctionDescription;

FunctionDescription::FunctionDescription(
    css::uno::Reference< css::container::XHierarchicalNameAccess > const &
        manager,
    com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
    sal_uInt16 index):
    m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}

FunctionDescription::~FunctionDescription() {}

css::uno::Sequence<
    css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
    {
        osl::MutexGuard guard(m_mutex);
        if (m_exceptionsInit) {
            return m_exceptions;
        }
    }
    typereg::Reader reader(getReader());
    sal_uInt16 n = reader.getMethodExceptionCount(m_index);
    css::uno::Sequence<
        css::uno::Reference< css::reflection::XCompoundTypeDescription > >
            exceptions(n);
    for (sal_uInt16 i = 0; i < n; ++i) {
        rtl::OUString name(
            reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
        css::uno::Any any;
        try {
            any = m_manager->getByHierarchicalName(name);
        } catch (css::container::NoSuchElementException & e) {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.container.NoSuchElementException: "))
                 + e.Message),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        if (!(any >>= exceptions[i])
            || exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
        {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
                 + name),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        OSL_ASSERT(exceptions[i].is());
    }
    osl::MutexGuard guard(m_mutex);
    if (!m_exceptionsInit) {
        m_exceptions = exceptions;
        m_exceptionsInit;
    }
    return m_exceptions;
}

typereg::Reader FunctionDescription::getReader() const {
    return typereg::Reader(
        m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<|endoftext|>


<commit_before>//
// vtTerrainScene - Container class for all of the terrains loaded
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "vtlib/vtlib.h"
#include "TerrainScene.h"
#include "Light.h"
#include "SkyDome.h"
#include "Terrain.h"
#include "TimeEngines.h"

///////////////////////////////////////////////////////////////////////
//
// A small engine that allows the SkyDome to stay around the Camera.
//
class vtSkyTrackEngine : public vtEngine
{
public:
	vtSkyTrackEngine();
	virtual void Eval();
	vtCamera *m_pCamera;
};

vtSkyTrackEngine::vtSkyTrackEngine() : vtEngine()
{
	m_pCamera = NULL;
}

void vtSkyTrackEngine::Eval()
{
	vtTransform *pTarget = (vtTransform *) GetTarget();
	if (!pTarget || !m_pCamera)
		return;
	FPoint3 pos1 = m_pCamera->GetTrans();
	FPoint3 pos2 = pTarget->GetTrans();
	pos2.x = pos1.x;
	pos2.z = pos1.z;
	pTarget->SetTrans(pos2);
}

///////////////////////////////////////////////////////////////////////
//
// vtTerrainScene class
//

vtTerrainScene::vtTerrainScene()
{
	horizon_color.Set(0.70f, 0.85f, 1.0f);
	azimuth_color.Set(0.12f, 0.32f, 0.70f);

	m_yondist = 1000.0f * WORLD_SCALE;

	m_pSkyDome = NULL;
	m_pFirstTerrain = NULL;
	m_pCurrentTerrain = NULL;
	m_pTime = NULL;
	m_pSunLight = NULL;
}

vtTerrainScene::~vtTerrainScene()
{
	// delete all the terrains that were appended
	// TODO: proper cleanup
}

void vtTerrainScene::create_skydome(vtString datapath)
{
	if (m_pSkyDome != NULL)
		return;

	// create a day-night dome
	m_pSkyDome = new vtSkyDome();
	m_pSkyDome->SetDayColors(horizon_color, azimuth_color);
	m_pSkyDome->SetDawnTimes(5, 0, 7, 0);
	m_pSkyDome->SetDuskTimes(17, 0, 19, 0);
	m_pSkyDome->Create(datapath + "Sky/bsc.data", 3,
					   1.0f,		// initially unit radius
					   datapath + "Sky/glow2.png",
					   datapath + "Sky/moon5_256.png");
	m_pSkyDome->SetName2("The Sky");
	m_pAtmosphereGroup->AddChild(m_pSkyDome);

	vtSkyTrackEngine *pEng = new vtSkyTrackEngine();
	pEng->SetName2("Sky-Camera-Following");
	pEng->m_pCamera = vtGetScene()->GetCamera();
	pEng->SetTarget(m_pSkyDome);
	vtGetScene()->AddEngine(pEng);
}

//
// Find a terrain whose name begins with a given string
//
vtTerrain *vtTerrainScene::FindTerrainByName(const char *name)
{
	int len = strlen(name);
	if (!len)
		return NULL;

	for (vtTerrain *pTerr = m_pFirstTerrain; pTerr; pTerr=pTerr->GetNext())
	{
		if (!strncmp(name, pTerr->GetName(), len))
			return pTerr;
	}
	return NULL;
}

void vtTerrainScene::create_fog()
{
#if 0
	int dist = m_pFirstTerrain->m_Params.m_iFogDistance;

	m_pFog = new vtFog();
	m_pFog->SetStart(1.0f);  // only useful for linear - broken
	m_pFog->SetEnd(dist * 1000.0f * WORLD_SCALE);

	// 1 / ( dist / slope + max )
	// dist = visability distance
	// slope = how fast density varies by dist, smaller = see farther (guessing)
	// max = max density of fog = (2 - max), so 1.2 = max density of 0.8

	m_pFog->SetDensity( 1.0f / (dist/4.0f + 1.3f) ); // vis dis function of density

	m_pFog->SetColor(horizon_color);
	//m_pFog->SetKind(FOG_Exponential2 | FOG_Pixel); // from linear
	m_pFog->SetKind(FOG_Linear); // from linear
#endif
}

void vtTerrainScene::create_engines(bool bDoSound)
{
	// Set Time in motion
	m_pTime = new TimeEngine(this, 0);
	m_pTime->SetName2("Time");
	vtGetScene()->AddEngine(m_pTime);
}

vtRoot *vtTerrainScene::BeginTerrainScene(bool bDoSound)
{
	create_engines(bDoSound);

	m_pTop = new vtRoot();
	m_pTop->SetName2("All Terrain");

	// create the sun
	vtLight *pLight = new vtLight();
	m_pSunLight = new vtMovLight(pLight);

	// default location: over our right shoulder, pointing downward
	m_pSunLight->Translate1(FPoint3(1000.0f, 1000.0f, 1000.0f));
	m_pSunLight->RotateLocal(FPoint3(0,1,0), PIf/4.0f);
	m_pSunLight->RotateLocal(FPoint3(1,0,0), -PIf/4.0f);
	m_pSunLight->SetName2("SunLight");

	m_pTop->AddChild(m_pSunLight);

	// create sky group - this holds all celestial objects
	m_pAtmosphereGroup = new vtGroup();
	m_pAtmosphereGroup->SetName2("Atmosphere Group");
	m_pTop->AddChild(m_pAtmosphereGroup);

	return m_pTop;
}

void vtTerrainScene::AppendTerrain(vtTerrain *pTerrain)
{
	// add to linked list
	pTerrain->SetNext(m_pFirstTerrain);
	m_pFirstTerrain = pTerrain;
}

//
// call after you have appended all terrains
//
void vtTerrainScene::Finish(const char *datapath)
{
	create_skydome(datapath);

	// create fog AFTER the shapes
//	if (m_pFirstTerrain != NULL)
//		create_fog();

	// start out with no scene active
	for (vtTerrain *t = m_pFirstTerrain; t != NULL; t=t->GetNext())
		t->ActivateEngines(false);
}

void vtTerrainScene::SetTerrain(vtTerrain *pTerrain)
{
	if (m_pCurrentTerrain != NULL)
	{
		// turn off the scene graph of the previous terrain
		m_pCurrentTerrain->m_pTerrainGroup->SetEnabled(false);

		// turn off the engines specific to the previous terrain
		m_pCurrentTerrain->ActivateEngines(false);
	}
	m_pCurrentTerrain = pTerrain;

	// if setting to no terrain nothing more to do
	if (!pTerrain)
	{
		if (m_pSkyDome != NULL)
			m_pSkyDome->SetEnabled(false);
		return;
	}

	// switch
	m_pTop->AddChild(m_pCurrentTerrain->m_pTerrainGroup);
	m_pCurrentTerrain->m_pTerrainGroup->SetEnabled(true);

	// switch to the projection of this terrain
	m_pCurrentTerrain->SetGlobalProjection();

	// move the sky to fit the new current terrain
	m_pSkyDome->SetEnabled(true);
	float radius = pTerrain->GetRadius() * 2.9f;
	float max_radius = (450000 * WORLD_SCALE);
	if (radius > max_radius)
		radius = max_radius;
	m_pSkyDome->SetRadius(radius);
	FPoint3 center = pTerrain->GetCenter();
	center.y = 0.0f;
	m_pSkyDome->SetTrans(center);

	// Set background color to match the ocean
	vtGetScene()->SetBgColor(m_pCurrentTerrain->GetOceanColor());

	// turn on the engines specific to the new terrain
	m_pCurrentTerrain->ActivateEngines(true);

	// set the time to the time of the new terrain
	TParams &param = m_pCurrentTerrain->GetParams();
	int time = param.m_iInitTime * 3600;
	SetTimeOfDay(time, true);

	// setup time engine
	m_pTime->SetTime(time);
	m_pTime->SetRealIncrement(param.m_fTimeSpeed);
	m_pTime->SetEnabled(param.m_bTimeOn);

	// handle the atmosphere
	m_pSkyDome->SetEnabled(param.m_bSky);
	SetFog(param.m_bFog);
}

void vtTerrainScene::ToggleFog()
{
	SetFog(!m_bFog);
}

void vtTerrainScene::SetFog(bool fog)
{
#if 0
	m_bFog = fog;
	if (m_bFog)
	{
		vtGetScene()->SetFog(m_pFog);
		vtGetScene()->SetBackColor(horizon_color);
//		vtGetScene()->GetCamera()->GetYon(m_pFirstTerrain
		vtGetScene()->GetCamera()->SetYon(m_pFirstTerrain->m_Params.m_iFogDistance	* 1000.0f * WORLD_SCALE);
	}
	else
	{
		vtGetScene()->SetFog(NULL);
		vtScene::SetBgColor(m_pCurrentTerrain->GetOceanColor());
		vtGetScene()->GetCamera()->SetYon(m_yondist);
	}
#endif
}

void vtTerrainScene::SetTimeOfDay(unsigned int time, bool fFullRefresh)
{
	if (m_pSkyDome)
	{
		m_pSkyDome->SetSunLight(GetSunLight());
		m_pSkyDome->SetTimeOfDay(time, fFullRefresh);
//		m_pSkyDome->ApplyDayColors();
	}
	// TODO? Update the fog color to match the color of the horizon.
}

<commit_msg>chg to use vtTerrain::Enable<commit_after>//
// vtTerrainScene - Container class for all of the terrains loaded
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "vtlib/vtlib.h"
#include "TerrainScene.h"
#include "Light.h"
#include "SkyDome.h"
#include "Terrain.h"
#include "TimeEngines.h"

///////////////////////////////////////////////////////////////////////
//
// A small engine that allows the SkyDome to stay around the Camera.
//
class vtSkyTrackEngine : public vtEngine
{
public:
	vtSkyTrackEngine();
	virtual void Eval();
	vtCamera *m_pCamera;
};

vtSkyTrackEngine::vtSkyTrackEngine() : vtEngine()
{
	m_pCamera = NULL;
}

void vtSkyTrackEngine::Eval()
{
	vtTransform *pTarget = (vtTransform *) GetTarget();
	if (!pTarget || !m_pCamera)
		return;
	FPoint3 pos1 = m_pCamera->GetTrans();
	FPoint3 pos2 = pTarget->GetTrans();
	pos2.x = pos1.x;
	pos2.z = pos1.z;
	pTarget->SetTrans(pos2);
}

///////////////////////////////////////////////////////////////////////
//
// vtTerrainScene class
//

vtTerrainScene::vtTerrainScene()
{
	horizon_color.Set(0.70f, 0.85f, 1.0f);
	azimuth_color.Set(0.12f, 0.32f, 0.70f);

	m_yondist = 1000.0f * WORLD_SCALE;

	m_pSkyDome = NULL;
	m_pFirstTerrain = NULL;
	m_pCurrentTerrain = NULL;
	m_pTime = NULL;
	m_pSunLight = NULL;
}

vtTerrainScene::~vtTerrainScene()
{
	// delete all the terrains that were appended
	// TODO: proper cleanup
}

void vtTerrainScene::create_skydome(vtString datapath)
{
	if (m_pSkyDome != NULL)
		return;

	// create a day-night dome
	m_pSkyDome = new vtSkyDome();
	m_pSkyDome->SetDayColors(horizon_color, azimuth_color);
	m_pSkyDome->SetDawnTimes(5, 0, 7, 0);
	m_pSkyDome->SetDuskTimes(17, 0, 19, 0);
	m_pSkyDome->Create(datapath + "Sky/bsc.data", 3,
					   1.0f,		// initially unit radius
					   datapath + "Sky/glow2.png",
					   datapath + "Sky/moon5_256.png");
	m_pSkyDome->SetName2("The Sky");
	m_pAtmosphereGroup->AddChild(m_pSkyDome);

	vtSkyTrackEngine *pEng = new vtSkyTrackEngine();
	pEng->SetName2("Sky-Camera-Following");
	pEng->m_pCamera = vtGetScene()->GetCamera();
	pEng->SetTarget(m_pSkyDome);
	vtGetScene()->AddEngine(pEng);
}

//
// Find a terrain whose name begins with a given string
//
vtTerrain *vtTerrainScene::FindTerrainByName(const char *name)
{
	int len = strlen(name);
	if (!len)
		return NULL;

	for (vtTerrain *pTerr = m_pFirstTerrain; pTerr; pTerr=pTerr->GetNext())
	{
		if (!strncmp(name, pTerr->GetName(), len))
			return pTerr;
	}
	return NULL;
}

void vtTerrainScene::create_fog()
{
#if 0
	int dist = m_pFirstTerrain->m_Params.m_iFogDistance;

	m_pFog = new vtFog();
	m_pFog->SetStart(1.0f);  // only useful for linear - broken
	m_pFog->SetEnd(dist * 1000.0f * WORLD_SCALE);

	// 1 / ( dist / slope + max )
	// dist = visability distance
	// slope = how fast density varies by dist, smaller = see farther (guessing)
	// max = max density of fog = (2 - max), so 1.2 = max density of 0.8

	m_pFog->SetDensity( 1.0f / (dist/4.0f + 1.3f) ); // vis dis function of density

	m_pFog->SetColor(horizon_color);
	//m_pFog->SetKind(FOG_Exponential2 | FOG_Pixel); // from linear
	m_pFog->SetKind(FOG_Linear); // from linear
#endif
}

void vtTerrainScene::create_engines(bool bDoSound)
{
	// Set Time in motion
	m_pTime = new TimeEngine(this, 0);
	m_pTime->SetName2("Time");
	vtGetScene()->AddEngine(m_pTime);
}

vtRoot *vtTerrainScene::BeginTerrainScene(bool bDoSound)
{
	create_engines(bDoSound);

	m_pTop = new vtRoot();
	m_pTop->SetName2("All Terrain");

	// create the sun
	vtLight *pLight = new vtLight();
	m_pSunLight = new vtMovLight(pLight);

	// default location: over our right shoulder, pointing downward
	m_pSunLight->Translate1(FPoint3(1000.0f, 1000.0f, 1000.0f));
	m_pSunLight->RotateLocal(FPoint3(0,1,0), PIf/4.0f);
	m_pSunLight->RotateLocal(FPoint3(1,0,0), -PIf/4.0f);
	m_pSunLight->SetName2("SunLight");

	m_pTop->AddChild(m_pSunLight);

	// create sky group - this holds all celestial objects
	m_pAtmosphereGroup = new vtGroup();
	m_pAtmosphereGroup->SetName2("Atmosphere Group");
	m_pTop->AddChild(m_pAtmosphereGroup);

	return m_pTop;
}

void vtTerrainScene::AppendTerrain(vtTerrain *pTerrain)
{
	// add to linked list
	pTerrain->SetNext(m_pFirstTerrain);
	m_pFirstTerrain = pTerrain;
}

//
// call after you have appended all terrains
//
void vtTerrainScene::Finish(const char *datapath)
{
	create_skydome(datapath);

	// create fog AFTER the shapes
//	if (m_pFirstTerrain != NULL)
//		create_fog();

	// start out with no scene active
	for (vtTerrain *t = m_pFirstTerrain; t != NULL; t=t->GetNext())
		t->ActivateEngines(false);
}

void vtTerrainScene::SetTerrain(vtTerrain *pTerrain)
{
	if (m_pCurrentTerrain != NULL)
	{
		// turn off the scene graph of the previous terrain
		m_pCurrentTerrain->Enable(false);

		// turn off the engines specific to the previous terrain
		m_pCurrentTerrain->ActivateEngines(false);
	}
	m_pCurrentTerrain = pTerrain;

	// if setting to no terrain nothing more to do
	if (!pTerrain)
	{
		if (m_pSkyDome != NULL)
			m_pSkyDome->SetEnabled(false);
		return;
	}

	// switch
	m_pTop->AddChild(m_pCurrentTerrain->m_pTerrainGroup);
	m_pCurrentTerrain->Enable(true);

	// switch to the projection of this terrain
	m_pCurrentTerrain->SetGlobalProjection();

	// move the sky to fit the new current terrain
	m_pSkyDome->SetEnabled(true);
	float radius = pTerrain->GetRadius() * 2.9f;
	float max_radius = (450000 * WORLD_SCALE);
	if (radius > max_radius)
		radius = max_radius;
	m_pSkyDome->SetRadius(radius);
	FPoint3 center = pTerrain->GetCenter();
	center.y = 0.0f;
	m_pSkyDome->SetTrans(center);

	// Set background color to match the ocean
	vtGetScene()->SetBgColor(m_pCurrentTerrain->GetOceanColor());

	// turn on the engines specific to the new terrain
	m_pCurrentTerrain->ActivateEngines(true);

	// set the time to the time of the new terrain
	TParams &param = m_pCurrentTerrain->GetParams();
	int time = param.m_iInitTime * 3600;
	SetTimeOfDay(time, true);

	// setup time engine
	m_pTime->SetTime(time);
	m_pTime->SetRealIncrement(param.m_fTimeSpeed);
	m_pTime->SetEnabled(param.m_bTimeOn);

	// handle the atmosphere
	m_pSkyDome->SetEnabled(param.m_bSky);
	SetFog(param.m_bFog);
}

void vtTerrainScene::ToggleFog()
{
	SetFog(!m_bFog);
}

void vtTerrainScene::SetFog(bool fog)
{
#if 0
	m_bFog = fog;
	if (m_bFog)
	{
		vtGetScene()->SetFog(m_pFog);
		vtGetScene()->SetBackColor(horizon_color);
//		vtGetScene()->GetCamera()->GetYon(m_pFirstTerrain
		vtGetScene()->GetCamera()->SetYon(m_pFirstTerrain->m_Params.m_iFogDistance	* 1000.0f * WORLD_SCALE);
	}
	else
	{
		vtGetScene()->SetFog(NULL);
		vtScene::SetBgColor(m_pCurrentTerrain->GetOceanColor());
		vtGetScene()->GetCamera()->SetYon(m_yondist);
	}
#endif
}

void vtTerrainScene::SetTimeOfDay(unsigned int time, bool fFullRefresh)
{
	if (m_pSkyDome)
	{
		m_pSkyDome->SetSunLight(GetSunLight());
		m_pSkyDome->SetTimeOfDay(time, fFullRefresh);
//		m_pSkyDome->ApplyDayColors();
	}
	// TODO? Update the fog color to match the color of the horizon.
}

<|endoftext|>


<commit_before><commit_msg>cppcheck: redundantAssignment<commit_after><|endoftext|>