text:
// Copyright 2018, Intel Corporation

#include "tile/codegen/thread_inner.h"

#include <algorithm>

#include <boost/format.hpp>

#include "base/util/throw.h"
#include "tile/codegen/tile.h"
#include "tile/math/util.h"
#include "tile/stripe/stripe.h"

namespace vertexai {
namespace tile {
namespace codegen {

using namespace stripe;  // NOLINT
using math::NearestPo2;
using math::RoundUp;

void DoThreadInnerPass(const AliasMap& scope, Block* block, const proto::ThreadInnerPass& options) {
  if (block->ref_outs(true).size() != 1) {
    if (block->ref_outs(true).size() == 0) {
      // We may remove the output refinements in the contracts during optimizations,
      // so here is not definitely wrong.
      return;
    }
    throw std::runtime_error("Thread inner pass only works with a single output");
  }
  const Refinement* out_ref = block->ref_outs(true)[0];
  const auto& idxs = block->idxs;
  Affine flat = out_ref->FlatAccess();
  std::vector<size_t> sorted_idxs;
  // Pull across indexes that are part of the output
  for (size_t i = 0; i < idxs.size(); i++) {
    // TODO: Rollup
    if (flat.get(idxs[i].name) != 0) {
      sorted_idxs.push_back(i);
    }
  }
  IVLOG(1, "Output indexes: " << sorted_idxs);
  // Sort indexes by is_out, power-of-twoness, then size
  auto sort_func = [&](size_t i, size_t j) {
    bool out_i = flat.get(idxs[i].name) == 0;
    bool out_j = flat.get(idxs[j].name) == 0;
    if (out_i != out_j) {
      return out_j;
    }
    double ratio_i = static_cast<double>(idxs[i].range) / NearestPo2(idxs[i].range);
    double ratio_j = static_cast<double>(idxs[j].range) / NearestPo2(idxs[j].range);
    if (ratio_i != ratio_j) {
      return ratio_i > ratio_j;
    }
    return idxs[i].range > idxs[j].range;
  };
  TileShape tile(block->idxs.size(), 1);
  std::sort(sorted_idxs.begin(), sorted_idxs.end(), sort_func);
  IVLOG(1, "Sorted indexes: " << sorted_idxs);
  size_t cur = 0;
  size_t threads = options.threads();
  while (threads > 1 && cur < sorted_idxs.size()) {
    size_t ci = sorted_idxs[cur];
    size_t split = std::min(size_t(threads), size_t(NearestPo2(idxs[ci].range)));
    tile[ci] = split;
    threads /= split;
    cur++;
  }
  for (size_t i = 0; i < tile.size(); i++) {
    tile[i] = RoundUp(block->idxs[i].range, tile[i]);
  }
  ApplyTile(block, tile, false, false, true);
  block->add_tags(FromProto(options.outer_set()));
  block->SubBlock(0)->add_tags(FromProto(options.inner_set()));
}

// Localize starting from root for things that match reqs
void ThreadInnerPass::Apply(CompilerState* state) const {
  auto reqs = stripe::FromProto(options_.reqs());
  RunOnBlocks(state->entry(), reqs, [this](const AliasMap& map, stripe::Block* block) {  //
    DoThreadInnerPass(map, block, options_);
  });
}

namespace {
[[gnu::unused]] char reg = []() -> char {
  CompilePassFactory<ThreadInnerPass, proto::ThreadInnerPass>::Register();
  return 0;
}();
}  // namespace
}  // namespace codegen
}  // namespace tile
}  // namespace vertexai

ext: cc

max_stars_repo_name: DaniDeniz/plaidml

max_issues_repo_name: DaniDeniz/plaidml

max_forks_repo_name: DaniDeniz/plaidml


text:
#include <eosio/chain/exceptions.hpp>
#include <eosiolib_native/vm_api.h>
#include <boost/exception/all.hpp>

using namespace eosio::chain;
using namespace fc;

[[ noreturn ]] void fc_throw_exception(int type, const char* fmt, ...) {

#define CASE_EXCEPTION(exc_type) \
   case (int)exception_type::enum_##exc_type: \
      throw exc_type( FC_LOG_MESSAGE( error, output.data() ) ); \
      break;

#define CASE_FC_EXCEPTION(exc_type) \
   case (int)exception_type::enum_##exc_type: \
      throw fc::exc_type( FC_LOG_MESSAGE( error, output.data() ) ); \
      break;

   std::vector<char> output(256);
   memset(output.data(), 0, output.size());

   va_list args;
   va_start(args, fmt);
   int len = vsnprintf(output.data(), output.size()-1, fmt, args);
   va_end(args);

   switch(type) {
      CASE_FC_EXCEPTION(exception)
      CASE_FC_EXCEPTION(timeout_exception)
      CASE_FC_EXCEPTION(file_not_found_exception)
      CASE_FC_EXCEPTION(parse_error_exception)
      CASE_FC_EXCEPTION(invalid_arg_exception)
      CASE_FC_EXCEPTION(key_not_found_exception)
      CASE_FC_EXCEPTION(bad_cast_exception)
      CASE_FC_EXCEPTION(out_of_range_exception)
      CASE_FC_EXCEPTION(invalid_operation_exception)
      CASE_FC_EXCEPTION(unknown_host_exception)
      CASE_FC_EXCEPTION(canceled_exception)
      CASE_FC_EXCEPTION(assert_exception)
      CASE_FC_EXCEPTION(eof_exception)
      CASE_FC_EXCEPTION(null_optional)
      CASE_FC_EXCEPTION(udt_exception)
      CASE_FC_EXCEPTION(aes_exception)
      CASE_FC_EXCEPTION(overflow_exception)
      CASE_FC_EXCEPTION(underflow_exception)
      CASE_FC_EXCEPTION(divide_by_zero_exception)

      CASE_EXCEPTION(chain_type_exception)
      CASE_EXCEPTION(name_type_exception)
      CASE_EXCEPTION(public_key_type_exception)
      CASE_EXCEPTION(private_key_type_exception)
      CASE_EXCEPTION(authority_type_exception)
      CASE_EXCEPTION(action_type_exception)
      CASE_EXCEPTION(transaction_type_exception)
      CASE_EXCEPTION(abi_type_exception)
      CASE_EXCEPTION(block_id_type_exception)
      CASE_EXCEPTION(transaction_id_type_exception)
      CASE_EXCEPTION(packed_transaction_type_exception)
      CASE_EXCEPTION(asset_type_exception)
      CASE_EXCEPTION(chain_id_type_exception)
      CASE_EXCEPTION(fixed_key_type_exception)
      CASE_EXCEPTION(symbol_type_exception)
      CASE_EXCEPTION(fork_database_exception)
      CASE_EXCEPTION(fork_db_block_not_found)
      CASE_EXCEPTION(block_validate_exception)
      CASE_EXCEPTION(unlinkable_block_exception)
      CASE_EXCEPTION(block_tx_output_exception)
      CASE_EXCEPTION(block_concurrency_exception)
      CASE_EXCEPTION(block_lock_exception)
      CASE_EXCEPTION(block_resource_exhausted)
      CASE_EXCEPTION(block_too_old_exception)
      CASE_EXCEPTION(block_from_the_future)
      CASE_EXCEPTION(wrong_signing_key)
      CASE_EXCEPTION(wrong_producer)
      CASE_EXCEPTION(transaction_exception)
      CASE_EXCEPTION(tx_decompression_error)
      CASE_EXCEPTION(tx_no_action)
      CASE_EXCEPTION(tx_no_auths)
      CASE_EXCEPTION(cfa_irrelevant_auth)
      CASE_EXCEPTION(expired_tx_exception)
      CASE_EXCEPTION(tx_exp_too_far_exception)
      CASE_EXCEPTION(invalid_ref_block_exception)
      CASE_EXCEPTION(tx_duplicate)
      CASE_EXCEPTION(deferred_tx_duplicate)
      CASE_EXCEPTION(cfa_inside_generated_tx)
      CASE_EXCEPTION(tx_not_found)
      CASE_EXCEPTION(too_many_tx_at_once)
      CASE_EXCEPTION(tx_too_big)
      CASE_EXCEPTION(unknown_transaction_compression)
      CASE_EXCEPTION(action_validate_exception)
      CASE_EXCEPTION(account_name_exists_exception)
      CASE_EXCEPTION(invalid_action_args_exception)
      CASE_EXCEPTION(eosio_assert_message_exception)
      CASE_EXCEPTION(eosio_assert_code_exception)
      CASE_EXCEPTION(action_not_found_exception)
      CASE_EXCEPTION(action_data_and_struct_mismatch)
      CASE_EXCEPTION(unaccessible_api)
      CASE_EXCEPTION(abort_called)
      CASE_EXCEPTION(inline_action_too_big)
      CASE_EXCEPTION(database_exception)
      CASE_EXCEPTION(permission_query_exception)
      CASE_EXCEPTION(account_query_exception)
      CASE_EXCEPTION(contract_table_query_exception)
      CASE_EXCEPTION(contract_query_exception)
      CASE_EXCEPTION(guard_exception)
      CASE_EXCEPTION(database_guard_exception)
      CASE_EXCEPTION(reversible_guard_exception)
      CASE_EXCEPTION(wasm_exception)
      CASE_EXCEPTION(page_memory_error)
      CASE_EXCEPTION(wasm_execution_error)
      CASE_EXCEPTION(wasm_serialization_error)
      CASE_EXCEPTION(overlapping_memory_error)
      CASE_EXCEPTION(binaryen_exception)
      CASE_EXCEPTION(resource_exhausted_exception)
      CASE_EXCEPTION(ram_usage_exceeded)
      CASE_EXCEPTION(tx_net_usage_exceeded)
      CASE_EXCEPTION(block_net_usage_exceeded)
      CASE_EXCEPTION(tx_cpu_usage_exceeded)
      CASE_EXCEPTION(block_cpu_usage_exceeded)
      CASE_EXCEPTION(deadline_exception)
      CASE_EXCEPTION(greylist_net_usage_exceeded)
      CASE_EXCEPTION(greylist_cpu_usage_exceeded)
      CASE_EXCEPTION(leeway_deadline_exception)
      CASE_EXCEPTION(authorization_exception)
      CASE_EXCEPTION(tx_duplicate_sig)
      CASE_EXCEPTION(tx_irrelevant_sig)
      CASE_EXCEPTION(unsatisfied_authorization)
      CASE_EXCEPTION(missing_auth_exception)
      CASE_EXCEPTION(irrelevant_auth_exception)
      CASE_EXCEPTION(insufficient_delay_exception)
      CASE_EXCEPTION(invalid_permission)
      CASE_EXCEPTION(unlinkable_min_permission_action)
      CASE_EXCEPTION(invalid_parent_permission)
      CASE_EXCEPTION(misc_exception)
      CASE_EXCEPTION(rate_limiting_state_inconsistent)
      CASE_EXCEPTION(unknown_block_exception)
      CASE_EXCEPTION(unknown_transaction_exception)
      CASE_EXCEPTION(fixed_reversible_db_exception)
      CASE_EXCEPTION(extract_genesis_state_exception)
      CASE_EXCEPTION(subjective_block_production_exception)
      CASE_EXCEPTION(multiple_voter_info)
      CASE_EXCEPTION(unsupported_feature)
      CASE_EXCEPTION(node_management_success)
      CASE_EXCEPTION(plugin_exception)
      CASE_EXCEPTION(missing_chain_api_plugin_exception)
      CASE_EXCEPTION(missing_wallet_api_plugin_exception)
      CASE_EXCEPTION(missing_history_api_plugin_exception)
      CASE_EXCEPTION(missing_net_api_plugin_exception)
      CASE_EXCEPTION(missing_chain_plugin_exception)
      CASE_EXCEPTION(plugin_config_exception)
      CASE_EXCEPTION(wallet_exception)
      CASE_EXCEPTION(wallet_exist_exception)
      CASE_EXCEPTION(wallet_nonexistent_exception)
      CASE_EXCEPTION(wallet_locked_exception)
      CASE_EXCEPTION(wallet_missing_pub_key_exception)
      CASE_EXCEPTION(wallet_invalid_password_exception)
      CASE_EXCEPTION(wallet_not_available_exception)
      CASE_EXCEPTION(wallet_unlocked_exception)
      CASE_EXCEPTION(key_exist_exception)
      CASE_EXCEPTION(key_nonexistent_exception)
      CASE_EXCEPTION(unsupported_key_type_exception)
      CASE_EXCEPTION(invalid_lock_timeout_exception)
      CASE_EXCEPTION(secure_enclave_exception)
      CASE_EXCEPTION(whitelist_blacklist_exception)
      CASE_EXCEPTION(actor_whitelist_exception)
      CASE_EXCEPTION(actor_blacklist_exception)
      CASE_EXCEPTION(contract_whitelist_exception)
      CASE_EXCEPTION(contract_blacklist_exception)
      CASE_EXCEPTION(action_blacklist_exception)
      CASE_EXCEPTION(key_blacklist_exception)
      CASE_EXCEPTION(controller_emit_signal_exception)
      CASE_EXCEPTION(checkpoint_exception)
      CASE_EXCEPTION(abi_exception)
      CASE_EXCEPTION(abi_not_found_exception)
      CASE_EXCEPTION(invalid_ricardian_clause_exception)
      CASE_EXCEPTION(invalid_ricardian_action_exception)
      CASE_EXCEPTION(invalid_type_inside_abi)
      CASE_EXCEPTION(duplicate_abi_type_def_exception)
      CASE_EXCEPTION(duplicate_abi_struct_def_exception)
      CASE_EXCEPTION(duplicate_abi_action_def_exception)
      CASE_EXCEPTION(duplicate_abi_table_def_exception)
      CASE_EXCEPTION(duplicate_abi_err_msg_def_exception)
      CASE_EXCEPTION(abi_serialization_deadline_exception)
      CASE_EXCEPTION(abi_recursion_depth_exception)
      CASE_EXCEPTION(abi_circular_def_exception)
      CASE_EXCEPTION(unpack_exception)
      CASE_EXCEPTION(pack_exception)
      CASE_EXCEPTION(duplicate_abi_variant_def_exception)
      CASE_EXCEPTION(unsupported_abi_version_exception)
      CASE_EXCEPTION(contract_exception)
      CASE_EXCEPTION(invalid_table_payer)
      CASE_EXCEPTION(table_access_violation)
      CASE_EXCEPTION(invalid_table_iterator)
      CASE_EXCEPTION(table_not_in_cache)
      CASE_EXCEPTION(table_operation_not_permitted)
      CASE_EXCEPTION(invalid_contract_vm_type)
      CASE_EXCEPTION(invalid_contract_vm_version)
      CASE_EXCEPTION(set_exact_code)
      CASE_EXCEPTION(wast_file_not_found)
      CASE_EXCEPTION(abi_file_not_found)
      CASE_EXCEPTION(producer_exception)
      CASE_EXCEPTION(producer_priv_key_not_found)
      CASE_EXCEPTION(missing_pending_block_state)
      CASE_EXCEPTION(producer_double_confirm)
      CASE_EXCEPTION(producer_schedule_exception)
      CASE_EXCEPTION(producer_not_in_schedule)
      CASE_EXCEPTION(reversible_blocks_exception)
      CASE_EXCEPTION(invalid_reversible_blocks_dir)
      CASE_EXCEPTION(reversible_blocks_backup_dir_exist)
      CASE_EXCEPTION(gap_in_reversible_blocks_db)
      CASE_EXCEPTION(block_log_exception)
      CASE_EXCEPTION(block_log_unsupported_version)
      CASE_EXCEPTION(block_log_append_fail)
      CASE_EXCEPTION(block_log_not_found)
      CASE_EXCEPTION(block_log_backup_dir_exist)
      CASE_EXCEPTION(http_exception)
      CASE_EXCEPTION(invalid_http_client_root_cert)
      CASE_EXCEPTION(invalid_http_response)
      CASE_EXCEPTION(resolved_to_multiple_ports)
      CASE_EXCEPTION(fail_to_resolve_host)
      CASE_EXCEPTION(http_request_fail)
      CASE_EXCEPTION(invalid_http_request)
      CASE_EXCEPTION(resource_limit_exception)
      CASE_EXCEPTION(mongo_db_exception)
      CASE_EXCEPTION(mongo_db_insert_fail)
      CASE_EXCEPTION(mongo_db_update_fail)
      CASE_EXCEPTION(contract_api_exception)
      CASE_EXCEPTION(crypto_api_exception)
      CASE_EXCEPTION(db_api_exception)
      CASE_EXCEPTION(arithmetic_exception)
      CASE_EXCEPTION(abi_generation_exception)
      default:
         break;
   }
   throw exception( FC_LOG_MESSAGE( error, output.data() ) );
#undef   CASE_EXCEPTION
#undef   CASE_FC_EXCEPTION
}

