<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "snippetsparser.h"

#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QLatin1String>
#include <QtCore/QLatin1Char>
#include <QtCore/QVariant>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QDebug>
#include <QtGui/QTextDocument>

using namespace TextEditor;

SnippetsParser::SnippetsParser(const QString &fileName) : m_fileName(fileName)
{}

const QList<CompletionItem> &SnippetsParser::execute(ICompletionCollector *collector,
                                                     const QIcon &icon,
                                                     int order)
{
    if (!QFile::exists(m_fileName)) {
        m_snippets.clear();
    } else {
        const QDateTime &lastModified = QFileInfo(m_fileName).lastModified();
        if (m_lastTrackedFileChange.isNull() || m_lastTrackedFileChange != lastModified) {
            m_snippets.clear();
            QFile file(m_fileName);
            file.open(QIODevice::ReadOnly);
            QXmlStreamReader xml(&file);
            if (xml.readNextStartElement()) {
                if (xml.name() == QLatin1String("snippets")) {
                    while (xml.readNextStartElement()) {
                        if (xml.name() == QLatin1String("snippet")) {
                            TextEditor::CompletionItem item(collector);
                            QString title;
                            QString data;
                            QString description = xml.attributes().value("description").toString();

                            while (!xml.atEnd()) {
                                xml.readNext();
                                if (xml.isEndElement()) {
                                    int i = 0;
                                    while (i < data.size() && data.at(i).isLetterOrNumber())
                                        ++i;
                                    title = data.left(i);
                                    item.text = title;
                                    if (!description.isEmpty()) {
                                        item.text +=  QLatin1Char(' ');
                                        item.text += description;
                                    }
                                    item.data = QVariant::fromValue(data);

                                    QString infotip = data;
                                    while (infotip.size() && infotip.at(infotip.size()-1).isSpace())
                                        infotip.chop(1);
                                    infotip = Qt::escape(infotip);
                                    infotip.replace(QLatin1Char('\n'), QLatin1String("
"));
                                    infotip.replace(QLatin1Char(' '), QLatin1String(" "));
                                    {
                                        QString s = QLatin1String("<nobr>");
                                        int count = 0;
                                        for (int i = 0; i < infotip.count(); ++i) {
                                            if (infotip.at(i) != QChar::ObjectReplacementCharacter) {
                                                s += infotip.at(i);
                                                continue;
                                            }
                                            if (++count % 2) {
                                                s += QLatin1String("");
                                            } else {
                                                if (infotip.at(i-1) == QChar::ObjectReplacementCharacter)
                                                    s += QLatin1String("...");
                                                s += QLatin1String("");
                                            }
                                        }
                                        infotip = s;
                                    }
                                    item.details = infotip;

                                    item.icon = icon;
                                    item.order = order;
                                    item.isSnippet = true;
                                    m_snippets.append(item);
                                    break;
                                }

                                if (xml.isCharacters())
                                    data += xml.text();
                                else if (xml.isStartElement()) {
                                    if (xml.name() != QLatin1String("tab"))
                                        xml.raiseError(QLatin1String("invalid snippets file"));
                                    else {
                                        data += QChar::ObjectReplacementCharacter;
                                        data += xml.readElementText();
                                        data += QChar::ObjectReplacementCharacter;
                                    }
                                }
                            }
                        } else {
                            xml.skipCurrentElement();
                        }
                    }
                } else {
                    xml.skipCurrentElement();
                }
            }
            if (xml.hasError())
                qWarning() << m_fileName << xml.errorString() << xml.lineNumber() << xml.columnNumber();
            file.close();

            m_lastTrackedFileChange = lastModified;
        }
    }

    return m_snippets;
}
<commit_msg>Trim the snippets to avoid adding superfluous newlines at the end<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "snippetsparser.h"

#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QLatin1String>
#include <QtCore/QLatin1Char>
#include <QtCore/QVariant>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QDebug>
#include <QtGui/QTextDocument>

using namespace TextEditor;

SnippetsParser::SnippetsParser(const QString &fileName) : m_fileName(fileName)
{}

const QList<CompletionItem> &SnippetsParser::execute(ICompletionCollector *collector,
                                                     const QIcon &icon,
                                                     int order)
{
    if (!QFile::exists(m_fileName)) {
        m_snippets.clear();
    } else {
        const QDateTime &lastModified = QFileInfo(m_fileName).lastModified();
        if (m_lastTrackedFileChange.isNull() || m_lastTrackedFileChange != lastModified) {
            m_snippets.clear();
            QFile file(m_fileName);
            file.open(QIODevice::ReadOnly);
            QXmlStreamReader xml(&file);
            if (xml.readNextStartElement()) {
                if (xml.name() == QLatin1String("snippets")) {
                    while (xml.readNextStartElement()) {
                        if (xml.name() == QLatin1String("snippet")) {
                            TextEditor::CompletionItem item(collector);
                            QString title;
                            QString data;
                            QString description = xml.attributes().value("description").toString();

                            while (!xml.atEnd()) {
                                xml.readNext();
                                if (xml.isEndElement()) {
                                    int i = 0;
                                    while (i < data.size() && data.at(i).isLetterOrNumber())
                                        ++i;
                                    title = data.left(i);
                                    item.text = title;
                                    if (!description.isEmpty()) {
                                        item.text +=  QLatin1Char(' ');
                                        item.text += description;
                                    }
                                    item.data = QVariant::fromValue(data.trimmed());

                                    QString infotip = data;
                                    while (infotip.size() && infotip.at(infotip.size()-1).isSpace())
                                        infotip.chop(1);
                                    infotip = Qt::escape(infotip);
                                    infotip.replace(QLatin1Char('\n'), QLatin1String("
"));
                                    infotip.replace(QLatin1Char(' '), QLatin1String(" "));
                                    {
                                        QString s = QLatin1String("<nobr>");
                                        int count = 0;
                                        for (int i = 0; i < infotip.count(); ++i) {
                                            if (infotip.at(i) != QChar::ObjectReplacementCharacter) {
                                                s += infotip.at(i);
                                                continue;
                                            }
                                            if (++count % 2) {
                                                s += QLatin1String("");
                                            } else {
                                                if (infotip.at(i-1) == QChar::ObjectReplacementCharacter)
                                                    s += QLatin1String("...");
                                                s += QLatin1String("");
                                            }
                                        }
                                        infotip = s;
                                    }
                                    item.details = infotip;

                                    item.icon = icon;
                                    item.order = order;
                                    item.isSnippet = true;
                                    m_snippets.append(item);
                                    break;
                                }

                                if (xml.isCharacters())
                                    data += xml.text();
                                else if (xml.isStartElement()) {
                                    if (xml.name() != QLatin1String("tab"))
                                        xml.raiseError(QLatin1String("invalid snippets file"));
                                    else {
                                        data += QChar::ObjectReplacementCharacter;
                                        data += xml.readElementText();
                                        data += QChar::ObjectReplacementCharacter;
                                    }
                                }
                            }
                        } else {
                            xml.skipCurrentElement();
                        }
                    }
                } else {
                    xml.skipCurrentElement();
                }
            }
            if (xml.hasError())
                qWarning() << m_fileName << xml.errorString() << xml.lineNumber() << xml.columnNumber();
            file.close();

            m_lastTrackedFileChange = lastModified;
        }
    }

    return m_snippets;
}
<|endoftext|>


<commit_before>
#include "vtrc-transport-tcp.h"

#include "vtrc-protocol-layer.h"
#include "vtrc-transport-stream-impl.h"

namespace vtrc { namespace common {

    namespace basio = boost::asio;
    namespace bip   = boost::asio::ip;
    namespace bsys  = boost::system;

    namespace {
        typedef transport_tcp::socket_type socket_type;
        typedef transport_impl<socket_type, transport_tcp> impl_type;

    }

    struct transport_tcp::impl: public impl_type {

        impl( vtrc::shared_ptr<socket_type> s, const std::string &n )
            :impl_type(s, n)
        { }

        std::string prepare_for_write(const char *data, size_t len)
        {
            return get_parent( )->prepare_for_write( data, len );
        }

        void set_no_delay( bool value )
        {
            get_socket( ).set_option( bip::tcp::no_delay( value ) );
        }

    };

    transport_tcp::transport_tcp( vtrc::shared_ptr<socket_type> sock )
        :impl_(new impl(sock, "tcp"))
    {
        impl_->set_parent( this );
    }

    transport_tcp::~transport_tcp(  )
    {
        delete impl_;
    }

    std::string transport_tcp::name( ) const
    {
        return impl_->name( );
    }

    void transport_tcp::close( )
    {
        impl_->close( );
    }

    void transport_tcp::write( const char *data, size_t length )
    {
        return impl_->write( data, length );
    }

    void transport_tcp::write(const char *data, size_t length,
                       const system_closure_type &success, bool on_send_success)
    {
        impl_->write( data, length, success, on_send_success );
    }

    native_handle_type transport_tcp::native_hanlde( ) const
    {
        native_handle_type nh;
#ifdef _WIN32
        nh.value.win_handle =
            reinterpret_cast<native_handle_type::handle>
                ((SOCKET)impl_->get_socket( ).native_handle( ));
#else
        nh.value.unix_fd = impl_->get_socket( ).native_handle( );
#endif
        return nh;
    }

    void transport_tcp::set_no_delay( bool value )
    {
        impl_->set_no_delay( value );
    }

    std::string transport_tcp::prepare_for_write(const char *data, size_t len)
    {
        return impl_->prepare_for_write( data, len );
    }

    socket_type &transport_tcp::get_socket( )
    {
        return impl_->get_socket( );
    }

    const socket_type &transport_tcp::get_socket( ) const
    {
        return impl_->get_socket( );
    }

}}
<commit_msg>win pipes native handles<commit_after>
#include "vtrc-transport-tcp.h"

#include "vtrc-protocol-layer.h"
#include "vtrc-transport-stream-impl.h"

namespace vtrc { namespace common {

    namespace basio = boost::asio;
    namespace bip   = boost::asio::ip;
    namespace bsys  = boost::system;

    namespace {
        typedef transport_tcp::socket_type socket_type;
        typedef transport_impl<socket_type, transport_tcp> impl_type;

    }

    struct transport_tcp::impl: public impl_type {

        impl( vtrc::shared_ptr<socket_type> s, const std::string &n )
            :impl_type(s, n)
        { }

        std::string prepare_for_write(const char *data, size_t len)
        {
            return get_parent( )->prepare_for_write( data, len );
        }

        void set_no_delay( bool value )
        {
            get_socket( ).set_option( bip::tcp::no_delay( value ) );
        }

    };

    transport_tcp::transport_tcp( vtrc::shared_ptr<socket_type> sock )
        :impl_(new impl(sock, "tcp"))
    {
        impl_->set_parent( this );
    }

    transport_tcp::~transport_tcp(  )
    {
        delete impl_;
    }

    std::string transport_tcp::name( ) const
    {
        return impl_->name( );
    }

    void transport_tcp::close( )
    {
        impl_->close( );
    }

    void transport_tcp::write( const char *data, size_t length )
    {
        return impl_->write( data, length );
    }

    void transport_tcp::write(const char *data, size_t length,
                     const system_closure_type &success, bool on_send_success)
    {
        impl_->write( data, length, success, on_send_success );
    }

    native_handle_type transport_tcp::native_hanlde( ) const
    {
        native_handle_type nh;
#ifdef _WIN32
        nh.value.win_handle =
            reinterpret_cast<native_handle_type::handle>
                ((SOCKET)impl_->get_socket( ).native_handle( ));
#else
        nh.value.unix_fd = impl_->get_socket( ).native_handle( );
#endif
        return nh;
    }

    void transport_tcp::set_no_delay( bool value )
    {
        impl_->set_no_delay( value );
    }

    std::string transport_tcp::prepare_for_write(const char *data, size_t len)
    {
        return impl_->prepare_for_write( data, len );
    }

    socket_type &transport_tcp::get_socket( )
    {
        return impl_->get_socket( );
    }

    const socket_type &transport_tcp::get_socket( ) const
    {
        return impl_->get_socket( );
    }

}}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "context.h"
#include "variablemap.h"
#include <vespa/document/select/value.h>

namespace document::select {

Context::Context()
    : _doc(NULL),
      _docId(NULL),
      _docUpdate(NULL),
      _variables()
{ }

Context::Context(const Document& doc)
    : _doc(&doc),
      _docId(NULL),
      _docUpdate(NULL),
      _variables()
{ }

Context::Context(const DocumentId& docId)
    : _doc(NULL),
      _docId(&docId),
      _docUpdate(NULL),
      _variables()
{ }

Context::Context(const DocumentUpdate& docUpdate)
    : _doc(NULL),
      _docId(NULL),
      _docUpdate(&docUpdate),
      _variables()
{ }

Context::~Context() { }

std::unique_ptr<Value>
Context::getValue(const vespalib::string & value) const {
    VariableMap::const_iterator iter = _variables->find(value);

    if (iter != _variables->end()) {
        return std::make_unique<FloatValue>(iter->second);
    } else {
        return std::make_unique<FloatValue>(0.0);
    }
}

void
Context::setVariableMap(std::unique_ptr<VariableMap> map) {
    _variables = std::move(map);
}

}
<commit_msg>Do not follow the nullptr.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "context.h"
#include "variablemap.h"
#include <vespa/document/select/value.h>

namespace document::select {

Context::Context()
    : _doc(NULL),
      _docId(NULL),
      _docUpdate(NULL),
      _variables()
{ }

Context::Context(const Document& doc)
    : _doc(&doc),
      _docId(NULL),
      _docUpdate(NULL),
      _variables()
{ }

Context::Context(const DocumentId& docId)
    : _doc(NULL),
      _docId(&docId),
      _docUpdate(NULL),
      _variables()
{ }

Context::Context(const DocumentUpdate& docUpdate)
    : _doc(NULL),
      _docId(NULL),
      _docUpdate(&docUpdate),
      _variables()
{ }

Context::~Context() { }

std::unique_ptr<Value>
Context::getValue(const vespalib::string & value) const {
    if (_variables) {
        VariableMap::const_iterator iter = _variables->find(value);

        if (iter != _variables->end()) {
            return std::make_unique<FloatValue>(iter->second);
        } else {
            return std::make_unique<FloatValue>(0.0);
        }
    } else {
        return std::make_unique<FloatValue>(0.0);
    }
}

void
Context::setVariableMap(std::unique_ptr<VariableMap> map) {
    _variables = std::move(map);
}

}
<|endoftext|>


<commit_before>
#include <stdint.h>
#include <x86intrin.h>
#include <math.h>
#include <assert.h>

#include <iostream>
#include <vector>
#include <functional>

#include "histogram.h"

static uint64_t power(uint64_t base, uint64_t exp)
{
    int result = 1;
    while(exp)
    {
        result *= base; exp--;
    }
    return result;
}

static uint64_t valueFromIndex(uint32_t bucketIndex, uint32_t subBucketIndex)
{
    return ((uint64_t) subBucketIndex) << bucketIndex;
}

Histogram::Histogram( uint64_t highestTrackableValue,
                      uint64_t numberOfSignificantValueDigits ) :
    highestTrackableValue{ highestTrackableValue },
    numberOfSignificantValueDigits{ numberOfSignificantValueDigits },
    counts{ 0 },
    totalCount{ 0 }
{
    init();
    counts.resize(countsArrayLength);
}

Histogram::~Histogram()
{
}

void Histogram::init()
{
    auto largestValueWithSingleUnitResolution = 2 * power(10, numberOfSignificantValueDigits);
    auto subBucketCountMagnitude = (uint32_t) ceil(log(largestValueWithSingleUnitResolution)/log(2));

    subBucketHalfCountMagnitude = ((subBucketCountMagnitude > 1) ? subBucketCountMagnitude : 1) - 1;

    subBucketCount     = (uint32_t) pow(2, (subBucketHalfCountMagnitude + 1));
    subBucketHalfCount = subBucketCount / 2;
    subBucketMask      = subBucketCount - 1;

    // determine exponent range needed to support the trackable value with no overflow:
    auto trackableValue = (uint64_t) subBucketCount - 1;
    auto bucketsNeeded = 1;
    while (trackableValue < highestTrackableValue)
    {
        trackableValue <<= 1;
        bucketsNeeded++;
    }
    bucketCount = bucketsNeeded;
    countsArrayLength = (bucketCount + 1) * (subBucketCount / 2);
}

/////////////////// Properties /////////////////////

uint64_t Histogram::getHighestTrackableValue() const
{
    return highestTrackableValue;
}

uint64_t Histogram::getNumberOfSignificantValueDigits() const
{
    return numberOfSignificantValueDigits;
}

uint64_t Histogram::getTotalCount() const
{
    return totalCount;
}

void Histogram::forAll(std::function<void (const uint64_t value, const uint64_t count)> func) const
{
    uint32_t bucketIndex      = 0;
    uint32_t subBucketIndex   = 0;
    uint32_t countToIndex     = 0;
    uint64_t valueAtThisIndex = 0;

    while (countToIndex < totalCount)
    {
        auto countAtThisIndex = getCountAtIndex(bucketIndex, subBucketIndex);
        func(valueAtThisIndex, countAtThisIndex);

        countToIndex += countAtThisIndex;
        subBucketIndex++;

        if (subBucketIndex >= subBucketCount)
        {
            subBucketIndex = subBucketHalfCount;
            bucketIndex++;
        }

        valueAtThisIndex = subBucketIndex << bucketIndex;
    }
}

uint64_t Histogram::getMaxValue() const
{
    uint64_t maxValue = 0;

    forAll([&] (uint64_t value, uint64_t count)
    {
        if (0 != count)
        {
            maxValue = value;
        }
    });

    return maxValue;
}

uint64_t Histogram::getMinValue() const
{
    uint64_t minValue = 0;

    forAll([&] (uint64_t value, uint64_t count)
    {
        if (0 != count && 0 == minValue)
        {
            minValue = value;
        }
    });

    return minValue;
}

double Histogram::getMeanValue() const
{
    uint64_t totalValue = 0;

    forAll([&] (uint64_t value, uint64_t count)
    {
        if (0 != count)
        {
            totalValue += count * medianEquivalentValue(value);
        }
    });

    return (totalValue * 1.0) / totalCount;
}

uint64_t Histogram::getValueAtPercentile(double requestedPercentile) const
{
    auto percentile        = fmin(fmax(requestedPercentile, 0), 100.0);
    auto countAtPercentile = (uint64_t) (((percentile / 100.0) * totalCount) + 0.5);
    countAtPercentile      = (uint64_t) countAtPercentile > 1 ? countAtPercentile : 1;

    auto totalToCurrentIJ = 0UL;
    for (uint32_t i = 0; i < bucketCount; i++)
    {
        uint32_t j = (i == 0) ? 0 : (subBucketCount / 2);
        for (; j < subBucketCount; j++)
        {
            totalToCurrentIJ += getCountAtIndex(i, j);
            if (totalToCurrentIJ >= countAtPercentile)
            {
                return valueFromIndex(i, j);
            }
        }
    }

    return 0;
}

double Histogram::getPercentileAtOrBelowValue(uint64_t value) const
{
    auto totalToCurrentIJ = 0ULL;

    auto targetBucketIndex    = getBucketIndex(value);
    auto targetSubBucketIndex = getSubBucketIndex(value, targetBucketIndex);

    if (targetBucketIndex >= bucketCount)
    {
        return 100.0;
    }

    for (uint32_t i = 0; i <= targetBucketIndex; i++)
    {
        auto j = (i == 0) ? 0 : (subBucketCount / 2);
        auto subBucketCap = (i == targetBucketIndex) ? (targetSubBucketIndex + 1) : subBucketCount;

        for (; j < subBucketCap; j++)
        {
            totalToCurrentIJ += getCountAtIndex(i, j);
        }
    }

    return (100.0 * totalToCurrentIJ) / getTotalCount();
}

uint64_t Histogram::getCountBetweenValues(uint64_t lo, uint64_t hi) const
{
    auto count = 0ULL;

    auto loBucketIndex    = getBucketIndex(lo);
    auto loSubBucketIndex = getSubBucketIndex(lo, loBucketIndex);
    auto valueAtLo        = valueFromIndex(loBucketIndex, loSubBucketIndex);

    auto hiBucketIndex    = getBucketIndex(hi);
    auto hiSubBucketIndex = getSubBucketIndex(hi, hiBucketIndex);
    auto valueAtHi        = valueFromIndex(hiBucketIndex, hiSubBucketIndex);

    if (loBucketIndex >= bucketCount || hiBucketIndex >= bucketCount)
    {
        return 0;
    }

    for (auto i = loBucketIndex; i <= hiBucketIndex; i++)
    {
        auto j = (i == 0) ? 0 : (subBucketCount / 2);
        for (; j < subBucketCount; j++)
        {
            auto valueAtIndex = valueFromIndex(i, j);
            if (valueAtIndex > valueAtHi)
            {
                return count;
            }
            if (valueAtIndex >= valueAtLo)
            {
                count += getCountAtIndex(i, j);
            }
        }
    }

    return count;
}

/////////////////// Index Calcuations /////////////////////

uint32_t Histogram::countsIndexFor(uint64_t value) const
{
    auto bucketIndex    = getBucketIndex(value);
    auto subBucketIndex = getSubBucketIndex(value, bucketIndex);
    auto countsIndex    = countsArrayIndex(bucketIndex, subBucketIndex);

    return countsIndex;
}

uint64_t Histogram::getCountAtValue(uint64_t value) const
{
    return counts[countsIndexFor(value)];
}

uint64_t Histogram::getCountAtIndex(uint32_t bucketIndex, uint32_t subBucketIndex) const
{
    return counts[countsArrayIndex(bucketIndex, subBucketIndex)];
}

uint32_t Histogram::getSubBucketIndex(uint64_t value, uint32_t bucketIndex) const
{
    return (uint32_t)(value >> bucketIndex);
}

uint32_t Histogram::countsArrayIndex(uint32_t bucketIndex, uint32_t subBucketIndex) const
{
    assert(subBucketIndex < subBucketCount);
    assert(bucketIndex < bucketCount);
    assert(bucketIndex == 0 || (subBucketIndex >= subBucketHalfCount));

    // Calculate the index for the first entry in the bucket:
    // (The following is the equivalent of ((bucketIndex + 1) * subBucketHalfCount) ):
    auto bucketBaseIndex = (bucketIndex + 1) << subBucketHalfCountMagnitude;
    // Calculate the offset in the bucket:
    auto offsetInBucket = subBucketIndex - subBucketHalfCount;
    // The following is the equivalent of ((subBucketIndex  - subBucketHalfCount) + bucketBaseIndex;
    return bucketBaseIndex + offsetInBucket;
}

/////////////////// Value Recording /////////////////////

void Histogram::recordValue(uint64_t value)
{
    incrementCountAtIndex(countsIndexFor(value));
    incrementTotalCount();
}

void Histogram::recordValue(uint64_t value, uint64_t expectedInterval)
{
    recordValue(value);
    if (expectedInterval <= 0 || value <= expectedInterval)
    {
        return;
    }
    uint64_t missingValue = value - expectedInterval;
    for (; missingValue >= expectedInterval; missingValue -= expectedInterval)
    {
        recordValue(missingValue);
    }
}

uint32_t Histogram::getBucketIndex(uint64_t value) const
{
    auto pow2ceiling = 64 - __lzcnt64(value | subBucketMask); // smallest power of 2 containing value
    return pow2ceiling - (subBucketHalfCountMagnitude + 1);
}

void Histogram::incrementCountAtIndex(uint32_t countsIndex)
{
    counts[countsIndex]++;
}

void Histogram::incrementTotalCount()
{
    totalCount++;
}

/////////////////// Utility /////////////////////

bool Histogram::valuesAreEquivalent(uint64_t a, uint64_t b) const
{
    return lowestEquivalentValue(a) == lowestEquivalentValue(b);
}

uint64_t Histogram::lowestEquivalentValue(uint64_t value) const
{
    auto bucketIndex    = (uint64_t) getBucketIndex(value);
    auto subBucketIndex = (uint64_t) getSubBucketIndex(value, bucketIndex);

    return subBucketIndex << bucketIndex;
}

uint64_t Histogram::medianEquivalentValue(uint64_t value) const
{
    return lowestEquivalentValue(value) + (sizeOfEquivalentRange(value) >> 1);
}

uint64_t Histogram::sizeOfEquivalentRange(uint64_t value) const
{
    auto bucketIndex    = getBucketIndex(value);
    auto subBucketIndex = getSubBucketIndex(value, bucketIndex);
    uint64_t distanceToNextValue = (1 << ((subBucketIndex >= subBucketCount) ? (bucketIndex + 1) : bucketIndex));
    return distanceToNextValue;
}

void Histogram::print(std::ostream& stream) const
{
    stream << "identityCount: "                  << identityCount <<
            ", highestTrackableValue: "          << highestTrackableValue <<
            ", numberOfSignificantValueDigits: " << numberOfSignificantValueDigits <<
            ", subBucketHalfCountMagnitude: "    << subBucketHalfCountMagnitude <<
            ", subBucketHalfCount: "             << subBucketHalfCount <<
            ", subBucketMask: "                  << subBucketMask <<
            ", subBucketCount: "                 << subBucketCount <<
            ", bucketCount: "                    << bucketCount <<
            ", countsArrayLength: "              << countsArrayLength;
}

std::ostream& operator<< (std::ostream& stream, const Histogram& histogram)
{
    histogram.print(stream);
    return stream;
}<commit_msg>Make method inline<commit_after>
#include <stdint.h>
#include <x86intrin.h>
#include <math.h>
#include <assert.h>

#include <iostream>
#include <vector>
#include <functional>

#include "histogram.h"

static uint64_t power(uint64_t base, uint64_t exp)
{
    int result = 1;
    while(exp)
    {
        result *= base; exp--;
    }
    return result;
}

static inline uint64_t valueFromIndex(uint32_t bucketIndex, uint32_t subBucketIndex)
{
    return ((uint64_t) subBucketIndex) << bucketIndex;
}

Histogram::Histogram( uint64_t highestTrackableValue,
                      uint64_t numberOfSignificantValueDigits ) :
    highestTrackableValue{ highestTrackableValue },
    numberOfSignificantValueDigits{ numberOfSignificantValueDigits },
    counts{ 0 },
    totalCount{ 0 }
{
    init();
    counts.resize(countsArrayLength);
}

Histogram::~Histogram()
{
}

void Histogram::init()
{
    auto largestValueWithSingleUnitResolution = 2 * power(10, numberOfSignificantValueDigits);
    auto subBucketCountMagnitude = (uint32_t) ceil(log(largestValueWithSingleUnitResolution)/log(2));

    subBucketHalfCountMagnitude = ((subBucketCountMagnitude > 1) ? subBucketCountMagnitude : 1) - 1;

    subBucketCount     = (uint32_t) pow(2, (subBucketHalfCountMagnitude + 1));
    subBucketHalfCount = subBucketCount / 2;
    subBucketMask      = subBucketCount - 1;

    // determine exponent range needed to support the trackable value with no overflow:
    auto trackableValue = (uint64_t) subBucketCount - 1;
    auto bucketsNeeded = 1;
    while (trackableValue < highestTrackableValue)
    {
        trackableValue <<= 1;
        bucketsNeeded++;
    }
    bucketCount = bucketsNeeded;
    countsArrayLength = (bucketCount + 1) * (subBucketCount / 2);
}

/////////////////// Properties /////////////////////

uint64_t Histogram::getHighestTrackableValue() const
{
    return highestTrackableValue;
}

uint64_t Histogram::getNumberOfSignificantValueDigits() const
{
    return numberOfSignificantValueDigits;
}

uint64_t Histogram::getTotalCount() const
{
    return totalCount;
}

void Histogram::forAll(std::function<void (const uint64_t value, const uint64_t count)> func) const
{
    uint32_t bucketIndex      = 0;
    uint32_t subBucketIndex   = 0;
    uint32_t countToIndex     = 0;
    uint64_t valueAtThisIndex = 0;

    while (countToIndex < totalCount)
    {
        auto countAtThisIndex = getCountAtIndex(bucketIndex, subBucketIndex);
        func(valueAtThisIndex, countAtThisIndex);

        countToIndex += countAtThisIndex;
        subBucketIndex++;

        if (subBucketIndex >= subBucketCount)
        {
            subBucketIndex = subBucketHalfCount;
            bucketIndex++;
        }

        valueAtThisIndex = subBucketIndex << bucketIndex;
    }
}

uint64_t Histogram::getMaxValue() const
{
    uint64_t maxValue = 0;

    forAll([&] (uint64_t value, uint64_t count)
    {
        if (0 != count)
        {
            maxValue = value;
        }
    });

    return maxValue;
}

uint64_t Histogram::getMinValue() const
{
    uint64_t minValue = 0;

    forAll([&] (uint64_t value, uint64_t count)
    {
        if (0 != count && 0 == minValue)
        {
            minValue = value;
        }
    });

    return minValue;
}

double Histogram::getMeanValue() const
{
    uint64_t totalValue = 0;

    forAll([&] (uint64_t value, uint64_t count)
    {
        if (0 != count)
        {
            totalValue += count * medianEquivalentValue(value);
        }
    });

    return (totalValue * 1.0) / totalCount;
}

uint64_t Histogram::getValueAtPercentile(double requestedPercentile) const
{
    auto percentile        = fmin(fmax(requestedPercentile, 0), 100.0);
    auto countAtPercentile = (uint64_t) (((percentile / 100.0) * totalCount) + 0.5);
    countAtPercentile      = (uint64_t) countAtPercentile > 1 ? countAtPercentile : 1;

    auto totalToCurrentIJ = 0UL;
    for (uint32_t i = 0; i < bucketCount; i++)
    {
        uint32_t j = (i == 0) ? 0 : (subBucketCount / 2);
        for (; j < subBucketCount; j++)
        {
            totalToCurrentIJ += getCountAtIndex(i, j);
            if (totalToCurrentIJ >= countAtPercentile)
            {
                return valueFromIndex(i, j);
            }
        }
    }

    return 0;
}

double Histogram::getPercentileAtOrBelowValue(uint64_t value) const
{
    auto totalToCurrentIJ = 0ULL;

    auto targetBucketIndex    = getBucketIndex(value);
    auto targetSubBucketIndex = getSubBucketIndex(value, targetBucketIndex);

    if (targetBucketIndex >= bucketCount)
    {
        return 100.0;
    }

    for (uint32_t i = 0; i <= targetBucketIndex; i++)
    {
        auto j = (i == 0) ? 0 : (subBucketCount / 2);
        auto subBucketCap = (i == targetBucketIndex) ? (targetSubBucketIndex + 1) : subBucketCount;

        for (; j < subBucketCap; j++)
        {
            totalToCurrentIJ += getCountAtIndex(i, j);
        }
    }

    return (100.0 * totalToCurrentIJ) / getTotalCount();
}

uint64_t Histogram::getCountBetweenValues(uint64_t lo, uint64_t hi) const
{
    auto count = 0ULL;

    auto loBucketIndex    = getBucketIndex(lo);
    auto loSubBucketIndex = getSubBucketIndex(lo, loBucketIndex);
    auto valueAtLo        = valueFromIndex(loBucketIndex, loSubBucketIndex);

    auto hiBucketIndex    = getBucketIndex(hi);
    auto hiSubBucketIndex = getSubBucketIndex(hi, hiBucketIndex);
    auto valueAtHi        = valueFromIndex(hiBucketIndex, hiSubBucketIndex);

    if (loBucketIndex >= bucketCount || hiBucketIndex >= bucketCount)
    {
        return 0;
    }

    for (auto i = loBucketIndex; i <= hiBucketIndex; i++)
    {
        auto j = (i == 0) ? 0 : (subBucketCount / 2);
        for (; j < subBucketCount; j++)
        {
            auto valueAtIndex = valueFromIndex(i, j);
            if (valueAtIndex > valueAtHi)
            {
                return count;
            }
            if (valueAtIndex >= valueAtLo)
            {
                count += getCountAtIndex(i, j);
            }
        }
    }

    return count;
}

/////////////////// Index Calcuations /////////////////////

uint32_t Histogram::countsIndexFor(uint64_t value) const
{
    auto bucketIndex    = getBucketIndex(value);
    auto subBucketIndex = getSubBucketIndex(value, bucketIndex);
    auto countsIndex    = countsArrayIndex(bucketIndex, subBucketIndex);

    return countsIndex;
}

uint64_t Histogram::getCountAtValue(uint64_t value) const
{
    return counts[countsIndexFor(value)];
}

uint64_t Histogram::getCountAtIndex(uint32_t bucketIndex, uint32_t subBucketIndex) const
{
    return counts[countsArrayIndex(bucketIndex, subBucketIndex)];
}

uint32_t Histogram::getSubBucketIndex(uint64_t value, uint32_t bucketIndex) const
{
    return (uint32_t)(value >> bucketIndex);
}

uint32_t Histogram::countsArrayIndex(uint32_t bucketIndex, uint32_t subBucketIndex) const
{
    assert(subBucketIndex < subBucketCount);
    assert(bucketIndex < bucketCount);
    assert(bucketIndex == 0 || (subBucketIndex >= subBucketHalfCount));

    // Calculate the index for the first entry in the bucket:
    // (The following is the equivalent of ((bucketIndex + 1) * subBucketHalfCount) ):
    auto bucketBaseIndex = (bucketIndex + 1) << subBucketHalfCountMagnitude;
    // Calculate the offset in the bucket:
    auto offsetInBucket = subBucketIndex - subBucketHalfCount;
    // The following is the equivalent of ((subBucketIndex  - subBucketHalfCount) + bucketBaseIndex;
    return bucketBaseIndex + offsetInBucket;
}

/////////////////// Value Recording /////////////////////

void Histogram::recordValue(uint64_t value)
{
    incrementCountAtIndex(countsIndexFor(value));
    incrementTotalCount();
}

void Histogram::recordValue(uint64_t value, uint64_t expectedInterval)
{
    recordValue(value);
    if (expectedInterval <= 0 || value <= expectedInterval)
    {
        return;
    }
    uint64_t missingValue = value - expectedInterval;
    for (; missingValue >= expectedInterval; missingValue -= expectedInterval)
    {
        recordValue(missingValue);
    }
}

uint32_t Histogram::getBucketIndex(uint64_t value) const
{
    auto pow2ceiling = 64 - __lzcnt64(value | subBucketMask); // smallest power of 2 containing value
    return pow2ceiling - (subBucketHalfCountMagnitude + 1);
}

void Histogram::incrementCountAtIndex(uint32_t countsIndex)
{
    counts[countsIndex]++;
}

void Histogram::incrementTotalCount()
{
    totalCount++;
}

/////////////////// Utility /////////////////////

bool Histogram::valuesAreEquivalent(uint64_t a, uint64_t b) const
{
    return lowestEquivalentValue(a) == lowestEquivalentValue(b);
}

uint64_t Histogram::lowestEquivalentValue(uint64_t value) const
{
    auto bucketIndex    = (uint64_t) getBucketIndex(value);
    auto subBucketIndex = (uint64_t) getSubBucketIndex(value, bucketIndex);

    return subBucketIndex << bucketIndex;
}

uint64_t Histogram::medianEquivalentValue(uint64_t value) const
{
    return lowestEquivalentValue(value) + (sizeOfEquivalentRange(value) >> 1);
}

uint64_t Histogram::sizeOfEquivalentRange(uint64_t value) const
{
    auto bucketIndex    = getBucketIndex(value);
    auto subBucketIndex = getSubBucketIndex(value, bucketIndex);
    uint64_t distanceToNextValue = (1 << ((subBucketIndex >= subBucketCount) ? (bucketIndex + 1) : bucketIndex));
    return distanceToNextValue;
}

void Histogram::print(std::ostream& stream) const
{
    stream << "identityCount: "                  << identityCount <<
            ", highestTrackableValue: "          << highestTrackableValue <<
            ", numberOfSignificantValueDigits: " << numberOfSignificantValueDigits <<
            ", subBucketHalfCountMagnitude: "    << subBucketHalfCountMagnitude <<
            ", subBucketHalfCount: "             << subBucketHalfCount <<
            ", subBucketMask: "                  << subBucketMask <<
            ", subBucketCount: "                 << subBucketCount <<
            ", bucketCount: "                    << bucketCount <<
            ", countsArrayLength: "              << countsArrayLength;
}

std::ostream& operator<< (std::ostream& stream, const Histogram& histogram)
{
    histogram.print(stream);
    return stream;
}<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

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

ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abc/core.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::_str_to_str_backend

namespace abc {

_str_to_str_backend::_str_to_str_backend(char_range const & crFormat) {
   ABC_TRACE_FN((this, crFormat));

   auto it(crFormat.cbegin());

   // TODO: parse the format string.

   // If we still have any characters, they are garbage.
   if (it != crFormat.cend()) {
      ABC_THROW(syntax_error, (
         SL("unexpected character"), crFormat, unsigned(it - crFormat.cend())
      ));
   }
}

void _str_to_str_backend::write(
   void const * p, size_t cb, text::encoding enc, io::ostream * posOut
) {
   ABC_TRACE_FN((this, p, cb, enc, posOut));

   // TODO: apply format options.
   posOut->write_raw(p, cb, enc);
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::str_base

namespace abc {

str_base::c_str_pointer str_base::c_str() const {
   char_t const * pchData(data());
   if (m_rvpd.get_bNulT()) {
      // The string already includes a NUL terminator, so we can simply return the same array.
      return c_str_pointer(pchData, c_str_pointer::deleter_type(false));
   }
   if (size_t cch = size()) {
      // The string is not empty but lacks a NUL terminator: create a temporary copy that includes a
      // NUL, and return it.
      c_str_pointer psz(
         memory::alloc<char_t const []>(cch + 1 /*NUL*/).release(),
         c_str_pointer::deleter_type(true)
      );
      memory::copy(const_cast<char_t *>(psz.get()), pchData, cch);
      terminate(sizeof(char_t), const_cast<char_t *>(psz.get()) + cch);
      return std::move(psz);
   }
   // The string is empty, so a static NUL character will suffice.
   return c_str_pointer(
      reinterpret_cast<char_t const *>(&smc_chNUL), c_str_pointer::deleter_type(false)
   );
}

} //namespace abc

namespace std {

// Implementation based on the Fowler/Noll/Vo variant 1a (FNV-1a) algorithm. See
// <http://www.isthe.com/chongo/tech/comp/fnv/> for details.
//
// The primes are calculated by src/fnv_hash_basis.py.
size_t hash<abc::str_base>::operator()(abc::str_base const & s) const {
   ABC_TRACE_FN((this, s));

   static_assert(
      sizeof(size_t) * 8 == ABC_HOST_WORD_SIZE,
      "unexpected sizeof(size_t) will break FNV prime/basis selection"
   );
#if ABC_HOST_WORD_SIZE == 16
   size_t const c_iFNVPrime(0x1135);
   size_t const c_iFNVBasis(16635u);
#elif ABC_HOST_WORD_SIZE == 32
   size_t const c_iFNVPrime(0x01000193);
   size_t const c_iFNVBasis(2166136261u);
#elif ABC_HOST_WORD_SIZE == 64
   size_t const c_iFNVPrime(0x00000100000001b3);
   size_t const c_iFNVBasis(14695981039346656037u);
#endif
   size_t iHash(c_iFNVBasis);
   for (auto it(s.cbegin()), itEnd(s.cend()); it != itEnd; ++it) {
      iHash ^= size_t(*it);
      iHash *= c_iFNVPrime;
   }
   return iHash;
}

} //namespace std

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::mstr

namespace abc {

void mstr::set_size(size_t cch) {
   ABC_TRACE_FN((this, cch));

   if (cch != size()) {
      if (cch > capacity()) {
         // Enlarge the item array.
         set_capacity(cch, true);
      }
      m_ci = cch;
   }
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////

<commit_msg>Add missing ABC_TRACE_FN<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

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

ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abc/core.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::_str_to_str_backend

namespace abc {

_str_to_str_backend::_str_to_str_backend(char_range const & crFormat) {
   ABC_TRACE_FN((this, crFormat));

   auto it(crFormat.cbegin());

   // TODO: parse the format string.

   // If we still have any characters, they are garbage.
   if (it != crFormat.cend()) {
      ABC_THROW(syntax_error, (
         SL("unexpected character"), crFormat, unsigned(it - crFormat.cend())
      ));
   }
}

void _str_to_str_backend::write(
   void const * p, size_t cb, text::encoding enc, io::ostream * posOut
) {
   ABC_TRACE_FN((this, p, cb, enc, posOut));

   // TODO: apply format options.
   posOut->write_raw(p, cb, enc);
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::str_base

namespace abc {

str_base::c_str_pointer str_base::c_str() const {
   ABC_TRACE_FN((this));

   char_t const * pchData(data());
   if (m_rvpd.get_bNulT()) {
      // The string already includes a NUL terminator, so we can simply return the same array.
      return c_str_pointer(pchData, c_str_pointer::deleter_type(false));
   }
   if (size_t cch = size()) {
      // The string is not empty but lacks a NUL terminator: create a temporary copy that includes a
      // NUL, and return it.
      c_str_pointer psz(
         memory::alloc<char_t const []>(cch + 1 /*NUL*/).release(),
         c_str_pointer::deleter_type(true)
      );
      memory::copy(const_cast<char_t *>(psz.get()), pchData, cch);
      terminate(sizeof(char_t), const_cast<char_t *>(psz.get()) + cch);
      return std::move(psz);
   }
   // The string is empty, so a static NUL character will suffice.
   return c_str_pointer(
      reinterpret_cast<char_t const *>(&smc_chNUL), c_str_pointer::deleter_type(false)
   );
}

} //namespace abc

namespace std {

// Implementation based on the Fowler/Noll/Vo variant 1a (FNV-1a) algorithm. See
// <http://www.isthe.com/chongo/tech/comp/fnv/> for details.
//
// The primes are calculated by src/fnv_hash_basis.py.
size_t hash<abc::str_base>::operator()(abc::str_base const & s) const {
   ABC_TRACE_FN((this, s));

   static_assert(
      sizeof(size_t) * 8 == ABC_HOST_WORD_SIZE,
      "unexpected sizeof(size_t) will break FNV prime/basis selection"
   );
#if ABC_HOST_WORD_SIZE == 16
   size_t const c_iFNVPrime(0x1135);
   size_t const c_iFNVBasis(16635u);
#elif ABC_HOST_WORD_SIZE == 32
   size_t const c_iFNVPrime(0x01000193);
   size_t const c_iFNVBasis(2166136261u);
#elif ABC_HOST_WORD_SIZE == 64
   size_t const c_iFNVPrime(0x00000100000001b3);
   size_t const c_iFNVBasis(14695981039346656037u);
#endif
   size_t iHash(c_iFNVBasis);
   for (auto it(s.cbegin()), itEnd(s.cend()); it != itEnd; ++it) {
      iHash ^= size_t(*it);
      iHash *= c_iFNVPrime;
   }
   return iHash;
}

} //namespace std

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::mstr

namespace abc {

void mstr::set_size(size_t cch) {
   ABC_TRACE_FN((this, cch));

   if (cch != size()) {
      if (cch > capacity()) {
         // Enlarge the item array.
         set_capacity(cch, true);
      }
      m_ci = cch;
   }
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>#include <fstream>
#include "GoTools/trivariate/SplineVolume.h"
#include "GoTools/trivariate/SmoothVolume.h"
#include "GoTools/geometry/ObjectHeader.h"
#include "GoTools/utils/errormacros.h"
#include "GoTools/trivariate/CoonsPatchVolumeGen.h"

using namespace Go;
using namespace std;

//===========================================================================
//
// File: createCoonsVolume
//
//
// Description:
//
// This program demonstrates the use of the static function 'createCoonsPatch'
// in namespace 'CoonsPatchVolumeGen'.
// The function can create a new 'SplineVolume' representing the coons patch of
// six SplineSurfaces, the six faces of the volume.
//
// This program reads the 6 boundary surfaces needed to create the volume.
// The surfaces must be non-rational, lie in the same space, and have
// conciding edge curves where needed. The input file must satisfy these
// conditions. This is not tested.
// The B-spline bases of the surfaces might be reversed, swapped, have order
// raised, knots inserted and parameter interval rescaled to [0,1].
// The input filename is data/volume_boundaries.g2. This file is created
// by the example program createVolumeBoundaries in compositemodel.
//
// The input surfaces are not all particularily "nice". Thus, a Coons
// approach is not expected to give a very good parameterization. To
// improve the representation, the volume is smoothed, i.e. the inner
// coefficients of the volume is modified to minimize a smoothing
// funcitonal. The volume is written to the file data/volume1.g2 prior to
// smoothing and data/volume1.g2 after smoothing
//
//===========================================================================

int main(int argc, char* argv[] )
{
   // Open input volume file.
  ifstream is("data/volume_boundaries.g2");
  ALWAYS_ERROR_IF(is.bad(), "Bad or no volume input filename");

  // Read surfaces
  vector<shared_ptr<SplineSurface> > bdsf(6);
  for (int ki=0; ki<6; ++ki)
    {
        ObjectHeader head;
	head.read(is);
	bdsf[ki] = shared_ptr<SplineSurface>(new SplineSurface());
	bdsf[ki]->read(is);
    }

  std::cout << "Create Coons volume" << std::endl;

  // Create Coons volume
  shared_ptr<SplineVolume> vol(CoonsPatchVolumeGen::createCoonsPatch(bdsf[0].get(),
								     bdsf[1].get(),
								     bdsf[2].get(),
								     bdsf[3].get(),
								     bdsf[4].get(),
								     bdsf[5].get()));

  // Write to file
  ofstream of1("data/volume1.g2");
  vol->writeStandardHeader(of1);
  vol->write(of1);

  // Write constant parameter surfaces to file. Visualization purpose
  ofstream of1_1("data/volume1_sfs1.g2");
  double start = vol->startparam(0);
  double end = vol->endparam(0);
  double del = (end - start)/(double)4;
  int kj;
  for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol->constParamSurface(start, 0));
      tmp->writeStandardHeader(of1_1);
      tmp->write(of1_1);
    }
  ofstream of1_2("data/volume1_sfs2.g2");
  start = vol->startparam(1);
  end = vol->endparam(1);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol->constParamSurface(start, 1));
      tmp->writeStandardHeader(of1_2);
      tmp->write(of1_2);
    }
  ofstream of1_3("data/volume1_sfs3.g2");
  start = vol->startparam(2);
  end = vol->endparam(2);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol->constParamSurface(start, 2));
      tmp->writeStandardHeader(of1_3);
      tmp->write(of1_3);
    }

  std::cout << "Volume smoothing" << std::endl;

  // Perform smoothing
  SmoothVolume smooth(true);  // Create engine. Do not modify input volume

  // Set all volume coefficients to be free, except those at the boundaries
  int numcfs[3];
  for (int ki=0; ki<3; ++ki)
    numcfs[ki] = vol->numCoefs(ki);
  vector<CoefStatus> coefstat(numcfs[0]*numcfs[1]*numcfs[2], CoefFree);

  // Fix coefficients at the boundaries
  for (int kr=0; kr<numcfs[2]; kr+=(numcfs[2]-1))
    for (int kj=0; kj<numcfs[1]; ++kj)
      for (int ki=0; ki<numcfs[0]; ++ki)
	coefstat[(kj+kr*numcfs[1])*numcfs[0]+ki] = CoefKnown;

  for (int kr=0; kr<numcfs[2]; ++kr)
    for (int kj=0; kj<numcfs[1]; kj+=(numcfs[1]-1))
      for (int ki=0; ki<numcfs[0]; ++ki)
	coefstat[(kj+kr*numcfs[1])*numcfs[0]+ki] = CoefKnown;

  for (int kr=0; kr<numcfs[2]; ++kr)
    for (int kj=0; kj<numcfs[1]; ++kj)
      for (int ki=0; ki<numcfs[0]; ki+=(numcfs[0]-1))
	coefstat[(kj+kr*numcfs[1])*numcfs[0]+ki] = CoefKnown;

  // Attach data to smoothing engine
  smooth.attach(vol, coefstat);

  // Define weights. Only smoothing is performed, thus only smoothing
  // weights are set
  double wgt1 = 1.0e-5; // Minimize expression in 1. derivative. Use with care
  double wgt2 = 0.5;    // Minimize expression in 2. derivative.
  double wgt3 = 1.0 - wgt2 - wgt1; // Minimize expression in 3. derivative.
  smooth.setOptimize(wgt1, wgt2, wgt3);

  // Perform smoothing and fetch result
  shared_ptr<SplineVolume> vol2;
  int status = smooth.equationSolve(vol2);
  std::cout << "Volume smoothing status: " << status << std::endl;

  // Write to file
  ofstream of2("data/volume2.g2");
  vol->writeStandardHeader(of2);
  vol->write(of2);

  // Write constant parameter surfaces to file. Visualization purpose
  ofstream of2_1("data/volume2_sfs1.g2");
  start = vol2->startparam(0);
  end = vol2->endparam(0);
  del = (end - start)/(double)4;
  for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol2->constParamSurface(start, 0));
      tmp->writeStandardHeader(of2_1);
      tmp->write(of2_1);
    }
  ofstream of2_2("data/volume2_sfs2.g2");
  start = vol2->startparam(1);
  end = vol2->endparam(1);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol2->constParamSurface(start, 1));
      tmp->writeStandardHeader(of2_2);
      tmp->write(of2_2);
    }
  ofstream of2_3("data/volume2_sfs3.g2");
  start = vol2->startparam(2);
  end = vol2->endparam(2);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol2->constParamSurface(start, 2));
      tmp->writeStandardHeader(of2_3);
      tmp->write(of2_3);
    }
}

