text:
/*****************************************************************************
 * Copyright [2017] [taurus.ai]
 *
 * 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.
 *****************************************************************************/
/**
 * Tool for td position show and set.
 * @Author cjiang (changhao.jiang@taurus.ai)
 * @since   Oct, 2017
 */

#include "TDUserStruct.h"
#include "Timer.h"
#include "PosHandler.hpp"
#include "longfist/LFConstants.h"
#include "longfist/LFUtils.h"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>

using namespace boost::program_options;
using kungfu::yijinjing::PosHandlerPtr;

WC_NAMESPACE_START

#define TIME_FORMAT "%Y%m%d-%H:%M:%S"

        vector<string> split_text(string line)
{
string buff {""};
vector<string> v;
for (auto n: line)
{
if (n != ',' && n != ' ')
{
buff += n;
}
else if ((n == ',' || n == ' ') && buff != "")
{
v.push_back(buff);
buff = "";
}
}
if (buff.length() > 0)
v.push_back(buff);
return v;
}

void fill_data(PosHandlerPtr pos, vector<string>& data, int indice[])
{
    if (indice[0] >= 0 && indice[1] >= 0)
    {
        pos->set_pos(data[0], LF_CHAR_Net, std::stoi(data[indice[0]]), std::stoi(data[indice[1]]));
    }
    if (indice[2] >= 0 && indice[3] >= 0)
    {
        pos->set_pos(data[0], LF_CHAR_Long, std::stoi(data[indice[2]]), std::stoi(data[indice[3]]));
    }
    if (indice[4] >= 0 && indice[5] >= 0)
    {
        pos->set_pos(data[0], LF_CHAR_Short, std::stoi(data[indice[4]]), std::stoi(data[indice[5]]));
    }
}

bool set_pos_tool(const string& user_name, short source, const string& file_name, bool is_csv)
{
    std::ifstream my_file(file_name);
    if (!my_file.is_open())
    {
        std::cout << "[ERROR] cannot open file: " << file_name << std::endl;
        return false;
    }
    TDUserInfoHelperPtr helper = TDUserInfoHelperPtr(new TDUserInfoHelper(source));
    helper->load(user_name, true);
    json js;

    if (is_csv)
    {
        PosHandlerPtr pos = kungfu::yijinjing::PosHandler::create(source);
        // start to parse csv file
        string line;
        vector<string> data;
        bool started = false;
        int number_idx[] = { -1/*net_tot*/, -1/*net_yd*/,
                             -1/*long_tot*/, -1/*long_yd*/,
                             -1/*short_tot*/, -1/*short_yd*/};
        while (std::getline(my_file, line))
        {
            data = split_text(line);
            if (!started)
            {
                char c = data[1][0];
                if (c <= '9' && c >= '0')
                {
                    // no header line
                    if (data.size() == 7)
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            number_idx[i] = i+1;
                        }
                        fill_data(pos, data, number_idx);
                    }
                    else
                    {
                        std::cout << "column types unrecognized!" << std::endl;
                    }
                }
                else
                {
                    for (int i = 1; i < data.size(); i++)
                    {
                        string column = data[i];
                        if (column.compare("net_tot") == 0)
                            number_idx[0] = i;
                        else if (column.compare("net_yd") == 0)
                            number_idx[1] = i;
                        else if (column.compare("long_tot") == 0)
                            number_idx[2] = i;
                        else if (column.compare("long_yd") == 0)
                            number_idx[3] = i;
                        else if (column.compare("short_tot") == 0)
                            number_idx[4] = i;
                        else if (column.compare("short_yd") == 0)
                            number_idx[5] = i;
                    }
                }
                started = true;
            }
            else
            {
                fill_data(pos, data, number_idx);
            }
        }
        js = pos->to_json();
        std::cout << "set pos from csv file: " << file_name << std::endl;
    }
    else
    {
        std::string contents((std::istreambuf_iterator<char>(my_file)),
                             std::istreambuf_iterator<char>());
        js = json::parse(contents);
        std::cout << "set pos from json file: " << file_name << std::endl;
    }
    js["is_manual"] = true;
    helper->set_pos(user_name, js);
}

bool get_pos_tool(const string& user_name, short source, bool print_raw, bool need_detail, bool print_file, bool is_csv, const string& output_file)
{
    std::cout << "=========== (name)" << user_name << " (source)" << source << " =========" << std::endl;
    TDUserInfoHelperPtr helper = TDUserInfoHelperPtr(new TDUserInfoHelper(source, user_name));
    if (need_detail)
    {
        // print detail if need
        auto info = helper->get_const_user_info(user_name);
        if (info != nullptr)
        {
            std::cout << "status:\t[" << info->status << "]" << std::endl;
            std::cout << "start_time:\t" << info->start_time
                      << " (" << yijinjing::parseNano(info->start_time, TIME_FORMAT) << ")"
                      << std::endl;
            std::cout << "end_time:\t" << info->end_time
                      << " (" << yijinjing::parseNano(info->end_time, TIME_FORMAT) << ")"
                      << std::endl;

            std::cout << "last_order_index:\t" << info->last_order_index << std::endl;
            std::cout << "name:\t" << info->name << std::endl;
            std::cout << "========" << std::endl;
            std::cout << "orders:" << std::endl;
            for (int i = 0; i <= info->last_order_index; i++)
            {
                const TDOrderInfo& order = info->orders[i];
                if (order.status != ORDER_INFO_RAW)
                {
                    std::cout << "\t(order_id)" << order.order_id
                              << " (local_id)" << order.local_id
                              << " (ticker)" << order.ticker
                              << " (status)" << order.status << std::endl;
                }
            }
            std::cout << "========" << std::endl;
        }
    }
    json js = helper->get_pos(user_name);

    if (print_raw || js.find("Source") == js.end() || js.find("Pos") == js.end())
    {
        std::cout << js.dump() << std::endl;
        std::cout << "-------" << std::endl;
    }
    PosHandlerPtr pos = kungfu::yijinjing::PosHandler::create(source, js.dump());
    auto tickers = pos->get_tickers();
    if (js.find("nano") != js.end())
    {
        long nano = js["nano"].get<long>();
        std::cout << "nano:\t" << nano << " (" << yijinjing::parseNano(nano, TIME_FORMAT) << ")" << std::endl;
    }
    else
    {
        std::cout << "nano:\tNone" << std::endl;
    }
    if (js.find("ok") != js.end())
    {
        if (js["ok"].get<bool>())
            std::cout << "ok:\tYes" << std::endl;
        else
            std::cout << "ok:\tNo" << std::endl;
    }
    else
    {
        std::cout << "ok:\tNone" << std::endl;
    }
    std::cout << "-------" << std::endl;
    for (auto ticker: tickers)
    {
        std::cout << ticker;
        std::cout << "\t(net)" << pos->get_net_total(ticker) << "," << pos->get_net_yestd(ticker)
                  << "\t(long)" << pos->get_long_total(ticker) << "," << pos->get_long_yestd(ticker)
                  << "\t(short)" << pos->get_short_total(ticker) << "," << pos->get_short_yestd(ticker)
                  << std::endl;
    }
    std::cout << "-------" << std::endl;

    if (print_file)
    {
        std::ofstream of;
        of.open(output_file, std::ios::out | std::ios::trunc | std::ios::binary);
        if (of.is_open())
        {
            if (is_csv)
            {
                of << "ticker, net_tot, net_yd, long_tot, long_yd, short_tot, short_yd\n";
                for (auto ticker: tickers)
                {
                    of << ticker << ", " << pos->get_net_total(ticker) << ", " << pos->get_net_yestd(ticker)
                       << ", " << pos->get_long_total(ticker) << ", " << pos->get_long_yestd(ticker)
                       << ", " << pos->get_short_total(ticker) << ", " << pos->get_short_yestd(ticker) << std::endl;
                }
                std::cout << "printed to csv file: " << output_file << std::endl;
            }
            else
            {
                of << js.dump() << std::endl;
                std::cout << "printed to json file: " << output_file << std::endl;
            }
        }
        else
        {
            std::cout << "[ERROR] cannot open file: " << output_file << std::endl;
        }
        of.close();
        std::cout << "-------" << std::endl;
    }
}

WC_NAMESPACE_END

void list_user_folder()
{
    if (!boost::filesystem::exists(TD_USER_INFO_FOLDER))
    {
        std::cout << "base folder does not exists! " << TD_USER_INFO_FOLDER << std::endl;
    }
    else
    {
        boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
        vector<string> unrelated_files;
        std::cout << "+-------------------------------+" << std::endl;
        std::cout << "|          TD Pos Files         |" << std::endl;
        std::cout << "+----------------+--------------+" << std::endl;
        std::cout << "| strategy_name  | source       |" << std::endl;
        std::cout << "+----------------+--------------+" << std::endl;
        for ( boost::filesystem::directory_iterator itr( TD_USER_INFO_FOLDER );
              itr != end_itr;
              ++itr )
        {
            if (boost::filesystem::is_regular_file(itr->status()))
            {
                string filename = itr->path().filename().string();
                int idx = filename.find('.');
                if (idx > 0)
                {
                    try
                    {
                        short source;
                        string td_name;
                        source = (short)std::stoi(filename.substr(idx + 1));
                        JournalPair jp = getTdJournalPair(source);
                        if (jp.second.length() > 0)
                        {
                            printf("|%16s|%11s %2d|\n", filename.substr(0, idx).c_str(), jp.second.c_str(), source);
                            std::cout << "+----------------+--------------+" << std::endl;
                        }
                        else
                        {
                            unrelated_files.push_back(filename);
                        }
                    }
                    catch(...)
                    {
                        unrelated_files.push_back(filename);
                    }

                }
            }
        }
        if (unrelated_files.size() > 0)
        {
            std::cout << "Unexpected files in folder " << TD_USER_INFO_FOLDER << ":\n";
            for (auto fn: unrelated_files)
                std::cout << "\t" << fn << std::endl;
        }
    }
}

