<commit_before>/*  -*- c++ -*-
    passphrasedialog.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.

    Libkleopatra 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.

    Based on kpgpui.cpp
    Copyright (C) 2001,2002 the KPGP authors
    See file libkdenetwork/AUTHORS.kpgp for details

    This file is part of KPGP, the KDE PGP/GnuPG support library.

    KPGP is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
*/

#ifndef HAVE_CONFIG_H
#include <config.h>
#endif

#include "passphrasedialog.h"

#include <kpassdlg.h>
#include <kiconloader.h>
#include <klocale.h>

#include <qlabel.h>
#include <qlayout.h>
#include <qfontmetrics.h>

struct Kleo::PassphraseDialog::Private {
  KPasswordEdit * lineedit;
};

Kleo::PassphraseDialog::PassphraseDialog( const QString & msg, const QString & caption,
					  QWidget * parent, const char * name, bool modal )
  : KDialogBase( parent, name, modal, caption, Ok|Cancel, Ok ), d( 0 )
{
  d = new Private();

  QWidget * w = new QWidget( this );
  setMainWidget( w );

  QHBoxLayout * hlay = new QHBoxLayout( w, marginHint(), spacingHint() );

  QLabel * label = new QLabel( w );
  label->setPixmap( BarIcon( "pgp-keys" ) );
  hlay->addWidget( label, 0, AlignTop );

  QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing

  vlay->addWidget( new QLabel( msg.isEmpty() ? i18n("Please enter your passphrase:") : msg, w ) );

  d->lineedit = new KPasswordEdit( KPasswordEdit::OneStar, w, "d->lineedit" );
  d->lineedit->setMinimumWidth( fontMetrics().width("*") * 20 );
  d->lineedit->setFocus();

  vlay->addWidget( d->lineedit );

  connect( d->lineedit, SIGNAL(returnPressed()), SLOT(slotOk()) );

  disableResize();
}

Kleo::PassphraseDialog::~PassphraseDialog() {
  delete d; d = 0;
}

const char * Kleo::PassphraseDialog::passphrase() const {
  return d->lineedit->password();
}

void Kleo::PassphraseDialog::slotOk() {
  const char * pass = passphrase();
  emit finished( pass ? pass : "" );
  KDialogBase::slotOk();
}

void Kleo::PassphraseDialog::slotCancel() {
  emit canceled();
  KDialogBase::slotCancel();
}

void Kleo::PassphraseDialog::virtual_hook( int id, void * data ) {
  return KDialogBase::virtual_hook( id, data );
}

#include "passphrasedialog.moc"
<commit_msg>* Add a label for the passphrase lineedit * Use a bigger icon size * Fix margin<commit_after>/*  -*- c++ -*-
    passphrasedialog.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.

    Libkleopatra 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.

    Based on kpgpui.cpp
    Copyright (C) 2001,2002 the KPGP authors
    See file libkdenetwork/AUTHORS.kpgp for details

    This file is part of KPGP, the KDE PGP/GnuPG support library.

    KPGP is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
*/

#ifndef HAVE_CONFIG_H
#include <config.h>
#endif

#include "passphrasedialog.h"

#include <kpassdlg.h>
#include <kiconloader.h>
#include <klocale.h>

#include <qlabel.h>
#include <qlayout.h>
#include <qfontmetrics.h>

struct Kleo::PassphraseDialog::Private {
  KPasswordEdit * lineedit;
};

Kleo::PassphraseDialog::PassphraseDialog( const QString & msg, const QString & caption,
					  QWidget * parent, const char * name, bool modal )
  : KDialogBase( parent, name, modal, caption, Ok|Cancel, Ok ), d( 0 )
{
  d = new Private();

  QWidget * w = new QWidget( this );
  setMainWidget( w );

  QHBoxLayout * hlay = new QHBoxLayout( w, 0, spacingHint() );

  QLabel * label = new QLabel( w );
  label->setPixmap( DesktopIcon( "pgp-keys", KIcon::SizeMedium ) );
  hlay->addWidget( label, 0, AlignTop );

  QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing

  vlay->addWidget( new QLabel( msg.isEmpty() ? i18n("Please enter your passphrase:") : msg, w ) );

  vlay->addWidget( new QLabel( i18n( "Enter passphrase:" ), w ) );
  d->lineedit = new KPasswordEdit( KPasswordEdit::OneStar, w, "d->lineedit" );
  d->lineedit->setMinimumWidth( fontMetrics().width("*") * 20 );
  d->lineedit->setFocus();

  vlay->addWidget( d->lineedit );

  connect( d->lineedit, SIGNAL(returnPressed()), SLOT(slotOk()) );

  disableResize();
}

Kleo::PassphraseDialog::~PassphraseDialog() {
  delete d; d = 0;
}

const char * Kleo::PassphraseDialog::passphrase() const {
  return d->lineedit->password();
}

void Kleo::PassphraseDialog::slotOk() {
  const char * pass = passphrase();
  emit finished( pass ? pass : "" );
  KDialogBase::slotOk();
}

void Kleo::PassphraseDialog::slotCancel() {
  emit canceled();
  KDialogBase::slotCancel();
}

void Kleo::PassphraseDialog::virtual_hook( int id, void * data ) {
  return KDialogBase::virtual_hook( id, data );
}

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


<commit_before>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/dom/CharacterData.h"

#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/MutationEvent.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/dom/Text.h"
#include "core/editing/FrameSelection.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/platform/text/TextBreakIterator.h"

using namespace std;

namespace WebCore {

void CharacterData::atomize()
{
    m_data = AtomicString(m_data);
}

void CharacterData::setData(const String& data)
{
    const String& nonNullData = !data.isNull() ? data : emptyString();
    if (m_data == nonNullData)
        return;

    RefPtr<CharacterData> protect = this;

    unsigned oldLength = length();

    setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length());
    document()->textRemoved(this, 0, oldLength);
}

String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return String();
    }

    return m_data.substring(offset, count);
}

unsigned CharacterData::parserAppendData(const String& string, unsigned offset, unsigned lengthLimit)
{
    unsigned oldLength = m_data.length();

    ASSERT(lengthLimit >= oldLength);

    unsigned characterLength = string.length() - offset;
    unsigned characterLengthLimit = min(characterLength, lengthLimit - oldLength);

    // Check that we are not on an unbreakable boundary.
    // Some text break iterator implementations work best if the passed buffer is as small as possible,
    // see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
    // We need at least two characters look-ahead to account for UTF-16 surrogates.
    ASSERT(!string.is8Bit() || string.containsOnlyLatin1()); // Latin-1 doesn't have unbreakable boundaries.
    if (characterLengthLimit < characterLength && !string.is8Bit()) {
        NonSharedCharacterBreakIterator it(string.characters16() + offset, (characterLengthLimit + 2 > characterLength) ? characterLength : characterLengthLimit + 2);
        if (!it.isBreak(characterLengthLimit))
            characterLengthLimit = it.preceding(characterLengthLimit);
    }

    if (!characterLengthLimit)
        return 0;

    if (string.is8Bit())
        m_data.append(string.characters8() + offset, characterLengthLimit);
    else
        m_data.append(string.characters16() + offset, characterLengthLimit);

    ASSERT(!renderer() || isTextNode());
    if (isTextNode())
        toText(this)->updateTextRenderer(oldLength, 0);

    document()->incDOMTreeVersion();

    if (parentNode())
        parentNode()->childrenChanged();

    return characterLengthLimit;
}

void CharacterData::appendData(const String& data)
{
    String newStr = m_data;
    newStr.append(data);

    setDataAndUpdate(newStr, m_data.length(), 0, data.length());

    // FIXME: Should we call textInserted here?
}

void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return;
    }

    String newStr = m_data;
    newStr.insert(data, offset);

    setDataAndUpdate(newStr, offset, 0, data.length());

    document()->textInserted(this, offset, data.length());
}

void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return;
    }

    unsigned realCount;
    if (offset + count > length())
        realCount = length() - offset;
    else
        realCount = count;

    String newStr = m_data;
    newStr.remove(offset, realCount);

    setDataAndUpdate(newStr, offset, count, 0);

    document()->textRemoved(this, offset, realCount);
}

void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return;
    }

    unsigned realCount;
    if (offset + count > length())
        realCount = length() - offset;
    else
        realCount = count;

    String newStr = m_data;
    newStr.remove(offset, realCount);
    newStr.insert(data, offset);

    setDataAndUpdate(newStr, offset, count, data.length());

    // update the markers for spell checking and grammar checking
    document()->textRemoved(this, offset, realCount);
    document()->textInserted(this, offset, data.length());
}

String CharacterData::nodeValue() const
{
    return m_data;
}

bool CharacterData::containsOnlyWhitespace() const
{
    return m_data.containsOnlyWhitespace();
}

void CharacterData::setNodeValue(const String& nodeValue)
{
    setData(nodeValue);
}

void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength)
{
    String oldData = m_data;
    m_data = newData;

    ASSERT(!renderer() || isTextNode());
    if (isTextNode())
        toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength);

    if (document()->frame())
        document()->frame()->selection()->textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);

    document()->incDOMTreeVersion();
    didModifyData(oldData);
}

