<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef THROTTLING_SEMAPHORE_HPP_
#define THROTTLING_SEMAPHORE_HPP_

#include "containers/scoped.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "concurrency/wait_any.hpp"
#include "containers/intrusive_list.hpp"
#include "arch/timing.hpp"

/* TODO (daniel): Document
 * It attempts to meet the following design goals:
 * - No lock is ever granted if the given capacity is currently violated (except when using lock_force).
 *   If necessary, lock requests are delayed indefinitely. Note that the capacity requirements
 *   of the issued lock itself are not considered in this guarantee (so no request is
 *   hold back indefinitely if its own count is higher than the capacity).
 * - throttling_semaphore_t does adapt to changing conditions. If locks are released
 *   earlier or later than expected, the delay times of queued lock requests are re-evaluated
 *   automatically.
 * - The configuration of delay times is robust, i.e. throttling_semaphore_t works reasonably well
 *   for a wide range of `delay_at_half` values.
 */
class throttling_semaphore_t : public repeating_timer_callback_t {
    struct lock_request_t : public intrusive_list_node_t<lock_request_t> {
        semaphore_available_callback_t *cb;
        int count;
        int64_t target_delay;
        int64_t total_time_waited;
        int64_t time_since_recalc;
        int64_t recalc_delay;
        void on_available() {
            cb->on_semaphore_available();
            delete this;
        }
        void progress(int64_t time_passed) {
            total_time_waited += time_passed;
            time_since_recalc += time_passed;
        }
    };

    int capacity, current;
    double throttling_threshold; // No throttling if current < capacity * throttling_threshold.
    int64_t delay_granularity;
    int64_t delay_at_half;
    intrusive_list_t<lock_request_t> waiters;
    scoped_ptr_t<repeating_timer_t> timer;
    bool maintain_ordering;

public:
    /* throttling_semaphore_t starts throttling transactions when current >= cap * thre.
     * The granularity in which delays are processed is gran (smaller = higher resolution, more overhead).
     * If current is halfway in between (cap - (cap * thre)) and cap, the delay will be d_half.
     */
    explicit throttling_semaphore_t(int cap, double thre = 0.5, int64_t gran = 25, int64_t d_half = 100) :
        capacity(cap),
        current(0),
        throttling_threshold(thre),
        delay_granularity(gran),
        delay_at_half(d_half),
        maintain_ordering(true)
    {
        rassert(throttling_threshold >= 0.0 && throttling_threshold <= 1.0);
        rassert(delay_granularity > 0);
        rassert(capacity >= 0 || capacity == SEMAPHORE_NO_LIMIT);
    }

    void lock(semaphore_available_callback_t *cb, int count = 1);

    void co_lock(int count = 1);
    void co_lock_interruptible(signal_t *interruptor, int count = 1);

    void unlock(int count = 1);

    void force_lock(int count = 1);

    // This does not trigger any request to be re-scheduled immediately.
    // Instead the new capacity will become effective as part of the regular
    // re-calculation schedule.
    void set_capacity(int new_capacity) { capacity = new_capacity; }
    int get_capacity() const { return capacity; }

    virtual void on_ring(); // Called periodically by timer

private:
    void on_waiters_changed(); // Should be called after a change to waiters

    int64_t compute_target_delay() const; // The "heart" of throttling_semaphore_t.
};

class throttling_semaphore_acq_t {
public:
    throttling_semaphore_acq_t(throttling_semaphore_t *_acquiree, int c = 1) : acquiree(_acquiree), count(c) {
        acquiree->co_lock(count);
    }

    throttling_semaphore_acq_t(throttling_semaphore_acq_t &&movee) : acquiree(movee.acquiree) {
        movee.acquiree = NULL;
    }

    ~throttling_semaphore_acq_t() {
        if (acquiree) {
            acquiree->unlock(count);
        }
    }

private:
    throttling_semaphore_t *acquiree;
    int count;
    DISABLE_COPYING(throttling_semaphore_acq_t);
};

#endif /* THROTTLING_SEMAPHORE_HPP_ */
<commit_msg>Allow using throttling_semaphore_acq_t for force_lock.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef THROTTLING_SEMAPHORE_HPP_
#define THROTTLING_SEMAPHORE_HPP_

#include "containers/scoped.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "concurrency/wait_any.hpp"
#include "containers/intrusive_list.hpp"
#include "arch/timing.hpp"

/* TODO (daniel): Document
 * It attempts to meet the following design goals:
 * - No lock is ever granted if the given capacity is currently violated (except when using lock_force).
 *   If necessary, lock requests are delayed indefinitely. Note that the capacity requirements
 *   of the issued lock itself are not considered in this guarantee (so no request is
 *   hold back indefinitely if its own count is higher than the capacity).
 * - throttling_semaphore_t does adapt to changing conditions. If locks are released
 *   earlier or later than expected, the delay times of queued lock requests are re-evaluated
 *   automatically.
 * - The configuration of delay times is robust, i.e. throttling_semaphore_t works reasonably well
 *   for a wide range of `delay_at_half` values.
 */
class throttling_semaphore_t : public repeating_timer_callback_t {
    struct lock_request_t : public intrusive_list_node_t<lock_request_t> {
        semaphore_available_callback_t *cb;
        int count;
        int64_t target_delay;
        int64_t total_time_waited;
        int64_t time_since_recalc;
        int64_t recalc_delay;
        void on_available() {
            cb->on_semaphore_available();
            delete this;
        }
        void progress(int64_t time_passed) {
            total_time_waited += time_passed;
            time_since_recalc += time_passed;
        }
    };

    int capacity, current;
    double throttling_threshold; // No throttling if current < capacity * throttling_threshold.
    int64_t delay_granularity;
    int64_t delay_at_half;
    intrusive_list_t<lock_request_t> waiters;
    scoped_ptr_t<repeating_timer_t> timer;
    bool maintain_ordering;

public:
    /* throttling_semaphore_t starts throttling transactions when current >= cap * thre.
     * The granularity in which delays are processed is gran (smaller = higher resolution, more overhead).
     * If current is halfway in between (cap - (cap * thre)) and cap, the delay will be d_half.
     */
    explicit throttling_semaphore_t(int cap, double thre = 0.5, int64_t gran = 25, int64_t d_half = 100) :
        capacity(cap),
        current(0),
        throttling_threshold(thre),
        delay_granularity(gran),
        delay_at_half(d_half),
        maintain_ordering(true)
    {
        rassert(throttling_threshold >= 0.0 && throttling_threshold <= 1.0);
        rassert(delay_granularity > 0);
        rassert(capacity >= 0 || capacity == SEMAPHORE_NO_LIMIT);
    }

    void lock(semaphore_available_callback_t *cb, int count = 1);

    void co_lock(int count = 1);
    void co_lock_interruptible(signal_t *interruptor, int count = 1);

    void unlock(int count = 1);

    void force_lock(int count = 1);

    // This does not trigger any request to be re-scheduled immediately.
    // Instead the new capacity will become effective as part of the regular
    // re-calculation schedule.
    void set_capacity(int new_capacity) { capacity = new_capacity; }
    int get_capacity() const { return capacity; }

    virtual void on_ring(); // Called periodically by timer

private:
    void on_waiters_changed(); // Should be called after a change to waiters

    int64_t compute_target_delay() const; // The "heart" of throttling_semaphore_t.
};

class throttling_semaphore_acq_t {
public:
    throttling_semaphore_acq_t(throttling_semaphore_t *_acquiree, int c = 1, bool use_the_force = false) :
                acquiree(_acquiree),
                count(c) {

        if (use_the_force)
            acquiree->force_lock(count);
        else
            acquiree->co_lock(count);
    }

    throttling_semaphore_acq_t(throttling_semaphore_acq_t &&movee) : acquiree(movee.acquiree) {
        movee.acquiree = NULL;
    }

    ~throttling_semaphore_acq_t() {
        if (acquiree) {
            acquiree->unlock(count);
        }
    }

private:
    throttling_semaphore_t *acquiree;
    int count;
    DISABLE_COPYING(throttling_semaphore_acq_t);
};

#endif /* THROTTLING_SEMAPHORE_HPP_ */
<|endoftext|>


<commit_before>#include <sstream>
#include <vector>
#include <limits>
#include "person.hpp"
#include "PersonsFile.hpp"

using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
using Output_Files = std::vector<std::ofstream>;

class Database_Sorter {
	bool is_database_empty;
	std::string database_file_name;
	std::string vault_name;
public:
	Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount,
		std::string _vault_name = "F:\\1\\temp_files\\")
		: database_file_name(database_file_name),
		database_file(database_file_name),
		output_file(output_file_name),
		RAM_amount(_RAM_amount * 1024 * 1024),
		is_database_empty(true),
		vault_name(_vault_name)
	{
		;
	}
	void sortDatabase() {
		database_file.seekg(0, std::ios::end);
		size_t database_size = static_cast<size_t>(database_file.tellg());
		database_file.seekg(0, std::ios::beg);
		sortFile(database_file_name, database_size, 0);
	}
	void closeDatabase() {
		database_file.close();
		output_file.close();
	}