void vm_api_throw_exception(int type, const char* fmt, ...) {
   get_vm_api()->throw_exception(type, fmt);
}

ext: cpp

max_stars_repo_name: learnforpractice/pyeos

max_issues_repo_name: openchatproject/safeos

max_forks_repo_name: learnforpractice/pyeos


text: #include <boost/mpl/aux_/preprocessed/plain/apply_fwd.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <iostream>
#include <fstream>
#include <iterator>
#include <exception>

#include "libtorrent/config.hpp"

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/bind.hpp>
#include <boost/program_options.hpp>
#include <boost/regex.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_pex.hpp"

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/identify_client.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/ip_filter.hpp"

using boost::bind;

#ifdef _WIN32

#if defined(_MSC_VER)
#	define for if (false) {} else for
#endif

#include <windows.h>
#include <conio.h>

bool sleep_and_input(char* c)
{
	Sleep(500);
	if (_kbhit())
	{
		*c = _getch();
		return true;
	}
	return false;
};

void clear_home()
{
	CONSOLE_SCREEN_BUFFER_INFO si;
	HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
	GetConsoleScreenBufferInfo(h, &si);
	COORD c = {0, 0};
	DWORD n;
	FillConsoleOutputCharacter(h, ' ', si.dwSize.X * si.dwSize.Y, c, &n);
	SetConsoleCursorPosition(h, c);
}

#else

#include <stdlib.h>
#include <stdio.h>

#include <termios.h>
#include <string.h>
#include <sys/ioctl.h>

#define ANSI_TERMINAL_COLORS

struct set_keypress
{
	set_keypress()
	{
		termios new_settings;
		tcgetattr(0,&stored_settings);
		new_settings = stored_settings;
		// Disable canonical mode, and set buffer size to 1 byte
		new_settings.c_lflag &= (~ICANON);
		new_settings.c_cc[VTIME] = 0;
		new_settings.c_cc[VMIN] = 1;
		tcsetattr(0,TCSANOW,&new_settings);
	}
	~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); }
	termios stored_settings;
};

bool sleep_and_input(char* c)
{
	// sets the terminal to single-character mode
	// and resets when destructed
	set_keypress s;

	fd_set set;
	FD_ZERO(&set);
	FD_SET(0, &set);
	timeval tv = {0, 500000};
	if (select(1, &set, 0, 0, &tv) > 0)
	{
		*c = getc(stdin);
		return true;
	}
	return false;
}

void clear_home()
{
	std::cout << "\033[2J\033[0;0H";
}

#endif

char const* esc(char const* code)
{
#ifdef ANSI_TERMINAL_COLORS
	// this is a silly optimization
	// to avoid copying of strings
	enum { num_strings = 20 };
	static char buf[num_strings][20];
	static int round_robin = 0;
	char* ret = buf[round_robin];
	++round_robin;
	if (round_robin >= num_strings) round_robin = 0;
	ret[0] = '\033';
	ret[1] = '[';
	int i = 2;
	int j = 0;
	while (code[j]) ret[i++] = code[j++];
	ret[i++] = 'm';
	ret[i++] = 0;
	return ret;
#else
	return "";
#endif
}

std::string to_string(int v, int width)
{
	std::stringstream s;
	s.flags(std::ios_base::right);
	s.width(width);
	s.fill(' ');
	s << v;
	return s.str();
}

std::string const& to_string(float v, int width, int precision = 3)
{
	static std::string ret;
	ret.resize(20);
	int size = std::sprintf(&ret[0], "%*.*f", width, precision, v);
	ret.resize((std::min)(size, width));
	return ret;
}

std::string pos_to_string(float v, int width, int precision = 4)
{
	std::stringstream s;
	s.precision(precision);
	s.flags(std::ios_base::right);
	s.width(width);
	s.fill(' ');
	s << fabs(v);
	return s.str();
}

std::string ratio(float a, float b)
{
	std::stringstream s;
	if (a > b)
	{
		if (b < 0.001f) s << " inf:1";
		else s << pos_to_string(a/b, 4) << ":1";
	}
	else if (a < b)
	{
		if (a < 0.001f) s << " 1:inf";
		else s << "1:" << pos_to_string(b/a, 4);
	}
	else
	{
		s << "   1:1";
	}

	return s.str();
}

std::string const& add_suffix(float val)
{
	static std::string ret;
	const char* prefix[] = {"kB", "MB", "GB", "TB"};
	const int num_prefix = sizeof(prefix) / sizeof(const char*);
	for (int i = 0; i < num_prefix; ++i)
	{
		val /= 1000.f;
		if (fabs(val) < 1000.f)
		{
			ret = to_string(val, 4);
			ret += prefix[i];
			return ret;
		}
	}
	ret = to_string(val, 4);
	ret += "PB";
	return ret;
}

std::string const& piece_bar(std::vector<bool> const& p, int width)
{
	static const char* lookup[] =
	{
		// black, blue, cyan, white
		"40", "44", "46", "47"
	};

	double piece_per_char = p.size() / double(width);
	static std::string bar;
	bar.clear();
	bar.reserve(width * 6);
	bar += "[";

	// the [piece, piece + pieces_per_char) range is the pieces that are represented by each character
	double piece = 0;
	for (int i = 0; i < width; ++i, piece += piece_per_char)
	{
		int num_pieces = 0;
		int num_have = 0;
		int end = (std::max)(int(piece + piece_per_char), int(piece) + 1);
		for (int k = int(piece); k < end; ++k, ++num_pieces)
			if (p[k]) ++num_have;
		int color = int(std::ceil(num_have / float(num_pieces) * (sizeof(lookup) / sizeof(lookup[0]) - 1)));
		bar += esc(lookup[color]);
		bar += " ";
	}
	bar += esc("0");
	bar += "]";
	return bar;
}

std::string const& progress_bar(float progress, int width, char const* code = "33")
{
	static std::string bar;
	bar.clear();
	bar.reserve(width + 10);

	int progress_chars = static_cast<int>(progress * width + .5f);
	bar = esc(code);
	std::fill_n(std::back_inserter(bar), progress_chars, '#');
	bar += esc("0");
	std::fill_n(std::back_inserter(bar), width - progress_chars, '-');
	return bar;
}

int peer_index(libtorrent::tcp::endpoint addr, std::vector<libtorrent::peer_info> const& peers)
{
	using namespace libtorrent;
	std::vector<peer_info>::const_iterator i = std::find_if(peers.begin()
		, peers.end(), bind(&peer_info::ip, _1) == addr);
	if (i == peers.end()) return -1;

	return i - peers.begin();
}

