<commit_before>/*
// Copyright (c) 2015 Pierre Guillot.
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/

#include "xpd_instance.hpp"
#include "xpd_patch.hpp"

extern "C"
{
#include "../cpd/cpd.h"
}

namespace xpd
{
    class smuggler
    {
    public:
        ~smuggler() xpd_noexcept {}
    public:
        inline static xpd_constexpr void const* gettie(tie const& tie) xpd_noexcept {return tie.ptr;}
        inline static xpd_constexpr tie createtie(void *ptr) xpd_noexcept {return tie(ptr);}
        inline static xpd_constexpr void const* getsymbol(symbol const& symbol) xpd_noexcept {return symbol.ptr;}
        inline static xpd_constexpr symbol createsymbol(void *ptr) xpd_noexcept {return symbol(ptr);}
    };

    struct instance::internal : public smuggler
    {
    public:
        c_instance object;
        instance*  ref;

        static internal* allocate(instance* _ref)
        {
            c_hook_console console;
            console.m_log   = (c_hook_print)instance::internal::m_log_hook;
            console.m_post  = (c_hook_print)instance::internal::m_post_hook;
            console.m_error = (c_hook_print)instance::internal::m_error_hook;
            console.m_fatal = (c_hook_print)instance::internal::m_fatal_hook;

            c_hook_midi midi;
            midi.m_noteon           = (c_hook_noteon)instance::internal::m_noteon;
            midi.m_controlchange    = (c_hook_controlchange)instance::internal::m_controlchange;
            midi.m_programchange    = (c_hook_programchange)instance::internal::m_programchange;
            midi.m_pitchbend        = (c_hook_pitchbend)instance::internal::m_pitchbend;
            midi.m_aftertouch       = (c_hook_aftertouch)instance::internal::m_aftertouch;
            midi.m_polyaftertouch   = (c_hook_polyaftertouch)instance::internal::m_polyaftertouch;
            midi.m_byte             = (c_hook_byte)instance::internal::m_byte;

            internal* ptr = (internal *)cpd_instance_new(sizeof(internal));
            if(ptr)
            {
                ptr->ref = _ref;
                cpd_instance_set_hook_console(reinterpret_cast<c_instance*>(ptr), &console);
                cpd_instance_set_hook_midi(reinterpret_cast<c_instance*>(ptr), &midi);

            }
            return ptr;
        }

        static void m_post_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::normal, std::string(s)));
        }

        static void m_log_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::log, std::string(s)));
        }

        static void m_error_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::error, std::string(s)));
        }

        static void m_fatal_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::fatal, std::string(s)));
        }

        static void m_noteon(instance::internal* instance, int port, int channel, int pitch, int velocity)
        {
            instance->ref->receive(midi::event::note(channel, pitch, velocity));
        }

        static void m_controlchange(instance::internal* instance, int port, int channel, int control, int value)
        {
            instance->ref->receive(midi::event::control_change(channel, control, value));
        }

        static void m_programchange(instance::internal* instance, int port, int channel, int value)
        {
            instance->ref->receive(midi::event::program_change(channel, value));
        }

        static void m_pitchbend(instance::internal* instance, int port, int channel, int value)
        {
            instance->ref->receive(midi::event::pitch_bend(channel, value));
        }

        static void m_aftertouch(instance::internal* instance, int port, int channel, int value)
        {
            instance->ref->receive(midi::event::after_touch(channel, value));
        }

        static void m_polyaftertouch(instance::internal* instance, int port, int channel, int pitch, int value)
        {
            instance->ref->receive(midi::event::poly_after_touch(channel, pitch, value));
        }

        static void m_byte(instance::internal* instance, int port, int value)
        {
            instance->ref->receive(midi::event::byte(value));
        }

        static void m_bang(instance::internal* instance, c_tie* tie)
        {
            instance->ref->receive(createtie(tie), instance::m_sym_bang, std::vector<atom>());
        }

        static void m_float(instance::internal* instance, c_tie* tie, c_float f)
        {
            instance->ref->receive(createtie(tie), instance::m_sym_float, std::vector<atom>(1, f));
        }

        static void m_symbol(instance::internal* instance, c_tie* tie, c_symbol* s)
        {
            symbol sy(createsymbol(s));
            instance->ref->receive(createtie(tie), instance::m_sym_symbol, std::vector<atom>(1, sy));
        }

        static void m_gpointer(instance::internal* instance, c_tie* tie, c_gpointer *g)
        {
            instance->ref->receive(createtie(tie), instance::m_sym_gpointer, std::vector<atom>());
        }

        static void m_list(instance::internal* instance, c_tie* tie, c_list *list)
        {
            std::vector<atom> vec(cpd_list_get_size(list));
            for(size_t i = 0; i < vec.size(); ++i)
            {
                if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = cpd_list_get_float(list, i);
                }
                else if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = createsymbol(cpd_list_get_symbol(list, i));
                }
            }
#ifdef _XPD_CPP11_NOSUPPORT_
            instance->ref->receive(createtie(tie), instance::m_sym_list, vec);
#else
            instance->ref->receive(createtie(tie), instance::m_sym_list, std::move(vec));
#endif
        }

        static void m_anything(instance::internal* instance, c_tie* tie, c_symbol *s, c_list *list)
        {
            std::vector<atom> vec(cpd_list_get_size(list));
            for(size_t i = 0; i < vec.size(); ++i)
            {
                if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = cpd_list_get_float(list, i);
                }
                else if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = createsymbol(cpd_list_get_symbol(list, i));
                }
            }
#ifdef _XPD_CPP11_NOSUPPORT_
            instance->ref->receive(createtie(tie), createsymbol(s), vec);
#else
            instance->ref->receive(createtie(tie), createsymbol(s), std::move(vec));
#endif
        }
    };

    // ==================================================================================== //
    //                                          INSTANCE                                    //
    // ==================================================================================== //

    symbol   instance::m_sym_bang;
    symbol   instance::m_sym_float;
    symbol   instance::m_sym_symbol;
    symbol   instance::m_sym_list;
    symbol   instance::m_sym_gpointer;

    instance::instance()
    {
        environment::lock();
        m_sym_bang      = symbol("bang");
        m_sym_float     = symbol("float");
        m_sym_symbol    = symbol("symbol");
        m_sym_list      = symbol("list");
        m_sym_gpointer  = symbol("gpointer");
        m_ptr = internal::allocate(this);
        environment::unlock();
        if(!m_ptr)
        {
            throw "can't allocate instance.";
        }
    }

    instance::~instance() xpd_noexcept
    {
        release();
        environment::lock();
        cpd_instance_free(reinterpret_cast<c_instance *>(m_ptr));
        environment::unlock();
    }

    patch* instance::load(std::string const& name, std::string const& path)
    {
        int todo;
        patch* p = NULL;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        void* ptr = cpd_patch_new(name.c_str(), path.c_str());
        if(ptr)
        {
            p = new patch(ptr, name, path, cpd_patch_get_dollarzero(reinterpret_cast<c_patch *>(m_ptr)));
        }
        environment::unlock();
        return p;
    }

    void instance::close(patch& p)
    {
        int todo;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        cpd_patch_free(reinterpret_cast<c_patch *>(p.m_ptr));
        delete &p;
        environment::unlock();
    }

    int instance::samplerate() const xpd_noexcept
    {
        return cpd_instance_get_samplerate(reinterpret_cast<c_instance *>(m_ptr));
    }

    void instance::prepare(const int nins, const int nouts, const int samplerate, const int nsamples) xpd_noexcept
    {
        environment::lock();
        cpd_instance_dsp_prepare(reinterpret_cast<c_instance *>(m_ptr), nins, nouts, samplerate, nsamples);
        environment::unlock();
    }

    void instance::perform(int nsamples, const int nins, const float** inputs, const int nouts, float** outputs) xpd_noexcept
    {
        environment::lock();
        cpd_instance_dsp_perform(reinterpret_cast<c_instance *>(m_ptr), nsamples, nins, inputs, nouts, outputs);
        environment::unlock();
    }

    void instance::release() xpd_noexcept
    {
        environment::lock();
        cpd_instance_dsp_release(reinterpret_cast<c_instance *>(m_ptr));
        environment::unlock();
    }

    void instance::send(console::post const& post) xpd_noexcept
    {
        int todo_set_instance;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        if(post.type == console::error)
        {
            cpd_console_error(post.text.c_str());
        }
        else if(post.type == console::fatal)
        {
            cpd_console_fatal(post.text.c_str());
        }
        else if(post.type == console::normal)
        {
            cpd_console_post(post.text.c_str());
        }
        else
        {
            cpd_console_log(post.text.c_str());
        }
        environment::unlock();
    }

    void instance::send(tie name, symbol s, std::vector<atom> const& atoms) const
    {
        int todo_set_instance;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        c_list* list = cpd_list_create(atoms.size());
        for(size_t i = 0; i < atoms.size(); ++i)
        {
            if(atoms[i].type() == atom::float_t)
            {
                cpd_list_set_float(list, i, float_t(atoms[i]));
            }
            else if(atoms[i].type() == atom::symbol_t)
            {
                cpd_list_set_float(list, i, symbol(atoms[i]));
            }
        }
        cpd_messagesend_anything(reinterpret_cast<c_tie const *>(smuggler::gettie(name)),
                                 reinterpret_cast<c_symbol const *>(smuggler::getsymbol(s)), list);

        environment::unlock();
    }

    void instance::send(midi::event const& event) const
    {
        int todo_set_instance;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        if(event.type() == midi::event::note_t)
        {
            cpd_midisend_noteon(event.channel(), event.pitch(), event.velocity());
        }
        else if(event.type() == midi::event::control_change_t)
        {
            cpd_midisend_controlchange(event.channel(), event.controler(), event.value());
        }
        else if(event.type() == midi::event::program_change_t)
        {
            cpd_midisend_programchange(event.channel(), event.program());
        }
        else if(event.type() == midi::event::pitch_bend_t)
        {
            cpd_midisend_pitchbend(event.channel(), event.bend());
        }
        else if(event.type() == midi::event::after_touch_t)
        {
            cpd_midisend_pitchbend(event.channel(), event.value());
        }
        else if(event.type() == midi::event::poly_after_touch_t)
        {
            cpd_midisend_polyaftertouch(event.channel(), event.pitch(), event.value());
        }
        else
        {
            cpd_midisend_byte(0, event.value());
        }
        environment::unlock();
    }

    void instance::listener_add(listener& listener)
    {
        m_listeners.insert(&listener);
    }

    void instance::listener_remove(listener& listener)
    {
        m_listeners.erase(&listener);
    }
}

<commit_msg>retry<commit_after>/*
// Copyright (c) 2015 Pierre Guillot.
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/

#include "xpd_instance.hpp"
#include "xpd_patch.hpp"

extern "C"
{
#include "../cpd/cpd.h"
}

namespace xpd
{
    class smuggler
    {
    public:
        ~smuggler() xpd_noexcept {}
    public:
        inline static xpd_constexpr void const* gettie(tie const& tie) xpd_noexcept {return tie.ptr;}
        inline static xpd_constexpr tie createtie(void *ptr) xpd_noexcept {return tie(ptr);}
        inline static xpd_constexpr void const* getsymbol(symbol const& symbol) xpd_noexcept {return symbol.ptr;}
        inline static xpd_constexpr symbol createsymbol(void *ptr) xpd_noexcept {return symbol(ptr);}
    };

    struct instance::internal : public smuggler
    {
    public:
        c_instance object;
        instance*  ref;

        static internal* allocate(instance* _ref)
        {
            c_hook_console console;
            console.m_log   = (c_hook_print)instance::internal::m_log_hook;
            console.m_post  = (c_hook_print)instance::internal::m_post_hook;
            console.m_error = (c_hook_print)instance::internal::m_error_hook;
            console.m_fatal = (c_hook_print)instance::internal::m_fatal_hook;

            c_hook_midi midi;
            midi.m_noteon           = (c_hook_noteon)instance::internal::m_noteon;
            midi.m_controlchange    = (c_hook_controlchange)instance::internal::m_controlchange;
            midi.m_programchange    = (c_hook_programchange)instance::internal::m_programchange;
            midi.m_pitchbend        = (c_hook_pitchbend)instance::internal::m_pitchbend;
            midi.m_aftertouch       = (c_hook_aftertouch)instance::internal::m_aftertouch;
            midi.m_polyaftertouch   = (c_hook_polyaftertouch)instance::internal::m_polyaftertouch;
            midi.m_byte             = (c_hook_byte)instance::internal::m_byte;

            internal* ptr = (internal *)cpd_instance_new(sizeof(internal));
            if(ptr)
            {
                ptr->ref = _ref;
                cpd_instance_set_hook_console(reinterpret_cast<c_instance*>(ptr), &console);
                cpd_instance_set_hook_midi(reinterpret_cast<c_instance*>(ptr), &midi);

            }
            return ptr;
        }

        static void m_post_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::normal, std::string(s)));
        }

        static void m_log_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::log, std::string(s)));
        }

        static void m_error_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::error, std::string(s)));
        }

        static void m_fatal_hook(instance::internal* instance, const char *s)
        {
            instance->ref->receive(console::post(console::fatal, std::string(s)));
        }

        static void m_noteon(instance::internal* instance, int port, int channel, int pitch, int velocity)
        {
            instance->ref->receive(midi::event::note(channel, pitch, velocity));
        }

        static void m_controlchange(instance::internal* instance, int port, int channel, int control, int value)
        {
            instance->ref->receive(midi::event::control_change(channel, control, value));
        }

        static void m_programchange(instance::internal* instance, int port, int channel, int value)
        {
            instance->ref->receive(midi::event::program_change(channel, value));
        }

        static void m_pitchbend(instance::internal* instance, int port, int channel, int value)
        {
            instance->ref->receive(midi::event::pitch_bend(channel, value));
        }

        static void m_aftertouch(instance::internal* instance, int port, int channel, int value)
        {
            instance->ref->receive(midi::event::after_touch(channel, value));
        }

        static void m_polyaftertouch(instance::internal* instance, int port, int channel, int pitch, int value)
        {
            instance->ref->receive(midi::event::poly_after_touch(channel, pitch, value));
        }

        static void m_byte(instance::internal* instance, int port, int value)
        {
            instance->ref->receive(midi::event::byte(value));
        }

        static void m_bang(instance::internal* instance, c_tie* tie)
        {
            instance->ref->receive(createtie(tie), instance::m_sym_bang, std::vector<atom>());
        }

        static void m_float(instance::internal* instance, c_tie* tie, c_float f)
        {
            instance->ref->receive(createtie(tie), instance::m_sym_float, std::vector<atom>(1, f));
        }

        static void m_symbol(instance::internal* instance, c_tie* tie, c_symbol* s)
        {
            symbol sy(createsymbol(s));
            instance->ref->receive(createtie(tie), instance::m_sym_symbol, std::vector<atom>(1, sy));
        }

        static void m_gpointer(instance::internal* instance, c_tie* tie, c_gpointer *g)
        {
            instance->ref->receive(createtie(tie), instance::m_sym_gpointer, std::vector<atom>());
        }

        static void m_list(instance::internal* instance, c_tie* tie, c_list *list)
        {
            std::vector<atom> vec(cpd_list_get_size(list));
            for(size_t i = 0; i < vec.size(); ++i)
            {
                if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = cpd_list_get_float(list, i);
                }
                else if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = createsymbol(cpd_list_get_symbol(list, i));
                }
            }
#ifdef _XPD_CPP11_NOSUPPORT_
            instance->ref->receive(createtie(tie), instance::m_sym_list, vec);
#else
            instance->ref->receive(createtie(tie), instance::m_sym_list, std::move(vec));
#endif
        }

        static void m_anything(instance::internal* instance, c_tie* tie, c_symbol *s, c_list *list)
        {
            std::vector<atom> vec(cpd_list_get_size(list));
            for(size_t i = 0; i < vec.size(); ++i)
            {
                if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = cpd_list_get_float(list, i);
                }
                else if(cpd_list_get_type(list, i) == Z_FLOAT)
                {
                    vec[i] = createsymbol(cpd_list_get_symbol(list, i));
                }
            }
#ifdef _XPD_CPP11_NOSUPPORT_
            instance->ref->receive(createtie(tie), createsymbol(s), vec);
#else
            instance->ref->receive(createtie(tie), createsymbol(s), std::move(vec));
#endif
        }
    };

    // ==================================================================================== //
    //                                          INSTANCE                                    //
    // ==================================================================================== //

    symbol   instance::m_sym_bang;
    symbol   instance::m_sym_float;
    symbol   instance::m_sym_symbol;
    symbol   instance::m_sym_list;
    symbol   instance::m_sym_gpointer;

    instance::instance()
    {
        environment::lock();
        m_sym_bang      = symbol("bang");
        m_sym_float     = symbol("float");
        m_sym_symbol    = symbol("symbol");
        m_sym_list      = symbol("list");
        m_sym_gpointer  = symbol("gpointer");
        m_ptr = internal::allocate(this);
        environment::unlock();
        if(!m_ptr)
        {
            throw "can't allocate instance.";
        }
    }

    instance::~instance() xpd_noexcept
    {
        release();
        environment::lock();
        cpd_instance_free(reinterpret_cast<c_instance *>(m_ptr));
        environment::unlock();
    }

    patch* instance::load(std::string const& name, std::string const& path)
    {
        int todo;
        patch* p = xpd_nullptr;
        void* ptr = xpd_nullptr;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        if(path.empty())
        {
            ptr = cpd_patch_new(name.c_str(), xpd_nullptr);
        }
        else
        {
            ptr = cpd_patch_new(name.c_str(), path.c_str());
        }

        if(ptr)
        {
            p = new patch(ptr, name, path, cpd_patch_get_dollarzero(reinterpret_cast<c_patch *>(m_ptr)));
        }
        environment::unlock();
        return p;
    }

    void instance::close(patch& p)
    {
        int todo;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        cpd_patch_free(reinterpret_cast<c_patch *>(p.m_ptr));
        delete &p;
        environment::unlock();
    }

    int instance::samplerate() const xpd_noexcept
    {
        return cpd_instance_get_samplerate(reinterpret_cast<c_instance *>(m_ptr));
    }

    void instance::prepare(const int nins, const int nouts, const int samplerate, const int nsamples) xpd_noexcept
    {
        environment::lock();
        cpd_instance_dsp_prepare(reinterpret_cast<c_instance *>(m_ptr), nins, nouts, samplerate, nsamples);
        environment::unlock();
    }

    void instance::perform(int nsamples, const int nins, const float** inputs, const int nouts, float** outputs) xpd_noexcept
    {
        environment::lock();
        cpd_instance_dsp_perform(reinterpret_cast<c_instance *>(m_ptr), nsamples, nins, inputs, nouts, outputs);
        environment::unlock();
    }

    void instance::release() xpd_noexcept
    {
        environment::lock();
        cpd_instance_dsp_release(reinterpret_cast<c_instance *>(m_ptr));
        environment::unlock();
    }

    void instance::send(console::post const& post) xpd_noexcept
    {
        int todo_set_instance;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        if(post.type == console::error)
        {
            cpd_console_error(post.text.c_str());
        }
        else if(post.type == console::fatal)
        {
            cpd_console_fatal(post.text.c_str());
        }
        else if(post.type == console::normal)
        {
            cpd_console_post(post.text.c_str());
        }
        else
        {
            cpd_console_log(post.text.c_str());
        }
        environment::unlock();
    }

    void instance::send(tie name, symbol s, std::vector<atom> const& atoms) const
    {
        int todo_set_instance;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        c_list* list = cpd_list_create(atoms.size());
        for(size_t i = 0; i < atoms.size(); ++i)
        {
            if(atoms[i].type() == atom::float_t)
            {
                cpd_list_set_float(list, i, float_t(atoms[i]));
            }
            else if(atoms[i].type() == atom::symbol_t)
            {
                cpd_list_set_float(list, i, symbol(atoms[i]));
            }
        }
        cpd_messagesend_anything(reinterpret_cast<c_tie const *>(smuggler::gettie(name)),
                                 reinterpret_cast<c_symbol const *>(smuggler::getsymbol(s)), list);

        environment::unlock();
    }

    void instance::send(midi::event const& event) const
    {
        int todo_set_instance;
        environment::lock();
        cpd_instance_set(reinterpret_cast<c_instance *>(m_ptr));
        if(event.type() == midi::event::note_t)
        {
            cpd_midisend_noteon(event.channel(), event.pitch(), event.velocity());
        }
        else if(event.type() == midi::event::control_change_t)
        {
            cpd_midisend_controlchange(event.channel(), event.controler(), event.value());
        }
        else if(event.type() == midi::event::program_change_t)
        {
            cpd_midisend_programchange(event.channel(), event.program());
        }
        else if(event.type() == midi::event::pitch_bend_t)
        {
            cpd_midisend_pitchbend(event.channel(), event.bend());
        }
        else if(event.type() == midi::event::after_touch_t)
        {
            cpd_midisend_pitchbend(event.channel(), event.value());
        }
        else if(event.type() == midi::event::poly_after_touch_t)
        {
            cpd_midisend_polyaftertouch(event.channel(), event.pitch(), event.value());
        }
        else
        {
            cpd_midisend_byte(0, event.value());
        }
        environment::unlock();
    }

    void instance::listener_add(listener& listener)
    {
        m_listeners.insert(&listener);
    }

    void instance::listener_remove(listener& listener)
    {
        m_listeners.erase(&listener);
    }
}

<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>

using namespace std;

class CMyString
{
public:
	CMyString(char *pData = NULL);
	CMyString(const CMyString &str);
	~CMyString(void);
private:
	char *m_pData;
};<commit_msg>Assignment Operators<commit_after>#include <iostream>
#include <cstdlib>

using namespace std;

class CMyString
{
public:
	CMyString(char *pData = NULL);
	CMyString(const CMyString &str);
	~CMyString(void);
private:
	char *m_pData;
};

CMyString& CMyString::operator =(const CMyString &str)
{
	if (this == &str)
	{
		return *this;
	}

	delete[]m_pData;
	m_pData = NULL;

	m_pData = new char[strlen(str.m_pData) + 1];
	strcpy(m_pData, str.m_pData);

	return *this;
}<|endoftext|>


<commit_before>#pragma once

#if defined(__arm__)
#  define __NR_inotify_rm_watch 318
#elif defined(__x86_64__)
#  define __NR_inotify_rm_watch 255
#else
#  error
#endif

#error
<commit_msg>inotify_rm_watch: not needed (yet)<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <stdlib.h>
#include "Args.hpp"

using namespace std;

static void Usage(void)
{
   cout << "Usage : test [option list] [camera # | video name]" << endl << endl;
   cout << "  Camera number is an integer corresponding to /dev/video??" << endl;

   cout << "\t--frame=<frame num>  start at given frame" << endl;
   cout << "\t--all                write to disk all detected images in each frame" << endl;
   cout << "\t--batch              run without GUI" << endl;
   cout << "\t--skip=<x>           skip frames, only processing every <x> - file input only." << endl;
   cout << "\t--calibrate          bring up crosshair to calibrate camera position" << endl;
   cout << "\t--capture            save raw camera video to output file" << endl;
   cout << "\t--captureSkip=       only save one of every N frames" << endl;
   cout << "\t--save               write processed video to output file" << endl;
   cout << "\t--saveSkip=          only save one of every N processed frames" << endl;
   cout << "\t--no-rects           start with detection rectangles disabled" << endl;
   cout << "\t--no-tracking        start with tracking rectangles disabled" << endl;
   cout << "\t--no-detection       disable object detection" << endl;
   cout << "\t--d12Base=           base directory for d12 info" << endl;
   cout << "\t--d12Dir=            pick d12 dir and stage number" << endl;
   cout << "\t--d12Stage=          from command line" << endl;
   cout << "\t--d24Base=           base directory for d24 info" << endl;
   cout << "\t--d24Dir=            pick d24 dir and stage number" << endl;
   cout << "\t--d24Stage=          from command line" << endl;
   cout << "\t--groundTruth        only test frames which have ground truth data " << endl;
   cout << "\t--xmlFile=           XML file to read/write settings to/from" << endl;
   cout << endl;
   cout << "Examples:" << endl;
   cout << "test : start in GUI mode, open default camera, start detecting and tracking while displaying results in the GUI" << endl;
   cout << "test --batch --capture : Start without a gui, write captured video to disk.  This is the normal way the code is run on the robot during matches. The code communicates via network tables to the roborio." << endl;
   cout << "test --batch --all foo.mp4 : run through foo.mp4. For each frame, write to disk images of all recognized objects. Might be useful for grabbing negative samples from a video known to have no positives in it" << endl;
}

Args::Args(void)
{
	captureAll         = false;
	tracking           = true;
	rects              = true;
	batchMode          = false;
	pause              = false;
	skip               = 0;
	calibrate          = false;
	writeVideo         = false;
	writeVideoSkip     = 1;
	saveVideo          = false;
	saveVideoSkip      = 1;
	detection          = true;
	d12BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/d12";
	d12DirNum          = -1;
	d12StageNum        = -1;
	d12Threshold       = 45;
	d24BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/d24";
	d24DirNum          = -1;
	d24StageNum        = -1;
	d24Threshold       = 98;
	c12BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/c12";
	c12DirNum          = -1;
	c12StageNum        = -1;
	c12Threshold       = 21;
	c24BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/c24";
	c24DirNum          = -1;
	c24StageNum        = -1;
	c24Threshold       = 5;
	frameStart         = 0.0;
	groundTruth        = false;
	xmlFilename        = "/home/ubuntu/2016VisionCode/zebravision/settings.xml";
}

bool Args::processArgs(int argc, const char **argv)
{
	const string frameOpt           = "--frame=";          // start at given frame
	const string captureAllOpt      = "--all";             // capture all detected images in each frame
	const string batchModeOpt       = "--batch";           // run without GUI
	const string pauseOpt           = "--pause";           // start paused
	const string skipOpt            = "--skip=";           // skip frames in input video file
	const string calibrateOpt       = "--calibrate";       // bring up crosshair to calibrate camera position
	const string writeVideoOpt      = "--capture";         // save camera video to output file
	const string writeVideoSkipOpt  = "--captureSkip=";    // skip frames in output video file
	const string saveVideoOpt       = "--save";            // write processed video to output file
	const string saveVideoSkipOpt   = "--saveSkip=";       // only write every N frames of processed video
	const string rectsOpt           = "--no-rects";        // start with detection rectangles disabled
	const string trackingOpt        = "--no-tracking";     // start with tracking rectangles disabled
	const string detectOpt          = "--no-detection";    // disable object detection
	const string d12BaseOpt         = "--d12Base=";        // d12 base dir
	const string d12DirOpt          = "--d12Dir=";         // pick d12 dir and stage number
	const string d12StageOpt        = "--d12Stage=";       // from command line
	const string d12ThresholdOpt    = "--d12Threshold=";
	const string d24BaseOpt         = "--d24Base=";        // d24 base dir
	const string d24DirOpt          = "--d24Dir=";         // pick d24 dir and stage number
	const string d24StageOpt        = "--d24Stage=";       // from command line
	const string d24ThresholdOpt    = "--d24Threshold=";
	const string c12BaseOpt         = "--c12Base=";        // c12 base dir
	const string c12DirOpt          = "--c12Dir=";         // pick c12 dir and stage number
	const string c12StageOpt        = "--c12Stage=";       // from command line
	const string c12ThresholdOpt    = "--c12Threshold=";
	const string c24BaseOpt         = "--c24Base=";        // c24 base dir
	const string c24DirOpt          = "--c24Dir=";         // pick c24 dir and stage number
	const string c24StageOpt        = "--c24Stage=";       // from command line
	const string c24ThresholdOpt    = "--c24Threshold=";
	const string groundTruthOpt     = "--groundTruth";     // only test frames which have ground truth data
	const string xmlFileOpt         = "--xmlFile=";        // read camera settings from XML file
	const string badOpt             = "--";
	// Read through command line args, extract
	// cmd line parameters and input filename
	int fileArgc;
	for (fileArgc = 1; fileArgc < argc; fileArgc++)
	{
		if (frameOpt.compare(0, frameOpt.length(), argv[fileArgc], frameOpt.length()) == 0)
			frameStart = atoi(argv[fileArgc] + frameOpt.length());
		else if (captureAllOpt.compare(0, captureAllOpt.length(), argv[fileArgc], captureAllOpt.length()) == 0)
			captureAll = true;
		else if (batchModeOpt.compare(0, batchModeOpt.length(), argv[fileArgc], batchModeOpt.length()) == 0)
			batchMode = true;
		else if (pauseOpt.compare(0, pauseOpt.length(), argv[fileArgc], pauseOpt.length()) == 0)
			pause = true;
		else if (skipOpt.compare(0, skipOpt.length(), argv[fileArgc], skipOpt.length()) == 0)
			skip = atoi(argv[fileArgc] + skipOpt.length());
		else if (calibrateOpt.compare(0, calibrateOpt.length(), argv[fileArgc], calibrateOpt.length()) == 0)
			calibrate = true;
		else if (writeVideoSkipOpt.compare(0, writeVideoSkipOpt.length(), argv[fileArgc], writeVideoSkipOpt.length()) == 0)
			writeVideoSkip = atoi(argv[fileArgc] + writeVideoSkipOpt.length());
		else if (writeVideoOpt.compare(0, writeVideoOpt.length(), argv[fileArgc], writeVideoOpt.length()) == 0)
			writeVideo = true;
		else if (saveVideoSkipOpt.compare(0, saveVideoSkipOpt.length(), argv[fileArgc], saveVideoSkipOpt.length()) == 0)
			saveVideoSkip = atoi(argv[fileArgc] + saveVideoSkipOpt.length());
		else if (saveVideoOpt.compare(0, saveVideoOpt.length(), argv[fileArgc], saveVideoOpt.length()) == 0)
			saveVideo = true;
		else if (detectOpt.compare(0, detectOpt.length(), argv[fileArgc], detectOpt.length()) == 0)
			detection = false;
		else if (trackingOpt.compare(0, trackingOpt.length(), argv[fileArgc], trackingOpt.length()) == 0)
			tracking = false;
		else if (rectsOpt.compare(0, rectsOpt.length(), argv[fileArgc], rectsOpt.length()) == 0)
			rects = false;
		else if (d12BaseOpt.compare(0, d12BaseOpt.length(), argv[fileArgc], d12BaseOpt.length()) == 0)
			d12BaseDir = string(argv[fileArgc] + d12BaseOpt.length());
		else if (d12DirOpt.compare(0, d12DirOpt.length(), argv[fileArgc], d12DirOpt.length()) == 0)
			d12DirNum = atoi(argv[fileArgc] + d12DirOpt.length());
		else if (d12StageOpt.compare(0, d12StageOpt.length(), argv[fileArgc], d12StageOpt.length()) == 0)
			d12StageNum = atoi(argv[fileArgc] + d12StageOpt.length());
		else if (d12ThresholdOpt.compare(0, d12ThresholdOpt.length(), argv[fileArgc], d12ThresholdOpt.length()) == 0)
			d12Threshold = atoi(argv[fileArgc] + d12ThresholdOpt.length());
		else if (d24BaseOpt.compare(0, d24BaseOpt.length(), argv[fileArgc], d24BaseOpt.length()) == 0)
			d24BaseDir = string(argv[fileArgc] + d24BaseOpt.length());
		else if (d24DirOpt.compare(0, d24DirOpt.length(), argv[fileArgc], d24DirOpt.length()) == 0)
			d24DirNum = atoi(argv[fileArgc] + d24DirOpt.length());
		else if (d24StageOpt.compare(0, d24StageOpt.length(), argv[fileArgc], d24StageOpt.length()) == 0)
			d24StageNum = atoi(argv[fileArgc] + d24StageOpt.length());
		else if (d24ThresholdOpt.compare(0, d24ThresholdOpt.length(), argv[fileArgc], d24ThresholdOpt.length()) == 0)
			d24Threshold = atoi(argv[fileArgc] + d24ThresholdOpt.length());
		else if (c12BaseOpt.compare(0, c12BaseOpt.length(), argv[fileArgc], c12BaseOpt.length()) == 0)
			c12BaseDir = string(argv[fileArgc] + c12BaseOpt.length());
		else if (c12DirOpt.compare(0, c12DirOpt.length(), argv[fileArgc], c12DirOpt.length()) == 0)
			c12DirNum = atoi(argv[fileArgc] + c12DirOpt.length());
		else if (c12StageOpt.compare(0, c12StageOpt.length(), argv[fileArgc], c12StageOpt.length()) == 0)
			c12StageNum = atoi(argv[fileArgc] + c12StageOpt.length());
		else if (c12ThresholdOpt.compare(0, c12ThresholdOpt.length(), argv[fileArgc], c12ThresholdOpt.length()) == 0)
			c12Threshold = atoi(argv[fileArgc] + c12ThresholdOpt.length());
		else if (c24BaseOpt.compare(0, c24BaseOpt.length(), argv[fileArgc], c24BaseOpt.length()) == 0)
			c24BaseDir = string(argv[fileArgc] + c24BaseOpt.length());
		else if (c24DirOpt.compare(0, c24DirOpt.length(), argv[fileArgc], c24DirOpt.length()) == 0)
			c24DirNum = atoi(argv[fileArgc] + c24DirOpt.length());
		else if (c24StageOpt.compare(0, c24StageOpt.length(), argv[fileArgc], c24StageOpt.length()) == 0)
			c24StageNum = atoi(argv[fileArgc] + c24StageOpt.length());
		else if (c24ThresholdOpt.compare(0, c24ThresholdOpt.length(), argv[fileArgc], c24ThresholdOpt.length()) == 0)
			c24Threshold = atoi(argv[fileArgc] + c24ThresholdOpt.length());
		else if (groundTruthOpt.compare(0, groundTruthOpt.length(), argv[fileArgc], groundTruthOpt.length()) == 0)
			groundTruth = true;
		else if (xmlFileOpt.compare(0, xmlFileOpt.length(), argv[fileArgc], xmlFileOpt.length()) == 0)
			xmlFilename = string(argv[fileArgc] + xmlFileOpt.length());
		else if (badOpt.compare(0, badOpt.length(), argv[fileArgc], badOpt.length()) == 0) // unknown option
		{
			cerr << "Unknown command line option " << argv[fileArgc] << endl;
			Usage();
			return false;
		}
		else // first non -- arg is filename or camera number
			break;
	}
	if (argc > (fileArgc + 1))
	{
	   cerr << "Extra arguments after file name" << endl;
	   Usage();
	   return false;
	}
	if (fileArgc < argc)
		inputName = argv[fileArgc];
	return true;
}
<commit_msg>Update args<commit_after>#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <stdlib.h>
#include "Args.hpp"

using namespace std;

static void Usage(void)
{
   cout << "Usage : test [option list] [camera # | input file name]" << endl << endl;
   cout << "  Camera number is an integer corresponding to /dev/video??" << endl;
   cout << "  Input files can be video, combined video & depth (ZMS or SVO) or PNG/JPG images" << endl;

   cout << "\t--frame=<frame num>  start at given frame" << endl;
   cout << "\t--all                write to disk all detected images in each frame" << endl;
   cout << "\t--batch              run without GUI" << endl;
   cout << "\t--skip=<x>           skip frames, only processing every <x> - file input only" << endl;
   cout << "\t--pause              start paused" << endl;
   cout << "\t--calibrate          bring up crosshair to calibrate camera position" << endl;
   cout << "\t--capture            write raw camera video to output file" << endl;
   cout << "\t--captureSkip=       only write one of every N frames" << endl;
   cout << "\t--save               write processed video to output file" << endl;
   cout << "\t--saveSkip=          only write one of every N processed frames" << endl;
   cout << "\t--no-rects           start with detection rectangles disabled" << endl;
   cout << "\t--no-tracking        start with tracking rectangles disabled" << endl;
   cout << "\t--no-detection       disable object detection" << endl;
   cout << "\t--d12Base=           base directory for d12 info" << endl;
   cout << "\t--d12Dir=            pick d12 dir and stage number" << endl;
   cout << "\t--d12Stage=          from command line" << endl;
   cout << "\t--d12Threshold=      set d12 detection threshold" << endl;
   cout << "\t--d24Base=           base directory for d24 info" << endl;
   cout << "\t--d24Dir=            pick d24 dir and stage number" << endl;
   cout << "\t--d24Stage=          from command line" << endl;
   cout << "\t--d24Threshold=      set d24 detection threshold" << endl;
   cout << "\t--c12Base=           base directory for c12 info" << endl;
   cout << "\t--c12Dir=            pick c12 dir and stage number" << endl;
   cout << "\t--c12Stage=          from command line" << endl;
   cout << "\t--c12Threshold=      set c12 detection threshold" << endl;
   cout << "\t--c24Base=           base directory for c24 info" << endl;
   cout << "\t--c24Dir=            pick c24 dir and stage number" << endl;
   cout << "\t--c24Stage=          from command line" << endl;
   cout << "\t--c24Threshold=      set c24 detection threshold" << endl;
   cout << "\t--groundTruth        only test frames which have ground truth data " << endl;
   cout << "\t--xmlFile=           XML file to read/write settings to/from" << endl;
   cout << endl;
   cout << "Examples:" << endl;
   cout << "test : start in GUI mode, open default camera, start detecting and tracking while displaying results in the GUI" << endl;
   cout << "test --batch --capture : Start without a gui, write captured video to disk.  This is the normal way the code is run on the robot during matches. The code communicates via ZMQ to the roborio." << endl;
   cout << "test --batch --all foo.mp4 : run through foo.mp4. For each frame, write to disk images of all recognized objects. Might be useful for grabbing negative samples from a video known to have no positives in it" << endl;
}

Args::Args(void)
{
	captureAll         = false;
	tracking           = true;
	rects              = true;
	batchMode          = false;
	pause              = false;
	skip               = 0;
	calibrate          = false;
	writeVideo         = false;
	writeVideoSkip     = 1;
	saveVideo          = false;
	saveVideoSkip      = 1;
	detection          = true;
	d12BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/d12";
	d12DirNum          = -1;
	d12StageNum        = -1;
	d12Threshold       = 45;
	d24BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/d24";
	d24DirNum          = -1;
	d24StageNum        = -1;
	d24Threshold       = 98;
	c12BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/c12";
	c12DirNum          = -1;
	c12StageNum        = -1;
	c12Threshold       = 21;
	c24BaseDir         = "/home/ubuntu/2016VisionCode/zebravision/c24";
	c24DirNum          = -1;
	c24StageNum        = -1;
	c24Threshold       = 5;
	frameStart         = 0.0;
	groundTruth        = false;
	xmlFilename        = "/home/ubuntu/2016VisionCode/zebravision/settings.xml";
}

bool Args::processArgs(int argc, const char **argv)
{
	const string frameOpt           = "--frame=";          // start at given frame
	const string captureAllOpt      = "--all";             // capture all detected images in each frame
	const string batchModeOpt       = "--batch";           // run without GUI
	const string pauseOpt           = "--pause";           // start paused
	const string skipOpt            = "--skip=";           // skip frames in input video file
	const string calibrateOpt       = "--calibrate";       // bring up crosshair to calibrate camera position
	const string writeVideoOpt      = "--capture";         // save camera video to output file
	const string writeVideoSkipOpt  = "--captureSkip=";    // skip frames in output video file
	const string saveVideoOpt       = "--save";            // write processed video to output file
	const string saveVideoSkipOpt   = "--saveSkip=";       // only write every N frames of processed video
	const string rectsOpt           = "--no-rects";        // start with detection rectangles disabled
	const string trackingOpt        = "--no-tracking";     // start with tracking rectangles disabled
	const string detectOpt          = "--no-detection";    // disable object detection
	const string d12BaseOpt         = "--d12Base=";        // d12 base dir
	const string d12DirOpt          = "--d12Dir=";         // pick d12 dir and stage number
	const string d12StageOpt        = "--d12Stage=";       // from command line
	const string d12ThresholdOpt    = "--d12Threshold=";
	const string d24BaseOpt         = "--d24Base=";        // d24 base dir
	const string d24DirOpt          = "--d24Dir=";         // pick d24 dir and stage number
	const string d24StageOpt        = "--d24Stage=";       // from command line
	const string d24ThresholdOpt    = "--d24Threshold=";
	const string c12BaseOpt         = "--c12Base=";        // c12 base dir
	const string c12DirOpt          = "--c12Dir=";         // pick c12 dir and stage number
	const string c12StageOpt        = "--c12Stage=";       // from command line
	const string c12ThresholdOpt    = "--c12Threshold=";
	const string c24BaseOpt         = "--c24Base=";        // c24 base dir
	const string c24DirOpt          = "--c24Dir=";         // pick c24 dir and stage number
	const string c24StageOpt        = "--c24Stage=";       // from command line
	const string c24ThresholdOpt    = "--c24Threshold=";
	const string groundTruthOpt     = "--groundTruth";     // only test frames which have ground truth data
	const string xmlFileOpt         = "--xmlFile=";        // read camera settings from XML file
	const string badOpt             = "--";
	// Read through command line args, extract
	// cmd line parameters and input filename
	int fileArgc;
	for (fileArgc = 1; fileArgc < argc; fileArgc++)
	{
		if (frameOpt.compare(0, frameOpt.length(), argv[fileArgc], frameOpt.length()) == 0)
			frameStart = atoi(argv[fileArgc] + frameOpt.length());
		else if (captureAllOpt.compare(0, captureAllOpt.length(), argv[fileArgc], captureAllOpt.length()) == 0)
			captureAll = true;
		else if (batchModeOpt.compare(0, batchModeOpt.length(), argv[fileArgc], batchModeOpt.length()) == 0)
			batchMode = true;
		else if (pauseOpt.compare(0, pauseOpt.length(), argv[fileArgc], pauseOpt.length()) == 0)
			pause = true;
		else if (skipOpt.compare(0, skipOpt.length(), argv[fileArgc], skipOpt.length()) == 0)
			skip = atoi(argv[fileArgc] + skipOpt.length());
		else if (calibrateOpt.compare(0, calibrateOpt.length(), argv[fileArgc], calibrateOpt.length()) == 0)
			calibrate = true;
		else if (writeVideoSkipOpt.compare(0, writeVideoSkipOpt.length(), argv[fileArgc], writeVideoSkipOpt.length()) == 0)
			writeVideoSkip = atoi(argv[fileArgc] + writeVideoSkipOpt.length());
		else if (writeVideoOpt.compare(0, writeVideoOpt.length(), argv[fileArgc], writeVideoOpt.length()) == 0)
			writeVideo = true;
		else if (saveVideoSkipOpt.compare(0, saveVideoSkipOpt.length(), argv[fileArgc], saveVideoSkipOpt.length()) == 0)
			saveVideoSkip = atoi(argv[fileArgc] + saveVideoSkipOpt.length());
		else if (saveVideoOpt.compare(0, saveVideoOpt.length(), argv[fileArgc], saveVideoOpt.length()) == 0)
			saveVideo = true;
		else if (detectOpt.compare(0, detectOpt.length(), argv[fileArgc], detectOpt.length()) == 0)
			detection = false;
		else if (trackingOpt.compare(0, trackingOpt.length(), argv[fileArgc], trackingOpt.length()) == 0)
			tracking = false;
		else if (rectsOpt.compare(0, rectsOpt.length(), argv[fileArgc], rectsOpt.length()) == 0)
			rects = false;
		else if (d12BaseOpt.compare(0, d12BaseOpt.length(), argv[fileArgc], d12BaseOpt.length()) == 0)
			d12BaseDir = string(argv[fileArgc] + d12BaseOpt.length());
		else if (d12DirOpt.compare(0, d12DirOpt.length(), argv[fileArgc], d12DirOpt.length()) == 0)
			d12DirNum = atoi(argv[fileArgc] + d12DirOpt.length());
		else if (d12StageOpt.compare(0, d12StageOpt.length(), argv[fileArgc], d12StageOpt.length()) == 0)
			d12StageNum = atoi(argv[fileArgc] + d12StageOpt.length());
		else if (d12ThresholdOpt.compare(0, d12ThresholdOpt.length(), argv[fileArgc], d12ThresholdOpt.length()) == 0)
			d12Threshold = atoi(argv[fileArgc] + d12ThresholdOpt.length());
		else if (d24BaseOpt.compare(0, d24BaseOpt.length(), argv[fileArgc], d24BaseOpt.length()) == 0)
			d24BaseDir = string(argv[fileArgc] + d24BaseOpt.length());
		else if (d24DirOpt.compare(0, d24DirOpt.length(), argv[fileArgc], d24DirOpt.length()) == 0)
			d24DirNum = atoi(argv[fileArgc] + d24DirOpt.length());
		else if (d24StageOpt.compare(0, d24StageOpt.length(), argv[fileArgc], d24StageOpt.length()) == 0)
			d24StageNum = atoi(argv[fileArgc] + d24StageOpt.length());
		else if (d24ThresholdOpt.compare(0, d24ThresholdOpt.length(), argv[fileArgc], d24ThresholdOpt.length()) == 0)
			d24Threshold = atoi(argv[fileArgc] + d24ThresholdOpt.length());
		else if (c12BaseOpt.compare(0, c12BaseOpt.length(), argv[fileArgc], c12BaseOpt.length()) == 0)
			c12BaseDir = string(argv[fileArgc] + c12BaseOpt.length());
		else if (c12DirOpt.compare(0, c12DirOpt.length(), argv[fileArgc], c12DirOpt.length()) == 0)
			c12DirNum = atoi(argv[fileArgc] + c12DirOpt.length());
		else if (c12StageOpt.compare(0, c12StageOpt.length(), argv[fileArgc], c12StageOpt.length()) == 0)
			c12StageNum = atoi(argv[fileArgc] + c12StageOpt.length());
		else if (c12ThresholdOpt.compare(0, c12ThresholdOpt.length(), argv[fileArgc], c12ThresholdOpt.length()) == 0)
			c12Threshold = atoi(argv[fileArgc] + c12ThresholdOpt.length());
		else if (c24BaseOpt.compare(0, c24BaseOpt.length(), argv[fileArgc], c24BaseOpt.length()) == 0)
			c24BaseDir = string(argv[fileArgc] + c24BaseOpt.length());
		else if (c24DirOpt.compare(0, c24DirOpt.length(), argv[fileArgc], c24DirOpt.length()) == 0)
			c24DirNum = atoi(argv[fileArgc] + c24DirOpt.length());
		else if (c24StageOpt.compare(0, c24StageOpt.length(), argv[fileArgc], c24StageOpt.length()) == 0)
			c24StageNum = atoi(argv[fileArgc] + c24StageOpt.length());
		else if (c24ThresholdOpt.compare(0, c24ThresholdOpt.length(), argv[fileArgc], c24ThresholdOpt.length()) == 0)
			c24Threshold = atoi(argv[fileArgc] + c24ThresholdOpt.length());
		else if (groundTruthOpt.compare(0, groundTruthOpt.length(), argv[fileArgc], groundTruthOpt.length()) == 0)
			groundTruth = true;
		else if (xmlFileOpt.compare(0, xmlFileOpt.length(), argv[fileArgc], xmlFileOpt.length()) == 0)
			xmlFilename = string(argv[fileArgc] + xmlFileOpt.length());
		else if (badOpt.compare(0, badOpt.length(), argv[fileArgc], badOpt.length()) == 0) // unknown option
		{
			cerr << "Unknown command line option " << argv[fileArgc] << endl;
			Usage();
			return false;
		}
		else // first non -- arg is filename or camera number
			break;
	}
	if (argc > (fileArgc + 1))
	{
	   cerr << "Extra arguments after file name" << endl;
	   Usage();
	   return false;
	}
	if (fileArgc < argc)
		inputName = argv[fileArgc];
	return true;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperQtWidgetModel.h"

//Use to create command line from the application parameters
#include "otbWrapperOutputProcessXMLParameter.h"

namespace otb
{

namespace Wrapper
{

QtWidgetModel
::QtWidgetModel(Application* app) :
  m_Application(app),
  m_LogOutput(),
  m_IsRunning(false)
{
  // Init only if not already done
  if(!m_Application->IsInitialized())
    {
    m_Application->Init();
    }

  m_LogOutput = QtLogOutput::New();

 // Attach log output to the Application logger
  m_Application->GetLogger()->SetTimeStampFormat(itk::LoggerBase::HUMANREADABLE);
  m_Application->GetLogger()->AddLogOutput(m_LogOutput);
}

QtWidgetModel::~QtWidgetModel()
{
}

void
QtWidgetModel
::NotifyUpdate()
{
  // Update the parameters
  m_Application->UpdateParameters();
  emit UpdateGui();

  // Notify all
  if (!m_IsRunning)
    {
    bool applicationStatus = m_Application->IsApplicationReady();
    emit SetApplicationReady(applicationStatus);
    }
}

void
QtWidgetModel
::ExecuteAndWriteOutputSlot()
{
  // Deactivate the Execute button while processing
  emit SetApplicationReady(false);
  m_IsRunning = true;

  //Buld corresponding command line and display to the Log tab

  //Build XML DOM from m_application

  OutputProcessXMLParameter::Pointer outXMLParam = OutputProcessXMLParameter::New();

  TiXmlElement* XMLAppElement = outXMLParam->ParseApplication(m_Application);

  //Create command line from the XML dom
  TiXmlElement * pName, *pParam;
  std::ostringstream cmdLine;

  if(XMLAppElement)
    {
    pName = XMLAppElement->FirstChildElement("name");

    cmdLine << "otbcli_" << pName->FirstChild()->ValueStr();
    cmdLine << " ";

    std::cout << "App name " << pName->FirstChild()->ValueStr() << std::endl;

    //Parse application parameters
    pParam = XMLAppElement->FirstChildElement("parameter");

    while(pParam)
        {
        //Get pareter key
        cmdLine << "-";
        cmdLine << pParam->FirstChildElement("key")->FirstChild()->ValueStr();
        cmdLine << " ";

        //Some parameters can have multiple values. Test it and handle this
        //specific case
        TiXmlElement * values = pParam->FirstChildElement("values");

        if (values)
          {
          //Loop over value
          TiXmlElement * pValue = pParam->FirstChildElement("value");
          while(pValue)
            {
            cmdLine << pValue->FirstChild()->ValueStr();
            cmdLine << " ";

            pValue = pValue->NextSiblingElement(); // iteration over multiple values
            }
          }
        else
          {
          //Get parameter value
          cmdLine << pParam->FirstChildElement("value")->FirstChild()->ValueStr();
          cmdLine << " ";

          //In case of OutputImageparameter we need to report output pixel type
          TiXmlElement * pPixType = pParam->FirstChildElement("pixtype");

          if (pPixType)
            {
            cmdLine << pPixType->FirstChild()->ValueStr();
            cmdLine << " ";
            }
          }

        pParam = pParam->NextSiblingElement(); // iteration over parameters
        }

    std::cout << cmdLine.str() << std::endl;

    //Report the command line string to the app logger
    m_Application->GetLogger()->Write(itk::LoggerBase::INFO, cmdLine.str());
    }
  else
    {
    //itkExceptionMacro(<< "Could not load XML application descriptor");
    std::cout << "ERROR" << std::endl;
    }

  // launch the output image writing
  AppliThread * taskAppli = new AppliThread( m_Application );

  QObject::connect(
    taskAppli,
    SIGNAL( ExceptionRaised( QString ) ),
    // to:
    this,
    SIGNAL( ExceptionRaised( QString ) )
  );

  QObject::connect(
    taskAppli,
    SIGNAL( ApplicationExecutionDone( int ) ),
    // to:
    this,
    SLOT( OnApplicationExecutionDone( int ) )
  );

  taskAppli->Execute();

  // Tell the Progress Reporter to begin
  emit SetProgressReportBegin();
}

void
QtWidgetModel
::OnApplicationExecutionDone( int status )
{
  m_IsRunning = false;

  // Require GUI update.
  NotifyUpdate();

  // For the view to activate the button "Execute"
  emit SetApplicationReady( true );

  // For the progressReport to close the Progress widget
  emit SetProgressReportDone( status );
}

void
QtWidgetModel
::SendLogWARNING( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::WARNING, mes );
}

void
QtWidgetModel
::SendLogINFO( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::INFO, mes );
}

void
QtWidgetModel
::SendLogDEBUG( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::DEBUG, mes );
}

}

}

namespace otb
{

namespace Wrapper
{

AppliThread
::~AppliThread()
{
  wait();
}

void
AppliThread
::run()
{
  int result = -1;

  //
  // Try to execute OTB-application.
  try
    {
    result = m_Application->ExecuteAndWriteOutput();
    }
  //
  // Catch standard exceptions.
  catch( std::exception& err )
    {
    std::ostringstream message;

    message
      << "The following error occurred during OTB-application execution: "
      << err.what()
      << std::endl;

    m_Application->GetLogger()->Write( itk::LoggerBase::FATAL, message.str() );

    // Signal exception.
    emit ExceptionRaised( err.what() );
    }
  //
  // Catch other exceptions.
  catch( ... )
    {
    m_Application->GetLogger()->Write(
      itk::LoggerBase::FATAL,
      "An unknown exception has been raised during OTB-application execution"
    );

    // Signal exception.
    emit ExceptionRaised( "Exception raised by OTB-application." );
    }
  //
  // Signal OTB-application has ended with result status.
  emit ApplicationExecutionDone( result );
}

}

}
<commit_msg>ENH: Remove cout and add comments<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperQtWidgetModel.h"

//Use to create command line from the application parameters
#include "otbWrapperOutputProcessXMLParameter.h"

namespace otb
{

namespace Wrapper
{

QtWidgetModel
::QtWidgetModel(Application* app) :
  m_Application(app),
  m_LogOutput(),
  m_IsRunning(false)
{
  // Init only if not already done
  if(!m_Application->IsInitialized())
    {
    m_Application->Init();
    }

  m_LogOutput = QtLogOutput::New();

  // Attach log output to the Application logger
  m_Application->GetLogger()->SetTimeStampFormat(itk::LoggerBase::HUMANREADABLE);
  m_Application->GetLogger()->AddLogOutput(m_LogOutput);
}

QtWidgetModel::~QtWidgetModel()
{
}

void
QtWidgetModel
::NotifyUpdate()
{
  // Update the parameters
  m_Application->UpdateParameters();
  emit UpdateGui();

  // Notify all
  if (!m_IsRunning)
    {
    bool applicationStatus = m_Application->IsApplicationReady();
    emit SetApplicationReady(applicationStatus);
    }
}

void
QtWidgetModel
::ExecuteAndWriteOutputSlot()
{
  // Deactivate the Execute button while processing
  emit SetApplicationReady(false);
  m_IsRunning = true;

  //Buld corresponding command line and display to the Log tab

  //Build XML DOM from m_application
  OutputProcessXMLParameter::Pointer outXMLParam = OutputProcessXMLParameter::New();

  TiXmlElement* XMLAppElement = outXMLParam->ParseApplication(m_Application);

  //Create command line from the XML document
  TiXmlElement * pName, *pParam;
  std::ostringstream cmdLine;

  if(XMLAppElement)
    {
    pName = XMLAppElement->FirstChildElement("name");

    cmdLine << "otbcli_" << pName->FirstChild()->ValueStr();
    cmdLine << " ";

    //Parse application parameters
    pParam = XMLAppElement->FirstChildElement("parameter");

    while(pParam)
      {
      //Get pareter key
      cmdLine << "-";
      cmdLine << pParam->FirstChildElement("key")->FirstChild()->ValueStr();
      cmdLine << " ";

      //Some parameters can have multiple values. Test it and handle this
      //specific case
      TiXmlElement * values = pParam->FirstChildElement("values");

      if (values)
        {
        //Loop over value
        TiXmlElement * pValue = pParam->FirstChildElement("value");
        while(pValue)
          {
          cmdLine << pValue->FirstChild()->ValueStr();
          cmdLine << " ";

          pValue = pValue->NextSiblingElement(); // iteration over multiple values
          }
        }
      else
        {
        //Get parameter value
        cmdLine << pParam->FirstChildElement("value")->FirstChild()->ValueStr();
        cmdLine << " ";

        //In case of OutputImageparameter we need to report output pixel type
        TiXmlElement * pPixType = pParam->FirstChildElement("pixtype");

        if (pPixType)
          {
          cmdLine << pPixType->FirstChild()->ValueStr();
          cmdLine << " ";
          }
        }

      pParam = pParam->NextSiblingElement(); // iteration over parameters
      }

    //Report the command line string to the application logger
    m_Application->GetLogger()->Write(itk::LoggerBase::INFO, cmdLine.str());
    }

  // launch the output image writing
  AppliThread * taskAppli = new AppliThread( m_Application );

  QObject::connect(
    taskAppli,
    SIGNAL( ExceptionRaised( QString ) ),
    // to:
    this,
    SIGNAL( ExceptionRaised( QString ) )
  );

  QObject::connect(
    taskAppli,
    SIGNAL( ApplicationExecutionDone( int ) ),
    // to:
    this,
    SLOT( OnApplicationExecutionDone( int ) )
  );

  taskAppli->Execute();

  // Tell the Progress Reporter to begin
  emit SetProgressReportBegin();
}

void
QtWidgetModel
::OnApplicationExecutionDone( int status )
{
  m_IsRunning = false;

  // Require GUI update.
  NotifyUpdate();

  // For the view to activate the button "Execute"
  emit SetApplicationReady( true );

  // For the progressReport to close the Progress widget
  emit SetProgressReportDone( status );
}

void
QtWidgetModel
::SendLogWARNING( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::WARNING, mes );
}

void
QtWidgetModel
::SendLogINFO( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::INFO, mes );
}

void
QtWidgetModel
::SendLogDEBUG( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::DEBUG, mes );
}

}

}

namespace otb
{

namespace Wrapper
{

AppliThread
::~AppliThread()
{
  wait();
}

void
AppliThread
::run()
{
  int result = -1;

  //
  // Try to execute OTB-application.
  try
    {
    result = m_Application->ExecuteAndWriteOutput();
    }
  //
  // Catch standard exceptions.
  catch( std::exception& err )
    {
    std::ostringstream message;

    message
      << "The following error occurred during OTB-application execution: "
      << err.what()
      << std::endl;

    m_Application->GetLogger()->Write( itk::LoggerBase::FATAL, message.str() );

    // Signal exception.
    emit ExceptionRaised( err.what() );
    }
  //
  // Catch other exceptions.
  catch( ... )
    {
    m_Application->GetLogger()->Write(
      itk::LoggerBase::FATAL,
      "An unknown exception has been raised during OTB-application execution"
    );

    // Signal exception.
    emit ExceptionRaised( "Exception raised by OTB-application." );
    }
  //
  // Signal OTB-application has ended with result status.
  emit ApplicationExecutionDone( result );
}

}

}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIPCRERegexMatcher.cpp
    created:    Mon Jul 27 2009
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   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.
 ***************************************************************************/