<commit_msg>Modified comments<commit_after>#include <fstream>
#include "GoTools/trivariate/SplineVolume.h"
#include "GoTools/trivariate/SmoothVolume.h"
#include "GoTools/geometry/ObjectHeader.h"
#include "GoTools/utils/errormacros.h"
#include "GoTools/trivariate/CoonsPatchVolumeGen.h"

using namespace Go;
using namespace std;

//===========================================================================
//
// File: createCoonsVolume
//
//
// Description:
//
// This program demonstrates the use of the static function 'createCoonsPatch'
// in namespace 'CoonsPatchVolumeGen'.
// The function can create a new 'SplineVolume' representing the coons patch of
// six SplineSurfaces, the six faces of the volume.
//
// This program reads the 6 boundary surfaces needed to create the volume.
// The surfaces must be non-rational, lie in the same space, and have
// conciding edge curves where needed. The input file must satisfy these
// conditions. This is not tested.
// The B-spline bases of the surfaces might be reversed, swapped, have order
// raised, knots inserted and parameter interval rescaled to [0,1].
// The input filename is data/volume_boundaries.g2. This file is created
// by the example program createVolumeBoundaries in compositemodel.
//
// The input surfaces are not particularily aligned. Thus, a Coons
// approach may not necessarily give a perfect parameterization. To
// improve the representation, the volume is smoothed, i.e. the inner
// coefficients of the volume is modified to minimize a smoothing
// funcitonal. The volume is written to the file data/volume1.g2 prior to
// smoothing and data/volume1.g2 after smoothing
//
//===========================================================================