private:
	void outputFile(std::string const & file_name) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		std::ifstream file(file_name);
		char ch;
		while (file.get(ch)) {
			output_file.put(ch);
		}
		file.close();
	}
	void sortFile(std::string const & file_name, size_t file_size, size_t sort_i) {
		if (file_size < RAM_amount) {
			RAMsort(file_name, sort_i);
		}
		else {
			std::vector<Persons_File> persons_files = stuffPersonsToFiles(file_name, sort_i);
			for (size_t i = 0; i < persons_files.size(); i++) {
				if (!persons_files[i].is_empty) {
					if (persons_files[i].is_same) {
						outputFile(persons_files[i].file_name);
					}
					else {
						sortFile(persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
					}
				}
			}
		}
	}

	void RAMsort(std::string const & file_name, size_t sort_i) {
		persons.clear();
		readFileIntoRAM(file_name);
		sortPersons(persons, sort_i);
	}
	void readFileIntoRAM(std::string const & file_name) {
		/*std::string str;

		std::ifstream file(file_name, std::ios::in | std::ios::ate);
		if (file) {
			std::ifstream::streampos filesize = file.tellg();
			str.reserve(filesize);

			file.seekg(0);
			while (!file.eof())
			{
				str += file.get();
			}
		}*/
		std::ifstream is(file_name, std::ifstream::binary);
		if (is) {
			// get length of file:
			is.seekg(0, is.end);
			size_t length = is.tellg();
			is.seekg(0, is.beg);

			char * buffer = new char[length];
			// read data as a block:
			is.read(buffer, length);
			is.close();
			size_t previous_i = 0;
			size_t i = 0;
			bool state = false;
			person current_person;
			while (i < length) {
				if (buffer[i] == ' ') {
					if (!state) {
						current_person.name_i = i - previous_i + 1;
						state = true;
					}
					else {
						current_person.name_length = i - previous_i - current_person.name_i;
						state = false;
					}
				}
				else if (buffer[i] == '\r') {
					current_person.str = new char[i - previous_i + 1];
					strncpy(current_person.str, &(buffer[previous_i]), i - previous_i);
					current_person.str[i - previous_i] = '\0';
					persons.push_back(current_person);

					previous_i = i + 2;
					i++;
				}
				i++;
			}
			persons.shrink_to_fit();
			delete[] buffer;
		}
		/*std::ifstream file(file_name);
		std::stringstream s;

		person current_person;
		while (!file.eof()) {
			file >> current_person;
			current_person.name.shrink_to_fit();
			current_person.surname.shrink_to_fit();
			persons.push_back(current_person);
		}*/
	}
	void sortPersons(Persons & entered_persons, size_t sort_i) {
		size_t full_bucket_i;
		Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i, full_bucket_i);
		if (full_bucket_i != std::numeric_limits<size_t>::max()) {
			outputBucket(buckets[full_bucket_i], output_file);
		}
		else {
			for (auto bucket : buckets) {
				if (!bucket.empty()) {
					sortPersons(bucket, sort_i + 1);
				}
			}
		}
	}
	Buckets stuffPersonsToBuckets(Persons & persons, size_t sort_i, size_t & full_bucket_i) {
		bool is_same = true;
		char * key = new char[persons[0].name_length + 1];
		strncpy(key, persons[0].getName(), persons[0].name_length);
		key[persons[0].name_length] = '\0';

		full_bucket_i = persons[0].i(sort_i);
		size_t persons_size = persons.size();
		Buckets buckets(n_literals);
		for (auto person : persons) {
			size_t currentI = person.i(sort_i);
			full_bucket_i = currentI;
			buckets[currentI].push_back(std::move(person));
			if (is_same) {
				if (strcmp(key, person.getName()) != 0) {
					is_same = false;
				}
			}
		}
		persons.clear();
		persons.shrink_to_fit();
		if (!is_same) {
			full_bucket_i = std::numeric_limits<size_t>::max();
		}
		delete[] key;
		return buckets;
	}
	void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
		for (auto person : bucket) {
			outputPerson(person);
		}
	}
	void outputPerson(person _person) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		output_file << _person.str;
	}

	std::vector<Persons_File> stuffPersonsToFiles(/*std::ifstream & base_file, */
		std::string base_file_name, size_t sort_i) {
		std::ifstream base_file(base_file_name);
		bool is_same = true;
		std::vector<Persons_File> files(n_literals);

		person current_person;
		size_t currentTargetFileI;
		std::string str1, str2, str3;
		while (!base_file.eof()) {
			base_file >> str1;
			current_person.name_i = str1.length() + 1;
			base_file >> str2;
			current_person.name_length = str2.length();
			base_file >> str3;
			str1 += " " + str2 + " " + str3;
			current_person.str = new char[str1.length() + 1];
			strncpy(current_person.str, str1.c_str(), str1.length());
			current_person.str[str1.length()] = '\0';
			currentTargetFileI = current_person.i(sort_i);
			if (files[currentTargetFileI].is_empty) {
				files[currentTargetFileI].openNew(calcDerivedFileName(base_file_name, currentTargetFileI));
				files[currentTargetFileI].is_empty = false;
				files[currentTargetFileI].key = new char[current_person.name_length + 1];
				strncpy(files[currentTargetFileI].key, current_person.str, current_person.name_length);
				files[currentTargetFileI].key[current_person.name_length] = '\0';
				files[currentTargetFileI].is_same = true;
			}
			else {
				if (files[currentTargetFileI].is_same) {
					//char * temp = current_person.getName();
					if (strcmp(files[currentTargetFileI].key, str2.c_str()) != 0) {
						files[currentTargetFileI].is_same = false;
					}
				}
				files[currentTargetFileI].stream << std::endl;
			}
			files[currentTargetFileI].stream << current_person;
		}
		for (size_t i = 0; i < files.size(); i++) {
			if (!files[i].is_empty) {
				files[i].file_size = static_cast<size_t>(files[i].stream.tellg());
			}
			files[i].stream.close();
		}
		base_file.close();
		return files;
	}
	std::vector<Persons_File> createDerivedFiles(std::string const & base_file_name) {
		std::vector<Persons_File> files(n_literals);
		for (size_t i = 0; i < files.size(); i++) {
			std::string str;
			if (base_file_name == database_file_name) {
				str = vault_name + static_cast<char>(i + 64) + ".txt";
			}
			else {
				str = base_file_name + static_cast<char>(i + 64) + ".txt";
			}
			files[i].openNew(str);
		}
		return files;
	}
	std::string calcDerivedFileName(const std::string & base_file_name, size_t file_i) {
		std::string derived_file_name;
		if (base_file_name == database_file_name) {
			derived_file_name = vault_name + static_cast<char>(file_i + 64) + ".txt";
		}
		else {
			derived_file_name = base_file_name + static_cast<char>(file_i + 64) + ".txt";
		}
		return derived_file_name;
	}

	std::vector<person> persons;
	std::ifstream database_file;
	std::ofstream output_file;
	const size_t RAM_amount;
};
//memory: max 27 files,
<commit_msg>Update Database_Sorter.hpp<commit_after>#include <sstream>
#include <vector>
#include <limits>
#include "person.hpp"
#include "PersonsFile.hpp"

using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
using Output_Files = std::vector<std::ofstream>;

class Database_Sorter {
	bool is_database_empty;
	std::string database_file_name;
	std::string vault_name;
public:
	Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount,
		std::string _vault_name = "F:\\1\\temp_files\\")
		: database_file_name(database_file_name),
		//database_file(database_file_name),
		output_file(output_file_name),
		RAM_amount(_RAM_amount * 1024 * 1024),
		is_database_empty(true),
		vault_name(_vault_name)
	{
		;
	}
	void sortDatabase() {
                std::fstream database_file(database_file_name);
		database_file.seekg(0, std::ios::end);
		size_t database_size = static_cast<size_t>(database_file.tellg());
		database_file.seekg(0, std::ios::beg);
		sortFile(database_file_name, database_size, 0);
	}
	void closeDatabase() {
		database_file.close();
		output_file.close();
	}
private:
	void outputFile(std::string const & file_name) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		std::ifstream file(file_name);
		char ch;
		while (file.get(ch)) {
			output_file.put(ch);
		}
		file.close();
	}
	void sortFile(std::string const & file_name, size_t file_size, size_t sort_i) {
		if (file_size < RAM_amount) {
			RAMsort(file_name, sort_i);
		}
		else {
			std::vector<Persons_File> persons_files = stuffPersonsToFiles(file_name, sort_i);
			for (size_t i = 0; i < persons_files.size(); i++) {
				if (!persons_files[i].is_empty) {
					if (persons_files[i].is_same) {
						outputFile(persons_files[i].file_name);
					}
					else {
						sortFile(persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
					}
				}
			}
		}
	}

	void RAMsort(std::string const & file_name, size_t sort_i) {
		persons.clear();
		readFileIntoRAM(file_name);
		sortPersons(persons, sort_i);
	}
	void readFileIntoRAM(std::string const & file_name) {
		std::ifstream is(file_name, std::ifstream::binary);
		if (is) {
			// get length of file:
			is.seekg(0, is.end);
			size_t length = is.tellg();
			is.seekg(0, is.beg);

			char * buffer = new char[length];
			// read data as a block:
			is.read(buffer, length);
			is.close();
			size_t previous_i = 0;
			size_t i = 0;
			bool state = false;
			person current_person;
			while (i < length) {
				if (buffer[i] == ' ') {
					if (!state) {
						current_person.name_i = i - previous_i + 1;
						state = true;
					}
					else {
						current_person.name_length = i - previous_i - current_person.name_i;
						state = false;
					}
				}
				else if (buffer[i] == '\r') {
					current_person.str = new char[i - previous_i + 1];
					strncpy(current_person.str, &(buffer[previous_i]), i - previous_i);
					current_person.str[i - previous_i] = '\0';
					persons.push_back(current_person);

					previous_i = i + 2;
					i++;
				}
				i++;
			}
			persons.shrink_to_fit();
			delete[] buffer;
		}
	}
	void sortPersons(Persons & entered_persons, size_t sort_i) {
		size_t full_bucket_i;
		Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i, full_bucket_i);
		if (full_bucket_i != std::numeric_limits<size_t>::max()) {
			outputBucket(buckets[full_bucket_i], output_file);
		}
		else {
			for (auto bucket : buckets) {
				if (!bucket.empty()) {
					sortPersons(bucket, sort_i + 1);
				}
			}
		}
	}
	Buckets stuffPersonsToBuckets(Persons & persons, size_t sort_i, size_t & full_bucket_i) {
		bool is_same = true;
		char * key = new char[persons[0].name_length + 1];
		strncpy(key, persons[0].getName(), persons[0].name_length);
		key[persons[0].name_length] = '\0';

		full_bucket_i = persons[0].i(sort_i);
		size_t persons_size = persons.size();
		Buckets buckets(n_literals);
		for (auto person : persons) {
			size_t currentI = person.i(sort_i);
			full_bucket_i = currentI;
			buckets[currentI].push_back(std::move(person));
			if (is_same) {
				if (strcmp(key, person.getName()) != 0) {
					is_same = false;
				}
			}
		}
		persons.clear();
		persons.shrink_to_fit();
		if (!is_same) {
			full_bucket_i = std::numeric_limits<size_t>::max();
		}
		delete[] key;
		return buckets;
	}
	void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
		for (auto person : bucket) {
			outputPerson(person);
		}
	}
	void outputPerson(person _person) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		output_file << _person.str;
	}

	std::vector<Persons_File> stuffPersonsToFiles(/*std::ifstream & base_file, */
		std::string base_file_name, size_t sort_i) {
		std::ifstream base_file(base_file_name);
		bool is_same = true;
		std::vector<Persons_File> files(n_literals);

		person current_person;
		size_t currentTargetFileI;
		std::string str1, str2, str3;
		while (!base_file.eof()) {
			base_file >> str1;
			current_person.name_i = str1.length() + 1;
			base_file >> str2;
			current_person.name_length = str2.length();
			base_file >> str3;
			str1 += " " + str2 + " " + str3;
			current_person.str = new char[str1.length() + 1];
			strncpy(current_person.str, str1.c_str(), str1.length());
			current_person.str[str1.length()] = '\0';
			currentTargetFileI = current_person.i(sort_i);
			if (files[currentTargetFileI].is_empty) {
				files[currentTargetFileI].openNew(calcDerivedFileName(base_file_name, currentTargetFileI));
				files[currentTargetFileI].is_empty = false;
				files[currentTargetFileI].key = new char[current_person.name_length + 1];
				strncpy(files[currentTargetFileI].key, current_person.str, current_person.name_length);
				files[currentTargetFileI].key[current_person.name_length] = '\0';
				files[currentTargetFileI].is_same = true;
			}
			else {
				if (files[currentTargetFileI].is_same) {
					//char * temp = current_person.getName();
					if (strcmp(files[currentTargetFileI].key, str2.c_str()) != 0) {
						files[currentTargetFileI].is_same = false;
					}
				}
				files[currentTargetFileI].stream << std::endl;
			}
			files[currentTargetFileI].stream << current_person;
		}
		for (size_t i = 0; i < files.size(); i++) {
			if (!files[i].is_empty) {
				files[i].file_size = static_cast<size_t>(files[i].stream.tellg());
			}
			files[i].stream.close();
		}
		base_file.close();
		return files;
	}
	std::vector<Persons_File> createDerivedFiles(std::string const & base_file_name) {
		std::vector<Persons_File> files(n_literals);
		for (size_t i = 0; i < files.size(); i++) {
			std::string str;
			if (base_file_name == database_file_name) {
				str = vault_name + static_cast<char>(i + 64) + ".txt";
			}
			else {
				str = base_file_name + static_cast<char>(i + 64) + ".txt";
			}
			files[i].openNew(str);
		}
		return files;
	}
	std::string calcDerivedFileName(const std::string & base_file_name, size_t file_i) {
		std::string derived_file_name;
		if (base_file_name == database_file_name) {
			derived_file_name = vault_name + static_cast<char>(file_i + 64) + ".txt";
		}
		else {
			derived_file_name = base_file_name + static_cast<char>(file_i + 64) + ".txt";
		}
		return derived_file_name;
	}

	std::vector<person> persons;
	//std::ifstream database_file;
	std::ofstream output_file;
	const size_t RAM_amount;
};
//memory: max 27 files,
<|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file joint_observation_model_iid.hpp
 * \date Febuary 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP
