<commit_before>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   VoiceToolWidget.cpp
 *  @brief  Widget for voice communication control
 *
 */

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "VoiceToolWidget.h"
#include "CommunicationsService.h"
#include "VoiceStateWidget.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "UiProxyWidget.h"
#include "VoiceControllerWidget.h"
#include "VoiceUsersInfoWidget.h"

#include "DebugOperatorNew.h"

namespace CommUI
{
    VoiceToolWidget::VoiceToolWidget(Foundation::Framework* framework) :
        framework_(framework),
        voice_users_info_widget_(0),
        in_world_voice_session_(0),
        voice_state_widget_(0),
        voice_controller_widget_(0),
        voice_controller_proxy_widget_(0),
        channel_selection_(0)
    {
        setupUi(this);
        InitializeInWorldVoice();
    }

    VoiceToolWidget::~VoiceToolWidget()
    {
        UninitializeInWorldVoice();
    }

    void VoiceToolWidget::InitializeInWorldVoice()
    {
        if (framework_ &&  framework_->GetServiceManager())
        {
            Communications::ServiceInterface *communication_service = framework_->GetService<Communications::ServiceInterface>();
            if (communication_service)
                ConnectInWorldVoiceSession( communication_service->InWorldVoiceSession() );
        }
    }

    void VoiceToolWidget::ConnectInWorldVoiceSession(Communications::InWorldVoice::SessionInterface* session)
    {
        in_world_voice_session_ = session;
        if (!session)
            return;

        QObject::connect(in_world_voice_session_, SIGNAL(StartSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StopSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StateChanged(Communications::InWorldVoice::SessionInterface::State)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface*)) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantLeft(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(destroyed()), this, SLOT(UninitializeInWorldVoice()));
        QObject::connect(in_world_voice_session_, SIGNAL(SpeakerVoiceActivityChanged(double)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ActiceChannelChanged(QString)), this, SLOT(UpdateUI()));
        QObject::connect(in_world_voice_session_, SIGNAL(ChannelListChanged(QStringList)), this, SLOT(UpdateUI()));
    }

    void VoiceToolWidget::Minimize()
    {

    }

    void VoiceToolWidget::Maximize()
    {

    }

