<commit_before>/*************************************************************************
 *
 *  $RCSfile: VisAreaContext.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: cl $ $Date: 2001-02-21 18:04:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_VISAREACONTEXT_HXX
#define _XMLOFF_VISAREACONTEXT_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _VCL_MAPUNIT_HXX
#include <vcl/mapunit.hxx>
#endif

class Rectangle;

namespace com { namespace sun { namespace star { namespace awt {
    struct Rectangle;
} } } }

class XMLVisAreaContext : public SvXMLImportContext
{
public:
    // read all attributes and set the values in rRect
    XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                                      Rectangle& rRect, const MapUnit aMapUnit);

    XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                                      ::com::sun::star::awt::Rectangle& rRect, const sal_Int16 nMeasureUnit);

    virtual ~XMLVisAreaContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                                    const NAMESPACE_RTL(OUString)& rLocalName,
                                                    const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual void EndElement();

private:
    void process(   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                    ::com::sun::star::awt::Rectangle& rRect,
                    const sal_Int16 nMeasureUnit );

};

#endif
<commit_msg>remove <xmloff/<commit_after>/*************************************************************************
 *
 *  $RCSfile: VisAreaContext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: sab $ $Date: 2001-02-27 10:40:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_VISAREACONTEXT_HXX
#define _XMLOFF_VISAREACONTEXT_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

#ifndef _VCL_MAPUNIT_HXX
#include <vcl/mapunit.hxx>
#endif

class Rectangle;

namespace com { namespace sun { namespace star { namespace awt {
    struct Rectangle;
} } } }

class XMLVisAreaContext : public SvXMLImportContext
{
public:
    // read all attributes and set the values in rRect
    XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                                      Rectangle& rRect, const MapUnit aMapUnit);

    XMLVisAreaContext( SvXMLImport& rImport, USHORT nPrfx, const NAMESPACE_RTL(OUString)& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                                      ::com::sun::star::awt::Rectangle& rRect, const sal_Int16 nMeasureUnit);

    virtual ~XMLVisAreaContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                                    const NAMESPACE_RTL(OUString)& rLocalName,
                                                    const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual void EndElement();

private:
    void process(   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                    ::com::sun::star::awt::Rectangle& rRect,
                    const sal_Int16 nMeasureUnit );

};

#endif
<|endoftext|>


<commit_before>#ifndef GROUP__BY__HPP
#define GROUP__BY__HPP

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    template <typename Container, typename KeyFunc>
    class GroupBy;

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T>, KeyFunc);

    template <typename Container, typename KeyFunc>
    class GroupBy  {
        private:
            Container container;
            KeyFunc key_func;

            friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);

            template <typename T, typename KF>
            friend GroupBy<std::initializer_list<T>, KF> groupby(
                    std::initializer_list<T>, KF);

            using key_func_ret =
                decltype(std::declval<KeyFunc>()(
                            std::declval<iterator_deref<Container>>()));

            GroupBy(Container container, KeyFunc key_func)
                : container(std::forward<Container>(container)),
                key_func(key_func)
            { }

        public:
            GroupBy() = delete;
            GroupBy(const GroupBy&) = delete;
            GroupBy& operator=(const GroupBy&) = delete;
            GroupBy& operator=(GroupBy&&) = delete;

            GroupBy(GroupBy&&) = default;

            class Iterator;
            class Group;

        private:
            using KeyGroupPair =
                std::pair<key_func_ret, Group>;
        public:

            class Iterator
                : public std::iterator<std::input_iterator_tag, KeyGroupPair>
            {
                private:
                    iterator_type<Container> sub_iter;
                    iterator_type<Container> sub_iter_peek;
                    const iterator_type<Container> sub_end;
                    KeyFunc key_func;

                public:
                    Iterator (iterator_type<Container> si,
                              iterator_type<Container> end,
                              KeyFunc key_func)
                        : sub_iter{si},
                        sub_end{end},
                        key_func(key_func)
                    { }

                    KeyGroupPair operator*() {
                        return KeyGroupPair(
                                this->key_func(*this->sub_iter),
                                Group(
                                    *this,
                                    this->key_func(*this->sub_iter)));
                    }

                    Iterator& operator++() {
                        return *this;
                    }

                    Iterator operator++(int) {
                        auto ret = *this;
                        ++*this;
                        return ret;
                    }

                    bool operator!=(const Iterator&) const {
                        return !this->exhausted();
                    }

                    bool operator==(const Iterator& other) const {
                        return !(*this != other);
                    }

                    void increment_iterator() {
                        if (this->sub_iter != this->sub_end) {
                            ++this->sub_iter;
                        }
                    }

                    bool exhausted() const {
                        return !(this->sub_iter != this->sub_end);
                    }

                    iterator_deref<Container> current() {
                        return *this->sub_iter;
                    }

                    key_func_ret next_key() {
                        return this->key_func(*this->sub_iter);
                    }
            };

            class Group {
                private:
                    friend Iterator;
                    friend class GroupIterator;
                    Iterator& owner;
                    key_func_ret key;

                    // completed is set if a Group is iterated through
                    // completely.  It is checked in the destructor, and
                    // if the Group has not been completed, the destructor
                    // exhausts it.  This ensures that the next Group starts
                    // at the correct position when the user short-circuits
                    // iteration over a Group.
                    // The move constructor sets the rvalue's completed
                    // attribute to true, so its destructor doesn't do anything
                    // when called.
                    mutable bool completed = false;

                    Group(Iterator& owner, key_func_ret key) :
                        owner(owner),
                        key(key)
                    { }

                public:
                    ~Group() {
                        if (!this->completed) {
                            for (auto iter = this->begin(), end = this->end();
                                    iter != end;
                                    ++iter) { }
                        }
                    }

                    // movable, non-copyable
                    Group() = delete;
                    Group(const Group&) = delete;
                    Group& operator=(const Group&) = delete;
                    Group& operator=(Group&&) = delete;

                    Group(Group&& other)
                            : owner{other.owner},
                            key{other.key},
                            completed{other.completed} {
                        other.completed = true;
                    }

                    class GroupIterator
                        : public std::iterator<std::input_iterator_tag,
                                iterator_traits_deref<Container>>
                    {
                        private:
                            const key_func_ret key;
                            const Group& group;

                            bool not_at_end() {
                                return !this->group.owner.exhausted()&&
                                    this->group.owner.next_key() == this->key;
                            }

                        public:
                            GroupIterator(const Group& group,
                                          key_func_ret key)
                                : key{key},
                                group{group}
                            { }

                            GroupIterator(const GroupIterator&) = default;

                            bool operator!=(const GroupIterator&) const {
                                return !this->group.completed;
#if 0
                                if (this->not_at_end()) {
                                    return true;
                                } else {
                                    this->group.completed = true;
                                    return false;
                                }
#endif
                            }

                            bool operator==(const GroupIterator& other) const {
                                return !(*this != other);
                            }

                            GroupIterator& operator++() {
                                this->group.owner.increment_iterator();
                                if (!this->not_at_end()) {
                                    this->group.completed = true;
                                }
                                return *this;
                            }

                            GroupIterator operator++(int) {
                                auto ret = *this;
                                ++*this;
                                return ret;
                            }

                            iterator_deref<Container> operator*() {
                                return this->group.owner.current();
                            }
                    };

                    GroupIterator begin() {
                        return {*this, key};
                    }

                    GroupIterator end() {
                        return {*this, key};
                    }

            };

            Iterator begin() {
                return {std::begin(this->container),
                        std::end(this->container),
                        this->key_func};
            }

            Iterator end() {
                return {std::end(this->container),
                        std::end(this->container),
                        this->key_func};
            }

    };

    // Takes something and returns it, used for default key of comparing
    // items in the sequence directly
    template <typename Container>
    class ItemReturner {
        public:
            iterator_deref<Container> operator() (
                    iterator_deref<Container> item) const {
                return item;
            }
    };

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(
            Container&& container, KeyFunc key_func) {
        return {std::forward<Container>(container), key_func};
    }

    template <typename Container>
    auto groupby(Container&& container) ->
            decltype(groupby(std::forward<Container>(container),
                        ItemReturner<Container>())) {
        return groupby(std::forward<Container>(container),
                ItemReturner<Container>());
    }

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T> il, KeyFunc key_func) {
        return {std::move(il), key_func};
    }

    template <typename T>
    auto groupby(std::initializer_list<T> il) ->
            decltype(groupby(std::move(il),
                        ItemReturner<std::initializer_list<T>>())) {
        return groupby(
                std::move(il),
                ItemReturner<std::initializer_list<T>>());
    }

}

#endif //#ifndef GROUP__BY__HPP
<commit_msg>corrects include guards<commit_after>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    template <typename Container, typename KeyFunc>
    class GroupBy;

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T>, KeyFunc);

    template <typename Container, typename KeyFunc>
    class GroupBy  {
        private:
            Container container;
            KeyFunc key_func;

            friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);

            template <typename T, typename KF>
            friend GroupBy<std::initializer_list<T>, KF> groupby(
                    std::initializer_list<T>, KF);

            using key_func_ret =
                decltype(std::declval<KeyFunc>()(
                            std::declval<iterator_deref<Container>>()));

            GroupBy(Container container, KeyFunc key_func)
                : container(std::forward<Container>(container)),
                key_func(key_func)
            { }

        public:
            GroupBy() = delete;
            GroupBy(const GroupBy&) = delete;
            GroupBy& operator=(const GroupBy&) = delete;
            GroupBy& operator=(GroupBy&&) = delete;

            GroupBy(GroupBy&&) = default;

            class Iterator;
            class Group;

        private:
            using KeyGroupPair =
                std::pair<key_func_ret, Group>;
        public:

            class Iterator
                : public std::iterator<std::input_iterator_tag, KeyGroupPair>
            {
                private:
                    iterator_type<Container> sub_iter;
                    iterator_type<Container> sub_iter_peek;
                    const iterator_type<Container> sub_end;
                    KeyFunc key_func;

                public:
                    Iterator (iterator_type<Container> si,
                              iterator_type<Container> end,
                              KeyFunc key_func)
                        : sub_iter{si},
                        sub_end{end},
                        key_func(key_func)
                    { }

                    KeyGroupPair operator*() {
                        return KeyGroupPair(
                                this->key_func(*this->sub_iter),
                                Group(
                                    *this,
                                    this->key_func(*this->sub_iter)));
                    }

                    Iterator& operator++() {
                        return *this;
                    }

                    Iterator operator++(int) {
                        auto ret = *this;
                        ++*this;
                        return ret;
                    }

                    bool operator!=(const Iterator&) const {
                        return !this->exhausted();
                    }

                    bool operator==(const Iterator& other) const {
                        return !(*this != other);
                    }

                    void increment_iterator() {
                        if (this->sub_iter != this->sub_end) {
                            ++this->sub_iter;
                        }
                    }

                    bool exhausted() const {
                        return !(this->sub_iter != this->sub_end);
                    }

                    iterator_deref<Container> current() {
                        return *this->sub_iter;
                    }

                    key_func_ret next_key() {
                        return this->key_func(*this->sub_iter);
                    }
            };

            class Group {
                private:
                    friend Iterator;
                    friend class GroupIterator;
                    Iterator& owner;
                    key_func_ret key;

                    // completed is set if a Group is iterated through
                    // completely.  It is checked in the destructor, and
                    // if the Group has not been completed, the destructor
                    // exhausts it.  This ensures that the next Group starts
                    // at the correct position when the user short-circuits
                    // iteration over a Group.
                    // The move constructor sets the rvalue's completed
                    // attribute to true, so its destructor doesn't do anything
                    // when called.
                    mutable bool completed = false;

                    Group(Iterator& owner, key_func_ret key) :
                        owner(owner),
                        key(key)
                    { }

                public:
                    ~Group() {
                        if (!this->completed) {
                            for (auto iter = this->begin(), end = this->end();
                                    iter != end;
                                    ++iter) { }
                        }
                    }

                    // movable, non-copyable
                    Group() = delete;
                    Group(const Group&) = delete;
                    Group& operator=(const Group&) = delete;
                    Group& operator=(Group&&) = delete;

                    Group(Group&& other)
                            : owner{other.owner},
                            key{other.key},
                            completed{other.completed} {
                        other.completed = true;
                    }

                    class GroupIterator
                        : public std::iterator<std::input_iterator_tag,
                                iterator_traits_deref<Container>>
                    {
                        private:
                            const key_func_ret key;
                            const Group& group;

                            bool not_at_end() {
                                return !this->group.owner.exhausted()&&
                                    this->group.owner.next_key() == this->key;
                            }

                        public:
                            GroupIterator(const Group& group,
                                          key_func_ret key)
                                : key{key},
                                group{group}
                            { }

                            GroupIterator(const GroupIterator&) = default;

                            bool operator!=(const GroupIterator&) const {
                                return !this->group.completed;
#if 0
                                if (this->not_at_end()) {
                                    return true;
                                } else {
                                    this->group.completed = true;
                                    return false;
                                }
#endif
                            }

                            bool operator==(const GroupIterator& other) const {
                                return !(*this != other);
                            }

                            GroupIterator& operator++() {
                                this->group.owner.increment_iterator();
                                if (!this->not_at_end()) {
                                    this->group.completed = true;
                                }
                                return *this;
                            }

                            GroupIterator operator++(int) {
                                auto ret = *this;
                                ++*this;
                                return ret;
                            }

                            iterator_deref<Container> operator*() {
                                return this->group.owner.current();
                            }
                    };

                    GroupIterator begin() {
                        return {*this, key};
                    }

                    GroupIterator end() {
                        return {*this, key};
                    }

            };

            Iterator begin() {
                return {std::begin(this->container),
                        std::end(this->container),
                        this->key_func};
            }

            Iterator end() {
                return {std::end(this->container),
                        std::end(this->container),
                        this->key_func};
            }

    };

    // Takes something and returns it, used for default key of comparing
    // items in the sequence directly
    template <typename Container>
    class ItemReturner {
        public:
            iterator_deref<Container> operator() (
                    iterator_deref<Container> item) const {
                return item;
            }
    };

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(
            Container&& container, KeyFunc key_func) {
        return {std::forward<Container>(container), key_func};
    }

    template <typename Container>
    auto groupby(Container&& container) ->
            decltype(groupby(std::forward<Container>(container),
                        ItemReturner<Container>())) {
        return groupby(std::forward<Container>(container),
                ItemReturner<Container>());
    }

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T> il, KeyFunc key_func) {
        return {std::move(il), key_func};
    }

    template <typename T>
    auto groupby(std::initializer_list<T> il) ->
            decltype(groupby(std::move(il),
                        ItemReturner<std::initializer_list<T>>())) {
        return groupby(
                std::move(il),
                ItemReturner<std::initializer_list<T>>());
    }

}

#endif
<|endoftext|>


<commit_before>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_

#include "iterbase.hpp"

#include <type_traits>
#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    template <typename Container, typename KeyFunc>
    class GroupBy;

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T>, KeyFunc);

    template <typename Container, typename KeyFunc>
    class GroupBy  {
        private:
            Container container;
            KeyFunc key_func;

            friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);

            template <typename T, typename KF>
            friend GroupBy<std::initializer_list<T>, KF> groupby(
                    std::initializer_list<T>, KF);

            using key_func_ret = typename
                std::result_of<KeyFunc(iterator_deref<Container>)>::type;

            GroupBy(Container&& in_container, KeyFunc in_key_func)
                : container(std::forward<Container>(in_container)),
                key_func(in_key_func)
            { }

        public:
            GroupBy() = delete;
            GroupBy(const GroupBy&) = delete;
            GroupBy& operator=(const GroupBy&) = delete;
            GroupBy& operator=(GroupBy&&) = delete;

            GroupBy(GroupBy&&) = default;

            class Iterator;
            class Group;

        private:
            using KeyGroupPair =
                std::pair<key_func_ret, Group>;
        public:

            class Iterator
                : public std::iterator<std::input_iterator_tag, KeyGroupPair>
            {
                private:
                    iterator_type<Container> sub_iter;
                    iterator_type<Container> sub_end;
                    DerefHolder<iterator_deref<Container>> item;
                    KeyFunc *key_func;

                public:
                    Iterator(iterator_type<Container>&& si,
                              iterator_type<Container>&& end,
                              KeyFunc& in_key_func)
                        : sub_iter{std::move(si)},
                        sub_end{std::move(end)},
                        key_func(&in_key_func)
                    {
                        if (this->sub_iter != this->sub_end) {
                            this->item.reset(*this->sub_iter);
                        }
                    }

                    KeyGroupPair operator*() {
                        // FIXME double deref
                        return {
                            (*this->key_func)(this->item.get()),
                            Group{*this, (*this->key_func)(this->item.get())}
                        };
                    }

                    Iterator& operator++() {
                        return *this;
                    }

                    Iterator operator++(int) {
                        auto ret = *this;
                        ++*this;
                        return ret;
                    }

                    bool operator!=(const Iterator& other) const {
                        return this->sub_iter != other.sub_iter;
                    }

                    bool operator==(const Iterator& other) const {
                        return !(*this != other);
                    }

                    void increment_iterator() {
                        if (this->sub_iter != this->sub_end) {
                            ++this->sub_iter;
                            if (this->sub_iter != this->sub_end) {
                                this->item.reset(*this->sub_iter);
                            }
                        }
                    }

                    bool exhausted() const {
                        return !(this->sub_iter != this->sub_end);
                    }

                    iterator_deref<Container> pull() {
                        return this->item.pull();
                    }

                    // FIXME double deref. Two deref holders?
                    key_func_ret next_key() {
                        return (*this->key_func)(this->item.get());
                    }
            };

            class Group {
                private:
                    friend Iterator;
                    friend class GroupIterator;
                    Iterator& owner;
                    key_func_ret key;

                    // completed is set if a Group is iterated through
                    // completely.  It is checked in the destructor, and
                    // if the Group has not been completed, the destructor
                    // exhausts it.  This ensures that the next Group starts
                    // at the correct position when the user short-circuits
                    // iteration over a Group.
                    // The move constructor sets the rvalue's completed
                    // attribute to true, so its destructor doesn't do anything
                    // when called.
                    bool completed = false;

                    Group(Iterator& in_owner, key_func_ret in_key) :
                        owner(in_owner),
                        key(in_key)
                    { }

                public:
                    ~Group() {
                        if (!this->completed) {
                            for (auto iter = this->begin(), end = this->end();
                                    iter != end;
                                    ++iter) { }
                        }
                    }

                    // move-constructible, non-copy-constructible,
                    // non-assignable
                    Group() = delete;
                    Group(const Group&) = delete;
                    Group& operator=(const Group&) = delete;
                    Group& operator=(Group&&) = delete;

                    Group(Group&& other)
                            : owner{other.owner},
                            key{other.key},
                            completed{other.completed} {
                        other.completed = true;
                    }

                    class GroupIterator
                        : public std::iterator<std::input_iterator_tag,
                                iterator_traits_deref<Container>>
                    {
                        private:
                            typename std::remove_reference<key_func_ret>::type  *key;
                            Group *group_p;

                            bool not_at_end() {
                                return !this->group_p->owner.exhausted()&&
                                    this->group_p->owner.next_key() == *this->key;
                            }

                        public:
                            GroupIterator(Group *in_group_p,
                                          key_func_ret& in_key)
                                : key{&in_key},
                                group_p{in_group_p}
                            { }

                            bool operator!=(const GroupIterator& other) const {
                                return !(*this == other);
                            }

                            bool operator==(const GroupIterator& other) const {
                                return this->group_p == other.group_p;
                            }

                            GroupIterator& operator++() {
                                this->group_p->owner.increment_iterator();
                                if (!this->not_at_end()) {
                                    this->group_p->completed = true;
                                    this->group_p = nullptr;
                                }
                                return *this;
                            }

                            GroupIterator operator++(int) {
                                auto ret = *this;
                                ++*this;
                                return ret;
                            }

                            iterator_deref<Container> operator*() {
                                return this->group_p->owner.pull();
                            }
                    };

                    GroupIterator begin() {
                        return {this, key};
                    }

                    GroupIterator end() {
                        return {nullptr, key};
                    }

            };

            Iterator begin() {
                return {std::begin(this->container),
                        std::end(this->container),
                        this->key_func};
            }

            Iterator end() {
                return {std::end(this->container),
                        std::end(this->container),
                        this->key_func};
            }

    };

    // Takes something and returns it, used for default key of comparing
    // items in the sequence directly
    template <typename Container>
    class ItemReturner {
        public:
            iterator_deref<Container> operator() (
                    iterator_deref<Container> item) const {
                return item;
            }
    };

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(
            Container&& container, KeyFunc key_func) {
        return {std::forward<Container>(container), key_func};
    }

    template <typename Container>
    auto groupby(Container&& container) ->
            decltype(groupby(std::forward<Container>(container),
                        ItemReturner<Container>())) {
        return groupby(std::forward<Container>(container),
                ItemReturner<Container>());
    }

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T> il, KeyFunc key_func) {
        return {std::move(il), key_func};
    }

    template <typename T>
    auto groupby(std::initializer_list<T> il) ->
            decltype(groupby(std::move(il),
                        ItemReturner<std::initializer_list<T>>())) {
        return groupby(
                std::move(il),
                ItemReturner<std::initializer_list<T>>());
    }

}

#endif
<commit_msg>groupby uses get() instead of pull()<commit_after>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_

#include "iterbase.hpp"

#include <type_traits>
#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    template <typename Container, typename KeyFunc>
    class GroupBy;

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T>, KeyFunc);

    template <typename Container, typename KeyFunc>
    class GroupBy  {
        private:
            Container container;
            KeyFunc key_func;

            friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);

            template <typename T, typename KF>
            friend GroupBy<std::initializer_list<T>, KF> groupby(
                    std::initializer_list<T>, KF);

            using key_func_ret = typename
                std::result_of<KeyFunc(iterator_deref<Container>)>::type;

            GroupBy(Container&& in_container, KeyFunc in_key_func)
                : container(std::forward<Container>(in_container)),
                key_func(in_key_func)
            { }

        public:
            GroupBy() = delete;
            GroupBy(const GroupBy&) = delete;
            GroupBy& operator=(const GroupBy&) = delete;
            GroupBy& operator=(GroupBy&&) = delete;

            GroupBy(GroupBy&&) = default;

            class Iterator;
            class Group;

        private:
            using KeyGroupPair =
                std::pair<key_func_ret, Group>;
        public:

            class Iterator
                : public std::iterator<std::input_iterator_tag, KeyGroupPair>
            {
                private:
                    using Holder = DerefHolder<iterator_deref<Container>>;
                    iterator_type<Container> sub_iter;
                    iterator_type<Container> sub_end;
                    Holder item;
                    KeyFunc *key_func;

                public:
                    Iterator(iterator_type<Container>&& si,
                              iterator_type<Container>&& end,
                              KeyFunc& in_key_func)
                        : sub_iter{std::move(si)},
                        sub_end{std::move(end)},
                        key_func(&in_key_func)
                    {
                        if (this->sub_iter != this->sub_end) {
                            this->item.reset(*this->sub_iter);
                        }
                    }

                    KeyGroupPair operator*() {
                        return {
                            (*this->key_func)(this->item.get()),
                            Group{*this, (*this->key_func)(this->item.get())}
                        };
                    }

                    Iterator& operator++() {
                        return *this;
                    }

                    Iterator operator++(int) {
                        auto ret = *this;
                        ++*this;
                        return ret;
                    }

                    bool operator!=(const Iterator& other) const {
                        return this->sub_iter != other.sub_iter;
                    }

                    bool operator==(const Iterator& other) const {
                        return !(*this != other);
                    }

                    void increment_iterator() {
                        if (this->sub_iter != this->sub_end) {
                            ++this->sub_iter;
                            if (this->sub_iter != this->sub_end) {
                                this->item.reset(*this->sub_iter);
                            }
                        }
                    }

                    bool exhausted() const {
                        return !(this->sub_iter != this->sub_end);
                    }

                    typename Holder::reference get() {
                        return this->item.get();
                    }

                    key_func_ret next_key() {
                        return (*this->key_func)(this->item.get());
                    }
            };

            class Group {
                private:
                    friend Iterator;
                    friend class GroupIterator;
                    Iterator& owner;
                    key_func_ret key;

                    // completed is set if a Group is iterated through
                    // completely.  It is checked in the destructor, and
                    // if the Group has not been completed, the destructor
                    // exhausts it.  This ensures that the next Group starts
                    // at the correct position when the user short-circuits
                    // iteration over a Group.
                    // The move constructor sets the rvalue's completed
                    // attribute to true, so its destructor doesn't do anything
                    // when called.
                    bool completed = false;

                    Group(Iterator& in_owner, key_func_ret in_key) :
                        owner(in_owner),
                        key(in_key)
                    { }

                public:
                    ~Group() {
                        if (!this->completed) {
                            for (auto iter = this->begin(), end = this->end();
                                    iter != end;
                                    ++iter) { }
                        }
                    }

                    // move-constructible, non-copy-constructible,
                    // non-assignable
                    Group() = delete;
                    Group(const Group&) = delete;
                    Group& operator=(const Group&) = delete;
                    Group& operator=(Group&&) = delete;

                    Group(Group&& other)
                            : owner{other.owner},
                            key{other.key},
                            completed{other.completed} {
                        other.completed = true;
                    }

                    class GroupIterator
                        : public std::iterator<std::input_iterator_tag,
                                iterator_traits_deref<Container>>
                    {
                        private:
                            typename std::remove_reference<key_func_ret>::type  *key;
                            Group *group_p;

                            bool not_at_end() {
                                return !this->group_p->owner.exhausted()&&
                                    this->group_p->owner.next_key() == *this->key;
                            }

                        public:
                            GroupIterator(Group *in_group_p,
                                          key_func_ret& in_key)
                                : key{&in_key},
                                group_p{in_group_p}
                            { }

                            bool operator!=(const GroupIterator& other) const {
                                return !(*this == other);
                            }

                            bool operator==(const GroupIterator& other) const {
                                return this->group_p == other.group_p;
                            }

                            GroupIterator& operator++() {
                                this->group_p->owner.increment_iterator();
                                if (!this->not_at_end()) {
                                    this->group_p->completed = true;
                                    this->group_p = nullptr;
                                }
                                return *this;
                            }

                            GroupIterator operator++(int) {
                                auto ret = *this;
                                ++*this;
                                return ret;
                            }

                            iterator_deref<Container> operator*() {
                                return this->group_p->owner.get();
                            }
                    };

                    GroupIterator begin() {
                        return {this, key};
                    }

                    GroupIterator end() {
                        return {nullptr, key};
                    }

            };

            Iterator begin() {
                return {std::begin(this->container),
                        std::end(this->container),
                        this->key_func};
            }

            Iterator end() {
                return {std::end(this->container),
                        std::end(this->container),
                        this->key_func};
            }

    };

    // Takes something and returns it, used for default key of comparing
    // items in the sequence directly
    template <typename Container>
    class ItemReturner {
        public:
            iterator_deref<Container> operator() (
                    iterator_deref<Container> item) const {
                return item;
            }
    };

    template <typename Container, typename KeyFunc>
    GroupBy<Container, KeyFunc> groupby(
            Container&& container, KeyFunc key_func) {
        return {std::forward<Container>(container), key_func};
    }

    template <typename Container>
    auto groupby(Container&& container) ->
            decltype(groupby(std::forward<Container>(container),
                        ItemReturner<Container>())) {
        return groupby(std::forward<Container>(container),
                ItemReturner<Container>());
    }

    template <typename T, typename KeyFunc>
    GroupBy<std::initializer_list<T>, KeyFunc> groupby(
            std::initializer_list<T> il, KeyFunc key_func) {
        return {std::move(il), key_func};
    }

    template <typename T>
    auto groupby(std::initializer_list<T> il) ->
            decltype(groupby(std::move(il),
                        ItemReturner<std::initializer_list<T>>())) {
        return groupby(
                std::move(il),
                ItemReturner<std::initializer_list<T>>());
    }

}

#endif
<|endoftext|>


<commit_before>
#include "simulation.h"

/*! \mainpage Molecular Simulation
 *
 * \section int_sec Introduction
 *
 * \par This program is a simulated molecular lab for experimenting with DNA operations.
 *
 * \par Execution of a directory of DIMACS CNF (*.cnf) expressions can be performed with the Perl runSimulation.pl.
 *
 * \section sys_sec System requirements
 *
 * \par MolecularSimulation requires the following software to be installed on your system:
 *   - GCC
 *   - Perl
 *
 *	\par Additional requirements for generating documentation:
 *   - Doxygen
 *
 * \par This program was designed to execute in a 64-bit *NIX environment.  It has been tested on Apple OS X 10.6.8.  The final build will execute natively on the RIT CS machines (portability of the Perl scripts is in progress).
 *
 * \section alg_sec Algorithms
 * \par There are three molecular Satisfiability algorithms implemented in this environment.
 *
 * \subsection lip_sec Lipton's algorithm
 *
 *	\par Introduced in 1995 by Lipton, this algorithm creates an exponential search space for the CNF expression.  Once the space is created, each variable is evaluated and the space is reduced to only the solutions that satisfy all remaining strings.  This algorithm is analogous to a conventional brute-force search for all solutions.
 *
 * \subsection ogi_sec Ogihara and Ray's algorithm
 *
 *  \par Originally introduced in 1996 by Ogihara, and extended in 1997 with Ray, this algorithm builds a solution space with a breadth-first search evaluation.  Prior to execution to the algorithm, each of the clauses variable's in the CNF expression are sorted.
 *
 * \subsection dis_sec Distribution algorithm
 *
 * \par The distribution algorithm parses an input CNF expression into growing and self regulated set of possible combinations.  A possible combination begins with all members of the first clause, and subsequent variables from independent clauses are built upon the reduced state.  If there exist self-complementary assignments spanning a clause, then the clause is eliminated.
 *
 * \section exe_sec Execution
 *
 * \par Automation of execution can be done simply by executing the perl script
 *
 * $ perl runSimulation.pl
 *
 * \par from the directory: project/implementation/molecularSimulation/
 *
 * \par This file will sequentially invoke `build.pl' and `executeMolecularSat.pl'
 *
 * \subsection input_sec Input
 *
 *  \par Input is provided as DIMACS CNF (*.cnf) to execute a specified algorithm.  Arguments may be provided to assist in debugging (-d) or write the simulation results to a file.
 *
 *
 * \subsection output_sec Output
 *
 * \par Output consists of a summary of a test execution.  This output conforms to the SAT Competition format for the status of the `*.cnf' expression.  If desired, the output may be directed to a file.  Conditional formatting of comment fields provide execution details.
 */