#define FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP

#include <Eigen/Dense>

#include <memory>
#include <type_traits>

#include <fl/util/traits.hpp>
#include <fl/util/meta.hpp>
#include <fl/distribution/gaussian.hpp>

#include <fl/model/adaptive_model.hpp>
#include <fl/model/observation/observation_model_interface.hpp>

namespace fl
{

// Forward declarations
template <typename...Models> class JointObservationModel;

/**
 * Traits of JointObservationModel<MultipleOf<ObservationModel, Count>>
 */
template <
    typename ObsrvModel,
    int Count
>
struct Traits<
           JointObservationModel<MultipleOf<ObsrvModel, Count>, Adaptive<>>
        >
{
    enum : signed int { ModelCount = Count };

    typedef ObsrvModel LocalObsrvModel;
    typedef typename Traits<ObsrvModel>::Scalar Scalar;
    typedef typename Traits<ObsrvModel>::Obsrv LocalObsrv;
    typedef typename Traits<ObsrvModel>::State LocalState;
    typedef typename Traits<ObsrvModel>::Param LocalParam;
    typedef typename Traits<ObsrvModel>::Noise LocalNoise;

    enum : signed int
    {
        StateDim = LocalState::SizeAtCompileTime,
        ObsrvDim = ExpandSizes<LocalObsrv::SizeAtCompileTime, Count>::Size,
        NoiseDim = ExpandSizes<LocalNoise::SizeAtCompileTime, Count>::Size,
        ParamDim = ExpandSizes<LocalParam::SizeAtCompileTime, Count>::Size
    };

    typedef Eigen::Matrix<Scalar, ObsrvDim, 1> Obsrv;
    typedef Eigen::Matrix<Scalar, StateDim, 1> State;
    typedef Eigen::Matrix<Scalar, NoiseDim, 1> Noise;
    typedef Eigen::Matrix<Scalar, ParamDim, 1> Param;

    typedef ObservationModelInterface<
                Obsrv,
                State,
                Noise
            > ObservationModelBase;
};

/**
 * \ingroup observation_models
 *
 * \brief JointObservationModel itself is an observati
 * on model which contains
 * internally multiple models all of the \em same type. The joint model can be
 * simply summarized as \f$ h(x, \theta, w) = [ h_{local}(x, \theta_1, w_1),
 * h_{local}(x, \theta_2, w_2), \ldots, h_{local}(x, \theta_n, w_n) ]^T \f$
 *
 * where \f$x\f$ is the state variate, \f$\theta = [ \theta_1, \theta_2, \ldots,
 * \theta_n ]^T\f$ and \f$w = [ w_1, w_2, \ldots, w_n ]^T\f$  are the the
 * parameters and noise terms of each of the \f$n\f$ models.
 *
 * JointObservationModel implements the ObservationModelInterface and the
 * AdaptiveModel interface. That being said, the JointObservationModel can be
 * used as a regular observation model or even as an adaptive observation model
 * which provides a set of parameters that can be changed at any time. This
 * implies that all sub-models must implement the the AdaptiveModel
 * interface. However, if the sub-model is not adaptive, JointObservationModel
 * applies a decorator call the NotAdaptive operator on the sub-model. This
 * operator enables any model to be treated as if it is adaptive without
 * effecting the model behaviour.
 */
template <
    typename LocalObsrvModel,
    int Count
>
class JointObservationModel<MultipleOf<LocalObsrvModel, Count>>
    : public JointObservationModel<
          MultipleOf<typename MakeAdaptive<LocalObsrvModel>::Type, Count>,
          Adaptive<>
      >
{ };

template <
    typename LocalObsrvModel,
    int Count
>
class JointObservationModel<MultipleOf<LocalObsrvModel, Count>, Adaptive<>>
    : public Traits<
                 JointObservationModel<MultipleOf<LocalObsrvModel, Count>>
             >::ObservationModelBase
{
public:
    typedef JointObservationModel<MultipleOf<LocalObsrvModel,Count>> This;

    typedef typename Traits<This>::Obsrv Obsrv;
    typedef typename Traits<This>::State State;
    typedef typename Traits<This>::Noise Noise;

public:
    explicit JointObservationModel(
            const LocalObsrvModel& local_obsrv_model,
            int count = ToDimension<Count>::Value)
        : local_obsrv_model_(local_obsrv_model),
          count_(count)
    {
        assert(count_ > 0);
    }

    explicit
    JointObservationModel(const MultipleOf<LocalObsrvModel, Count>& mof)
        : local_obsrv_model_(mof.instance),
          count_(mof.count)
    {
        assert(count_ > 0);
    }

    /**
     * \brief Overridable default destructor
     */
    ~JointObservationModel() { }

    /**
     * \copydoc ObservationModelInterface::predict_obsrv
     */
    virtual Obsrv predict_obsrv(const State& state,
                                const Noise& noise,
                                double delta_time)
    {
        Obsrv y = Obsrv::Zero(obsrv_dimension(), 1);

        int obsrv_dim = local_obsrv_model_.obsrv_dimension();
        int noise_dim = local_obsrv_model_.noise_dimension();

        const int count = count_;
        for (int i = 0; i < count; ++i)
        {
            y.middleRows(i * obsrv_dim, obsrv_dim) =
                local_obsrv_model_.predict_obsrv(
                    state,
                    noise.middleRows(i * noise_dim, noise_dim),
                    delta_time);
        }

        return y;
    }

    virtual int obsrv_dimension() const
    {
        return local_obsrv_model_.obsrv_dimension() * count_;
    }

    virtual int noise_dimension() const
    {
        return local_obsrv_model_.noise_dimension() * count_;
    }

    virtual int state_dimension() const
    {
        return local_obsrv_model_.state_dimension();
    }

    LocalObsrvModel& local_observation_model()
    {
        return local_obsrv_model_;
    }

protected:
    LocalObsrvModel local_obsrv_model_;
    int count_;
};

///**
// * Traits of the \em Adaptive JointObservationModel
// */
//template <
//    typename ObsrvModel,
//    int Count
//>
//struct Traits<
//           JointObservationModel<MultipleOf<Adaptive<ObsrvModel>, Count>>
//        >
//    : Traits<JointObservationModel<MultipleOf<ObsrvModel, Count>>>
//{
//    typedef Traits<JointObservationModel<MultipleOf<ObsrvModel, Count>>> Base;

//    typedef typename Traits<ObsrvModel>::Param LocalParam;

//    enum : signed int
//    {
//        ParamDim = ExpandSizes<LocalParam::SizeAtCompileTime, Count>::Size
//    };

//    typedef Eigen::Matrix<typename Base::Scalar, ParamDim, 1> Param;

//    typedef ObservationModelInterface<
//                typename Base::Obsrv,
//                typename Base::State,
//                typename Base::Noise
//            > ObservationModelBase;

//    typedef AdaptiveModel<Param> AdaptiveModelBase;
//};

///**
// * \ingroup observation_models
// *
// * JointObservationModel for adaptive local observation models
// */
//template <
//    typename LocalObsrvModel,
//    int Count>
//class JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>>
//    : public Traits<
//                 JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>>
//             >::ObservationModelBase,
//      public Traits<
//                JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>>
//             >::AdaptiveModelBase

//{
//public:
//    typedef JointObservationModel<MultipleOf<Adaptive<LocalObsrvModel>, Count>> This;

//    typedef typename Traits<This>::Param Param;

//public:
//    virtual Param param() const { return param_; }
//    virtual void param(Param new_param) {  param_ = new_param; }
//    virtual int param_dimension() const { return param_.rows(); }

//protected:
//    Param param_;
//};

}

#endif

<commit_msg>Added ForwardAdaptive<LocalModel> to decorate non-aadptive models<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file joint_observation_model_iid.hpp
 * \date Febuary 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP
#define FL__MODEL__OBSERVATION__JOINT_OBSERVATION_MODEL_IID_HPP

#include <Eigen/Dense>

#include <memory>
#include <type_traits>