    void VoiceToolWidget::UpdateInWorldVoiceIndicator()
    {
        if (!in_world_voice_session_)
            return;

        if (in_world_voice_session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_users_info_widget_->hide();
            voice_state_widget_->hide();
            if (voice_controller_proxy_widget_)
                voice_controller_proxy_widget_->hide();
            return;
        }
        else
        {
            voice_users_info_widget_->show();
            voice_state_widget_->show();
            //if (voice_controller_proxy_widget_)
            //{
            //    voice_controller_proxy_widget_->show();
            //}
        }

        if (in_world_voice_session_->IsAudioSendingEnabled())
        {
            if (voice_state_widget_)
            {
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_ONLINE);
                voice_state_widget_->SetVoiceActivity(in_world_voice_session_->SpeakerVoiceActivity());
            }
        }
        else
        {
            if (voice_state_widget_)
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_OFFLINE);
        }

        if (voice_users_info_widget_)
        {
            double channel_voice_activity = 0;
            QList<Communications::InWorldVoice::ParticipantInterface*> list = in_world_voice_session_->Participants();
            foreach(Communications::InWorldVoice::ParticipantInterface* p, list)
            {
                if (p->IsSpeaking())
                {
                    channel_voice_activity = 1;
                    break;
                }
            }
            voice_users_info_widget_->SetVoiceActivity(channel_voice_activity);
            voice_users_info_widget_->SetUsersCount(in_world_voice_session_->Participants().count());
        }
    }

    void VoiceToolWidget::ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface* p)
    {
        connect(p, SIGNAL(StartSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
        connect(p, SIGNAL(StopSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
    }

    void VoiceToolWidget::UninitializeInWorldVoice()
    {
        if (voice_controller_proxy_widget_)
            framework_->UiService()->RemoveWidgetFromScene(voice_controller_proxy_widget_);
        if (voice_controller_widget_)
            SAFE_DELETE(voice_controller_widget_);
        in_world_voice_session_ = 0;
    }

    void VoiceToolWidget::ToggleVoiceControlWidget()
    {
        if (!in_world_voice_session_ || !voice_controller_proxy_widget_)
            return;

        if (voice_controller_proxy_widget_->isVisible())
            voice_controller_proxy_widget_->AnimatedHide();
        else
        {
            voice_controller_proxy_widget_->show();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END
        }
    }

    void VoiceToolWidget::UpdateUI()
    {
        QString channel = in_world_voice_session_->GetActiveChannel();

        if (!voice_state_widget_)
        {
            voice_state_widget_ = new VoiceStateWidget(0);
            connect(voice_state_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
            this->layout()->addWidget(voice_state_widget_);
            voice_state_widget_->show();
        }

        if (!voice_users_info_widget_)
        {
            voice_users_info_widget_ = new CommUI::VoiceUsersInfoWidget(0);
            connect(voice_users_info_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
            this->layout()->addWidget(voice_users_info_widget_);
        }
        voice_users_info_widget_->show();
        voice_users_info_widget_->updateGeometry();

        if (!channel_selection_)
        {
            channel_selection_ = new QComboBox();
            this->layout()->addWidget(channel_selection_);
        }

        disconnect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        channel_selection_->clear();
        channel_selection_->addItems(in_world_voice_session_->GetChannels());
        channel_selection_->addItems( QStringList() << ""); // no active channel
        channel_selection_->setCurrentIndex(channel_selection_->findText(in_world_voice_session_->GetActiveChannel()));
        channel_selection_->updateGeometry();
        connect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        this->update();

        if (voice_controller_widget_)
        {
            SAFE_DELETE(voice_controller_widget_);
            voice_controller_proxy_widget_ = 0; // automatically deleted by framework
        }
        if (in_world_voice_session_->GetState() == Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_controller_widget_ = new VoiceControllerWidget(in_world_voice_session_);
            voice_controller_proxy_widget_ = framework_->UiService()->AddWidgetToScene(voice_controller_widget_);
            voice_controller_proxy_widget_->setWindowTitle("In-world voice");
            voice_controller_proxy_widget_->hide();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END

            if (framework_)
            {
                /// @todo Make these configurable
                input_context_ = framework_->GetInput()->RegisterInputContext("CommunicationWidget", 90);
                connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_widget_, SLOT(SetPushToTalkOn()));
                connect(input_context_.get(), SIGNAL(MouseMiddleReleased(MouseEvent*)),voice_controller_widget_, SLOT(SetPushToTalkOff()));
                connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_widget_, SLOT(Toggle()));
            }
        }
        UpdateInWorldVoiceIndicator();
    }
} // CommUI
<commit_msg>Removed unnecessay lines.<commit_after>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   VoiceToolWidget.cpp
 *  @brief  Widget for voice communication control
 *
 */

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "VoiceToolWidget.h"
#include "CommunicationsService.h"
#include "VoiceStateWidget.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "UiProxyWidget.h"
#include "VoiceControllerWidget.h"
#include "VoiceUsersInfoWidget.h"

#include "DebugOperatorNew.h"

namespace CommUI
{
    VoiceToolWidget::VoiceToolWidget(Foundation::Framework* framework) :
        framework_(framework),
        voice_users_info_widget_(0),
        in_world_voice_session_(0),
        voice_state_widget_(0),
        voice_controller_widget_(0),
        voice_controller_proxy_widget_(0),
        channel_selection_(0)
    {
        setupUi(this);
        InitializeInWorldVoice();
    }

    VoiceToolWidget::~VoiceToolWidget()
    {
        UninitializeInWorldVoice();
    }

    void VoiceToolWidget::InitializeInWorldVoice()
    {
        if (framework_ &&  framework_->GetServiceManager())
        {
            Communications::ServiceInterface *communication_service = framework_->GetService<Communications::ServiceInterface>();
            if (communication_service)
                ConnectInWorldVoiceSession( communication_service->InWorldVoiceSession() );
        }
    }

    void VoiceToolWidget::ConnectInWorldVoiceSession(Communications::InWorldVoice::SessionInterface* session)
    {
        in_world_voice_session_ = session;
        if (!session)
            return;

        QObject::connect(in_world_voice_session_, SIGNAL(StartSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StopSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StateChanged(Communications::InWorldVoice::SessionInterface::State)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface*)) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantLeft(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(destroyed()), this, SLOT(UninitializeInWorldVoice()));
        QObject::connect(in_world_voice_session_, SIGNAL(SpeakerVoiceActivityChanged(double)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ActiceChannelChanged(QString)), this, SLOT(UpdateUI()));
        QObject::connect(in_world_voice_session_, SIGNAL(ChannelListChanged(QStringList)), this, SLOT(UpdateUI()));
    }

    void VoiceToolWidget::Minimize()
    {

    }

    void VoiceToolWidget::Maximize()
    {

    }

    void VoiceToolWidget::UpdateInWorldVoiceIndicator()
    {
        if (!in_world_voice_session_)
            return;

        if (in_world_voice_session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_users_info_widget_->hide();
            voice_state_widget_->hide();
            if (voice_controller_proxy_widget_)
                voice_controller_proxy_widget_->hide();
            return;
        }
        else
        {
            voice_users_info_widget_->show();
            voice_state_widget_->show();
        }

        if (in_world_voice_session_->IsAudioSendingEnabled())
        {
            if (voice_state_widget_)
            {
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_ONLINE);
                voice_state_widget_->SetVoiceActivity(in_world_voice_session_->SpeakerVoiceActivity());
            }
        }
        else
        {
            if (voice_state_widget_)
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_OFFLINE);
        }

        if (voice_users_info_widget_)
        {
            double channel_voice_activity = 0;
            QList<Communications::InWorldVoice::ParticipantInterface*> list = in_world_voice_session_->Participants();
            foreach(Communications::InWorldVoice::ParticipantInterface* p, list)
            {
                if (p->IsSpeaking())
                {
                    channel_voice_activity = 1;
                    break;
                }
            }
            voice_users_info_widget_->SetVoiceActivity(channel_voice_activity);
            voice_users_info_widget_->SetUsersCount(in_world_voice_session_->Participants().count());
        }
    }

    void VoiceToolWidget::ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface* p)
    {
        connect(p, SIGNAL(StartSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
        connect(p, SIGNAL(StopSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
    }

    void VoiceToolWidget::UninitializeInWorldVoice()
    {
        if (voice_controller_proxy_widget_)
            framework_->UiService()->RemoveWidgetFromScene(voice_controller_proxy_widget_);
        if (voice_controller_widget_)
            SAFE_DELETE(voice_controller_widget_);
        in_world_voice_session_ = 0;
    }

    void VoiceToolWidget::ToggleVoiceControlWidget()
    {
        if (!in_world_voice_session_ || !voice_controller_proxy_widget_)
            return;

        if (voice_controller_proxy_widget_->isVisible())
            voice_controller_proxy_widget_->AnimatedHide();
        else
        {
            voice_controller_proxy_widget_->show();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END
        }
    }

    void VoiceToolWidget::UpdateUI()
    {
        QString channel = in_world_voice_session_->GetActiveChannel();

        if (!voice_state_widget_)
        {
            voice_state_widget_ = new VoiceStateWidget(0);
            connect(voice_state_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
            this->layout()->addWidget(voice_state_widget_);
            voice_state_widget_->show();
        }

        if (!voice_users_info_widget_)
        {
            voice_users_info_widget_ = new CommUI::VoiceUsersInfoWidget(0);
            connect(voice_users_info_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
            this->layout()->addWidget(voice_users_info_widget_);
        }
        voice_users_info_widget_->show();
        voice_users_info_widget_->updateGeometry();

        if (!channel_selection_)
        {
            channel_selection_ = new QComboBox();
            this->layout()->addWidget(channel_selection_);
        }

        disconnect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        channel_selection_->clear();
        channel_selection_->addItems(in_world_voice_session_->GetChannels());
        channel_selection_->addItems( QStringList() << ""); // no active channel
        channel_selection_->setCurrentIndex(channel_selection_->findText(in_world_voice_session_->GetActiveChannel()));
        channel_selection_->updateGeometry();
        connect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        this->update();

        if (voice_controller_widget_)
        {
            SAFE_DELETE(voice_controller_widget_);
            voice_controller_proxy_widget_ = 0; // automatically deleted by framework
        }
        if (in_world_voice_session_->GetState() == Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_controller_widget_ = new VoiceControllerWidget(in_world_voice_session_);
            voice_controller_proxy_widget_ = framework_->UiService()->AddWidgetToScene(voice_controller_widget_);
            voice_controller_proxy_widget_->setWindowTitle("In-world voice");
            voice_controller_proxy_widget_->hide();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END

            if (framework_)
            {
                /// @todo Make these configurable
                input_context_ = framework_->GetInput()->RegisterInputContext("CommunicationWidget", 90);
                connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_widget_, SLOT(SetPushToTalkOn()));
                connect(input_context_.get(), SIGNAL(MouseMiddleReleased(MouseEvent*)),voice_controller_widget_, SLOT(SetPushToTalkOff()));
                connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_widget_, SLOT(Toggle()));
            }
        }
        UpdateInWorldVoiceIndicator();
    }
} // CommUI
<|endoftext|>


<commit_before>#ifndef ITER_ENUMERATE_H_
#define ITER_ENUMERATE_H_

#include "iterbase.hpp"

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

// enumerate functionality for python-style for-each enumerate loops
// for (auto e : enumerate(vec)) {
//     std::cout << e.index
//               << ": "
//               << e.element
//               << '\n';
// }

namespace iter {

    //Forward declarations of Enumerable and enumerate
    template <typename Container>
    class Enumerable;

    template <typename Container>
    Enumerable<Container> enumerate(Container&&);

    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T>);

    template <typename Container>
    class Enumerable {
        private:
            Container container;

            // The only thing allowed to directly instantiate an Enumerable is
            // the enumerate function
            friend Enumerable enumerate<Container>(Container&&);
            template <typename T>
            friend Enumerable<std::initializer_list<T>> enumerate(
                    std::initializer_list<T>);

            // for IterYield
            using BasePair = std::pair<std::size_t, iterator_deref<Container>>;

            // Value constructor for use only in the enumerate function
            Enumerable(Container&& container)
                : container(std::forward<Container>(container))
            { }

        public:
            // "yielded" by the Enumerable::Iterator.  Has a .index, and a
            // .element referencing the value yielded by the subiterator
            class IterYield : public BasePair {
                public:
                    using BasePair::BasePair;
                    decltype(BasePair::first)& index = BasePair::first;
                    decltype(BasePair::second)& element = BasePair::second;
            };

            //  Holds an iterator of the contained type and a size_t for the
            //  index.  Each call to ++ increments both of these data members.
            //  Each dereference returns an IterYield.
            class Iterator :
                public std::iterator<std::input_iterator_tag, IterYield>
            {
                private:
                    iterator_type<Container> sub_iter;
                    std::size_t index;
                public:
                    Iterator(iterator_type<Container>&& si)
                        : sub_iter{std::move(si)},
                        index{0}
                    { }

                    IterYield operator*() {
                        return {this->index, *this->sub_iter};
                    }

                    Iterator& operator++() {
                        ++this->sub_iter;
                        ++this->index;
                        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);
                    }
            };

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

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

    };

    template <typename Container>
    Enumerable<Container> enumerate(Container&& container) {
        return {std::forward<Container>(container)};
    }

    // for initializer lists.  copy constructs the list into the Enumerable
    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(
            std::initializer_list<T> il)
    {
        return {std::move(il)};
    }
}

#endif
<commit_msg>eliminates shadow warnings from enumerate<commit_after>#ifndef ITER_ENUMERATE_H_
#define ITER_ENUMERATE_H_

#include "iterbase.hpp"

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

// enumerate functionality for python-style for-each enumerate loops
// for (auto e : enumerate(vec)) {
//     std::cout << e.index
//               << ": "
//               << e.element
//               << '\n';
// }

namespace iter {

    //Forward declarations of Enumerable and enumerate
    template <typename Container>
    class Enumerable;

    template <typename Container>
    Enumerable<Container> enumerate(Container&&);

    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T>);

    template <typename Container>
    class Enumerable {
        private:
            Container container;

            // The only thing allowed to directly instantiate an Enumerable is
            // the enumerate function
            friend Enumerable enumerate<Container>(Container&&);
            template <typename T>
            friend Enumerable<std::initializer_list<T>> enumerate(
                    std::initializer_list<T>);

            // for IterYield
            using BasePair = std::pair<std::size_t, iterator_deref<Container>>;

            // Value constructor for use only in the enumerate function
            Enumerable(Container&& in_container)
                : container(std::forward<Container>(in_container))
            { }

        public:
            // "yielded" by the Enumerable::Iterator.  Has a .index, and a
            // .element referencing the value yielded by the subiterator
            class IterYield : public BasePair {
                public:
                    using BasePair::BasePair;
                    decltype(BasePair::first)& index = BasePair::first;
                    decltype(BasePair::second)& element = BasePair::second;
            };

            //  Holds an iterator of the contained type and a size_t for the
            //  index.  Each call to ++ increments both of these data members.
            //  Each dereference returns an IterYield.
            class Iterator :
                public std::iterator<std::input_iterator_tag, IterYield>
            {
                private:
                    iterator_type<Container> sub_iter;
                    std::size_t index;
                public:
                    Iterator(iterator_type<Container>&& si)
                        : sub_iter{std::move(si)},
                        index{0}
                    { }

                    IterYield operator*() {
                        return {this->index, *this->sub_iter};
                    }

                    Iterator& operator++() {
                        ++this->sub_iter;
                        ++this->index;
                        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);
                    }
            };

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

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

    };

    template <typename Container>
    Enumerable<Container> enumerate(Container&& container) {
        return {std::forward<Container>(container)};
    }

    // for initializer lists.  copy constructs the list into the Enumerable
    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(
            std::initializer_list<T> il)
    {
        return {std::move(il)};
    }
}

#endif
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/common/plat/pegasus/prdfP8ExExtraSig.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#ifndef __prdfP8ExExtraSig_H
#define __prdfP8ExExtraSig_H

#include <prdrSignatures.H>

PRDR_ERROR_SIGNATURE( P8EX_L2CE_LD_ISSUED, 0x0fff0000, "L2FIR[0]",
                      "L2 Cache Read CE, Line Delete Issued");
PRDR_ERROR_SIGNATURE( P8EX_L2CE_LD_FAILURE, 0x0fff0001, "L2FIR[0]",
                      "L2 Cache Read CE, Line Delete Failed");
PRDR_ERROR_SIGNATURE( P8EX_L2_ARRAY_REPAIR_COMPLETE, 0x0fff0002, "L2FIR[0]",
                      "L2 Array Repair Complete");
PRDR_ERROR_SIGNATURE( P8EX_L2_ARRAY_REPAIR_FAILURE, 0x0fff0003, "L2FIR[0]",
                      "L2 Array Repair Failure");
PRDR_ERROR_SIGNATURE( P8EX_L2_ARRAY_REPAIR_OUT_OF, 0x0fff0004, "L2FIR[0]",
                      "No L2 Array Repairs Left");

PRDR_ERROR_SIGNATURE( P8EX_L3CE_LD_ISSUED, 0x0fff0005, "L3FIR[4]",
                      "L3 Cache Read CE, Line Delete Issued");
PRDR_ERROR_SIGNATURE( P8EX_L3CE_LD_FAILURE, 0x0fff0006, "L3FIR[4]",
                      "L3 Cache Read CE, Line Delete Failed");
