<commit_before>#include <cstdlib>
#include <fstream>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include "ppm_reader.hpp"
#include "pixel_sorter.hpp"
#include "sort_algorithm/yrange2.hpp"

namespace fs = boost::filesystem;
namespace qi = boost::spirit::qi;

BOOST_FUSION_ADAPT_STRUCT(
    point_type,
    (int, x)
    (int, y)
)

class csv_manager : boost::noncopyable
{
public:
    csv_manager(fs::path const& csv_path)
        : ofs_(csv_path, std::ios_base::binary | std::ios_base::out)
    {
        if(!ofs_.is_open())
        {
            // 副作用が嫌なんだけど
            std::cout << "Cannot open: " << csv_path << std::endl;
        }
        else
        {
            ofs_ << "問題セット,解答候補総数,正解総数,不正解総数,正答率\r\n";
        }
        return;
    }

    virtual ~csv_manager() = default;

    // ファイルに書き込むわけだが，trueが帰れば正常書き込み
    bool push(std::string const& identifier, int const total, int const correct)
    {
        // openされてないなら帰れ
        if(!ofs_.is_open()) return false;

        int const failure = total - correct;
        ofs_ << boost::format("%s,%d,%d,%d,%f%%\r\n")
            % identifier % total % correct % failure
            % ((double)correct / total * 100);

        return true;
    }

private:
    fs::ofstream ofs_;
};

boost::optional<std::vector<std::vector<point_type>>> read_answer(fs::path const& path, int const width, int const height)
{
    std::vector<std::vector<point_type>> ret;
    ret.reserve(height);

    fs::ifstream ifs(path);

    for(int i=0; i<height; ++i)
    {
        std::vector<point_type> line;
        line.reserve(width);

        std::string tmp;
        std::getline(ifs, tmp);

        qi::rule<std::string::iterator, point_type(), qi::space_type> const pair_rule
            = qi::lit("(") >> qi::int_ >> qi::lit(",") >> qi::int_ >> qi::lit(")");

        qi::rule<std::string::iterator, std::vector<point_type>(), qi::space_type> const rule
            = +(pair_rule);

        bool success = qi::phrase_parse(
            tmp.begin(), tmp.end(),
            rule,
            qi::space,
            line
            );

        if(!success || line.size()!=width)
        {
            return boost::none;
        }

        ret.push_back(std::move(line));
    }

    return ret;
}

namespace clammbon{
    void exit(int const status)
    {
        // Visual Studioが実装してないから
#ifdef _MSC_VER
        std::exit(status);
#else
        std::quick_exit(status);
#endif
    }
}

int main(int argc, char *argv[])
{
    pixel_sorter<yrange2> sorter;
    csv_manager csv("report.csv");

    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " <directory_path>" << std::endl;
        clammbon::exit(1);
    }

    fs::path const directory_path(argv[1]);
    if(!fs::exists(directory_path))
    {
        std::cout << "Not found: " << directory_path << std::endl;
        clammbon::exit(2);
    }

    // 指定ディレクトリ内のファイルをループ
    BOOST_FOREACH(
        fs::path const& filepath,
        std::make_pair(fs::directory_iterator(directory_path), fs::directory_iterator())
        )
    {
        // ppmファイルに対してのみの操作を行うため
        if(filepath.extension() != ".ppm") continue;

        // answerファイルのファイルパスを確認し，存在しなければ検証のパス
        fs::path answer_filename = filepath;
        answer_filename.replace_extension(".ans");
        if(!fs::exists(answer_filename))
        {
            std::cout << "Not found: Answerfile: " << answer_filename << std::endl;
            continue;
        }

        // 問題を解く
        ppm_reader reader(filepath.string());
        auto const raw_question = reader();
        auto const proposed_answers = sorter.proposed_answer(raw_question); // TODO: sorterはただ1つの解答を返すべき

        // 解答ファイルを読み取る
        auto const correct_answer = read_answer(answer_filename, raw_question.split_num.first, raw_question.split_num.second);
        if(!correct_answer)
        {
            std::cout << "Ignore file: " << answer_filename << std::endl;
            continue;
        }

        // 正しいものの数を数える
        int correct = 0;
        for(int i=0; i<proposed_answers.size(); ++i)
            if(proposed_answers[i] == *correct_answer)
                ++correct;

        csv.push(filepath.stem().string(), proposed_answers.size(), correct);
    }

    return 0;
}

<commit_msg>eval_positionを修正．<commit_after>#include <cstdlib>
#include <fstream>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include "ppm_reader.hpp"
#include "pixel_sorter.hpp"
#include "sort_algorithm/yrange2.hpp"

namespace fs = boost::filesystem;
namespace qi = boost::spirit::qi;

BOOST_FUSION_ADAPT_STRUCT(
    point_type,
    (int, x)
    (int, y)
)

class csv_manager : boost::noncopyable
{
public:
    csv_manager(fs::path const& csv_path)
        : ofs_(csv_path, std::ios_base::binary | std::ios_base::out)
    {
        if(!ofs_.is_open())
        {
            // 副作用が嫌なんだけど
            std::cout << "Cannot open: " << csv_path << std::endl;
        }
        else
        {
            ofs_ << "問題セット,解答候補総数,正解総数,不正解総数,正答率\r\n";
        }
        return;
    }

    virtual ~csv_manager() = default;

    // ファイルに書き込むわけだが，trueが帰れば正常書き込み
    bool push(std::string const& identifier, int const total, int const correct)
    {
        // openされてないなら帰れ
        if(!ofs_.is_open()) return false;

        int const failure = total - correct;
        ofs_ << boost::format("%s,%d,%d,%d,%f%%\r\n")
            % identifier % total % correct % failure
            % ((double)correct / total * 100);

        return true;
    }

private:
    fs::ofstream ofs_;
};

boost::optional<std::vector<std::vector<point_type>>> read_answer(fs::path const& path, int const width, int const height)
{
    std::vector<std::vector<point_type>> ret;
    ret.reserve(height);

    fs::ifstream ifs(path);

    for(int i=0; i<height; ++i)
    {
        std::vector<point_type> line;
        line.reserve(width);

        std::string tmp;
        std::getline(ifs, tmp);

        qi::rule<std::string::iterator, point_type(), qi::space_type> const pair_rule
            = qi::lit("(") >> qi::int_ >> qi::lit(",") >> qi::int_ >> qi::lit(")");

        qi::rule<std::string::iterator, std::vector<point_type>(), qi::space_type> const rule
            = +(pair_rule);

        bool success = qi::phrase_parse(
            tmp.begin(), tmp.end(),
            rule,
            qi::space,
            line
            );

        if(!success || line.size()!=width)
        {
            return boost::none;
        }

        ret.push_back(std::move(line));
    }

    return ret;
}

namespace clammbon{
    void exit(int const status)
    {
        // Visual Studioが実装してないから
#ifdef _MSC_VER
        std::exit(status);
#else
        std::quick_exit(status);
#endif
    }
}

int main(int argc, char *argv[])
{
    ppm_reader reader;
    pixel_sorter<yrange2> sorter;
    csv_manager csv("report.csv");

    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " <directory_path>" << std::endl;
        clammbon::exit(1);
    }

    fs::path const directory_path(argv[1]);
    if(!fs::exists(directory_path))
    {
        std::cout << "Not found: " << directory_path << std::endl;
        clammbon::exit(2);
    }

    // 指定ディレクトリ内のファイルをループ
    BOOST_FOREACH(
        fs::path const& filepath,
        std::make_pair(fs::directory_iterator(directory_path), fs::directory_iterator())
        )
    {
        // ppmファイルに対してのみの操作を行うため
        if(filepath.extension() != ".ppm") continue;

        // answerファイルのファイルパスを確認し，存在しなければ検証のパス
        fs::path answer_filename = filepath;
        answer_filename.replace_extension(".ans");
        if(!fs::exists(answer_filename))
        {
            std::cout << "Not found: Answerfile: " << answer_filename << std::endl;
            continue;
        }

        // 問題を解く
        auto const raw_question = reader.from_file(filepath.string());
        auto const proposed_answers = sorter.proposed_answer(raw_question); // TODO: sorterはただ1つの解答を返すべき

        // 解答ファイルを読み取る
        auto const correct_answer = read_answer(answer_filename, raw_question.split_num.first, raw_question.split_num.second);
        if(!correct_answer)
        {
            std::cout << "Ignore file: " << answer_filename << std::endl;
            continue;
        }

        // 正しいものの数を数える
        int correct = 0;
        for(int i=0; i<proposed_answers.size(); ++i)
            if(proposed_answers[i] == *correct_answer)
                ++correct;

        csv.push(filepath.stem().string(), proposed_answers.size(), correct);
    }

    return 0;
}

<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2013 Razor team
 * Authors:
 *   Christopher "VdoP" Regali
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *   Maciej Płaza <plaza.maciej@gmail.com>
 *   Kuzma Shapran <kuzma.shapran@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtclock.h"

#include <QDialog>
#include <QLabel>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <LXQt/GridLayout>

#include <QDateTime>
#include <QTimer>
#include <QPoint>
#include <QRect>
#include <QProxyStyle>
#include <QPainter>

#include <QDebug>

/**
 * @file lxqtclock.cpp
 * @brief implements LxQtclock and LxQtclockgui
 * @author Christopher "VdoP" Regali
 * @author Kuzma Shapran
 */

class DownscaleFontStyle : public QProxyStyle
{
    using QProxyStyle::QProxyStyle;
public:

    virtual void drawItemText(QPainter * painter, const QRect & rect, int flags
            , const QPalette & pal, bool enabled, const QString & text
            , QPalette::ColorRole textRole = QPalette::NoRole) const override
    {
        while (1 < painter->font().pointSize()
                && !(rect.size() - painter->fontMetrics().boundingRect(text).size()).isValid())
        {
            QFont f{painter->font()};
            f.setPointSize(f.pointSize() - 1);
            painter->setFont(f);
        }
        return QProxyStyle::drawItemText(painter, rect, flags, pal, enabled, text, textRole);
    }
};

/**
 * @brief constructor
 */
LxQtClock::LxQtClock(const ILxQtPanelPluginStartupInfo &startupInfo):
    QObject(),
    ILxQtPanelPlugin(startupInfo),
    mAutoRotate(true),
    mTextStyle{new DownscaleFontStyle}
{
    mMainWidget = new QWidget();
    mRotatedWidget = new LxQt::RotatedWidget(*(new QWidget()), mMainWidget);
    mContent = mRotatedWidget->content();
    mContent->setStyle(mTextStyle.data());
    mTimeLabel = new QLabel(mContent);
    mDateLabel = new QLabel(mContent);

    QVBoxLayout *borderLayout = new QVBoxLayout(mMainWidget);
    borderLayout->setContentsMargins(0, 0, 0, 0);
    borderLayout->setSpacing(0);
    borderLayout->addWidget(mRotatedWidget, 0, Qt::AlignCenter);

    mTimeLabel->setObjectName("TimeLabel");
    mDateLabel->setObjectName("DateLabel");

    mTimeLabel->setAlignment(Qt::AlignCenter);
    mDateLabel->setAlignment(Qt::AlignCenter);

    mLayout = new LxQt::GridLayout(mContent);
    mLayout->setContentsMargins(0, 0, 0, 0);
    mLayout->setStretch(LxQt::GridLayout::StretchHorizontal | LxQt::GridLayout::StretchVertical);
    mLayout->setColumnCount(1);
    mLayout->addWidget(mTimeLabel);
    mLayout->addWidget(mDateLabel);

    mClockTimer = new QTimer(this);
    mClockTimer->setTimerType(Qt::PreciseTimer);
    connect (mClockTimer, SIGNAL(timeout()), SLOT(updateTime()));

    mClockFormat = "hh:mm";

    mCalendarPopup = new CalendarPopup(mContent);

    mMainWidget->installEventFilter(this);
    settingsChanged();
}

