<commit_before>/*
 * Copyright 2010-2012 Esrille Inc.
 *
 * 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 "HTMLBodyElementImp.h"

#include <org/w3c/dom/html/Window.h>

namespace org { namespace w3c { namespace dom { namespace bootstrap {

void HTMLBodyElementImp::eval()
{
    HTMLElementImp::eval();
    HTMLElementImp::evalBackground(this);
    HTMLElementImp::evalBgcolor(this);
}

// Node
Node HTMLBodyElementImp::cloneNode(bool deep)
{
    return new(std::nothrow) HTMLBodyElementImp(this, deep);
}

// HTMLBodyElement
html::Function HTMLBodyElementImp::getOnafterprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnblur()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnblur(html::Function onblur)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnerror()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnerror(html::Function onerror)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnfocus()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnfocus(html::Function onfocus)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnhashchange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnload(html::Function onload)
{
    getOwnerDocument().getDefaultView().setOnload(onload);
}

html::Function HTMLBodyElementImp::getOnmessage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnmessage(html::Function onmessage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnoffline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnoffline(html::Function onoffline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnonline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnonline(html::Function ononline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpopstate()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpagehide()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpageshow()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnredo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnredo(html::Function onredo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnresize()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnresize(html::Function onresize)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnstorage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnstorage(html::Function onstorage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnundo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnundo(html::Function onundo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnunload(html::Function onunload)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getText()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setText(std::u16string text)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBgColor()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBgColor(std::u16string bgColor)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBackground()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBackground(std::u16string background)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setLink(std::u16string link)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getVLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setVLink(std::u16string vLink)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getALink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setALink(std::u16string aLink)
{
    // TODO: implement me!
}

}}}}  // org::w3c::dom::bootstrap
<commit_msg>(HTMLBodyElementImp::eval) : Evaluate text attribute.<commit_after>/*
 * Copyright 2010-2012 Esrille Inc.
 *
 * 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 "HTMLBodyElementImp.h"

#include <org/w3c/dom/html/Window.h>

namespace org { namespace w3c { namespace dom { namespace bootstrap {

void HTMLBodyElementImp::eval()
{
    HTMLElementImp::eval();
    HTMLElementImp::evalBackground(this);
    HTMLElementImp::evalBgcolor(this);
    HTMLElementImp::evalColor(this, u"text", u"color");
}

// Node
Node HTMLBodyElementImp::cloneNode(bool deep)
{
    return new(std::nothrow) HTMLBodyElementImp(this, deep);
}

// HTMLBodyElement
html::Function HTMLBodyElementImp::getOnafterprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnblur()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnblur(html::Function onblur)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnerror()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnerror(html::Function onerror)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnfocus()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnfocus(html::Function onfocus)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnhashchange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnload(html::Function onload)
{
    getOwnerDocument().getDefaultView().setOnload(onload);
}

html::Function HTMLBodyElementImp::getOnmessage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnmessage(html::Function onmessage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnoffline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnoffline(html::Function onoffline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnonline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnonline(html::Function ononline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpopstate()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpagehide()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpageshow()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnredo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnredo(html::Function onredo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnresize()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnresize(html::Function onresize)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnstorage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnstorage(html::Function onstorage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnundo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnundo(html::Function onundo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnunload(html::Function onunload)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getText()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setText(std::u16string text)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBgColor()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBgColor(std::u16string bgColor)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBackground()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBackground(std::u16string background)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setLink(std::u16string link)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getVLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setVLink(std::u16string vLink)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getALink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setALink(std::u16string aLink)
{
    // TODO: implement me!
}

}}}}  // org::w3c::dom::bootstrap
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Bastian Holst <bastianholst@gmx.de>
//

// Self
#include "WikipediaModel.h"

// Plugin
#include "GeonamesParser.h"

// Marble
#include "GeoDataLatLonAltBox.h"
#include "MarbleGlobal.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "MarbleDirs.h"
#include "WikipediaItem.h"
#include "MarbleLocale.h"
#include "MarbleDebug.h"

// Qt
#include <QtCore/QUrl>
#include <QtCore/QString>
#include <QtGui/QIcon>
#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtSvg/QSvgRenderer>

using namespace Marble;

WikipediaModel::WikipediaModel( QObject *parent )
    : AbstractDataPluginModel( "wikipedia", parent ),
      m_marbleWidget( 0 ),
      m_showThumbnail( true )
{
    m_wikipediaIcon.addFile( MarbleDirs::path( "svg/wikipedia_shadow.svg" ) );

    m_languageCode = MarbleLocale::languageCode();
}

WikipediaModel::~WikipediaModel()
{
}

void WikipediaModel::setShowThumbnail( bool show )
{
    m_showThumbnail = show;
}

void WikipediaModel::getAdditionalItems( const GeoDataLatLonAltBox& box,
                                         const MarbleModel *model,
                                         qint32 number )
{
    // Geonames only supports wikipedia articles for earth
    if ( model->planetId() != "earth" ) {
        return;
    }

    QString geonamesUrl( "http://ws.geonames.org/wikipediaBoundingBox" );
    geonamesUrl += "?north=";
    geonamesUrl += QString::number( box.north() * RAD2DEG );
    geonamesUrl += "&south=";
    geonamesUrl += QString::number( box.south() * RAD2DEG );
    geonamesUrl += "&east=";
    geonamesUrl += QString::number( box.east() * RAD2DEG );
    geonamesUrl += "&west=";
    geonamesUrl += QString::number( box.west() * RAD2DEG );
    geonamesUrl += "&maxRows=";
    geonamesUrl += QString::number( number );
    geonamesUrl += "&lang=";
    geonamesUrl += m_languageCode;

    downloadDescriptionFile( QUrl( geonamesUrl ) );
}

void WikipediaModel::parseFile( const QByteArray& file )
{
    QList<WikipediaItem*> list;
    GeonamesParser parser( m_marbleWidget, &list, this );

    parser.read( file );

    QList<AbstractDataPluginItem*> items;
    QList<WikipediaItem*>::const_iterator it;

    for ( it = list.constBegin(); it != list.constEnd(); ++it ) {
        if ( itemExists( (*it)->id() ) ) {
            delete *it;
            continue;
        }

        (*it)->setIcon( m_wikipediaIcon );
        // Currently all wikipedia articles with geotags are on earth
        (*it)->setTarget( "earth" );
        QUrl thumbnailImageUrl = (*it)->thumbnailImageUrl();
        if ( m_showThumbnail && !thumbnailImageUrl.isEmpty() ) {
            downloadItem( thumbnailImageUrl, "thumbnail", *it );
        }
        else {
            items << *it;
        }
    }

    addItemsToList( items );
}

void WikipediaModel::setMarbleWidget(MarbleWidget *widget)
{
    m_marbleWidget = widget;
}

#include "WikipediaModel.moc"
<commit_msg>construct a QUrl rather than a QString<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Bastian Holst <bastianholst@gmx.de>
//

// Self
#include "WikipediaModel.h"

// Plugin
#include "GeonamesParser.h"

// Marble
#include "GeoDataLatLonAltBox.h"
#include "MarbleGlobal.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "MarbleDirs.h"
#include "WikipediaItem.h"
#include "MarbleLocale.h"
#include "MarbleDebug.h"

// Qt
#include <QtCore/QUrl>
#include <QtCore/QString>
#include <QtGui/QIcon>
#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtSvg/QSvgRenderer>

using namespace Marble;

WikipediaModel::WikipediaModel( QObject *parent )
    : AbstractDataPluginModel( "wikipedia", parent ),
      m_marbleWidget( 0 ),
      m_wikipediaIcon( MarbleDirs::path( "svg/wikipedia_shadow.svg" ) ),
      m_showThumbnail( true )
{
    m_languageCode = MarbleLocale::languageCode();
}

WikipediaModel::~WikipediaModel()
{
}

void WikipediaModel::setShowThumbnail( bool show )
{
    m_showThumbnail = show;
}

void WikipediaModel::getAdditionalItems( const GeoDataLatLonAltBox& box,
                                         const MarbleModel *model,
                                         qint32 number )
{
    // Geonames only supports wikipedia articles for earth
    if ( model->planetId() != "earth" ) {
        return;
    }

    QUrl geonamesUrl( "http://ws.geonames.org/wikipediaBoundingBox" );
    geonamesUrl.addQueryItem( "north", QString::number( box.north( GeoDataCoordinates::Degree ) ) );
    geonamesUrl.addQueryItem( "south", QString::number( box.south( GeoDataCoordinates::Degree ) ) );
    geonamesUrl.addQueryItem( "east", QString::number( box.east( GeoDataCoordinates::Degree ) ) );
    geonamesUrl.addQueryItem( "west", QString::number( box.west( GeoDataCoordinates::Degree ) ) );
    geonamesUrl.addQueryItem( "maxRows", QString::number( number ) );
    geonamesUrl.addQueryItem( "lang", m_languageCode );

    downloadDescriptionFile( geonamesUrl );
}

void WikipediaModel::parseFile( const QByteArray& file )
{
    QList<WikipediaItem*> list;
    GeonamesParser parser( m_marbleWidget, &list, this );

    parser.read( file );

    QList<AbstractDataPluginItem*> items;
    QList<WikipediaItem*>::const_iterator it;

    for ( it = list.constBegin(); it != list.constEnd(); ++it ) {
        if ( itemExists( (*it)->id() ) ) {
            delete *it;
            continue;
        }

        (*it)->setIcon( m_wikipediaIcon );
        // Currently all wikipedia articles with geotags are on earth
        (*it)->setTarget( "earth" );
        QUrl thumbnailImageUrl = (*it)->thumbnailImageUrl();
        if ( m_showThumbnail && !thumbnailImageUrl.isEmpty() ) {
            downloadItem( thumbnailImageUrl, "thumbnail", *it );
        }
        else {
            items << *it;
        }
    }

    addItemsToList( items );
}

void WikipediaModel::setMarbleWidget(MarbleWidget *widget)
{
    m_marbleWidget = widget;
}

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


<commit_before>#include "xchainer/routines/logic.h"

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
#include <string>
#include <vector>

#include <gtest/gtest.h>
#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/device_id.h"
#include "xchainer/dtype.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/array_check.h"
#include "xchainer/testing/device_session.h"

namespace xchainer {
namespace {

class LogicTest : public ::testing::TestWithParam<std::string> {
protected:
    void SetUp() override {
        const std::string& backend_name = GetParam();
        device_session_.emplace(DeviceId{backend_name, 0});
    }

    void TearDown() override { device_session_.reset(); }

private:
    nonstd::optional<testing::DeviceSession> device_session_;
};

TEST_P(LogicTest, Equal) {
    using T = float;

    struct Param {
        T a;
        T b;
        bool e;
    };

    std::vector<Param> data = {{1.0f, 1.0f, true},
                               {1.0f, -1.0f, false},
                               {2.0f, 3.0f, false},
                               {1.0f, std::nanf(""), false},
                               {std::nanf(""), std::nanf(""), false},
                               {std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), true},
                               {0.0f, -0.0f, true}};
    std::vector<T> a_data;
    std::vector<T> b_data;
    std::vector<bool> e_data;
    std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });
    std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });
    std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });
    Shape shape{static_cast<int64_t>(data.size())};
    Array a = testing::BuildArray(shape).WithData<T>(a_data);
    Array b = testing::BuildArray(shape).WithData<T>(b_data);
    Array e = testing::BuildArray(shape).WithData<bool>(e_data);
    Array c = Equal(a, b);

    ASSERT_EQ(c.dtype(), Dtype::kBool);
    EXPECT_TRUE(c.IsContiguous());
    EXPECT_ARRAY_EQ(e, c);
}

TEST_P(LogicTest, EqualBroadcast) {
    using T = int32_t;

    Array a = testing::BuildArray({2, 3}).WithData<T>({1, 2, 3, 4, 3, 2});
    Array b = testing::BuildArray({2, 1}).WithData<T>({3, 2});
    Array e = testing::BuildArray({2, 3}).WithData<bool>({false, false, true, false, false, true});
    Array o = Equal(a, b);
    EXPECT_ARRAY_EQ(e, o);
}

TEST_P(LogicTest, Greater) {
    using T = float;

    struct Param {
        T a;
        T b;
        bool e;
    };

    std::vector<Param> data = {{1.0f, 1.0f, false},
                               {1.0f, -1.0f, true},
                               {2.0f, 3.0f, false},
                               {1.0f, std::nanf(""), false},
                               {std::nanf(""), std::nanf(""), false},
                               {std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), false},
                               {std::numeric_limits<T>::infinity(), 100, true},
                               {-std::numeric_limits<T>::infinity(), 100, false},
                               {0.0f, -0.0f, false}};
    std::vector<T> a_data;
    std::vector<T> b_data;
    std::vector<bool> e_data;
    std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });
    std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });
    std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });
    Shape shape{static_cast<int64_t>(data.size())};
    Array a = testing::BuildArray(shape).WithData<T>(a_data);
    Array b = testing::BuildArray(shape).WithData<T>(b_data);
    Array e = testing::BuildArray(shape).WithData<bool>(e_data);
    Array c = Greater(a, b);

    ASSERT_EQ(c.dtype(), Dtype::kBool);
    EXPECT_TRUE(c.IsContiguous());
    EXPECT_ARRAY_EQ(e, c);
}

TEST_P(LogicTest, GreaterBroadcast) {
    using T = int32_t;

    Array a = testing::BuildArray({2, 3}).WithData<T>({1, 2, 3, 4, 3, 2});
    Array b = testing::BuildArray({2, 1}).WithData<T>({2, 2});
    Array e = testing::BuildArray({2, 3}).WithData<bool>({false, false, true, true, true, false});
    Array o = Greater(a, b);
    EXPECT_ARRAY_EQ(e, o);
}

TEST_P(LogicTest, LogicalNot) {
    using T = float;

    struct Param {
        T a;
        bool e;
    };

    std::vector<Param> data = {
            {1.0f, false}, {0.0f, true}, {-0.0f, true}, {std::nanf(""), false}, {std::numeric_limits<T>::infinity(), false}};
    std::vector<T> a_data;
    std::vector<bool> e_data;
    std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });
    std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });
    Shape shape{static_cast<int64_t>(data.size())};
    Array a = testing::BuildArray(shape).WithData<T>(a_data);
    Array e = testing::BuildArray(shape).WithData<bool>(e_data);
    Array c = LogicalNot(a);

    ASSERT_EQ(c.dtype(), Dtype::kBool);
    EXPECT_TRUE(c.IsContiguous());
    EXPECT_ARRAY_EQ(e, c);
}

INSTANTIATE_TEST_CASE_P(
        ForEachBackend,
        LogicTest,
        ::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
                std::string{"cuda"},
#endif  // XCHAINER_ENABLE_CUDA
                std::string{"native"}));

}  // namespace
}  // namespace xchainer
<commit_msg>logic_test.cc: CheckForward<commit_after>#include "xchainer/routines/logic.h"

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
#include <string>
#include <vector>

#include <gtest/gtest.h>
#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/device_id.h"
#include "xchainer/dtype.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/array_check.h"
#include "xchainer/testing/device_session.h"
#include "xchainer/testing/routines.h"

namespace xchainer {
namespace {

class LogicTest : public ::testing::TestWithParam<std::string> {
protected:
    void SetUp() override {
        const std::string& backend_name = GetParam();
        device_session_.emplace(DeviceId{backend_name, 0});
    }

    void TearDown() override { device_session_.reset(); }

private:
    nonstd::optional<testing::DeviceSession> device_session_;
};

TEST_P(LogicTest, Equal) {
    using T = float;

    struct Param {
        T a;
        T b;
        bool e;
    };

    std::vector<Param> data = {{1.0f, 1.0f, true},
                               {1.0f, -1.0f, false},
                               {2.0f, 3.0f, false},
                               {1.0f, std::nanf(""), false},
                               {std::nanf(""), std::nanf(""), false},
                               {std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), true},
                               {0.0f, -0.0f, true}};
    std::vector<T> a_data;
    std::vector<T> b_data;
    std::vector<bool> e_data;
    std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });
    std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });
    std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });
    Shape shape{static_cast<int64_t>(data.size())};
    Array a = testing::BuildArray(shape).WithData<T>(a_data);
    Array b = testing::BuildArray(shape).WithData<T>(b_data);
    Array e = testing::BuildArray(shape).WithData<bool>(e_data);

    testing::CheckForward(
            [](const std::vector<Array>& xs) {
                Array y = Equal(xs[0], xs[1]);
                EXPECT_EQ(y.dtype(), Dtype::kBool);
                EXPECT_TRUE(y.IsContiguous());
                return std::vector<Array>{y};
            },
            {a, b},
            {e},
            // TODO(sonots): Run concurrency test in CUDA
            GetParam() == "cuda" ? 0 : 1);
}

TEST_P(LogicTest, EqualBroadcast) {
    using T = int32_t;

    Array a = testing::BuildArray({2, 3}).WithData<T>({1, 2, 3, 4, 3, 2});
    Array b = testing::BuildArray({2, 1}).WithData<T>({3, 2});
    Array e = testing::BuildArray({2, 3}).WithData<bool>({false, false, true, false, false, true});

    testing::CheckForward(
            [](const std::vector<Array>& xs) { return std::vector<Array>{Equal(xs[0], xs[1])}; },
            {a, b},
            {e},
            // TODO(sonots): Run concurrency test in CUDA
            GetParam() == "cuda" ? 0 : 1);
}

TEST_P(LogicTest, Greater) {
    using T = float;

    struct Param {
        T a;
        T b;
        bool e;
    };

    std::vector<Param> data = {{1.0f, 1.0f, false},
                               {1.0f, -1.0f, true},
                               {2.0f, 3.0f, false},
                               {1.0f, std::nanf(""), false},
                               {std::nanf(""), std::nanf(""), false},
                               {std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), false},
                               {std::numeric_limits<T>::infinity(), 100, true},
                               {-std::numeric_limits<T>::infinity(), 100, false},
                               {0.0f, -0.0f, false}};
    std::vector<T> a_data;
    std::vector<T> b_data;
    std::vector<bool> e_data;
    std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });
    std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });
    std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });
    Shape shape{static_cast<int64_t>(data.size())};
    Array a = testing::BuildArray(shape).WithData<T>(a_data);
    Array b = testing::BuildArray(shape).WithData<T>(b_data);
    Array e = testing::BuildArray(shape).WithData<bool>(e_data);

    testing::CheckForward(
            [](const std::vector<Array>& xs) {
                Array y = Greater(xs[0], xs[1]);
                EXPECT_EQ(y.dtype(), Dtype::kBool);
                EXPECT_TRUE(y.IsContiguous());
                return std::vector<Array>{y};
            },
            {a, b},
            {e},
            // TODO(sonots): Run concurrency test in CUDA
            GetParam() == "cuda" ? 0 : 1);
}

TEST_P(LogicTest, GreaterBroadcast) {
    using T = int32_t;

    Array a = testing::BuildArray({2, 3}).WithData<T>({1, 2, 3, 4, 3, 2});
    Array b = testing::BuildArray({2, 1}).WithData<T>({2, 2});
    Array e = testing::BuildArray({2, 3}).WithData<bool>({false, false, true, true, true, false});

    testing::CheckForward(
            [](const std::vector<Array>& xs) { return std::vector<Array>{Greater(xs[0], xs[1])}; },
            {a, b},
            {e},
            // TODO(sonots): Run concurrency test in CUDA
            GetParam() == "cuda" ? 0 : 1);
}

TEST_P(LogicTest, LogicalNot) {
    using T = float;

    struct Param {
        T a;
        bool e;
    };

    std::vector<Param> data = {
            {1.0f, false}, {0.0f, true}, {-0.0f, true}, {std::nanf(""), false}, {std::numeric_limits<T>::infinity(), false}};
    std::vector<T> a_data;
    std::vector<bool> e_data;
    std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });
    std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });
    Shape shape{static_cast<int64_t>(data.size())};
    Array a = testing::BuildArray(shape).WithData<T>(a_data);
    Array e = testing::BuildArray(shape).WithData<bool>(e_data);

    testing::CheckForward(
            [](const std::vector<Array>& xs) {
                Array y = LogicalNot(xs[0]);
                EXPECT_EQ(y.dtype(), Dtype::kBool);
                EXPECT_TRUE(y.IsContiguous());
                return std::vector<Array>{y};
            },
            {a},
            {e},
            // TODO(sonots): Run concurrency test in CUDA
            GetParam() == "cuda" ? 0 : 1);
}

INSTANTIATE_TEST_CASE_P(
        ForEachBackend,
        LogicTest,
        ::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
                std::string{"cuda"},
#endif  // XCHAINER_ENABLE_CUDA
                std::string{"native"}));

}  // namespace
}  // namespace xchainer
<|endoftext|>


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

#ifndef _XIMPPAGE_HXX
#define _XIMPPAGE_HXX

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

#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif

#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif

#ifndef _XIMPSHAPE_HXX
#include "ximpshap.hxx"
#endif

//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)

class SdXMLGenericPageContext : public SvXMLImportContext
{
    // the shape group this group is working on
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxShapes;

protected:
    rtl::OUString               maPageLayoutName;
    rtl::OUString               maUseHeaderDeclName;
    rtl::OUString               maUseFooterDeclName;
    rtl::OUString               maUseDateTimeDeclName;

    void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
        { mxShapes = rNew; }

    /** sets the page style on this page */
    void SetStyle( rtl::OUString& rStyleName );

    /** sets the presentation layout at this page. It is used for drawing pages and for the handout master */
    void SetLayout();

    /** deletes all shapes on this drawing page */
    void DeleteAllShapes();

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

    /** sets the properties from a page master style with the given name on this contexts page */
    void SetPageMaster( rtl::OUString& rsPageMasterName );