PRDR_ERROR_SIGNATURE( P8EX_L3_ARRAY_REPAIR_COMPLETE, 0x0fff0007, "L3FIR[4]",
                      "L3 Array Repair Complete");
PRDR_ERROR_SIGNATURE( P8EX_L3_ARRAY_REPAIR_FAILURE, 0x0fff0008, "L3FIR[4]",
                      "L3 Array Repair Failure");
PRDR_ERROR_SIGNATURE( P8EX_L3_ARRAY_REPAIR_OUT_OF, 0x0fff0009, "L3FIR[4]",
                      "No L3 Array Repairs Left");

#endif // __prdfP8ExExtraSig_H
<commit_msg>PRD: Making L2/L3 Column repair failures Predictive<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/common/plat/pegasus/prdfP8ExExtraSig.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#ifndef __prdfP8ExExtraSig_H
#define __prdfP8ExExtraSig_H

#include <prdrSignatures.H>

PRDR_ERROR_SIGNATURE( P8EX_L2CE_LD_ISSUED, 0x0fff0000, "L2FIR[0]",
                      "L2 Cache Read CE, Line Delete Issued");
PRDR_ERROR_SIGNATURE( P8EX_L2CE_LD_FAILURE, 0x0fff0001, "L2FIR[0]",
                      "L2 Cache Read CE, Line Delete Failed");
PRDR_ERROR_SIGNATURE( P8EX_L2_ARRAY_REPAIR_COMPLETE, 0x0fff0002, "L2FIR[0]",
                      "L2 Array Repair Complete");
PRDR_ERROR_SIGNATURE( P8EX_L2_ARRAY_REPAIR_FAILURE, 0x0fff0003, "L2FIR[0]",
                      "L2 Array Repair Failure");
PRDR_ERROR_SIGNATURE( P8EX_L2_ARRAY_REPAIR_OUT_OF, 0x0fff0004, "L2FIR[0]",
                      "No L2 Array Repairs Left");
PRDR_ERROR_SIGNATURE( P8EX_L2_ARRAY_REPAIR_HW_OUT_OF, 0x0fff000a, "L2FIR[0]",
                      "No L2 Array Repairs Left in HW");

PRDR_ERROR_SIGNATURE( P8EX_L3CE_LD_ISSUED, 0x0fff0005, "L3FIR[4]",
                      "L3 Cache Read CE, Line Delete Issued");
PRDR_ERROR_SIGNATURE( P8EX_L3CE_LD_FAILURE, 0x0fff0006, "L3FIR[4]",
                      "L3 Cache Read CE, Line Delete Failed");
PRDR_ERROR_SIGNATURE( P8EX_L3_ARRAY_REPAIR_COMPLETE, 0x0fff0007, "L3FIR[4]",
                      "L3 Array Repair Complete");
PRDR_ERROR_SIGNATURE( P8EX_L3_ARRAY_REPAIR_FAILURE, 0x0fff0008, "L3FIR[4]",
                      "L3 Array Repair Failure");
PRDR_ERROR_SIGNATURE( P8EX_L3_ARRAY_REPAIR_OUT_OF, 0x0fff0009, "L3FIR[4]",
                      "No L3 Array Repairs Left");
PRDR_ERROR_SIGNATURE( P8EX_L3_ARRAY_REPAIR_HW_OUT_OF, 0x0fff000b, "L3FIR[4]",
                      "No L3 Array Repairs Left in HW");

#endif // __prdfP8ExExtraSig_H
<|endoftext|>


<commit_before>// Solution to problem from Crack Coding interviews. Implement an
// algorithm to determine if a string has all unique characters
#include "check_unique_char.h"

CheckUniqueChar::CheckUniqueChar() {

}

CheckUniqueChar::~CheckUniqueChar() {

}

// Takes O(n) running time
bool CheckUniqueChar::solver_boolean(std::string test_string) {

}

// Takes O(nlogn) running time
bool CheckUniqueChar::solver_sorted(std::string test_string) {

}

bool CheckUniqueChar::test_case() {

}<commit_msg>Check for empty strings<commit_after>// Solution to problem from Crack Coding interviews. Implement an
// algorithm to determine if a string has all unique characters
#include "check_unique_char.h"

CheckUniqueChar::CheckUniqueChar() {

}

CheckUniqueChar::~CheckUniqueChar() {

}

// Takes O(n) running time
bool CheckUniqueChar::solver_boolean(std::string test_string) {
	if (test_string == "") {
		return false;
	}
}

// Takes O(nlogn) running time
bool CheckUniqueChar::solver_sorted(std::string test_string) {

}

bool CheckUniqueChar::test_case() {

}<|endoftext|>


<commit_before>#include "QtSqlLiteTest.h"
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTextCodec>
#include <QSqlTableModel>

QtSqlLiteTest::QtSqlLiteTest(QWidget *parent)
    : QWidget(parent)
{
    // 打开数据库
    if(createDB("/debug", "myDB.db"))
    {
        const QString createTablaSql = "create table if not exists logevent (id INTEGER PRIMARY KEY autoincrement, event varchar, msg varchar, volume int)";
        sqlQuery(createTablaSql);
    }

    // 初始化界面
    m_addDataBtn = new QPushButton("addData", this);
    m_eventLE = new QLineEdit("测试中文", this);
    m_msgLE = new QLineEdit("msg", this);
    m_volumeLE = new QLineEdit("100", this);

    QVBoxLayout *mainLayOut = new QVBoxLayout(this);

    QHBoxLayout *layout1 = new QHBoxLayout();
    layout1->addWidget(m_eventLE);
    layout1->addWidget(m_msgLE);
    layout1->addWidget(m_volumeLE);
    layout1->addWidget(m_addDataBtn);

    m_tableView = new QTableView(this);

    mainLayOut->addLayout(layout1);
    mainLayOut->addWidget(m_tableView);

    m_model = new QSqlTableModel(this);
    m_model->setTable("logevent");
    m_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    m_model->select();
    m_tableView->setModel(m_model);
    m_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    this->setLayout(mainLayOut);

    // 槽连接
    connect(m_addDataBtn, &QPushButton::clicked, this, &QtSqlLiteTest::addData);
}

void QtSqlLiteTest::addData()
{
    QString event = m_eventLE->text();
    QString msg = m_msgLE->text();
    QString volume = m_volumeLE->text();
//    QString addDataSql = "INSERT INTO logevent VALUES(NULL, '" + event + "', '" + msg + "', " + volume + ")";
//    sqlQuery(addDataSql);

    int rowNum = m_model->rowCount();//获得表的行数
    m_model->insertRow(rowNum); //添加一行
    m_model->setData(m_model->index(rowNum, 1), event);
    m_model->setData(m_model->index(rowNum, 2), msg);
    m_model->setData(m_model->index(rowNum, 3), volume);

    m_model->database().transaction(); //开始事务操作
    if (m_model->submitAll()) // 提交所有被修改的数据到数据库中
    {
        m_model->database().commit(); //提交成功，事务将真正修改数据库数据
    } else {
        m_model->database().rollback(); //提交失败，事务回滚
    }
}

QtSqlLiteTest::~QtSqlLiteTest()
{
    m_db.close();
}

bool QtSqlLiteTest::createDB(const QString dbFilePath, const QString dbFileName)
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(dbFileName);

    bool openRet = m_db.open();
    qDebug() << ((openRet) ? (dbFileName + " open sucees") : (dbFileName + " open fail, " + m_db.lastError().driverText()));

    return openRet;
}

bool QtSqlLiteTest::sqlQuery(const QString sql)
{
    QSqlQuery query;
    bool queryRet = query.exec(sql);
    if(!queryRet)
    {
        qDebug() << (sql + " query fail");
    }
    return queryRet;
}
<commit_msg>test select<commit_after>#include "QtSqlLiteTest.h"
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTextCodec>
#include <QSqlTableModel>
#include <QDir>

QtSqlLiteTest::QtSqlLiteTest(QWidget *parent)
    : QWidget(parent)
{
    // 打开数据库
    QString path = QDir::currentPath() + "/debug";
    if(createDB(path, "myDB.db"))
    {
        const QString createTablaSql = "create table if not exists logevent (id INTEGER PRIMARY KEY autoincrement, event varchar, msg varchar, volume int)";
        sqlQuery(createTablaSql);
    }

    // 初始化界面
    m_addDataBtn = new QPushButton("addData", this);
    m_eventLE = new QLineEdit("测试中文", this);
    m_msgLE = new QLineEdit("msg", this);
    m_volumeLE = new QLineEdit("100", this);

    QVBoxLayout *mainLayOut = new QVBoxLayout(this);

    QHBoxLayout *layout1 = new QHBoxLayout();
    layout1->addWidget(m_eventLE);
    layout1->addWidget(m_msgLE);
    layout1->addWidget(m_volumeLE);
    layout1->addWidget(m_addDataBtn);

    m_tableView = new QTableView(this);

    mainLayOut->addLayout(layout1);
    mainLayOut->addWidget(m_tableView);

    m_model = new QSqlTableModel(this);
    m_model->setTable("logevent");
    m_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
//    m_model->setFilter("event='测试中文'");
    m_model->select();
//    m_model->removeColumn(0);
    m_tableView->setModel(m_model);
    m_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    this->setLayout(mainLayOut);

    // 槽连接
    connect(m_addDataBtn, &QPushButton::clicked, this, &QtSqlLiteTest::addData);
}

