<commit_before>#ifdef _DEBUG
#include <iostream>
#include <boost/format.hpp>
#endif

#include <vector>
#include <algorithm>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <data_type.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/adjacent.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/yrange2.hpp>
#include <gui.hpp>

// 2値座標系式から1値座標系式に変えながら和
// 指定した範囲の配列の和を返す
int yrange2::array_sum(return_type const& array_, int const x, int const y, int const height, int const width) const
{
    int sum = 0;
    for(int i=0; i<height; ++i)
    {
        for(int j=0; j<width; ++j)
        {
            auto const& target_point = array_[y + i][x + j];
			if (target_point.x == std::numeric_limits<int>::max() && target_point.y == std::numeric_limits<int>::max()) return -1;
			else
            {
                auto const point = target_point.y * width + target_point.x;
                sum += (point > 1000) ? 777 : point;
            }
        }
    }
    return sum;
}

/*縦列単位で入れ替え*/
void yrange2::column_replacement(answer_type_y & answer)
{
	int const sepx = data_.split_num.first;
	int const sepy = data_.split_num.second;
	uint_fast64_t good_val;
	std::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));
	good_matrix = answer.points;
	good_val = form_evaluate(data_,comp_,good_matrix);

	for (int i = 0; i < sepx; ++i){
		for (int j = 0; j < sepy; ++j){
			answer.points[j].insert(answer.points[j].begin(), answer.points[j][sepx - 1]);
			answer.points[j].pop_back();
		}
		auto const temp_score = form_evaluate(data_,comp_, answer.points);
		if (good_val>temp_score){
			good_val = temp_score;
			good_matrix = answer.points;
		}
	}
	answer.points = good_matrix;
	answer.score = good_val;
}

/*横列単位で入れ替え*/
void yrange2::row_replacement(answer_type_y& answer)
{
	int const sepx = data_.split_num.first;
	int const sepy = data_.split_num.second;
	uint_fast64_t good_val;
	std::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));
	std::vector<point_type> temp_vec;
	good_matrix = answer.points;
	good_val = form_evaluate(data_, comp_, answer.points);
	for (int i = 0; i < sepy; ++i){
		answer.points.insert(answer.points.begin(), answer.points[sepy - 1]);
		answer.points.pop_back();
		auto const temp_score = form_evaluate(data_, comp_, answer.points);
		if (good_val>temp_score){
			good_val = temp_score;
			good_matrix = answer.points;
		}
	}
	answer.points = good_matrix;
	answer.score = good_val;
}

//cv::matの塊にする
cv::Mat yrange2::combine_image(answer_type_y const& answer)
{
	int const one_picx = data_.size.first / data_.split_num.first;
	int const one_picy = data_.size.second / data_.split_num.second;

	splitter sp;//どこからか持ってきてたsplitter
	split_image_type splitted = sp.split_image(data_);
	cv::Mat comb_pic(cv::Size(data_.size.first, data_.size.second), CV_8UC3);
#pragma omp parallel
	for (int i = 0; i < data_.split_num.second; ++i){
		for (int j = 0; j < data_.split_num.first; ++j){
			cv::Rect roi_rect(j*one_picx, i*one_picy, one_picx, one_picy);
			cv::Mat roi_mat(comb_pic, roi_rect);
			splitted[answer.points[i][j].y][answer.points[i][j].x].copyTo(roi_mat);
		}
	}
	return std::move(comb_pic.clone());
}

yrange2::yrange2(question_raw_data const& data, compared_type const& comp)
    : data_(data), comp_(comp), adjacent_data_(select_minimum(comp))
{
}

std::vector<answer_type_y> yrange2::operator() ()
{
	auto const width = data_.split_num.first;
	auto const height = data_.split_num.second;
	int constexpr yrange2_show_ans = 8;

	auto const exists = [height, width](point_type const& p)
	{
		return 0 <= p.x && p.x < width && 0 <= p.y && p.y < height;
	};

    std::vector<std::vector<std::vector<point_type>>>& sorted_matrix = sorted_matrix_;
    sorted_matrix.clear();
    sorted_matrix.resize(
        width*height,
		std::vector<std::vector<point_type>>(
		    height * 2 - 1,
		    std::vector<point_type>(
		        width * 2 - 1,
                { std::numeric_limits<int>::max(), std::numeric_limits<int>::max() }
                )
            )
        );

	std::vector<answer_type_y> answer;
	answer.reserve(width*height * 2);
	splitter sp;

	//すべてのピースから並べ始めるためのループ
#pragma omp parallel for
	for (int c = 0; c < width*height; ++c)
	{
		sorted_matrix.at(c)[height - 1][width - 1] = point_type{ c%width, c / width };

		//上に見ていく
		for (int i = 0; i < height - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1 - i][width - 1];
			sorted_matrix.at(c)[height - 2 - i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].up;
			if (sorted_matrix.at(c)[height - 2 - i][width - 1].y < 0 || sorted_matrix.at(c)[height - 2 - i][width - 1].y >= height) break;
		}
		//下に見ていく
		for (int i = 0; i < height - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1 + i][width - 1];
			sorted_matrix.at(c)[height + i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].down;
			if (sorted_matrix.at(c)[height + i][width - 1].y < 0 || sorted_matrix.at(c)[height + i][width - 1].y >= height) break;
		}
		//右に見ていく
		for (int i = 0; i < width - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1][width - 1 + i];
			sorted_matrix.at(c)[height - 1][width + i] = adjacent_data_[adjacent.y][adjacent.x].right;
			if (sorted_matrix.at(c)[height - 1][width + i].x < 0 || sorted_matrix.at(c)[height - 1][width + i].x >= width) break;
		}
		//左に見ていく
		for (int i = 0; i < width - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1][width - 1 - i];
			sorted_matrix.at(c)[height - 1][width - 2 - i] = adjacent_data_[adjacent.y][adjacent.x].left;
			if (sorted_matrix.at(c)[height - 1][width - 2 - i].x < 0 || sorted_matrix.at(c)[height - 1][width - 2 - i].x >= width) break;
		}

		//中心を除き上に向かってループ，右に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height - i - 1][width + j - 1];
			auto const& upper = sorted_matrix.at(c)[height - i - 2][width + j - 1];
			auto const& right = sorted_matrix.at(c)[height - i - 1][width + j];

			if (exists(center) && exists(upper) && exists(right))
				sorted_matrix.at(c)[height - i - 2][width + j] = ur_choose(comp_, upper, center, right);
			else
				break;
		}
		//中心を除き上に向かってループ，左に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height - i - 1][width - j - 1];
			auto const& upper = sorted_matrix.at(c)[height - i - 2][width - j - 1];
			auto const& left = sorted_matrix.at(c)[height - i - 1][width - j - 2];

			if (exists(center) && exists(upper) && exists(left))
				sorted_matrix.at(c)[height - i - 2][width - j - 2] = ul_choose(comp_, upper, left, center);
			else
				break;
		}
		//中心を除き下に向かってループ，右に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height + i - 1][width + j - 1];
			auto const& lower = sorted_matrix.at(c)[height + i][width + j - 1];
			auto const& right = sorted_matrix.at(c)[height + i - 1][width + j];

			if (exists(center) && exists(lower) && exists(right))
				sorted_matrix.at(c)[height + i][width + j] = dr_choose(comp_, center, right, lower);
			else
				break;
		}
		//中心を除き下に向かってループ，左に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height + i - 1][width - j - 1];
			auto const& lower = sorted_matrix.at(c)[height + i][width - j - 1];
			auto const& left = sorted_matrix.at(c)[height + i - 1][width - j - 2];

			if (exists(center) && exists(lower) && exists(left))
				sorted_matrix.at(c)[height + i][width - j - 2] = dl_choose(comp_, left, center, lower);
			else
				break;
		}
	}

	for (int c = 0; c < height*width; ++c)
	{
		for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x)
		{
			if (array_sum(sorted_matrix.at(c), x, y, height, width) == ((width*height - 1)*(width*height) / 2) && get_kind_num(data_, sorted_matrix.at(c), x, y) == width*height)
			{
				std::vector<std::vector<point_type>> one_answer(height, std::vector<point_type>(width, point_type{ -1, -1 }));
				for (int i = 0; i < height; i++) for (int j = 0; j < width; j++)
				{
					one_answer[i][j] = sorted_matrix.at(c)[y + i][x + j];
				}
				answer.push_back(answer_type_y{ one_answer, 0, cv::Mat() });
			}
		}
	}
	//#########################################################yrange2.5#########################################################//

	//現段階で重複しているものは1つに絞る
	// unique()を使う準備としてソートが必要
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });
	// unique()をしただけでは後ろにゴミが残るので、eraseで削除する
	answer.erase(std::unique(answer.begin(), answer.end()), answer.end());

	//縦入れ替え，横入れ替え
#pragma omp parallel for
	for (int c = 0; c < answer.size(); ++c)
	{
		row_replacement(answer.at(c));
		column_replacement(answer.at(c));
	}

	//もっかいやっとく
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });
	answer.erase(std::unique(answer.begin(), answer.end()), answer.end());

	//無駄に多く返してもしょうがないので枝抜き
	int const yrange2_ans = answer.size();
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.score < b.score; });
	if (answer.size() >= yrange2_show_ans) answer.resize(yrange2_show_ans);

	//一枚のcv::Matにする
#pragma omp parallel for
	for (int c = 0; c < answer.size(); ++c)
	{
		answer.at(c).mat_image = std::move(combine_image(answer.at(c)));
	}