#include <fl/util/traits.hpp>
#include <fl/util/meta.hpp>
#include <fl/distribution/gaussian.hpp>

#include <fl/model/adaptive_model.hpp>
#include <fl/model/observation/observation_model_interface.hpp>

namespace fl
{

// Forward declarations
template <typename...Models> class JointObservationModel;

/**
 * Traits of JointObservationModel<MultipleOf<ObservationModel, Count>>
 */
template <
    typename ObsrvModel,
    int Count
>
struct Traits<
           JointObservationModel<MultipleOf<ObsrvModel, Count>, Adaptive<>>
        >
{
    enum : signed int { ModelCount = Count };

    typedef ObsrvModel LocalObsrvModel;
    typedef typename Traits<ObsrvModel>::Scalar Scalar;
    typedef typename Traits<ObsrvModel>::Obsrv LocalObsrv;
    typedef typename Traits<ObsrvModel>::State LocalState;
    typedef typename Traits<ObsrvModel>::Param LocalParam;
    typedef typename Traits<ObsrvModel>::Noise LocalNoise;

    enum : signed int
    {
        StateDim = LocalState::SizeAtCompileTime,
        ObsrvDim = ExpandSizes<LocalObsrv::SizeAtCompileTime, Count>::Size,
        NoiseDim = ExpandSizes<LocalNoise::SizeAtCompileTime, Count>::Size,
        ParamDim = ExpandSizes<LocalParam::SizeAtCompileTime, Count>::Size
    };

    typedef Eigen::Matrix<Scalar, ObsrvDim, 1> Obsrv;
    typedef Eigen::Matrix<Scalar, StateDim, 1> State;
    typedef Eigen::Matrix<Scalar, NoiseDim, 1> Noise;
    typedef Eigen::Matrix<Scalar, ParamDim, 1> Param;

    typedef ObservationModelInterface<
                Obsrv,
                State,
                Noise
            > ObservationModelBase;
};

/**
 * \ingroup observation_models
 *
 * \brief JointObservationModel itself is an observation model which contains
 * internally multiple models all of the \em same type. The joint model can be
 * simply summarized as \f$ h(x, \theta, w) = [ h_{local}(x, \theta_1, w_1),
 * h_{local}(x, \theta_2, w_2), \ldots, h_{local}(x, \theta_n, w_n) ]^T \f$
 *
 * where \f$x\f$ is the state variate, \f$\theta = [ \theta_1, \theta_2, \ldots,
 * \theta_n ]^T\f$ and \f$w = [ w_1, w_2, \ldots, w_n ]^T\f$  are the the
 * parameters and noise terms of each of the \f$n\f$ models.
 *
 * JointObservationModel implements the ObservationModelInterface and the
 * AdaptiveModel interface. That being said, the JointObservationModel can be
 * used as a regular observation model or even as an adaptive observation model
 * which provides a set of parameters that can be changed at any time. This
 * implies that all sub-models must implement the the AdaptiveModel
 * interface. However, if the sub-model is not adaptive, JointObservationModel
 * applies a decorator call the NotAdaptive operator on the sub-model. This
 * operator enables any model to be treated as if it is adaptive without
 * effecting the model behaviour.
 */
template <
    typename LocalObsrvModel,
    int Count
>
#ifdef GENERATING_DOCUMENTATION
class JointObservationModel<MultipleOf<LocalObsrvModel, Count>>
#else
class JointObservationModel<MultipleOf<LocalObsrvModel, Count>, Adaptive<>>
#endif
    : public Traits<
                 JointObservationModel<MultipleOf<LocalObsrvModel, Count>>
             >::ObservationModelBase
{
public:
    typedef JointObservationModel<MultipleOf<LocalObsrvModel,Count>> This;

    typedef typename Traits<This>::Obsrv Obsrv;
    typedef typename Traits<This>::State State;
    typedef typename Traits<This>::Noise Noise;

public:
    explicit JointObservationModel(
            const LocalObsrvModel& local_obsrv_model,
            int count = ToDimension<Count>::Value)
        : local_obsrv_model_(local_obsrv_model),
          count_(count)
    {
        assert(count_ > 0);
    }

    explicit
    JointObservationModel(const MultipleOf<LocalObsrvModel, Count>& mof)
        : local_obsrv_model_(mof.instance),
          count_(mof.count)
    {
        assert(count_ > 0);
    }

    /**
     * \brief Overridable default destructor
     */
    ~JointObservationModel() { }

    /**
     * \copydoc ObservationModelInterface::predict_obsrv
     */
    virtual Obsrv predict_obsrv(const State& state,
                                const Noise& noise,
                                double delta_time)
    {
        Obsrv y = Obsrv::Zero(obsrv_dimension(), 1);

        int obsrv_dim = local_obsrv_model_.obsrv_dimension();
        int noise_dim = local_obsrv_model_.noise_dimension();

        const int count = count_;
        for (int i = 0; i < count; ++i)
        {
            y.middleRows(i * obsrv_dim, obsrv_dim) =
                local_obsrv_model_.predict_obsrv(
                    state,
                    noise.middleRows(i * noise_dim, noise_dim),
                    delta_time);
        }

        return y;
    }

    virtual int obsrv_dimension() const
    {
        return local_obsrv_model_.obsrv_dimension() * count_;
    }

    virtual int noise_dimension() const
    {
        return local_obsrv_model_.noise_dimension() * count_;
    }

    virtual int state_dimension() const
    {
        return local_obsrv_model_.state_dimension();
    }

    LocalObsrvModel& local_observation_model()
    {
        return local_obsrv_model_;
    }

protected:
    LocalObsrvModel local_obsrv_model_;
    int count_;
};

/**
 * \internal
 * \ingroup observation_models
 *
 * Forwards an adaptive LocalObsrvModel type to the JointObservationModel
 * implementation. \sa ForwardAdaptive for more details.
 */
template <
    typename LocalObsrvModel,
    int Count
>
class JointObservationModel<MultipleOf<LocalObsrvModel, Count>>
    : public JointObservationModel<
          MultipleOf<typename ForwardAdaptive<LocalObsrvModel>::Type, Count>,
          Adaptive<>
      >
{ };

}

#endif

<|endoftext|>


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

#pragma once

#include "iceoryx_utils/platform/types.hpp"

#include <cstdlib>
#include <stdio.h>
#include <type_traits>

#define _WINSOCKAPI_
#define WIN32_LEAN_AND_MEAN

#include <windows.h>

#define SEM_FAILED 0

using sem_t = PVOID;
static constexpr LONG MAX_SEMAPHORE_VALUE = LONG_MAX;
static constexpr int MAX_SEMAPHORE_NAME_LENGTH = 128;

inline int sem_getvalue(sem_t* sem, int* sval)
{
    return -1;
}

inline int sem_post(sem_t* sem)
{
    int retVal = (ReleaseSemaphore(sem, 1, nullptr) == 0) ? -1 : 0;
    return retVal;
}

inline int sem_wait(sem_t* sem)
{
    int retVal = (WaitForSingleObject(sem, INFINITE) == WAIT_FAILED) ? -1 : 0;
    return retVal;
}

inline int sem_trywait(sem_t* sem)
{
    if (WaitForSingleObject(sem, 0) == WAIT_FAILED)
    {
        return -1;
    }
    return 0;
}

inline int sem_timedwait(sem_t* sem, const struct timespec* abs_timeout)
{
    DWORD timeoutInMilliseconds = static_cast<DWORD>(1);
    int retVal = (WaitForSingleObject(sem, timeoutInMilliseconds) == WAIT_FAILED) ? -1 : 0;

    return retVal;
}

inline int sem_close(sem_t* sem)
{
    int retVal = CloseHandle(sem) ? 0 : -1;
    return retVal;
}

inline int sem_destroy(sem_t* sem)
{
    // semaphores are closed in windows when the last process which is
    // holding a semaphore calls CloseHandle
    return 0;
}

inline int sem_init(sem_t* sem, int pshared, unsigned int value)
{
    *sem = CreateSemaphore(nullptr, static_cast<LONG>(value), MAX_SEMAPHORE_VALUE, nullptr);
    if (sem != nullptr)
        return 0;
    return -1;
}

inline sem_t* sem_open(const char* name, int oflag)
{
    return nullptr;
}

inline sem_t* sem_open(const char* name, int oflag, mode_t mode, unsigned int value)
{
    wchar_t semaphoreName[MAX_SEMAPHORE_NAME_LENGTH];
    mbstowcs(semaphoreName, name, MAX_SEMAPHORE_NAME_LENGTH);
    return static_cast<sem_t*>(OpenSemaphoreW(0, false, semaphoreName));
}

inline int sem_unlink(const char* name)
{
    // semaphores are closed in windows when the last process which is
    // holding a semaphore calls CloseHandle
    return 0;
}
<commit_msg>iox-#33 semaphore partially runs<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include "iceoryx_utils/platform/types.hpp"

#include <cstdlib>
#include <stdio.h>
#include <type_traits>

#define _WINSOCKAPI_
#define WIN32_LEAN_AND_MEAN

#include <windows.h>

#define SEM_FAILED 0

using sem_t = PVOID;
static constexpr LONG MAX_SEMAPHORE_VALUE = LONG_MAX;
static constexpr int MAX_SEMAPHORE_NAME_LENGTH = 128;

inline int sem_getvalue(sem_t* sem, int* sval)
{
    return -1;
}

inline int sem_post(sem_t* sem)
{
    int retVal = (ReleaseSemaphore(sem, 1, nullptr) == 0) ? -1 : 0;
    return retVal;
}

inline int sem_wait(sem_t* sem)
{
    int retVal = (WaitForSingleObject(sem, INFINITE) == WAIT_FAILED) ? -1 : 0;
    return retVal;
}

inline int sem_trywait(sem_t* sem)
{
    if (WaitForSingleObject(sem, 0) == WAIT_FAILED)
    {
        return -1;
    }
    return 0;
}

inline int sem_timedwait(sem_t* sem, const struct timespec* abs_timeout)
{
    DWORD timeoutInMilliseconds = static_cast<DWORD>(1);
    int retVal = (WaitForSingleObject(sem, timeoutInMilliseconds) == WAIT_FAILED) ? -1 : 0;

    return retVal;
}

inline int sem_close(sem_t* sem)
{
    int retVal = CloseHandle(sem) ? 0 : -1;
    return retVal;
}

inline int sem_destroy(sem_t* sem)
{
    // semaphores are closed in windows when the last process which is
    // holding a semaphore calls CloseHandle
    return 0;
}

