<commit_before>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/Client/Contact>
#include "TelepathyQt4/Client/_gen/contact.moc.hpp"

#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/ContactManager>
#include <TelepathyQt4/Client/ReferencedHandles>
#include <TelepathyQt4/Constants>

#include "TelepathyQt4/debug-internal.h"

namespace Telepathy
{
namespace Client
{

struct Contact::Private
{
    Private(ContactManager *manager, const ReferencedHandles &handle)
        : manager(manager), handle(handle), isAvatarTokenKnown(false),
          subscriptionState(PresenceStateNo), publishState(PresenceStateNo)
    {
    }

    ContactManager *manager;
    ReferencedHandles handle;
    QString id;

    QSet<Feature> requestedFeatures;
    QSet<Feature> actualFeatures;

    QString alias;
    bool isAvatarTokenKnown;
    QString avatarToken;
    SimplePresence simplePresence;

    PresenceState subscriptionState;
    PresenceState publishState;
};

ContactManager *Contact::manager() const
{
    return mPriv->manager;
}

ReferencedHandles Contact::handle() const
{
    return mPriv->handle;
}

QString Contact::id() const
{
    return mPriv->id;
}

QSet<Contact::Feature> Contact::requestedFeatures() const
{
    return mPriv->requestedFeatures;
}

QSet<Contact::Feature> Contact::actualFeatures() const
{
    return mPriv->actualFeatures;
}

QString Contact::alias() const
{
    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {
        warning() << "Contact::alias() used on" << this
            << "for which FeatureAlias hasn't been requested - returning id";
        return id();
    }

    return mPriv->alias;
}

bool Contact::isAvatarTokenKnown() const
{
    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {
        warning() << "Contact::isAvatarTokenKnown() used on" << this
            << "for which FeatureAvatarToken hasn't been requested - returning false";
        return false;
    }

    return mPriv->isAvatarTokenKnown;
}

QString Contact::avatarToken() const
{
    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {
        warning() << "Contact::avatarToken() used on" << this
            << "for which FeatureAvatarToken hasn't been requested - returning \"\"";
        return QString("");
    } else if (!isAvatarTokenKnown()) {
        warning() << "Contact::avatarToken() used on" << this
            << "for which the avatar token is not (yet) known - returning \"\"";
        return QString("");
    }

    return mPriv->avatarToken;
}

QString Contact::presenceStatus() const
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        warning() << "Contact::presenceStatus() used on" << this
            << "for which FeatureSimplePresence hasn't been requested - returning \"unknown\"";
        return QString("unknown");
    }

    return mPriv->simplePresence.status;
}

uint Contact::presenceType() const
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        warning() << "Contact::presenceType() used on" << this
            << "for which FeatureSimplePresence hasn't been requested - returning Unknown";
        return ConnectionPresenceTypeUnknown;
    }

    return mPriv->simplePresence.type;
}

QString Contact::presenceMessage() const
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        warning() << "Contact::presenceMessage() used on" << this
            << "for which FeatureSimplePresence hasn't been requested - returning \"\"";
        return QString("");
    }

    return mPriv->simplePresence.statusMessage;
}

Contact::PresenceState Contact::subscriptionState() const
{
    return mPriv->subscriptionState;
}

Contact::PresenceState Contact::publishState() const
{
    return mPriv->publishState;
}

PendingOperation *Contact::requestPresenceSubscription(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->requestContactsPresenceSubscription(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

PendingOperation *Contact::removePresenceSubscription(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->removeContactsPresenceSubscription(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

PendingOperation *Contact::authorizePresencePublication(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->authorizeContactsPresencePublication(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

PendingOperation *Contact::removePresencePublication(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->removeContactsPresencePublication(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

Contact::~Contact()
{
    debug() << "Contact" << id() << "destroyed";
    delete mPriv;
}

Contact::Contact(ContactManager *manager, const ReferencedHandles &handle,
        const QSet<Feature> &requestedFeatures, const QVariantMap &attributes)
    : QObject(0), mPriv(new Private(manager, handle))
{
    augment(requestedFeatures, attributes);
}

void Contact::augment(const QSet<Feature> &requestedFeatures, const QVariantMap &attributes) {
    mPriv->requestedFeatures.unite(requestedFeatures);

    mPriv->id = qdbus_cast<QString>(attributes[TELEPATHY_INTERFACE_CONNECTION "/contact-id"]);

    foreach (Feature feature, requestedFeatures) {
        QString maybeAlias;
        SimplePresence maybePresence;

        switch (feature) {
            case FeatureAlias:
                maybeAlias = qdbus_cast<QString>(attributes.value(
                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_ALIASING "/alias"));

                if (!maybeAlias.isEmpty()) {
                    receiveAlias(maybeAlias);
                } else if (mPriv->alias.isEmpty()) {
                    mPriv->alias = mPriv->id;
                }
                break;

            case FeatureAvatarToken:
                if (attributes.contains(
                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS "/token")) {
                    receiveAvatarToken(qdbus_cast<QString>(attributes.value(
                                    TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS "/token")));
                } else {
                    if (manager()->supportedFeatures().contains(FeatureAvatarToken)) {
                        // AvatarToken being supported but not included in the mapping indicates
                        // that the avatar token is not known - however, the feature is working fine
                        mPriv->actualFeatures.insert(FeatureAvatarToken);
                    }
                    // In either case, the avatar token can't be known
                    mPriv->isAvatarTokenKnown = false;
                    mPriv->avatarToken = "";
                }
                break;

            case FeatureSimplePresence:
                maybePresence = qdbus_cast<SimplePresence>(attributes.value(
                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE "/presence"));

                if (!maybePresence.status.isEmpty()) {
                    receiveSimplePresence(maybePresence);
                } else {
                    mPriv->simplePresence.type = ConnectionPresenceTypeUnknown;
                    mPriv->simplePresence.status = "unknown";
                    mPriv->simplePresence.statusMessage = "";
                }
                break;

            default:
                warning() << "Unknown feature" << feature << "encountered when augmenting Contact";
                break;
        }
    }
}

void Contact::receiveAlias(const QString &alias)
{
    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {
        return;
    }

    mPriv->actualFeatures.insert(FeatureAlias);

    if (mPriv->alias != alias) {
        mPriv->alias = alias;
        emit aliasChanged(alias);
    }
}

void Contact::receiveAvatarToken(const QString &token)
{
    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {
        return;
    }

    mPriv->actualFeatures.insert(FeatureAvatarToken);

    if (!mPriv->isAvatarTokenKnown || mPriv->avatarToken != token) {
        mPriv->isAvatarTokenKnown = true;
        mPriv->avatarToken = token;
        emit avatarTokenChanged(token);
    }
}

void Contact::receiveSimplePresence(const SimplePresence &presence)
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        return;
    }

    mPriv->actualFeatures.insert(FeatureSimplePresence);

    if (mPriv->simplePresence.status != presence.status
            || mPriv->simplePresence.statusMessage != presence.statusMessage) {
        mPriv->simplePresence = presence;
        emit simplePresenceChanged(presenceStatus(), presenceType(), presenceMessage());
    }
}

void Contact::setSubscriptionState(Contact::PresenceState state)
{
    mPriv->subscriptionState = state;
    emit subscriptionStateChanged(state);
}

void Contact::setPublishState(Contact::PresenceState state)
{
    mPriv->publishState = state;
    emit publishStateChanged(state);
}

} // Telepathy::Client
} // Telepathy
<commit_msg>Contact: Make sure subscription/publishStateChanged is not emitted if nothing happened.<commit_after>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/Client/Contact>
#include "TelepathyQt4/Client/_gen/contact.moc.hpp"

#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/ContactManager>
#include <TelepathyQt4/Client/ReferencedHandles>
#include <TelepathyQt4/Constants>

#include "TelepathyQt4/debug-internal.h"

namespace Telepathy
{
namespace Client
{

struct Contact::Private
{
    Private(ContactManager *manager, const ReferencedHandles &handle)
        : manager(manager), handle(handle), isAvatarTokenKnown(false),
          subscriptionState(PresenceStateNo), publishState(PresenceStateNo)
    {
    }

    ContactManager *manager;
    ReferencedHandles handle;
    QString id;

    QSet<Feature> requestedFeatures;
    QSet<Feature> actualFeatures;

    QString alias;
    bool isAvatarTokenKnown;
    QString avatarToken;
    SimplePresence simplePresence;

    PresenceState subscriptionState;
    PresenceState publishState;
};

ContactManager *Contact::manager() const
{
    return mPriv->manager;
}

ReferencedHandles Contact::handle() const
{
    return mPriv->handle;
}

QString Contact::id() const
{
    return mPriv->id;
}

QSet<Contact::Feature> Contact::requestedFeatures() const
{
    return mPriv->requestedFeatures;
}

QSet<Contact::Feature> Contact::actualFeatures() const
{
    return mPriv->actualFeatures;
}

QString Contact::alias() const
{
    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {
        warning() << "Contact::alias() used on" << this
            << "for which FeatureAlias hasn't been requested - returning id";
        return id();
    }

    return mPriv->alias;
}

bool Contact::isAvatarTokenKnown() const
{
    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {
        warning() << "Contact::isAvatarTokenKnown() used on" << this
            << "for which FeatureAvatarToken hasn't been requested - returning false";
        return false;
    }

    return mPriv->isAvatarTokenKnown;
}

QString Contact::avatarToken() const
{
    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {
        warning() << "Contact::avatarToken() used on" << this
            << "for which FeatureAvatarToken hasn't been requested - returning \"\"";
        return QString("");
    } else if (!isAvatarTokenKnown()) {
        warning() << "Contact::avatarToken() used on" << this
            << "for which the avatar token is not (yet) known - returning \"\"";
        return QString("");
    }

    return mPriv->avatarToken;
}

QString Contact::presenceStatus() const
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        warning() << "Contact::presenceStatus() used on" << this
            << "for which FeatureSimplePresence hasn't been requested - returning \"unknown\"";
        return QString("unknown");
    }

    return mPriv->simplePresence.status;
}

uint Contact::presenceType() const
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        warning() << "Contact::presenceType() used on" << this
            << "for which FeatureSimplePresence hasn't been requested - returning Unknown";
        return ConnectionPresenceTypeUnknown;
    }

    return mPriv->simplePresence.type;
}

QString Contact::presenceMessage() const
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        warning() << "Contact::presenceMessage() used on" << this
            << "for which FeatureSimplePresence hasn't been requested - returning \"\"";
        return QString("");
    }

    return mPriv->simplePresence.statusMessage;
}