public:
    TYPEINFO();

    SdXMLGenericPageContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
        com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);
    virtual ~SdXMLGenericPageContext();

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

    const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
        { return mxShapes; }
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
        { return mxShapes; }
};

#endif  //  _XIMPGROUP_HXX
<commit_msg>INTEGRATION: CWS vgbugs07 (1.7.274); FILE MERGED 2007/06/04 13:23:25 vg 1.7.274.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ximppage.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:11:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XIMPPAGE_HXX
#define _XIMPPAGE_HXX

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

#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif

#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif

#ifndef _XIMPSHAPE_HXX
#include "ximpshap.hxx"
#endif

//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)

class SdXMLGenericPageContext : public SvXMLImportContext
{
    // the shape group this group is working on
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxShapes;

protected:
    rtl::OUString               maPageLayoutName;
    rtl::OUString               maUseHeaderDeclName;
    rtl::OUString               maUseFooterDeclName;
    rtl::OUString               maUseDateTimeDeclName;

    void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
        { mxShapes = rNew; }

    /** sets the page style on this page */
    void SetStyle( rtl::OUString& rStyleName );

    /** sets the presentation layout at this page. It is used for drawing pages and for the handout master */
    void SetLayout();

    /** deletes all shapes on this drawing page */
    void DeleteAllShapes();

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