inline int sem_init(sem_t* sem, int pshared, unsigned int value)
{
    *sem = CreateSemaphore(nullptr, static_cast<LONG>(value), MAX_SEMAPHORE_VALUE, nullptr);
    if (sem != nullptr)
        return 0;
    return -1;
}

inline sem_t* sem_open(const char* name, int oflag)
{
    return static_cast<sem_t*>(CreateSemaphore(nullptr, 0, MAX_SEMAPHORE_VALUE, name));
}

inline sem_t* sem_open(const char* name, int oflag, mode_t mode, unsigned int value)
{
    // GetLastError returns ERROR_ALREADY_EXISTS ... when specific O_FLAG is set use
    // this
    return static_cast<sem_t*>(CreateSemaphore(nullptr, value, MAX_SEMAPHORE_VALUE, name));
}

inline int sem_unlink(const char* name)
{
    // semaphores are closed in windows when the last process which is
    // holding a semaphore calls CloseHandle
    return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <datastreamdlg.hxx>

#include <sfx2/filedlghelper.hxx>
#include <svtools/inettbc.hxx>
#include <vcl/layout.hxx>
#include <address.hxx>
#include <docsh.hxx>

namespace sc {

DataStreamDlg::DataStreamDlg(ScDocShell *pDocShell, Window* pParent)
    : ModalDialog(pParent, "DataStreamDialog", "modules/scalc/ui/datastreams.ui")
    , mpDocShell(pDocShell)
{
    get(m_pCbUrl, "url");
    get(m_pBtnBrowse, "browse");
    get(m_pRBScriptData, "scriptdata");
    get(m_pRBValuesInLine, "valuesinline");
    get(m_pRBAddressValue, "addressvalue");
    get(m_pCBRefreshOnEmpty, "refresh_ui");
    get(m_pRBDataDown, "datadown");
    get(m_pRBRangeDown, "rangedown");
    get(m_pRBNoMove, "nomove");
    get(m_pRBMaxLimit, "maxlimit");
    get(m_pEdRange, "range");
    get(m_pEdLimit, "limit");
    get(m_pBtnOk, "ok");
    get(m_pVclFrameLimit, "framelimit");
    get(m_pVclFrameMove, "framemove");

    m_pCbUrl->SetSelectHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pRBAddressValue->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pRBAddressValue->Enable(false);
    m_pRBNoMove->Hide();
    m_pRBValuesInLine->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pEdRange->SetModifyHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pBtnBrowse->SetClickHdl( LINK( this, DataStreamDlg, BrowseHdl ) );
    UpdateEnable();
}

IMPL_LINK_NOARG(DataStreamDlg, BrowseHdl)
{
    sfx2::FileDialogHelper aFileDialog(0, 0);
    if ( aFileDialog.Execute() != ERRCODE_NONE )
        return 0;

    m_pCbUrl->SetText( aFileDialog.GetPath() );
    UpdateEnable();
    return 0;
}

IMPL_LINK_NOARG(DataStreamDlg, UpdateHdl)
{
    UpdateEnable();
    return 0;
}

void DataStreamDlg::UpdateEnable()
{
    bool bOk = !m_pCbUrl->GetURL().isEmpty();
    if (m_pRBAddressValue->IsChecked())
    {
        m_pVclFrameLimit->Disable();
        m_pVclFrameMove->Disable();
        m_pEdRange->Disable();
    }
    else
    {
        m_pVclFrameLimit->Enable();
        m_pVclFrameMove->Enable();
        m_pEdRange->Enable();
        if (bOk)
        {
            // Check the given range to make sure it's valid.
            ScRange aTest = GetStartRange();
            if (!aTest.IsValid())
                bOk = false;
        }
    }
    m_pBtnOk->Enable(bOk);
    setOptimalLayoutSize();
}

ScRange DataStreamDlg::GetStartRange()
{
    OUString aStr = m_pEdRange->GetText();
    ScDocument* pDoc = mpDocShell->GetDocument();
    ScRange aRange;
    sal_uInt16 nRes = aRange.Parse(aStr, pDoc);
    if ((nRes & SCA_VALID) != SCA_VALID || !aRange.IsValid())
    {
        // Invalid range.
        aRange.SetInvalid();
        return aRange;
    }

    // Make sure it's only one row tall.
    if (aRange.aStart.Row() != aRange.aEnd.Row())
        aRange.SetInvalid();

    return aRange;
}

void DataStreamDlg::Init(
    const OUString& rURL, const ScRange& rRange, const sal_Int32 nLimit,
    DataStream::MoveType eMove, const sal_uInt32 nSettings)
{
    m_pEdLimit->SetText(OUString::number(nLimit));
    m_pCbUrl->SetText(rURL);
    if (nSettings & DataStream::SCRIPT_STREAM)
        m_pRBScriptData->Check();
    if (!(nSettings & DataStream::VALUES_IN_LINE))
        m_pRBAddressValue->Check();

    OUString aStr = rRange.Format(SCA_VALID);
    m_pEdRange->SetText(aStr);

    switch (eMove)
    {
        case DataStream::MOVE_DOWN:
            m_pRBDataDown->Check();
        break;
        break;
        case DataStream::RANGE_DOWN:
            m_pRBRangeDown->Check();
        break;
        case DataStream::MOVE_UP:
        case DataStream::NO_MOVE:
        default:
            ;
    }

    UpdateEnable();
}

void DataStreamDlg::StartStream(DataStream *pStream)
{
    ScRange aStartRange = GetStartRange();
    if (!aStartRange.IsValid())
        // Don't start the stream without a valid range.
        return;

    sal_Int32 nLimit = 0;
    if (m_pRBMaxLimit->IsChecked())
        nLimit = m_pEdLimit->GetText().toInt32();
    OUString rURL = m_pCbUrl->GetText();
    sal_uInt32 nSettings = 0;
    if (m_pRBScriptData->IsChecked())
       nSettings |= DataStream::SCRIPT_STREAM;
    if (m_pRBValuesInLine->IsChecked())
       nSettings |= DataStream::VALUES_IN_LINE;

    DataStream::MoveType eMove =
        m_pRBRangeDown->IsChecked() ? DataStream::RANGE_DOWN : DataStream::MOVE_DOWN;

    if (pStream)
    {
        pStream->Decode(rURL, aStartRange, nLimit, eMove, nSettings);
        pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked());
        return;
    }

    pStream = DataStream::Set(mpDocShell, rURL, aStartRange, nLimit, eMove, nSettings);
    pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked());
    DataStream::MakeToolbarVisible();
    pStream->StartImport();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Disable script source option.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <datastreamdlg.hxx>

#include <sfx2/filedlghelper.hxx>
#include <svtools/inettbc.hxx>
#include <vcl/layout.hxx>
#include <address.hxx>
#include <docsh.hxx>

namespace sc {

DataStreamDlg::DataStreamDlg(ScDocShell *pDocShell, Window* pParent)
    : ModalDialog(pParent, "DataStreamDialog", "modules/scalc/ui/datastreams.ui")
    , mpDocShell(pDocShell)
{
    get(m_pCbUrl, "url");
    get(m_pBtnBrowse, "browse");
    get(m_pRBScriptData, "scriptdata");
    get(m_pRBValuesInLine, "valuesinline");
    get(m_pRBAddressValue, "addressvalue");
    get(m_pCBRefreshOnEmpty, "refresh_ui");
    get(m_pRBDataDown, "datadown");
    get(m_pRBRangeDown, "rangedown");
    get(m_pRBNoMove, "nomove");
    get(m_pRBMaxLimit, "maxlimit");
    get(m_pEdRange, "range");
    get(m_pEdLimit, "limit");
    get(m_pBtnOk, "ok");
    get(m_pVclFrameLimit, "framelimit");
    get(m_pVclFrameMove, "framemove");

    m_pCbUrl->SetSelectHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pRBAddressValue->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pRBAddressValue->Enable(false);
    m_pRBScriptData->Enable(false);
    m_pRBNoMove->Hide();
    m_pRBValuesInLine->SetClickHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pEdRange->SetModifyHdl( LINK( this, DataStreamDlg, UpdateHdl ) );
    m_pBtnBrowse->SetClickHdl( LINK( this, DataStreamDlg, BrowseHdl ) );
    UpdateEnable();
}

IMPL_LINK_NOARG(DataStreamDlg, BrowseHdl)
{
    sfx2::FileDialogHelper aFileDialog(0, 0);
    if ( aFileDialog.Execute() != ERRCODE_NONE )
        return 0;

    m_pCbUrl->SetText( aFileDialog.GetPath() );
    UpdateEnable();
    return 0;
}

IMPL_LINK_NOARG(DataStreamDlg, UpdateHdl)
{
    UpdateEnable();
    return 0;
}

void DataStreamDlg::UpdateEnable()
{
    bool bOk = !m_pCbUrl->GetURL().isEmpty();
    if (m_pRBAddressValue->IsChecked())
    {
        m_pVclFrameLimit->Disable();
        m_pVclFrameMove->Disable();
        m_pEdRange->Disable();
    }
    else
    {
        m_pVclFrameLimit->Enable();
        m_pVclFrameMove->Enable();
        m_pEdRange->Enable();
        if (bOk)
        {
            // Check the given range to make sure it's valid.
            ScRange aTest = GetStartRange();
            if (!aTest.IsValid())
                bOk = false;
        }
    }
    m_pBtnOk->Enable(bOk);
    setOptimalLayoutSize();
}

ScRange DataStreamDlg::GetStartRange()
{
    OUString aStr = m_pEdRange->GetText();
    ScDocument* pDoc = mpDocShell->GetDocument();
    ScRange aRange;
    sal_uInt16 nRes = aRange.Parse(aStr, pDoc);
    if ((nRes & SCA_VALID) != SCA_VALID || !aRange.IsValid())
    {
        // Invalid range.
        aRange.SetInvalid();
        return aRange;
    }

    // Make sure it's only one row tall.
    if (aRange.aStart.Row() != aRange.aEnd.Row())
        aRange.SetInvalid();

    return aRange;
}

void DataStreamDlg::Init(
    const OUString& rURL, const ScRange& rRange, const sal_Int32 nLimit,
    DataStream::MoveType eMove, const sal_uInt32 nSettings)
{
    m_pEdLimit->SetText(OUString::number(nLimit));
    m_pCbUrl->SetText(rURL);
    if (nSettings & DataStream::SCRIPT_STREAM)
        m_pRBScriptData->Check();
    if (!(nSettings & DataStream::VALUES_IN_LINE))
        m_pRBAddressValue->Check();

    OUString aStr = rRange.Format(SCA_VALID);
    m_pEdRange->SetText(aStr);

    switch (eMove)
    {
        case DataStream::MOVE_DOWN:
            m_pRBDataDown->Check();
        break;
        break;
        case DataStream::RANGE_DOWN:
            m_pRBRangeDown->Check();
        break;
        case DataStream::MOVE_UP:
        case DataStream::NO_MOVE:
        default:
            ;
    }

    UpdateEnable();
}

void DataStreamDlg::StartStream(DataStream *pStream)
{
    ScRange aStartRange = GetStartRange();
    if (!aStartRange.IsValid())
        // Don't start the stream without a valid range.
        return;

    sal_Int32 nLimit = 0;
    if (m_pRBMaxLimit->IsChecked())
        nLimit = m_pEdLimit->GetText().toInt32();
    OUString rURL = m_pCbUrl->GetText();
    sal_uInt32 nSettings = 0;
    if (m_pRBScriptData->IsChecked())
       nSettings |= DataStream::SCRIPT_STREAM;
    if (m_pRBValuesInLine->IsChecked())
       nSettings |= DataStream::VALUES_IN_LINE;

    DataStream::MoveType eMove =
        m_pRBRangeDown->IsChecked() ? DataStream::RANGE_DOWN : DataStream::MOVE_DOWN;

    if (pStream)
    {
        pStream->Decode(rURL, aStartRange, nLimit, eMove, nSettings);
        pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked());
        return;
    }

    pStream = DataStream::Set(mpDocShell, rURL, aStartRange, nLimit, eMove, nSettings);
    pStream->SetRefreshOnEmptyLine(m_pCBRefreshOnEmpty->IsChecked());
    DataStream::MakeToolbarVisible();
    pStream->StartImport();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <image_cloud/common/small_helpers.hpp>
#include <image_cloud/common/type.hpp>
#include <image_cloud/common/calibration/multi_score.hpp>
#include <image_cloud/common/calibration/structs.hpp>

#include <deque>

#include <opencv2/core/core.hpp>
#include <math.h>

#ifndef SEARCH_GRID_6D_H_
#define SEARCH_GRID_6D_H_

namespace search
{
	inline void grid_setup(Search_setup setup, std::vector<Search_value>& results){
		for(int x=0; x < setup.x.steps_max; ++x)
		{
			for(int y=0; y < setup.y.steps_max; ++y)
			{
				for(int z=0; z < setup.z.steps_max; ++z)
				{
					for(int roll=0; roll < setup.roll.steps_max; ++roll)
					{
						for(int pitch=0; pitch < setup.pitch.steps_max; ++pitch)
						{
							for(int yaw=0; yaw < setup.yaw.steps_max; ++yaw)
							{
								results.push_back(Search_value(setup.x.at(x), setup.y.at(y), setup.z.at(z), setup.roll.at(roll), setup.pitch.at(pitch), setup.yaw.at(yaw)));
							}
						}
					}
				}
			}
		}
	}

	template <typename PointT, typename ImageT>
	inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::vector<pcl::PointCloud<PointT> > &pointclouds, const std::vector<cv::Mat> &edge_images, std::vector<Search_value>& results){
		for(int i=0; i < results.size(); ++i){
			score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i));
		}
	}

	template <typename PointT, typename ImageT>
	inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::deque<pcl::PointCloud<PointT> > &pointclouds, const std::deque<cv::Mat> &edge_images, std::vector<Search_value>& results){
		for(int i=0; i < results.size(); ++i){
			score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i));
		}
	}

	template <typename PointT, typename ImageT>
	inline void get_best_tf(	tf::Transform in,
						tf::Transform &out,
						const image_geometry::PinholeCameraModel &camera_model,
						const std::deque<pcl::PointCloud<PointT> > &pointclouds,
						const std::deque<cv::Mat> &images,
						float range = 0.5,
						int steps = 3)
	{
		Search_setup search_range;
		std::vector<Search_value> results;

		double r,p,y;
		in.getBasis().getRPY(r, p, y);
		search_range.x.init_range(in.getOrigin()[0], range, steps);
		search_range.y.init_range(in.getOrigin()[1], range, steps);
		search_range.z.init_range(in.getOrigin()[2], range, steps);
		search_range.roll.init_range(r, range, steps);
		search_range.pitch.init_range(p, range, steps);
		search_range.yaw.init_range(y, range, steps);

		grid_setup(search_range, results);

		calculate<PointT, ImageT>( camera_model, pointclouds, images, results );

		int best_result_idx = 0;
		long unsigned int best_result = 0;
		for(int i=0; i< results.size(); ++i){
			if(results.at(i).result > best_result){
				best_result_idx = i;
				best_result = results.at(i).result;
			}
		}
		//printf("%d: \t%s\n", best_result_idx, results.at(best_result_idx).to_string().c_str());

		results.at(best_result_idx).get_transform(out);
	}

}