int main(int argc, char* argv[] )
{
   // Open input volume file.
  ifstream is("data/volume_boundaries.g2");
  ALWAYS_ERROR_IF(is.bad(), "Bad or no volume input filename");

  // Read surfaces
  vector<shared_ptr<SplineSurface> > bdsf(6);
  for (int ki=0; ki<6; ++ki)
    {
        ObjectHeader head;
	head.read(is);
	bdsf[ki] = shared_ptr<SplineSurface>(new SplineSurface());
	bdsf[ki]->read(is);
    }

  std::cout << "Create Coons volume" << std::endl;

  // Create Coons volume. The surfaces are assumed to be ordered in the sequence:
  // umin, umax, vmin, vmax, wmin, wmax
  shared_ptr<SplineVolume> vol(CoonsPatchVolumeGen::createCoonsPatch(bdsf[0].get(),
								     bdsf[1].get(),
								     bdsf[2].get(),
								     bdsf[3].get(),
								     bdsf[4].get(),
								     bdsf[5].get()));

  // Write to file
  ofstream of1("data/volume1.g2");
  vol->writeStandardHeader(of1);
  vol->write(of1);

  // Write constant parameter surfaces to file. Visualization purpose
  ofstream of1_1("data/volume1_sfs1.g2");
  double start = vol->startparam(0);
  double end = vol->endparam(0);
  double del = (end - start)/(double)4;
  int kj;
  for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol->constParamSurface(start, 0));
      tmp->writeStandardHeader(of1_1);
      tmp->write(of1_1);
    }
  ofstream of1_2("data/volume1_sfs2.g2");
  start = vol->startparam(1);
  end = vol->endparam(1);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol->constParamSurface(start, 1));
      tmp->writeStandardHeader(of1_2);
      tmp->write(of1_2);
    }
  ofstream of1_3("data/volume1_sfs3.g2");
  start = vol->startparam(2);
  end = vol->endparam(2);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol->constParamSurface(start, 2));
      tmp->writeStandardHeader(of1_3);
      tmp->write(of1_3);
    }

  std::cout << "Volume smoothing" << std::endl;

  // Perform smoothing
  SmoothVolume smooth(true);  // Create engine. Do not modify input volume

  // Set all volume coefficients to be free, except those at the boundaries
  int numcfs[3];
  for (int ki=0; ki<3; ++ki)
    numcfs[ki] = vol->numCoefs(ki);
  vector<CoefStatus> coefstat(numcfs[0]*numcfs[1]*numcfs[2], CoefFree);

  // Fix coefficients at the boundaries
  for (int kr=0; kr<numcfs[2]; kr+=(numcfs[2]-1))
    for (int kj=0; kj<numcfs[1]; ++kj)
      for (int ki=0; ki<numcfs[0]; ++ki)
	coefstat[(kj+kr*numcfs[1])*numcfs[0]+ki] = CoefKnown;

  for (int kr=0; kr<numcfs[2]; ++kr)
    for (int kj=0; kj<numcfs[1]; kj+=(numcfs[1]-1))
      for (int ki=0; ki<numcfs[0]; ++ki)
	coefstat[(kj+kr*numcfs[1])*numcfs[0]+ki] = CoefKnown;

  for (int kr=0; kr<numcfs[2]; ++kr)
    for (int kj=0; kj<numcfs[1]; ++kj)
      for (int ki=0; ki<numcfs[0]; ki+=(numcfs[0]-1))
	coefstat[(kj+kr*numcfs[1])*numcfs[0]+ki] = CoefKnown;

  // Attach data to smoothing engine
  smooth.attach(vol, coefstat);

  // Define weights. Only smoothing is performed, thus only smoothing
  // weights are set
  double wgt1 = 1.0e-5; // Minimize expression in 1. derivative. Use with care
  double wgt2 = 0.5;    // Minimize expression in 2. derivative.
  double wgt3 = 1.0 - wgt2 - wgt1; // Minimize expression in 3. derivative.
  smooth.setOptimize(wgt1, wgt2, wgt3);

  // Perform smoothing and fetch result
  shared_ptr<SplineVolume> vol2;
  int status = smooth.equationSolve(vol2);
  std::cout << "Volume smoothing status: " << status << std::endl;

  // Write to file
  ofstream of2("data/volume2.g2");
  vol->writeStandardHeader(of2);
  vol->write(of2);

  // Write constant parameter surfaces to file. Visualization purpose
  ofstream of2_1("data/volume2_sfs1.g2");
  start = vol2->startparam(0);
  end = vol2->endparam(0);
  del = (end - start)/(double)4;
  for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol2->constParamSurface(start, 0));
      tmp->writeStandardHeader(of2_1);
      tmp->write(of2_1);
    }
  ofstream of2_2("data/volume2_sfs2.g2");
  start = vol2->startparam(1);
  end = vol2->endparam(1);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol2->constParamSurface(start, 1));
      tmp->writeStandardHeader(of2_2);
      tmp->write(of2_2);
    }
  ofstream of2_3("data/volume2_sfs3.g2");
  start = vol2->startparam(2);
  end = vol2->endparam(2);
  del = (end - start)/(double)4;
   for (kj=0; kj<5; ++kj, start+=del)
    {
      shared_ptr<SplineSurface> tmp(vol2->constParamSurface(start, 2));
      tmp->writeStandardHeader(of2_3);
      tmp->write(of2_3);
    }
}