#ifdef _DEBUG
    std::cout << "There are " << yrange2_ans << " solutions" << std::endl;
	for (auto const& one_answer : answer)
	{
		for (int i = 0; i < one_answer.points.size(); ++i)
		{
			for (int j = 0; j < one_answer.points.at(0).size(); ++j)
			{
				auto const& data = one_answer.points[i][j];
				std::cout << boost::format("(%2d,%2d) ") % data.x % data.y;
			}
			std::cout << "\n";
		}
		std::cout << "score = " << one_answer.score << std::endl;
	}
	gui::show_image(data_, comp_, answer);
#endif
	return answer;
}

std::vector<std::vector<std::vector<point_type>>> const& yrange2::sorted_matrix()
{
    return sorted_matrix_;
}
<commit_msg>first commit<commit_after>#ifdef _DEBUG
#include <iostream>
#include <boost/format.hpp>
#endif

#include <vector>
#include <algorithm>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <data_type.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/adjacent.hpp>
#include <sort_algorithm/compare.hpp>
#include <sort_algorithm/yrange2.hpp>
#include <gui.hpp>

// 2値座標系式から1値座標系式に変えながら和
// 指定した範囲の配列の和を返す
int yrange2::array_sum(return_type const& array_, int const x, int const y, int const height, int const width) const
{
    int sum = 0;
    for(int i=0; i<height; ++i)
    {
        for(int j=0; j<width; ++j)
        {
            auto const& target_point = array_[y + i][x + j];
			if (target_point.x == std::numeric_limits<int>::max() && target_point.y == std::numeric_limits<int>::max()) return -1;
			else
            {
                auto const point = target_point.y * width + target_point.x;
                sum += (point > 1000) ? 777 : point;
            }
        }
    }
    return sum;
}

/*縦列単位で入れ替え*/
void yrange2::column_replacement(answer_type_y & answer)
{
	int const sepx = data_.split_num.first;
	int const sepy = data_.split_num.second;
	uint_fast64_t good_val;
	std::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));
	good_matrix = answer.points;
	good_val = form_evaluate(data_,comp_,good_matrix);

	for (int i = 0; i < sepx; ++i){
		for (int j = 0; j < sepy; ++j){
			answer.points[j].insert(answer.points[j].begin(), answer.points[j][sepx - 1]);
			answer.points[j].pop_back();
		}
		auto const temp_score = form_evaluate(data_,comp_, answer.points);
		if (good_val>temp_score){
			good_val = temp_score;
			good_matrix = answer.points;
		}
	}
	answer.points = good_matrix;
	answer.score = good_val;
}

/*横列単位で入れ替え*/
void yrange2::row_replacement(answer_type_y& answer)
{
	int const sepx = data_.split_num.first;
	int const sepy = data_.split_num.second;
	uint_fast64_t good_val;
	std::vector<std::vector<point_type> > good_matrix(sepy, std::vector<point_type>(sepx));
	std::vector<point_type> temp_vec;
	good_matrix = answer.points;
	good_val = form_evaluate(data_, comp_, answer.points);
	for (int i = 0; i < sepy; ++i){
		answer.points.insert(answer.points.begin(), answer.points[sepy - 1]);
		answer.points.pop_back();
		auto const temp_score = form_evaluate(data_, comp_, answer.points);
		if (good_val>temp_score){
			good_val = temp_score;
			good_matrix = answer.points;
		}
	}
	answer.points = good_matrix;
	answer.score = good_val;
}

//cv::matの塊にする
cv::Mat yrange2::combine_image(answer_type_y const& answer)
{
	int const one_picx = data_.size.first / data_.split_num.first;
	int const one_picy = data_.size.second / data_.split_num.second;

	splitter sp;//どこからか持ってきてたsplitter
	split_image_type splitted = sp.split_image(data_);
	cv::Mat comb_pic(cv::Size(data_.size.first, data_.size.second), CV_8UC3);
#pragma omp parallel
	for (int i = 0; i < data_.split_num.second; ++i){
		for (int j = 0; j < data_.split_num.first; ++j){
			cv::Rect roi_rect(j*one_picx, i*one_picy, one_picx, one_picy);
			cv::Mat roi_mat(comb_pic, roi_rect);
			splitted[answer.points[i][j].y][answer.points[i][j].x].copyTo(roi_mat);
		}
	}
	return std::move(comb_pic.clone());
}

yrange2::yrange2(question_raw_data const& data, compared_type const& comp)
    : data_(data), comp_(comp), adjacent_data_(select_minimum(comp))
{
}

std::vector<answer_type_y> yrange2::operator() ()
{
	auto const width = data_.split_num.first;
	auto const height = data_.split_num.second;
	int constexpr yrange2_show_ans = 8;

	auto const exists = [height, width](point_type const& p)
	{
		return 0 <= p.x && p.x < width && 0 <= p.y && p.y < height;
	};

    std::vector<std::vector<std::vector<point_type>>>& sorted_matrix = sorted_matrix_;
    sorted_matrix.clear();
    sorted_matrix.resize(
        width*height,
		std::vector<std::vector<point_type>>(
		    height * 2 - 1,
		    std::vector<point_type>(
		        width * 2 - 1,
                { std::numeric_limits<int>::max(), std::numeric_limits<int>::max() }
                )
            )
        );

	std::vector<answer_type_y> answer;
	answer.reserve(width*height * 2);
	splitter sp;

	//すべてのピースから並べ始めるためのループ
#pragma omp parallel for
	for (int c = 0; c < width*height; ++c)
	{
		sorted_matrix.at(c)[height - 1][width - 1] = point_type{ c%width, c / width };

		//上に見ていく
		for (int i = 0; i < height - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1 - i][width - 1];
			sorted_matrix.at(c)[height - 2 - i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].up;
			if (sorted_matrix.at(c)[height - 2 - i][width - 1].y < 0 || sorted_matrix.at(c)[height - 2 - i][width - 1].y >= height) break;
		}
		//下に見ていく
		for (int i = 0; i < height - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1 + i][width - 1];
			sorted_matrix.at(c)[height + i][width - 1] = adjacent_data_[adjacent.y][adjacent.x].down;
			if (sorted_matrix.at(c)[height + i][width - 1].y < 0 || sorted_matrix.at(c)[height + i][width - 1].y >= height) break;
		}
		//右に見ていく
		for (int i = 0; i < width - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1][width - 1 + i];
			sorted_matrix.at(c)[height - 1][width + i] = adjacent_data_[adjacent.y][adjacent.x].right;
			if (sorted_matrix.at(c)[height - 1][width + i].x < 0 || sorted_matrix.at(c)[height - 1][width + i].x >= width) break;
		}
		//左に見ていく
		for (int i = 0; i < width - 1; ++i)
		{
			auto const& adjacent = sorted_matrix.at(c)[height - 1][width - 1 - i];
			sorted_matrix.at(c)[height - 1][width - 2 - i] = adjacent_data_[adjacent.y][adjacent.x].left;
			if (sorted_matrix.at(c)[height - 1][width - 2 - i].x < 0 || sorted_matrix.at(c)[height - 1][width - 2 - i].x >= width) break;
		}

		//中心を除き上に向かってループ，右に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height - i - 1][width + j - 1];
			auto const& upper = sorted_matrix.at(c)[height - i - 2][width + j - 1];
			auto const& right = sorted_matrix.at(c)[height - i - 1][width + j];

			if (exists(center) && exists(upper) && exists(right))
				sorted_matrix.at(c)[height - i - 2][width + j] = ur_choose(comp_, upper, center, right);
			else
				break;
		}
		//中心を除き上に向かってループ，左に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height - i - 1][width - j - 1];
			auto const& upper = sorted_matrix.at(c)[height - i - 2][width - j - 1];
			auto const& left = sorted_matrix.at(c)[height - i - 1][width - j - 2];

			if (exists(center) && exists(upper) && exists(left))
				sorted_matrix.at(c)[height - i - 2][width - j - 2] = ul_choose(comp_, upper, left, center);
			else
				break;
		}
		//中心を除き下に向かってループ，右に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height + i - 1][width + j - 1];
			auto const& lower = sorted_matrix.at(c)[height + i][width + j - 1];
			auto const& right = sorted_matrix.at(c)[height + i - 1][width + j];

			if (exists(center) && exists(lower) && exists(right))
				sorted_matrix.at(c)[height + i][width + j] = dr_choose(comp_, center, right, lower);
			else
				break;
		}
		//中心を除き下に向かってループ，左に見ていく
		for (int i = 0; i < height - 1; ++i) for (int j = 0; j < width - 1; ++j)
		{
			auto const& center = sorted_matrix.at(c)[height + i - 1][width - j - 1];
			auto const& lower = sorted_matrix.at(c)[height + i][width - j - 1];
			auto const& left = sorted_matrix.at(c)[height + i - 1][width - j - 2];

			if (exists(center) && exists(lower) && exists(left))
				sorted_matrix.at(c)[height + i][width - j - 2] = dl_choose(comp_, left, center, lower);
			else
				break;
		}
	}

	for (int c = 0; c < height*width; ++c)
	{
		for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x)
		{
			if (array_sum(sorted_matrix.at(c), x, y, height, width) == ((width*height - 1)*(width*height) / 2) && get_kind_num(data_, sorted_matrix.at(c), x, y) == width*height)
			{
				std::vector<std::vector<point_type>> one_answer(height, std::vector<point_type>(width, point_type{ -1, -1 }));
				for (int i = 0; i < height; i++) for (int j = 0; j < width; j++)
				{
					one_answer[i][j] = sorted_matrix.at(c)[y + i][x + j];
				}
				answer.push_back(answer_type_y{ one_answer, 0, cv::Mat() });
			}
		}
	}

	//現段階で重複しているものは1つに絞る
	// unique()を使う準備としてソートが必要
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });
	// unique()をしただけでは後ろにゴミが残るので、eraseで削除する
	answer.erase(std::unique(answer.begin(), answer.end()), answer.end());

	//縦入れ替え，横入れ替え
