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

#include "qllcpsocket.h"

#if defined(QT_SIMULATOR)
#include "qllcpsocket_simulator_p.h"
#elif defined(Q_OS_SYMBIAN)
#include "qllcpsocket_symbian_p.h"
#elif defined(Q_WS_MAEMO_6) || defined(Q_WS_MEEGO)
#include "qllcpsocket_meego_p.h"
#else
#include "qllcpsocket_p.h"
#endif

QTM_BEGIN_NAMESPACE

/*!
    \class QLlcpSocket
    \brief The QLlcpSocket class provides an NFC LLCP socket.

    \ingroup connectivity-nfc
    \inmodule QtConnectivity

    NFC LLCP protocol is a peer-to-peer communication protocol between two NFC compliant devices.
*/

/*!
    \enum QLlcpSocket::SocketError

    This enum describes the errors that can occur. The most recent error can be retrieved through a
    call to error().

    \value UnknownSocketError   An unidentified error has occurred.
*/

/*!
    \enum QLlcpSocket::SocketState

    This enum describes the different state in which a socket can be.

    \value UnconnectedState The socket is not connected.
    \value ConnectingState  The socket has started establishing a connection.
    \value ConnectedState   A connection is established.
    \value ClosingState     The socket is about to close.
    \value BoundState       The socket is bound to a local port (for servers).
    \value ListeningState   The socket is listening for incoming connections (for internal use).
*/

/*!
    \fn QLlcpSocket::connected()

    This signal is emitted after connectToService() has been called and a connection has been
    successfully established.

    \sa connectToService(), disconnected()
*/

/*!
    \fn QLlcpSocket::disconnected()

    This signal is emitted when the socket has been disconnected.

    \sa disconnectFromService(),
*/

/*!
    \fn QLlcpSocket::error(QLlcpSocket::SocketError socketError)

    This signal is emitted when an error occurs. The \a socketError parameter describes the error.
*/

/*!
    \fn QLlcpSocket::stateChanged(QLlcpSocket::SocketState socketState)

    This signal is emitted when the state of the socket changes. The \a socketState parameter
    describes the new state.
*/

/*!
    Construct a new unconnected LLCP socket with \a parent.
*/
QLlcpSocket::QLlcpSocket(QObject *parent)
:   QIODevice(parent), d_ptr(new QLlcpSocketPrivate(this))
{
    setOpenMode(QIODevice::NotOpen);
}

/*!
    \internal
*/
QLlcpSocket::QLlcpSocket(QLlcpSocketPrivate *d, QObject *parent)
:   QIODevice(parent), d_ptr(d)
{
    setOpenMode(QIODevice::ReadWrite);
    d_ptr->q_ptr = this;
}

/*!
    Destroys the LLCP socket.
*/
QLlcpSocket::~QLlcpSocket()
{
    delete d_ptr;
}

/*!
    Connects to the service identified by the URI \a serviceUri on \a target.
*/
void QLlcpSocket::connectToService(QNearFieldTarget *target, const QString &serviceUri)
{
    Q_D(QLlcpSocket);

    d->connectToService(target, serviceUri);
}

/*!
    Disconnects the socket.
*/
void QLlcpSocket::disconnectFromService()
{
    Q_D(QLlcpSocket);

    d->disconnectFromService();
}

/*!
    Disconnects the socket.
*/
void QLlcpSocket::close()
{
    Q_D(QLlcpSocket);

    QIODevice::close();

    d->disconnectFromService();
}

/*!
    Binds the LLCP socket to local \a port. Returns true on success; otherwise returns false.
*/
bool QLlcpSocket::bind(quint8 port)
{
    Q_D(QLlcpSocket);

    return d->bind(port);
}

/*!
    Returns true if at least one datagram (service data units) is waiting to be read; otherwise
    returns false.

    \sa pendingDatagramSize(), readDatagram()
*/
bool QLlcpSocket::hasPendingDatagrams() const
{
    Q_D(const QLlcpSocket);

    return d->hasPendingDatagrams();
}

/*!
    Returns the size of the first pending datagram (service data unit). If there is no datagram
    available, this function returns -1.

    \sa hasPendingDatagrams(), readDatagram()
*/
qint64 QLlcpSocket::pendingDatagramSize() const
{
    Q_D(const QLlcpSocket);

    return d->pendingDatagramSize();
}

/*!
    Sends the datagram at \a data of size \a size to the service that this socket is connected to.
    Returns the number of bytes sent on success; otherwise return -1;
*/
qint64 QLlcpSocket::writeDatagram(const char *data, qint64 size)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(data, size);
}

/*!
    \reimp

    Always returns true.
*/
bool QLlcpSocket::isSequential() const
{
	return true;
}

/*!
    \overload

    Sends the datagram \a datagram to the service that this socket is connected to.
*/
qint64 QLlcpSocket::writeDatagram(const QByteArray &datagram)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(datagram);
}

/*!
    Receives a datagram no larger than \a maxSize bytes and stores it in \a data. The sender's
    details are stored in \a target and \a port (unless the pointers are 0).

    Returns the size of the datagram on success; otherwise returns -1.

    If maxSize is too small, the rest of the datagram will be lost. To avoid loss of data, call
    pendingDatagramSize() to determine the size of the pending datagram before attempting to read
    it. If maxSize is 0, the datagram will be discarded.

    \sa writeDatagram(), hasPendingDatagrams(), pendingDatagramSize()
*/
qint64 QLlcpSocket::readDatagram(char *data, qint64 maxSize, QNearFieldTarget **target,
                                 quint8 *port)
{
    Q_D(QLlcpSocket);

    return d->readDatagram(data, maxSize, target, port);
}

/*!
    Sends the datagram at \a data of size \a size to the service identified by the URI
    \a port on \a target. Returns the number of bytes sent on success; otherwise returns -1.

    \sa readDatagram()
*/
qint64 QLlcpSocket::writeDatagram(const char *data, qint64 size, QNearFieldTarget *target,
                                  quint8 port)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(data, size, target, port);
}

/*!
    \overload

    Sends the datagram \a datagram to the service identified by the URI \a port on \a target.
*/
qint64 QLlcpSocket::writeDatagram(const QByteArray &datagram, QNearFieldTarget *target,
                                  quint8 port)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(datagram, target, port);
}

/*!
    Returns the type of error that last occurred.
*/
QLlcpSocket::SocketError QLlcpSocket::error() const
{
    Q_D(const QLlcpSocket);

    return d->error();
}

/*!
    Returns the state of the socket.
*/
QLlcpSocket::SocketState QLlcpSocket::state() const
{
    Q_D(const QLlcpSocket);

    return d->state();
}

/*!
    \reimp
*/
qint64 QLlcpSocket::bytesAvailable() const
{
    Q_D(const QLlcpSocket);

    return d->bytesAvailable() + QIODevice::bytesAvailable();
}

/*!
    \reimp
*/
bool QLlcpSocket::canReadLine() const
{
    Q_D(const QLlcpSocket);

    return d->canReadLine() || QIODevice::canReadLine();
}

/*!
    \reimp
*/
bool QLlcpSocket::waitForReadyRead(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForReadyRead(msecs);
}

/*!
    \reimp
*/
bool QLlcpSocket::waitForBytesWritten(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForBytesWritten(msecs);
}

/*!
    Waits until the socket is connected, up to \a msecs milliseconds. If the connection has been
    established, this function returns true; otherwise it returns false. In the case where it
    returns false, you can call error() to determine the cause of the error.

    If msecs is -1, this function will not time out.
*/
bool QLlcpSocket::waitForConnected(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForConnected(msecs);
}

/*!
    Waits until the socket is disconnected, up to \a msecs milliseconds. If the connection has been
    disconnected, this function returns true; otherwise it returns false. In the case where it
    returns false, you can call error() to determine the cause of the error.

    If msecs is -1, this function will not time out.
*/
bool QLlcpSocket::waitForDisconnected(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForDisconnected(msecs);
}

/*!
    \internal
*/
qint64 QLlcpSocket::readData(char *data, qint64 maxlen)
{
    Q_D(QLlcpSocket);

    return d->readData(data, maxlen);
}

/*!
    \internal
*/
qint64 QLlcpSocket::writeData(const char *data, qint64 len)
{
    Q_D(QLlcpSocket);

    return d->writeData(data, len);
}

#include <moc_qllcpsocket.cpp>

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

#include "qllcpsocket.h"

#if defined(QT_SIMULATOR)
#include "qllcpsocket_simulator_p.h"
#elif defined(Q_OS_SYMBIAN)
#include "qllcpsocket_symbian_p.h"
#elif defined(Q_WS_MAEMO_6) || defined(Q_WS_MEEGO)
#include "qllcpsocket_meego_p.h"
#else
#include "qllcpsocket_p.h"
#endif

QTM_BEGIN_NAMESPACE

/*!
    \class QLlcpSocket
    \brief The QLlcpSocket class provides an NFC LLCP socket.

    \ingroup connectivity-nfc
    \inmodule QtConnectivity

    NFC LLCP protocol is a peer-to-peer communication protocol between two NFC compliant devices.
*/

/*!
    \enum QLlcpSocket::SocketError

    This enum describes the errors that can occur. The most recent error can be retrieved through a
    call to error().

    \value UnknownSocketError       An unidentified error has occurred.
    \value RemoteHostClosedError    The remote host closed the connection.
*/

/*!
    \enum QLlcpSocket::SocketState

    This enum describes the different state in which a socket can be.

    \value UnconnectedState The socket is not connected.
    \value ConnectingState  The socket has started establishing a connection.
    \value ConnectedState   A connection is established.
    \value ClosingState     The socket is about to close.
    \value BoundState       The socket is bound to a local port (for servers).
    \value ListeningState   The socket is listening for incoming connections (for internal use).
*/

/*!
    \fn QLlcpSocket::connected()

    This signal is emitted after connectToService() has been called and a connection has been
    successfully established.

    \sa connectToService(), disconnected()
*/

/*!
    \fn QLlcpSocket::disconnected()

    This signal is emitted when the socket has been disconnected.

    \sa disconnectFromService(),
*/