    /** sets the properties from a page master style with the given name on this contexts page */
    void SetPageMaster( rtl::OUString& rsPageMasterName );

public:
    TYPEINFO();

    SdXMLGenericPageContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
        com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);
    virtual ~SdXMLGenericPageContext();

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

    const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
        { return mxShapes; }
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
        { return mxShapes; }
};

#endif  //  _XIMPGROUP_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fonthdl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: dvo $ $Date: 2001-06-29 21:07:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_FONTTYPES_HXX
#include <fonthdl.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _VCL_VCLENUM_HXX
#include <vcl/vclenum.hxx>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::xmloff::token;

static SvXMLEnumMapEntry __READONLY_DATA aFontFamilyGenericMapping[] =
{
    { XML_DECORATIVE,       FAMILY_DECORATIVE },

    { XML_MODERN,           FAMILY_MODERN   },
    { XML_ROMAN,            FAMILY_ROMAN    },
    { XML_SCRIPT,           FAMILY_SCRIPT   },
    { XML_SWISS,            FAMILY_SWISS    },
    { XML_SYSTEM,           FAMILY_SYSTEM   },
    { XML_TOKEN_INVALID,    0               }
};

static SvXMLEnumMapEntry __READONLY_DATA aFontPitchMapping[] =
{
    { XML_FIXED,            PITCH_FIXED     },
    { XML_VARIABLE,         PITCH_VARIABLE  },
    { XML_TOKEN_INVALID,    0               }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontFamilyNamePropHdl
//

XMLFontFamilyNamePropHdl::~XMLFontFamilyNamePropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontFamilyNamePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    String sValue;
    sal_Int32 nPos = 0;

    do
    {
        sal_Int32 nFirst = nPos;
        nPos = SvXMLUnitConverter::indexOfComma( rStrImpValue, nPos );
        sal_Int32 nLast = (-1 == nPos ? rStrImpValue.getLength() : nPos);
        if( nLast > 0 )
            nLast--;

        // skip trailing blanks
        while( sal_Unicode(' ') == rStrImpValue[nLast] && nLast > nFirst )
            nLast--;

        // skip leading blanks
        while( sal_Unicode(' ') == rStrImpValue[nFirst] && nFirst <= nLast )
            nFirst++;

        // remove quotes
        sal_Unicode c = rStrImpValue[nFirst];
        if( nFirst < nLast && (sal_Unicode('\'') == c || sal_Unicode('\"') == c) && rStrImpValue[nLast] == c )
        {
            nFirst++;
            nLast--;
        }

        if( nFirst <= nLast )
        {
            if( sValue.Len() != 0 )
                sValue += sal_Unicode(';');

            OUString sTemp = rStrImpValue.copy( nFirst, nLast-nFirst+1 );
            sValue += sTemp.getStr();
        }

        if( -1 != nPos )
            nPos++;
    }
    while( -1 != nPos );

    if( sValue.Len() )
    {
        rValue <<= OUString(sValue.GetBuffer());
        bRet = sal_True;
    }

    return bRet;
}