#endif
<commit_msg>add origin point to calculation list if not present<commit_after>#include <image_cloud/common/small_helpers.hpp>
#include <image_cloud/common/type.hpp>
#include <image_cloud/common/calibration/multi_score.hpp>
#include <image_cloud/common/calibration/structs.hpp>

#include <deque>

#include <opencv2/core/core.hpp>
#include <math.h>

#ifndef SEARCH_GRID_6D_H_
#define SEARCH_GRID_6D_H_

namespace search
{
	inline void grid_setup(Search_setup setup, std::vector<Search_value>& results){
		for(int x=0; x < setup.x.steps_max; ++x)
		{
			for(int y=0; y < setup.y.steps_max; ++y)
			{
				for(int z=0; z < setup.z.steps_max; ++z)
				{
					for(int roll=0; roll < setup.roll.steps_max; ++roll)
					{
						for(int pitch=0; pitch < setup.pitch.steps_max; ++pitch)
						{
							for(int yaw=0; yaw < setup.yaw.steps_max; ++yaw)
							{
								results.push_back(Search_value(setup.x.at(x), setup.y.at(y), setup.z.at(z), setup.roll.at(roll), setup.pitch.at(pitch), setup.yaw.at(yaw)));
							}
						}
					}
				}
			}
		}
	}

	template <typename PointT, typename ImageT>
	inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::vector<pcl::PointCloud<PointT> > &pointclouds, const std::vector<cv::Mat> &edge_images, std::vector<Search_value>& results, bool pre_filtred=true){
		for(int i=0; i < results.size(); ++i){
			if(pre_filtred)
			{
				score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i));

			}
			else{
				score::multi_score_filter_depth<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i));
			}
		}
	}

	template <typename PointT, typename ImageT>
	inline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::deque<pcl::PointCloud<PointT> > &pointclouds, const std::deque<cv::Mat> &edge_images, std::vector<Search_value>& results, bool pre_filtred=true){
		for(int i=0; i < results.size(); ++i){
			if(pre_filtred)
			{
				score::multi_score<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i));
			}
			else{
				score::multi_score_filter_depth<PointT, ImageT>(camera_model, pointclouds, edge_images, results.at(i));
			}
		}
	}

	template <typename PointT, typename ImageT>
	inline void get_best_tf(	tf::Transform in,
						tf::Transform &out,
						const image_geometry::PinholeCameraModel &camera_model,
						const std::deque<pcl::PointCloud<PointT> > &pointclouds,
						const std::deque<cv::Mat> &images,
						float range_axis = 0.5,
						float range_rot = 0.5,
						int steps = 3,
						bool pre_filtred = true,
						Multi_search_result *multi_result = NULL)
	{
		Search_setup search_range;
		std::vector<Search_value> result_list;

		double r,p,y;
		in.getBasis().getRPY(r, p, y);
		search_range.x.init_range(in.getOrigin()[0], range_axis, steps);
		search_range.y.init_range(in.getOrigin()[1], range_axis, steps);
		search_range.z.init_range(in.getOrigin()[2], range_axis, steps);
		search_range.roll.init_range(r, range_rot, steps);
		search_range.pitch.init_range(p, range_rot, steps);
		search_range.yaw.init_range(y, range_rot, steps);

		grid_setup(search_range, result_list);

		Search_value origin_empty;
		origin_empty.init(in);

		// Add origin
		if(result_list.size() %2 == 0){
			result_list.insert(result_list.begin()+(result_list.size()/2), origin_empty);
		}

		calculate<PointT, ImageT>( camera_model, pointclouds, images, result_list, pre_filtred);

		// get origin
		Search_value origin = result_list.at( (result_list.size()) / 2);
		std::cout << "center"<< spacer << origin.to_string() << "\n";
		std::cout << "empty" << spacer << origin_empty.to_string() << "\n";
//
		assert(origin.x == origin_empty.x);
		assert(origin.y == origin_empty.y);
		assert(origin.z == origin_empty.z);
		assert(origin.roll == origin_empty.roll);
		assert(origin.pitch == origin_empty.pitch);
		assert(origin.yaw == origin_empty.yaw);
		assert(origin.result != origin_empty.result);

		long unsigned int worse = 0;
		long unsigned int best_result = 0;
		long unsigned int best_result_idx = 0;

		for(int i=0; i< result_list.size(); ++i){
			if(result_list.at(i).result > best_result){
				best_result_idx = i;
				best_result = result_list.at(i).result;
			}
			if( origin.result > result_list.at(i).result ){
				++worse;
			}
		}

		result_list.at(best_result_idx).get_transform(out);

		if(multi_result != NULL){
			multi_result->best = result_list.at(best_result_idx);
			multi_result->in = origin;
			multi_result->nr_worse = worse;
			multi_result->nr_total = result_list.size();
		}
	}

}

#endif
<|endoftext|>


<commit_before>#include "VideoArea.h"
#include "ui_VideoArea.h"

#include "tcam_qt4.h"

#include <iostream>

using namespace tcam;

VideoArea::VideoArea (QWidget* parent, DeviceInfo* i)
    : QWidget(parent),
      ui(new Ui::VideoArea),
      device(nullptr),
      received_new_image(false),
      playing(false)
{
    ui->setupUi(this);

    if (i != nullptr)
    {
        device = std::make_shared<tcam::CaptureDevice>(*i);
    }

    //new QShortcut(QKeySequence(tr("Ctrl-SPACE")), this, SLOT(action()), 0, Qt::WidgetShortcut);
}

VideoArea::~VideoArea ()
{
    delete ui;
}

void VideoArea::start ()
{
    if (device == nullptr)
    {
        return;
    }

    sink = std::make_shared<ImageSink>();

    sink->registerCallback(this->callback, this);

    bool ret = device->start_stream(sink);

    if (ret == true)
    {
        std::cout << "RUNNING..." << std::endl;
        playing = true;
    }
}