#include "CEGUI/PCRERegexMatcher.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
PCRERegexMatcher::PCRERegexMatcher() :
    d_regex(0)
{
}

//----------------------------------------------------------------------------//
PCRERegexMatcher::~PCRERegexMatcher()
{
    release();
}

//----------------------------------------------------------------------------//
void PCRERegexMatcher::setRegexString(const String& regex)
{
    // release old regex string.
    release();
    d_string.clear();
    // try to compile this new regex string
    const char* prce_error;
    int pcre_erroff;
    d_regex = pcre_compile(regex.c_str(), PCRE_UTF8,
                           &prce_error, &pcre_erroff, 0);

    // handle failure
    if (!d_regex)
        CEGUI_THROW(InvalidRequestException(
            "Bad RegEx set: '" + regex + "'.  Additional Information: " +
            prce_error));

    // set this last so that upon failure object is in consistant state.
    d_string = regex;
}

//----------------------------------------------------------------------------//
const String& PCRERegexMatcher::getRegexString() const
{
    return d_string;
}

//----------------------------------------------------------------------------//
RegexMatcher::MatchState PCRERegexMatcher::getMatchStateOfString(
                                                        const String& str) const
{
    // if the regex is not valid, then an exception is thrown
    if (!d_regex)
        CEGUI_THROW(InvalidRequestException(
            "Attempt to use invalid RegEx '" + d_string + "'."));

    int match[3];
    const char* utf8_str = str.c_str();
    const int len = static_cast<int>(strlen(utf8_str));
    const int result = pcre_exec(d_regex, 0, utf8_str, len, 0,
                                 PCRE_PARTIAL_SOFT | PCRE_ANCHORED, match, 3);

    if (result == PCRE_ERROR_PARTIAL)
        return MS_PARTIAL;

    // a match must be for the entire string
    if (result >= 0)
        return (match[1] - match[0] == len) ? MS_VALID : MS_INVALID;

    // no match found or if test string or regex is 0
    if (result == PCRE_ERROR_NOMATCH || result == PCRE_ERROR_NULL)
        return MS_INVALID;

    // anything else is an error
    CEGUI_THROW(InvalidRequestException(
        "PCRE Error: " + PropertyHelper<int>::toString(result) +
        " occurred while attempting to match the RegEx '" +
        d_string + "'."));
}