USING_WC_NAMESPACE
/**
 * main entrance
 */
int main(int argc, const char* argv[])
{
    options_description desc{"Options"};
    desc.add_options()
            ("help,h", "Help screen")
            ("type,t", value<string>(), "type (\"set\"/\"get\")")
            ("source,s", value<int>(), "source index (eg CTP=1)")
            ("name,n", value<string>(), "strategy name")
            ("output,o", "output to file")
            ("raw,r", "print raw data")
            ("detail,d", "print user info details")
            ("list,l", "list all files")
            ("json,j", value<string>(), "json_file")
            ("csv,c", value<string>(), "csv_file format:\nticker, net_tot, net_yd, long_tot, long_yd, short_tot, short_yd");

    variables_map vm;
    store(parse_command_line(argc, argv, desc), vm);
    notify(vm);

    if (vm.count("list"))
    {
        list_user_folder();
        return 0;
    }
    bool need_help = vm.count("help");

    if (need_help)
    {
        std::cout << desc << std::endl;
        return 0;
    }

    short source = -1;
    string type = "";
    string name = "";
    string csv_file = "";
    string json_file = "";

    if (vm.count("source"))
    {
        source = vm["source"].as<int>();
    }
    if (vm.count("type"))
    {
        type = vm["type"].as<string>();
    }
    if (vm.count("name"))
    {
        name = vm["name"].as<string>();
    }
    if (vm.count("csv"))
    {
        csv_file = vm["csv"].as<string>();
    }
    if (vm.count("json"))
    {
        json_file = vm["json"].as<string>();
    }

    // filter out
    if (name.length() == 0)
    {
        std::cout << "no available name" << std::endl;
        need_help = true;
    }
    if (source < 0)
    {
        std::cout << "no available source" << std::endl;
        need_help = true;
    }

    if (type.compare("set") == 0)
    {
        if (csv_file.length() == 0 && json_file.length() == 0)
        {
            std::cout << "no available file" << std::endl;
            need_help = true;
        }
    }
    else if (type.compare("get") == 0)
    {
        if (vm.count("output") > 0 && csv_file.length() == 0 && json_file.length() == 0)
        {
            std::cout << "no available file" << std::endl;
            need_help = true;
        }
    }
    else
    {
        std::cout << "no allowed type (set/get) is determined. (" << type << ")" << std::endl;
        need_help = true;
    }

    // do something
    if (need_help)
    {
        std::cout << desc << std::endl;
    }
    else
    {
        if (type.compare("set") == 0)
        {
            if (vm.count("csv") > 0)
            {
                set_pos_tool(name, source, csv_file, true);
            }
            if (vm.count("json") > 0)
            {
                set_pos_tool(name, source, json_file, false);
            }
        }
        else
        {
            if (vm.count("output") > 0)
            {
                if (vm.count("csv") > 0)
                {
                    get_pos_tool(name, source, vm.count("raw") > 0, vm.count("detail") > 0, true, true, csv_file);
                }
                if (vm.count("json") > 0)
                {
                    get_pos_tool(name, source, vm.count("raw") > 0, vm.count("detail") > 0, true, false, json_file);
                }

            }
            // get mode
            get_pos_tool(name, source, vm.count("raw") > 0, vm.count("detail") > 0, false, false, "");
        }
    }
}

max_stars_repo_name: litaotao/kungfu

max_issues_repo_name: litaotao/kungfu

max_forks_repo_name: litaotao/kungfu


text:
#include "graphalgos.hpp"

#include "../manager/errors.hpp"   // for InconsistentDataError
#include "../util/fault_codes.hpp" // for FAULT_CRITICAL_PATH_INFEASIBLE
#include "datastructures/fast_reset_vector.hpp"
#include "instance/instance.hpp" // for Instance
#include "instance/job.hpp"      // for Job
#include "instance/laggraph.hpp" // for LagGraph, LagGraph::(anonymous)

#include <algorithm>           // for move, max, reverse
#include <assert.h>            // for assert
#include <bits/std_function.h> // for function
#include <boost/range/adaptor/reversed.hpp>
#include <ext/alloc_traits.h> // for __alloc_traits<>::value_type
#include <functional>         // for function
#include <numeric>
#include <string> // for string
#include <unordered_set>

NecessaryOrderComputer::NecessaryOrderComputer(const Instance & instance_in)
    : predecessor_count(instance_in.job_count(), 0),
      successor_count(instance_in.job_count(), 0), instance(instance_in)
{
	CriticalPathComputer cp(this->instance);
	this->earliest_starts = cp.get_forward();
	this->latest_finishs = cp.get_reverse();
	this->compute();
}

void
NecessaryOrderComputer::compute()
{
	std::vector<unsigned int> by_es(this->instance.job_count());
	std::vector<unsigned int> by_lf(this->instance.job_count());

	std::iota(by_es.begin(), by_es.end(), 0);
	std::iota(by_lf.begin(), by_lf.end(), 0);

	std::sort(by_es.begin(), by_es.end(),
	          [&](unsigned int lhs, unsigned int rhs) {
		          return this->earliest_starts[lhs] < this->earliest_starts[rhs];
	          });
	std::sort(by_lf.begin(), by_lf.end(),
	          [&](unsigned int lhs, unsigned int rhs) {
		          return this->latest_finishs[lhs] < this->latest_finishs[rhs];
	          });

	size_t finished = 0;
	for (const auto & v : by_es) {
		while (this->latest_finishs[by_lf[finished]] <= this->earliest_starts[v]) {
			finished++;
		}
		this->predecessor_count[v] = finished;
	}

	size_t started = 0;
	auto start_it = by_es.rbegin();
	for (auto it = by_lf.rbegin(); it != by_lf.rend(); it++) {
		while (this->earliest_starts[*start_it] >= this->latest_finishs[*it]) {
			started++;
			start_it++;
		}

		this->successor_count[*it] = started;
	}
}

const std::vector<size_t> &
NecessaryOrderComputer::get_successor_count() const noexcept
{
	return this->successor_count;
}

const std::vector<size_t> &
NecessaryOrderComputer::get_predecessor_count() const noexcept
{
	return this->predecessor_count;
}

TopologicalSort::TopologicalSort(const LagGraph & graph_in) : graph(graph_in) {}

std::vector<LagGraph::vertex>
TopologicalSort::get()
{
	using vertex = LagGraph::vertex;

	std::vector<unsigned int> indices(this->graph.vertex_count(), 0);

	unsigned int index = (unsigned int)(this->graph.vertex_count() - 1);

	std::function<bool(vertex, vertex)> visit = [&](vertex v, vertex from) {
		(void)from;
		(void)v;
		return true;
	};
	std::function<void(vertex, vertex, int)> traverse = [&](vertex from,
	                                                        vertex to, int lag) {
		(void)from;
		(void)to;
		(void)lag;
	};
	std::function<void(vertex)> backtrack = [&](unsigned int v) {
		if (indices[v] <= index) {
			indices[v] = index;
			index--;
		}
	};

#ifdef ASSERTIONS
	bool finished = false;
#endif

	std::vector<bool> visited;

	for (vertex v = 0; v < this->graph.vertex_count(); ++v) {
		if (this->graph.reverse_neighbor_count(v) > 0) {
			continue; // Only select vertices without incoming edges as roots
		}
		assert(indices[v] == 0);
		DFS<decltype(visit), decltype(backtrack), decltype(traverse)>(
		    this->graph, v, visit, backtrack, traverse);

#ifdef ASSERTIONS
		if (index == ((unsigned int)0 - 1)) {
			finished = true;
		}
#endif
	}

#ifdef ASSERTIONS
	assert(finished);
#endif

	std::vector<vertex> ordered(this->graph.vertex_count());
	for (vertex v = 0; v < this->graph.vertex_count(); ++v) {
		ordered[indices[v]] = v;
	}

	return ordered;
}

CriticalPathComputer::CriticalPathComputer(const Instance & instance_in)
    : l("CritPath"), instance(instance_in)
{}

std::vector<unsigned int>
CriticalPathComputer::get_forward()
{
	using vertex = LagGraph::vertex;
	const LagGraph & graph = this->instance.get_laggraph();

	std::vector<vertex> topological_order = TopologicalSort(graph).get();
	std::vector<unsigned int> earliest_start(graph.vertex_count());

	for (auto v : topological_order) {
		earliest_start[v] = this->instance.get_job(v).get_release();
	}

	for (auto v : topological_order) {
		const auto ec = graph.neighbors(v);
		for (auto edge = ec.cbegin(); edge != ec.cend(); ++edge) {
			unsigned int new_start;
			if (edge->lag < -1 * (int)earliest_start[v]) {
				new_start = 0;
			} else {
				new_start = (unsigned int)((int)earliest_start[v] + edge->lag);
			}

			earliest_start[edge->t] = std::max(earliest_start[edge->t], new_start);
		}
	}

	return earliest_start;
}

