<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_thermal_init.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] 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                                                     */

///
/// @file p9_mss_thermal_init.C
/// @brief configure and start the OCC and thermal cache
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <lib/mc/mc.H>
#include <generic/memory/lib/utils/find.H>
#include <p9_mss_thermal_init.H>

using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{

///
/// @brief configure and start the OCC and thermal cache
/// @param[in] i_target the controller target
/// @return FAPI2_RC_SUCCESS iff ok
/// @note called on cumulus and centaur
///
    fapi2::ReturnCode p9_mss_thermal_init( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
    {
        FAPI_INF("Start thermal_init");

        //TODO:RTC 164009
        //Set runtime throttles to safemode values once OCC is working
#if 0

        for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))
        {
            FAPI_TRY (mss::mc::set_runtime_throttles_to_safe(l_mca));
        }

#endif
        FAPI_TRY (mss::mc::disable_emergency_throttle(i_target));

        FAPI_INF("End thermal_init");
        return fapi2::FAPI2_RC_SUCCESS;
    fapi_try_exit:
        FAPI_ERR("Error executing mss_thermal_init");
        return fapi2::current_err;
    }
} //extern C
<commit_msg>Set runtime mss throttles to safe for OCC to set<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_thermal_init.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] 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                                                     */

///
/// @file p9_mss_thermal_init.C
/// @brief configure and start the OCC and thermal cache
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <lib/mc/mc.H>
#include <generic/memory/lib/utils/find.H>
#include <p9_mss_thermal_init.H>

using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{

///
/// @brief configure and start the OCC and thermal cache
/// @param[in] i_target the controller target
/// @return FAPI2_RC_SUCCESS iff ok
/// @note called on cumulus and centaur
///
    fapi2::ReturnCode p9_mss_thermal_init( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
    {
        FAPI_INF("Start thermal_init");

        // Prior to starting OCC, we go into "safemode" throttling
        // After OCC is started, they can change throttles however they want
#ifdef __HOSTBOOT_MODULE

        for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))
        {
            FAPI_TRY (mss::mc::set_runtime_throttles_to_safe(l_mca));
        }

#endif
        FAPI_TRY (mss::mc::disable_emergency_throttle(i_target));

        FAPI_INF("End thermal_init");
        return fapi2::FAPI2_RC_SUCCESS;
    fapi_try_exit:
        FAPI_ERR("Error executing mss_thermal_init");
        return fapi2::current_err;
    }
} //extern C
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "mobileappwizardpages.h"

#include "qmlstandaloneapp.h"
#include "qmlstandaloneappwizard.h"
#include "qmlstandaloneappwizardpages.h"
#include "targetsetuppage.h"

#include "qt4projectmanagerconstants.h"

#include <projectexplorer/baseprojectwizarddialog.h>
#include <projectexplorer/customwizard/customwizard.h>
#include <projectexplorer/projectexplorer.h>
#include <coreplugin/editormanager/editormanager.h>

#include <QtCore/QCoreApplication>
#include <QtGui/QIcon>

namespace Qt4ProjectManager {
namespace Internal {

class QmlStandaloneAppWizardDialog : public AbstractMobileAppWizardDialog
{
    Q_OBJECT

public:
    explicit QmlStandaloneAppWizardDialog(QWidget *parent = 0);

private:
    class QmlStandaloneAppWizardSourcesPage *m_qmlSourcesPage;
    friend class QmlStandaloneAppWizard;
};

QmlStandaloneAppWizardDialog::QmlStandaloneAppWizardDialog(QWidget *parent)
    : AbstractMobileAppWizardDialog(parent)
    , m_qmlSourcesPage(0)
{
    setWindowTitle(tr("New Qt Quick Application"));
    setIntroDescription(tr("This wizard generates a Qt Quick application project."));

    m_qmlSourcesPage = new QmlStandaloneAppWizardSourcesPage;
    const int qmlSourcesPagePageId = addPage(m_qmlSourcesPage);
    wizardProgress()->item(qmlSourcesPagePageId)->setTitle(tr("QML Sources"));
}

class QmlStandaloneAppWizardPrivate
{
    class QmlStandaloneApp *standaloneApp;
    class QmlStandaloneAppWizardDialog *wizardDialog;
    friend class QmlStandaloneAppWizard;
};

QmlStandaloneAppWizard::QmlStandaloneAppWizard()
    : AbstractMobileAppWizard(parameters())
    , m_d(new QmlStandaloneAppWizardPrivate)
{
    m_d->standaloneApp = new QmlStandaloneApp;
    m_d->wizardDialog = 0;
}

QmlStandaloneAppWizard::~QmlStandaloneAppWizard()
{
    delete m_d->standaloneApp;
    delete m_d;
}

Core::BaseFileWizardParameters QmlStandaloneAppWizard::parameters()
{
    Core::BaseFileWizardParameters parameters(ProjectWizard);
    parameters.setIcon(QIcon(QLatin1String(Constants::ICON_QML_STANDALONE)));
    parameters.setDisplayName(tr("Qt Quick Application"));
    parameters.setId(QLatin1String("QA.QMLA Application"));
    parameters.setDescription(tr("Creates a Qt Quick application project that can contain "
                                 "both QML and C++ code and includes a QDeclarativeView.\n\n"
                                 "You can build the application and deploy it on desktop and "
                                 "mobile target platforms. For example, you can create signed "
                                 "Symbian Installation System (SIS) packages for this type of "
                                 "projects."));
    parameters.setCategory(QLatin1String(Constants::QML_WIZARD_CATEGORY));
    parameters.setDisplayCategory(QCoreApplication::translate(Constants::QML_WIZARD_TR_SCOPE,
                                                              Constants::QML_WIZARD_TR_CATEGORY));
    return parameters;
}

AbstractMobileAppWizardDialog *QmlStandaloneAppWizard::createWizardDialogInternal(QWidget *parent) const
{
    m_d->wizardDialog = new QmlStandaloneAppWizardDialog(parent);
    const QList<TargetSetupPage::ImportInfo> &qtVersions
        = TargetSetupPage::importInfosForKnownQtVersions();
    QList<TargetSetupPage::ImportInfo> qmlQtVersions;
    foreach (const TargetSetupPage::ImportInfo &qtVersion, qtVersions) {
        const QString versionString = qtVersion.version->qtVersionString();
        bool isNumber;
        const int majorVersion = versionString.mid(0, 1).toInt(&isNumber);
        if (!isNumber || majorVersion < 4)
            continue;
        const int minorVersion = versionString.mid(2, 1).toInt(&isNumber);
        if (!isNumber || (majorVersion == 4 && minorVersion < 7))
            continue;
        qmlQtVersions << qtVersion;
    }
    m_d->wizardDialog->m_targetsPage->setImportInfos(qmlQtVersions);

    return m_d->wizardDialog;
}

void QmlStandaloneAppWizard::prepareGenerateFiles(const QWizard *w,
    QString *errorMessage) const
{
    Q_UNUSED(errorMessage)
    const QmlStandaloneAppWizardDialog *wizard = qobject_cast<const QmlStandaloneAppWizardDialog*>(w);
    const QString mainQmlFile = wizard->m_qmlSourcesPage->mainQmlFile();
    if (!mainQmlFile.isEmpty())
        m_d->standaloneApp->setMainQmlFile(mainQmlFile);
}

bool QmlStandaloneAppWizard::postGenerateFilesInternal(const Core::GeneratedFiles &l,
    QString *errorMessage)
{
    const bool success = ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);
    if (success && !m_d->standaloneApp->mainQmlFile().isEmpty()) {
        ProjectExplorer::ProjectExplorerPlugin::instance()->setCurrentFile(0, m_d->standaloneApp->mainQmlFile());
        Core::EditorManager::instance()->openEditor(m_d->standaloneApp->mainQmlFile(),
                                                    QString(), Core::EditorManager::ModeSwitch);
    }
    return success;
}

AbstractMobileApp *QmlStandaloneAppWizard::app() const
{
    return m_d->standaloneApp;
}

AbstractMobileAppWizardDialog *QmlStandaloneAppWizard::wizardDialog() const
{
    return m_d->wizardDialog;
}

} // namespace Internal
} // namespace Qt4ProjectManager

#include "qmlstandaloneappwizard.moc"
<commit_msg>Qt Quick App Wizard: Reset main file<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "mobileappwizardpages.h"

#include "qmlstandaloneapp.h"
#include "qmlstandaloneappwizard.h"
#include "qmlstandaloneappwizardpages.h"
#include "targetsetuppage.h"

#include "qt4projectmanagerconstants.h"

#include <projectexplorer/baseprojectwizarddialog.h>
#include <projectexplorer/customwizard/customwizard.h>
#include <projectexplorer/projectexplorer.h>
#include <coreplugin/editormanager/editormanager.h>

#include <QtCore/QCoreApplication>
#include <QtGui/QIcon>