/*!
    \fn QLlcpSocket::error(QLlcpSocket::SocketError socketError)

    This signal is emitted when an error occurs. The \a socketError parameter describes the error.
*/

/*!
    \fn QLlcpSocket::stateChanged(QLlcpSocket::SocketState socketState)

    This signal is emitted when the state of the socket changes. The \a socketState parameter
    describes the new state.
*/

/*!
    Construct a new unconnected LLCP socket with \a parent.
*/
QLlcpSocket::QLlcpSocket(QObject *parent)
:   QIODevice(parent), d_ptr(new QLlcpSocketPrivate(this))
{
    setOpenMode(QIODevice::NotOpen);
}

/*!
    \internal
*/
QLlcpSocket::QLlcpSocket(QLlcpSocketPrivate *d, QObject *parent)
:   QIODevice(parent), d_ptr(d)
{
    setOpenMode(QIODevice::ReadWrite);
    d_ptr->q_ptr = this;
}

/*!
    Destroys the LLCP socket.
*/
QLlcpSocket::~QLlcpSocket()
{
    delete d_ptr;
}

/*!
    Connects to the service identified by the URI \a serviceUri on \a target.
*/
void QLlcpSocket::connectToService(QNearFieldTarget *target, const QString &serviceUri)
{
    Q_D(QLlcpSocket);

    d->connectToService(target, serviceUri);
}

/*!
    Disconnects the socket.
*/
void QLlcpSocket::disconnectFromService()
{
    Q_D(QLlcpSocket);

    d->disconnectFromService();
}

/*!
    Disconnects the socket.
*/
void QLlcpSocket::close()
{
    Q_D(QLlcpSocket);

    QIODevice::close();

    d->disconnectFromService();
}

/*!
    Binds the LLCP socket to local \a port. Returns true on success; otherwise returns false.
*/
bool QLlcpSocket::bind(quint8 port)
{
    Q_D(QLlcpSocket);

    return d->bind(port);
}

/*!
    Returns true if at least one datagram (service data units) is waiting to be read; otherwise
    returns false.

    \sa pendingDatagramSize(), readDatagram()
*/
bool QLlcpSocket::hasPendingDatagrams() const
{
    Q_D(const QLlcpSocket);

    return d->hasPendingDatagrams();
}

/*!
    Returns the size of the first pending datagram (service data unit). If there is no datagram
    available, this function returns -1.

    \sa hasPendingDatagrams(), readDatagram()
*/
qint64 QLlcpSocket::pendingDatagramSize() const
{
    Q_D(const QLlcpSocket);

    return d->pendingDatagramSize();
}

/*!
    Sends the datagram at \a data of size \a size to the service that this socket is connected to.
    Returns the number of bytes sent on success; otherwise return -1;
*/
qint64 QLlcpSocket::writeDatagram(const char *data, qint64 size)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(data, size);
}

/*!
    \reimp

    Always returns true.
*/
bool QLlcpSocket::isSequential() const
{
	return true;
}

/*!
    \overload

    Sends the datagram \a datagram to the service that this socket is connected to.
*/
qint64 QLlcpSocket::writeDatagram(const QByteArray &datagram)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(datagram);
}

/*!
    Receives a datagram no larger than \a maxSize bytes and stores it in \a data. The sender's
    details are stored in \a target and \a port (unless the pointers are 0).

    Returns the size of the datagram on success; otherwise returns -1.

    If maxSize is too small, the rest of the datagram will be lost. To avoid loss of data, call
    pendingDatagramSize() to determine the size of the pending datagram before attempting to read
    it. If maxSize is 0, the datagram will be discarded.

    \sa writeDatagram(), hasPendingDatagrams(), pendingDatagramSize()
*/
qint64 QLlcpSocket::readDatagram(char *data, qint64 maxSize, QNearFieldTarget **target,
                                 quint8 *port)
{
    Q_D(QLlcpSocket);

    return d->readDatagram(data, maxSize, target, port);
}

/*!
    Sends the datagram at \a data of size \a size to the service identified by the URI
    \a port on \a target. Returns the number of bytes sent on success; otherwise returns -1.

    \sa readDatagram()
*/
qint64 QLlcpSocket::writeDatagram(const char *data, qint64 size, QNearFieldTarget *target,
                                  quint8 port)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(data, size, target, port);
}

/*!
    \overload

    Sends the datagram \a datagram to the service identified by the URI \a port on \a target.
*/
qint64 QLlcpSocket::writeDatagram(const QByteArray &datagram, QNearFieldTarget *target,
                                  quint8 port)
{
    Q_D(QLlcpSocket);

    return d->writeDatagram(datagram, target, port);
}

/*!
    Returns the type of error that last occurred.
*/
QLlcpSocket::SocketError QLlcpSocket::error() const
{
    Q_D(const QLlcpSocket);

    return d->error();
}

/*!
    Returns the state of the socket.
*/
QLlcpSocket::SocketState QLlcpSocket::state() const
{
    Q_D(const QLlcpSocket);

    return d->state();
}

/*!
    \reimp
*/
qint64 QLlcpSocket::bytesAvailable() const
{
    Q_D(const QLlcpSocket);

    return d->bytesAvailable() + QIODevice::bytesAvailable();
}

/*!
    \reimp
*/
bool QLlcpSocket::canReadLine() const
{
    Q_D(const QLlcpSocket);

    return d->canReadLine() || QIODevice::canReadLine();
}

/*!
    \reimp
*/
bool QLlcpSocket::waitForReadyRead(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForReadyRead(msecs);
}

/*!
    \reimp
*/
bool QLlcpSocket::waitForBytesWritten(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForBytesWritten(msecs);
}

/*!
    Waits until the socket is connected, up to \a msecs milliseconds. If the connection has been
    established, this function returns true; otherwise it returns false. In the case where it
    returns false, you can call error() to determine the cause of the error.

    If msecs is -1, this function will not time out.
*/
bool QLlcpSocket::waitForConnected(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForConnected(msecs);
}

/*!
    Waits until the socket is disconnected, up to \a msecs milliseconds. If the connection has been
    disconnected, this function returns true; otherwise it returns false. In the case where it
    returns false, you can call error() to determine the cause of the error.

    If msecs is -1, this function will not time out.
*/
bool QLlcpSocket::waitForDisconnected(int msecs)
{
    Q_D(QLlcpSocket);

    return d->waitForDisconnected(msecs);
}

/*!
    \internal
*/
qint64 QLlcpSocket::readData(char *data, qint64 maxlen)
{
    Q_D(QLlcpSocket);

    return d->readData(data, maxlen);
}

/*!
    \internal
*/
qint64 QLlcpSocket::writeData(const char *data, qint64 len)
{
    Q_D(QLlcpSocket);

    return d->writeData(data, len);
}

#include <moc_qllcpsocket.cpp>

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>#include "oniguruma.h"
#include "onig-result.h"
#include "unicode-utils.h"

OnigResult::OnigResult(OnigRegion* region, const string& searchString) : searchString_(searchString) {
  region_ = region;
}

OnigResult::~OnigResult() {
  onig_region_free(region_, 1);
}

int OnigResult::Count() {
  return region_->num_regs;
}

int OnigResult::LocationAt(int index) {
  int bytes = *(region_->beg + index);
  if (bytes > 0)
    return UnicodeUtils::characters_in_bytes(searchString_.data(), bytes);
  else
    return 0;
}

int OnigResult::LengthAt(int index) {
  int bytes = *(region_->end + index) - *(region_->beg + index);
  if (bytes > 0) {
    const char *search = searchString_.data() + *(region_->beg + index);
    return UnicodeUtils::characters_in_bytes(search, bytes);
  } else {
    return 0;
  }
}
<commit_msg>Do member data initialization in initializer list.<commit_after>#include "oniguruma.h"
#include "onig-result.h"
#include "unicode-utils.h"

OnigResult::OnigResult(OnigRegion* region, const string& searchString)
    : searchString_(searchString),
      region_(region) {
}

OnigResult::~OnigResult() {
  onig_region_free(region_, 1);
}

int OnigResult::Count() {
  return region_->num_regs;
}

int OnigResult::LocationAt(int index) {
  int bytes = *(region_->beg + index);
  if (bytes > 0)
    return UnicodeUtils::characters_in_bytes(searchString_.data(), bytes);
  else
    return 0;
}

int OnigResult::LengthAt(int index) {
  int bytes = *(region_->end + index) - *(region_->beg + index);
  if (bytes > 0) {
    const char *search = searchString_.data() + *(region_->beg + index);
    return UnicodeUtils::characters_in_bytes(search, bytes);
  } else {
    return 0;
  }
}
<|endoftext|>


<commit_before>#ifndef SRC_ONLINE_SCW_HPP_
#define SRC_ONLINE_SCW_HPP_

#include <Eigen/Core>
#include <boost/math/special_functions/erf.hpp>
#include <cmath>
#include <cstdbool>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
#include "utility.hpp"