void print_peer_info(std::ostream& out, std::vector<libtorrent::peer_info> const& peers)
{
	using namespace libtorrent;
	out << "IP                      down    (total)   up      (total)  sent-req recv flags       source fail hshf sndb inactive wait disk block-progress "
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
		"country "
#endif
		"peer-rate client \n";

	for (std::vector<peer_info>::const_iterator i = peers.begin();
		i != peers.end(); ++i)
	{
		if (i->flags & (peer_info::handshake))
			continue;

		out.fill(' ');
		std::stringstream ip;
		ip << i->ip.address().to_string() << ":" << i->ip.port();
		out.width(22);
		out << ip.str() << " ";
		out.width(2);
		out << esc("32") << (i->down_speed > 0 ? add_suffix(i->down_speed) + "/s " : "         ")
			<< "(" << add_suffix(i->total_download) << ") " << esc("0")
			<< esc("31") << (i->up_speed > 0 ? add_suffix(i->up_speed) + "/s ": "         ")
			<< "(" << add_suffix(i->total_upload) << ") " << esc("0")
			<< to_string(i->download_queue_length, 3) << " ("
			<< to_string(i->target_dl_queue_length, 3) << ") "
			<< to_string(i->upload_queue_length, 3) << " "
			<< ((i->flags & peer_info::interesting)?'I':'.')
			<< ((i->flags & peer_info::choked)?'C':'.')
			<< ((i->flags & peer_info::remote_interested)?'i':'.')
			<< ((i->flags & peer_info::remote_choked)?'c':'.')
			<< ((i->flags & peer_info::supports_extensions)?'e':'.')
			<< ((i->flags & peer_info::local_connection)?'l':'r')
			<< ((i->flags & peer_info::seed)?'s':'.')
			<< ((i->flags & peer_info::on_parole)?'p':'.')
			<< ((i->flags & peer_info::optimistic_unchoke)?'O':'.')
#ifndef TORRENT_DISABLE_ENCRYPTION
			<< ((i->flags & peer_info::rc4_encrypted)?'E':
				(i->flags & peer_info::plaintext_encrypted)?'e':'.')
#else
			<< "  "
#endif
			<< " "
			<< ((i->source & peer_info::tracker)?"T":"_")
			<< ((i->source & peer_info::pex)?"P":"_")
			<< ((i->source & peer_info::dht)?"D":"_")
			<< ((i->source & peer_info::lsd)?"L":"_")
			<< ((i->source & peer_info::resume_data)?"R":"_") << "  "
			<< to_string(i->failcount, 4) << " "
			<< to_string(i->num_hashfails, 4) << " "
			<< to_string(i->send_buffer_size, 4) << " "
			<< to_string(total_seconds(i->last_active), 8) << " "
			<< to_string(total_seconds(i->last_request), 4) << " "
			<< to_string(i->pending_disk_bytes, 4) << " ";

		if (i->downloading_piece_index >= 0)
		{
			out << progress_bar(
				i->downloading_progress / float(i->downloading_total), 15);
		}
		else
		{
			out << progress_bar(0.f, 15);
		}

#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
		if (i->country[0] == 0)
		{
			out << " ..";
		}
		else
		{
			out << " " << i->country[0] << i->country[1];
		}
#endif
		out << " " << (i->remote_dl_rate > 0 ? add_suffix(i->remote_dl_rate) + "/s ": "         ") << " ";

		if (i->flags & peer_info::handshake)
		{
			out << esc("31") << " waiting for handshake" << esc("0") << "\n";
		}
		else if (i->flags & peer_info::connecting)
		{
			out << esc("31") << " connecting to peer" << esc("0") << "\n";
		}
		else if (i->flags & peer_info::queued)
		{
			out << esc("33") << " queued" << esc("0") << "\n";
		}
		else
		{
			out << " " << i->client << "\n";
		}
	}
}

typedef std::multimap<std::string, libtorrent::torrent_handle> handles_t;

using boost::bind;
using boost::filesystem::path;
using boost::filesystem::exists;
using boost::filesystem::directory_iterator;
using boost::filesystem::extension;

// monitored_dir is true if this torrent is added because
// it was found in the directory that is monitored. If it
// is, it should be remembered so that it can be removed
// if it's no longer in that directory.
void add_torrent(libtorrent::session& ses
	, handles_t& handles
	, std::string const& torrent
	, float preferred_ratio
	, bool compact_mode
	, path const& save_path
	, bool monitored_dir) try
{
	using namespace libtorrent;

	std::ifstream in(torrent.c_str(), std::ios_base::binary);
	in.unsetf(std::ios_base::skipws);
	entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>());
	torrent_info t(e);

	std::cout << t.name() << "\n";

	entry resume_data;
	try
	{
		std::stringstream s;
		s << t.name() << ".fastresume";
		boost::filesystem::ifstream resume_file(save_path / s.str(), std::ios_base::binary);
		resume_file.unsetf(std::ios_base::skipws);
		resume_data = bdecode(
			std::istream_iterator<char>(resume_file)
			, std::istream_iterator<char>());
	}
	catch (invalid_encoding&) {}
	catch (boost::filesystem::filesystem_error&) {}

	torrent_handle h = ses.add_torrent(t, save_path, resume_data
		, compact_mode ? storage_mode_compact : storage_mode_sparse, false);
	handles.insert(std::make_pair(
		monitored_dir?std::string(torrent):std::string(), h));

	h.set_max_connections(60);
	h.set_max_uploads(-1);
	h.set_ratio(preferred_ratio);
	h.set_sequenced_download_threshold(15);
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
	h.resolve_countries(true);
#endif
}
catch (std::exception&) {};

void scan_dir(path const& dir_path
	, libtorrent::session& ses
	, handles_t& handles
	, float preferred_ratio
	, bool compact_mode
	, path const& save_path)
{
	std::set<std::string> valid;

	using namespace libtorrent;

	for (directory_iterator i(dir_path), end; i != end; ++i)
	{
		if (extension(*i) != ".torrent") continue;
		std::string file = i->string();

		handles_t::iterator k = handles.find(file);
		if (k != handles.end())
		{
			valid.insert(file);
			continue;
		}

		// the file has been added to the dir, start
		// downloading it.
		add_torrent(ses, handles, file, preferred_ratio, compact_mode ? storage_mode_compact
			: storage_mode_sparse
			, save_path, true);
		valid.insert(file);
	}

	// remove the torrents that are no longer in the directory

	for (handles_t::iterator i = handles.begin(); !handles.empty() && i != handles.end();)
	{
		if (i->first.empty() || valid.find(i->first) != valid.end())
		{
			++i;
			continue;
		}

		torrent_handle& h = i->second;
		if (!h.is_valid())
		{
			handles.erase(i++);
			continue;
		}

		h.pause();
		if (h.has_metadata())
		{
			entry data = h.write_resume_data();
			std::stringstream s;
			s << h.get_torrent_info().name() << ".fastresume";
			boost::filesystem::ofstream out(h.save_path() / s.str(), std::ios_base::binary);
			out.unsetf(std::ios_base::skipws);
			bencode(std::ostream_iterator<char>(out), data);
		}
		ses.remove_torrent(h);
		handles.erase(i++);
	}
}