void QtSqlLiteTest::addData()
{
    QString event = m_eventLE->text();
    QString msg = m_msgLE->text();
    QString volume = m_volumeLE->text();
//    QString addDataSql = "INSERT INTO logevent VALUES(NULL, '" + event + "', '" + msg + "', " + volume + ")";
//    sqlQuery(addDataSql);

    int rowNum = m_model->rowCount();//获得表的行数
    m_model->insertRow(rowNum); //添加一行
    m_model->setData(m_model->index(rowNum, 1), event);
    m_model->setData(m_model->index(rowNum, 2), msg);
    m_model->setData(m_model->index(rowNum, 3), volume);

    m_model->database().transaction(); //开始事务操作
    if (m_model->submitAll()) // 提交所有被修改的数据到数据库中
    {
        m_model->database().commit(); //提交成功，事务将真正修改数据库数据
    } else {
        m_model->database().rollback(); //提交失败，事务回滚
    }
}

QtSqlLiteTest::~QtSqlLiteTest()
{
    m_db.close();
}

bool QtSqlLiteTest::createDB(const QString dbFilePath, const QString dbFileName)
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(dbFilePath + "/" + dbFileName);

    bool openRet = m_db.open();
    qDebug() << ((openRet) ? (dbFileName + " open sucees") : (dbFileName + " open fail, " + m_db.lastError().driverText()));

    return openRet;
}

bool QtSqlLiteTest::sqlQuery(const QString sql)
{
    QSqlQuery query;
    bool queryRet = query.exec(sql);
    if(!queryRet)
    {
        qDebug() << (sql + " query fail");
    }
    return queryRet;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <typeinfo>

using namespace std;

class JsonNode {};

class JsonList : public JsonNode {
    public:
        vector<JsonNode> children;
};

class JsonNumber : public JsonNode {
    public:
        string value;
};

//JsonNode object(char * str);
JsonNode list(char * str);
//JsonNode string_f(char * str);
JsonNode number(char * str);
JsonNode root(char * str);

// JsonNode object(char * str){
//     JsonObject ret;
//     ret.content = str;
//     return ret;
// }

JsonNode list(char * str){
    JsonNode ret;
    JsonNode (*next_state)(char *);

    while(str[0] == ' ' || str[0] == '\n'){
        str++;
    }
    switch (str[0]){
        // case '{':
        //     next_state = &object;
        //     break;
        case '[':
            next_state = &list;
            break;
        // case '"':
        //     next_state = &string_f;
        //     break;
        default:
            next_state = &number;
            break;
    }
    str++;
    return next_state(str);
}

// JsonNode string_f(char * str){
//     JsonNode ret;
//     ret.type = "string";
//     ret.content = str;
//     return ret;
// }

JsonNode number(char * str){
    JsonNumber ret;
    ret = JsonNumber();
    ret.value = str[0];
    return ret;
}

JsonNode root(char * str){
    JsonNode (*next_state)(char *);
    while(str[0] == ' ' || str[0] == '\n'){
        str++;
    }
    switch (str[0]){
        // case '{':
        //     next_state = &object;
        //     break;
        case '[':
            next_state = &list;
            break;
        // case '"':
        //     next_state = &string_f;
        //     break;
        default:
            next_state = &number;
            break;
    }
    str++;
    return next_state(str);
}

int main(int argc, char *argv[]){
    char * str = "[8, 2]";
    cout << "OUTPUT" << "\n" << "==========" << "\n";
    JsonList b;
    JsonNode * a = &b;
    a = root(str);
    //cout << b << "\n";
    return 0;
}<commit_msg>[src/json] add drafts<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <typeinfo>

using namespace std;

class JsonNode {};

class JsonList : public JsonNode {
    public:
        vector<JsonNode> children;
};

class JsonNumber : public JsonNode {
    public:
        string value;
};

//JsonNode object(char * str);
JsonNode list(char * str);
//JsonNode string_f(char * str);
JsonNode number(char * str);
JsonNode root(char * str);

// JsonNode object(char * str){
//     JsonObject ret;
//     ret.content = str;
//     return ret;
// }

JsonNode list(char * str){
    JsonNode ret;
    JsonNode (*next_state)(char *);

    while(str[0] == ' ' || str[0] == '\n'){
        str++;
    }
    switch (str[0]){
        // case '{':
        //     next_state = &object;
        //     break;
        case '[':
            next_state = &list;
            break;
        // case '"':
        //     next_state = &string_f;
        //     break;
        default:
            next_state = &number;
            break;
    }
    str++;
    return next_state(str);
}

// JsonNode string_f(char * str){
//     JsonNode ret;
//     ret.type = "string";
//     ret.content = str;
//     return ret;
// }

JsonNode number(char * str){
    JsonNumber ret;
    ret = JsonNumber();
    ret.value = str[0];
    return ret;
}

JsonNode root(char * str){
    JsonNode (*next_state)(char *);
    while(str[0] == ' ' || str[0] == '\n'){
        str++;
    }
    switch (str[0]){
        // case '{':
        //     next_state = &object;
        //     break;
        case '[':
            next_state = &list;
            break;
        // case '"':
        //     next_state = &string_f;
        //     break;
        default:
            next_state = &number;
            break;
    }
    str++;
    return next_state(str);
}

int main(int argc, char *argv[]){
    char * str = "[8, 2]";
    cout << "OUTPUT" << "\n" << "==========" << "\n";
    JsonList b;
    JsonNode * a = &b;
    a = root(str);
    //cout << b << "\n";
    return 0;
}

char * findEnd(char type, char * str){
    return "";
}

class JsonToken {
    public:
        JsonToken(char * str);
        ~JsonToken();
        char type;
        std::vector<JsonToken*> children;
};

JsonToken::JsonToken(char * str) {
    for(char * i = str; i[0] != '\0'; i++) {
        switch (i[0]){
        case '{':
            type = '{';
            break;
        case '[':
            type = '[';
            break;
        case '"':
            type = '"';
            break;
        default:
            cout << "fail: " << i[0] << "\n";
            break;
        }
        children.push_back(new JsonToken(findEnd(type, i)));
    }
}

JsonToken::~JsonToken() {
    for(int i = 0; i < children.size(); i++){
        delete children.at(i);
    }
}

/*
TOKENS

/^,$/, 'comma'
/^:$/, 'end-label'
/^\{$/, 'begin-object'
/^\}$/, 'end-object'
/^\[$/, 'begin-array'
/^\]$/, 'end-array'
/^"(\\["\\/bfnrtu"]|[^"\\"])*"$/, 'string'
/^"([^"]|\\")*$/, 'maybe-string'
/^null$/, 'null'
/^(true|false)$/, 'boolean'
/^-?\d+(\.\d+)?([eE]-?\d+)?$/, 'number'
/^-?\d+\.$/, 'maybe-decimal-number'
/^-$/, 'maybe-negative-number'
/^\w+$/, 'symbol'

TESTS :

{
    "name": "Juventus Milan",
    "money": 10000,
    "players": [
        {
            "name": "ballotelli",
            "inventory":[
                {
                    "type": "balais",
                    "speed": 1000
                }
            ],
        },
                {
            "name": "chabal",
            "inventory":[
                {
                    "type": "potion",
                    "puissance": 10
                }
            ],
        }
    ]
}

*/<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <typeinfo>
#include <exception>

#include "json.h"

using namespace std;

int skip_whitespace(string message, int start){
    int ret = 0;
    while(start + ret  < message.length()){
        switch(message[start + ret]){
            case '\n':
            case '\t':
            case '\r':
            case ' ':
                break;
            default:
                return ret;
        }
        ret++;
    }
    throw "a";
}

string cut_from(string message, int from){
    return message.substr(from, message.length());
}

JsonDict::JsonDict(){}

void JsonDict::add(JsonString key, JsonValue * value){
    dict[(string) key] = value;
}

JsonList::JsonList(){}

void JsonList::add(JsonValue * value){
    content.push_back(value);
}

JsonString::JsonString(){}

JsonString::JsonString(string val){
    value = val;
}

JsonString::operator std::string() const{
    return value;
}

JsonString JsonString::operator=(const JsonString &str){
    value = str.value;
    return *this;
}

JsonValue * createNumber(string message, int &i){
    return new JsonValue();
}

JsonValue * createValue(string message, int &i){
    int bak = i;
    i = 0;
    string s;
    while(i < message.length()){
        i += skip_whitespace(message, i);
        switch(message[i]){
            case '{':
                s = cut_from(message, i + 1 );
                i = bak;
                return createDict(s, i);
                break;
            case '[':
                s = cut_from(message, i + 1 );
                i = bak;
                return createList(s, i);
                break;
            case '"':
                s = cut_from(message, i + 1 );
                i = bak;
                return createString(s, i);
                break;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return createNumber(cut_from(message, i), i);
                break;
            default:
                throw 1;
        }
    }
    throw 1;
}

JsonDict * createDict(string message, int &i){
    JsonDict * r = new JsonDict();
    i = 0;
    while(1){
        JsonString * key;
        JsonValue * value;
        bool colon = false;
        bool coma = false;
        bool gotkey = false;
        while(i < message.length()){
            i += skip_whitespace(message, i);
            switch(message[i]){
                case '"':
                    key = createString(cut_from(message, i + 1 ), i);
                    gotkey = true;
                    break;
                case '}':
                    i++;
                    return r;
                    break;
                default:
                    throw 1;
            }
            if(gotkey){
                break;
            }
            i++;
        }
        i++;
        while(i < message.length() && !colon){
            i += skip_whitespace(message, i);
            switch(message[i]){
                case ':':
                    colon = true;
                    break;
                default:
                    throw 1;
            }
            i++;
        }

        i += skip_whitespace(message, i);

        value = createValue(cut_from(message, i), i);
        i++;
        r->add(*key, value);
        while(i < message.length() && !coma){
            i += skip_whitespace(message, i);
            switch(message[i]){
                case ',':
                    coma = true;
                    break;
                case '}':
                    i++;
                    return r;
                    break;
                default:
                    throw 1;
            }
            i++;
        }
    }
}

JsonList * createList(string message, int &i){
    JsonList * r = new JsonList();
    i = 0;
    while(1){
        JsonValue * value;
        i += skip_whitespace(message, i);
        value = createValue(cut_from(message, i), i);
        i++;
        r->add(value);
        i += skip_whitespace(message, i);
        switch(message[i]){
            case ',':
                i++;
                break;
            case ']':
                i++;
                return r;
                break;
            default:
                throw 1;
        }
    }
}

JsonString * createString(string message, int &i){
    int bak = i;
    i = 0;
    while(i < message.length()){
        switch(message[i]){
        case '\\':
            i++;
            break;
        case '"':
            i++;
            string s = message.substr(0, i - 1);
            i += bak;
            return new JsonString(s);
            break;
        }
    i++;
    }
    throw 1;
}

int main(){
    int i = 0;
    JsonValue * val = createValue("[\"elem 1 \"    ,\n \"elem2\"]", i);
    JsonList* listptr = dynamic_cast<JsonList*>(val);
    JsonValue * one = listptr->content.at(1);
    JsonString * strptr = dynamic_cast<JsonString*>(one);
    cout << strptr->value << endl;
    return 0;
}

// Dict
// -----------
// int main(){
//     int i = 0;
//     JsonValue * val = createValue("{\"cle1\" :   \"val1\"   , \"cle2\" : \"val2\" ,  \"cle3\":\"val3\",\"cle3\":\"val3bis\"}", i);
//     JsonDict* strptr = dynamic_cast<JsonDict*>(val);
//     cout << "Len=" << strptr->dict.size() << endl;
//     JsonValue * c = strptr->dict["cle3"];
//     JsonString * cstr = dynamic_cast<JsonString*>(c);
//     cout << cstr->value << endl;
//     return 0;
// }<commit_msg>[code/json] refactoring<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <typeinfo>
#include <exception>

#include "json.h"

using namespace std;

int skip_whitespace(string message, int start){
    int ret = 0;
    while(start + ret < message.length()){
        switch(message[start + ret]){
            case '\n':
            case '\t':
            case '\r':
            case ' ':
                break;
            default:
                return ret;
        }
        ret++;
    }
    throw "a";
}

int skip_colon(string message, int start){
    int ret;
    bool colon = false;

    ret = skip_whitespace(message, start);
    while(start + ret < message.length() && !colon){
        switch(message[start + ret]){
            case ':':
                colon = true;
                break;
            default:
                throw 1;
        }
        ret++;
    }
    ret += skip_whitespace(message, start + ret);
    return ret;
}

string cut_from(string message, int from){
    return message.substr(from, message.length());
}

JsonDict::JsonDict(){}

void JsonDict::add(JsonString key, JsonValue * value){
    dict[(string) key] = value;
}

JsonList::JsonList(){}

void JsonList::add(JsonValue * value){
    content.push_back(value);
}

JsonString::JsonString(){}

JsonString::JsonString(string val){
    value = val;
}

JsonString::operator std::string() const{
    return value;
}

JsonString JsonString::operator=(const JsonString &str){
    value = str.value;
    return *this;
}

JsonValue * createNumber(string message, int &i){
    return new JsonValue();
}

JsonValue * createValue(string message, int &i){
    int bak = i;
    i = 0;
    string s;
    while(i < message.length()){
        i += skip_whitespace(message, i);
        switch(message[i]){
            case '{':
                s = cut_from(message, i + 1 );
                i = bak;
                return createDict(s, i);
                break;
            case '[':
                s = cut_from(message, i + 1 );
                i = bak;
                return createList(s, i);
                break;
            case '"':
                s = cut_from(message, i + 1 );
                i = bak;
                return createString(s, i);
                break;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return createNumber(cut_from(message, i), i);
                break;
            default:
                throw 1;
        }
    }
    throw 1;
}

JsonDict * createDict(string message, int &i){
    JsonString * key;
    JsonValue * value;
    bool colon = false;
    bool coma = false;

    JsonDict * r = new JsonDict();
    i = skip_whitespace(message, 0);

    while(1){
        if(message[i] == '}'){
            i++;
            return r;
        }
        i += skip_whitespace(message, i);
        key = createString(cut_from(message, i + 1 ), i);
        i++;
        i += skip_colon(message, i);
        value = createValue(cut_from(message, i), i);
        i++;
        r->add(*key, value);
        i += skip_whitespace(message, i);
        if(message[i] == ','){
            i++;
        }
    }
}

JsonList * createList(string message, int &i){
    JsonList * r = new JsonList();
    i = 0;
    while(1){
        JsonValue * value;
        i += skip_whitespace(message, i);
        value = createValue(cut_from(message, i), i);
        i++;
        r->add(value);
        i += skip_whitespace(message, i);
        switch(message[i]){
            case ',':
                i++;
                break;
            case ']':
                i++;
                return r;
                break;
            default:
                throw 1;
        }
    }
}

JsonString * createString(string message, int &i){
    int bak = i;
    i = 0;
    while(i < message.length()){
        switch(message[i]){
        case '\\':
            i++;
            break;
        case '"':
            i++;
            string s = message.substr(0, i - 1);
            i += bak;
            return new JsonString(s);
            break;
        }
    i++;
    }
    throw 1;
}

// List
// -----------
int listmain(){
    int i = 0;
    JsonValue * val = createValue("[\"elem 1 \"    ,\n \"elem2\"]", i);
    JsonList* listptr = dynamic_cast<JsonList*>(val);
    JsonValue * one = listptr->content.at(1);
    JsonString * strptr = dynamic_cast<JsonString*>(one);
    cout << strptr->value << endl;
    return 0;
}

// Dict
// -----------
int dictmain(){
    int i = 0;
    JsonValue * val = createValue("{\"cle1\" :   \"val1\"   , \"cle2\" : \"val2\" ,  \"cle3\":\"val3\",\"cle3\":\"val3bis\"}", i);
    JsonDict* strptr = dynamic_cast<JsonDict*>(val);
    cout << "Len=" << strptr->dict.size() << endl;
    JsonValue * c = strptr->dict["cle3"];
    JsonString * cstr = dynamic_cast<JsonString*>(c);
    cout << cstr->value << endl;
    return 0;
}

int main(){
    listmain();
    cout << "------------" << endl;
    return dictmain();
}<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "app/gfx/gl/gl_implementation.h"

#include <algorithm>
#include <string>

#include "app/app_switches.h"
#include "base/at_exit.h"
#include "base/command_line.h"

namespace gfx {
namespace {
struct NamePair {
  std::wstring name;
  GLImplementation implemention;
};

typedef std::vector<base::NativeLibrary> LibraryArray;

GLImplementation g_gl_implementation = kGLImplementationNone;
LibraryArray* g_libraries;
GLGetProcAddressProc g_get_proc_address;

void CleanupNativeLibraries(void* unused) {
  if (g_libraries) {
    for (LibraryArray::iterator it = g_libraries->begin();
         it != g_libraries->end(); ++it) {
      base::UnloadNativeLibrary(*it);
    }
    delete g_libraries;
    g_libraries = NULL;
  }
}
}

GLImplementation GetNamedGLImplementation(const std::wstring& name) {
  static const NamePair name_pairs[] = {
    { L"desktop", kGLImplementationDesktopGL },
    { L"osmesa", kGLImplementationOSMesaGL },
    { L"egl", kGLImplementationEGLGLES2 },
    { L"mock", kGLImplementationMockGL }
  };

  for (size_t i = 0; i < arraysize(name_pairs); ++i) {
    if (name == name_pairs[i].name)
      return name_pairs[i].implemention;
  }

  return kGLImplementationNone;
}

bool InitializeBestGLBindings(
    const GLImplementation* allowed_implementations_begin,
    const GLImplementation* allowed_implementations_end) {
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseGL)) {
    std::wstring requested_implementation_name =
        CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kUseGL);
    GLImplementation requested_implementation =
        GetNamedGLImplementation(requested_implementation_name);
    if (std::find(allowed_implementations_begin,
                  allowed_implementations_end,
                  requested_implementation) == allowed_implementations_end) {
      LOG(ERROR) << "Requested GL implementation is not allowed.";
      return false;
    }

    if (InitializeGLBindings(requested_implementation))
      return true;
  } else {
    for (const GLImplementation* p = allowed_implementations_begin;
         p < allowed_implementations_end;
         ++p) {
      if (InitializeGLBindings(*p))
        return true;
    }
  }

  LOG(ERROR) << "Could not initialize GL.";
  return false;
}