class SCW {
private :
  const std::size_t kDim;
  const double kC;
  const double kPhi;

private :
  Eigen::VectorXd _covariances;
  Eigen::VectorXd _means;

private :
  inline double cdf(const double x) const {
    return 0.5 * (1.0 + boost::math::erf(x / std::sqrt(2.0)));
  }

public :
  SCW(const std::size_t dim, const double c, const double eta)
    : kDim(dim),
      kC(c),
      kPhi(cdf(eta)),
      _covariances(Eigen::VectorXd::Ones(kDim)),
      _means(Eigen::VectorXd::Zero(kDim)) {

    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, "Dimension Error. (Dimension > 0)");
    static_assert(std::numeric_limits<decltype(c)>::max() > 0, "Hyper Parameter Error. (c > 0)");
    static_assert(std::numeric_limits<decltype(eta)>::max() > 0, "Hyper Parameter Error. (η > 0)");
    assert(dim > 0);
    assert(c > 0);
    assert(eta > 0);
  }

  virtual ~SCW() { }

  double suffer_loss(const Eigen::VectorXd& x, const int label) {
    const auto confidence = calculate_confidence(x);
    return std::max(0.0, kPhi * std::sqrt(confidence) - label * _means.dot(x));
  }

  double calculate_alpha(const double m, const double n, const double v, const double ganma) const {
    const auto numerator = -(2.0 * m * n + kPhi * kPhi * m * v) + ganma;
    const auto denominator = 2.0 * (n * n + n * v * kPhi * kPhi);
    return std::max(0.0, numerator / denominator);
  }

  double calculate_beta(const double alpha, const double v) const {
    const auto u = std::pow(-alpha * v * kPhi + 4.0 * v , 2.0) / 4.0;
    return alpha * kPhi / (std::sqrt(u) + v * alpha * kPhi);
  }

  double calculate_confidence(const Eigen::VectorXd& f) {
    auto confidence = 0.0;
    utility::enumerate(f.data(), f.data() + f.size(), 0,
                       [&](const int index, const double value) {
                         confidence += _covariances[index] * value * value;
                       });
    return confidence;
  }

  bool update(const Eigen::VectorXd& x, const int label) {
    const auto v = calculate_confidence(x);
    const auto m = label * _means.dot(x);
    const auto n = v + 1.0 / 2.0 * kC;
    const auto ganma = kPhi * std::sqrt(kPhi * kPhi * m * m * v * v + 4.0 * n * v * (n + v * kPhi * kPhi));
    const auto alpha = calculate_alpha(m, n, v, ganma);
    const auto beta = calculate_beta(alpha, ganma);

    if (suffer_loss(x, label) <= 0.0) { return false; }

    utility::enumerate(x.data(), x.data() + x.size(), 0,
                       [&](const int index, const double value) {
                         const auto v = _covariances[index] * value;
                         _means[index] += alpha * label * v;
                         _covariances[index] -= beta * v * v;
                       });

    return true;
  }

  int predict(const Eigen::VectorXd& x) {
    return _means.dot(x) < 0.0 ? -1 : 1;
  }

  void save(const std::string& filename) {
    std::ofstream ofs(filename);
    assert(ofs);
    boost::archive::text_oarchive oa(ofs);
    oa << *this;
    ofs.close();
  }

  void load(const std::string& filename) {
    std::ifstream ifs(filename);
    assert(ifs);
    boost::archive::text_iarchive ia(ifs);
    ia >> *this;
    ifs.close();
  }

private :
  friend class boost::serialization::access;
  BOOST_SERIALIZATION_SPLIT_MEMBER();
  template <class Archive>
  void save(Archive& ar, const unsigned int version) const {
    std::vector<double> covariances_vector(_covariances.data(), _covariances.data() + _covariances.size());
    std::vector<double> means_vector(_means.data(), _means.data() + _means.size());
    ar & boost::serialization::make_nvp("covariances", covariances_vector);
    ar & boost::serialization::make_nvp("means", means_vector);
    ar & boost::serialization::make_nvp("dimension", const_cast<std::size_t&>(kDim));
    ar & boost::serialization::make_nvp("phi", const_cast<double&>(kPhi));
    ar & boost::serialization::make_nvp("c", const_cast<double&>(kC));
  }

  template <class Archive>
  void load(Archive& ar, const unsigned int version) {
    std::vector<double> covariances_vector;
    std::vector<double> means_vector;
    ar & boost::serialization::make_nvp("covariances", covariances_vector);
    ar & boost::serialization::make_nvp("means", means_vector);
    ar & boost::serialization::make_nvp("dimension", const_cast<std::size_t&>(kDim));
    ar & boost::serialization::make_nvp("phi", const_cast<double&>(kPhi));
    ar & boost::serialization::make_nvp("c", const_cast<double&>(kC));
    _covariances = Eigen::Map<Eigen::VectorXd>(&covariances_vector[0], covariances_vector.size());
    _means = Eigen::Map<Eigen::VectorXd>(&means_vector[0], means_vector.size());
  }

};

#endif
<commit_msg>constの追加と変数名の変更<commit_after>#ifndef SRC_ONLINE_SCW_HPP_
#define SRC_ONLINE_SCW_HPP_

#include <Eigen/Core>
#include <boost/math/special_functions/erf.hpp>
#include <cmath>
#include <cstdbool>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
#include "utility.hpp"

class SCW {
private :
  const std::size_t kDim;
  const double kC;
  const double kPhi;

private :
  Eigen::VectorXd _covariances;
  Eigen::VectorXd _means;

private :
  inline double cdf(const double x) const {
    return 0.5 * (1.0 + boost::math::erf(x / std::sqrt(2.0)));
  }

public :
  SCW(const std::size_t dim, const double c, const double eta)
    : kDim(dim),
      kC(c),
      kPhi(cdf(eta)),
      _covariances(Eigen::VectorXd::Ones(kDim)),
      _means(Eigen::VectorXd::Zero(kDim)) {

    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, "Dimension Error. (Dimension > 0)");
    static_assert(std::numeric_limits<decltype(c)>::max() > 0, "Hyper Parameter Error. (c > 0)");
    static_assert(std::numeric_limits<decltype(eta)>::max() > 0, "Hyper Parameter Error. (η > 0)");
    assert(dim > 0);
    assert(c > 0);
    assert(eta > 0);
  }

  virtual ~SCW() { }

  double suffer_loss(const Eigen::VectorXd& f, const int label) const {
    const auto confidence = calculate_confidence(f);
    return std::max(0.0, kPhi * std::sqrt(confidence) - label * _means.dot(f));
  }

  double calculate_alpha(const double m, const double n, const double v, const double ganma) const {
    const auto numerator = -(2.0 * m * n + kPhi * kPhi * m * v) + ganma;
    const auto denominator = 2.0 * (n * n + n * v * kPhi * kPhi);
    return std::max(0.0, numerator / denominator);
  }

  double calculate_beta(const double alpha, const double v) const {
    const auto u = std::pow(-alpha * v * kPhi + 4.0 * v , 2.0) / 4.0;
    return alpha * kPhi / (std::sqrt(u) + v * alpha * kPhi);
  }

  double calculate_confidence(const Eigen::VectorXd& f) const {
    auto confidence = 0.0;
    utility::enumerate(f.data(), f.data() + f.size(), 0,
                       [&](const int index, const double value) {
                         confidence += _covariances[index] * value * value;
                       });
    return confidence;
  }

  bool update(const Eigen::VectorXd& feature, const int label) {
    const auto v = calculate_confidence(feature);
    const auto m = label * _means.dot(feature);
    const auto n = v + 1.0 / 2.0 * kC;
    const auto ganma = kPhi * std::sqrt(kPhi * kPhi * m * m * v * v + 4.0 * n * v * (n + v * kPhi * kPhi));
    const auto alpha = calculate_alpha(m, n, v, ganma);
    const auto beta = calculate_beta(alpha, ganma);

    if (suffer_loss(feature, label) <= 0.0) { return false; }

    utility::enumerate(feature.data(), feature.data() + feature.size(), 0,
                       [&](const int index, const double value) {
                         const auto v = _covariances[index] * value;
                         _means[index] += alpha * label * v;
                         _covariances[index] -= beta * v * v;
                       });

    return true;
  }

  int predict(const Eigen::VectorXd& x) {
    return _means.dot(x) < 0.0 ? -1 : 1;
  }

  void save(const std::string& filename) {
    std::ofstream ofs(filename);
    assert(ofs);
    boost::archive::text_oarchive oa(ofs);
    oa << *this;
    ofs.close();
  }

  void load(const std::string& filename) {
    std::ifstream ifs(filename);
    assert(ifs);
    boost::archive::text_iarchive ia(ifs);
    ia >> *this;
    ifs.close();
  }

private :
  friend class boost::serialization::access;
  BOOST_SERIALIZATION_SPLIT_MEMBER();
  template <class Archive>
  void save(Archive& ar, const unsigned int version) const {
    std::vector<double> covariances_vector(_covariances.data(), _covariances.data() + _covariances.size());
    std::vector<double> means_vector(_means.data(), _means.data() + _means.size());
    ar & boost::serialization::make_nvp("covariances", covariances_vector);
    ar & boost::serialization::make_nvp("means", means_vector);
    ar & boost::serialization::make_nvp("dimension", const_cast<std::size_t&>(kDim));
    ar & boost::serialization::make_nvp("phi", const_cast<double&>(kPhi));
    ar & boost::serialization::make_nvp("c", const_cast<double&>(kC));
  }

  template <class Archive>
  void load(Archive& ar, const unsigned int version) {
    std::vector<double> covariances_vector;
    std::vector<double> means_vector;
    ar & boost::serialization::make_nvp("covariances", covariances_vector);
    ar & boost::serialization::make_nvp("means", means_vector);
    ar & boost::serialization::make_nvp("dimension", const_cast<std::size_t&>(kDim));
    ar & boost::serialization::make_nvp("phi", const_cast<double&>(kPhi));
    ar & boost::serialization::make_nvp("c", const_cast<double&>(kC));
    _covariances = Eigen::Map<Eigen::VectorXd>(&covariances_vector[0], covariances_vector.size());
    _means = Eigen::Map<Eigen::VectorXd>(&means_vector[0], means_vector.size());
  }

};

#endif
<|endoftext|>


<commit_before>#ifndef LISTHOOKEDPOINTING_HPP
#define LISTHOOKEDPOINTING_HPP