Contact::PresenceState Contact::subscriptionState() const
{
    return mPriv->subscriptionState;
}

Contact::PresenceState Contact::publishState() const
{
    return mPriv->publishState;
}

PendingOperation *Contact::requestPresenceSubscription(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->requestContactsPresenceSubscription(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

PendingOperation *Contact::removePresenceSubscription(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->removeContactsPresenceSubscription(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

PendingOperation *Contact::authorizePresencePublication(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->authorizeContactsPresencePublication(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

PendingOperation *Contact::removePresencePublication(const QString &message)
{
    QSharedPointer<Contact> self =
        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);
    return mPriv->manager->removeContactsPresencePublication(
            QList<QSharedPointer<Contact> >() << self,
            message);
}

Contact::~Contact()
{
    debug() << "Contact" << id() << "destroyed";
    delete mPriv;
}

Contact::Contact(ContactManager *manager, const ReferencedHandles &handle,
        const QSet<Feature> &requestedFeatures, const QVariantMap &attributes)
    : QObject(0), mPriv(new Private(manager, handle))
{
    augment(requestedFeatures, attributes);
}

void Contact::augment(const QSet<Feature> &requestedFeatures, const QVariantMap &attributes) {
    mPriv->requestedFeatures.unite(requestedFeatures);

    mPriv->id = qdbus_cast<QString>(attributes[TELEPATHY_INTERFACE_CONNECTION "/contact-id"]);

    foreach (Feature feature, requestedFeatures) {
        QString maybeAlias;
        SimplePresence maybePresence;

        switch (feature) {
            case FeatureAlias:
                maybeAlias = qdbus_cast<QString>(attributes.value(
                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_ALIASING "/alias"));

                if (!maybeAlias.isEmpty()) {
                    receiveAlias(maybeAlias);
                } else if (mPriv->alias.isEmpty()) {
                    mPriv->alias = mPriv->id;
                }
                break;

            case FeatureAvatarToken:
                if (attributes.contains(
                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS "/token")) {
                    receiveAvatarToken(qdbus_cast<QString>(attributes.value(
                                    TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS "/token")));
                } else {
                    if (manager()->supportedFeatures().contains(FeatureAvatarToken)) {
                        // AvatarToken being supported but not included in the mapping indicates
                        // that the avatar token is not known - however, the feature is working fine
                        mPriv->actualFeatures.insert(FeatureAvatarToken);
                    }
                    // In either case, the avatar token can't be known
                    mPriv->isAvatarTokenKnown = false;
                    mPriv->avatarToken = "";
                }
                break;

            case FeatureSimplePresence:
                maybePresence = qdbus_cast<SimplePresence>(attributes.value(
                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE "/presence"));

                if (!maybePresence.status.isEmpty()) {
                    receiveSimplePresence(maybePresence);
                } else {
                    mPriv->simplePresence.type = ConnectionPresenceTypeUnknown;
                    mPriv->simplePresence.status = "unknown";
                    mPriv->simplePresence.statusMessage = "";
                }
                break;

            default:
                warning() << "Unknown feature" << feature << "encountered when augmenting Contact";
                break;
        }
    }
}

void Contact::receiveAlias(const QString &alias)
{
    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {
        return;
    }

    mPriv->actualFeatures.insert(FeatureAlias);

    if (mPriv->alias != alias) {
        mPriv->alias = alias;
        emit aliasChanged(alias);
    }
}

void Contact::receiveAvatarToken(const QString &token)
{
    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {
        return;
    }

    mPriv->actualFeatures.insert(FeatureAvatarToken);

    if (!mPriv->isAvatarTokenKnown || mPriv->avatarToken != token) {
        mPriv->isAvatarTokenKnown = true;
        mPriv->avatarToken = token;
        emit avatarTokenChanged(token);
    }
}

void Contact::receiveSimplePresence(const SimplePresence &presence)
{
    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {
        return;
    }

    mPriv->actualFeatures.insert(FeatureSimplePresence);

    if (mPriv->simplePresence.status != presence.status
            || mPriv->simplePresence.statusMessage != presence.statusMessage) {
        mPriv->simplePresence = presence;
        emit simplePresenceChanged(presenceStatus(), presenceType(), presenceMessage());
    }
}

void Contact::setSubscriptionState(Contact::PresenceState state)
{
    if (mPriv->subscriptionState == state) {
        return;
    }
    mPriv->subscriptionState = state;
    emit subscriptionStateChanged(state);
}

void Contact::setPublishState(Contact::PresenceState state)
{
    if (mPriv->publishState == state) {
        return;
    }
    mPriv->publishState = state;
    emit publishStateChanged(state);
}

} // Telepathy::Client
} // Telepathy
<|endoftext|>


<commit_before><commit_msg>Remove qDebug from Issue #41<commit_after><|endoftext|>


<commit_before><commit_msg>Backport crash fixes to Phantom::doExit from master<commit_after><|endoftext|>


<commit_before><commit_msg>Add to CRC_List CRC-3/GSM<commit_after><|endoftext|>


<commit_before><commit_msg>two functions to read plates: fits and par<commit_after><|endoftext|>


<commit_before><commit_msg>tls_wrap: move members to initialization list<commit_after><|endoftext|>


<commit_before><commit_msg>fix potential crash when peers get disconnected when we announce pieces to them<commit_after><|endoftext|>


<commit_before>#include <bashclass/BVariableCall.h>
#include <bashclass/BTypes.h>
#include <iostream>

std::string BVariableCall::getTypeValueAsString() {
    if(!m_variable || !m_variable->hasKnownType()) {
        return BType::UNDEFINED;
    }
    return m_variable->getType()->getValue();
}

void BVariableCall::setExpression(std::shared_ptr<IBCallable> expression) {

    if(!m_variable) {
        std::cerr << "Expression cannot be assigned to the undefined variable "
                  << m_lexicalToken->getValue() << std::endl;
        return;
    }

    // Compare types
    std::string expressionType = expression->getTypeValueAsString();
    std::string variableType = m_variable->getType()->getValue();
    if(!m_variable->hasKnownType()) {
        std::cerr << "Cannot assign expression to an undefined type for variable "
                  << m_variable->getName()->getValue() << std::endl;
    } else if(expressionType == BType::UNDEFINED) {
        std::cerr << "Variable " << m_variable->getName()->getValue()
                  << " cannot be assigned an undefined expression" << std::endl;
    } else if(variableType != BType::TYPE_VALUE_ANY && variableType != expressionType) {
        std::cerr << "Variable " << m_variable->getName()->getValue() << " expects an expression of type "
                  << variableType << " but given " << expressionType << std::endl;
    }

    // Set expression
    m_expression = expression;
}<commit_msg>Enhanced code<commit_after>#include <bashclass/BVariableCall.h>
#include <bashclass/BTypes.h>
#include <iostream>

std::string BVariableCall::getTypeValueAsString() {
    if(!m_variable || !m_variable->hasKnownType()) {
        return BType::UNDEFINED;
    }
    return m_variable->getType()->getValue();
}

void BVariableCall::setExpression(std::shared_ptr<IBCallable> expression) {

    // Set expression
    m_expression = expression;

    // Variable is required to compare the type of the expression
    if(m_variable) {
        // Compare types
        std::string expressionType = expression->getTypeValueAsString();
        std::string variableType = m_variable->getType()->getValue();
        if(!m_variable->hasKnownType()) {
            std::cerr << "Cannot assign expression to an undefined type for variable "
                      << m_variable->getName()->getValue() << std::endl;
        } else if(expressionType == BType::UNDEFINED) {
            std::cerr << "Variable " << m_variable->getName()->getValue()
                      << " cannot be assigned an undefined expression" << std::endl;
        } else if(variableType != BType::TYPE_VALUE_ANY && variableType != expressionType) {
            std::cerr << "Variable " << m_variable->getName()->getValue() << " expects an expression of type "
                      << variableType << " but given " << expressionType << std::endl;
        }
    } else {
        std::cerr << "Expression cannot be evaluated because it is assigned to an undefined variable "
                  << m_lexicalToken->getValue() << std::endl;
    }
}<|endoftext|>


<commit_before>//===-- sanitizer_coverage_mapping.cc -------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Mmap-based implementation of sanitizer coverage.
//
// This is part of the implementation of code coverage that does not require
// __sanitizer_cov_dump() call. Data is stored in 2 files per process.
//
// $pid.sancov.map describes process memory layout in the following text-based
// format:
// <pointer size in bits>  // 1 line, 32 or 64
// <mapping start> <mapping end> <base address> <dso name> // repeated
// ...
// Mapping lines are NOT sorted. This file is updated every time memory layout
// is changed (i.e. in dlopen() and dlclose() interceptors).
//
// $pid.sancov.raw is a binary dump of PC values, sizeof(uptr) each. Again, not
// sorted. This file is extended by 64Kb at a time and mapped into memory. It
// contains one or more 0 words at the end, up to the next 64Kb aligned offset.
//
// To convert these 2 files to the usual .sancov format, run sancov.py rawunpack
// $pid.sancov.raw.
//
//===----------------------------------------------------------------------===//

#include "sanitizer_allocator_internal.h"
#include "sanitizer_libc.h"
#include "sanitizer_procmaps.h"

namespace __sanitizer {

static const uptr kMaxNumberOfModules = 1 << 14;
static const uptr kMaxTextSize = 64 * 1024;

struct CachedMapping {
 public:
  bool NeedsUpdate(uptr pc) {
    int new_pid = internal_getpid();
    if (last_pid == new_pid && pc && pc >= last_range_start &&
        pc < last_range_end)
      return false;
    last_pid = new_pid;
    return true;
  }

  void SetModuleRange(uptr start, uptr end) {
    last_range_start = start;
    last_range_end = end;
  }

 private:
  uptr last_range_start, last_range_end;
  int last_pid;
};

static CachedMapping cached_mapping;
static StaticSpinMutex mapping_mu;

void CovUpdateMapping(uptr caller_pc) {
  if (!common_flags()->coverage || !common_flags()->coverage_direct) return;

  SpinMutexLock l(&mapping_mu);

  if (!cached_mapping.NeedsUpdate(caller_pc))
    return;

  InternalScopedString text(kMaxTextSize);
  InternalScopedBuffer<LoadedModule> modules(kMaxNumberOfModules);
  CHECK(modules.data());
  int n_modules = GetListOfModules(modules.data(), kMaxNumberOfModules,
                                   /* filter */ 0);

  text.append("%d\n", sizeof(uptr) * 8);
  for (int i = 0; i < n_modules; ++i) {
    const char *module_name = StripModuleName(modules[i].full_name());
    for (unsigned j = 0; j < modules[i].n_ranges(); ++j) {
      if (modules[i].address_range_executable(j)) {
        uptr start = modules[i].address_range_start(j);
        uptr end = modules[i].address_range_end(j);
        uptr base = modules[i].base_address();
        text.append("%zx %zx %zx %s\n", start, end, base, module_name);
        if (caller_pc && caller_pc >= start && caller_pc < end)
          cached_mapping.SetModuleRange(start, end);
      }
    }
  }

  int err;
  InternalScopedString tmp_path(64 +
                                internal_strlen(common_flags()->coverage_dir));
  uptr res = internal_snprintf((char *)tmp_path.data(), tmp_path.size(),
                    "%s/%zd.sancov.map.tmp", common_flags()->coverage_dir,
                    internal_getpid());
  CHECK_LE(res, tmp_path.size());
  uptr map_fd = OpenFile(tmp_path.data(), true);
  if (internal_iserror(map_fd, &err)) {
    Report(" Coverage: failed to open %s for writing: %d\n", tmp_path.data(), err);
    Die();
  }

  res = internal_write(map_fd, text.data(), text.length());
  if (internal_iserror(res, &err)) {
    Printf("sancov.map write failed: %d\n", err);
    Die();
  }
  internal_close(map_fd);

  InternalScopedString path(64 + internal_strlen(common_flags()->coverage_dir));
  res = internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.map",
                    common_flags()->coverage_dir, internal_getpid());
  CHECK_LE(res, path.size());
  res = internal_rename(tmp_path.data(), path.data());
  if (internal_iserror(res, &err)) {
    Printf("sancov.map rename failed: %d\n", err);
    Die();
  }
}

}  // namespace __sanitizer
<commit_msg>[asan] Fix line >80 chars.<commit_after>//===-- sanitizer_coverage_mapping.cc -------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Mmap-based implementation of sanitizer coverage.
//
// This is part of the implementation of code coverage that does not require
// __sanitizer_cov_dump() call. Data is stored in 2 files per process.
//
// $pid.sancov.map describes process memory layout in the following text-based
// format:
// <pointer size in bits>  // 1 line, 32 or 64
// <mapping start> <mapping end> <base address> <dso name> // repeated
// ...
// Mapping lines are NOT sorted. This file is updated every time memory layout
// is changed (i.e. in dlopen() and dlclose() interceptors).
//
// $pid.sancov.raw is a binary dump of PC values, sizeof(uptr) each. Again, not
// sorted. This file is extended by 64Kb at a time and mapped into memory. It
// contains one or more 0 words at the end, up to the next 64Kb aligned offset.
//
// To convert these 2 files to the usual .sancov format, run sancov.py rawunpack
// $pid.sancov.raw.
//
//===----------------------------------------------------------------------===//

#include "sanitizer_allocator_internal.h"
#include "sanitizer_libc.h"
#include "sanitizer_procmaps.h"

namespace __sanitizer {

static const uptr kMaxNumberOfModules = 1 << 14;
static const uptr kMaxTextSize = 64 * 1024;

struct CachedMapping {
 public:
  bool NeedsUpdate(uptr pc) {
    int new_pid = internal_getpid();
    if (last_pid == new_pid && pc && pc >= last_range_start &&
        pc < last_range_end)
      return false;
    last_pid = new_pid;
    return true;
  }

  void SetModuleRange(uptr start, uptr end) {
    last_range_start = start;
    last_range_end = end;
  }

 private:
  uptr last_range_start, last_range_end;
  int last_pid;
};

static CachedMapping cached_mapping;
static StaticSpinMutex mapping_mu;

void CovUpdateMapping(uptr caller_pc) {
  if (!common_flags()->coverage || !common_flags()->coverage_direct) return;

  SpinMutexLock l(&mapping_mu);

  if (!cached_mapping.NeedsUpdate(caller_pc))
    return;

  InternalScopedString text(kMaxTextSize);
  InternalScopedBuffer<LoadedModule> modules(kMaxNumberOfModules);
  CHECK(modules.data());
  int n_modules = GetListOfModules(modules.data(), kMaxNumberOfModules,
                                   /* filter */ 0);

  text.append("%d\n", sizeof(uptr) * 8);
  for (int i = 0; i < n_modules; ++i) {
    const char *module_name = StripModuleName(modules[i].full_name());
    for (unsigned j = 0; j < modules[i].n_ranges(); ++j) {
      if (modules[i].address_range_executable(j)) {
        uptr start = modules[i].address_range_start(j);
        uptr end = modules[i].address_range_end(j);
        uptr base = modules[i].base_address();
        text.append("%zx %zx %zx %s\n", start, end, base, module_name);
        if (caller_pc && caller_pc >= start && caller_pc < end)
          cached_mapping.SetModuleRange(start, end);
      }
    }
  }

  int err;
  InternalScopedString tmp_path(64 +
                                internal_strlen(common_flags()->coverage_dir));
  uptr res = internal_snprintf((char *)tmp_path.data(), tmp_path.size(),
                    "%s/%zd.sancov.map.tmp", common_flags()->coverage_dir,
                    internal_getpid());
  CHECK_LE(res, tmp_path.size());
  uptr map_fd = OpenFile(tmp_path.data(), true);
  if (internal_iserror(map_fd, &err)) {
    Report(" Coverage: failed to open %s for writing: %d\n", tmp_path.data(),
           err);
    Die();
  }

  res = internal_write(map_fd, text.data(), text.length());
  if (internal_iserror(res, &err)) {
    Printf("sancov.map write failed: %d\n", err);
    Die();
  }
  internal_close(map_fd);

  InternalScopedString path(64 + internal_strlen(common_flags()->coverage_dir));
  res = internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.map",
                    common_flags()->coverage_dir, internal_getpid());
  CHECK_LE(res, path.size());
  res = internal_rename(tmp_path.data(), path.data());
  if (internal_iserror(res, &err)) {
    Printf("sancov.map rename failed: %d\n", err);
    Die();
  }
}

}  // namespace __sanitizer
<|endoftext|>


<commit_before>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>

using namespace std;

stack<string> lv1;
stack<string> lv2;
stack<string> lv3;

string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
	if(now < temptime) return 0;

	do{
		printf("test\n");
		if(temp.empty()){

		}else{

			switch(templv){
				case 1:
					lv1.push(temp);break;
				case 2:
					lv2.push(temp);break;
				case 3:
					lv3.push(temp);break;
			}
		}
		if(users<usernum)
			cin >>temptime>>templv>>temp;
			users++;
		else
			return 0;
	}while(temptime<=now);

}
int main(int argc, char const *argv[])
{
		int time;
		scanf("%d%d",&usernum,&time);
		for (int i = 0; i < time; ++i)
		{
			read(i);
			cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;

		}

	return 0;
}<commit_msg>update uoj2254<commit_after>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>

