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

#ifndef _SDR_EVENT_EVENTHANDLER_HXX
#define _SDR_EVENT_EVENTHANDLER_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#include <vector>

#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////
// predeclarations

namespace sdr
{
    namespace event
    {
        class BaseEvent;
        class EventHandler;

        // typedefs for a list of BaseEvents
        typedef ::std::vector< BaseEvent* > BaseEventVector;
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace event
    {
        class BaseEvent
        {
            // the EventHandler this event is registered at
            EventHandler&                                   mrEventHandler;

        public:
            // basic constructor.
            BaseEvent(EventHandler& rEventHandler);

            // destructor
            virtual ~BaseEvent();

            // the called method if the event is triggered
            virtual void ExecuteEvent() = 0;
        };
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace event
    {
        class EventHandler
        {
            BaseEventVector                                 maVector;

            // to allow BaseEvents to use the add/remove functionality
            friend class BaseEvent;

            // methods to add/remove events. These are private since
            // they are used from BaseEvent only.
            void AddEvent(BaseEvent& rBaseEvent);
            void RemoveEvent(BaseEvent& rBaseEvent);

            // access to a event, 0L when no more events
            BaseEvent* GetEvent();

        public:
            // basic constructor.
            EventHandler();

            // destructor
            virtual ~EventHandler();

            // Trigger and consume the events
            virtual void ExecuteEvents();

            // for control
            sal_Bool IsEmpty() const;
        };
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace event
    {
        class TimerEventHandler : public EventHandler, public Timer
        {
        public:
            // basic constructor.
            TimerEventHandler(sal_uInt32 nTimeout = 1L);

            // destructor
            virtual ~TimerEventHandler();

            // The timer when it is triggered; from class Timer
            virtual void Timeout();

            // reset the timer
            void Restart();
        };
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_EVENT_EVENTHANDLER_HXX

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

#ifndef _SDR_EVENT_EVENTHANDLER_HXX
#define _SDR_EVENT_EVENTHANDLER_HXX

#include <sal/types.h>

#include <vector>
#include <vcl/timer.hxx>

//////////////////////////////////////////////////////////////////////////////
// predeclarations

namespace sdr
{
    namespace event
    {
        class BaseEvent;
        class EventHandler;

        // typedefs for a list of BaseEvents
        typedef ::std::vector< BaseEvent* > BaseEventVector;
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace event
    {
        class BaseEvent
        {
            // the EventHandler this event is registered at
            EventHandler&                                   mrEventHandler;

        public:
            // basic constructor.
            BaseEvent(EventHandler& rEventHandler);

            // destructor
            virtual ~BaseEvent();

            // the called method if the event is triggered
            virtual void ExecuteEvent() = 0;
        };
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace event
    {
        class EventHandler
        {
            BaseEventVector                                 maVector;

            // to allow BaseEvents to use the add/remove functionality
            friend class BaseEvent;

            // methods to add/remove events. These are private since
            // they are used from BaseEvent only.
            void AddEvent(BaseEvent& rBaseEvent);
            void RemoveEvent(BaseEvent& rBaseEvent);

            // access to a event, 0L when no more events
            BaseEvent* GetEvent();

        public:
            // basic constructor.
            EventHandler();

            // destructor
            virtual ~EventHandler();

            // Trigger and consume the events
            virtual void ExecuteEvents();

            // for control
            sal_Bool IsEmpty() const;
        };
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace event
    {
        class TimerEventHandler : public EventHandler, public Timer
        {
        public:
            // basic constructor.
            TimerEventHandler(sal_uInt32 nTimeout = 1L);

            // destructor
            virtual ~TimerEventHandler();

            // The timer when it is triggered; from class Timer
            virtual void Timeout();

            // reset the timer
            void Restart();
        };
    } // end of namespace event
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_EVENT_EVENTHANDLER_HXX

// eof
<|endoftext|>


<commit_before><commit_msg>[FIXED] save file with group<commit_after><|endoftext|>


<commit_before>/**
 * Copyright 2014 Kevin Townsend
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <stdint.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
namespace townsend {
    namespace algorithm {
        template <typename RandomAccessIterator>
        RandomAccessIterator bwtEncode(RandomAccessIterator first, RandomAccessIterator last);
        template <typename RandomAccessIterator>
        void bwtDecode(RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator key);
    }
}
//implementation
//template <class RandomAccessIterator>

template <class RandomAccessIterator>
RandomAccessIterator townsend::algorithm::bwtEncode(RandomAccessIterator first, RandomAccessIterator last){
    using namespace std;
    class encodeHelper{
        struct Node{
            typename RandomAccessIterator::value_type value;
            Node* parent;
            Node* left;
            Node* right;
            int treeHeight;
        };
        RandomAccessIterator first;
        RandomAccessIterator last;
        uint64_t originalSize;
        vector<Node> tree;
        public:
        RandomAccessIterator key;

        public:
        encodeHelper(RandomAccessIterator first, RandomAccessIterator last){
            this->first = first;
            this->last = last;
            originalSize = last-first;
            tree.resize(originalSize+1);
            for(int64_t i = 0; i < originalSize; i++){
                tree[i].value = first[i];
            }
            Node* root = &tree.back();
            for(int i = originalSize - 1; i >= 0; i--){
                root=treeAdd(root, &tree[i]);
            }
            tmp = first;
            dfs(root);
            checkHeights(root);
        }
        private:
        Node* treeAdd(Node* root, Node* newNode){
            assert(root != NULL);
            assert(newNode != NULL);
            bool isLesser = compare(newNode, root);
            if(isLesser){
                if(root->left == NULL){
                    root->left = newNode;
                    newNode->parent = root;
                    newNode->treeHeight = 1;
                }else
                    treeAdd(root->left, newNode);
            }else{
                if(root->right == NULL){
                    root->right = newNode;
                    newNode->parent = root;
                    newNode->treeHeight = 1;
                }else
                    treeAdd(root->right, newNode);
            }
            setHeight(root);
            //TODO: balance
            return avlBalance(root);
        }

        bool compare(Node* left, Node* right){
            size_t leftIndex = left - &tree[0];
            size_t rightIndex = right - &tree[0];
            if(leftIndex == originalSize)
                return false;
            if(rightIndex == originalSize)
                return true;
            RandomAccessIterator leftIterator = first + leftIndex;
            RandomAccessIterator rightIterator = first + rightIndex;
            if(*leftIterator < *rightIterator)
                return true;
            else if(*leftIterator > *rightIterator)
                return false;
            else{
                assert(*leftIterator == *rightIterator);
                return compareInTree(left + 1, right + 1);
            }
            return true;
        }
        bool compareInTree(Node* left, Node* right){
            vector<bool> leftPath;
            Node* current = left;
            while(current->parent != NULL){
                if(current == current->parent->left)
                    leftPath.push_back(0);
                else{
                    assert(current == current->parent->right);
                    leftPath.push_back(1);
                }
                current = current->parent;
            }
            vector<bool> rightPath;
            current = right;
            while(current->parent != NULL){
                if(current == current->parent->left)
                    rightPath.push_back(0);
                else{
                    assert(current == current->parent->right);
                    rightPath.push_back(1);
                }
                current = current->parent;
            }
            while(rightPath.size() != 0 && leftPath.size() != 0){
                bool leftStep = leftPath.back();
                leftPath.pop_back();
                bool rightStep = rightPath.back();
                rightPath.pop_back();
                if(leftStep < rightStep)
                    return true;
                else if(leftStep > rightStep)
                    return false;
                assert(leftStep == rightStep);
            }
            assert(!(rightPath.size() == 0 && leftPath.size() == 0));
            if(leftPath.size() == 0){
                assert(rightPath.size () != 0);
                return rightPath.back();
            }else{
                return !leftPath.back();
            }
        }
        RandomAccessIterator tmp;
        void dfs(Node* n){
            if(n == NULL)
                return;
            dfs(n->left);
            if(&tree.front() == n){
                key = tmp;
            }else{
                *tmp = (n-1)->value;
                tmp++;
            }

            dfs(n->right);
        }
        void checkHeights(Node* n){
            int leftHeight=0;
            int rightHeight=0;
            if(n->left != NULL){
                checkHeights(n->left);
                leftHeight=n->left->treeHeight;
            }
            if(n->right != NULL){
                checkHeights(n->right);
                rightHeight=n->right->treeHeight;
            }
            assert(n->treeHeight == max(leftHeight,rightHeight) + 1);
        }
        void setHeight(Node* n){
            int leftHeight=0;
            int rightHeight=0;
            if(n->left != NULL){
                leftHeight=n->left->treeHeight;
            }
            if(n->right != NULL){
                rightHeight=n->right->treeHeight;
            }
            n->treeHeight = max(leftHeight,rightHeight) + 1;
        }
        Node* avlBalance(Node* n){
            while(abs(childrenHeightDiff(n)) > 1){
                if(childrenHeightDiff(n) < 1){
                    if(childrenHeightDiff(n->left) > 0)
                        rotLeft(n->left);
                    n=rotRight(n);
                }else{
                    assert(childrenHeightDiff(n) > 1);
                    if(childrenHeightDiff(n->right) > 0)
                        rotLeft(n->right);
                    n=rotLeft(n);
                }
            }
            return n;

        }
        int childrenHeightDiff(Node* n){
            int leftHeight=0;
            int rightHeight=0;
            if(n->left != NULL){
                leftHeight=n->left->treeHeight;
            }
            if(n->right != NULL){
                rightHeight=n->right->treeHeight;
            }
            return rightHeight - leftHeight;
        }
        Node* rotLeft(Node* n){
            Node* p = n->parent;
            assert(n->right != NULL);
            Node* r = n->right;
            Node* f = r->left;
            r->left = n;
            n->parent = r;
            n->right = f;
            if(f != NULL)
                f->parent=n;
            r->parent=p;
            if(p!=NULL){
                if(p->left==n)
                    p->left=r;
                else{
                    assert(p->right==n);
                    p->right=r;}
            }
            setHeight(r->left);
            setHeight(r);
            return r;
        }
        Node* rotRight(Node* n){
            Node* p = n->parent;
            assert(n->left != NULL);
            Node* l = n->left;
            Node* f = l->right;
            l->right = n;
            n->parent = l;
            n->left = f;
            if(f != NULL)
                f->parent=n;
            l->parent=p;
            if(p!=NULL){
                if(p->right==n)
                    p->right=l;
                else{
                    assert(p->left==n);
                    p->left=l;}
            }
            setHeight(l->right);
            setHeight(l);
            return l;
        }
    };
    encodeHelper eh(first, last);
    return eh.key;
}
template<class RandomAccessIterator>
void townsend::algorithm::bwtDecode(RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator key){
    using namespace std;
    vector<typename RandomAccessIterator::value_type> bwtEncoded(first, last);
    typename RandomAccessIterator::value_type empty;
    bwtEncoded.insert(bwtEncoded.begin() + (key-first), empty);
    RandomAccessIterator bwtEncodedKey = bwtEncoded.begin() + (key - first);
    map<typename RandomAccessIterator::value_type,uint64_t> sums;
    map<typename RandomAccessIterator::value_type,uint64_t> cummulativeSum;
    uint64_t keyIndex = key - first;
    uint64_t sum = 0;
    for(auto i = first; i != last; i++){
        sums[*i]++;
    }
    for(auto it = sums.begin();it != sums.end();it++){
        cummulativeSum[it->first] = sum;
        sum += it->second;
    }
    vector<uint64_t> fmIndex;
    for(auto it = bwtEncoded.begin(); it != bwtEncoded.end(); it++){
        if(it == bwtEncodedKey){
            fmIndex.push_back(last-first);
        }else{
            uint64_t index = cummulativeSum[*it];
            fmIndex.push_back(index);
            cummulativeSum[*it]++;
        }
    }
    auto tmp = last - 1;
    for(auto trav = bwtEncoded.end()-1; trav != bwtEncodedKey; trav = bwtEncoded.begin() + fmIndex[trav - bwtEncoded.begin()]){
        *tmp-- = *trav;
    }
    assert(tmp+1 == first);
    return;
}
<commit_msg>fixing gcc4.4 issue<commit_after>/**
 * Copyright 2014 Kevin Townsend
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <stdint.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
namespace townsend {
    namespace algorithm {
        template <typename RandomAccessIterator>
        RandomAccessIterator bwtEncode(RandomAccessIterator first, RandomAccessIterator last);
        template <typename RandomAccessIterator>
        void bwtDecode(RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator key);
    }
}
//implementation
//template <class RandomAccessIterator>

template <class RandomAccessIterator>
RandomAccessIterator townsend::algorithm::bwtEncode(RandomAccessIterator first, RandomAccessIterator last){
    using namespace std;
    class encodeHelper{
        struct Node{
            typename RandomAccessIterator::value_type value;
            Node* parent;
            Node* left;
            Node* right;
            int treeHeight;
        };
        RandomAccessIterator first;
        RandomAccessIterator last;
        uint64_t originalSize;
        Node* tree;
        public:
        RandomAccessIterator key;

        public:
        encodeHelper(RandomAccessIterator first, RandomAccessIterator last){
            this->first = first;
            this->last = last;
            originalSize = last-first;
            tree = new Node[originalSize+1];
            for(int64_t i = 0; i < originalSize; i++){
                tree[i].value = first[i];
            }
            Node* root = tree + originalSize;
            for(int i = originalSize - 1; i >= 0; i--){
                root=treeAdd(root, &tree[i]);
            }
            tmp = first;
            dfs(root);
            checkHeights(root);
        }
        ~encodeHelper(){
            delete [] tree;
        }
        private:
        Node* treeAdd(Node* root, Node* newNode){
            assert(root != NULL);
            assert(newNode != NULL);
            bool isLesser = compare(newNode, root);
            if(isLesser){
                if(root->left == NULL){
                    root->left = newNode;
                    newNode->parent = root;
                    newNode->treeHeight = 1;
                }else
                    treeAdd(root->left, newNode);
            }else{
                if(root->right == NULL){
                    root->right = newNode;
                    newNode->parent = root;
                    newNode->treeHeight = 1;
                }else
                    treeAdd(root->right, newNode);
            }
            setHeight(root);
            //TODO: balance
            return avlBalance(root);
        }

        bool compare(Node* left, Node* right){
            size_t leftIndex = left - &tree[0];
            size_t rightIndex = right - &tree[0];
            if(leftIndex == originalSize)
                return false;
            if(rightIndex == originalSize)
                return true;
            RandomAccessIterator leftIterator = first + leftIndex;
            RandomAccessIterator rightIterator = first + rightIndex;
            if(*leftIterator < *rightIterator)
                return true;
            else if(*leftIterator > *rightIterator)
                return false;
            else{
                assert(*leftIterator == *rightIterator);
                return compareInTree(left + 1, right + 1);
            }
            return true;
        }
        bool compareInTree(Node* left, Node* right){
            vector<bool> leftPath;
            Node* current = left;
            while(current->parent != NULL){
                if(current == current->parent->left)
                    leftPath.push_back(0);
                else{
                    assert(current == current->parent->right);
                    leftPath.push_back(1);
                }
                current = current->parent;
            }
            vector<bool> rightPath;
            current = right;
            while(current->parent != NULL){
                if(current == current->parent->left)
                    rightPath.push_back(0);
                else{
                    assert(current == current->parent->right);
                    rightPath.push_back(1);
                }
                current = current->parent;
            }
            while(rightPath.size() != 0 && leftPath.size() != 0){
                bool leftStep = leftPath.back();
                leftPath.pop_back();
                bool rightStep = rightPath.back();
                rightPath.pop_back();
                if(leftStep < rightStep)
                    return true;
                else if(leftStep > rightStep)
                    return false;
                assert(leftStep == rightStep);
            }
            assert(!(rightPath.size() == 0 && leftPath.size() == 0));
            if(leftPath.size() == 0){
                assert(rightPath.size () != 0);
                return rightPath.back();
            }else{
                return !leftPath.back();
            }
        }
        RandomAccessIterator tmp;
        void dfs(Node* n){
            if(n == NULL)
                return;
            dfs(n->left);
            if(tree == n){
                key = tmp;
            }else{
                *tmp = (n-1)->value;
                tmp++;
            }

            dfs(n->right);
        }
        void checkHeights(Node* n){
            int leftHeight=0;
            int rightHeight=0;
            if(n->left != NULL){
                checkHeights(n->left);
                leftHeight=n->left->treeHeight;
            }
            if(n->right != NULL){
                checkHeights(n->right);
                rightHeight=n->right->treeHeight;
            }
            assert(n->treeHeight == max(leftHeight,rightHeight) + 1);
        }
        void setHeight(Node* n){
            int leftHeight=0;
            int rightHeight=0;
            if(n->left != NULL){
                leftHeight=n->left->treeHeight;
            }
            if(n->right != NULL){
                rightHeight=n->right->treeHeight;
            }
            n->treeHeight = max(leftHeight,rightHeight) + 1;
        }
        Node* avlBalance(Node* n){
            while(abs(childrenHeightDiff(n)) > 1){
                if(childrenHeightDiff(n) < 1){
                    if(childrenHeightDiff(n->left) > 0)
                        rotLeft(n->left);
                    n=rotRight(n);
                }else{
                    assert(childrenHeightDiff(n) > 1);
                    if(childrenHeightDiff(n->right) > 0)
                        rotLeft(n->right);
                    n=rotLeft(n);
                }
            }
            return n;

        }
        int childrenHeightDiff(Node* n){
            int leftHeight=0;
            int rightHeight=0;
            if(n->left != NULL){
                leftHeight=n->left->treeHeight;
            }
            if(n->right != NULL){
                rightHeight=n->right->treeHeight;
            }
            return rightHeight - leftHeight;
        }
        Node* rotLeft(Node* n){
            Node* p = n->parent;
            assert(n->right != NULL);
            Node* r = n->right;
            Node* f = r->left;
            r->left = n;
            n->parent = r;
            n->right = f;
            if(f != NULL)
                f->parent=n;
            r->parent=p;
            if(p!=NULL){
                if(p->left==n)
                    p->left=r;
                else{
                    assert(p->right==n);
                    p->right=r;}
            }
            setHeight(r->left);
            setHeight(r);
            return r;
        }
        Node* rotRight(Node* n){
            Node* p = n->parent;
            assert(n->left != NULL);
            Node* l = n->left;
            Node* f = l->right;
            l->right = n;
            n->parent = l;
            n->left = f;
            if(f != NULL)
                f->parent=n;
            l->parent=p;
            if(p!=NULL){
                if(p->right==n)
                    p->right=l;
                else{
                    assert(p->left==n);
                    p->left=l;}
            }
            setHeight(l->right);
            setHeight(l);
            return l;
        }
    };
    encodeHelper eh(first, last);
    return eh.key;
}
template<class RandomAccessIterator>
void townsend::algorithm::bwtDecode(RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator key){
    using namespace std;
    vector<typename RandomAccessIterator::value_type> bwtEncoded(first, last);
    typename RandomAccessIterator::value_type empty;
    bwtEncoded.insert(bwtEncoded.begin() + (key-first), empty);
    RandomAccessIterator bwtEncodedKey = bwtEncoded.begin() + (key - first);
    map<typename RandomAccessIterator::value_type,uint64_t> sums;
    map<typename RandomAccessIterator::value_type,uint64_t> cummulativeSum;
    uint64_t keyIndex = key - first;
    uint64_t sum = 0;
    for(auto i = first; i != last; i++){
        sums[*i]++;
    }
    for(auto it = sums.begin();it != sums.end();it++){
        cummulativeSum[it->first] = sum;
        sum += it->second;
    }
    vector<uint64_t> fmIndex;
    for(auto it = bwtEncoded.begin(); it != bwtEncoded.end(); it++){
        if(it == bwtEncodedKey){
            fmIndex.push_back(last-first);
        }else{
            uint64_t index = cummulativeSum[*it];
            fmIndex.push_back(index);
            cummulativeSum[*it]++;
        }
    }
    auto tmp = last - 1;
    for(auto trav = bwtEncoded.end()-1; trav != bwtEncodedKey; trav = bwtEncoded.begin() + fmIndex[trav - bwtEncoded.begin()]){
        *tmp-- = *trav;
    }
    assert(tmp+1 == first);
    return;
}
<|endoftext|>


<commit_before>#include "php_cld2.h"
#include "CLD2Detector.h"

zend_class_entry *cld2_ce;
zend_object_handlers cld2_object_handlers;

struct cld2 {
    zend_object std;
    CLD2Detector *detector;
};

void cld2_free_storage(void *object TSRMLS_CC)
{
    cld2 *obj = (cld2 *)object;
    delete obj->detector;

    zend_hash_destroy(obj->std.properties);
    FREE_HASHTABLE(obj->std.properties);

    efree(obj);
}

zend_object_value cld2_create_handler(zend_class_entry *type TSRMLS_DC)
{
    zend_object_value retval;

    cld2 *obj = (cld2 *)emalloc(sizeof(cld2));
    memset(obj, 0, sizeof(cld2));
    obj->std.ce = type;

    ALLOC_HASHTABLE(obj->std.properties);
    zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
    object_properties_init((zend_object*) &(obj->std.properties), type);
    retval.handle = zend_objects_store_put(obj, NULL,
        cld2_free_storage, NULL TSRMLS_CC);
    retval.handlers = &cld2_object_handlers;

    return retval;
}

PHP_METHOD(CLD2, __construct)
{
    CLD2Detector *detector = NULL;
    zval *object = getThis();
    detector = new CLD2Detector();
    cld2 *obj = (cld2 *)zend_object_store_get_object(object TSRMLS_CC);
    obj->detector = detector;
}

PHP_METHOD(CLD2, detect)
{
    CLD2Detector *detector;
    char *text;
    int text_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &text, &text_len) == FAILURE) {
        RETURN_NULL();
    }

    cld2 *obj = (cld2 *)zend_object_store_get_object(getThis() TSRMLS_CC);

    detector = obj->detector;

    if (detector == NULL) {
        RETURN_NULL();
    }

    // Prepare array
    const char* buffer = strdup(text);
    DetectedLanguage lang = detector->detect(buffer);
    char* language_code = strdup(lang.languageCode);
    char* language_name = strdup(lang.languageName);
    array_init(return_value);
    add_assoc_string(return_value, "language_code", language_code, 1);
    add_assoc_string(return_value, "language_name", language_name, 1);
    add_assoc_long(return_value, "language_probability", lang.languageProbability);
    add_assoc_bool(return_value, "is_reliable", lang.isReliable);
}

PHP_METHOD(CLD2, isPlainText)
{
    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(getThis() TSRMLS_CC);
    detector = obj->detector;
    if (detector == NULL) {
        RETURN_NULL();
    }
    RETURN_BOOL(detector->isPlainText());
};

PHP_METHOD(CLD2, setPlainText)
{
    bool isPlainText;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &isPlainText) == FAILURE) {
        RETURN_NULL();
    }

    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(
            getThis() TSRMLS_CC);
    detector = obj->detector;

    if (detector == NULL) {
        RETURN_NULL();
    }

    detector->setPlainText(isPlainText);
};

PHP_METHOD(CLD2, getTldHint)
{
    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(getThis() TSRMLS_CC);
    detector = obj->detector;
    if (detector == NULL) {
        RETURN_NULL();
    }
    RETURN_STRING(detector->getTldHint(), 1);
};

PHP_METHOD(CLD2, setTldHint)
{
    char *hint;
    int hint_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hint, &hint_len) == FAILURE) {
        RETURN_NULL();
    }

    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(
            getThis() TSRMLS_CC);
    detector = obj->detector;

    if (detector == NULL) {
        RETURN_NULL();
    }

    detector->setTldHint(hint);
};

// TODO: complete this method
PHP_METHOD(CLD2, getEncHint)
{
}

// TODO: complete this method
PHP_METHOD(CLD2, setEncHint)
{
}

// TODO: complete this method
PHP_METHOD(CLD2, getLangHint)
{
}

// TODO: complete this method
PHP_METHOD(CLD2, setLangHint)
{
}

zend_function_entry cld2_methods[] = {
    PHP_ME(CLD2, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
    PHP_ME(CLD2, detect, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, isPlainText, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, setPlainText, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, getTldHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, setTldHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, getEncHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, setEncHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, getLangHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(CLD2, setLangHint, NULL, ZEND_ACC_PUBLIC)
    {NULL, NULL, NULL}
};

PHP_MINIT_FUNCTION(cld2)
{
    zend_class_entry ce;
    INIT_NS_CLASS_ENTRY(ce, "CLD2", "Detector", cld2_methods);
    cld2_ce = zend_register_internal_class(&ce TSRMLS_CC);
    cld2_ce->create_object = cld2_create_handler;
    memcpy(&cld2_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
    cld2_object_handlers.clone_obj = NULL;
    return SUCCESS;
}

zend_module_entry cld2_module_entry = {
    STANDARD_MODULE_HEADER,
    PHP_CLD2_EXTNAME,
    NULL,                  /* Functions */
    PHP_MINIT(cld2),
    NULL,                  /* MSHUTDOWN */
    NULL,                  /* RINIT */
    NULL,                  /* RSHUTDOWN */
    NULL,                  /* MINFO */
    PHP_CLD2_EXTVER,
    STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_CLD2
extern "C" {
ZEND_GET_MODULE(cld2)
}
#endif
<commit_msg>Naming<commit_after>#include "php_cld2.h"
#include "CLD2Detector.h"

zend_class_entry *cld2_detector_ce;
zend_object_handlers cld2_object_handlers;

struct cld2 {
    zend_object std;
    CLD2Detector *detector;
};

void cld2_free_storage(void *object TSRMLS_CC)
{
    cld2 *obj = (cld2 *)object;
    delete obj->detector;

    zend_hash_destroy(obj->std.properties);
    FREE_HASHTABLE(obj->std.properties);

    efree(obj);
}

zend_object_value cld2_create_handler(zend_class_entry *type TSRMLS_DC)
{
    zend_object_value retval;

    cld2 *obj = (cld2 *)emalloc(sizeof(cld2));
    memset(obj, 0, sizeof(cld2));
    obj->std.ce = type;

    ALLOC_HASHTABLE(obj->std.properties);
    zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
    object_properties_init((zend_object*) &(obj->std.properties), type);
    retval.handle = zend_objects_store_put(obj, NULL,
        cld2_free_storage, NULL TSRMLS_CC);
    retval.handlers = &cld2_object_handlers;

    return retval;
}

PHP_METHOD(cld2_detector, __construct)
{
    CLD2Detector *detector = NULL;
    zval *object = getThis();
    detector = new CLD2Detector();
    cld2 *obj = (cld2 *)zend_object_store_get_object(object TSRMLS_CC);
    obj->detector = detector;
}

PHP_METHOD(cld2_detector, detect)
{
    CLD2Detector *detector;
    char *text;
    int text_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &text, &text_len) == FAILURE) {
        RETURN_NULL();
    }

    cld2 *obj = (cld2 *)zend_object_store_get_object(getThis() TSRMLS_CC);

    detector = obj->detector;

    if (detector == NULL) {
        RETURN_NULL();
    }

    // Prepare array
    const char* buffer = strdup(text);
    DetectedLanguage lang = detector->detect(buffer);
    char* language_code = strdup(lang.languageCode);
    char* language_name = strdup(lang.languageName);
    array_init(return_value);
    add_assoc_string(return_value, "language_code", language_code, 1);
    add_assoc_string(return_value, "language_name", language_name, 1);
    add_assoc_long(return_value, "language_probability", lang.languageProbability);
    add_assoc_bool(return_value, "is_reliable", lang.isReliable);
}

PHP_METHOD(cld2_detector, isPlainText)
{
    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(getThis() TSRMLS_CC);
    detector = obj->detector;
    if (detector == NULL) {
        RETURN_NULL();
    }
    RETURN_BOOL(detector->isPlainText());
};

PHP_METHOD(cld2_detector, setPlainText)
{
    bool isPlainText;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &isPlainText) == FAILURE) {
        RETURN_NULL();
    }

    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(
            getThis() TSRMLS_CC);
    detector = obj->detector;

    if (detector == NULL) {
        RETURN_NULL();
    }

    detector->setPlainText(isPlainText);
};

PHP_METHOD(cld2_detector, getTldHint)
{
    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(getThis() TSRMLS_CC);
    detector = obj->detector;
    if (detector == NULL) {
        RETURN_NULL();
    }
    RETURN_STRING(detector->getTldHint(), 1);
};

PHP_METHOD(cld2_detector, setTldHint)
{
    char *hint;
    int hint_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hint, &hint_len) == FAILURE) {
        RETURN_NULL();
    }

    CLD2Detector *detector;
    cld2 *obj = (cld2 *)zend_object_store_get_object(
            getThis() TSRMLS_CC);
    detector = obj->detector;

    if (detector == NULL) {
        RETURN_NULL();
    }

    detector->setTldHint(hint);
};

// TODO: complete this method
PHP_METHOD(cld2_detector, getEncHint)
{
}

// TODO: complete this method
PHP_METHOD(cld2_detector, setEncHint)
{
}

// TODO: complete this method
PHP_METHOD(cld2_detector, getLangHint)
{
}

// TODO: complete this method
PHP_METHOD(cld2_detector, setLangHint)
{
}

zend_function_entry cld2_methods[] = {
    PHP_ME(cld2_detector, __construct, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
    PHP_ME(cld2_detector, detect, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, isPlainText, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, setPlainText, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, getTldHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, setTldHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, getEncHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, setEncHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, getLangHint, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(cld2_detector, setLangHint, NULL, ZEND_ACC_PUBLIC)
    {NULL, NULL, NULL}
};

PHP_MINIT_FUNCTION(cld2)
{
    zend_class_entry ce;
    INIT_NS_CLASS_ENTRY(ce, "CLD2", "Detector", cld2_methods);
    cld2_detector_ce = zend_register_internal_class(&ce TSRMLS_CC);
    cld2_detector_ce->create_object = cld2_create_handler;
    memcpy(&cld2_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
    cld2_object_handlers.clone_obj = NULL;
    return SUCCESS;
}

zend_module_entry cld2_module_entry = {
    STANDARD_MODULE_HEADER,
    PHP_CLD2_EXTNAME,
    NULL,                  /* Functions */
    PHP_MINIT(cld2),
    NULL,                  /* MSHUTDOWN */
    NULL,                  /* RINIT */
    NULL,                  /* RSHUTDOWN */
    NULL,                  /* MINFO */
    PHP_CLD2_EXTVER,
    STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_CLD2
extern "C" {
ZEND_GET_MODULE(cld2)
}
#endif
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#ifndef _StageImpl_hh
#define _StageImpl_hh

#include <Warsaw/config.hh>
#include <Warsaw/Stage.hh>
#include <Warsaw/Traversal.hh>
#include <Berlin/ImplVar.hh>
#include <Berlin/GraphicImpl.hh>
#include <Berlin/RegionImpl.hh>
#include <Berlin/Geometry.hh>
#include <Prague/Sys/Thread.hh>
#include <list>

class StageHandleImpl;

class StageImpl : public virtual POA_Layout::Stage,
		  public GraphicImpl
{
  class Sequence;
  class QuadTree;
 public:
  StageImpl();
  ~StageImpl();

  virtual void request(Warsaw::Graphic::Requisition &);

  virtual void traverse(Warsaw::Traversal_ptr);

  virtual void allocate(Warsaw::Tag, const Warsaw::Allocation::Info &);
  virtual void need_redraw();
  virtual void need_redraw_region(Warsaw::Region_ptr);
  virtual void need_resize();
  //. relayout the children. If the bounding box changes call needResize on the parent

  virtual Warsaw::Region_ptr bbox();
  virtual CORBA::Long layers();
  virtual Layout::StageHandle_ptr layer(Layout::Stage::Index);
  // begin() and end() 'lock' the stage
  // in that only after the last end() conditions
  // for needRedraw() & needResize() are done
  virtual void begin();
  virtual void end();
  virtual Layout::StageHandle_ptr insert(Warsaw::Graphic_ptr, const Warsaw::Vertex &, const Warsaw::Vertex &, Layout::Stage::Index);
  virtual void remove(Layout::StageHandle_ptr);

  void move(StageHandleImpl *, const Warsaw::Vertex &);
  void resize(StageHandleImpl *, const Warsaw::Vertex &);
  void relayer(StageHandleImpl *, Layout::Stage::Index);
private:
  //. Returns a tag that is not yet used by any child of the Stage.
  Warsaw::Tag unique_tag();
  //. Returns a handle to the child of the Stage that has the given tag.
  //. It returns 0 is no child has the given tag.
  StageHandleImpl *tag_to_handle(Warsaw::Tag);
  //. Marks the region occupied by the given StageHandle as damaged.
  //. This is done by either merging that region with the one allready
  //. damaged or by creating a setting the damaged region to the region
  //. of the given StageHandle.
  void damage(StageHandleImpl *);

  Sequence            *_children;
  QuadTree            *_tree;
  long                 _nesting;
  Impl_var<RegionImpl> _damage;
  Impl_var<RegionImpl> _bbregion;
  bool                 _need_redraw : 1;
  bool                 _need_resize : 1;
  Prague::Mutex        _mutex;
};

class StageHandleImpl : public virtual POA_Layout::StageHandle
{
 public:
  StageHandleImpl(StageImpl *, Warsaw::Graphic_ptr, Warsaw::Tag, const Warsaw::Vertex &, const Warsaw::Vertex &, Layout::Stage::Index);
  virtual Layout::Stage_ptr parent();
  virtual Warsaw::Graphic_ptr child();
  virtual void remove();
  virtual Warsaw::Vertex position();
  virtual void position(const Warsaw::Vertex &);
  virtual Warsaw::Vertex size();
  virtual void size(const Warsaw::Vertex &);
  virtual Layout::Stage::Index layer();
  virtual void layer(Layout::Stage::Index);

  const Geometry::Rectangle<Warsaw::Coord> &bbox();
  void bbox(RegionImpl &);
 private:
  //. Calculates the BoundingBox of the graphic in this StageHandle and
  //. stores the result in _bbox.
  void cache_bbox();
  //. The stage this StageHandle belongs into.
  StageImpl                         *_parent;
  //. The graphic forming this StageHandle.
  Warsaw::Graphic_var                _child;
  //. This tag is unique for the parent-Stage and identifies this StageHandle.
  Warsaw::Tag                        _tag;
  //. The position of the graphic forming this StageHandle.
  Warsaw::Vertex                     _position;
  //. The size of the graphic forming this StageHandle
  Warsaw::Vertex                     _size;
  //. The layer this StageHandle has.
  Layout::Stage::Index               _layer;
  //. The boundingbox of the graphic of this StageHandle as calculated
  //. by cache_bbox().
  Geometry::Rectangle<Warsaw::Coord> _bbox;
  //. The alignment along the x-axis.
  Warsaw::Alignment                  _xalign;
  //. The alignment along the y-axis.
  Warsaw::Alignment                  _yalign;
  //. A mutex for thread safety.
  Prague::Mutex                      _mutex;
};

#endif
<commit_msg>updates to the inlined docs<commit_after>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#ifndef _StageImpl_hh
#define _StageImpl_hh

#include <Warsaw/config.hh>
#include <Warsaw/Stage.hh>
#include <Warsaw/Traversal.hh>
#include <Berlin/ImplVar.hh>
#include <Berlin/GraphicImpl.hh>
#include <Berlin/RegionImpl.hh>
#include <Berlin/Geometry.hh>
#include <Prague/Sys/Thread.hh>
#include <list>

class StageHandleImpl;

class StageImpl : public virtual POA_Layout::Stage,
		  public GraphicImpl
{
  class Sequence;
  class QuadTree;
 public:
  StageImpl();
  ~StageImpl();

  virtual void request(Warsaw::Graphic::Requisition &);

  virtual void traverse(Warsaw::Traversal_ptr);

  virtual void allocate(Warsaw::Tag, const Warsaw::Allocation::Info &);
  virtual void need_redraw();
  virtual void need_redraw_region(Warsaw::Region_ptr);
  //. relayout the children. If the bounding box changes call need_resize on the parent
  virtual void need_resize();

  virtual Warsaw::Region_ptr bbox();
  virtual CORBA::Long layers();
  virtual Layout::StageHandle_ptr layer(Layout::Stage::Index);
  virtual void begin();
  virtual void end();
  virtual Layout::StageHandle_ptr insert(Warsaw::Graphic_ptr, const Warsaw::Vertex &, const Warsaw::Vertex &, Layout::Stage::Index);
  virtual void remove(Layout::StageHandle_ptr);

  void move(StageHandleImpl *, const Warsaw::Vertex &);
  void resize(StageHandleImpl *, const Warsaw::Vertex &);
  void relayer(StageHandleImpl *, Layout::Stage::Index);
private:
  //. Return a new unique tag in the scope of this parent
  Warsaw::Tag unique_tag();
  //. Return a handle to the child of the Stage that has the given tag.
  //. It returns 0 if no child has the given tag.
  StageHandleImpl *tag_to_handle(Warsaw::Tag);
  //. Mark the region occupied by the given StageHandle as damaged.
  //. This is done by either merging that region with the one allready
  //. damaged or by creating a new onw
  void damage(StageHandleImpl *);

  Sequence            *_children;
  QuadTree            *_tree;
  long                 _nesting;
  Impl_var<RegionImpl> _damage;
  Impl_var<RegionImpl> _bbregion;
  bool                 _need_redraw : 1;
  bool                 _need_resize : 1;
  Prague::Mutex        _mutex;
};

class StageHandleImpl : public virtual POA_Layout::StageHandle
{
 public:
  StageHandleImpl(StageImpl *, Warsaw::Graphic_ptr, Warsaw::Tag, const Warsaw::Vertex &, const Warsaw::Vertex &, Layout::Stage::Index);
  virtual Layout::Stage_ptr parent();
  virtual Warsaw::Graphic_ptr child();
  virtual void remove();
  virtual Warsaw::Vertex position();
  virtual void position(const Warsaw::Vertex &);
  virtual Warsaw::Vertex size();
  virtual void size(const Warsaw::Vertex &);
  virtual Layout::Stage::Index layer();
  virtual void layer(Layout::Stage::Index);

  const Geometry::Rectangle<Warsaw::Coord> &bbox();
  void bbox(RegionImpl &);
 private:
  //. Calculate the bounding box of the graphic in this StageHandle and
  //. stores the result in _bbox.
  void cache_bbox();
  //. The stage this StageHandle belongs into.
  StageImpl                         *_parent;
  //. The graphic forming this StageHandle.
  Warsaw::Graphic_var                _child;
  //. This tag is unique for the parent-Stage and identifies this StageHandle.
  Warsaw::Tag                        _tag;
  //. The position of the graphic forming this StageHandle.
  Warsaw::Vertex                     _position;
  //. The size of the graphic forming this StageHandle
  Warsaw::Vertex                     _size;
  //. The layer this StageHandle has.
  Layout::Stage::Index               _layer;
  //. The bounding box of the graphic of this StageHandle as calculated
  //. by cache_bbox().
  Geometry::Rectangle<Warsaw::Coord> _bbox;
  //. The alignment along the x-axis.
  Warsaw::Alignment                  _xalign;
  //. The alignment along the y-axis.
  Warsaw::Alignment                  _yalign;
  //. A mutex for thread safety.
  Prague::Mutex                      _mutex;
};

#endif
<|endoftext|>


<commit_before>// Time:  ctor: O(b)
//        pick: O(1)
// Space: O(b)

class Solution {
public:
    Solution(int N, vector<int> blacklist) :
        n_(N - blacklist.size()) {
        unordered_set<int> whitelist;
        for (int i = n_; i < N; ++i) {
            whitelist.emplace(i);
        }
        for (const auto& black : blacklist) {
            whitelist.erase(black);
        }
        auto white = whitelist.cbegin();
        for (const auto& black : blacklist) {
            if (black < n_) {
                lookup_[black] = *(white++);
            }
        }
    }

    int pick() {
        int index = rand() % n_;
        return lookup_.count(index) ? lookup_[index] : index;
    }

private:
    int n_;
    unordered_map<int, int> lookup_;
};

// Time:  ctor: O(nlogn)
//        pick: O(logn)
// Space: O(n)
class Solution2 {
public:
    Solution(int N, vector<int> blacklist) :
        n_(N - blacklist.size()),
        blacklist_(blacklist) {

        sort(blacklist_.begin(), blacklist_.end());
    }

    int pick() {
        int index = rand() % n_;
        int left = 0, right = blacklist_.size() - 1;
        while (left <= right) {
            auto mid = left + (right - left) / 2;
            if (index + mid < blacklist_[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return index + left;
    }

private:
    int n_;
    vector<int> blacklist_;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(N, blacklist);
 * int param_1 = obj.pick();
 */
<commit_msg>Update random-pick-with-blacklist.cpp<commit_after>// Time:  ctor: O(b)
//        pick: O(1)
// Space: O(b)

class Solution {
public:
    Solution(int N, vector<int> blacklist) :
        n_(N - blacklist.size()) {
        unordered_set<int> whitelist;
        for (int i = n_; i < N; ++i) {
            whitelist.emplace(i);
        }
        for (const auto& black : blacklist) {
            whitelist.erase(black);
        }
        auto white = whitelist.cbegin();
        for (const auto& black : blacklist) {
            if (black < n_) {
                lookup_[black] = *(white++);
            }
        }
    }

    int pick() {
        int index = rand() % n_;
        return lookup_.count(index) ? lookup_[index] : index;
    }

private:
    int n_;
    unordered_map<int, int> lookup_;
};

// Time:  ctor: O(blogb)
//        pick: O(logb)
// Space: O(b)
class Solution2 {
public:
    Solution(int N, vector<int> blacklist) :
        n_(N - blacklist.size()),
        blacklist_(blacklist) {

        sort(blacklist_.begin(), blacklist_.end());
    }

    int pick() {
        int index = rand() % n_;
        int left = 0, right = blacklist_.size() - 1;
        while (left <= right) {
            auto mid = left + (right - left) / 2;
            if (index + mid < blacklist_[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return index + left;
    }

private:
    int n_;
    vector<int> blacklist_;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(N, blacklist);
 * int param_1 = obj.pick();
 */
<|endoftext|>


<commit_before>// Time:  O(n * C(n, c)), try out all possible substrings with the minimum c deletion.
// Space: O(n * c), the depth is at most c, and it costs n at each depth

// DFS solution.
class Solution {
public:
    vector<string> removeInvalidParentheses(string s)  {
        // Calculate the minimum left and right parantheses to remove
        int left_removed = 0, right_removed = 0;
        for (const auto& c : s) {
            if (c == '(') {
                ++left_removed;
            } else if (c == ')') {
                if (!left_removed) {
                    ++right_removed;
                } else {
                    --left_removed;
                }
            }
        }
        vector<string> res;
        removeInvalidParentheses(s, 0, left_removed, right_removed, &res);
        return res;
    }

    void removeInvalidParentheses(const string& s, int start,
                                  int left_removed, int right_removed, vector<string> *res) {

        if (left_removed == 0 && right_removed == 0) {
            if (isValid(s)) {
                res->emplace_back(s);
            }
            return;
        }

        for (int i = start; i < s.length(); ++i) {
            if (right_removed == 0 && left_removed > 0 && s[i] == '(') {
                if (i == start || s[i] != s[i - 1]) {  // Skip duplicated.
                    string tmp = s;
                    tmp.erase(i, 1);
                    removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res);
                }
            } else if (right_removed > 0 && s[i] == ')') {
                if (i == start || s[i] != s[i - 1]) {  // Skip duplicated.
                    string tmp = s;
                    tmp.erase(i, 1);
                    removeInvalidParentheses(tmp, i, left_removed, right_removed - 1, res);
                }
            }

        }
    }

private:
    // Check whether s is valid or not.
    bool isValid(string s) {
        int sum = 0;
        for (const auto &c : s) {
            if (c == '(') {
                ++sum;
            } else if (c == ')') {
                --sum;
            }
            if (sum < 0) {
                return false;
            }
        }
        return sum == 0;
    }
};
<commit_msg>Update remove-invalid-parentheses.cpp<commit_after>// Time:  O(C(n, c)), try out all possible substrings with the minimum c deletion.
// Space: O(c), the depth is at most c, and it costs n at each depth

// DFS solution.
class Solution {
public:
    vector<string> removeInvalidParentheses(string s)  {
        // Calculate the minimum left and right parantheses to remove
        int left_removed = 0, right_removed = 0;
        for (const auto& c : s) {
            if (c == '(') {
                ++left_removed;
            } else if (c == ')') {
                if (!left_removed) {
                    ++right_removed;
                } else {
                    --left_removed;
                }
            }
        }
        vector<string> res;
        vector<int> removed;
        removeInvalidParentheses(s, 0, left_removed, right_removed, &removed, &res);
        return res;
    }

    void removeInvalidParentheses(const string& s, int start,
                                  int left_removed, int right_removed,
                                  vector<int> *removed, vector<string> *res) {

        if (left_removed == 0 && right_removed == 0) {
            string tmp;
            for (int i = 0, j = 0; i < s.length(); ++i) {
                if (j < removed->size() && i == (*removed)[j]) {
                    ++j;
                } else {
                    tmp.push_back(s[i]);
                }
            }
            if (isValid(tmp)) {
                res->emplace_back(tmp);
            }
            return;
        }

        for (int i = start; i < s.length(); ++i) {
            if (right_removed == 0 && left_removed > 0 && s[i] == '(') {
                if (i == start || s[i] != s[i - 1]) {  // Skip duplicated.
                    removed->emplace_back(i);
                    removeInvalidParentheses(s, i + 1, left_removed - 1, right_removed,
                                             removed, res);
                    removed->pop_back();
                }
            } else if (right_removed > 0 && s[i] == ')') {
                if (i == start || s[i] != s[i - 1]) {  // Skip duplicated.
                    removed->emplace_back(i);
                    removeInvalidParentheses(s, i + 1, left_removed, right_removed - 1,
                                             removed, res);
                    removed->pop_back();
                }
            }

        }
    }

private:
    // Check whether s is valid or not.
    bool isValid(string s) {
        int sum = 0;
        for (const auto &c : s) {
            if (c == '(') {
                ++sum;
            } else if (c == ')') {
                --sum;
            }
            if (sum < 0) {
                return false;
            }
        }
        return sum == 0;
    }
};

// Time:  O(n * C(n, c)), try out all possible substrings with the minimum c deletion.
// Space: O(n * c), the depth is at most c, and it costs n at each depth
// DFS solution.
class Solution2 {
public:
    vector<string> removeInvalidParentheses(string s)  {
        // Calculate the minimum left and right parantheses to remove
        int left_removed = 0, right_removed = 0;
        for (const auto& c : s) {
            if (c == '(') {
                ++left_removed;
            } else if (c == ')') {
                if (!left_removed) {
                    ++right_removed;
                } else {
                    --left_removed;
                }
            }
        }
        vector<string> res;
        removeInvalidParentheses(s, 0, left_removed, right_removed, &res);
        return res;
    }

    void removeInvalidParentheses(const string& s, int start,
                                  int left_removed, int right_removed, vector<string> *res) {

        if (left_removed == 0 && right_removed == 0) {
            if (isValid(s)) {
                res->emplace_back(s);
            }
            return;
        }

        for (int i = start; i < s.length(); ++i) {
            if (right_removed == 0 && left_removed > 0 && s[i] == '(') {
                if (i == start || s[i] != s[i - 1]) {  // Skip duplicated.
                    string tmp = s;
                    tmp.erase(i, 1);
                    removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res);
                }
            } else if (right_removed > 0 && s[i] == ')') {
                if (i == start || s[i] != s[i - 1]) {  // Skip duplicated.
                    string tmp = s;
                    tmp.erase(i, 1);
                    removeInvalidParentheses(tmp, i, left_removed, right_removed - 1, res);
                }
            }

        }
    }

private:
    // Check whether s is valid or not.
    bool isValid(string s) {
        int sum = 0;
        for (const auto &c : s) {
            if (c == '(') {
                ++sum;
            } else if (c == ')') {
                --sum;
            }
            if (sum < 0) {
                return false;
            }
        }
        return sum == 0;
    }
};
<|endoftext|>


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

  Library: CppMicroServices

  Copyright (c) The CppMicroServices developers. See the COPYRIGHT
  file at the top-level directory of this distribution and at
  https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include <iostream>

namespace {

// This is dummy code to silence some linkers warning about
// empty object files.
struct CMakeResourceDependencies
{
  CMakeResourceDependencies() { std::cout << std::flush; }
};
}
<commit_msg>Fix Makefile builds on macOS (#352)<commit_after>/*=============================================================================

  Library: CppMicroServices

  Copyright (c) The CppMicroServices developers. See the COPYRIGHT
  file at the top-level directory of this distribution and at
  https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

namespace {

// This is dummy code to silence some linkers warning about
// empty object files.
struct CMakeResourceDependencies
{
  CMakeResourceDependencies() { }
};
}
<|endoftext|>


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

  Program:   Monteverdi2
  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 "mvdMainWindow.h"
#include "ui_mvdMainWindow.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAboutDialog.h"
#include "mvdApplication.h"
#include "mvdColorDynamicsController.h"
#include "mvdColorDynamicsWidget.h"
#include "mvdColorSetupController.h"
#include "mvdDatasetModel.h"
#include "mvdGLImageWidget.h"
#include "mvdImageModelRenderer.h"
#include "mvdImageViewManipulator.h"
#include "mvdQuicklookModel.h"
#include "mvdQuicklookViewManipulator.h"
#include "mvdVectorImageModel.h"

namespace mvd
{
/*
  TRANSLATOR mvd::MainWindow

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
MainWindow
::MainWindow( QWidget* parent, Qt::WindowFlags flags ) :
  QMainWindow( parent, flags ),
  m_UI( new mvd::Ui::MainWindow() )
{
  m_UI->setupUi( this );

  Initialize();
}

/*****************************************************************************/
MainWindow
::~MainWindow()
{
}

/*****************************************************************************/
void
MainWindow
::Initialize()
{
  setObjectName( "mvd::MainWindow" );
  setWindowTitle( PROJECT_NAME );

  // instanciate the manipulator and the renderer relative to this widget
  ImageViewManipulator* imageViewManipulator = new ImageViewManipulator();
  ImageModelRenderer* imageModelRenderer = new ImageModelRenderer();

  // set the GLImageWidget as the centralWidget in MainWindow.
  setCentralWidget(
    new GLImageWidget(
      imageViewManipulator,
      imageModelRenderer,
      this
    )
  );

  // grab the keyboard notifications in this widget
  centralWidget()->grabKeyboard();

  // add the needed docks
  InitializeDockWidgets();

  // Connect Quit action of main menu to QApplication's quit() slot.
  QObject::connect(
    m_UI->action_Quit, SIGNAL( activated() ),
    qApp, SLOT( quit() )
  );

  /*
  // Connect the setLargestPossibleregion
  QObject::connect(
    centralWidget(), SIGNAL( ModelImageRegionChanged(const ImageRegionType&) ),
    imageViewManipulator, SLOT( OnModelImageRegionChanged(const ImageRegionType&)) );
  */

  // Connect Appllication and MainWindow when selected model is about
  // to change.
  QObject::connect(
    qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ),
    this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) )
  );

  // Connect Appllication and MainWindow when selected model has been
  // changed.
  QObject::connect(
    qApp, SIGNAL( SelectedModelChanged( AbstractModel* ) ),
    this, SLOT( OnSelectedModelChanged( AbstractModel* ) )
  );

  // Change to NULL model to force emitting GUI signals when GUI is
  // instanciated. So, GUI will be initialized and controller-widgets
  // disabled.
  Application::Instance()->SetModel( NULL );
}

/*****************************************************************************/
void
MainWindow
::InitializeDockWidgets()
{
  // instanciate the manipulator and the renderer relative to this widget
  QuicklookViewManipulator* qlViewManipulator = new QuicklookViewManipulator();
  ImageModelRenderer* qlModelRenderer = new ImageModelRenderer();

  //
  // EXPERIMENTAL QUICKLOOK Widget.
  GLImageWidget* qlWidget = new GLImageWidget(
    qlViewManipulator,
    qlModelRenderer,
    this
  );
  // TODO: Set better minimum size for quicklook GL widget.
  qlWidget->setMinimumSize(100,100);

  AddWidgetToDock(
    qlWidget,
    QUICKLOOK_DOCK,
    tr( "Quicklook" ),
    Qt::LeftDockWidgetArea
    );

  /*
  // Connect the setLargestPossibleregion
  QObject::connect(
    qlWidget, SIGNAL( ModelImageRegionChanged(const ImageRegionType&) ),
    qlViewManipulator, SLOT( OnModelImageRegionChanged(const ImageRegionType&)) );
  */

  //
  // COLOR SETUP.
  ColorSetupWidget* colorSetupWgt = new ColorSetupWidget( this );

  ColorSetupController* colorSetupCtrl = new ColorSetupController(
    // wraps:
    colorSetupWgt,
    // as child of:
    AddWidgetToDock(
      colorSetupWgt,
      VIDEO_COLOR_SETUP_DOCK,
      tr( "Video color setup" ),
      Qt::LeftDockWidgetArea
    )
  );

  //
  // COLOR DYNAMICS.
  ColorDynamicsWidget* colorDynWgt = new ColorDynamicsWidget( this );

  // Controller is childed to dock.
  ColorDynamicsController* colorDynamicsCtrl = new ColorDynamicsController(
    // wraps:
    colorDynWgt,
    // as child of:
    AddWidgetToDock(
      colorDynWgt,
      VIDEO_COLOR_DYNAMICS_DOCK,
      tr( "Video color dynamics" ),
      Qt::LeftDockWidgetArea
    )
  );

  //
  // CHAIN CONTROLLERS.
  // Forward model update signals of color-setup controller...
  QObject::connect(
    colorSetupCtrl,
    SIGNAL( RgbChannelIndexChanged( RgbaChannel, int ) ),
    // to: ...color-dynamics controller model update signal.
    colorDynamicsCtrl,
    SLOT( OnRgbChannelIndexChanged( RgbaChannel, int ) )
  );

  //
  // EXPERIMENTAL TOOLBOX.

#if 0

  QToolBox* toolBox = new QToolBox( this );

  toolBox->setObjectName( "mvd::VideoColorToolBox" );

  toolBox->addItem( new ColorSetupWidget( toolBox ), tr( "Video color setup" ) );
  toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( "Video color dynamics" ) );

  AddWidgetToDock(
    toolBox,
    "videoColorSettingsDock",
    tr( "Video color dynamics" ),
    Qt::LeftDockWidgetArea
  );
#endif
}

/*****************************************************************************/
QDockWidget*
MainWindow
::AddWidgetToDock( QWidget* widget,
		   const QString& dockName,
		   const QString& dockTitle,
		   Qt::DockWidgetArea dockArea )
{
  // New dock.
  QDockWidget* dockWidget = new QDockWidget( dockTitle, this );

  // You can use findChild( dockName ) to get dock-widget.
  dockWidget->setObjectName( dockName );
  dockWidget->setWidget( widget );

  // Features.
  dockWidget->setFloating( false );
  dockWidget->setFeatures(
    QDockWidget::DockWidgetMovable |
    QDockWidget::DockWidgetFloatable
  );

  // Add dock.
  addDockWidget( dockArea, dockWidget );

  return dockWidget;
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/
void
MainWindow
::on_action_Open_activated()
{
  QString filename(
    QFileDialog::getOpenFileName( this, tr( "Open file..." ) )
  );

  if( filename.isNull() )
    {
    return;
    }

  // TODO: Replace with complex model (list of DatasetModel) when
  // implemented.
  DatasetModel* model = new DatasetModel();

  model->setObjectName( "mvd::DatasetModel('" + filename + "'" );

  try
    {
    // Init parameters :
    // - filename
    // - widget size (-> compute the best lod fitting the widget size )
    model->ImportImage(
      filename,
      centralWidget()->width(), centralWidget()->height()
    );
    }
  catch( std::exception& exc )
    {
    delete model;
    model = NULL;

    QMessageBox::warning( this, tr("Exception!"), exc.what() );
    return;
    }

  Application::Instance()->SetModel( model );
}

/*****************************************************************************/
void
MainWindow
::on_action_About_activated()
{
  AboutDialog aboutDialog( this );

  aboutDialog.exec();
}

/*****************************************************************************/
void
MainWindow
::OnAboutToChangeSelectedModel( const AbstractModel* )
{
  //
  // COLOR SETUP.
  SetControllerModel( GetColorSetupDock(), NULL );

  //
  // COLOR DYNAMICS.
  SetControllerModel( GetColorDynamicsDock(), NULL );

  // De-assign models to view after controllers (LIFO disconnect).
  qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel( NULL );
  qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
    NULL
  );

  //
  //
  const Application* app = Application::ConstInstance();
  assert( app!=NULL );

  const DatasetModel* datasetModel =
    qobject_cast< const DatasetModel* >( app->GetModel() );

  // It is Ok there is no previously selected model (e.g. at
  // application startup.
  if( datasetModel==NULL )
    {
    return;
    }

  assert( datasetModel->HasSelectedImageModel() );

  const VectorImageModel* vectorImageModel =
    qobject_cast< const VectorImageModel* >(
      datasetModel->GetSelectedImageModel()
    );

  assert( vectorImageModel!=NULL );

  //
  // MAIN VIEW.

  // Disconnect previously selected model from view.
  QObject::disconnect(
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    centralWidget(),
    SLOT( updateGL() )
  );

  // TODO : where to do this
  QObject::disconnect(
    // vectorImageModel->GetQuicklookModel(),
    // TODO: Remove temporary hack by better design.
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    GetQuicklookDock()->widget(),
    SLOT( updateGL()  )
  );
}

/*****************************************************************************/
void
MainWindow
::OnSelectedModelChanged( AbstractModel* model )
{
  if( model==NULL )
    return;

  DatasetModel* datasetModel = qobject_cast< DatasetModel* >( model );

  assert( datasetModel!=NULL );
  assert( datasetModel->HasSelectedImageModel() );

  VectorImageModel* vectorImageModel =
    qobject_cast< VectorImageModel* >(
      datasetModel->GetSelectedImageModel()
    );

  assert( vectorImageModel!=NULL );

  //
  // COLOR SETUP.
  SetControllerModel( GetColorSetupDock(), vectorImageModel );

  //
  // COLOR DYNAMICS.
  SetControllerModel( GetColorDynamicsDock(), vectorImageModel );

  //
  // MAIN VIEW.

  // Assign newly selected model to view.
  qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel(
    vectorImageModel
  );

  // Connect newly selected model to view (after all other widgets are
  // connected to prevent signals/slots to produce multiple view
  // refreshes).
  QObject::connect(
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    centralWidget(),
    SLOT( updateGL()  )
  );

  //
  // QUICKLOOK VIEW.

  // Assign newly selected model to view.
  qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
    vectorImageModel->GetQuicklookModel()
  );

  // Connect newly selected model to view (after all other widgets are
  // connected to prevent signals/slots to produce multiple view
  // refreshes).
  // TODO : find where to do this
  QObject::connect(
    // vectorImageModel->GetQuicklookModel(),
    // TODO: Remove temporary hack by better design.
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    GetQuicklookDock()->widget(),
    SLOT( updateGL()  )
  );

  /*
  // Connect newly selected model to UI controller.
  QObject::connect(
    GetColorSetupDock()->widget(),
    SIGNAL( CurrentIndexChanged( RgbaChannel, int ) ),
    // to:
    vectorImageModel->GetQuicklookModel(),
    SLOT( OnCurrentIndexChanged( RgbaChannel, int ) )
  );
  */
}

/*****************************************************************************/

} // end namespace 'mvd'
<commit_msg>ENH: Shared OpenGL contexts between quicklook view and image-model view.<commit_after>/*=========================================================================

  Program:   Monteverdi2
  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 "mvdMainWindow.h"
#include "ui_mvdMainWindow.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAboutDialog.h"
#include "mvdApplication.h"
#include "mvdColorDynamicsController.h"
#include "mvdColorDynamicsWidget.h"
#include "mvdColorSetupController.h"
#include "mvdDatasetModel.h"
#include "mvdGLImageWidget.h"
#include "mvdImageModelRenderer.h"
#include "mvdImageViewManipulator.h"
#include "mvdQuicklookModel.h"
#include "mvdQuicklookViewManipulator.h"
#include "mvdVectorImageModel.h"

namespace mvd
{
/*
  TRANSLATOR mvd::MainWindow

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
MainWindow
::MainWindow( QWidget* parent, Qt::WindowFlags flags ) :
  QMainWindow( parent, flags ),
  m_UI( new mvd::Ui::MainWindow() )
{
  m_UI->setupUi( this );

  Initialize();
}

/*****************************************************************************/
MainWindow
::~MainWindow()
{
}

/*****************************************************************************/
void
MainWindow
::Initialize()
{
  setObjectName( "mvd::MainWindow" );
  setWindowTitle( PROJECT_NAME );

  // instanciate the manipulator and the renderer relative to this widget
  ImageViewManipulator* imageViewManipulator = new ImageViewManipulator();
  ImageModelRenderer* imageModelRenderer = new ImageModelRenderer();

  // set the GLImageWidget as the centralWidget in MainWindow.
  setCentralWidget(
    new GLImageWidget(
      imageViewManipulator,
      imageModelRenderer,
      this
    )
  );

  // grab the keyboard notifications in this widget
  centralWidget()->grabKeyboard();

  // add the needed docks
  InitializeDockWidgets();

  // Connect Quit action of main menu to QApplication's quit() slot.
  QObject::connect(
    m_UI->action_Quit, SIGNAL( activated() ),
    qApp, SLOT( quit() )
  );

  /*
  // Connect the setLargestPossibleregion
  QObject::connect(
    centralWidget(), SIGNAL( ModelImageRegionChanged(const ImageRegionType&) ),
    imageViewManipulator, SLOT( OnModelImageRegionChanged(const ImageRegionType&)) );
  */

  // Connect Appllication and MainWindow when selected model is about
  // to change.
  QObject::connect(
    qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ),
    this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) )
  );

  // Connect Appllication and MainWindow when selected model has been
  // changed.
  QObject::connect(
    qApp, SIGNAL( SelectedModelChanged( AbstractModel* ) ),
    this, SLOT( OnSelectedModelChanged( AbstractModel* ) )
  );

  // Change to NULL model to force emitting GUI signals when GUI is
  // instanciated. So, GUI will be initialized and controller-widgets
  // disabled.
  Application::Instance()->SetModel( NULL );
}

/*****************************************************************************/
void
MainWindow
::InitializeDockWidgets()
{
  // instanciate the manipulator and the renderer relative to this widget
  QuicklookViewManipulator* qlViewManipulator = new QuicklookViewManipulator();
  ImageModelRenderer* qlModelRenderer = new ImageModelRenderer();

  //
  // EXPERIMENTAL QUICKLOOK Widget.
  assert( qobject_cast< GLImageWidget* >( centralWidget() )!=NULL );
  GLImageWidget* qlWidget = new GLImageWidget(
    qlViewManipulator,
    qlModelRenderer,
    this,
    qobject_cast< GLImageWidget* >( centralWidget() )
  );
  // TODO: Set better minimum size for quicklook GL widget.
  qlWidget->setMinimumSize(100,100);

  AddWidgetToDock(
    qlWidget,
    QUICKLOOK_DOCK,
    tr( "Quicklook" ),
    Qt::LeftDockWidgetArea
    );

  /*
  // Connect the setLargestPossibleregion
  QObject::connect(
    qlWidget, SIGNAL( ModelImageRegionChanged(const ImageRegionType&) ),
    qlViewManipulator, SLOT( OnModelImageRegionChanged(const ImageRegionType&)) );
  */

  //
  // COLOR SETUP.
  ColorSetupWidget* colorSetupWgt = new ColorSetupWidget( this );

  ColorSetupController* colorSetupCtrl = new ColorSetupController(
    // wraps:
    colorSetupWgt,
    // as child of:
    AddWidgetToDock(
      colorSetupWgt,
      VIDEO_COLOR_SETUP_DOCK,
      tr( "Video color setup" ),
      Qt::LeftDockWidgetArea
    )
  );

  //
  // COLOR DYNAMICS.
  ColorDynamicsWidget* colorDynWgt = new ColorDynamicsWidget( this );

  // Controller is childed to dock.
  ColorDynamicsController* colorDynamicsCtrl = new ColorDynamicsController(
    // wraps:
    colorDynWgt,
    // as child of:
    AddWidgetToDock(
      colorDynWgt,
      VIDEO_COLOR_DYNAMICS_DOCK,
      tr( "Video color dynamics" ),
      Qt::LeftDockWidgetArea
    )
  );

  //
  // CHAIN CONTROLLERS.
  // Forward model update signals of color-setup controller...
  QObject::connect(
    colorSetupCtrl,
    SIGNAL( RgbChannelIndexChanged( RgbaChannel, int ) ),
    // to: ...color-dynamics controller model update signal.
    colorDynamicsCtrl,
    SLOT( OnRgbChannelIndexChanged( RgbaChannel, int ) )
  );

  //
  // EXPERIMENTAL TOOLBOX.

#if 0

  QToolBox* toolBox = new QToolBox( this );

  toolBox->setObjectName( "mvd::VideoColorToolBox" );

  toolBox->addItem( new ColorSetupWidget( toolBox ), tr( "Video color setup" ) );
  toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( "Video color dynamics" ) );

  AddWidgetToDock(
    toolBox,
    "videoColorSettingsDock",
    tr( "Video color dynamics" ),
    Qt::LeftDockWidgetArea
  );
#endif
}

/*****************************************************************************/
QDockWidget*
MainWindow
::AddWidgetToDock( QWidget* widget,
		   const QString& dockName,
		   const QString& dockTitle,
		   Qt::DockWidgetArea dockArea )
{
  // New dock.
  QDockWidget* dockWidget = new QDockWidget( dockTitle, this );

  // You can use findChild( dockName ) to get dock-widget.
  dockWidget->setObjectName( dockName );
  dockWidget->setWidget( widget );

  // Features.
  dockWidget->setFloating( false );
  dockWidget->setFeatures(
    QDockWidget::DockWidgetMovable |
    QDockWidget::DockWidgetFloatable
  );

  // Add dock.
  addDockWidget( dockArea, dockWidget );

  return dockWidget;
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/
void
MainWindow
::on_action_Open_activated()
{
  QString filename(
    QFileDialog::getOpenFileName( this, tr( "Open file..." ) )
  );

  if( filename.isNull() )
    {
    return;
    }

  // TODO: Replace with complex model (list of DatasetModel) when
  // implemented.
  DatasetModel* model = new DatasetModel();

  model->setObjectName( "mvd::DatasetModel('" + filename + "'" );

  try
    {
    // Init parameters :
    // - filename
    // - widget size (-> compute the best lod fitting the widget size )
    model->ImportImage(
      filename,
      centralWidget()->width(), centralWidget()->height()
    );
    }
  catch( std::exception& exc )
    {
    delete model;
    model = NULL;

    QMessageBox::warning( this, tr("Exception!"), exc.what() );
    return;
    }

  Application::Instance()->SetModel( model );
}

/*****************************************************************************/
void
MainWindow
::on_action_About_activated()
{
  AboutDialog aboutDialog( this );

  aboutDialog.exec();
}

/*****************************************************************************/
void
MainWindow
::OnAboutToChangeSelectedModel( const AbstractModel* )
{
  //
  // COLOR SETUP.
  SetControllerModel( GetColorSetupDock(), NULL );

  //
  // COLOR DYNAMICS.
  SetControllerModel( GetColorDynamicsDock(), NULL );

  // De-assign models to view after controllers (LIFO disconnect).
  qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel( NULL );
  qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
    NULL
  );

  //
  //
  const Application* app = Application::ConstInstance();
  assert( app!=NULL );

  const DatasetModel* datasetModel =
    qobject_cast< const DatasetModel* >( app->GetModel() );

  // It is Ok there is no previously selected model (e.g. at
  // application startup.
  if( datasetModel==NULL )
    {
    return;
    }

  assert( datasetModel->HasSelectedImageModel() );

  const VectorImageModel* vectorImageModel =
    qobject_cast< const VectorImageModel* >(
      datasetModel->GetSelectedImageModel()
    );

  assert( vectorImageModel!=NULL );

  //
  // MAIN VIEW.

  // Disconnect previously selected model from view.
  QObject::disconnect(
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    centralWidget(),
    SLOT( updateGL() )
  );

  // TODO : where to do this
  QObject::disconnect(
    // vectorImageModel->GetQuicklookModel(),
    // TODO: Remove temporary hack by better design.
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    GetQuicklookDock()->widget(),
    SLOT( updateGL()  )
  );
}

/*****************************************************************************/
void
MainWindow
::OnSelectedModelChanged( AbstractModel* model )
{
  if( model==NULL )
    return;

  DatasetModel* datasetModel = qobject_cast< DatasetModel* >( model );

  assert( datasetModel!=NULL );
  assert( datasetModel->HasSelectedImageModel() );

  VectorImageModel* vectorImageModel =
    qobject_cast< VectorImageModel* >(
      datasetModel->GetSelectedImageModel()
    );

  assert( vectorImageModel!=NULL );

  //
  // COLOR SETUP.
  SetControllerModel( GetColorSetupDock(), vectorImageModel );

  //
  // COLOR DYNAMICS.
  SetControllerModel( GetColorDynamicsDock(), vectorImageModel );

  //
  // MAIN VIEW.

  // Assign newly selected model to view.
  qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel(
    vectorImageModel
  );

  // Connect newly selected model to view (after all other widgets are
  // connected to prevent signals/slots to produce multiple view
  // refreshes).
  QObject::connect(
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    centralWidget(),
    SLOT( updateGL()  )
  );

  //
  // QUICKLOOK VIEW.

  // Assign newly selected model to view.
  qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
    vectorImageModel->GetQuicklookModel()
  );

  // Connect newly selected model to view (after all other widgets are
  // connected to prevent signals/slots to produce multiple view
  // refreshes).
  // TODO : find where to do this
  QObject::connect(
    // vectorImageModel->GetQuicklookModel(),
    // TODO: Remove temporary hack by better design.
    vectorImageModel,
    SIGNAL( SettingsUpdated() ),
    // to:
    GetQuicklookDock()->widget(),
    SLOT( updateGL()  )
  );

  /*
  // Connect newly selected model to UI controller.
  QObject::connect(
    GetColorSetupDock()->widget(),
    SIGNAL( CurrentIndexChanged( RgbaChannel, int ) ),
    // to:
    vectorImageModel->GetQuicklookModel(),
    SLOT( OnCurrentIndexChanged( RgbaChannel, int ) )
  );
  */
}

/*****************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


<commit_before>/**
 * \file dcs/debug.hpp
 *
 * \brief Provides helper functions and macros for debugging purpose.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DCS_DEBUG_HPP
#define DCS_DEBUG_HPP

#ifndef NDEBUG
//@{ for C99 and C++0x
//# 	include <cstdio>
//# 	define DCS_DEBUG_WHERESTR_  "[file %s, function %s, line %d]: "
//#	define DCS_DEBUG_WHEREARG_  __FILE__, __func__, __LINE__
//#	define DCS_DEBUG_PRINT2_(...)       fprintf(stderr, __VA_ARGS__)
//#	define DCS_DEBUG_PRINT(fmt, ...)  DCS_DEBUG_PRINT2_(DCS_DEBUG_WHERESTR_ fmt, DCS_DEBUG_WHEREARG_, __VA_ARGS__)
//@} for C99 and C++0x

#   include <algorithm>
#	include <cassert>
#	include <iostream>
#	include <iterator>
# 	include <set>
# 	include <sstream>
# 	include <string>
# 	include <typeinfo>
# 	include <vector>

/// Macro for telling whether we are in debug mode.
# 	define DCS_DEBUG /**/
/// Macro for expanding its argument \c x
#	define DCS_DEBUG_EXPAND__(x) x
/// Macro for writing to standard error its argument \c x
#	if !defined(DCS_DEBUG_LEVEL) || (DCS_DEBUG_LEVEL > 0)
#		define DCS_DEBUG_TRACE(x) ::std::cerr << "[Debug (" << __FILE__ << ":" << __func__ << ":" << __LINE__ << ")>> " << DCS_DEBUG_EXPAND__(x) << ::std::endl;
#	else
#		define DCS_DEBUG_TRACE(x) /**/
#	endif // !defined(DCS_DEBUG_LEVEL) ...
#	ifdef DCS_DEBUG_LEVEL
#		define DCS_DEBUG_TRACE_L(l,x) if (DCS_DEBUG_EXPAND__(l) <= DCS_DEBUG_LEVEL) { ::std::cerr << "[Debug (" << __FILE__ << ":" << __func__ << ":" << __LINE__ << ")>> " << DCS_DEBUG_EXPAND__(x) << ::std::endl; }
#	else
#		define DCS_DEBUG_TRACE_L(l,x) DCS_DEBUG_TRACE(x)
#	endif // DCS_DEBUG_LEVEL
/// Macro for getting the underlying debug output stream.
# 	define DCS_DEBUG_STREAM ::std::cerr
/// Macro for setting flags \c x of the underlying debug output stream.
# 	define DCS_DEBUG_STREAM_SETFLAGS(x) ::std::cerr.setf((x))
/// Macro for converting the given argumento into a string.
# 	define DCS_DEBUG_STRINGIFY(x) #x
/// Macro for converting the a type into a string.
# 	define DCS_DEBUG_TYPE2STR(x) typeid(x).name()
/// Macro for executing one or more statements only when debug is enabled.
#	define DCS_DEBUG_DO(x) x
/// Macro for assertion
#	define DCS_DEBUG_ASSERT(x) assert(x)

#else // NDEBUG

# 	include <string>

/// Macro for telling that we are in debug mode.
# 	undef DCS_DEBUG /**/
/// Macro for telling what level of debugging to enable.
# 	undef DCS_DEBUG_LEVEL /**/
/// Macro for writing to standard error its argument \c x
#	define DCS_DEBUG_TRACE(x) /**/
/// Macro for writing to standard error its argument \c x only when the
/// debugging level is greater than or equal to \c l.
#	define DCS_DEBUG_TRACE_L(l,x) /**/
/// Macro for getting the underlying debug output stream.
# 	define DCS_DEBUG_STREAM /**/
/// Macro for setting flags \c x of the underlying debug output stream.
# 	define DCS_DEBUG_STREAM_SETFLAGS(x) /**/
/// Macro for converting the given argumento into a string.
# 	define DCS_DEBUG_STRINGIFY(x) /**/
/// Macro for converting the a type into a string.
# 	define DCS_DEBUG_TYPE2STR(x) /**/
/// Macro for executing one or more statements only when debug is enabled.
#	define DCS_DEBUG_DO(x) /**/
/// Macro for assertion
#	define DCS_DEBUG_ASSERT(x) /**/
#endif // NDEBUG

namespace dcs { namespace debug {

template <typename FwdItT>
::std::string to_string(FwdItT first, FwdItT last)
{
#ifdef DCS_DEBUG
	typedef typename ::std::iterator_traits<FwdItT>::value_type value_type;

    ::std::ostringstream oss;
    ::std::copy(first,
                last,
                ::std::ostream_iterator<value_type>(oss, " "));

    return oss.str();
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( first );
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( last );

    return "";
#endif // DCS_DEBUG
}

template <typename T>
::std::string to_string(T const& t)
{
#ifdef DCS_DEBUG
    ::std::ostringstream oss;
	oss << t;
    return oss.str();
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( t );

    return "";
#endif // DCS_DEBUG
}

template <typename T>
::std::string to_string(::std::vector<T> const& v)
{
#ifdef DCS_DEBUG
	//return to_string(v.begin(), v.end());
	const std::size_t n = v.size();
    ::std::ostringstream oss;
	oss << "{";
	for (std::size_t i = 0; i < n; ++i)
	{
		if (i > 0)
		{
			oss << ",";
		}
		oss << v[i];
	}
	oss << "]";
	return oss.str();
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( v );

    return "";
#endif // DCS_DEBUG
}

template <typename T>
::std::string to_string(::std::set<T> const& s)
{
#ifdef DCS_DEBUG
	return to_string(s.begin(), s.end());
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( v );

    return "";
#endif // DCS_DEBUG
}

}} // Namespace dcs::debug

#endif // DCS_DEBUG_HPP
<commit_msg>[debug] (bug-fix) Bad open parenthesis in debug message<commit_after>/**
 * \file dcs/debug.hpp
 *
 * \brief Provides helper functions and macros for debugging purpose.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DCS_DEBUG_HPP
#define DCS_DEBUG_HPP

#ifndef NDEBUG
//@{ for C99 and C++0x
//# 	include <cstdio>
//# 	define DCS_DEBUG_WHERESTR_  "[file %s, function %s, line %d]: "
//#	define DCS_DEBUG_WHEREARG_  __FILE__, __func__, __LINE__
//#	define DCS_DEBUG_PRINT2_(...)       fprintf(stderr, __VA_ARGS__)
//#	define DCS_DEBUG_PRINT(fmt, ...)  DCS_DEBUG_PRINT2_(DCS_DEBUG_WHERESTR_ fmt, DCS_DEBUG_WHEREARG_, __VA_ARGS__)
//@} for C99 and C++0x

#   include <algorithm>
#	include <cassert>
#	include <iostream>
#	include <iterator>
# 	include <set>
# 	include <sstream>
# 	include <string>
# 	include <typeinfo>
# 	include <vector>

/// Macro for telling whether we are in debug mode.
# 	define DCS_DEBUG /**/
/// Macro for expanding its argument \c x
#	define DCS_DEBUG_EXPAND__(x) x
/// Macro for writing to standard error its argument \c x
#	if !defined(DCS_DEBUG_LEVEL) || (DCS_DEBUG_LEVEL > 0)
#		define DCS_DEBUG_TRACE(x) ::std::cerr << "[Debug (" << __FILE__ << ":" << __func__ << ":" << __LINE__ << ")>> " << DCS_DEBUG_EXPAND__(x) << ::std::endl;
#	else
#		define DCS_DEBUG_TRACE(x) /**/
#	endif // !defined(DCS_DEBUG_LEVEL) ...
#	ifdef DCS_DEBUG_LEVEL
#		define DCS_DEBUG_TRACE_L(l,x) if (DCS_DEBUG_EXPAND__(l) <= DCS_DEBUG_LEVEL) { ::std::cerr << "[Debug (" << __FILE__ << ":" << __func__ << ":" << __LINE__ << ")>> " << DCS_DEBUG_EXPAND__(x) << ::std::endl; }
#	else
#		define DCS_DEBUG_TRACE_L(l,x) DCS_DEBUG_TRACE(x)
#	endif // DCS_DEBUG_LEVEL
/// Macro for getting the underlying debug output stream.
# 	define DCS_DEBUG_STREAM ::std::cerr
/// Macro for setting flags \c x of the underlying debug output stream.
# 	define DCS_DEBUG_STREAM_SETFLAGS(x) ::std::cerr.setf((x))
/// Macro for converting the given argumento into a string.
# 	define DCS_DEBUG_STRINGIFY(x) #x
/// Macro for converting the a type into a string.
# 	define DCS_DEBUG_TYPE2STR(x) typeid(x).name()
/// Macro for executing one or more statements only when debug is enabled.
#	define DCS_DEBUG_DO(x) x
/// Macro for assertion
#	define DCS_DEBUG_ASSERT(x) assert(x)

#else // NDEBUG

# 	include <string>

/// Macro for telling that we are in debug mode.
# 	undef DCS_DEBUG /**/
/// Macro for telling what level of debugging to enable.
# 	undef DCS_DEBUG_LEVEL /**/
/// Macro for writing to standard error its argument \c x
#	define DCS_DEBUG_TRACE(x) /**/
/// Macro for writing to standard error its argument \c x only when the
/// debugging level is greater than or equal to \c l.
#	define DCS_DEBUG_TRACE_L(l,x) /**/
/// Macro for getting the underlying debug output stream.
# 	define DCS_DEBUG_STREAM /**/
/// Macro for setting flags \c x of the underlying debug output stream.
# 	define DCS_DEBUG_STREAM_SETFLAGS(x) /**/
/// Macro for converting the given argumento into a string.
# 	define DCS_DEBUG_STRINGIFY(x) /**/
/// Macro for converting the a type into a string.
# 	define DCS_DEBUG_TYPE2STR(x) /**/
/// Macro for executing one or more statements only when debug is enabled.
#	define DCS_DEBUG_DO(x) /**/
/// Macro for assertion
#	define DCS_DEBUG_ASSERT(x) /**/
#endif // NDEBUG

namespace dcs { namespace debug {

template <typename FwdItT>
::std::string to_string(FwdItT first, FwdItT last)
{
#ifdef DCS_DEBUG
	typedef typename ::std::iterator_traits<FwdItT>::value_type value_type;

    ::std::ostringstream oss;
    ::std::copy(first,
                last,
                ::std::ostream_iterator<value_type>(oss, " "));

    return oss.str();
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( first );
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( last );

    return "";
#endif // DCS_DEBUG
}

template <typename T>
::std::string to_string(T const& t)
{
#ifdef DCS_DEBUG
    ::std::ostringstream oss;
	oss << t;
    return oss.str();
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( t );

    return "";
#endif // DCS_DEBUG
}

template <typename T>
::std::string to_string(::std::vector<T> const& v)
{
#ifdef DCS_DEBUG
	//return to_string(v.begin(), v.end());
	const std::size_t n = v.size();
    ::std::ostringstream oss;
	oss << "[";
	for (std::size_t i = 0; i < n; ++i)
	{
		if (i > 0)
		{
			oss << ",";
		}
		oss << v[i];
	}
	oss << "]";
	return oss.str();
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( v );

    return "";
#endif // DCS_DEBUG
}

template <typename T>
::std::string to_string(::std::set<T> const& s)
{
#ifdef DCS_DEBUG
	return to_string(s.begin(), s.end());
#else // DCS_DEBUG
	DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( v );

    return "";
#endif // DCS_DEBUG
}

}} // Namespace dcs::debug

#endif // DCS_DEBUG_HPP
<|endoftext|>