void VideoArea::stop ()
{

    device->stop_stream();
    playing = false;
}

bool VideoArea::setVideoFormat (const tcam::VideoFormat& format)
{
    if (playing)
    {
        return false;
    }

    return device->set_video_format(format);
}

tcam::VideoFormat VideoArea::getVideoFormat () const
{
    return device->get_active_video_format();
}

std::vector<tcam::VideoFormatDescription> VideoArea::getAvailableVideoFormats () const
{
    return device->get_available_video_formats();
}

QTreeWidget* VideoArea::get_property_tree (QWidget* p)
{
    return create_property_tree(p, device->get_available_properties());
}

void VideoArea::callback (MemoryBuffer* buffer, void* user_data)
{
    VideoArea* self = static_cast<VideoArea*>(user_data);

    self->internal_callback(buffer);
}

void VideoArea::internal_callback(MemoryBuffer* buffer)
{
    if (buffer->get_data() == NULL || buffer->getImageBuffer().length == 0)
    {
        return;
    }

    // if (buffer->getImageBuffer().format.height != active_format.getSize().height|| buffer->getImageBuffer().format.width != active_format.getSize().width)
    // {
    //     std::cout << "Faulty format!!!" << std::endl;
    //     return;
    // }

    // TODO:
    if (buffer->getImageBuffer().pitch == 0 )
    {
        return;
    }

    auto buf = buffer->getImageBuffer();
    unsigned int height = buffer->getImageBuffer().format.height;
    unsigned int width = buffer->getImageBuffer().format.width;

    if (buf.format.fourcc == FOURCC_Y800)
    {
        this->m = QPixmap::fromImage(QImage(buf.pData,
                                            width, height,
                                            QImage::Format_Indexed8));
    }
    else if (buf.format.fourcc == FOURCC_Y16)
    {
        this->m = QPixmap::fromImage(QImage(buf.pData,
                                            width, height,
                                            QImage::Format_Mono));
    }
    else if (buf.format.fourcc == FOURCC_RGB24)
    {
        QImage image = QImage(buf.pData,
                              width, height,
                              QImage::Format_RGB888);
        // rgb24 is really bgr, thus swap r <-> b
        this->m = QPixmap::fromImage(image.rgbSwapped());
    }
    else if (buf.format.fourcc == FOURCC_RGB32)
    {
        this->m = QPixmap::fromImage(QImage(buf.pData,
                                            width, height,
                                            QImage::Format_RGB32));
    }
    else
    {
        std::cout << "Unable to interpret buffer format" << std::endl;
        return;
    }

    this->received_new_image = true;
    this->update();

}

void VideoArea::paintEvent (QPaintEvent* e)
{

    if (m.width() == 0)
    {
        return;
    }

    if (received_new_image)
    {
        unsigned int w = ui->label->width();
        unsigned int h = ui->label->height();
        auto l = this->layout();

        int margin = l->margin();

        // ui->label->setPixmap(m.scaled(w - margin,
        //                               h -margin,
        //                               Qt::KeepAspectRatio,
        //                               Qt::FastTransformation ));

        ui->label->setPixmap(m);

        // ui->label->setPixmap(m.scaled(w,
        //                               h,
        //                               Qt::KeepAspectRatio));

        // ,
                                      // Qt::FastTransformation ));

        new_image=false;
        received_new_image = false;
    }
}

void VideoArea::resizeEvent (QResizeEvent* event)
{
    //std::cout << "RESIZE!!!" << std::endl;

  // get label dimensions
  int w = ui->label->width();
  int h = ui->label->height();

  // set a scaled pixmap to a w x h window keeping its aspect ratio
  // ui->label->setPixmap(m.scaled(w, h, Qt::KeepAspectRatio));
  ui->label->setPixmap(m);

  //ui->label->adjustSize();

}
<commit_msg>Remove commented code<commit_after>#include "VideoArea.h"
#include "ui_VideoArea.h"

#include "tcam_qt4.h"

#include <iostream>

using namespace tcam;

VideoArea::VideoArea (QWidget* parent, DeviceInfo* i)
    : QWidget(parent),
      ui(new Ui::VideoArea),
      device(nullptr),
      received_new_image(false),
      playing(false)
{
    ui->setupUi(this);

    if (i != nullptr)
    {
        device = std::make_shared<tcam::CaptureDevice>(*i);
    }

    //new QShortcut(QKeySequence(tr("Ctrl-SPACE")), this, SLOT(action()), 0, Qt::WidgetShortcut);
}

VideoArea::~VideoArea ()
{
    delete ui;
}

void VideoArea::start ()
{
    if (device == nullptr)
    {
        return;
    }

    sink = std::make_shared<ImageSink>();

    sink->registerCallback(this->callback, this);

    bool ret = device->start_stream(sink);

    if (ret == true)
    {
        std::cout << "RUNNING..." << std::endl;
        playing = true;
    }
}

void VideoArea::stop ()
{

    device->stop_stream();
    playing = false;
}

bool VideoArea::setVideoFormat (const tcam::VideoFormat& format)
{
    if (playing)
    {
        return false;
    }

    return device->set_video_format(format);
}

tcam::VideoFormat VideoArea::getVideoFormat () const
{
    return device->get_active_video_format();
}

std::vector<tcam::VideoFormatDescription> VideoArea::getAvailableVideoFormats () const
{
    return device->get_available_video_formats();
}

QTreeWidget* VideoArea::get_property_tree (QWidget* p)
{
    return create_property_tree(p, device->get_available_properties());
}

void VideoArea::callback (MemoryBuffer* buffer, void* user_data)
{
    VideoArea* self = static_cast<VideoArea*>(user_data);

    self->internal_callback(buffer);
}

void VideoArea::internal_callback(MemoryBuffer* buffer)
{
    if (buffer->get_data() == NULL || buffer->getImageBuffer().length == 0)
    {
        return;
    }

    // if (buffer->getImageBuffer().format.height != active_format.getSize().height|| buffer->getImageBuffer().format.width != active_format.getSize().width)
    // {
    //     std::cout << "Faulty format!!!" << std::endl;
    //     return;
    // }

    // TODO:
    if (buffer->getImageBuffer().pitch == 0 )
    {
        return;
    }

    auto buf = buffer->getImageBuffer();
    unsigned int height = buffer->getImageBuffer().format.height;
    unsigned int width = buffer->getImageBuffer().format.width;

    if (buf.format.fourcc == FOURCC_Y800)
    {
        this->m = QPixmap::fromImage(QImage(buf.pData,
                                            width, height,
                                            QImage::Format_Indexed8));
    }
    else if (buf.format.fourcc == FOURCC_Y16)
    {
        this->m = QPixmap::fromImage(QImage(buf.pData,
                                            width, height,
                                            QImage::Format_Mono));
    }
    else if (buf.format.fourcc == FOURCC_RGB24)
    {
        QImage image = QImage(buf.pData,
                              width, height,
                              QImage::Format_RGB888);
        // rgb24 is really bgr, thus swap r <-> b
        this->m = QPixmap::fromImage(image.rgbSwapped());
    }
    else if (buf.format.fourcc == FOURCC_RGB32)
    {
        this->m = QPixmap::fromImage(QImage(buf.pData,
                                            width, height,
                                            QImage::Format_RGB32));
    }
    else
    {
        std::cout << "Unable to interpret buffer format" << std::endl;
        return;
    }

    this->received_new_image = true;
    this->update();

}

void VideoArea::paintEvent (QPaintEvent* e)
{

    if (m.width() == 0)
    {
        return;
    }

    if (received_new_image)
    {
        ui->label->setPixmap(m);

        new_image=false;
        received_new_image = false;
    }
}

void VideoArea::resizeEvent (QResizeEvent* /* event */)
{
  // set a scaled pixmap to a w x h window keeping its aspect ratio
  // ui->label->setPixmap(m.scaled(w, h, Qt::KeepAspectRatio));
  ui->label->setPixmap(m);

  //ui->label->adjustSize();

}
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "condor_daemon_core.h"
// for 'param' function
#include "condor_config.h"

#include "BaseReplicaTransferer.h"
#include "FilesOperations.h"
#include "Utils.h"

BaseReplicaTransferer::BaseReplicaTransferer(
                                 const MyString&  pDaemonSinfulString,
                                 const MyString&  pVersionFilePath,
                                 //const MyString&  pStateFilePath ):
								 const StringList& pStateFilePathsList ):
   m_daemonSinfulString( pDaemonSinfulString ),
   m_versionFilePath( pVersionFilePath ),
   //m_stateFilePathsList( pStateFilePathsList ),
   m_socket( 0 ),
   m_connectionTimeout( DEFAULT_SEND_COMMAND_TIMEOUT ),
   m_maxTransferLifetime( DEFAULT_MAX_TRANSFER_LIFETIME )
{
	// 'malloc'-allocated string
	char* stateFilePathsAsString =
		const_cast<StringList&>(pStateFilePathsList).print_to_string();
	// copying the string lists
	if ( stateFilePathsAsString ) {
		m_stateFilePathsList.initializeFromString( stateFilePathsAsString );
	}
	free( stateFilePathsAsString );
}

BaseReplicaTransferer::~BaseReplicaTransferer()
{
        delete m_socket;
}

int
BaseReplicaTransferer::reinitialize( )
{
    dprintf( D_ALWAYS, "BaseReplicaTransferer::reinitialize started\n" );

    char* buffer = param( "HAD_CONNECTION_TIMEOUT" );

    if( buffer ) {
        bool result = false;

		m_connectionTimeout = utilAtoi( buffer, &result );
		//strtol( buffer, 0, 10 );

        if( ! result || m_connectionTimeout <= 0 ) {
            utilCrucialError(
				utilConfigurationError("HAD_CONNECTION_TIMEOUT",
									   "HAD").Value( ) );
        }
        free( buffer );
    } else {
		utilCrucialError(
       		utilNoParameterError("HAD_CONNECTION_TIMEOUT", "HAD").Value( ) );
    }

	m_maxTransferLifetime = param_integer( "MAX_TRANSFER_LIFETIME",
											DEFAULT_MAX_TRANSFER_LIFETIME );
    return TRANSFERER_TRUE;
}