namespace Qt4ProjectManager {
namespace Internal {

class QmlStandaloneAppWizardDialog : public AbstractMobileAppWizardDialog
{
    Q_OBJECT

public:
    explicit QmlStandaloneAppWizardDialog(QWidget *parent = 0);

private:
    class QmlStandaloneAppWizardSourcesPage *m_qmlSourcesPage;
    friend class QmlStandaloneAppWizard;
};

QmlStandaloneAppWizardDialog::QmlStandaloneAppWizardDialog(QWidget *parent)
    : AbstractMobileAppWizardDialog(parent)
    , m_qmlSourcesPage(0)
{
    setWindowTitle(tr("New Qt Quick Application"));
    setIntroDescription(tr("This wizard generates a Qt Quick application project."));

    m_qmlSourcesPage = new QmlStandaloneAppWizardSourcesPage;
    const int qmlSourcesPagePageId = addPage(m_qmlSourcesPage);
    wizardProgress()->item(qmlSourcesPagePageId)->setTitle(tr("QML Sources"));
}

class QmlStandaloneAppWizardPrivate
{
    class QmlStandaloneApp *standaloneApp;
    class QmlStandaloneAppWizardDialog *wizardDialog;
    friend class QmlStandaloneAppWizard;
};

QmlStandaloneAppWizard::QmlStandaloneAppWizard()
    : AbstractMobileAppWizard(parameters())
    , m_d(new QmlStandaloneAppWizardPrivate)
{
    m_d->standaloneApp = new QmlStandaloneApp;
    m_d->wizardDialog = 0;
}

QmlStandaloneAppWizard::~QmlStandaloneAppWizard()
{
    delete m_d->standaloneApp;
    delete m_d;
}

Core::BaseFileWizardParameters QmlStandaloneAppWizard::parameters()
{
    Core::BaseFileWizardParameters parameters(ProjectWizard);
    parameters.setIcon(QIcon(QLatin1String(Constants::ICON_QML_STANDALONE)));
    parameters.setDisplayName(tr("Qt Quick Application"));
    parameters.setId(QLatin1String("QA.QMLA Application"));
    parameters.setDescription(tr("Creates a Qt Quick application project that can contain "
                                 "both QML and C++ code and includes a QDeclarativeView.\n\n"
                                 "You can build the application and deploy it on desktop and "
                                 "mobile target platforms. For example, you can create signed "
                                 "Symbian Installation System (SIS) packages for this type of "
                                 "projects."));
    parameters.setCategory(QLatin1String(Constants::QML_WIZARD_CATEGORY));
    parameters.setDisplayCategory(QCoreApplication::translate(Constants::QML_WIZARD_TR_SCOPE,
                                                              Constants::QML_WIZARD_TR_CATEGORY));
    return parameters;
}

AbstractMobileAppWizardDialog *QmlStandaloneAppWizard::createWizardDialogInternal(QWidget *parent) const
{
    m_d->wizardDialog = new QmlStandaloneAppWizardDialog(parent);
    const QList<TargetSetupPage::ImportInfo> &qtVersions
        = TargetSetupPage::importInfosForKnownQtVersions();
    QList<TargetSetupPage::ImportInfo> qmlQtVersions;
    foreach (const TargetSetupPage::ImportInfo &qtVersion, qtVersions) {
        const QString versionString = qtVersion.version->qtVersionString();
        bool isNumber;
        const int majorVersion = versionString.mid(0, 1).toInt(&isNumber);
        if (!isNumber || majorVersion < 4)
            continue;
        const int minorVersion = versionString.mid(2, 1).toInt(&isNumber);
        if (!isNumber || (majorVersion == 4 && minorVersion < 7))
            continue;
        qmlQtVersions << qtVersion;
    }
    m_d->wizardDialog->m_targetsPage->setImportInfos(qmlQtVersions);

    return m_d->wizardDialog;
}

void QmlStandaloneAppWizard::prepareGenerateFiles(const QWizard *w,
    QString *errorMessage) const
{
    Q_UNUSED(errorMessage)
    const QmlStandaloneAppWizardDialog *wizard = qobject_cast<const QmlStandaloneAppWizardDialog*>(w);
    const QString mainQmlFile = wizard->m_qmlSourcesPage->mainQmlFile();
    m_d->standaloneApp->setMainQmlFile(mainQmlFile);
}

bool QmlStandaloneAppWizard::postGenerateFilesInternal(const Core::GeneratedFiles &l,
    QString *errorMessage)
{
    const bool success = ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);
    if (success && !m_d->standaloneApp->mainQmlFile().isEmpty()) {
        ProjectExplorer::ProjectExplorerPlugin::instance()->setCurrentFile(0, m_d->standaloneApp->mainQmlFile());
        Core::EditorManager::instance()->openEditor(m_d->standaloneApp->mainQmlFile(),
                                                    QString(), Core::EditorManager::ModeSwitch);
    }
    return success;
}

AbstractMobileApp *QmlStandaloneAppWizard::app() const
{
    return m_d->standaloneApp;
}

AbstractMobileAppWizardDialog *QmlStandaloneAppWizard::wizardDialog() const
{
    return m_d->wizardDialog;
}

} // namespace Internal
} // namespace Qt4ProjectManager

#include "qmlstandaloneappwizard.moc"
<|endoftext|>


<commit_before>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_CLIPPER_H__
#define __MAPNIK_VECTOR_TILE_GEOMETRY_CLIPPER_H__

// mapnik-vector-tile
#include "vector_tile_config.hpp"
#include "vector_tile_processor.hpp"

// mapbox
#include <mapbox/geometry.hpp>
#include <mapbox/geometry/wagyu/quick_clip.hpp>
#include <mapbox/geometry/wagyu/wagyu.hpp>

// boost
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/geometry/algorithms/intersection.hpp>
#include <boost/geometry/algorithms/unique.hpp>
#pragma GCC diagnostic pop

namespace mapnik
{

namespace vector_tile_impl
{

namespace detail
{

template <typename T>
double area(mapbox::geometry::linear_ring<T> const& poly) {
    std::size_t size = poly.size();
    if (size < 3) {
        return 0.0;
    }

    double a = 0.0;
    auto itr = poly.begin();
    auto itr_prev = poly.end();
    --itr_prev;
    a += static_cast<double>(itr_prev->x + itr->x) * static_cast<double>(itr_prev->y - itr->y);
    ++itr;
    itr_prev = poly.begin();
    for (; itr != poly.end(); ++itr, ++itr_prev) {
        a += static_cast<double>(itr_prev->x + itr->x) * static_cast<double>(itr_prev->y - itr->y);
    }
    return -a * 0.5;
}

inline mapbox::geometry::wagyu::fill_type get_wagyu_fill_type(polygon_fill_type type)
{
    switch (type)
    {
    case polygon_fill_type_max:
    case even_odd_fill:
        return mapbox::geometry::wagyu::fill_type_even_odd;
    case non_zero_fill:
        return mapbox::geometry::wagyu::fill_type_non_zero;
    case positive_fill:
        return mapbox::geometry::wagyu::fill_type_positive;
    case negative_fill:
        return mapbox::geometry::wagyu::fill_type_negative;
    }
}

} // end ns detail

template <typename NextProcessor>
class geometry_clipper
{
private:
    NextProcessor & next_;
    mapnik::box2d<int> const& tile_clipping_extent_;
    double area_threshold_;
    bool strictly_simple_;
    bool multi_polygon_union_;
    polygon_fill_type fill_type_;
    bool process_all_rings_;
public:
    geometry_clipper(mapnik::box2d<int> const& tile_clipping_extent,
                     double area_threshold,
                     bool strictly_simple,
                     bool multi_polygon_union,
                     polygon_fill_type fill_type,
                     bool process_all_rings,
                     NextProcessor & next) :
              next_(next),
              tile_clipping_extent_(tile_clipping_extent),
              area_threshold_(area_threshold),
              strictly_simple_(strictly_simple),
              multi_polygon_union_(multi_polygon_union),
              fill_type_(fill_type),
              process_all_rings_(process_all_rings)
    {
    }

    void operator() (mapbox::geometry::point<std::int64_t> & geom)
    {
        next_(geom);
    }

    void operator() (mapbox::geometry::multi_point<std::int64_t> & geom)
    {
        // Here we remove repeated points from multi_point
        auto last = std::unique(geom.begin(), geom.end());
        geom.erase(last, geom.end());
        next_(geom);
    }

    void operator() (mapbox::geometry::geometry_collection<std::int64_t> & geom)
    {
        for (auto & g : geom)
        {
            mapbox::util::apply_visitor((*this), g);
        }
    }

    void operator() (mapbox::geometry::line_string<std::int64_t> & geom)
    {
        boost::geometry::unique(geom);
        if (geom.size() < 2)
        {
            return;
        }
        mapbox::geometry::multi_line_string<int64_t> result;
        mapbox::geometry::linear_ring<std::int64_t> clip_box;
        clip_box.reserve(5);
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        boost::geometry::intersection(clip_box, geom, result);
        if (result.empty())
        {
            return;
        }
        next_(result);
    }