///
/// Default constructor for simulation.
///
simulation::simulation(){

}

///
/// Destructor for simulation.
///
simulation::~simulation(){

}

///
/// Start simulation.
///
void simulation::start(int argc, char ** argv){

	arguments testArguments;

	// Set version revision number

	testArguments.versionNumber = (char*) malloc (10);
	strcpy(testArguments.versionNumber, "1.0.1");

	testArguments.parseArguments(argc, argv);					///< Parse user arguments

	// Print debug argument list
	if(testArguments.debug)	testArguments.printArguments();

	testArguments.inputCNF.parseCNF( testArguments.filename);	///< Parse DIMACS CNF

	// Print CNF details
/*
	if(testArguments.debug){
		testArguments.inputCNF.printCNF_table();
		testArguments.inputCNF.printCNF_order();
	}
*/

	testArguments = executeTest(testArguments);					///< Execute algorithm
	testArguments.writeOutput();								///< Write output results

	// Print debug argument list
	if(testArguments.debug)	testArguments.printArguments();

}

///
/// main simulation entry
///
int main(int argc, char ** argv){

	simulation myRun;

	myRun.start(argc, argv);

	return 0;
}
<commit_msg>Main entry<commit_after>#include "simulation.h"

/*! \mainpage Molecular Simulation
 *
 * \section int_sec Introduction
 *
 * \par This program is a simulated molecular lab for experimenting with DNA operations.
 *
 * \par Execution of a directory of DIMACS CNF (*.cnf) expressions can be performed with the Perl runSimulation.pl.
 *
 * \section sys_sec System requirements
 *
 * \par MolecularSimulation requires the following software to be installed on your system:
 *   - GCC
 *   - Perl
 *
 *	\par Additional requirements for generating documentation:
 *   - Doxygen
 *
 * \par This program was designed to execute in a 64-bit *NIX environment.  It has been tested on Apple OS X 10.6.8.  The final build will execute natively on the RIT CS machines (portability of the Perl scripts is in progress).
 *
 * \section alg_sec Algorithms
 * \par There are three molecular Satisfiability algorithms implemented in this environment.
 *
 * \subsection lip_sec Lipton's algorithm
 *
 *	\par Introduced in 1995 by Lipton, this algorithm creates an exponential search space for the CNF expression.  Once the space is created, each variable is evaluated and the space is reduced to only the solutions that satisfy all remaining strings.  This algorithm is analogous to a conventional brute-force search for all solutions.
 *
 * \subsection ogi_sec Ogihara and Ray's algorithm
 *
 *  \par Originally introduced in 1996 by Ogihara, and extended in 1997 with Ray, this algorithm builds a solution space with a breadth-first search evaluation.  Prior to execution to the algorithm, each of the clauses variable's in the CNF expression are sorted.
 *
 * \subsection dis_sec Distribution algorithm
 *
 * \par The distribution algorithm parses an input CNF expression into growing and self regulated set of possible combinations.  A possible combination begins with all members of the first clause, and subsequent variables from independent clauses are built upon the reduced state.  If there exist self-complementary assignments spanning a clause, then the clause is eliminated.
 *
 * \section exe_sec Execution
 *
 * \par Automation of execution can be done simply by executing the perl script
 *
 * $ perl runSimulation.pl
 *
 * \par from the directory: project/implementation/molecularSimulation/
 *
 * \par This file will sequentially invoke `build.pl' and `executeMolecularSat.pl'
 *
 * \subsection input_sec Input
 *
 *  \par Input is provided as DIMACS CNF (*.cnf) to execute a specified algorithm.  Arguments may be provided to assist in debugging (-d) or write the simulation results to a file.
 *
 *
 * \subsection output_sec Output
 *
 * \par Output consists of a summary of a test execution.  This output conforms to the SAT Competition format for the status of the `*.cnf' expression.  If desired, the output may be directed to a file.  Conditional formatting of comment fields provide execution details.
 */