/**
 * @brief destructor
 */
LxQtClock::~LxQtClock()
{
    delete mMainWidget;
}

QDateTime LxQtClock::currentDateTime()
{
    return QDateTime(mUseUTC ? QDateTime::currentDateTimeUtc() : QDateTime::currentDateTime());
}

/**
 * @brief updates the time
 * Color and font settings can be configured in Qt CSS
 */
void LxQtClock::updateTime()
{
    //XXX: do we need this with PreciseTimer ?
    if (currentDateTime().time().msec() > 500)
        restartTimer();

    showTime();
}

void LxQtClock::showTime()
{
    QDateTime now{currentDateTime()};
    if (mDateOnNewLine)
    {
        mTimeLabel->setText(QLocale::system().toString(now, mTimeFormat));
        mDateLabel->setText(QLocale::system().toString(now, mDateFormat));
    }
    else
    {
        mTimeLabel->setText(QLocale::system().toString(now, mClockFormat));
    }
    mTimeLabel->adjustSize();
    mDateLabel->adjustSize();

    mRotatedWidget->update();
}

void LxQtClock::restartTimer()
{
    if (mClockTimer->isActive())
        mClockTimer->stop();
    int updateInterval = mClockTimer->interval();
    QDateTime now{currentDateTime()};
    int delay = updateInterval - ((now.time().msec() + now.time().second() * 1000) % updateInterval);
    QTimer::singleShot(delay, Qt::PreciseTimer, mClockTimer, SLOT(start()));
    QTimer::singleShot(delay, Qt::PreciseTimer, this, SLOT(updateTime()));
}

void LxQtClock::settingsChanged()
{
    mFirstDayOfWeek = settings()->value("firstDayOfWeek", -1).toInt();
    if (-1 == mFirstDayOfWeek)
        mCalendarPopup->setFirstDayOfWeek(QLocale::system().firstDayOfWeek());
    else
        mCalendarPopup->setFirstDayOfWeek(static_cast<Qt::DayOfWeek>(mFirstDayOfWeek));

    mTimeFormat = settings()->value("timeFormat", QLocale::system().timeFormat(QLocale::ShortFormat).toUpper().contains("AP") ? "h:mm AP" : "HH:mm").toString();

    mUseUTC = settings()->value("UTC", false).toBool();
    if (mUseUTC)
        mTimeFormat += "' Z'";

    mDateFormat = settings()->value("dateFormat", Qt::SystemLocaleShortDate).toString();

    bool dateBeforeTime = (settings()->value("showDate", "no").toString().toLower() == "before");
    bool dateAfterTime = (settings()->value("showDate", "no").toString().toLower() == "after");
    mDateOnNewLine = (settings()->value("showDate", "no").toString().toLower() == "below");

    mAutoRotate = settings()->value("autoRotate", true).toBool();

    if (dateBeforeTime)
        mClockFormat = QString("%1 %2").arg(mDateFormat).arg(mTimeFormat);
    else if (dateAfterTime)
        mClockFormat = QString("%1 %2").arg(mTimeFormat).arg(mDateFormat);
    else
        mClockFormat = mTimeFormat;

    mDateLabel->setHidden(!mDateOnNewLine);

    realign();

    // mDateFormat usually does not contain time portion, but since it's possible to use custom date format - it has to be supported. [Kuzma Shapran]
    int updateInterval = QString(mTimeFormat + " " + mDateFormat).replace(QRegExp("'[^']*'"),"").contains("s") ? 1000 : 60000;

    QDateTime now = currentDateTime();

    showTime();

    if (mClockTimer->interval() != updateInterval)
    {
        mClockTimer->setInterval(updateInterval);

        restartTimer();
    }
}

void LxQtClock::realign()
{
    QSize min_size{0, 0};
    QSize max_size{QWIDGETSIZE_MAX, QWIDGETSIZE_MAX};
    Qt::Corner origin = Qt::TopLeftCorner;
    if (mAutoRotate)
        switch (panel()->position())
        {
        case ILxQtPanel::PositionTop:
        case ILxQtPanel::PositionBottom:
            origin = Qt::TopLeftCorner;
            break;

        case ILxQtPanel::PositionLeft:
            origin = Qt::BottomLeftCorner;
            break;

        case ILxQtPanel::PositionRight:
            origin = Qt::TopRightCorner;
            break;
        }
    else if (!panel()->isHorizontal())
    {
        min_size.setWidth(panel()->globalGometry().width());
        max_size.setWidth(min_size.width());
    }

    mLayout->setCellMinimumSize(min_size);
    mLayout->setCellMaximumSize(max_size);

    int label_height = mTimeLabel->sizeHint().height();
    min_size.setHeight(mDateOnNewLine ? label_height * 2 : label_height);
    max_size.setHeight(min_size.height());
    mContent->setMinimumSize(min_size);
    mContent->setMaximumSize(max_size);
    mContent->adjustSize();

    mRotatedWidget->setOrigin(origin);
    mRotatedWidget->adjustContentSize();
    mRotatedWidget->update();
}

void LxQtClock::activated(ActivationReason reason)
{
    if (reason != ILxQtPanelPlugin::Trigger)
        return;

    if (!mCalendarPopup->isVisible())
    {
        QRect pos = calculatePopupWindowPos(mCalendarPopup->size());
        mCalendarPopup->move(pos.topLeft());
        mCalendarPopup->show();
    }
    else
    {
        mCalendarPopup->hide();
    }
}

QDialog * LxQtClock::configureDialog()
{
     return new LxQtClockConfiguration(*settings());
}

bool LxQtClock::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == mMainWidget)
    {
        if (event->type() == QEvent::ToolTip)
            mMainWidget->setToolTip(QDateTime::currentDateTime().toString(Qt::DefaultLocaleLongDate));

        return false;
    }

    return false;
}
<commit_msg>plugin-clock: adjust size only when needed<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2013 Razor team
 * Authors:
 *   Christopher "VdoP" Regali
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *   Maciej Płaza <plaza.maciej@gmail.com>
 *   Kuzma Shapran <kuzma.shapran@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtclock.h"

#include <QDialog>
#include <QLabel>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <LXQt/GridLayout>

#include <QDateTime>
#include <QTimer>
#include <QPoint>
#include <QRect>
#include <QProxyStyle>
#include <QPainter>

#include <QDebug>

/**
 * @file lxqtclock.cpp
 * @brief implements LxQtclock and LxQtclockgui
 * @author Christopher "VdoP" Regali
 * @author Kuzma Shapran
 */

class DownscaleFontStyle : public QProxyStyle
{
    using QProxyStyle::QProxyStyle;
public:

    virtual void drawItemText(QPainter * painter, const QRect & rect, int flags
            , const QPalette & pal, bool enabled, const QString & text
            , QPalette::ColorRole textRole = QPalette::NoRole) const override
    {
        while (1 < painter->font().pointSize()
                && !(rect.size() - painter->fontMetrics().boundingRect(text).size()).isValid())
        {
            QFont f{painter->font()};
            f.setPointSize(f.pointSize() - 1);
            painter->setFont(f);
        }
        return QProxyStyle::drawItemText(painter, rect, flags, pal, enabled, text, textRole);
    }
};

/**
 * @brief constructor
 */
LxQtClock::LxQtClock(const ILxQtPanelPluginStartupInfo &startupInfo):
    QObject(),
    ILxQtPanelPlugin(startupInfo),
    mAutoRotate(true),
    mTextStyle{new DownscaleFontStyle}
{
    mMainWidget = new QWidget();
    mRotatedWidget = new LxQt::RotatedWidget(*(new QWidget()), mMainWidget);
    mContent = mRotatedWidget->content();
    mContent->setStyle(mTextStyle.data());
    mTimeLabel = new QLabel(mContent);
    mDateLabel = new QLabel(mContent);

    QVBoxLayout *borderLayout = new QVBoxLayout(mMainWidget);
    borderLayout->setContentsMargins(0, 0, 0, 0);
    borderLayout->setSpacing(0);
    borderLayout->addWidget(mRotatedWidget, 0, Qt::AlignCenter);

    mTimeLabel->setObjectName("TimeLabel");
    mDateLabel->setObjectName("DateLabel");

    mTimeLabel->setAlignment(Qt::AlignCenter);
    mDateLabel->setAlignment(Qt::AlignCenter);

    mLayout = new LxQt::GridLayout(mContent);
    mLayout->setContentsMargins(0, 0, 0, 0);
    mLayout->setStretch(LxQt::GridLayout::StretchHorizontal | LxQt::GridLayout::StretchVertical);
    mLayout->setColumnCount(1);
    mLayout->addWidget(mTimeLabel);
    mLayout->addWidget(mDateLabel);

    mClockTimer = new QTimer(this);
    mClockTimer->setTimerType(Qt::PreciseTimer);
    connect (mClockTimer, SIGNAL(timeout()), SLOT(updateTime()));

    mClockFormat = "hh:mm";

    mCalendarPopup = new CalendarPopup(mContent);

    mMainWidget->installEventFilter(this);
    settingsChanged();
}

/**
 * @brief destructor
 */
LxQtClock::~LxQtClock()
{
    delete mMainWidget;
}

QDateTime LxQtClock::currentDateTime()
{
    return QDateTime(mUseUTC ? QDateTime::currentDateTimeUtc() : QDateTime::currentDateTime());
}

/**
 * @brief updates the time
 * Color and font settings can be configured in Qt CSS
 */
void LxQtClock::updateTime()
{
    //XXX: do we need this with PreciseTimer ?
    if (currentDateTime().time().msec() > 500)
        restartTimer();

    showTime();
}

void LxQtClock::showTime()
{
    QDateTime now{currentDateTime()};
    if (mDateOnNewLine)
    {
        mTimeLabel->setText(QLocale::system().toString(now, mTimeFormat));
        mDateLabel->setText(QLocale::system().toString(now, mDateFormat));
    }
    else
    {
        mTimeLabel->setText(QLocale::system().toString(now, mClockFormat));
    }
    mTimeLabel->adjustSize();
    mDateLabel->adjustSize();

    mRotatedWidget->update();
}

void LxQtClock::restartTimer()
{
    if (mClockTimer->isActive())
        mClockTimer->stop();
    int updateInterval = mClockTimer->interval();
    QDateTime now{currentDateTime()};
    int delay = updateInterval - ((now.time().msec() + now.time().second() * 1000) % updateInterval);
    QTimer::singleShot(delay, Qt::PreciseTimer, mClockTimer, SLOT(start()));
    QTimer::singleShot(delay, Qt::PreciseTimer, this, SLOT(updateTime()));
}