using namespace std;

stack<string> lv1;
stack<string> lv2;
stack<string> lv3;

string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
	if(now < temptime) return 0;

	do{
		printf("test\n");
		if(temp.empty()){

		}else{

			switch(templv){
				case 1:
					lv1.push(temp);break;
				case 2:
					lv2.push(temp);break;
				case 3:
					lv3.push(temp);break;
			}
		}
		if(users<usernum){
			cin >>temptime>>templv>>temp;
			users++;}
		else
			return 0;
	}while(temptime<=now);

}
int main(int argc, char const *argv[])
{
		int time;
		scanf("%d%d",&usernum,&time);
		for (int i = 0; i < time; ++i)
		{
			read(i);
			cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;

		}

	return 0;
}<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Memetic-Core-70k-61404");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-POSOnly"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "61404"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Increase version to 1.0.2.6 r6<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Memetic-Core-r6-61404");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-POSOnly"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "61404"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>/*------------------------------------------------------------------------------

    Copyright (c) 2004 Media Development Loan Fund

    This file is part of the LiveSupport project.
    http://livesupport.campware.org/
    To report bugs, send an e-mail to bugs@campware.org

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

    LiveSupport is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

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

    Author   : $Author: maroy $
    Version  : $Revision: 1.2 $
    Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/eventScheduler/src/SchedulerThread.cxx,v $

------------------------------------------------------------------------------*/