int main(int ac, char* av[])
{
#if BOOST_VERSION < 103400
	using boost::filesystem::no_check;
	path::default_name_check(no_check);
#endif

	int listen_port;
	float preferred_ratio;
	int download_limit;
	int upload_limit;
	int upload_slots_limit;
	int half_open_limit;
	std::string save_path_str;
	std::string log_level;
	std::string ip_filter_file;
	std::string allocation_mode;
	std::string in_monitor_dir;
	std::string bind_to_interface;
	std::string proxy;
	std::string proxy_login;
	std::string proxy_type;
	int poll_interval;

	namespace po = boost::program_options;
	try
	{

		po::options_description desc("supported options");
		desc.add_options()
		("help,h", "display this help message")
		("port,p", po::value<int>(&listen_port)->default_value(6881)
			, "set listening port")
		("ratio,r", po::value<float>(&preferred_ratio)->default_value(0)
			, "set the preferred upload/download ratio. 0 means infinite. Values "
			"smaller than 1 are clamped to 1.")
		("max-download-rate,d", po::value<int>(&download_limit)->default_value(0)
			, "the maximum download rate given in kB/s. 0 means infinite.")
		("max-upload-rate,u", po::value<int>(&upload_limit)->default_value(0)
			, "the maximum upload rate given in kB/s. 0 means infinite.")
		("max-upload-slots", po::value<int>(&upload_slots_limit)->default_value(8)
			, "the maximum number of upload slots. 0 means infinite.")
		("save-path,s", po::value<std::string>(&save_path_str)->default_value("./")
			, "the path where the downloaded file/folder should be placed.")
		("log-level,l", po::value<std::string>(&log_level)->default_value("info")
			, "sets the level at which events are logged [debug | info | warning | fatal].")
		("ip-filter,f", po::value<std::string>(&ip_filter_file)->default_value("")
			, "sets the path to the ip-filter file used to block access from certain "
			"ips. ")
		("allocation-mode,a", po::value<std::string>(&allocation_mode)->default_value("compact")
			, "sets mode used for allocating the downloaded files on disk. "
			"Possible options are [full | compact]")
		("input-file,i", po::value<std::vector<std::string> >()
			, "adds an input .torrent file. At least one is required. arguments "
			"without any flag are implicitly an input file. To start a torrentless "
			"download, use <info-hash>@<tracker-url> instead of specifying a file.")
		("monitor-dir,m", po::value<std::string>(&in_monitor_dir)
			, "monitors the given directory, looking for .torrent files and "
			"automatically starts downloading them. It will stop downloading "
			"torrent files that are removed from the directory")
		("poll-interval,t", po::value<int>(&poll_interval)->default_value(2)
			, "if a directory is being monitored, this is the interval (given "
			"in seconds) between two refreshes of the directory listing")
		("half-open-limit,o", po::value<int>(&half_open_limit)->default_value(-1)
			, "Sets the maximum number of simultaneous half-open tcp connections")
		("bind,b", po::value<std::string>(&bind_to_interface)->default_value("")
			, "Sets the local interface to bind outbound and the listen "
			"socket to")
		("proxy-server,x", po::value<std::string>(&proxy)->default_value("")
			, "Sets the http proxy to be used for tracker and web seeds "
			"connections. The string is expected to be on the form: "
			"<hostname>:<port>. If no port is specified, 8080 is assumed")
		("proxy-login,n", po::value<std::string>(&proxy_login)->default_value("")
			, "Sets the username and password used to authenticate with the http "
			"proxy. The string should be given in the form: <username>:<password>")
		("proxy-type", po::value<std::string>(&proxy_type)->default_value("socks5")
			, "Sets the type of proxy to use [socks5 | http] ")
			;

		po::positional_options_description p;
		p.add("input-file", -1);

		po::variables_map vm;
		po::store(po::command_line_parser(ac, av).
			options(desc).positional(p).run(), vm);
		po::notify(vm);

		// make sure the arguments stays within the usable limits
		path monitor_dir(in_monitor_dir);
		if (listen_port < 0 || listen_port > 65525) listen_port = 6881;
		if (preferred_ratio != 0 && preferred_ratio < 1.f) preferred_ratio = 1.f;
		upload_limit *= 1000;
		download_limit *= 1000;
		if (download_limit <= 0) download_limit = -1;
		if (upload_limit <= 0) upload_limit = -1;
		if (poll_interval < 2) poll_interval = 2;
		if (half_open_limit < 1) half_open_limit = -1;
		if (upload_slots_limit <= 0) upload_slots_limit = -1;
		if (!monitor_dir.empty() && !exists(monitor_dir))
		{
			std::cerr << "The monitor directory doesn't exist: " << monitor_dir.string() << std::endl;
			return 1;
		}

		if (vm.count("help")
			|| vm.count("input-file") + vm.count("monitor-dir") == 0)
		{
			std::cout << desc << "\n";
			return 1;
		}

		bool compact_allocation_mode = (allocation_mode == "compact");

		using namespace libtorrent;

		std::vector<std::string> input;
		if (vm.count("input-file") > 0)
			input = vm["input-file"].as< std::vector<std::string> >();

		session_settings settings;
		proxy_settings ps;

		if (!proxy.empty())
		{
			try
			{
				std::size_t i = proxy.find(':');
				ps.hostname = proxy.substr(0, i);
				if (i == std::string::npos) ps.port = 8080;
				else ps.port = boost::lexical_cast<int>(
					proxy.substr(i + 1));
				if (proxy_type == "socks5")
					ps.type = proxy_settings::socks5;
				else
					ps.type = proxy_settings::http;
			}
			catch (std::exception&)
			{
				std::cerr << "Proxy hostname did not match the required format: "
					<< proxy << std::endl;
				return 1;
			}

			if (!proxy_login.empty())
			{
				std::size_t i = proxy_login.find(':');
				if (i == std::string::npos)
				{
					std::cerr << "Proxy login did not match the required format: "
					<< proxy_login << std::endl;
					return 1;
				}
				ps.username = proxy_login.substr(0, i);
				ps.password = proxy_login.substr(i + 1);
				if (proxy_type == "socks5")
					ps.type = proxy_settings::socks5_pw;
				else
					ps.type = proxy_settings::http_pw;
			}
		}

		settings.user_agent = "client_test/" LIBTORRENT_VERSION;

		std::deque<std::string> events;

		ptime next_dir_scan = time_now();

		// the string is the filename of the .torrent file, but only if
		// it was added through the directory monitor. It is used to
		// be able to remove torrents that were added via the directory
		// monitor when they're not in the directory anymore.
		handles_t handles;
		session ses;
		// UPnP port mapping
		ses.start_upnp();
		// NAT-PMP port mapping
		ses.start_natpmp();
		// Local service discovery (finds peers on the local network)
		ses.start_lsd();
		ses.add_extension(&create_metadata_plugin);
		ses.add_extension(&create_ut_pex_plugin);

		ses.set_max_uploads(upload_slots_limit);
		ses.set_max_half_open_connections(half_open_limit);
		ses.set_download_rate_limit(download_limit);
		ses.set_upload_rate_limit(upload_limit);
		ses.listen_on(std::make_pair(listen_port, listen_port + 10)
			, bind_to_interface.c_str());
		ses.set_settings(settings);
		ses.set_tracker_proxy(ps);
		ses.set_peer_proxy(ps);
		ses.set_web_seed_proxy(ps);

		if (log_level == "debug")
			ses.set_severity_level(alert::debug);
		else if (log_level == "warning")
			ses.set_severity_level(alert::warning);
		else if (log_level == "fatal")
			ses.set_severity_level(alert::fatal);
		else
			ses.set_severity_level(alert::info);

#ifndef TORRENT_DISABLE_DHT
		settings.use_dht_as_fallback = false;

		boost::filesystem::ifstream dht_state_file(".dht_state"
			, std::ios_base::binary);
		dht_state_file.unsetf(std::ios_base::skipws);
		entry dht_state;
		try
		{
			dht_state = bdecode(
				std::istream_iterator<char>(dht_state_file)
				, std::istream_iterator<char>());
		}
		catch (std::exception&) {}
		ses.start_dht(dht_state);
		ses.add_dht_router(std::make_pair(std::string("router.bittorrent.com")
			, 6881));
		ses.add_dht_router(std::make_pair(std::string("router.utorrent.com")
			, 6881));
		ses.add_dht_router(std::make_pair(std::string("router.bitcomet.com")
			, 6881));
#endif

		// look for ipfilter.dat
		// poor man's parser
		// reads emule ipfilter files.
		// with the following format:
		//
		// <first-ip> - <last-ip> , <access> , <comment>
		//
		// first-ip is an ip address that defines the first
		// address of the range
		// last-ip is the last ip address in the range
		// access is a number specifying the access control
		// for this ip-range. Right now values > 127 = allowed
		// and numbers <= 127 = blocked
		// the rest of the line is ignored
		//
		// In the original spec ranges may not overlap, but
		// here ranges may overlap, and it is the last added
		// rule that has precedence for addresses that may fall
		// into more than one range.
		if (!ip_filter_file.empty())
		{
			std::ifstream in(ip_filter_file.c_str());
			ip_filter filter;
			while (in.good())
			{
				char line[300];
				in.getline(line, 300);
				int len = in.gcount();
				if (len <= 0) continue;
				if (line[0] == '#') continue;
				int a, b, c, d;
				char dummy;
				std::stringstream ln(line);
				ln >> a >> dummy >> b >> dummy >> c >> dummy >> d >> dummy;
				address_v4 start((a << 24) + (b << 16) + (c << 8) + d);
				ln >> a >> dummy >> b >> dummy >> c >> dummy >> d >> dummy;
				address_v4 last((a << 24) + (b << 16) + (c << 8) + d);
				int flags;
				ln >> flags;
				if (flags <= 127) flags = ip_filter::blocked;
				else flags = 0;
				if (ln.fail()) break;
				filter.add_rule(start, last, flags);
			}
			ses.set_ip_filter(filter);
		}
		boost::filesystem::path save_path(save_path_str);

		// load the torrents given on the commandline
		boost::regex ex("([0-9A-Fa-f]{40})@(.+)");
		for (std::vector<std::string>::const_iterator i = input.begin();
			i != input.end(); ++i)
		{
			try
			{
				// first see if this is a torrentless download
				boost::cmatch what;
				if (boost::regex_match(i->c_str(), what, ex))
				{
					sha1_hash info_hash = boost::lexical_cast<sha1_hash>(what[1]);

					torrent_handle h = ses.add_torrent(std::string(what[2]).c_str()
						, info_hash, 0, save_path, entry(), compact_allocation_mode ? storage_mode_compact
						: storage_mode_sparse);
					handles.insert(std::make_pair(std::string(), h));

					h.set_max_connections(60);
					h.set_max_uploads(-1);
					h.set_ratio(preferred_ratio);
					h.set_sequenced_download_threshold(15);
					continue;
				}
				// if it's a torrent file, open it as usual
				add_torrent(ses, handles, i->c_str(), preferred_ratio
					, compact_allocation_mode ? storage_mode_compact : storage_mode_sparse, save_path, false);
			}
			catch (std::exception& e)
			{
				std::cout << e.what() << "\n";
			}
		}

		// main loop
		std::vector<peer_info> peers;
		std::vector<partial_piece_info> queue;

		bool print_peers = false;
		bool print_log = false;
		bool print_downloads = false;
		bool print_piece_bar = false;
		bool print_file_progress = false;

		for (;;)
		{
			char c;
			if (sleep_and_input(&c))
			{
				if (c == 'q')
				{
					for (handles_t::iterator i = handles.begin();
						i != handles.end(); ++i)
					{
						torrent_handle& h = i->second;
						if (!h.is_valid() || !h.has_metadata()) continue;

						h.pause();

						entry data = h.write_resume_data();
						std::stringstream s;
						s << h.get_torrent_info().name() << ".fastresume";
						boost::filesystem::ofstream out(h.save_path() / s.str(), std::ios_base::binary);
						out.unsetf(std::ios_base::skipws);
						bencode(std::ostream_iterator<char>(out), data);
						ses.remove_torrent(h);
					}
					break;
				}

				if(c == 'r')
				{
					// force reannounce on all torrents
					std::for_each(handles.begin(), handles.end()
						, bind(&torrent_handle::force_reannounce
						, bind(&handles_t::value_type::second, _1)));
				}

				if(c == 'p')
				{
					// pause all torrents
					std::for_each(handles.begin(), handles.end()
						, bind(&torrent_handle::pause
						, bind(&handles_t::value_type::second, _1)));
				}

				if(c == 'u')
				{
					// unpause all torrents
					std::for_each(handles.begin(), handles.end()
						, bind(&torrent_handle::resume
						, bind(&handles_t::value_type::second, _1)));
				}

				if (c == 'i') print_peers = !print_peers;
				if (c == 'l') print_log = !print_log;
				if (c == 'd') print_downloads = !print_downloads;
				if (c == 'f') print_file_progress = !print_file_progress;
				if (c == 'a') print_piece_bar = !print_piece_bar;
			}

			int terminal_width = 80;

#ifndef _WIN32
			{
				winsize size;
				ioctl(STDOUT_FILENO, TIOCGWINSZ, (char*)&size);
				terminal_width = size.ws_col;
			}
#endif

			// loop through the alert queue to see if anything has happened.
			std::auto_ptr<alert> a;
			a = ses.pop_alert();
			std::string now = time_now_string();
			while (a.get())
			{
				std::stringstream event_string;
				if (a->severity() == alert::fatal)
					event_string << esc("31"); // red
				else if (a->severity() == alert::warning)
					event_string << esc("33"); // yellow

				event_string << now << ": ";
				if (torrent_finished_alert* p = dynamic_cast<torrent_finished_alert*>(a.get()))
				{
					p->handle.set_max_connections(60);

					// write resume data for the finished torrent
					torrent_handle h = p->handle;
					entry data = h.write_resume_data();
					std::stringstream s;
					s << h.get_torrent_info().name() << ".fastresume";
					boost::filesystem::ofstream out(h.save_path() / s.str(), std::ios_base::binary);
					out.unsetf(std::ios_base::skipws);
					bencode(std::ostream_iterator<char>(out), data);

					event_string << p->handle.get_torrent_info().name() << ": "
						<< a->msg();
				}
				else if (peer_error_alert* p = dynamic_cast<peer_error_alert*>(a.get()))
				{
					event_string << identify_client(p->pid) << ": " << a->msg();
				}
				else if (invalid_request_alert* p = dynamic_cast<invalid_request_alert*>(a.get()))
				{
					event_string << identify_client(p->pid) << ": " << a->msg();
				}
				else if (tracker_warning_alert* p = dynamic_cast<tracker_warning_alert*>(a.get()))
				{
					event_string << "tracker message: " << p->msg();
				}
				else if (tracker_reply_alert* p = dynamic_cast<tracker_reply_alert*>(a.get()))
				{
					event_string << p->msg() << " (" << p->num_peers << ")";
				}
				else if (url_seed_alert* p = dynamic_cast<url_seed_alert*>(a.get()))
				{
					event_string << "web seed '" << p->url << "': " << p->msg();
				}
				else if (peer_blocked_alert* p = dynamic_cast<peer_blocked_alert*>(a.get()))
				{
					event_string << "(" << p->ip << ") " << p->msg();
				}
				else if (torrent_alert* p = dynamic_cast<torrent_alert*>(a.get()))
				{
					std::string name;
					try { name = p->handle.name(); } catch (std::exception&) {}
					event_string << "(" << name << ") " << p->msg();
				}
				else
				{
					event_string << a->msg();
				}
				event_string << esc("0");
				events.push_back(event_string.str());

				if (events.size() >= 20) events.pop_front();
				a = ses.pop_alert();
			}

			session_status sess_stat = ses.status();

			std::stringstream out;
			for (handles_t::iterator i = handles.begin();
				i != handles.end();)
			{
				torrent_handle& h = i->second;
				if (!h.is_valid())
				{
					handles.erase(i++);
					continue;
				}
				else
				{
					++i;
				}

				out << "- " << esc("37") << std::setw(40)
					<< std::setiosflags(std::ios::left);
				if (h.has_metadata())
				{
					std::string name = h.get_torrent_info().name();
					if (name.size() > 40) name.resize(40);
					out << name;
				}
				else
				{
					out << "-";
				}
				out << esc("0") << " ";
				torrent_status s = h.status();

				if (s.state != torrent_status::seeding)
				{
					static char const* state_str[] =
						{"queued", "checking", "connecting", "downloading metadata"
						, "downloading", "finished", "seeding", "allocating"};
					out << state_str[s.state] << " ";
				}

				if ((print_downloads && s.state != torrent_status::seeding)
					|| print_peers)
					h.get_peer_info(peers);

				if (s.state != torrent_status::seeding)
				{
					char const* progress_bar_color = "33"; // yellow
					if (s.state == torrent_status::checking_files
						|| s.state == torrent_status::downloading_metadata)
					{
						progress_bar_color = "35"; // magenta
					}
					else if (s.current_tracker.empty())
					{
						progress_bar_color = "31"; // red
					}
					else if (sess_stat.has_incoming_connections)
					{
						progress_bar_color = "32"; // green
					}
					out.precision(4);
					out.width(5);
					out.fill(' ');
					out << (s.progress*100) << "% ";
					out << progress_bar(s.progress, terminal_width - 63, progress_bar_color);
					out << "\n";
					out << "  total downloaded: " << esc("32") << s.total_done << esc("0") << " Bytes ";
					out	<< "peers: " << s.num_peers << " "
						<< "seeds: " << s.num_seeds << " "
						<< "distributed copies: " << s.distributed_copies << "\n"
						<< "  download: " << esc("32") << (s.download_rate > 0 ? add_suffix(s.download_rate) + "/s ": "         ") << esc("0")
						<< "(" << esc("32") << add_suffix(s.total_download) << esc("0") << ") ";
				}
				else
				{
					out << "download: " << "(" << esc("32") << add_suffix(s.total_download) << esc("0") << ") ";
				}
				out << "upload: " << esc("31") << (s.upload_rate > 0 ? add_suffix(s.upload_rate) + "/s ": "         ") << esc("0")
					<< "(" << esc("31") << add_suffix(s.total_upload) << esc("0") << ") "
					<< "ratio: " << ratio(s.total_payload_download, s.total_payload_upload) << "\n";
				if (s.state != torrent_status::seeding)
				{
					boost::posix_time::time_duration t = s.next_announce;
					out << "  next announce: " << esc("37")
						<< to_string(t.hours(),2) << ":"
						<< to_string(t.minutes(),2) << ":"
						<< to_string(t.seconds(), 2) << esc("0") << " ";
					out << "tracker: " << s.current_tracker << "\n";
					if (print_piece_bar && s.progress < 1.f && s.pieces)
						out << piece_bar(*s.pieces, terminal_width - 3) << "\n";
				}

				if (print_peers && !peers.empty())
					print_peer_info(out, peers);

				if (print_downloads && s.state != torrent_status::seeding)
				{
					h.get_download_queue(queue);
					std::sort(queue.begin(), queue.end(), bind(&partial_piece_info::piece_index, _1)
						< bind(&partial_piece_info::piece_index, _2));
					for (std::vector<partial_piece_info>::iterator i = queue.begin();
						i != queue.end(); ++i)
					{
						out << to_string(i->piece_index, 4) << ": [";
						for (int j = 0; j < i->blocks_in_piece; ++j)
						{
							int index = peer_index(i->blocks[j].peer, peers);
							char str[] = "+";
							if (index >= 0)
								str[0] = (index < 10)?'0' + index:'A' + index - 10;

#ifdef ANSI_TERMINAL_COLORS
							if (i->blocks[j].bytes_progress > 0
								&& i->blocks[j].state == block_info::requested)
							{
								if (i->blocks[j].num_peers > 1)
									out << esc("1;7");
								else
									out << esc("33;7");
								out << to_string(i->blocks[j].bytes_progress / float(i->blocks[j].block_size) * 10, 1) << esc("0");
							}
							else if (i->blocks[j].state == block_info::finished) out << esc("32;7") << str << esc("0");
							else if (i->blocks[j].state == block_info::writing) out << esc("35;7") << str << esc("0");
							else if (i->blocks[j].state == block_info::requested) out << str;
							else out << " ";
#else
							if (i->blocks[j].state == block_info::finished) out << "#";
							else if (i->blocks[j].state == block_info::writing) out << "+";
							else if (i->blocks[j].state == block_info::requested) out << str;
							else out << " ";
#endif
						}
						char* piece_state[4] = {"", "slow", "medium", "fast"};
						out << "] " << piece_state[i->piece_state] << "\n";
					}

					out << "___________________________________\n";
				}

				if (print_file_progress
					&& s.state != torrent_status::seeding
					&& h.has_metadata())
				{
					std::vector<float> file_progress;
					h.file_progress(file_progress);
					torrent_info const& info = h.get_torrent_info();
					for (int i = 0; i < info.num_files(); ++i)
					{
						if (file_progress[i] == 1.f)
							out << progress_bar(file_progress[i], 40, "32") << " "
								<< info.file_at(i).path.leaf() << "\n";
						else
							out << progress_bar(file_progress[i], 40, "33") << " "
								<< info.file_at(i).path.leaf() << "\n";
					}

					out << "___________________________________\n";
				}

			}

			if (print_log)
			{
				for (std::deque<std::string>::iterator i = events.begin();
					i != events.end(); ++i)
				{
					out << *i << "\n";
				}
			}

			clear_home();
			puts(out.str().c_str());

			if (!monitor_dir.empty()
				&& next_dir_scan < time_now())
			{
				scan_dir(monitor_dir, ses, handles, preferred_ratio
					, compact_allocation_mode, save_path);
				next_dir_scan = time_now() + seconds(poll_interval);
			}
		}

#ifndef TORRENT_DISABLE_DHT
		dht_state = ses.dht_state();
		boost::filesystem::ofstream out(".dht_state"
			, std::ios_base::binary);
		out.unsetf(std::ios_base::skipws);
		bencode(std::ostream_iterator<char>(out), dht_state);
#endif
	}
	catch (std::exception& e)
	{
  		std::cout << e.what() << "\n";
	}

#ifdef TORRENT_PROFILE
	print_checkpoints();
#endif
	return 0;
}