void CharacterData::didModifyData(const String& oldData)
{
    if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(this))
        mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(this, oldData));

    if (parentNode())
        parentNode()->childrenChanged();

    if (!isInShadowTree()) {
        if (document()->hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
            dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, true, 0, oldData, m_data));
        dispatchSubtreeModifiedEvent();
    }
    InspectorInstrumentation::characterDataModified(document(), this);
}

int CharacterData::maxCharacterOffset() const
{
    return static_cast<int>(length());
}

bool CharacterData::offsetInCharacters() const
{
    return true;
}

} // namespace WebCore
<commit_msg>Remove 'String::append' from 'Source/core/dom/CharacterData.cpp'.<commit_after>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/dom/CharacterData.h"

#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/MutationEvent.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/dom/Text.h"
#include "core/editing/FrameSelection.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/platform/text/TextBreakIterator.h"

using namespace std;

namespace WebCore {

void CharacterData::atomize()
{
    m_data = AtomicString(m_data);
}

void CharacterData::setData(const String& data)
{
    const String& nonNullData = !data.isNull() ? data : emptyString();
    if (m_data == nonNullData)
        return;

    RefPtr<CharacterData> protect = this;

    unsigned oldLength = length();

    setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length());
    document()->textRemoved(this, 0, oldLength);
}

String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return String();
    }

    return m_data.substring(offset, count);
}

unsigned CharacterData::parserAppendData(const String& string, unsigned offset, unsigned lengthLimit)
{
    unsigned oldLength = m_data.length();

    ASSERT(lengthLimit >= oldLength);

    unsigned characterLength = string.length() - offset;
    unsigned characterLengthLimit = min(characterLength, lengthLimit - oldLength);

    // Check that we are not on an unbreakable boundary.
    // Some text break iterator implementations work best if the passed buffer is as small as possible,
    // see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
    // We need at least two characters look-ahead to account for UTF-16 surrogates.
    ASSERT(!string.is8Bit() || string.containsOnlyLatin1()); // Latin-1 doesn't have unbreakable boundaries.
    if (characterLengthLimit < characterLength && !string.is8Bit()) {
        NonSharedCharacterBreakIterator it(string.characters16() + offset, (characterLengthLimit + 2 > characterLength) ? characterLength : characterLengthLimit + 2);
        if (!it.isBreak(characterLengthLimit))
            characterLengthLimit = it.preceding(characterLengthLimit);
    }

    if (!characterLengthLimit)
        return 0;

    if (string.is8Bit())
        m_data.append(string.characters8() + offset, characterLengthLimit);
    else
        m_data.append(string.characters16() + offset, characterLengthLimit);

    ASSERT(!renderer() || isTextNode());
    if (isTextNode())
        toText(this)->updateTextRenderer(oldLength, 0);

    document()->incDOMTreeVersion();

    if (parentNode())
        parentNode()->childrenChanged();

    return characterLengthLimit;
}

void CharacterData::appendData(const String& data)
{
    String newStr = m_data + data;

    setDataAndUpdate(newStr, m_data.length(), 0, data.length());

    // FIXME: Should we call textInserted here?
}

void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return;
    }

    String newStr = m_data;
    newStr.insert(data, offset);

    setDataAndUpdate(newStr, offset, 0, data.length());

    document()->textInserted(this, offset, data.length());
}

void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return;
    }

    unsigned realCount;
    if (offset + count > length())
        realCount = length() - offset;
    else
        realCount = count;

    String newStr = m_data;
    newStr.remove(offset, realCount);

    setDataAndUpdate(newStr, offset, count, 0);

    document()->textRemoved(this, offset, realCount);
}

void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
{
    if (offset > length()) {
        es.throwDOMException(IndexSizeError);
        return;
    }

    unsigned realCount;
    if (offset + count > length())
        realCount = length() - offset;
    else
        realCount = count;

    String newStr = m_data;
    newStr.remove(offset, realCount);
    newStr.insert(data, offset);

    setDataAndUpdate(newStr, offset, count, data.length());

    // update the markers for spell checking and grammar checking
    document()->textRemoved(this, offset, realCount);
    document()->textInserted(this, offset, data.length());
}

String CharacterData::nodeValue() const
{
    return m_data;
}

bool CharacterData::containsOnlyWhitespace() const
{
    return m_data.containsOnlyWhitespace();
}

void CharacterData::setNodeValue(const String& nodeValue)
{
    setData(nodeValue);
}

void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength)
{
    String oldData = m_data;
    m_data = newData;

    ASSERT(!renderer() || isTextNode());
    if (isTextNode())
        toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength);

    if (document()->frame())
        document()->frame()->selection()->textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);

    document()->incDOMTreeVersion();
    didModifyData(oldData);
}

void CharacterData::didModifyData(const String& oldData)
{
    if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(this))
        mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(this, oldData));

    if (parentNode())
        parentNode()->childrenChanged();

    if (!isInShadowTree()) {
        if (document()->hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
            dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, true, 0, oldData, m_data));
        dispatchSubtreeModifiedEvent();
    }
    InspectorInstrumentation::characterDataModified(document(), this);
}

int CharacterData::maxCharacterOffset() const
{
    return static_cast<int>(length());
}

bool CharacterData::offsetInCharacters() const
{
    return true;
}

} // namespace WebCore
<|endoftext|>


<commit_before>// Copyright (c) 2014, Ruslan Baratov
// All rights reserved.

#include <sober/sober.hpp>

class Delegate : public sober::network::api::OpenWeatherMap {
 public:
  using Base = sober::network::api::OpenWeatherMap;
  using StatusCode = sober::network::http::response::attribute::StatusCode;
  using ErrorCode = boost::system::error_code;

  Delegate(sober::network::http::Stream& stream):
      Base(stream),
      max_count_(10) {
  }

  virtual void on_start() override;

  virtual boost::posix_time::time_duration watchdog_period() override {
    return boost::posix_time::milliseconds(1000);
  }

  virtual bool force_stop() override {
    ++counter_;
    std::cout << "Count " << counter_ << "/" << max_count_ << std::endl;
    bool stop = (counter_ >= max_count_);
    if (stop) {
      std::cerr << "Timeout reached" << std::endl;
    }
    return stop;
  }

  virtual void on_success() override {
    try {
      Base::on_success();
    }
    catch (const std::exception& exc) {
      std::cerr << "Parse failed: " << exc.what() << std::endl;
      return;
    }
    const Attribute& attr = attribute();
    std::cout << "Success..." << std::endl;
    std::cout << "  longitude: " << attr.longitude << std::endl;
    std::cout << "  latitude: " << attr.latitude << std::endl;
    std::cout << "  temperature: " << attr.temperature << std::endl;
    std::cout << "  temperature(human): " << attr.temperature_human
        << std::endl;
    std::cout << "  description: " << attr.description << std::endl;
    std::cout << "  icon: " << attr.icon << std::endl;
  }

  virtual bool restart_on_error(const ErrorCode& error) override {
    std::cerr << "Error: " << error.message() << std::endl;
    return false;
  }

  virtual bool restart_on_error(const StatusCode& status_code) override {
    std::cerr << "Error(bad status code): " << status_code << std::endl;
    return false;
  }

 private:
  const int max_count_;
  int counter_;
};

void Delegate::on_start() {
  counter_ = 0;
}

int main() {
  try {
    const bool debug = sober::utils::always();

    if (debug) {
      sober::log::Logger::init_logs_for_testing(true, true);
    }
    else {
      sober::log::Logger::init_logs_for_testing(false, false);
    }

    namespace net = sober::network;

    net::Engine engine;
    net::http::Stream stream(engine);

    Delegate delegate(stream);

    const char* city = "Madrid";
    std::cout << "City: " << city << std::endl;

    delegate.async_get_city(city);

    engine.run();
    return sober::Exit::OK;
  }
  catch (std::exception& exc) {
    std::cerr << "Exception: " << exc.what() << std::endl;
    return sober::Exit::FAIL;
  }
}
<commit_msg>Suppress logging on example<commit_after>// Copyright (c) 2014, Ruslan Baratov
// All rights reserved.

#include <sober/sober.hpp>

class Delegate : public sober::network::api::OpenWeatherMap {
 public:
  using Base = sober::network::api::OpenWeatherMap;
  using StatusCode = sober::network::http::response::attribute::StatusCode;
  using ErrorCode = boost::system::error_code;

  Delegate(sober::network::http::Stream& stream):
      Base(stream),
      max_count_(10) {
  }

  virtual void on_start() override;

  virtual boost::posix_time::time_duration watchdog_period() override {
    return boost::posix_time::milliseconds(1000);
  }

  virtual bool force_stop() override {
    ++counter_;
    std::cout << "Count " << counter_ << "/" << max_count_ << std::endl;
    bool stop = (counter_ >= max_count_);
    if (stop) {
      std::cerr << "Timeout reached" << std::endl;
    }
    return stop;
  }