    void operator() (mapbox::geometry::multi_line_string<std::int64_t> & geom)
    {
        if (geom.empty())
        {
            return;
        }

        mapbox::geometry::linear_ring<std::int64_t> clip_box;
        clip_box.reserve(5);
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        boost::geometry::unique(geom);
        mapbox::geometry::multi_line_string<int64_t> results;
        for (auto const& line : geom)
        {
            if (line.size() < 2)
            {
               continue;
            }
            boost::geometry::intersection(clip_box, line, results);
        }
        if (results.empty())
        {
            return;
        }
        next_(results);
    }

    void operator() (mapbox::geometry::polygon<std::int64_t> & geom)
    {
        if (geom.empty() || ((geom.front().size() < 3) && !process_all_rings_))
        {
            return;
        }

        mapbox::geometry::wagyu::wagyu<std::int64_t> clipper;
        mapbox::geometry::point<std::int64_t> min_pt(tile_clipping_extent_.minx(), tile_clipping_extent_.miny());
        mapbox::geometry::point<std::int64_t> max_pt(tile_clipping_extent_.maxx(), tile_clipping_extent_.maxy());
        mapbox::geometry::box<std::int64_t> b(min_pt, max_pt);
        //clipper.reverse_rings(true);

        bool first = true;
        for (auto & ring : geom) {
            if (ring.size() < 3)
            {
                if (first) {
                    if (process_all_rings_) {
                        first = false;
                    } else {
                        return;
                    }
                }
                continue;
            }
            double area = detail::area(ring);
            if (first) {
                first = false;
                if ((std::abs(area) < area_threshold_)  && !process_all_rings_) {
                    return;
                }
                if (area < 0) {
                    std::reverse(ring.begin(), ring.end());
                }
                auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                if (!new_ring) {
                    if (process_all_rings_) {
                        continue;
                    }
                    return;
                }
                clipper.add_ring(*new_ring);
            } else {
                if (std::abs(area) < area_threshold_) {
                    continue;
                }
                if (area > 0)
                {
                    std::reverse(ring.begin(), ring.end());
                }
                auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                if (!new_ring) {
                    continue;
                }
                clipper.add_ring(*new_ring);
            }
        }

        mapbox::geometry::multi_polygon<std::int64_t> mp;

        clipper.execute(mapbox::geometry::wagyu::clip_type_union,
                        mp,
                        detail::get_wagyu_fill_type(fill_type_),
                        mapbox::geometry::wagyu::fill_type_even_odd);

        if (mp.empty())
        {
            return;
        }
        next_(mp);
    }

    void operator() (mapbox::geometry::multi_polygon<std::int64_t> & geom)
    {
        if (geom.empty())
        {
            return;
        }

        mapbox::geometry::point<std::int64_t> min_pt(tile_clipping_extent_.minx(), tile_clipping_extent_.miny());
        mapbox::geometry::point<std::int64_t> max_pt(tile_clipping_extent_.maxx(), tile_clipping_extent_.maxy());
        mapbox::geometry::box<std::int64_t> b(min_pt, max_pt);

        mapbox::geometry::multi_polygon<std::int64_t> mp;

        if (multi_polygon_union_)
        {
            mapbox::geometry::wagyu::wagyu<std::int64_t> clipper;
            //clipper.reverse_rings(true);
            for (auto & poly : geom)
            {
                bool first = true;
                for (auto & ring : poly) {
                    if (ring.size() < 3)
                    {
                        if (first) {
                            first = false;
                            if (!process_all_rings_) {
                                return;
                            }
                        }
                        continue;
                    }
                    double area = detail::area(ring);
                    if (first) {
                        first = false;
                        if ((std::abs(area) < area_threshold_)  && !process_all_rings_) {
                            return;
                        }
                        if (area < 0) {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            if (process_all_rings_) {
                                continue;
                            }
                            return;
                        }
                        clipper.add_ring(*new_ring);
                    } else {
                        if (std::abs(area) < area_threshold_) {
                            continue;
                        }
                        if (area > 0)
                        {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            continue;
                        }
                        clipper.add_ring(*new_ring);
                    }
                }
            }
            clipper.execute(mapbox::geometry::wagyu::clip_type_union,
                            mp,
                            detail::get_wagyu_fill_type(fill_type_),
                            mapbox::geometry::wagyu::fill_type_even_odd);
        }
        else
        {
            for (auto & poly : geom)
            {
                mapbox::geometry::wagyu::wagyu<std::int64_t> clipper;
                mapbox::geometry::multi_polygon<std::int64_t> tmp_mp;
                bool first = true;
                for (auto & ring : poly) {
                    if (ring.size() < 3)
                    {
                        if (first) {
                            first = false;
                            if (!process_all_rings_) {
                                return;
                            }
                        }
                        continue;
                    }
                    double area = detail::area(ring);
                    if (first) {
                        first = false;
                        if ((std::abs(area) < area_threshold_)  && !process_all_rings_) {
                            return;
                        }
                        if (area < 0) {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            if (process_all_rings_) {
                                continue;
                            }
                            return;
                        }
                        clipper.add_ring(*new_ring);
                    } else {
                        if (std::abs(area) < area_threshold_) {
                            continue;
                        }
                        if (area > 0)
                        {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            continue;
                        }
                        clipper.add_ring(*new_ring);
                    }
                }
                clipper.execute(mapbox::geometry::wagyu::clip_type_union,
                                tmp_mp,
                                detail::get_wagyu_fill_type(fill_type_),
                                mapbox::geometry::wagyu::fill_type_even_odd);
                mp.insert(mp.end(), tmp_mp.begin(), tmp_mp.end());
            }
        }

        if (mp.empty())
        {
            return;
        }
        next_(mp);
    }
};

} // end ns vector_tile_impl

} // end ns mapnik

#endif // __MAPNIK_VECTOR_GEOMETRY_CLIPPER_H__
<commit_msg>Added return to appease gcc<commit_after>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_CLIPPER_H__
#define __MAPNIK_VECTOR_TILE_GEOMETRY_CLIPPER_H__

// mapnik-vector-tile
#include "vector_tile_config.hpp"
#include "vector_tile_processor.hpp"

// mapbox
#include <mapbox/geometry.hpp>
#include <mapbox/geometry/wagyu/quick_clip.hpp>
#include <mapbox/geometry/wagyu/wagyu.hpp>

// boost
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/geometry/algorithms/intersection.hpp>
#include <boost/geometry/algorithms/unique.hpp>
#pragma GCC diagnostic pop

namespace mapnik
{

namespace vector_tile_impl
{

namespace detail
{

template <typename T>
double area(mapbox::geometry::linear_ring<T> const& poly) {
    std::size_t size = poly.size();
    if (size < 3) {
        return 0.0;
    }

    double a = 0.0;
    auto itr = poly.begin();
    auto itr_prev = poly.end();
    --itr_prev;
    a += static_cast<double>(itr_prev->x + itr->x) * static_cast<double>(itr_prev->y - itr->y);
    ++itr;
    itr_prev = poly.begin();
    for (; itr != poly.end(); ++itr, ++itr_prev) {
        a += static_cast<double>(itr_prev->x + itr->x) * static_cast<double>(itr_prev->y - itr->y);
    }
    return -a * 0.5;
}

inline mapbox::geometry::wagyu::fill_type get_wagyu_fill_type(polygon_fill_type type)
{
    switch (type)
    {
    case polygon_fill_type_max:
    case even_odd_fill:
        return mapbox::geometry::wagyu::fill_type_even_odd;
    case non_zero_fill:
        return mapbox::geometry::wagyu::fill_type_non_zero;
    case positive_fill:
        return mapbox::geometry::wagyu::fill_type_positive;
    case negative_fill:
        return mapbox::geometry::wagyu::fill_type_negative;
    }
    // Added return here to make gcc happy
    return mapbox::geometry::wagyu::fill_type_even_odd;
}

} // end ns detail

template <typename NextProcessor>
class geometry_clipper
{
private:
    NextProcessor & next_;
    mapnik::box2d<int> const& tile_clipping_extent_;
    double area_threshold_;
    bool strictly_simple_;
    bool multi_polygon_union_;
    polygon_fill_type fill_type_;
    bool process_all_rings_;
public:
    geometry_clipper(mapnik::box2d<int> const& tile_clipping_extent,
                     double area_threshold,
                     bool strictly_simple,
                     bool multi_polygon_union,
                     polygon_fill_type fill_type,
                     bool process_all_rings,
                     NextProcessor & next) :
              next_(next),
              tile_clipping_extent_(tile_clipping_extent),
              area_threshold_(area_threshold),
              strictly_simple_(strictly_simple),
              multi_polygon_union_(multi_polygon_union),
              fill_type_(fill_type),
              process_all_rings_(process_all_rings)
    {
    }

    void operator() (mapbox::geometry::point<std::int64_t> & geom)
    {
        next_(geom);
    }

    void operator() (mapbox::geometry::multi_point<std::int64_t> & geom)
    {
        // Here we remove repeated points from multi_point
        auto last = std::unique(geom.begin(), geom.end());
        geom.erase(last, geom.end());
        next_(geom);
    }

