<commit_before>#include "entry_ctrl.hpp"
#include "account.hpp"
#include "account_ctrl.hpp"
#include "account_reader.hpp"
#include "decimal_text_ctrl.hpp"
#include "entry.hpp"
#include "finformat.hpp"
#include "locale.hpp"
#include "transaction_type.hpp"
#include <boost/scoped_ptr.hpp>
#include <jewel/decimal.hpp>
#include <wx/button.h>
#include <wx/gbsizer.h>
#include <wx/gdicmn.h>
#include <wx/panel.h>
#include <wx/string.h>
#include <cassert>
#include <vector>

using boost::scoped_ptr;
using jewel::Decimal;
using std::vector;

#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;

namespace phatbooks
{
namespace gui
{

BEGIN_EVENT_TABLE(EntryCtrl, wxPanel)
	EVT_BUTTON
	(	s_split_button_id,
		EntryCtrl::on_split_button_click
	)
END_EVENT_TABLE()

EntryCtrl::EntryCtrl
(	wxWindow* p_parent,
	vector<Account> const& p_accounts,
	PhatbooksDatabaseConnection& p_database_connection,
	transaction_type::TransactionType p_transaction_type,
	wxSize const& p_text_ctrl_size,
	bool p_is_source,
	Decimal const& p_primary_amount
):
	wxPanel(p_parent),
	m_database_connection(p_database_connection),
	m_is_source(p_is_source),
	m_primary_amount(p_primary_amount),
	m_transaction_type(p_transaction_type),
	m_account_reader(0),
	m_text_ctrl_size(p_text_ctrl_size),
	m_top_sizer(0),
	m_side_descriptor(0),
	m_next_row(0)
{
	assert (m_account_name_boxes.empty());
	assert (m_comment_boxes.empty());

	assert_transaction_type_validity(m_transaction_type);

	m_top_sizer = new wxGridBagSizer();
	SetSizer(m_top_sizer);

	// Row 0

	assert (m_next_row == 0);

	m_side_descriptor = new wxStaticText(this, wxID_ANY, side_description());
	m_top_sizer->Add(m_side_descriptor, wxGBPosition(m_next_row, 0));

	wxStaticText* const comment_label = new wxStaticText
	(	this,
		wxID_ANY,
		wxString(" Memo:"),
		wxDefaultPosition,
		wxDefaultSize,
		wxALIGN_LEFT
	);
	m_top_sizer->Add(comment_label, wxGBPosition(m_next_row, 1));

	m_split_button = new wxButton
	(	this,
		s_split_button_id,
		wxString("Split..."),
		wxDefaultPosition,
		m_text_ctrl_size
	);
	m_top_sizer->Add(m_split_button, wxGBPosition(m_next_row, 3));

	// Subsequent rows

	++m_next_row;

	if (m_is_source)
	{
		assert (!m_account_reader);
		m_account_reader = create_source_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}
	else
	{
		assert (!m_account_reader);
		m_account_reader = create_destination_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}

	vector<Account>::const_iterator it = p_accounts.begin();
	vector<Account>::const_iterator const end = p_accounts.end();

	// TODO Factor this out. (Re-used add_row().)
	for (size_t entry_num = 0; it != end; ++it, ++m_next_row, ++entry_num)
	{
		AccountCtrl* account_name_box = new AccountCtrl
		(	this,
			wxID_ANY,
			*it,
			m_text_ctrl_size,
			m_account_reader->begin(),
			m_account_reader->end(),
			m_database_connection
		);
		m_top_sizer->Add(account_name_box, wxGBPosition(m_next_row, 0));
		m_account_name_boxes.push_back(account_name_box);
		wxTextCtrl* comment_ctrl = new wxTextCtrl
		(	this,
			wxID_ANY,
			wxEmptyString,
			wxDefaultPosition,
			wxSize(m_text_ctrl_size.x * 2, m_text_ctrl_size.y),
			wxALIGN_LEFT
		);
		m_top_sizer->
			Add(comment_ctrl, wxGBPosition(m_next_row, 1), wxGBSpan(1, 2));
		m_comment_boxes.push_back(comment_ctrl);

		Decimal::places_type const precision = m_primary_amount.places();
		DecimalTextCtrl* amount_ctrl = new DecimalTextCtrl
		(	this,
			wxID_ANY,
			m_text_ctrl_size,
			precision,
			false
		);
		if (entry_num == 0)
		{
			amount_ctrl->set_amount(m_primary_amount);
		}
		m_top_sizer->Add(amount_ctrl, wxGBPosition(m_next_row, 3));
		m_amount_boxes.push_back(amount_ctrl);
	}

	m_top_sizer->Fit(this);
	m_top_sizer->SetSizeHints(this);
	// Fit();
	// Layout();
	GetParent()->Fit();
}

EntryCtrl::~EntryCtrl()
{
	delete m_account_reader;
	m_account_reader = 0;
}

void
EntryCtrl::refresh_for_transaction_type
(	transaction_type::TransactionType p_transaction_type
)
{
	JEWEL_DEBUG_LOG << "Entered EntryCtrl::refresh_for_transaction_type." << endl;
	assert_transaction_type_validity(p_transaction_type);
	if (p_transaction_type == m_transaction_type)
	{
		// Do nothing
		return;
	}
	assert (p_transaction_type != m_transaction_type);
	m_transaction_type = p_transaction_type;

	delete m_account_reader;
	m_account_reader = 0;

	if (m_is_source)
	{
		assert (!m_account_reader);
		m_account_reader = create_source_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}
	else
	{
		assert (!m_account_reader);
		m_account_reader = create_destination_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}
	for
	(	vector<AccountCtrl*>::size_type i = 0;
		i != m_account_name_boxes.size();
		++i
	)
	{
		assert (m_account_reader);
		m_account_name_boxes[i]->
			set(m_account_reader->begin(), m_account_reader->end());
	}
	return;
}

void
EntryCtrl::set_primary_amount(Decimal const& p_primary_amount)
{
	m_primary_amount = p_primary_amount;
	typedef vector<DecimalTextCtrl*>::size_type Size;
	Size const sz = m_amount_boxes.size();
	assert (sz > 0);
	m_amount_boxes[0]->set_amount(m_primary_amount);
	for (Size i = 1; i != sz; ++i)
	{
		m_amount_boxes[i]->set_amount(Decimal(0, m_primary_amount.places()));
	}
	return;
}

vector<Entry>
EntryCtrl::make_entries() const
{
	assert (m_account_name_boxes.size() == m_comment_boxes.size());
	assert (m_comment_boxes.size() == m_amount_boxes.size());
	assert (m_amount_boxes.size() == m_account_name_boxes.size());
	typedef std::vector<Entry>::size_type Size;
	Size const sz = m_account_name_boxes.size();

	vector<Entry> ret;
	for (Size i = 0; i != sz; ++i)
	{
		Entry entry(m_database_connection);

		assert (m_account_name_boxes[i]);
		entry.set_account(m_account_name_boxes[i]->account());

		assert (m_comment_boxes[i]);
		entry.set_comment(wx_to_bstring(m_comment_boxes[i]->GetValue()));

		assert (m_amount_boxes[i]);
		Decimal amount = m_amount_boxes[i]->amount();
		if (!transaction_type_is_actual(m_transaction_type))
		{
			amount = -amount;
		}
		if (m_is_source)
		{
			amount = -amount;
		}
		entry.set_amount(amount);

		entry.set_whether_reconciled(false);

		ret.push_back(entry);
		assert (!entry.has_id());
	}

	assert (ret.size() == sz);
	return ret;
}

void
EntryCtrl::on_split_button_click(wxCommandEvent& event)
{
	(void)event;  // Silence compiler warning re. unused parameter.
	add_row();
	return;
}

void
EntryCtrl::add_row()
{
	assert (m_account_name_boxes.size() >= 1);
	AccountCtrl* account_name_box = new AccountCtrl
	(	this,
		wxID_ANY,
		m_account_name_boxes.at(m_account_name_boxes.size() - 1)->account(),
		m_text_ctrl_size,
		m_account_reader->begin(),
		m_account_reader->end(),
		m_database_connection
	);
	m_top_sizer->Add(account_name_box, wxGBPosition(m_next_row, 0));
	m_account_name_boxes.push_back(account_name_box);
	wxTextCtrl* comment_ctrl = new wxTextCtrl
	(	this,
		wxID_ANY,
		wxEmptyString,
		wxDefaultPosition,
		wxSize(m_text_ctrl_size.x * 2, m_text_ctrl_size.y),
		wxALIGN_LEFT
	);
	m_top_sizer->
		Add(comment_ctrl, wxGBPosition(m_next_row, 1), wxGBSpan(1, 2));
	m_comment_boxes.push_back(comment_ctrl);

	DecimalTextCtrl* amount_ctrl = new DecimalTextCtrl
	(	this,
		wxID_ANY,
		m_text_ctrl_size,
		m_primary_amount.places(),
		false
	);
	m_top_sizer->Add(amount_ctrl, wxGBPosition(m_next_row, 3));
	m_amount_boxes.push_back(amount_ctrl);

	++m_next_row;

	Layout();  // Must call this.
	m_top_sizer->Fit(this);
	m_top_sizer->SetSizeHints(this);
	// GetParent()->Layout(); // Do not call this.
	// GetParent()->GetSizer()->RecalcSizes();  // Do not call this.
	GetParent()->Fit();

	return;
}

wxString
EntryCtrl::side_description() const
{
	if (m_is_source)
	{
		return " Source:";
	}
	assert (!m_is_source);
	return " Destination:";
}

}  // namespace gui
}  // namespace phatbooks
<commit_msg>On EntryCtrl, "Split" button now says "Split" instead of "Split...". The dots were misleading as conventionally this implies a new dialog window will pop up.<commit_after>#include "entry_ctrl.hpp"
#include "account.hpp"
#include "account_ctrl.hpp"
#include "account_reader.hpp"
#include "decimal_text_ctrl.hpp"
#include "entry.hpp"
#include "finformat.hpp"
#include "locale.hpp"
#include "transaction_type.hpp"
#include <boost/scoped_ptr.hpp>
#include <jewel/decimal.hpp>
#include <wx/button.h>
#include <wx/gbsizer.h>
#include <wx/gdicmn.h>
#include <wx/panel.h>
#include <wx/string.h>
#include <cassert>
#include <vector>

using boost::scoped_ptr;
using jewel::Decimal;
using std::vector;

#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;