  virtual void on_success() override {
    try {
      Base::on_success();
    }
    catch (const std::exception& exc) {
      std::cerr << "Parse failed: " << exc.what() << std::endl;
      return;
    }
    const Attribute& attr = attribute();
    std::cout << "Success..." << std::endl;
    std::cout << "  longitude: " << attr.longitude << std::endl;
    std::cout << "  latitude: " << attr.latitude << std::endl;
    std::cout << "  temperature: " << attr.temperature << std::endl;
    std::cout << "  temperature(human): " << attr.temperature_human
        << std::endl;
    std::cout << "  description: " << attr.description << std::endl;
    std::cout << "  icon: " << attr.icon << std::endl;
  }

  virtual bool restart_on_error(const ErrorCode& error) override {
    std::cerr << "Error: " << error.message() << std::endl;
    return false;
  }

  virtual bool restart_on_error(const StatusCode& status_code) override {
    std::cerr << "Error(bad status code): " << status_code << std::endl;
    return false;
  }

 private:
  const int max_count_;
  int counter_;
};

void Delegate::on_start() {
  counter_ = 0;
}

int main() {
  try {
    const bool debug = !sober::utils::always();

    if (debug) {
      sober::log::Logger::init_logs_for_testing(true, true);
    }
    else {
      sober::log::Logger::init_logs_for_testing(false, false);
    }

    namespace net = sober::network;

    net::Engine engine;
    net::http::Stream stream(engine);

    Delegate delegate(stream);

    const char* city = "Madrid";
    std::cout << "City: " << city << std::endl;

    delegate.async_get_city(city);

    engine.run();
    return sober::Exit::OK;
  }
  catch (std::exception& exc) {
    std::cerr << "Exception: " << exc.what() << std::endl;
    return sober::Exit::FAIL;
  }
}
<|endoftext|>


<commit_before>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

HadesMem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

HadesMem 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with HadesMem.  If not, see <http://www.gnu.org/licenses/>.
*/

// Windows API
#include <tchar.h>
#include <crtdbg.h>
#include <Windows.h>

// C++ Standard Library
#include <limits>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <exception>

// Boost
#pragma warning(push, 1)
#include <boost/timer.hpp>
#include <boost/python.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#pragma warning(pop)

// Hades
#include "HadesMemory/Memory.hpp"

bool GetInput(boost::python::object const& PythonNamespace)
{
  // Prompt for input
  std::cout << ">";

  // Get command from user
  std::string Input;
  while (!std::getline(std::cin, Input) || Input.empty())
  {
    std::cout << "Invalid command." << std::endl;
    std::cout << ">";

    // Reset input stream if necessary
    if (!std::cin)
    {
      std::cin.clear();
      std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
    }
  }

  // Check for quit request
  if (Input == "quit" || Input == "exit")
  {
    return false;
  }

  try
  {
    // Run script
    boost::python::exec(Input.c_str(), PythonNamespace, PythonNamespace);
  }
  catch (...)
  {
    // Handle exceptions
    boost::python::handle_exception();

    // Print error string
    PyErr_Print();
  }

  return true;
}

// Program entry-point.
int wmain(int argc, wchar_t *argv[ ], wchar_t* /*envp*/[])
{
  // Program timer
  boost::timer ProgTimer;

  try
  {
    // Attempt to detect memory leaks in debug mode
#ifdef _DEBUG
    int CurrentFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
    int NewFlags = (_CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF |
      _CRTDBG_CHECK_ALWAYS_DF);
    _CrtSetDbgFlag(CurrentFlags | NewFlags);
#endif

    // Get default heap
    HANDLE ProcHeap = GetProcessHeap();
    if (!ProcHeap)
    {
      std::error_code const LastError = Hades::GetLastErrorCode();
      BOOST_THROW_EXCEPTION(Hades::HadesError() <<
        Hades::ErrorFunction("wmain") <<
        Hades::ErrorString("Could not get process heap.") <<
        Hades::ErrorCode(LastError));
    }

    // Detect heap corruption
    if (!HeapSetInformation(ProcHeap, HeapEnableTerminationOnCorruption,
      NULL, 0))
    {
      std::error_code const LastError = Hades::GetLastErrorCode();
      BOOST_THROW_EXCEPTION(Hades::HadesError() <<
        Hades::ErrorFunction("wmain") <<
        Hades::ErrorString("Could not set heap information.") <<
        Hades::ErrorCode(LastError));
    }

    // Hades version number
    std::wstring const VerNum(L"TRUNK");

    // Version and copyright output
#if defined(_M_X64)
    std::wcout << "MemSandbox AMD64 [Version " << VerNum << "]\n";
#elif defined(_M_IX86)
    std::wcout << "MemSandbox IA32 [Version " << VerNum << "]\n";
#else
#error "[HadesMem] Unsupported architecture."
#endif
    std::wcout << "Copyright (C) 2010 RaptorFactor. All rights reserved." <<
      std::endl;
    std::wcout << "Website: http://www.raptorfactor.com/, "
      "Email: raptorfactor@raptorfactor.com." << std::endl;
    std::wcout << "Built on " << __DATE__ << " at " << __TIME__ << "." <<
      std::endl << std::endl;

    // Auto-close flag (Set by Boost.ProgramOptions)
    bool KeepOpen = false;
    // Path to script file (Set by Boost.ProgramOptions)
    std::wstring FilePath;
    // Script string (Set by Boost.ProgramOptions)
    std::string ScriptStr;

    // Set program option descriptions
    boost::program_options::options_description OptsDesc("Allowed options");
    OptsDesc.add_options()
      ("help", "display help")
      ("keep-open", boost::program_options::wvalue<bool>(&KeepOpen)->
        zero_tokens(), "keep console window open")
      ("file", boost::program_options::wvalue<std::wstring>(&FilePath),
        "file to execute")
      ("string", boost::program_options::value<std::string>(&ScriptStr),
        "string to execute")
      ;

    // Parse program options
    boost::program_options::variables_map Opts;
    boost::program_options::store(boost::program_options::parse_command_line(
      argc, argv, OptsDesc), Opts);
    boost::program_options::notify(Opts);

    // Print help if requested
    if (Opts.count("help"))
    {
      // Print help
      std::cout << OptsDesc << std::endl;

      // Stop window from automatically closing if required
      if (KeepOpen)
      {
        std::wcin.clear();
        std::wcin.sync();
        std::wcin.get();
      }

      // Quit
      return 1;
    }

    // Initialize Python
    Py_Initialize();

    // Debug output
    std::wcout << "Python " << Py_GetVersion() << "\n" << std::endl;

    // Retrieve the main module.
    boost::python::object PythonMain(boost::python::import("__main__"));

    // Retrieve the main module's namespace
    boost::python::object PythonGlobal(PythonMain.attr("__dict__"));

    try
    {
      // Import PyHadesMem
      boost::python::exec("import PyHadesMem", PythonGlobal, PythonGlobal);
    }
    catch (...)
    {
      // Print error string
      PyErr_Print();

      // Throw exception
      BOOST_THROW_EXCEPTION(Hades::HadesError() <<
        Hades::ErrorFunction("_tmain") <<
        Hades::ErrorString("Failed to load PyHadesMem."));
    }

    // If user has passed in a file-name then run it
    if (!FilePath.empty())
    {
      // Get file
      boost::filesystem::path const FilePathReal(FilePath);
      if (!boost::filesystem::exists(FilePathReal))
      {
        BOOST_THROW_EXCEPTION(Hades::HadesError() <<
          Hades::ErrorFunction("_tmain") <<
          Hades::ErrorString("Requested file could not be found."));
      }

      try
      {
        // Run file
        boost::python::exec_file(FilePathReal.string().c_str(), PythonGlobal,
          PythonGlobal);
      }
      catch (...)
      {
        // Handle exceptions
        boost::python::handle_exception();

        // Print error string
        PyErr_Print();
      }

    }
    // If user has passed in a string then run it
    else if (!ScriptStr.empty())
    {
      try
      {
        // Run script
        boost::python::exec(ScriptStr.c_str(), PythonGlobal, PythonGlobal);
      }
      catch (...)
      {
        // Handle exceptions
        boost::python::handle_exception();

        // Print error string
        PyErr_Print();
      }
    }
    // Otherwise process commands from user
    else
    {
      for (;;)
      {
        try
        {
          if (!GetInput(PythonGlobal))
          {
            break;
          }
        }
        catch (std::exception const& e)
        {
          // Dump error information
          std::cout << boost::diagnostic_information(e);
        }
      }
    }

    // Print elapsed time
    std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
      std::endl;

    // Stop window from automatically closing if required
    if (KeepOpen)
    {
      std::wcin.clear();
      std::wcin.sync();
      std::wcin.get();
    }
  }
  catch (std::exception const& e)
  {
    // Dump error information
    std::cout << boost::diagnostic_information(e);

    // Print elapsed time
    std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
      std::endl;

    // Always keep window open in case of an error
    std::wcin.clear();
    std::wcin.sync();
    std::wcin.get();
  }
}
<commit_msg>* Output fix.<commit_after>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

HadesMem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

HadesMem 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with HadesMem.  If not, see <http://www.gnu.org/licenses/>.
*/

// Windows API
#include <tchar.h>
#include <crtdbg.h>
#include <Windows.h>

// C++ Standard Library
#include <limits>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <exception>