std::vector<unsigned int>
CriticalPathComputer::get_reverse()
{
	using vertex = LagGraph::vertex;
	const LagGraph & graph = this->instance.get_laggraph();

	std::vector<vertex> topological_order = TopologicalSort(graph).get();
	std::reverse(topological_order.begin(), topological_order.end());

	std::vector<unsigned int> latest_finish(graph.vertex_count());

	for (auto v : topological_order) {
		latest_finish[v] = this->instance.get_job(v).get_deadline();
	}

	for (auto v : topological_order) {
		for (auto edge : graph.reverse_neighbors(v)) {
			assert(edge.s == v);
			auto t = edge.t;
			const Job & t_job = this->instance.get_job(t);
			const Job & s_job = this->instance.get_job(v);

			int new_finish = (int)latest_finish[v] - (int)s_job.get_duration() +
			                 (int)t_job.get_duration() - (int)edge.lag;

			if (new_finish < 0) {
				BOOST_LOG(l.e()) << "Negative latest finish time detected.";
				BOOST_LOG(l.d()) << "LF-Times computed so far:";
				for (auto w : topological_order) {
					BOOST_LOG(l.d()) << "-> " << w << ": " << latest_finish[w];
					if (w == v) {
						BOOST_LOG(l.d()) << "--> Results in " << new_finish << " for " << t;
						break;
					}
				}

				throw InconsistentDataError(this->instance, -1,
				                            FAULT_CRITICAL_PATH_INFEASIBLE,
				                            "Negative latest finish time");
			}

			if ((unsigned int)new_finish < latest_finish[t]) {
				latest_finish[t] = (unsigned int)new_finish;
			}
		}
	}

	return latest_finish;
}

APLPComputer::APLPComputer(const Instance & instance_in) : instance(instance_in)
{}

std::vector<std::vector<int>>
APLPComputer::get()
{
	this->result.clear();
	this->result.resize(this->instance.job_count(),
	                    std::vector<int>(this->instance.job_count(), -1));

	this->topological_order =
	    TopologicalSort(this->instance.get_laggraph()).get();

	for (unsigned int jid = 0; jid < this->instance.job_count(); ++jid) {
		this->compute_SSLP(jid);
	}

	// TODO this is unsafe! But fast…
	return std::move(this->result);
}

// TODO this can be sped up.
// TODO make this fail if there are negative edges / cycles
void
APLPComputer::compute_SSLP(unsigned int start_job)
{
	const LagGraph & graph = this->instance.get_laggraph();

	this->result[start_job][start_job] = 0;

	auto it = this->topological_order.begin();

	// skip forward to job A
	while (*it != start_job) {
		it++;
	}

	// relax edges
	while (it != topological_order.end()) {
		const unsigned int v = *it;
		it++;

		if (this->result[start_job][v] == -1) { // no path here
			continue;
		}

		for (const auto & edge : graph.neighbors(v)) {
			int relaxed_dist = this->result[start_job][v] + edge.lag;
			assert(relaxed_dist >= 0); // negative paths break things for now

			this->result[start_job][edge.t] =
			    std::max(this->result[start_job][edge.t], relaxed_dist);
		}
	}
}

ext: cpp

max_stars_repo_name: kit-algo/TCPSPSuite

max_issues_repo_name: kit-algo/TCPSPSuite

max_forks_repo_name: kit-algo/TCPSPSuite


text:
#include "cucumber-cpp/internal/CukeCommands.hpp"

#include <sstream>
#include <boost/algorithm/string.hpp>

namespace cucumber {
namespace internal {

shared_ptr<Scenario> CukeCommands::currentScenario;

CukeCommands::CukeCommands() : hasStarted(false) {
}

CukeCommands::~CukeCommands() {
    if (hasStarted) {
        hookRegistrar.execAfterAllHooks();
    }
}

void CukeCommands::beginScenario(const TagExpression::tag_list *tags) {
    if (!hasStarted) {
        hasStarted = true;
        hookRegistrar.execBeforeAllHooks();
    }

    currentScenario = shared_ptr<Scenario>(new Scenario(tags));
    hookRegistrar.execBeforeHooks(currentScenario.get());
}

void CukeCommands::endScenario() {
    hookRegistrar.execAfterHooks(currentScenario.get());
    contextManager.purgeContexts();
    currentScenario.reset();
}

const std::string CukeCommands::snippetText(const std::string stepKeyword, const std::string stepName) const {
    std::stringstream snippetText; // TODO Escape stepName
    snippetText << boost::to_upper_copy(stepKeyword) << "(\"^" << stepName << "$\") {" << std::endl;
    snippetText << "    pending();" << std::endl;
    snippetText << "}" << std::endl;
    return snippetText.str();
}

MatchResult CukeCommands::stepMatches(const std::string description) const {
    return stepManager.stepMatches(description);
}

InvokeResult CukeCommands::invoke(step_id_type id, const InvokeArgs *pArgs) {
    StepInfo *stepInfo = stepManager.getStep(id);
    InvokeResult result = hookRegistrar.execStepChain(currentScenario.get(), stepInfo, pArgs);
    hookRegistrar.execAfterStepHooks(currentScenario.get());
    return result;
}

}
}

max_stars_repo_name: AndreasAugustin/Gherkin-Demos-cpp

max_issues_repo_name: AndreasAugustin/Gherkin-Demos-cpp

max_forks_repo_name: AndreasAugustin/Gherkin-Demos-cpp


text:
// Copyright 2017 Peter Dimov.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt

#include <boost/mp11/set.hpp>
#include <boost/mp11/list.hpp>
#include <boost/mp11/utility.hpp>
#include <boost/core/lightweight_test_trait.hpp>
#include <type_traits>
#include <tuple>
#include <utility>

int main()
{
    using boost::mp11::mp_list;
    using boost::mp11::mp_is_set;
    using boost::mp11::mp_true;
    using boost::mp11::mp_false;

    {
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<void>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<int>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<char[]>, mp_false>));
    }

    {
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, void, void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, void, void, void>>, mp_false>));

        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, int>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, int, void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, int, int>>, mp_false>));

        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, int, char[]>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, int, char[], void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, int, char[], int>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<mp_list<void, int, char[], char[]>>, mp_false>));
    }

    {
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, void, void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, void, void, void>>, mp_false>));

        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, int>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, int, void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, int, int>>, mp_false>));

        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, int, char[]>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, int, char[], void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, int, char[], int>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::tuple<void, int, char[], char[]>>, mp_false>));
    }

    {
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::pair<void, void>>, mp_false>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::pair<void, int>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::pair<int, void>>, mp_true>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_is_set<std::pair<int, int>>, mp_false>));
    }

    return boost::report_errors();
}


text:
#define BOOST_TEST_MODULE math_test_module
#include <boost/test/unit_test.hpp>
#include <vector>
#include <iostream>

#include "math_lib.h"

using namespace std;
namespace tt = boost::test_tools;
namespace utf = boost::unit_test;

/*
template <typename T>
std::ostream& operator<<(std::ostream& out, std::vector<T> vec) {
    for (const auto& v : vec) {
        out << v << " ";
    }
    return out;
}
*/