void LxQtClock::settingsChanged()
{
    mFirstDayOfWeek = settings()->value("firstDayOfWeek", -1).toInt();
    if (-1 == mFirstDayOfWeek)
        mCalendarPopup->setFirstDayOfWeek(QLocale::system().firstDayOfWeek());
    else
        mCalendarPopup->setFirstDayOfWeek(static_cast<Qt::DayOfWeek>(mFirstDayOfWeek));

    mTimeFormat = settings()->value("timeFormat", QLocale::system().timeFormat(QLocale::ShortFormat).toUpper().contains("AP") ? "h:mm AP" : "HH:mm").toString();

    mUseUTC = settings()->value("UTC", false).toBool();
    if (mUseUTC)
        mTimeFormat += "' Z'";

    mDateFormat = settings()->value("dateFormat", Qt::SystemLocaleShortDate).toString();

    bool dateBeforeTime = (settings()->value("showDate", "no").toString().toLower() == "before");
    bool dateAfterTime = (settings()->value("showDate", "no").toString().toLower() == "after");
    mDateOnNewLine = (settings()->value("showDate", "no").toString().toLower() == "below");

    mAutoRotate = settings()->value("autoRotate", true).toBool();

    if (dateBeforeTime)
        mClockFormat = QString("%1 %2").arg(mDateFormat).arg(mTimeFormat);
    else if (dateAfterTime)
        mClockFormat = QString("%1 %2").arg(mTimeFormat).arg(mDateFormat);
    else
        mClockFormat = mTimeFormat;

    mDateLabel->setHidden(!mDateOnNewLine);

    realign();

    // mDateFormat usually does not contain time portion, but since it's possible to use custom date format - it has to be supported. [Kuzma Shapran]
    int updateInterval = QString(mTimeFormat + " " + mDateFormat).replace(QRegExp("'[^']*'"),"").contains("s") ? 1000 : 60000;

    QDateTime now = currentDateTime();

    showTime();

    if (mClockTimer->interval() != updateInterval)
    {
        mClockTimer->setInterval(updateInterval);

        restartTimer();
    }
}

void LxQtClock::realign()
{
    QSize min_size{0, 0};
    QSize max_size{QWIDGETSIZE_MAX, QWIDGETSIZE_MAX};
    Qt::Corner origin = Qt::TopLeftCorner;
    if (mAutoRotate)
        switch (panel()->position())
        {
        case ILxQtPanel::PositionTop:
        case ILxQtPanel::PositionBottom:
            origin = Qt::TopLeftCorner;
            break;

        case ILxQtPanel::PositionLeft:
            origin = Qt::BottomLeftCorner;
            break;

        case ILxQtPanel::PositionRight:
            origin = Qt::TopRightCorner;
            break;
        }
    else if (!panel()->isHorizontal())
    {
        min_size.setWidth(panel()->globalGometry().width());
        max_size.setWidth(min_size.width());
    }

    mLayout->setCellMinimumSize(min_size);
    mLayout->setCellMaximumSize(max_size);

    int label_height = mTimeLabel->sizeHint().height();
    min_size.setHeight(mDateOnNewLine ? label_height * 2 : label_height);
    max_size.setHeight(min_size.height());

    const bool changed = mContent->maximumSize() != max_size || mContent->minimumSize() != min_size
        || mRotatedWidget->origin() != origin;

    mContent->setMinimumSize(min_size);
    mContent->setMaximumSize(max_size);
    mRotatedWidget->setOrigin(origin);

    if (changed)
    {
        mRotatedWidget->adjustContentSize();
        mRotatedWidget->update();
    }
}

void LxQtClock::activated(ActivationReason reason)
{
    if (reason != ILxQtPanelPlugin::Trigger)
        return;

    if (!mCalendarPopup->isVisible())
    {
        QRect pos = calculatePopupWindowPos(mCalendarPopup->size());
        mCalendarPopup->move(pos.topLeft());
        mCalendarPopup->show();
    }
    else
    {
        mCalendarPopup->hide();
    }
}

QDialog * LxQtClock::configureDialog()
{
     return new LxQtClockConfiguration(*settings());
}

bool LxQtClock::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == mMainWidget)
    {
        if (event->type() == QEvent::ToolTip)
            mMainWidget->setToolTip(QDateTime::currentDateTime().toString(Qt::DefaultLocaleLongDate));

        return false;
    }

    return false;
}
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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 "flusspferd/object.hpp"
#include "flusspferd/property_iterator.hpp"
#include "flusspferd/function.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/root.hpp"
#include "flusspferd/arguments.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/implementation/init.hpp"
#include "flusspferd/implementation/value.hpp"
#include "flusspferd/implementation/object.hpp"
#include <cassert>
#include <js/jsapi.h>

using namespace flusspferd;

object::object() : Impl::object_impl(0) { }
object::~object() { }

void object::seal(bool deep) {
  if (!JS_SealObject(Impl::current_context(), get(), deep))
    throw exception("Could not seal object");
}

object object::get_parent() {
  if (!is_valid())
    throw exception("Could not get object parent (object is null)");
  return Impl::wrap_object(JS_GetParent(Impl::current_context(), get()));
}

object object::get_prototype() {
  if (!is_valid())
    throw exception("Could not get object prototype (object is null)");
  return Impl::wrap_object(JS_GetPrototype(Impl::current_context(), get()));
}

void object::set_parent(object const &o) {
  if (!is_valid())
    throw exception("Could not set parent (object is null)");
  if (!JS_SetParent(Impl::current_context(), get(), o.get_const()))
    throw exception("Could not set object parent");
}

void object::set_prototype(object const &o) {
  if (!is_valid())
    throw exception("Could not set object prototype (object is null)");
  if (!JS_SetPrototype(Impl::current_context(), get(), o.get_const()))
    throw exception("Could not set object prototype");
}

void object::set_property(char const *name, value const &v_) {
  if (!is_valid())
    throw exception("Could not set property (object is null)");
  value v = v_;
  if (!JS_SetProperty(Impl::current_context(), get(), name,
                      Impl::get_jsvalp(v)))
    throw exception("Could not set property");
}

void object::set_property(std::string const &name, value const &v) {
  set_property(name.c_str(), v);
}

void object::set_property(value const &id, value const &v_) {
  if (!is_valid())
    throw exception("Could not set property (object is null)");
  local_root_scope scope;
  value v = v_;
  string name = id.to_string();
  if (!JS_SetUCProperty(Impl::current_context(), get(),
                        name.data(), name.length(),
                        Impl::get_jsvalp(v)))
    throw exception("Could not set property");
}

value object::get_property(char const *name) const {
  if (!is_valid())
    throw exception("Could not get property (object is null)");
  value result;
  if (!JS_GetProperty(Impl::current_context(), get_const(),
                      name, Impl::get_jsvalp(result)))
    throw exception("Could not get property");
  return result;
}

value object::get_property(std::string const &name) const {
  return get_property(name.c_str());
}

value object::get_property(value const &id) const {
  if (!is_valid())
    throw exception("Could not get property (object is null)");
  value result;
  local_root_scope scope;
  string name = id.to_string();
  if (!JS_GetUCProperty(Impl::current_context(), get_const(),
                        name.data(), name.length(),
                        Impl::get_jsvalp(result)))
    throw exception("Could not get property");
  return result;
}

bool object::has_property(char const *name) const {
  if (!is_valid())
    throw exception("Could not check property (object is null)");
  JSBool foundp;
  if (!JS_HasProperty(Impl::current_context(), get_const(), name,
                      &foundp))
    throw exception("Could not check property");
  return foundp;
}

bool object::has_property(std::string const &name) const {
  return has_property(name.c_str());
}

bool object::has_property(value const &id) const {
  if (!is_valid())
    throw exception("Could not check property (object is null)");
  local_root_scope scope;
  string name = id.to_string();
  JSBool foundp;
  if (!JS_HasUCProperty(Impl::current_context(), get_const(),
                        name.data(), name.length(),
                        &foundp))
    throw exception("Could not check property");
  return foundp;
}

void object::delete_property(char const *name) {
  if (!is_valid())
    throw exception("Could not delete property (object is null)");
  if (!JS_DeleteProperty(Impl::current_context(), get(), name))
    throw exception("Could not delete property");
}

void object::delete_property(std::string const &name) {
  delete_property(name.c_str());
}

void object::delete_property(value const &id) {
  if (!is_valid())
    throw exception("Could not delete property (object is null)");
  local_root_scope scope;
  string name = id.to_string();
  jsval dummy;
  if (!JS_DeleteUCProperty2(Impl::current_context(), get(),
                            name.data(), name.length(), &dummy))
    throw exception("Could not delete property");
}

property_iterator object::begin() const {
  return property_iterator(*this);
}

property_iterator object::end() const {
  return property_iterator();
}

void object::define_property(
  string const &name, value const &init_value,
  struct property_attributes const attrs)
{
  if (!is_valid())
    throw exception("Could not define property (object is null)");

  unsigned flags = attrs.flags;
  value v;
  v = init_value;

  function getter;
  if (attrs.getter) getter = attrs.getter.get();
  function setter;
  if (attrs.setter) setter = attrs.setter.get();

  JSObject *getter_o = Impl::get_object(getter);
  JSObject *setter_o = Impl::get_object(setter);

  unsigned sm_flags = 0;

  if (~flags & dont_enumerate) sm_flags |= JSPROP_ENUMERATE;
  if (flags & read_only_property) sm_flags |= JSPROP_READONLY;
  if (flags & permanent_property) sm_flags |= JSPROP_PERMANENT;
  if (flags & shared_property) sm_flags |= JSPROP_SHARED;

  if (getter_o) sm_flags |= JSPROP_GETTER;
  if (setter_o) sm_flags |= JSPROP_SETTER;

  if(!JS_DefineUCProperty(Impl::current_context(), get_const(),
                          name.data(), name.length(),
                          Impl::get_jsval(v),
                          *(JSPropertyOp*) &getter_o,
                          *(JSPropertyOp*) &setter_o,
                          sm_flags))
    throw exception("Could not define property");
}

void object::define_property(
  std::string const &name_, value const &init_value,
  struct property_attributes attrs)
{
  local_root_scope scope;
  string name(name_);
  define_property(name, init_value, attrs);
}

void object::define_property(
  char const *name_, value const &init_value,
  struct property_attributes const attrs)
{
  local_root_scope scope;
  string name(name_);
  define_property(name, init_value,attrs);
}

bool object::is_valid() const {
  return get_const();
}

value object::apply(object const &fn, arguments const &arg_) {
  if (!is_valid())
    throw exception("Could not apply function (object is null)");

  value fnv(fn);
  root_value result((value()));

  arguments arg(arg_);

  JSBool status = JS_CallFunctionValue(
      Impl::current_context(),
      get(),
      Impl::get_jsval(fnv),
      arg.size(),
      arg.get(),
      Impl::get_jsvalp(result));

  if (!status)
    throw exception("Could not call function");

  return result;
}

value object::call(char const *fn, arguments const &arg_) {
  if (!is_valid())
    throw exception("Could not call function (object is null)");

  root_value result((value()));

  arguments arg(arg_);

  JSBool status = JS_CallFunctionName(
      Impl::current_context(),
      get(),
      fn,
      arg.size(),
      arg.get(),
      Impl::get_jsvalp(result));

  if (!status)
    throw exception("Could not call function");

  return result;
}

value object::call(std::string const &fn, arguments const &arg) {
  return call(fn.c_str(), arg);
}

value object::call(object o, arguments const &arg) {
  return o.apply(*this, arg);
}

value object::call(arguments const &arg) {
  return call(global(), arg);
}

bool object::is_array() const {
  return JS_IsArrayObject(Impl::current_context(), get_const());
}

/*
bool object::property_attributes(char const *name_, struct object::property_attributes &attrs) {
  local_root_scope scope;
  string name(name_);
  //return property_attributes(name, attrs);
}

bool object::property_attributes(std::string name_, struct property_attributes &attrs) {
  local_root_scope scope;
  string name(name_);
  //return property_attributes(name, attrs);
}
*/