#include "base.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace ListHookedPointing {
    void terminate(void);

    class Item;
    bool append(IOHIKeyboard *kbd);
    Item *get(const IOHIKeyboard *kbd);
    Item *get(void);
    void refresh(void);

    // ----------------------------------------------------------------------
    class Item {
    public:
      Item(void) { pointing = NULL; }

      void initialize(IOHIPointing *_pointing);
      void refresh(void);
      void terminate(void);

      IOHIPointing *get(void) const { return pointing; }

    private:
      IOHIPointing *pointing;
      RelativePointerEventCallback orig_relativePointerEventAction;
      ScrollWheelEventCallback orig_scrollWheelEventAction;
      OSObject *orig_relativePointerEventTarget;
      OSObject *orig_scrollWheelEventTarget;

      RelativePointerEventCallback getCurrent_relativePointerEventAction(void) const {
        return reinterpret_cast<RelativePointerEventCallback>(pointing->_relativePointerEventAction);
      }
      ScrollWheelEventCallback getCurrent_scrollWheelEventAction(void) const {
        return reinterpret_cast<ScrollWheelEventCallback>(pointing->_scrollWheelEventAction);
      }
    };

    // ----------------------------------------------------------------------
    void hook_RelativePointerEventCallback(OSObject *target,
                                           int buttons,
                                           int dx,
                                           int dy,
                                           AbsoluteTime ts,
                                           OSObject *sender,
                                           void *refcon);
    void hook_ScrollWheelEventCallback(OSObject * target,
                                       short deltaAxis1,
                                       short deltaAxis2,
                                       short deltaAxis3,
                                       IOFixed fixedDelta1,
                                       IOFixed fixedDelta2,
                                       IOFixed fixedDelta3,
                                       SInt32 pointDelta1,
                                       SInt32 pointDelta2,
                                       SInt32 pointDelta3,
                                       SInt32 options,
                                       AbsoluteTime ts,
                                       OSObject *sender,
                                       void *refcon);
  }
}

#endif
<commit_msg>update ListingHookedPointing<commit_after>#ifndef LISTHOOKEDPOINTING_HPP
#define LISTHOOKEDPOINTING_HPP

#include "base.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace ListHookedPointing {
    void terminate(void);

    class Item;
    bool append(IOHIKeyboard *kbd);
    Item *get(const IOHIKeyboard *kbd);
    Item *get(void);
    void refresh(void);

    // ----------------------------------------------------------------------
    class Item {
    public:
      Item(void) { pointing = NULL; }

      void initialize(IOHIPointing *_pointing);
      void refresh(void);
      void terminate(void);

      IOHIPointing *get(void) const { return pointing; }

      RelativePointerEventCallback getOrig_relativePointerEventAction() const { return orig_relativePointerEventAction; }
      ScrollWheelEventCallback getOrig_scrollWheelEventAction() const { return orig_scrollWheelEventAction; }
      OSObject *getOrig_relativePointerEventTarget() const { return orig_relativePointerEventTarget; }
      OSObject *getOrig_scrollWheelEventTarget() const { return orig_scrollWheelEventTarget; }

    private:
      IOHIPointing *pointing;
      RelativePointerEventCallback orig_relativePointerEventAction;
      ScrollWheelEventCallback orig_scrollWheelEventAction;
      OSObject *orig_relativePointerEventTarget;
      OSObject *orig_scrollWheelEventTarget;

      RelativePointerEventCallback getCurrent_relativePointerEventAction(void) const {
        return reinterpret_cast<RelativePointerEventCallback>(pointing->_relativePointerEventAction);
      }
      ScrollWheelEventCallback getCurrent_scrollWheelEventAction(void) const {
        return reinterpret_cast<ScrollWheelEventCallback>(pointing->_scrollWheelEventAction);
      }
    };

    // ----------------------------------------------------------------------
    void hook_RelativePointerEventCallback(OSObject *target,
                                           int buttons,
                                           int dx,
                                           int dy,
                                           AbsoluteTime ts,
                                           OSObject *sender,
                                           void *refcon);
    void hook_ScrollWheelEventCallback(OSObject * target,
                                       short deltaAxis1,
                                       short deltaAxis2,
                                       short deltaAxis3,
                                       IOFixed fixedDelta1,
                                       IOFixed fixedDelta2,
                                       IOFixed fixedDelta3,
                                       SInt32 pointDelta1,
                                       SInt32 pointDelta2,
                                       SInt32 pointDelta3,
                                       SInt32 options,
                                       AbsoluteTime ts,
                                       OSObject *sender,
                                       void *refcon);
  }
}

#endif
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mcommonpixmaps.h"
#include "mthemedaemon.h"
#include "mdebug.h"
#include "mpixmaphandle.h"

#include <QFile>
#include <QDir>

using namespace M::MThemeDaemonProtocol;

#define VERSION(major, minor) ((major << 16) | minor)
const unsigned int PRELOAD_FILE_VERSION = VERSION(0, 1);

MCommonPixmaps::MCommonPixmaps(MThemeDaemon *daemon, bool loadMostUsed) :
    minRequestsForCache(0),
    daemon(daemon)
{
    if (loadMostUsed) {
        connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(loadOne()));
        connect(this, SIGNAL(mostUsedPixmapsChanged(M::MThemeDaemonProtocol::MostUsedPixmaps)), SLOT(considerSaving()));
    }
    timerSinceLastSave.invalidate();
}

MCommonPixmaps::~MCommonPixmaps()
{
    // please call clear before destroying this object
    Q_ASSERT(mostUsedPixmaps.count() == 0);
}

void MCommonPixmaps::clear()
{
    // release all most used pixmaps
    foreach(const PixmapIdentifier & id, mostUsedPixmaps) {
        if (toLoadList.contains(id))
            continue;

        ImageResource *resource = daemon->findImageResource(id.imageId);
        resource->releasePixmap(id.size);
    }

    cpuMonitor.stop();
    mostUsedPixmaps.clear();
    toLoadList.clear();
    requestCounts.clear();
    minRequestsForCache = 0;
}

void MCommonPixmaps::load()
{
    clear();

    if (!QFile::exists(cacheFilename())) {
        return;
    }
    QFile file(cacheFilename());
    if (!file.open(QIODevice::ReadOnly)) {
        mWarning("MCommonPixmaps") << "Could not load most used pixmaps from" << cacheFilename();
        return;
    }

    QDataStream stream(&file);

    unsigned int version;
    stream >> version;
    if (version != PRELOAD_FILE_VERSION)
        return;

    while (file.bytesAvailable()) {
        QString imageId;
        QSize size;
        quint32 requestCount;
        bool isMostUsed;
        stream >> imageId >> size >> requestCount >> isMostUsed;

        PixmapIdentifier id(imageId, size);
        requestCounts.insert(id, requestCount);
        if (isMostUsed) {
            toLoadList.insert(PixmapIdentifier(imageId, size));
            mostUsedPixmaps.insert(PixmapIdentifier(imageId, size));
        }
    }

    if (!toLoadList.isEmpty()) {
        cpuMonitor.start(2000);
    }

    file.close();
}

void MCommonPixmaps::save() const
{
    QFile file(cacheFilename());
    if (!file.open(QIODevice::WriteOnly)) {
        mWarning("MCommonPixmaps") << "Could not save most used pixmaps to" << cacheFilename();
        return;
    }

    QDataStream stream(&file);
    stream << PRELOAD_FILE_VERSION;

    QHash<PixmapIdentifier, quint32>::const_iterator i = requestCounts.begin();

    for (; i != requestCounts.end(); ++i) {
        const PixmapIdentifier& id = i.key();

        bool isMostUsed = mostUsedPixmaps.contains(id);
        stream << id.imageId << id.size << i.value() << isMostUsed;
    }

    file.close();
}

void MCommonPixmaps::loadOne()
{
    // stop the timer, so we can adjust the frequency depending on the usage
    cpuMonitor.stop();

    if ((cpuMonitor.usage() != -1) && (cpuMonitor.usage() < 30)) {
        const int batchSize = 5;
        for (int i = 0; i < batchSize; ++i) {
            if (!toLoadList.isEmpty()) {
                PixmapIdentifier id = *toLoadList.begin();
                toLoadList.erase(toLoadList.begin());

                ImageResource *resource = daemon->findImageResource(id.imageId);
                if (resource) {
                    resource->fetchPixmap(id.size);
                } else {
                    mWarning("MCommonPixmaps") << QString("Themedaemon could not find resource %1 while loading most used pixmaps. Removing from list.").arg(id.imageId);
                    requestCounts.remove(id);
                    mostUsedPixmaps.remove(id);
                }
            } else {
                break;
            }
        }
        if (!toLoadList.isEmpty()) {
            // there's still items in the list, so start the timer with small delay
            cpuMonitor.start(100);
        } else {
            if (toLoadList.isEmpty()) {
                disconnect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), this, SLOT(loadOne()));
                connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(updateClientsAboutMostUsed()));
                cpuMonitor.start(5000);
            }
        }
    } else {
        // the cpu usage was too high, so start start the timer with longer delay
        cpuMonitor.start(1000);
    }
}

void MCommonPixmaps::updateClientsAboutMostUsed()
{
    cpuMonitor.stop();
    // only wakeup all clients if the device is idle
    if ((cpuMonitor.usage() != -1) && (cpuMonitor.usage() < 10)) {
        MostUsedPixmaps mostUsed;
        mostUsed.addedHandles = mostUsedPixmapHandles();
        emit mostUsedPixmapsChanged(mostUsed);
        disconnect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), this, SLOT(updateClientsAboutMostUsed()));
    } else {
        cpuMonitor.start(5000);
    }
}