    void operator() (mapbox::geometry::geometry_collection<std::int64_t> & geom)
    {
        for (auto & g : geom)
        {
            mapbox::util::apply_visitor((*this), g);
        }
    }

    void operator() (mapbox::geometry::line_string<std::int64_t> & geom)
    {
        boost::geometry::unique(geom);
        if (geom.size() < 2)
        {
            return;
        }
        mapbox::geometry::multi_line_string<int64_t> result;
        mapbox::geometry::linear_ring<std::int64_t> clip_box;
        clip_box.reserve(5);
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        boost::geometry::intersection(clip_box, geom, result);
        if (result.empty())
        {
            return;
        }
        next_(result);
    }

    void operator() (mapbox::geometry::multi_line_string<std::int64_t> & geom)
    {
        if (geom.empty())
        {
            return;
        }

        mapbox::geometry::linear_ring<std::int64_t> clip_box;
        clip_box.reserve(5);
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.miny());
        clip_box.emplace_back(tile_clipping_extent_.maxx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.maxy());
        clip_box.emplace_back(tile_clipping_extent_.minx(),tile_clipping_extent_.miny());
        boost::geometry::unique(geom);
        mapbox::geometry::multi_line_string<int64_t> results;
        for (auto const& line : geom)
        {
            if (line.size() < 2)
            {
               continue;
            }
            boost::geometry::intersection(clip_box, line, results);
        }
        if (results.empty())
        {
            return;
        }
        next_(results);
    }

    void operator() (mapbox::geometry::polygon<std::int64_t> & geom)
    {
        if (geom.empty() || ((geom.front().size() < 3) && !process_all_rings_))
        {
            return;
        }

        mapbox::geometry::wagyu::wagyu<std::int64_t> clipper;
        mapbox::geometry::point<std::int64_t> min_pt(tile_clipping_extent_.minx(), tile_clipping_extent_.miny());
        mapbox::geometry::point<std::int64_t> max_pt(tile_clipping_extent_.maxx(), tile_clipping_extent_.maxy());
        mapbox::geometry::box<std::int64_t> b(min_pt, max_pt);
        //clipper.reverse_rings(true);

        bool first = true;
        for (auto & ring : geom) {
            if (ring.size() < 3)
            {
                if (first) {
                    if (process_all_rings_) {
                        first = false;
                    } else {
                        return;
                    }
                }
                continue;
            }
            double area = detail::area(ring);
            if (first) {
                first = false;
                if ((std::abs(area) < area_threshold_)  && !process_all_rings_) {
                    return;
                }
                if (area < 0) {
                    std::reverse(ring.begin(), ring.end());
                }
                auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                if (!new_ring) {
                    if (process_all_rings_) {
                        continue;
                    }
                    return;
                }
                clipper.add_ring(*new_ring);
            } else {
                if (std::abs(area) < area_threshold_) {
                    continue;
                }
                if (area > 0)
                {
                    std::reverse(ring.begin(), ring.end());
                }
                auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                if (!new_ring) {
                    continue;
                }
                clipper.add_ring(*new_ring);
            }
        }

        mapbox::geometry::multi_polygon<std::int64_t> mp;

        clipper.execute(mapbox::geometry::wagyu::clip_type_union,
                        mp,
                        detail::get_wagyu_fill_type(fill_type_),
                        mapbox::geometry::wagyu::fill_type_even_odd);

        if (mp.empty())
        {
            return;
        }
        next_(mp);
    }

    void operator() (mapbox::geometry::multi_polygon<std::int64_t> & geom)
    {
        if (geom.empty())
        {
            return;
        }

        mapbox::geometry::point<std::int64_t> min_pt(tile_clipping_extent_.minx(), tile_clipping_extent_.miny());
        mapbox::geometry::point<std::int64_t> max_pt(tile_clipping_extent_.maxx(), tile_clipping_extent_.maxy());
        mapbox::geometry::box<std::int64_t> b(min_pt, max_pt);

        mapbox::geometry::multi_polygon<std::int64_t> mp;

        if (multi_polygon_union_)
        {
            mapbox::geometry::wagyu::wagyu<std::int64_t> clipper;
            //clipper.reverse_rings(true);
            for (auto & poly : geom)
            {
                bool first = true;
                for (auto & ring : poly) {
                    if (ring.size() < 3)
                    {
                        if (first) {
                            first = false;
                            if (!process_all_rings_) {
                                return;
                            }
                        }
                        continue;
                    }
                    double area = detail::area(ring);
                    if (first) {
                        first = false;
                        if ((std::abs(area) < area_threshold_)  && !process_all_rings_) {
                            return;
                        }
                        if (area < 0) {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            if (process_all_rings_) {
                                continue;
                            }
                            return;
                        }
                        clipper.add_ring(*new_ring);
                    } else {
                        if (std::abs(area) < area_threshold_) {
                            continue;
                        }
                        if (area > 0)
                        {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            continue;
                        }
                        clipper.add_ring(*new_ring);
                    }
                }
            }
            clipper.execute(mapbox::geometry::wagyu::clip_type_union,
                            mp,
                            detail::get_wagyu_fill_type(fill_type_),
                            mapbox::geometry::wagyu::fill_type_even_odd);
        }
        else
        {
            for (auto & poly : geom)
            {
                mapbox::geometry::wagyu::wagyu<std::int64_t> clipper;
                mapbox::geometry::multi_polygon<std::int64_t> tmp_mp;
                bool first = true;
                for (auto & ring : poly) {
                    if (ring.size() < 3)
                    {
                        if (first) {
                            first = false;
                            if (!process_all_rings_) {
                                return;
                            }
                        }
                        continue;
                    }
                    double area = detail::area(ring);
                    if (first) {
                        first = false;
                        if ((std::abs(area) < area_threshold_)  && !process_all_rings_) {
                            return;
                        }
                        if (area < 0) {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            if (process_all_rings_) {
                                continue;
                            }
                            return;
                        }
                        clipper.add_ring(*new_ring);
                    } else {
                        if (std::abs(area) < area_threshold_) {
                            continue;
                        }
                        if (area > 0)
                        {
                            std::reverse(ring.begin(), ring.end());
                        }
                        auto new_ring = mapbox::geometry::wagyu::quick_clip::quick_lr_clip(ring, b);
                        if (!new_ring) {
                            continue;
                        }
                        clipper.add_ring(*new_ring);
                    }
                }
                clipper.execute(mapbox::geometry::wagyu::clip_type_union,
                                tmp_mp,
                                detail::get_wagyu_fill_type(fill_type_),
                                mapbox::geometry::wagyu::fill_type_even_odd);
                mp.insert(mp.end(), tmp_mp.begin(), tmp_mp.end());
            }
        }

        if (mp.empty())
        {
            return;
        }
        next_(mp);
    }
};

} // end ns vector_tile_impl

} // end ns mapnik

#endif // __MAPNIK_VECTOR_GEOMETRY_CLIPPER_H__
<|endoftext|>


<commit_before>// Source : https://oj.leetcode.com/problems/longest-palindromic-substring/
// Author : Hao Chen
// Date   : 2014-07-17

/**********************************************************************************
*
* Given a string S, find the longest palindromic substring in S.
* You may assume that the maximum length of S is 1000,
* and there exists one unique longest palindromic substring.
*
**********************************************************************************/

#include <iostream>
#include <string>
using namespace std;

string findPalindrome(string s, int left, int right)
{
    int n = s.size();
    int l = left;
    int r = right;
    while (left>=0 && right<=n-1 && s[left] == s[right]) {
        left--;
        right++;
    }
    return s.substr(left+1, right-left-1);
}

string longestPalindrome(string s) {
    int n = s.size();
    if (n<=1) return s;

    string longest;

    string str;
    for (int i=0; i<n-1; i++) {
        str = findPalindrome(s, i, i);
        if (str.size() > longest.size()){
            longest = str;
        }
        str = findPalindrome(s, i, i+1);
        if (str.size() > longest.size()){
            longest = str;
        }
    }

    return longest;
}

int main(int argc, char**argv)
{
    string s = "abacdfgdcaba";
    if (argc > 1){
        s = argv[1];
    }
    cout <<  s << " : " << longestPalindrome(s) << endl;
    return 0;
}
<commit_msg>Longest Palindromic Substring DP way, but Memory Limit Exceeded error<commit_after>// Source : https://oj.leetcode.com/problems/longest-palindromic-substring/
// Author : Hao Chen
// Date   : 2014-07-17

/**********************************************************************************
*
* Given a string S, find the longest palindromic substring in S.
* You may assume that the maximum length of S is 1000,
* and there exists one unique longest palindromic substring.
*
**********************************************************************************/

#include <iostream>
#include <string>
#include <vector>
using namespace std;

string findPalindrome(string s, int left, int right)
{
    int n = s.size();
    int l = left;
    int r = right;
    while (left>=0 && right<=n-1 && s[left] == s[right]) {
        left--;
        right++;
    }
    return s.substr(left+1, right-left-1);
}