bool object::get_property_attributes(string const &name, struct property_attributes &attrs) {
  JSBool found;
  void *getter_op, *setter_op;
  uintN sm_flags;

  attrs.flags = 0;
  attrs.getter = boost::none;
  attrs.setter = boost::none;
  JSBool success = JS_GetUCPropertyAttrsGetterAndSetter(
          Impl::current_context(), get_const(), name.data(), name.length(),
          &sm_flags, &found, (JSPropertyOp*)&getter_op, (JSPropertyOp*)&setter_op);

  if (!success)
    throw exception("Could not query property attributes");

  if (!found)
    return false;

  if (~sm_flags & JSPROP_ENUMERATE) attrs.flags |= dont_enumerate;
  if (sm_flags & JSPROP_PERMANENT) attrs.flags |= permanent_property;
  if (sm_flags & JSPROP_READONLY) attrs.flags |= read_only_property;
  if (sm_flags & JSPROP_SHARED) attrs.flags |= shared_property;

  if (getter_op) {
    if (sm_flags & JSPROP_GETTER) {
      attrs.getter = Impl::wrap_object((JSObject*)getter_op);
    } else {
      // What do i set attrs.getter to here....?
    }
  }

  if (setter_op) {
    if (sm_flags & JSPROP_SETTER) {
      attrs.setter = Impl::wrap_object((JSObject*)setter_op);
    } else {
      // What do i set attrs.setter to here....?
    }
  }
  return true;
}
<commit_msg>Core: add ctors for property_attributes and other overloads to get_property_attributes<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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 "flusspferd/object.hpp"
#include "flusspferd/property_iterator.hpp"
#include "flusspferd/function.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/root.hpp"
#include "flusspferd/arguments.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/implementation/init.hpp"
#include "flusspferd/implementation/value.hpp"
#include "flusspferd/implementation/object.hpp"
#include <cassert>
#include <js/jsapi.h>

using namespace flusspferd;

object::object() : Impl::object_impl(0) { }
object::~object() { }

void object::seal(bool deep) {
  if (!JS_SealObject(Impl::current_context(), get(), deep))
    throw exception("Could not seal object");
}

object object::get_parent() {
  if (!is_valid())
    throw exception("Could not get object parent (object is null)");
  return Impl::wrap_object(JS_GetParent(Impl::current_context(), get()));
}

object object::get_prototype() {
  if (!is_valid())
    throw exception("Could not get object prototype (object is null)");
  return Impl::wrap_object(JS_GetPrototype(Impl::current_context(), get()));
}

void object::set_parent(object const &o) {
  if (!is_valid())
    throw exception("Could not set parent (object is null)");
  if (!JS_SetParent(Impl::current_context(), get(), o.get_const()))
    throw exception("Could not set object parent");
}

void object::set_prototype(object const &o) {
  if (!is_valid())
    throw exception("Could not set object prototype (object is null)");
  if (!JS_SetPrototype(Impl::current_context(), get(), o.get_const()))
    throw exception("Could not set object prototype");
}

void object::set_property(char const *name, value const &v_) {
  if (!is_valid())
    throw exception("Could not set property (object is null)");
  value v = v_;
  if (!JS_SetProperty(Impl::current_context(), get(), name,
                      Impl::get_jsvalp(v)))
    throw exception("Could not set property");
}

void object::set_property(std::string const &name, value const &v) {
  set_property(name.c_str(), v);
}

void object::set_property(value const &id, value const &v_) {
  if (!is_valid())
    throw exception("Could not set property (object is null)");
  local_root_scope scope;
  value v = v_;
  string name = id.to_string();
  if (!JS_SetUCProperty(Impl::current_context(), get(),
                        name.data(), name.length(),
                        Impl::get_jsvalp(v)))
    throw exception("Could not set property");
}

value object::get_property(char const *name) const {
  if (!is_valid())
    throw exception("Could not get property (object is null)");
  value result;
  if (!JS_GetProperty(Impl::current_context(), get_const(),
                      name, Impl::get_jsvalp(result)))
    throw exception("Could not get property");
  return result;
}

value object::get_property(std::string const &name) const {
  return get_property(name.c_str());
}

value object::get_property(value const &id) const {
  if (!is_valid())
    throw exception("Could not get property (object is null)");
  value result;
  local_root_scope scope;
  string name = id.to_string();
  if (!JS_GetUCProperty(Impl::current_context(), get_const(),
                        name.data(), name.length(),
                        Impl::get_jsvalp(result)))
    throw exception("Could not get property");
  return result;
}

bool object::has_property(char const *name) const {
  if (!is_valid())
    throw exception("Could not check property (object is null)");
  JSBool foundp;
  if (!JS_HasProperty(Impl::current_context(), get_const(), name,
                      &foundp))
    throw exception("Could not check property");
  return foundp;
}

bool object::has_property(std::string const &name) const {
  return has_property(name.c_str());
}

bool object::has_property(value const &id) const {
  if (!is_valid())
    throw exception("Could not check property (object is null)");
  local_root_scope scope;
  string name = id.to_string();
  JSBool foundp;
  if (!JS_HasUCProperty(Impl::current_context(), get_const(),
                        name.data(), name.length(),
                        &foundp))
    throw exception("Could not check property");
  return foundp;
}

void object::delete_property(char const *name) {
  if (!is_valid())
    throw exception("Could not delete property (object is null)");
  if (!JS_DeleteProperty(Impl::current_context(), get(), name))
    throw exception("Could not delete property");
}

void object::delete_property(std::string const &name) {
  delete_property(name.c_str());
}

void object::delete_property(value const &id) {
  if (!is_valid())
    throw exception("Could not delete property (object is null)");
  local_root_scope scope;
  string name = id.to_string();
  jsval dummy;
  if (!JS_DeleteUCProperty2(Impl::current_context(), get(),
                            name.data(), name.length(), &dummy))
    throw exception("Could not delete property");
}

property_iterator object::begin() const {
  return property_iterator(*this);
}

property_iterator object::end() const {
  return property_iterator();
}

void object::define_property(
  string const &name, value const &init_value,
  struct property_attributes const attrs)
{
  if (!is_valid())
    throw exception("Could not define property (object is null)");

  unsigned flags = attrs.flags;
  value v;
  v = init_value;

  function getter;
  if (attrs.getter) getter = attrs.getter.get();
  function setter;
  if (attrs.setter) setter = attrs.setter.get();

  JSObject *getter_o = Impl::get_object(getter);
  JSObject *setter_o = Impl::get_object(setter);

  unsigned sm_flags = 0;

  if (~flags & dont_enumerate) sm_flags |= JSPROP_ENUMERATE;
  if (flags & read_only_property) sm_flags |= JSPROP_READONLY;
  if (flags & permanent_property) sm_flags |= JSPROP_PERMANENT;
  if (flags & shared_property) sm_flags |= JSPROP_SHARED;

  if (getter_o) sm_flags |= JSPROP_GETTER;
  if (setter_o) sm_flags |= JSPROP_SETTER;

  if(!JS_DefineUCProperty(Impl::current_context(), get_const(),
                          name.data(), name.length(),
                          Impl::get_jsval(v),
                          *(JSPropertyOp*) &getter_o,
                          *(JSPropertyOp*) &setter_o,
                          sm_flags))
    throw exception("Could not define property");
}

void object::define_property(
  std::string const &name_, value const &init_value,
  struct property_attributes attrs)
{
  local_root_scope scope;
  string name(name_);
  define_property(name, init_value, attrs);
}

void object::define_property(
  char const *name_, value const &init_value,
  struct property_attributes const attrs)
{
  local_root_scope scope;
  string name(name_);
  define_property(name, init_value,attrs);
}

bool object::is_valid() const {
  return get_const();
}

value object::apply(object const &fn, arguments const &arg_) {
  if (!is_valid())
    throw exception("Could not apply function (object is null)");

  value fnv(fn);
  root_value result((value()));

  arguments arg(arg_);

  JSBool status = JS_CallFunctionValue(
      Impl::current_context(),
      get(),
      Impl::get_jsval(fnv),
      arg.size(),
      arg.get(),
      Impl::get_jsvalp(result));

  if (!status)
    throw exception("Could not call function");

  return result;
}

value object::call(char const *fn, arguments const &arg_) {
  if (!is_valid())
    throw exception("Could not call function (object is null)");

  root_value result((value()));

  arguments arg(arg_);

  JSBool status = JS_CallFunctionName(
      Impl::current_context(),
      get(),
      fn,
      arg.size(),
      arg.get(),
      Impl::get_jsvalp(result));

  if (!status)
    throw exception("Could not call function");

  return result;
}

value object::call(std::string const &fn, arguments const &arg) {
  return call(fn.c_str(), arg);
}

value object::call(object o, arguments const &arg) {
  return o.apply(*this, arg);
}

value object::call(arguments const &arg) {
  return call(global(), arg);
}

bool object::is_array() const {
  return JS_IsArrayObject(Impl::current_context(), get_const());
}

bool object::get_property_attributes(char const *name_, struct property_attributes &attrs) {
  local_root_scope scope;
  string name(name_);
  return get_property_attributes(name, attrs);
}

bool object::get_property_attributes(std::string name_, struct property_attributes &attrs) {
  local_root_scope scope;
  string name(name_);
  return get_property_attributes(name, attrs);
}

bool object::get_property_attributes(string const &name, struct property_attributes &attrs) {
  JSBool found;
  void *getter_op, *setter_op;
  uintN sm_flags;

  attrs.flags = 0;
  attrs.getter = boost::none;
  attrs.setter = boost::none;
  JSBool success = JS_GetUCPropertyAttrsGetterAndSetter(
          Impl::current_context(), get_const(), name.data(), name.length(),
          &sm_flags, &found, (JSPropertyOp*)&getter_op, (JSPropertyOp*)&setter_op);

  if (!success)
    throw exception("Could not query property attributes");

  if (!found)
    return false;

  if (~sm_flags & JSPROP_ENUMERATE) attrs.flags |= dont_enumerate;
  if (sm_flags & JSPROP_PERMANENT) attrs.flags |= permanent_property;
  if (sm_flags & JSPROP_READONLY) attrs.flags |= read_only_property;
  if (sm_flags & JSPROP_SHARED) attrs.flags |= shared_property;

  if (getter_op) {
    if (sm_flags & JSPROP_GETTER) {
      attrs.getter = Impl::wrap_object((JSObject*)getter_op);
    } else {
      // What do i set attrs.getter to here....?
    }
  }

  if (setter_op) {
    if (sm_flags & JSPROP_SETTER) {
      attrs.setter = Impl::wrap_object((JSObject*)setter_op);
    } else {
      // What do i set attrs.setter to here....?
    }
  }
  return true;
}

object::property_attributes::property_attributes()
  : flags(0u),
    getter(boost::none),
    setter(boost::none)
{}

object::property_attributes::property_attributes(unsigned flags,
                        boost::optional<function const &> getter,
                        boost::optional<function const &> setter)
  : flags(flags),
    getter(getter),
    setter(setter)
{}
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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 "flusspferd/string.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/spidermonkey/init.hpp"
#include "flusspferd/spidermonkey/value.hpp"
#include "flusspferd/spidermonkey/context.hpp"
#include <js/jsapi.h>
#include <cstring>

using namespace flusspferd;

Impl::string_impl::string_impl(char const *s)
 : str(JS_NewStringCopyZ(Impl::current_context(), s))
{
  if (!str)
    throw exception("Could not create string");
}

Impl::string_impl::string_impl(char const *s, std::size_t n)
  : str(JS_NewStringCopyN(Impl::current_context(), s, n))
{
  if (!str)
    throw exception("Could not create string");
}

Impl::string_impl::string_impl(char16_t const *s, std::size_t n)
  : str(JS_NewUCStringCopyN(Impl::current_context(), s, n))
{
  if (!str)
    throw exception("Could not create string");
}