<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "DSHelper.h"

#include "../base/Exception.h"
#include "../base/Logger.h"

#include <stdio.h>
#include <oleauto.h>

#include <string>

using namespace std;

namespace avg {

#pragma warning(disable : 4995)
HRESULT AddGraphToRot(IUnknown *pUnkGraph, DWORD *pdwRegister)
{
    IMoniker * pMoniker;
    IRunningObjectTable *pROT;
    WCHAR wsz[128];
    HRESULT hr;

    if (!pUnkGraph || !pdwRegister) {
        return E_POINTER;
    }

    if (FAILED(GetRunningObjectTable(0, &pROT))) {
        return E_FAIL;
    }

    hr = swprintf(wsz, NUMELMS(wsz), L"FilterGraph %08x pid %08x\0",
            (DWORD_PTR)pUnkGraph, GetCurrentProcessId());

    hr = CreateItemMoniker(L"!", wsz, &pMoniker);
    if (SUCCEEDED(hr)) {
        hr = pROT->Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, pUnkGraph, pMoniker,
                pdwRegister);
        pMoniker->Release();
    }

    pROT->Release();
    return hr;
}

void RemoveGraphFromRot(DWORD pdwRegister)
{
    IRunningObjectTable *pROT;

    if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) {
        pROT->Revoke(pdwRegister);
        pROT->Release();
    }
}