/* ============================================================ include files */

#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif

#include "LiveSupport/Core/TimeConversion.h"

#include "SchedulerThread.h"

using namespace LiveSupport::Core;
using namespace LiveSupport::EventScheduler;

/* ===================================================  local data structures */

/* ================================================  local constants & macros */

/* ===============================================  local function prototypes */

/* =============================================================  module code */

/*------------------------------------------------------------------------------
 *  Constructor.
 *----------------------------------------------------------------------------*/
SchedulerThread :: SchedulerThread(
                        Ptr<EventContainerInterface>::Ref   eventContainer,
                        Ptr<time_duration>::Ref             granularity)
                                                                    throw ()
{
    this->eventContainer = eventContainer;
    this->granularity    = granularity;
    this->shouldRun      = true;

    getNextEvent(TimeConversion::now());
}

/*------------------------------------------------------------------------------
 *  Get the next event from the eventContainer
 *----------------------------------------------------------------------------*/
void
SchedulerThread :: getNextEvent(Ptr<ptime>::Ref     when)       throw ()
{
    nextEvent = eventContainer->getNextEvent(when);
    if (nextEvent.get()) {
        nextEventTime = nextEvent->getScheduledTime();
        nextInitTime.reset(new ptime(*nextEventTime
                                   - *granularity
                                   - *nextEvent->maxTimeToInitialize()));
        nextEventEnd.reset(new ptime(*nextEventTime
                                   + *nextEvent->eventLength()));
    }
}

/*------------------------------------------------------------------------------
 *  The main execution body of the thread.
 *----------------------------------------------------------------------------*/
void
SchedulerThread :: nextStep(Ptr<ptime>::Ref     now)            throw ()
{
    if (!nextEvent.get()) {
        return;
    }

    if (imminent(now, nextInitTime)) {
        nextEvent->initialize();
    } else if (imminent(now, nextEventTime)) {
        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventTime
                                                         - *now));
        TimeConversion::sleep(timeLeft);
        nextEvent->start();
    } else if (imminent(now, nextEventEnd)) {
        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventEnd
                                                         - *now));
        TimeConversion::sleep(timeLeft);
        nextEvent->stop();
        nextEvent->deInitialize();
    }
}

/*------------------------------------------------------------------------------
 *  The main execution body of the thread.
 *----------------------------------------------------------------------------*/
void
SchedulerThread :: run(void)                                    throw ()
{
    while (shouldRun) {
        Ptr<ptime>::Ref     start = TimeConversion::now();

        nextStep(start);

        // sleep until the next granularity
        Ptr<ptime>::Ref             end = TimeConversion::now();
        Ptr<time_duration>::Ref     diff(new time_duration(*end - *start));
        if (*diff <= *granularity) {
            Ptr<time_duration>::Ref sleepTime(new time_duration(*granularity
                                                              - *diff));
            TimeConversion::sleep(sleepTime);
        }
    }
}

<commit_msg>minor sanity changes...<commit_after>/*------------------------------------------------------------------------------

    Copyright (c) 2004 Media Development Loan Fund

    This file is part of the LiveSupport project.
    http://livesupport.campware.org/
    To report bugs, send an e-mail to bugs@campware.org

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

    LiveSupport is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

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

    Author   : $Author: maroy $
    Version  : $Revision: 1.3 $
    Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/eventScheduler/src/SchedulerThread.cxx,v $

------------------------------------------------------------------------------*/

/* ============================================================ include files */

#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif

#include "LiveSupport/Core/TimeConversion.h"

#include "SchedulerThread.h"

using namespace LiveSupport::Core;
using namespace LiveSupport::EventScheduler;

/* ===================================================  local data structures */

/* ================================================  local constants & macros */

/* ===============================================  local function prototypes */

/* =============================================================  module code */

/*------------------------------------------------------------------------------
 *  Constructor.
 *----------------------------------------------------------------------------*/
SchedulerThread :: SchedulerThread(
                        Ptr<EventContainerInterface>::Ref   eventContainer,
                        Ptr<time_duration>::Ref             granularity)
                                                                    throw ()
{
    this->eventContainer = eventContainer;
    this->granularity    = granularity;
    this->shouldRun      = false;
}

/*------------------------------------------------------------------------------
 *  Get the next event from the eventContainer
 *----------------------------------------------------------------------------*/
void
SchedulerThread :: getNextEvent(Ptr<ptime>::Ref     when)       throw ()
{
    nextEvent = eventContainer->getNextEvent(when);
    if (nextEvent.get()) {
        nextEventTime = nextEvent->getScheduledTime();
        nextInitTime.reset(new ptime(*nextEventTime
                                   - *granularity
                                   - *nextEvent->maxTimeToInitialize()));
        nextEventEnd.reset(new ptime(*nextEventTime
                                   + *nextEvent->eventLength()));
    }
}

/*------------------------------------------------------------------------------
 *  The main execution body of the thread.
 *----------------------------------------------------------------------------*/
void
SchedulerThread :: nextStep(Ptr<ptime>::Ref     now)            throw ()
{
    if (!nextEvent.get()) {
        return;
    }

    if (imminent(now, nextInitTime)) {
        nextEvent->initialize();
    } else if (imminent(now, nextEventTime)) {
        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventTime
                                                         - *now));
        TimeConversion::sleep(timeLeft);
        nextEvent->start();
    } else if (imminent(now, nextEventEnd)) {
        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventEnd
                                                         - *now));
        TimeConversion::sleep(timeLeft);
        nextEvent->stop();
        nextEvent->deInitialize();
    }
}

/*------------------------------------------------------------------------------
 *  The main execution body of the thread.
 *----------------------------------------------------------------------------*/
