<commit_before>/* main.cpp
 *
 * Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Implement robot_class to provide functionality for robot.
 */

#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
#include "visionalg.h"
#include "shifter.h"

//constructor - initialize drive
robot_class::robot_class() {
    //do nothing
    GetWatchdog().SetEnabled(false); //we don't want Watchdog
}

void robot_class::RobotInit() {
    //Run-Time INIT
    //set necessary inversions
    drive.SetInvertedMotor(left_front_motor.type,  left_front_motor.reverse);
    drive.SetInvertedMotor(left_rear_motor.type,   left_rear_motor.reverse);
    drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
    drive.SetInvertedMotor(right_rear_motor.type,  right_rear_motor.reverse);
    global_state.set_state(STATE_DRIVING);
    init_camera();
}

void robot_class::DisabledInit() {
    //do nothing
}

void robot_class::AutonomousInit() {
    //do nothing
}

void robot_class::TeleopInit() {
    //do nothing
}

void robot_class::DisabledPeriodic() {
    //do nothing
}

void robot_class::AutonomousPeriodic() {
    update_sensors();
}

void robot_class::TeleopPeriodic() {
    update_sensors();
}

void robot_class::DisabledContinuous() {
    //do nothing
}

void robot_class::AutonomousContinuous() {
    //do nothing
}

void robot_class::TeleopContinuous() {
    if(global_state.get_state() == STATE_DRIVING) {
        //Turret rotation controlled by gunner joystick during drive state only. Must press button 1
        if (gunner_joystick.GetRawButton(1)) {
            turret_rotation_jag.Set(gunner_joystick.GetX());
        }
        if (left_joystick.GetRawButton(1)) {
            //arcade drive
            drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
        }
        else {
            //tank drive
            float left = left_joystick.GetY();
            float right = right_joystick.GetY();
            //explicitly state drive power is based on Y axis of that side joy
            drive.TankDrive(left, right);
        }
        if (right_joystick.GetRawButton(11) || left_joystick.GetRawButton(11)) {
            servo_shifter.set(shifter::HIGH);
            // set servo to high gear
        }
        else if (left_joystick.GetRawButton(10) || right_joystick.GetRawButton(10)) {
            servo_shifter.set(shifter::LOW);
            //Sets servo to low gear
        }
        if(left_joystick.GetRawButton(3)) {
            global_state.set_state(STATE_SHOOTING);
        }
        //Turret rotation controlled by gunner joystick during drive state only. Must press button 1
        if(gunner_joystick.GetRawButton(1)) {
            turret_rotation_jag.Set(gunner_joystick.GetX());
        }
        if(bridge_arm_switch.Get() == 1){//limit switch is pressed
            bridge_arm_spike.Set(Relay::kOff);
        }
        else {
            bridge_arm_spike.Set(Relay::kOn);
            if(gunner_joystick.GetRawButton(2)){//up
               bridge_arm_spike.Set(Relay::kForward);
            }
            if(gunner_joystick.GetRawButton(3)){//down
               bridge_arm_spike.Set(Relay::kReverse);
            }
        }
        if(gunner_joystick.GetRawButton(10)) {
            turret_winch_jag.Set(0.1);
        }
        else if(gunner_joystick.GetRawButton(11)) {
            turret_winch_jag.Set(-0.1);
        }
        if(gunner_joystick.GetRawButton(9)) {
            printf("pot voltage: %f\n", launch_angle_pot.GetVoltage());
        }
    }
    else if(global_state.get_state() == STATE_SHOOTING) {
        // disable motor safety check to stop wasting netconsole space
        drive.SetSafetyEnabled(false);
        vision_processing::update();
        vector<double> target_degrees = vision_processing::get_degrees();
        vector<double> target_distances = vision_processing::get_distance();
        printf("Number of targets detected: %d\n", target_degrees.size());
        if(target_degrees.size() >= 1) {
            printf("Angle (degrees) of camera: %f\n", target_degrees[0]);
        }
        else {
            printf("No target detected\n");
        }
        if(target_distances.size() >= 1) {
            printf("Distance of target:       %f\n", target_distances[0]);
        }
        if(!left_joystick.GetRawButton(3)) {
            global_state.set_state(STATE_DRIVING);
            drive.SetSafetyEnabled(true);
        }
    }
    //TEMPORARY: GUNNER LAUNCHER WHEEL CONTROLS
    if (gunner_joystick.GetRawButton(7)) {
        left_launcher_jag.Set(1.0);
        right_launcher_jag.Set(1.0);
    }
    else {
        left_launcher_jag.Set(0.0);
        right_launcher_jag.Set(0.0);
    }
    if (global_state.get_state() != STATE_SHOOTING) {
        //MANUAL ROLLER CONTROL
        if (gunner_joystick.GetRawButton(11)) {
            //rollers up
            rollers.set_direction(roller_t::UP);
        }
        else if (gunner_joystick.GetRawButton(10)) {
            //rollers down
            rollers.set_direction(roller_t::DOWN);
        }
        else if (gunner_joystick.GetRawButton(9)) {
            rollers.set_direction(roller_t::OFF);
        }
        else {
            //auto belts
        }
        //
        Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
    }
}

void robot_class::update_sensors() {
    //run functions in update registry
    registry().update();
}

//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
<commit_msg>fixes for motor testing code<commit_after>/* main.cpp
 *
 * Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Implement robot_class to provide functionality for robot.
 */

#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
#include "visionalg.h"
#include "shifter.h"

//constructor - initialize drive
robot_class::robot_class() {
    //do nothing
    GetWatchdog().SetEnabled(false); //we don't want Watchdog
}

void robot_class::RobotInit() {
    //Run-Time INIT
    //set necessary inversions
    drive.SetInvertedMotor(left_front_motor.type,  left_front_motor.reverse);
    drive.SetInvertedMotor(left_rear_motor.type,   left_rear_motor.reverse);
    drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
    drive.SetInvertedMotor(right_rear_motor.type,  right_rear_motor.reverse);
    global_state.set_state(STATE_DRIVING);
    init_camera();
}

void robot_class::DisabledInit() {
    //do nothing
}

void robot_class::AutonomousInit() {
    //do nothing
}

void robot_class::TeleopInit() {
    //do nothing
}

void robot_class::DisabledPeriodic() {
    //do nothing
}

void robot_class::AutonomousPeriodic() {
    update_sensors();
}

void robot_class::TeleopPeriodic() {
    update_sensors();
}

void robot_class::DisabledContinuous() {
    //do nothing
}

void robot_class::AutonomousContinuous() {
    //do nothing
}

void robot_class::TeleopContinuous() {
    if(global_state.get_state() == STATE_DRIVING) {
        //Turret rotation controlled by gunner joystick during drive state only. Must press button 1
        if (gunner_joystick.GetRawButton(1)) {
            turret_rotation_jag.Set(-gunner_joystick.GetX());
        }
        if (left_joystick.GetRawButton(1)) {
            //arcade drive
            drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
        }
        else {
            //tank drive
            float left = left_joystick.GetY();
            float right = right_joystick.GetY();
            //explicitly state drive power is based on Y axis of that side joy
            drive.TankDrive(left, right);
        }
        if (right_joystick.GetRawButton(11) || left_joystick.GetRawButton(11)) {
            servo_shifter.set(shifter::HIGH);
            // set servo to high gear
        }
        else if (left_joystick.GetRawButton(10) || right_joystick.GetRawButton(10)) {
            servo_shifter.set(shifter::LOW);
            //Sets servo to low gear
        }
        if(left_joystick.GetRawButton(3)) {
            global_state.set_state(STATE_SHOOTING);
        }
        //Turret rotation controlled by gunner joystick during drive state only. Must press button 1
        if(gunner_joystick.GetRawButton(1)) {
            turret_rotation_jag.Set(gunner_joystick.GetX());
        }
        if(bridge_arm_switch.Get() == 1){//limit switch is pressed
            bridge_arm_spike.Set(Relay::kOff);
        }
        else {
            bridge_arm_spike.Set(Relay::kOn);
            if(gunner_joystick.GetRawButton(2)){//up
               bridge_arm_spike.Set(Relay::kForward);
            }
            if(gunner_joystick.GetRawButton(3)){//down
               bridge_arm_spike.Set(Relay::kReverse);
            }
        }
        if(gunner_joystick.GetRawButton(6)) {
            turret_winch_jag.Set(-0.2);
        }
        else if(gunner_joystick.GetRawButton(7)) {
            turret_winch_jag.Set(0.2);
        }
        else {
            turret_winch_jag.Set(0.0);
        }
        if(gunner_joystick.GetRawButton(9)) {
            printf("pot voltage: %f\n", launch_angle_pot.GetVoltage());
        }
    }
    else if(global_state.get_state() == STATE_SHOOTING) {
        // disable motor safety check to stop wasting netconsole space
        drive.SetSafetyEnabled(false);
        vision_processing::update();
        vector<double> target_degrees = vision_processing::get_degrees();
        vector<double> target_distances = vision_processing::get_distance();
        printf("Number of targets detected: %d\n", target_degrees.size());
        if(target_degrees.size() >= 1) {
            printf("Angle (degrees) of camera: %f\n", target_degrees[0]);
        }
        else {
            printf("No target detected\n");
        }
        if(target_distances.size() >= 1) {
            printf("Distance of target:       %f\n", target_distances[0]);
        }
        if(!left_joystick.GetRawButton(3)) {
            global_state.set_state(STATE_DRIVING);
            drive.SetSafetyEnabled(true);
        }
    }
    //TEMPORARY: GUNNER LAUNCHER WHEEL CONTROLS
    if (gunner_joystick.GetRawButton(4)) {
        left_launcher_jag.Set(1.0);
        right_launcher_jag.Set(1.0);
    }
    else {
        left_launcher_jag.Set(0.0);
        right_launcher_jag.Set(0.0);
    }
    if (global_state.get_state() != STATE_SHOOTING) {
        //MANUAL ROLLER CONTROL
        if (gunner_joystick.GetRawButton(11)) {
            //rollers up
            rollers.set_direction(roller_t::UP);
        }
        else if (gunner_joystick.GetRawButton(10)) {
            //rollers down
            rollers.set_direction(roller_t::DOWN);
        }
        else if (gunner_joystick.GetRawButton(9)) {
            rollers.set_direction(roller_t::OFF);
        }
        else {
            //auto belts
        }
        //
        Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
    }
}