#pragma omp parallel for
	for (int c = 0; c < answer.size(); ++c)
	{
		row_replacement(answer.at(c));
		column_replacement(answer.at(c));
	}

	//もっかいやっとく
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.points < b.points; });
	answer.erase(std::unique(answer.begin(), answer.end()), answer.end());

	//無駄に多く返してもしょうがないので枝抜き
	int const yrange2_ans = answer.size();
	std::sort(answer.begin(), answer.end(), [](answer_type_y a, answer_type_y b){return a.score < b.score; });
	if (answer.size() >= yrange2_show_ans) answer.resize(yrange2_show_ans);

	//一枚のcv::Matにする
#pragma omp parallel for
	for (int c = 0; c < answer.size(); ++c)
	{
		answer.at(c).mat_image = std::move(combine_image(answer.at(c)));
	}

#ifdef _DEBUG
    std::cout << "There are " << yrange2_ans << " solutions by yrange2." << std::endl;
	for (auto const& one_answer : answer)
	{
		for (int i = 0; i < one_answer.points.size(); ++i)
		{
			for (int j = 0; j < one_answer.points.at(0).size(); ++j)
			{
				auto const& data = one_answer.points[i][j];
				std::cout << boost::format("(%2d,%2d) ") % data.x % data.y;
			}
			std::cout << "\n";
		}
		std::cout << "score = " << one_answer.score << std::endl;
	}
	gui::show_image(data_, comp_, answer);
#endif
	return answer;
}

std::vector<std::vector<std::vector<point_type>>> const& yrange2::sorted_matrix()
{
    return sorted_matrix_;
}
<|endoftext|>


<commit_before>/*
 * strings.cpp
 *
 *  Created on: Jan 27, 2011
 *      Author: Craig Rasmussen
 */

#include <stdlib.h>

#include <src/columns/HyPerCol.hpp>
#include <src/io/LinearActivityProbe.hpp>
#include <src/io/PointProbe.hpp>
#include <src/layers/LIF.hpp>
#include <src/layers/Retina.hpp>
#include <src/connections/HyPerConn.hpp>
#include <src/connections/CocircConn.hpp>

using namespace PV;

int main(int argc, char* argv[])
{
   // create the managing hypercolumn
   HyPerCol * hc = new HyPerCol("column", argc, argv);

   // create the layers
   HyPerLayer * retina = new Retina("Retina", hc);
   HyPerLayer * l1     = new LIF("L1", hc);

   // connect the layers
   new HyPerConn("Retina to L1", hc, retina, l1, CHANNEL_EXC);
   new CocircConn("L1 to L1",    hc, l1,     l1, CHANNEL_EXC);

   int locX = 39;
   int locY = 31; // 53;
   int locF = 0;

   // add probes
   LayerProbe * probe   = new LinearActivityProbe(hc, DimX, locY, locF);
   LayerProbe * ptprobe = new PointProbe(locX, locY, locF, "L1:");

   l1->insertProbe(probe);

   // run the simulation
   hc->initFinish();
   hc->run();

   /* clean up (HyPerCol owns layers and connections, don't delete them) */
   delete hc;
   delete probe;
   delete ptprobe;

   return 0;
}
<commit_msg>Initial WORKING version.<commit_after>/*
 * strings.cpp
 *
 *  Created on: Jan 27, 2011
 *      Author: Craig Rasmussen
 */

#include <stdlib.h>

#include "StringImage.hpp"
#include <src/columns/HyPerCol.hpp>
#include <src/layers/LIF.hpp>
#include <src/connections/HyPerConn.hpp>

using namespace PV;

int main(int argc, char* argv[])
{
   // create the managing hypercolumn
   HyPerCol * hc = new HyPerCol("column", argc, argv);

   // create the layers
   HyPerLayer * strings = new StringImage("Strings", hc);
   HyPerLayer * complex = new LIF("Complex", hc);

   // connect the layers
   new HyPerConn("Strings to Complex", hc, strings, complex, CHANNEL_EXC);

   // run the simulation
   hc->initFinish();
   hc->run();

   /* clean up (HyPerCol owns layers and connections, don't delete them) */
   delete hc;

   return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Directory.h"
#include "utils/Charsets.h"
#include "factory/IFileSystem.h"
#include "File.h"
#include "logging/Logger.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
#include <winapifamily.h>

namespace medialibrary
{

namespace fs
{

Directory::Directory(const std::string& path , factory::IFileSystem& fsFactory)
    : CommonDirectory( toAbsolute( path ), fsFactory )
{
}

void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
    WIN32_FIND_DATA f;
    auto pattern = m_path + '*';
    auto wpattern = charset::ToWide( pattern.c_str() );
    auto h = FindFirstFile( wpattern.get(), &f );
    if ( h == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to browse ", m_path );
        std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
    }
    do
    {
        auto file = charset::FromWide( f.cFileName );
        if ( file[0] == '.' )
            continue;
        auto path = m_path + file.get();
        if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
            m_dirs.emplace_back( m_fsFactory.createDirectory( path ) );
        else
            m_files.emplace_back( std::make_shared<File>( path ) );
    } while ( FindNextFile( h, &f ) != 0 );
    FindClose( h );
#else
    // We must remove the trailing /
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
    // «Do not use a trailing backslash (\), which indicates the root directory of a drive»
    assert( *m_path.rbegin() == '\\' );
    auto tmpPath = m_path.substr( 0, m_path.length() - 1 );
    auto wpath = charset::ToWide( tmpPath.c_str() );
    auto handle = CreateFile( wpath.get(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
                              FILE_FLAG_BACKUP_SEMANTICS, nullptr );
    if ( handle == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to open directory ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
    }

    std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
            decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );

    // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
    size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
    std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
                reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
                [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
    if ( dirInfo == nullptr )
        throw std::bad_alloc();

    while ( true )
    {
        auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
        if ( h == 0 )
        {
            auto error = GetLastError();
            if ( error == ERROR_FILE_NOT_FOUND )
                break;
            else if ( error == ERROR_MORE_DATA )
            {
                buffSize *= 2;
                dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
                if ( dirInfo == nullptr )
                    throw std::bad_alloc();
                continue;
            }
            LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
            throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
        }

        auto file = charset::FromWide( dirInfo->FileName );
        if ( file[0] == '.' )
            continue;
        auto path = m_path + file.get();
        if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
            m_dirs.emplace_back( m_fsFactory.createDirectory( path ) );
        else
            m_files.emplace_back( std::make_shared<File>( path ) );
    }
#endif
}

std::string Directory::toAbsolute( const std::string& path )
{
    TCHAR buff[MAX_PATH];
    auto wpath = charset::ToWide( path.c_str() );
    if ( GetFullPathName( wpath.get(), MAX_PATH, buff, nullptr ) == 0 )
    {
        LOG_ERROR( "Failed to convert ", path, " to absolute path" );
        std::system_error( GetLastError(), std::generic_category(), "Failed to convert to absolute path" );
    }
    auto upath = charset::FromWide( buff );
    return std::string( upath.get() );
}

}

}
<commit_msg>fs: win32: Directory: Use CreateFile2<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Directory.h"
#include "utils/Charsets.h"
#include "factory/IFileSystem.h"
#include "File.h"
#include "logging/Logger.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
#include <winapifamily.h>

namespace medialibrary
{

namespace fs
{

Directory::Directory(const std::string& path , factory::IFileSystem& fsFactory)
    : CommonDirectory( toAbsolute( path ), fsFactory )
{
}

void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
    WIN32_FIND_DATA f;
    auto pattern = m_path + '*';
    auto wpattern = charset::ToWide( pattern.c_str() );
    auto h = FindFirstFile( wpattern.get(), &f );
    if ( h == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to browse ", m_path );
        std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
    }
    do
    {
        auto file = charset::FromWide( f.cFileName );
        if ( file[0] == '.' )
            continue;
        auto path = m_path + file.get();
        if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
            m_dirs.emplace_back( m_fsFactory.createDirectory( path ) );
        else
            m_files.emplace_back( std::make_shared<File>( path ) );
    } while ( FindNextFile( h, &f ) != 0 );
    FindClose( h );
#else
    // We must remove the trailing /
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
    // «Do not use a trailing backslash (\), which indicates the root directory of a drive»
    assert( *m_path.rbegin() == '\\' );
    auto tmpPath = m_path.substr( 0, m_path.length() - 1 );
    auto wpath = charset::ToWide( tmpPath.c_str() );

    CREATEFILE2_EXTENDED_PARAMETERS params{};
    params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
    auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &params );
    if ( handle == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to open directory ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
    }

    std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
            decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );

    // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
    size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
    std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
                reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
                [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
    if ( dirInfo == nullptr )
        throw std::bad_alloc();

    while ( true )
    {
        auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
        if ( h == 0 )
        {
            auto error = GetLastError();
            if ( error == ERROR_FILE_NOT_FOUND )
                break;
            else if ( error == ERROR_MORE_DATA )
            {
                buffSize *= 2;
                dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
                if ( dirInfo == nullptr )
                    throw std::bad_alloc();
                continue;
            }
            LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
            throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
        }

        auto file = charset::FromWide( dirInfo->FileName );
        if ( file[0] == '.' )
            continue;
        auto path = m_path + file.get();
        if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
            m_dirs.emplace_back( m_fsFactory.createDirectory( path ) );
        else
            m_files.emplace_back( std::make_shared<File>( path ) );
    }
#endif
}

std::string Directory::toAbsolute( const std::string& path )
{
    TCHAR buff[MAX_PATH];
    auto wpath = charset::ToWide( path.c_str() );
    if ( GetFullPathName( wpath.get(), MAX_PATH, buff, nullptr ) == 0 )
    {
        LOG_ERROR( "Failed to convert ", path, " to absolute path" );
        std::system_error( GetLastError(), std::generic_category(), "Failed to convert to absolute path" );
    }
    auto upath = charset::FromWide( buff );
    return std::string( upath.get() );
}

}

}
<|endoftext|>