namespace phatbooks
{
namespace gui
{

BEGIN_EVENT_TABLE(EntryCtrl, wxPanel)
	EVT_BUTTON
	(	s_split_button_id,
		EntryCtrl::on_split_button_click
	)
END_EVENT_TABLE()

EntryCtrl::EntryCtrl
(	wxWindow* p_parent,
	vector<Account> const& p_accounts,
	PhatbooksDatabaseConnection& p_database_connection,
	transaction_type::TransactionType p_transaction_type,
	wxSize const& p_text_ctrl_size,
	bool p_is_source,
	Decimal const& p_primary_amount
):
	wxPanel(p_parent),
	m_database_connection(p_database_connection),
	m_is_source(p_is_source),
	m_primary_amount(p_primary_amount),
	m_transaction_type(p_transaction_type),
	m_account_reader(0),
	m_text_ctrl_size(p_text_ctrl_size),
	m_top_sizer(0),
	m_side_descriptor(0),
	m_next_row(0)
{
	assert (m_account_name_boxes.empty());
	assert (m_comment_boxes.empty());

	assert_transaction_type_validity(m_transaction_type);

	m_top_sizer = new wxGridBagSizer();
	SetSizer(m_top_sizer);

	// Row 0

	assert (m_next_row == 0);

	m_side_descriptor = new wxStaticText(this, wxID_ANY, side_description());
	m_top_sizer->Add(m_side_descriptor, wxGBPosition(m_next_row, 0));

	wxStaticText* const comment_label = new wxStaticText
	(	this,
		wxID_ANY,
		wxString(" Memo:"),
		wxDefaultPosition,
		wxDefaultSize,
		wxALIGN_LEFT
	);
	m_top_sizer->Add(comment_label, wxGBPosition(m_next_row, 1));

	m_split_button = new wxButton
	(	this,
		s_split_button_id,
		wxString("Split"),
		wxDefaultPosition,
		m_text_ctrl_size
	);
	m_top_sizer->Add(m_split_button, wxGBPosition(m_next_row, 3));

	// Subsequent rows

	++m_next_row;

	if (m_is_source)
	{
		assert (!m_account_reader);
		m_account_reader = create_source_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}
	else
	{
		assert (!m_account_reader);
		m_account_reader = create_destination_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}

	vector<Account>::const_iterator it = p_accounts.begin();
	vector<Account>::const_iterator const end = p_accounts.end();

	// TODO Factor this out. (Re-used add_row().)
	for (size_t entry_num = 0; it != end; ++it, ++m_next_row, ++entry_num)
	{
		AccountCtrl* account_name_box = new AccountCtrl
		(	this,
			wxID_ANY,
			*it,
			m_text_ctrl_size,
			m_account_reader->begin(),
			m_account_reader->end(),
			m_database_connection
		);
		m_top_sizer->Add(account_name_box, wxGBPosition(m_next_row, 0));
		m_account_name_boxes.push_back(account_name_box);
		wxTextCtrl* comment_ctrl = new wxTextCtrl
		(	this,
			wxID_ANY,
			wxEmptyString,
			wxDefaultPosition,
			wxSize(m_text_ctrl_size.x * 2, m_text_ctrl_size.y),
			wxALIGN_LEFT
		);
		m_top_sizer->
			Add(comment_ctrl, wxGBPosition(m_next_row, 1), wxGBSpan(1, 2));
		m_comment_boxes.push_back(comment_ctrl);

		Decimal::places_type const precision = m_primary_amount.places();
		DecimalTextCtrl* amount_ctrl = new DecimalTextCtrl
		(	this,
			wxID_ANY,
			m_text_ctrl_size,
			precision,
			false
		);
		if (entry_num == 0)
		{
			amount_ctrl->set_amount(m_primary_amount);
		}
		m_top_sizer->Add(amount_ctrl, wxGBPosition(m_next_row, 3));
		m_amount_boxes.push_back(amount_ctrl);
	}

	m_top_sizer->Fit(this);
	m_top_sizer->SetSizeHints(this);
	// Fit();
	// Layout();
	GetParent()->Fit();
}

EntryCtrl::~EntryCtrl()
{
	delete m_account_reader;
	m_account_reader = 0;
}

void
EntryCtrl::refresh_for_transaction_type
(	transaction_type::TransactionType p_transaction_type
)
{
	JEWEL_DEBUG_LOG << "Entered EntryCtrl::refresh_for_transaction_type." << endl;
	assert_transaction_type_validity(p_transaction_type);
	if (p_transaction_type == m_transaction_type)
	{
		// Do nothing
		return;
	}
	assert (p_transaction_type != m_transaction_type);
	m_transaction_type = p_transaction_type;

	delete m_account_reader;
	m_account_reader = 0;

	if (m_is_source)
	{
		assert (!m_account_reader);
		m_account_reader = create_source_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}
	else
	{
		assert (!m_account_reader);
		m_account_reader = create_destination_account_reader
		(	m_database_connection,
			m_transaction_type
		);
	}
	for
	(	vector<AccountCtrl*>::size_type i = 0;
		i != m_account_name_boxes.size();
		++i
	)
	{
		assert (m_account_reader);
		m_account_name_boxes[i]->
			set(m_account_reader->begin(), m_account_reader->end());
	}
	return;
}

void
EntryCtrl::set_primary_amount(Decimal const& p_primary_amount)
{
	m_primary_amount = p_primary_amount;
	typedef vector<DecimalTextCtrl*>::size_type Size;
	Size const sz = m_amount_boxes.size();
	assert (sz > 0);
	m_amount_boxes[0]->set_amount(m_primary_amount);
	for (Size i = 1; i != sz; ++i)
	{
		m_amount_boxes[i]->set_amount(Decimal(0, m_primary_amount.places()));
	}
	return;
}

vector<Entry>
EntryCtrl::make_entries() const
{
	assert (m_account_name_boxes.size() == m_comment_boxes.size());
	assert (m_comment_boxes.size() == m_amount_boxes.size());
	assert (m_amount_boxes.size() == m_account_name_boxes.size());
	typedef std::vector<Entry>::size_type Size;
	Size const sz = m_account_name_boxes.size();

	vector<Entry> ret;
	for (Size i = 0; i != sz; ++i)
	{
		Entry entry(m_database_connection);

		assert (m_account_name_boxes[i]);
		entry.set_account(m_account_name_boxes[i]->account());

		assert (m_comment_boxes[i]);
		entry.set_comment(wx_to_bstring(m_comment_boxes[i]->GetValue()));

		assert (m_amount_boxes[i]);
		Decimal amount = m_amount_boxes[i]->amount();
		if (!transaction_type_is_actual(m_transaction_type))
		{
			amount = -amount;
		}
		if (m_is_source)
		{
			amount = -amount;
		}
		entry.set_amount(amount);

		entry.set_whether_reconciled(false);

		ret.push_back(entry);
		assert (!entry.has_id());
	}

	assert (ret.size() == sz);
	return ret;
}

void
EntryCtrl::on_split_button_click(wxCommandEvent& event)
{
	(void)event;  // Silence compiler warning re. unused parameter.
	add_row();
	return;
}

void
EntryCtrl::add_row()
{
	assert (m_account_name_boxes.size() >= 1);
	AccountCtrl* account_name_box = new AccountCtrl
	(	this,
		wxID_ANY,
		m_account_name_boxes.at(m_account_name_boxes.size() - 1)->account(),
		m_text_ctrl_size,
		m_account_reader->begin(),
		m_account_reader->end(),
		m_database_connection
	);
	m_top_sizer->Add(account_name_box, wxGBPosition(m_next_row, 0));
	m_account_name_boxes.push_back(account_name_box);
	wxTextCtrl* comment_ctrl = new wxTextCtrl
	(	this,
		wxID_ANY,
		wxEmptyString,
		wxDefaultPosition,
		wxSize(m_text_ctrl_size.x * 2, m_text_ctrl_size.y),
		wxALIGN_LEFT
	);
	m_top_sizer->
		Add(comment_ctrl, wxGBPosition(m_next_row, 1), wxGBSpan(1, 2));
	m_comment_boxes.push_back(comment_ctrl);

	DecimalTextCtrl* amount_ctrl = new DecimalTextCtrl
	(	this,
		wxID_ANY,
		m_text_ctrl_size,
		m_primary_amount.places(),
		false
	);
	m_top_sizer->Add(amount_ctrl, wxGBPosition(m_next_row, 3));
	m_amount_boxes.push_back(amount_ctrl);

	++m_next_row;

	Layout();  // Must call this.
	m_top_sizer->Fit(this);
	m_top_sizer->SetSizeHints(this);
	// GetParent()->Layout(); // Do not call this.
	// GetParent()->GetSizer()->RecalcSizes();  // Do not call this.
	GetParent()->Fit();

	return;
}

wxString
EntryCtrl::side_description() const
{
	if (m_is_source)
	{
		return " Source:";
	}
	assert (!m_is_source);
	return " Destination:";
}

}  // namespace gui
}  // namespace phatbooks
<|endoftext|>


<commit_before>/*

Copyright (c) 2017 Maksim Galkin

This file is subject to the terms and conditions of the MIT license,
distributed with this code package in the LICENSE file, also available at:
https://github.com/yacoder/allo-cpp/blob/master/LICENSE

*/

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "allo.hpp"

#include <array>
#include <string>
#include <vector>

TEST_CASE("Counting strategy can count", "[counting-strategy]")
{
   allo::strategies::counting_strategy counting_strategy;

   REQUIRE(counting_strategy.number_of_allocations() == 0);
   REQUIRE(counting_strategy.number_of_deallocations() == 0);

   REQUIRE(counting_strategy.allocate<void>(100) == nullptr);

   REQUIRE(counting_strategy.number_of_allocations() == 1);
   REQUIRE(counting_strategy.number_of_deallocations() == 0);

   REQUIRE(counting_strategy.deallocate<void>(&counting_strategy, 1) == false);

   REQUIRE(counting_strategy.number_of_allocations() == 1);
   REQUIRE(counting_strategy.number_of_deallocations() == 1);
}

TEST_CASE("Never-look-back strategy allocates until out of buffer", "[never-look-back-strategy]")
{
   std::array<uint8_t, 3> buffer{};
   auto* buffer_begin = buffer.data();
   auto* buffer_end = buffer.data() + buffer.size();
   allo::strategies::never_look_back_strategy never_look_back_strategy(buffer_begin, buffer_end);

   auto* first_byte = never_look_back_strategy.allocate<uint8_t>(1);
   REQUIRE(first_byte == buffer.data());

   auto* too_large = never_look_back_strategy.allocate<uint8_t>(3);
   REQUIRE(too_large == nullptr);

   auto* last_two_bytes = never_look_back_strategy.allocate<uint8_t>(2);
   REQUIRE(last_two_bytes == buffer.data() + 1);

   // should run out of buffer by now
   REQUIRE(never_look_back_strategy.allocate<uint8_t>(1) == nullptr);

   // strategy must not recognize other pointers
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(nullptr, 1) == false);
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(buffer_end, 1) == false);

   // strategy must recognize the pointers it allocated
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(first_byte, 1) == true);
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(last_two_bytes, 2) == true);

   // even after we have deallocated everything, we can't allocate again fom it
   REQUIRE(never_look_back_strategy.allocate<uint8_t>(1) == nullptr);
}