// Boost
#pragma warning(push, 1)
#include <boost/timer.hpp>
#include <boost/python.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#pragma warning(pop)

// Hades
#include "HadesMemory/Memory.hpp"

bool GetInput(boost::python::object const& PythonNamespace)
{
  // Prompt for input
  std::cout << ">";

  // Get command from user
  std::string Input;
  while (!std::getline(std::cin, Input) || Input.empty())
  {
    std::cout << "Invalid command." << std::endl;
    std::cout << ">";

    // Reset input stream if necessary
    if (!std::cin)
    {
      std::cin.clear();
      std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
    }
  }

  // Check for quit request
  if (Input == "quit" || Input == "exit")
  {
    return false;
  }

  try
  {
    // Run script
    boost::python::exec(Input.c_str(), PythonNamespace, PythonNamespace);
  }
  catch (...)
  {
    // Handle exceptions
    boost::python::handle_exception();

    // Print error string
    PyErr_Print();
  }

  return true;
}

// Program entry-point.
int wmain(int argc, wchar_t *argv[ ], wchar_t* /*envp*/[])
{
  // Program timer
  boost::timer ProgTimer;

  try
  {
    // Attempt to detect memory leaks in debug mode
#ifdef _DEBUG
    int CurrentFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
    int NewFlags = (_CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF |
      _CRTDBG_CHECK_ALWAYS_DF);
    _CrtSetDbgFlag(CurrentFlags | NewFlags);
#endif

    // Get default heap
    HANDLE ProcHeap = GetProcessHeap();
    if (!ProcHeap)
    {
      std::error_code const LastError = Hades::GetLastErrorCode();
      BOOST_THROW_EXCEPTION(Hades::HadesError() <<
        Hades::ErrorFunction("wmain") <<
        Hades::ErrorString("Could not get process heap.") <<
        Hades::ErrorCode(LastError));
    }

    // Detect heap corruption
    if (!HeapSetInformation(ProcHeap, HeapEnableTerminationOnCorruption,
      NULL, 0))
    {
      std::error_code const LastError = Hades::GetLastErrorCode();
      BOOST_THROW_EXCEPTION(Hades::HadesError() <<
        Hades::ErrorFunction("wmain") <<
        Hades::ErrorString("Could not set heap information.") <<
        Hades::ErrorCode(LastError));
    }

    // Hades version number
    std::wstring const VerNum(L"TRUNK");

    // Version and copyright output
#if defined(_M_X64)
    std::wcout << "Hades MemSandbox AMD64 [Version " << VerNum << "]\n";
#elif defined(_M_IX86)
    std::wcout << "Hades MemSandbox IA32 [Version " << VerNum << "]\n";
#else
#error "[HadesMem] Unsupported architecture."
#endif
    std::wcout << "Copyright (C) 2010 RaptorFactor. All rights reserved." <<
      std::endl;
    std::wcout << "Website: http://www.raptorfactor.com/, "
      "Email: raptorfactor@raptorfactor.com." << std::endl;
    std::wcout << "Built on " << __DATE__ << " at " << __TIME__ << "." <<
      std::endl << std::endl;

    // Auto-close flag (Set by Boost.ProgramOptions)
    bool KeepOpen = false;
    // Path to script file (Set by Boost.ProgramOptions)
    std::wstring FilePath;
    // Script string (Set by Boost.ProgramOptions)
    std::string ScriptStr;

    // Set program option descriptions
    boost::program_options::options_description OptsDesc("Allowed options");
    OptsDesc.add_options()
      ("help", "display help")
      ("keep-open", boost::program_options::wvalue<bool>(&KeepOpen)->
        zero_tokens(), "keep console window open")
      ("file", boost::program_options::wvalue<std::wstring>(&FilePath),
        "file to execute")
      ("string", boost::program_options::value<std::string>(&ScriptStr),
        "string to execute")
      ;

    // Parse program options
    boost::program_options::variables_map Opts;
    boost::program_options::store(boost::program_options::parse_command_line(
      argc, argv, OptsDesc), Opts);
    boost::program_options::notify(Opts);

    // Print help if requested
    if (Opts.count("help"))
    {
      // Print help
      std::cout << OptsDesc << std::endl;

      // Stop window from automatically closing if required
      if (KeepOpen)
      {
        std::wcin.clear();
        std::wcin.sync();
        std::wcin.get();
      }

      // Quit
      return 1;
    }

    // Initialize Python
    Py_Initialize();

    // Debug output
    std::wcout << "Python " << Py_GetVersion() << "\n" << std::endl;

    // Retrieve the main module.
    boost::python::object PythonMain(boost::python::import("__main__"));

    // Retrieve the main module's namespace
    boost::python::object PythonGlobal(PythonMain.attr("__dict__"));

    try
    {
      // Import PyHadesMem
      boost::python::exec("import PyHadesMem", PythonGlobal, PythonGlobal);
    }
    catch (...)
    {
      // Print error string
      PyErr_Print();

      // Throw exception
      BOOST_THROW_EXCEPTION(Hades::HadesError() <<
        Hades::ErrorFunction("_tmain") <<
        Hades::ErrorString("Failed to load PyHadesMem."));
    }

    // If user has passed in a file-name then run it
    if (!FilePath.empty())
    {
      // Get file
      boost::filesystem::path const FilePathReal(FilePath);
      if (!boost::filesystem::exists(FilePathReal))
      {
        BOOST_THROW_EXCEPTION(Hades::HadesError() <<
          Hades::ErrorFunction("_tmain") <<
          Hades::ErrorString("Requested file could not be found."));
      }

      try
      {
        // Run file
        boost::python::exec_file(FilePathReal.string().c_str(), PythonGlobal,
          PythonGlobal);
      }
      catch (...)
      {
        // Handle exceptions
        boost::python::handle_exception();

        // Print error string
        PyErr_Print();
      }

    }
    // If user has passed in a string then run it
    else if (!ScriptStr.empty())
    {
      try
      {
        // Run script
        boost::python::exec(ScriptStr.c_str(), PythonGlobal, PythonGlobal);
      }
      catch (...)
      {
        // Handle exceptions
        boost::python::handle_exception();

        // Print error string
        PyErr_Print();
      }
    }
    // Otherwise process commands from user
    else
    {
      for (;;)
      {
        try
        {
          if (!GetInput(PythonGlobal))
          {
            break;
          }
        }
        catch (std::exception const& e)
        {
          // Dump error information
          std::cout << boost::diagnostic_information(e);
        }
      }
    }

    // Print elapsed time
    std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
      std::endl;

    // Stop window from automatically closing if required
    if (KeepOpen)
    {
      std::wcin.clear();
      std::wcin.sync();
      std::wcin.get();
    }
  }
  catch (std::exception const& e)
  {
    // Dump error information
    std::cout << boost::diagnostic_information(e);

    // Print elapsed time
    std::wcout << "\nElapsed Time: " << ProgTimer.elapsed() << "." <<
      std::endl;

    // Always keep window open in case of an error
    std::wcin.clear();
    std::wcin.sync();
    std::wcin.get();
  }
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "stan/prob/distributions/multivariate/continuous/multi_normal_cholesky.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <stan/agrad/rev.hpp>

using Eigen::Dynamic;
using Eigen::Matrix;
using std::vector;

TEST(ProbDistributionsMultiNormalCholesky,NotVectorized) {
  Matrix<double,Dynamic,1> y(3,1);
  y << 2.0, -2.0, 11.0;
  Matrix<double,Dynamic,1> mu(3,1);
  mu << 1.0, -1.0, 3.0;
  Matrix<double,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 0.0,
    0.0, 0.0, 5.0;
  Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
  EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}
TEST(ProbDistributionsMultiNormal,Vectorized) {
  vector< Matrix<double,Dynamic,1> > vec_y(2);
  vector< Matrix<double,1,Dynamic> > vec_y_t(2);
  Matrix<double,Dynamic,1> y(3);
  Matrix<double,1,Dynamic> y_t(3);
  y << 2.0, -2.0, 11.0;
  vec_y[0] = y;
  vec_y_t[0] = y;
  y << 4.0, -2.0, 1.0;
  vec_y[1] = y;
  vec_y_t[1] = y;
  y_t = y;

  vector< Matrix<double,Dynamic,1> > vec_mu(2);
  vector< Matrix<double,1,Dynamic> > vec_mu_t(2);
  Matrix<double,Dynamic,1> mu(3);
  Matrix<double,1,Dynamic> mu_t(3);
  mu << 1.0, -1.0, 3.0;
  vec_mu[0] = mu;
  vec_mu_t[0] = mu;
  mu << 2.0, -1.0, 4.0;
  vec_mu[1] = mu;
  vec_mu_t[1] = mu;
  mu_t = mu;

  Matrix<double,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 10.0, -3.0, 0.0,
    -3.0,  5.0, 0.0,
    0.0, 0.0, 5.0;
  Sigma = Sigma.llt().matrixL();

  //y and mu vectorized
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu,Sigma));
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu,Sigma));
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu_t,Sigma));
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu_t,Sigma));

  //y vectorized
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu,Sigma));
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu,Sigma));
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu_t,Sigma));
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu_t,Sigma));

  //mu vectorized
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu,Sigma));
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu,Sigma));
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu_t,Sigma));
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu_t,Sigma));
}
TEST(ProbDistributionsMultiNormalCholesky,MultiNormalVar) {
  using stan::agrad::var;
  Matrix<var,Dynamic,1> y(3,1);
  y << 2.0, -2.0, 11.0;
  Matrix<var,Dynamic,1> mu(3,1);
  mu << 1.0, -1.0, 3.0;
  Matrix<var,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 0.0,
    0.0, 0.0, 5.0;
  Matrix<var,Dynamic,Dynamic> L = Sigma.llt().matrixL();
  EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L).val());
}