///
/// Default constructor for simulation.
///
simulation::simulation(){

}

///
/// Destructor for simulation.
///
simulation::~simulation(){

}

///
/// Start simulation.
///
void simulation::start(int argc, char ** argv){

	arguments testArguments;

	// Set version revision number

	testArguments.versionNumber = (char*) malloc (10);
	strcpy(testArguments.versionNumber, "1.0.1");

	testArguments.parseArguments(argc, argv);					///< Parse user arguments

	// Print debug argument list
	if(testArguments.debug)	testArguments.printArguments();

	testArguments.inputCNF.parseCNF( testArguments.filename);	///< Parse DIMACS CNF

	// Print CNF details
/*
	if(testArguments.debug){
		testArguments.inputCNF.printCNF_table();
		testArguments.inputCNF.printCNF_order();
	}
*/

	testArguments = executeTest(testArguments);					///< Execute algorithm
	testArguments.writeOutput();								///< Write output results

	// Print debug argument list
	if(testArguments.debug)	testArguments.printArguments();

}

///
/// main simulation entry
///
int main(int argc, char ** argv){

	simulation myRun;

	myRun.start(argc, argv);

	return 0;
}
<|endoftext|>


<commit_before>// time complexity - O(n)
// space complexity - O(1)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        if (nums.size() == 1) return 1;
        int size = nums.size();
        int i = 1;
        int last = nums[0];
        while (i < size) {
            if (last == nums[i]) {
                nums.erase(nums.begin() + i);
                size--;
            } else {
                last = nums[i];
                i++;
            }
        }
        return i;
    }
};<commit_msg>updated removeDupe.cpp<commit_after>// time complexity - O(n)
// space complexity - O(1)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        int writing = 1;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[writing-1] != nums[i]) {
                nums[writing++] = nums[i];
            }
        }
        return writing;
    }
};<|endoftext|>