<commit_before>
#include "calib.hpp"
#include "cv.h"
#include "cxmisc.h"
#include "highgui.h"
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

namespace libcv
{
    CalibCam::CalibCam()
        : m_display(true), m_mx1(NULL), m_mx2(NULL), m_my1(NULL), m_my2(NULL)
    {
    }

    CalibCam::~CalibCam()
    {
        if(m_mx1 != NULL)
            cvReleaseMat(&m_mx1);
        if(m_mx2 != NULL)
            cvReleaseMat(&m_mx2);
        if(m_my1 != NULL)
            cvReleaseMat(&m_my1);
        if(m_my2 != NULL)
            cvReleaseMat(&m_my2);
    }

    bool CalibCam::load(const std::string& path)
    {
        std::string used;
        used = path + "/mx1.xml";
        m_mx1 = (CvMat*)cvLoad(used.c_str());
        used = path + "/mx2.xml";
        m_mx2 = (CvMat*)cvLoad(used.c_str());
        used = path + "/my1.xml";
        m_my1 = (CvMat*)cvLoad(used.c_str());
        used = path + "/my2.xml";
        m_my2 = (CvMat*)cvLoad(used.c_str());

        used = path + "/size";
        std::ifstream ifs(used.c_str());
        if(!ifs) {
            std::cout << "Couldn't load !" << std::endl;
            return false;
        }
        ifs >> m_imgSize.width >> m_imgSize.height;
        std::cout << "Size loaded : " << m_imgSize.width << "x" << m_imgSize.height << std::endl;
        return true;
    }

    bool CalibCam::save(const std::string& path) const
    {
        std::string used = path;
        used += "/mx1.xml";
        cvSave(used.c_str(), m_mx1, "mx1");
        used = path + "/mx2.xml";
        cvSave(used.c_str(), m_mx2, "mx2");
        used = path + "/my1.xml";
        cvSave(used.c_str(), m_my1, "my1");
        used = path + "/my2.xml";
        cvSave(used.c_str(), m_my2, "my2");
        used = path + "/size";
        std::ofstream ofs(used.c_str());
        if(!ofs) {
            std::cout << "Couldn't save !" << std::endl;
            return false;
        }
        ofs << m_imgSize.width << " " << m_imgSize.height << std::endl;
        std::cout << "Size saved : " << m_imgSize.width << "x" << m_imgSize.height << std::endl;

        return true;
    }

    void CalibCam::start(int nx, int ny, float size, CvSize img)
    {
        m_nx = nx;
        m_ny = ny;
        m_size = size;
        m_imgSize = img;
        m_frames = 0;

        if(m_mx1 != NULL)
            cvReleaseMat(&m_mx1);
        if(m_mx2 != NULL)
            cvReleaseMat(&m_mx2);
        if(m_my1 != NULL)
            cvReleaseMat(&m_my1);
        if(m_my2 != NULL)
            cvReleaseMat(&m_my2);
        m_mx1 = m_mx2 = m_my1 = m_my2 = NULL;
    }

    void CalibCam::end()
    {
        size_t nframes = m_frames;
        if(nframes == 0)
            return;
        int n = m_nx * m_ny;
        std::vector<CvPoint3D32f> objectPoints(nframes * m_nx * m_ny);

        /* Store normal coordinates of corners into the objectPoints list */
        for(int i = 0; i < m_nx; ++i) {
            for(int j = 0; j < m_ny; ++j)
                objectPoints[i*m_nx + j] = cvPoint3D32f(i * m_size, j * m_size, 0);
        }
        for(size_t i = 0; i < nframes; ++i)
            std::copy(objectPoints.begin(), objectPoints.begin() + n, objectPoints.begin() + i*n);

        /* Prepare some matrix */
        std::vector<int> npoints(nframes, n);
        int N = nframes * n;
        CvMat _objPoints  = cvMat(1, N, CV_32FC3, &objectPoints[0]);
        CvMat _imgPoints1 = cvMat(1, N, CV_32FC2, &m_corners[0][0]);
        CvMat _imgPoints2 = cvMat(1, N, CV_32FC2, &m_corners[1][0]);
        CvMat _npoints    = cvMat(1, npoints.size(), CV_32S, &npoints[0]);

        double M1[3][3], M2[3][3], D1[5], D2[5];
        double R[3][2], T[3], E[3][3], F[3][3];
        double Q[4][4];
        CvMat _M1 = cvMat(3, 3, CV_64F, M1);
        CvMat _M2 = cvMat(3, 3, CV_64F, M2);
        CvMat _D1 = cvMat(1, 5, CV_64F, D1);
        CvMat _D2 = cvMat(1, 5, CV_64F, D2);
        CvMat _R  = cvMat(3, 3, CV_64F, R);
        CvMat _T  = cvMat(3, 1, CV_64F, T);
        CvMat _E  = cvMat(3, 3, CV_64F, E);
        CvMat _F  = cvMat(3, 3, CV_64F, F);
        CvMat _Q  = cvMat(4, 4, CV_64F, Q);
        cvSetIdentity(&_M1);
        cvSetIdentity(&_M2);
        cvZero(&_D1);
        cvZero(&_D2);

        /* Calibrate the stereo cameras */
        std::cout << "Calibrating ..." << std::endl;
        cvStereoCalibrate(&_objPoints, &_imgPoints1,
                &_imgPoints2, &_npoints,
                &_M1, &_D1, &_M2, &_D2,
                m_imgSize, &_R, &_T, &_E, &_F,
                cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS,
                    100, 1e-5),
                CV_CALIB_FIX_ASPECT_RATIO  +
                CV_CALIB_ZERO_TANGENT_DIST +
                CV_CALIB_SAME_FOCAL_LENGTH);
        std::cout << "Done." << std::endl;

        /* Compute m_m{x,y}{1,2} */
        m_mx1 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        m_my1 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        m_mx2 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        m_my2 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        double R1[3][3], R2[3][3], P1[3][4], P2[3][4];
        CvMat _R1 = cvMat(3, 3, CV_64F, R1);
        CvMat _R2 = cvMat(3, 3, CV_64F, R2);
        CvMat _P1 = cvMat(3, 4, CV_64F, P1);
        CvMat _P2 = cvMat(3, 4, CV_64F, P2);
        cvStereoRectify(&_M1, &_M2, &_D1, &_D2, m_imgSize,
                &_R, &_T,
                &_R1, &_R2, &_P1, &_P2, &_Q,
                0);
        cvInitUndistortRectifyMap(&_M1, &_D1, &_R1, &_P1, m_mx1, m_my1);
        cvInitUndistortRectifyMap(&_M2, &_D2, &_R2, &_P2, m_mx2, m_my2);
    }

    bool CalibCam::compute(IplImage* i1, IplImage* i2)
    {
        std::vector<CvPoint2D32f> ret1 = computeOne(i1, "Left");
        std::vector<CvPoint2D32f> ret2 = computeOne(i2, "Right");
        if(ret1.empty() || ret2.empty())
            return false;

        size_t N = m_corners[0].size();
        m_corners[0].resize(N + m_nx * m_ny, cvPoint2D32f(0,0));
        std::copy(ret1.begin(), ret1.end(), m_corners[0].begin() + N);
        N = m_corners[1].size();
        m_corners[1].resize(N + m_nx * m_ny, cvPoint2D32f(0,0));
        std::copy(ret2.begin(), ret2.end(), m_corners[1].begin() + N);
        ++m_frames;
        return true;
    }

    std::vector<CvPoint2D32f> CalibCam::computeOne(IplImage* img, const std::string& win)
    {
        /* Find the chessboard corners */
        std::vector<CvPoint2D32f> temp(m_nx * m_ny);
        int count = 0;
        int result = cvFindChessboardCorners(img, cvSize(m_nx, m_ny),
                &temp[0], &count,
                CV_CALIB_CB_ADAPTIVE_THRESH |
                CV_CALIB_CB_NORMALIZE_IMAGE);
        if(!result) {
            temp.clear();
            return temp;
        }

        cvFindCornerSubPix(img, &temp[0], count,
                cvSize(11, 11), cvSize(-1, -1),
                cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS,
                    30, 0.01));

        if(m_display) {
            cvDrawChessboardCorners(img, cvSize(m_nx, m_ny), &temp[0],
                    count, result);
            cvShowImage(win.c_str(), img);
        }

        return temp;
    }

}

<commit_msg>Improved calib algorithm.<commit_after>
#include "calib.hpp"
#include "cv.h"
#include "cxmisc.h"
#include "highgui.h"
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

namespace libcv
{
    CalibCam::CalibCam()
        : m_display(true), m_mx1(NULL), m_mx2(NULL), m_my1(NULL), m_my2(NULL)
    {
    }

    CalibCam::~CalibCam()
    {
        if(m_mx1 != NULL)
            cvReleaseMat(&m_mx1);
        if(m_mx2 != NULL)
            cvReleaseMat(&m_mx2);
        if(m_my1 != NULL)
            cvReleaseMat(&m_my1);
        if(m_my2 != NULL)
            cvReleaseMat(&m_my2);
    }