void
SchedulerThread :: run(void)                                    throw ()
{
    shouldRun = true;
    getNextEvent(TimeConversion::now());

    while (shouldRun) {
        Ptr<ptime>::Ref     start = TimeConversion::now();

        nextStep(start);

        // sleep until the next granularity
        Ptr<ptime>::Ref             end = TimeConversion::now();
        Ptr<time_duration>::Ref     diff(new time_duration(*end - *start));
        if (*diff <= *granularity) {
            Ptr<time_duration>::Ref sleepTime(new time_duration(*granularity
                                                              - *diff));
            TimeConversion::sleep(sleepTime);
        }
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkDevice.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkPicture.h"
#include "SkPicturePlayback.h"
#include "SkPictureRecord.h"
#include "SkStream.h"

static void usage() {
    SkDebugf("Usage: filter -i inFile [-o outFile] [-t textureDir] [-h|--help]");
    SkDebugf("\n\n");
    SkDebugf("    -i inFile  : file to file.\n");
    SkDebugf("    -o outFile : result of filtering.\n");
    SkDebugf("    -t textureDir : directory in which to place textures.\n");
    SkDebugf("    -h|--help  : Show this help message.\n");
}

// SkFilterRecord allows the filter to manipulate the read in SkPicture
class SkFilterRecord : public SkPictureRecord {
public:
    SkFilterRecord(uint32_t recordFlags, SkDevice* device)
        : INHERITED(recordFlags, device)
        , fTransSkipped(0)
        , fTransTot(0)
        , fScalesSkipped(0)
        , fScalesTot(0) {
    }

    virtual bool translate(SkScalar dx, SkScalar dy) SK_OVERRIDE {
        ++fTransTot;

#if 0
        if (0 == dx && 0 == dy) {
            ++fTransSkipped;
            return true;
        }
#endif

        return INHERITED::translate(dx, dy);
    }

    virtual bool scale(SkScalar sx, SkScalar sy) SK_OVERRIDE {
        ++fScalesTot;

#if 0
        if (SK_Scalar1 == sx && SK_Scalar1 == sy) {
            ++fScalesSkipped;
            return true;
        }
#endif

        return INHERITED::scale(sx, sy);
    }

    void saveImages(const SkString& path) {
        SkTRefArray<SkBitmap>* bitmaps = fBitmapHeap->extractBitmaps();

        if (NULL != bitmaps) {
            for (int i = 0; i < bitmaps->count(); ++i) {
                SkString filename(path);
                if (!path.endsWith("\\")) {
                    filename.append("\\");
                }
                filename.append("image");
                filename.appendS32(i);
                filename.append(".png");

                SkImageEncoder::EncodeFile(filename.c_str(), (*bitmaps)[i],
                                           SkImageEncoder::kPNG_Type, 0);
            }
        }

        bitmaps->unref();
    }

    void report() {
        SkDebugf("%d Trans skipped (out of %d)\n", fTransSkipped, fTransTot);
        SkDebugf("%d Scales skipped (out of %d)\n", fScalesSkipped, fScalesTot);
    }

protected:
    int fTransSkipped;
    int fTransTot;

    int fScalesSkipped;
    int fScalesTot;

private:
    typedef SkPictureRecord INHERITED;
};

// Wrap SkPicture to allow installation of a SkFilterRecord object
class SkFilterPicture : public SkPicture {
public:
    SkFilterPicture(int width, int height, SkPictureRecord* record) {
        fWidth = width;
        fHeight = height;
        fRecord = record;
        SkSafeRef(fRecord);
    }

private:
    typedef SkPicture INHERITED;
};

static bool PNGEncodeBitmapToStream(SkWStream* stream, const SkBitmap& bitmap) {
    return SkImageEncoder::EncodeStream(stream, bitmap, SkImageEncoder::kPNG_Type, 100);
}

// This function is not marked as 'static' so it can be referenced externally
// in the iOS build.
int tool_main(int argc, char** argv) {
    SkGraphics::Init();

    if (argc < 3) {
        usage();
        return -1;
    }

    SkString inFile, outFile, textureDir;

    char* const* stop = argv + argc;
    for (++argv; argv < stop; ++argv) {
        if (strcmp(*argv, "-i") == 0) {
            argv++;
            if (argv < stop && **argv) {
                inFile.set(*argv);
            } else {
                SkDebugf("missing arg for -i\n");
                usage();
                return -1;
            }
        } else if (strcmp(*argv, "-o") == 0) {
            argv++;
            if (argv < stop && **argv) {
                outFile.set(*argv);
            } else {
                SkDebugf("missing arg for -o\n");
                usage();
                return -1;
            }
        } else if (strcmp(*argv, "-t") == 0) {
            argv++;
            if (argv < stop && **argv) {
                textureDir.set(*argv);
            } else {
                SkDebugf("missing arg for -t\n");
                usage();
                return -1;
            }
        } else if (strcmp(*argv, "--help") == 0 || strcmp(*argv, "-h") == 0) {
            usage();
            return 0;
        } else {
            SkDebugf("unknown arg %s\n", *argv);
            usage();
            return -1;
        }
    }

    if (inFile.isEmpty()) {
        usage();
        return -1;
    }

    SkPicture* inPicture = NULL;

    SkFILEStream inStream(inFile.c_str());
    if (inStream.isValid()) {
        inPicture = SkNEW_ARGS(SkPicture,
                               (&inStream, NULL, &SkImageDecoder::DecodeStream));
    }

    if (NULL == inPicture) {
        SkDebugf("Could not read file %s\n", inFile.c_str());
        return -1;
    }

    SkBitmap bm;
    bm.setConfig(SkBitmap::kNo_Config, inPicture->width(), inPicture->height());
    SkAutoTUnref<SkDevice> dev(SkNEW_ARGS(SkDevice, (bm)));

    SkAutoTUnref<SkFilterRecord> filterRecord(SkNEW_ARGS(SkFilterRecord, (0, dev)));

    // Playback the read in picture to the SkFilterRecorder to allow filtering
    filterRecord->beginRecording();
    inPicture->draw(filterRecord);
    filterRecord->endRecording();

    filterRecord->report();

    if (!outFile.isEmpty()) {
        SkFilterPicture outPicture(inPicture->width(), inPicture->height(), filterRecord);
        SkFILEWStream outStream(outFile.c_str());

        outPicture.serialize(&outStream, &PNGEncodeBitmapToStream);
    }

    if (!textureDir.isEmpty()) {
        filterRecord->saveImages(textureDir);
    }

    SkGraphics::Term();

    return 0;
}

#if !defined SK_BUILD_FOR_IOS
int main(int argc, char * const argv[]) {
    return tool_main(argc, (char**) argv);
}
#endif
<commit_msg>Sanitizing source files in Skia_Periodic_House_Keeping<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkDevice.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkPicture.h"
#include "SkPicturePlayback.h"
#include "SkPictureRecord.h"
#include "SkStream.h"

static void usage() {
    SkDebugf("Usage: filter -i inFile [-o outFile] [-t textureDir] [-h|--help]");
    SkDebugf("\n\n");
    SkDebugf("    -i inFile  : file to file.\n");
    SkDebugf("    -o outFile : result of filtering.\n");
    SkDebugf("    -t textureDir : directory in which to place textures.\n");
    SkDebugf("    -h|--help  : Show this help message.\n");
}

// SkFilterRecord allows the filter to manipulate the read in SkPicture
class SkFilterRecord : public SkPictureRecord {
public:
    SkFilterRecord(uint32_t recordFlags, SkDevice* device)
        : INHERITED(recordFlags, device)
        , fTransSkipped(0)
        , fTransTot(0)
        , fScalesSkipped(0)
        , fScalesTot(0) {
    }

    virtual bool translate(SkScalar dx, SkScalar dy) SK_OVERRIDE {
        ++fTransTot;

#if 0
        if (0 == dx && 0 == dy) {
            ++fTransSkipped;
            return true;
        }
#endif

        return INHERITED::translate(dx, dy);
    }

    virtual bool scale(SkScalar sx, SkScalar sy) SK_OVERRIDE {
        ++fScalesTot;

#if 0
        if (SK_Scalar1 == sx && SK_Scalar1 == sy) {
            ++fScalesSkipped;
            return true;
        }
#endif

        return INHERITED::scale(sx, sy);
    }

    void saveImages(const SkString& path) {
        SkTRefArray<SkBitmap>* bitmaps = fBitmapHeap->extractBitmaps();

        if (NULL != bitmaps) {
            for (int i = 0; i < bitmaps->count(); ++i) {
                SkString filename(path);
                if (!path.endsWith("\\")) {
                    filename.append("\\");
                }
                filename.append("image");
                filename.appendS32(i);
                filename.append(".png");

                SkImageEncoder::EncodeFile(filename.c_str(), (*bitmaps)[i],
                                           SkImageEncoder::kPNG_Type, 0);
            }
        }

        bitmaps->unref();
    }

    void report() {
        SkDebugf("%d Trans skipped (out of %d)\n", fTransSkipped, fTransTot);
        SkDebugf("%d Scales skipped (out of %d)\n", fScalesSkipped, fScalesTot);
    }

protected:
    int fTransSkipped;
    int fTransTot;

    int fScalesSkipped;
    int fScalesTot;

private:
    typedef SkPictureRecord INHERITED;
};

// Wrap SkPicture to allow installation of a SkFilterRecord object
class SkFilterPicture : public SkPicture {
public:
    SkFilterPicture(int width, int height, SkPictureRecord* record) {
        fWidth = width;
        fHeight = height;
        fRecord = record;
        SkSafeRef(fRecord);
    }

private:
    typedef SkPicture INHERITED;
};

static bool PNGEncodeBitmapToStream(SkWStream* stream, const SkBitmap& bitmap) {
    return SkImageEncoder::EncodeStream(stream, bitmap, SkImageEncoder::kPNG_Type, 100);
}

// This function is not marked as 'static' so it can be referenced externally
// in the iOS build.
int tool_main(int argc, char** argv) {
    SkGraphics::Init();

    if (argc < 3) {
        usage();
        return -1;
    }

    SkString inFile, outFile, textureDir;

    char* const* stop = argv + argc;
    for (++argv; argv < stop; ++argv) {
        if (strcmp(*argv, "-i") == 0) {
            argv++;
            if (argv < stop && **argv) {
                inFile.set(*argv);
            } else {
                SkDebugf("missing arg for -i\n");
                usage();
                return -1;
            }
        } else if (strcmp(*argv, "-o") == 0) {
            argv++;
            if (argv < stop && **argv) {
                outFile.set(*argv);
            } else {
                SkDebugf("missing arg for -o\n");
                usage();
                return -1;
            }
        } else if (strcmp(*argv, "-t") == 0) {
            argv++;
            if (argv < stop && **argv) {
                textureDir.set(*argv);
            } else {
                SkDebugf("missing arg for -t\n");
                usage();
                return -1;
            }
        } else if (strcmp(*argv, "--help") == 0 || strcmp(*argv, "-h") == 0) {
            usage();
            return 0;
        } else {
            SkDebugf("unknown arg %s\n", *argv);
            usage();
            return -1;
        }
    }

    if (inFile.isEmpty()) {
        usage();
        return -1;
    }

    SkPicture* inPicture = NULL;

    SkFILEStream inStream(inFile.c_str());
    if (inStream.isValid()) {
        inPicture = SkNEW_ARGS(SkPicture,
                               (&inStream, NULL, &SkImageDecoder::DecodeStream));
    }

    if (NULL == inPicture) {
        SkDebugf("Could not read file %s\n", inFile.c_str());
        return -1;
    }

    SkBitmap bm;
    bm.setConfig(SkBitmap::kNo_Config, inPicture->width(), inPicture->height());
    SkAutoTUnref<SkDevice> dev(SkNEW_ARGS(SkDevice, (bm)));

    SkAutoTUnref<SkFilterRecord> filterRecord(SkNEW_ARGS(SkFilterRecord, (0, dev)));

    // Playback the read in picture to the SkFilterRecorder to allow filtering
    filterRecord->beginRecording();
    inPicture->draw(filterRecord);
    filterRecord->endRecording();

    filterRecord->report();

    if (!outFile.isEmpty()) {
        SkFilterPicture outPicture(inPicture->width(), inPicture->height(), filterRecord);
        SkFILEWStream outStream(outFile.c_str());

        outPicture.serialize(&outStream, &PNGEncodeBitmapToStream);
    }

    if (!textureDir.isEmpty()) {
        filterRecord->saveImages(textureDir);
    }

    SkGraphics::Term();

    return 0;
}

#if !defined SK_BUILD_FOR_IOS
int main(int argc, char * const argv[]) {
    return tool_main(argc, (char**) argv);
}
#endif
<|endoftext|>


<commit_before>/******************************************************************************
 ** Filename: clusttool.cpp
 ** Purpose:  Misc. tools for use with the clustering routines
 ** Author:   Dan Johnson
 **
 ** (c) Copyright Hewlett-Packard Company, 1988.
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 *****************************************************************************/

//--------------------------Include Files----------------------------------
#include "clusttool.h"
#include <cmath>
#include "emalloc.h"

using tesseract::TFile;

//---------------Global Data Definitions and Declarations--------------------
#define TOKENSIZE 80         ///< max size of tokens read from an input file
#define QUOTED_TOKENSIZE "79"
#define MAXSAMPLESIZE 65535  ///< max num of dimensions in feature space

/**
 * This routine reads N floats from the specified text file
 * and places them into Buffer.  If Buffer is nullptr, a buffer
 * is created and passed back to the caller.  If EOF is
 * encountered before any floats can be read, nullptr is
 * returned.
 * @param fp open text file to read floats from
 * @param N number of floats to read
 * @param Buffer pointer to buffer to place floats into
 * @return Pointer to buffer holding floats or nullptr if EOF
 * @note Globals: None
 */
static float *ReadNFloats(TFile *fp, uint16_t N, float Buffer[]) {
  const int kMaxLineSize = 1024;
  char line[kMaxLineSize];
  if (fp->FGets(line, kMaxLineSize) == nullptr) {
    tprintf("Hit EOF in ReadNFloats!\n");
    return nullptr;
  }
  bool needs_free = false;

  if (Buffer == nullptr) {
    Buffer = static_cast<float *>(Emalloc(N * sizeof(float)));
    needs_free = true;
  }

  char *startptr = line;
  for (int i = 0; i < N; i++) {
    char *endptr;
    Buffer[i] = strtof(startptr, &endptr);
    if (endptr == startptr) {
      tprintf("Read of %d floats failed!\n", N);
      if (needs_free) Efree(Buffer);
      return nullptr;
    }
    startptr = endptr;
  }
  return Buffer;
}

/**
 * This routine writes a text representation of N floats from
 * an array to a file.  All of the floats are placed on one line.
 * @param File open text file to write N floats to
 * @param N number of floats to write
 * @param Array array of floats to write
 * @return None
 * @note Globals: None
 */
static void WriteNFloats(FILE * File, uint16_t N, float Array[]) {
  for (int i = 0; i < N; i++)
    fprintf(File, " %9.6f", Array[i]);
  fprintf(File, "\n");
}

/**
 * This routine writes to the specified text file a word
 * which represents the ProtoStyle.  It does not append
 * a carriage return to the end.
 * @param File open text file to write prototype style to
 * @param ProtoStyle prototype style to write
 * @return None
 * @note Globals: None
 */
static void WriteProtoStyle(FILE *File, PROTOSTYLE ProtoStyle) {
  switch (ProtoStyle) {
    case spherical:
      fprintf (File, "spherical");
      break;
    case elliptical:
      fprintf (File, "elliptical");
      break;
    case mixed:
      fprintf (File, "mixed");
      break;
    case automatic:
      fprintf (File, "automatic");
      break;
  }
}

/**
 * This routine reads a single integer from the specified
 * file and checks to ensure that it is between 0 and
 * MAXSAMPLESIZE.
 * @param fp open text file to read sample size from
 * @return Sample size
 * @note Globals: None
 */
uint16_t ReadSampleSize(TFile *fp) {
  int SampleSize = 0;

  const int kMaxLineSize = 100;
  char line[kMaxLineSize];
  ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);
  ASSERT_HOST(sscanf(line, "%d", &SampleSize) == 1);
  ASSERT_HOST(SampleSize >= 0 && SampleSize <= MAXSAMPLESIZE);
  return SampleSize;
}

/**
 * This routine reads textual descriptions of sets of parameters
 * which describe the characteristics of feature dimensions.
 *
 * @param fp open text file to read N parameter descriptions from
 * @param N number of parameter descriptions to read
 * @return Pointer to an array of parameter descriptors.
 * @note Globals: None
 */
PARAM_DESC *ReadParamDesc(TFile *fp, uint16_t N) {
  PARAM_DESC *ParamDesc;
  char linear_token[TOKENSIZE], essential_token[TOKENSIZE];

  ParamDesc = static_cast<PARAM_DESC *>(Emalloc (N * sizeof (PARAM_DESC)));
  for (int i = 0; i < N; i++) {
    const int kMaxLineSize = TOKENSIZE * 4;
    char line[kMaxLineSize];
    ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);
    ASSERT_HOST(sscanf(line,
                "%" QUOTED_TOKENSIZE "s %" QUOTED_TOKENSIZE "s %f %f",
                linear_token, essential_token, &ParamDesc[i].Min,
                &ParamDesc[i].Max) == 4);
    ParamDesc[i].Circular = (linear_token[0] == 'c');
    ParamDesc[i].NonEssential = (linear_token[0] != 'e');
    ParamDesc[i].Range = ParamDesc[i].Max - ParamDesc[i].Min;
    ParamDesc[i].HalfRange = ParamDesc[i].Range / 2;
    ParamDesc[i].MidRange = (ParamDesc[i].Max + ParamDesc[i].Min) / 2;
  }
  return (ParamDesc);
}