Impl::string_impl::string_impl(value const &v)
  : str(JS_ValueToString(Impl::current_context(),
                         Impl::get_jsval(const_cast<value&>(v))))
{
  if (!str)
    throw exception("Could not create string");
}

namespace {
  JSString *get_string(string const &s) {
    return Impl::get_string(const_cast<string&>(s));
  }
}

string::string() { }
string::string(value const &v) : Impl::string_impl(v) { }
string::string(char const *s) : Impl::string_impl(s) { }
string::string(std::string const &s)
  : Impl::string_impl(s.data(), s.size()) { }
string::string(std::basic_string<char16_t> const &s)
  : Impl::string_impl(s.data(), s.size()) { }
string::~string() { }

std::size_t string::length() const {
  assert(get_string(*this));
  return JS_GetStringLength(get_string(*this));
}

char const *string::c_str() const {
  assert(get_string(*this));
  return JS_GetStringBytes(get_string(*this));
}

std::string string::to_string() const {
  assert(get_string(*this));
  return JS_GetStringBytes(get_string(*this));
}

std::basic_string<char16_t> string::to_utf16_string() const {
  JSString *str = get_string(*this);
  assert(str);
  std::size_t len = JS_GetStringLength(str);
  jschar *text = JS_GetStringChars(str);
  return std::basic_string<char16_t>(text, len);
}

bool operator==(string const &lhs, std::string const &rhs) {
  return JS_CompareStrings(get_string(lhs), get_string(rhs)) == 0;
}

bool operator<(string const &lhs, string const &rhs) {
  return JS_CompareStrings(get_string(lhs), get_string(rhs)) < 0;
}

string string::substr(size_t start, size_t length) {
  JSContext *ctx = Impl::current_context();
  JSString *new_string =
    JS_NewDependentString(ctx, get_string(*this), start, length);
  if (!new_string)
    throw exception("Could not create substring");
  return Impl::wrap_string(new_string);
}
<commit_msg>added missing method definition<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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 "flusspferd/string.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/spidermonkey/init.hpp"
#include "flusspferd/spidermonkey/value.hpp"
#include "flusspferd/spidermonkey/context.hpp"
#include <js/jsapi.h>
#include <cstring>

using namespace flusspferd;

Impl::string_impl::string_impl(char const *s)
 : str(JS_NewStringCopyZ(Impl::current_context(), s))
{
  if (!str)
    throw exception("Could not create string");
}

Impl::string_impl::string_impl(char const *s, std::size_t n)
  : str(JS_NewStringCopyN(Impl::current_context(), s, n))
{
  if (!str)
    throw exception("Could not create string");
}

Impl::string_impl::string_impl(char16_t const *s, std::size_t n)
  : str(JS_NewUCStringCopyN(Impl::current_context(), s, n))
{
  if (!str)
    throw exception("Could not create string");
}

Impl::string_impl::string_impl(value const &v)
  : str(JS_ValueToString(Impl::current_context(),
                         Impl::get_jsval(const_cast<value&>(v))))
{
  if (!str)
    throw exception("Could not create string");
}

namespace {
  JSString *get_string(string const &s) {
    return Impl::get_string(const_cast<string&>(s));
  }
}

string::string() { }
string::string(value const &v) : Impl::string_impl(v) { }
string::string(char const *s) : Impl::string_impl(s) { }
string::string(std::string const &s)
  : Impl::string_impl(s.data(), s.size()) { }
string::string(std::basic_string<char16_t> const &s)
  : Impl::string_impl(s.data(), s.size()) { }
string::~string() { }

string &string::operator=(string const &o) {
  string_impl::operator=(o);
  return *this;
}

std::size_t string::length() const {
  assert(get_string(*this));
  return JS_GetStringLength(get_string(*this));
}

char const *string::c_str() const {
  assert(get_string(*this));
  return JS_GetStringBytes(get_string(*this));
}

std::string string::to_string() const {
  assert(get_string(*this));
  return JS_GetStringBytes(get_string(*this));
}

std::basic_string<char16_t> string::to_utf16_string() const {
  JSString *str = get_string(*this);
  assert(str);
  std::size_t len = JS_GetStringLength(str);
  jschar *text = JS_GetStringChars(str);
  return std::basic_string<char16_t>(text, len);
}

bool operator==(string const &lhs, std::string const &rhs) {
  return JS_CompareStrings(get_string(lhs), get_string(rhs)) == 0;
}

bool operator<(string const &lhs, string const &rhs) {
  return JS_CompareStrings(get_string(lhs), get_string(rhs)) < 0;
}

string string::substr(size_t start, size_t length) {
  JSContext *ctx = Impl::current_context();
  JSString *new_string =
    JS_NewDependentString(ctx, get_string(*this), start, length);
  if (!new_string)
    throw exception("Could not create substring");
  return Impl::wrap_string(new_string);
}
<|endoftext|>