    bool CalibCam::load(const std::string& path)
    {
        std::string used;
        used = path + "/mx1.xml";
        m_mx1 = (CvMat*)cvLoad(used.c_str());
        used = path + "/mx2.xml";
        m_mx2 = (CvMat*)cvLoad(used.c_str());
        used = path + "/my1.xml";
        m_my1 = (CvMat*)cvLoad(used.c_str());
        used = path + "/my2.xml";
        m_my2 = (CvMat*)cvLoad(used.c_str());

        used = path + "/size";
        std::ifstream ifs(used.c_str());
        if(!ifs) {
            std::cout << "Couldn't load !" << std::endl;
            return false;
        }
        ifs >> m_imgSize.width >> m_imgSize.height;
        std::cout << "Size loaded : " << m_imgSize.width << "x" << m_imgSize.height << std::endl;
        return true;
    }

    bool CalibCam::save(const std::string& path) const
    {
        std::string used = path;
        used += "/mx1.xml";
        cvSave(used.c_str(), m_mx1, "mx1");
        used = path + "/mx2.xml";
        cvSave(used.c_str(), m_mx2, "mx2");
        used = path + "/my1.xml";
        cvSave(used.c_str(), m_my1, "my1");
        used = path + "/my2.xml";
        cvSave(used.c_str(), m_my2, "my2");
        used = path + "/size";
        std::ofstream ofs(used.c_str());
        if(!ofs) {
            std::cout << "Couldn't save !" << std::endl;
            return false;
        }
        ofs << m_imgSize.width << " " << m_imgSize.height << std::endl;
        std::cout << "Size saved : " << m_imgSize.width << "x" << m_imgSize.height << std::endl;

        return true;
    }

    void CalibCam::start(int nx, int ny, float size, CvSize img)
    {
        m_nx = nx;
        m_ny = ny;
        m_size = size;
        m_imgSize = img;
        m_frames = 0;

        if(m_mx1 != NULL)
            cvReleaseMat(&m_mx1);
        if(m_mx2 != NULL)
            cvReleaseMat(&m_mx2);
        if(m_my1 != NULL)
            cvReleaseMat(&m_my1);
        if(m_my2 != NULL)
            cvReleaseMat(&m_my2);
        m_mx1 = m_mx2 = m_my1 = m_my2 = NULL;
    }

    void CalibCam::end()
    {
        size_t nframes = m_frames;
        if(nframes == 0)
            return;
        int n = m_nx * m_ny;
        std::vector<CvPoint3D32f> objectPoints(nframes * m_nx * m_ny);

        /* Store normal coordinates of corners into the objec tPoints list */
        for(int i = 0; i < m_ny; ++i) {
            for(int j = 0; j < m_nx; ++j)
                objectPoints[i*m_nx + j] = cvPoint3D32f(i * m_size, j * m_size, 0);
        }
        for(size_t i = 1; i < nframes; ++i)
            std::copy(objectPoints.begin(), objectPoints.begin() + n, objectPoints.begin() + i*n);

        /* Prepare some matrix */
        std::vector<int> npoints(nframes, n);
        int N = nframes * n;
        CvMat _objPoints  = cvMat(1, N,       CV_32FC3, &objectPoints[0]);
        CvMat _imgPoints1 = cvMat(1, N,       CV_32FC2, &m_corners[0][0]);
        CvMat _imgPoints2 = cvMat(1, N,       CV_32FC2, &m_corners[1][0]);
        CvMat _npoints    = cvMat(1, nframes, CV_32S, &npoints[0]);

        double M1[3][3], M2[3][3], D1[5],   D2[5];
        double R[3][2],  T[3],     E[3][3], F[3][3];
        double Q[4][4];
        CvMat _M1 = cvMat(3, 3, CV_64F, M1);
        CvMat _M2 = cvMat(3, 3, CV_64F, M2);
        CvMat _D1 = cvMat(1, 5, CV_64F, D1);
        CvMat _D2 = cvMat(1, 5, CV_64F, D2);
        CvMat _R  = cvMat(3, 3, CV_64F, R);
        CvMat _T  = cvMat(3, 1, CV_64F, T);
        CvMat _E  = cvMat(3, 3, CV_64F, E);
        CvMat _F  = cvMat(3, 3, CV_64F, F);
        CvMat _Q  = cvMat(4, 4, CV_64F, Q);
        cvSetIdentity(&_M1);
        cvSetIdentity(&_M2);
        cvZero(&_D1);
        cvZero(&_D2);

        /* Calibrate the stereo cameras */
        std::cout << "Calibrating ..." << std::endl;
        cvStereoCalibrate(&_objPoints, &_imgPoints1,
                &_imgPoints2, &_npoints,
                &_M1, &_D1, &_M2, &_D2,
                m_imgSize, &_R, &_T, &_E, &_F,
                cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS,
                    100, 1e-5),
                CV_CALIB_FIX_ASPECT_RATIO  +
                CV_CALIB_ZERO_TANGENT_DIST +
                CV_CALIB_SAME_FOCAL_LENGTH);
        std::cout << "Done." << std::endl;

        /* Compute m_m{x,y}{1,2} */
        m_mx1 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        m_my1 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        m_mx2 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        m_my2 = cvCreateMat(m_imgSize.height, m_imgSize.width, CV_32F);
        double R1[3][3], R2[3][3], P1[3][4], P2[3][4];
        CvMat _R1 = cvMat(3, 3, CV_64F, R1);
        CvMat _R2 = cvMat(3, 3, CV_64F, R2);
        CvMat _P1 = cvMat(3, 4, CV_64F, P1);
        CvMat _P2 = cvMat(3, 4, CV_64F, P2);
        cvStereoRectify(&_M1, &_M2, &_D1, &_D2, m_imgSize,
                &_R, &_T,
                &_R1, &_R2, &_P1, &_P2, &_Q,
                0);
        cvInitUndistortRectifyMap(&_M1, &_D1, &_R1, &_P1, m_mx1, m_my1);
        cvInitUndistortRectifyMap(&_M2, &_D2, &_R2, &_P2, m_mx2, m_my2);
    }

    bool CalibCam::compute(IplImage* i1, IplImage* i2)
    {
        std::vector<CvPoint2D32f> ret1 = computeOne(i1, "Left");
        std::vector<CvPoint2D32f> ret2 = computeOne(i2, "Right");
        if(ret1.empty() || ret2.empty())
            return false;

        size_t N = m_corners[0].size();
        m_corners[0].resize(N + m_nx * m_ny, cvPoint2D32f(0,0));
        std::copy(ret1.begin(), ret1.end(), m_corners[0].begin() + N);
        N = m_corners[1].size();
        m_corners[1].resize(N + m_nx * m_ny, cvPoint2D32f(0,0));
        std::copy(ret2.begin(), ret2.end(), m_corners[1].begin() + N);
        ++m_frames;
        return true;
    }

    std::vector<CvPoint2D32f> CalibCam::computeOne(IplImage* img, const std::string& win)
    {
        /* Find the chessboard corners */
        std::vector<CvPoint2D32f> temp(m_nx * m_ny);
        int count = 0;
        int result = cvFindChessboardCorners(img, cvSize(m_nx, m_ny),
                &temp[0], &count,
                CV_CALIB_CB_ADAPTIVE_THRESH |
                CV_CALIB_CB_NORMALIZE_IMAGE);
        if(!result || count != m_nx*m_ny) {
            temp.clear();
            return temp;
        }

        cvFindCornerSubPix(img, &temp[0], count,
                cvSize(11, 11), cvSize(-1, -1),
                cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS,
                    30, 0.01));

        if(m_display) {
            cvDrawChessboardCorners(img, cvSize(m_nx, m_ny), &temp[0],
                    count, result);
            cvShowImage(win.c_str(), img);
        }

        return temp;
    }

}

<|endoftext|>


<commit_before>#include <person.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    auto people = std::vector<Person>{
        {"Peter", false, 56},
        {"Martha", true, 24},
        {"Jane", true, 52},
        {"David", false, 84},
        {"Tom", false, 32},
        {"Rose", true, 31}
    };

    auto females = std::vector<Person>{};

    std::copy_if(people.cbegin(), people.cend(),
                 std::back_inserter(females),
                 [](const Person& person) {
                     return person.isFemale();
                 });

    std::cout << "Female person names: \n";
    for (auto person: females) {
        std::cout << person.name() << '\n';
    }
}
<commit_msg>functional_objects: C++14 generalized lambda captures example<commit_after>#include <person.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <memory>
#include <vector>

class Session {
public:
    Session()
    {
    }
    static std::unique_ptr<Session> create_session()
    {
        return std::make_unique<Session>();
    }
    unsigned id() const { return m_id; }
private:
    unsigned m_id = 0;
};

std::ostream& operator<<(std::ostream& out, const Session& s)
{
    return out << s.id();
}

class Response {
public:
    Response(const std::string& data)
        : m_data{data}
    {
    }
    std::string data() const { return m_data; }
private:
    std::string m_data;
};

class Request {
public:
    Request(const std::string& r, unsigned id)
        : m_r{r}
        , m_id{id}
    {
    }

    template<typename Handler>
    void on_completed(Handler h)
    {
        h(Response{"ok"});
    }
private:
    std::string m_r;
    unsigned m_id;
};

std::ostream& operator<<(std::ostream& out, const Response& r)
{
    return out << r.data();
}

class Server {
public:
    Request request(const std::string& r, unsigned id)
    {
        return Request(r, id);
    }
};

unsigned current_time()
{
    static unsigned time = 0;
    return time++;
}