sal_Bool XMLFontFamilyNamePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    OUString aStrFamilyName;

    if( rValue >>= aStrFamilyName )
    {
        OUStringBuffer sValue( aStrFamilyName.getLength() + 2L );
        sal_Int32 nPos = 0L;
        do
        {
            sal_Int32 nFirst = nPos;
            nPos = aStrFamilyName.indexOf( sal_Unicode(';'), nPos );
            sal_Int32 nLast = (-1L == nPos ? aStrFamilyName.getLength() : nPos);

            // Set position to the character behind the ';', so we won't
            // forget this.
            if( -1L != nPos )
                nPos++;

            // If the property value was empty, we stop now.
            // If there is a ';' at the first position, the empty name
            // at the start will be removed.
            if( 0L == nLast )
                continue;

            // nFirst and nLast now denote the first and last character of
            // one font name.
            nLast--;

            // skip trailing blanks
            while( sal_Unicode(' ') == aStrFamilyName[nLast] && nLast > nFirst )
                nLast--;

            // skip leading blanks
            while( sal_Unicode(' ') == aStrFamilyName[nFirst] && nFirst <= nLast )
                nFirst++;

            if( nFirst <= nLast )
            {
                if( sValue.getLength() != 0L )
                {
                    sValue.append( sal_Unicode( ',' ) );
                    sValue.append( sal_Unicode( ' ' ));
                }
                sal_Int32 nLen = nLast-nFirst+1L;
                OUString sFamily( aStrFamilyName.copy( nFirst, nLen ) );
                sal_Bool bQuote = sal_False;
                for( sal_Int32 i=0; i < nLen; i++ )
                {
                    sal_Unicode c = sFamily[i];
                    if( sal_Unicode(' ') == c || sal_Unicode(',') == c )
                    {
                        bQuote = sal_True;
                        break;
                    }
                }
                if( bQuote )
                    sValue.append( sal_Unicode('\'') );
                sValue.append( sFamily );
                if( bQuote )
                    sValue.append( sal_Unicode('\'') );
            }
        }
        while( -1L != nPos );

        rStrExpValue = sValue.makeStringAndClear();

        bRet = sal_True;
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontFamilyPropHdl
//

XMLFontFamilyPropHdl::~XMLFontFamilyPropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontFamilyPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewFamily;

    if( ( bRet = rUnitConverter.convertEnum( eNewFamily, rStrImpValue, aFontFamilyGenericMapping ) ) )
        rValue <<= (sal_Int16)eNewFamily;

    return bRet;
}

sal_Bool XMLFontFamilyPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    OUStringBuffer aOut;

    sal_Int16 nFamily;
    if( rValue >>= nFamily )
    {
        FontFamily eFamily = (FontFamily)nFamily;
        if( eFamily != FAMILY_DONTKNOW )
            bRet = rUnitConverter.convertEnum( aOut, eFamily, aFontFamilyGenericMapping );
    }

    rStrExpValue = aOut.makeStringAndClear();

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontEncodingPropHdl
//

XMLFontEncodingPropHdl::~XMLFontEncodingPropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontEncodingPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_True;

    if( IsXMLToken( rStrImpValue, XML_X_SYMBOL ) )
        rValue <<= (sal_Int16) RTL_TEXTENCODING_SYMBOL;

    return bRet;
}

sal_Bool XMLFontEncodingPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    OUStringBuffer aOut;
    sal_Int16 nSet;

    if( rValue >>= nSet )
    {
        if( (rtl_TextEncoding)nSet == RTL_TEXTENCODING_SYMBOL )
        {
            aOut.append( GetXMLToken(XML_X_SYMBOL) );
            rStrExpValue = aOut.makeStringAndClear();
            bRet = sal_True;
        }
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontPitchPropHdl
//

XMLFontPitchPropHdl::~XMLFontPitchPropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontPitchPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    USHORT eNewPitch;

    if( ( bRet = rUnitConverter.convertEnum( eNewPitch, rStrImpValue, aFontPitchMapping ) ) )
        rValue <<= (sal_Int16)eNewPitch;

    return bRet;
}

sal_Bool XMLFontPitchPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nPitch;
    OUStringBuffer aOut;

    FontPitch ePitch;
    if( rValue >>= nPitch )
        ePitch =  (FontPitch)nPitch;

    if( PITCH_DONTKNOW != ePitch )
    {
        bRet = rUnitConverter.convertEnum( aOut, ePitch, aFontPitchMapping, XML_FIXED );
        rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}
<commit_msg>INTEGRATION: CWS ooo20040704 (1.6.344); FILE MERGED 2004/07/03 14:46:50 waratah 1.6.344.1: #i30874# Correct uninitiliased warnings<commit_after>/*************************************************************************
 *
 *  $RCSfile: fonthdl.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-08 15:00:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_FONTTYPES_HXX
#include <fonthdl.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _VCL_VCLENUM_HXX
#include <vcl/vclenum.hxx>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::xmloff::token;

static SvXMLEnumMapEntry __READONLY_DATA aFontFamilyGenericMapping[] =
{
    { XML_DECORATIVE,       FAMILY_DECORATIVE },

    { XML_MODERN,           FAMILY_MODERN   },
    { XML_ROMAN,            FAMILY_ROMAN    },
    { XML_SCRIPT,           FAMILY_SCRIPT   },
    { XML_SWISS,            FAMILY_SWISS    },
    { XML_SYSTEM,           FAMILY_SYSTEM   },
    { XML_TOKEN_INVALID,    0               }
};

static SvXMLEnumMapEntry __READONLY_DATA aFontPitchMapping[] =
{
    { XML_FIXED,            PITCH_FIXED     },
    { XML_VARIABLE,         PITCH_VARIABLE  },
    { XML_TOKEN_INVALID,    0               }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontFamilyNamePropHdl
//

XMLFontFamilyNamePropHdl::~XMLFontFamilyNamePropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontFamilyNamePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    String sValue;
    sal_Int32 nPos = 0;

    do
    {
        sal_Int32 nFirst = nPos;
        nPos = SvXMLUnitConverter::indexOfComma( rStrImpValue, nPos );
        sal_Int32 nLast = (-1 == nPos ? rStrImpValue.getLength() : nPos);
        if( nLast > 0 )
            nLast--;

        // skip trailing blanks
        while( sal_Unicode(' ') == rStrImpValue[nLast] && nLast > nFirst )
            nLast--;

        // skip leading blanks
        while( sal_Unicode(' ') == rStrImpValue[nFirst] && nFirst <= nLast )
            nFirst++;

        // remove quotes
        sal_Unicode c = rStrImpValue[nFirst];
        if( nFirst < nLast && (sal_Unicode('\'') == c || sal_Unicode('\"') == c) && rStrImpValue[nLast] == c )
        {
            nFirst++;
            nLast--;
        }

        if( nFirst <= nLast )
        {
            if( sValue.Len() != 0 )
                sValue += sal_Unicode(';');

            OUString sTemp = rStrImpValue.copy( nFirst, nLast-nFirst+1 );
            sValue += sTemp.getStr();
        }

        if( -1 != nPos )
            nPos++;
    }
    while( -1 != nPos );

    if( sValue.Len() )
    {
        rValue <<= OUString(sValue.GetBuffer());
        bRet = sal_True;
    }

    return bRet;
}

sal_Bool XMLFontFamilyNamePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    OUString aStrFamilyName;

    if( rValue >>= aStrFamilyName )
    {
        OUStringBuffer sValue( aStrFamilyName.getLength() + 2L );
        sal_Int32 nPos = 0L;
        do
        {
            sal_Int32 nFirst = nPos;
            nPos = aStrFamilyName.indexOf( sal_Unicode(';'), nPos );
            sal_Int32 nLast = (-1L == nPos ? aStrFamilyName.getLength() : nPos);

            // Set position to the character behind the ';', so we won't
            // forget this.
            if( -1L != nPos )
                nPos++;

            // If the property value was empty, we stop now.
            // If there is a ';' at the first position, the empty name
            // at the start will be removed.
            if( 0L == nLast )
                continue;

            // nFirst and nLast now denote the first and last character of
            // one font name.
            nLast--;

            // skip trailing blanks
            while( sal_Unicode(' ') == aStrFamilyName[nLast] && nLast > nFirst )
                nLast--;

            // skip leading blanks
            while( sal_Unicode(' ') == aStrFamilyName[nFirst] && nFirst <= nLast )
                nFirst++;

            if( nFirst <= nLast )
            {
                if( sValue.getLength() != 0L )
                {
                    sValue.append( sal_Unicode( ',' ) );
                    sValue.append( sal_Unicode( ' ' ));
                }
                sal_Int32 nLen = nLast-nFirst+1L;
                OUString sFamily( aStrFamilyName.copy( nFirst, nLen ) );
                sal_Bool bQuote = sal_False;
                for( sal_Int32 i=0; i < nLen; i++ )
                {
                    sal_Unicode c = sFamily[i];
                    if( sal_Unicode(' ') == c || sal_Unicode(',') == c )
                    {
                        bQuote = sal_True;
                        break;
                    }
                }
                if( bQuote )
                    sValue.append( sal_Unicode('\'') );
                sValue.append( sFamily );
                if( bQuote )
                    sValue.append( sal_Unicode('\'') );
            }
        }
        while( -1L != nPos );

        rStrExpValue = sValue.makeStringAndClear();

        bRet = sal_True;
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontFamilyPropHdl
//

XMLFontFamilyPropHdl::~XMLFontFamilyPropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontFamilyPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewFamily;

    if( ( bRet = rUnitConverter.convertEnum( eNewFamily, rStrImpValue, aFontFamilyGenericMapping ) ) )
        rValue <<= (sal_Int16)eNewFamily;

    return bRet;
}