void robot_class::update_sensors() {
    //run functions in update registry
    registry().update();
}

//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
<|endoftext|>


<commit_before>1511820c-ad5a-11e7-a8c2-ac87a332f658<commit_msg>more bug fix<commit_after>158ee09e-ad5a-11e7-aac3-ac87a332f658<|endoftext|>


<commit_before>#include "staging/thread_collector.hpp"
#include "playground.hpp"

//template<typename T>
//using deleted_unique_ptr = std::unique_ptr<T, std::function<void(T*)>>;

int main(int argc, char *argv[])
{
    std::cout << argv[0] << " running" << std::endl;

    //deleted_unique_ptr<bullshit> bullptr(new bullshit, [](auto p) { delete p; });

    auto bullptr2 = std::make_shared<bullshit>();

    const auto runner = [bull = std::move(bullptr2)](const unsigned ms = 500) {
        bull->hello();
        std::this_thread::sleep_for(std::chrono::milliseconds(ms));
        //throw std::exception();
    };

    staging::thread_collector collector_default;
    staging::thread_collector collector(runner);
    collector.spawn(runner);
    collector.spawn(runner, 40);

    collector_default = std::move(collector);
    collector_default.swap(collector);

    /*auto thread_count = 10000;
    while (thread_count--)
        collector.spawn(runner);*/

    collector_default.join();
    collector.join();

    //std::thread wtf(runner);

    std::cout << argv[0] << " finished" << std::endl;
    return EXIT_SUCCESS;
}
<commit_msg>testing with silly amount of threads<commit_after>#include "staging/thread_collector.hpp"
#include "playground.hpp"

//template<typename T>
//using deleted_unique_ptr = std::unique_ptr<T, std::function<void(T*)>>;