string getStringProp(IPropertyBag *pPropBag, LPCOLESTR pszPropName)
{
    VARIANT varName;
    VariantInit(&varName);
    HRESULT hr = pPropBag->Read(pszPropName, &varName, 0);
    if (FAILED(hr)) {
        return "";
    }
//    checkForDShowError(hr, string("DSHelper::getStringProp(")+pszPropName+")::Read PropBag");

    string s;
    int lenWStr = SysStringLen(varName.bstrVal);
    int lenAStr = WideCharToMultiByte(CP_ACP, 0, varName.bstrVal, lenWStr, 0, 0, NULL, NULL);
    if (lenAStr > 0) {
        char* pAStr = new char[lenAStr + 1];
        WideCharToMultiByte(CP_ACP, 0, varName.bstrVal, lenWStr, pAStr, lenAStr, NULL, NULL);
        pAStr[lenAStr] = 0;
        s = pAStr;
        delete[] pAStr;
    }

    VariantClear(&varName);
    return s;
}

PixelFormat mediaSubtypeToPixelFormat(const GUID& subtype)
{
    if (subtype == MEDIASUBTYPE_RGB24) {
        return B8G8R8;
    } else if (subtype == MEDIASUBTYPE_RGB32) {
        return B8G8R8X8;
    } else if (subtype == MEDIASUBTYPE_RGB8) {
        return I8;
    } else if (subtype == MEDIASUBTYPE_UYVY) {
        return YCbCr422;
    } else if (subtype == MEDIASUBTYPE_YUY2) {
        return YUYV422;
    } else if (subtype == MEDIASUBTYPE_RGB565) {
        return B5G6R5;
//    } else if (Subtype == MEDIASUBTYPE_Y800 && DesiredPF == "BY8_GBRG") {
//        return BAYER8_GBRG;
    } else if (subtype == MEDIASUBTYPE_Y800) {
        return I8;
    } else {
        return NO_PIXELFORMAT;
    }
}