<commit_before>// Correctness 100%
// Performance 80%
// Task score 90%

// you can use includes, for example:
// #include <algorithm>
#include <bitset>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(int M, vector<int> &A) {
    // for(unsigned int i=0; i<A.size(); ++i)
        // cout << A[i] << " ";
    // cout << endl;
    // write your code in C++11
    long i(0);
    long j(0);
    long k(0);
    long count(0);
    bitset<100001> mybitset;
    vector<long> myvector(100001,0);
    while( i<A.size() ) {
        // cout << i << " " << j << " ";
        if( j<A.size() ) {
            if( mybitset[A[j]]==0 ) {
                mybitset[A[j]]= 1;
                myvector[A[j]]= j;
                j++;
            }
            else {
                k=myvector[A[j]];
                // cout << i << " " << k << " " << j << endl;
                count += (j-i+2)*(j-i+1)/2;
                count -= k-i+1;
                count -= (j-k+1)*(j-k)/2;
                i=k+1;
                j=i;
                mybitset.reset();
            }
        }
        else {
            count += (j-i+1)*(j-i)/2;
            i=j;
        }
        if( count>1000000000 )
            return 1000000000;
        // cout << count << endl;
    }
    return count;
}
<commit_msg>Update solution.cpp<commit_after>// Correctness 100%
// Performance 80%
// Task score 90%