BOOST_AUTO_TEST_SUITE(math_lib_test_suite)

    BOOST_AUTO_TEST_CASE(test_factorial) {
        // integer
        BOOST_TEST(factorial(0) == 1);
        BOOST_TEST(factorial(1) == 1);
        BOOST_TEST(factorial(2) == 2);
        BOOST_TEST(factorial(3) == 6);
        BOOST_TEST(factorial(10) == 3628800);
        BOOST_TEST(factorial(-1) == 1);
        // double
        BOOST_TEST(factorial(0.5) == 1);
        BOOST_TEST(factorial(1.5) == 1.5);
        BOOST_TEST(factorial(2.5) == 3.75);
    }

    BOOST_AUTO_TEST_CASE(test_round_to, * utf::tolerance(0.000001)) {
        BOOST_TEST(roundTo(125, 1) == 130);
        BOOST_TEST(roundTo(125, 2) == 100);
        BOOST_TEST(roundTo(125.456, 1) == 130);
        BOOST_TEST(roundTo(125.456, 0) == 125);
        BOOST_TEST(roundTo(125.456, -1) == 125.5);
        // less one
        BOOST_TEST(roundTo(0.416, 1) == 0);
        BOOST_TEST(roundTo(0.416, 0) == 0);
        BOOST_TEST(roundTo(0.416, -1) == 0.4);
    }

    BOOST_AUTO_TEST_CASE(test_odd) {
        BOOST_TEST(!odd(2));
        BOOST_TEST(odd(1));
        BOOST_TEST(odd(3));
        BOOST_TEST(!odd(0));
        BOOST_TEST(odd(-1));
    }

    BOOST_AUTO_TEST_CASE(test_average_1) {
        // contract: double average(double x, double y);
        BOOST_TEST(average(2, 4) == 3);
        BOOST_TEST(average(2, 5) == 3.5);
        BOOST_TEST(average(0, 1) == 0.5);
        BOOST_TEST(average(-1, 1) == 0);
        BOOST_TEST(average(2.5, 0.5) == 1.5);
    }

    BOOST_AUTO_TEST_CASE(test_average_2) {
        // contract: double average(const std::vector<double>& vals);
        BOOST_TEST(average({2, 4}) == 3);
        BOOST_TEST(average({2, 5}) == 3.5);
        BOOST_TEST(average({0, 1}) == 0.5);
        BOOST_TEST(average({-1, 1}) == 0);
        BOOST_TEST(average({2.5, 0.5}) == 1.5);
        BOOST_TEST(average({-2, 2, 3}) == 1);
    }

    BOOST_AUTO_TEST_CASE(test_average_3, * utf::tolerance(0.000001)) {
        // contract: void average(const std::vector<double>& vals, double &mean, double &err);
        {const vector<double> input {4, 5, 7, 2};
            double mean, err;
            average(input, mean, err);
            BOOST_TEST(mean == 4.5);
            BOOST_TEST(err == 1.04083299973307);
        }
        {const vector<double> input {2, 5};
            double mean, err;
            average(input, mean, err);
            BOOST_TEST(mean == 3.5);
            BOOST_TEST(err == 1.5);
        }
    }

    BOOST_AUTO_TEST_CASE(test_sqr_add, * utf::tolerance(0.000001)) {
        // contract: double sqrAdd(const std::vector<double>& vals);
        BOOST_TEST(sqrAdd({3, 4}) == 5);
        BOOST_TEST(sqrAdd({3, 4, 5}) == sqrt(50));
        BOOST_TEST(sqrAdd({7.1, 3.2, 78.5, 0.56}) == 78.8873475279781);
    }

    BOOST_AUTO_TEST_CASE(test_poly) {
        // f(x) = 2*x^2 + x + 3.5; f(0)
        const vector<double> coeffs = {3.5, 1, 2};
        BOOST_TEST(poly(0, coeffs) == 3.5);
        BOOST_TEST(poly(1, coeffs) == 6.5);
        BOOST_TEST(poly(-1, coeffs) == 4.5);
    }

    BOOST_AUTO_TEST_CASE(test_calculate_pdf) {
        // weights: 1, 1, 1, 1 => pdf: 0.25, 0.5, 0.75, 1 and sum = 4
        {
            vector<double> weights = {1, 1, 1, 1};
            auto sum = calculate_pdf(weights);
            BOOST_TEST(sum == 4);
            const vector<double> res = {0.25, 0.5, 0.75, 1};
            BOOST_TEST(weights == res);
        }
        {
            vector<double> weights = {1};
            auto sum = calculate_pdf(weights);
            BOOST_TEST(sum == 1);
            const vector<double> res = {1};
            BOOST_TEST(weights == res);
        }
        {
            vector<double> weights = {0.5, 2, 1};
            auto sum = calculate_pdf(weights);
            BOOST_TEST(sum == 3.5);
            const vector<double> res = {5./35, 25./35, 1};
            BOOST_TEST(weights == res);
        }
        // test with predicate: e.g. cont with struct a.weight:
        {
            struct Tmp {double weight = 0;};
            vector<Tmp> weights = {Tmp{0.5}, Tmp{2}, Tmp{1}};
            vector<double> res;
            auto sum = calculate_pdf(weights, [](const Tmp& t){ return t.weight;}, res);
            BOOST_TEST(sum == 3.5);
            const vector<double> expected = {5./35, 25./35, 1};
            BOOST_TEST(res == expected);
        }
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: gwlsrm/Units

max_issues_repo_name: gwlsrm/Units

max_forks_repo_name: gwlsrm/Units


text:
// ---------------------------------------------------------------------------|
// Test Harness includes
// ---------------------------------------------------------------------------|
#include "test/support/callbacks/callback-checker.h"

// ---------------------------------------------------------------------------|
// Boost includes
// ---------------------------------------------------------------------------|
#include <boost/foreach.hpp>

// ---------------------------------------------------------------------------|
// Boost Test Framework
// ---------------------------------------------------------------------------|
#include <boost/test/unit_test.hpp>

// ---------------------------------------------------------------------------|
// File wide namespace use
// ---------------------------------------------------------------------------|
using namespace std;
using namespace rel_ops;

// ---------------------------------------------------------------------------|
namespace YumaTest
{

// ---------------------------------------------------------------------------|
void CallbackChecker::addExpectedCallback(const string& modName,
                                          const string& containerName,
                                          const vector<string>& elementHierarchy,
                                          const string& operation,
                                          const string& type,
                                          const string& phase)
{
    string name = modName + "_" + containerName + "_";
    BOOST_FOREACH (const string& val, elementHierarchy)
    {
        name += val + "_";
    }
    name += operation;

    SILCallbackLog::CallbackInfo cbInfo(name, type, phase);

    expectedCallbacks_.push_back(cbInfo);
}

// ---------------------------------------------------------------------------|
void CallbackChecker::checkCallbacks(const std::string& modName)
{
    bool callbackError = false;
    SILCallbackLog& cbLog = SILCallbackLog::getInstance();
    SILCallbackLog::ModuleCallbackData actualCallbacks = cbLog.getModuleCallbacks(modName);

    SILCallbackLog::ModuleCallbackData::iterator it_act, it_exp;
    for(it_act = actualCallbacks.begin(), it_exp = expectedCallbacks_.begin();
        it_act != actualCallbacks.end() && it_exp !=  expectedCallbacks_.end();
        ++it_act, ++it_exp)
    {
        BOOST_CHECK(*it_act == *it_exp);
        if (*it_act != *it_exp)
        {
            callbackError = true;
        }
    }

    BOOST_CHECK_MESSAGE(actualCallbacks.size() <= expectedCallbacks_.size(),
                        "Unexpected callbacks were logged");
    BOOST_CHECK_MESSAGE(actualCallbacks.size() >= expectedCallbacks_.size(),
                        "Further callbacks were expected");
    if (actualCallbacks.size() != expectedCallbacks_.size())
    {
        callbackError = true;
    }

    // Debug output to help understand failures
    if (callbackError)
    {
        cout << "\nActual Callbacks:\n";
        for(it_act = actualCallbacks.begin(); it_act != actualCallbacks.end(); ++it_act)
        {
            cout << it_act->cbName << ", " << it_act->cbType << ", " << it_act->cbPhase << "\n";
        }
        cout << "\nExpected Callbacks:\n";
        for(it_exp = expectedCallbacks_.begin(); it_exp != expectedCallbacks_.end(); ++it_exp)
        {
            cout << it_exp->cbName << ", " << it_exp->cbType << ", " << it_exp->cbPhase << "\n";
        }
    }
}

// ---------------------------------------------------------------------------|
void CallbackChecker::resetExpectedCallbacks()
{
    expectedCallbacks_.clear();
}

// ---------------------------------------------------------------------------|
void  CallbackChecker::resetModuleCallbacks(const std::string& modName)
{
    SILCallbackLog& cbLog = SILCallbackLog::getInstance();
    cbLog.resetModuleCallbacks(modName);
}

} // namespace YumaTest


text:
//
// Copyright (c) 2015-2019 CNRS INRIA
//

#ifndef __pinocchio_multibody_visitior_fusion_hpp__
#define __pinocchio_multibody_visitior_fusion_hpp__

#define BOOST_FUSION_INVOKE_MAX_ARITY 10

#include "pinocchio/deprecated.hpp"

#include <boost/variant/static_visitor.hpp>
#include <boost/fusion/include/invoke.hpp>
#include <boost/fusion/container/generation/make_vector.hpp>

namespace boost
{
  namespace fusion
  {

    /// \brief  Append the element T at the front of boost fusion vector V.
    template<typename T,typename V>
    typename result_of::push_front<V const, T>::type
    append(T const& t,V const& v)
    {
      return push_front(v,t);
    }

    /// \brief Append the elements T1 and T2 at the front of boost fusion vector V.
    template<typename T1,typename T2,typename V>
    typename result_of::push_front<typename result_of::push_front<V const, T2>::type const, T1>::type
    append(T1 const& t1,T2 const& t2,V const& v)
    {
      return push_front(push_front(v,t2),t1);
    }

    /// \brief Append the elements T1 and T2 at the front of boost fusion vector V.
    /// \note This function is now deprecated. Please use the new name append.
    template<typename T1,typename T2,typename V>
    PINOCCHIO_DEPRECATED
    typename result_of::push_front<typename result_of::push_front<V const, T2>::type const, T1>::type
    append2(T1 const& t1,T2 const& t2,V const& v)
    {
      return append2(t1,t2,v);
    }

    /// \brief Append the elements T1, T2 and T3 at the front of boost fusion vector V.
    template<typename T1,typename T2, typename T3, typename V>
    typename result_of::push_front<
    typename result_of::push_front<
    typename result_of::push_front<V const,T3>::type const,T2>::type const,T1>::type
    append(T1 const& t1, T2 const& t2, T3 const& t3, V const& v)
    {
      return push_front(push_front(push_front(v,t3),t2),t1);
    }

    /// \brief Append the elements T1, T2, T3 and T4 at the front of boost fusion vector V.
    template<typename T1,typename T2, typename T3, typename T4, typename V>
    typename result_of::push_front<
    typename result_of::push_front<
    typename result_of::push_front<
    typename result_of::push_front<V const,T4>::type const,T3>::type const,T2>::type const,T1>::type
    append(T1 const& t1, T2 const& t2, T3 const& t3, T4 const& t4, V const& v)
    {
      return push_front(push_front(push_front(push_front(v,t4),t3),t2),t1);
    }

    /// \brief Append the elements T1, T2, T3, T4 and T5 at the front of boost fusion vector V.
    template<typename T1,typename T2, typename T3, typename T4, typename T5, typename V>
    typename result_of::push_front<
    typename result_of::push_front<
    typename result_of::push_front<
    typename result_of::push_front<
    typename result_of::push_front<V const,T5>::type const,T4>::type const,T3>::type const,T2>::type const,T1>::type
    append(T1 const& t1, T2 const& t2, T3 const& t3, T4 const& t4, T5 const& t5, V const& v)
    {
      return push_front(push_front(push_front(push_front(push_front(v,t5),t4),t3),t2),t1);
    }

  }
}

#endif // ifndef __pinocchio_multibody_visitior_fusion_hpp__

ext: hpp


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_LINALG_FUNCTIONS_GALLERY_ORTHOG_HPP_INCLUDED
#define NT2_LINALG_FUNCTIONS_GALLERY_ORTHOG_HPP_INCLUDED
#include <nt2/linalg/functions/orthog.hpp>
#include <nt2/include/functions/whereij.hpp>
#include <nt2/include/functions/sin.hpp>
#include <nt2/include/functions/cos.hpp>
#include <nt2/include/functions/sinpi.hpp>
#include <nt2/include/functions/cospi.hpp>
#include <nt2/include/functions/ric.hpp>
#include <nt2/include/functions/cic.hpp>
#include <nt2/include/functions/cif.hpp>
#include <nt2/include/functions/rif.hpp>
#include <nt2/include/functions/tril.hpp>
#include <nt2/include/functions/from_diag.hpp>
#include <nt2/include/functions/ones.hpp>
#include <nt2/include/functions/eye.hpp>
#include <nt2/include/functions/rec.hpp>
#include <nt2/include/functions/max.hpp>
#include <nt2/include/functions/sqrt.hpp>
#include <nt2/include/constants/two.hpp>
#include <nt2/include/constants/pi.hpp>
#include <nt2/include/constants/half.hpp>
#include <nt2/include/constants/twopi.hpp>
#include <nt2/include/functions/multiplies.hpp>
#include <nt2/include/functions/mul_i.hpp>
#include <nt2/include/functions/exp.hpp>
#include <nt2/include/functions/divides.hpp>
#include <nt2/include/functions/is_eqz.hpp>
#include <nt2/include/functions/is_nez.hpp>
#include <nt2/include/functions/oneminus.hpp>
#include <nt2/include/functions/sqrt.hpp>
#include <nt2/include/functions/horzcat.hpp>
#include <nt2/include/functions/mtimes.hpp>
#include <nt2/include/functions/logical_and.hpp>
#include <boost/mpl/int.hpp>
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>

namespace nt2
{
  namespace details
  {
    struct isij0
    {
      template < class I, class J> inline
      typename meta::as_logical<I>::type operator()(const I & i , const J& j) const
      {
        return nt2::is_eqz(i*j);
      }
    };
    struct isi0
    {
      template < class I, class J> inline
      typename meta::as_logical<I>::type operator()(const I & i , const J& ) const
      {
        return nt2::is_eqz(i);
      }
    };
    struct isdiagpos
    {
      template < class I, class J> inline
      typename meta::as_logical<I>::type operator()(const I & i , const J& j ) const
      {
        return nt2::logical_and(nt2::is_nez(i), nt2::eq(i, j));
      }
    };
    template < class A0, class K, class T > struct orthog_return{};
  }
#define NT2_ORTHOG(V, K, Body)                                      \
  namespace ext                                                     \
  {                                                                 \
    NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::orthog##K##_, tag::cpu_,  \
                                (A0)(T),                            \
                                (scalar_<integer_<A0> >)            \
                                (target_<scalar_<floating_<T> > > ) \
                              )                                     \
    {                                                               \
      typedef typename T::type t_t;                                 \
      BOOST_DISPATCH_RETURNS(2, (A0 const& n,  T const& t),         \
                             Body                                   \
                            )                                       \
        };                                                          \
  }                                                                 \
  namespace details                                                 \
  {                                                                 \
    template < class A0, class T >                                  \
    struct orthog_return < A0,  boost::mpl::int_<V>, T>             \
      {                                                             \
        typedef typename nt2::meta::as_<T> Target;                  \
        typedef typename nt2::meta::call<nt2::tag::orthog##K##_(A0, \
                                               Target)>::type type; \
      };                                                            \
   }                                                                \
  template<class T>                                                 \
  typename details::orthog_return<ptrdiff_t,                        \
                                  boost::mpl::int_<V>, T>::type     \
                    orthog(ptrdiff_t n, const boost::mpl::int_<V>&) \
  {                                                                 \
    return nt2::orthog##K(n, meta::as_<T>());                       \
  }                                                                 \