sal_Bool XMLFontFamilyPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    OUStringBuffer aOut;

    sal_Int16 nFamily;
    if( rValue >>= nFamily )
    {
        FontFamily eFamily = (FontFamily)nFamily;
        if( eFamily != FAMILY_DONTKNOW )
            bRet = rUnitConverter.convertEnum( aOut, eFamily, aFontFamilyGenericMapping );
    }

    rStrExpValue = aOut.makeStringAndClear();

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontEncodingPropHdl
//

XMLFontEncodingPropHdl::~XMLFontEncodingPropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontEncodingPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_True;

    if( IsXMLToken( rStrImpValue, XML_X_SYMBOL ) )
        rValue <<= (sal_Int16) RTL_TEXTENCODING_SYMBOL;

    return bRet;
}

sal_Bool XMLFontEncodingPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    OUStringBuffer aOut;
    sal_Int16 nSet;

    if( rValue >>= nSet )
    {
        if( (rtl_TextEncoding)nSet == RTL_TEXTENCODING_SYMBOL )
        {
            aOut.append( GetXMLToken(XML_X_SYMBOL) );
            rStrExpValue = aOut.makeStringAndClear();
            bRet = sal_True;
        }
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontPitchPropHdl
//

XMLFontPitchPropHdl::~XMLFontPitchPropHdl()
{
    // Nothing to do
}

sal_Bool XMLFontPitchPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    USHORT eNewPitch;

    if( ( bRet = rUnitConverter.convertEnum( eNewPitch, rStrImpValue, aFontPitchMapping ) ) )
        rValue <<= (sal_Int16)eNewPitch;

    return bRet;
}

sal_Bool XMLFontPitchPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nPitch;
    OUStringBuffer aOut;

    FontPitch ePitch = PITCH_DONTKNOW;
    if( rValue >>= nPitch )
        ePitch =  (FontPitch)nPitch;

    if( PITCH_DONTKNOW != ePitch )
    {
        bRet = rUnitConverter.convertEnum( aOut, ePitch, aFontPitchMapping, XML_FIXED );
        rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}
<|endoftext|>


<commit_before><commit_msg>lowered dist threshhold<commit_after><|endoftext|>


<commit_before>#pragma once

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

#include "cxxtest/TestSuite.h"

#include <zcm/message_tracker.hpp>

using namespace std;

class MessageTrackerTest : public CxxTest::TestSuite
{
  public:
    void setUp() override {}
    void tearDown() override {}

    struct example_t {
        uint64_t utime;
        int decode(void* data, int start, int max) { return 0; }
        static const char* getTypeName() { return "example_t"; }
    };

    struct data_t {
            uint64_t utime;
            int offset;
            int bufInd;
        };

    void testFreqStats()
    {
        constexpr size_t numMsgs = 1000;
        zcm::MessageTracker<example_t> mt(nullptr, "", 0.25, numMsgs);
        for (size_t i = 0; i < 1000; ++i) {
            example_t tmp;
            tmp.utime = i * 1e4;
            mt.newMsg(&tmp, tmp.utime + 1);
            TS_ASSERT_EQUALS(mt.lastMsgHostUtime(), tmp.utime + 1);
        }
        TS_ASSERT_DELTA(mt.getHz(), 100, 1e-5);
        TS_ASSERT_LESS_THAN(mt.getJitterUs(), 1e-5);
    }

    void testGetRange()
    {
        constexpr size_t numMsgs = 1000;
        // RRR (Bendes) You're telling the message tracker to not track any
        //              messages older than 100 us     0.0001s = 100us
        zcm::MessageTracker<example_t> mt(nullptr, "", 0.0001, numMsgs);
        for (size_t i = 0; i < 1000; ++i) {
            example_t tmp;
            tmp.utime = i + 101;
            mt.newMsg(&tmp);
        }

        vector<example_t*> gotRange = mt.getRange(101, 105);
        TS_ASSERT_EQUALS(gotRange.size(), 5);
        for (auto msg : gotRange) {
            TS_ASSERT(msg->utime >= 101 && msg->utime <= 105);
            delete msg;
        }

        gotRange = mt.getRange(105, 105);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 105);
            delete msg;
        }

        gotRange = mt.getRange(110, 105);
        TS_ASSERT_EQUALS(gotRange.size(), 0);

        gotRange = mt.getRange(0, 1);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 101);
            delete msg;
        }

        gotRange = mt.getRange(1200, 1300);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 1100);
            delete msg;
        }

        gotRange = mt.getRange(1201, 1300);
        TS_ASSERT_EQUALS(gotRange.size(), 0);

        gotRange = mt.getRange(0, 0);
        TS_ASSERT_EQUALS(gotRange.size(), 0);

        gotRange = mt.getRange(100, 100);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 101);
            delete msg;
        }

        gotRange = mt.getRange(1102, 1205);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 1100);
            delete msg;
        }
    }

    void testGetInternalBuf()
    {
        struct data_t {
            uint64_t utime;
            int offset;
            int bufInd;
            int decode(void* data, int start, int max) { return 0; }
            static const char* getTypeName() { return "data_t"; }
        };

        size_t numMsgs = 10;
        zcm::MessageTracker<data_t> mt(nullptr, "", 0.25, numMsgs);
        for (int i = 0; i < 10; i++) {
            data_t d = {123456780 + (uint64_t)i, 100 + i, i};
            mt.newMsg(&d, 0);
        }
        data_t* out = mt.get((uint64_t)123456785);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);
        out = mt.get((uint64_t)123456790);
        TS_ASSERT_EQUALS(out->bufInd, 9);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 9);

    }

    void testGetTrackerUsingInternalBuf()
    {
        size_t numMsgs = 100;
        zcm::Tracker<data_t> mt(0.25, numMsgs);
        for (int i = 0; i < (int) numMsgs; i++) {
            data_t d = {1234567810  + (uint64_t)i, 100 + i, i};
            mt.newMsg(&d);
        }
        data_t* out = mt.get((uint64_t)1234567815);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);
        out = mt.get((uint64_t)1234567950);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, (uint64_t) 99);
        out = mt.get((uint64_t)1234567890);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->utime, (uint64_t)1234567890);

    }

    void testGetTrackerUsingProvidedBuf()
    {

        size_t numMsgs = 10;
        zcm::Tracker<data_t> mt(0.25, numMsgs);
        std::vector<data_t*> buf(10);
        data_t d;
        for (int i = 0; i < 10; i++) {
            d.utime = 1234567810  + (uint64_t)i;
            d.bufInd = i;
            data_t* tmp = new data_t(d);
            buf[i] = tmp;
        }

        std::mutex bufLock;
        std::unique_lock<std::mutex> lk(bufLock);
        data_t* out = mt.get((uint64_t)1234567815, buf.begin(), buf.end(), lk);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);
        out = mt.get((uint64_t)1234567840, buf.begin(), buf.end(), lk);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 9);
        out = mt.get((uint64_t)1234567813, std::next(buf.begin(), 5), buf.end(), lk);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);

        // free the dynamically allocated memory
        for (int i = 0; i < 10; i++) {
            delete buf[i];
         }
    }
};
<commit_msg>test fix<commit_after>#pragma once

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

#include "cxxtest/TestSuite.h"

#include <zcm/message_tracker.hpp>

using namespace std;

class MessageTrackerTest : public CxxTest::TestSuite
{
  public:
    void setUp() override {}
    void tearDown() override {}

    struct example_t {
        uint64_t utime;
        int decode(void* data, int start, int max) { return 0; }
        static const char* getTypeName() { return "example_t"; }
    };

    struct data_t {
            uint64_t utime;
            int offset;
            int bufInd;
        };

    void testFreqStats()
    {
        constexpr size_t numMsgs = 1000;
        zcm::MessageTracker<example_t> mt(nullptr, "", 0.25, numMsgs);
        for (size_t i = 0; i < 1000; ++i) {
            example_t tmp;
            tmp.utime = i * 1e4;
            mt.newMsg(&tmp, tmp.utime + 1);
            TS_ASSERT_EQUALS(mt.lastMsgHostUtime(), tmp.utime + 1);
        }
        TS_ASSERT_DELTA(mt.getHz(), 100, 1e-5);
        TS_ASSERT_LESS_THAN(mt.getJitterUs(), 1e-5);
    }