//----------------------------------------------------------------------------//
void PCRERegexMatcher::release()
{
    if (d_regex)
    {
        pcre_free(d_regex);
        d_regex = 0;
    }
}

} // End of  CEGUI namespace section
<commit_msg>Support pcre < 8.0 with the backwards compatible PCRE_PARTIAL option<commit_after>/***********************************************************************
    filename:   CEGUIPCRERegexMatcher.cpp
    created:    Mon Jul 27 2009
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   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.
 ***************************************************************************/
#include "CEGUI/PCRERegexMatcher.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
PCRERegexMatcher::PCRERegexMatcher() :
    d_regex(0)
{
}

//----------------------------------------------------------------------------//
PCRERegexMatcher::~PCRERegexMatcher()
{
    release();
}

//----------------------------------------------------------------------------//
void PCRERegexMatcher::setRegexString(const String& regex)
{
    // release old regex string.
    release();
    d_string.clear();
    // try to compile this new regex string
    const char* prce_error;
    int pcre_erroff;
    d_regex = pcre_compile(regex.c_str(), PCRE_UTF8,
                           &prce_error, &pcre_erroff, 0);

    // handle failure
    if (!d_regex)
        CEGUI_THROW(InvalidRequestException(
            "Bad RegEx set: '" + regex + "'.  Additional Information: " +
            prce_error));

    // set this last so that upon failure object is in consistant state.
    d_string = regex;
}