int main()
{
    auto people = std::vector<Person>{
        {"Peter", false, 56},
        {"Martha", true, 24},
        {"Jane", true, 52},
        {"David", false, 84},
        {"Tom", false, 32},
        {"Rose", true, 31}
    };

    auto females = std::vector<Person>{};

    std::copy_if(people.cbegin(), people.cend(),
                 std::back_inserter(females),
                 [](const Person& person) {
                     return person.isFemale();
                 });

    std::cout << "Female person names: \n";
    for (auto person: females) {
        std::cout << person.name() << '\n';
    }

    // C++14: generalized lambda captures
    auto server = Server{};
    auto session = Session::create_session();
    auto request = server.request("GET /", session->id());

    request.on_completed(
        [session = std::move(session),
         time = current_time()
        ]
        (const Response& response)
        {
            std::cout << "Got response: " << response
                      << " for session: " << *session
                      << " the request took: "
                      << (current_time() - time)
                      << " milliseconds"
                      << '\n';
        }
    );
}
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_FILESYSTEM_HH
#define DUNE_STUFF_FILESYSTEM_HH

#include "debug.hh"
#include <string>
#include <fstream>

#include <dune/fem/io/file/iointerface.hh>

namespace Stuff {

//! strip filename from \path if present, return empty string if only filename present
std::string pathOnly ( std::string path )
{
	if (!path.empty())
	{
		char buf[1024];//not _exactly_ sure this is max path length, but it's suggested in wx source

		// Local copy
		strcpy (buf, path.c_str() );

		int l = path.length();
		int i = l - 1;

		// Search backward for a backward or forward slash
		while (i > -1)
		{
			if ( ( path[i] == '/' ) || ( path[i] == '\\' ) )
			{
				// Don't return an empty string
				if (i == 0)
					i ++;
				buf[i] = 0;
				return std::string(buf);
			}
			i --;
		}
	}
	return std::string();
}

//! return everything after the last slash
std::string filenameOnly( const std::string& path )
{
	size_t last_slash_position = path.find_last_of('/');
	return path.substr( last_slash_position + 1 );
}

//! may include filename, will be stripped
void testCreateDirectory( const std::string path ) {
	std::string pathonly = pathOnly( path );
	Dune::IOInterface::createPath( pathonly );
}

//! read a file and output all lines containing filter string to a stream
template < class Stream >
void fileToStreamFiltered( Stream& stream, std::string filename, std::string filter )
{
	std::ifstream file( filename.c_str(), std::ifstream::in );
	ASSERT_EXCEPTION( file.good(), filename.c_str() );
	while ( file.good() ) {
		std::string line;
		std::getline ( file, line );
		if ( line.find( filter ) != std::string::npos )
			stream << line << "\n";
	}
	file.close();
}

//! output programs mem usage stats by reading from /proc
template < class Stream >
void meminfo( Stream& stream )
{
	stream << "Memory info: \n";
	stream.Resume();
	pid_t pid = getpid();
	std::stringstream filename;
	filename << "/proc/" << pid << "/status";

	fileToStreamFiltered( stream, filename.str(), "Vm" );
	fileToStreamFiltered( stream, "/proc/meminfo", "Mem" );
	stream << "------------ \n\n" << std::endl;
}

} //end namespace Stuff

#endif // DUNE_STUFF_FILESYSTEM_HH
<commit_msg>filesystem fix<commit_after>#ifndef DUNE_STUFF_FILESYSTEM_HH
#define DUNE_STUFF_FILESYSTEM_HH

#include "debug.hh"
#include <string>
#include <fstream>

#include <dune/fem/io/file/iointerface.hh>

namespace Stuff {

//! strip filename from \path if present, return empty string if only filename present
std::string pathOnly ( std::string path )
{
	if (!path.empty())
	{
		char buf[1024];//not _exactly_ sure this is max path length, but it's suggested in wx source

		// Local copy
		strcpy (buf, path.c_str() );

		int l = path.length();
		int i = l - 1;

		// Search backward for a backward or forward slash
		while (i > -1)
		{
			if ( ( path[i] == '/' ) || ( path[i] == '\\' ) )
			{
				// Don't return an empty string
				if (i == 0)
					i ++;
				buf[i] = 0;
				return std::string(buf);
			}
			i --;
		}
	}
	return std::string();
}

//! return everything after the last slash
std::string filenameOnly( const std::string& path )
{
	size_t last_slash_position = path.find_last_of('/');
	return path.substr( last_slash_position + 1 );
}

//! may include filename, will be stripped
void testCreateDirectory( const std::string path ) {
	std::string pathonly = pathOnly( path );
	if( ! pathonly.empty() )
		Dune::IOInterface::createPath( pathonly );
}

//! read a file and output all lines containing filter string to a stream
template < class Stream >
void fileToStreamFiltered( Stream& stream, std::string filename, std::string filter )
{
	std::ifstream file( filename.c_str(), std::ifstream::in );
	ASSERT_EXCEPTION( file.good(), filename.c_str() );
	while ( file.good() ) {
		std::string line;
		std::getline ( file, line );
		if ( line.find( filter ) != std::string::npos )
			stream << line << "\n";
	}
	file.close();
}

//! output programs mem usage stats by reading from /proc
template < class Stream >
void meminfo( Stream& stream )
{
	stream << "Memory info: \n";
	stream.Resume();
	pid_t pid = getpid();
	std::stringstream filename;
	filename << "/proc/" << pid << "/status";

	fileToStreamFiltered( stream, filename.str(), "Vm" );
	fileToStreamFiltered( stream, "/proc/meminfo", "Mem" );
	stream << "------------ \n\n" << std::endl;
}

} //end namespace Stuff

#endif // DUNE_STUFF_FILESYSTEM_HH
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "repair/repair.hh"
#include "message/messaging_service.hh"
#include <vector>
#include <algorithm>
#include <random>

extern logging::logger rlogger;

struct shard_config {
    unsigned shard;
    unsigned shard_count;
    unsigned ignore_msb;
    sstring partitioner_name;
};

static const std::vector<row_level_diff_detect_algorithm>& suportted_diff_detect_algorithms() {
    static std::vector<row_level_diff_detect_algorithm> _algorithms = {
        row_level_diff_detect_algorithm::send_full_set,
    };
    return _algorithms;
};

static row_level_diff_detect_algorithm get_common_diff_detect_algorithm(const std::vector<gms::inet_address>& nodes) {
    std::vector<std::vector<row_level_diff_detect_algorithm>> nodes_algorithms(nodes.size());
    parallel_for_each(boost::irange(size_t(0), nodes.size()), [&nodes_algorithms, &nodes] (size_t idx) {
        return netw::get_local_messaging_service().send_repair_get_diff_algorithms(netw::messaging_service::msg_addr(nodes[idx])).then(
                [&nodes_algorithms, &nodes, idx] (std::vector<row_level_diff_detect_algorithm> algorithms) {
            std::sort(algorithms.begin(), algorithms.end());
            nodes_algorithms[idx] = std::move(algorithms);
            rlogger.trace("Got node_algorithms={}, from node={}", nodes_algorithms[idx], nodes[idx]);
        });
    }).get();

    auto common_algorithms = suportted_diff_detect_algorithms();
    for (auto& algorithms : nodes_algorithms) {
        std::sort(common_algorithms.begin(), common_algorithms.end());
        std::vector<row_level_diff_detect_algorithm> results;
        std::set_intersection(algorithms.begin(), algorithms.end(),
                common_algorithms.begin(), common_algorithms.end(),
                std::back_inserter(results));
        common_algorithms = std::move(results);
    }
    rlogger.trace("peer_algorithms={}, local_algorithms={}, common_diff_detect_algorithms={}",
            nodes_algorithms, suportted_diff_detect_algorithms(), common_algorithms);
    if (common_algorithms.empty()) {
        throw std::runtime_error("Can not find row level repair diff detect algorithm");
    }
    return common_algorithms.back();
}

static uint64_t get_random_seed() {
    static thread_local std::default_random_engine random_engine{std::random_device{}()};
    static thread_local std::uniform_int_distribution<uint64_t> random_dist{};
    return random_dist(random_engine);
}
<commit_msg>repair: Add decorated_key_with_hash<commit_after>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "repair/repair.hh"
#include "message/messaging_service.hh"
#include "xx_hasher.hh"
#include "dht/i_partitioner.hh"
#include <vector>
#include <algorithm>
#include <random>

extern logging::logger rlogger;

struct shard_config {
    unsigned shard;
    unsigned shard_count;
    unsigned ignore_msb;
    sstring partitioner_name;
};

static const std::vector<row_level_diff_detect_algorithm>& suportted_diff_detect_algorithms() {
    static std::vector<row_level_diff_detect_algorithm> _algorithms = {
        row_level_diff_detect_algorithm::send_full_set,
    };
    return _algorithms;
};

static row_level_diff_detect_algorithm get_common_diff_detect_algorithm(const std::vector<gms::inet_address>& nodes) {
    std::vector<std::vector<row_level_diff_detect_algorithm>> nodes_algorithms(nodes.size());
    parallel_for_each(boost::irange(size_t(0), nodes.size()), [&nodes_algorithms, &nodes] (size_t idx) {
        return netw::get_local_messaging_service().send_repair_get_diff_algorithms(netw::messaging_service::msg_addr(nodes[idx])).then(
                [&nodes_algorithms, &nodes, idx] (std::vector<row_level_diff_detect_algorithm> algorithms) {
            std::sort(algorithms.begin(), algorithms.end());
            nodes_algorithms[idx] = std::move(algorithms);
            rlogger.trace("Got node_algorithms={}, from node={}", nodes_algorithms[idx], nodes[idx]);
        });
    }).get();

    auto common_algorithms = suportted_diff_detect_algorithms();
    for (auto& algorithms : nodes_algorithms) {
        std::sort(common_algorithms.begin(), common_algorithms.end());
        std::vector<row_level_diff_detect_algorithm> results;
        std::set_intersection(algorithms.begin(), algorithms.end(),
                common_algorithms.begin(), common_algorithms.end(),
                std::back_inserter(results));
        common_algorithms = std::move(results);
    }
    rlogger.trace("peer_algorithms={}, local_algorithms={}, common_diff_detect_algorithms={}",
            nodes_algorithms, suportted_diff_detect_algorithms(), common_algorithms);
    if (common_algorithms.empty()) {
        throw std::runtime_error("Can not find row level repair diff detect algorithm");
    }
    return common_algorithms.back();
}