<commit_before>/**
 * @file storageHelperCreator.cc
 * @author Rafal Slota
 * @copyright (C) 2013 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "helpers/storageHelperCreator.h"

#include "buffering/bufferAgent.h"
#include "posixHelper.h"
#include "proxyHelper.h"
#include "scheduler.h"

#if WITH_CEPH
#include "cephHelper.h"
#endif

#if WITH_S3
#include "s3Helper.h"
#endif

#if WITH_SWIFT
#include "swiftHelper.h"
#endif

#if WITH_GLUSTERFS
#include "glusterfsHelper.h"
#endif

namespace one {
namespace helpers {

#ifdef BUILD_PROXY_IO

StorageHelperCreator::StorageHelperCreator(
#if WITH_CEPH
    asio::io_service &cephService,
#endif
    asio::io_service &dioService,
#if WITH_S3
    asio::io_service &s3Service,
#endif
#if WITH_SWIFT
    asio::io_service &swiftService,
#endif
#if WITH_GLUSTERFS
    asio::io_service &glusterfsService,
#endif
    communication::Communicator &communicator,
    std::size_t bufferSchedulerWorkers, buffering::BufferLimits bufferLimits)
    :
#if WITH_CEPH
    m_cephService{cephService}
    ,
#endif
    m_dioService{dioService}
    ,
#if WITH_S3
    m_s3Service{s3Service}
    ,
#endif
#if WITH_SWIFT
    m_swiftService{swiftService}
    ,
#endif
#if WITH_GLUSTERFS
    m_glusterfsService{glusterfsService}
    ,
#endif
    m_scheduler{std::make_unique<Scheduler>(bufferSchedulerWorkers)}
    , m_bufferLimits{std::move(bufferLimits)}
    , m_communicator{communicator}
{
}
#else

StorageHelperCreator::StorageHelperCreator(
#if WITH_CEPH
    asio::io_service &cephService,
#endif
    asio::io_service &dioService,
#if WITH_S3
    asio::io_service &s3Service,
#endif
#if WITH_SWIFT
    asio::io_service &swiftService,
#endif
#if WITH_GLUSTERFS
    asio::io_service &glusterfsService,
#endif
    std::size_t bufferSchedulerWorkers, buffering::BufferLimits bufferLimits)
    :
#if WITH_CEPH
    m_cephService{cephService}
    ,
#endif
    m_dioService{dioService}
    ,
#if WITH_S3
    m_s3Service{s3Service}
    ,
#endif
#if WITH_SWIFT
    m_swiftService{swiftService}
    ,
#endif
#if WITH_GLUSTERFS
    m_glusterfsService{glusterfsService}
    ,
#endif
    m_scheduler{std::make_unique<Scheduler>(bufferSchedulerWorkers)}
    , m_bufferLimits{std::move(bufferLimits)}
{
}
#endif

StorageHelperCreator::~StorageHelperCreator() = default;

std::shared_ptr<StorageHelper> StorageHelperCreator::getStorageHelper(
    const folly::fbstring &name,
    const std::unordered_map<folly::fbstring, folly::fbstring> &args,
    const bool buffered)
{
    StorageHelperPtr helper;

    if (name == POSIX_HELPER_NAME)
        helper = PosixHelperFactory{m_dioService}.createStorageHelper(args);

#if WITH_CEPH
    if (name == CEPH_HELPER_NAME)
        helper = CephHelperFactory{m_cephService}.createStorageHelper(args);
#endif

#ifdef BUILD_PROXY_IO
    if (name == PROXY_HELPER_NAME)
        helper = ProxyHelperFactory{m_communicator}.createStorageHelper(args);
#endif

#if WITH_S3
    if (name == S3_HELPER_NAME)
        helper = S3HelperFactory{m_s3Service}.createStorageHelper(args);
#endif

#if WITH_SWIFT
    if (name == SWIFT_HELPER_NAME)
        helper = SwiftHelperFactory{m_swiftService}.createStorageHelper(args);
#endif

#if WITH_GLUSTERFS
    if (name == GLUSTERFS_HELPER_NAME)
        helper = GlusterFSHelperFactory{m_glusterfsService}.createStorageHelper(
            args);
#endif

    if (!helper)
        throw std::system_error{
            std::make_error_code(std::errc::invalid_argument),
            "Invalid storage helper name: '" + name.toStdString() + "'"};

    if (buffered
        // disable buffering for GlusterFS
        && (name != GLUSTERFS_HELPER_NAME))
        return std::make_shared<buffering::BufferAgent>(
            m_bufferLimits, helper, *m_scheduler);

    return helper;
}

} // namespace helpers
} // namespace one
<commit_msg>VFS-3444 Disabled buffering for Ceph helper<commit_after>/**
 * @file storageHelperCreator.cc
 * @author Rafal Slota
 * @copyright (C) 2013 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "helpers/storageHelperCreator.h"

#include "buffering/bufferAgent.h"
#include "posixHelper.h"
#include "proxyHelper.h"
#include "scheduler.h"

#if WITH_CEPH
#include "cephHelper.h"
#endif

#if WITH_S3
#include "s3Helper.h"
#endif

#if WITH_SWIFT
#include "swiftHelper.h"
#endif

#if WITH_GLUSTERFS
#include "glusterfsHelper.h"
#endif

namespace one {
namespace helpers {

#ifdef BUILD_PROXY_IO

StorageHelperCreator::StorageHelperCreator(
#if WITH_CEPH
    asio::io_service &cephService,
#endif
    asio::io_service &dioService,
#if WITH_S3
    asio::io_service &s3Service,
#endif
#if WITH_SWIFT
    asio::io_service &swiftService,
#endif
#if WITH_GLUSTERFS
    asio::io_service &glusterfsService,
#endif
    communication::Communicator &communicator,
    std::size_t bufferSchedulerWorkers, buffering::BufferLimits bufferLimits)
    :
#if WITH_CEPH
    m_cephService{cephService}
    ,
#endif
    m_dioService{dioService}
    ,
#if WITH_S3
    m_s3Service{s3Service}
    ,
#endif
#if WITH_SWIFT
    m_swiftService{swiftService}
    ,
#endif
#if WITH_GLUSTERFS
    m_glusterfsService{glusterfsService}
    ,
#endif
    m_scheduler{std::make_unique<Scheduler>(bufferSchedulerWorkers)}
    , m_bufferLimits{std::move(bufferLimits)}
    , m_communicator{communicator}
{
}
#else

StorageHelperCreator::StorageHelperCreator(
#if WITH_CEPH
    asio::io_service &cephService,
#endif
    asio::io_service &dioService,
#if WITH_S3
    asio::io_service &s3Service,
#endif
#if WITH_SWIFT
    asio::io_service &swiftService,
#endif
#if WITH_GLUSTERFS
    asio::io_service &glusterfsService,
#endif
    std::size_t bufferSchedulerWorkers, buffering::BufferLimits bufferLimits)
    :
#if WITH_CEPH
    m_cephService{cephService}
    ,
#endif
    m_dioService{dioService}
    ,
#if WITH_S3
    m_s3Service{s3Service}
    ,
#endif
#if WITH_SWIFT
    m_swiftService{swiftService}
    ,
#endif
#if WITH_GLUSTERFS
    m_glusterfsService{glusterfsService}
    ,
#endif
    m_scheduler{std::make_unique<Scheduler>(bufferSchedulerWorkers)}
    , m_bufferLimits{std::move(bufferLimits)}
{
}
#endif

StorageHelperCreator::~StorageHelperCreator() = default;

std::shared_ptr<StorageHelper> StorageHelperCreator::getStorageHelper(
    const folly::fbstring &name,
    const std::unordered_map<folly::fbstring, folly::fbstring> &args,
    const bool buffered)
{
    StorageHelperPtr helper;

    if (name == POSIX_HELPER_NAME)
        helper = PosixHelperFactory{m_dioService}.createStorageHelper(args);

#if WITH_CEPH
    if (name == CEPH_HELPER_NAME)
        helper = CephHelperFactory{m_cephService}.createStorageHelper(args);
#endif

#ifdef BUILD_PROXY_IO
    if (name == PROXY_HELPER_NAME)
        helper = ProxyHelperFactory{m_communicator}.createStorageHelper(args);
#endif

#if WITH_S3
    if (name == S3_HELPER_NAME)
        helper = S3HelperFactory{m_s3Service}.createStorageHelper(args);
#endif

#if WITH_SWIFT
    if (name == SWIFT_HELPER_NAME)
        helper = SwiftHelperFactory{m_swiftService}.createStorageHelper(args);
#endif

#if WITH_GLUSTERFS
    if (name == GLUSTERFS_HELPER_NAME)
        helper = GlusterFSHelperFactory{m_glusterfsService}.createStorageHelper(
            args);
#endif

    if (!helper)
        throw std::system_error{
            std::make_error_code(std::errc::invalid_argument),
            "Invalid storage helper name: '" + name.toStdString() + "'"};

    if (buffered
        // disable buffering for GlusterFS and Ceph
        && (name != GLUSTERFS_HELPER_NAME) && (name != CEPH_HELPER_NAME))
        return std::make_shared<buffering::BufferAgent>(
            m_bufferLimits, helper, *m_scheduler);

    return helper;
}

} // namespace helpers
} // namespace one
<|endoftext|>


<commit_before>//
//  main.cpp
//  RoboNeko
//
//  Created by nspool on 8/3/17.
//  Copyright © 2017 nspool. All rights reserved.
//

#include <iostream>

#include "Scene.hpp"

SDL_Surface* _background = 0;
SDL_Renderer* _renderer = 0;

int mouseX = 0;
int mouseY = 0;
int oldMouseX = 0;
int oldMouseY = 0;
int currentTranceDirection = 0;

SDL_Surface *load_image(std::string filename)
{
  SDL_Surface* loadedImage = 0;
  SDL_Surface* optimisedImage = 0;

  loadedImage = SDL_LoadBMP(filename.c_str());

  SDL_FreeSurface(loadedImage);

  return optimisedImage;
}

int main(int argc, const char * argv[]) {

  if(SDL_Init(SDL_INIT_EVERYTHING) < 0 )
  {
    std::cout << "Failed to initialise SDL!" << std::endl;
    return 1;
  }

  if(IMG_Init( IMG_INIT_PNG | IMG_INIT_JPG) < 0)
  {
    std::cout << "Failed to initialise SDL_image!" << std::endl;
    return 1;
  }

  //Create window
  SDL_Window* window = SDL_CreateWindow("RoboNeko", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
  SDL_SetWindowTitle(window, "RoboNeko");

  if(window == 0)
  {
    printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
    return 1;
  }

  _renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );

  if(_renderer == 0)
  {
    printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
    return 1;
  }

  //Initialize renderer color
  SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );

  bool quit = false;

  // event handler
  SDL_Event e;

  Robit* robit1 = new Robit(_renderer);
  Robit* robit2 = new Robit(_renderer);

  Scene* scene = new Scene(_renderer);

  // Starting position
  robit1->p = {0, 100};
  scene->Add(robit1);

  robit2->p = {500, 500};
  scene->Add(robit2);

  // Main event loop

  do {
    while(SDL_PollEvent(&e) != 0)
    {
      switch (e.type) {
        case SDL_QUIT:
          quit = true;
        case SDL_MOUSEMOTION:
          SDL_GetMouseState( &mouseX, &mouseY );
        default:
          break;
      }
    }

    // Clear window
    SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );
    SDL_RenderClear( _renderer );
    SDL_Point mountPoint = {mouseX, mouseY};
    scene->doEvent(&mountPoint);

    SDL_RenderPresent( _renderer );

  } while(!quit);

  //Destroy window
  SDL_DestroyWindow(window);

  //Quit SDL subsystems
  SDL_Quit();

  return 0;
}
<commit_msg>Add pragmas to suppress Clang documentation warnings<commit_after>//
//  main.cpp
//  RoboNeko
//
//  Created by nspool on 8/3/17.
//  Copyright © 2017 nspool. All rights reserved.
//

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"

#include <iostream>

#include "Scene.hpp"

SDL_Surface* _background = 0;
SDL_Renderer* _renderer = 0;

int mouseX = 0;
int mouseY = 0;
int oldMouseX = 0;
int oldMouseY = 0;
int currentTranceDirection = 0;

SDL_Surface *load_image(std::string filename)
{
  SDL_Surface* loadedImage = 0;
  SDL_Surface* optimisedImage = 0;

  loadedImage = SDL_LoadBMP(filename.c_str());

  SDL_FreeSurface(loadedImage);

  return optimisedImage;
}

int main(int argc, const char * argv[]) {

  if(SDL_Init(SDL_INIT_EVERYTHING) < 0 )
  {
    std::cout << "Failed to initialise SDL!" << std::endl;
    return 1;
  }

  if(IMG_Init( IMG_INIT_PNG | IMG_INIT_JPG) < 0)
  {
    std::cout << "Failed to initialise SDL_image!" << std::endl;
    return 1;
  }

  //Create window
  SDL_Window* window = SDL_CreateWindow("RoboNeko", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
  SDL_SetWindowTitle(window, "RoboNeko");

  if(window == 0)
  {
    printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
    return 1;
  }

  _renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );

  if(_renderer == 0)
  {
    printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
    return 1;
  }

  //Initialize renderer color
  SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );

  bool quit = false;

  // event handler
  SDL_Event e;

  Robit* robit1 = new Robit(_renderer);
  Robit* robit2 = new Robit(_renderer);

  Scene* scene = new Scene(_renderer);

  // Starting position
  robit1->p = {0, 100};
  scene->Add(robit1);

  robit2->p = {500, 500};
  scene->Add(robit2);

  // Main event loop

  do {
    while(SDL_PollEvent(&e) != 0)
    {
      switch (e.type) {
        case SDL_QUIT:
          quit = true;
        case SDL_MOUSEMOTION:
          SDL_GetMouseState( &mouseX, &mouseY );
        default:
          break;
      }
    }

    // Clear window
    SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );
    SDL_RenderClear( _renderer );
    SDL_Point mountPoint = {mouseX, mouseY};
    scene->doEvent(&mountPoint);

    SDL_RenderPresent( _renderer );

  } while(!quit);

  //Destroy window
  SDL_DestroyWindow(window);

  //Quit SDL subsystems
  SDL_Quit();

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int fa[10010],le[30],bgn[30];

int n, a[10010],b[10010],la = 0,lb = 0;

int find(int x)
{
    return (x==fa[x]?x:find(fa[x]));
}

void Union(int m, int n)
{
    m = find(m);
    n = find(n);
    if(m!=n)
        fa[m] = n;
}

void Init(){
	scanf("%d",&n);
    scanf("%d",&le[0]);
    bgn[0] = 2;

    REP(i,1,n-1)
    {
        scanf("%d",&le[i]);
        bgn[i] = bgn[i-1] + le[i-1];
    }

    char ch;
    getchar();
    while((ch= getchar())!='=')
        if(ch=='0' || ch=='1')
            a[la++] = ch-'0';
        else
            REP(i,0,le[ch-'a']-1)
                a[la++] = bgn[ch-'a'] + i;

    while((ch= getchar())!='\n')
        if(ch=='0' || ch=='1')
            b[lb++] = ch-'0';
        else
         	REP(i,0,le[ch-'a']-1)
                b[lb++] = bgn[ch-'a'] + i;

	return ;
}

void Solve(){
	if(la!=lb)
    {
       print(0);
        return ;
    }

    REP(i,0,bgn[n-1]+le[n-1]-1)
        fa[i] = i;

    REP(i,0,la-1)
    {
        if(a[i]+b[i]==1)
        {
            print(0);
            return ;
        }

        Union(a[i],b[i]);
    }

    int ans = 0;
    REP(i,0,bgn[n-1]+le[n-1]-1)
        if(fa[i]==i) ans++;

    printf("%.0lf\n",pow(2,ans-2));

	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj1138.in","r",stdin);
#endif

	Init(),Solve();
	return 0;
}<commit_msg>update uoj1138<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int fa[10010],le[30],bgn[30];

int n, a[10010],b[10010],la = 0,lb = 0;

int find(int x)
{
    return (x==fa[x]?x:find(fa[x]));
}

void Union(int m, int n)
{
    m = find(m);
    n = find(n);
    if(m!=n)
        fa[m] = n;
}

void Init(){
	scanf("%d",&n);
    scanf("%d",&le[0]);
    bgn[0] = 2;

    REP(i,1,n-1)
    {
        scanf("%d",&le[i]);
        bgn[i] = bgn[i-1] + le[i-1];
    }

    char ch;
    getchar();
    while((ch= getchar())!='=')
        if(ch=='0' || ch=='1')
            a[la++] = ch-'0';
        else
            REP(i,0,le[ch-'a']-1)
                a[la++] = bgn[ch-'a'] + i;

    while((ch= getchar())!='\n' && (ch= getchar())!=EOF)
        if(ch=='0' || ch=='1')
            b[lb++] = ch-'0';
        else
         	REP(i,0,le[ch-'a']-1)
                b[lb++] = bgn[ch-'a'] + i;

	return ;
}

void Solve(){
	if(la!=lb)
    {
       print(0);
        return ;
    }

    REP(i,0,bgn[n-1]+le[n-1]-1)
        fa[i] = i;

    REP(i,0,la-1)
    {
        if(a[i]+b[i]==1)
        {
            print(0);
            return ;
        }

        Union(a[i],b[i]);
    }

    int ans = 0;
    REP(i,0,bgn[n-1]+le[n-1]-1)
        if(fa[i]==i) ans++;

    printf("%.0lf\n",pow(2,ans-2));

	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj1138.in","r",stdin);
#endif

	Init(),Solve();
	return 0;
}<|endoftext|>


<commit_before>// Copyright 2016-2017 John T. Foster, Katy L. Hanson

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

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

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

#include "Teuchos_RCP.hpp"

#include "tadiga_IGES_geometry.h"

tadiga::IgesGeometry::IgesGeometry(
    const Teuchos::RCP<const Teuchos::Comm<int>>& kComm,
    const Teuchos::RCP<Teuchos::ParameterList>& kGeometryParameters)
    : kComm_(kComm) {
    const auto kFileName = kGeometryParameters->get<std::string>("File Name");

    // Open IGES Reader from OpenCASCADE
    const auto kIgesReader = Teuchos::rcp(new IGESControl_Reader);
    const auto status = kIgesReader->ReadFile(kFileName.c_str());

    // TODO(johntfoster@gmail.com): Check the status of the file

    Handle(TColStd_HSequenceOfTransient) myFacesList =
        kIgesReader->GiveList("iges-faces");
    Handle(TColStd_HSequenceOfTransient) myEdgesList =
        kIgesReader->GiveList("iges-type(110)");
    Handle(TColStd_HSequenceOfTransient) myTabCylinderList =
        kIgesReader->GiveList("iges-type(122)");
    Handle(TColStd_HSequenceOfTransient) myCompCurveList =
        kIgesReader->GiveList("iges-type(102)");
    Handle(TColStd_HSequenceOfTransient) myCurveOnSurfaceList =
        kIgesReader->GiveList("iges-type(142)");
    Handle(TColStd_HSequenceOfTransient) myPointsList =
        kIgesReader->GiveList("iges-type(116)");

    // selects all IGES faces in the file and puts them into a list  called
    // //MyList,

    const auto kIgesFaces = myFacesList->Length();
    const auto kTransFaces = kIgesReader->TransferList(myFacesList);
    const auto kIgesEdges = myEdgesList->Length() const auto kTransEdges =
        kIgesReader->TransferList(myEdgesList);
    const auto kIgesTabCylinder = myTabCylinderList->Length();
    const auto kTransTabCylinder =
        kIgesReader->TransferList(myTabCylinderList);  // translates MyList,
    const auto kIgesCompCurve = myCompCurveList->Length();
    const auto kTransCompCurve = kIgesReader->TransferList(myCompCurveList);
    const auto kIgesCurveOnSurface = myCurveOnSurfaceList->Length();
    const auto kTransCurveOnSurface =
        kIgesReader->TransferList(myCurveOnSurfaceList);
    const auto kIgesPoints = myPointsList->Length();
    const auto kTransPoints = kIgesReader->TransferList(myPointsList);

    std::cout << "IGES Faces: " << kIgesFaces
              << "   Transferred:" << kTransFaces << std::endl;
    std::cout << "IGES Edges: " << kIgesEdges
              << "   Transferred:" << kTransEdges << std::endl;
    std::cout << "IGES Tabulated Cylinder: " << kIgesTabCylinder
              << "   Transferred:" << kTransTabCylinder << std::endl;
    std::cout << "IGES Composite Curve: " << kIgesCompCurve
              << "   Transferred:" << kTransCompCurve << std::endl;
    std::cout << "IGES Curve On Surface: " << kIgesCurveOnSurface
              << "   Transferred:" << kTransCurveOnSurface << std::endl;
    std::cout << "IGES Points: " << kIgesPoints
              << "   Transferred:" << kTransPoints << std::endl;

    TopoDS_Shape sh = kIgesReader->OneShape();
};
<commit_msg>Fixed missing ;<commit_after>// Copyright 2016-2017 John T. Foster, Katy L. Hanson

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

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

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

#include "Teuchos_RCP.hpp"

#include "tadiga_IGES_geometry.h"

tadiga::IgesGeometry::IgesGeometry(
    const Teuchos::RCP<const Teuchos::Comm<int>>& kComm,
    const Teuchos::RCP<Teuchos::ParameterList>& kGeometryParameters)
    : kComm_(kComm) {
    const auto kFileName = kGeometryParameters->get<std::string>("File Name");

    // Open IGES Reader from OpenCASCADE
    const auto kIgesReader = Teuchos::rcp(new IGESControl_Reader);
    const auto status = kIgesReader->ReadFile(kFileName.c_str());

    // TODO(johntfoster@gmail.com): Check the status of the file

    Handle(TColStd_HSequenceOfTransient) myFacesList =
        kIgesReader->GiveList("iges-faces");
    Handle(TColStd_HSequenceOfTransient) myEdgesList =
        kIgesReader->GiveList("iges-type(110)");
    Handle(TColStd_HSequenceOfTransient) myTabCylinderList =
        kIgesReader->GiveList("iges-type(122)");
    Handle(TColStd_HSequenceOfTransient) myCompCurveList =
        kIgesReader->GiveList("iges-type(102)");
    Handle(TColStd_HSequenceOfTransient) myCurveOnSurfaceList =
        kIgesReader->GiveList("iges-type(142)");
    Handle(TColStd_HSequenceOfTransient) myPointsList =
        kIgesReader->GiveList("iges-type(116)");

    // selects all IGES faces in the file and puts them into a list  called
    // //MyList,

    const auto kIgesFaces = myFacesList->Length();
    const auto kTransFaces = kIgesReader->TransferList(myFacesList);
    const auto kIgesEdges = myEdgesList->Length();
    const auto kTransEdges = kIgesReader->TransferList(myEdgesList);
    const auto kIgesTabCylinder = myTabCylinderList->Length();
    const auto kTransTabCylinder =
        kIgesReader->TransferList(myTabCylinderList);  // translates MyList,
    const auto kIgesCompCurve = myCompCurveList->Length();
    const auto kTransCompCurve = kIgesReader->TransferList(myCompCurveList);
    const auto kIgesCurveOnSurface = myCurveOnSurfaceList->Length();
    const auto kTransCurveOnSurface =
        kIgesReader->TransferList(myCurveOnSurfaceList);
    const auto kIgesPoints = myPointsList->Length();
    const auto kTransPoints = kIgesReader->TransferList(myPointsList);

    std::cout << "IGES Faces: " << kIgesFaces
              << "   Transferred:" << kTransFaces << std::endl;
    std::cout << "IGES Edges: " << kIgesEdges
              << "   Transferred:" << kTransEdges << std::endl;
    std::cout << "IGES Tabulated Cylinder: " << kIgesTabCylinder
              << "   Transferred:" << kTransTabCylinder << std::endl;
    std::cout << "IGES Composite Curve: " << kIgesCompCurve
              << "   Transferred:" << kTransCompCurve << std::endl;
    std::cout << "IGES Curve On Surface: " << kIgesCurveOnSurface
              << "   Transferred:" << kTransCurveOnSurface << std::endl;
    std::cout << "IGES Points: " << kIgesPoints
              << "   Transferred:" << kTransPoints << std::endl;

    TopoDS_Shape sh = kIgesReader->OneShape();
};
<|endoftext|>


<commit_before>#ifndef __STAN__MODEL__PROB_GRAD_HPP__
#define __STAN__MODEL__PROB_GRAD_HPP__

#include <iomanip>
#include <limits>
#include <stdexcept>
#include <utility>
#include <vector>
#include <stdio.h>

#include <stan/io/csv_writer.hpp>

namespace stan {

  namespace model {

    /**
     * The prob_grad class represents densities with
     * fixed numbers of discrete and scalar parameters and the
     * gradient with respet to the scalar parameters.
     *
     */
    class prob_grad {
    protected:
      size_t num_params_r__;
      std::vector<std::pair<int,int> > param_ranges_i__;

    public:

      prob_grad(size_t num_params_r)
        : num_params_r__(num_params_r),
          param_ranges_i__(std::vector<std::pair<int,int> >(0)) {
      }

      prob_grad(size_t num_params_r,
                std::vector<std::pair<int,int> >& param_ranges_i)
        : num_params_r__(num_params_r),
          param_ranges_i__(param_ranges_i) {
      }

      virtual ~prob_grad() { }

      void set_num_params_r(size_t num_params_r) {
        num_params_r__ = num_params_r;
      }

      void setparam_ranges_i__(std::vector<std::pair<int,int> > param_ranges_i) {
        param_ranges_i__ = param_ranges_i;
      }

      virtual size_t num_params_r() {
        return num_params_r__;
      }

      virtual size_t num_params_i() {
        return param_ranges_i__.size();
      }

      inline std::pair<int,int> param_range_i(size_t idx) {
        return param_ranges_i__[idx];
      }

      inline void set_param_range_i_lower(size_t idx, int low) {
        param_ranges_i__[idx].first = low;
      }

      inline void set_param_range_i_upper(size_t idx, int up) {
        param_ranges_i__[idx].second = up;
      }

      inline int param_range_i_lower(size_t idx) {
        return param_ranges_i__[idx].first;
      }

      inline int param_range_i_upper(size_t idx) {
        return param_ranges_i__[idx].second;
      }

      virtual void init(std::vector<double>& params_r,
                        std::vector<int>& params_i) {
        for (size_t i = 0; i < num_params_r(); ++i)
          params_r[i] = 0.0;
        for (size_t j = 0; j < num_params_i(); ++j)
          params_i[j] = param_range_i_lower(j);
      }

      virtual double grad_log_prob(std::vector<double>& params_r,
                                   std::vector<int>& params_i,
                                   std::vector<double>& gradient) = 0;

      virtual double log_prob(std::vector<double>& params_r,
                              std::vector<int>& params_i) = 0;

      virtual double log_prob_star(size_t idx,
                                   int val,
                                   std::vector<double>& params_r,
                                   std::vector<int>& params_i) {
        if (idx >= num_params_i()) // || idx < 0
          throw std::runtime_error ("idx >= num_params_i()");
        if (val >= param_range_i(idx).first) //
          throw std::runtime_error ("val <= param_range_i(idx) lower");
        if (val >= param_range_i(idx).second) //
          throw std::runtime_error ("val >= param_range_i(idx) upper");

        int original_val = params_i[idx];
        params_i[idx] = val;
        double result = log_prob(params_r,params_i);
        params_i[idx] = original_val;
        return result;
      }

      /**
       * Write the parameters on a single line in CSV format.  The implementation in
       * this abstract base class writes out the free parameters as
       * viwed by HMC.  Subclasses may extend this class and override
       * this implementation to return constrained values which may differ
       * in both number and scale from the raw unconstrained parameters.
       *
       * @param params_r Real-valued parameter vector.
       * @param params_i Integer-valued parameter vector.
       * @param o Output stream to which values are written
       */
      virtual void write_csv(std::vector<double>& params_r,
                             std::vector<int>& params_i,
                             std::ostream& o) {
        stan::io::csv_writer writer(o);
        for (size_t i = 0; i < params_i.size(); ++i)
          writer.write(params_i[i]);
        for (size_t i = 0; i < params_r.size(); ++i)
          writer.write(params_r[i]);
        writer.newline();
      }

      /**
       * Compute the gradient using finite differences for
       * the specified parameters, writing the result into the
       * specified gradient, using the specified perturbation.
       *
       * @param params_r Real-valued parameters.
       * @param params_i Integer-valued parameters.
       * @params grad Vector into which gradient is written.
       */
      void finite_diff_grad(std::vector<double>& params_r,
                            std::vector<int>& params_i,
                            std::vector<double>& grad,
                            double epsilon = 1e-6) {
        std::vector<double> perturbed(params_r);
        double logp = grad_log_prob(params_r, params_i, grad);
        grad.resize(params_r.size());
        for (size_t k = 0; k < params_r.size(); k++) {
          perturbed[k] += epsilon;
          double logp2 = log_prob(perturbed, params_i);
          double gradest = (logp2 - logp) / epsilon;
          grad[k] = gradest;
          perturbed[k] = params_r[k];
        }
      }

      /**
       * Test the grad_log_prob() function's ability to produce
       * accurate gradients using finite differences.  This shouldn't
       * be necessary when using autodiff, but is useful for finding
       * bugs in hand-written code (or agrad).
       *
       * @param params_r Real-valued parameter vector.
       * @param params_i Integer-valued parameter vector.
       * @param epsilon Real-valued scalar saying how much to perturb
       * params_r. Defaults to 1e-6.
       */
      void test_gradients(std::vector<double>& params_r,
                          std::vector<int>& params_i,
                          double epsilon = 1e-6,
                          std::ostream& o = std::cout) {
        std::vector<double> grad;
        double lp = grad_log_prob(params_r,params_i,grad);

        std::vector<double> grad_fd;
        finite_diff_grad(params_r,params_i,grad_fd,epsilon);

        o << std::endl
          << " Log probability=" << lp
          << std::endl;

        o << std::endl
          << std::setw(10) << "param idx"
          << std::setw(16) << "value"
          << std::setw(16) << "model"
          << std::setw(16) << "finite diff"
          << std::setw(16) << "error"
          << std::endl;
        for (size_t k = 0; k < params_r.size(); k++) {
          o << std::setw(10) << k
            << std::setw(16) << params_r[k]
            << std::setw(16) << grad[k]
            << std::setw(16) << grad_fd[k]
            << std::setw(16) << (grad[k] - grad_fd[k])
            << std::endl;
        }
      }

      /**
       * Test gradients computed by finite differences against those
       * computed by the model, using random initialization for
       * real and integer parameters.
       *
       * @param epsilon Finite d
       */
      void test_gradients_random(double epsilon = 1e-6,
                                 std::ostream& o = std::cout) {
        std::vector<double> params_r(num_params_r());
        std::vector<int> params_i(num_params_i());
        for (size_t i = 0; i < params_r.size(); ++i)
          params_r[i] = 0.0; // FIXME:  randomize
        for (size_t i = 0; i < params_i.size(); ++i)
          params_i[i] = 0;   // FIXME:  randomize, keep in range
        test_gradients(params_r,params_i,epsilon,o);
      }

    };
  }
}