//----------------------------------------------------------------------------//
const String& PCRERegexMatcher::getRegexString() const
{
    return d_string;
}

//----------------------------------------------------------------------------//
RegexMatcher::MatchState PCRERegexMatcher::getMatchStateOfString(
                                                        const String& str) const
{
    // if the regex is not valid, then an exception is thrown
    if (!d_regex)
        CEGUI_THROW(InvalidRequestException(
            "Attempt to use invalid RegEx '" + d_string + "'."));

    int match[3];
    const char* utf8_str = str.c_str();
    const int len = static_cast<int>(strlen(utf8_str));
    // PCRE_PARTIAL is a backwards compatible synonym for PCRE_PARTIAL_SOFT
    // using it is a requirement if we want to support pcre < 8.0
    const int result = pcre_exec(d_regex, 0, utf8_str, len, 0,
                                 PCRE_PARTIAL | PCRE_ANCHORED, match, 3);

    if (result == PCRE_ERROR_PARTIAL)
        return MS_PARTIAL;

    // a match must be for the entire string
    if (result >= 0)
        return (match[1] - match[0] == len) ? MS_VALID : MS_INVALID;

    // no match found or if test string or regex is 0
    if (result == PCRE_ERROR_NOMATCH || result == PCRE_ERROR_NULL)
        return MS_INVALID;

    // anything else is an error
    CEGUI_THROW(InvalidRequestException(
        "PCRE Error: " + PropertyHelper<int>::toString(result) +
        " occurred while attempting to match the RegEx '" +
        d_string + "'."));
}