max_stars_repo_name: xeddmc/Halite

max_issues_repo_name: ialexsilva/Halite

max_forks_repo_name: ialexsilva/Halite


text:
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>

//#include <iostream>

namespace ublas = boost::numeric::ublas;

int main(int argc, char ** argv)
{
    ublas::matrix<double> M(3, 3, 1);
    ublas::identity_matrix<double> I(3);
    ublas::zero_matrix<double> Z(3);
    ublas::scalar_matrix<double> S(2, 3);

    for (size_t idxRow = 0; idxRow < M.size1(); idxRow++)
    {
        for (size_t idxCol = 0; idxCol < M.size2(); idxCol++)
        {
            M(idxRow, idxCol) = 3 * idxRow + idxCol;
        }
    }

    std::cout << "M: " << M << std::endl;
    std::cout << ublas::row(M, 0) << std::endl;
    std::cout << ublas::inner_prod(ublas::row(M, 0), ublas::row(M, 1)) << std::endl;
    std::cout << ublas::project(ublas::row(M, 1), ublas::range(0, 2)) << std::endl;

    getchar();

    return 0;
}

max_stars_repo_name: Aithosa/Notes

max_issues_repo_name: Aithosa/Notes

max_forks_repo_name: Aithosa/Notes


text:
/* $Id: test_image_modifications.cpp 48153 2011-01-01 15:57:50Z mordante $ */
/*
   Copyright (C) 2011 by Karol Kozub <karol.alt@gmail.com>
   Part of the Battle for Wesnoth Project http://www.wesnoth.org/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define GETTEXT_DOMAIN "wesnoth-test"

#include <boost/test/unit_test.hpp>
#include <sstream>

#include "game_config.hpp"
#include "config_cache.hpp"
#include "config.hpp"
#include "color_range.hpp"
#include "image.hpp"
#include "image_modifications.hpp"
#include "log.hpp"
#include "filesystem.hpp"

using namespace image;

namespace {
/// Sets up the environment for every test
class environment_setup
{
public:
	environment_setup()
		// redirects the output to an ignored stream
		:output_redirect_(ignored_stream_)
	{
		set_up_color_info();
		set_up_team_colors();
		set_up_image_paths();
	}

private:
	/** Sets up color_info configuration
	 *
	 * This is required by the RC modifications
	 */
	void set_up_color_info()
	{
		config cfg;
		cfg.add_child("color_range",
			       create_color_range("red",
						  "FF0000,FFFFFF,000000,FF0000",
						  "Red"));
		cfg.add_child("color_range",
			       create_color_range("blue",
						  "2E419B,FFFFFF,0F0F0F,0000FF",
						  "Blue"));

		game_config::add_color_info(cfg);
	}

	/** Sets up team color mapping
	 *
	 * This is required by TC modification
	 */
	void set_up_team_colors()
	{
		std::vector<std::string> tc;

		tc.push_back("red");
		tc.push_back("blue");

		image::set_team_colors(&tc);
	}

	/** Sets up the paths later used to load images
	 *
	 * This is required by all the modifications that use image::get_image
	 * to load images from disk
	 */
	void set_up_image_paths()
	{
		config cfg;

		cfg.add_child("binary_path",
			      create_path_config("data/core"));

		paths_manager_.set_paths(cfg);
	}

	config create_color_range(const std::string& id,
				  const std::string& rgb,
				  const std::string& name)
	{
		config cfg;

		cfg["id"] = id;
		cfg["rgb"] = rgb;
		cfg["name"] = name;

		return cfg;
	}

	config create_path_config(const std::string& path)
	{
		config cfg;

		cfg["path"] = path;

		return cfg;
	}

	std::stringstream ignored_stream_;
	lg::tredirect_output_setter output_redirect_;
	binary_paths_manager paths_manager_;
};
} // anonymous namespace

BOOST_AUTO_TEST_SUITE(image_modification_parsing)

/** Tests if modifications with a higher priority are placed before the others
 *
 * The RC modification has a higher priority than other modifications and has
 * to be applied before all the others. This test checks if that order is taken
 * care of by the queue.
 */
BOOST_AUTO_TEST_CASE(test_modificaiton_queue_order)
{
	environment_setup env_setup;

	modification_queue queue;
	modification* low_priority_mod = new fl_modification();
	modification* high_priority_mod = new rc_modification();

	queue.push(low_priority_mod);
	queue.push(high_priority_mod);

	BOOST_REQUIRE_EQUAL(queue.size(), 2);

	BOOST_CHECK_EQUAL(queue.top(), high_priority_mod);
	queue.pop();
	BOOST_CHECK_EQUAL(queue.top(), low_priority_mod);
	queue.pop();

	// reverse insertion order now
	queue.push(high_priority_mod);
	queue.push(low_priority_mod);

	BOOST_REQUIRE_EQUAL(queue.size(), 2);

	BOOST_CHECK_EQUAL(queue.top(), high_priority_mod);
	queue.pop();
	BOOST_CHECK_EQUAL(queue.top(), low_priority_mod);
	queue.pop();

	delete low_priority_mod;
	delete high_priority_mod;
}

/// Tests if the TC modification is correctly decoded
BOOST_AUTO_TEST_CASE(test_tc_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~TC(1,blue)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	rc_modification* mod = dynamic_cast<rc_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	const std::vector<Uint32>& old_color = game_config::tc_info("blue");
	// The first team color is red
	const color_range& new_color = game_config::color_info("red");
	std::map<Uint32, Uint32> expected = recolor_range(new_color, old_color);

	BOOST_CHECK(expected == mod->map());

	delete mod;
}

/// Tests if the TC modification with invalid arguments is ignored
BOOST_AUTO_TEST_CASE(test_tc_modification_decoding_invalid_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~TC()~TC(1)~TC(0,blue)");

	BOOST_REQUIRE_EQUAL(queue.size(), 0);
}

/// Tests if the RC modification is correctly decoded
BOOST_AUTO_TEST_CASE(test_rc_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~RC(red>blue)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	rc_modification* mod = dynamic_cast<rc_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	const std::vector<Uint32>& old_color = game_config::tc_info("red");
	const color_range& new_color = game_config::color_info("blue");
	std::map<Uint32, Uint32> expected = recolor_range(new_color, old_color);

	BOOST_CHECK(expected == mod->map());

	delete mod;
}

/// Tests if the RC modification with invalid arguments is ignored
BOOST_AUTO_TEST_CASE(test_rc_modification_decoding_invalid_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~RC()~RC(blue)~RC(>)");

	BOOST_REQUIRE_EQUAL(queue.size(), 0);
}