// Note: codility may have a bug here
// because random access for vector should be O(1)
// i.e. performance will be not affected by N
// but in the codility test, the performance drops linear like O(N)

// you can use includes, for example:
// #include <algorithm>
#include <bitset>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(int M, vector<int> &A) {
    // for(unsigned int i=0; i<A.size(); ++i)
        // cout << A[i] << " ";
    // cout << endl;
    // write your code in C++11
    long i(0);
    long j(0);
    long k(0);
    long count(0);
    bitset<100001> mybitset;
    vector<long> myvector(100001,0);
    while( i<A.size() ) {
        // cout << i << " " << j << " ";
        if( j<A.size() ) {
            if( mybitset[A[j]]==0 ) {
                mybitset[A[j]]= 1;
                myvector[A[j]]= j;
                j++;
            }
            else {
                k=myvector[A[j]];
                // cout << i << " " << k << " " << j << endl;
                count += (j-i+2)*(j-i+1)/2;
                count -= k-i+1;
                count -= (j-k+1)*(j-k)/2;
                i=k+1;
                j=i;
                mybitset.reset();
            }
        }
        else {
            count += (j-i+1)*(j-i)/2;
            i=j;
        }
        if( count>1000000000 )
            return 1000000000;
        // cout << count << endl;
    }
    return count;
}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/local_discovery/service_discovery_shared_client.h"