TEST_CASE("Counting allocator works with standard vector", "[counting-allocator][counting-strategy][vector]")
{
   using allocator_t = allo::counting_allocator<int>;
   allo::strategies::counting_strategy counting_strategy;

   {
      allocator_t allocator(counting_strategy);
      std::vector<int, allocator_t> v(allocator);
      v.push_back(1);

      REQUIRE(counting_strategy.number_of_allocations() == 1);
      REQUIRE(counting_strategy.number_of_deallocations() == 0);
   }

   REQUIRE(counting_strategy.number_of_allocations() == 1);
   REQUIRE(counting_strategy.number_of_deallocations() == 1);
}

TEST_CASE("Never-look-back strategy works with standard vector",
          "[never-look-back-strategy][never-look-back-allocator][vector]")
{
   const int N = 2048;
   std::array<uint8_t, N> buffer{};
   auto* buffer_begin = buffer.data();
   auto* buffer_end = buffer.data() + buffer.size();

   allo::strategies::never_look_back_strategy never_look_back_strategy(buffer_begin, buffer_end);

   // We will use counting allocator to make sure no allocations fall through to std allocator.
   allo::strategies::counting_strategy counting_strategy;

   {
      allo::counting_allocator<uint16_t> counting_allocator(counting_strategy);
      allo::never_look_back_allocator<uint16_t, decltype(counting_allocator)> allocator(never_look_back_strategy,
                                                                                counting_allocator);
      std::vector<uint16_t, decltype(allocator)> v(allocator);
      v.reserve(N / 2);
      v.push_back(42);

      REQUIRE(v[0] == 42);
      REQUIRE(*reinterpret_cast<uint16_t*>(&buffer[0]) == 42);
      REQUIRE(counting_strategy.number_of_allocations() == 0);
      REQUIRE(counting_strategy.number_of_deallocations() == 0);
   }

   REQUIRE(counting_strategy.number_of_allocations() == 0);
   REQUIRE(counting_strategy.number_of_deallocations() == 0);
}

TEST_CASE("Wrapped map works as a map", "[wrapped-map]")
{
   allo::containers::wrapped_map<uint16_t, std::string> wrapped_map(1000);
   auto& m = wrapped_map.unwrap();

   m[42] = "hello, world!";

   REQUIRE(m.size() == 1);
   REQUIRE(m[42] == "hello, world!");
}

TEST_CASE("Wrapped map must not abandon memory if it had to allocate outside private pool", "[wrapped-map][abandon]")
{
    // We will use counting allocator to make sure no allocations fall through to std allocator.
    allo::strategies::counting_strategy counting_strategy;

    {
        allo::counting_allocator<uint16_t> counting_allocator(counting_strategy);

        // Create with empty private pool.
        // So in the end we must get as many deallocations as allocations.
        allo::containers::wrapped_map<uint16_t, std::string, allo::counting_allocator> wrapped_map(0, counting_allocator);
        auto& map = wrapped_map.unwrap();

        map[42] = "hello, world!";

        REQUIRE(map.size() == 1);
        REQUIRE(map[42] == "hello, world!");
    }

    REQUIRE(counting_strategy.number_of_allocations() > 0);
    REQUIRE(counting_strategy.number_of_deallocations() == counting_strategy.number_of_allocations());
}
<commit_msg>formatting update in tests.cpp<commit_after>/*

Copyright (c) 2017 Maksim Galkin

This file is subject to the terms and conditions of the MIT license,
distributed with this code package in the LICENSE file, also available at:
https://github.com/yacoder/allo-cpp/blob/master/LICENSE

*/

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "allo.hpp"

#include <array>
#include <string>
#include <vector>

TEST_CASE("Counting strategy can count", "[counting-strategy]")
{
   allo::strategies::counting_strategy counting_strategy;

   REQUIRE(counting_strategy.number_of_allocations() == 0);
   REQUIRE(counting_strategy.number_of_deallocations() == 0);

   REQUIRE(counting_strategy.allocate<void>(100) == nullptr);

   REQUIRE(counting_strategy.number_of_allocations() == 1);
   REQUIRE(counting_strategy.number_of_deallocations() == 0);

   REQUIRE(counting_strategy.deallocate<void>(&counting_strategy, 1) == false);

   REQUIRE(counting_strategy.number_of_allocations() == 1);
   REQUIRE(counting_strategy.number_of_deallocations() == 1);
}

TEST_CASE("Never-look-back strategy allocates until out of buffer", "[never-look-back-strategy]")
{
   std::array<uint8_t, 3> buffer{};
   auto* buffer_begin = buffer.data();
   auto* buffer_end = buffer.data() + buffer.size();
   allo::strategies::never_look_back_strategy never_look_back_strategy(buffer_begin, buffer_end);

   auto* first_byte = never_look_back_strategy.allocate<uint8_t>(1);
   REQUIRE(first_byte == buffer.data());

   auto* too_large = never_look_back_strategy.allocate<uint8_t>(3);
   REQUIRE(too_large == nullptr);

   auto* last_two_bytes = never_look_back_strategy.allocate<uint8_t>(2);
   REQUIRE(last_two_bytes == buffer.data() + 1);

   // should run out of buffer by now
   REQUIRE(never_look_back_strategy.allocate<uint8_t>(1) == nullptr);

   // strategy must not recognize other pointers
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(nullptr, 1) == false);
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(buffer_end, 1) == false);

   // strategy must recognize the pointers it allocated
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(first_byte, 1) == true);
   REQUIRE(never_look_back_strategy.deallocate<uint8_t>(last_two_bytes, 2) == true);

   // even after we have deallocated everything, we can't allocate again fom it
   REQUIRE(never_look_back_strategy.allocate<uint8_t>(1) == nullptr);
}

TEST_CASE("Counting allocator works with standard vector", "[counting-allocator][counting-strategy][vector]")
{
   using allocator_t = allo::counting_allocator<int>;
   allo::strategies::counting_strategy counting_strategy;

   {
      allocator_t allocator(counting_strategy);
      std::vector<int, allocator_t> v(allocator);
      v.push_back(1);

      REQUIRE(counting_strategy.number_of_allocations() == 1);
      REQUIRE(counting_strategy.number_of_deallocations() == 0);
   }

   REQUIRE(counting_strategy.number_of_allocations() == 1);
   REQUIRE(counting_strategy.number_of_deallocations() == 1);
}

TEST_CASE("Never-look-back strategy works with standard vector",
          "[never-look-back-strategy][never-look-back-allocator][vector]")
{
   const int N = 2048;
   std::array<uint8_t, N> buffer{};
   auto* buffer_begin = buffer.data();
   auto* buffer_end = buffer.data() + buffer.size();

   allo::strategies::never_look_back_strategy never_look_back_strategy(buffer_begin, buffer_end);

   // We will use counting allocator to make sure no allocations fall through to std allocator.
   allo::strategies::counting_strategy counting_strategy;

   {
      allo::counting_allocator<uint16_t> counting_allocator(counting_strategy);
      allo::never_look_back_allocator<uint16_t, decltype(counting_allocator)> allocator(never_look_back_strategy,
                                                                                counting_allocator);
      std::vector<uint16_t, decltype(allocator)> v(allocator);
      v.reserve(N / 2);
      v.push_back(42);

      REQUIRE(v[0] == 42);
      REQUIRE(*reinterpret_cast<uint16_t*>(&buffer[0]) == 42);
      REQUIRE(counting_strategy.number_of_allocations() == 0);
      REQUIRE(counting_strategy.number_of_deallocations() == 0);
   }

   REQUIRE(counting_strategy.number_of_allocations() == 0);
   REQUIRE(counting_strategy.number_of_deallocations() == 0);
}

TEST_CASE("Wrapped map works as a map", "[wrapped-map]")
{
   allo::containers::wrapped_map<uint16_t, std::string> wrapped_map(1000);
   auto& m = wrapped_map.unwrap();

   m[42] = "hello, world!";

   REQUIRE(m.size() == 1);
   REQUIRE(m[42] == "hello, world!");
}

TEST_CASE("Wrapped map must not abandon memory if it had to allocate outside private pool", "[wrapped-map][abandon]")
{
   // We will use counting allocator to make sure no allocations fall through to std allocator.
   allo::strategies::counting_strategy counting_strategy;

   {
      allo::counting_allocator<uint16_t> counting_allocator(counting_strategy);

      // Create with empty private pool.
      // So in the end we must get as many deallocations as allocations.
      allo::containers::wrapped_map<uint16_t, std::string, allo::counting_allocator> wrapped_map(0, counting_allocator);
      auto& map = wrapped_map.unwrap();

      map[42] = "hello, world!";

      REQUIRE(map.size() == 1);
      REQUIRE(map[42] == "hello, world!");
   }

   REQUIRE(counting_strategy.number_of_allocations() > 0);
   REQUIRE(counting_strategy.number_of_deallocations() == counting_strategy.number_of_allocations());
}
<|endoftext|>


<commit_before>//headers
#include"game.h"

// display axis
// y
// ^
// |
// |
//  ------->x

//variables
short sDir; // snake direction
bool gameOver = false; //game over flag
bool gamePause = false; //game pause flag
bool gameWelcome = false; //game before start flag
int score; // score of game
int fps; // frame rate of game
bool sDirFlag = true; // snake direction change input flag
bool testFlag = false; //for testing the game
bool gridFlag = true; //show hide grids

// initalze the program
void myInit() {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    initGrid(ROWS,COLUMNS);
    initGame();
    gameWelcome = true;
}

//timer function for animation fps
void myTimer(int) {
    glutPostRedisplay();
    //increase fps by one unit after score increaases by 5
    if ((score % 2) == 0 && score != 0) {
        fps = MIN_FPS + floor(score / 2);
        if (fps > FPS) fps = FPS;
    }
    glutTimerFunc(1000 / fps, myTimer, 0);
}

//display function
void myDisplay() {
    glClear(GL_COLOR_BUFFER_BIT);
    //Welcome screen
    if (gameWelcome && !gamePause && !gameOver) {
        renderWelcome();
    }
    //Game screen
    else if (!gameWelcome && !gamePause && !gameOver) {
        renderGame();
    }
    //Pause Screen
    else if (!gameWelcome && gamePause && !gameOver) {
        renderPause();
    }
    //Exit Screen
    else if (gameOver && !gameWelcome) {
        renderExit();
    }
    glFlush();
    glutSwapBuffers();
}