void
BaseReplicaTransferer::safeUnlinkStateAndVersionFiles(
	const StringList& stateFilePathsList,
    const MyString&   versionFilePath,
    const MyString&   extension)
{
	FilesOperations::safeUnlinkFile( versionFilePath.Value( ),
                                     extension.Value( ) );
	StringList& stateFilePathsListRef =
		const_cast<StringList&>(stateFilePathsList);
	stateFilePathsListRef.rewind();

	char* stateFilePath = NULL;

	while( ( stateFilePath = stateFilePathsListRef.next( ) ) ) {
		FilesOperations::safeUnlinkFile( stateFilePath,
                                     	 extension.Value( ) );
	}
	stateFilePathsListRef.rewind();
}
<commit_msg>param+nonsense -> param_integer for HAD_CONNECTION_TIMEOUT, documentation said default was 5, code didn't agree in all cases<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "condor_daemon_core.h"
// for 'param' function
#include "condor_config.h"

#include "BaseReplicaTransferer.h"
#include "FilesOperations.h"
#include "Utils.h"

BaseReplicaTransferer::BaseReplicaTransferer(
                                 const MyString&  pDaemonSinfulString,
                                 const MyString&  pVersionFilePath,
                                 //const MyString&  pStateFilePath ):
								 const StringList& pStateFilePathsList ):
   m_daemonSinfulString( pDaemonSinfulString ),
   m_versionFilePath( pVersionFilePath ),
   //m_stateFilePathsList( pStateFilePathsList ),
   m_socket( 0 ),
   m_connectionTimeout( DEFAULT_SEND_COMMAND_TIMEOUT ),
   m_maxTransferLifetime( DEFAULT_MAX_TRANSFER_LIFETIME )
{
	// 'malloc'-allocated string
	char* stateFilePathsAsString =
		const_cast<StringList&>(pStateFilePathsList).print_to_string();
	// copying the string lists
	if ( stateFilePathsAsString ) {
		m_stateFilePathsList.initializeFromString( stateFilePathsAsString );
	}
	free( stateFilePathsAsString );
}

BaseReplicaTransferer::~BaseReplicaTransferer()
{
        delete m_socket;
}

int
BaseReplicaTransferer::reinitialize( )
{
    dprintf( D_ALWAYS, "BaseReplicaTransferer::reinitialize started\n" );

	m_connectionTimeout = param_integer("HAD_CONNECTION_TIMEOUT",
										DEFAULT_SEND_COMMAND_TIMEOUT,
										0); // min value

	m_maxTransferLifetime = param_integer( "MAX_TRANSFER_LIFETIME",
											DEFAULT_MAX_TRANSFER_LIFETIME );
    return TRANSFERER_TRUE;
}

void
BaseReplicaTransferer::safeUnlinkStateAndVersionFiles(
	const StringList& stateFilePathsList,
    const MyString&   versionFilePath,
    const MyString&   extension)
{
	FilesOperations::safeUnlinkFile( versionFilePath.Value( ),
                                     extension.Value( ) );
	StringList& stateFilePathsListRef =
		const_cast<StringList&>(stateFilePathsList);
	stateFilePathsListRef.rewind();

	char* stateFilePath = NULL;

	while( ( stateFilePath = stateFilePathsListRef.next( ) ) ) {
		FilesOperations::safeUnlinkFile( stateFilePath,
                                     	 extension.Value( ) );
	}
	stateFilePathsListRef.rewind();
}
<|endoftext|>


<commit_before>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__

#include <sstream>
#include <iostream>

#include "point.hpp"

namespace util {

template <typename T>
struct rect {

	/**
	 * Default constructor.
	 */
	rect() {};

	rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
		minX(minX_),
		minY(minY_),
		maxX(maxX_),
		maxY(maxY_) {};

	T minX;
	T minY;
	T maxX;
	T maxY;

	T width() const {

		return maxX - minX;
	}

	T height() const {

		return maxY - minY;
	}

	bool intersects(const rect<T>& other) const {

		// two non-intersecting rectanlges are separated by a line parallel to
		// either x or y

		// separated by x-line
		if (maxX < other.minX || minX > other.maxX)
			return false;

		// separated by y-line
		if (maxY < other.minY || minY > other.maxY)
			return false;

		return true;
	}

	bool contains(const point<T>& point) const {

		return minX <= point.x && minY <= point.y && maxX >= point.x && maxY >= point.y;
	}

	template <typename S>
	rect<T>& operator+=(const point<S>& other) {

		minX += other.x;
		maxX += other.x;
		minY += other.y;
		maxY += other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator-=(const point<S>& other) {

		minX -= other.x;
		maxX -= other.x;
		minY -= other.y;
		maxY -= other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const S& s) {

		minX *= s;
		maxX *= s;
		minY *= s;
		maxY *= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const S& s) {

		minX /= s;
		maxX /= s;
		minY /= s;
		maxY /= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const point<S>& p) {

		minX *= p.x;
		maxX *= p.x;
		minY *= p.y;
		maxY *= p.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const point<S>& p) {

		minX /= p.x;
		maxX /= p.x;
		minY /= p.y;
		maxY /= p.y;

		return *this;
	}

	template <typename S>
	bool operator==(const rect<S>& other) const {

		return minX == other.minX &&
		       minY == other.minY &&
		       maxX == other.maxX &&
		       maxY == other.maxY;
	}

	template <typename S>
	bool operator!=(const rect<S>& other) const {

		return !(*this == other);
	}
};

template <typename T, typename S>
rect<T> operator+(const rect<T>& p, const point<S>& o) {

	rect<T> result(p);

	return result += o;
}

template <typename T, typename S>
rect<T> operator-(const rect<T>& p, const point<S>& o) {

	rect<T> result(p);

	return result -= o;
}

template <typename T, typename S>
rect<T> operator*(const rect<T>& p, const S& s) {

	rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
rect<T> operator/(const rect<T>& p, const S& s) {

	rect<T> result(p);

	return result /= s;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const rect<T>& rect) {

	os << "[" << rect.minX << ", " << rect.minY
	   << ", " << rect.maxX << ", " << rect.maxY << "]";

	return os;
}

} // namespace util

#endif // UTIL_RECT_H__

<commit_msg>made 'contains' query in rect exclude left and bottom border<commit_after>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__

#include <sstream>
#include <iostream>

#include "point.hpp"

namespace util {

template <typename T>
struct rect {

	/**
	 * Default constructor.
	 */
	rect() {};

	template <typename S>
	rect(const rect<S>& other) :
		minX(other.minX),
		minY(other.minY),
		maxX(other.maxX),
		maxY(other.maxY) {};

	rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
		minX(minX_),
		minY(minY_),
		maxX(maxX_),
		maxY(maxY_) {};

	T minX;
	T minY;
	T maxX;
	T maxY;

	T width() const {

		return maxX - minX;
	}

	T height() const {

		return maxY - minY;
	}

	bool intersects(const rect<T>& other) const {

		// two non-intersecting rectanlges are separated by a line parallel to
		// either x or y

		// separated by x-line
		if (maxX < other.minX || minX > other.maxX)
			return false;

		// separated by y-line
		if (maxY < other.minY || minY > other.maxY)
			return false;

		return true;
	}

	bool contains(const point<T>& point) const {

		return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y;
	}

	template <typename S>
	rect<T>& operator+=(const point<S>& other) {

		minX += other.x;
		maxX += other.x;
		minY += other.y;
		maxY += other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator-=(const point<S>& other) {

		minX -= other.x;
		maxX -= other.x;
		minY -= other.y;
		maxY -= other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const S& s) {

		minX *= s;
		maxX *= s;
		minY *= s;
		maxY *= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const S& s) {

		minX /= s;
		maxX /= s;
		minY /= s;
		maxY /= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const point<S>& p) {

		minX *= p.x;
		maxX *= p.x;
		minY *= p.y;
		maxY *= p.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const point<S>& p) {

		minX /= p.x;
		maxX /= p.x;
		minY /= p.y;
		maxY /= p.y;

		return *this;
	}

	template <typename S>
	bool operator==(const rect<S>& other) const {

		return minX == other.minX &&
		       minY == other.minY &&
		       maxX == other.maxX &&
		       maxY == other.maxY;
	}

	template <typename S>
	bool operator!=(const rect<S>& other) const {

		return !(*this == other);
	}
};

template <typename T, typename S>
rect<T> operator+(const rect<T>& p, const point<S>& o) {

	rect<T> result(p);

	return result += o;
}

template <typename T, typename S>
rect<T> operator-(const rect<T>& p, const point<S>& o) {

	rect<T> result(p);

	return result -= o;
}

template <typename T, typename S>
rect<T> operator*(const rect<T>& p, const S& s) {

	rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
rect<T> operator/(const rect<T>& p, const S& s) {

	rect<T> result(p);

	return result /= s;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const rect<T>& rect) {

	os << "[" << rect.minX << ", " << rect.minY
	   << ", " << rect.maxX << ", " << rect.maxY << "]";

	return os;
}

} // namespace util

#endif // UTIL_RECT_H__

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////
// nth_prime.cpp
// Find the nth prime.
// Usage: $ ./nth_prime 999

#include <primesieve/soe/PrimeSieve.h>
#include <iostream>
#include <cstdlib>
#include <limits>
#include <exception>

class stop_primesieve : public std::exception { };

int n = 100000000;
int count = 0;

void nthprime(unsigned int prime)
{
  if (++count == n) {
    std::cout << n << "th prime = " << prime << std::endl;
    throw stop_primesieve();
  }
}

int main(int, char** argv)
{
  if (argv[1])
    n = atoi(argv[1]);
  try {
    PrimeSieve ps;
    ps.generatePrimes(0, std::numeric_limits<int>::max(), nthprime);
  }
  catch (stop_primesieve&) { }
  return 0;
}
<commit_msg>count variable name conflicts with std::count from <algorithm> (pgcpp compiler)<commit_after>////////////////////////////////////////////////////////////////////
// nth_prime.cpp
// Find the nth prime.
// Usage: $ ./nth_prime 999

#include <primesieve/soe/PrimeSieve.h>
#include <iostream>
#include <cstdlib>
#include <limits>
#include <exception>

class stop_primesieve : public std::exception { };

int n = 100000000;
int i = 0;

void nthprime(unsigned int prime)
{
  if (++i == n) {
    std::cout << n << "th prime = " << prime << std::endl;
    throw stop_primesieve();
  }
}

int main(int, char** argv)
{
  if (argv[1])
    n = atoi(argv[1]);
  try {
    PrimeSieve ps;
    ps.generatePrimes(0, std::numeric_limits<int>::max(), nthprime);
  }
  catch (stop_primesieve&) { }
  return 0;
}
<|endoftext|>