//----------------------------------------------------------------------------//
void PCRERegexMatcher::release()
{
    if (d_regex)
    {
        pcre_free(d_regex);
        d_regex = 0;
    }
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>//
//  Expression.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Expression.h"

Expression::Expression(){
}
Expression::~Expression(){

}
bool Expression::canAdd(Expression* b){     //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)

    if (this->type == b->type) {
        if (type == "nthRoot") {
            if (this operand == b.getOperand() && this root == b.getRoot()) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }
    return false;
}
bool Expression::canSubtract(Expression* b){
    if (this->type == b->type) {
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }
    return false;
}
bool Expression::canMultiply(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "int" && b->type == "rational") return true;
    else if(this->type == "rational" && b->type == "int") return true;

    return false;

}
bool Expression::canDivide(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "int"){
        if(b->type == "euler" || b->type == "pi" || b->type == "rational") return true;
    }
    else if(this->type == "rational" && b->type == "int") return true;

    return false;
}
ostream& operator<<(ostream &output, Expression &e){
    return e.print(output);
}
<commit_msg>fixed canSub/Mult/div w/r/t nthroot<commit_after>//
//  Expression.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Expression.h"

Expression::Expression(){
}
Expression::~Expression(){

}
bool Expression::canAdd(Expression* b){     //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)

    if (this->type == b->type) {
        if (type == "nthRoot") {
            if (this operand == b.getOperand() && this root == b.getRoot()) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }
    return false;
}
bool Expression::canSubtract(Expression* b){
    if (this->type == b->type) {
        if (type == "nthRoot") {
            if (this operand == b.getOperand() && this root == b.getRoot()) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }
    return false;
}
bool Expression::canMultiply(Expression* b){
    if (this->type == b->type) {
        if (type == "nthRoot") {
            if (this operand == b.getOperand()) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }
    else if(this->type == "int" && b->type == "rational") return true;
    else if(this->type == "rational" && b->type == "int") return true;

    return false;

}
bool Expression::canDivide(Expression* b){
    if (this->type == b->type) {
        if (type == "nthRoot") {
            if (this operand == b.getOperand()) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }
    else if(this->type == "int"){
        if(b->type == "euler" || b->type == "pi" || b->type == "rational") return true;
    }
    else if(this->type == "rational" && b->type == "int") return true;

    return false;
}
ostream& operator<<(ostream &output, Expression &e){
    return e.print(output);
}
<|endoftext|>


<commit_before><commit_msg>Renamed Conditional to If<commit_after><|endoftext|>


<commit_before>#pragma once

#include <boost/mpl/for_each.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/add_pointer.hpp>
#include <boost/shared_ptr.hpp>

namespace metaSMT
{
  namespace mpl = boost::mpl;

  template<typename Vec, template<class T> class Algo>
  class eval_visitor
  {
    public:
      typedef typename Algo<typename mpl::at_c <Vec, 0>::type>::result_type result_type;

      eval_visitor (unsigned wanted) :
         wanted_ (wanted)
       , result_ ( new result_type )
      {
        //       BOOST_STATIC_ASSERT ( !typename mpl::empty < Vec >::value );
      }
      result_type get_result() const
      {
        return *result_;
      }

    protected:
      unsigned wanted_;
      boost::shared_ptr < result_type > result_;
  };

  template<typename Vec, template<class T> class Algo>
  struct eval_visitor_0 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_0 ( unsigned wanted )
      : eval_visitor<Vec, Algo> ( wanted )
    {}

    template<typename U>
      void operator() (U const &)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo;
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }
  };

  template<typename Vec, template<class T> class Algo, typename ARG0>
  struct eval_visitor_1 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_1 (unsigned wanted, ARG0 arg0) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1>
  struct eval_visitor_2 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_2 (unsigned wanted, ARG0 arg0, ARG1 arg1) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1) {}

    template<typename U>
      void operator() (U *)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2>
  struct eval_visitor_3 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_3 (unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1)
      , arg2_ (arg2) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ , arg2_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
      ARG2 arg2_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3>
  struct eval_visitor_4 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_4 (unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1)
      , arg2_ (arg2)
      , arg3_ (arg3) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ , arg2_, arg3_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
      ARG2 arg2_;
      ARG3 arg3_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3, typename ARG4>
  struct eval_visitor_5 : public eval_visitor < Vec, Algo >

  {
    eval_visitor_5 (unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1)
      , arg2_ (arg2)
      , arg3_ (arg3)
      , arg4_ (arg4) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ , arg2_, arg3_, arg4_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
      ARG2 arg2_;
      ARG3 arg3_;
      ARG4 arg4_;
  };

  /**
   * \brief Run algorithm API
   *
   * compile an algorithm for multiple contexts. Select at run-time
   * which algorithm will be used.
   *
   * The call to run_algorithm is parametrized with an boost MPL sequence
   * of Context-types and an algorithm template that will be
   * instanciated for all Contexts. At run-time specific instance of the
   * Algorithm can be executed by passing its index in the sequence.
   * Furthermore parameters can be passed to the contexts operator().
   *
   * \code
   * typedef boost::mpl::vector <
   *     DirectSolver_Context < Boolector >
   *   , DirectSolver_Context < BitBlast < SAT_Aiger < MiniSAT > > >
   *   , DirectSolver_Context < BitBlast < SAT_Aiger < PicoSAT > > >
   *   , DirectSolver_Context < BitBlast < CUDD_Context > >

   *   , GraphSolver_Context < Boolector >
   *   , GraphSolver_Context < BitBlast < SAT_Aiger < MiniSAT > > >
   *   , GraphSolver_Context < BitBlast < SAT_Aiger < PicoSAT > > >
   *   , GraphSolver_Context < BitBlast < CUDD_Context > >
   *
   *     > SolverVec;
   *  DirectSolver_Context< Boolector > ctx;
   *
   *  template<typename Context>
   *  struct MyAlgorithm {
   *    typedef void result_type;
   *    result_type operator() () {
   *      Context ctx;
   *      ...
   *    }
   *  }
   *
   *  int main(int argc, const char *argv[])
   *  {
   *    unsigned i = atoi(argv[1]);
   *    run_algorithm<SolverVec, MyAlgorithm>(i);
   *    return 0;
   *  }
   * \endcode
   * \ingroup Support
   * \defgroup run_algorithm Run algorithm
   * @{
   */

  template<typename Vec, template<class T> class Algo>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted )
  {
    eval_visitor_0<Vec, Algo> visitor ( wanted );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0 )
  {
    eval_visitor_1<Vec, Algo, ARG0> visitor ( wanted, arg0 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1 )
  {
    eval_visitor_2<Vec, Algo, ARG0, ARG1> visitor ( wanted, arg0, arg1 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2 )
  {
    eval_visitor_3<Vec, Algo, ARG0, ARG1, ARG2> visitor ( wanted, arg0, arg1, arg2 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3 >
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3 )
  {
    eval_visitor_4<Vec, Algo, ARG0, ARG1, ARG2, ARG3> visitor ( wanted, arg0, arg1, arg2, arg3 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3, typename ARG4 >
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4 )
  {
    eval_visitor_5<Vec, Algo, ARG0, ARG1, ARG2, ARG3, ARG4> visitor ( wanted, arg0, arg1, arg2, arg3, arg4 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

  /**@}*/
}

<commit_msg>added missing include to run_algorithm<commit_after>#pragma once

#include <boost/mpl/for_each.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/find.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/add_pointer.hpp>
#include <boost/shared_ptr.hpp>

namespace metaSMT
{
  namespace mpl = boost::mpl;

  template<typename Vec, template<class T> class Algo>
  class eval_visitor
  {
    public:
      typedef typename Algo<typename mpl::at_c <Vec, 0>::type>::result_type result_type;

      eval_visitor (unsigned wanted) :
         wanted_ (wanted)
       , result_ ( new result_type )
      {
        //       BOOST_STATIC_ASSERT ( !typename mpl::empty < Vec >::value );
      }
      result_type get_result() const
      {
        return *result_;
      }

    protected:
      unsigned wanted_;
      boost::shared_ptr < result_type > result_;
  };

  template<typename Vec, template<class T> class Algo>
  struct eval_visitor_0 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_0 ( unsigned wanted )
      : eval_visitor<Vec, Algo> ( wanted )
    {}

    template<typename U>
      void operator() (U const &)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo;
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }
  };

  template<typename Vec, template<class T> class Algo, typename ARG0>
  struct eval_visitor_1 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_1 (unsigned wanted, ARG0 arg0) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1>
  struct eval_visitor_2 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_2 (unsigned wanted, ARG0 arg0, ARG1 arg1) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1) {}

    template<typename U>
      void operator() (U *)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2>
  struct eval_visitor_3 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_3 (unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1)
      , arg2_ (arg2) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ , arg2_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
      ARG2 arg2_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3>
  struct eval_visitor_4 : public eval_visitor < Vec, Algo >
  {
    eval_visitor_4 (unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1)
      , arg2_ (arg2)
      , arg3_ (arg3) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ , arg2_, arg3_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
      ARG2 arg2_;
      ARG3 arg3_;
  };

  template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3, typename ARG4>
  struct eval_visitor_5 : public eval_visitor < Vec, Algo >

  {
    eval_visitor_5 (unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4) :
        eval_visitor < Vec, Algo > ( wanted )
      , arg0_ (arg0)
      , arg1_ (arg1)
      , arg2_ (arg2)
      , arg3_ (arg3)
      , arg4_ (arg4) {}

    template<typename U>
      void operator() (U*)
      {
        typedef typename mpl::find < Vec,U>::type iter;
        unsigned pos = iter::pos::value;

        if (pos == eval_visitor<Vec,Algo>::wanted_)
        {
          Algo< U > algo ( arg0_ , arg1_ , arg2_, arg3_, arg4_ );
          *eval_visitor<Vec,Algo>::result_ = algo ();
        }
      }

    private:
      ARG0 arg0_;
      ARG1 arg1_;
      ARG2 arg2_;
      ARG3 arg3_;
      ARG4 arg4_;
  };

  /**
   * \brief Run algorithm API
   *
   * compile an algorithm for multiple contexts. Select at run-time
   * which algorithm will be used.
   *
   * The call to run_algorithm is parametrized with an boost MPL sequence
   * of Context-types and an algorithm template that will be
   * instanciated for all Contexts. At run-time specific instance of the
   * Algorithm can be executed by passing its index in the sequence.
   * Furthermore parameters can be passed to the contexts operator().
   *
   * \code
   * typedef boost::mpl::vector <
   *     DirectSolver_Context < Boolector >
   *   , DirectSolver_Context < BitBlast < SAT_Aiger < MiniSAT > > >
   *   , DirectSolver_Context < BitBlast < SAT_Aiger < PicoSAT > > >
   *   , DirectSolver_Context < BitBlast < CUDD_Context > >

   *   , GraphSolver_Context < Boolector >
   *   , GraphSolver_Context < BitBlast < SAT_Aiger < MiniSAT > > >
   *   , GraphSolver_Context < BitBlast < SAT_Aiger < PicoSAT > > >
   *   , GraphSolver_Context < BitBlast < CUDD_Context > >
   *
   *     > SolverVec;
   *  DirectSolver_Context< Boolector > ctx;
   *
   *  template<typename Context>
   *  struct MyAlgorithm {
   *    typedef void result_type;
   *    result_type operator() () {
   *      Context ctx;
   *      ...
   *    }
   *  }
   *
   *  int main(int argc, const char *argv[])
   *  {
   *    unsigned i = atoi(argv[1]);
   *    run_algorithm<SolverVec, MyAlgorithm>(i);
   *    return 0;
   *  }
   * \endcode
   * \ingroup Support
   * \defgroup run_algorithm Run algorithm
   * @{
   */

  template<typename Vec, template<class T> class Algo>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted )
  {
    eval_visitor_0<Vec, Algo> visitor ( wanted );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0 )
  {
    eval_visitor_1<Vec, Algo, ARG0> visitor ( wanted, arg0 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1 )
  {
    eval_visitor_2<Vec, Algo, ARG0, ARG1> visitor ( wanted, arg0, arg1 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2>
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2 )
  {
    eval_visitor_3<Vec, Algo, ARG0, ARG1, ARG2> visitor ( wanted, arg0, arg1, arg2 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3 >
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3 )
  {
    eval_visitor_4<Vec, Algo, ARG0, ARG1, ARG2, ARG3> visitor ( wanted, arg0, arg1, arg2, arg3 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

 template<typename Vec, template<class T> class Algo, typename ARG0, typename ARG1, typename ARG2, typename ARG3, typename ARG4 >
  typename eval_visitor<Vec, Algo>::result_type run_algorithm ( unsigned wanted, ARG0 arg0, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4 )
  {
    eval_visitor_5<Vec, Algo, ARG0, ARG1, ARG2, ARG3, ARG4> visitor ( wanted, arg0, arg1, arg2, arg3, arg4 );
    mpl::for_each<Vec, boost::add_pointer<mpl::_> > (visitor);

    return visitor.get_result ();
  }

  /**@}*/
}

<|endoftext|>