static uint64_t get_random_seed() {
    static thread_local std::default_random_engine random_engine{std::random_device{}()};
    static thread_local std::uniform_int_distribution<uint64_t> random_dist{};
    return random_dist(random_engine);
}

class decorated_key_with_hash {
public:
    dht::decorated_key dk;
    repair_hash hash;
    decorated_key_with_hash(const schema& s, dht::decorated_key key, uint64_t seed)
        : dk(key) {
        xx_hasher h(seed);
        feed_hash(h, dk.key(), s);
        hash = repair_hash(h.finalize_uint64());
    }
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DAVTypes.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:35:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DAVTYPES_HXX_
#define _DAVTYPES_HXX_

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

namespace webdav_ucp
{
/* RFC 2518

15.1 Class 1

   A class 1 compliant resource MUST meet all "MUST" requirements in all
   sections of this document.

   Class 1 compliant resources MUST return, at minimum, the value "1" in
   the DAV header on all responses to the OPTIONS method.

15.2 Class 2

   A class 2 compliant resource MUST meet all class 1 requirements and
   support the LOCK method, the supportedlock property, the
   lockdiscovery property, the Time-Out response header and the Lock-
   Token request header.  A class "2" compliant resource SHOULD also
   support the Time-Out request header and the owner XML element.

   Class 2 compliant resources MUST return, at minimum, the values "1"
   and "2" in the DAV header on all responses to the OPTIONS method.
*/

struct DAVCapabilities
{
    bool class1;
    bool class2;
    bool executable; // supports "executable" property (introduced by mod_dav)

    DAVCapabilities() : class1( false ), class2( false ), executable( false ) {}
};

enum Depth { DAVZERO = 0, DAVONE = 1, DAVINFINITY = -1 };

enum ProppatchOperation { PROPSET = 0, PROPREMOVE = 1 };

struct ProppatchValue
{
    ProppatchOperation       operation;
    rtl::OUString            name;
    com::sun::star::uno::Any value;

    ProppatchValue( const ProppatchOperation o,
                    const rtl::OUString & n,
                    const com::sun::star::uno::Any & v )
    : operation( o ), name( n ), value( v ) {}
};

} // namespace webdav_ucp

#endif // _DAVTYPES_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.6.138); FILE MERGED 2008/04/01 16:02:25 thb 1.6.138.2: #i85898# Stripping all external header guards 2008/03/31 15:30:30 rt 1.6.138.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: DAVTypes.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DAVTYPES_HXX_
#define _DAVTYPES_HXX_

#include <rtl/ustring.hxx>
#include <com/sun/star/uno/Any.hxx>

namespace webdav_ucp
{
/* RFC 2518

15.1 Class 1

   A class 1 compliant resource MUST meet all "MUST" requirements in all
   sections of this document.

   Class 1 compliant resources MUST return, at minimum, the value "1" in
   the DAV header on all responses to the OPTIONS method.

15.2 Class 2

   A class 2 compliant resource MUST meet all class 1 requirements and
   support the LOCK method, the supportedlock property, the
   lockdiscovery property, the Time-Out response header and the Lock-
   Token request header.  A class "2" compliant resource SHOULD also
   support the Time-Out request header and the owner XML element.

   Class 2 compliant resources MUST return, at minimum, the values "1"
   and "2" in the DAV header on all responses to the OPTIONS method.
*/

struct DAVCapabilities
{
    bool class1;
    bool class2;
    bool executable; // supports "executable" property (introduced by mod_dav)

    DAVCapabilities() : class1( false ), class2( false ), executable( false ) {}
};

enum Depth { DAVZERO = 0, DAVONE = 1, DAVINFINITY = -1 };

enum ProppatchOperation { PROPSET = 0, PROPREMOVE = 1 };

struct ProppatchValue
{
    ProppatchOperation       operation;
    rtl::OUString            name;
    com::sun::star::uno::Any value;