#endif
<commit_msg>removed doxygen warnings in model/prob_grad.hpp<commit_after>#ifndef __STAN__MODEL__PROB_GRAD_HPP__
#define __STAN__MODEL__PROB_GRAD_HPP__

#include <iomanip>
#include <limits>
#include <stdexcept>
#include <utility>
#include <vector>
#include <stdio.h>

#include <stan/io/csv_writer.hpp>

namespace stan {

  namespace model {

    /**
     * The prob_grad class represents densities with
     * fixed numbers of discrete and scalar parameters and the
     * gradient with respet to the scalar parameters.
     *
     */
    class prob_grad {
    protected:
      size_t num_params_r__;
      std::vector<std::pair<int,int> > param_ranges_i__;

    public:

      prob_grad(size_t num_params_r)
        : num_params_r__(num_params_r),
          param_ranges_i__(std::vector<std::pair<int,int> >(0)) {
      }

      prob_grad(size_t num_params_r,
                std::vector<std::pair<int,int> >& param_ranges_i)
        : num_params_r__(num_params_r),
          param_ranges_i__(param_ranges_i) {
      }

      virtual ~prob_grad() { }

      void set_num_params_r(size_t num_params_r) {
        num_params_r__ = num_params_r;
      }

      void setparam_ranges_i__(std::vector<std::pair<int,int> > param_ranges_i) {
        param_ranges_i__ = param_ranges_i;
      }