void SetGLImplementation(GLImplementation implementation) {
  g_gl_implementation = implementation;
}

GLImplementation GetGLImplementation() {
  return g_gl_implementation;
}

void AddGLNativeLibrary(base::NativeLibrary library) {
  DCHECK(library);

  if (!g_libraries) {
    g_libraries = new LibraryArray;
    base::AtExitManager::RegisterCallback(CleanupNativeLibraries, NULL);
  }

  g_libraries->push_back(library);
}

void SetGLGetProcAddressProc(GLGetProcAddressProc proc) {
  DCHECK(proc);
  g_get_proc_address = proc;
}

void* GetGLProcAddress(const char* name) {
  DCHECK(g_gl_implementation != kGLImplementationNone);

  if (g_get_proc_address) {
    void* proc = g_get_proc_address(name);
    if (proc)
      return proc;
  }

  if (g_libraries) {
    for (size_t i = 0; i < g_libraries->size(); ++i) {
      void* proc = base::GetFunctionPointerFromNativeLibrary((*g_libraries)[i],
                                                             name);
      if (proc)
        return proc;
    }
  }

  return NULL;
}

}  // namespace gfx
<commit_msg>De-wstringify gl_implementation.cc.<commit_after>// Copyright (c) 2010 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 "app/gfx/gl/gl_implementation.h"

#include <algorithm>
#include <string>

#include "app/app_switches.h"
#include "base/at_exit.h"
#include "base/command_line.h"