string longestPalindrome_recursive_way(string s) {
    int n = s.size();
    if (n<=1) return s;

    string longest;

    string str;
    for (int i=0; i<n-1; i++) {
        str = findPalindrome(s, i, i);
        if (str.size() > longest.size()){
            longest = str;
        }
        str = findPalindrome(s, i, i+1);
        if (str.size() > longest.size()){
            longest = str;
        }
    }

    return longest;
}

//Memory Limit Exceeded
string longestPalindrome_dp_way(string s) {

    string longest;

    int n = s.size();
    if (n<=1) return s;

    //Construct a matrix, and consdier matrix[i][j] as s[i] -> s[j] is Palindrome or not.
    vector< vector<int> > matrix (n, vector<int>(n));

    // Dynamic Programming
    //   1) if i == j, then matrix[i][j] = true;
    //   2) if i != j, then matrix[i][j] = (s[i]==s[j] && matrix[i+1][j-1])
    for (int i=n-1; i>=0; i--){
        for (int j=i; j<n; j++){
            // The following if statement can be broken to
            //   1) i==j, matrix[i][j] = true
            //   2) the length from i to j is 2 or 3, then, check s[i] == s[j]
            //   3) the length from i to j > 3, then, check s[i]==s[j] && matrix[i+1][j-1]
            if ( i==j || (s[i]==s[j] && (j-i<2 || matrix[i+1][j-1]) ) )  {
                matrix[i][j] = true;
                if (longest.size() < j-i+1){
                    longest = s.substr(i, j-i+1);
                }
            }
        }
    }

    return longest;
}
string longestPalindrome(string s) {
    return longestPalindrome_dp_way(s);
}

int main(int argc, char**argv)
{
    string s = "abacdfgdcaba";
    if (argc > 1){
        s = argv[1];
    }
    cout <<  s << " : " << longestPalindrome(s) << endl;
    return 0;
}
<|endoftext|>


<commit_before>#include "modules.h"

#ifndef MODBASE_CPP
#define MODBASE_CPP
Module::Module() {}

Module::~Module() {}

void Module::init(std::tr1::unordered_map<std::string, std::string> modConf, ModuleInterface* modFace) {
	config = modConf;
	serverData = modFace;
}

void Module::onLoadComplete() {}