/// Tests if the PAL modification is correctly decoded
BOOST_AUTO_TEST_CASE(test_pal_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue =
		modification::decode("~PAL(000000,005000 > FFFFFF,FF00FF)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	rc_modification* mod = dynamic_cast<rc_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	std::vector<Uint32> const& old_palette = game_config::tc_info("000000,005000");
	std::vector<Uint32> const& new_palette = game_config::tc_info("FFFFFF,FF00FF");
	std::map<Uint32, Uint32> expected;

	for(size_t i = 0; i < old_palette.size() && i < new_palette.size(); ++i) {
	environment_setup env_setup;

		expected[old_palette[i]] = new_palette[i];
	}

	BOOST_CHECK(expected == mod->map());

	delete mod;
}

/// Tests if the PAL modification with invalid arguments is ignored
BOOST_AUTO_TEST_CASE(test_pal_modification_decoding_invalid_args)
{
	environment_setup env_setup;

	modification_queue queue =
		modification::decode("~PAL()~PAL(>)");

	BOOST_REQUIRE_EQUAL(queue.size(), 0);
}

/// Tests if the FL modification is correctly decoded without arguments
BOOST_AUTO_TEST_CASE(test_fl_modification_decoding_default)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~FL()");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	fl_modification* mod = dynamic_cast<fl_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(mod->get_horiz());
	BOOST_CHECK(!mod->get_vert());

	delete mod;
}

/// Tests if the FL modification is correctly decoded with the horiz argument
BOOST_AUTO_TEST_CASE(test_fl_modification_decoding_horiz)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~FL(horiz)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	fl_modification* mod = dynamic_cast<fl_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(mod->get_horiz());
	BOOST_CHECK(!mod->get_vert());

	delete mod;
}

/// Tests if the FL modification is correctly decoded with the vert argument
BOOST_AUTO_TEST_CASE(test_fl_modification_decoding_vert)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~FL(vert)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	fl_modification* mod = dynamic_cast<fl_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(!mod->get_horiz());
	BOOST_CHECK(mod->get_vert());

	delete mod;
}

/// Tests if the FL modification is correctly decoded with both horiz and vert
BOOST_AUTO_TEST_CASE(test_fl_modification_decoding_horiz_and_vert)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~FL(horiz,vert)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	fl_modification* mod = dynamic_cast<fl_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(mod->get_horiz());
	BOOST_CHECK(mod->get_vert());

	delete mod;
}

/// Tests if the GS modification is correctly decoded
BOOST_AUTO_TEST_CASE(test_gs_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~GS()");

	BOOST_REQUIRE(queue.size() == 1);

	gs_modification* mod = dynamic_cast<gs_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_CHECK(mod != NULL);

	delete mod;
}

/// Tests if the CROP modification without arguments is ignored
BOOST_AUTO_TEST_CASE(test_crop_modification_decoding_no_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~CROP()");

	BOOST_REQUIRE_EQUAL(queue.size(), 0);
}

/// Tests if the CROP modification is correctly decoded when given one argument
BOOST_AUTO_TEST_CASE(test_crop_modification_decoding_1_arg)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~CROP(1)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	crop_modification* mod = dynamic_cast<crop_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	const SDL_Rect& slice = mod->get_slice();

	BOOST_CHECK_EQUAL(slice.x, 1);
	BOOST_CHECK_EQUAL(slice.y, 0);
	BOOST_CHECK_EQUAL(slice.w, 0);
	BOOST_CHECK_EQUAL(slice.h, 0);

	delete mod;
}

/// Tests if the CROP modification is correctly decoded when given two args
BOOST_AUTO_TEST_CASE(test_crop_modification_decoding_2_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~CROP(1,2)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	crop_modification* mod = dynamic_cast<crop_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	const SDL_Rect& slice = mod->get_slice();

	BOOST_CHECK_EQUAL(slice.x, 1);
	BOOST_CHECK_EQUAL(slice.y, 2);
	BOOST_CHECK_EQUAL(slice.w, 0);
	BOOST_CHECK_EQUAL(slice.h, 0);

	delete mod;
}

/// Tests if the CROP modification is correctly decoded when given three args
BOOST_AUTO_TEST_CASE(test_crop_modification_decoding_3_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~CROP(1,2,3)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	crop_modification* mod = dynamic_cast<crop_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	const SDL_Rect& slice = mod->get_slice();

	BOOST_CHECK_EQUAL(slice.x, 1);
	BOOST_CHECK_EQUAL(slice.y, 2);
	BOOST_CHECK_EQUAL(slice.w, 3);
	BOOST_CHECK_EQUAL(slice.h, 0);

	delete mod;
}

/// Tests if the CROP modification is correctly decoded when given four args
BOOST_AUTO_TEST_CASE(test_crop_modification_decoding_4_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~CROP(1,2,3,4)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	crop_modification* mod = dynamic_cast<crop_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	const SDL_Rect& slice = mod->get_slice();

	BOOST_CHECK_EQUAL(slice.x, 1);
	BOOST_CHECK_EQUAL(slice.y, 2);
	BOOST_CHECK_EQUAL(slice.w, 3);
	BOOST_CHECK_EQUAL(slice.h, 4);

	delete mod;
}

/** Tests if the BLIT modification with one argument is correctly decoded
 *
 * @todo check if the surface is correct
 */
BOOST_AUTO_TEST_CASE(test_blit_modification_decoding_1_arg)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BLIT(wesnoth-icon.png)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	blit_modification* mod = dynamic_cast<blit_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(!mod->get_surface().null());
	BOOST_CHECK_EQUAL(mod->get_x(), 0);
	BOOST_CHECK_EQUAL(mod->get_y(), 0);

	delete mod;
}

/** Tests if the BLIT modification with three arguments is correctly decoded
 *
 * @todo check if the surface is correct
 */
BOOST_AUTO_TEST_CASE(test_blit_modification_decoding_3_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BLIT(wesnoth-icon.png,1,2)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	blit_modification* mod = dynamic_cast<blit_modification*>(queue.top());

	BOOST_REQUIRE(mod != NULL);
	// The dynamic_cast returns NULL if the argument doesn't match the type

	BOOST_CHECK(!mod->get_surface().null());
	BOOST_CHECK_EQUAL(mod->get_x(), 1);
	BOOST_CHECK_EQUAL(mod->get_y(), 2);

	delete mod;
}

/// Tests if the BLIT modification with invalid arguments is ignored
BOOST_AUTO_TEST_CASE(test_blit_modification_decoding_invalid_args)
{
	environment_setup env_setup;

	modification_queue queue =
		modification::decode("~BLIT()"
				     "~BLIT(wesnoth-icon.png,1,-2)"
				     "~BLIT(wesnoth-icon.png,-1,2)"
				     "~BLIT(wesnoth-icon.png,-1,-2)");

	BOOST_CHECK_EQUAL(queue.size(), 0);
}

/** Tests if the MASK modification with one argument is correctly decoded
 *
 * @todo check if the surface is correct
 */
BOOST_AUTO_TEST_CASE(test_mask_modification_decoding_1_arg)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~MASK(wesnoth-icon.png)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	mask_modification* mod = dynamic_cast<mask_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(!mod->get_mask().null());
	BOOST_CHECK_EQUAL(mod->get_x(), 0);
	BOOST_CHECK_EQUAL(mod->get_y(), 0);

	delete mod;
}

/** Tests if the MASK modification with three arguments is correctly decoded
 *
 * @todo check if the surface is correct
 */
BOOST_AUTO_TEST_CASE(test_mask_modification_decoding_3_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~MASK(wesnoth-icon.png,3,4)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	mask_modification* mod = dynamic_cast<mask_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(!mod->get_mask().null());
	BOOST_CHECK_EQUAL(mod->get_x(), 3);
	BOOST_CHECK_EQUAL(mod->get_y(), 4);

	delete mod;
}

/// Tests if the MASK modification with invalid arguments is ignored
BOOST_AUTO_TEST_CASE(test_mask_modification_decoding_invalid_args)
{
	environment_setup env_setup;

	modification_queue queue =
		modification::decode("~MASK()"
				     "~MASK(wesnoth-icon.png,3,-4)"
				     "~MASK(wesnoth-icon.png,-3,4)"
				     "~MASK(wesnoth-icon.png,-3,-4)");

	BOOST_CHECK_EQUAL(queue.size(), 0);
}

/// Tests if the L modification without arguments is ignored
BOOST_AUTO_TEST_CASE(test_l_modification_decoding_no_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~L()");

	BOOST_CHECK_EQUAL(queue.size(), 0);
}

/** Tests if the L modification with one argument is correctly decoded
 *
 * @todo check if the surface is correct
 */
BOOST_AUTO_TEST_CASE(test_l_modification_decoding_1_arg)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~L(wesnoth-icon.png)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	light_modification* mod = dynamic_cast<light_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(!mod->get_surface().null());

	delete mod;
}

/// Tests if the SCALE modification without arguments is ignored
BOOST_AUTO_TEST_CASE(test_scale_modification_decoding_no_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~SCALE()");

	BOOST_CHECK_EQUAL(queue.size(), 0);
}

/// Tests if the SCALE modification with one argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_scale_modification_decoding_1_arg)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~SCALE(3)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	scale_modification* mod = dynamic_cast<scale_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_w(), 3);
	BOOST_CHECK_EQUAL(mod->get_h(), 0);

	delete mod;
}

/// Tests if the SCALE modification with two arguments is correctly decoded
BOOST_AUTO_TEST_CASE(test_scale_modification_decoding_2_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~SCALE(4,5)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	scale_modification* mod = dynamic_cast<scale_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_w(), 4);
	BOOST_CHECK_EQUAL(mod->get_h(), 5);

	delete mod;
}

/// Tests if the O modification with a percent argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_o_modification_decoding_percent_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~O(45%)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	o_modification* mod = dynamic_cast<o_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(mod->get_opacity() > 0.44);
	BOOST_CHECK(mod->get_opacity() < 0.46);

	delete mod;
}

/// Tests if the O modification with a fraction argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_o_modification_decoding_fraction_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~O(0.34)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	o_modification* mod = dynamic_cast<o_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK(mod->get_opacity() > 0.33);
	BOOST_CHECK(mod->get_opacity() < 0.35);

	delete mod;
}

/// Tests if the BL modification without arguments is correctly decoded
BOOST_AUTO_TEST_CASE(test_bl_modification_decoding_no_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BL()");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	bl_modification* mod = dynamic_cast<bl_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_depth(), 0);

	delete mod;
}

/// Tests if the BL modification with one argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_bl_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BL(2)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	bl_modification* mod = dynamic_cast<bl_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_depth(), 2);

	delete mod;
}

/// Tests if the R, G and B modifications without args are correctly decoded
BOOST_AUTO_TEST_CASE(test_rgb_modification_decoding_no_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~R()~G()~B()");

	BOOST_REQUIRE_EQUAL(queue.size(), 3);

	for(int i = 0; i < 3; i++) {
	environment_setup env_setup;

		cs_modification* mod = dynamic_cast<cs_modification*>(queue.top());

		// The dynamic_cast returns NULL if the argument doesn't match the type
		BOOST_REQUIRE(mod != NULL);

		BOOST_CHECK_EQUAL(mod->get_r(), 0);
		BOOST_CHECK_EQUAL(mod->get_g(), 0);
		BOOST_CHECK_EQUAL(mod->get_b(), 0);

		queue.pop();

		delete mod;
	}
}

/// Tests if the R modification with one argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_r_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~R(123)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	cs_modification* mod = dynamic_cast<cs_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_r(), 123);
	BOOST_CHECK_EQUAL(mod->get_g(), 0);
	BOOST_CHECK_EQUAL(mod->get_b(), 0);

	delete mod;
}

/// Tests if the G modification with one argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_g_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~G(132)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	cs_modification* mod = dynamic_cast<cs_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_r(), 0);
	BOOST_CHECK_EQUAL(mod->get_g(), 132);
	BOOST_CHECK_EQUAL(mod->get_b(), 0);

	delete mod;
}