namespace gfx {
namespace {

typedef std::vector<base::NativeLibrary> LibraryArray;

GLImplementation g_gl_implementation = kGLImplementationNone;
LibraryArray* g_libraries;
GLGetProcAddressProc g_get_proc_address;

void CleanupNativeLibraries(void* unused) {
  if (g_libraries) {
    for (LibraryArray::iterator it = g_libraries->begin();
         it != g_libraries->end(); ++it) {
      base::UnloadNativeLibrary(*it);
    }
    delete g_libraries;
    g_libraries = NULL;
  }
}
}

GLImplementation GetNamedGLImplementation(const std::string& name) {
  static const struct {
    const char* name;
    GLImplementation implemention;
  } name_pairs[] = {
    { "desktop", kGLImplementationDesktopGL },
    { "osmesa", kGLImplementationOSMesaGL },
    { "egl", kGLImplementationEGLGLES2 },
    { "mock", kGLImplementationMockGL }
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(name_pairs); ++i) {
    if (name == name_pairs[i].name)
      return name_pairs[i].implemention;
  }

  return kGLImplementationNone;
}

bool InitializeBestGLBindings(
    const GLImplementation* allowed_implementations_begin,
    const GLImplementation* allowed_implementations_end) {
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseGL)) {
    std::string requested_implementation_name =
        CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL);
    GLImplementation requested_implementation =
        GetNamedGLImplementation(requested_implementation_name);
    if (std::find(allowed_implementations_begin,
                  allowed_implementations_end,
                  requested_implementation) == allowed_implementations_end) {
      LOG(ERROR) << "Requested GL implementation is not allowed.";
      return false;
    }

    if (InitializeGLBindings(requested_implementation))
      return true;
  } else {
    for (const GLImplementation* p = allowed_implementations_begin;
         p < allowed_implementations_end;
         ++p) {
      if (InitializeGLBindings(*p))
        return true;
    }
  }

  LOG(ERROR) << "Could not initialize GL.";
  return false;
}

void SetGLImplementation(GLImplementation implementation) {
  g_gl_implementation = implementation;
}

GLImplementation GetGLImplementation() {
  return g_gl_implementation;
}

void AddGLNativeLibrary(base::NativeLibrary library) {
  DCHECK(library);

  if (!g_libraries) {
    g_libraries = new LibraryArray;
    base::AtExitManager::RegisterCallback(CleanupNativeLibraries, NULL);
  }

  g_libraries->push_back(library);
}

void SetGLGetProcAddressProc(GLGetProcAddressProc proc) {
  DCHECK(proc);
  g_get_proc_address = proc;
}

void* GetGLProcAddress(const char* name) {
  DCHECK(g_gl_implementation != kGLImplementationNone);

  if (g_get_proc_address) {
    void* proc = g_get_proc_address(name);
    if (proc)
      return proc;
  }

  if (g_libraries) {
    for (size_t i = 0; i < g_libraries->size(); ++i) {
      void* proc = base::GetFunctionPointerFromNativeLibrary((*g_libraries)[i],
                                                             name);
      if (proc)
        return proc;
    }
  }

  return NULL;
}

}  // namespace gfx
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <tuple>

#include "acmacs-base/argv.hh"
#include "acmacs-base/filesystem.hh"
#include "acmacs-base/named-type.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"

// ----------------------------------------------------------------------

// using namespace acmacs::argv;

// struct Options : public argv
// {
//     Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

//     argument<str> period{*this, arg_name{"monthly|yearly|weekly"}, mandatory};
//     argument<Date> start{*this, arg_name{"start-date"}, mandatory};
//     argument<Date> end{*this, arg_name{"end-date"}, mandatory};
//     argument<str> output{*this, arg_name{"output.json"}, dflt{""}};
// };

// ----------------------------------------------------------------------

inline bool is_acmacs_file(const fs::path& path)
{
    if (path.extension() == ".ace")
        return true;
    if (path.extension() == ".bz2") {
        if (path.stem().extension() == ".acd1")
            return true;
    }
    return false;
}

// ----------------------------------------------------------------------

class SerumIds
{
 public:
    using Name = acmacs::chart::Name;
    using Passage = acmacs::chart::Passage;
    using Reassortant = acmacs::chart::Reassortant;
    using Annotations = acmacs::chart::Annotations;
    using SerumId = acmacs::chart::SerumId;
    using SerumIdRoot = acmacs::named_t<std::string, struct SerumIdRootTag>;
    using SerumEntry = std::tuple<Name, Reassortant, Annotations, SerumId, Passage>;
    using TableEntry = std::tuple<acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate>;
    using Entry = std::tuple<SerumIdRoot, SerumId, Name, Reassortant, Annotations, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate, Passage>;

    SerumIds() = default;

    constexpr size_t size() const { return data_.size(); }
    void sort() { std::sort(data_.begin(), data_.end()); /* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); */ }

    void add(const SerumEntry& serum, const TableEntry& table)
        {
            data_.emplace_back(serum_id_root(serum, table), std::get<SerumId>(serum),
                               std::get<Name>(serum), std::get<Reassortant>(serum), std::get<Annotations>(serum),
                               std::get<acmacs::chart::Lab>(table), std::get<acmacs::chart::Assay>(table), std::get<acmacs::chart::RbcSpecies>(table), std::get<acmacs::chart::TableDate>(table),
                               std::get<Passage>(serum));
        }

    void print() const
        {
            for (const auto& entry : data_)
                std::cout << std::get<SerumIdRoot>(entry) << ' ' << std::get<SerumId>(entry) << ' ' << std::get<Name>(entry) << ' ' << std::get<acmacs::chart::TableDate>(entry) << '\n';
        }

 private:
    std::vector<Entry> data_;

    SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const
        {
            const auto& serum_id = std::get<SerumId>(serum);
            if (std::get<acmacs::chart::Lab>(table) == "MELB") {
                if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R') && serum_id[5] == '-' && serum_id.back() == 'D')
                    return SerumIdRoot(serum_id.substr(0, 5));
                else
                    return SerumIdRoot(serum_id);
            }
            else
                return SerumIdRoot(serum_id);
        }

};

// ----------------------------------------------------------------------