TEST(ProbDistributionsMultiNormalCholesky,MultiNormalOneRow) {
  Matrix<double,Dynamic,Dynamic> y(1,3);
  y << 2.0, -2.0, 11.0;
  Matrix<double,Dynamic,1> mu(3,1);
  mu << 1.0, -1.0, 3.0;
  Matrix<double,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 0.0,
    0.0, 0.0, 5.0;
  Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
  EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}

TEST(ProbDistributionsMultiNormalCholesky, error_check) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;

  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 3.0;
  sigma = sigma.llt().matrixL();
  EXPECT_NO_THROW(stan::prob::multi_normal_cholesky_rng(mu, sigma,rng));

  mu << stan::math::positive_infinity(),
    -2.0,
    11.0;
  EXPECT_THROW(stan::prob::multi_normal_cholesky_rng(mu,sigma,rng),std::domain_error);
}

TEST(ProbDistributionsMultiNormalCholesky, marginalOneChiSquareGoodnessFitTest) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 3.0;
  sigma = sigma.llt().matrixL();
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;
  int N = 10000;
  int K = boost::math::round(2 * std::pow(N, 0.4));
  boost::math::normal_distribution<>dist (2.0,3.0);
  boost::math::chi_squared mydist(K-1);

  double loc[K - 1];
  for(int i = 1; i < K; i++)
    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));

  int count = 0;
  int bin [K];
  double expect [K];
  for(int i = 0 ; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }
  Eigen::VectorXd a(mu.rows());
  while (count < N) {
    a = stan::prob::multi_normal_cholesky_rng(mu,sigma,rng);
    int i = 0;
    while (i < K-1 && a(0) > loc[i])
      ++i;
    ++bin[i];
    count++;
   }

  double chi = 0;
  for(int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);

  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsMultiNormalCholesky, marginalTwoChiSquareGoodnessFitTest) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 3.0;
  sigma = sigma.llt().matrixL();
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;
  int N = 10000;
  int K = boost::math::round(2 * std::pow(N, 0.4));
  boost::math::normal_distribution<>dist (-2.0,2.0);
  boost::math::chi_squared mydist(K-1);

  double loc[K - 1];
  for(int i = 1; i < K; i++)
    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));

  int count = 0;
  int bin [K];
  double expect [K];
  for(int i = 0 ; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }
  Eigen::VectorXd a(mu.rows());
  while (count < N) {
    a = stan::prob::multi_normal_cholesky_rng(mu,sigma,rng);
    int i = 0;
    while (i < K-1 && a(1) > loc[i])
      ++i;
    ++bin[i];
    count++;
   }

  double chi = 0;
  for(int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);

  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsMultiNormalCholesky, marginalThreeChiSquareGoodnessFitTest) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 16.0;
  sigma = sigma.llt().matrixL();
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;
  int N = 10000;
  int K = boost::math::round(2 * std::pow(N, 0.4));
  boost::math::normal_distribution<>dist (11.0,4.0);
  boost::math::chi_squared mydist(K-1);

  double loc[K - 1];
  for(int i = 1; i < K; i++)
    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));

  int count = 0;
  int bin [K];
  double expect [K];
  for(int i = 0 ; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }
  Eigen::VectorXd a(mu.rows());
  while (count < N) {
    a = stan::prob::multi_normal_cholesky_rng(mu,sigma,rng);
    int i = 0;
    while (i < K-1 && a(2) > loc[i])
      ++i;
    ++bin[i];
    count++;
   }

  double chi = 0;
  for(int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);

  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<commit_msg>use dedicated variable for Cholesky factor in tests<commit_after>#include <gtest/gtest.h>
#include "stan/prob/distributions/multivariate/continuous/multi_normal_cholesky.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <stan/agrad/rev.hpp>

using Eigen::Dynamic;
using Eigen::Matrix;
using std::vector;

TEST(ProbDistributionsMultiNormalCholesky,NotVectorized) {
  Matrix<double,Dynamic,1> y(3,1);
  y << 2.0, -2.0, 11.0;
  Matrix<double,Dynamic,1> mu(3,1);
  mu << 1.0, -1.0, 3.0;
  Matrix<double,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 0.0,
    0.0, 0.0, 5.0;
  Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
  EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}
TEST(ProbDistributionsMultiNormal,Vectorized) {
  vector< Matrix<double,Dynamic,1> > vec_y(2);
  vector< Matrix<double,1,Dynamic> > vec_y_t(2);
  Matrix<double,Dynamic,1> y(3);
  Matrix<double,1,Dynamic> y_t(3);
  y << 2.0, -2.0, 11.0;
  vec_y[0] = y;
  vec_y_t[0] = y;
  y << 4.0, -2.0, 1.0;
  vec_y[1] = y;
  vec_y_t[1] = y;
  y_t = y;

  vector< Matrix<double,Dynamic,1> > vec_mu(2);
  vector< Matrix<double,1,Dynamic> > vec_mu_t(2);
  Matrix<double,Dynamic,1> mu(3);
  Matrix<double,1,Dynamic> mu_t(3);
  mu << 1.0, -1.0, 3.0;
  vec_mu[0] = mu;
  vec_mu_t[0] = mu;
  mu << 2.0, -1.0, 4.0;
  vec_mu[1] = mu;
  vec_mu_t[1] = mu;
  mu_t = mu;

  Matrix<double,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 10.0, -3.0, 0.0,
    -3.0,  5.0, 0.0,
    0.0, 0.0, 5.0;
  Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();

  //y and mu vectorized
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu,L));
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu,L));
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y,vec_mu_t,L));
  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::prob::multi_normal_cholesky_log(vec_y_t,vec_mu_t,L));

  //y vectorized
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu,L));
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu,L));
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y,mu_t,L));
  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::prob::multi_normal_cholesky_log(vec_y_t,mu_t,L));

  //mu vectorized
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu,L));
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu,L));
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y,vec_mu_t,L));
  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::prob::multi_normal_cholesky_log(y_t,vec_mu_t,L));
}
TEST(ProbDistributionsMultiNormalCholesky,MultiNormalVar) {
  using stan::agrad::var;
  Matrix<var,Dynamic,1> y(3,1);
  y << 2.0, -2.0, 11.0;
  Matrix<var,Dynamic,1> mu(3,1);
  mu << 1.0, -1.0, 3.0;
  Matrix<var,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 0.0,
    0.0, 0.0, 5.0;
  Matrix<var,Dynamic,Dynamic> L = Sigma.llt().matrixL();
  EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L).val());
}

TEST(ProbDistributionsMultiNormalCholesky,MultiNormalOneRow) {
  Matrix<double,Dynamic,Dynamic> y(1,3);
  y << 2.0, -2.0, 11.0;
  Matrix<double,Dynamic,1> mu(3,1);
  mu << 1.0, -1.0, 3.0;
  Matrix<double,Dynamic,Dynamic> Sigma(3,3);
  Sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 0.0,
    0.0, 0.0, 5.0;
  Matrix<double,Dynamic,Dynamic> L = Sigma.llt().matrixL();
  EXPECT_FLOAT_EQ(-11.73908, stan::prob::multi_normal_cholesky_log(y,mu,L));
}

TEST(ProbDistributionsMultiNormalCholesky, error_check) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;

  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 3.0;
  Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
  EXPECT_NO_THROW(stan::prob::multi_normal_cholesky_rng(mu, L, rng));

  mu << stan::math::positive_infinity(),
    -2.0,
    11.0;
  EXPECT_THROW(stan::prob::multi_normal_cholesky_rng(mu,sigma,rng),std::domain_error);
}