/**
 * This routine reads a textual description of a prototype from
 * the specified file.
 *
 * @param fp open text file to read prototype from
 * @param N number of dimensions used in prototype
 * @return List of prototypes
 * @note Globals: None
 */
PROTOTYPE *ReadPrototype(TFile *fp, uint16_t N) {
  char sig_token[TOKENSIZE], shape_token[TOKENSIZE];
  PROTOTYPE *Proto;
  int SampleCount;
  int i;

  const int kMaxLineSize = TOKENSIZE * 4;
  char line[kMaxLineSize];
  if (fp->FGets(line, kMaxLineSize) == nullptr ||
      sscanf(line, "%" QUOTED_TOKENSIZE "s %" QUOTED_TOKENSIZE "s %d",
             sig_token, shape_token, &SampleCount) != 3) {
    tprintf("Invalid prototype: %s\n", line);
    return nullptr;
  }
  Proto = static_cast<PROTOTYPE *>(Emalloc(sizeof(PROTOTYPE)));
  Proto->Cluster = nullptr;
  Proto->Significant = (sig_token[0] == 's');

  switch (shape_token[0]) {
    case 's':
      Proto->Style = spherical;
      break;
    case 'e':
      Proto->Style = elliptical;
      break;
    case 'a':
      Proto->Style = automatic;
      break;
    default:
      tprintf("Invalid prototype style specification:%s\n", shape_token);
      Proto->Style = elliptical;
  }

  ASSERT_HOST(SampleCount >= 0);
  Proto->NumSamples = SampleCount;

  Proto->Mean = ReadNFloats(fp, N, nullptr);
  ASSERT_HOST(Proto->Mean != nullptr);

  switch (Proto->Style) {
    case spherical:
      ASSERT_HOST(ReadNFloats(fp, 1, &(Proto->Variance.Spherical)) != nullptr);
      Proto->Magnitude.Spherical =
          1.0 / sqrt(2.0 * M_PI * Proto->Variance.Spherical);
      Proto->TotalMagnitude = pow(Proto->Magnitude.Spherical, static_cast<float>(N));
      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));
      Proto->Weight.Spherical = 1.0 / Proto->Variance.Spherical;
      Proto->Distrib = nullptr;
      break;
    case elliptical:
      Proto->Variance.Elliptical = ReadNFloats(fp, N, nullptr);
      ASSERT_HOST(Proto->Variance.Elliptical != nullptr);
      Proto->Magnitude.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));
      Proto->Weight.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));
      Proto->TotalMagnitude = 1.0;
      for (i = 0; i < N; i++) {
        Proto->Magnitude.Elliptical[i] =
            1.0 / sqrt(2.0 * M_PI * Proto->Variance.Elliptical[i]);
        Proto->Weight.Elliptical[i] = 1.0 / Proto->Variance.Elliptical[i];
        Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];
      }
      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));
      Proto->Distrib = nullptr;
      break;
    default:
      Efree(Proto);
      tprintf("Invalid prototype style\n");
      return nullptr;
  }
  return Proto;
}