//scaling & transform screen function
void myReshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
	glOrtho(0.0, COLUMNS, 0.0, ROWS, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

//keyboard special key
void mySpecialKeyboard(int key, int, int) {
    switch (key) {
        case GLUT_KEY_UP:
			if (!gameOver && !gamePause && !gameWelcome)
				turnUp();
            break;
        case GLUT_KEY_DOWN:
			if (!gameOver && !gamePause && !gameWelcome)
				turnDown();
            break;
        case GLUT_KEY_RIGHT:
			if (!gameOver && !gamePause && !gameWelcome)
				turnRight();
            break;
        case GLUT_KEY_LEFT:
			if (!gameOver && !gamePause && !gameWelcome)
				turnLeft();
            break;
    }
}

//keyboard alphanumeric
void myKeyboard(unsigned char key, int, int) {
    switch (key) {
        //restart after game over
        case 'n':
        case 'N':
            if (gameOver) {
                initGame();
                gameOver = !gameOver;
                gamePause = !gamePause;
                gameWelcome = true;
            }
            break;
        //pause
        case 'p':
        case 'P':
            if(!gameOver && !gameWelcome)
                gamePause = !gamePause;
            break;
        //exit
        case 'q':
        case 'Q':
            if (!gameOver && !gameWelcome)
                makeGameOver();
            else
                exit(0);
            break;
		//turn up
		case 'w':
		case 'W':
			if (!gameOver && !gamePause && !gameWelcome)
				turnUp();
			break;
		//start and turn down
		case 's':
		case 'S':
			if(gameWelcome)
				gameWelcome = false;
			else if (!gameOver && !gamePause && !gameWelcome)
				turnDown();
			break;
		//turn left
		case 'a':
		case 'A':
			if (!gameOver && !gamePause && !gameWelcome)
				turnLeft();
			break;
		//turn right
		case 'd':
		case 'D':
			if (!gameOver && !gamePause && !gameWelcome)
				turnRight();
			break;
		//test mode activation
		case 't':
		case 'T':
			testFlag = !testFlag;
			break;
        //show or hide grids
        case 'g':
        case 'G':
            gridFlag = !gridFlag;
            break;
    }
}

//main()
int main(int argc, char **argv) {
	srand((unsigned int)time(NULL));
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(600, 600);
    glutCreateWindow("Classical Snakes");
    glutPositionWindow(500, 100);
    glutDisplayFunc(myDisplay);
    glutReshapeFunc(myReshape);
    glutTimerFunc(0,myTimer,0);
    glutSpecialFunc(mySpecialKeyboard);
    glutKeyboardFunc(myKeyboard);
    myInit();
    glutMainLoop();
    return 0;
}
<commit_msg>Fixed scaling on non square displays<commit_after>//headers
#include"game.h"

// display axis
// y
// ^
// |
// |
//  ------->x

//variables
short sDir; // snake direction
bool gameOver = false; //game over flag
bool gamePause = false; //game pause flag
bool gameWelcome = false; //game before start flag
int score; // score of game
int fps; // frame rate of game
bool sDirFlag = true; // snake direction change input flag
bool testFlag = false; //for testing the game
bool gridFlag = true; //show hide grids

// initalze the program
void myInit() {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    initGrid(ROWS,COLUMNS);
    initGame();
    gameWelcome = true;
}

//timer function for animation fps
void myTimer(int) {
    glutPostRedisplay();
    //increase fps by one unit after score increaases by 5
    if ((score % 2) == 0 && score != 0) {
        fps = MIN_FPS + floor(score / 2);
        if (fps > FPS) fps = FPS;
    }
    glutTimerFunc(1000 / fps, myTimer, 0);
}

//display function
void myDisplay() {
    glClear(GL_COLOR_BUFFER_BIT);
    //Welcome screen
    if (gameWelcome && !gamePause && !gameOver) {
        renderWelcome();
    }
    //Game screen
    else if (!gameWelcome && !gamePause && !gameOver) {
        renderGame();
    }
    //Pause Screen
    else if (!gameWelcome && gamePause && !gameOver) {
        renderPause();
    }
    //Exit Screen
    else if (gameOver && !gameWelcome) {
        renderExit();
    }
    glFlush();
    glutSwapBuffers();
}

//scaling & transform screen function
void myReshape(int w, int h) {
    if(w == h)
        glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    else if(w < h)
        glViewport(0.0, (h - w)/2, (GLsizei)w, (GLsizei)w);
    else
        glViewport((w - h)/2, 0.0, (GLsizei)h, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, COLUMNS, 0.0, ROWS, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

//keyboard special key
void mySpecialKeyboard(int key, int, int) {
    switch (key) {
        case GLUT_KEY_UP:
			if (!gameOver && !gamePause && !gameWelcome)
				turnUp();
            break;
        case GLUT_KEY_DOWN:
			if (!gameOver && !gamePause && !gameWelcome)
				turnDown();
            break;
        case GLUT_KEY_RIGHT:
			if (!gameOver && !gamePause && !gameWelcome)
				turnRight();
            break;
        case GLUT_KEY_LEFT:
			if (!gameOver && !gamePause && !gameWelcome)
				turnLeft();
            break;
    }
}

//keyboard alphanumeric
void myKeyboard(unsigned char key, int, int) {
    switch (key) {
        //restart after game over
        case 'n':
        case 'N':
            if (gameOver) {
                initGame();
                gameOver = !gameOver;
                gamePause = !gamePause;
                gameWelcome = true;
            }
            break;
        //pause
        case 'p':
        case 'P':
            if(!gameOver && !gameWelcome)
                gamePause = !gamePause;
            break;
        //exit
        case 'q':
        case 'Q':
            if (!gameOver && !gameWelcome)
                makeGameOver();
            else
                exit(0);
            break;
		//turn up
		case 'w':
		case 'W':
			if (!gameOver && !gamePause && !gameWelcome)
				turnUp();
			break;
		//start and turn down
		case 's':
		case 'S':
			if(gameWelcome)
				gameWelcome = false;
			else if (!gameOver && !gamePause && !gameWelcome)
				turnDown();
			break;
		//turn left
		case 'a':
		case 'A':
			if (!gameOver && !gamePause && !gameWelcome)
				turnLeft();
			break;
		//turn right
		case 'd':
		case 'D':
			if (!gameOver && !gamePause && !gameWelcome)
				turnRight();
			break;
		//test mode activation
		case 't':
		case 'T':
			testFlag = !testFlag;
			break;
        //show or hide grids
        case 'g':
        case 'G':
            gridFlag = !gridFlag;
            break;
    }
}

//main()
int main(int argc, char **argv) {
	srand((unsigned int)time(NULL));
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(600, 600);
    glutCreateWindow("Classical Snakes");
    glutPositionWindow(500, 100);
    glutDisplayFunc(myDisplay);
    glutReshapeFunc(myReshape);
    glutTimerFunc(0,myTimer,0);
    glutSpecialFunc(mySpecialKeyboard);
    glutKeyboardFunc(myKeyboard);
    myInit();
    glutMainLoop();
    return 0;
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017 Darius Rückert
 * Licensed under the MIT License.
 * See LICENSE file for more information.
 */

#include "saiga/opengl/rendering/lighting/attenuated_light.h"

#include "saiga/core/imgui/imgui.h"
#include "saiga/core/util/assert.h"

namespace Saiga
{
void LightDistanceAttenuation::renderImGui()
{
    ImGui::InputFloat3("attenuation", &attenuation[0]);
    float c = Evaluate(radius);
    ImGui::Text("Cutoff Intensity: %f", c);
    ImGui::InputFloat("cutoffRadius", &radius);
}

}  // namespace Saiga
<commit_msg>attenuation slider<commit_after>/**
 * Copyright (c) 2017 Darius Rückert
 * Licensed under the MIT License.
 * See LICENSE file for more information.
 */

#include "saiga/opengl/rendering/lighting/attenuated_light.h"

#include "saiga/core/imgui/imgui.h"
#include "saiga/core/util/assert.h"

namespace Saiga
{
void LightDistanceAttenuation::renderImGui()
{
    ImGui::SliderFloat("atten. a", &attenuation[0], 0, 2);
    ImGui::SliderFloat("atten. b", &attenuation[1], 0, 2);
    ImGui::SliderFloat("atten. c", &attenuation[2], 0, 2);
    ImGui::InputFloat3("attenuation", &attenuation[0]);
    float c = Evaluate(radius);
    ImGui::Text("Cutoff Intensity: %f", c);
    ImGui::InputFloat("cutoffRadius", &radius);
}

}  // namespace Saiga
<|endoftext|>


<commit_before>#include "Box2D/Box2D.h"

#include "pixelboost/graphics/renderer/box2d/box2dRenderer.h"
#include "pixelboost/logic/system/physics/2d/physics.h"

using namespace pb;

PhysicsSystem2D::PhysicsSystem2D(glm::vec2 gravity)
    : _DebugRender(false)
    , _PositionIterations(3)
    , _VelocityIterations(3)
{
    _World = new b2World(b2Vec2(gravity.x, gravity.y));

    _DebugRenderer = new Box2dRenderer();
    _World->SetDebugDraw(_DebugRenderer);
}

PhysicsSystem2D::~PhysicsSystem2D()
{

}

pb::Uid PhysicsSystem2D::GetType()
{
    return PhysicsSystem2D::GetStaticType();
}

pb::Uid PhysicsSystem2D::GetStaticType()
{
    return pb::TypeHash("pb::PhysicsSystem2D");
}

void PhysicsSystem2D::Update(Scene* scene, float time)
{
    _World->Step(time, _VelocityIterations, _PositionIterations);
}

void PhysicsSystem2D::Render(Scene* scene, Viewport* viewport, RenderPass renderPass)
{
    if (_DebugRender)
    {
        _DebugRenderer->SetScene(scene);
        _World->DrawDebugData();
    }
}

b2World* PhysicsSystem2D::GetPhysicsWorld()
{
    return _World;
}

void PhysicsSystem2D::SetDebugRender(bool debugRender, int layer)
{
    _DebugRender = debugRender;
    _DebugRenderer->SetLayer(layer);
}
<commit_msg>Fix memory leak<commit_after>#include "Box2D/Box2D.h"

#include "pixelboost/graphics/renderer/box2d/box2dRenderer.h"
#include "pixelboost/logic/system/physics/2d/physics.h"

using namespace pb;

PhysicsSystem2D::PhysicsSystem2D(glm::vec2 gravity)
    : _DebugRender(false)
    , _PositionIterations(3)
    , _VelocityIterations(3)
{
    _World = new b2World(b2Vec2(gravity.x, gravity.y));

    _DebugRenderer = new Box2dRenderer();
    _World->SetDebugDraw(_DebugRenderer);
}

PhysicsSystem2D::~PhysicsSystem2D()
{
    delete _World;
}

pb::Uid PhysicsSystem2D::GetType()
{
    return PhysicsSystem2D::GetStaticType();
}

pb::Uid PhysicsSystem2D::GetStaticType()
{
    return pb::TypeHash("pb::PhysicsSystem2D");
}

void PhysicsSystem2D::Update(Scene* scene, float time)
{
    _World->Step(time, _VelocityIterations, _PositionIterations);
}

void PhysicsSystem2D::Render(Scene* scene, Viewport* viewport, RenderPass renderPass)
{
    if (_DebugRender)
    {
        _DebugRenderer->SetScene(scene);
        _World->DrawDebugData();
    }
}

b2World* PhysicsSystem2D::GetPhysicsWorld()
{
    return _World;
}

void PhysicsSystem2D::SetDebugRender(bool debugRender, int layer)
{
    _DebugRender = debugRender;
    _DebugRenderer->SetLayer(layer);
}
<|endoftext|>


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

// Base header file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif

#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>

#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>

#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>

#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"

XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)

/**
 * Processor interface options
 */
struct ProcessorOptions
{
    XalanNode*  initOptions;
    XalanNode*  compileOptions;
    XalanNode*  parseOptions;
    XalanNode*  resultOptions;
    XalanNode*  transformOptions;

    ProcessorOptions() :
            initOptions(0),
            compileOptions(0),
            parseOptions(0),
            resultOptions(0),
            transformOptions(0)
    {
    }
};

/**
 * Test case
 */
class TestCase
{
public:

    TestCase();

    TestCase(const TestCase& theRhs);

    XalanDOMString  stylesheet;
    XalanDOMString  inputDocument;
    XalanDOMString  resultDocument;
    XalanDOMString  resultDirectory;
    XalanDOMString  goldResult;
    long            numIterations;
    long            minTimeToExecute;
    bool            verifyResult;
    XalanDOMString  inputMode;

    typedef XalanMap<XalanDOMString, ProcessorOptions>  ProcessorOptionsMap;

    ProcessorOptionsMap processorOptions;
};

typedef TestCase                    TestCaseType;
typedef XalanVector<TestCaseType>   TestCasesType;

/**
 *  Test harness
 */
template <class Processor>
class TestHarness
{
public:

    typedef typename Processor::CompiledStylesheetType  CompiledStylesheetType;
    typedef typename Processor::ParsedInputSourceType   ParsedInputSourceType;
    typedef typename Processor::ResultTargetType        ResultTargetType;

    typedef typename XalanXMLFileReporter::Hashtable    TestAttributesType;

    TestHarness();

    void init(
            XalanFileUtility&       fileUtility,
            XalanXMLFileReporter&   reporter,
            Logger&                 logger);

    void terminate();

    void executeTestCase(const TestCaseType& testCase);

    void executeTestCases(const TestCasesType& testCases);

protected:

    Processor m_processor;

    XalanFileUtility*       m_fileUtility;

    XalanXMLFileReporter*   m_reporter;

    Logger*                 m_logger;
};

template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
    TestCasesType::const_iterator testCaseIter = testCases.begin();
    while (testCaseIter != testCases.end())
    {
        executeTestCase(*testCaseIter);
        ++testCaseIter;
    }
}

template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
    TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());

    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));

    try {

        CompiledStylesheetType  compiledStylesheet;
        ParsedInputSourceType   parsedInputSource;
        ResultTargetType        resultTarget;

        static const ProcessorOptions defaultProcessor;

        TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());

        const ProcessorOptions&  processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;

        m_fileUtility->checkAndCreateDir(testCase.resultDirectory);

        Timer timeCompile;

        if (testCase.inputMode == XalanDOMString("stream"))
        {
#if defined(XALAN_CLASSIC_IOSTREAMS)
            XALAN_USING_XALAN(CharVectorType)
            XALAN_USING_XALAN(c_str)

            XALAN_USING_STD(istringstream)

            CharVectorType  buffer;
            fileToStream(testCase.stylesheet, buffer);

            istrstream      compilerStream(c_str(buffer));
#else
            XALAN_USING_STD(istringstream)

            istringstream compilerStream;
            fileToStream(testCase.stylesheet, compilerStream);
#endif
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    compilerStream,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else if (testCase.inputMode == XalanDOMString("file"))
        {
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    testCase.stylesheet,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else
        {
            XALAN_USING_STD(endl)

            m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is inavlid for stylesheet: "
                    << testCase.stylesheet
                    << endl;
        }

        m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);

        long numIterations = 0;

        long totalParseInputTime = 0;
        long minParseInputTime = LONG_MAX;
        long maxParseInputTime = 0 ;

        long totalTransformTime = 0;
        long minTransformTime = LONG_MAX;
        long maxTransformTime = 0;

        Timer timeTotalRun;
        timeTotalRun.start();

        while (numIterations < testCase.numIterations
            && timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
        {
            Timer timeInput;
            if (testCase.inputMode == XalanDOMString("stream"))
            {
#if defined(XALAN_CLASSIC_IOSTREAMS)
                XALAN_USING_XALAN(CharVectorType)
                XALAN_USING_XALAN(c_str)

                XALAN_USING_STD(istringstream)

                CharVectorType  buffer;
                fileToStream(testCase.inputDocument, buffer);

                istrstream      inputStream(c_str(buffer));
#else
                XALAN_USING_STD(istringstream)

                istringstream inputStream;
                fileToStream(testCase.inputDocument, inputStream);
#endif

                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        inputStream,
                        processor.parseOptions);
                timeInput.stop();
            }
            else if (testCase.inputMode == XalanDOMString("file"))
            {
                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        testCase.inputDocument,
                        processor.parseOptions);
                timeInput.stop();
            }
            else
            {
                XALAN_USING_STD(endl)

                m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is inavlid for input document: "
                    << testCase.inputDocument
                    << endl;
            }

            totalParseInputTime += timeInput.getElapsedTime();
            minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
            maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;

            resultTarget = m_processor.createResultTarget(
                    testCase.resultDocument,
                    processor.resultOptions);

            Timer timeTransform;
            timeTransform.start();
            m_processor.transform(
                    compiledStylesheet,
                    parsedInputSource,
                    resultTarget);
            timeTransform.stop();

            totalTransformTime += timeTransform.getElapsedTime();
            minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
            maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;

            ++numIterations;
        }

        timeTotalRun.stop();

        m_processor.releaseStylesheet(compiledStylesheet);
        m_processor.releaseInputSource(parsedInputSource);
        m_processor.releaseResultTarget(resultTarget);

        if (true == testCase.verifyResult)
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
            if (checkFileExists(testCase.resultDocument))
            {
                if (checkFileExists(testCase.goldResult))
                {
                    if (m_fileUtility->compareSerializedResults(
                            testCase.resultDocument,
                            testCase.goldResult))
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
                    }
                    else
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
                    }
                }
                else
                {
                    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
                }
            }
            else
            {
                testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
            }
        }
        else
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
        }

        m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
        m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
        m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
        m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));

    }
    catch (const XalanDOMString& exception)
    {
        XALAN_USING_STD(endl)

        m_logger->error()
                << "Error encountered during transformation: "
                << testCase.stylesheet.c_str()
                << ", error: "
                << exception.c_str()
                << endl;

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
    }

    m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}