TEST(ProbDistributionsMultiNormalCholesky, marginalOneChiSquareGoodnessFitTest) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 3.0;
  Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;
  int N = 10000;
  int K = boost::math::round(2 * std::pow(N, 0.4));
  boost::math::normal_distribution<>dist (2.0,3.0);
  boost::math::chi_squared mydist(K-1);

  double loc[K - 1];
  for(int i = 1; i < K; i++)
    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));

  int count = 0;
  int bin [K];
  double expect [K];
  for(int i = 0 ; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }
  Eigen::VectorXd a(mu.rows());
  while (count < N) {
    a = stan::prob::multi_normal_cholesky_rng(mu,L,rng);
    int i = 0;
    while (i < K-1 && a(0) > loc[i])
      ++i;
    ++bin[i];
    count++;
   }

  double chi = 0;
  for(int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);

  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsMultiNormalCholesky, marginalTwoChiSquareGoodnessFitTest) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 3.0;
  Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;
  int N = 10000;
  int K = boost::math::round(2 * std::pow(N, 0.4));
  boost::math::normal_distribution<>dist (-2.0,2.0);
  boost::math::chi_squared mydist(K-1);

  double loc[K - 1];
  for(int i = 1; i < K; i++)
    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));

  int count = 0;
  int bin [K];
  double expect [K];
  for(int i = 0 ; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }
  Eigen::VectorXd a(mu.rows());
  while (count < N) {
    a = stan::prob::multi_normal_cholesky_rng(mu,L,rng);
    int i = 0;
    while (i < K-1 && a(1) > loc[i])
      ++i;
    ++bin[i];
    count++;
   }

  double chi = 0;
  for(int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);

  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsMultiNormalCholesky, marginalThreeChiSquareGoodnessFitTest) {
  boost::random::mt19937 rng;
  Matrix<double,Dynamic,Dynamic> sigma(3,3);
  sigma << 9.0, -3.0, 0.0,
    -3.0,  4.0, 1.0,
    0.0, 1.0, 16.0;
  Matrix<double,Dynamic,Dynamic> L = sigma.llt().matrixL();
  Matrix<double,Dynamic,Dynamic> mu(3,1);
  mu << 2.0,
    -2.0,
    11.0;
  int N = 10000;
  int K = boost::math::round(2 * std::pow(N, 0.4));
  boost::math::normal_distribution<>dist (11.0,4.0);
  boost::math::chi_squared mydist(K-1);

  double loc[K - 1];
  for(int i = 1; i < K; i++)
    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));

  int count = 0;
  int bin [K];
  double expect [K];
  for(int i = 0 ; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }
  Eigen::VectorXd a(mu.rows());
  while (count < N) {
    a = stan::prob::multi_normal_cholesky_rng(mu,L,rng);
    int i = 0;
    while (i < K-1 && a(2) > loc[i])
      ++i;
    ++bin[i];
    count++;
   }

  double chi = 0;
  for(int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);

  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"

using namespace std;

namespace bohrium {

/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
 * theoretically execute the two instructions in a single operation,
 * thus accepts broadcast, reduction, extension methods, etc. */
    BROADEST,

/* A very simple mode that only fuses same shaped arrays thus no
 * broadcast, reduction, extension methods, etc. */
    SAME_SHAPE,

/* The sentinel */
    NONE
};

/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;

/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;

/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/

static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    const int a_nop = bh_operands(a->opcode);
    for(int i=0; i<a_nop; ++i)
    {
        if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
           && not bh_view_aligned(&b->operand[0], &a->operand[i]))
            return false;
    }
    const int b_nop = bh_operands(b->opcode);
    for(int i=0; i<b_nop; ++i)
    {
        if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
           && not bh_view_aligned(&a->operand[0], &b->operand[i]))
            return false;
    }
    return true;
}

static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
        return false;

    const int a_nop = bh_operands(a->opcode);
    for(int i=0; i<a_nop; ++i)
    {
        if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
           && not bh_view_aligned_and_same_shape(&b->operand[0], &a->operand[i]))
            return false;
    }
    const int b_nop = bh_operands(b->opcode);
    for(int i=0; i<b_nop; ++i)
    {
        if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
           && not bh_view_aligned_and_same_shape(&a->operand[0], &b->operand[i]))
            return false;
    }
    return true;
}

/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/

/* Get the selected fuse model by reading the environment
 * variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
    using namespace boost;

    //Check enviroment variable
    const char *env = getenv("BH_FUSE_MODEL");
    if(env != NULL)
    {
        string e(env);
        if(iequals(e, string("broadest")))
        {
            //cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
            return BROADEST;
        }
        else if(iequals(e, string("same_shape")))
        {
            //cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
            return SAME_SHAPE;
        }
        else
        {
            cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
            cerr << "', using the default model instead" << endl;
        }
    }
    //cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
    return default_fuse_model;
}

/* Determines whether it is legal to fuse two instructions into one
 * kernel using the 'selected_fuse_model'.
 *
 * @a The first instruction
 * @b The second instruction
 * @return The boolean answer
 */
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
    switch(selected_fuse_model)
    {
        case NONE:
            selected_fuse_model = get_selected_fuse_model();
            return check_fusible(a, b);
        case BROADEST:
            return fuse_broadest(a,b);
        case SAME_SHAPE:
            return fuse_same_shape(a,b);
        default:
            throw runtime_error("No fuse module is selected!");
    }
}

} //namespace bohrium
<commit_msg>fuse: now all instructions must have same shape in fuse_same_shape()<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"

using namespace std;

namespace bohrium {

/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
 * theoretically execute the two instructions in a single operation,
 * thus accepts broadcast, reduction, extension methods, etc. */
    BROADEST,

/* A very simple mode that only fuses same shaped arrays thus no
 * broadcast, reduction, extension methods, etc. */
    SAME_SHAPE,

/* The sentinel */
    NONE
};

/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;

/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;

/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/

static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    const int a_nop = bh_operands(a->opcode);
    for(int i=0; i<a_nop; ++i)
    {
        if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
           && not bh_view_aligned(&b->operand[0], &a->operand[i]))
            return false;
    }
    const int b_nop = bh_operands(b->opcode);
    for(int i=0; i<b_nop; ++i)
    {
        if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
           && not bh_view_aligned(&a->operand[0], &b->operand[i]))
            return false;
    }
    return true;
}

static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
        return false;

    const int a_nop = bh_operands(a->opcode);
    const int b_nop = bh_operands(b->opcode);
    const bh_intp *shape = a->operand[0].shape;
    const bh_intp ndim = a->operand[0].ndim;
    for(int i=1; i<a_nop; ++i)
    {
        if(bh_is_constant(&a->operand[i]))
            continue;
        if(ndim != a->operand[i].ndim)
            return false;
        for(bh_intp j=0; j<ndim; ++j)
        {
            if(a->operand[i].shape[j] != shape[j])
                return false;
        }
    }
    for(int i=0; i<b_nop; ++i)
    {
        if(bh_is_constant(&b->operand[i]))
            continue;
        if(ndim != b->operand[i].ndim)
            return false;
        for(bh_intp j=0; j<ndim; ++j)
        {
            if(b->operand[i].shape[j] != shape[j])
                return false;
        }
    }
    return fuse_broadest(a, b);
}

/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/

/* Get the selected fuse model by reading the environment
 * variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
    using namespace boost;

    //Check enviroment variable
    const char *env = getenv("BH_FUSE_MODEL");
    if(env != NULL)
    {
        string e(env);
        if(iequals(e, string("broadest")))
        {
            //cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
            return BROADEST;
        }
        else if(iequals(e, string("same_shape")))
        {
            //cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
            return SAME_SHAPE;
        }
        else
        {
            cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
            cerr << "', using the default model instead" << endl;
        }
    }
    //cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
    return default_fuse_model;
}

/* Determines whether it is legal to fuse two instructions into one
 * kernel using the 'selected_fuse_model'.
 *
 * @a The first instruction
 * @b The second instruction
 * @return The boolean answer
 */
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
    switch(selected_fuse_model)
    {
        case NONE:
            selected_fuse_model = get_selected_fuse_model();
            return check_fusible(a, b);
        case BROADEST:
            return fuse_broadest(a,b);
        case SAME_SHAPE:
            return fuse_same_shape(a,b);
        default:
            throw runtime_error("No fuse module is selected!");
    }
}

} //namespace bohrium
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: tp_SeriesToAxis.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "tp_SeriesToAxis.hxx"

#include "ResId.hxx"
#include "TabPages.hrc"
#include "chartview/ChartSfxItemIds.hxx"
#include "NoWarningThisInCTOR.hxx"

// header for class SfxBoolItem
#include <svtools/eitem.hxx>
// header for SfxInt32Item
#include <svtools/intitem.hxx>

//.............................................................................
namespace chart
{
//.............................................................................

SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) :
    SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs),
    aGrpAxis(this, SchResId(GRP_OPT_AXIS)),
    aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)),
    aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)),

    aGrpBar(this, SchResId(GB_BAR)),
    aFTGap(this,SchResId(FT_GAP)),
    aMTGap(this,SchResId(MT_GAP)),
    aFTOverlap(this,SchResId(FT_OVERLAP)),
    aMTOverlap(this,SchResId(MT_OVERLAP)),
    aCBConnect(this,SchResId(CB_CONNECTOR)),
    aCBAxisSideBySide(this,SchResId(CB_BARS_SIDE_BY_SIDE))
{
    FreeResource();

    aRbtAxis1.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
    aRbtAxis2.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

SchOptionTabPage::~SchOptionTabPage()
{
}

IMPL_LINK( SchOptionTabPage, EnableHdl, RadioButton *, EMPTYARG )
{
    if( m_nAllSeriesAxisIndex == 0 )
        aCBAxisSideBySide.Enable( aRbtAxis2.IsChecked());
    else if( m_nAllSeriesAxisIndex == 1 )
        aCBAxisSideBySide.Enable( aRbtAxis1.IsChecked());

    return 0;
}
/*************************************************************************
|*
|* Erzeugung
|*
\*************************************************************************/

SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs)
{
    return new SchOptionTabPage(pWindow, rOutAttrs);
}