int main(int /*argc*/, const char* /*argv*/[])
{
    int exit_code = 0;
    try {
        // Options opt(argc, argv);
        SerumIds serum_ids;
        size_t charts_processed = 0;
        for (auto& entry : fs::directory_iterator(".")) {
            if (entry.is_regular_file() && is_acmacs_file(entry.path())) {
                // std::cout << entry.path() << '\n';
                auto chart = acmacs::chart::import_from_file(entry.path());
                std::tuple table(chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());
                auto sera = chart->sera();
                for (auto serum : *sera)
                    serum_ids.add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);
                  // name_id.emplace_back(serum->designation_without_serum_id(), serum->serum_id(), date);
                ++charts_processed;
            }
        }
        std::cout << charts_processed << " charts processed\n";
        std::cout << serum_ids.size() << " entries\n";
        serum_ids.sort();
          // std::cout << serum_ids.size() << " entries\n";
        serum_ids.print();

        // std::vector<std::pair<std::string, std::vector<std::string>>> name_ids;
        // for (const auto& entry : name_id) {
        //     if (name_ids.empty() || name_ids.back().first != entry.first)
        //         name_ids.emplace_back(entry.first, std::vector<std::string>{entry.second});
        //     else
        //         name_ids.back().second.push_back(entry.second);
        // }
        // std::cout << name_ids.size() << " serum names found\n";

        // for (const auto& entry : name_ids) {
        //     std::cout << entry.first << '\n';
        //     for (const auto& serum_id : entry.second) {
        //         std::cout << "  " << serum_id;
        //         if (serum_id[0] == 'F' || serum_id[0] == 'R') {
        //             if (serum_id.back() != 'D')
        //                 std::cout << "  Warning: FIX!";
        //         }
        //         else
        //             std::cout << "  Warning: not MELB";
        //         std::cout << '\n';
        //     }
        // }
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>scan serum ids of MELB tables<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <tuple>

#include "acmacs-base/argv.hh"
#include "acmacs-base/filesystem.hh"
#include "acmacs-base/named-type.hh"
#include "acmacs-base/string.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart.hh"

// ----------------------------------------------------------------------

// using namespace acmacs::argv;

// struct Options : public argv
// {
//     Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

//     argument<str> period{*this, arg_name{"monthly|yearly|weekly"}, mandatory};
//     argument<Date> start{*this, arg_name{"start-date"}, mandatory};
//     argument<Date> end{*this, arg_name{"end-date"}, mandatory};
//     argument<str> output{*this, arg_name{"output.json"}, dflt{""}};
// };

// ----------------------------------------------------------------------

inline bool is_acmacs_file(const fs::path& path)
{
    if (path.extension() == ".ace")
        return true;
    if (path.extension() == ".bz2") {
        if (path.stem().extension() == ".acd1")
            return true;
    }
    return false;
}

// ----------------------------------------------------------------------

class SerumIds
{
 public:
    using Name = acmacs::chart::Name;
    using Passage = acmacs::chart::Passage;
    using Reassortant = acmacs::chart::Reassortant;
    using Annotations = acmacs::chart::Annotations;
    using SerumId = acmacs::chart::SerumId;
    using SerumIdRoot = acmacs::named_t<std::string, struct SerumIdRootTag>;
    using SerumEntry = std::tuple<Name, Reassortant, Annotations, SerumId, Passage>;
    using TableEntry = std::tuple<acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate>;
    using Entry = std::tuple<SerumIdRoot, SerumId, Name, Reassortant, Annotations, acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate, Passage>;
    using Entries = std::vector<Entry>;
    using EntryPtr = typename Entries::const_iterator;
    using PerSerumIdEntry = std::tuple<EntryPtr, EntryPtr>;
    using PerSerumIdRootEntry = std::tuple<EntryPtr, EntryPtr, std::vector<PerSerumIdEntry>>;
    using PerSerumIdRootEntries = std::vector<PerSerumIdRootEntry>;

    SerumIds() = default;

    size_t size() const { return data_.size(); }
    void sort() { std::sort(data_.begin(), data_.end()); /* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); */ }

    void add(const SerumEntry& serum, const TableEntry& table)
        {
            data_.emplace_back(serum_id_root(serum, table), std::get<SerumId>(serum),
                               std::get<Name>(serum), std::get<Reassortant>(serum), std::get<Annotations>(serum),
                               std::get<acmacs::chart::VirusType>(table), std::get<acmacs::chart::Lab>(table), std::get<acmacs::chart::Assay>(table), std::get<acmacs::chart::RbcSpecies>(table), std::get<acmacs::chart::TableDate>(table),
                               std::get<Passage>(serum));
        }

    void scan()
        {
            for (EntryPtr entry_ptr = data_.begin(); entry_ptr != data_.end(); ++entry_ptr) {
                if (per_root_.empty() || std::get<SerumIdRoot>(*entry_ptr) !=  std::get<SerumIdRoot>(*std::get<0>(per_root_.back()))) {
                    per_root_.emplace_back(entry_ptr, entry_ptr + 1, std::vector<PerSerumIdEntry>{{entry_ptr, entry_ptr + 1}});
                }
                else {
                    std::get<1>(per_root_.back()) = entry_ptr + 1;
                    const auto last = std::get<0>(std::get<2>(per_root_.back()).back());
                    const auto name = make_name(entry_ptr), name_last = make_name(last);
                    if (std::get<SerumId>(*entry_ptr) != std::get<SerumId>(*last) || name != name_last) {
                        std::get<2>(per_root_.back()).emplace_back(entry_ptr, entry_ptr + 1);
                    }
                    else {
                        std::get<1>(std::get<2>(per_root_.back()).back()) = entry_ptr + 1;
                    }
                }
            }
            std::cout << "per_root_ " << per_root_.size() << '\n';
        }

        void print(bool print_good) const
        {
            // for (const auto& entry : data_)
            //     std::cout << std::get<SerumIdRoot>(entry) << ' ' << std::get<SerumId>(entry) << ' ' << std::get<Name>(entry) << ' ' << std::get<acmacs::chart::TableDate>(entry) << '\n';

            const bool show_assay = std::get<acmacs::chart::VirusType>(*std::get<0>(per_root_.front())) == "A(H3N2)";
            const bool show_rbc = show_assay;
            for (const auto& per_root_entry : per_root_) {
                const auto name = make_name(std::get<0>(per_root_entry)), name_last = make_name(std::get<1>(per_root_entry) - 1);
                if (const bool good = std::get<2>(per_root_entry).size() == 1; !good || print_good) {
                    std::cout << std::get<SerumIdRoot>(*std::get<0>(per_root_entry)) << ' ' << (std::get<1>(per_root_entry) - std::get<0>(per_root_entry)) << '\n';
                    for (const auto& per_serum_id_entry : std::get<2>(per_root_entry)) {
                        const auto tabs = tables(std::get<0>(per_serum_id_entry), std::get<1>(per_serum_id_entry), show_assay, show_rbc);
                        std::cout << "    " << std::get<SerumId>(*std::get<0>(per_serum_id_entry)) << ' ' << tabs.size()
                                  << " [" << make_name(std::get<0>(per_serum_id_entry)) << ']';
                        for (const auto& table : tabs)
                            std::cout << ' ' << table;
                        std::cout << '\n';
                    }
                }
            }
        }

 private:
    Entries data_;
    PerSerumIdRootEntries per_root_;

    SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const
        {
            const auto& serum_id = std::get<SerumId>(serum);
            if (std::get<acmacs::chart::Lab>(table) == "MELB") {
                if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R') && serum_id[5] == '-' && serum_id.back() == 'D')
                    return SerumIdRoot(serum_id.substr(0, 5));
                else
                    return SerumIdRoot(serum_id);
            }
            else
                return SerumIdRoot(serum_id);
        }

    static inline std::string make_name(EntryPtr ptr)
        {
            return string::join({std::get<Name>(*ptr), std::get<Reassortant>(*ptr), string::join(" ", std::get<Annotations>(*ptr))});
        }

    static inline std::vector<std::string> tables(EntryPtr first, EntryPtr last, bool assay, bool rbc)
    {
        std::vector<std::string> tables(static_cast<size_t>(last - first));
        std::transform(first, last, tables.begin(), [assay, rbc](const auto& entry) {
            std::vector<std::string> fields;
            if (assay)
                fields.push_back(std::get<acmacs::chart::Assay>(entry));
            if (rbc)
                fields.push_back(std::get<acmacs::chart::RbcSpecies>(entry));
            fields.push_back(std::get<acmacs::chart::TableDate>(entry));
            return string::join(":", fields);
        });
        std::reverse(tables.begin(), tables.end());
        return tables;
    }

};

// ----------------------------------------------------------------------

int main(int /*argc*/, const char* /*argv*/[])
{
    int exit_code = 0;
    try {
        // Options opt(argc, argv);
        SerumIds serum_ids;
        size_t charts_processed = 0;
        for (auto& entry : fs::directory_iterator(".")) {
            if (entry.is_regular_file() && is_acmacs_file(entry.path())) {
                // std::cout << entry.path() << '\n';
                auto chart = acmacs::chart::import_from_file(entry.path());
                std::tuple table(chart->info()->virus_type(), chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());
                auto sera = chart->sera();
                for (auto serum : *sera)
                    serum_ids.add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);
                  // name_id.emplace_back(serum->designation_without_serum_id(), serum->serum_id(), date);
                ++charts_processed;
            }
        }
        std::cout << charts_processed << " charts processed\n";
        std::cout << serum_ids.size() << " entries\n";
        serum_ids.sort();
        serum_ids.scan();
          // std::cout << serum_ids.size() << " entries\n";
        serum_ids.print(false);

        // std::vector<std::pair<std::string, std::vector<std::string>>> name_ids;
        // for (const auto& entry : name_id) {
        //     if (name_ids.empty() || name_ids.back().first != entry.first)
        //         name_ids.emplace_back(entry.first, std::vector<std::string>{entry.second});
        //     else
        //         name_ids.back().second.push_back(entry.second);
        // }
        // std::cout << name_ids.size() << " serum names found\n";

        // for (const auto& entry : name_ids) {
        //     std::cout << entry.first << '\n';
        //     for (const auto& serum_id : entry.second) {
        //         std::cout << "  " << serum_id;
        //         if (serum_id[0] == 'F' || serum_id[0] == 'R') {
        //             if (serum_id.back() != 'D')
        //                 std::cout << "  Warning: FIX!";
        //         }
        //         else
        //             std::cout << "  Warning: not MELB";
        //         std::cout << '\n';
        //     }
        // }
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char int8_t;
typedef unsigned char bool;

char *numConv[]={
	"",
	"Ҽ",
	"",
	"",
	"",
	"",
	"½",
	"",
	"",
	""
};
#define DISP_10 "ʰ"
#define DISP_100 ""
#define DISP_1000 "Ǫ"
#define DISP_10000 ""
#define DISP_1E8 ""
#define DISP_1E16 ""
#define DISP_1E24 ""

bool conv1000(char* src, int8_t len){
	char *p=src; int8_t digit, i; bool allZero=1, outZero=0;
	for(i=len, p=src; i>0 && '\0'!=*p; i--,p++){
		digit=*p-'0';
		if(digit){
			allZero=0;
			break;
		}
	}
	if(allZero){
		return 0;
	}
	for(i=len, p=src; i>0 && '\0'!=*p; i--,p++){
		digit=*p-'0';
		if(!digit){
			outZero=1;
			continue;
		}
		if(outZero){
			printf(numConv[0]);
		}
		outZero=0;
		printf(numConv[digit]);
		switch(i){
			case 2:
				printf(DISP_10);
			break;
			case 3:
				printf(DISP_100);
			break;
			case 4:
				printf(DISP_1000);
			break;
		}
	}
	return 1;
}
bool padZero(char *src, int8_t len){
	char *p=src; bool foundZero=0;
	while(*p && len){
		if('0'==*p){
			foundZero=1;
		}else if(*p>='1' && *p<='9'){
			return foundZero;
		}
		p++; len--;
	}
	return 0;
}
bool conv10000(char *src, int8_t len){
	bool hasNum0=0, hasNum1=0;
	if(len<=4){
		return conv1000(src,len);
	}
	hasNum0=conv1000(src,len-4);
	if(hasNum0){
		printf(DISP_10000);
	}
	src+=(len-4);
	hasNum1=conv1000(src,4);
	return hasNum0 || hasNum1;
}
void conv(char *src){
	int8_t len=strlen(src), firstLen=len&(0x7), nonZero=1, i;
	if(!firstLen){
		firstLen=8;
	}
	conv10000(src,firstLen);
	len-=firstLen;
	if(!len){
		return;
	}
	src+=firstLen;
	while(len>0){
		if(nonZero){
			switch(len>>3){
				case 3:
					printf(DISP_1E24);
				break;
				case 2:
					printf(DISP_1E16);
				break;
				case 1:
					printf(DISP_1E8);
				break;
			}
		}
		nonZero=conv10000(src,8);
		len-=8;
		src+=8;
	}
}
int main(int argc, char* argv[]){
	char *num=NULL, *p=NULL;
	size_t len=0;

	if(argc<2){
		fputs("Usage: cnum number\n",stderr);
		return 1;
	}
	num=argv[1];
	for(p=num,len=0; *p; p++,len++){
		if(*p<'0' || *p>'9'){
			fputs("Invalid number\n",stderr);
			return 1;
		}
		if(len>=32){
			fputs("Number too large\n",stderr);
			return 1;
		}
	}
	conv(num);
	putchar('\n');
	return 0;
}<commit_msg>updated<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char int8_t;
typedef unsigned char bool;

char *numConv[]={
	"",
	"Ҽ",
	"",
	"",
	"",
	"",
	"½",
	"",
	"",
	""
};
#define DISP_10 "ʰ"
#define DISP_100 ""
#define DISP_1000 "Ǫ"
#define DISP_10000 ""
#define DISP_1E8 ""
#define DISP_1E16 ""
#define DISP_1E24 ""

bool conv1000(char* src, int8_t len){
	char *p=src; int8_t digit, i; bool allZero=1, outZero=0;
	for(i=len, p=src; i>0 && '\0'!=*p; i--,p++){
		if(*p>='0' && *p<='9'){
			allZero=0;
			break;
		}
	}
	if(allZero){
		return 0;
	}
	for(i=len, p=src; i>0 && '\0'!=*p; i--,p++){
		digit=*p-'0';
		if(!digit){
			outZero=1;
			continue;
		}
		if(outZero){
			printf(numConv[0]);
		}
		outZero=0;
		printf(numConv[digit]);
		switch(i){
			case 2:
				printf(DISP_10);
			break;
			case 3:
				printf(DISP_100);
			break;
			case 4:
				printf(DISP_1000);
			break;
		}
	}
	return 1;
}
bool conv10000(char *src, int8_t len){
	bool hasNum0=0, hasNum1=0;
	if(len<=4){
		return conv1000(src,len);
	}
	hasNum0=conv1000(src,len-4);
	if(hasNum0){
		printf(DISP_10000);
	}
	src+=(len-4);
	hasNum1=conv1000(src,4);
	return hasNum0 || hasNum1;
}
void conv(char *src){
	int8_t len=strlen(src), firstLen=len&(0x7), nonZero=1, i;
	if(!firstLen){
		firstLen=8;
	}
	conv10000(src,firstLen);
	len-=firstLen;
	if(!len){
		return;
	}
	src+=firstLen;
	while(len>0){
		if(nonZero){
			switch(len>>3){
				case 3:
					printf(DISP_1E24);
				break;
				case 2:
					printf(DISP_1E16);
				break;
				case 1:
					printf(DISP_1E8);
				break;
			}
		}
		nonZero=conv10000(src,8);
		len-=8;
		src+=8;
	}
}
int main(int argc, char* argv[]){
	char *num=NULL, *p=NULL;
	size_t len=0;

	if(argc<2){
		fputs("Usage: cnum number\n",stderr);
		return 1;
	}
	num=argv[1];
	for(p=num,len=0; *p; p++,len++){
		if(*p<'0' || *p>'9'){
			fputs("Invalid number\n",stderr);
			return 1;
		}
		if(len>=32){
			fputs("Number too large\n",stderr);
			return 1;
		}
	}
	conv(num);
	putchar('\n');
	return 0;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: astconstant.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:10:58 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#ifndef _IDLC_ASTCONSTANT_HXX_
#include <idlc/astconstant.hxx>
#endif
#ifndef _IDLC_ASTSCOPE_HXX_
#include <idlc/astscope.hxx>
#endif

#include "registry/writer.hxx"

using namespace ::rtl;

AstConstant::AstConstant(const ExprType type,
                         const NodeType nodeType,
                         AstExpression* pExpr,
                         const ::rtl::OString& name,
                         AstScope* pScope)
    : AstDeclaration(nodeType, name, pScope)
    , m_pConstValue(pExpr)
    , m_constValueType(type)
{
}

AstConstant::AstConstant(const ExprType type,
                         AstExpression* pExpr,
                         const ::rtl::OString& name,
                         AstScope* pScope)
    : AstDeclaration(NT_const, name, pScope)
    , m_pConstValue(pExpr)
    , m_constValueType(type)
{
}

AstConstant::~AstConstant()
{

}

sal_Bool AstConstant::dumpBlob(
    typereg::Writer & rBlob, sal_uInt16 index, bool published)
{
    RTConstValue    aConst;
    sal_Unicode*    str = NULL;

    AstExprValue *exprVal = getConstValue()->getExprValue();
    switch (getConstValueType())
    {
        case ET_short:
            aConst.m_type = RT_TYPE_INT16;
            aConst.m_value.aShort = exprVal->u.sval;
            break;
        case ET_ushort:
            aConst.m_type = RT_TYPE_UINT16;
            aConst.m_value.aUShort = exprVal->u.usval;
            break;
        case ET_long:
            aConst.m_type = RT_TYPE_INT32;
            aConst.m_value.aLong = exprVal->u.lval;
            break;
        case ET_ulong:
            aConst.m_type = RT_TYPE_UINT32;
            aConst.m_value.aULong = exprVal->u.ulval;
            break;
        case ET_hyper:
            aConst.m_type = RT_TYPE_INT64;
            aConst.m_value.aHyper = exprVal->u.hval;
            break;
        case ET_uhyper:
            aConst.m_type = RT_TYPE_UINT64;
            aConst.m_value.aUHyper = exprVal->u.uhval;
            break;
        case ET_float:
            aConst.m_type = RT_TYPE_FLOAT;
            aConst.m_value.aFloat = exprVal->u.fval;
            break;
        case ET_double:
            aConst.m_type = RT_TYPE_DOUBLE;
            aConst.m_value.aDouble = exprVal->u.dval;
            break;
        case ET_byte:
            aConst.m_type = RT_TYPE_BYTE;
            aConst.m_value.aByte = exprVal->u.byval;
            break;
        case ET_boolean:
            aConst.m_type = RT_TYPE_BOOL;
            aConst.m_value.aBool = exprVal->u.bval;
            break;
        default:
            {
                fprintf(stderr, "%s: exprtype to const type: cannot convert ExprType\n",
                        idlc()->getOptions()->getProgramName().getStr());
                return sal_False;
            }
    }

    OString name = getLocalName();

    OUString type;
    if ( getNodeType() != NT_enum_val )
    {
        type = OStringToOUString(exprTypeToString(getConstValueType()), RTL_TEXTENCODING_UTF8);
    }

    rBlob.setFieldData(
        index, getDocumentation(), OUString(),
        RT_ACCESS_CONST | (published ? RT_ACCESS_PUBLISHED : 0),
        OStringToOUString(name, RTL_TEXTENCODING_UTF8), type, aConst);
    if (str)
        delete[] str;

    return sal_True;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.9.58); FILE MERGED 2008/04/01 12:31:27 thb 1.9.58.2: #i85898# Stripping all external header guards 2008/03/31 07:23:50 rt 1.9.58.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: astconstant.cxx,v $
 * $Revision: 1.10 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#include <idlc/astconstant.hxx>
#include <idlc/astscope.hxx>

#include "registry/writer.hxx"

using namespace ::rtl;

AstConstant::AstConstant(const ExprType type,
                         const NodeType nodeType,
                         AstExpression* pExpr,
                         const ::rtl::OString& name,
                         AstScope* pScope)
    : AstDeclaration(nodeType, name, pScope)
    , m_pConstValue(pExpr)
    , m_constValueType(type)
{
}

AstConstant::AstConstant(const ExprType type,
                         AstExpression* pExpr,
                         const ::rtl::OString& name,
                         AstScope* pScope)
    : AstDeclaration(NT_const, name, pScope)
    , m_pConstValue(pExpr)
    , m_constValueType(type)
{
}

AstConstant::~AstConstant()
{

}

sal_Bool AstConstant::dumpBlob(
    typereg::Writer & rBlob, sal_uInt16 index, bool published)
{
    RTConstValue    aConst;
    sal_Unicode*    str = NULL;

    AstExprValue *exprVal = getConstValue()->getExprValue();
    switch (getConstValueType())
    {
        case ET_short:
            aConst.m_type = RT_TYPE_INT16;
            aConst.m_value.aShort = exprVal->u.sval;
            break;
        case ET_ushort:
            aConst.m_type = RT_TYPE_UINT16;
            aConst.m_value.aUShort = exprVal->u.usval;
            break;
        case ET_long:
            aConst.m_type = RT_TYPE_INT32;
            aConst.m_value.aLong = exprVal->u.lval;
            break;
        case ET_ulong:
            aConst.m_type = RT_TYPE_UINT32;
            aConst.m_value.aULong = exprVal->u.ulval;
            break;
        case ET_hyper:
            aConst.m_type = RT_TYPE_INT64;
            aConst.m_value.aHyper = exprVal->u.hval;
            break;
        case ET_uhyper:
            aConst.m_type = RT_TYPE_UINT64;
            aConst.m_value.aUHyper = exprVal->u.uhval;
            break;
        case ET_float:
            aConst.m_type = RT_TYPE_FLOAT;
            aConst.m_value.aFloat = exprVal->u.fval;
            break;
        case ET_double:
            aConst.m_type = RT_TYPE_DOUBLE;
            aConst.m_value.aDouble = exprVal->u.dval;
            break;
        case ET_byte:
            aConst.m_type = RT_TYPE_BYTE;
            aConst.m_value.aByte = exprVal->u.byval;
            break;
        case ET_boolean:
            aConst.m_type = RT_TYPE_BOOL;
            aConst.m_value.aBool = exprVal->u.bval;
            break;
        default:
            {
                fprintf(stderr, "%s: exprtype to const type: cannot convert ExprType\n",
                        idlc()->getOptions()->getProgramName().getStr());
                return sal_False;
            }
    }

    OString name = getLocalName();

    OUString type;
    if ( getNodeType() != NT_enum_val )
    {
        type = OStringToOUString(exprTypeToString(getConstValueType()), RTL_TEXTENCODING_UTF8);
    }

    rBlob.setFieldData(
        index, getDocumentation(), OUString(),
        RT_ACCESS_CONST | (published ? RT_ACCESS_PUBLISHED : 0),
        OStringToOUString(name, RTL_TEXTENCODING_UTF8), type, aConst);
    if (str)
        delete[] str;

    return sal_True;
}
<|endoftext|>


<commit_before><commit_msg>Create a string instead of strdup'ing a cstring.<commit_after><|endoftext|>