#include "content/public/browser/browser_thread.h"

#if defined(OS_WIN)
#include "base/files/file_path.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/timer/elapsed_timer.h"
#include "chrome/browser/local_discovery/service_discovery_client_utility.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/firewall_manager_win.h"
#endif  // OS_WIN

#if defined(OS_MACOSX)
#include "chrome/browser/local_discovery/service_discovery_client_mac_factory.h"
#endif

#if defined(ENABLE_MDNS)
#include "chrome/browser/local_discovery/service_discovery_client_mdns.h"
#endif  // ENABLE_MDNS

namespace {

#if defined(OS_WIN)
bool IsFirewallReady() {
  base::FilePath exe_path;
  if (!PathService::Get(base::FILE_EXE, &exe_path))
    return false;
  base::ElapsedTimer timer;
  scoped_ptr<installer::FirewallManager> manager =
      installer::FirewallManager::Create(BrowserDistribution::GetDistribution(),
                                         exe_path);
  if (!manager)
    return false;
  bool is_ready = manager->CanUseLocalPorts();
  UMA_HISTOGRAM_TIMES("LocalDiscovery.FirewallAccessTime", timer.Elapsed());
  UMA_HISTOGRAM_BOOLEAN("LocalDiscovery.IsFirewallReady", is_ready);
  return is_ready;
}
#endif  // OS_WIN

}  // namespace

namespace local_discovery {

using content::BrowserThread;

namespace {
ServiceDiscoverySharedClient* g_service_discovery_client = NULL;
}  // namespace

ServiceDiscoverySharedClient::ServiceDiscoverySharedClient() {
  DCHECK(!g_service_discovery_client);
  g_service_discovery_client = this;
}

ServiceDiscoverySharedClient::~ServiceDiscoverySharedClient() {
  DCHECK_EQ(g_service_discovery_client, this);
  g_service_discovery_client = NULL;
}

#if defined(ENABLE_MDNS) || defined(OS_MACOSX)

scoped_refptr<ServiceDiscoverySharedClient>
    ServiceDiscoverySharedClient::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (g_service_discovery_client)
    return g_service_discovery_client;

#if defined(OS_MACOSX)
  return ServiceDiscoveryClientMacFactory::CreateInstance();
#else

#if defined(OS_WIN)
  static bool is_firewall_ready = IsFirewallReady();
  if (!is_firewall_ready) {
    // TODO(vitalybuka): Remove after we find what to do with firewall for
    // user-level installs. crbug.com/366408
    return new ServiceDiscoveryClientUtility();
  }
#endif  // OS_WIN
  return new ServiceDiscoveryClientMdns();
#endif
}

#else

scoped_refptr<ServiceDiscoverySharedClient>
    ServiceDiscoverySharedClient::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  NOTIMPLEMENTED();
  return NULL;
}

#endif  // ENABLE_MDNS

}  // namespace local_discovery
<commit_msg>Disable firewall check. It takes signifficant time, need to be on FILE thread.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/local_discovery/service_discovery_shared_client.h"

#include "content/public/browser/browser_thread.h"

#if defined(OS_WIN)
#include "base/files/file_path.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/timer/elapsed_timer.h"
#include "chrome/browser/local_discovery/service_discovery_client_utility.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/firewall_manager_win.h"
#endif  // OS_WIN

#if defined(OS_MACOSX)
#include "chrome/browser/local_discovery/service_discovery_client_mac_factory.h"
#endif