std::string mediaTypeToString(const GUID& type)
{
    if (type == MEDIATYPE_Video) {
        return "MEDIATYPE_Video";
    } else if (type == GUID_NULL) {
        return "GUID_NULL";
    } else {
        return "Unknown";
    }
}

string mediaSubtypeToString(const GUID & subtype)
{
    if (subtype == MEDIASUBTYPE_RGB24) {
        return "MEDIASUBTYPE_RGB24";
    } else if (subtype == MEDIASUBTYPE_RGB32) {
        return "MEDIASUBTYPE_RGB32";
    } else if (subtype == MEDIASUBTYPE_RGB8) {
        return "MEDIASUBTYPE_RGB8";
    } else if (subtype == MEDIASUBTYPE_UYVY) {
        return "MEDIASUBTYPE_UYVY";
    } else if (subtype == MEDIASUBTYPE_YUY2) {
        return "MEDIASUBTYPE_YUY2";
    } else if (subtype == MEDIASUBTYPE_MJPG) {
        return "MEDIASUBTYPE_MJPG";
    } else if (subtype == MEDIASUBTYPE_RGB555) {
        return "MEDIASUBTYPE_RGB555";
    } else if (subtype == MEDIASUBTYPE_RGB565) {
        return "MEDIASUBTYPE_RGB565";
    } else if (subtype == MEDIASUBTYPE_Y800) {
        return "MEDIASUBTYPE_Y800";
    } else if (subtype == GUID_NULL) {
        return "GUID_NULL";
    } else {
        return "Unknown";
    }
}

string mediaFormattypeToString(const GUID& formattype)
{
    if (formattype == FORMAT_None) {
        return "FORMAT_None";
    } else if (formattype == FORMAT_VideoInfo) {
        return "FORMAT_VideoInfo";
    } else if (formattype == FORMAT_VideoInfo2) {
        return "FORMAT_VideoInfo2";
    } else if (formattype == GUID_NULL) {
        return "GUID_NULL";
    } else {
        return "Unknown";
    }
}

string camImageFormatToString(const AM_MEDIA_TYPE* pMediaType)
{
    stringstream ss;
    VIDEOINFOHEADER* pVideoInfo = (VIDEOINFOHEADER*)(pMediaType->pbFormat);
    BITMAPINFOHEADER* pBitmapInfo = &pVideoInfo->bmiHeader;
    PixelFormat pf = mediaSubtypeToPixelFormat(pMediaType->subtype);
    ss << "(" << pBitmapInfo->biWidth << "x" << pBitmapInfo->biHeight << "), " << pf
            << ", " << 10000000./pVideoInfo->AvgTimePerFrame << " fps.";
    return ss.str();
}

bool isDSFeatureCamControl(CameraFeature feature)
{
    switch(feature) {
        case CAM_FEATURE_BRIGHTNESS:
        case CAM_FEATURE_SHARPNESS:
        case CAM_FEATURE_WHITE_BALANCE:
        case CAM_FEATURE_HUE:
        case CAM_FEATURE_SATURATION:
        case CAM_FEATURE_GAMMA:
        case CAM_FEATURE_GAIN:
            return false;
        case CAM_FEATURE_EXPOSURE:
        case CAM_FEATURE_IRIS:
        case CAM_FEATURE_FOCUS:
        case CAM_FEATURE_ZOOM:
        case CAM_FEATURE_PAN:
        case CAM_FEATURE_TILT:
            return true;
        case CAM_FEATURE_SHUTTER:
        case CAM_FEATURE_TEMPERATURE:
        case CAM_FEATURE_TRIGGER:
        case CAM_FEATURE_OPTICAL_FILTER:
        case CAM_FEATURE_CAPTURE_SIZE:
        case CAM_FEATURE_CAPTURE_QUALITY:
        case CAM_FEATURE_CONTRAST:
            AVG_TRACE(Logger::WARNING, "isDSFeatureCamControl: "
                    + cameraFeatureToString(feature) + " not supported by DirectShow.");
            return false;
        default:
            AVG_TRACE(Logger::WARNING, "isDSFeatureCamControl: "
                    + cameraFeatureToString(feature) + " unknown.");
            return false;
    }
}

long getDSFeatureID(CameraFeature feature)
{
    switch(feature) {
        case CAM_FEATURE_BRIGHTNESS:
            return VideoProcAmp_Brightness;
        case CAM_FEATURE_SHARPNESS:
            return VideoProcAmp_Sharpness;
        case CAM_FEATURE_WHITE_BALANCE:
            return VideoProcAmp_WhiteBalance;
        case CAM_FEATURE_HUE:
            return VideoProcAmp_Hue;
        case CAM_FEATURE_SATURATION:
            return VideoProcAmp_Saturation;
        case CAM_FEATURE_GAMMA:
            return VideoProcAmp_Gamma;
        case CAM_FEATURE_GAIN:
            return VideoProcAmp_Gain;
        case CAM_FEATURE_EXPOSURE:
            return CameraControl_Exposure;
        case CAM_FEATURE_IRIS:
            return CameraControl_Iris;
        case CAM_FEATURE_FOCUS:
            return CameraControl_Focus;
        case CAM_FEATURE_ZOOM:
            return CameraControl_Zoom;
        case CAM_FEATURE_PAN:
            return CameraControl_Pan;
        case CAM_FEATURE_TILT:
            return CameraControl_Tilt;
        case CAM_FEATURE_SHUTTER:
        case CAM_FEATURE_TEMPERATURE:
        case CAM_FEATURE_TRIGGER:
        case CAM_FEATURE_OPTICAL_FILTER:
        case CAM_FEATURE_CAPTURE_SIZE:
        case CAM_FEATURE_CAPTURE_QUALITY:
        case CAM_FEATURE_CONTRAST:
            AVG_TRACE(Logger::WARNING, "getDSFeatureID: "+cameraFeatureToString(feature)
                    +" not supported by DirectShow.");
            return 0;
        default:
            AVG_TRACE(Logger::WARNING, "getDSFeatureID: "+cameraFeatureToString(feature)+" unknown.");
            return -1;
    }
}

}
<commit_msg>dscamera branch: Dump doesn't report negative heights anymore.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "DSHelper.h"

#include "../base/Exception.h"
#include "../base/Logger.h"

#include <stdio.h>
#include <oleauto.h>

#include <string>

using namespace std;

namespace avg {

#pragma warning(disable : 4995)
HRESULT AddGraphToRot(IUnknown *pUnkGraph, DWORD *pdwRegister)
{
    IMoniker * pMoniker;
    IRunningObjectTable *pROT;
    WCHAR wsz[128];
    HRESULT hr;

    if (!pUnkGraph || !pdwRegister) {
        return E_POINTER;
    }

    if (FAILED(GetRunningObjectTable(0, &pROT))) {
        return E_FAIL;
    }

    hr = swprintf(wsz, NUMELMS(wsz), L"FilterGraph %08x pid %08x\0",
            (DWORD_PTR)pUnkGraph, GetCurrentProcessId());

    hr = CreateItemMoniker(L"!", wsz, &pMoniker);
    if (SUCCEEDED(hr)) {
        hr = pROT->Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, pUnkGraph, pMoniker,
                pdwRegister);
        pMoniker->Release();
    }

    pROT->Release();
    return hr;
}