/// Tests if the B modification with one argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_b_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~B(312)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	cs_modification* mod = dynamic_cast<cs_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_r(), 0);
	BOOST_CHECK_EQUAL(mod->get_g(), 0);
	BOOST_CHECK_EQUAL(mod->get_b(), 312);

	delete mod;
}

/// Tests if the BRIGHTEN modification is correctly decoded
BOOST_AUTO_TEST_CASE(test_brighten_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BRIGHTEN()");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	brighten_modification* mod = dynamic_cast<brighten_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_CHECK(mod != NULL);

	delete mod;
}

/// Tests if the DARKEN modification is correctly decoded
BOOST_AUTO_TEST_CASE(test_draken_modification_decoding)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~DARKEN()");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	darken_modification* mod = dynamic_cast<darken_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_CHECK(mod != NULL);

	delete mod;
}

/// Tests if the BG modification without arguments is correctly decoded
BOOST_AUTO_TEST_CASE(test_bg_modification_decoding_no_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BG()");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	background_modification* mod = dynamic_cast<background_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_color().r, 0);
	BOOST_CHECK_EQUAL(mod->get_color().g, 0);
	BOOST_CHECK_EQUAL(mod->get_color().b, 0);
	BOOST_CHECK_EQUAL(mod->get_color().unused, 255);

	delete mod;
}

/// Tests if the BG modification with one argument is correctly decoded
BOOST_AUTO_TEST_CASE(test_bg_modification_decoding_1_arg)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BG(1)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	background_modification* mod = dynamic_cast<background_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_color().r, 1);
	BOOST_CHECK_EQUAL(mod->get_color().g, 0);
	BOOST_CHECK_EQUAL(mod->get_color().b, 0);
	BOOST_CHECK_EQUAL(mod->get_color().unused, 255);

	delete mod;
}

/// Tests if the BG modification with two arguments is correctly decoded
BOOST_AUTO_TEST_CASE(test_bg_modification_decoding_2_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BG(1,2)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	background_modification* mod = dynamic_cast<background_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_color().r, 1);
	BOOST_CHECK_EQUAL(mod->get_color().g, 2);
	BOOST_CHECK_EQUAL(mod->get_color().b, 0);
	BOOST_CHECK_EQUAL(mod->get_color().unused, 255);

	delete mod;
}

/// Tests if the BG modification with three arguments is correctly decoded
BOOST_AUTO_TEST_CASE(test_bg_modification_decoding_3_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BG(1,2,3)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	background_modification* mod = dynamic_cast<background_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_color().r, 1);
	BOOST_CHECK_EQUAL(mod->get_color().g, 2);
	BOOST_CHECK_EQUAL(mod->get_color().b, 3);
	BOOST_CHECK_EQUAL(mod->get_color().unused, 255);

	delete mod;
}