/**/

  NT2_ORTHOG(1, 1, (nt2::sinpi(nt2::rif(n,T())*nt2::cif(n,T())/t_t(n+1))*nt2::sqrt(Two<t_t>()/t_t(n+1))))
  NT2_ORTHOG(2, 2, (nt2::sinpi(nt2::rif(n,T())*nt2::cif(n,T())*nt2::Two<t_t>()/t_t(2*n+1))*(Two<t_t>()/nt2::sqrt(t_t(2*n+1)))))
  NT2_ORTHOG(3, 3, (nt2::exp(nt2::mul_i(nt2::ric(n,T())*nt2::cic(n,T())*nt2::Twopi<t_t>()/t_t(n)))/nt2::sqrt(t_t(n))))
  NT2_ORTHOG(4, 4, (nt2::mtimes(nt2::from_diag(nt2::rec(nt2::sqrt(nt2::cath(t_t(n), _(t_t(1), t_t(n-1)))*_(t_t(1), t_t(n))))),
                                nt2::whereij(details::isdiagpos(),
                                             nt2::from_diag(nt2::oneminus(nt2::_(t_t(1), t_t(n)))),
                                             nt2::whereij(details::isi0(),
                                                          nt2::ones(n, T()),
                                                          nt2::tril(nt2::ones(n, T()))
                                                         )
                                            )
                               )
                   )
            )
  NT2_ORTHOG(5, 5,((nt2::cospi(nt2::ric(n,T())*nt2::cic(n,T())*nt2::Two<t_t>()/t_t(n))+
                    nt2::sinpi(nt2::ric(n,T())*nt2::cic(n,T())*nt2::Two<t_t>()/t_t(n)))/nt2::sqrt(t_t(n))))
  NT2_ORTHOG(6, 6, (nt2::cospi((nt2::rif(n, T())-Half<t_t>())*(nt2::cif(n, T())-Half<t_t>())/t_t(n))*nt2::sqrt(nt2::Two<t_t>()/t_t(n))))
  NT2_ORTHOG(7, 7, (nt2::whereij(details::isij0(), nt2::ones(n,T())/nt2::sqrt(t_t(n)),nt2::eye(n,T())-ones(n,T())*(1+rec(sqrt(t_t(n))))/t_t(n-1))))
  NT2_ORTHOG(-1, m1, (nt2::cospi(nt2::ric(n,T())*nt2::cic(n,T())*nt2::rec(nt2::max(t_t(1), t_t(n-1))))))
  NT2_ORTHOG(-2, m2, (nt2::cospi(nt2::ric(n,T())*(nt2::cic(n,T())+nt2::Half<t_t>())*nt2::rec(t_t(n)))))

#undef ORTHOG

  template<int K, class T>
  typename details::orthog_return<ptrdiff_t,  boost::mpl::int_<K>, T>::type
  orthog(ptrdiff_t n)
  {
    return nt2::orthog<T>(n, boost::mpl::int_<K>());
  }

}

#endif


text:
/*
 * Bayes++ the Bayesian Filtering Library
 * Copyright (c) 2002 Michael Stevens
 * See accompanying Bayes++.htm for terms and conditions of use.
 *
 * $Id$
 */

/*
 * Example of using Bayesian Filter Class to solve a simple problem.
 *
 * The example implements a simple quadratic observer.
 *  This tries to estimate the state of system while also trying to
 *  calibrate a simple linear model of the system which includes
 *  a scale factor and a bias.
 *  Estimating both the system state and a scale factor results in a
 *  quadratic (product of two states and therefore non-linear) observation.
 *  The system model is a 1D brownian motion with a known perturbation.
 */

#include "BayesFilter/infFlt.hpp"
#include "Test/random.hpp"
#include <cmath>
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
#include <boost/random.hpp>

namespace
{
	namespace FM = Bayesian_filter_matrix;
	using namespace FM;

	// Choose Filtering Scheme to use
	typedef Bayesian_filter::Information_scheme FilterScheme;

	// Square
	template <class scalar>
	inline scalar sqr(scalar x)
	{
		return x*x;
	}

	// Random numbers from Boost
	Bayesian_filter_test::Boost_random localRng;

	// Constant Dimensions
	const unsigned NX = 3;			// Filter State dimension 	(SystemState, Scale, Bias)

	// Filter Parameters
	// Noise on observing system state
	const Float OBS_NOISE = 0.01;
	// Prediction Noise: no Prediction noise as pertubation is known
	const Float X_NOISE = 0.0;	// System State
	const Float S_NOISE = 0.0;	// Scale
	const Float B_NOISE = 0.0;	// Bias
	// Filter's Initial state uncertainty: System state is unknown
	const Float i_X_NOISE = 1000.;
	const Float i_S_NOISE = 0.1;
	const Float i_B_NOISE = 0.1;

}//namespace