/*************************************************************************
|*
|* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen
|*
\*************************************************************************/
BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs)
{
    if(aRbtAxis2.IsChecked())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y));
    else
        rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y));

    if(aMTGap.IsVisible())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,static_cast< sal_Int32 >( aMTGap.GetValue())));

    if(aMTOverlap.IsVisible())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,static_cast< sal_Int32 >( aMTOverlap.GetValue())));

    if(aCBConnect.IsVisible())
        rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked()));

    // model property is "group bars per axis", UI feature is the other way
    // round: "show bars side by side"
    if(aCBAxisSideBySide.IsVisible())
        rOutAttrs.Put(SfxBoolItem(SCHATTR_GROUP_BARS_PER_AXIS, ! aCBAxisSideBySide.IsChecked()));

    return TRUE;
}
/*************************************************************************
|*
|* Initialisierung
|*
\*************************************************************************/

void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs)
{
    const SfxPoolItem *pPoolItem = NULL;

    aRbtAxis1.Check(TRUE);
    aRbtAxis2.Check(FALSE);
    if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();
        if(nVal==CHART_AXIS_SECONDARY_Y)
        {
            aRbtAxis2.Check(TRUE);
            aRbtAxis1.Check(FALSE);
        }
    }

    long nTmp;
    if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
        aMTGap.SetValue(nTmp);
    }
    else
    {
        aMTGap.Show(FALSE);
        aFTGap.Show(FALSE);
    }

    if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
        aMTOverlap.SetValue(nTmp);
    }
    else
    {
        aMTOverlap.Show(FALSE);
        aFTOverlap.Show(FALSE);
    }
    if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
        aCBConnect.Check(bCheck);
    }
    else
    {
        aCBConnect.Show(FALSE);
    }
    if (rInAttrs.GetItemState(SCHATTR_AXIS_FOR_ALL_SERIES, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        m_nAllSeriesAxisIndex = static_cast< const SfxInt32Item * >( pPoolItem )->GetValue();
        aCBAxisSideBySide.Disable();
    }
    if (rInAttrs.GetItemState(SCHATTR_GROUP_BARS_PER_AXIS, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        // model property is "group bars per axis", UI feature is the other way
        // round: "show bars side by side"
        BOOL bCheck = ! static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
        aCBAxisSideBySide.Check( bCheck );
    }
    else
    {
        aCBAxisSideBySide.Show(FALSE);
    }

}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS chart22 (1.9.46); FILE MERGED 2008/04/17 11:29:35 iha 1.9.46.2: RESYNC: (1.9-1.10); FILE MERGED 2008/02/21 17:13:32 iha 1.9.46.1: #i65549# Plotting of missing values + cleanuo<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: tp_SeriesToAxis.cxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "tp_SeriesToAxis.hxx"

#include "ResId.hxx"
#include "TabPages.hrc"
#include "chartview/ChartSfxItemIds.hxx"
#include "NoWarningThisInCTOR.hxx"

// header for class SfxBoolItem
#include <svtools/eitem.hxx>
// header for SfxInt32Item
#include <svtools/intitem.hxx>
//SfxIntegerListItem
#include <svtools/ilstitem.hxx>
#include <com/sun/star/chart/MissingValueTreatment.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) :
    SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs),
    aGrpAxis(this, SchResId(GRP_OPT_AXIS)),
    aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)),
    aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)),

    aGrpBar(this, SchResId(GB_BAR)),
    aFTGap(this,SchResId(FT_GAP)),
    aMTGap(this,SchResId(MT_GAP)),
    aFTOverlap(this,SchResId(FT_OVERLAP)),
    aMTOverlap(this,SchResId(MT_OVERLAP)),
    aCBConnect(this,SchResId(CB_CONNECTOR)),
    aCBAxisSideBySide(this,SchResId(CB_BARS_SIDE_BY_SIDE)),
    m_aFL_EmptyCells(this,SchResId(FL_PLOT_MISSING_VALUES)),
    m_aRB_DontPaint(this,SchResId(RB_DONT_PAINT)),
    m_aRB_AssumeZero(this,SchResId(RB_ASSUME_ZERO)),
    m_aRB_ContinueLine(this,SchResId(RB_CONTINUE_LINE)),
    m_bProvidesSecondaryYAxis(true),
    m_bProvidesOverlapAndGapWidth(false)
{
    FreeResource();

    aRbtAxis1.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
    aRbtAxis2.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl ));
}

SchOptionTabPage::~SchOptionTabPage()
{
}

IMPL_LINK( SchOptionTabPage, EnableHdl, RadioButton *, EMPTYARG )
{
    if( m_nAllSeriesAxisIndex == 0 )
        aCBAxisSideBySide.Enable( aRbtAxis2.IsChecked());
    else if( m_nAllSeriesAxisIndex == 1 )
        aCBAxisSideBySide.Enable( aRbtAxis1.IsChecked());

    return 0;
}

SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs)
{
    return new SchOptionTabPage(pWindow, rOutAttrs);
}

BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs)
{
    if(aRbtAxis2.IsChecked())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y));
    else
        rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y));

    if(aMTGap.IsVisible())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,static_cast< sal_Int32 >( aMTGap.GetValue())));

    if(aMTOverlap.IsVisible())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,static_cast< sal_Int32 >( aMTOverlap.GetValue())));

    if(aCBConnect.IsVisible())
        rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked()));

    // model property is "group bars per axis", UI feature is the other way
    // round: "show bars side by side"
    if(aCBAxisSideBySide.IsVisible())
        rOutAttrs.Put(SfxBoolItem(SCHATTR_GROUP_BARS_PER_AXIS, ! aCBAxisSideBySide.IsChecked()));

    if(m_aRB_DontPaint.IsChecked())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_MISSING_VALUE_TREATMENT,::com::sun::star::chart::MissingValueTreatment::LEAVE_GAP));
    else if(m_aRB_AssumeZero.IsChecked())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_MISSING_VALUE_TREATMENT,::com::sun::star::chart::MissingValueTreatment::USE_ZERO));
    else if(m_aRB_ContinueLine.IsChecked())
        rOutAttrs.Put(SfxInt32Item(SCHATTR_MISSING_VALUE_TREATMENT,::com::sun::star::chart::MissingValueTreatment::CONTINUE));

    return TRUE;
}

void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs)
{
    const SfxPoolItem *pPoolItem = NULL;

    aRbtAxis1.Check(TRUE);
    aRbtAxis2.Check(FALSE);
    if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();
        if(nVal==CHART_AXIS_SECONDARY_Y)
        {
            aRbtAxis2.Check(TRUE);
            aRbtAxis1.Check(FALSE);
        }
    }

    long nTmp;
    if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
        aMTGap.SetValue(nTmp);
    }

    if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue();
        aMTOverlap.SetValue(nTmp);
    }

    if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
        aCBConnect.Check(bCheck);
    }

    if (rInAttrs.GetItemState(SCHATTR_AXIS_FOR_ALL_SERIES, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        m_nAllSeriesAxisIndex = static_cast< const SfxInt32Item * >( pPoolItem )->GetValue();
        aCBAxisSideBySide.Disable();
    }
    if (rInAttrs.GetItemState(SCHATTR_GROUP_BARS_PER_AXIS, TRUE, &pPoolItem) == SFX_ITEM_SET)
    {
        // model property is "group bars per axis", UI feature is the other way
        // round: "show bars side by side"
        BOOL bCheck = ! static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
        aCBAxisSideBySide.Check( bCheck );
    }
    else
    {
        aCBAxisSideBySide.Show(FALSE);
    }

    //missing value treatment
    {
        ::com::sun::star::uno::Sequence < sal_Int32 > aMissingValueTreatments;
        if( rInAttrs.GetItemState(SCHATTR_AVAILABLE_MISSING_VALUE_TREATMENTS, TRUE, &pPoolItem) == SFX_ITEM_SET )
            aMissingValueTreatments =((const SfxIntegerListItem*)pPoolItem)->GetConstSequence();

        if ( aMissingValueTreatments.getLength()>1 && rInAttrs.GetItemState(SCHATTR_MISSING_VALUE_TREATMENT,TRUE, &pPoolItem) == SFX_ITEM_SET)
        {
            m_aRB_DontPaint.Enable(FALSE);
            m_aRB_AssumeZero.Enable(FALSE);
            m_aRB_ContinueLine.Enable(FALSE);

            for( sal_Int32 nN =0; nN<aMissingValueTreatments.getLength(); nN++ )
            {
                sal_Int32 nVal = aMissingValueTreatments[nN];
                if(nVal==::com::sun::star::chart::MissingValueTreatment::LEAVE_GAP)
                    m_aRB_DontPaint.Enable(TRUE);
                else if(nVal==::com::sun::star::chart::MissingValueTreatment::USE_ZERO)
                    m_aRB_AssumeZero.Enable(TRUE);
                else if(nVal==::com::sun::star::chart::MissingValueTreatment::CONTINUE)
                    m_aRB_ContinueLine.Enable(TRUE);
            }

            long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();
            if(nVal==::com::sun::star::chart::MissingValueTreatment::LEAVE_GAP)
                m_aRB_DontPaint.Check(TRUE);
            else if(nVal==::com::sun::star::chart::MissingValueTreatment::USE_ZERO)
                m_aRB_AssumeZero.Check(TRUE);
            else if(nVal==::com::sun::star::chart::MissingValueTreatment::CONTINUE)
                m_aRB_ContinueLine.Check(TRUE);
        }
        else
        {
            m_aRB_DontPaint.Show(FALSE);
            m_aRB_AssumeZero.Show(FALSE);
            m_aRB_ContinueLine.Show(FALSE);
            m_aFL_EmptyCells.Show(FALSE);
        }
    }

    AdaptControlPositionsAndVisibility();
}