/**
 * This routine writes an array of dimension descriptors to
 * the specified text file.
 * @param File open text file to write param descriptors to
 * @param N number of param descriptors to write
 * @param ParamDesc array of param descriptors to write
 * @return None
 * @note Globals: None
 */
void WriteParamDesc(FILE *File, uint16_t N, const PARAM_DESC ParamDesc[]) {
  int i;

  for (i = 0; i < N; i++) {
    if (ParamDesc[i].Circular)
      fprintf (File, "circular ");
    else
      fprintf (File, "linear   ");

    if (ParamDesc[i].NonEssential)
      fprintf (File, "non-essential ");
    else
      fprintf (File, "essential     ");

    fprintf (File, "%10.6f %10.6f\n", ParamDesc[i].Min, ParamDesc[i].Max);
  }
}

/**
 * This routine writes a textual description of a prototype
 * to the specified text file.
 * @param File open text file to write prototype to
 * @param N number of dimensions in feature space
 * @param Proto prototype to write out
 * @return None
 * @note Globals: None
 */
void WritePrototype(FILE *File, uint16_t N, PROTOTYPE *Proto) {
  int i;

  if (Proto->Significant)
    fprintf (File, "significant   ");
  else
    fprintf (File, "insignificant ");
  WriteProtoStyle (File, static_cast<PROTOSTYLE>(Proto->Style));
  fprintf (File, "%6d\n\t", Proto->NumSamples);
  WriteNFloats (File, N, Proto->Mean);
  fprintf (File, "\t");

  switch (Proto->Style) {
    case spherical:
      WriteNFloats (File, 1, &(Proto->Variance.Spherical));
      break;
    case elliptical:
      WriteNFloats (File, N, Proto->Variance.Elliptical);
      break;
    case mixed:
      for (i = 0; i < N; i++)
      switch (Proto->Distrib[i]) {
        case normal:
          fprintf (File, " %9s", "normal");
          break;
        case uniform:
          fprintf (File, " %9s", "uniform");
          break;
        case D_random:
          fprintf (File, " %9s", "random");
          break;
        case DISTRIBUTION_COUNT:
          ASSERT_HOST(!"Distribution count not allowed!");
      }
      fprintf (File, "\n\t");
      WriteNFloats (File, N, Proto->Variance.Elliptical);
  }
}
<commit_msg>clusttool: Replace strtof by std::stringstream<commit_after>/******************************************************************************
 ** Filename: clusttool.cpp
 ** Purpose:  Misc. tools for use with the clustering routines
 ** Author:   Dan Johnson
 **
 ** (c) Copyright Hewlett-Packard Company, 1988.
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 *****************************************************************************/

//--------------------------Include Files----------------------------------
#include "clusttool.h"
#include <cmath>            // for std::isnan
#include <locale>           // for std::locale::classic
#include <sstream>          // for std::stringstream
#include "emalloc.h"

using tesseract::TFile;

//---------------Global Data Definitions and Declarations--------------------
#define TOKENSIZE 80         ///< max size of tokens read from an input file
#define QUOTED_TOKENSIZE "79"
#define MAXSAMPLESIZE 65535  ///< max num of dimensions in feature space

/**
 * This routine reads N floats from the specified text file
 * and places them into Buffer.  If Buffer is nullptr, a buffer
 * is created and passed back to the caller.  If EOF is
 * encountered before any floats can be read, nullptr is
 * returned.
 * @param fp open text file to read floats from
 * @param N number of floats to read
 * @param Buffer pointer to buffer to place floats into
 * @return Pointer to buffer holding floats or nullptr if EOF
 * @note Globals: None
 */
static float *ReadNFloats(TFile *fp, uint16_t N, float Buffer[]) {
  const int kMaxLineSize = 1024;
  char line[kMaxLineSize];
  if (fp->FGets(line, kMaxLineSize) == nullptr) {
    tprintf("Hit EOF in ReadNFloats!\n");
    return nullptr;
  }
  bool needs_free = false;

  if (Buffer == nullptr) {
    Buffer = static_cast<float *>(Emalloc(N * sizeof(float)));
    needs_free = true;
  }

  std::stringstream stream(line);
  // Use "C" locale (needed for float values Buffer[i]).
  stream.imbue(std::locale::classic());
  for (uint16_t i = 0; i < N; i++) {
    float f = NAN;
    stream >> f;
    if (std::isnan(f)) {
      tprintf("Read of %u floats failed!\n", N);
      if (needs_free) Efree(Buffer);
      return nullptr;
    }
    Buffer[i] = f;
  }
  return Buffer;
}

/**
 * This routine writes a text representation of N floats from
 * an array to a file.  All of the floats are placed on one line.
 * @param File open text file to write N floats to
 * @param N number of floats to write
 * @param Array array of floats to write
 * @return None
 * @note Globals: None
 */
static void WriteNFloats(FILE * File, uint16_t N, float Array[]) {
  for (int i = 0; i < N; i++)
    fprintf(File, " %9.6f", Array[i]);
  fprintf(File, "\n");
}

/**
 * This routine writes to the specified text file a word
 * which represents the ProtoStyle.  It does not append
 * a carriage return to the end.
 * @param File open text file to write prototype style to
 * @param ProtoStyle prototype style to write
 * @return None
 * @note Globals: None
 */
static void WriteProtoStyle(FILE *File, PROTOSTYLE ProtoStyle) {
  switch (ProtoStyle) {
    case spherical:
      fprintf (File, "spherical");
      break;
    case elliptical:
      fprintf (File, "elliptical");
      break;
    case mixed:
      fprintf (File, "mixed");
      break;
    case automatic:
      fprintf (File, "automatic");
      break;
  }
}

/**
 * This routine reads a single integer from the specified
 * file and checks to ensure that it is between 0 and
 * MAXSAMPLESIZE.
 * @param fp open text file to read sample size from
 * @return Sample size
 * @note Globals: None
 */
uint16_t ReadSampleSize(TFile *fp) {
  int SampleSize = 0;

  const int kMaxLineSize = 100;
  char line[kMaxLineSize];
  ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);
  ASSERT_HOST(sscanf(line, "%d", &SampleSize) == 1);
  ASSERT_HOST(SampleSize >= 0 && SampleSize <= MAXSAMPLESIZE);
  return SampleSize;
}

/**
 * This routine reads textual descriptions of sets of parameters
 * which describe the characteristics of feature dimensions.
 *
 * @param fp open text file to read N parameter descriptions from
 * @param N number of parameter descriptions to read
 * @return Pointer to an array of parameter descriptors.
 * @note Globals: None
 */