void Module::onChannelMsg(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserMsg(std::string server, std::string nick, std::string message) {}

void Module::onChannelNotice(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserNotice(std::string server, std::string nick, std::string message) {}

void Module::onChannelCTCP(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserCTCP(std::string server, std::string nick, std::string message) {}

void Module::onChannelCTCPReply(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserCTCPReply(std::string server, std::string nick, std::string message) {}

void Module::onChannelJoin(std::string server, std::string channel, std::string hostmask) {}

void Module::onChannelPart(std::string server, std::string channel, std::string hostmask, std::string reason) {}

void Module::onUserQuit(std::string server, std::string hostmask, std::string reason) {}

void Module::onChannelKick(std::string server, std::string channel, std::string kicker, std::string kickee, std::string reason) {}

void Module::onChannelMode(std::string server, std::string channel, std::string setter, char mode, bool add, std::string param) {}

void Module::onNumeric(std::string server, std::string numeric, std::vector<std::string> parsedLine) {}

void Module::onOtherData(std::string server, std::vector<std::string> parsedLine) {}

void Module::onOutChannelMessage(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserMessage(std::string server, std::string target, std::string message) {}

void Module::onOutChannelNotice(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserNotice(std::string server, std::string target, std::string message) {}

void Module::onOutChannelCTCP(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserCTCP(std::string server, std::string target, std::string message) {}

void Module::onOutChannelCTCPReply(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserCTCPReply(std::string server, std::string target, std::string message) {}

std::string Module::getDesc() { return "This module has no description."; }

std::string Module::getHelp() { return "There is no help available for this module."; }

void Module::sendPrivMsg(std::string server, std::string target, std::string message) {
	serverData->sendToServer(server, "PRIVMSG " + target + " :" + message);
}

void Module::sendNotice(std::string server, std::string target, std::string message) {
	serverData->sendToServer(server, "NOTICE " + target + " :" + message);
}

void Module::sendCTCP(std::string server, std::string target, std::string type, std::string params) {
	if (params == "")
		serverData->sendToServer(server, "PRIVMSG " + target + " :" + (char)1 + type + (char)1);
	else
		serverData->sendToServer(server, "PRIVMSG " + target + " :" + (char)1 + type + " " + params + (char)1);
}

void Module::sendCTCPReply(std::string server, std::string target, std::string type, std::string data) {
	if (data == "")
		serverData->sendToServer(server, "NOTICE " + target + " :" + (char)1 + type + (char)1);
	else
		serverData->sendToServer(server, "NOTICE " + target + " :" + (char)1 + type + " " + data + (char)1);
}

void Module::joinChannel(std::string server, std::string channel, std::string key) {
	serverData->sendToServer(server, "JOIN " + channel + " " + key);
}

void Module::partChannel(std::string server, std::string channel, std::string reason) {
	serverData->sendToServer(server, "PART " + channel + " :" + reason);
}

void Module::kickChannelUser(std::string server, std::string channel, std::string nick, std::string reason) {
	serverData->sendToServer(server, "KICK " + channel + " " + nick + " :" + reason);
}

void Module::setMode(std::string server, std::string channel, char mode, bool add, std::string param) {
	if (param == "") {
		if (add)
			serverData->sendToServer(server, "MODE " + channel + " +" + mode);
		else
			serverData->sendToServer(server, "MODE " + channel + " -" + mode);
	} else {
		if (add)
			serverData->sendToServer(server, "MODE " + channel + " +" + mode + " " + param);
		else
			serverData->sendToServer(server, "MODE " + channel + " -" + mode + " " + param);
	}
}

void Module::sendOtherCommand(std::string server, std::string command, std::string data) {
	serverData->sendToServer(server, command + " " + data);
}

void Module::connectServer(std::string server, std::tr1::unordered_map<std::string, std::string> serverConf) {
	serverData->connectServer(server, serverConf);
}

void Module::quitServer(std::string server, std::string reason) {
	serverData->sendToServer(server, "QUIT :" + reason);
}

unsigned int getBotVersion() {
	return 900; // alpha 1
}

std::vector<std::string> Module::splitHostmask(std::string hostmask) {
	std::vector<std::string> splitmask;
	int exclamationPoint = hostmask.find_first_of('!');
	int atSign = hostmask.find_first_of('@');
	splitmask.push_back(hostmask.substr(0, exclamationPoint));
	splitmask.push_back(hostmask.substr(exclamationPoint, atSign - exclamationPoint));
	splitmask.push_back(hostmask.substr(atSign));
	return splitmask;
}

std::vector<std::string> Module::splitBySpace(std::string line) {
	std::vector<std::string> split;
	std::string temp = "";
	for (unsigned int i = 0; i < line.size(); i++) {
		if (line[i] == ' ') {
			split.push_back(temp);
			temp = "";
		} else
			temp += line[i];
	}
	if (temp != "")
		split.push_back(temp);
	return split;
}

std::list<std::string> Module::getServers() {
	return serverData->getServers();
}

std::tr1::unordered_map<std::string, Module*> Module::getModules() {
	return serverData->getModules();
}

std::vector<std::vector<char> > Module::getServerChanModes(std::string server) {
	return serverData->getServerChanModes(server);
}

std::tr1::unordered_map<char, char> Module::getServerPrefixes(std::string server) {
	return serverData->getServerPrefixes(server);
}
#endif<commit_msg>Fix the getBotVersion function.<commit_after>#include "modules.h"

#ifndef MODBASE_CPP
#define MODBASE_CPP
Module::Module() {}

Module::~Module() {}

void Module::init(std::tr1::unordered_map<std::string, std::string> modConf, ModuleInterface* modFace) {
	config = modConf;
	serverData = modFace;
}

void Module::onLoadComplete() {}

void Module::onChannelMsg(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserMsg(std::string server, std::string nick, std::string message) {}

void Module::onChannelNotice(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserNotice(std::string server, std::string nick, std::string message) {}

void Module::onChannelCTCP(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserCTCP(std::string server, std::string nick, std::string message) {}

void Module::onChannelCTCPReply(std::string server, std::string channel, char target, std::string nick, std::string message) {}

void Module::onUserCTCPReply(std::string server, std::string nick, std::string message) {}

void Module::onChannelJoin(std::string server, std::string channel, std::string hostmask) {}

void Module::onChannelPart(std::string server, std::string channel, std::string hostmask, std::string reason) {}

void Module::onUserQuit(std::string server, std::string hostmask, std::string reason) {}

void Module::onChannelKick(std::string server, std::string channel, std::string kicker, std::string kickee, std::string reason) {}

void Module::onChannelMode(std::string server, std::string channel, std::string setter, char mode, bool add, std::string param) {}

void Module::onNumeric(std::string server, std::string numeric, std::vector<std::string> parsedLine) {}

void Module::onOtherData(std::string server, std::vector<std::string> parsedLine) {}

void Module::onOutChannelMessage(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserMessage(std::string server, std::string target, std::string message) {}

void Module::onOutChannelNotice(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserNotice(std::string server, std::string target, std::string message) {}

void Module::onOutChannelCTCP(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserCTCP(std::string server, std::string target, std::string message) {}

void Module::onOutChannelCTCPReply(std::string server, std::string target, char status, std::string message) {}

void Module::onOutUserCTCPReply(std::string server, std::string target, std::string message) {}

std::string Module::getDesc() { return "This module has no description."; }

std::string Module::getHelp() { return "There is no help available for this module."; }

void Module::sendPrivMsg(std::string server, std::string target, std::string message) {
	serverData->sendToServer(server, "PRIVMSG " + target + " :" + message);
}

void Module::sendNotice(std::string server, std::string target, std::string message) {
	serverData->sendToServer(server, "NOTICE " + target + " :" + message);
}

void Module::sendCTCP(std::string server, std::string target, std::string type, std::string params) {
	if (params == "")
		serverData->sendToServer(server, "PRIVMSG " + target + " :" + (char)1 + type + (char)1);
	else
		serverData->sendToServer(server, "PRIVMSG " + target + " :" + (char)1 + type + " " + params + (char)1);
}

void Module::sendCTCPReply(std::string server, std::string target, std::string type, std::string data) {
	if (data == "")
		serverData->sendToServer(server, "NOTICE " + target + " :" + (char)1 + type + (char)1);
	else
		serverData->sendToServer(server, "NOTICE " + target + " :" + (char)1 + type + " " + data + (char)1);
}

void Module::joinChannel(std::string server, std::string channel, std::string key) {
	serverData->sendToServer(server, "JOIN " + channel + " " + key);
}

void Module::partChannel(std::string server, std::string channel, std::string reason) {
	serverData->sendToServer(server, "PART " + channel + " :" + reason);
}

void Module::kickChannelUser(std::string server, std::string channel, std::string nick, std::string reason) {
	serverData->sendToServer(server, "KICK " + channel + " " + nick + " :" + reason);
}

void Module::setMode(std::string server, std::string channel, char mode, bool add, std::string param) {
	if (param == "") {
		if (add)
			serverData->sendToServer(server, "MODE " + channel + " +" + mode);
		else
			serverData->sendToServer(server, "MODE " + channel + " -" + mode);
	} else {
		if (add)
			serverData->sendToServer(server, "MODE " + channel + " +" + mode + " " + param);
		else
			serverData->sendToServer(server, "MODE " + channel + " -" + mode + " " + param);
	}
}

void Module::sendOtherCommand(std::string server, std::string command, std::string data) {
	serverData->sendToServer(server, command + " " + data);
}

void Module::connectServer(std::string server, std::tr1::unordered_map<std::string, std::string> serverConf) {
	serverData->connectServer(server, serverConf);
}

void Module::quitServer(std::string server, std::string reason) {
	serverData->sendToServer(server, "QUIT :" + reason);
}

unsigned int Module::getBotVersion() {
	return 900; // alpha 1
}

std::vector<std::string> Module::splitHostmask(std::string hostmask) {
	std::vector<std::string> splitmask;
	int exclamationPoint = hostmask.find_first_of('!');
	int atSign = hostmask.find_first_of('@');
	splitmask.push_back(hostmask.substr(0, exclamationPoint));
	splitmask.push_back(hostmask.substr(exclamationPoint, atSign - exclamationPoint));
	splitmask.push_back(hostmask.substr(atSign));
	return splitmask;
}

std::vector<std::string> Module::splitBySpace(std::string line) {
	std::vector<std::string> split;
	std::string temp = "";
	for (unsigned int i = 0; i < line.size(); i++) {
		if (line[i] == ' ') {
			split.push_back(temp);
			temp = "";
		} else
			temp += line[i];
	}
	if (temp != "")
		split.push_back(temp);
	return split;
}

std::list<std::string> Module::getServers() {
	return serverData->getServers();
}

std::tr1::unordered_map<std::string, Module*> Module::getModules() {
	return serverData->getModules();
}

std::vector<std::vector<char> > Module::getServerChanModes(std::string server) {
	return serverData->getServerChanModes(server);
}

std::tr1::unordered_map<char, char> Module::getServerPrefixes(std::string server) {
	return serverData->getServerPrefixes(server);
}
#endif<|endoftext|>


<commit_before>
<commit_msg>Update reverse_words.cpp<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>

std::ofstream outputfile("output.txt");

void print_reverse(const std::string &sentence, int iteration)
{
    std::vector<std::string> words;
    std::stringstream stream(sentence);

    outputfile << "Case #" << iteration << ": ";

    for(std::string word; stream >> word;)
        words.push_back(word);

    for(std::vector<std::string>::reverse_iterator it = words.rbegin(); it != words.rend(); ++it)
        outputfile << *it << " ";
}

int main()
{
    std::string sentence;
    std::string fileName;
    std::string word;
    int cases = 0;
	int cnt = 1;

    std::cout << "Enter Input File Name: ";
    getline(std::cin,fileName);

    std::ifstream streamIn;
	streamIn.open(fileName);

	if(!streamIn)
    {
        std::cout << "Error Opening File.\n";
        return -1;
    }

    streamIn >> cases;
	streamIn.ignore();

    while(!streamIn.fail() && cnt != cases+1)
	{
		getline(streamIn,sentence);
		print_reverse(sentence,cnt);
		outputfile << "\n";
		++cnt;
	}

    return 0;
}

<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "apply_bucket_diff_state.h"
#include "mergehandler.h"
#include "persistenceutil.h"
#include <vespa/document/base/documentid.h>
#include <vespa/persistence/spi/result.h>
#include <vespa/vespalib/stllike/asciistream.h>

using storage::spi::Result;
using vespalib::RetainGuard;

namespace storage {

ApplyBucketDiffState::ApplyBucketDiffState(const MergeBucketInfoSyncer& merge_bucket_info_syncer, const spi::Bucket& bucket, RetainGuard&& retain_guard)
    : _merge_bucket_info_syncer(merge_bucket_info_syncer),
      _bucket(bucket),
      _fail_message(),
      _failed_flag(),
      _stale_bucket_info(false),
      _promise(),
      _tracker(),
      _delayed_reply(),
      _sender(nullptr),
      _retain_guard(std::move(retain_guard))
{
}

ApplyBucketDiffState::~ApplyBucketDiffState()
{
    try {
        sync_bucket_info();
    } catch (std::exception& e) {
        if (_fail_message.empty()) {
            _fail_message = e.what();
        }
    }
    if (_promise.has_value()) {
        _promise.value().set_value(_fail_message);
    }
    if (_delayed_reply) {
        if (!_delayed_reply->getResult().failed() && !_fail_message.empty()) {
            _delayed_reply->setResult(api::ReturnCode(api::ReturnCode::INTERNAL_FAILURE, _fail_message));
        }
        if (_sender) {
            _sender->sendReply(std::move(_delayed_reply));
        } else {
            _tracker->sendReply();
        }
    }
}

void
ApplyBucketDiffState::on_entry_complete(std::unique_ptr<Result> result, const document::DocumentId &doc_id, const char *op)
{
    if (result->hasError() && !_failed_flag.test_and_set()) {
        vespalib::asciistream ss;
        ss << "Failed " << op
           << " for " << doc_id.toString()
           << " in " << _bucket
           << ": " << result->toString();
        _fail_message = ss.str();
    }
}

void
ApplyBucketDiffState::mark_stale_bucket_info()
{
    _stale_bucket_info = true;
}

void
ApplyBucketDiffState::sync_bucket_info()
{
    if (_stale_bucket_info) {
        _merge_bucket_info_syncer.sync_bucket_info(_bucket);
        _stale_bucket_info = false;
    }
}

std::future<vespalib::string>
ApplyBucketDiffState::get_future()
{
    _promise = std::promise<vespalib::string>();
    return _promise.value().get_future();
}

void
ApplyBucketDiffState::set_delayed_reply(std::unique_ptr<MessageTracker>&& tracker, std::shared_ptr<api::StorageReply>&& delayed_reply)
{
    _tracker = std::move(tracker);
    _delayed_reply = std::move(delayed_reply);
}

void
ApplyBucketDiffState::set_delayed_reply(std::unique_ptr<MessageTracker>&& tracker, MessageSender& sender, std::shared_ptr<api::StorageReply>&& delayed_reply)
{
    _tracker = std::move(tracker);
    _sender = &sender;
    _delayed_reply = std::move(delayed_reply);
}

}
<commit_msg>Add comment about _tracker->_reply and _delayed_reply in ApplyBucketDiffState pointing to the same reply.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "apply_bucket_diff_state.h"
#include "mergehandler.h"
#include "persistenceutil.h"
#include <vespa/document/base/documentid.h>
#include <vespa/persistence/spi/result.h>
#include <vespa/vespalib/stllike/asciistream.h>

using storage::spi::Result;
using vespalib::RetainGuard;

namespace storage {

ApplyBucketDiffState::ApplyBucketDiffState(const MergeBucketInfoSyncer& merge_bucket_info_syncer, const spi::Bucket& bucket, RetainGuard&& retain_guard)
    : _merge_bucket_info_syncer(merge_bucket_info_syncer),
      _bucket(bucket),
      _fail_message(),
      _failed_flag(),
      _stale_bucket_info(false),
      _promise(),
      _tracker(),
      _delayed_reply(),
      _sender(nullptr),
      _retain_guard(std::move(retain_guard))
{
}

ApplyBucketDiffState::~ApplyBucketDiffState()
{
    try {
        sync_bucket_info();
    } catch (std::exception& e) {
        if (_fail_message.empty()) {
            _fail_message = e.what();
        }
    }
    if (_promise.has_value()) {
        _promise.value().set_value(_fail_message);
    }
    if (_delayed_reply) {
        if (!_delayed_reply->getResult().failed() && !_fail_message.empty()) {
            _delayed_reply->setResult(api::ReturnCode(api::ReturnCode::INTERNAL_FAILURE, _fail_message));
        }
        if (_sender) {
            _sender->sendReply(std::move(_delayed_reply));
        } else {
            // _tracker->_reply and _delayed_reply points to the same reply.
            _tracker->sendReply();
        }
    }
}

void
ApplyBucketDiffState::on_entry_complete(std::unique_ptr<Result> result, const document::DocumentId &doc_id, const char *op)
{
    if (result->hasError() && !_failed_flag.test_and_set()) {
        vespalib::asciistream ss;
        ss << "Failed " << op
           << " for " << doc_id.toString()
           << " in " << _bucket
           << ": " << result->toString();
        _fail_message = ss.str();
    }
}

void
ApplyBucketDiffState::mark_stale_bucket_info()
{
    _stale_bucket_info = true;
}

void
ApplyBucketDiffState::sync_bucket_info()
{
    if (_stale_bucket_info) {
        _merge_bucket_info_syncer.sync_bucket_info(_bucket);
        _stale_bucket_info = false;
    }
}

std::future<vespalib::string>
ApplyBucketDiffState::get_future()
{
    _promise = std::promise<vespalib::string>();
    return _promise.value().get_future();
}

void
ApplyBucketDiffState::set_delayed_reply(std::unique_ptr<MessageTracker>&& tracker, std::shared_ptr<api::StorageReply>&& delayed_reply)
{
    _tracker = std::move(tracker);
    _delayed_reply = std::move(delayed_reply);
}

void
ApplyBucketDiffState::set_delayed_reply(std::unique_ptr<MessageTracker>&& tracker, MessageSender& sender, std::shared_ptr<api::StorageReply>&& delayed_reply)
{
    _tracker = std::move(tracker);
    _sender = &sender;
    _delayed_reply = std::move(delayed_reply);
}

}
<|endoftext|>


<commit_before>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <guichan.hpp>
#include <SDL/SDL.h>

#include "fflistbox.hpp"

int FFListBox::mInstances = 0;
gcn::Image *FFListBox::mHand = NULL;

FFListBox::FFListBox()
{
	if (mInstances == 0)
	{
		mHand = gcn::Image::load("images/hand.png");
	}

	mInstances++;
	setBorderSize(0);
}

FFListBox::~FFListBox()
{
	mInstances--;

	if (mInstances == 0)
	{
		delete mHand;
	}
}

void FFListBox::draw(gcn::Graphics* graphics)
{
		if (mListModel == NULL)
		{
			return;
		}

		graphics->setColor(getForegroundColor());
		graphics->setFont(getFont());

		int i, fontHeight;
		int y = 0;

		fontHeight = getFont()->getHeight();

		/**
		 * @todo Check cliprects so we do not have to iterate over elements in the list model
		 */
		for (i = 0; i < mListModel->getNumberOfElements(); ++i)
		{
			graphics->drawText(mListModel->getElementAt(i), 16, y);

			if (i == mSelected)
			{
				if (isFocused())
				{
					graphics->drawImage(mHand, 0, y);
				}
				else if ((SDL_GetTicks() / 100) & 1)
				{
					graphics->drawImage(mHand, 0, y);
				}
			}

			y += fontHeight;
		}
}

void FFListBox::setSelected(int i)
{
	if (i >= 0 &&
			i < getListModel()->getNumberOfElements() &&
			getListModel()->getElementAt(i) == "")
	{
		if (i < getSelected())
		{
			i--;
		}
		else
		{
			i++;
		}
	}

	ListBox::setSelected(i);
}
<commit_msg>Wrapping of keyboard selection has been added.<commit_after>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <guichan.hpp>
#include <SDL/SDL.h>

#include "fflistbox.hpp"

int FFListBox::mInstances = 0;
gcn::Image *FFListBox::mHand = NULL;

FFListBox::FFListBox()
{
	if (mInstances == 0)
	{
		mHand = gcn::Image::load("images/hand.png");
	}

	mInstances++;
	setBorderSize(0);
	setWrappingKeyboardSelection(true);
}

FFListBox::~FFListBox()
{
	mInstances--;

	if (mInstances == 0)
	{
		delete mHand;
	}
}

void FFListBox::draw(gcn::Graphics* graphics)
{
		if (mListModel == NULL)
		{
			return;
		}

		graphics->setColor(getForegroundColor());
		graphics->setFont(getFont());

		int i, fontHeight;
		int y = 0;

		fontHeight = getFont()->getHeight();

		/**
		 * @todo Check cliprects so we do not have to iterate over elements in the list model
		 */
		for (i = 0; i < mListModel->getNumberOfElements(); ++i)
		{
			graphics->drawText(mListModel->getElementAt(i), 16, y);

			if (i == mSelected)
			{
				if (isFocused())
				{
					graphics->drawImage(mHand, 0, y);
				}
				else if ((SDL_GetTicks() / 100) & 1)
				{
					graphics->drawImage(mHand, 0, y);
				}
			}

			y += fontHeight;
		}
}

void FFListBox::setSelected(int i)
{
	if (i >= 0 &&
			i < getListModel()->getNumberOfElements() &&
			getListModel()->getElementAt(i) == "")
	{
		if (i < getSelected())
		{
			i--;
		}
		else
		{
			i++;
		}
	}

	ListBox::setSelected(i);
}
<|endoftext|>


<commit_before>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2021 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "CustomPaintWidget.h"
#include <math.h>
#include <QEvent>
#include <QPainter>
#include <QPointer>
#include <QVBoxLayout>
#include "Code/Interface/QRDInterface.h"
#include "Code/QRDUtils.h"

CustomPaintWidgetInternal::CustomPaintWidgetInternal(CustomPaintWidget &parentCustom, bool rendering)
    : m_Custom(parentCustom), m_Rendering(rendering)
{
  setAttribute(Qt::WA_OpaquePaintEvent);
  setMouseTracking(true);
  if(m_Rendering)
    setAttribute(Qt::WA_PaintOnScreen);
}

CustomPaintWidgetInternal::~CustomPaintWidgetInternal()
{
}

CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)
{
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);

  setAttribute(Qt::WA_OpaquePaintEvent);

  m_Dark = Formatter::DarkCheckerColor();
  m_Light = Formatter::LightCheckerColor();

  QVBoxLayout *l = new QVBoxLayout(this);
  l->setContentsMargins(0, 0, 0, 0);
  l->setSpacing(0);
  setLayout(l);

  RecreateInternalWidget();
}

CustomPaintWidget::~CustomPaintWidget()
{
  if(m_Ctx)
    m_Ctx->RemoveCaptureViewer(this);
}

void CustomPaintWidget::SetContext(ICaptureContext &ctx)
{
  if(m_Ctx)
    m_Ctx->RemoveCaptureViewer(this);

  m_Ctx = &ctx;
  m_Ctx->AddCaptureViewer(this);

  RecreateInternalWidget();
}

void CustomPaintWidget::OnCaptureLoaded()
{
  RecreateInternalWidget();
}

void CustomPaintWidget::OnCaptureClosed()
{
  // forget any output we used to have
  SetOutput(NULL);
}

void CustomPaintWidget::OnSelectedEventChanged(uint32_t eventId)
{
  // nothing, we only care about capture loaded/closed events
}

void CustomPaintWidget::OnEventChanged(uint32_t eventId)
{
  // nothing, we only care about capture loaded/closed events
}

void CustomPaintWidget::update()
{
  m_Internal->update();
  QWidget::update();
}

WindowingData CustomPaintWidget::GetWidgetWindowingData()
{
  // switch to rendering here and recreate the widget, so we have an updated winId for the windowing
  // data
  m_Rendering = true;
  RecreateInternalWidget();
  return m_Ctx->CreateWindowingData(m_Internal);
}

void CustomPaintWidget::SetOutput(IReplayOutput *out)
{
  m_Output = out;
  m_Rendering = (out != NULL);

  RecreateInternalWidget();
}

void CustomPaintWidget::RecreateInternalWidget()
{
  if(!GUIInvoke::onUIThread())
  {
    GUIInvoke::call(this, [this]() { RecreateInternalWidget(); });
    return;
  }

  // if no capture is loaded, we're not rendering anymore.
  m_Rendering = m_Rendering && m_Ctx && m_Ctx->IsCaptureLoaded();

  // we need to recreate the widget if it's not matching out rendering state.
  if(m_Internal == NULL || m_Rendering != m_Internal->IsRendering())
  {
    delete m_Internal;
    m_Internal = new CustomPaintWidgetInternal(*this, m_Rendering);

    layout()->addWidget(m_Internal);
  }
}

void CustomPaintWidget::changeEvent(QEvent *event)
{
  if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange)
  {
    m_Dark = Formatter::DarkCheckerColor();
    m_Light = Formatter::LightCheckerColor();
    update();
  }
}

void CustomPaintWidget::renderInternal(QPaintEvent *e)
{
  if(m_Ctx && m_Output)
  {
    QPointer<CustomPaintWidget> me(this);
    m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) {
      if(me && me->m_Output)
        me->m_Output->Display();
    });
  }
}

void CustomPaintWidget::paintInternal(QPaintEvent *e)
{
  if(m_BackCol.isValid())
  {
    QPainter p(m_Internal);
    p.fillRect(rect(), m_BackCol);
  }
  else
  {
    int numX = (int)ceil((float)rect().width() / 64.0f);
    int numY = (int)ceil((float)rect().height() / 64.0f);

    QPainter p(m_Internal);
    for(int x = 0; x < numX; x++)
    {
      for(int y = 0; y < numY; y++)
      {
        QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;

        p.fillRect(QRect(x * 64, y * 64, 64, 64), col);
      }
    }
  }
}

void CustomPaintWidgetInternal::mousePressEvent(QMouseEvent *e)
{
  emit m_Custom.clicked(e);
}

void CustomPaintWidgetInternal::mouseDoubleClickEvent(QMouseEvent *event)
{
  emit m_Custom.doubleClicked(event);
}

void CustomPaintWidgetInternal::mouseMoveEvent(QMouseEvent *e)
{
  emit m_Custom.mouseMove(e);
}

void CustomPaintWidgetInternal::wheelEvent(QWheelEvent *e)
{
  emit m_Custom.mouseWheel(e);
}

void CustomPaintWidgetInternal::resizeEvent(QResizeEvent *e)
{
  emit m_Custom.resize(e);
}

void CustomPaintWidget::keyPressEvent(QKeyEvent *e)
{
  emit keyPress(e);
}

void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)
{
  emit keyRelease(e);
}

void CustomPaintWidget::paintEvent(QPaintEvent *e)
{
  // don't paint this widget
}

void CustomPaintWidgetInternal::paintEvent(QPaintEvent *e)
{
  if(m_Rendering)
    m_Custom.renderInternal(e);
  else
    m_Custom.paintInternal(e);
}

#if defined(RENDERDOC_PLATFORM_APPLE)
bool CustomPaintWidgetInternal::event(QEvent *e)
{
  if(m_Rendering && e->type() == QEvent::UpdateRequest)
    paintEvent(NULL);
  return QWidget::event(e);
}
#endif
<commit_msg>Don't call output displays while closing a capture<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2021 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "CustomPaintWidget.h"
#include <math.h>
#include <QEvent>
#include <QPainter>
#include <QPointer>
#include <QVBoxLayout>
#include "Code/Interface/QRDInterface.h"
#include "Code/QRDUtils.h"

CustomPaintWidgetInternal::CustomPaintWidgetInternal(CustomPaintWidget &parentCustom, bool rendering)
    : m_Custom(parentCustom), m_Rendering(rendering)
{
  setAttribute(Qt::WA_OpaquePaintEvent);
  setMouseTracking(true);
  if(m_Rendering)
    setAttribute(Qt::WA_PaintOnScreen);
}

CustomPaintWidgetInternal::~CustomPaintWidgetInternal()
{
}

CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)
{
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);

  setAttribute(Qt::WA_OpaquePaintEvent);

  m_Dark = Formatter::DarkCheckerColor();
  m_Light = Formatter::LightCheckerColor();

  QVBoxLayout *l = new QVBoxLayout(this);
  l->setContentsMargins(0, 0, 0, 0);
  l->setSpacing(0);
  setLayout(l);

  RecreateInternalWidget();
}

CustomPaintWidget::~CustomPaintWidget()
{
  if(m_Ctx)
    m_Ctx->RemoveCaptureViewer(this);
}

void CustomPaintWidget::SetContext(ICaptureContext &ctx)
{
  if(m_Ctx)
    m_Ctx->RemoveCaptureViewer(this);

  m_Ctx = &ctx;
  m_Ctx->AddCaptureViewer(this);

  RecreateInternalWidget();
}

void CustomPaintWidget::OnCaptureLoaded()
{
  RecreateInternalWidget();
}

void CustomPaintWidget::OnCaptureClosed()
{
  // forget any output we used to have
  SetOutput(NULL);
}

void CustomPaintWidget::OnSelectedEventChanged(uint32_t eventId)
{
  // nothing, we only care about capture loaded/closed events
}

void CustomPaintWidget::OnEventChanged(uint32_t eventId)
{
  // nothing, we only care about capture loaded/closed events
}

void CustomPaintWidget::update()
{
  m_Internal->update();
  QWidget::update();
}

WindowingData CustomPaintWidget::GetWidgetWindowingData()
{
  // switch to rendering here and recreate the widget, so we have an updated winId for the windowing
  // data
  m_Rendering = true;
  RecreateInternalWidget();
  return m_Ctx->CreateWindowingData(m_Internal);
}

void CustomPaintWidget::SetOutput(IReplayOutput *out)
{
  m_Output = out;
  m_Rendering = (out != NULL);

  RecreateInternalWidget();
}

void CustomPaintWidget::RecreateInternalWidget()
{
  if(!GUIInvoke::onUIThread())
  {
    GUIInvoke::call(this, [this]() { RecreateInternalWidget(); });
    return;
  }

  // if no capture is loaded, we're not rendering anymore.
  m_Rendering = m_Rendering && m_Ctx && m_Ctx->IsCaptureLoaded();

  // we need to recreate the widget if it's not matching out rendering state.
  if(m_Internal == NULL || m_Rendering != m_Internal->IsRendering())
  {
    delete m_Internal;
    m_Internal = new CustomPaintWidgetInternal(*this, m_Rendering);

    layout()->addWidget(m_Internal);
  }
}

void CustomPaintWidget::changeEvent(QEvent *event)
{
  if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange)
  {
    m_Dark = Formatter::DarkCheckerColor();
    m_Light = Formatter::LightCheckerColor();
    update();
  }
}

void CustomPaintWidget::renderInternal(QPaintEvent *e)
{
  if(m_Ctx && m_Output && m_Ctx->IsCaptureLoaded())
  {
    QPointer<CustomPaintWidget> me(this);
    m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) {
      if(me && me->m_Output && me->m_Ctx->IsCaptureLoaded())
        me->m_Output->Display();
    });
  }
}

void CustomPaintWidget::paintInternal(QPaintEvent *e)
{
  if(m_BackCol.isValid())
  {
    QPainter p(m_Internal);
    p.fillRect(rect(), m_BackCol);
  }
  else
  {
    int numX = (int)ceil((float)rect().width() / 64.0f);
    int numY = (int)ceil((float)rect().height() / 64.0f);

    QPainter p(m_Internal);
    for(int x = 0; x < numX; x++)
    {
      for(int y = 0; y < numY; y++)
      {
        QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;

        p.fillRect(QRect(x * 64, y * 64, 64, 64), col);
      }
    }
  }
}

void CustomPaintWidgetInternal::mousePressEvent(QMouseEvent *e)
{
  emit m_Custom.clicked(e);
}

void CustomPaintWidgetInternal::mouseDoubleClickEvent(QMouseEvent *event)
{
  emit m_Custom.doubleClicked(event);
}

void CustomPaintWidgetInternal::mouseMoveEvent(QMouseEvent *e)
{
  emit m_Custom.mouseMove(e);
}

void CustomPaintWidgetInternal::wheelEvent(QWheelEvent *e)
{
  emit m_Custom.mouseWheel(e);
}

void CustomPaintWidgetInternal::resizeEvent(QResizeEvent *e)
{
  emit m_Custom.resize(e);
}

void CustomPaintWidget::keyPressEvent(QKeyEvent *e)
{
  emit keyPress(e);
}

void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)
{
  emit keyRelease(e);
}

void CustomPaintWidget::paintEvent(QPaintEvent *e)
{
  // don't paint this widget
}

void CustomPaintWidgetInternal::paintEvent(QPaintEvent *e)
{
  if(m_Rendering)
    m_Custom.renderInternal(e);
  else
    m_Custom.paintInternal(e);
}

#if defined(RENDERDOC_PLATFORM_APPLE)
bool CustomPaintWidgetInternal::event(QEvent *e)
{
  if(m_Rendering && e->type() == QEvent::UpdateRequest)
    paintEvent(NULL);
  return QWidget::event(e);
}
#endif
<|endoftext|>