    void testGetRange()
    {
        constexpr size_t numMsgs = 1000;
        zcm::MessageTracker<example_t> mt(nullptr, "", 0.001, numMsgs);
        for (size_t i = 0; i < 1000; ++i) {
            example_t tmp;
            tmp.utime = i + 101;
            mt.newMsg(&tmp);
        }

        vector<example_t*> gotRange = mt.getRange(101, 105);
        TS_ASSERT_EQUALS(gotRange.size(), 5);
        for (auto msg : gotRange) {
            TS_ASSERT(msg->utime >= 101 && msg->utime <= 105);
            delete msg;
        }

        gotRange = mt.getRange(105, 105);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 105);
            delete msg;
        }

        gotRange = mt.getRange(110, 105);
        TS_ASSERT_EQUALS(gotRange.size(), 0);

        gotRange = mt.getRange(0, 1);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 101);
            delete msg;
        }

        gotRange = mt.getRange(1200, 1300);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 1100);
            delete msg;
        }

        gotRange = mt.getRange(100, 100);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 101);
            delete msg;
        }

        gotRange = mt.getRange(1102, 1205);
        TS_ASSERT_EQUALS(gotRange.size(), 1);
        for (auto msg : gotRange) {
            TS_ASSERT_EQUALS(msg->utime, 1100);
            delete msg;
        }
    }

    void testGetInternalBuf()
    {
        struct data_t {
            uint64_t utime;
            int offset;
            int bufInd;
            int decode(void* data, int start, int max) { return 0; }
            static const char* getTypeName() { return "data_t"; }
        };

        size_t numMsgs = 10;
        zcm::MessageTracker<data_t> mt(nullptr, "", 0.25, numMsgs);
        for (int i = 0; i < 10; i++) {
            data_t d = {123456780 + (uint64_t)i, 100 + i, i};
            mt.newMsg(&d, 0);
        }
        data_t* out = mt.get((uint64_t)123456785);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);
        out = mt.get((uint64_t)123456790);
        TS_ASSERT_EQUALS(out->bufInd, 9);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 9);

    }

    void testGetTrackerUsingInternalBuf()
    {
        size_t numMsgs = 100;
        zcm::Tracker<data_t> mt(0.25, numMsgs);
        for (int i = 0; i < (int) numMsgs; i++) {
            data_t d = {1234567810  + (uint64_t)i, 100 + i, i};
            mt.newMsg(&d);
        }
        data_t* out = mt.get((uint64_t)1234567815);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);
        out = mt.get((uint64_t)1234567950);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, (uint64_t) 99);
        out = mt.get((uint64_t)1234567890);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->utime, (uint64_t)1234567890);

    }

    void testGetTrackerUsingProvidedBuf()
    {

        size_t numMsgs = 10;
        zcm::Tracker<data_t> mt(0.25, numMsgs);
        std::vector<data_t*> buf(10);
        data_t d;
        for (int i = 0; i < 10; i++) {
            d.utime = 1234567810  + (uint64_t)i;
            d.bufInd = i;
            data_t* tmp = new data_t(d);
            buf[i] = tmp;
        }

        std::mutex bufLock;
        std::unique_lock<std::mutex> lk(bufLock);
        data_t* out = mt.get((uint64_t)1234567815, buf.begin(), buf.end(), lk);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);
        out = mt.get((uint64_t)1234567840, buf.begin(), buf.end(), lk);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 9);
        out = mt.get((uint64_t)1234567813, std::next(buf.begin(), 5), buf.end(), lk);
        TS_ASSERT(out != nullptr);
        if (out!= nullptr)
            TS_ASSERT_EQUALS(out->bufInd, 5);

        // free the dynamically allocated memory
        for (int i = 0; i < 10; i++) {
            delete buf[i];
         }
    }
};
<|endoftext|>


<commit_before>/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 14:05:18
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <chrono>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef tuple<int, int, int, int, int> state; // x, y, dir, a, b

int A, B;
int h, w;
string c[100];

stack<state> S;

bool valid(int x, int y, int a, int b)
{
  return (a <= A && b <= B && c[x][y] == '.');
}

int main()
{
  auto start = std::chrono::system_clock::now();
  cin >> A >> B;
  cin >> h >> w;
  for (auto i = 0; i < h; i++)
  {
    cin >> c[i];
  }
  S.push(state(1, 1, 0, 0, 0));
  while (!S.empty())
  {
    auto end = std::chrono::system_clock::now();
    double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
    if (elapsed > 2000) {
      cout << "Yes" << endl;
      return 0;
    }
    int now_x = get<0>(S.top());
    int now_y = get<1>(S.top());
    int now_dir = get<2>(S.top());
    int now_a = get<3>(S.top());
    int now_b = get<4>(S.top());
    #if DEBUG == 1
    cerr << "(" << now_x << ", " << now_y << "), "
         << now_dir << ", "
         << "(" << now_a << ", " << now_b << ")" << endl;
    #endif
    S.pop();
    if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)
    {
      cout << "Yes" << endl;
      return 0;
    }
    else
    {
      int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};
      int new_a[3] = {now_a + 1, now_a, now_a};
      int new_b[3] = {now_b, now_b + 1, now_b};
      for (auto k = 0; k < 3; k++)
      {
        int new_x = now_x + dx[new_dir[k]];
        int new_y = now_y + dy[new_dir[k]];
        if (valid(new_x, new_y, new_a[k], new_b[k]))
        {
          S.push(state(new_x, new_y, new_dir[k], new_a[k], new_b[k]));
        }
      }
    }
  }
  cout << "No" << endl;
}<commit_msg>submit B.cpp to 'B - 駆け抜けろ！埼大山車部！！' (maximum-cup-2018) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 14:05:18
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <chrono>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef tuple<int, int, int, int, int> state; // x, y, dir, a, b

int A, B;
int h, w;
string c[100];

stack<state> S;

bool valid(int x, int y, int a, int b)
{
  return (a <= A && b <= B && c[x][y] == '.');
}

int main()
{
  auto start = std::chrono::system_clock::now();
  cin >> A >> B;
  cin >> h >> w;
  for (auto i = 0; i < h; i++)
  {
    cin >> c[i];
  }
  S.push(state(1, 1, 0, 0, 0));
  while (!S.empty())
  {
    auto end = std::chrono::system_clock::now();
    double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
    if (elapsed > 2950) {
      cout << "No" << endl;
      return 0;
    }
    int now_x = get<0>(S.top());
    int now_y = get<1>(S.top());
    int now_dir = get<2>(S.top());
    int now_a = get<3>(S.top());
    int now_b = get<4>(S.top());
    #if DEBUG == 1
    cerr << "(" << now_x << ", " << now_y << "), "
         << now_dir << ", "
         << "(" << now_a << ", " << now_b << ")" << endl;
    #endif
    S.pop();
    if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)
    {
      cout << "Yes" << endl;
      return 0;
    }
    else
    {
      int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};
      int new_a[3] = {now_a + 1, now_a, now_a};
      int new_b[3] = {now_b, now_b + 1, now_b};
      for (auto k = 0; k < 3; k++)
      {
        int new_x = now_x + dx[new_dir[k]];
        int new_y = now_y + dy[new_dir[k]];
        if (valid(new_x, new_y, new_a[k], new_b[k]))
        {
          S.push(state(new_x, new_y, new_dir[k], new_a[k], new_b[k]));
        }
      }
    }
  }
  cout << "No" << endl;
}<|endoftext|>


<commit_before>#ifndef STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP
#define STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP

#include <stan/interface_callbacks/writer/base_writer.hpp>
#include <stan/mcmc/hmc/integrators/base_integrator.hpp>
#include <iostream>
#include <iomanip>

namespace stan {
  namespace mcmc {

    template <class Hamiltonian>
    class base_leapfrog : public base_integrator<Hamiltonian> {
    public:
      base_leapfrog()
        : base_integrator<Hamiltonian>() {}

      void evolve(typename Hamiltonian::PointType& z,
                  Hamiltonian& hamiltonian,
                  const double epsilon,
                  interface_callbacks::writer::base_writer& writer) {
        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z, writer);

        end_update_p(z, hamiltonian, 0.5 * epsilon);
      }

      void verbose_evolve(typename Hamiltonian::PointType& z,
                          Hamiltonian& hamiltonian,
                          const double epsilon,
                          interface_callbacks::writer::base_writer& writer) {
        std::stringstream msg;
        msg.precision(6);

        int width = 14;
        int nColumn = 4;

        msg << "Verbose Hamiltonian Evolution, Step Size = " << epsilon << ":";
        this->writer_(msg.str());

        msg.str("");
        msg << "    " << std::setw(nColumn * width)
            << std::setfill('-')
            << "" << std::setfill(' ');
        this->writer_(msg.str());

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "Poisson"
            << std::setw(width) << std::left << "Initial"
            << std::setw(width) << std::left << "Current"
            << std::setw(width) << std::left << "DeltaH";
        this->writer_(msg.str());

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "Operator"
            << std::setw(width) << std::left << "Hamiltonian"
            << std::setw(width) << std::left << "Hamiltonian"
            << std::setw(width) << std::left << "/ Stepsize^{2}";
        this->writer_(msg.str());

        msg.str("");
        msg << "    " << std::setw(nColumn * width)
            << std::setfill('-')
            << "" << std::setfill(' ');
        this->writer_(msg.str());

        double H0 = hamiltonian.H(z);

        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        double H1 = hamiltonian.H(z);

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "hat{V}/2"
            << std::setw(width) << std::left << H0
            << std::setw(width) << std::left << H1
            << std::setw(width) << std::left << (H1 - H0) / (epsilon * epsilon);
        this->writer_(msg.str());

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z, writer);