void MCommonPixmaps::increaseRequestCount(const M::MThemeDaemonProtocol::PixmapIdentifier &id, ImageResource *resource)
{
    QHash<PixmapIdentifier, quint32>::iterator requestCount = requestCounts.find(id);
    if (requestCount == requestCounts.end()) {
        requestCount = requestCounts.insert(id, 0);
    }
    ++requestCount.value();

    if (toLoadList.contains(id)) {
        toLoadList.remove(id);
        resource->fetchPixmap(id.size);
    }

    // pixmap has higher request count value than the current minimum for cache?
    if (requestCount.value() > minRequestsForCache && !mostUsedPixmaps.contains(id)) {
        // this pixmap might end up in mostUsedPixmaps list

        // check if there's still room for this pixmap
        if (mostUsedPixmaps.count() < MCommonPixmaps::CacheSize) {
            // yep, just add this pixmap and return
            MPixmapHandle handle = resource->fetchPixmap(id.size);
            mostUsedPixmaps.insert(id);

            MostUsedPixmaps packet;
            packet.addedHandles.append(PixmapHandle(id, handle));

            return;
        }

        // there was no room, so we'll check if we can make it
        QSet<PixmapIdentifier>::iterator i = mostUsedPixmaps.begin();
        QSet<PixmapIdentifier>::iterator leastUsed = i;
        quint32 leastUsedRequests = requestCounts[*leastUsed];
        quint32 secondlyLeastUsedRequests = leastUsedRequests;
        ++i;

        // find the least used pixmap from most used list
        for (; i != mostUsedPixmaps.end(); ++i) {
            const PixmapIdentifier &curId = *i;
            quint32 count = requestCounts[curId];
            if (count < leastUsedRequests) {
                secondlyLeastUsedRequests = leastUsedRequests;
                leastUsedRequests = count;
                leastUsed = i;
            }
        }

        // if the least used is still above the current, we'll just update the limit
        if (leastUsedRequests >= requestCount.value()) {
            minRequestsForCache = leastUsedRequests;
            return;
        }

        // otherwise we have a new pixmap for the list

        // update the limit, there may be duplicate request counts in the most used list
        minRequestsForCache = (secondlyLeastUsedRequests > requestCount.value()) ? requestCount.value() : secondlyLeastUsedRequests;

        // allocate one pixmap for the list
        MPixmapHandle handle = resource->fetchPixmap(id.size);
        MostUsedPixmaps packet;
        packet.addedHandles.append(PixmapHandle(id, handle));

        // release the old one from the list
        if (!toLoadList.remove(*leastUsed)) {
            packet.removedIdentifiers.append(id);
        }
        if (toLoadList.isEmpty()) {
            emit mostUsedPixmapsChanged(packet);
        }

        mostUsedPixmaps.remove(*leastUsed);
        mostUsedPixmaps.insert(id);
    }
}

void MCommonPixmaps::reload(const PixmapIdentifier &id, ImageResource *oldResource)
{
    if (toLoadList.contains(id) || !mostUsedPixmaps.contains(id)) {
        // no need to do anything
        return;
    }

    oldResource->releasePixmap(id.size);
    toLoadList.insert(id);
}

QList<M::MThemeDaemonProtocol::PixmapHandle> MCommonPixmaps::mostUsedPixmapHandles()
{
    QSet<M::MThemeDaemonProtocol::PixmapIdentifier> validMostUsedPixmaps(mostUsedPixmaps);
    validMostUsedPixmaps.subtract(toLoadList);

    // we could also save the handles earlier but it is cheap to do the query
    QList<PixmapHandle> pixmapHandles;
    foreach(const M::MThemeDaemonProtocol::PixmapIdentifier& id, validMostUsedPixmaps) {
        MPixmapHandle handle = daemon->findImageResource(id.imageId)->pixmapHandle(id.size);
        pixmapHandles.append(M::MThemeDaemonProtocol::PixmapHandle(id, handle));
    }

    return pixmapHandles;
}

QString MCommonPixmaps::cacheFilename() const
{
    return daemon->systemThemeCacheDirectory() + QDir::separator() + daemon->currentTheme() + QDir::separator() + QLatin1String("preload.list");
}

void MCommonPixmaps::considerSaving()
{
    // we do not allow more than one update in 10 seconds
    const int delay = 10000;
    if (!timerSinceLastSave.isValid() || timerSinceLastSave.hasExpired(delay)) {
        save();
        timerSinceLastSave.start();
    }
}
<commit_msg>Changes: replace magic numbers with constants<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mcommonpixmaps.h"
#include "mthemedaemon.h"
#include "mdebug.h"
#include "mpixmaphandle.h"

#include <QFile>
#include <QDir>

using namespace M::MThemeDaemonProtocol;

namespace {
    // before loading one item from the queue the cpu usage must
    // be below the given percentage
    const int maximumCpuUsageBeforeLoadingOneItem = 30;

    // when the cpu has been busy wait that many milliseconds before
    // doing the next check
    const int delayBeforeLoadingNextItemWhenBusy = 1000;

    // when the cpu was idle (we loaded an item) wait that many milliseconds
    // before doing the next check
    const int delayBeforeLoadingNextItemWhenIdle = 100;

    // this one is a tradeof between the time needed to load all pixmaps and
    // increased cpu usage
    const int numberOfPixmapsToLoadAtOnce = 5;

    // before sending the most used pixmaps the device should be pretty
    // idle as this wakes up all processes connected to the themedaemon
    const int maximumCpuUsageBeforeSendingMostUsed = 10;

    // check the cpu usage for that many seconds before deciding if
    // a most used package can be sent
    const int delayBeforeSendingMostUsed = 5000;
}

#define VERSION(major, minor) ((major << 16) | minor)
const unsigned int PRELOAD_FILE_VERSION = VERSION(0, 1);

MCommonPixmaps::MCommonPixmaps(MThemeDaemon *daemon, bool loadMostUsed) :
    minRequestsForCache(0),
    daemon(daemon)
{
    if (loadMostUsed) {
        connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(loadOne()));
        connect(this, SIGNAL(mostUsedPixmapsChanged(M::MThemeDaemonProtocol::MostUsedPixmaps)), SLOT(considerSaving()));
    }
    timerSinceLastSave.invalidate();
}

MCommonPixmaps::~MCommonPixmaps()
{
    // please call clear before destroying this object
    Q_ASSERT(mostUsedPixmaps.count() == 0);
}

void MCommonPixmaps::clear()
{
    // release all most used pixmaps
    foreach(const PixmapIdentifier & id, mostUsedPixmaps) {
        if (toLoadList.contains(id))
            continue;

        ImageResource *resource = daemon->findImageResource(id.imageId);
        resource->releasePixmap(id.size);
    }

    cpuMonitor.stop();
    mostUsedPixmaps.clear();
    toLoadList.clear();
    requestCounts.clear();
    minRequestsForCache = 0;
}

void MCommonPixmaps::load()
{
    clear();

    if (!QFile::exists(cacheFilename())) {
        return;
    }
    QFile file(cacheFilename());
    if (!file.open(QIODevice::ReadOnly)) {
        mWarning("MCommonPixmaps") << "Could not load most used pixmaps from" << cacheFilename();
        return;
    }

    QDataStream stream(&file);

    unsigned int version;
    stream >> version;
    if (version != PRELOAD_FILE_VERSION)
        return;

    while (file.bytesAvailable()) {
        QString imageId;
        QSize size;
        quint32 requestCount;
        bool isMostUsed;
        stream >> imageId >> size >> requestCount >> isMostUsed;

        PixmapIdentifier id(imageId, size);
        requestCounts.insert(id, requestCount);
        if (isMostUsed) {
            toLoadList.insert(PixmapIdentifier(imageId, size));
            mostUsedPixmaps.insert(PixmapIdentifier(imageId, size));
        }
    }

    if (!toLoadList.isEmpty()) {
        cpuMonitor.start(delayBeforeLoadingNextItemWhenBusy);
    }

    file.close();
}

void MCommonPixmaps::save() const
{
    QFile file(cacheFilename());
    if (!file.open(QIODevice::WriteOnly)) {
        mWarning("MCommonPixmaps") << "Could not save most used pixmaps to" << cacheFilename();
        return;
    }

    QDataStream stream(&file);
    stream << PRELOAD_FILE_VERSION;

    QHash<PixmapIdentifier, quint32>::const_iterator i = requestCounts.begin();

    for (; i != requestCounts.end(); ++i) {
        const PixmapIdentifier& id = i.key();

        bool isMostUsed = mostUsedPixmaps.contains(id);
        stream << id.imageId << id.size << i.value() << isMostUsed;
    }

    file.close();
}

void MCommonPixmaps::loadOne()
{
    // stop the timer, so we can adjust the frequency depending on the usage
    cpuMonitor.stop();

    if ((cpuMonitor.usage() != -1) && (cpuMonitor.usage() < maximumCpuUsageBeforeLoadingOneItem)) {
        for (int i = 0; i < numberOfPixmapsToLoadAtOnce; ++i) {
            if (!toLoadList.isEmpty()) {
                PixmapIdentifier id = *toLoadList.begin();
                toLoadList.erase(toLoadList.begin());

                ImageResource *resource = daemon->findImageResource(id.imageId);
                if (resource) {
                    resource->fetchPixmap(id.size);
                } else {
                    mWarning("MCommonPixmaps") << QString("Themedaemon could not find resource %1 while loading most used pixmaps. Removing from list.").arg(id.imageId);
                    requestCounts.remove(id);
                    mostUsedPixmaps.remove(id);
                }
            } else {
                break;
            }
        }
        if (!toLoadList.isEmpty()) {
            // there's still items in the list, so start the timer with small delay
            cpuMonitor.start(delayBeforeLoadingNextItemWhenIdle);
        } else {
            if (toLoadList.isEmpty()) {
                disconnect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), this, SLOT(loadOne()));
                connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(updateClientsAboutMostUsed()));
                cpuMonitor.start(delayBeforeSendingMostUsed);
            }
        }
    } else {
        // the cpu usage was too high, so start start the timer with longer delay
        cpuMonitor.start(delayBeforeLoadingNextItemWhenBusy);
    }
}

void MCommonPixmaps::updateClientsAboutMostUsed()
{
    cpuMonitor.stop();
    // only wakeup all clients if the device is idle
    if ((cpuMonitor.usage() != -1) && (cpuMonitor.usage() < maximumCpuUsageBeforeSendingMostUsed)) {
        MostUsedPixmaps mostUsed;
        mostUsed.addedHandles = mostUsedPixmapHandles();
        emit mostUsedPixmapsChanged(mostUsed);
        disconnect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), this, SLOT(updateClientsAboutMostUsed()));
    } else {
        cpuMonitor.start(delayBeforeSendingMostUsed);
    }
}