#if defined(ENABLE_MDNS)
#include "chrome/browser/local_discovery/service_discovery_client_mdns.h"
#endif  // ENABLE_MDNS

namespace {

#if defined(OS_WIN)
void ReportFirewallStats() {
  base::FilePath exe_path;
  if (!PathService::Get(base::FILE_EXE, &exe_path))
    return;
  base::ElapsedTimer timer;
  scoped_ptr<installer::FirewallManager> manager =
      installer::FirewallManager::Create(BrowserDistribution::GetDistribution(),
                                         exe_path);
  if (!manager)
    return;
  bool is_ready = manager->CanUseLocalPorts();
  UMA_HISTOGRAM_TIMES("LocalDiscovery.FirewallAccessTime", timer.Elapsed());
  UMA_HISTOGRAM_BOOLEAN("LocalDiscovery.IsFirewallReady", is_ready);
}
#endif  // OS_WIN

}  // namespace

namespace local_discovery {

using content::BrowserThread;

namespace {
ServiceDiscoverySharedClient* g_service_discovery_client = NULL;
}  // namespace

ServiceDiscoverySharedClient::ServiceDiscoverySharedClient() {
  DCHECK(!g_service_discovery_client);
  g_service_discovery_client = this;
}

ServiceDiscoverySharedClient::~ServiceDiscoverySharedClient() {
  DCHECK_EQ(g_service_discovery_client, this);
  g_service_discovery_client = NULL;
}

#if defined(ENABLE_MDNS) || defined(OS_MACOSX)

scoped_refptr<ServiceDiscoverySharedClient>
    ServiceDiscoverySharedClient::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (g_service_discovery_client)
    return g_service_discovery_client;

#if defined(OS_MACOSX)
  return ServiceDiscoveryClientMacFactory::CreateInstance();
#else

#if defined(OS_WIN)
  static bool reported =
      BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
                              base::Bind(&ReportFirewallStats));
  // TODO(vitalybuka): Switch to |ServiceDiscoveryClientMdns| after we find what
  // to do with firewall for user-level installs. crbug.com/366408
  return new ServiceDiscoveryClientUtility();
#endif  // OS_WIN
  return new ServiceDiscoveryClientMdns();
#endif
}

#else

scoped_refptr<ServiceDiscoverySharedClient>
    ServiceDiscoverySharedClient::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  NOTIMPLEMENTED();
  return NULL;
}

#endif  // ENABLE_MDNS

}  // namespace local_discovery
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/privacy_blacklist/blacklist_manager.h"

#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

void GetBlacklistHasMatchOnIOThread(const BlacklistManager* manager,
                                    const GURL& url,
                                    bool *has_match) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
  const Blacklist* blacklist = manager->GetCompiledBlacklist();
  scoped_ptr<Blacklist::Match> match(blacklist->findMatch(url));
  *has_match = (match.get() != NULL);
  ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
                         new MessageLoop::QuitTask());
}

}  // namespace

class BlacklistManagerBrowserTest : public ExtensionBrowserTest {
 public:
  virtual void SetUp() {
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnablePrivacyBlacklists);
    ExtensionBrowserTest::SetUp();
  }

  virtual void SetUpInProcessBrowserTestFixture() {
    ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();

    received_blacklist_notification_ = false;
    host_resolver()->AddSimulatedFailure("www.example.com");
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type != NotificationType::BLACKLIST_MANAGER_ERROR &&
        type != NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED) {
      ExtensionBrowserTest::Observe(type, source, details);
      return;
    }
    received_blacklist_notification_ = true;
    MessageLoop::current()->Quit();
  }

 protected:
  BlacklistManager* GetBlacklistManager() {
    return browser()->profile()->GetBlacklistManager();
  }

  bool GetAndResetReceivedBlacklistNotification() {
    bool result = received_blacklist_notification_;
    received_blacklist_notification_ = false;
    return result;
  }

  bool BlacklistHasMatch(const std::string& url) {
    bool has_match = false;
    ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
                           NewRunnableFunction(GetBlacklistHasMatchOnIOThread,
                                               GetBlacklistManager(),
                                               GURL(url),
                                               &has_match));
    ui_test_utils::RunMessageLoop();
    return has_match;
  }

 private:
  bool received_blacklist_notification_;
};

IN_PROC_BROWSER_TEST_F(BlacklistManagerBrowserTest, Basic) {
  static const char kTestUrl[] = "http://www.example.com/annoying_ads/ad.jpg";

  NotificationRegistrar registrar;
  registrar.Add(this,
                NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED,
                Source<Profile>(browser()->profile()));

  // Test loading an extension with blacklist.
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("common").AppendASCII("privacy_blacklist")));

  // Wait until the blacklist is loaded and ready.
  if (!GetAndResetReceivedBlacklistNotification())
    ui_test_utils::RunMessageLoop();

  // The blacklist should block our test URL.
  EXPECT_TRUE(BlacklistHasMatch(kTestUrl));

  // TODO(phajdan.jr): Verify that we really blocked the request etc.
  ui_test_utils::NavigateToURL(browser(), GURL(kTestUrl));
}
<commit_msg>Mark BlacklistManagerBrowserTest.Basic as flaky. BUG=29113<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/privacy_blacklist/blacklist_manager.h"

#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

void GetBlacklistHasMatchOnIOThread(const BlacklistManager* manager,
                                    const GURL& url,
                                    bool *has_match) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
  const Blacklist* blacklist = manager->GetCompiledBlacklist();
  scoped_ptr<Blacklist::Match> match(blacklist->findMatch(url));
  *has_match = (match.get() != NULL);
  ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
                         new MessageLoop::QuitTask());
}

}  // namespace

class BlacklistManagerBrowserTest : public ExtensionBrowserTest {
 public:
  virtual void SetUp() {
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnablePrivacyBlacklists);
    ExtensionBrowserTest::SetUp();
  }

  virtual void SetUpInProcessBrowserTestFixture() {
    ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();

    received_blacklist_notification_ = false;
    host_resolver()->AddSimulatedFailure("www.example.com");
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type != NotificationType::BLACKLIST_MANAGER_ERROR &&
        type != NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED) {
      ExtensionBrowserTest::Observe(type, source, details);
      return;
    }
    received_blacklist_notification_ = true;
    MessageLoop::current()->Quit();
  }

 protected:
  BlacklistManager* GetBlacklistManager() {
    return browser()->profile()->GetBlacklistManager();
  }

  bool GetAndResetReceivedBlacklistNotification() {
    bool result = received_blacklist_notification_;
    received_blacklist_notification_ = false;
    return result;
  }

  bool BlacklistHasMatch(const std::string& url) {
    bool has_match = false;
    ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
                           NewRunnableFunction(GetBlacklistHasMatchOnIOThread,
                                               GetBlacklistManager(),
                                               GURL(url),
                                               &has_match));
    ui_test_utils::RunMessageLoop();
    return has_match;
  }

 private:
  bool received_blacklist_notification_;
};