        double H2 = hamiltonian.H(z);

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "hat{T}"
            << std::setw(width) << std::left << H0
            << std::setw(width) << std::left << H2
            << std::setw(width) << std::left << (H2 - H0) / (epsilon * epsilon);
        this->writer_(msg.str());

        end_update_p(z, hamiltonian, 0.5 * epsilon);

        double H3 = hamiltonian.H(z);

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "hat{V}/2"
            << std::setw(width) << std::left << H0
            << std::setw(width) << std::left << H3
            << std::setw(width) << std::left << (H3 - H0) / (epsilon * epsilon);
        this->writer_(msg.str());

        msg.str("");
        msg << "    "
            << std::setw(nColumn * width)
            << std::setfill('-')
            << ""
            << std::setfill(' ');
        this->writer_(msg.str());
      }

      virtual void begin_update_p(typename Hamiltonian::PointType& z,
                                  Hamiltonian& hamiltonian,
                                  double epsilon) = 0;
      virtual void update_q(typename Hamiltonian::PointType& z,
                            Hamiltonian& hamiltonian,
                            double epsilon) = 0;
      virtual void end_update_p(typename Hamiltonian::PointType& z,
                                Hamiltonian& hamiltonian,
                                double epsilon) = 0;
    };

  }  // mcmc
}  // stan
#endif
<commit_msg>Fixing use of writer in base_leapfrog.hpp<commit_after>#ifndef STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP
#define STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP

#include <stan/interface_callbacks/writer/base_writer.hpp>
#include <stan/mcmc/hmc/integrators/base_integrator.hpp>
#include <iostream>
#include <iomanip>

namespace stan {
  namespace mcmc {

    template <class Hamiltonian>
    class base_leapfrog : public base_integrator<Hamiltonian> {
    public:
      base_leapfrog()
        : base_integrator<Hamiltonian>() {}

      void evolve(typename Hamiltonian::PointType& z,
                  Hamiltonian& hamiltonian,
                  const double epsilon,
                  interface_callbacks::writer::base_writer& writer) {
        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z, writer);

        end_update_p(z, hamiltonian, 0.5 * epsilon);
      }

      void verbose_evolve(typename Hamiltonian::PointType& z,
                          Hamiltonian& hamiltonian,
                          const double epsilon,
                          interface_callbacks::writer::base_writer& writer) {
        std::stringstream msg;
        msg.precision(6);

        int width = 14;
        int nColumn = 4;

        msg << "Verbose Hamiltonian Evolution, Step Size = " << epsilon << ":";
        writer(msg.str());

        msg.str("");
        msg << "    " << std::setw(nColumn * width)
            << std::setfill('-')
            << "" << std::setfill(' ');
        writer(msg.str());

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "Poisson"
            << std::setw(width) << std::left << "Initial"
            << std::setw(width) << std::left << "Current"
            << std::setw(width) << std::left << "DeltaH";
        writer(msg.str());

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "Operator"
            << std::setw(width) << std::left << "Hamiltonian"
            << std::setw(width) << std::left << "Hamiltonian"
            << std::setw(width) << std::left << "/ Stepsize^{2}";
        writer(msg.str());

        msg.str("");
        msg << "    " << std::setw(nColumn * width)
            << std::setfill('-')
            << "" << std::setfill(' ');
        writer(msg.str());

        double H0 = hamiltonian.H(z);

        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        double H1 = hamiltonian.H(z);

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "hat{V}/2"
            << std::setw(width) << std::left << H0
            << std::setw(width) << std::left << H1
            << std::setw(width) << std::left << (H1 - H0) / (epsilon * epsilon);
        writer(msg.str());

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z, writer);

        double H2 = hamiltonian.H(z);

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "hat{T}"
            << std::setw(width) << std::left << H0
            << std::setw(width) << std::left << H2
            << std::setw(width) << std::left << (H2 - H0) / (epsilon * epsilon);
        writer(msg.str());

        end_update_p(z, hamiltonian, 0.5 * epsilon);

        double H3 = hamiltonian.H(z);

        msg.str("");
        msg << "    "
            << std::setw(width) << std::left << "hat{V}/2"
            << std::setw(width) << std::left << H0
            << std::setw(width) << std::left << H3
            << std::setw(width) << std::left << (H3 - H0) / (epsilon * epsilon);
        writer(msg.str());

        msg.str("");
        msg << "    "
            << std::setw(nColumn * width)
            << std::setfill('-')
            << ""
            << std::setfill(' ');
        writer(msg.str());
      }

      virtual void begin_update_p(typename Hamiltonian::PointType& z,
                                  Hamiltonian& hamiltonian,
                                  double epsilon) = 0;
      virtual void update_q(typename Hamiltonian::PointType& z,
                            Hamiltonian& hamiltonian,
                            double epsilon) = 0;
      virtual void end_update_p(typename Hamiltonian::PointType& z,
                                Hamiltonian& hamiltonian,
                                double epsilon) = 0;
    };

  }  // mcmc
}  // stan
#endif
<|endoftext|>


<commit_before>#ifndef STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP
#define STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/kernel_cl.hpp>

namespace stan {
namespace math {
namespace opencl_kernels {

// \cond
static const char* normal_id_glm_kernel_code = STRINGIFY(
    // \endcond
    /**
     * GPU implementation of Generalized Linear Model (GLM)
     * with Normal distribution and identity link function.
     *
     * Must be run with at least N threads and local size equal to LOCAL_SIZE_.
     * @param[in] y_glob vector parameter
     * @param[in] x design matrix
     * @param[in] alpha intercept (in log odds)
     * @param[in] beta weight vector
     * @param[in] sigma_glob (Sequence of) scale parameters for the normal
     * @param[out] mu_derivative_glob intermediate variable used in the model
     * @param[out] mu_derivative_sum partially summed mu_derivative_glob (1
     * value per work group)
     * @param[out] y_minus_mu_over_sigma_squared_sum intermediate variable used
     * in the model
     * @param[out] sigma_derivative derivative with respect to sigma
     * @param[out] log_sigma_sum partially summed logarithm of sigma (1 value
     * per work group)
     * @param N number of cases
     * @param M number of attributes
     * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively
     * it is a scalar)
     * @param is_sigma_vector 0 or 1 - whether sigma is a vector (alternatively
     * it is a scalar)
     * @param need_mu_derivative interpreted as boolean - whether mu_derivative
     * needs to be computed
     * @param need_mu_derivative_sum interpreted as boolean - whether
     * mu_derivative_sum needs to be computed
     * @param need_sigma_derivative interpreted as boolean - whether
     * sigma_derivative needs to be computed
     * @param need_log_sigma_sum interpreted as boolean - whether log_sigma_sum
     * needs to be computed
     */
    __kernel void normal_id_glm(
        __global double* mu_derivative_glob, __global double* mu_derivative_sum,
        __global double* y_minus_mu_over_sigma_squared_sum,
        __global double* sigma_derivative, __global double* log_sigma_sum,
        const __global double* y_glob, const __global double* x,
        const __global double* alpha, const __global double* beta,
        const __global double* sigma_glob, const int N, const int M,
        const int is_alpha_vector, const int is_sigma_vector,
        const int need_mu_derivative, const int need_mu_derivative_sum,
        const int need_sigma_derivative, const int need_log_sigma_sum) {
      const int gid = get_global_id(0);
      const int lid = get_local_id(0);
      const int lsize = get_local_size(0);
      const int wgid = get_group_id(0);

      __local double res_loc[LOCAL_SIZE_];

      double y_minus_mu_over_sigma_squared = 0;
      double log_sigma = 0;
      double mu_derivative = 0;
      if (gid < N) {
        double y_minus_mu_over_sigma = 0;
        for (int i = 0, j = 0; i < M; i++, j += N) {
          y_minus_mu_over_sigma += x[j + gid] * beta[i];
        }
        double sigma = sigma_glob[gid * is_sigma_vector];
        double inv_sigma = 1 / sigma;
        y_minus_mu_over_sigma = (y_glob[gid] - y_minus_mu_over_sigma
                                 - alpha[gid * is_alpha_vector])
                                * inv_sigma;
        mu_derivative = inv_sigma * y_minus_mu_over_sigma;
        if (need_mu_derivative) {
          mu_derivative_glob[gid] = mu_derivative;
        }
        y_minus_mu_over_sigma_squared
            = y_minus_mu_over_sigma * y_minus_mu_over_sigma;
        if (need_sigma_derivative) {
          sigma_derivative[gid]
              = (y_minus_mu_over_sigma_squared - 1) * inv_sigma;
        }
        if (need_log_sigma_sum) {
          log_sigma = log(sigma);
        }
      }
      res_loc[lid] = y_minus_mu_over_sigma_squared;
      barrier(CLK_LOCAL_MEM_FENCE);
      for (int step = lsize / REDUCTION_STEP_SIZE; step > 0;
           step /= REDUCTION_STEP_SIZE) {
        if (lid < step) {
          for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {
            res_loc[lid] += res_loc[lid + step * i];
          }
        }
        barrier(CLK_LOCAL_MEM_FENCE);
      }
      if (lid == 0) {
        y_minus_mu_over_sigma_squared_sum[wgid] = res_loc[0];
      }

      if (need_mu_derivative_sum) {
        barrier(CLK_LOCAL_MEM_FENCE);
        res_loc[lid] = mu_derivative;
        barrier(CLK_LOCAL_MEM_FENCE);
        for (int step = lsize / REDUCTION_STEP_SIZE; step > 0;
             step /= REDUCTION_STEP_SIZE) {
          if (lid < step) {
            for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {
              res_loc[lid] += res_loc[lid + step * i];
            }
          }
          barrier(CLK_LOCAL_MEM_FENCE);
        }
        if (lid == 0) {
          mu_derivative_sum[wgid] = res_loc[0];
        }
      }

      if (need_log_sigma_sum) {
        barrier(CLK_LOCAL_MEM_FENCE);
        res_loc[lid] = log_sigma;
        barrier(CLK_LOCAL_MEM_FENCE);
        for (int step = lsize / REDUCTION_STEP_SIZE; step > 0;
             step /= REDUCTION_STEP_SIZE) {
          if (lid < step) {
            for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {
              res_loc[lid] += res_loc[lid + step * i];
            }
          }
          barrier(CLK_LOCAL_MEM_FENCE);
        }
        if (lid == 0) {
          log_sigma_sum[wgid] = res_loc[0];
        }
      }
    }
    // \cond
);
// \endcond

/**
 * See the docs for \link kernels/normal_id_glm_lpdf.hpp
 * normal_id_glm() \endlink
 */
const kernel_cl<out_buffer, out_buffer, out_buffer, out_buffer, out_buffer,
                in_buffer, in_buffer, in_buffer, in_buffer, in_buffer, int, int,
                int, int, int, int, int, int>
    normal_id_glm("normal_id_glm", normal_id_glm_kernel_code,
                  {{"REDUCTION_STEP_SIZE", 4}, {"LOCAL_SIZE_", 64}});

}  // namespace opencl_kernels
}  // namespace math
}  // namespace stan