void MCommonPixmaps::increaseRequestCount(const M::MThemeDaemonProtocol::PixmapIdentifier &id, ImageResource *resource)
{
    QHash<PixmapIdentifier, quint32>::iterator requestCount = requestCounts.find(id);
    if (requestCount == requestCounts.end()) {
        requestCount = requestCounts.insert(id, 0);
    }
    ++requestCount.value();

    if (toLoadList.contains(id)) {
        toLoadList.remove(id);
        resource->fetchPixmap(id.size);
    }

    // pixmap has higher request count value than the current minimum for cache?
    if (requestCount.value() > minRequestsForCache && !mostUsedPixmaps.contains(id)) {
        // this pixmap might end up in mostUsedPixmaps list

        // check if there's still room for this pixmap
        if (mostUsedPixmaps.count() < MCommonPixmaps::CacheSize) {
            // yep, just add this pixmap and return
            MPixmapHandle handle = resource->fetchPixmap(id.size);
            mostUsedPixmaps.insert(id);

            MostUsedPixmaps packet;
            packet.addedHandles.append(PixmapHandle(id, handle));

            return;
        }

        // there was no room, so we'll check if we can make it
        QSet<PixmapIdentifier>::iterator i = mostUsedPixmaps.begin();
        QSet<PixmapIdentifier>::iterator leastUsed = i;
        quint32 leastUsedRequests = requestCounts[*leastUsed];
        quint32 secondlyLeastUsedRequests = leastUsedRequests;
        ++i;

        // find the least used pixmap from most used list
        for (; i != mostUsedPixmaps.end(); ++i) {
            const PixmapIdentifier &curId = *i;
            quint32 count = requestCounts[curId];
            if (count < leastUsedRequests) {
                secondlyLeastUsedRequests = leastUsedRequests;
                leastUsedRequests = count;
                leastUsed = i;
            }
        }

        // if the least used is still above the current, we'll just update the limit
        if (leastUsedRequests >= requestCount.value()) {
            minRequestsForCache = leastUsedRequests;
            return;
        }

        // otherwise we have a new pixmap for the list

        // update the limit, there may be duplicate request counts in the most used list
        minRequestsForCache = (secondlyLeastUsedRequests > requestCount.value()) ? requestCount.value() : secondlyLeastUsedRequests;

        // allocate one pixmap for the list
        MPixmapHandle handle = resource->fetchPixmap(id.size);
        MostUsedPixmaps packet;
        packet.addedHandles.append(PixmapHandle(id, handle));

        // release the old one from the list
        if (!toLoadList.remove(*leastUsed)) {
            packet.removedIdentifiers.append(id);
        }
        if (toLoadList.isEmpty()) {
            emit mostUsedPixmapsChanged(packet);
        }

        mostUsedPixmaps.remove(*leastUsed);
        mostUsedPixmaps.insert(id);
    }
}

void MCommonPixmaps::reload(const PixmapIdentifier &id, ImageResource *oldResource)
{
    if (toLoadList.contains(id) || !mostUsedPixmaps.contains(id)) {
        // no need to do anything
        return;
    }

    oldResource->releasePixmap(id.size);
    toLoadList.insert(id);
}

QList<M::MThemeDaemonProtocol::PixmapHandle> MCommonPixmaps::mostUsedPixmapHandles()
{
    QSet<M::MThemeDaemonProtocol::PixmapIdentifier> validMostUsedPixmaps(mostUsedPixmaps);
    validMostUsedPixmaps.subtract(toLoadList);

    // we could also save the handles earlier but it is cheap to do the query
    QList<PixmapHandle> pixmapHandles;
    foreach(const M::MThemeDaemonProtocol::PixmapIdentifier& id, validMostUsedPixmaps) {
        MPixmapHandle handle = daemon->findImageResource(id.imageId)->pixmapHandle(id.size);
        pixmapHandles.append(M::MThemeDaemonProtocol::PixmapHandle(id, handle));
    }

    return pixmapHandles;
}

QString MCommonPixmaps::cacheFilename() const
{
    return daemon->systemThemeCacheDirectory() + QDir::separator() + daemon->currentTheme() + QDir::separator() + QLatin1String("preload.list");
}

void MCommonPixmaps::considerSaving()
{
    // we do not allow more than one update in 10 seconds
    const int delay = 10000;
    if (!timerSinceLastSave.isValid() || timerSinceLastSave.hasExpired(delay)) {
        save();
        timerSinceLastSave.start();
    }
}
<|endoftext|>


<commit_before>/*
 * Date Started: 11/02/17
 * Original Author: Sajid Anower
 * Editors:
 * Purpose: Widget to display signal strength of the antenna
 * This code is released under the MIT License. Copyright BLUEsat UNSW, 2017
 */
#include "ros_video_components/ros_signal_strength.hpp"

#define RECT_X 0
#define RECT_Y 0
#define RECT_WIDTH RECT_X*40
#define RECT_HEIGHT 150
#define MAXDATA 100
#define MAXNUM 5
#define NUMCOLOR 3
#define GREEN 4
#define YELLOW 2
#define RED 1
#define HASH MAXDATA/MAXNUM
#define TOO_WEAK MAXDATA/20

ROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :
    QQuickPaintedItem(parent),
    topic_value("/rover/signal"),
    ros_ready(false),
    data(50) {
}

void ROS_Signal_Strength::setup(ros::NodeHandle * nh) {

    signal_sub = nh->subscribe(
        "/rover/signal", // TODO
        1,
        &ROS_Signal_Strength::receive_signal,
        this
    );
    ros_ready = true;
}

void ROS_Signal_Strength::paint(QPainter * painter) {
    int x = RECT_X;
    int y = RECT_Y;
    int widthV = width(); // RECT_WIDTH;
    int heightV = height(); // RECT_HEIGHT;

    QLinearGradient linearGradient(0, 0, 100, 100);
    int num = 0;
    float hash = HASH;
    if (data >= MAXDATA) {
        num = MAXNUM;
    } else if (data <= TOO_WEAK) {
        num = 0;
        linearGradient.setColorAt(0.0, Qt::white);
        painter->setBrush(linearGradient);
    } else {
        num = (data/hash) + 1;
    }
    // draw the outer main rectangle
    painter->drawRect(x, y, widthV - 1, heightV - 1);

    int i = 0;

    int barWidth = widthV/MAXNUM;
    int barHeight = heightV/MAXNUM;
    y += ((MAXNUM-1) * heightV) /MAXNUM;
    const int increment = heightV/MAXNUM;
    if (num == 0) {
        ROS_INFO("NO SIGNAL\n");
    } else {
        for (i = 1; i <= num; i++) {
            if (num >= GREEN) {
                linearGradient.setColorAt(0.2, Qt::green);
            } else if (num >= YELLOW) {
                linearGradient.setColorAt(0.2, Qt::yellow);
            } else {
                linearGradient.setColorAt(0.2, Qt::red);
            }
            painter->setBrush(linearGradient);
            painter->drawRect(x, y, barWidth, barHeight);
            x += barWidth; // move x along
            barHeight += increment; // increase height
            y -= increment; // decrease height
        }
    }
}

void ROS_Signal_Strength::set_topic(const QString & new_value) {
    ROS_INFO("set_topic");
    if (topic_value != new_value) {
        topic_value = new_value;
        if (ros_ready) {
            signal_sub.shutdown();
            signal_sub = nh->subscribe(
                topic_value.toStdString(), // TODO
                1,
                &ROS_Signal_Strength::receive_signal,
                this
            );
        }
        emit topic_changed();
    }
}

QString ROS_Signal_Strength::get_topic() const {
    return topic_value;
}

void ROS_Signal_Strength::
        receive_signal(const std_msgs::Float32::ConstPtr & msg) {
    data = msg->data;
    ROS_INFO("Received signal message");
    update();
}
<commit_msg>Tweak<commit_after>/*
 * Date Started: 11/02/17
 * Original Author: Sajid Anower
 * Editors:
 * Purpose: Widget to display signal strength of the antenna
 * This code is released under the MIT License. Copyright BLUEsat UNSW, 2017
 */
#include "ros_video_components/ros_signal_strength.hpp"

#define RECT_X 0
#define RECT_Y 0
#define RECT_WIDTH RECT_X*40
#define RECT_HEIGHT 150
#define MAXDATA 100
#define MAXNUM 5
#define NUMCOLOR 3
#define GREEN 4
#define YELLOW 2
#define RED 1
#define HASH MAXDATA/MAXNUM
#define TOO_WEAK MAXDATA/20

ROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :
    QQuickPaintedItem(parent),
    topic_value("/rover/signal"),
    ros_ready(false),
    data(50) {}

void ROS_Signal_Strength::setup(ros::NodeHandle * nh) {

    signal_sub = nh->subscribe(
        "/rover/signal", // TODO
        1,
        &ROS_Signal_Strength::receive_signal,
        this
    );
    ros_ready = true;
}

void ROS_Signal_Strength::paint(QPainter * painter) {
    int x = RECT_X;
    int y = RECT_Y;
    int widthV = width(); // RECT_WIDTH;
    int heightV = height(); // RECT_HEIGHT;

    QLinearGradient linearGradient(0, 0, 100, 100);
    int num = 0;
    float hash = HASH;
    if (data >= MAXDATA) {
        num = MAXNUM;
    } else if (data <= TOO_WEAK) {
        num = 0;
        linearGradient.setColorAt(0.0, Qt::white);
        painter->setBrush(linearGradient);
    } else {
        num = (data/hash) + 1;
    }
    // draw the outer main rectangle
    painter->drawRect(x, y, widthV - 1, heightV - 1);

    int i = 0;

    int barWidth = widthV/MAXNUM;
    int barHeight = heightV/MAXNUM;
    y += ((MAXNUM-1) * heightV) /MAXNUM;
    const int increment = heightV/MAXNUM;
    if (num == 0) {
        ROS_INFO("NO SIGNAL\n");
    } else {
        for (i = 1; i <= num; i++) {
            if (num >= GREEN) {
                linearGradient.setColorAt(0.2, Qt::green);
            } else if (num >= YELLOW) {
                linearGradient.setColorAt(0.2, Qt::yellow);
            } else {
                linearGradient.setColorAt(0.2, Qt::red);
            }
            painter->setBrush(linearGradient);
            painter->drawRect(x, y, barWidth, barHeight);
            x += barWidth; // move x along
            barHeight += increment; // increase height
            y -= increment; // decrease height
        }
    }
}