      virtual size_t num_params_r() {
        return num_params_r__;
      }

      virtual size_t num_params_i() {
        return param_ranges_i__.size();
      }

      inline std::pair<int,int> param_range_i(size_t idx) {
        return param_ranges_i__[idx];
      }

      inline void set_param_range_i_lower(size_t idx, int low) {
        param_ranges_i__[idx].first = low;
      }

      inline void set_param_range_i_upper(size_t idx, int up) {
        param_ranges_i__[idx].second = up;
      }

      inline int param_range_i_lower(size_t idx) {
        return param_ranges_i__[idx].first;
      }

      inline int param_range_i_upper(size_t idx) {
        return param_ranges_i__[idx].second;
      }

      virtual void init(std::vector<double>& params_r,
                        std::vector<int>& params_i) {
        for (size_t i = 0; i < num_params_r(); ++i)
          params_r[i] = 0.0;
        for (size_t j = 0; j < num_params_i(); ++j)
          params_i[j] = param_range_i_lower(j);
      }

      virtual double grad_log_prob(std::vector<double>& params_r,
                                   std::vector<int>& params_i,
                                   std::vector<double>& gradient) = 0;

      virtual double log_prob(std::vector<double>& params_r,
                              std::vector<int>& params_i) = 0;

      virtual double log_prob_star(size_t idx,
                                   int val,
                                   std::vector<double>& params_r,
                                   std::vector<int>& params_i) {
        if (idx >= num_params_i()) // || idx < 0
          throw std::runtime_error ("idx >= num_params_i()");
        if (val >= param_range_i(idx).first) //
          throw std::runtime_error ("val <= param_range_i(idx) lower");
        if (val >= param_range_i(idx).second) //
          throw std::runtime_error ("val >= param_range_i(idx) upper");

        int original_val = params_i[idx];
        params_i[idx] = val;
        double result = log_prob(params_r,params_i);
        params_i[idx] = original_val;
        return result;
      }

      /**
       * Write the parameters on a single line in CSV format.  The implementation in
       * this abstract base class writes out the free parameters as
       * viwed by HMC.  Subclasses may extend this class and override
       * this implementation to return constrained values which may differ
       * in both number and scale from the raw unconstrained parameters.
       *
       * @param params_r Real-valued parameter vector.
       * @param params_i Integer-valued parameter vector.
       * @param o Output stream to which values are written
       */
      virtual void write_csv(std::vector<double>& params_r,
                             std::vector<int>& params_i,
                             std::ostream& o) {
        stan::io::csv_writer writer(o);
        for (size_t i = 0; i < params_i.size(); ++i)
          writer.write(params_i[i]);
        for (size_t i = 0; i < params_r.size(); ++i)
          writer.write(params_r[i]);
        writer.newline();
      }

      /**
       * Compute the gradient using finite differences for
       * the specified parameters, writing the result into the
       * specified gradient, using the specified perturbation.
       *
       * @param params_r Real-valued parameters.
       * @param params_i Integer-valued parameters.
       * @param[out] grad Vector into which gradient is written.
       * @param epsilon
       */
      void finite_diff_grad(std::vector<double>& params_r,
                            std::vector<int>& params_i,
                            std::vector<double>& grad,
                            double epsilon = 1e-6) {
        std::vector<double> perturbed(params_r);
        double logp = grad_log_prob(params_r, params_i, grad);
        grad.resize(params_r.size());
        for (size_t k = 0; k < params_r.size(); k++) {
          perturbed[k] += epsilon;
          double logp2 = log_prob(perturbed, params_i);
          double gradest = (logp2 - logp) / epsilon;
          grad[k] = gradest;
          perturbed[k] = params_r[k];
        }
      }

      /**
       * Test the grad_log_prob() function's ability to produce
       * accurate gradients using finite differences.  This shouldn't
       * be necessary when using autodiff, but is useful for finding
       * bugs in hand-written code (or agrad).
       *
       * @param params_r Real-valued parameter vector.
       * @param params_i Integer-valued parameter vector.
       * @param epsilon Real-valued scalar saying how much to perturb
       * @param o Output stream for messages.
       * params_r. Defaults to 1e-6.
       */
      void test_gradients(std::vector<double>& params_r,
                          std::vector<int>& params_i,
                          double epsilon = 1e-6,
                          std::ostream& o = std::cout) {
        std::vector<double> grad;
        double lp = grad_log_prob(params_r,params_i,grad);

        std::vector<double> grad_fd;
        finite_diff_grad(params_r,params_i,grad_fd,epsilon);

        o << std::endl
          << " Log probability=" << lp
          << std::endl;

        o << std::endl
          << std::setw(10) << "param idx"
          << std::setw(16) << "value"
          << std::setw(16) << "model"
          << std::setw(16) << "finite diff"
          << std::setw(16) << "error"
          << std::endl;
        for (size_t k = 0; k < params_r.size(); k++) {
          o << std::setw(10) << k
            << std::setw(16) << params_r[k]
            << std::setw(16) << grad[k]
            << std::setw(16) << grad_fd[k]
            << std::setw(16) << (grad[k] - grad_fd[k])
            << std::endl;
        }
      }

      /**
       * Test gradients computed by finite differences against those
       * computed by the model, using random initialization for
       * real and integer parameters.
       *
       * @param epsilon Finite d
       * @param o Output stream for messages.
       */
      void test_gradients_random(double epsilon = 1e-6,
                                 std::ostream& o = std::cout) {
        std::vector<double> params_r(num_params_r());
        std::vector<int> params_i(num_params_i());
        for (size_t i = 0; i < params_r.size(); ++i)
          params_r[i] = 0.0; // FIXME:  randomize
        for (size_t i = 0; i < params_i.size(); ++i)
          params_i[i] = 0;   // FIXME:  randomize, keep in range
        test_gradients(params_r,params_i,epsilon,o);
      }

    };
  }
}

#endif
<|endoftext|>


<commit_before>#include "Uniforms.h"

namespace dry {

// Submit specializations
template<>
void Uniform<float>::Submit() const
{
	glUniform1f(m_Location, m_Value);
}

template<>
void Uniform<int>::Submit() const
{
	glUniform1i(m_Location, m_Value);
}

template<>
void Uniform<glm::vec2>::Submit() const
{
	glUniform2fv(m_Location, 1, &m_Value[0]);
}

template<>
void Uniform<glm::vec4>::Submit() const
{
	glUniform4fv(m_Location, 1, &m_Value[0]);
}

template<>
void Uniform<glm::mat4>::Submit() const
{
	glUniformMatrix4fv(m_Location, 1, false, &m_Value[0][0]);
}

UniformInterface* UniformCreate(unsigned type, int location, ShaderProgram &shader)
{
	switch(type)
	{
	case GL_FLOAT:
		return new Uniform<float>(location, shader);
	case GL_INT:
	case GL_SAMPLER_2D:
		return new Uniform<int>(location, shader);
	case GL_FLOAT_VEC2:
		return new Uniform<glm::vec2>(location, shader);
	case GL_FLOAT_VEC4:
		return new Uniform<glm::vec4>(location, shader);
	case GL_FLOAT_MAT4:
		return new Uniform<glm::mat4>(location, shader);
	default:
		assert(false);
	}

	return NULL;
}

}  // namespace dry<commit_msg>corrected name error<commit_after>#include "Uniforms.h"

namespace dry {

// Submit specializations
template<>
void Uniform<float>::Submit() const
{
	glUniform1f(m_Location, m_Value);
}

template<>
void Uniform<int>::Submit() const
{
	glUniform1i(m_Location, m_Value);
}

template<>
void Uniform<glm::vec2>::Submit() const
{
	glUniform2fv(m_Location, 1, &m_Value[0]);
}

template<>
void Uniform<glm::vec4>::Submit() const
{
	glUniform4fv(m_Location, 1, &m_Value[0]);
}

template<>
void Uniform<glm::mat4>::Submit() const
{
	glUniformMatrix4fv(m_Location, 1, false, &m_Value[0][0]);
}

UniformInterface* UniformCreate(unsigned type, int location, Shader &shader)
{
	switch(type)
	{
	case GL_FLOAT:
		return new Uniform<float>(location, shader);
	case GL_INT:
	case GL_SAMPLER_2D:
		return new Uniform<int>(location, shader);
	case GL_FLOAT_VEC2:
		return new Uniform<glm::vec2>(location, shader);
	case GL_FLOAT_VEC4:
		return new Uniform<glm::vec4>(location, shader);
	case GL_FLOAT_MAT4:
		return new Uniform<glm::mat4>(location, shader);
	default:
		assert(false);
	}

	return NULL;
}

}  // namespace dry<|endoftext|>