#endif
#endif
<commit_msg>improved docs<commit_after>#ifndef STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP
#define STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/kernel_cl.hpp>

namespace stan {
namespace math {
namespace opencl_kernels {

// \cond
static const char* normal_id_glm_kernel_code = STRINGIFY(
    // \endcond
    /**
     * GPU implementation of Generalized Linear Model (GLM)
     * with Normal distribution and identity link function.
     *
     * Must be run with at least N threads and local size equal to LOCAL_SIZE_.
     * @param[in] y_glob vector parameter
     * @param[in] x design matrix
     * @param[in] alpha intercept (in log odds)
     * @param[in] beta weight vector
     * @param[in] sigma_glob (Sequence of) scale parameters for the normal
     * @param[out] mu_derivative_glob intermediate variable used in the model
     * @param[out] mu_derivative_sum partially summed mu_derivative_glob (1
     * value per work group)
     * @param[out] y_minus_mu_over_sigma_squared_sum Partial sum of squares of
     * y, scaled by expected mean and given variance.
     * @param[out] sigma_derivative derivative with respect to sigma
     * @param[out] log_sigma_sum partially summed logarithm of sigma (1 value
     * per work group)
     * @param N number of cases
     * @param M number of attributes
     * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively
     * it is a scalar)
     * @param is_sigma_vector 0 or 1 - whether sigma is a vector (alternatively
     * it is a scalar)
     * @param need_mu_derivative interpreted as boolean - whether mu_derivative
     * needs to be computed
     * @param need_mu_derivative_sum interpreted as boolean - whether
     * mu_derivative_sum needs to be computed
     * @param need_sigma_derivative interpreted as boolean - whether
     * sigma_derivative needs to be computed
     * @param need_log_sigma_sum interpreted as boolean - whether log_sigma_sum
     * needs to be computed
     */
    __kernel void normal_id_glm(
        __global double* mu_derivative_glob, __global double* mu_derivative_sum,
        __global double* y_minus_mu_over_sigma_squared_sum,
        __global double* sigma_derivative, __global double* log_sigma_sum,
        const __global double* y_glob, const __global double* x,
        const __global double* alpha, const __global double* beta,
        const __global double* sigma_glob, const int N, const int M,
        const int is_alpha_vector, const int is_sigma_vector,
        const int need_mu_derivative, const int need_mu_derivative_sum,
        const int need_sigma_derivative, const int need_log_sigma_sum) {
      const int gid = get_global_id(0);
      const int lid = get_local_id(0);
      const int lsize = get_local_size(0);
      const int wgid = get_group_id(0);

      __local double res_loc[LOCAL_SIZE_];

      double y_minus_mu_over_sigma_squared = 0;
      double log_sigma = 0;
      double mu_derivative = 0;
      if (gid < N) {
        double y_minus_mu_over_sigma = 0;
        for (int i = 0, j = 0; i < M; i++, j += N) {
          y_minus_mu_over_sigma += x[j + gid] * beta[i];
        }
        double sigma = sigma_glob[gid * is_sigma_vector];
        double inv_sigma = 1 / sigma;
        y_minus_mu_over_sigma = (y_glob[gid] - y_minus_mu_over_sigma
                                 - alpha[gid * is_alpha_vector])
                                * inv_sigma;
        mu_derivative = inv_sigma * y_minus_mu_over_sigma;
        if (need_mu_derivative) {
          mu_derivative_glob[gid] = mu_derivative;
        }
        y_minus_mu_over_sigma_squared
            = y_minus_mu_over_sigma * y_minus_mu_over_sigma;
        if (need_sigma_derivative) {
          sigma_derivative[gid]
              = (y_minus_mu_over_sigma_squared - 1) * inv_sigma;
        }
        if (need_log_sigma_sum) {
          log_sigma = log(sigma);
        }
      }
      res_loc[lid] = y_minus_mu_over_sigma_squared;
      barrier(CLK_LOCAL_MEM_FENCE);
      for (int step = lsize / REDUCTION_STEP_SIZE; step > 0;
           step /= REDUCTION_STEP_SIZE) {
        if (lid < step) {
          for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {
            res_loc[lid] += res_loc[lid + step * i];
          }
        }
        barrier(CLK_LOCAL_MEM_FENCE);
      }
      if (lid == 0) {
        y_minus_mu_over_sigma_squared_sum[wgid] = res_loc[0];
      }

      if (need_mu_derivative_sum) {
        barrier(CLK_LOCAL_MEM_FENCE);
        res_loc[lid] = mu_derivative;
        barrier(CLK_LOCAL_MEM_FENCE);
        for (int step = lsize / REDUCTION_STEP_SIZE; step > 0;
             step /= REDUCTION_STEP_SIZE) {
          if (lid < step) {
            for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {
              res_loc[lid] += res_loc[lid + step * i];
            }
          }
          barrier(CLK_LOCAL_MEM_FENCE);
        }
        if (lid == 0) {
          mu_derivative_sum[wgid] = res_loc[0];
        }
      }

      if (need_log_sigma_sum) {
        barrier(CLK_LOCAL_MEM_FENCE);
        res_loc[lid] = log_sigma;
        barrier(CLK_LOCAL_MEM_FENCE);
        for (int step = lsize / REDUCTION_STEP_SIZE; step > 0;
             step /= REDUCTION_STEP_SIZE) {
          if (lid < step) {
            for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {
              res_loc[lid] += res_loc[lid + step * i];
            }
          }
          barrier(CLK_LOCAL_MEM_FENCE);
        }
        if (lid == 0) {
          log_sigma_sum[wgid] = res_loc[0];
        }
      }
    }
    // \cond
);
// \endcond

/**
 * See the docs for \link kernels/normal_id_glm_lpdf.hpp
 * normal_id_glm() \endlink
 */
const kernel_cl<out_buffer, out_buffer, out_buffer, out_buffer, out_buffer,
                in_buffer, in_buffer, in_buffer, in_buffer, in_buffer, int, int,
                int, int, int, int, int, int>
    normal_id_glm("normal_id_glm", normal_id_glm_kernel_code,
                  {{"REDUCTION_STEP_SIZE", 4}, {"LOCAL_SIZE_", 64}});

}  // namespace opencl_kernels
}  // namespace math
}  // namespace stan

#endif
#endif
<|endoftext|>