void SchOptionTabPage::Init( bool bProvidesSecondaryYAxis, bool bProvidesOverlapAndGapWidth, bool bProvidesBarConnectors )
{
    m_bProvidesSecondaryYAxis = bProvidesSecondaryYAxis;
    m_bProvidesOverlapAndGapWidth = bProvidesOverlapAndGapWidth;
    m_bProvidesBarConnectors = bProvidesBarConnectors;

    AdaptControlPositionsAndVisibility();
}

void SchOptionTabPage::AdaptControlPositionsAndVisibility()
{
    aRbtAxis1.Show(m_bProvidesSecondaryYAxis);
    aRbtAxis2.Show(m_bProvidesSecondaryYAxis);
    aGrpAxis.Show(m_bProvidesSecondaryYAxis);

    aMTGap.Show(m_bProvidesOverlapAndGapWidth);
    aFTGap.Show(m_bProvidesOverlapAndGapWidth);

    aMTOverlap.Show(m_bProvidesOverlapAndGapWidth);
    aFTOverlap.Show(m_bProvidesOverlapAndGapWidth);

    aCBConnect.Show(m_bProvidesBarConnectors);

    if( !aMTGap.IsVisible() && !aMTOverlap.IsVisible() )
    {
        aGrpBar.Show(FALSE);
        Point aPos;
        if( !aRbtAxis1.IsVisible() && !aRbtAxis2.IsVisible() )
            aPos = aGrpAxis.GetPosPixel();
        else
            aPos = aGrpBar.GetPosPixel();

        long nDiffX = aRbtAxis1.GetPosPixel().getX() - aGrpAxis.GetPosPixel().getX();
        long nDiffY = aRbtAxis1.GetPosPixel().getY() - aGrpAxis.GetPosPixel().getY();
        long nDiffY1 = aRbtAxis2.GetPosPixel().getY() - aRbtAxis1.GetPosPixel().getY();

        m_aFL_EmptyCells.SetPosPixel( aPos );
        m_aRB_DontPaint.SetPosPixel( Point( aPos.getX() + nDiffX, aPos.getY() + nDiffY ) );
        m_aRB_AssumeZero.SetPosPixel( Point( aPos.getX() + nDiffX, aPos.getY() + nDiffY + nDiffY1  ) );
        m_aRB_ContinueLine.SetPosPixel( Point( aPos.getX() + nDiffX, aPos.getY() + nDiffY + nDiffY1 * 2 ) );
    }

    if( !m_aRB_DontPaint.IsVisible() )
    {
        m_aRB_ContinueLine.SetPosPixel( m_aRB_AssumeZero.GetPosPixel() );
        m_aRB_AssumeZero.SetPosPixel( m_aRB_DontPaint.GetPosPixel() );
    }
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


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

#include "chrome/browser/chromeos/status/status_area_button.h"

#include "grit/theme_resources.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/skbitmap_operations.h"
#include "views/border.h"
#include "views/view.h"

namespace chromeos {

// A 0.7 black to decorate status text. Same color is used for icon borders.
static const SkColor kStatusTextHaloColor = SkColorSetARGB(0xB3, 0, 0, 0);

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false),
      use_menu_button_paint_(false), active_(true) {
  set_border(NULL);

  // Use an offset that is top aligned with toolbar.
  set_menu_offset(0, 2);

  // Use a halo for status text as the icons.
  SetTextHaloColor(kStatusTextHaloColor);
}

void StatusAreaButton::OnPaint(gfx::Canvas* canvas, bool for_drag) {
  if (state() == BS_PUSHED) {
    // Apply 10% white when pushed down.
    canvas->FillRectInt(SkColorSetARGB(0x19, 0xFF, 0xFF, 0xFF),
        0, 0, width(), height());
  }

  if (use_menu_button_paint_) {
    views::MenuButton::Paint(canvas, for_drag);
  } else {
    DrawIcon(canvas);
    OnPaintFocusBorder(canvas);
  }
}

gfx::Size StatusAreaButton::GetPreferredSize() {
  gfx::Insets insets = views::MenuButton::GetInsets();
  gfx::Size prefsize(icon_width() + insets.width(),
                     icon_height() + insets.height());

  // Adjusts size when use menu button paint.
  if (use_menu_button_paint_) {
    gfx::Size menu_button_size = views::MenuButton::GetPreferredSize();
    prefsize.SetSize(
      std::max(prefsize.width(), menu_button_size.width()),
      std::max(prefsize.height(), menu_button_size.height())
    );

    // Shift 1-pixel down for odd number of pixels in vertical space.
    if ((prefsize.height() - menu_button_size.height()) % 2) {
      insets_.Set(insets.top() + 1, insets.left(),
          insets.bottom(), insets.right());
    }
  }

  // Add padding.
  prefsize.Enlarge(2 * horizontal_padding(), 0);

  return prefsize;
}

gfx::Insets StatusAreaButton::GetInsets() const {
  return insets_;
}

void StatusAreaButton::SetText(const std::wstring& text) {
  // TextButtons normally remember the max text size, so the button's preferred
  // size will always be as large as the largest text ever put in it.
  // We clear that max text size, so we can adjust the size to fit the text.
  ClearMaxTextSize();
  views::MenuButton::SetText(text);
}

void StatusAreaButton::DrawIcon(gfx::Canvas* canvas) {
  canvas->DrawBitmapInt(icon(), horizontal_padding(), 0);
}

bool StatusAreaButton::Activate() {
  if (active_) {
    return views::MenuButton::Activate();
  } else {
    return true;
  }
}

}  // namespace chromeos
<commit_msg>Fix resizing behavior of the input method button in the chromeos status bar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/status/status_area_button.h"

#include "grit/theme_resources.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/skbitmap_operations.h"
#include "views/border.h"
#include "views/view.h"

namespace chromeos {

// A 0.7 black to decorate status text. Same color is used for icon borders.
static const SkColor kStatusTextHaloColor = SkColorSetARGB(0xB3, 0, 0, 0);

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false),
      use_menu_button_paint_(false), active_(true) {
  set_border(NULL);

  // Use an offset that is top aligned with toolbar.
  set_menu_offset(0, 2);

  // Use a halo for status text as the icons.
  SetTextHaloColor(kStatusTextHaloColor);
}

void StatusAreaButton::OnPaint(gfx::Canvas* canvas, bool for_drag) {
  if (state() == BS_PUSHED) {
    // Apply 10% white when pushed down.
    canvas->FillRectInt(SkColorSetARGB(0x19, 0xFF, 0xFF, 0xFF),
        0, 0, width(), height());
  }

  if (use_menu_button_paint_) {
    views::MenuButton::Paint(canvas, for_drag);
  } else {
    DrawIcon(canvas);
    OnPaintFocusBorder(canvas);
  }
}

gfx::Size StatusAreaButton::GetPreferredSize() {
  gfx::Insets insets = views::MenuButton::GetInsets();
  gfx::Size prefsize(icon_width() + insets.width(),
                     icon_height() + insets.height());

  // Adjusts size when use menu button paint.
  if (use_menu_button_paint_) {
    gfx::Size menu_button_size = views::MenuButton::GetPreferredSize();
    prefsize.SetSize(
      std::max(prefsize.width(), menu_button_size.width()),
      std::max(prefsize.height(), menu_button_size.height())
    );

    // Shift 1-pixel down for odd number of pixels in vertical space.
    if ((prefsize.height() - menu_button_size.height()) % 2) {
      insets_.Set(insets.top() + 1, insets.left(),
          insets.bottom(), insets.right());
    }
  }

  // Add padding.
  prefsize.Enlarge(2 * horizontal_padding(), 0);

  return prefsize;
}

gfx::Insets StatusAreaButton::GetInsets() const {
  return insets_;
}

void StatusAreaButton::SetText(const std::wstring& text) {
  // TextButtons normally remember the max text size, so the button's preferred
  // size will always be as large as the largest text ever put in it.
  // We clear that max text size, so we can adjust the size to fit the text.
  // The order is important.  ClearMaxTextSize sets the size to that of the
  // current text, so it must be called after SetText.
  views::MenuButton::SetText(text);
  ClearMaxTextSize();
  PreferredSizeChanged();
}

void StatusAreaButton::DrawIcon(gfx::Canvas* canvas) {
  canvas->DrawBitmapInt(icon(), horizontal_padding(), 0);
}

bool StatusAreaButton::Activate() {
  if (active_) {
    return views::MenuButton::Activate();
  } else {
    return true;
  }
}

}  // namespace chromeos
<|endoftext|>