template <class Processor>
TestHarness<Processor>::TestHarness()
{

}

template <class Processor>
void
TestHarness<Processor>::init(
        XalanFileUtility&       fileUtility,
        XalanXMLFileReporter&   reporter,
        Logger&                 logger)
{
    m_processor.init();

    m_fileUtility = &fileUtility;

    m_reporter = &reporter;

    m_logger = &logger;
}

template <class Processor>
void
TestHarness<Processor>::terminate()
{
   m_processor.terminate();
}

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

// Base header file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif

#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>

#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>

#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>

#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"

XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)

/**
 * Processor interface options
 */
struct ProcessorOptions
{
    XalanNode*  initOptions;
    XalanNode*  compileOptions;
    XalanNode*  parseOptions;
    XalanNode*  resultOptions;
    XalanNode*  transformOptions;

    ProcessorOptions() :
            initOptions(0),
            compileOptions(0),
            parseOptions(0),
            resultOptions(0),
            transformOptions(0)
    {
    }
};

/**
 * Test case
 */
class TestCase
{
public:

    TestCase();

    TestCase(const TestCase& theRhs);

    XalanDOMString  stylesheet;
    XalanDOMString  inputDocument;
    XalanDOMString  resultDocument;
    XalanDOMString  resultDirectory;
    XalanDOMString  goldResult;
    long            numIterations;
    long            minTimeToExecute;
    bool            verifyResult;
    XalanDOMString  inputMode;

    typedef XalanMap<XalanDOMString, ProcessorOptions>  ProcessorOptionsMap;

    ProcessorOptionsMap processorOptions;
};

typedef TestCase                    TestCaseType;
typedef XalanVector<TestCaseType>   TestCasesType;

/**
 *  Test harness
 */
template <class Processor>
class TestHarness
{
public:

    typedef typename Processor::CompiledStylesheetType  CompiledStylesheetType;
    typedef typename Processor::ParsedInputSourceType   ParsedInputSourceType;
    typedef typename Processor::ResultTargetType        ResultTargetType;

    typedef typename XalanXMLFileReporter::Hashtable    TestAttributesType;

    TestHarness();

    void init(
            XalanFileUtility&       fileUtility,
            XalanXMLFileReporter&   reporter,
            Logger&                 logger);

    void terminate();

    void executeTestCase(const TestCaseType& testCase);

    void executeTestCases(const TestCasesType& testCases);

protected:

    Processor m_processor;

    XalanFileUtility*       m_fileUtility;

    XalanXMLFileReporter*   m_reporter;

    Logger*                 m_logger;
};

template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
    TestCasesType::const_iterator testCaseIter = testCases.begin();
    while (testCaseIter != testCases.end())
    {
        executeTestCase(*testCaseIter);
        ++testCaseIter;
    }
}