void RemoveGraphFromRot(DWORD pdwRegister)
{
    IRunningObjectTable *pROT;

    if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) {
        pROT->Revoke(pdwRegister);
        pROT->Release();
    }
}

string getStringProp(IPropertyBag *pPropBag, LPCOLESTR pszPropName)
{
    VARIANT varName;
    VariantInit(&varName);
    HRESULT hr = pPropBag->Read(pszPropName, &varName, 0);
    if (FAILED(hr)) {
        return "";
    }
//    checkForDShowError(hr, string("DSHelper::getStringProp(")+pszPropName+")::Read PropBag");

    string s;
    int lenWStr = SysStringLen(varName.bstrVal);
    int lenAStr = WideCharToMultiByte(CP_ACP, 0, varName.bstrVal, lenWStr, 0, 0, NULL, NULL);
    if (lenAStr > 0) {
        char* pAStr = new char[lenAStr + 1];
        WideCharToMultiByte(CP_ACP, 0, varName.bstrVal, lenWStr, pAStr, lenAStr, NULL, NULL);
        pAStr[lenAStr] = 0;
        s = pAStr;
        delete[] pAStr;
    }

    VariantClear(&varName);
    return s;
}

PixelFormat mediaSubtypeToPixelFormat(const GUID& subtype)
{
    if (subtype == MEDIASUBTYPE_RGB24) {
        return B8G8R8;
    } else if (subtype == MEDIASUBTYPE_RGB32) {
        return B8G8R8X8;
    } else if (subtype == MEDIASUBTYPE_RGB8) {
        return I8;
    } else if (subtype == MEDIASUBTYPE_UYVY) {
        return YCbCr422;
    } else if (subtype == MEDIASUBTYPE_YUY2) {
        return YUYV422;
    } else if (subtype == MEDIASUBTYPE_RGB565) {
        return B5G6R5;
//    } else if (Subtype == MEDIASUBTYPE_Y800 && DesiredPF == "BY8_GBRG") {
//        return BAYER8_GBRG;
    } else if (subtype == MEDIASUBTYPE_Y800) {
        return I8;
    } else {
        return NO_PIXELFORMAT;
    }
}

std::string mediaTypeToString(const GUID& type)
{
    if (type == MEDIATYPE_Video) {
        return "MEDIATYPE_Video";
    } else if (type == GUID_NULL) {
        return "GUID_NULL";
    } else {
        return "Unknown";
    }
}

string mediaSubtypeToString(const GUID & subtype)
{
    if (subtype == MEDIASUBTYPE_RGB24) {
        return "MEDIASUBTYPE_RGB24";
    } else if (subtype == MEDIASUBTYPE_RGB32) {
        return "MEDIASUBTYPE_RGB32";
    } else if (subtype == MEDIASUBTYPE_RGB8) {
        return "MEDIASUBTYPE_RGB8";
    } else if (subtype == MEDIASUBTYPE_UYVY) {
        return "MEDIASUBTYPE_UYVY";
    } else if (subtype == MEDIASUBTYPE_YUY2) {
        return "MEDIASUBTYPE_YUY2";
    } else if (subtype == MEDIASUBTYPE_MJPG) {
        return "MEDIASUBTYPE_MJPG";
    } else if (subtype == MEDIASUBTYPE_RGB555) {
        return "MEDIASUBTYPE_RGB555";
    } else if (subtype == MEDIASUBTYPE_RGB565) {
        return "MEDIASUBTYPE_RGB565";
    } else if (subtype == MEDIASUBTYPE_Y800) {
        return "MEDIASUBTYPE_Y800";
    } else if (subtype == GUID_NULL) {
        return "GUID_NULL";
    } else {
        return "Unknown";
    }
}

string mediaFormattypeToString(const GUID& formattype)
{
    if (formattype == FORMAT_None) {
        return "FORMAT_None";
    } else if (formattype == FORMAT_VideoInfo) {
        return "FORMAT_VideoInfo";
    } else if (formattype == FORMAT_VideoInfo2) {
        return "FORMAT_VideoInfo2";
    } else if (formattype == GUID_NULL) {
        return "GUID_NULL";
    } else {
        return "Unknown";
    }
}

string camImageFormatToString(const AM_MEDIA_TYPE* pMediaType)
{
    stringstream ss;
    VIDEOINFOHEADER* pVideoInfo = (VIDEOINFOHEADER*)(pMediaType->pbFormat);
    BITMAPINFOHEADER* pBitmapInfo = &pVideoInfo->bmiHeader;
    PixelFormat pf = mediaSubtypeToPixelFormat(pMediaType->subtype);
    int height = abs(pBitmapInfo->biHeight);
    ss << "(" << pBitmapInfo->biWidth << "x" << height << "), " << pf
            << ", " << 10000000./pVideoInfo->AvgTimePerFrame << " fps.";
    return ss.str();
}

bool isDSFeatureCamControl(CameraFeature feature)
{
    switch(feature) {
        case CAM_FEATURE_BRIGHTNESS:
        case CAM_FEATURE_SHARPNESS:
        case CAM_FEATURE_WHITE_BALANCE:
        case CAM_FEATURE_HUE:
        case CAM_FEATURE_SATURATION:
        case CAM_FEATURE_GAMMA:
        case CAM_FEATURE_GAIN:
            return false;
        case CAM_FEATURE_EXPOSURE:
        case CAM_FEATURE_IRIS:
        case CAM_FEATURE_FOCUS:
        case CAM_FEATURE_ZOOM:
        case CAM_FEATURE_PAN:
        case CAM_FEATURE_TILT:
            return true;
        case CAM_FEATURE_SHUTTER:
        case CAM_FEATURE_TEMPERATURE:
        case CAM_FEATURE_TRIGGER:
        case CAM_FEATURE_OPTICAL_FILTER:
        case CAM_FEATURE_CAPTURE_SIZE:
        case CAM_FEATURE_CAPTURE_QUALITY:
        case CAM_FEATURE_CONTRAST:
            AVG_TRACE(Logger::WARNING, "isDSFeatureCamControl: "
                    + cameraFeatureToString(feature) + " not supported by DirectShow.");
            return false;
        default:
            AVG_TRACE(Logger::WARNING, "isDSFeatureCamControl: "
                    + cameraFeatureToString(feature) + " unknown.");
            return false;
    }
}

long getDSFeatureID(CameraFeature feature)
{
    switch(feature) {
        case CAM_FEATURE_BRIGHTNESS:
            return VideoProcAmp_Brightness;
        case CAM_FEATURE_SHARPNESS:
            return VideoProcAmp_Sharpness;
        case CAM_FEATURE_WHITE_BALANCE:
            return VideoProcAmp_WhiteBalance;
        case CAM_FEATURE_HUE:
            return VideoProcAmp_Hue;
        case CAM_FEATURE_SATURATION:
            return VideoProcAmp_Saturation;
        case CAM_FEATURE_GAMMA:
            return VideoProcAmp_Gamma;
        case CAM_FEATURE_GAIN:
            return VideoProcAmp_Gain;
        case CAM_FEATURE_EXPOSURE:
            return CameraControl_Exposure;
        case CAM_FEATURE_IRIS:
            return CameraControl_Iris;
        case CAM_FEATURE_FOCUS:
            return CameraControl_Focus;
        case CAM_FEATURE_ZOOM:
            return CameraControl_Zoom;
        case CAM_FEATURE_PAN:
            return CameraControl_Pan;
        case CAM_FEATURE_TILT:
            return CameraControl_Tilt;
        case CAM_FEATURE_SHUTTER:
        case CAM_FEATURE_TEMPERATURE:
        case CAM_FEATURE_TRIGGER:
        case CAM_FEATURE_OPTICAL_FILTER:
        case CAM_FEATURE_CAPTURE_SIZE:
        case CAM_FEATURE_CAPTURE_QUALITY:
        case CAM_FEATURE_CONTRAST:
            AVG_TRACE(Logger::WARNING, "getDSFeatureID: "+cameraFeatureToString(feature)
                    +" not supported by DirectShow.");
            return 0;
        default:
            AVG_TRACE(Logger::WARNING, "getDSFeatureID: "+cameraFeatureToString(feature)+" unknown.");
            return -1;
    }
}

}
<|endoftext|>


<commit_before>// Copyright (C) 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Main
//
// (C) Stefan Hoops 2002
//

#include <stdlib.h>
#include <sstream>
#include <string>
#include <iostream>

#include <SBWTranslator.h>

#include <SBW/SBW.h>

#define COPASI_MAIN

#include <copasi/copasi.h>
#include <copasi/commandline/COptions.h>
#include <copasi/report/CCopasiRootContainer.h>
#include <copasi/CopasiDataModel/CCopasiDataModel.h>
#include <copasi/utilities/CVersion.h>
#include <copasi/utilities/CDirEntry.h>

using namespace SystemsBiologyWorkbench;
using namespace std;

int Copasi2SBMLTranslator::mLevel = 3;
int Copasi2SBMLTranslator::mVersion = 1;

Copasi2SBMLTranslator::Copasi2SBMLTranslator()
{
}
Copasi2SBMLTranslator::~Copasi2SBMLTranslator()
{
}

void Copasi2SBMLTranslator::registerMethods(MethodTable<Copasi2SBMLTranslator> &table)
{
  table.addMethod(&Copasi2SBMLTranslator::getName,            "string getName()", false, "Return the name of this importer");
  table.addMethod(&Copasi2SBMLTranslator::getVersion,         "string getVersion()", false, "Return the version of this importer");
  table.addMethod(&Copasi2SBMLTranslator::getAuthor,          "string getAuthor()", false, "Return the corresponding author for this importer");
  table.addMethod(&Copasi2SBMLTranslator::getDescription,       "string getDescription()", false, "Return a description for this importer");
  table.addMethod(&Copasi2SBMLTranslator::getName,        "string getDisplayName()", false, "Return the display name for this importer.");
  table.addMethod(&Copasi2SBMLTranslator::getCopyright,       "string getCopyright()", false, "Return the copyright for this importer");
  table.addMethod(&Copasi2SBMLTranslator::getURL,           "string getURL()", false, "Return a URL for this reporter.");
  table.addMethod(&Copasi2SBMLTranslator::getFileExtension,            "string getFileExtension()", false, "Returns the file extension as a string");
  table.addMethod(&Copasi2SBMLTranslator::getFileType,                 "string getFileType()", false, "Returns a string describing the type of file");
  table.addMethod(&Copasi2SBMLTranslator::translate,          "string translate(string)", false, "Translate SBML string to COPASI.");
  table.addMethod(&Copasi2SBMLTranslator::translateToSBML,          "string translateToSBML(string)", false, "Translate COPASI string to SBML.");
  table.addMethod(&Copasi2SBMLTranslator::translateFileToSBML,          "string translateFileToSBML(string)", false, "Translate COPASI string to SBML.");
}

std::string Copasi2SBMLTranslator::translateFileToSBML(const std::string &fileName)
{
  CCopasiRootContainer::init(0, NULL);
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();
  pDataModel->loadModel(fileName, NULL);
  string sbml = pDataModel->exportSBMLToString(NULL, mLevel, mVersion);
  return sbml;
}