/*
 * Prediction model
 * Linear state predict model with additive control input
 */
class QCpredict : public Bayesian_filter::Linrz_predict_model
{
	Float motion;
	mutable FM::Vec fx;
public:
	QCpredict();
		;
	void predict(const FM::Vec& u)
	{
		motion = u[0];
	}
	const FM::Vec& f(const FM::Vec& x) const
	{
		// Constant scale and bias, system state perturbed by control input
		fx = x;
		fx[0] += motion;
		return fx;
	};
};

QCpredict::QCpredict() : Bayesian_filter::Linrz_predict_model(NX, NX), fx(NX)
{
	FM::identity (Fx);

	// Setup constant noise model: G is identity
	q[0] = sqr(X_NOISE);
	q[1] = sqr(S_NOISE);
	q[2] = sqr(B_NOISE);
	FM::identity (G);
}

/*
 * Quadratic observation model
 */
class QCobserve : public Bayesian_filter::Linrz_uncorrelated_observe_model
{
	mutable FM::Vec z_pred;
public:
	QCobserve ();
	const FM::Vec& h(const FM::Vec& x) const
	{	// Quadratic Observation model
		z_pred[0] = x[0] * x[1] + x[2];
		return z_pred;
	};
	void state (const FM::Vec& x)
	// Linearised model, Jacobian of h at x
	{
		Hx(0,0) = x[1];
		Hx(0,1) = x[0];
		Hx(0,2) = 1.;
	}
};

QCobserve::QCobserve () :
	Bayesian_filter::Linrz_uncorrelated_observe_model(NX,1), z_pred(1)
{
	// Observation Noise variance
	Zv[0] = OBS_NOISE*OBS_NOISE;
}

int main()
{
	// Global setup for test output
	std::cout.flags(std::ios::scientific); std::cout.precision(6);

	// Setup the test filters
	FM::Vec x_true (NX);

	// True State to be observed
	x_true[0] = 10.;	// System State
	x_true[1] = 1.0;	// Scale
	x_true[2] = 0.0;	// Bias

	std::cout << "Quadratic Calibration" << std::endl;
	std::cout << "Init " << x_true << std::endl;

	// Construct Prediction and Observation model and Calibration filter
	QCpredict linearPredict;
	QCobserve nonlinObserve;
	FilterScheme obsAndCalib (NX);

	// Give the filter an true initial guess of the system state
	obsAndCalib.x[0] = x_true[0];
	obsAndCalib.x[1] = 1.;		// Assumed initial Scale
	obsAndCalib.x[2] = 0.;		// Assumed initial Bias
	obsAndCalib.X.clear();
	obsAndCalib.X(0,0) = sqr(i_X_NOISE);
	obsAndCalib.X(1,1) = sqr(i_S_NOISE);
	obsAndCalib.X(2,2) = sqr(i_B_NOISE);

	obsAndCalib.init ();

	// Iterate the filter with test observations
	FM::Vec u(1), z_true(1), z(1);
	for (unsigned i = 0; i < 100; i++ )
	{
		// Predict true state using Brownian control input
		localRng.normal (u);				// normally distributed
		x_true[0] += u[0];
		linearPredict.predict (u);

		// Predict filter with known perturbation
		obsAndCalib.predict (linearPredict);

		// True Observation: Quadratic observation model
		z_true[0] = x_true[0] * x_true[1] + x_true[2];

		// Observation with additive noise
		localRng.normal (z, z_true[0], OBS_NOISE);	// normally distributed mean z_true[0], stdDev OBS_NOISE.

		// Filter observation using model linearised at state estimate x
		nonlinObserve.state (obsAndCalib.x);
		obsAndCalib.observe (nonlinObserve, z);
	}

	// Update the filter to state and covariance are available
	obsAndCalib.update ();

	// Print everything: True, filter, covariance
	std::cout << "True " << x_true <<  std::endl;
	std::cout << "Calb " << obsAndCalib.x << std::endl;
	std::cout << obsAndCalib.X << std::endl;
	return 0;
}

max_stars_repo_name: Exadios/Bayes-

max_issues_repo_name: Exadios/Bayes-

max_forks_repo_name: Exadios/Bayes-


text:
#pragma once

#include <boost/aura/base/base_mesh_bundle.hpp>
#include <boost/aura/base/cuda/feed.hpp>
#include <boost/aura/base/cuda/kernel.hpp>
#include <boost/aura/base/cuda/safecall.hpp>
#include <boost/aura/meta/tsizeof.hpp>

#include <cuda.h>

namespace boost
{
namespace aura
{
namespace base_detail
{
namespace cuda
{

typedef void* arg_t;
template <std::size_t N>
using args_tt = std::array<arg_t, N>;

// Alias for returned packed arguments
template <std::size_t N>
using args_t = std::pair<char*, args_tt<N>>;

/// Copy arguments to memory block recursively
template <typename ArgsItr, typename T0>
void fill_args_(char* p, ArgsItr it, const T0 a0)
{
        std::memcpy(p, &a0, sizeof(T0));
        *it = p;
}

template <typename ArgsItr, typename T0, typename... Targs>
void fill_args_(char* p, ArgsItr it, const T0 a0, const Targs... ar)
{
        std::memcpy(p, &a0, sizeof(T0));
        *it = p;
        fill_args_(p + sizeof(T0), ++it, ar...);
}

/// Pack arguments
template <typename... Targs>
args_t<sizeof...(Targs)> args_impl(const Targs... ar)
{
        args_tt<sizeof...(Targs)> pa;
        char* p = (char*)malloc(tsizeof<Targs...>::sz);
        char* ptr = p;
        fill_args_(p, pa.begin(), ar...);
        return std::make_pair(ptr, pa);
}

namespace detail
{

template <unsigned long N, typename MeshType, typename BundleType>
inline void invoke_impl(kernel& k, const MeshType& m, const BundleType& b,
        const args_t<N>&& a, feed& f)
{
        auto mesh_bundle = adjust_mesh_bundle(m, b);
        f.get_device().activate();

#if AURA_DEBUG_MESH_BUNDLE
        std::cout << mesh_bundle.first[0] << " " << mesh_bundle.first[1] << " "
                  << mesh_bundle.first[2] << " " << mesh_bundle.second[0] << " "
                  << mesh_bundle.second[1] << " " << mesh_bundle.second[2]
                  << std::endl;
#endif

        AURA_CUDA_SAFE_CALL(cuLaunchKernel(k.get_base_kernel(),
                mesh_bundle.first[0], mesh_bundle.first[1],
                mesh_bundle.first[2], mesh_bundle.second[0],
                mesh_bundle.second[1], mesh_bundle.second[2], 0,
                f.get_base_feed(), const_cast<void**>(&a.second[0]), NULL));
        f.get_device().deactivate();
        free(a.first);
}

} // namespace detail

} // cuda
} // base_detail
} // aura
} // boost

max_stars_repo_name: sschaetz/aura

max_issues_repo_name: sschaetz/aura

max_forks_repo_name: sschaetz/aura


text:
// This file is a part of the OpenSurgSim project.
// Copyright 2012-2013, SimQuest Solutions Inc.
//
// 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.

/// \file
/// Tests for the OsgProgram class.

#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Graphics/OsgProgram.h"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#include <gtest/gtest.h>

#include <sstream>

namespace
{
/// Sample vertex shader code
const std::string vertexShader =
	"varying vec4 vertColor;\n"
	"void main(void)\n"
	"{\n"
	"	gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
	"	vertColor.rgb = gl_Normal;\n"
	"	vertColor.a = 1.0;\n"
	"}\n";

/// Sample geometry shader code
const std::string geometryShader =
	"#version 150\n"
	"#extension GL_EXT_gpu_shader4 : enable\n"
	"#extension GL_EXT_geometry_shader4 : enable\n"
	"layout(triangles) in;\n"
	"layout(triangle_strip, max_vertices=3) out;\n"
	"in vec4 vertColor[3];\n"
	"out vec4 geomColor;\n"
	"void main()\n"
	"{\n"
	"	for (int i = 0; i < gl_VerticesIn; ++i)\n"
	"	{\n"
	"		gl_Position = gl_PositionIn[i];\n"
	"		geomColor = vertColor[i];\n"
	"		EmitVertex();\n"
	"	}\n"
	"	EndPrimitive();\n"
	"};";

/// Sample fragment shader code
const std::string fragmentShader =
	"varying vec4 geomColor;\n"
	"void main(void)\n"
	"{\n"
	"	gl_FragColor = geomColor;\n"
	"}";
}