PARAM_DESC *ReadParamDesc(TFile *fp, uint16_t N) {
  PARAM_DESC *ParamDesc;
  char linear_token[TOKENSIZE], essential_token[TOKENSIZE];

  ParamDesc = static_cast<PARAM_DESC *>(Emalloc (N * sizeof (PARAM_DESC)));
  for (int i = 0; i < N; i++) {
    const int kMaxLineSize = TOKENSIZE * 4;
    char line[kMaxLineSize];
    ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);
    ASSERT_HOST(sscanf(line,
                "%" QUOTED_TOKENSIZE "s %" QUOTED_TOKENSIZE "s %f %f",
                linear_token, essential_token, &ParamDesc[i].Min,
                &ParamDesc[i].Max) == 4);
    ParamDesc[i].Circular = (linear_token[0] == 'c');
    ParamDesc[i].NonEssential = (linear_token[0] != 'e');
    ParamDesc[i].Range = ParamDesc[i].Max - ParamDesc[i].Min;
    ParamDesc[i].HalfRange = ParamDesc[i].Range / 2;
    ParamDesc[i].MidRange = (ParamDesc[i].Max + ParamDesc[i].Min) / 2;
  }
  return (ParamDesc);
}

/**
 * This routine reads a textual description of a prototype from
 * the specified file.
 *
 * @param fp open text file to read prototype from
 * @param N number of dimensions used in prototype
 * @return List of prototypes
 * @note Globals: None
 */
PROTOTYPE *ReadPrototype(TFile *fp, uint16_t N) {
  char sig_token[TOKENSIZE], shape_token[TOKENSIZE];
  PROTOTYPE *Proto;
  int SampleCount;
  int i;

  const int kMaxLineSize = TOKENSIZE * 4;
  char line[kMaxLineSize];
  if (fp->FGets(line, kMaxLineSize) == nullptr ||
      sscanf(line, "%" QUOTED_TOKENSIZE "s %" QUOTED_TOKENSIZE "s %d",
             sig_token, shape_token, &SampleCount) != 3) {
    tprintf("Invalid prototype: %s\n", line);
    return nullptr;
  }
  Proto = static_cast<PROTOTYPE *>(Emalloc(sizeof(PROTOTYPE)));
  Proto->Cluster = nullptr;
  Proto->Significant = (sig_token[0] == 's');

  switch (shape_token[0]) {
    case 's':
      Proto->Style = spherical;
      break;
    case 'e':
      Proto->Style = elliptical;
      break;
    case 'a':
      Proto->Style = automatic;
      break;
    default:
      tprintf("Invalid prototype style specification:%s\n", shape_token);
      Proto->Style = elliptical;
  }

  ASSERT_HOST(SampleCount >= 0);
  Proto->NumSamples = SampleCount;

  Proto->Mean = ReadNFloats(fp, N, nullptr);
  ASSERT_HOST(Proto->Mean != nullptr);

  switch (Proto->Style) {
    case spherical:
      ASSERT_HOST(ReadNFloats(fp, 1, &(Proto->Variance.Spherical)) != nullptr);
      Proto->Magnitude.Spherical =
          1.0 / sqrt(2.0 * M_PI * Proto->Variance.Spherical);
      Proto->TotalMagnitude = pow(Proto->Magnitude.Spherical, static_cast<float>(N));
      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));
      Proto->Weight.Spherical = 1.0 / Proto->Variance.Spherical;
      Proto->Distrib = nullptr;
      break;
    case elliptical:
      Proto->Variance.Elliptical = ReadNFloats(fp, N, nullptr);
      ASSERT_HOST(Proto->Variance.Elliptical != nullptr);
      Proto->Magnitude.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));
      Proto->Weight.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));
      Proto->TotalMagnitude = 1.0;
      for (i = 0; i < N; i++) {
        Proto->Magnitude.Elliptical[i] =
            1.0 / sqrt(2.0 * M_PI * Proto->Variance.Elliptical[i]);
        Proto->Weight.Elliptical[i] = 1.0 / Proto->Variance.Elliptical[i];
        Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];
      }
      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));
      Proto->Distrib = nullptr;
      break;
    default:
      Efree(Proto);
      tprintf("Invalid prototype style\n");
      return nullptr;
  }
  return Proto;
}

/**
 * This routine writes an array of dimension descriptors to
 * the specified text file.
 * @param File open text file to write param descriptors to
 * @param N number of param descriptors to write
 * @param ParamDesc array of param descriptors to write
 * @return None
 * @note Globals: None
 */
void WriteParamDesc(FILE *File, uint16_t N, const PARAM_DESC ParamDesc[]) {
  int i;

  for (i = 0; i < N; i++) {
    if (ParamDesc[i].Circular)
      fprintf (File, "circular ");
    else
      fprintf (File, "linear   ");

    if (ParamDesc[i].NonEssential)
      fprintf (File, "non-essential ");
    else
      fprintf (File, "essential     ");

    fprintf (File, "%10.6f %10.6f\n", ParamDesc[i].Min, ParamDesc[i].Max);
  }
}

/**
 * This routine writes a textual description of a prototype
 * to the specified text file.
 * @param File open text file to write prototype to
 * @param N number of dimensions in feature space
 * @param Proto prototype to write out
 * @return None
 * @note Globals: None
 */
void WritePrototype(FILE *File, uint16_t N, PROTOTYPE *Proto) {
  int i;

  if (Proto->Significant)
    fprintf (File, "significant   ");
  else
    fprintf (File, "insignificant ");
  WriteProtoStyle (File, static_cast<PROTOSTYLE>(Proto->Style));
  fprintf (File, "%6d\n\t", Proto->NumSamples);
  WriteNFloats (File, N, Proto->Mean);
  fprintf (File, "\t");

  switch (Proto->Style) {
    case spherical:
      WriteNFloats (File, 1, &(Proto->Variance.Spherical));
      break;
    case elliptical:
      WriteNFloats (File, N, Proto->Variance.Elliptical);
      break;
    case mixed:
      for (i = 0; i < N; i++)
      switch (Proto->Distrib[i]) {
        case normal:
          fprintf (File, " %9s", "normal");
          break;
        case uniform:
          fprintf (File, " %9s", "uniform");
          break;
        case D_random:
          fprintf (File, " %9s", "random");
          break;
        case DISTRIBUTION_COUNT:
          ASSERT_HOST(!"Distribution count not allowed!");
      }
      fprintf (File, "\n\t");
      WriteNFloats (File, N, Proto->Variance.Elliptical);
  }
}
<|endoftext|>


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

#include "servprov.hxx"

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#endif

#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

using namespace ::com::sun::star;

uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(
    const uno::Reference<lang::XMultiServiceFactory> & xSMgr)
throw (uno::Exception)
{
    uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );
    return xService;
}

::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") );

}

uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aServiceNames( 1 );
    aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) );
    return aServiceNames;
}

extern "C" {

void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )
    {
        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),
                                            EmbedServer_getImplementationName(),
                                            EmbedServer_createInstance,
                                            EmbedServer_getSupportedServiceNames() );
    }

    if (xFactory.is())
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );

            uno::Reference< registry::XRegistryKey >  xNewKey;

            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
                                        EmbedServer_getImplementationName() +
                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") )  );

            uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();
            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
                xNewKey->createKey( rServices.getConstArray()[ind] );

            return sal_True;
        }
        catch (registry::InvalidRegistryException &)
                {
                    OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
                }
        }
        return sal_False;
}

} // extern "C"

// Fix strange warnings about some
// ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.
// warning C4505: 'xxx' : unreferenced local function has been removed
#if defined(_MSC_VER)
#pragma warning(disable: 4505)
#endif
<commit_msg>INTEGRATION: CWS obo05 (1.4.8); FILE MERGED 2006/08/28 13:47:49 obo 1.4.8.1: #i53611# diable warnings C4917 and 4555<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: register.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2006-09-25 13:30:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#if defined(_MSC_VER) && (_MSC_VER > 1310)
#pragma warning(disable : 4917 4555)
#endif

#include "servprov.hxx"

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#endif

#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

using namespace ::com::sun::star;

uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(
    const uno::Reference<lang::XMultiServiceFactory> & xSMgr)
throw (uno::Exception)
{
    uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );
    return xService;
}

::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") );

}

uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aServiceNames( 1 );
    aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) );
    return aServiceNames;
}

extern "C" {

void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )
    {
        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),
                                            EmbedServer_getImplementationName(),
                                            EmbedServer_createInstance,
                                            EmbedServer_getSupportedServiceNames() );
    }

    if (xFactory.is())
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );

            uno::Reference< registry::XRegistryKey >  xNewKey;

            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
                                        EmbedServer_getImplementationName() +
                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") )  );

            uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();
            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
                xNewKey->createKey( rServices.getConstArray()[ind] );

            return sal_True;
        }
        catch (registry::InvalidRegistryException &)
                {
                    OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
                }
        }
        return sal_False;
}

} // extern "C"

// Fix strange warnings about some
// ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.
// warning C4505: 'xxx' : unreferenced local function has been removed
#if defined(_MSC_VER)
#pragma warning(disable: 4505)
#endif<|endoftext|>