std::string Copasi2SBMLTranslator::translate(const std::string &sbmlString)
{
  CCopasiRootContainer::init(0, NULL);
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();
  pDataModel->importSBMLFromString(sbmlString);

  string tempDir;
  COptions::getValue("Tmp", tempDir);
  string tempFile = "tmp.cps";
  CDirEntry::makePathAbsolute(tempFile, tempDir);
  tempFile = CDirEntry::fileName(tempFile);
  pDataModel->saveModel(tempFile, NULL, true);
  std::ifstream ifs(tempFile);
  std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
  ifs.close();
  CDirEntry::remove(tempFile);
  return str;
}

std::string Copasi2SBMLTranslator::translateToSBML(const std::string &copasiString)
{
  CCopasiRootContainer::init(0, NULL);
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();

  istringstream str(copasiString);

  pDataModel->loadModel(str, COptions::getPWD(), NULL);
  string sbml = pDataModel->exportSBMLToString(NULL, mLevel, mVersion);
  return sbml;
}

DataBlockWriter Copasi2SBMLTranslator::getName(Module from, DataBlockReader reader)
{
  static string name("Copasi2SBML Translator");
  return DataBlockWriter();
}

DataBlockWriter Copasi2SBMLTranslator::getVersion(Module from, DataBlockReader reader)
{
  static string version(CVersion::VERSION.getVersion());
  return DataBlockWriter() << version;
}

DataBlockWriter Copasi2SBMLTranslator::getAuthor(Module from, DataBlockReader reader)
{
  static string author("Frank T. Bergmann");
  return DataBlockWriter() << author;
}
DataBlockWriter Copasi2SBMLTranslator::getDescription(Module from, DataBlockReader reader)
{
  static string description("This converter converts a COPASI model to an SBML file");
  return DataBlockWriter();
}
DataBlockWriter Copasi2SBMLTranslator::getCopyright(Module from, DataBlockReader reader)
{
  static string copy("(c) 2012 COPASI Team");
  return DataBlockWriter() << copy;
}
DataBlockWriter Copasi2SBMLTranslator::getURL(Module from, DataBlockReader reader)
{
  static string url("http://copasi.org");
  return DataBlockWriter() << url;
}
DataBlockWriter Copasi2SBMLTranslator::getFileExtension(Module from, DataBlockReader reader)
{
  static string extension(".cps");
  return DataBlockWriter() << extension;
}
DataBlockWriter Copasi2SBMLTranslator::getFileType(Module from, DataBlockReader reader)
{
  static string fileType("COPASI file");
  return DataBlockWriter() << fileType;
}
DataBlockWriter Copasi2SBMLTranslator::translateFileToSBML(Module from, DataBlockReader reader)
{
  std::string fileName; reader >> fileName;
  return DataBlockWriter() << translateFileToSBML(fileName);
}
DataBlockWriter Copasi2SBMLTranslator::translate(Module from, DataBlockReader reader)
{
  std::string model; reader >> model;
  return DataBlockWriter() << translate(model);
}
DataBlockWriter Copasi2SBMLTranslator::translateToSBML(Module from, DataBlockReader reader)
{
  std::string model; reader >> model;
  return DataBlockWriter() << translateToSBML(model);
}

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

  try
    {
      setlocale(LC_ALL, "C");
      bool doTranslate = false;
      string fileName;

      for (int i = 0; i < argc; i++)
        {
          string current(argv[i]);

          if (current == "-f" && i + 1 < argc)
            {
              doTranslate = true;
              fileName = argv[i + 1];
              i++;
            }
        }

      if (doTranslate)
        {
          cout << Copasi2SBMLTranslator::translateFileToSBML(fileName) << endl;
          exit(0);
        }

      ModuleImpl modImpl(
        "org.copasi.copasi2sbml", // module identification
        "Copasi to SBML Translator", // humanly readable name
        UniqueModule); // management scheme

      modImpl.addServiceObject(
        "translator", // service identification
        "Copasi2SBML Translator", // humanly readable name
        "plugin/sbmlTranslator/bidirectional", // category
        new Copasi2SBMLTranslator()); // service implementation

      modImpl.run(argc, argv);
    }
  catch (SBWException *e)
    {
      fprintf(stderr, "Copasi2SBMLTranslator exception: %s\n", e->getMessage().c_str());
      return -1;
    }

  return 0;
}
<commit_msg>- fix compilation on OSX<commit_after>// Copyright (C) 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Main
//
// (C) Stefan Hoops 2002
//

#include <stdlib.h>
#include <sstream>
#include <string>
#include <iostream>

#include <SBWTranslator.h>

#include <SBW/SBW.h>

#define COPASI_MAIN

#include <copasi/copasi.h>
#include <copasi/commandline/COptions.h>
#include <copasi/report/CCopasiRootContainer.h>
#include <copasi/CopasiDataModel/CCopasiDataModel.h>
#include <copasi/utilities/CVersion.h>
#include <copasi/utilities/CDirEntry.h>

using namespace SystemsBiologyWorkbench;
using namespace std;

int Copasi2SBMLTranslator::mLevel = 3;
int Copasi2SBMLTranslator::mVersion = 1;

Copasi2SBMLTranslator::Copasi2SBMLTranslator()
{
}
Copasi2SBMLTranslator::~Copasi2SBMLTranslator()
{
}

void Copasi2SBMLTranslator::registerMethods(MethodTable<Copasi2SBMLTranslator> &table)
{
  table.addMethod(&Copasi2SBMLTranslator::getName,            "string getName()", false, "Return the name of this importer");
  table.addMethod(&Copasi2SBMLTranslator::getVersion,         "string getVersion()", false, "Return the version of this importer");
  table.addMethod(&Copasi2SBMLTranslator::getAuthor,          "string getAuthor()", false, "Return the corresponding author for this importer");
  table.addMethod(&Copasi2SBMLTranslator::getDescription,       "string getDescription()", false, "Return a description for this importer");
  table.addMethod(&Copasi2SBMLTranslator::getName,        "string getDisplayName()", false, "Return the display name for this importer.");
  table.addMethod(&Copasi2SBMLTranslator::getCopyright,       "string getCopyright()", false, "Return the copyright for this importer");
  table.addMethod(&Copasi2SBMLTranslator::getURL,           "string getURL()", false, "Return a URL for this reporter.");
  table.addMethod(&Copasi2SBMLTranslator::getFileExtension,            "string getFileExtension()", false, "Returns the file extension as a string");
  table.addMethod(&Copasi2SBMLTranslator::getFileType,                 "string getFileType()", false, "Returns a string describing the type of file");
  table.addMethod(&Copasi2SBMLTranslator::translate,          "string translate(string)", false, "Translate SBML string to COPASI.");
  table.addMethod(&Copasi2SBMLTranslator::translateToSBML,          "string translateToSBML(string)", false, "Translate COPASI string to SBML.");
  table.addMethod(&Copasi2SBMLTranslator::translateFileToSBML,          "string translateFileToSBML(string)", false, "Translate COPASI string to SBML.");
}

std::string Copasi2SBMLTranslator::translateFileToSBML(const std::string &fileName)
{
  CCopasiRootContainer::init(0, NULL);
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();
  pDataModel->loadModel(fileName, NULL);
  string sbml = pDataModel->exportSBMLToString(NULL, mLevel, mVersion);
  return sbml;
}

std::string Copasi2SBMLTranslator::translate(const std::string &sbmlString)
{
  CCopasiRootContainer::init(0, NULL);
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();
  pDataModel->importSBMLFromString(sbmlString);

  string tempDir;
  COptions::getValue("Tmp", tempDir);
  string tempFile = "tmp.cps";
  CDirEntry::makePathAbsolute(tempFile, tempDir);
  tempFile = CDirEntry::fileName(tempFile);
  pDataModel->saveModel(tempFile, NULL, true);
  std::ifstream ifs(tempFile.c_str());
  std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
  ifs.close();
  CDirEntry::remove(tempFile);
  return str;
}

std::string Copasi2SBMLTranslator::translateToSBML(const std::string &copasiString)
{
  CCopasiRootContainer::init(0, NULL);
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();

  istringstream str(copasiString);

  pDataModel->loadModel(str, COptions::getPWD(), NULL);
  string sbml = pDataModel->exportSBMLToString(NULL, mLevel, mVersion);
  return sbml;
}

DataBlockWriter Copasi2SBMLTranslator::getName(Module from, DataBlockReader reader)
{
  static string name("Copasi2SBML Translator");
  return DataBlockWriter();
}

DataBlockWriter Copasi2SBMLTranslator::getVersion(Module from, DataBlockReader reader)
{
  static string version(CVersion::VERSION.getVersion());
  return DataBlockWriter() << version;
}

DataBlockWriter Copasi2SBMLTranslator::getAuthor(Module from, DataBlockReader reader)
{
  static string author("Frank T. Bergmann");
  return DataBlockWriter() << author;
}
DataBlockWriter Copasi2SBMLTranslator::getDescription(Module from, DataBlockReader reader)
{
  static string description("This converter converts a COPASI model to an SBML file");
  return DataBlockWriter();
}
DataBlockWriter Copasi2SBMLTranslator::getCopyright(Module from, DataBlockReader reader)
{
  static string copy("(c) 2012 COPASI Team");
  return DataBlockWriter() << copy;
}
DataBlockWriter Copasi2SBMLTranslator::getURL(Module from, DataBlockReader reader)
{
  static string url("http://copasi.org");
  return DataBlockWriter() << url;
}
DataBlockWriter Copasi2SBMLTranslator::getFileExtension(Module from, DataBlockReader reader)
{
  static string extension(".cps");
  return DataBlockWriter() << extension;
}
DataBlockWriter Copasi2SBMLTranslator::getFileType(Module from, DataBlockReader reader)
{
  static string fileType("COPASI file");
  return DataBlockWriter() << fileType;
}
DataBlockWriter Copasi2SBMLTranslator::translateFileToSBML(Module from, DataBlockReader reader)
{
  std::string fileName; reader >> fileName;
  return DataBlockWriter() << translateFileToSBML(fileName);
}
DataBlockWriter Copasi2SBMLTranslator::translate(Module from, DataBlockReader reader)
{
  std::string model; reader >> model;
  return DataBlockWriter() << translate(model);
}
DataBlockWriter Copasi2SBMLTranslator::translateToSBML(Module from, DataBlockReader reader)
{
  std::string model; reader >> model;
  return DataBlockWriter() << translateToSBML(model);
}

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

  try
    {
      setlocale(LC_ALL, "C");
      bool doTranslate = false;
      string fileName;

      for (int i = 0; i < argc; i++)
        {
          string current(argv[i]);

          if (current == "-f" && i + 1 < argc)
            {
              doTranslate = true;
              fileName = argv[i + 1];
              i++;
            }
        }

      if (doTranslate)
        {
          cout << Copasi2SBMLTranslator::translateFileToSBML(fileName) << endl;
          exit(0);
        }

      ModuleImpl modImpl(
        "org.copasi.copasi2sbml", // module identification
        "Copasi to SBML Translator", // humanly readable name
        UniqueModule); // management scheme

      modImpl.addServiceObject(
        "translator", // service identification
        "Copasi2SBML Translator", // humanly readable name
        "plugin/sbmlTranslator/bidirectional", // category
        new Copasi2SBMLTranslator()); // service implementation

      modImpl.run(argc, argv);
    }
  catch (SBWException *e)
    {
      fprintf(stderr, "Copasi2SBMLTranslator exception: %s\n", e->getMessage().c_str());
      return -1;
    }

  return 0;
}
<|endoftext|>