namespace SurgSim
{
namespace Graphics
{

TEST(OsgProgramTests, InitTest)
{
	OsgProgram program;

	EXPECT_NE(nullptr, program.getOsgProgram());

	EXPECT_EQ(0u, program.getOsgProgram()->getNumShaders());
}

TEST(OsgProgramTests, StateSetTest)
{
	OsgProgram program;

	// Create an OSG state set
	osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet();

	const osg::StateSet::AttributeList& attributes = stateSet->getAttributeList();
	EXPECT_EQ(0u, attributes.size());

	/// Add the program to the state set
	program.addToStateSet(stateSet.get());

	EXPECT_EQ(1u, attributes.size()) << "State set has no attributes, one program should have been added!";
	EXPECT_EQ(program.getOsgProgram(),
			  attributes.at(osg::StateAttribute::TypeMemberPair(osg::StateAttribute::PROGRAM, 0)).first)
			<< "First attribute in state set should be the added program!";

	/// Remove the program from the state set
	program.removeFromStateSet(stateSet.get());

	EXPECT_EQ(0u, attributes.size())
			<< "State set should no longer have any attributes, the program should have been removed!";
}

TEST(OsgProgramTests, SetShaderSourceTest)
{
	std::shared_ptr<OsgProgram> osgProgram = std::make_shared<OsgProgram>();
	std::shared_ptr<Program> program = osgProgram;

	EXPECT_FALSE(program->hasVertexShader());
	EXPECT_FALSE(program->hasGeometryShader());
	EXPECT_FALSE(program->hasFragmentShader());

	{
		SCOPED_TRACE("Set vertex shader source");
		program->setVertexShaderSource(vertexShader);

		std::string resultVertexShader;
		EXPECT_TRUE(program->hasVertexShader());
		EXPECT_TRUE(program->getVertexShaderSource(&resultVertexShader));
		EXPECT_EQ(vertexShader, resultVertexShader);

		EXPECT_EQ(1u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Set geometry shader source");
		program->setGeometryShaderSource(geometryShader);

		std::string resultGeometryShader;
		EXPECT_TRUE(program->hasGeometryShader());
		EXPECT_TRUE(program->getGeometryShaderSource(&resultGeometryShader));
		EXPECT_EQ(geometryShader, resultGeometryShader);

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Set fragment shader source");
		program->setFragmentShaderSource(fragmentShader);

		std::string resultFragmentShader;
		EXPECT_TRUE(program->hasFragmentShader());
		EXPECT_TRUE(program->getFragmentShaderSource(&resultFragmentShader));
		EXPECT_EQ(fragmentShader, resultFragmentShader);

		EXPECT_EQ(3u, osgProgram->getOsgProgram()->getNumShaders());
	}
}

void expectFileContents(const std::string& filePath, const std::string& contents)
{
	boost::filesystem::ifstream fileStream(filePath);
	std::stringstream resultStream(contents);

	ASSERT_FALSE(fileStream.bad());

	std::string fileLine;
	std::string resultLine;
	while (!fileStream.eof() && !resultStream.eof())
	{
		fileStream >> fileLine;
		resultStream >> resultLine;

		// Skip possible trailing newlines
		fileStream >> std::ws;
		resultStream >> std::ws;

		EXPECT_EQ(fileLine, resultLine);
	}
	EXPECT_TRUE(fileStream.eof());
	EXPECT_TRUE(resultStream.eof());
	fileStream.close();
}

TEST(OsgProgramTests, LoadShaderSourceTest)
{
	SurgSim::Framework::ApplicationData data("config.txt");

	std::string vertexShaderPath   = data.findFile("OsgProgramTests/shader.vert");
	std::string geometryShaderPath = data.findFile("OsgProgramTests/shader.geom");
	std::string fragmentShaderPath = data.findFile("OsgProgramTests/shader.frag");

	ASSERT_NE("", vertexShaderPath) << "Could not find vertex shader!";
	ASSERT_NE("", geometryShaderPath) << "Could not find geometry shader!";
	ASSERT_NE("", fragmentShaderPath) << "Could not find fragment shader!";

	std::shared_ptr<OsgProgram> osgProgram = std::make_shared<OsgProgram>();
	std::shared_ptr<Program> program = osgProgram;

	{
		SCOPED_TRACE("Load vertex shader source from file");
		EXPECT_TRUE(program->loadVertexShader(vertexShaderPath));
		std::string resultVertexShader;
		EXPECT_TRUE(program->getVertexShaderSource(&resultVertexShader));
		expectFileContents(vertexShaderPath, resultVertexShader);

		EXPECT_EQ(1u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Load geometry shader source from file");
		EXPECT_TRUE(program->loadGeometryShader(geometryShaderPath));
		std::string resultGeometryShader;
		EXPECT_TRUE(program->getGeometryShaderSource(&resultGeometryShader));
		expectFileContents(geometryShaderPath, resultGeometryShader);

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Load fragment shader source from file");
		EXPECT_TRUE(program->loadFragmentShader(fragmentShaderPath));
		std::string resultFragmentShader;
		EXPECT_TRUE(program->getFragmentShaderSource(&resultFragmentShader));
		expectFileContents(fragmentShaderPath, resultFragmentShader);

		EXPECT_EQ(3u, osgProgram->getOsgProgram()->getNumShaders());
	}
}

TEST(OsgProgramTests, ClearShaderTest)
{
	std::shared_ptr<OsgProgram> osgProgram = std::make_shared<OsgProgram>();
	std::shared_ptr<Program> program = osgProgram;

	// Set vertex, geometry, and fragment shaders
	EXPECT_FALSE(program->hasVertexShader());
	program->setVertexShaderSource(vertexShader);
	EXPECT_TRUE(program->hasVertexShader());

	EXPECT_FALSE(program->hasGeometryShader());
	program->setGeometryShaderSource(geometryShader);
	EXPECT_TRUE(program->hasGeometryShader());

	EXPECT_FALSE(program->hasFragmentShader());
	program->setFragmentShaderSource(fragmentShader);
	EXPECT_TRUE(program->hasFragmentShader());

	EXPECT_EQ(3u, osgProgram->getOsgProgram()->getNumShaders());

	{
		SCOPED_TRACE("Clear vertex shader");
		program->clearVertexShader();
		EXPECT_FALSE(program->hasVertexShader());
		EXPECT_TRUE(program->hasGeometryShader());
		EXPECT_TRUE(program->hasFragmentShader());

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}
	program->setVertexShaderSource(vertexShader);
	EXPECT_TRUE(program->hasVertexShader());

	{
		SCOPED_TRACE("Clear geometry shader");
		program->clearGeometryShader();
		EXPECT_TRUE(program->hasVertexShader());
		EXPECT_FALSE(program->hasGeometryShader());
		EXPECT_TRUE(program->hasFragmentShader());

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}
	program->setGeometryShaderSource(geometryShader);
	EXPECT_TRUE(program->hasGeometryShader());

	{
		SCOPED_TRACE("Clear fragment shader");
		program->clearFragmentShader();
		EXPECT_TRUE(program->hasVertexShader());
		EXPECT_TRUE(program->hasGeometryShader());
		EXPECT_FALSE(program->hasFragmentShader());

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}
	program->setFragmentShaderSource(fragmentShader);
	EXPECT_TRUE(program->hasFragmentShader());

	{
		SCOPED_TRACE("Clear the entire shader");
		program->clear();
		EXPECT_FALSE(program->hasVertexShader());
		EXPECT_FALSE(program->hasGeometryShader());
		EXPECT_FALSE(program->hasFragmentShader());

		EXPECT_EQ(0u, osgProgram->getOsgProgram()->getNumShaders());
	}
}

}  // namespace Graphics
}  // namespace SurgSim

max_stars_repo_name: dbungert/opensurgsim

max_issues_repo_name: dbungert/opensurgsim

max_forks_repo_name: dbungert/opensurgsim


text:
/*
 * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <iostream>

#include <boost/assign.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>

#include <pkmn/enums.hpp>
#include <pkmn/pocket.hpp>
#include <pkmn/paths.hpp>
#include <pkmn/database/queries.hpp>
#include <pkmn/types/dict.hpp>

#include "bag_impl.hpp"
#include "copy_sptrs.hpp"

namespace pkmn
{
    bag::sptr bag::make(unsigned int game)
    {
        return sptr(new bag_impl(game));
    }

    bag::sptr bag::make(std::string game)
    {
        //FRLG and HGSS are stored without spaces
        if(game != "Black 2" and game != "White 2") boost::erase_all(game, " ");
        return make(database::get_version_id(game));
    }

    pkmn::shared_ptr<SQLite::Database> bag_impl::_db;

    /*
     * The underlying SQLite database can return item categories, which correspond to bag
     * pockets, but these values are only guaranteed to be accurate for Generation VI.
     * As ugly as this 2D vector is, it's the best way to determine the correct pocket for
     * an item in earlier version groups.
     *
     * The outer vector corresponds to a game's version group, and the inner vector
     * corresponds to the Generation VI item pocket ID.
     */
    std::vector<std::vector<std::string> > bag_impl::_category_pockets =
        boost::assign::list_of<std::vector<std::string> >
        (
            boost::assign::list_of //Never used
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Items") //Poke Balls
                ("Items") //Machines
                ("Items") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Items") //Key
        )
        (
            boost::assign::list_of //RB
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Items") //Poke Balls
                ("Items") //Machines
                ("Items") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Items") //Key
        )
        (
            boost::assign::list_of //Yellow
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Items") //Poke Balls
                ("Items") //Machines
                ("Items") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Items") //Key
        )
        (
            boost::assign::list_of //GS
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Balls") //Poke Balls
                ("TM/HM") //Machines
                ("Items") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("KeyItems") //Key
        )
        (
            boost::assign::list_of //Crystal
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Balls") //Poke Balls
                ("TM/HM") //Machines
                ("Items") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("KeyItems") //Key
        )
        (
            boost::assign::list_of //RS
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Poke Balls") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //Emerald
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Poke Balls") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //FRLG
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Poke Balls") //Poke Balls
                ("TM Case") //Machines
                ("Berry Pouch") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //DP
                ("Items") //Invalid
                ("Items") //Misc
                ("Medicine") //Medicine
                ("Poke Balls") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Mail") //Mail
                ("Battle Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //Platinum
                ("Items") //Invalid
                ("Items") //Misc
                ("Medicine") //Medicine
                ("Poke Balls") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Mail") //Mail
                ("Battle Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //HGSS
                ("Items") //Invalid
                ("Items") //Misc
                ("Medicine") //Medicine
                ("Poke Balls") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Mail") //Mail
                ("Battle Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //BW
                ("Items") //Invalid
                ("Items") //Misc
                ("Medicine") //Medicine
                ("Items") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //Colosseum
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Poke Balls") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //XD
                ("Items") //Invalid
                ("Items") //Misc
                ("Items") //Medicine
                ("Poke Balls") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //B2W2
                ("Items") //Invalid
                ("Items") //Misc
                ("Medicine") //Medicine
                ("Items") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
        (
            boost::assign::list_of //XY
                ("Items") //Invalid
                ("Items") //Misc
                ("Medicine") //Medicine
                ("Items") //Poke Balls
                ("TMs and HMs") //Machines
                ("Berries") //Berries
                ("Items") //Mail
                ("Items") //Battle
                ("Key Items") //Key
        )
    ;

    bag_impl::bag_impl(unsigned int game): bag()
    {
        if(!_db) _db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));

        _game_id = game;
        _generation = database::get_generation(_game_id);
        _pockets = pkmn::dict<std::string, pocket::sptr>();

        switch(game)
        {
            case Versions::RED:
            case Versions::BLUE:
            case Versions::YELLOW:
                _pockets["Items"] = pocket::make(_game_id, "Items", 20);
                break;

            case Versions::GOLD:
            case Versions::SILVER:
            case Versions::CRYSTAL:
                _pockets["Items"] = pocket::make(_game_id, "Items", 20);
                _pockets["Balls"] = pocket::make(_game_id, "Balls", 12);
                _pockets["KeyItems"] = pocket::make(_game_id, "KeyItems", 26);
                _pockets["TM/HM"] = pocket::make(_game_id, "TM/HM", 99);
                break;

            case Versions::RUBY:
            case Versions::SAPPHIRE:
                _pockets["Items"] = pocket::make(_game_id, "Items", 20);
                _pockets["Poke Balls"] = pocket::make(_game_id, "Poke Balls", 16);
                _pockets["TMs and HMs"] = pocket::make(_game_id, "TMs and HMs", 64);
                _pockets["Berries"] = pocket::make(_game_id, "Berries", 46);
                _pockets["Key Items"] = pocket::make(_game_id, "Key Items", 20);
                break;

            case Versions::EMERALD:
                _pockets["Items"] = pocket::make(_game_id, "Items", 20);
                _pockets["Poke Balls"] = pocket::make(_game_id, "Poke Balls", 16);
                _pockets["TMs and HMs"] = pocket::make(_game_id, "TMs and HMs", 64);
                _pockets["Berries"] = pocket::make(_game_id, "Berries", 46);
                _pockets["Key Items"] = pocket::make(_game_id, "Key Items", 30);
                break;

            case Versions::FIRERED:
            case Versions::LEAFGREEN:
                _pockets["Items"] = pocket::make(_game_id, "Items", 42);
                _pockets["Key Items"] = pocket::make(_game_id, "Key Items", 30);
                _pockets["Poke Balls"] = pocket::make(_game_id, "Poke Balls", 13);
                _pockets["TM Case"] = pocket::make(_game_id, "TM Case", 58);
                _pockets["Berry Pouch"] = pocket::make(_game_id, "Berry Pouch", 43);
                break;

            case Versions::DIAMOND:
            case Versions::PEARL:
            case Versions::PLATINUM:
                _pockets["Items"] = pocket::make(_game_id, "Items", 165);
                _pockets["Medicine"] = pocket::make(_game_id, "Medicine", 40);
                _pockets["Poke Balls"] = pocket::make(_game_id, "Poke Balls", 15);
                _pockets["TMs and HMs"] = pocket::make(_game_id, "TMs and HMs", 100);
                _pockets["Berries"] = pocket::make(_game_id, "Berries", 64);
                _pockets["Mail"] = pocket::make(_game_id, "Mail", 12);
                _pockets["Battle Items"] = pocket::make(_game_id, "Battle Items", 30);
                _pockets["Key Items"] = pocket::make(_game_id, "Key Items", 50);
                break;

            case Versions::HEARTGOLD:
            case Versions::SOULSILVER:
                _pockets["Items"] = pocket::make(_game_id, "Items", 165);
                _pockets["Medicine"] = pocket::make(_game_id, "Medicine", 40);
                _pockets["Poke Balls"] = pocket::make(_game_id, "Poke Balls", 24);
                _pockets["TMs and HMs"] = pocket::make(_game_id, "TMs and HMs", 100);
                _pockets["Berries"] = pocket::make(_game_id, "Berries", 64);
                _pockets["Mail"] = pocket::make(_game_id, "Mail", 12);
                _pockets["Battle Items"] = pocket::make(_game_id, "Battle Items", 30);
                _pockets["Key Items"] = pocket::make(_game_id, "Key Items", 43);
                break;

            case Versions::BLACK:
            case Versions::WHITE:
            case Versions::BLACK_2:
            case Versions::WHITE_2:
            case Versions::X:
            case Versions::Y:
                _pockets["Items"] = pocket::make(_game_id, "Items", 310);
                _pockets["Medicine"] = pocket::make(_game_id, "Medicine", 48);
                _pockets["TMs and HMs"] = pocket::make(_game_id, "TMs and HMs", 109);
                _pockets["Berries"] = pocket::make(_game_id, "Berries", 64);
                _pockets["Key Items"] = pocket::make(_game_id, "Key Items", 83);

            default:
                break;
        }
    }

    bag_impl::bag_impl(const bag_impl& other) :
        _game_id(other._game_id),
        _generation(other._generation)
    {
        std::vector<std::string> pocket_names = other._pockets.keys();
        std::vector<pocket::sptr> pockets = other._pockets.vals();

        for(size_t i = 0; i < pocket_names.size(); i++)
        {
            _pockets[pocket_names[i]] = copy_pocket(pockets[i]);
        }
    }

    bag_impl& bag_impl::operator=(const bag_impl& other)
    {
        _game_id = other._game_id;
        _generation = other._generation;

        std::vector<std::string> pocket_names = other._pockets.keys();
        std::vector<pocket::sptr> pockets = other._pockets.vals();

        for(size_t i = 0; i < pocket_names.size(); i++)
        {
            _pockets[pocket_names[i]] = copy_pocket(pockets[i]);
        }

        return *this;
    }

    std::string bag_impl::get_game() const {return database::get_version_name(_game_id);}

    unsigned int bag_impl::get_generation() const {return _generation;}

    void bag_impl::add_item(pokemon_text item_name, unsigned int amount)
    {
        add_item(database::get_item_id(item_name), amount);
    }

    void bag_impl::add_item(unsigned int item_id, unsigned int amount)
    {
        _pockets[_get_pocket_name(item_id)]->add_item(item_id, amount);
    }

    void bag_impl::add_item(item::sptr item_sptr, unsigned int amount)
    {
        add_item(item_sptr->get_item_id(), amount);
    }

    void bag_impl::remove_item(pokemon_text item_name, unsigned int amount)
    {
        remove_item(database::get_item_id(item_name), amount);
    }

    void bag_impl::remove_item(unsigned int item_id, unsigned int amount)
    {
        _pockets[_get_pocket_name(item_id)]->remove_item(item_id, amount);
    }

    void bag_impl::remove_item(item::sptr item_sptr, unsigned int amount)
    {
        remove_item(item_sptr->get_item_id(), amount);
    }

    unsigned int bag_impl::get_item_amount(pokemon_text item_name) const
    {
        return get_item_amount(database::get_item_id(item_name));
    }

    unsigned int bag_impl::get_item_amount(unsigned int item_id) const
    {
        return _pockets[_get_pocket_name(item_id)]->get_item_amount(item_id);
    }

    unsigned int bag_impl::get_item_amount(item::sptr item_sptr) const
    {
        return get_item_amount(item_sptr->get_item_id());
    }

    pocket::sptr bag_impl::get_pocket(std::string name) const {return _pockets[name];}

    pkmn::dict<std::string, pocket::sptr> bag_impl::get_pockets() const {return _pockets;}

    unsigned int bag_impl::get_game_id() const {return _game_id;}

    //Determine correct pocket for given item
    std::string bag_impl::_get_pocket_name(unsigned int item_id) const
    {
        unsigned int version_group = database::get_version_group_id(_game_id);

        std::string query_string(str(boost::format("SELECT pocket_id FROM item_categories WHERE id=%d")
                                     % database::get_item_category_id(item_id)));
        SQLite::Statement pocket_id_query(*_db, query_string.c_str());
        unsigned int pocket_id = (pocket_id_query.executeStep()) ? int(pocket_id_query.getColumn(0)) : 0;

        return _category_pockets[version_group][pocket_id];
    }

    void bag_impl::_check() const
    {
        FOREACH(std::string& key, _pockets.keys().begin(), _pockets.keys().end())
        {
            if(_game_id != _pockets[key]->get_game_id())
            {
                throw std::runtime_error(str(boost::format("Pocket \"%s\" is invalid!")
                                             % key));
            }
        }
    }
} /* namespace pkmn */