template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
    TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());

    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));

    try {

        CompiledStylesheetType  compiledStylesheet;
        ParsedInputSourceType   parsedInputSource;
        ResultTargetType        resultTarget;

        static const ProcessorOptions defaultProcessor;

        TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());

        const ProcessorOptions&  processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;

        m_fileUtility->checkAndCreateDir(testCase.resultDirectory);

        Timer timeCompile;

        if (testCase.inputMode == XalanDOMString("stream"))
        {
#if defined(XALAN_CLASSIC_IOSTREAMS)
            XALAN_USING_XALAN(CharVectorType)
            XALAN_USING_XALAN(c_str)

            XALAN_USING_STD(istringstream)

            CharVectorType  buffer;
            fileToStream(testCase.stylesheet, buffer);

            istrstream      compilerStream(c_str(buffer));
#else
            XALAN_USING_STD(istringstream)

            istringstream compilerStream;
            fileToStream(testCase.stylesheet, compilerStream);
#endif
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    compilerStream,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else if (testCase.inputMode == XalanDOMString("file"))
        {
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    testCase.stylesheet,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else
        {
            XALAN_USING_STD(endl)

            m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is invalid for stylesheet: "
                    << testCase.stylesheet
                    << endl;
        }

        m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);

        long numIterations = 0;

        long totalParseInputTime = 0;
        long minParseInputTime = LONG_MAX;
        long maxParseInputTime = 0 ;

        long totalTransformTime = 0;
        long minTransformTime = LONG_MAX;
        long maxTransformTime = 0;

        Timer timeTotalRun;
        timeTotalRun.start();

        while (numIterations < testCase.numIterations
            && timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
        {
            Timer timeInput;
            if (testCase.inputMode == XalanDOMString("stream"))
            {
#if defined(XALAN_CLASSIC_IOSTREAMS)
                XALAN_USING_XALAN(CharVectorType)
                XALAN_USING_XALAN(c_str)

                XALAN_USING_STD(istringstream)

                CharVectorType  buffer;
                fileToStream(testCase.inputDocument, buffer);

                istrstream      inputStream(c_str(buffer));
#else
                XALAN_USING_STD(istringstream)

                istringstream inputStream;
                fileToStream(testCase.inputDocument, inputStream);
#endif

                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        inputStream,
                        processor.parseOptions);
                timeInput.stop();
            }
            else if (testCase.inputMode == XalanDOMString("file"))
            {
                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        testCase.inputDocument,
                        processor.parseOptions);
                timeInput.stop();
            }
            else
            {
                XALAN_USING_STD(endl)

                m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is inavlid for input document: "
                    << testCase.inputDocument
                    << endl;
            }

            totalParseInputTime += timeInput.getElapsedTime();
            minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
            maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;

            resultTarget = m_processor.createResultTarget(
                    testCase.resultDocument,
                    processor.resultOptions);

            Timer timeTransform;
            timeTransform.start();
            m_processor.transform(
                    compiledStylesheet,
                    parsedInputSource,
                    resultTarget);
            timeTransform.stop();

            totalTransformTime += timeTransform.getElapsedTime();
            minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
            maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;

            ++numIterations;
        }

        timeTotalRun.stop();

        m_processor.releaseStylesheet(compiledStylesheet);
        m_processor.releaseInputSource(parsedInputSource);
        m_processor.releaseResultTarget(resultTarget);

        if (true == testCase.verifyResult)
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
            if (checkFileExists(testCase.resultDocument))
            {
                if (checkFileExists(testCase.goldResult))
                {
                    if (m_fileUtility->compareSerializedResults(
                            testCase.resultDocument,
                            testCase.goldResult))
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
                    }
                    else
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
                    }
                }
                else
                {
                    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
                }
            }
            else
            {
                testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
            }
        }
        else
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
        }

        m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
        m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
        m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
        m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));

    }
    catch (const XalanDOMString& exception)
    {
        XALAN_USING_STD(endl)

        m_logger->error()
                << "Error encountered during transformation: "
                << testCase.stylesheet.c_str()
                << ", error: "
                << exception.c_str()
                << endl;

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
    }

    m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}

template <class Processor>
TestHarness<Processor>::TestHarness()
{

}

template <class Processor>
void
TestHarness<Processor>::init(
        XalanFileUtility&       fileUtility,
        XalanXMLFileReporter&   reporter,
        Logger&                 logger)
{
    m_processor.init();

    m_fileUtility = &fileUtility;

    m_reporter = &reporter;

    m_logger = &logger;
}

template <class Processor>
void
TestHarness<Processor>::terminate()
{
   m_processor.terminate();
}

#endif // TESTHARNESS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Shashwat Lal Das
 * Written (W) 2012 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/mathematics/Math.h>
#include <shogun/features/streaming/StreamingDenseFeatures.h>
#include <shogun/io/streaming/StreamingFileFromDenseFeatures.h>

namespace shogun
{
template<class T>
CStreamingDenseFeatures<T>::CStreamingDenseFeatures() :
		CStreamingDotFeatures()
{
	set_read_functions();
	init();
	parser.set_free_vector_after_release(false);
}

template<class T>
CStreamingDenseFeatures<T>::CStreamingDenseFeatures(CStreamingFile* file,
		bool is_labelled, int32_t size) :
		CStreamingDotFeatures()
{
	init(file, is_labelled, size);
	set_read_functions();
	parser.set_free_vector_after_release(false);
}

template<class T> CStreamingDenseFeatures<T>::CStreamingDenseFeatures(
		CDenseFeatures<T>* dense_features, float64_t* lab) :
		CStreamingDotFeatures()
{
	REQUIRE(dense_features, "%s::CStreamingDenseFeatures(): Features needed!\n");

	CStreamingFileFromDenseFeatures<T>* file;
	bool is_labelled;
	int32_t size=1024;

	is_labelled=lab;
	file=new CStreamingFileFromDenseFeatures<T>(dense_features, lab);
	init(file, is_labelled, size);
	set_read_functions();
	parser.set_free_vector_after_release(false);
	parser.set_free_vectors_on_destruct(false);
	seekable=true;
}

template<class T> CStreamingDenseFeatures<T>::~CStreamingDenseFeatures()
{
	SG_DEBUG("entering %s::~CStreamingDenseFeatures()\n", get_name());
	if (parser.is_running())
		parser.end_parser();
	SG_DEBUG("leaving %s::~CStreamingDenseFeatures()\n", get_name());
}

template<class T> void CStreamingDenseFeatures<T>::reset_stream()
{
	if (seekable)
	{
		((CStreamingFileFromDenseFeatures<T>*)working_file)->reset_stream();
		parser.exit_parser();
		parser.init(working_file, has_labels, 1);
		parser.set_free_vector_after_release(false);
		parser.start_parser();
	}
}

template<class T> float32_t CStreamingDenseFeatures<T>::dense_dot(
		const float32_t* vec2, int32_t vec2_len)
{
	ASSERT(vec2_len==current_vector.vlen);
	float32_t result=0;

	for (int32_t i=0; i<current_vector.vlen; i++)
		result+=current_vector[i]*vec2[i];

	return result;
}

template<class T> float64_t CStreamingDenseFeatures<T>::dense_dot(
		const float64_t* vec2, int32_t vec2_len)
{
	ASSERT(vec2_len==current_vector.vlen);
	float64_t result=0;

	for (int32_t i=0; i<current_vector.vlen; i++)
		result+=current_vector[i]*vec2[i];

	return result;
}

template<class T> void CStreamingDenseFeatures<T>::add_to_dense_vec(
		float32_t alpha, float32_t* vec2, int32_t vec2_len, bool abs_val)
{
	ASSERT(vec2_len==current_vector.vlen);

	if (abs_val)
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*CMath::abs(current_vector[i]);
	}
	else
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*current_vector[i];
	}
}

template<class T> void CStreamingDenseFeatures<T>::add_to_dense_vec(
		float64_t alpha, float64_t* vec2, int32_t vec2_len, bool abs_val)
{
	ASSERT(vec2_len==current_vector.vlen);

	if (abs_val)
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*CMath::abs(current_vector[i]);
	}
	else
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*current_vector[i];
	}
}

template<class T> int32_t CStreamingDenseFeatures<T>::get_nnz_features_for_vector()
{
	return current_vector.vlen;
}

template<class T> CFeatures* CStreamingDenseFeatures<T>::duplicate() const
{
	return new CStreamingDenseFeatures<T>(*this);
}

template<class T> int32_t CStreamingDenseFeatures<T>::get_num_vectors() const
{
//	if (current_vector.vector)
		return 1;
//	return 0;
}

template<class T> int32_t CStreamingDenseFeatures<T>::get_size() const
{
	return sizeof(T);
}

template<class T>
void CStreamingDenseFeatures<T>::set_vector_reader()
{
	parser.set_read_vector(&CStreamingFile::get_vector);
}

template<class T>
void CStreamingDenseFeatures<T>::set_vector_and_label_reader()
{
	parser.set_read_vector_and_label(&CStreamingFile::get_vector_and_label);
}

#define GET_FEATURE_TYPE(f_type, sg_type)				\
template<> EFeatureType CStreamingDenseFeatures<sg_type>::get_feature_type() const \
{									\
	return f_type;							\
}

GET_FEATURE_TYPE(F_BOOL, bool)
GET_FEATURE_TYPE(F_CHAR, char)
GET_FEATURE_TYPE(F_BYTE, uint8_t)
GET_FEATURE_TYPE(F_BYTE, int8_t)
GET_FEATURE_TYPE(F_SHORT, int16_t)
GET_FEATURE_TYPE(F_WORD, uint16_t)
GET_FEATURE_TYPE(F_INT, int32_t)
GET_FEATURE_TYPE(F_UINT, uint32_t)
GET_FEATURE_TYPE(F_LONG, int64_t)
GET_FEATURE_TYPE(F_ULONG, uint64_t)
GET_FEATURE_TYPE(F_SHORTREAL, float32_t)
GET_FEATURE_TYPE(F_DREAL, float64_t)
GET_FEATURE_TYPE(F_LONGREAL, floatmax_t)
#undef GET_FEATURE_TYPE

template<class T>
void CStreamingDenseFeatures<T>::init()
{
	working_file=NULL;
	current_vector.vector=NULL;
	seekable=false;
	current_vector.vlen=-1;
}

template<class T>
void CStreamingDenseFeatures<T>::init(CStreamingFile* file, bool is_labelled,
		int32_t size)
{
	init();
	has_labels=is_labelled;
	working_file=file;
	SG_REF(working_file);
	parser.init(file, is_labelled, size);
	seekable=false;
}

template<class T>
void CStreamingDenseFeatures<T>::start_parser()
{
	if (!parser.is_running())
		parser.start_parser();
}

template<class T>
void CStreamingDenseFeatures<T>::end_parser()
{
	parser.end_parser();
}

template<class T>
bool CStreamingDenseFeatures<T>::get_next_example()
{
	bool ret_value;
	ret_value=(bool)parser.get_next_example(current_vector.vector, current_vector.vlen,
			current_label);

	return ret_value;
}

template<class T>
SGVector<T> CStreamingDenseFeatures<T>::get_vector()
{
	current_vector=SGVector<T>(current_vector.vector, current_vector.vlen, false);

	return current_vector;
}

template<class T>
float64_t CStreamingDenseFeatures<T>::get_label()
{
	ASSERT(has_labels);

	return current_label;
}

template<class T>
void CStreamingDenseFeatures<T>::release_example()
{
	parser.finalize_example();
}

template<class T>
int32_t CStreamingDenseFeatures<T>::get_dim_feature_space() const
{
	return current_vector.vlen;
}

template<class T>
float32_t CStreamingDenseFeatures<T>::dot(CStreamingDotFeatures* df)
{
	ASSERT(df);
	ASSERT(df->get_feature_type() == get_feature_type());
	ASSERT(df->get_feature_class() == get_feature_class());
	CStreamingDenseFeatures<T>* sf=(CStreamingDenseFeatures<T>*)df;

	SGVector<T> other_vector=sf->get_vector();

	return SGVector<T>::dot(current_vector.vector, other_vector.vector, current_vector.vlen);
}

template<class T>
float32_t CStreamingDenseFeatures<T>::dot(SGVector<T> sgvec1)
{
	int32_t len1;
	len1=sgvec1.vlen;

	if (len1!=current_vector.vlen)
		SG_ERROR(
				"Lengths %d and %d not equal while computing dot product!\n", len1, current_vector.vlen);

	return SGVector<T>::dot(current_vector.vector, sgvec1.vector, len1);
}