/// Tests if the BG modification with four arguments is correctly decoded
BOOST_AUTO_TEST_CASE(test_bg_modification_decoding_4_args)
{
	environment_setup env_setup;

	modification_queue queue = modification::decode("~BG(1,2,3,4)");

	BOOST_REQUIRE_EQUAL(queue.size(), 1);

	background_modification* mod = dynamic_cast<background_modification*>(queue.top());

	// The dynamic_cast returns NULL if the argument doesn't match the type
	BOOST_REQUIRE(mod != NULL);

	BOOST_CHECK_EQUAL(mod->get_color().r, 1);
	BOOST_CHECK_EQUAL(mod->get_color().g, 2);
	BOOST_CHECK_EQUAL(mod->get_color().b, 3);
	BOOST_CHECK_EQUAL(mod->get_color().unused, 4);

	delete mod;
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


text:
// Copyright 2015-2020 Tier IV, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <quaternion_operation/quaternion_operation.h>

#include <boost/optional.hpp>
#include <memory>
#include <simple_sensor_simulator/exception.hpp>
#include <simple_sensor_simulator/sensor_simulation/lidar/lidar_sensor.hpp>
#include <simple_sensor_simulator/sensor_simulation/lidar/raycaster.hpp>
#include <simulation_interface/conversions.hpp>
#include <string>
#include <vector>

namespace simple_sensor_simulator
{
template <>
auto LidarSensor<sensor_msgs::msg::PointCloud2>::raycast(
  const std::vector<traffic_simulator_msgs::EntityStatus> & status, const rclcpp::Time & stamp)
  -> sensor_msgs::msg::PointCloud2
{
  Raycaster raycaster;
  boost::optional<geometry_msgs::msg::Pose> ego_pose;
  for (const auto & s : status) {
    if (configuration_.entity() == s.name()) {
      geometry_msgs::msg::Pose pose;
      simulation_interface::toMsg(s.pose(), pose);
      ego_pose = pose;
    } else {
      geometry_msgs::msg::Pose pose;
      simulation_interface::toMsg(s.pose(), pose);
      auto rotation = quaternion_operation::getRotationMatrix(pose.orientation);
      geometry_msgs::msg::Point center_point;
      simulation_interface::toMsg(s.bounding_box().center(), center_point);
      Eigen::Vector3d center(center_point.x, center_point.y, center_point.z);
      center = rotation * center;
      pose.position.x = pose.position.x + center.x();
      pose.position.y = pose.position.y + center.y();
      pose.position.z = pose.position.z + center.z();
      raycaster.addPrimitive<simple_sensor_simulator::primitives::Box>(
        s.name(), s.bounding_box().dimensions().x(), s.bounding_box().dimensions().y(),
        s.bounding_box().dimensions().z(), pose);
    }
  }
  if (ego_pose) {
    std::vector<double> vertical_angles;
    for (const auto v : configuration_.vertical_angles()) {
      vertical_angles.emplace_back(v);
    }
    const auto pointcloud = raycaster.raycast(
      "base_link", stamp, ego_pose.get(), configuration_.horizontal_resolution(), vertical_angles);
    detected_objects_ = raycaster.getDetectedObject();
    return pointcloud;
  }
  throw simple_sensor_simulator::SimulationRuntimeError("failed to found ego vehicle");
}
}  // namespace simple_sensor_simulator


text:
/*  $Id: Job.cpp,v 1.23 2016/10/05 08:52:58 severin Exp $ */

/*******

NAME - EEDB::JobQueue::Job

SYNOPSIS

DESCRIPTION

CONTACT

  Jessica Severin <severin@gsc.riken.jp>

LICENSE

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

APPENDIX

The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _

******/

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <rapidxml.hpp>  //rapidxml must be include before boost
#include <boost/algorithm/string.hpp>
#include <MQDB/MappedQuery.h>
#include <EEDB/JobQueue/Job.h>
#include <EEDB/Chrom.h>
#include <sqlite3.h>
#include <stdarg.h>

using namespace std;
using namespace MQDB;

const char*  EEDB::JobQueue::Job::class_name = "EEDB::JobQueue::Job";

void _eedb_job_delete_func(MQDB::DBObject *obj) {
  delete (EEDB::JobQueue::Job*)obj;
}
void _eedb_job_xml_func(MQDB::DBObject *obj, string &xml_buffer) {
  ((EEDB::JobQueue::Job*)obj)->_xml(xml_buffer);
}
void _eedb_job_simple_xml_func(MQDB::DBObject *obj, string &xml_buffer) {
  ((EEDB::JobQueue::Job*)obj)->_xml(xml_buffer);
}
string _eedb_job_display_desc_func(MQDB::DBObject *obj) {
  return ((EEDB::JobQueue::Job*)obj)->_display_desc();
}

EEDB::JobQueue::Job::Job() {
  init();
}

EEDB::JobQueue::Job::Job(EEDB::User *user) {
  init();

  if(!user) { return; }
  if(user->database() == NULL) { return; }

  _user = user;
  _status = "READY";
}

EEDB::JobQueue::Job::~Job() {
}

void EEDB::JobQueue::Job::init() {
  MQDB::MappedQuery::init();
  _classname                 = EEDB::JobQueue::Job::class_name;
  _funcptr_delete            = _eedb_job_delete_func;
  _funcptr_display_desc      = _eedb_job_display_desc_func;
  _funcptr_xml               = _eedb_job_xml_func;
  _funcptr_simple_xml        = _eedb_job_simple_xml_func;
  _created                   = 0;
  _completed                 = 0;
  _status                    = "READY";
  _metadata_loaded           = false;
  _user                      = NULL;
  _user_id                   = -1;
  _analysis_id               = -1;
}

////////////////////////////////////////////////////
//
// getter/setter methods of data which is stored in database
//
////////////////////////////////////////////////////

string    EEDB::JobQueue::Job::created_date_string() {
  string str;
  if(_created>0) {
    time_t t_update = _created;
    char *ct_value = ctime(&t_update);
    if(ct_value != NULL) {
      int len = strlen(ct_value);
      if(len>0) {
        ct_value[len-1] = '\0';
        str = ct_value;
      }
    }
  }
  return str;
}

string    EEDB::JobQueue::Job::completed_date_string() {
  string str;
  if(_completed>0) {
    time_t t_update = _completed;
    char *ct_value = ctime(&t_update);
    if(ct_value != NULL) {
      int len = strlen(ct_value);
      if(len>0) {
        ct_value[len-1] = '\0';
        str = ct_value;
      }
    }
  }
  return str;
}

EEDB::User*   EEDB::JobQueue::Job::user() {
  if(_user) { return _user; }

  if((_database != NULL) && (_user_id != -1)) {
    _user = EEDB::User::fetch_by_id(_database, _user_id);
  }
  return _user;
}

EEDB::MetadataSet*   EEDB::JobQueue::Job::metadataset() {
  if(!_metadata_loaded) {
    _metadata_loaded = true;
    if(_database != NULL) {
      vector<DBObject*> mdata = EEDB::Metadata::fetch_all_by_job_id(_database, _primary_db_id);
      _metadataset.add_metadata(mdata);
    }
    //$self->{'metadataset'}->remove_duplicates;
  }
  return &_metadataset;
}

void   EEDB::JobQueue::Job::status(string value) {
  _status = value;
}

string  EEDB::JobQueue::Job::display_name() {
  EEDB::Metadata *md;
  if((md = metadataset()->find_metadata("display_name", ""))) { return md->data(); }
  return "";
}

string  EEDB::JobQueue::Job::description() {
  EEDB::Metadata *md;
  if((md = metadataset()->find_metadata("description", ""))) { return md->data(); }
  return "";
}

string  EEDB::JobQueue::Job::genome_name() {
  EEDB::Metadata *md;
  if((md = metadataset()->find_metadata("assembly", ""))) { return md->data(); }
  return "";
}

////////////////////////////////////////////////////////////////

string EEDB::JobQueue::Job::_display_desc() {
  char buffer[2048];
  snprintf(buffer, 2040, "Job(db %ld ) %s",
    _primary_db_id,
    created_date_string().c_str());
  return buffer;
}

void EEDB::JobQueue::Job::_xml(string &xml_buffer) {

  xml_buffer.append("<job status=\"");
  xml_buffer.append(_status);
  xml_buffer.append("\" create_date=\"");
  xml_buffer.append(created_date_string());
  xml_buffer.append("\">\n");

  EEDB::MetadataSet *mdset = metadataset();
  if(mdset!=NULL) { mdset->xml(xml_buffer); }

  xml_buffer.append("</job>\n");
}

EEDB::JobQueue::Job::Job(void *xml_node) {
  //constructor using a rapidxml node
  init();
  if(xml_node==NULL) { return; }

  rapidxml::xml_node<>      *root_node = (rapidxml::xml_node<>*)xml_node;
  rapidxml::xml_node<>      *node;
  rapidxml::xml_attribute<> *attr;

  if(string(root_node->name()) != "job") { return; }

  if((attr = root_node->first_attribute("status"))) { _status = attr->value(); }

  if((attr = root_node->first_attribute("create_date"))) {
    string date_string = attr->value();
    _created = MQDB::seconds_from_epoch(date_string);
  }

  // metadata
  EEDB::MetadataSet *mdset = metadataset();
  if((node = root_node->first_node("mdata")) != NULL) {
    while(node) {
      EEDB::Metadata *mdata = new EEDB::Metadata(node);
      mdset->add_metadata(mdata);
      node = node->next_sibling("mdata");
    }
  }
  if((node = root_node->first_node("symbol")) != NULL) {
    while(node) {
      EEDB::Symbol *mdata = new EEDB::Symbol(node);
      mdset->add_metadata(mdata);
      node = node->next_sibling("symbol");
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////
//
// class level MQDB style fetch methods
//
//////////////////////////////////////////////////////////////////////////////////////////////////

void  EEDB::JobQueue::Job::init_from_row_map(map<string, dynadata> &row_map) {
  /*
   | job_id       | int(11)                                                 |      | PRI | NULL                | auto_increment |
   | analysis_id  | int(11)                                                 |      | MUL | 0                   |                |
   | user_id      | int(11)                                                 |      |     | 0                   |                |
   | job_claim    | char(40)                                                |      | MUL |                     |                |
   | worker_id    | int(11)                                                 |      | MUL | 0                   |                |
   | status       | enum('READY','BLOCKED','CLAIMED','RUN','DONE','FAILED') |      |     | READY               |                |
   | retry_count  | int(11)                                                 |      |     | 0                   |                |
   | created      | timestamp                                               | YES  |     | CURRENT_TIMESTAMP   |                |
   | completed    | datetime                                                |      |     | 0000-00-00 00:00:00 |                |
   | branch_code  | int(11)                                                 |      |     | 1                   |                |
   | runtime_msec | int(11)                                                 |      |     | 0                   |                |
   | query_count  | int(11)                                                 |      |     | 0                   |                |
   */

  _primary_db_id   = row_map["job_id"].i_int;
  _status          = row_map["status"].i_string;
  _user_id         = row_map["user_id"].i_int;
  _analysis_id     = row_map["analysis_id"].i_int;

  /*
   _taxon_id        = row_map["taxon_id"].i_int;
   _ucsc_name       = row_map["ucsc_name"].i_string;
   _primary_db_id   = row_map["collaboration_id"].i_int;
   _group_uuid      = row_map["uuid"].i_string;
   _owner_identity  = row_map["owner_openid"].i_string;
   _display_name    = row_map["display_name"].i_string;
   _member_status   = row_map["member_status"].i_string;

   if(row_map["openID"].type == STRING) {
   if(row_map["openID"].i_string == _owner_identity) { _member_status = "OWNER"; }
   }
   if(_member_status.empty()) { _member_status = "not_member"; }
   */

  if(row_map["completed"].type == MQDB::STRING) {
    string date_string = row_map["completed"].i_string;
    _completed = MQDB::seconds_from_epoch(date_string);
  }
  if(row_map["completed"].type == MQDB::TIMESTAMP) {
    _completed = row_map["completed"].i_timestamp;
  }
  if(row_map["created"].type == MQDB::STRING) {
    string date_string = row_map["created"].i_string;
    _created = MQDB::seconds_from_epoch(date_string);
  }
  if(row_map["created"].type == MQDB::TIMESTAMP) {
    _created = row_map["created"].i_timestamp;
  }

}

vector<MQDB::DBObject*>  EEDB::JobQueue::Job::fetch_all_by_user(EEDB::User *user) {
  vector<MQDB::DBObject*> t_result;
  if(!user) { return t_result; }
  if(user->database() == NULL) { return t_result; }

  MQDB::Database *db = user->database();
  //ignore DONE and older than 24hour jobs
  const char *sql = "SELECT * FROM job WHERE user_id=? AND status!='DONE' AND (UNIX_TIMESTAMP()-UNIX_TIMESTAMP(created))/86400<=1.0 ORDER BY created";
  return MQDB::fetch_multiple(EEDB::JobQueue::Job::create, db, sql, "d", user->primary_id());
}

EEDB::JobQueue::Job*  EEDB::JobQueue::Job::fetch_by_id(MQDB::Database *db, long int id) {
  const char *sql = "SELECT * FROM job WHERE job_id=?";
  EEDB::JobQueue::Job *job = (EEDB::JobQueue::Job*) MQDB::fetch_single(EEDB::JobQueue::Job::create, db, sql, "d", id);
  return job;
}

//////////////////////////////////////////////////////////////////////////////////////////////////
//
// MappedQuery storage methods
//
//////////////////////////////////////////////////////////////////////////////////////////////////

bool EEDB::JobQueue::Job::store() {
  if(_user == NULL) { return false; }
  MQDB::Database *db = _user->database();
  if(db==NULL) { return false; }

  db->do_sql("INSERT INTO job(user_id, status) VALUES(?,?)", "ds",
             _user->primary_id(), _status.c_str());

  if(db->last_insert_id() < 0) { return false; }

  _primary_db_id = db->last_insert_id();
  database(db);
  _peer_uuid = NULL;
  _db_id.clear();

  //now do the symbols and metadata
  store_metadata();
  return true;
}

bool EEDB::JobQueue::Job::store_metadata() {
  if(database() == NULL) { return false; }
  if(primary_id() == -1) { return false; }

  MQDB::Database *db = database();

  metadataset()->remove_duplicates();

  vector<EEDB::Metadata*> mdlist = metadataset()->metadata_list();
  for(unsigned int i=0; i<mdlist.size(); i++) {
    EEDB::Metadata *md = mdlist[i];
    if(md->classname() == EEDB::Metadata::class_name) {
      if(!md->check_exists_db(db)) { md->store(db); }
      md->store_link_to_job(this);
    }
  }
  return true;
}

bool EEDB::JobQueue::Job::update_metadata() {
  if(database() == NULL) { return false; }
  if(primary_id() == -1) { return false; }

  MQDB::Database *db = database();

  //unlink all old metadata
  db->do_sql("DELETE FROM job_2_metadata WHERE job_id=?", "d", primary_id());

  //store again
  store_metadata();
  return true;
}


text:
//
// keyvi - A key value store.
//
// Copyright 2015 Hendrik Muhs<hendrik.muhs@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

/*
 * json_value_store_test.cpp
 *
 *  Created on: Nov 5, 2014
 *      Author: hendrik
 */

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include "dictionary/fsa/internal/json_value_store.h"
#include "dictionary/fsa/internal/constants.h"

namespace keyvi {
namespace dictionary {
namespace fsa {
namespace internal {

// The name of the suite must be a different name to your class
BOOST_AUTO_TEST_SUITE( JsonValueTest )

BOOST_AUTO_TEST_CASE( minimization )
{
  JsonValueStore strings(
      IValueStoreWriter::vs_param_t{{TEMPORARY_PATH_KEY, "/tmp"}});
  bool no_minimization = false;
  uint32_t v = strings.GetValue("{\"mytestvalue\":25, \"mytestvalue2\":23}", no_minimization);
  BOOST_CHECK_EQUAL(v,0);
  uint32_t w = strings.GetValue("othervalue", no_minimization);
  uint32_t x = strings.GetValue("{\"mytestvalue3\":55, \"mytestvalue4\":773}", no_minimization);

  BOOST_CHECK(w>0);
  BOOST_CHECK_EQUAL(v,strings.GetValue("{\"mytestvalue\": 25, \"mytestvalue2\": 23}", no_minimization));
  BOOST_CHECK_EQUAL(x,strings.GetValue("{\"mytestvalue3\":55, \"mytestvalue4\":773}", no_minimization));
  BOOST_CHECK_EQUAL(w,strings.GetValue("othervalue", no_minimization));
}

BOOST_AUTO_TEST_CASE( minimization_longvalues )
{
  JsonValueStore strings(
      IValueStoreWriter::vs_param_t{{TEMPORARY_PATH_KEY, "/tmp"}});
  bool no_minimization = false;
  std::string value = "{\"";
  value += std::string(60000, 'a');
  value += "\":42}";

  uint32_t v = strings.GetValue(value, no_minimization);
  BOOST_CHECK_EQUAL(v,0);
  uint32_t w = strings.GetValue("othervalue", no_minimization);
  BOOST_CHECK(v != w);

  BOOST_CHECK(w>0);
  BOOST_CHECK_EQUAL(v,strings.GetValue(value, no_minimization));
  BOOST_CHECK_EQUAL(w,strings.GetValue("othervalue", no_minimization));
}

BOOST_AUTO_TEST_CASE( minimization2 )
{
  JsonValueStore strings(
      IValueStoreWriter::vs_param_t{{TEMPORARY_PATH_KEY, "/tmp"}});
  bool no_minimization = false;

  uint64_t v = strings.GetValue("{\"f\": 5571575, \"df\": 1362790, \"uqf\": 2129086, \"tf1df\": 99838, \"tf2df\": 274586, \"tf3df\": 481278, \"tf5df\": 811157}", no_minimization);
  uint64_t w = strings.GetValue("{\"f\": 3, \"df\": 1, \"uqf\": 1, \"tf1df\": 0, \"tf2df\": 0, \"tf3df\": 0, \"tf5df\": 0}", no_minimization);
  BOOST_CHECK(v != w);
}

BOOST_AUTO_TEST_CASE( persistence )
{
  JsonValueStore json_value_store(
      IValueStoreWriter::vs_param_t{{TEMPORARY_PATH_KEY, "/tmp"}});
  bool no_minimization = false;
  std::string value = "{\"";
  value += std::string(60000, 'a');
  value += "\":42}";

  uint32_t v = json_value_store.GetValue(value, no_minimization);
  uint32_t w = json_value_store.GetValue("{\"mytestvalue2\":23}", no_minimization);

  boost::filesystem::path temp_path =
            boost::filesystem::temp_directory_path();

  temp_path /= boost::filesystem::unique_path(
      "dictionary-unit-test-temp-dictionary-%%%%-%%%%-%%%%-%%%%");

  std::string filename = temp_path.native();

  std::ofstream out_stream(filename, std::ios::binary);
  json_value_store.Write(out_stream);
  out_stream.close();

  std::ifstream in_stream(filename, std::ios::binary);
  auto file_mapping = new boost::interprocess::file_mapping(
            filename.c_str(), boost::interprocess::read_only);

  JsonValueStoreReader reader(in_stream, file_mapping, false);

  BOOST_CHECK_EQUAL(value, reader.GetValueAsString(v));
  BOOST_CHECK_EQUAL("{\"mytestvalue2\":23}", reader.GetValueAsString(w));

  std::remove(filename.c_str());
}

BOOST_AUTO_TEST_SUITE_END()

} /* namespace internal */
} /* namespace fsa */
} /* namespace dictionary */
} /* namespace keyvi */

max_stars_repo_name: remusao/keyvi

max_issues_repo_name: remusao/keyvi

max_forks_repo_name: remusao/keyvi


text:
#if !defined(_TCPSERVER_H)
#define _TCPSERVER_H

#include <Server.hpp>

#include <boost/asio.hpp>

#include <cstring>
#include <functional>
#include <exception>
#include <stdexcept>
#include <tuple>
#include <memory>

class NetworkService;
class TransportProtocol;
class TCPConnection;

class TCPServer : public Server {

public:
	TCPServer(int threads, uint16_t server_port, NetworkService* callback_service, TransportProtocol tp);
	~TCPServer();

protected:

	// Wil be set during construction so this will be changed.
	boost::asio::ip::tcp::acceptor tcp_acceptor_ =
		boost::asio::ip::tcp::acceptor(this->boost_io_service_, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0));

	std::vector<std::shared_ptr<TCPConnection>> connections;

	void start_accept();
	void handle_accept(std::shared_ptr<TCPConnection> connection, const boost::system::error_code& error);

	void OnStart();
	void OnStop();

	void register_new_connection(std::shared_ptr<TCPConnection> connection);

private:

};

#endif //_TCPSERVER_H