IN_PROC_BROWSER_TEST_F(BlacklistManagerBrowserTest, FLAKY_Basic) {
  static const char kTestUrl[] = "http://www.example.com/annoying_ads/ad.jpg";

  NotificationRegistrar registrar;
  registrar.Add(this,
                NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED,
                Source<Profile>(browser()->profile()));

  // Test loading an extension with blacklist.
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("common").AppendASCII("privacy_blacklist")));

  // Wait until the blacklist is loaded and ready.
  if (!GetAndResetReceivedBlacklistNotification())
    ui_test_utils::RunMessageLoop();

  // The blacklist should block our test URL.
  EXPECT_TRUE(BlacklistHasMatch(kTestUrl));

  // TODO(phajdan.jr): Verify that we really blocked the request etc.
  ui_test_utils::NavigateToURL(browser(), GURL(kTestUrl));
}
<|endoftext|>


<commit_before><commit_msg>coverity#707864 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>// JPetReader.cpp - Reader
#include "JPetReader.h"
#include <cassert>
#include "../JPetUserInfoStructure/JPetUserInfoStructure.h"

JPetReader::JPetReader() :
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(0),
  fCurrentEventNumber(-1)
{/**/}

JPetReader::JPetReader(const char* p_filename) :
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(0),
  fCurrentEventNumber(-1)
{
  if (!openFileAndLoadData(p_filename, "tree")) {
    ERROR("error in opening file");
  }
}

JPetReader::~JPetReader()
{
  if (fFile) {
    delete fFile;
    fFile = 0;
  }
}

JPetReader::MyEvent& JPetReader::getCurrentEvent()
{
  if (loadCurrentEvent()) {
    return *fEvent;
  } else {
    ERROR("Could not read the current event");
    if (fEvent) {
      delete fEvent;
    }
    fEvent = new TNamed("Empty event", "Empty event");
  }
  return *fEvent;
}

bool JPetReader::JPetReader::nextEvent()
{
  fCurrentEventNumber++;
  return loadCurrentEvent();
}

bool JPetReader::firstEvent()
{
  fCurrentEventNumber = 0;
  return loadCurrentEvent();
}

bool JPetReader::lastEvent()
{
  fCurrentEventNumber = getNbOfAllEvents() - 1;
  return loadCurrentEvent();
}

bool JPetReader::nthEvent(int n)
{
  fCurrentEventNumber = n;
  return loadCurrentEvent();
}

void JPetReader::closeFile ()
{
  if (fFile) delete fFile;
  fFile = 0;
  fBranch = 0;
  fEvent = 0;
  fTree = 0;
  fCurrentEventNumber = -1;
}

bool JPetReader::openFile (const char* filename)
{
  closeFile();
  fFile = new TFile(filename);
  if ((!isOpen()) || fFile->IsZombie()) {
    ERROR(std::string("Cannot open file:")+std::string(filename));
    return false;
  }
  return true;
}

bool JPetReader::loadData(const char* treename)
{

  if (!isOpen() ) {
    ERROR("File not open");
    return false;
  }
  if (!treename) {
    ERROR("empty tree name");
    return false;
  }
  fTree = static_cast<TTree*>(fFile->Get(treename));
  if (!fTree) {
    ERROR("in reading tree");
    return false;
  }
  TObjArray* arr = fTree->GetListOfBranches();
  fBranch = (TBranch*)(arr->At(0));
  if (!fBranch) {
    ERROR("in reading branch from tree");
    return false;
  }
  fBranch->SetAddress(&fEvent);
  firstEvent();
  return true;
}

/**
 * @brief Returns a copy of the header read from input file.
 *
 * Using a copy rather than direct pointer is essential as the original header belongs to JPetReader::fTree and would be deleted along with it.
 */
JPetTreeHeader* JPetReader::getHeaderClone() const
{
  if (!fTree) {
    ERROR("No tree available");
    return 0;
  }
  // get a pointer to a header wchich belongs to fTree
  JPetTreeHeader* header =  (JPetTreeHeader*)fTree->GetUserInfo()->At(JPetUserInfoStructure::kHeader);
  // return a COPY of this header
  return new JPetTreeHeader( *header );
}
<commit_msg>Reformatting JPetReader.cpp<commit_after>// JPetReader.cpp - Reader
#include "JPetReader.h"
#include <cassert>
#include "../JPetUserInfoStructure/JPetUserInfoStructure.h"

JPetReader::JPetReader() :
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(0),
  fCurrentEventNumber(-1)
{/**/}

JPetReader::JPetReader(const char* p_filename) :
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(0),
  fCurrentEventNumber(-1)
{
  if (!openFileAndLoadData(p_filename, "tree")) {
    ERROR("error in opening file");
  }
}

JPetReader::~JPetReader()
{
  if (fFile) {
    delete fFile;
    fFile = 0;
  }
}

JPetReader::MyEvent& JPetReader::getCurrentEvent()
{
  if (loadCurrentEvent()) {
    return *fEvent;
  } else {
    ERROR("Could not read the current event");
    if (fEvent) {
      delete fEvent;
    }
    fEvent = new TNamed("Empty event", "Empty event");
  }
  return *fEvent;
}

bool JPetReader::JPetReader::nextEvent()
{
  fCurrentEventNumber++;
  return loadCurrentEvent();
}

bool JPetReader::firstEvent()
{
  fCurrentEventNumber = 0;
  return loadCurrentEvent();
}

bool JPetReader::lastEvent()
{
  fCurrentEventNumber = getNbOfAllEvents() - 1;
  return loadCurrentEvent();
}

bool JPetReader::nthEvent(int n)
{
  fCurrentEventNumber = n;
  return loadCurrentEvent();
}

void JPetReader::closeFile ()
{
  if (fFile) delete fFile;
  fFile = 0;
  fBranch = 0;
  fEvent = 0;
  fTree = 0;
  fCurrentEventNumber = -1;
}

bool JPetReader::openFile (const char* filename)
{
  closeFile();
  fFile = new TFile(filename);
  if ((!isOpen()) || fFile->IsZombie()) {
    ERROR(std::string("Cannot open file:")+std::string(filename));
    return false;
  }
  return true;
}

bool JPetReader::loadData(const char* treename)
{
  if (!isOpen() ) {
    ERROR("File not open");
    return false;
  }
  if (!treename) {
    ERROR("empty tree name");
    return false;
  }
  fTree = static_cast<TTree*>(fFile->Get(treename));
  if (!fTree) {
    ERROR("in reading tree");
    return false;
  }
  TObjArray* arr = fTree->GetListOfBranches();
  fBranch = (TBranch*)(arr->At(0));
  if (!fBranch) {
    ERROR("in reading branch from tree");
    return false;
  }
  fBranch->SetAddress(&fEvent);
  firstEvent();
  return true;
}

/**
 * @brief Returns a copy of the header read from input file.
 *
 * Using a copy rather than direct pointer is essential as the original header belongs to JPetReader::fTree and would be deleted along with it.
 */
JPetTreeHeader* JPetReader::getHeaderClone() const
{
  if (!fTree) {
    ERROR("No tree available");
    return 0;
  }
  // get a pointer to a header wchich belongs to fTree
  JPetTreeHeader* header =  (JPetTreeHeader*)fTree->GetUserInfo()->At(JPetUserInfoStructure::kHeader);
  // return a COPY of this header
  return new JPetTreeHeader( *header );
}
<|endoftext|>