template<class T>
int32_t CStreamingDenseFeatures<T>::get_num_features()
{
	return current_vector.vlen;
}

template<class T>
EFeatureClass CStreamingDenseFeatures<T>::get_feature_class() const
{
	return C_STREAMING_DENSE;
}

template<class T>
CFeatures* CStreamingDenseFeatures<T>::get_streamed_features(
		index_t num_elements)
{
	SG_DEBUG("entering %s(%p)::get_streamed_features(%d)\n", get_name(), this,
			num_elements);

	/* init matrix empty since num_rows is not yet known */
	SGMatrix<T> matrix;

	bool parser_flag=parser.is_running();
	if (!parser_flag)
		parser.start_parser();

	for (index_t i=0; i<num_elements; ++i)
	{
		/* check if we run out of data */
		if (!get_next_example())
		{
			SG_DEBUG("%s::get_streamed_features(): ran out of streaming "
					"data, returnung NULL!\n", get_name());
			return NULL;
		}

		/* allocate matrix memory during first run */
		if (!matrix.matrix)
		{
			SG_DEBUG("%s::get_streamed_features(): allocating %dx%d matrix\n",
					get_name(), current_vector.vlen, num_elements);
			matrix=SGMatrix<T>(current_vector.vlen, num_elements);
		}

		/* get an example from stream and copy to feature matrix */
		SGVector<T> vec=get_vector();

		/* check for inconsistent dimensions */
		if (vec.vlen!=matrix.num_rows)
		{
			SG_ERROR("%s::get_streamed_features(): streamed vectors have "
					"different dimensions. This is not allowed!\n", get_name());
		}

		/* copy vector into matrix */
		memcpy(&matrix.matrix[current_vector.vlen*i], vec.vector,
				vec.vlen*sizeof(T));

		/* evtl output vector */
		if (sg_io->get_loglevel()==MSG_DEBUG)
			vec.display_vector("streamed vector");

		/* clean up */
		release_example();
	}

	if (!parser_flag)
		parser.exit_parser();

	/* create new feature object from collected data */
	CDenseFeatures<T>* result=new CDenseFeatures<T>(matrix);

	SG_DEBUG("leaving %s(%p)::get_streamed_features(%d)\n", get_name(), this,
			num_elements);

	return result;
}

template class CStreamingDenseFeatures<bool> ;
template class CStreamingDenseFeatures<char> ;
template class CStreamingDenseFeatures<int8_t> ;
template class CStreamingDenseFeatures<uint8_t> ;
template class CStreamingDenseFeatures<int16_t> ;
template class CStreamingDenseFeatures<uint16_t> ;
template class CStreamingDenseFeatures<int32_t> ;
template class CStreamingDenseFeatures<uint32_t> ;
template class CStreamingDenseFeatures<int64_t> ;
template class CStreamingDenseFeatures<uint64_t> ;
template class CStreamingDenseFeatures<float32_t> ;
template class CStreamingDenseFeatures<float64_t> ;
template class CStreamingDenseFeatures<floatmax_t> ;
}
<commit_msg>white space<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Shashwat Lal Das
 * Written (W) 2012 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/mathematics/Math.h>
#include <shogun/features/streaming/StreamingDenseFeatures.h>
#include <shogun/io/streaming/StreamingFileFromDenseFeatures.h>

namespace shogun
{
template<class T>
CStreamingDenseFeatures<T>::CStreamingDenseFeatures() :
		CStreamingDotFeatures()
{
	set_read_functions();
	init();
	parser.set_free_vector_after_release(false);
}

template<class T>
CStreamingDenseFeatures<T>::CStreamingDenseFeatures(CStreamingFile* file,
		bool is_labelled, int32_t size) :
		CStreamingDotFeatures()
{
	init(file, is_labelled, size);
	set_read_functions();
	parser.set_free_vector_after_release(false);
}

template<class T> CStreamingDenseFeatures<T>::CStreamingDenseFeatures(
		CDenseFeatures<T>* dense_features, float64_t* lab) :
		CStreamingDotFeatures()
{
	REQUIRE(dense_features, "%s::CStreamingDenseFeatures(): Features needed!\n");

	CStreamingFileFromDenseFeatures<T>* file;
	bool is_labelled;
	int32_t size=1024;

	is_labelled=lab;
	file=new CStreamingFileFromDenseFeatures<T>(dense_features, lab);
	init(file, is_labelled, size);
	set_read_functions();
	parser.set_free_vector_after_release(false);
	parser.set_free_vectors_on_destruct(false);
	seekable=true;
}

template<class T> CStreamingDenseFeatures<T>::~CStreamingDenseFeatures()
{
	SG_DEBUG("entering %s::~CStreamingDenseFeatures()\n", get_name());
	if (parser.is_running())
		parser.end_parser();
	SG_DEBUG("leaving %s::~CStreamingDenseFeatures()\n", get_name());
}

template<class T> void CStreamingDenseFeatures<T>::reset_stream()
{
	if (seekable)
	{
		((CStreamingFileFromDenseFeatures<T>*)working_file)->reset_stream();
		parser.exit_parser();
		parser.init(working_file, has_labels, 1);
		parser.set_free_vector_after_release(false);
		parser.start_parser();
	}
}

template<class T> float32_t CStreamingDenseFeatures<T>::dense_dot(
		const float32_t* vec2, int32_t vec2_len)
{
	ASSERT(vec2_len==current_vector.vlen);
	float32_t result=0;

	for (int32_t i=0; i<current_vector.vlen; i++)
		result+=current_vector[i]*vec2[i];

	return result;
}

template<class T> float64_t CStreamingDenseFeatures<T>::dense_dot(
		const float64_t* vec2, int32_t vec2_len)
{
	ASSERT(vec2_len==current_vector.vlen);
	float64_t result=0;

	for (int32_t i=0; i<current_vector.vlen; i++)
		result+=current_vector[i]*vec2[i];

	return result;
}

template<class T> void CStreamingDenseFeatures<T>::add_to_dense_vec(
		float32_t alpha, float32_t* vec2, int32_t vec2_len, bool abs_val)
{
	ASSERT(vec2_len==current_vector.vlen);

	if (abs_val)
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*CMath::abs(current_vector[i]);
	}
	else
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*current_vector[i];
	}
}

template<class T> void CStreamingDenseFeatures<T>::add_to_dense_vec(
		float64_t alpha, float64_t* vec2, int32_t vec2_len, bool abs_val)
{
	ASSERT(vec2_len==current_vector.vlen);

	if (abs_val)
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*CMath::abs(current_vector[i]);
	}
	else
	{
		for (int32_t i=0; i<current_vector.vlen; i++)
			vec2[i]+=alpha*current_vector[i];
	}
}

template<class T> int32_t CStreamingDenseFeatures<T>::get_nnz_features_for_vector()
{
	return current_vector.vlen;
}

template<class T> CFeatures* CStreamingDenseFeatures<T>::duplicate() const
{
	return new CStreamingDenseFeatures<T>(*this);
}

template<class T> int32_t CStreamingDenseFeatures<T>::get_num_vectors() const
{
//	if (current_vector.vector)
		return 1;
//	return 0;
}

template<class T> int32_t CStreamingDenseFeatures<T>::get_size() const
{
	return sizeof(T);
}

template<class T>
void CStreamingDenseFeatures<T>::set_vector_reader()
{
	parser.set_read_vector(&CStreamingFile::get_vector);
}

template<class T>
void CStreamingDenseFeatures<T>::set_vector_and_label_reader()
{
	parser.set_read_vector_and_label(&CStreamingFile::get_vector_and_label);
}

#define GET_FEATURE_TYPE(f_type, sg_type)				\
template<> EFeatureType CStreamingDenseFeatures<sg_type>::get_feature_type() const \
{									\
	return f_type;							\
}

GET_FEATURE_TYPE(F_BOOL, bool)
GET_FEATURE_TYPE(F_CHAR, char)
GET_FEATURE_TYPE(F_BYTE, uint8_t)
GET_FEATURE_TYPE(F_BYTE, int8_t)
GET_FEATURE_TYPE(F_SHORT, int16_t)
GET_FEATURE_TYPE(F_WORD, uint16_t)
GET_FEATURE_TYPE(F_INT, int32_t)
GET_FEATURE_TYPE(F_UINT, uint32_t)
GET_FEATURE_TYPE(F_LONG, int64_t)
GET_FEATURE_TYPE(F_ULONG, uint64_t)
GET_FEATURE_TYPE(F_SHORTREAL, float32_t)
GET_FEATURE_TYPE(F_DREAL, float64_t)
GET_FEATURE_TYPE(F_LONGREAL, floatmax_t)
#undef GET_FEATURE_TYPE

template<class T>
void CStreamingDenseFeatures<T>::init()
{
	working_file=NULL;
	current_vector.vector=NULL;
	seekable=false;
	current_vector.vlen=-1;
}

template<class T>
void CStreamingDenseFeatures<T>::init(CStreamingFile* file, bool is_labelled,
		int32_t size)
{
	init();
	has_labels=is_labelled;
	working_file=file;
	SG_REF(working_file);
	parser.init(file, is_labelled, size);
	seekable=false;
}

template<class T>
void CStreamingDenseFeatures<T>::start_parser()
{
	if (!parser.is_running())
		parser.start_parser();
}

template<class T>
void CStreamingDenseFeatures<T>::end_parser()
{
	parser.end_parser();
}

template<class T>
bool CStreamingDenseFeatures<T>::get_next_example()
{
	bool ret_value;
	ret_value=(bool)parser.get_next_example(current_vector.vector,
			current_vector.vlen, current_label);

	return ret_value;
}

template<class T>
SGVector<T> CStreamingDenseFeatures<T>::get_vector()
{
	return current_vector;
}

template<class T>
float64_t CStreamingDenseFeatures<T>::get_label()
{
	ASSERT(has_labels);

	return current_label;
}

template<class T>
void CStreamingDenseFeatures<T>::release_example()
{
	parser.finalize_example();
}

template<class T>
int32_t CStreamingDenseFeatures<T>::get_dim_feature_space() const
{
	return current_vector.vlen;
}

template<class T>
float32_t CStreamingDenseFeatures<T>::dot(CStreamingDotFeatures* df)
{
	ASSERT(df);
	ASSERT(df->get_feature_type() == get_feature_type());
	ASSERT(df->get_feature_class() == get_feature_class());
	CStreamingDenseFeatures<T>* sf=(CStreamingDenseFeatures<T>*)df;

	SGVector<T> other_vector=sf->get_vector();

	return SGVector<T>::dot(current_vector.vector, other_vector.vector, current_vector.vlen);
}

template<class T>
float32_t CStreamingDenseFeatures<T>::dot(SGVector<T> sgvec1)
{
	int32_t len1;
	len1=sgvec1.vlen;

	if (len1!=current_vector.vlen)
		SG_ERROR(
				"Lengths %d and %d not equal while computing dot product!\n", len1, current_vector.vlen);

	return SGVector<T>::dot(current_vector.vector, sgvec1.vector, len1);
}