    ProppatchValue( const ProppatchOperation o,
                    const rtl::OUString & n,
                    const com::sun::star::uno::Any & v )
    : operation( o ), name( n ), value( v ) {}
};

} // namespace webdav_ucp

#endif // _DAVTYPES_HXX_
<|endoftext|>


<commit_before>/*
    Copyright 2010 Marco Martin <notmart@gmail.com>

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "pagedproxymodel.h"

#include <QDebug>

PagedProxyModel::PagedProxyModel(QObject *parent)
    : QAbstractProxyModel(parent),
      m_pageSize(16),
      m_currentPage(0)
{
}

PagedProxyModel::~PagedProxyModel()
{
}

int PagedProxyModel::totalPages()
{
    if (!sourceModel()) {
        return 0;
    }

    return sourceModel()->rowCount() / m_pageSize;
}

void PagedProxyModel::setCurrentPage(const int page)
{
    if (m_currentPage == page) {
        return;
    }

    beginResetModel();
    m_currentPage = page;
    endResetModel();
}

int PagedProxyModel::currentPage() const
{
    return m_currentPage;
}

void PagedProxyModel::setPageSize(const int size)
{
    if (m_pageSize == size) {
        return;
    }

    beginResetModel();
    m_pageSize = size;
    endResetModel();
}

int PagedProxyModel::pageSize() const
{
    return m_pageSize;
}

void PagedProxyModel::setSourceModelObject(QObject *source)
{
    QAbstractItemModel *model = qobject_cast<QAbstractItemModel *>(source);
    if (!model || model == sourceModel()) {
        return;
    }

    bool reset = false;
    if (sourceModel()) {
        reset = true;
        disconnect(sourceModel(), 0, this, 0);
        beginResetModel();
    }

    connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT(sourceDataChanged(QModelIndex,QModelIndex)));

    connect(model,  SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
            this, SLOT(sourceRowsAboutToBeInserted(QModelIndex,int,int)) );
    connect(model,  SIGNAL(rowsInserted(QModelIndex,int,int)),
            this, SLOT(sourceRowsInserted(QModelIndex,int,int)) );
    connect(model,  SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
            this, SLOT(sourceRowsAboutToBeRemoved(QModelIndex,int,int)) );
    connect(model,  SIGNAL(rowsRemoved(QModelIndex,int,int)),
            this, SLOT(sourceRowsRemoved(QModelIndex,int,int)) );

    connect(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
            this, SLOT(sourceRowsMoved(QModelIndex,int,int,QModelIndex,int)));

    connect(model, SIGNAL(modelAboutToBeReset()), this, SIGNAL(modelAboutToBeReset()));
    connect(model, SIGNAL(modelReset()), this, SIGNAL(modelReset()));
    connect(model, SIGNAL(layoutChanged()), this, SIGNAL(modelReset()));

    setSourceModel(model);

    if (reset) {
        endResetModel();
    }
}

QObject *PagedProxyModel::sourceModelObject() const
{
    return sourceModel();
}

void PagedProxyModel::sourceDataChanged(const QModelIndex &from, const QModelIndex &to)
{
    emit dataChanged(mapFromSource(from), mapFromSource(to));
}

void PagedProxyModel::sourceRowsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
{
    const int pageStart = (m_currentPage*m_pageSize);
    int newStart = qMin(m_pageSize, qMax(0, sourceStart - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (sourceEnd - sourceStart));
    int newDestinationRow = qMin(m_pageSize, qMax(0, destinationRow - pageStart));

    emit beginMoveRows(sourceParent, newStart, newEnd, destinationParent, newDestinationRow);
    endMoveRows();
}

void PagedProxyModel::sourceRowsAboutToBeInserted( const QModelIndex & parentIdx, int start, int end )
{
    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    //insert in pages bigger than us, not interested
    if (start > pageEnd) {
        return;
    }

    //FIXME: proper indexes should be calculated
    beginResetModel();
    return;

    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (end - start));

    m_oldRowCount = rowCount();
    //insert only the ones that are beyond the count
    if (newEnd > m_oldRowCount) {
        beginInsertRows(parentIdx, rowCount() - newEnd, newEnd );
    }
}

void PagedProxyModel::sourceRowsInserted( const QModelIndex& parentIdx, int start, int end )
{
    Q_UNUSED( parentIdx );

    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    if (start > pageEnd) {
        return;
    }

    //FIXME: proper mapped indexes should be calculated
    endResetModel();
    return;

    if (rowCount() > m_oldRowCount) {
        endInsertRows();
    }
    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (end - start));

    if (newStart <= m_oldRowCount) {
        emit dataChanged(PagedProxyModel::index(newStart, 0),
                         PagedProxyModel::index(qMin(newEnd, m_oldRowCount), 0));
    }
}

void PagedProxyModel::sourceRowsAboutToBeRemoved( const QModelIndex & parentIdx, int start, int end )
{
    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    if (start > pageEnd) {
        return;
    }

    //FIXME: proper mapped indexes should be calculated
    beginResetModel();
    return;

    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, qMax(0, end - pageStart));

    m_oldRowCount = rowCount();
    //insert only the ones that are beyond the count
    if (newEnd < m_oldRowCount) {
        beginRemoveRows(parentIdx, newStart, newEnd );
    }
}

void PagedProxyModel::sourceRowsRemoved( const QModelIndex& parentIdx, int start, int end )
{
    Q_UNUSED( parentIdx );

    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    if (start > pageEnd) {
        return;
    }

    //FIXME: proper mapped indexes should be calculated
    endResetModel();
    return;

    if (rowCount() < m_oldRowCount) {
        endRemoveRows();
    }
    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (end - start));

    if (sourceModel()->rowCount() - pageStart > rowCount()) {
        emit dataChanged(PagedProxyModel::index(newStart, 0),
                         PagedProxyModel::index(qMin((sourceModel()->rowCount() - pageStart), qMin(newEnd, m_oldRowCount)), 0));
    }
}

int PagedProxyModel::rowCount(const QModelIndex &parent) const
{
    if (!sourceModel()) {
        return 0;
    }

    return qMin(m_pageSize, (sourceModel()->rowCount(parent)-m_currentPage*m_pageSize));
}

QVariant PagedProxyModel::data(const QModelIndex &index, int role) const
{
    if (!sourceModel()) {
        return QVariant();
    }

    return sourceModel()->data(PagedProxyModel::index(index.row()+ (m_currentPage*m_pageSize), index.column(), QModelIndex()), role);
}

QModelIndex PagedProxyModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!sourceModel()) {
        return QModelIndex();
    }

    return sourceModel()->index(row, column, parent);
}

QModelIndex PagedProxyModel::parent(const QModelIndex &index) const
{
    Q_UNUSED(index)
    return QModelIndex();
}

QModelIndex PagedProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
{
    if (!sourceModel()) {
        return QModelIndex();
    }

    return sourceModel()->index(sourceIndex.row() - (m_currentPage*m_pageSize), sourceIndex.column(), QModelIndex());
}

QModelIndex PagedProxyModel::mapToSource(const QModelIndex &proxyIndex) const
{
    if (!sourceModel()) {
        return QModelIndex();
    }

    return sourceModel()->index(proxyIndex.row() + (m_currentPage*m_pageSize), proxyIndex.column(), QModelIndex());
}

int PagedProxyModel::columnCount(const QModelIndex &index) const
{
    if (!sourceModel()) {
        return 0;
    }
    return sourceModel()->columnCount(index);
}

#include "pagedproxymodel.moc"
<commit_msg>Port to the new signal and slot syntax<commit_after>/*
    Copyright 2010 Marco Martin <notmart@gmail.com>

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "pagedproxymodel.h"

#include <QDebug>

PagedProxyModel::PagedProxyModel(QObject *parent)
    : QAbstractProxyModel(parent),
      m_pageSize(16),
      m_currentPage(0)
{
}

PagedProxyModel::~PagedProxyModel()
{
}

int PagedProxyModel::totalPages()
{
    if (!sourceModel()) {
        return 0;
    }

    return sourceModel()->rowCount() / m_pageSize;
}

void PagedProxyModel::setCurrentPage(const int page)
{
    if (m_currentPage == page) {
        return;
    }

    beginResetModel();
    m_currentPage = page;
    endResetModel();
}

int PagedProxyModel::currentPage() const
{
    return m_currentPage;
}

void PagedProxyModel::setPageSize(const int size)
{
    if (m_pageSize == size) {
        return;
    }

    beginResetModel();
    m_pageSize = size;
    endResetModel();
}

int PagedProxyModel::pageSize() const
{
    return m_pageSize;
}

void PagedProxyModel::setSourceModelObject(QObject *source)
{
    QAbstractItemModel *model = qobject_cast<QAbstractItemModel *>(source);
    if (!model || model == sourceModel()) {
        return;
    }

    bool reset = false;
    if (sourceModel()) {
        reset = true;
        disconnect(sourceModel(), 0, this, 0);
        beginResetModel();
    }

    connect(model, &QAbstractItemModel::dataChanged, this, &PagedProxyModel::sourceDataChanged);

    connect(model, &QAbstractItemModel::rowsAboutToBeInserted, this, &PagedProxyModel::sourceRowsAboutToBeInserted);
    connect(model, &QAbstractItemModel::rowsInserted, this, &PagedProxyModel::sourceRowsInserted);
    connect(model, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PagedProxyModel::sourceRowsAboutToBeRemoved);
    connect(model, &QAbstractItemModel::rowsRemoved, this, &PagedProxyModel::sourceRowsRemoved);

    connect(model, &QAbstractItemModel::rowsMoved, this, &PagedProxyModel::sourceRowsMoved);

    connect(model, &QAbstractItemModel::modelAboutToBeReset, this, &PagedProxyModel::modelAboutToBeReset);
    connect(model, &QAbstractItemModel::modelReset, this, &PagedProxyModel::modelReset);
    connect(model, SIGNAL(layoutChanged()), this, SIGNAL(modelReset()));

    setSourceModel(model);

    if (reset) {
        endResetModel();
    }
}

QObject *PagedProxyModel::sourceModelObject() const
{
    return sourceModel();
}

void PagedProxyModel::sourceDataChanged(const QModelIndex &from, const QModelIndex &to)
{
    emit dataChanged(mapFromSource(from), mapFromSource(to));
}

void PagedProxyModel::sourceRowsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destinationParent, int destinationRow)
{
    const int pageStart = (m_currentPage*m_pageSize);
    int newStart = qMin(m_pageSize, qMax(0, sourceStart - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (sourceEnd - sourceStart));
    int newDestinationRow = qMin(m_pageSize, qMax(0, destinationRow - pageStart));

    emit beginMoveRows(sourceParent, newStart, newEnd, destinationParent, newDestinationRow);
    endMoveRows();
}

void PagedProxyModel::sourceRowsAboutToBeInserted( const QModelIndex & parentIdx, int start, int end )
{
    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    //insert in pages bigger than us, not interested
    if (start > pageEnd) {
        return;
    }

    //FIXME: proper indexes should be calculated
    beginResetModel();
    return;

    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (end - start));

    m_oldRowCount = rowCount();
    //insert only the ones that are beyond the count
    if (newEnd > m_oldRowCount) {
        beginInsertRows(parentIdx, rowCount() - newEnd, newEnd );
    }
}

void PagedProxyModel::sourceRowsInserted( const QModelIndex& parentIdx, int start, int end )
{
    Q_UNUSED( parentIdx );

    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    if (start > pageEnd) {
        return;
    }

    //FIXME: proper mapped indexes should be calculated
    endResetModel();
    return;

    if (rowCount() > m_oldRowCount) {
        endInsertRows();
    }
    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (end - start));

    if (newStart <= m_oldRowCount) {
        emit dataChanged(PagedProxyModel::index(newStart, 0),
                         PagedProxyModel::index(qMin(newEnd, m_oldRowCount), 0));
    }
}

void PagedProxyModel::sourceRowsAboutToBeRemoved( const QModelIndex & parentIdx, int start, int end )
{
    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    if (start > pageEnd) {
        return;
    }

    //FIXME: proper mapped indexes should be calculated
    beginResetModel();
    return;

    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, qMax(0, end - pageStart));

    m_oldRowCount = rowCount();
    //insert only the ones that are beyond the count
    if (newEnd < m_oldRowCount) {
        beginRemoveRows(parentIdx, newStart, newEnd );
    }
}

void PagedProxyModel::sourceRowsRemoved( const QModelIndex& parentIdx, int start, int end )
{
    Q_UNUSED( parentIdx );

    const int pageStart = (m_currentPage*m_pageSize);
    const int pageEnd = (m_currentPage*m_pageSize + m_pageSize);

    if (start > pageEnd) {
        return;
    }

    //FIXME: proper mapped indexes should be calculated
    endResetModel();
    return;

    if (rowCount() < m_oldRowCount) {
        endRemoveRows();
    }
    int newStart = qMin(m_pageSize, qMax(0, start - pageStart));
    int newEnd = qMin(m_pageSize, newStart + (end - start));

    if (sourceModel()->rowCount() - pageStart > rowCount()) {
        emit dataChanged(PagedProxyModel::index(newStart, 0),
                         PagedProxyModel::index(qMin((sourceModel()->rowCount() - pageStart), qMin(newEnd, m_oldRowCount)), 0));
    }
}

int PagedProxyModel::rowCount(const QModelIndex &parent) const
{
    if (!sourceModel()) {
        return 0;
    }

    return qMin(m_pageSize, (sourceModel()->rowCount(parent)-m_currentPage*m_pageSize));
}

QVariant PagedProxyModel::data(const QModelIndex &index, int role) const
{
    if (!sourceModel()) {
        return QVariant();
    }

    return sourceModel()->data(PagedProxyModel::index(index.row()+ (m_currentPage*m_pageSize), index.column(), QModelIndex()), role);
}

QModelIndex PagedProxyModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!sourceModel()) {
        return QModelIndex();
    }

    return sourceModel()->index(row, column, parent);
}

QModelIndex PagedProxyModel::parent(const QModelIndex &index) const
{
    Q_UNUSED(index)
    return QModelIndex();
}

QModelIndex PagedProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
{
    if (!sourceModel()) {
        return QModelIndex();
    }

    return sourceModel()->index(sourceIndex.row() - (m_currentPage*m_pageSize), sourceIndex.column(), QModelIndex());
}

QModelIndex PagedProxyModel::mapToSource(const QModelIndex &proxyIndex) const
{
    if (!sourceModel()) {
        return QModelIndex();
    }

    return sourceModel()->index(proxyIndex.row() + (m_currentPage*m_pageSize), proxyIndex.column(), QModelIndex());
}

int PagedProxyModel::columnCount(const QModelIndex &index) const
{
    if (!sourceModel()) {
        return 0;
    }
    return sourceModel()->columnCount(index);
}

#include "pagedproxymodel.moc"
<|endoftext|>