int main(int argc, char *argv[])
{
    std::cout << argv[0] << " running" << std::endl;

    //deleted_unique_ptr<bullshit> bullptr(new bullshit, [](auto p) { delete p; });

    auto bullptr2 = std::make_shared<bullshit>();

    const auto runner = [bull = std::move(bullptr2)](const unsigned ms = 500) {
        bull->hello();
        std::this_thread::sleep_for(std::chrono::milliseconds(ms));
        //throw std::exception();
    };

    staging::thread_collector collector_default;
    staging::thread_collector collector(runner);
    collector.spawn(runner);
    collector.spawn(runner, 40);

    collector_default = std::move(collector);
    collector_default.swap(collector);

    auto thread_count = 40000;
    while (thread_count--)
        collector.spawn(runner);

    collector_default.join();
    collector.join();

    //std::thread wtf(runner);

    std::cout << argv[0] << " finished" << std::endl;
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include "frameRate.h"

int main()
{
	sf::RenderWindow window(sf::VideoMode(800,600), "Project Topgun");
	window.setVerticalSyncEnabled(true);

	sf::Font font;
	if(false == font.loadFromFile("waltographUI.ttf"))
		return -1;

	FrameRate frameRate(font);

	sf::Texture pcTexture;
	if(false == pcTexture.loadFromFile("Biplane.png"))
		return -1;
	sf::Sprite pc;
	pc.setTexture(pcTexture);
	pc.setScale(0.1f, 0.1f);
	const auto pcBound = pc.getLocalBounds();
	pc.setOrigin(pcBound.width / 2.f, pcBound.height / 2.f);
	pc.setPosition(pc.getGlobalBounds().width, window.getSize().y / 2);

	while(window.isOpen())
	{
		sf::Event event;
		while(window.pollEvent(event))
		{
			if(sf::Event::Closed == event.type)
				window.close();
		}

		sf::Vector2f move(0, 0);
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
			move.x -= 1;
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
			move.x += 1;
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
			move.y -= 1;
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
			move.y += 1;
		pc.move(move);

		window.clear(sf::Color::White);

		frameRate.draw(window);

		window.draw(pc);

		window.display();
	}

	return 0;
}
<commit_msg>add adjustment by speed<commit_after>#include <SFML/Graphics.hpp>
#include "frameRate.h"

int main()
{
	sf::RenderWindow window(sf::VideoMode(800,600), "Project Topgun");
	window.setVerticalSyncEnabled(true);

	sf::Font font;
	if(false == font.loadFromFile("waltographUI.ttf"))
		return -1;

	FrameRate frameRate(font);

	sf::Texture pcTexture;
	if(false == pcTexture.loadFromFile("Biplane.png"))
		return -1;
	sf::Sprite pc;
	pc.setTexture(pcTexture);
	pc.setScale(0.1f, 0.1f);
	const auto pcBound = pc.getLocalBounds();
	pc.setOrigin(pcBound.width / 2.f, pcBound.height / 2.f);
	pc.setPosition(pc.getGlobalBounds().width, window.getSize().y / 2);

	sf::Clock clock;
	while(window.isOpen())
	{
		auto elapsedTime = clock.restart();

		sf::Event event;
		while(window.pollEvent(event))
		{
			if(sf::Event::Closed == event.type)
				window.close();
		}

		sf::Vector2f move(0, 0);
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
			move.x -= 1;
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
			move.x += 1;
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
			move.y -= 1;
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
			move.y += 1;
		pc.move(move * 100.f * elapsedTime.asSeconds());

		window.clear(sf::Color::White);

		frameRate.draw(window);

		window.draw(pc);

		window.display();
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

using namespace std;

//function to convert a vector of char * to a
//char * [] for use as an execvp argument
char ** conv_vec(vector<char*> v)
{
    //create a char * [] of proper size
    char ** t = new char* [v.size() + 1];

    //counter to keep track of the position
    //for entering char*
    unsigned i = 0;

    for (; i < v.size(); ++i)
    {
        //first make char[] entry of the right length
        t[i] = new char[strlen(v.at(i))];
        //then copy the entire string from the vector
        //into the char *[]
        strcpy(t[i], v.at(i));
    }

    //set the last position to a null character
    t[i] = '\0';

    return t;
}

char ** get_command(string& a, int flag)
{
    //first make a copy of the command string
    //so that we can check what delimiter strtok
    //stopped at
    char * copy = new char [a.length() + 1];
    strcpy(copy, a.c_str());

    //create a vector because we do not know
    //how many tokens are in the command entered
    vector<char *> temp;

    //create an empty char * [] to return. It can
    //either be empty if there is no input or
    //filled later when we convert the vector
    //into an array
    char ** vec = NULL;

    //bool done = false;
    //set a starting position to reference when
    //finding the position of the delimiter found
    char * begin = copy;

    //take the first token
    char * token = strtok(copy, " ;|&");

    //for position of delimiter
    unsigned int pos;

    while (token != 0)
    {
//        cout << token << endl;

        //the position of the delimiter with respect
        //to the beginning of the array
        pos = token - begin + strlen(token);

        //put the token at the end of the vector
        temp.push_back(token);

        //to find out which delimiter was found
        //if it was the end, it will not go through this
        if (pos < a.size())
        {
            //store delimiter character found
            char delim = a.at(pos);
//            cout << delim << endl;

            if (delim != ' ')
            {
                //if it was not ' ' then we have reached a
                //delimiter that indicates the end of the
                //command so we are done. Convert
                //the vector into the proper char * []
                vec = conv_vec(temp);

//                for (unsigned i = 0; vec[i] != 0; ++i)
//                {
//                    cout << i << endl;
//                    cout << vec[i] <<  endl;
//                }

                //remember to get rid of the dynamically allocated
                delete copy;

                if (delim == '|')
                {
                    //set flag bit
                    flag = 1;
                }
                else if (delim == '&')
                {
                    //set flag bit to 2
                    flag = 2;
                }
                else
                {
                    //then it was ; so set flag bit to 0
                    flag = 0;
                }

                a = a.substr(pos + 1, a.size() - pos + 1);

                return vec;
            }

        }

        token = strtok(NULL, " ;|&");
    }

    a = "";

    vec = conv_vec(temp);

    delete copy;

    flag = 0;

    return vec;
}

void display_prompt()
{
    cout << "$ ";
}

int main()
{
    int flag = 0;
    while (1)
    {

        display_prompt();
        string command;
        getline(cin, command);
        char ** argv = get_command(command, flag);

        cout << command << endl;

        if (strcmp(argv[0], "exit") == 0)
        {
            return 0;
        }

        for (int i = 0; argv[i] != 0; ++i)
        {
            cout << argv[i] << endl;
        }

        int fork_flag = fork();
        if (fork_flag == -1)
        {
            perror("fork");

            return 1;
        }
        else if (fork_flag == 0)
        {
            int execvp_flag = execvp(argv[0], argv);
            if (execvp_flag == -1)
            {
                perror("execvp");
                return 1;
            }
        }

        int wait_flag = wait(NULL);
        if (wait_flag == -1)
        {
            perror("wait");
            return 1;
        }
    }

    return 0;
}
<commit_msg>Edited get_command, display_prompt, and main<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

using namespace std;

//function to convert a vector of char * to a
//char * [] for use as an execvp argument
char ** conv_vec(vector<char*> v)
{
    //create a char * [] of proper size
    char ** t = new char* [v.size() + 1];

    //counter to keep track of the position
    //for entering char*
    unsigned i = 0;

    for (; i < v.size(); ++i)
    {
        //first make char[] entry of the right length
        t[i] = new char[strlen(v.at(i))];
        //then copy the entire string from the vector
        //into the char *[]
        strcpy(t[i], v.at(i));
    }

    //set the last position to a null character
    t[i] = '\0';

    return t;
}

char ** get_command(string& a, int& flag)
{
    //first make a copy of the command string
    //so that we can check what delimiter strtok
    //stopped at
    char * copy = new char [a.length() + 1];
    strcpy(copy, a.c_str());

    //create a vector because we do not know
    //how many tokens are in the command entered
    vector<char *> temp;

    //create an empty char * [] to return. It can
    //either be empty if there is no input or
    //filled later when we convert the vector
    //into an array
    char ** vec = NULL;

    //bool done = false;
    //set a starting position to reference when
    //finding the position of the delimiter found
    char * begin = copy;

    //take the first token
    char * token = strtok(copy, " ;|&");

    //for position of delimiter
    unsigned int pos;

    while (token != 0)
    {
//        cout << token << endl;

        //the position of the delimiter with respect
        //to the beginning of the array
        pos = token - begin + strlen(token);

        //put the token at the end of the vector
        temp.push_back(token);

        //to find out which delimiter was found
        //if it was the end, it will not go through this
        if (pos < a.size())
        {
            //store delimiter character found
            char delim = a.at(pos);
//            cout << delim << endl;

            if (delim != ' ' || (pos + 1 < a.size() && (a.at(pos + 1) == '&' ||
                a.at(pos + 1) == '|')))
            {
                //if it was not ' ' then we have reached a
                //delimiter that indicates the end of the
                //command so we are done. Convert
                //the vector into the proper char * []
                vec = conv_vec(temp);

//                for (unsigned i = 0; vec[i] != 0; ++i)
//                {
//                    cout << i << endl;
//                    cout << vec[i] <<  endl;
//                }

                //remember to get rid of the dynamically allocated
                delete copy;

                if (delim == '|' || (pos + 1 < a.size() && a.at(pos + 1) == '|'))
                {
                    //set flag bit
                    flag = 1;
                }
                else if (delim == '&' || (pos + 1 < a.size() && a.at(pos + 1)
                    == '&'))
                {
                    //set flag bit to 2
                    flag = 2;
                }
                else
                {
                    //then it was ; so set flag bit to 0
                    flag = 0;
                }

                cout << flag << endl;
                a = a.substr(pos + 1, a.size() - pos + 1);

                return vec;
            }

        }

        token = strtok(NULL, " ;|&");
    }

    a = "";

    vec = conv_vec(temp);

    delete copy;

    flag = 0;

    return vec;
}

void display_prompt()
{
    char host[15];

    int host_flag = gethostname(host, sizeof host);
    if(host_flag == -1)
    {
        perror("gethostname");
    }
    char *login = getlogin();
    if (login == 0)
    {
        perror("getlogin");
    }

    cout << login << '@' << host << "$ ";
}

int main()
{
    int flag = 0;
    while (1)
    {

        display_prompt();
        string command;
        getline(cin, command);
        while(flag != 0 || command != "")
        {
            char ** argv = get_command(command, flag);

            cout << command << endl;
            cout << flag << endl;

            if (strcmp(argv[0], "exit") == 0)
            {
                return 0;
            }

            for (int i = 0; argv[i] != 0; ++i)
            {
                cout << argv[i] << endl;
            }

            int fork_flag = fork();
            if (fork_flag == -1)
            {
                perror("fork");

                return 1;
            }
            else if (fork_flag == 0)
            {
                int execvp_flag = execvp(argv[0], argv);
                if (execvp_flag == -1)
                {
                    perror("execvp");
//                    return 1;
                }
            }

            int wait_flag = wait(NULL);
            if (wait_flag == -1)
            {
                perror("wait");
                if (flag == 2)
                {
                    break;
                }
//                return 1;
            }
            if (flag == 1)
            {
                break;
            }
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>d2c309ae-4b02-11e5-81de-28cfe9171a43<commit_msg>Bug fixes and performance improvements<commit_after>d2d0c24c-4b02-11e5-a35e-28cfe9171a43<|endoftext|>


<commit_before>// @(#)root/mathcore:$Id$
// Author: Rene Brun   31/08/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//______________________________________________________________________________
//
//     Abstract Base Class for Fitting

#include "TROOT.h"
#include "TVirtualFitter.h"
#include "TPluginManager.h"
#include "TEnv.h"
#include "TInterpreter.h"
#include "Math/MinimizerOptions.h"

TVirtualFitter *TVirtualFitter::fgFitter    = 0;
Int_t           TVirtualFitter::fgMaxpar    = 0;
// Int_t           TVirtualFitter::fgMaxiter   = 5000;
// Double_t        TVirtualFitter::fgPrecision = 1e-6;
// Double_t        TVirtualFitter::fgErrorDef  = 1;
TString         TVirtualFitter::fgDefault   = "";

ClassImp(TVirtualFitter)

//______________________________________________________________________________
TVirtualFitter::TVirtualFitter()
{
   // Default constructor.

   fMethodCall = 0;
   fFCN        = 0;
   fNpoints    = 0;
   fPointSize  = 0;
   fCacheSize  = 0;
   fCache      = 0;
}

//______________________________________________________________________________
TVirtualFitter::TVirtualFitter(const TVirtualFitter& tvf) :
  TNamed(tvf),
  fOption(tvf.fOption),
  fXfirst(tvf.fXfirst),
  fXlast(tvf.fXlast),
  fYfirst(tvf.fYfirst),
  fYlast(tvf.fYlast),
  fZfirst(tvf.fZfirst),
  fZlast(tvf.fZlast),
  fNpoints(tvf.fNpoints),
  fPointSize(tvf.fPointSize),
  fCacheSize(tvf.fCacheSize),
  fCache(tvf.fCache),
  fObjectFit(tvf.fObjectFit),
  fUserFunc(tvf.fUserFunc),
  fMethodCall(tvf.fMethodCall),
  fFCN(tvf.fFCN)
{
   //copy constructor
}

//______________________________________________________________________________
TVirtualFitter& TVirtualFitter::operator=(const TVirtualFitter& tvf)
{
   //assignment operator
   if(this!=&tvf) {
      TNamed::operator=(tvf);
      fOption=tvf.fOption;
      fXfirst=tvf.fXfirst;
      fXlast=tvf.fXlast;
      fYfirst=tvf.fYfirst;
      fYlast=tvf.fYlast;
      fZfirst=tvf.fZfirst;
      fZlast=tvf.fZlast;
      fNpoints=tvf.fNpoints;
      fPointSize=tvf.fPointSize;
      fCacheSize=tvf.fCacheSize;
      fCache=tvf.fCache;
      fObjectFit=tvf.fObjectFit;
      fUserFunc=tvf.fUserFunc;
      fMethodCall=tvf.fMethodCall;
      fFCN=tvf.fFCN;
   }
   return *this;
}

//______________________________________________________________________________
TVirtualFitter::~TVirtualFitter()
{
   // Cleanup virtual fitter.

   delete fMethodCall;
   delete [] fCache;
   fgFitter    = 0;
   fgMaxpar    = 0;
   fMethodCall = 0;
   fFCN        = 0;
}

//______________________________________________________________________________
TVirtualFitter *TVirtualFitter::Fitter(TObject *obj, Int_t maxpar)
{
   // Static function returning a pointer to the current fitter.
   // If the fitter does not exist, the default TFitter is created.
   // Don't delete the returned fitter object, it will be re-used.

   if (fgFitter && maxpar > fgMaxpar) {
      delete fgFitter;
      fgFitter = 0;
   }

   if (!fgFitter) {
      TPluginHandler *h;
      if (fgDefault.Length() == 0) fgDefault = gEnv->GetValue("Root.Fitter","Minuit");
      if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualFitter",fgDefault))) {
         if (h->LoadPlugin() == -1)
            return 0;
         fgFitter = (TVirtualFitter*) h->ExecPlugin(1, maxpar);
         fgMaxpar = maxpar;
      }
   }

   if (fgFitter) fgFitter->SetObjectFit(obj);
   return fgFitter;
}

//______________________________________________________________________________
void  TVirtualFitter::GetConfidenceIntervals(Int_t /*n*/, Int_t /*ndim*/, const Double_t * /*x*/, Double_t * /*ci*/, Double_t /*cl*/)
{
   //return confidence intervals in array x of dimension ndim
   //implemented in TFitter and TLinearFitter
}

//______________________________________________________________________________
void  TVirtualFitter::GetConfidenceIntervals(TObject * /*obj*/, Double_t /*cl*/)
{
   //return confidence intervals in TObject obj
   //implemented in TFitter and TLinearFitter
}

//______________________________________________________________________________
const char *TVirtualFitter::GetDefaultFitter()
{
   // static: return the name of the default fitter

   //return fgDefault.Data();
   return ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
}

//______________________________________________________________________________
TVirtualFitter *TVirtualFitter::GetFitter()
{
   // static: return the current Fitter
   return fgFitter;
}

//______________________________________________________________________________
Int_t TVirtualFitter::GetMaxIterations()
{
   // static: Return the maximum number of iterations
   // actually max number of function calls

   //return fgMaxiter;
   return ROOT::Math::MinimizerOptions::DefaultMaxFunctionCalls();
}

//______________________________________________________________________________
Double_t TVirtualFitter::GetErrorDef()
{
   // static: Return the Error Definition

//   return fgErrorDef;
   return ROOT::Math::MinimizerOptions::DefaultErrorDef();
}

//______________________________________________________________________________
Double_t TVirtualFitter::GetPrecision()
{
   // static: Return the fit relative precision

   //return fgPrecision;
   return ROOT::Math::MinimizerOptions::DefaultTolerance();
}

//______________________________________________________________________________
void TVirtualFitter::SetDefaultFitter(const char *name)
{
   // static: set name of default fitter

   ROOT::Math::MinimizerOptions::SetDefaultMinimizer(name,"");
   if (fgDefault == name) return;
   delete fgFitter;
   fgFitter = 0;
   fgDefault = name;
}

//______________________________________________________________________________
void TVirtualFitter::SetFitter(TVirtualFitter *fitter, Int_t maxpar)
{
   // Static function to set an alternative fitter

   fgFitter = fitter;
   fgMaxpar = maxpar;
}

//______________________________________________________________________________
void TVirtualFitter::SetFCN(void (*fcn)(Int_t &, Double_t *, Double_t &f, Double_t *, Int_t))
{
   // To set the address of the minimization objective function
   // called by the native compiler (see function below when called by CINT)

   fFCN = fcn;
}

//______________________________________________________________________________
void InteractiveFCN(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag)
{
   // Static function called when SetFCN is called in interactive mode

   TMethodCall *m = TVirtualFitter::GetFitter()->GetMethodCall();
   if (!m) return;

   Long_t args[5];
   args[0] = (Long_t)∦
   args[1] = (Long_t)gin;
   args[2] = (Long_t)&f;
   args[3] = (Long_t)u;
   args[4] = (Long_t)flag;
   m->SetParamPtrs(args);
   Double_t result;
   m->Execute(result);
}

//______________________________________________________________________________
Double_t *TVirtualFitter::SetCache(Int_t npoints, Int_t psize)
{
   // Initialize the cache array
   // npoints is the number of points to be stored (or already stored) in the cache
   // psize is the number of elements per point
   //
   // if (npoints*psize > fCacheSize) the existing cache is deleted
   // and a new array is created.
   // The function returns a pointer to the cache

   if (npoints*psize > fCacheSize) {
      delete [] fCache;
      fCacheSize = npoints*psize;
      fCache = new Double_t[fCacheSize];
   }
   fNpoints = npoints;
   fPointSize = psize;
   return fCache;
}

//______________________________________________________________________________
void TVirtualFitter::SetFCN(void *fcn)
{
   //  To set the address of the minimization objective function
   //
   //     this function is called by CINT instead of the function above

   if (!fcn) return;

   const char *funcname = gCint->Getp2f2funcname(fcn);
   if (funcname) {
      delete fMethodCall;
      fMethodCall = new TMethodCall();
      fMethodCall->InitWithPrototype(funcname,"Int_t&,Double_t*,Double_t&,Double_t*,Int_t");
   }
   fFCN = InteractiveFCN;
}

//______________________________________________________________________________
void TVirtualFitter::SetMaxIterations(Int_t niter)
{
   // static: Set the maximum number of iterations measured as function calls

   ROOT::Math::MinimizerOptions::SetDefaultMaxFunctionCalls(niter);
}

//______________________________________________________________________________
void TVirtualFitter::SetErrorDef(Double_t errdef)
{
   // static: Set the Error Definition (default=1)

//    fgErrorDef = errdef;
   ROOT::Math::MinimizerOptions::SetDefaultErrorDef(errdef);
   if (!fgFitter) return;
   Double_t arglist[1];
   arglist[0] = errdef;
   fgFitter->ExecuteCommand("SET ERRORDEF", arglist, 1);
}

//______________________________________________________________________________
void TVirtualFitter::SetPrecision(Double_t prec)
{
   // static: Set the fit relative precision

   //fgPrecision = prec;
   ROOT::Math::MinimizerOptions::SetDefaultTolerance(prec);
}
<commit_msg>fix a bug in the destructor of TVirtualFitter.  Set to zero the static instance (fgFitter) only if it is the same being  deleted.  This fix the problem reported at http://root.cern.ch/phpBB2/viewtopic.php?t=7627 where when deleting the TLinearFitter the static instance of the TBackCompFitter was set to zero.<commit_after>// @(#)root/mathcore:$Id$
// Author: Rene Brun   31/08/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//______________________________________________________________________________
//
//     Abstract Base Class for Fitting

#include "TROOT.h"
#include "TVirtualFitter.h"
#include "TPluginManager.h"
#include "TEnv.h"
#include "TInterpreter.h"
#include "Math/MinimizerOptions.h"

TVirtualFitter *TVirtualFitter::fgFitter    = 0;
Int_t           TVirtualFitter::fgMaxpar    = 0;
// Int_t           TVirtualFitter::fgMaxiter   = 5000;
// Double_t        TVirtualFitter::fgPrecision = 1e-6;
// Double_t        TVirtualFitter::fgErrorDef  = 1;
TString         TVirtualFitter::fgDefault   = "";

ClassImp(TVirtualFitter)

//______________________________________________________________________________
TVirtualFitter::TVirtualFitter()
{
   // Default constructor.

   fMethodCall = 0;
   fFCN        = 0;
   fNpoints    = 0;
   fPointSize  = 0;
   fCacheSize  = 0;
   fCache      = 0;
}

//______________________________________________________________________________
TVirtualFitter::TVirtualFitter(const TVirtualFitter& tvf) :
  TNamed(tvf),
  fOption(tvf.fOption),
  fXfirst(tvf.fXfirst),
  fXlast(tvf.fXlast),
  fYfirst(tvf.fYfirst),
  fYlast(tvf.fYlast),
  fZfirst(tvf.fZfirst),
  fZlast(tvf.fZlast),
  fNpoints(tvf.fNpoints),
  fPointSize(tvf.fPointSize),
  fCacheSize(tvf.fCacheSize),
  fCache(tvf.fCache),
  fObjectFit(tvf.fObjectFit),
  fUserFunc(tvf.fUserFunc),
  fMethodCall(tvf.fMethodCall),
  fFCN(tvf.fFCN)
{
   //copy constructor
}

//______________________________________________________________________________
TVirtualFitter& TVirtualFitter::operator=(const TVirtualFitter& tvf)
{
   //assignment operator
   if(this!=&tvf) {
      TNamed::operator=(tvf);
      fOption=tvf.fOption;
      fXfirst=tvf.fXfirst;
      fXlast=tvf.fXlast;
      fYfirst=tvf.fYfirst;
      fYlast=tvf.fYlast;
      fZfirst=tvf.fZfirst;
      fZlast=tvf.fZlast;
      fNpoints=tvf.fNpoints;
      fPointSize=tvf.fPointSize;
      fCacheSize=tvf.fCacheSize;
      fCache=tvf.fCache;
      fObjectFit=tvf.fObjectFit;
      fUserFunc=tvf.fUserFunc;
      fMethodCall=tvf.fMethodCall;
      fFCN=tvf.fFCN;
   }
   return *this;
}

//______________________________________________________________________________
TVirtualFitter::~TVirtualFitter()
{
   // Cleanup virtual fitter.

   delete fMethodCall;
   delete [] fCache;
   if ( fgFitter == this ) {
      fgFitter    = 0;
      fgMaxpar    = 0;
   }
   fMethodCall = 0;
   fFCN        = 0;
}

//______________________________________________________________________________
TVirtualFitter *TVirtualFitter::Fitter(TObject *obj, Int_t maxpar)
{
   // Static function returning a pointer to the current fitter.
   // If the fitter does not exist, the default TFitter is created.
   // Don't delete the returned fitter object, it will be re-used.

   if (fgFitter && maxpar > fgMaxpar) {
      delete fgFitter;
      fgFitter = 0;
   }

   if (!fgFitter) {
      TPluginHandler *h;
      if (fgDefault.Length() == 0) fgDefault = gEnv->GetValue("Root.Fitter","Minuit");
      if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualFitter",fgDefault))) {
         if (h->LoadPlugin() == -1)
            return 0;
         fgFitter = (TVirtualFitter*) h->ExecPlugin(1, maxpar);
         fgMaxpar = maxpar;
      }
   }

   if (fgFitter) fgFitter->SetObjectFit(obj);
   return fgFitter;
}

//______________________________________________________________________________
void  TVirtualFitter::GetConfidenceIntervals(Int_t /*n*/, Int_t /*ndim*/, const Double_t * /*x*/, Double_t * /*ci*/, Double_t /*cl*/)
{
   //return confidence intervals in array x of dimension ndim
   //implemented in TFitter and TLinearFitter
}

//______________________________________________________________________________
void  TVirtualFitter::GetConfidenceIntervals(TObject * /*obj*/, Double_t /*cl*/)
{
   //return confidence intervals in TObject obj
   //implemented in TFitter and TLinearFitter
}

//______________________________________________________________________________
const char *TVirtualFitter::GetDefaultFitter()
{
   // static: return the name of the default fitter

   //return fgDefault.Data();
   return ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
}

//______________________________________________________________________________
TVirtualFitter *TVirtualFitter::GetFitter()
{
   // static: return the current Fitter
   return fgFitter;
}

//______________________________________________________________________________
Int_t TVirtualFitter::GetMaxIterations()
{
   // static: Return the maximum number of iterations
   // actually max number of function calls

   //return fgMaxiter;
   return ROOT::Math::MinimizerOptions::DefaultMaxFunctionCalls();
}

//______________________________________________________________________________
Double_t TVirtualFitter::GetErrorDef()
{
   // static: Return the Error Definition

//   return fgErrorDef;
   return ROOT::Math::MinimizerOptions::DefaultErrorDef();
}

//______________________________________________________________________________
Double_t TVirtualFitter::GetPrecision()
{
   // static: Return the fit relative precision

   //return fgPrecision;
   return ROOT::Math::MinimizerOptions::DefaultTolerance();
}

//______________________________________________________________________________
void TVirtualFitter::SetDefaultFitter(const char *name)
{
   // static: set name of default fitter

   ROOT::Math::MinimizerOptions::SetDefaultMinimizer(name,"");
   if (fgDefault == name) return;
   delete fgFitter;
   fgFitter = 0;
   fgDefault = name;
}

//______________________________________________________________________________
void TVirtualFitter::SetFitter(TVirtualFitter *fitter, Int_t maxpar)
{
   // Static function to set an alternative fitter

   fgFitter = fitter;
   fgMaxpar = maxpar;
}

//______________________________________________________________________________
void TVirtualFitter::SetFCN(void (*fcn)(Int_t &, Double_t *, Double_t &f, Double_t *, Int_t))
{
   // To set the address of the minimization objective function
   // called by the native compiler (see function below when called by CINT)

   fFCN = fcn;
}

//______________________________________________________________________________
void InteractiveFCN(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag)
{
   // Static function called when SetFCN is called in interactive mode

   TMethodCall *m = TVirtualFitter::GetFitter()->GetMethodCall();
   if (!m) return;

   Long_t args[5];
   args[0] = (Long_t)∦
   args[1] = (Long_t)gin;
   args[2] = (Long_t)&f;
   args[3] = (Long_t)u;
   args[4] = (Long_t)flag;
   m->SetParamPtrs(args);
   Double_t result;
   m->Execute(result);
}

//______________________________________________________________________________
Double_t *TVirtualFitter::SetCache(Int_t npoints, Int_t psize)
{
   // Initialize the cache array
   // npoints is the number of points to be stored (or already stored) in the cache
   // psize is the number of elements per point
   //
   // if (npoints*psize > fCacheSize) the existing cache is deleted
   // and a new array is created.
   // The function returns a pointer to the cache

   if (npoints*psize > fCacheSize) {
      delete [] fCache;
      fCacheSize = npoints*psize;
      fCache = new Double_t[fCacheSize];
   }
   fNpoints = npoints;
   fPointSize = psize;
   return fCache;
}

//______________________________________________________________________________
void TVirtualFitter::SetFCN(void *fcn)
{
   //  To set the address of the minimization objective function
   //
   //     this function is called by CINT instead of the function above

   if (!fcn) return;

   const char *funcname = gCint->Getp2f2funcname(fcn);
   if (funcname) {
      delete fMethodCall;
      fMethodCall = new TMethodCall();
      fMethodCall->InitWithPrototype(funcname,"Int_t&,Double_t*,Double_t&,Double_t*,Int_t");
   }
   fFCN = InteractiveFCN;
}

//______________________________________________________________________________
void TVirtualFitter::SetMaxIterations(Int_t niter)
{
   // static: Set the maximum number of iterations measured as function calls

   ROOT::Math::MinimizerOptions::SetDefaultMaxFunctionCalls(niter);
}

//______________________________________________________________________________
void TVirtualFitter::SetErrorDef(Double_t errdef)
{
   // static: Set the Error Definition (default=1)

//    fgErrorDef = errdef;
   ROOT::Math::MinimizerOptions::SetDefaultErrorDef(errdef);
   if (!fgFitter) return;
   Double_t arglist[1];
   arglist[0] = errdef;
   fgFitter->ExecuteCommand("SET ERRORDEF", arglist, 1);
}

//______________________________________________________________________________
void TVirtualFitter::SetPrecision(Double_t prec)
{
   // static: Set the fit relative precision

   //fgPrecision = prec;
   ROOT::Math::MinimizerOptions::SetDefaultTolerance(prec);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "adaptive_manifold_filter.hpp"

using namespace std;
using namespace cv;

int main(int argc, const char* argv[])
{
    CommandLineParser cmd(argc, argv,
        "{ @0                   |      | Input image }"
        "{ o output             |      | Output image }"
        "{ j joint              |      | Image for joint filtering (optional) }"
        "{ s sigma_s            | 16.0 | Filter spatial standard deviation }"
        "{ r sigma_r            | 0.2  | Filter range standard deviation }"
        "{ t tree_height        | -1   | Height of the manifold tree (default = -1 : automatically computed) }"
        "{ i num_pca_iterations | 1    | Number of iterations to computed the eigenvector v1 }"
        "{ h help               |      | Print help message }"
    );

    if (cmd.has("help"))
    {
        cmd.about("This sample demonstrates adaptive manifold filter algorithm");
        cmd.printMessage();
        return 0;
    }

    const string inputImageName = cmd.get<string>(0);
    const string outputImageName = cmd.get<string>("output");
    const string jointImageName = cmd.get<string>("joint");
    const double sigma_s = cmd.get<double>("sigma_s");
    const double sigma_r = cmd.get<double>("sigma_r");
    const int tree_height = cmd.get<int>("tree_height");
    const int num_pca_iterations = cmd.get<int>("num_pca_iterations");

    if (!cmd.check())
    {
        cmd.printErrors();
        return -1;
    }

    if (inputImageName.empty())
    {
        cerr << "Missing input image" << endl;
        cmd.printMessage();
        return -1;
    }

    Mat img = imread(inputImageName);
    if (img.empty())
    {
        cerr << "Can't open image - " << inputImageName << endl;
        return -1;
    }

    Mat jointImg;
    if (!jointImageName.empty())
    {
        jointImg = imread(jointImageName);
        if (jointImg.empty())
        {
            cerr << "Can't open image - " << inputImageName << endl;
            return -1;
        }
    }

    AdaptiveManifoldFilter filter;
    filter.set("sigma_s", sigma_s);
    filter.set("sigma_r", sigma_r);
    filter.set("tree_height", tree_height);
    filter.set("num_pca_iterations", num_pca_iterations);

    Mat dst, tilde_dst;

    filter.apply(img, dst, tilde_dst, jointImg);

    if (!outputImageName.empty())
    {
        const string::size_type dotPos = outputImageName.find_last_of('.');
        const string name = outputImageName.substr(0, dotPos);
        const string ext = outputImageName.substr(dotPos + 1);

        imwrite(outputImageName, dst);
        imwrite(name + "_tilde." + ext, tilde_dst);
    }

    imshow("Input", img);
    imshow("Output", dst);
    imshow("Tilde Output", tilde_dst);
    waitKey();

    return 0;
}
<commit_msg>added comparison with NLM<commit_after>#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/contrib/contrib.hpp>
#include <opencv2/photo/photo.hpp>
#include "adaptive_manifold_filter.hpp"

using namespace std;
using namespace cv;

int main(int argc, const char* argv[])
{
    CommandLineParser cmd(argc, argv,
        "{ @0                   |      | Input image }"
        "{ o output             |      | Output image }"
        "{ j joint              |      | Image for joint filtering (optional) }"
        "{ s sigma_s            | 16.0 | Filter spatial standard deviation }"
        "{ r sigma_r            | 0.2  | Filter range standard deviation }"
        "{ t tree_height        | -1   | Height of the manifold tree (default = -1 : automatically computed) }"
        "{ i num_pca_iterations | 1    | Number of iterations to computed the eigenvector v1 }"
        "{ h help               |      | Print help message }"
    );

    if (cmd.has("help"))
    {
        cmd.about("This sample demonstrates adaptive manifold filter algorithm");
        cmd.printMessage();
        return 0;
    }

    const string inputImageName = cmd.get<string>(0);
    const string outputImageName = cmd.get<string>("output");
    const string jointImageName = cmd.get<string>("joint");
    const double sigma_s = cmd.get<double>("sigma_s");
    const double sigma_r = cmd.get<double>("sigma_r");
    const int tree_height = cmd.get<int>("tree_height");
    const int num_pca_iterations = cmd.get<int>("num_pca_iterations");

    if (!cmd.check())
    {
        cmd.printErrors();
        return -1;
    }

    if (inputImageName.empty())
    {
        cerr << "Missing input image" << endl;
        cmd.printMessage();
        return -1;
    }

    Mat img = imread(inputImageName);
    if (img.empty())
    {
        cerr << "Can't open image - " << inputImageName << endl;
        return -1;
    }

    Mat jointImg;
    if (!jointImageName.empty())
    {
        jointImg = imread(jointImageName);
        if (jointImg.empty())
        {
            cerr << "Can't open image - " << inputImageName << endl;
            return -1;
        }
    }

    AdaptiveManifoldFilter filter;
    filter.set("sigma_s", sigma_s);
    filter.set("sigma_r", sigma_r);
    filter.set("tree_height", tree_height);
    filter.set("num_pca_iterations", num_pca_iterations);

    Mat dst, tilde_dst;
    filter.apply(img, dst, tilde_dst, jointImg);

    TickMeter tm;
    tm.start();
    filter.apply(img, dst, tilde_dst, jointImg);
    tm.stop();
    cout << "Time : " << tm.getTimeMilli() << " ms" << endl;

    Mat nlm_dst;
    fastNlMeansDenoisingColored(img, nlm_dst, 10.0, 10.0);
    tm.reset(); tm.start();
    fastNlMeansDenoisingColored(img, nlm_dst, 10.0, 10.0);
    tm.stop();
    cout << "NLM : " << tm.getTimeMilli() << " ms" << endl;

    if (!outputImageName.empty())
    {
        const string::size_type dotPos = outputImageName.find_last_of('.');
        const string name = outputImageName.substr(0, dotPos);
        const string ext = outputImageName.substr(dotPos + 1);

        imwrite(outputImageName, dst);
        imwrite(name + "_tilde." + ext, tilde_dst);
    }

    imshow("Input", img);
    imshow("Output", dst);
    imshow("Tilde Output", tilde_dst);
    imshow("NLM", nlm_dst);
    waitKey();

    return 0;
}
<|endoftext|>


<commit_before>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 2.1b
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date	Revision	Changed By			Changes
------  ---------   ------------		---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2/24/15	1.0b		Patrick Rye			-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2/24/15	1.1b		Patrick Rye			-Attempted to allow movement on map through arrow keys.
											-Could not get this to work and broke everything. Rolling back to previous version.
											-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2/25/15	1.2b		Patrick Rye			-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2/26/15	1.3b		Patrick Rye			-Moved player movement to the room.h
=============================================================================================================================================================
2/27/15	2.0b		Patrick Rye			-Added a save function, for testing purposes.
										-Added load function.
										-Added function to see if file exists.
=============================================================================================================================================================
2/27/15	2.1b		Patrick Rye			-Moved save checker to basic.h
										-Renamed casechecker.h to basic.h
										-Added more comments explaining parts of the code.
										-Changed some names of functions to better reflect what they do.
										-Health is now carried between battles.
										-Moved healing to be able to happen between battles.
										-Added fail check for load function.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changes very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
/*********************************************************************************************************/
using namespace std;
Dungeon d;
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel;
int intLevelStart;
/*********************************************************************************************************/

char savefunction()
{
	/*
	Testing a possible save function.
	2 Return values possible.
	T = True, save succeeded.
	F = False, save failed.
	*/
	int intCheckSum = 0;
	int arrbattlesave[7];
	int arrmainsave[1] = {intMainLevel}; //An array of all the values needed to be saved from main.cpp
	int arrroomsave[80][20];
	for (int i = 0; i < 6; i++) {arrbattlesave[i] = getbattlevalue(i);} //Build array of player stats, and player health.
	for (int y = 0; y < 20; y++) {for (int x = 0; x < 80; x++) {arrroomsave[x][y] = d.getCell(x,y);}} //Build array of the dungeon.
	ofstream savefile;
	savefile.open ("save.bif");
	for (int i = 0; i < 7; i++) {savefile << arrbattlesave[i] << "\n";}
	//savefile << "\n";
	for (int i = 0; i < 1; i++) {savefile << arrmainsave[i] << "\n";}
	//savefile << "\n";
	for (int y = 0; y < 20; y++)
	{
		for (int x = 0; x < 80; x++) {savefile << arrroomsave[x][y] << "\n";}
		//savefile << " ";
	}
	savefile.close();
	//Save will now attempt to "load" the save it just made and compare it to the data available.
	//Checks to see if save is correct or not.
	ifstream loadfile("save.bif");
	int arrloadnumbers[1608];
	int x;
	for(int i = 0; i < 1608; i++) {loadfile>>arrloadnumbers[i];}
	loadfile.close();
	for (int i = 0; i < 8; i++)
	{
		if(i<7) {if (arrloadnumbers[i]==arrbattlesave[i]){intCheckSum++;}}
		else if (i == 7) {if (arrloadnumbers[i]==intMainLevel) {intCheckSum++;}}
	}
	int num = 7;
	for (int y = 0; y < 20; y++)
	{
		for (int x = 0; x < 80; x++)
		{
			num ++;
			if (arrloadnumbers[num]==d.getCell(x,y)) {intCheckSum++;}
		}
	}
	cout<<endl<<endl<<intCheckSum;
	if(intCheckSum >= 1608) {return 'T';} //All of the saved values are correct if it equals 1608.
	else {return 'F';} //Some of the values are wrong, say that the save failed.
}

bool loadfunction()
{
	ifstream loadfile("save.bif");
	int arrloadnumbers[1608];
	int x;
	for(int i = 0; i < 1608; i++) {loadfile>>arrloadnumbers[i];}
	loadfile.close();
	for (int i = 0; i < 8; i++)
	{
		if(i<7) {x = setbattlevalue(i,arrloadnumbers[i]);/*cout<<arrloadnumbers[i]<<endl;*/}
		else if (i == 7) {intLevelStart = arrloadnumbers[i];/*cout<<intLevelStart<<endl;*/}
	}
	int num = 7;
	for (int y = 0; y < 20; y++)
	{
		for (int x = 0; x < 80; x++)
		{
			num ++;
			d.setCell(x,y,arrloadnumbers[num]);
			//cout<<arrloadnumbers[num];
		}
	}
	//d.showDungeon();

	//Double check that all the values loaded are correct.
	ifstream checkfile("save.bif");
	for(int i = 0; i < 1608; i++) {checkfile>>arrloadnumbers[i];} //Rebuild the array.
	checkfile.close();
	int intCheckSum = 1;
	for (int i = 0; i < 8; i++)
	{
		if(i<7) {if (arrloadnumbers[i]==getbattlevalue(i)){intCheckSum++;}}
		else if (i == 7) {if (arrloadnumbers[i]==intMainLevel) {intCheckSum++;}}
	}
	num = 7;
	for (int y = 0; y < 20; y++)
	{
		for (int x = 0; x < 80; x++)
		{
			num ++;
			if (arrloadnumbers[num]==d.getCell(x,y)) {intCheckSum++;}
		}
	}
	cout<<endl<<endl<<intCheckSum;
	if(intCheckSum >= 1608) {return true;} //All of the saved values are correct if it equals 1608.
	else {return false;} //Some of the values are wrong, say that the save failed.
}

int main()
{

	cout << string(48, '\n');
	char chrPlayerMade = 'F';
	char charPlayerDirection;
	char charBattleEnding;
	char charExitFind;
	bool blLoadSuccess = false;
	bool blOldSave = false;
	char chrSaveSuccess = 'N'; //N means that save has not been run.
	intLevelStart = 1;
	if (saveexists()) //Check if there is a save present.
	{
		blLoadSuccess = loadfunction(); //Try to load the save.
		if (blLoadSuccess)
		{
			chrPlayerMade = 'T';
			blOldSave = true;
		}
		else {cout<<endl<<"There is a save present, but game is unable to load it."<<endl<<"Save is possibly corrupted."<<endl<<endl<<endl;} //Load failed.
	}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<"Welcome to the World of Attacker"<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by †"<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {d.playerfind(); d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go ( N , E , S , W )."<<endl<<"Enter X to exit, C to check yourself, H to heal, or P to save."<<endl;
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);
			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					system("pause");
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					system("pause");
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10) //Random chance to encounter monster.
				{
					cout << string(50, '\n');
					charBattleEnding = startbattle(intMainLevel); //Starts battle.
					if(charBattleEnding == 'F') {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	}
	cout << string(50, '\n');
	cout<<"You win!!";
	system("pause");
	return 0;
//End of main
}
<commit_msg>Update to V2.2b<commit_after>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 2.2b
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date	Revision	Changed By			Changes
------  ---------   ------------		---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2/24/15	1.0b		Patrick Rye			-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2/24/15	1.1b		Patrick Rye			-Attempted to allow movement on map through arrow keys.
											-Could not get this to work and broke everything. Rolling back to previous version.
											-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2/25/15	1.2b		Patrick Rye			-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2/26/15	1.3b		Patrick Rye			-Moved player movement to the room.h
=============================================================================================================================================================
2/27/15	2.0b		Patrick Rye			-Added a save function, for testing purposes.
										-Added load function.
										-Added function to see if file exists.
=============================================================================================================================================================
2/27/15	2.1b		Patrick Rye			-Moved save checker to basic.h
										-Renamed casechecker.h to basic.h
										-Added more comments explaining parts of the code.
										-Changed some names of functions to better reflect what they do.
										-Health is now carried between battles.
										-Moved healing to be able to happen between battles.
										-Added fail check for load function.
=============================================================================================================================================================
3/2/15	2.2b		Patrick Rye			-Improved code a bit.
										-Added version number tracker.
										-Prompt for loading save.
										-Prompt for incorrect save version.
										-Moved saving and loading functions to its own header.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changes very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
/*********************************************************************************************************/
using namespace std;
Dungeon d;
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel;
int intLevelStart;
const string CurrentVerison = "2.2b";
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
int getmainvalue(int intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}

int setmainvalue(int intlocation, int intvalue)
{
	if(intlocation != 0) {return 1;}
	else {intLevelStart = intvalue;}
	return 0;
}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{

	cout << string(48, '\n');
	char charPlayerDirection;
	char charBattleEnding;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';

	char chrSaveSuccess = 'N'; //N means that save has not been run.
	intLevelStart = 1;

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave(CurrentVerison);
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<"Welcome to the World of Attacker"<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by †"<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go ( N , E , S , W )."<<endl<<"Enter X to exit, C to check yourself, H to heal, or P to save."<<endl;
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);
			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					system("pause");
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					system("pause");
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10) //Random chance to encounter monster.
				{
					cout << string(50, '\n');
					charBattleEnding = startbattle(intMainLevel); //Starts battle.
					if(charBattleEnding == 'F') {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	}
	cout << string(50, '\n');
	cout<<"You win!!";
	system("pause");
	return 0;
//End of main
}
<|endoftext|>


<commit_before>4d9d1499-2748-11e6-89e7-e0f84713e7b8<commit_msg>new flies<commit_after>4db8c711-2748-11e6-8b35-e0f84713e7b8<|endoftext|>


<commit_before>99be058c-ad5a-11e7-89b8-ac87a332f658<commit_msg>bug fix<commit_after>9a6c9d4c-ad5a-11e7-bbd9-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <boost/variant.hpp>
#include <boost/timer/timer.hpp>
#include "variant.hpp"

#define TEXT "Testing various variant implementations with a longish string ........................................."
//#define BOOST_VARIANT_MINIMIZE_SIZE
namespace test {

template <typename V>
struct Holder
{
    typedef V value_type;
    std::vector<value_type> data;

    template <typename T>
    void append_move( T && obj)
    {
        data.emplace_back(std::move(obj));
    }

    template <typename T>
    void append(T const& obj)
    {
        data.push_back(obj);
    }
};

}

struct print
{
    template <typename T>
    void operator() (T const& val) const
    {
        std::cerr << val << ":" << typeid(T).name() <<  std::endl;
    }
};

template <typename V>
struct dummy : boost::static_visitor<>
{
    dummy(V & v)
        : v_(v) {}

    template <typename T>
    void operator() (T const& val) const
    {
        v_ = val;
    }
    V & v_;
};

template <typename V>
struct dummy2 : boost::static_visitor<>
{
    dummy2(V & v)
        : v_(v) {}

    template <typename T>
    void operator() (T const& val) const
    {
        v_.template set<T>(val);
    }
    V & v_;
};

int main (int argc, char** argv)
{
    if (argc!=2)
    {
        std::cerr << "Usage:" << argv[0] << " <num-runs>" << std::endl;
        return 1;
    }
    const int NUM_RUNS=std::stol(argv[1]);

#if 1
    {
        boost::timer::auto_cpu_timer t;
        test::Holder<util::variant<int,double,std::string> > h;
        h.data.reserve(NUM_RUNS);
        for (int i=0; i< NUM_RUNS;++i)
        {
            h.append_move(std::string(TEXT));
            h.append_move(123);
            h.append_move(3.14159);

        }
        std::cerr << h.data.size() << std::endl;
        util::variant<int,double,std::string> v;
        for (auto const& v2 : h.data)
        {
            dummy2<util::variant<int,double,std::string> > d(v);
            util::apply_visitor(v2, d);
        }
    }
#endif

#if 1
    {
        boost::timer::auto_cpu_timer t;
        test::Holder<boost::variant<int,double,std::string>> h;
        for (int i=0; i< NUM_RUNS;++i)
        {
            h.append_move(std::string(TEXT));
            h.append_move(123);
            h.append_move(3.14159);
        }

        std::cerr << h.data.size() << std::endl;
        boost::variant<int,double,std::string> v;
        for (auto const& v2 : h.data)
        {
            dummy<boost::variant<int,double,std::string> > d(v);
            boost::apply_visitor(d, v2);
        }
    }
#endif

#if 1

    std::cerr << util::detail::type_traits<bool, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<int, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<double, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<std::string, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<long, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<std::vector<int>, bool, int, double, std::string>::id << std::endl;

    typedef util::variant<bool,int, double, std::string> variant_type;
    variant_type v(std::string("test"));
    util::apply_visitor(v, print());

    v = std::string("ABC");
    util::apply_visitor(v, print());

    std::vector<variant_type> vec;
    vec.emplace_back(std::move(v));
    for (auto const& e : vec)
    {
        util::apply_visitor(e, print());
    }

    v=std::string("test");
    util::apply_visitor(v, print());
    v=123.345;
    util::apply_visitor(v, print());
    variant_type v2(std::string("testing a bit more"));
    util::apply_visitor(v2, print());
    variant_type v3(444);
    util::apply_visitor(v3, print());

    std::cerr << sizeof(v) << std::endl;
    std::cerr << sizeof(v2) << std::endl;
    std::cerr << sizeof(v3) << std::endl;
    std::cerr << sizeof(boost::variant<bool,int, double, std::string>) << std::endl;
#endif
    return EXIT_SUCCESS;

}
<commit_msg>remove unused boost::static_visitor<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <boost/variant.hpp>
#include <boost/timer/timer.hpp>
#include "variant.hpp"

#define TEXT "Testing various variant implementations with a longish string ........................................."
//#define BOOST_VARIANT_MINIMIZE_SIZE
namespace test {

template <typename V>
struct Holder
{
    typedef V value_type;
    std::vector<value_type> data;

    template <typename T>
    void append_move( T && obj)
    {
        data.emplace_back(std::move(obj));
    }

    template <typename T>
    void append(T const& obj)
    {
        data.push_back(obj);
    }
};

}

struct print
{
    template <typename T>
    void operator() (T const& val) const
    {
        std::cerr << val << ":" << typeid(T).name() <<  std::endl;
    }
};

template <typename V>
struct dummy : boost::static_visitor<>
{
    dummy(V & v)
        : v_(v) {}

    template <typename T>
    void operator() (T const& val) const
    {
        v_ = val;
    }
    V & v_;
};

template <typename V>
struct dummy2
{
    dummy2(V & v)
        : v_(v) {}

    template <typename T>
    void operator() (T const& val) const
    {
        v_.template set<T>(val);
    }
    V & v_;
};

int main (int argc, char** argv)
{
    if (argc!=2)
    {
        std::cerr << "Usage:" << argv[0] << " <num-runs>" << std::endl;
        return 1;
    }
    const int NUM_RUNS=std::stol(argv[1]);

#if 1
    {
        boost::timer::auto_cpu_timer t;
        test::Holder<util::variant<int,double,std::string> > h;
        h.data.reserve(NUM_RUNS);
        for (int i=0; i< NUM_RUNS;++i)
        {
            h.append_move(std::string(TEXT));
            h.append_move(123);
            h.append_move(3.14159);

        }
        std::cerr << h.data.size() << std::endl;
        util::variant<int,double,std::string> v;
        for (auto const& v2 : h.data)
        {
            dummy2<util::variant<int,double,std::string> > d(v);
            util::apply_visitor(v2, d);
        }
    }
#endif

#if 1
    {
        boost::timer::auto_cpu_timer t;
        test::Holder<boost::variant<int,double,std::string>> h;
        for (int i=0; i< NUM_RUNS;++i)
        {
            h.append_move(std::string(TEXT));
            h.append_move(123);
            h.append_move(3.14159);
        }

        std::cerr << h.data.size() << std::endl;
        boost::variant<int,double,std::string> v;
        for (auto const& v2 : h.data)
        {
            dummy<boost::variant<int,double,std::string> > d(v);
            boost::apply_visitor(d, v2);
        }
    }
#endif

#if 1

    std::cerr << util::detail::type_traits<bool, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<int, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<double, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<std::string, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<long, bool, int, double, std::string>::id << std::endl;
    std::cerr << util::detail::type_traits<std::vector<int>, bool, int, double, std::string>::id << std::endl;

    typedef util::variant<bool,int, double, std::string> variant_type;
    variant_type v(std::string("test"));
    util::apply_visitor(v, print());

    v = std::string("ABC");
    util::apply_visitor(v, print());

    std::vector<variant_type> vec;
    vec.emplace_back(std::move(v));
    for (auto const& e : vec)
    {
        util::apply_visitor(e, print());
    }

    v=std::string("test");
    util::apply_visitor(v, print());
    v=123.345;
    util::apply_visitor(v, print());
    variant_type v2(std::string("testing a bit more"));
    util::apply_visitor(v2, print());
    variant_type v3(444);
    util::apply_visitor(v3, print());

    std::cerr << sizeof(v) << std::endl;
    std::cerr << sizeof(v2) << std::endl;
    std::cerr << sizeof(v3) << std::endl;
    std::cerr << sizeof(boost::variant<bool,int, double, std::string>) << std::endl;
#endif
    return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>#include "imgui.h"
#include "imgui-sfml.h"
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>

// TEMP
enum class Direction{
    HORIZONTAL,
    VERTICAL,
    BOTH
};

void drawLine(sf::RenderWindow &window, sf::RectangleShape &line,
              const sf::Color &color=sf::Color::White, const int step=10,
              const Direction direction=Direction::BOTH, const int lineWidth=1)
{
    if(direction == Direction::BOTH){
        drawLine(window, line, color, step, Direction::HORIZONTAL);
        drawLine(window, line, color, step, Direction::VERTICAL);
    }
    else{
        sf::Vector2u winSize{window.getSize()};
        int edge{0};

        line.setFillColor(color);

        switch(direction){
            case Direction::HORIZONTAL:
                edge = window.getSize().x;
                line.setSize(sf::Vector2f(edge,lineWidth));
                break;
            case Direction::VERTICAL:
                edge = window.getSize().y;
                line.setSize(sf::Vector2f(lineWidth,edge));
                break;
        }

        for(int i=0; i<edge; i+=step){
            switch(direction){
                case Direction::HORIZONTAL:
                    line.setPosition(0,i);
                    break;
                case Direction::VERTICAL:
                    line.setPosition(i,0);
                    break;
            }
            window.draw(line);
        }
    }

}

void drawGrid(sf::RenderWindow &window)
{
    sf::RectangleShape line;

    int steps[]{12, 24, 96};
    sf::Color colors[]{sf::Color {35,85,125},
                       sf::Color {40,90,130},
                       sf::Color {60,110,150}};

    for(int i=0;i<3;++i)
        drawLine(window, line,colors[i], steps[i]);
}

// Exist some problem with rounding of <Vector2i size> variable
// For example:
// if init <size.x> value = 200, is losed 2 pixel when program
// step into next recurtion level (200/3 -> 198)
void drawFigure(      sf::RenderWindow &window,
                const sf::Vector2i     &position,
                const sf::Vector2i     &size,
                const int              depth,
                const sf::Color        &fillColor=sf::Color::White,
                const int              outlineThickness=1,
                const sf::Color        &outlineColor=sf::Color(0,0,0,0))
{
    sf::RectangleShape element;

    sf::Vector2i outerSize(size.x/3, size.y/3);
    sf::Vector2i innerSize(outerSize.x - outlineThickness*2,
                           outerSize.y - outlineThickness*2);

    element.setSize(sf::Vector2f(innerSize.x,innerSize.y));
    element.setFillColor(fillColor);

    element.setOutlineThickness(outlineThickness);
    element.setOutlineColor(outlineColor);

    sf::Vector2i point(position);

    for (int i=0; i<9; ++i)
    {
        if (i != 4){
            if (i!= 0 && !(i%3)){
                point.y += outerSize.x;
                point.x =  position.x;
            }

            element.setPosition(sf::Vector2f(point.x,point.y));

            if (depth == 1)
                window.draw(element);
            else{
                int thickness = outlineThickness > 1? outlineThickness/2 :
                                                      outlineThickness;
                drawFigure(window, point, outerSize, depth-1,
                           fillColor, thickness, outlineColor);
            }
         }
         point.x += outerSize.y;
    }
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"ReIGen", sf::Style::Titlebar|
                                                             sf::Style::Close);
    ImGui::SFML::Init(window);

    sf::Color bgColor(30,80,120);
    int uiWidth = 200;

    sf::Clock deltaClock;

    sf::Vector2i canvasCenter((window.getSize().x - uiWidth)/2,
                               window.getSize().y/2);
    sf::Vector2i figureSize(450,450);
    sf::Vector2i figurePosition(canvasCenter.x - figureSize.x/2,
                                canvasCenter.y - figureSize.y/2);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            ImGui::SFML::ProcessEvent(event);

            if (event.type == sf::Event::Closed)
                    window.close();
        }

        ImGui::SFML::Update(window, deltaClock.restart());

        ImGui::SetNextWindowPos(ImVec2(600,0));
        ImGui::SetNextWindowSize(ImVec2(uiWidth,600));
        ImGui::Begin("Settings", false, ImGuiWindowFlags_NoTitleBar|
                                        ImGuiWindowFlags_NoResize|
                                        ImGuiWindowFlags_NoMove|
                                        ImGuiWindowFlags_NoCollapse|
                                        ImGuiWindowFlags_ShowBorders);

        ImGui::End();

        window.clear(bgColor);
        drawGrid(window);
        drawFigure(window, figurePosition, figureSize, 4);
        ImGui::Render();
        window.display();
    }

    ImGui::SFML::Shutdown();
    return 0;
}
<commit_msg>improve Sierpinski Carpet definition (add zero level of the recurcion depth)<commit_after>#include "imgui.h"
#include "imgui-sfml.h"
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>

// TEMP
enum class Direction{
    HORIZONTAL,
    VERTICAL,
    BOTH
};

void drawLine(sf::RenderWindow &window, sf::RectangleShape &line,
              const sf::Color &color=sf::Color::White, const int step=10,
              const Direction direction=Direction::BOTH, const int lineWidth=1)
{
    if(direction == Direction::BOTH){
        drawLine(window, line, color, step, Direction::HORIZONTAL);
        drawLine(window, line, color, step, Direction::VERTICAL);
    }
    else{
        sf::Vector2u winSize{window.getSize()};
        int edge{0};

        line.setFillColor(color);

        switch(direction){
            case Direction::HORIZONTAL:
                edge = window.getSize().x;
                line.setSize(sf::Vector2f(edge,lineWidth));
                break;
            case Direction::VERTICAL:
                edge = window.getSize().y;
                line.setSize(sf::Vector2f(lineWidth,edge));
                break;
        }

        for(int i=0; i<edge; i+=step){
            switch(direction){
                case Direction::HORIZONTAL:
                    line.setPosition(0,i);
                    break;
                case Direction::VERTICAL:
                    line.setPosition(i,0);
                    break;
            }
            window.draw(line);
        }
    }

}

void drawGrid(sf::RenderWindow &window)
{
    sf::RectangleShape line;

    int steps[]{12, 24, 96};
    sf::Color colors[]{sf::Color {35,85,125},
                       sf::Color {40,90,130},
                       sf::Color {60,110,150}};

    for(int i=0;i<3;++i)
        drawLine(window, line,colors[i], steps[i]);
}

// Exist some problem with rounding of <Vector2i size> variable
// For example:
// if init <size.x> value = 200, is losed 2 pixel when program
// step into next recurtion level (200/3 -> 198)
void drawFigure(      sf::RenderWindow &window,
                const sf::Vector2i     &position,
                const sf::Vector2i     &size,
                const int              depth,
                const sf::Color        &fillColor=sf::Color::White,
                const int              outlineThickness=1,
                const sf::Color        &outlineColor=sf::Color(0,0,0,0))
{
    sf::RectangleShape element;

    sf::Vector2i outerSize(size.x/3, size.y/3);
    sf::Vector2i innerSize(outerSize.x - outlineThickness*2,
                           outerSize.y - outlineThickness*2);

    element.setSize(sf::Vector2f(innerSize.x,innerSize.y));
    element.setFillColor(fillColor);

    element.setOutlineThickness(outlineThickness);
    element.setOutlineColor(outlineColor);

    sf::Vector2i point(position);

    if (depth == 0){
        element.setSize(sf::Vector2f(size.x,size.y));
        element.setPosition(sf::Vector2f(position.x,position.y));
        window.draw(element);
        return;
    }

    for (int i=0; i<9; ++i)
    {
        if (i != 4){
            if (i!= 0 && !(i%3)){
                point.y += outerSize.x;
                point.x =  position.x;
            }

            element.setPosition(sf::Vector2f(point.x,point.y));

            if (depth == 1)
                window.draw(element);
            else{
                int thickness = outlineThickness > 1? outlineThickness/2 :
                                                      outlineThickness;
                drawFigure(window, point, outerSize, depth-1,
                           fillColor, thickness, outlineColor);
            }
         }
         point.x += outerSize.y;
    }
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"ReIGen", sf::Style::Titlebar|
                                                             sf::Style::Close);
    ImGui::SFML::Init(window);

    sf::Color bgColor(30,80,120);
    int uiWidth = 200;

    sf::Clock deltaClock;

    sf::Vector2i canvasCenter((window.getSize().x - uiWidth)/2,
                               window.getSize().y/2);
    sf::Vector2i figureSize(450,450);
    sf::Vector2i figurePosition(canvasCenter.x - figureSize.x/2,
                                canvasCenter.y - figureSize.y/2);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            ImGui::SFML::ProcessEvent(event);

            if (event.type == sf::Event::Closed)
                    window.close();
        }

        ImGui::SFML::Update(window, deltaClock.restart());

        ImGui::SetNextWindowPos(ImVec2(600,0));
        ImGui::SetNextWindowSize(ImVec2(uiWidth,600));
        ImGui::Begin("Settings", false, ImGuiWindowFlags_NoTitleBar|
                                        ImGuiWindowFlags_NoResize|
                                        ImGuiWindowFlags_NoMove|
                                        ImGuiWindowFlags_NoCollapse|
                                        ImGuiWindowFlags_ShowBorders);

        ImGui::End();

        window.clear(bgColor);
        drawGrid(window);
        drawFigure(window, figurePosition, figureSize, 0);
        ImGui::Render();
        window.display();
    }

    ImGui::SFML::Shutdown();
    return 0;
}
<|endoftext|>