template<class T>
int32_t CStreamingDenseFeatures<T>::get_num_features()
{
	return current_vector.vlen;
}

template<class T>
EFeatureClass CStreamingDenseFeatures<T>::get_feature_class() const
{
	return C_STREAMING_DENSE;
}

template<class T>
CFeatures* CStreamingDenseFeatures<T>::get_streamed_features(
		index_t num_elements)
{
	SG_DEBUG("entering %s(%p)::get_streamed_features(%d)\n", get_name(), this,
			num_elements);

	/* init matrix empty since num_rows is not yet known */
	SGMatrix<T> matrix;

	bool parser_flag=parser.is_running();
	if (!parser_flag)
		parser.start_parser();

	for (index_t i=0; i<num_elements; ++i)
	{
		/* check if we run out of data */
		if (!get_next_example())
		{
			SG_DEBUG("%s::get_streamed_features(): ran out of streaming "
					"data, returnung NULL!\n", get_name());
			return NULL;
		}

		/* allocate matrix memory during first run */
		if (!matrix.matrix)
		{
			SG_DEBUG("%s::get_streamed_features(): allocating %dx%d matrix\n",
					get_name(), current_vector.vlen, num_elements);
			matrix=SGMatrix<T>(current_vector.vlen, num_elements);
		}

		/* get an example from stream and copy to feature matrix */
		SGVector<T> vec=get_vector();

		/* check for inconsistent dimensions */
		if (vec.vlen!=matrix.num_rows)
		{
			SG_ERROR("%s::get_streamed_features(): streamed vectors have "
					"different dimensions. This is not allowed!\n", get_name());
		}

		/* copy vector into matrix */
		memcpy(&matrix.matrix[current_vector.vlen*i], vec.vector,
				vec.vlen*sizeof(T));

		/* evtl output vector */
		if (sg_io->get_loglevel()==MSG_DEBUG)
			vec.display_vector("streamed vector");

		/* clean up */
		release_example();
	}

	if (!parser_flag)
		parser.exit_parser();

	/* create new feature object from collected data */
	CDenseFeatures<T>* result=new CDenseFeatures<T>(matrix);

	SG_DEBUG("leaving %s(%p)::get_streamed_features(%d)\n", get_name(), this,
			num_elements);

	return result;
}

template class CStreamingDenseFeatures<bool> ;
template class CStreamingDenseFeatures<char> ;
template class CStreamingDenseFeatures<int8_t> ;
template class CStreamingDenseFeatures<uint8_t> ;
template class CStreamingDenseFeatures<int16_t> ;
template class CStreamingDenseFeatures<uint16_t> ;
template class CStreamingDenseFeatures<int32_t> ;
template class CStreamingDenseFeatures<uint32_t> ;
template class CStreamingDenseFeatures<int64_t> ;
template class CStreamingDenseFeatures<uint64_t> ;
template class CStreamingDenseFeatures<float32_t> ;
template class CStreamingDenseFeatures<float64_t> ;
template class CStreamingDenseFeatures<floatmax_t> ;
}
<|endoftext|>


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

#pragma once
#include <atomic>

namespace seastar {

extern __thread bool g_need_preempt;

inline bool need_preempt() {
#ifndef SEASTAR_DEBUG
    // prevent compiler from eliminating loads in a loop
    std::atomic_signal_fence(std::memory_order_seq_cst);
    return g_need_preempt;
#else
    return true;
#endif
}

}
<commit_msg>preempt: annotate for branch prediction<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2016 ScyllaDB.
 */

#pragma once
#include <atomic>

namespace seastar {

extern __thread bool g_need_preempt;

inline bool need_preempt() {
#ifndef SEASTAR_DEBUG
    // prevent compiler from eliminating loads in a loop
    std::atomic_signal_fence(std::memory_order_seq_cst);
    return __builtin_expect(g_need_preempt, false);
#else
    return true;
#endif
}

}
<|endoftext|>


<commit_before>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

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

	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 "Transceiver.h"
#include "radioDevice.h"
#include "DummyLoad.h"

#include <time.h>
#include <signal.h>

#include <GSMCommon.h>
#include <Logger.h>
#include <Configuration.h>

#ifdef RESAMPLE
  #define DEVICERATE 400e3
#else
  #define DEVICERATE 1625e3/6
#endif

using namespace std;

ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");

volatile bool gbShutdown = false;
static void ctrlCHandler(int signo)
{
   cout << "Received shutdown signal" << endl;;
   gbShutdown = true;
}

int main(int argc, char *argv[])
{
  std::string deviceArgs;

  if (argc == 3)
  {
    deviceArgs = std::string(argv[2]);
  }
  else
  {
    deviceArgs = "";
  }

  if ( signal( SIGINT, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGINT" << endl;
    exit(1);
  }

  if ( signal( SIGTERM, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGTERM" << endl;
    exit(1);
  }
  // Configure logger.
  gLogInit("transceiver",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);

  int numARFCN=1;

  LOG(NOTICE) << "starting transceiver with " << numARFCN << " ARFCNs (argc=" << argc << ")";

  srandom(time(NULL));

  int mOversamplingRate = numARFCN/2 + numARFCN;
  RadioDevice *usrp = RadioDevice::make(DEVICERATE * SAMPSPERSYM);
  if (!usrp->open(deviceArgs)) {
    LOG(ALERT) << "Transceiver exiting..." << std::endl;
    return EXIT_FAILURE;
  }

  RadioInterface* radio = new RadioInterface(usrp,3,SAMPSPERSYM,mOversamplingRate,false);
  Transceiver *trx = new Transceiver(5700,"127.0.0.1",SAMPSPERSYM,GSM::Time(3,0),radio);
  trx->receiveFIFO(radio->receiveFIFO());
/*
  signalVector *gsmPulse = generateGSMPulse(2,1);
  BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
  BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[0]),normalBurstSeg);
  signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
  signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
  signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
  signalVector totalBurst1(*modBurst,*modBurst9);
  signalVector totalBurst2(*modBurst,*modBurst);
  signalVector totalBurst(totalBurst1,totalBurst2);
  scaleVector(totalBurst,usrp->fullScaleInputValue());
  double beaconFreq = -1.0*(numARFCN-1)*200e3;
  signalVector finalVec(625*mOversamplingRate);
  for (int j = 0; j < numARFCN; j++) {
	signalVector *frequencyShifter = new signalVector(625*mOversamplingRate);
	frequencyShifter->fill(1.0);
	frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
  	signalVector *interpVec = polyphaseResampleVector(totalBurst,mOversamplingRate,1,interpolationFilter);
	multVector(*interpVec,*frequencyShifter);
	addVector(finalVec,*interpVec);
  }
  signalVector::iterator itr = finalVec.begin();
  short finalVecShort[2*finalVec.size()];
  short *shortItr = finalVecShort;
  while (itr < finalVec.end()) {
	*shortItr++ = (short) (itr->real());
	*shortItr++ = (short) (itr->imag());
	itr++;
  }
  usrp->loadBurst(finalVecShort,finalVec.size());
*/
  trx->start();
  //int i = 0;
  while(!gbShutdown) { sleep(1); }//i++; if (i==60) break;}

  cout << "Shutting down transceiver..." << endl;

//  trx->stop();
  delete trx;
//  delete radio;
}
<commit_msg>Transceiver52M: Read IP address and port to bind to from a configuration instead of hardcoding them.<commit_after>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

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

	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 "Transceiver.h"
#include "radioDevice.h"
#include "DummyLoad.h"

#include <time.h>
#include <signal.h>

#include <GSMCommon.h>
#include <Logger.h>
#include <Configuration.h>

#ifdef RESAMPLE
  #define DEVICERATE 400e3
#else
  #define DEVICERATE 1625e3/6
#endif

using namespace std;

ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");

volatile bool gbShutdown = false;
static void ctrlCHandler(int signo)
{
   cout << "Received shutdown signal" << endl;;
   gbShutdown = true;
}

int main(int argc, char *argv[])
{
  std::string deviceArgs;

  if (argc == 3)
  {
    deviceArgs = std::string(argv[2]);
  }
  else
  {
    deviceArgs = "";
  }

  if ( signal( SIGINT, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGINT" << endl;
    exit(1);
  }

  if ( signal( SIGTERM, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGTERM" << endl;
    exit(1);
  }
  // Configure logger.
  gLogInit("transceiver",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);

  int numARFCN=1;

  LOG(NOTICE) << "starting transceiver with " << numARFCN << " ARFCNs (argc=" << argc << ")";

  srandom(time(NULL));

  int mOversamplingRate = numARFCN/2 + numARFCN;
  RadioDevice *usrp = RadioDevice::make(DEVICERATE * SAMPSPERSYM);
  if (!usrp->open(deviceArgs)) {
    LOG(ALERT) << "Transceiver exiting..." << std::endl;
    return EXIT_FAILURE;
  }

  RadioInterface* radio = new RadioInterface(usrp,3,SAMPSPERSYM,mOversamplingRate,false);
  Transceiver *trx = new Transceiver(gConfig.getNum("TRX.Port"),gConfig.getStr("TRX.IP").c_str(),SAMPSPERSYM,GSM::Time(3,0),radio);
  trx->receiveFIFO(radio->receiveFIFO());
/*
  signalVector *gsmPulse = generateGSMPulse(2,1);
  BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
  BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[0]),normalBurstSeg);
  signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
  signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
  signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
  signalVector totalBurst1(*modBurst,*modBurst9);
  signalVector totalBurst2(*modBurst,*modBurst);
  signalVector totalBurst(totalBurst1,totalBurst2);
  scaleVector(totalBurst,usrp->fullScaleInputValue());
  double beaconFreq = -1.0*(numARFCN-1)*200e3;
  signalVector finalVec(625*mOversamplingRate);
  for (int j = 0; j < numARFCN; j++) {
	signalVector *frequencyShifter = new signalVector(625*mOversamplingRate);
	frequencyShifter->fill(1.0);
	frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
  	signalVector *interpVec = polyphaseResampleVector(totalBurst,mOversamplingRate,1,interpolationFilter);
	multVector(*interpVec,*frequencyShifter);
	addVector(finalVec,*interpVec);
  }
  signalVector::iterator itr = finalVec.begin();
  short finalVecShort[2*finalVec.size()];
  short *shortItr = finalVecShort;
  while (itr < finalVec.end()) {
	*shortItr++ = (short) (itr->real());
	*shortItr++ = (short) (itr->imag());
	itr++;
  }
  usrp->loadBurst(finalVecShort,finalVec.size());
*/
  trx->start();
  //int i = 0;
  while(!gbShutdown) { sleep(1); }//i++; if (i==60) break;}

  cout << "Shutting down transceiver..." << endl;

//  trx->stop();
  delete trx;
//  delete radio;
}
<|endoftext|>