void ROS_Signal_Strength::set_topic(const QString & new_value) {
    ROS_INFO("set_topic");
    if (topic_value != new_value) {
        topic_value = new_value;
        if (ros_ready) {
            signal_sub.shutdown();
            signal_sub = nh->subscribe(
                topic_value.toStdString(), // TODO
                1,
                &ROS_Signal_Strength::receive_signal,
                this
            );
        }
        emit topic_changed();
    }
}

QString ROS_Signal_Strength::get_topic() const {
    return topic_value;
}

void ROS_Signal_Strength::
        receive_signal(const std_msgs::Float32::ConstPtr & msg) {
    data = msg->data;
    ROS_INFO("Received signal message");
    update();
}
<|endoftext|>


<commit_before>
#include "OSDCaps.h"

#include "config.h"

void PoolsMap::dump()
{
  map<string, OSDCap>::iterator it;
  for (it = pools_map.begin(); it != pools_map.end(); ++it) {
    generic_dout(0) << it->first << " -> (" << (int)it->second.allow << "." << (int)it->second.deny << ")" << dendl;
  }
}

void PoolsMap::apply_caps(string& name, int& cap)
{
  map<string, OSDCap>::iterator iter;

  if ((iter = pools_map.find(name)) != pools_map.end()) {
    OSDCap& c = iter->second;
    cap |= c.allow;
    cap &= ~c.deny;
  }
}

void AuidMap::apply_caps(uint64_t uid, int& cap)
{
  map<uint64_t, OSDCap>::iterator iter;

  if ((iter = auid_map.find(uid)) != auid_map.end()) {
    OSDCap& auid_cap = iter->second;
    cap |= auid_cap.allow;
    cap &= ~auid_cap.deny;
  }
}

bool OSDCaps::get_next_token(string s, size_t& pos, string& token)
{
  int start = s.find_first_not_of(" \t", pos);
  int end;

  if (start < 0) {
    return false;
  }

  if (s[start] == '=' || s[start] == ',' || s[start] == ';') {
    end = start + 1;
  } else {
    end = s.find_first_of(";,= \t", start+1);
  }

  if (end < 0) {
    end=s.size();
  }

  token = s.substr(start, end - start);

  pos = end;

  return true;
}

bool OSDCaps::is_rwx(string& token, rwx_t& cap_val)
{
  const char *t = token.c_str();
  int val = 0;

  while (*t) {
    switch (*t) {
    case 'r':
      val |= OSD_POOL_CAP_R;
      break;
    case 'w':
      val |= OSD_POOL_CAP_W;
      break;
    case 'x':
      val |= OSD_POOL_CAP_X;
      break;
    default:
      return false;
    }
    t++;
  }

  cap_val = val;
  return true;
}

bool OSDCaps::parse(bufferlist::iterator& iter)
{
  string s;

  try {
    ::decode(s, iter);

    generic_dout(0) << "decoded caps: " << s << dendl;

    size_t pos = 0;
    string token;
    bool init = true;

    bool op_allow = false;
    bool op_deny = false;
    bool cmd_pool = false;
    bool cmd_uid = false;
    bool any_cmd = false;
    bool got_eq = false;
    list<string> name_list;
    bool last_is_comma = false;
    rwx_t cap_val = 0;

    while (pos < s.size()) {
      if (init) {
        op_allow = false;
        op_deny = false;
        cmd_pool = false;
	cmd_uid = false;
        any_cmd = false;
        got_eq = false;
        last_is_comma = false;
        cap_val = 0;
        init = false;
        name_list.clear();
      }

#define ASSERT_STATE(x) \
do { \
  if (!(x)) { \
       *_dout << "error parsing caps at pos=" << pos << " (" #x ")" << std::endl; \
  } \
} while (0)

      if (get_next_token(s, pos, token)) {
	if (token.compare("*") == 0) { //allow all operations
	  ASSERT_STATE(op_allow);
	  allow_all = true;
	} else if (token.compare("=") == 0) {
          ASSERT_STATE(any_cmd);
          got_eq = true;
        } else if (token.compare("allow") == 0) {
          ASSERT_STATE((!op_allow) && (!op_deny));
          op_allow = true;
        } else if (token.compare("deny") == 0) {
          ASSERT_STATE((!op_allow) && (!op_deny));
          op_deny = true;
        } else if ((token.compare("pools") == 0) ||
                   (token.compare("pool") == 0)) {
          ASSERT_STATE(!cmd_uid && (op_allow || op_deny));
          cmd_pool = true;
          any_cmd = true;
	} else if (token.compare("uid") == 0) {
	  ASSERT_STATE(!cmd_pool && (op_allow || op_deny));
	  any_cmd = true;
	  cmd_uid = true;
        } else if (is_rwx(token, cap_val)) {
          ASSERT_STATE(op_allow || op_deny);
        } else if (token.compare(";") != 0) {
	  ASSERT_STATE(got_eq);
          if (token.compare(",") == 0) {
            ASSERT_STATE(!last_is_comma);
	    last_is_comma = true;
          } else {
            last_is_comma = false;
            name_list.push_back(token);
          }
        }

        if (token.compare(";") == 0 || pos >= s.size()) {
          if (got_eq) {
            ASSERT_STATE(name_list.size() > 0);
            list<string>::iterator iter;
	    CapMap *working_map = &pools_map;
	    if (cmd_uid) working_map = &auid_map;
            for (iter = name_list.begin(); iter != name_list.end(); ++iter) {
              OSDCap& cap = working_map->get_cap(*iter);
              if (op_allow) {
                cap.allow |= cap_val;
              } else {
                cap.deny |= cap_val;
              }
            }
          } else {
            if (op_allow) {
              default_allow |= cap_val;
            } else {
              default_deny |= cap_val;
            }
          }
          init = true;
        }

      }
    }
  } catch (const buffer::error &err) {
    return false;
  }

  generic_dout(0) << "default allow=" << (int)default_allow << " default_deny=" << (int) default_deny << dendl;
  pools_map.dump();
  return true;
}

/**
 * Get the caps given this OSDCaps object for a given pool id
 * and uid (the pool's owner).
 *
 * Basic strategy: chain of permissions: default allow -> auid
 * -> pool -> default_deny.
 *
 * Starting with default allowed caps. Next check if you have caps on
 * the auid and apply, then apply any caps granted on the pool
 * (this lets users give out caps to their auid but keep one pool
 * private, for instance).
 * If these two steps haven't given you explicit caps
 * on the pool, check if you're the pool owner and grant full.
 */
int OSDCaps::get_pool_cap(string& pool_name, uint64_t uid)
{
  if (allow_all)
    return OSD_POOL_CAP_ALL;

  int explicit_cap = default_allow; //explicitly granted caps

  //if the owner is granted permissions on the pool owner's auid, grant them
  auid_map.apply_caps(uid, explicit_cap);

  //check for explicitly granted caps and apply if needed
  pools_map.apply_caps(pool_name, explicit_cap);

  //owner gets full perms by default:
  if (uid != CEPH_AUTH_UID_DEFAULT
      && uid == auid
      && explicit_cap == 0) {
    explicit_cap = OSD_POOL_CAP_ALL;
  }

  explicit_cap &= ~default_deny;

  return explicit_cap;
}

<commit_msg>osd: less chatty in log about caps<commit_after>
#include "OSDCaps.h"

#include "config.h"

void PoolsMap::dump()
{
  map<string, OSDCap>::iterator it;
  for (it = pools_map.begin(); it != pools_map.end(); ++it) {
    generic_dout(0) << it->first << " -> (" << (int)it->second.allow << "." << (int)it->second.deny << ")" << dendl;
  }
}

void PoolsMap::apply_caps(string& name, int& cap)
{
  map<string, OSDCap>::iterator iter;

  if ((iter = pools_map.find(name)) != pools_map.end()) {
    OSDCap& c = iter->second;
    cap |= c.allow;
    cap &= ~c.deny;
  }
}

void AuidMap::apply_caps(uint64_t uid, int& cap)
{
  map<uint64_t, OSDCap>::iterator iter;

  if ((iter = auid_map.find(uid)) != auid_map.end()) {
    OSDCap& auid_cap = iter->second;
    cap |= auid_cap.allow;
    cap &= ~auid_cap.deny;
  }
}

bool OSDCaps::get_next_token(string s, size_t& pos, string& token)
{
  int start = s.find_first_not_of(" \t", pos);
  int end;

  if (start < 0) {
    return false;
  }

  if (s[start] == '=' || s[start] == ',' || s[start] == ';') {
    end = start + 1;
  } else {
    end = s.find_first_of(";,= \t", start+1);
  }

  if (end < 0) {
    end=s.size();
  }

  token = s.substr(start, end - start);

  pos = end;

  return true;
}

bool OSDCaps::is_rwx(string& token, rwx_t& cap_val)
{
  const char *t = token.c_str();
  int val = 0;

  while (*t) {
    switch (*t) {
    case 'r':
      val |= OSD_POOL_CAP_R;
      break;
    case 'w':
      val |= OSD_POOL_CAP_W;
      break;
    case 'x':
      val |= OSD_POOL_CAP_X;
      break;
    default:
      return false;
    }
    t++;
  }

  cap_val = val;
  return true;
}

bool OSDCaps::parse(bufferlist::iterator& iter)
{
  string s;

  try {
    ::decode(s, iter);

    generic_dout(10) << "decoded caps: " << s << dendl;

    size_t pos = 0;
    string token;
    bool init = true;

    bool op_allow = false;
    bool op_deny = false;
    bool cmd_pool = false;
    bool cmd_uid = false;
    bool any_cmd = false;
    bool got_eq = false;
    list<string> name_list;
    bool last_is_comma = false;
    rwx_t cap_val = 0;

    while (pos < s.size()) {
      if (init) {
        op_allow = false;
        op_deny = false;
        cmd_pool = false;
	cmd_uid = false;
        any_cmd = false;
        got_eq = false;
        last_is_comma = false;
        cap_val = 0;
        init = false;
        name_list.clear();
      }

#define ASSERT_STATE(x) \
do { \
  if (!(x)) { \
       *_dout << "error parsing caps at pos=" << pos << " (" #x ")" << std::endl; \
  } \
} while (0)

      if (get_next_token(s, pos, token)) {
	if (token.compare("*") == 0) { //allow all operations
	  ASSERT_STATE(op_allow);
	  allow_all = true;
	} else if (token.compare("=") == 0) {
          ASSERT_STATE(any_cmd);
          got_eq = true;
        } else if (token.compare("allow") == 0) {
          ASSERT_STATE((!op_allow) && (!op_deny));
          op_allow = true;
        } else if (token.compare("deny") == 0) {
          ASSERT_STATE((!op_allow) && (!op_deny));
          op_deny = true;
        } else if ((token.compare("pools") == 0) ||
                   (token.compare("pool") == 0)) {
          ASSERT_STATE(!cmd_uid && (op_allow || op_deny));
          cmd_pool = true;
          any_cmd = true;
	} else if (token.compare("uid") == 0) {
	  ASSERT_STATE(!cmd_pool && (op_allow || op_deny));
	  any_cmd = true;
	  cmd_uid = true;
        } else if (is_rwx(token, cap_val)) {
          ASSERT_STATE(op_allow || op_deny);
        } else if (token.compare(";") != 0) {
	  ASSERT_STATE(got_eq);
          if (token.compare(",") == 0) {
            ASSERT_STATE(!last_is_comma);
	    last_is_comma = true;
          } else {
            last_is_comma = false;
            name_list.push_back(token);
          }
        }

        if (token.compare(";") == 0 || pos >= s.size()) {
          if (got_eq) {
            ASSERT_STATE(name_list.size() > 0);
            list<string>::iterator iter;
	    CapMap *working_map = &pools_map;
	    if (cmd_uid) working_map = &auid_map;
            for (iter = name_list.begin(); iter != name_list.end(); ++iter) {
              OSDCap& cap = working_map->get_cap(*iter);
              if (op_allow) {
                cap.allow |= cap_val;
              } else {
                cap.deny |= cap_val;
              }
            }
          } else {
            if (op_allow) {
              default_allow |= cap_val;
            } else {
              default_deny |= cap_val;
            }
          }
          init = true;
        }

      }
    }
  } catch (const buffer::error &err) {
    return false;
  }

  generic_dout(10) << "default allow=" << (int)default_allow << " default_deny=" << (int) default_deny << dendl;
  pools_map.dump();
  return true;
}

/**
 * Get the caps given this OSDCaps object for a given pool id
 * and uid (the pool's owner).
 *
 * Basic strategy: chain of permissions: default allow -> auid
 * -> pool -> default_deny.
 *
 * Starting with default allowed caps. Next check if you have caps on
 * the auid and apply, then apply any caps granted on the pool
 * (this lets users give out caps to their auid but keep one pool
 * private, for instance).
 * If these two steps haven't given you explicit caps
 * on the pool, check if you're the pool owner and grant full.
 */
int OSDCaps::get_pool_cap(string& pool_name, uint64_t uid)
{
  if (allow_all)
    return OSD_POOL_CAP_ALL;

  int explicit_cap = default_allow; //explicitly granted caps

  //if the owner is granted permissions on the pool owner's auid, grant them
  auid_map.apply_caps(uid, explicit_cap);

  //check for explicitly granted caps and apply if needed
  pools_map.apply_caps(pool_name, explicit_cap);

  //owner gets full perms by default:
  if (uid != CEPH_AUTH_UID_DEFAULT
      && uid == auid
      && explicit_cap == 0) {
    explicit_cap = OSD_POOL_CAP_ALL;
  }

  explicit_cap &= ~default_deny;

  return explicit_cap;
}

<|endoftext|>


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

#include "AccessibleComponentBase.hxx"

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessibleComponentBase::AccessibleComponentBase (void)
{
}

AccessibleComponentBase::~AccessibleComponentBase (void)
{
}

//=====  XAccessibleComponent  ================================================

sal_Bool SAL_CALL AccessibleComponentBase::contains (
        const ::com::sun::star::awt::Point& aPoint)
        throw (::com::sun::star::uno::RuntimeException)
{
    awt::Size aSize (getSize());
    return (aPoint.X >= 0)
        && (aPoint.X < aSize.Width)
        && (aPoint.Y >= 0)
        && (aPoint.Y < aSize.Height);
}

uno::Reference<XAccessible > SAL_CALL
    AccessibleComponentBase::getAccessibleAt (
        const awt::Point& aPoint)
    throw (uno::RuntimeException)
{
    return uno::Reference<XAccessible>();
}

awt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void)
    throw (uno::RuntimeException)
{
    return awt::Rectangle();
}

awt::Point SAL_CALL AccessibleComponentBase::getLocation (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox (getBounds());
    return awt::Point (aBBox.X, aBBox.Y);
}

awt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return awt::Point();
}

::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox (getBounds());
    return awt::Size (aBBox.Width, aBBox.Height);
}

void SAL_CALL AccessibleComponentBase::addFocusListener (
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener)
    throw (::com::sun::star::uno::RuntimeException)
{
    // Ignored
}

void SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener )
    throw (::com::sun::star::uno::RuntimeException)
{
    // Ignored
}

void SAL_CALL AccessibleComponentBase::grabFocus (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    // Ignored
}

sal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return Color(COL_BLACK).GetColor();
}

sal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return Color(COL_WHITE).GetColor();
}

//=====  XAccessibleExtendedComponent  ========================================

::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL
        AccessibleComponentBase::getFont (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return uno::Reference<awt::XFont>();
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("");
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("");
}

//=====  XTypeProvider  ===================================================

uno::Sequence<uno::Type> SAL_CALL
    AccessibleComponentBase::getTypes (void)
    throw (uno::RuntimeException)
{
    // Get list of types from the context base implementation...
    uno::Sequence<uno::Type> aTypeList (2);
    // ...and add the additional type for the component.
    const uno::Type aComponentType =
         ::getCppuType((const uno::Reference<XAccessibleComponent>*)0);
    const uno::Type aExtendedComponentType =
        ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0);
    aTypeList[0] = aComponentType;
    aTypeList[1] = aExtendedComponentType;

    return aTypeList;
}

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

#include "AccessibleComponentBase.hxx"

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessibleComponentBase::AccessibleComponentBase (void)
{
}

AccessibleComponentBase::~AccessibleComponentBase (void)
{
}

//=====  XAccessibleComponent  ================================================

sal_Bool SAL_CALL AccessibleComponentBase::containsPoint (
        const ::com::sun::star::awt::Point& aPoint)
        throw (::com::sun::star::uno::RuntimeException)
{
    awt::Size aSize (getSize());
    return (aPoint.X >= 0)
        && (aPoint.X < aSize.Width)
        && (aPoint.Y >= 0)
        && (aPoint.Y < aSize.Height);
}

uno::Reference<XAccessible > SAL_CALL
    AccessibleComponentBase::getAccessibleAtPoint (
        const awt::Point& aPoint)
    throw (uno::RuntimeException)
{
    return uno::Reference<XAccessible>();
}

awt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void)
    throw (uno::RuntimeException)
{
    return awt::Rectangle();
}

awt::Point SAL_CALL AccessibleComponentBase::getLocation (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox (getBounds());
    return awt::Point (aBBox.X, aBBox.Y);
}

awt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return awt::Point();
}

::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox (getBounds());
    return awt::Size (aBBox.Width, aBBox.Height);
}

void SAL_CALL AccessibleComponentBase::addFocusListener (
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener)
    throw (::com::sun::star::uno::RuntimeException)
{
    // Ignored
}

void SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener )
    throw (::com::sun::star::uno::RuntimeException)
{
    // Ignored
}

void SAL_CALL AccessibleComponentBase::grabFocus (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    // Ignored
}

sal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return Color(COL_BLACK).GetColor();
}

sal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return Color(COL_WHITE).GetColor();
}

//=====  XAccessibleExtendedComponent  ========================================

::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL
        AccessibleComponentBase::getFont (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return uno::Reference<awt::XFont>();
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("");
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("");
}

//=====  XTypeProvider  ===================================================

uno::Sequence<uno::Type> SAL_CALL
    AccessibleComponentBase::getTypes (void)
    throw (uno::RuntimeException)
{
    // Get list of types from the context base implementation...
    uno::Sequence<uno::Type> aTypeList (2);
    // ...and add the additional type for the component.
    const uno::Type aComponentType =
         ::getCppuType((const uno::Reference<XAccessibleComponent>*)0);
    const uno::Type aExtendedComponentType =
        ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0);
    aTypeList[0] = aComponentType;
    aTypeList[1] = aExtendedComponentType;

    return aTypeList;
}

} // end of namespace accessibility
<|endoftext|>


<commit_before>#include "tutorial.h"
#include "joedb/io/main_exception_catcher.h"

#include <chrono>
#include <thread>

/////////////////////////////////////////////////////////////////////////////
static int local_concurrency(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
 tutorial::Local_Client client("local_concurrency.joedb");

 while (true)
 {
  client.transaction([](tutorial::Generic_File_Database &db)
  {
   db.new_person();
  });

  std::cout << "I have just added one person. Total number of persons: ";
  std::cout << client.get_database().get_person_table().get_size() << '\n';
  std::this_thread::sleep_for(std::chrono::seconds(1));
 }

 return 0;
}

/////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
 return joedb::main_exception_catcher(local_concurrency, argc, argv);
}
<commit_msg>fix local_concurrency.cpp<commit_after>#include "tutorial.h"
#include "joedb/io/exception_catcher.h"

#include <chrono>
#include <thread>

/////////////////////////////////////////////////////////////////////////////
static int local_concurrency(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
 tutorial::Local_Client client("local_concurrency.joedb");

 while (true)
 {
  client.transaction([](tutorial::Generic_File_Database &db)
  {
   db.new_person();
  });

  std::cout << "I have just added one person. Total number of persons: ";
  std::cout << client.get_database().get_person_table().get_size() << '\n';
  std::this_thread::sleep_for(std::chrono::seconds(1));
 }

 return 0;
}

/////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
 return joedb::exception_catcher(local_concurrency, argc, argv);
}
<|endoftext|>