<commit_before>/*
    Copyright (C) 2008 Torsten Rahn <rahn@kde.org>

    This file is part of the KDE project

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

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

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "GeoSceneGroup.h"

#include <QtCore/QDebug>

#include "GeoSceneProperty.h"

namespace Marble
{

GeoSceneGroup::GeoSceneGroup( const QString& name )
    : m_name( name )
{
}

GeoSceneGroup::~GeoSceneGroup()
{
    qDeleteAll( m_properties );
}

bool GeoSceneGroup::propertyAvailable( const QString& name, bool& available )
{
    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name ) {
            available = (*it)->available();
            return true;
        }
    }

    available = false;

    return false;
}

bool GeoSceneGroup::setPropertyValue( const QString& name, bool value )
{
    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name ) {
            (*it)->setValue( value );
            return true;
        }
    }

    return false;
}

bool GeoSceneGroup::propertyValue( const QString& name, bool& value )
{
    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name ) {
            value = (*it)->value();
            return true;
        }
    }

    value = false;

    return false;
}

void GeoSceneGroup::addProperty( GeoSceneProperty* property )
{
    // Remove any property that has the same name
    QVector<GeoSceneProperty*>::iterator it = m_properties.begin();
    while (it != m_properties.end()) {
        GeoSceneProperty* currentProperty = *it;
        if ( currentProperty->name() == property->name() ) {
            delete currentProperty;
            it = m_properties.erase(it);
        }
        else {
            ++it;
        }
    }

    if ( property ) {
        m_properties.append( property );

        // Establish connection to the outside, e.g. the LegendBrowser
        connect ( property, SIGNAL( valueChanged( QString, bool ) ),
                            SIGNAL( valueChanged( QString, bool ) ) );
        emit valueChanged( property->name(), property->value() );
    }
}

GeoSceneProperty* GeoSceneGroup::property( const QString& name )
{
    GeoSceneProperty* property = 0;

    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name )
            property = *it;
            break;
    }

    return property;
}

QVector<GeoSceneProperty*> GeoSceneGroup::properties() const
{
    return m_properties;
}

QString GeoSceneGroup::name() const
{
    return m_name;
}

}

#include "GeoSceneGroup.moc"
<commit_msg>Fix bug introduced by commit 994465, add missing braces.<commit_after>/*
    Copyright (C) 2008 Torsten Rahn <rahn@kde.org>

    This file is part of the KDE project

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

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

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "GeoSceneGroup.h"

#include <QtCore/QDebug>

#include "GeoSceneProperty.h"

namespace Marble
{

GeoSceneGroup::GeoSceneGroup( const QString& name )
    : m_name( name )
{
}

GeoSceneGroup::~GeoSceneGroup()
{
    qDeleteAll( m_properties );
}

bool GeoSceneGroup::propertyAvailable( const QString& name, bool& available )
{
    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name ) {
            available = (*it)->available();
            return true;
        }
    }

    available = false;

    return false;
}

bool GeoSceneGroup::setPropertyValue( const QString& name, bool value )
{
    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name ) {
            (*it)->setValue( value );
            return true;
        }
    }

    return false;
}

bool GeoSceneGroup::propertyValue( const QString& name, bool& value )
{
    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name ) {
            value = (*it)->value();
            return true;
        }
    }

    value = false;

    return false;
}

void GeoSceneGroup::addProperty( GeoSceneProperty* property )
{
    // Remove any property that has the same name
    QVector<GeoSceneProperty*>::iterator it = m_properties.begin();
    while (it != m_properties.end()) {
        GeoSceneProperty* currentProperty = *it;
        if ( currentProperty->name() == property->name() ) {
            delete currentProperty;
            it = m_properties.erase(it);
        }
        else {
            ++it;
        }
    }

    if ( property ) {
        m_properties.append( property );

        // Establish connection to the outside, e.g. the LegendBrowser
        connect ( property, SIGNAL( valueChanged( QString, bool ) ),
                            SIGNAL( valueChanged( QString, bool ) ) );
        emit valueChanged( property->name(), property->value() );
    }
}

GeoSceneProperty* GeoSceneGroup::property( const QString& name )
{
    GeoSceneProperty* property = 0;

    QVector<GeoSceneProperty*>::const_iterator it = m_properties.constBegin();
    QVector<GeoSceneProperty*>::const_iterator end = m_properties.constEnd();
    for (; it != end; ++it) {
        if ( (*it)->name() == name ) {
            property = *it;
            break;
        }
    }

    return property;
}

QVector<GeoSceneProperty*> GeoSceneGroup::properties() const
{
    return m_properties;
}

QString GeoSceneGroup::name() const
{
    return m_name;
}

}

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


<commit_before>#pragma once

struct AlignmentLengths {
    uint32_t raLen;
    uint32_t qaLen;
    uint32_t sclip;
    uint32_t eclip;

    AlignmentLengths(char *cigar)
        : raLen(0)
        , qaLen(0)
        , sclip(0)
        , eclip(0)
    {}

    AlignmentLengths(uint32_t *cigar, uint32_t n_cigar)
        : raLen(0)
        , qaLen(0)
        , sclip(0)
        , eclip(0)
    {}

};

struct Alignment {
    AlignmentLengths lens;
    uint32_t pos; //1-based start position of the alignment
    uint32_t rapos;
    uint32_t SQO;
    uint32_t EQO;
    char strand;
    char *chrom;

    Alignment()
        : pos(0)
        , raLen(0)
        , rapos(0)
        , qaLen(0)
        , sclip(0)
        , eclip(0)
        , SQO(0)
        , EQO(0)
        , strand(0)
        , chrom(NULL)
    {}

    Alignment(bam1_t *aln);
    Alignment(char *sa_tag);
};
<commit_msg>first pass at alignment class<commit_after>#pragma once

#include "AlignmentOffsets.hpp"

#include <algorithm>
#include <string.h>

struct Alignment {
    AlignmentOffsets offsets;
    uint32_t pos; //1-based start position of the alignment
    uint32_t rapos;
    int SQO;
    int EQO;
    char strand;
    char *chrom;

    Alignment()
        : offsets()
        , pos(0)
        , rapos(0)
        , SQO(0)
        , EQO(0)
        , strand(0)
        , chrom(NULL)
    {}

    Alignment(bam1_t *aln) {
        rapos = aln->core.pos + 1;
        offsets = AlignmentOffsets(bam_get_cigar(aln), aln->core.n_cigar);
        if (bam_is_rev(aln)) {
            strand = '-';
            pos = rapos + offsets.raLen + offsets.eclip - 1;
            SQO = offsets.eclip;
            EQO = offsets.eclip + offsets.qaLen - 1;
        }
        else {
            strand = '+';
            pos = rapos - offsets.sclip;
            SQO = offsets.sclip;
            EQO = offsets.sclip + offsets.qaLen - 1;
        }
    }

    //Alignment(char *sa_tag);

    int start_diagonal() const {
        return rapos - offsets.sclip;
    }

    int end_diagonal() const {
        return (rapos + offsets.raLen) - (offsets.sclip + offsets.qaLen);
    }

    friend int mno(Alignment const& left, Alignment const& right) {
        int overlap = std::max(1 + std::min(left.EQO, right.EQO) - std::max(left.SQO, right.SQO), 0);
        int alen1 = 1 + left.EQO - left.SQO;
        int alen2 = 1 + right.EQO - right.SQO;
        return std::min(alen1 - overlap, alen2 - overlap);
    }

    friend int desert(Alignment const& left, Alignment const& right) {
        return right.SQO - left.EQO - 1;
    }

    friend int insert_size(Alignment const& left, Alignment const& right) {
        if (left.strand == '-') {
            return right.end_diagonal() - left.start_diagonal();
        }
        else {
            return left.end_diagonal() - right.start_diagonal();
        }
    }

    friend bool should_check(Alignment const& left, Alignment const& right) {
        return (strcmp(left.chrom, right.chrom) == 0 && left.strand == right.strand);
    }

};
<|endoftext|>


<commit_before>#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// VertexBuffer.cpp: Defines the abstract VertexBuffer class and VertexBufferInterface
// class with derivations, classes that perform graphics API agnostic vertex buffer operations.

#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "common/mathutil.h"

namespace rx
{

unsigned int VertexBuffer::mNextSerial = 1;

VertexBuffer::VertexBuffer()
{
    updateSerial();
}

VertexBuffer::~VertexBuffer()
{
}

void VertexBuffer::updateSerial()
{
    mSerial = mNextSerial++;
}

unsigned int VertexBuffer::getSerial() const
{
    return mSerial;
}

VertexBufferInterface::VertexBufferInterface(rx::Renderer *renderer, bool dynamic) : mRenderer(renderer)
{
    mDynamic = dynamic;
    mWritePosition = 0;
    mReservedSpace = 0;

    mVertexBuffer = renderer->createVertexBuffer();
}

VertexBufferInterface::~VertexBufferInterface()
{
    delete mVertexBuffer;
}

unsigned int VertexBufferInterface::getSerial() const
{
    return mVertexBuffer->getSerial();
}

unsigned int VertexBufferInterface::getBufferSize() const
{
    return mVertexBuffer->getBufferSize();
}

bool VertexBufferInterface::setBufferSize(unsigned int size)
{
    if (mVertexBuffer->getBufferSize() == 0)
    {
        return mVertexBuffer->initialize(size, mDynamic);
    }
    else
    {
        return mVertexBuffer->setBufferSize(size);
    }
}

unsigned int VertexBufferInterface::getWritePosition() const
{
    return mWritePosition;
}

void VertexBufferInterface::setWritePosition(unsigned int writePosition)
{
    mWritePosition = writePosition;
}

bool VertexBufferInterface::discard()
{
    return mVertexBuffer->discard();
}

bool VertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, const gl::VertexAttribCurrentValueData &currentValue,
                                                  GLint start, GLsizei count, GLsizei instances, unsigned int *outStreamOffset)
{
    unsigned int spaceRequired;
    if (!mVertexBuffer->getSpaceRequired(attrib, count, instances, &spaceRequired))
    {
        return false;
    }

    if (mWritePosition + spaceRequired < mWritePosition)
    {
        return false;
    }

    if (!reserveSpace(mReservedSpace))
    {
        return false;
    }
    mReservedSpace = 0;

    if (!mVertexBuffer->storeVertexAttributes(attrib, currentValue, start, count, instances, mWritePosition))
    {
        return false;
    }

    if (outStreamOffset)
    {
        *outStreamOffset = mWritePosition;
    }

    mWritePosition += spaceRequired;

    // Align to 16-byte boundary
    mWritePosition = rx::roundUp(mWritePosition, 16u);

    return true;
}

bool VertexBufferInterface::reserveVertexSpace(const gl::VertexAttribute &attribute, GLsizei count, GLsizei instances)
{
    unsigned int requiredSpace;
    if (!mVertexBuffer->getSpaceRequired(attribute, count, instances, &requiredSpace))
    {
        return false;
    }

    // Protect against integer overflow
    if (mReservedSpace + requiredSpace < mReservedSpace)
    {
         return false;
    }

    mReservedSpace += requiredSpace;

    // Align to 16-byte boundary
    mReservedSpace = rx::roundUp(mReservedSpace, 16u);

    return true;
}

VertexBuffer* VertexBufferInterface::getVertexBuffer() const
{
    return mVertexBuffer;
}

bool VertexBufferInterface::directStoragePossible(const gl::VertexAttribute &attrib,
                                                  const gl::VertexAttribCurrentValueData &currentValue) const
{
    gl::Buffer *buffer = attrib.mBoundBuffer.get();
    BufferStorage *storage = buffer ? buffer->getStorage() : NULL;
    gl::VertexFormat vertexFormat(attrib, currentValue.Type);

    // Alignment restrictions: In D3D, vertex data must be aligned to
    //  the format stride, or to a 4-byte boundary, whichever is smaller.
    //  (Undocumented, and experimentally confirmed)
    unsigned int outputElementSize;
    getVertexBuffer()->getSpaceRequired(attrib, 1, 0, &outputElementSize);
    size_t alignment = std::min(static_cast<size_t>(outputElementSize), 4u);

    bool isAligned = (static_cast<size_t>(attrib.stride()) % alignment == 0) &&
                     (static_cast<size_t>(attrib.mOffset) % alignment == 0);
    bool requiresConversion = (mRenderer->getVertexConversionType(vertexFormat) & VERTEX_CONVERT_CPU) > 0;

    return storage && storage->supportsDirectBinding() && !requiresConversion && isAligned;
}

StreamingVertexBufferInterface::StreamingVertexBufferInterface(rx::Renderer *renderer, std::size_t initialSize) : VertexBufferInterface(renderer, true)
{
    setBufferSize(initialSize);
}

StreamingVertexBufferInterface::~StreamingVertexBufferInterface()
{
}

bool StreamingVertexBufferInterface::reserveSpace(unsigned int size)
{
    bool result = true;
    unsigned int curBufferSize = getBufferSize();
    if (size > curBufferSize)
    {
        result = setBufferSize(std::max(size, 3 * curBufferSize / 2));
        setWritePosition(0);
    }
    else if (getWritePosition() + size > curBufferSize)
    {
        if (!discard())
        {
            return false;
        }
        setWritePosition(0);
    }

    return result;
}

StaticVertexBufferInterface::StaticVertexBufferInterface(rx::Renderer *renderer) : VertexBufferInterface(renderer, false)
{
}

StaticVertexBufferInterface::~StaticVertexBufferInterface()
{
}

bool StaticVertexBufferInterface::lookupAttribute(const gl::VertexAttribute &attribute, unsigned int *outStreamOffset)
{
    for (unsigned int element = 0; element < mCache.size(); element++)
    {
        if (mCache[element].type == attribute.mType &&
            mCache[element].size == attribute.mSize &&
            mCache[element].stride == attribute.stride() &&
            mCache[element].normalized == attribute.mNormalized &&
            mCache[element].pureInteger == attribute.mPureInteger)
        {
            if (mCache[element].attributeOffset == attribute.mOffset % attribute.stride())
            {
                if (outStreamOffset)
                {
                    *outStreamOffset = mCache[element].streamOffset;
                }
                return true;
            }
        }
    }

    return false;
}

bool StaticVertexBufferInterface::reserveSpace(unsigned int size)
{
    unsigned int curSize = getBufferSize();
    if (curSize == 0)
    {
        setBufferSize(size);
        return true;
    }
    else if (curSize >= size)
    {
        return true;
    }
    else
    {
        UNREACHABLE();   // Static vertex buffers can't be resized
        return false;
    }
}

bool StaticVertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, const gl::VertexAttribCurrentValueData &currentValue,
                                                       GLint start, GLsizei count, GLsizei instances, unsigned int *outStreamOffset)
{
    unsigned int streamOffset;
    if (VertexBufferInterface::storeVertexAttributes(attrib, currentValue, start, count, instances, &streamOffset))
    {
        int attributeOffset = attrib.mOffset % attrib.stride();
        VertexElement element = { attrib.mType, attrib.mSize, attrib.stride(), attrib.mNormalized, attrib.mPureInteger, attributeOffset, streamOffset };
        mCache.push_back(element);

        if (outStreamOffset)
        {
            *outStreamOffset = streamOffset;
        }

        return true;
    }
    else
    {
        return false;
    }
}

}
<commit_msg>Early out when direct binding not supported.<commit_after>#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// VertexBuffer.cpp: Defines the abstract VertexBuffer class and VertexBufferInterface
// class with derivations, classes that perform graphics API agnostic vertex buffer operations.

#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "common/mathutil.h"

namespace rx
{

unsigned int VertexBuffer::mNextSerial = 1;

VertexBuffer::VertexBuffer()
{
    updateSerial();
}

VertexBuffer::~VertexBuffer()
{
}

void VertexBuffer::updateSerial()
{
    mSerial = mNextSerial++;
}

unsigned int VertexBuffer::getSerial() const
{
    return mSerial;
}

VertexBufferInterface::VertexBufferInterface(rx::Renderer *renderer, bool dynamic) : mRenderer(renderer)
{
    mDynamic = dynamic;
    mWritePosition = 0;
    mReservedSpace = 0;

    mVertexBuffer = renderer->createVertexBuffer();
}

VertexBufferInterface::~VertexBufferInterface()
{
    delete mVertexBuffer;
}

unsigned int VertexBufferInterface::getSerial() const
{
    return mVertexBuffer->getSerial();
}

unsigned int VertexBufferInterface::getBufferSize() const
{
    return mVertexBuffer->getBufferSize();
}

bool VertexBufferInterface::setBufferSize(unsigned int size)
{
    if (mVertexBuffer->getBufferSize() == 0)
    {
        return mVertexBuffer->initialize(size, mDynamic);
    }
    else
    {
        return mVertexBuffer->setBufferSize(size);
    }
}

unsigned int VertexBufferInterface::getWritePosition() const
{
    return mWritePosition;
}

void VertexBufferInterface::setWritePosition(unsigned int writePosition)
{
    mWritePosition = writePosition;
}

bool VertexBufferInterface::discard()
{
    return mVertexBuffer->discard();
}

bool VertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, const gl::VertexAttribCurrentValueData &currentValue,
                                                  GLint start, GLsizei count, GLsizei instances, unsigned int *outStreamOffset)
{
    unsigned int spaceRequired;
    if (!mVertexBuffer->getSpaceRequired(attrib, count, instances, &spaceRequired))
    {
        return false;
    }

    if (mWritePosition + spaceRequired < mWritePosition)
    {
        return false;
    }

    if (!reserveSpace(mReservedSpace))
    {
        return false;
    }
    mReservedSpace = 0;

    if (!mVertexBuffer->storeVertexAttributes(attrib, currentValue, start, count, instances, mWritePosition))
    {
        return false;
    }

    if (outStreamOffset)
    {
        *outStreamOffset = mWritePosition;
    }

    mWritePosition += spaceRequired;

    // Align to 16-byte boundary
    mWritePosition = rx::roundUp(mWritePosition, 16u);

    return true;
}

bool VertexBufferInterface::reserveVertexSpace(const gl::VertexAttribute &attribute, GLsizei count, GLsizei instances)
{
    unsigned int requiredSpace;
    if (!mVertexBuffer->getSpaceRequired(attribute, count, instances, &requiredSpace))
    {
        return false;
    }

    // Protect against integer overflow
    if (mReservedSpace + requiredSpace < mReservedSpace)
    {
         return false;
    }

    mReservedSpace += requiredSpace;

    // Align to 16-byte boundary
    mReservedSpace = rx::roundUp(mReservedSpace, 16u);

    return true;
}

VertexBuffer* VertexBufferInterface::getVertexBuffer() const
{
    return mVertexBuffer;
}

bool VertexBufferInterface::directStoragePossible(const gl::VertexAttribute &attrib,
                                                  const gl::VertexAttribCurrentValueData &currentValue) const
{
    gl::Buffer *buffer = attrib.mBoundBuffer.get();
    BufferStorage *storage = buffer ? buffer->getStorage() : NULL;

    if (!storage || !storage->supportsDirectBinding())
    {
        return false;
    }

    gl::VertexFormat vertexFormat(attrib, currentValue.Type);

    // Alignment restrictions: In D3D, vertex data must be aligned to
    //  the format stride, or to a 4-byte boundary, whichever is smaller.
    //  (Undocumented, and experimentally confirmed)
    unsigned int outputElementSize;
    getVertexBuffer()->getSpaceRequired(attrib, 1, 0, &outputElementSize);
    size_t alignment = std::min(static_cast<size_t>(outputElementSize), 4u);

    bool isAligned = (static_cast<size_t>(attrib.stride()) % alignment == 0) &&
                     (static_cast<size_t>(attrib.mOffset) % alignment == 0);
    bool requiresConversion = (mRenderer->getVertexConversionType(vertexFormat) & VERTEX_CONVERT_CPU) > 0;

    return !requiresConversion && isAligned;
}

StreamingVertexBufferInterface::StreamingVertexBufferInterface(rx::Renderer *renderer, std::size_t initialSize) : VertexBufferInterface(renderer, true)
{
    setBufferSize(initialSize);
}

StreamingVertexBufferInterface::~StreamingVertexBufferInterface()
{
}

bool StreamingVertexBufferInterface::reserveSpace(unsigned int size)
{
    bool result = true;
    unsigned int curBufferSize = getBufferSize();
    if (size > curBufferSize)
    {
        result = setBufferSize(std::max(size, 3 * curBufferSize / 2));
        setWritePosition(0);
    }
    else if (getWritePosition() + size > curBufferSize)
    {
        if (!discard())
        {
            return false;
        }
        setWritePosition(0);
    }

    return result;
}

StaticVertexBufferInterface::StaticVertexBufferInterface(rx::Renderer *renderer) : VertexBufferInterface(renderer, false)
{
}

StaticVertexBufferInterface::~StaticVertexBufferInterface()
{
}

bool StaticVertexBufferInterface::lookupAttribute(const gl::VertexAttribute &attribute, unsigned int *outStreamOffset)
{
    for (unsigned int element = 0; element < mCache.size(); element++)
    {
        if (mCache[element].type == attribute.mType &&
            mCache[element].size == attribute.mSize &&
            mCache[element].stride == attribute.stride() &&
            mCache[element].normalized == attribute.mNormalized &&
            mCache[element].pureInteger == attribute.mPureInteger)
        {
            if (mCache[element].attributeOffset == attribute.mOffset % attribute.stride())
            {
                if (outStreamOffset)
                {
                    *outStreamOffset = mCache[element].streamOffset;
                }
                return true;
            }
        }
    }

    return false;
}

bool StaticVertexBufferInterface::reserveSpace(unsigned int size)
{
    unsigned int curSize = getBufferSize();
    if (curSize == 0)
    {
        setBufferSize(size);
        return true;
    }
    else if (curSize >= size)
    {
        return true;
    }
    else
    {
        UNREACHABLE();   // Static vertex buffers can't be resized
        return false;
    }
}

bool StaticVertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, const gl::VertexAttribCurrentValueData &currentValue,
                                                       GLint start, GLsizei count, GLsizei instances, unsigned int *outStreamOffset)
{
    unsigned int streamOffset;
    if (VertexBufferInterface::storeVertexAttributes(attrib, currentValue, start, count, instances, &streamOffset))
    {
        int attributeOffset = attrib.mOffset % attrib.stride();
        VertexElement element = { attrib.mType, attrib.mSize, attrib.stride(), attrib.mNormalized, attrib.mPureInteger, attributeOffset, streamOffset };
        mCache.push_back(element);

        if (outStreamOffset)
        {
            *outStreamOffset = streamOffset;
        }

        return true;
    }
    else
    {
        return false;
    }
}

}
<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "library/constants.h"
#include "library/trace.h"
#include "library/app_builder.h"
#include "library/type_context.h"
#include "library/locals.h"
#include "library/replace_visitor_with_tc.h"
#include "library/equations_compiler/equations.h"
#include "library/equations_compiler/util.h"

namespace lean {
[[ noreturn ]] static void throw_ill_formed_eqns() {
    throw exception("ill-formed match/equations expression");
}

static optional<pair<expr, unsigned>> get_eqn_fn_and_arity(expr e) {
    while (is_lambda(e))
        e = binding_body(e);
    if (!is_equation(e) && !is_no_equation(e)) throw_ill_formed_eqns();
    if (is_no_equation(e)) {
        return optional<pair<expr, unsigned>>();
    } else {
        expr const & lhs = equation_lhs(e);
        expr const & fn  = get_app_fn(lhs);
        lean_assert(is_local(fn));
        return optional<pair<expr, unsigned>>(fn, get_app_num_args(lhs));
    }
}

static expr consume_fn_prefix(expr eq, buffer<expr> const & fns) {
    for (unsigned i = 0; i < fns.size(); i++) {
        if (!is_lambda(eq)) throw_ill_formed_eqns();
        eq = binding_body(eq);
    }
    return instantiate_rev(eq, fns);
}

void equations_editor::unpack(expr const & e) {
    m_fns.clear();
    m_arity.clear();
    m_eqs.clear();
    lean_assert(is_equations(e));
    m_src = e;
    buffer<expr> eqs;
    unsigned num_fns = equations_num_fns(e);
    to_equations(e, eqs);
    /* Extract functions. */
    lean_assert(eqs.size() > 0);
    expr eq = eqs[0];
    for (unsigned i = 0; i < num_fns; i++) {
        lean_assert(is_lambda(eq));
        m_fns.push_back(mk_local(binding_name(eq), binding_domain(eq)));
        eq = binding_body(eq);
    }
    /* Extract equations */
    unsigned eqidx = 0;
    for (unsigned fidx = 0; fidx < num_fns; fidx++) {
        m_eqs.push_back(buffer<expr>());
        buffer<expr> & fn_eqs = m_eqs.back();
        if (eqidx >= eqs.size()) throw_ill_formed_eqns();
        expr eq = consume_fn_prefix(eqs[eqidx], m_fns);
        fn_eqs.push_back(eq);
        eqidx++;
        if (auto p = get_eqn_fn_and_arity(eq)) {
            if (p->first != m_fns[fidx]) throw_ill_formed_eqns();
            unsigned arity = p->second;
            m_arity.push_back(arity);
            while (eqidx < eqs.size()) {
                expr eq = consume_fn_prefix(eqs[eqidx], m_fns);
                if (auto p = get_eqn_fn_and_arity(eq)) {
                    if (p->first == m_fns[fidx]) {
                        if (p->second != arity) throw_ill_formed_eqns();
                        fn_eqs.push_back(eq);
                        eqidx++;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        } else {
            /* noequation, guess arity using type of function */
            expr type = mlocal_type(m_fns[fidx]);
            unsigned arity = 0;
            while (is_pi(type))
                type = binding_body(type);
            if (arity == 0) throw_ill_formed_eqns();
            m_arity.push_back(arity);
        }
    }
    if (eqs.size() != eqidx) throw_ill_formed_eqns();
    lean_assert(m_arity.size() == m_fns.size());
    lean_assert(m_eqs.size() == m_fns.size());
}

expr equations_editor::repack() {
    buffer<expr> new_eqs;
    for (buffer<expr> const & fn_eqs : m_eqs) {
        for (expr const & eq : fn_eqs) {
            new_eqs.push_back(Fun(m_fns, eq));
        }
    }
    return update_equations(m_src, new_eqs);
}

struct sigma_packer_fn {
    type_context & m_ctx;
    sigma_packer_fn(type_context & ctx):m_ctx(ctx) {}

    expr_pair mk_sigma_domain(expr const & pi_type, buffer<expr> & out_locals, unsigned n) {
        if (n == 0) return mk_pair(mk_constant(get_unit_name()), pi_type);
        expr type = pi_type;
        if (!is_pi(type)) type = m_ctx.relaxed_whnf(type);
        if (!is_pi(type)) throw_ill_formed_eqns();
        expr const & A = binding_domain(type);
        type_context::tmp_locals locals(m_ctx);
        expr a = locals.push_local_from_binding(type);
        out_locals.push_back(a);
        expr B, codomain;
        std::tie(B, codomain) = mk_sigma_domain(instantiate(binding_body(type), a), out_locals, n-1);
        B = locals.mk_lambda(B);
        return mk_pair(mk_app(m_ctx, get_sigma_name(), A, B), codomain);
    }

    expr mk_codomain(expr const & codomain, expr p, buffer<expr> const & locals, unsigned n) {
        buffer<expr> terms;
        for (unsigned i = 0; i < n; i++) {
            terms.push_back(mk_app(m_ctx, get_sigma_pr1_name(), p));
            p = mk_app(m_ctx, get_sigma_pr2_name(), p);
        }
        return replace_locals(codomain, locals, terms);
    }

    expr pack_as_unary(expr const & pi_type, unsigned n) {
        buffer<expr> locals;
        expr domain, pre_codomain;
        std::tie(domain, pre_codomain) = mk_sigma_domain(pi_type, locals, n);
        type_context::tmp_locals plocal(m_ctx);
        expr p = plocal.push_local("_p", domain);
        expr codomain = mk_codomain(pre_codomain, p, locals, n);
        return plocal.mk_pi(codomain);
    }

    class update_apps_fn : public replace_visitor_with_tc {
        buffer<expr> const &     m_old_fns;
        equations_editor const & m_editor;

        optional<unsigned> get_fn_idx(expr const & fn) {
            if (!is_local(fn)) return optional<unsigned>();
            for (unsigned fnidx = 0; fnidx < m_old_fns.size(); fnidx++) {
                if (mlocal_name(fn) == mlocal_name(m_old_fns[fnidx]))
                    return optional<unsigned>(fnidx);
            }
            return optional<unsigned>();
        }

        expr pack(unsigned i, unsigned arity, buffer<expr> const & args, expr const & type) {
            if (i == arity) {
                lean_assert(is_constant(type, get_unit_name()));
                return mk_constant(get_unit_star_name());
            } else {
                lean_assert(is_constant(get_app_fn(type), get_sigma_name()));
                expr a        = args[i];
                expr A        = app_arg(app_fn(type));
                expr B        = app_arg(type);
                lean_assert(is_lambda(B));
                expr new_type = instantiate(binding_body(B), a);
                expr b        = pack(i+1, arity, args, new_type);
                bool mask[2]  = {true, true};
                expr AB[2]    = {A, B};
                return mk_app(mk_app(m_ctx, get_sigma_mk_name(), 2, mask, AB), a, b);
            }
        }

        virtual expr visit_app(expr const & e) override {
            buffer<expr> args;
            expr const & fn = get_app_args(e, args);
            auto fnidx = get_fn_idx(fn);
            if (!fnidx) return replace_visitor_with_tc::visit_app(e);
            unsigned arity = m_editor.get_arity(*fnidx);
            if (args.size() < arity) {
                expr new_e = m_ctx.eta_expand(e);
                if (!is_lambda(new_e)) throw_ill_formed_eqns();
                return visit(new_e);
            }
            expr new_fn      = m_editor.get_fn(*fnidx);
            expr new_fn_type = m_ctx.infer(new_fn);
            expr sigma_type  = binding_domain(new_fn_type);
            expr arg         = pack(0, arity, args, sigma_type);
            expr r           = mk_app(new_fn, arg);
            return mk_app(r, args.size() - arity, args.data() + arity);
        }

    public:
        update_apps_fn(type_context & ctx, buffer<expr> const & old_fns, equations_editor const & editor):
            replace_visitor_with_tc(ctx), m_old_fns(old_fns), m_editor(editor) {}
    };

    expr operator()(expr const & e) {
        equations_editor editor;
        editor.unpack(e);
        buffer<expr> old_fns;
        for (unsigned fidx = 0; fidx < editor.get_num_fns(); fidx++) {
            expr & fn = editor.get_fn(fidx);
            old_fns.push_back(fn);
            expr new_type = pack_as_unary(mlocal_type(fn), editor.get_arity(fidx));
            fn = update_mlocal(fn, new_type);
        }
        update_apps_fn updt(m_ctx, old_fns, editor);
        for (unsigned fidx = 0; fidx < editor.get_num_fns(); fidx++) {
            buffer<expr> & eqs = editor.get_eqs_of(fidx);
            for (expr & eq : eqs)
                eq = updt(eq);
        }
        return editor.repack();
    }
};

expr pack_equations_domain(type_context & ctx, expr const & e) {
    return sigma_packer_fn(ctx)(e);
}
}
<commit_msg>feat(library/equations_compiler/util): pack_equations_domain does nothing if function is already unary<commit_after>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "library/constants.h"
#include "library/trace.h"
#include "library/app_builder.h"
#include "library/type_context.h"
#include "library/locals.h"
#include "library/replace_visitor_with_tc.h"
#include "library/equations_compiler/equations.h"
#include "library/equations_compiler/util.h"

namespace lean {
[[ noreturn ]] static void throw_ill_formed_eqns() {
    throw exception("ill-formed match/equations expression");
}

static optional<pair<expr, unsigned>> get_eqn_fn_and_arity(expr e) {
    while (is_lambda(e))
        e = binding_body(e);
    if (!is_equation(e) && !is_no_equation(e)) throw_ill_formed_eqns();
    if (is_no_equation(e)) {
        return optional<pair<expr, unsigned>>();
    } else {
        expr const & lhs = equation_lhs(e);
        expr const & fn  = get_app_fn(lhs);
        lean_assert(is_local(fn));
        return optional<pair<expr, unsigned>>(fn, get_app_num_args(lhs));
    }
}

static expr consume_fn_prefix(expr eq, buffer<expr> const & fns) {
    for (unsigned i = 0; i < fns.size(); i++) {
        if (!is_lambda(eq)) throw_ill_formed_eqns();
        eq = binding_body(eq);
    }
    return instantiate_rev(eq, fns);
}

void equations_editor::unpack(expr const & e) {
    m_fns.clear();
    m_arity.clear();
    m_eqs.clear();
    lean_assert(is_equations(e));
    m_src = e;
    buffer<expr> eqs;
    unsigned num_fns = equations_num_fns(e);
    to_equations(e, eqs);
    /* Extract functions. */
    lean_assert(eqs.size() > 0);
    expr eq = eqs[0];
    for (unsigned i = 0; i < num_fns; i++) {
        lean_assert(is_lambda(eq));
        m_fns.push_back(mk_local(binding_name(eq), binding_domain(eq)));
        eq = binding_body(eq);
    }
    /* Extract equations */
    unsigned eqidx = 0;
    for (unsigned fidx = 0; fidx < num_fns; fidx++) {
        m_eqs.push_back(buffer<expr>());
        buffer<expr> & fn_eqs = m_eqs.back();
        if (eqidx >= eqs.size()) throw_ill_formed_eqns();
        expr eq = consume_fn_prefix(eqs[eqidx], m_fns);
        fn_eqs.push_back(eq);
        eqidx++;
        if (auto p = get_eqn_fn_and_arity(eq)) {
            if (p->first != m_fns[fidx]) throw_ill_formed_eqns();
            unsigned arity = p->second;
            m_arity.push_back(arity);
            while (eqidx < eqs.size()) {
                expr eq = consume_fn_prefix(eqs[eqidx], m_fns);
                if (auto p = get_eqn_fn_and_arity(eq)) {
                    if (p->first == m_fns[fidx]) {
                        if (p->second != arity) throw_ill_formed_eqns();
                        fn_eqs.push_back(eq);
                        eqidx++;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        } else {
            /* noequation, guess arity using type of function */
            expr type = mlocal_type(m_fns[fidx]);
            unsigned arity = 0;
            while (is_pi(type))
                type = binding_body(type);
            if (arity == 0) throw_ill_formed_eqns();
            m_arity.push_back(arity);
        }
    }
    if (eqs.size() != eqidx) throw_ill_formed_eqns();
    lean_assert(m_arity.size() == m_fns.size());
    lean_assert(m_eqs.size() == m_fns.size());
}

expr equations_editor::repack() {
    buffer<expr> new_eqs;
    for (buffer<expr> const & fn_eqs : m_eqs) {
        for (expr const & eq : fn_eqs) {
            new_eqs.push_back(Fun(m_fns, eq));
        }
    }
    return update_equations(m_src, new_eqs);
}

struct sigma_packer_fn {
    type_context & m_ctx;
    sigma_packer_fn(type_context & ctx):m_ctx(ctx) {}

    expr_pair mk_sigma_domain(expr const & pi_type, buffer<expr> & out_locals, unsigned n) {
        if (n == 0) return mk_pair(mk_constant(get_unit_name()), pi_type);
        expr type = pi_type;
        if (!is_pi(type)) type = m_ctx.relaxed_whnf(type);
        if (!is_pi(type)) throw_ill_formed_eqns();
        expr const & A = binding_domain(type);
        type_context::tmp_locals locals(m_ctx);
        expr a = locals.push_local_from_binding(type);
        out_locals.push_back(a);
        expr B, codomain;
        std::tie(B, codomain) = mk_sigma_domain(instantiate(binding_body(type), a), out_locals, n-1);
        B = locals.mk_lambda(B);
        return mk_pair(mk_app(m_ctx, get_sigma_name(), A, B), codomain);
    }

    expr mk_codomain(expr const & codomain, expr p, buffer<expr> const & locals, unsigned n) {
        buffer<expr> terms;
        for (unsigned i = 0; i < n; i++) {
            terms.push_back(mk_app(m_ctx, get_sigma_pr1_name(), p));
            p = mk_app(m_ctx, get_sigma_pr2_name(), p);
        }
        return replace_locals(codomain, locals, terms);
    }

    expr pack_as_unary(expr const & pi_type, unsigned n) {
        buffer<expr> locals;
        expr domain, pre_codomain;
        std::tie(domain, pre_codomain) = mk_sigma_domain(pi_type, locals, n);
        type_context::tmp_locals plocal(m_ctx);
        expr p = plocal.push_local("_p", domain);
        expr codomain = mk_codomain(pre_codomain, p, locals, n);
        return plocal.mk_pi(codomain);
    }

    class update_apps_fn : public replace_visitor_with_tc {
        buffer<expr> const &     m_old_fns;
        equations_editor const & m_editor;

        optional<unsigned> get_fn_idx(expr const & fn) {
            if (!is_local(fn)) return optional<unsigned>();
            for (unsigned fnidx = 0; fnidx < m_old_fns.size(); fnidx++) {
                if (mlocal_name(fn) == mlocal_name(m_old_fns[fnidx]))
                    return optional<unsigned>(fnidx);
            }
            return optional<unsigned>();
        }

        expr pack(unsigned i, unsigned arity, buffer<expr> const & args, expr const & type) {
            if (i == arity) {
                lean_assert(is_constant(type, get_unit_name()));
                return mk_constant(get_unit_star_name());
            } else {
                lean_assert(is_constant(get_app_fn(type), get_sigma_name()));
                expr a        = args[i];
                expr A        = app_arg(app_fn(type));
                expr B        = app_arg(type);
                lean_assert(is_lambda(B));
                expr new_type = instantiate(binding_body(B), a);
                expr b        = pack(i+1, arity, args, new_type);
                bool mask[2]  = {true, true};
                expr AB[2]    = {A, B};
                return mk_app(mk_app(m_ctx, get_sigma_mk_name(), 2, mask, AB), a, b);
            }
        }

        virtual expr visit_app(expr const & e) override {
            buffer<expr> args;
            expr const & fn = get_app_args(e, args);
            auto fnidx = get_fn_idx(fn);
            if (!fnidx) return replace_visitor_with_tc::visit_app(e);
            expr new_fn = m_editor.get_fn(*fnidx);
            if (fn == new_fn) return replace_visitor_with_tc::visit_app(e);
            unsigned arity = m_editor.get_arity(*fnidx);
            if (args.size() < arity) {
                expr new_e = m_ctx.eta_expand(e);
                if (!is_lambda(new_e)) throw_ill_formed_eqns();
                return visit(new_e);
            }
            expr new_fn_type = m_ctx.infer(new_fn);
            expr sigma_type  = binding_domain(new_fn_type);
            expr arg         = pack(0, arity, args, sigma_type);
            expr r           = mk_app(new_fn, arg);
            return mk_app(r, args.size() - arity, args.data() + arity);
        }

    public:
        update_apps_fn(type_context & ctx, buffer<expr> const & old_fns, equations_editor const & editor):
            replace_visitor_with_tc(ctx), m_old_fns(old_fns), m_editor(editor) {}
    };

    expr operator()(expr const & e) {
        equations_editor editor;
        editor.unpack(e);
        buffer<expr> old_fns;
        bool modified = false;
        for (unsigned fidx = 0; fidx < editor.get_num_fns(); fidx++) {
            expr & fn = editor.get_fn(fidx);
            old_fns.push_back(fn);
            unsigned arity = editor.get_arity(fidx);
            if (arity > 1) {
                expr new_type = pack_as_unary(mlocal_type(fn), arity);
                fn = update_mlocal(fn, new_type);
                modified = true;
            }
        }
        if (!modified) return e;
        update_apps_fn updt(m_ctx, old_fns, editor);
        for (unsigned fidx = 0; fidx < editor.get_num_fns(); fidx++) {
            buffer<expr> & eqs = editor.get_eqs_of(fidx);
            for (expr & eq : eqs)
                eq = updt(eq);
        }
        return editor.repack();
    }
};

expr pack_equations_domain(type_context & ctx, expr const & e) {
    return sigma_packer_fn(ctx)(e);
}
}
<|endoftext|>


<commit_before>/*
 * LicenseVerifier.cpp
 *
 *  Created on: Nov 17, 2019
 *      Author: GC
 */
#include <cmath>
#include <algorithm>
#include <licensecc_properties.h>

#include "license_verifier.hpp"
#include "../pc_identifier/pc_identifier_facade.hpp"
#include "../base/StringUtils.h"
#include "../os/signature_verifier.hpp"

namespace license {
using namespace std;

LicenseVerifier::LicenseVerifier(EventRegistry& er) : m_event_registry(er) {}

LicenseVerifier::~LicenseVerifier() {}

FUNCTION_RETURN LicenseVerifier::verify_signature(const FullLicenseInfo& licInfo) {
	const string licInfoData(licInfo.printForSign());

	FUNCTION_RETURN ret = license::os::verify_signature(licInfoData, licInfo.license_signature);

	if (ret == FUNC_RET_OK) {
		m_event_registry.addEvent(SIGNATURE_VERIFIED, licInfo.source);
	} else {
		m_event_registry.addEvent(LICENSE_CORRUPTED, licInfo.source);
	}
	return ret;
}

// TODO: split in different classes
FUNCTION_RETURN LicenseVerifier::verify_limits(const FullLicenseInfo& licInfo) {
	bool is_valid = LCC_VERIFY_MAGIC(licInfo);
	if (!is_valid) {
		m_event_registry.addEvent(LICENSE_CORRUPTED, licInfo.source.c_str());
	}
	const time_t now = time(nullptr);
	auto expiry = licInfo.m_limits.find(PARAM_EXPIRY_DATE);
	if (is_valid && expiry != licInfo.m_limits.end()) {
		if (seconds_from_epoch(expiry->second) < now) {
			m_event_registry.addEvent(PRODUCT_EXPIRED, licInfo.source.c_str(), ("Expired " + expiry->second).c_str());
			is_valid = false;
		}
	}
	const auto start_date = licInfo.m_limits.find(PARAM_BEGIN_DATE);
	if (is_valid && start_date != licInfo.m_limits.end()) {
		if (seconds_from_epoch(start_date->second) > now) {
			m_event_registry.addEvent(PRODUCT_EXPIRED, licInfo.source.c_str(),
									  ("Valid from " + start_date->second).c_str());
			is_valid = false;
		}
	}
	const auto client_sig = licInfo.m_limits.find(PARAM_CLIENT_SIGNATURE);
	if (is_valid && client_sig != licInfo.m_limits.end()) {
		const LCC_EVENT_TYPE event = pc_identifier::PcIdentifierFacade::validate_pc_signature(client_sig->second);
		m_event_registry.addEvent(event, licInfo.source);
		is_valid = is_valid && (event == LICENSE_OK);
	}
	return is_valid ? FUNC_RET_OK : FUNC_RET_ERROR;
}

LicenseInfo LicenseVerifier::toLicenseInfo(const FullLicenseInfo& fullLicInfo) const {
	LicenseInfo info;
	info.license_type = LCC_LOCAL;

	const auto expiry = fullLicInfo.m_limits.find(PARAM_EXPIRY_DATE);
	if (expiry != fullLicInfo.m_limits.end()) {
		strncpy(info.expiry_date, expiry->second.c_str(), sizeof(info.expiry_date));
		info.has_expiry = true;
		const double secs = difftime(seconds_from_epoch(expiry->second), time(nullptr));
		info.days_left = max((int)round(secs / (60 * 60 * 24)), 0);
	} else {
		info.has_expiry = false;
		info.days_left = 9999;
		info.expiry_date[0] = '\0';
	}

	const auto start_date = fullLicInfo.m_limits.find(PARAM_BEGIN_DATE);
	if (start_date != fullLicInfo.m_limits.end()) {
	}

	const auto client_sig = fullLicInfo.m_limits.find(PARAM_CLIENT_SIGNATURE);
	info.linked_to_pc = (client_sig != fullLicInfo.m_limits.end());

	const auto proprietary_data = fullLicInfo.m_limits.find(PARAM_EXTRA_DATA);
	if (proprietary_data != fullLicInfo.m_limits.end()) {
		strncpy(info.proprietary_data, proprietary_data->second.c_str(), LCC_API_PROPRIETARY_DATA_SIZE);
	}
	return info;
}

} /* namespace license */
<commit_msg>minor fix<commit_after>/*
 * LicenseVerifier.cpp
 *
 *  Created on: Nov 17, 2019
 *      Author: GC
 */
#include <cmath>
#include <algorithm>
#include <licensecc_properties.h>

#include "license_verifier.hpp"
#include "../pc_identifier/pc_identifier_facade.hpp"
#include "../base/StringUtils.h"
#include "../os/signature_verifier.hpp"

namespace license {
using namespace std;

LicenseVerifier::LicenseVerifier(EventRegistry& er) : m_event_registry(er) {}

LicenseVerifier::~LicenseVerifier() {}

FUNCTION_RETURN LicenseVerifier::verify_signature(const FullLicenseInfo& licInfo) {
	const string licInfoData(licInfo.printForSign());

	FUNCTION_RETURN ret = license::os::verify_signature(licInfoData, licInfo.license_signature);

	if (ret == FUNC_RET_OK) {
		m_event_registry.addEvent(SIGNATURE_VERIFIED, licInfo.source);
	} else {
		m_event_registry.addEvent(LICENSE_CORRUPTED, licInfo.source);
	}
	return ret;
}

// TODO: split in different classes
FUNCTION_RETURN LicenseVerifier::verify_limits(const FullLicenseInfo& lic_info) {
	bool is_valid = LCC_VERIFY_MAGIC;
	if (!is_valid) {
		m_event_registry.addEvent(LICENSE_CORRUPTED, lic_info.source.c_str());
	}
	const time_t now = time(nullptr);
	auto expiry = lic_info.m_limits.find(PARAM_EXPIRY_DATE);
	if (is_valid && expiry != lic_info.m_limits.end()) {
		if (seconds_from_epoch(expiry->second) < now) {
			m_event_registry.addEvent(PRODUCT_EXPIRED, lic_info.source.c_str(), ("Expired " + expiry->second).c_str());
			is_valid = false;
		}
	}
	const auto start_date = lic_info.m_limits.find(PARAM_BEGIN_DATE);
	if (is_valid && start_date != lic_info.m_limits.end()) {
		if (seconds_from_epoch(start_date->second) > now) {
			m_event_registry.addEvent(PRODUCT_EXPIRED, lic_info.source.c_str(),
									  ("Valid from " + start_date->second).c_str());
			is_valid = false;
		}
	}
	const auto client_sig = lic_info.m_limits.find(PARAM_CLIENT_SIGNATURE);
	if (is_valid && client_sig != lic_info.m_limits.end()) {
		const LCC_EVENT_TYPE event = pc_identifier::PcIdentifierFacade::validate_pc_signature(client_sig->second);
		m_event_registry.addEvent(event, lic_info.source);
		is_valid = is_valid && (event == LICENSE_OK);
	}
	return is_valid ? FUNC_RET_OK : FUNC_RET_ERROR;
}

LicenseInfo LicenseVerifier::toLicenseInfo(const FullLicenseInfo& fullLicInfo) const {
	LicenseInfo info;
	info.license_type = LCC_LOCAL;

	const auto expiry = fullLicInfo.m_limits.find(PARAM_EXPIRY_DATE);
	if (expiry != fullLicInfo.m_limits.end()) {
		strncpy(info.expiry_date, expiry->second.c_str(), sizeof(info.expiry_date));
		info.has_expiry = true;
		const double secs = difftime(seconds_from_epoch(expiry->second), time(nullptr));
		info.days_left = max((int)round(secs / (60 * 60 * 24)), 0);
	} else {
		info.has_expiry = false;
		info.days_left = 9999;
		info.expiry_date[0] = '\0';
	}

	const auto start_date = fullLicInfo.m_limits.find(PARAM_BEGIN_DATE);
	if (start_date != fullLicInfo.m_limits.end()) {
	}

	const auto client_sig = fullLicInfo.m_limits.find(PARAM_CLIENT_SIGNATURE);
	info.linked_to_pc = (client_sig != fullLicInfo.m_limits.end());

	const auto proprietary_data = fullLicInfo.m_limits.find(PARAM_EXTRA_DATA);
	if (proprietary_data != fullLicInfo.m_limits.end()) {
		strncpy(info.proprietary_data, proprietary_data->second.c_str(), LCC_API_PROPRIETARY_DATA_SIZE);
	}
	return info;
}

} /* namespace license */
<|endoftext|>


<commit_before>#include <memory>
#include <vector>
#include "auto-wrap.h"
#include "patch.h"
#include <emscripten/bind.h>
#include <emscripten/val.h>

using std::vector;

template <>
inline Patch const *emscripten::val::as<Patch const *>(void) const {
  using namespace emscripten;
  using namespace internal;

  EM_DESTRUCTORS destructors;
  EM_GENERIC_WIRE_TYPE result = _emval_as(
    handle,
    TypeID<AllowedRawPointer<Patch const>>::get(),
    &destructors
  );
  DestructorsRunner destructors_runner(destructors);

  return fromGenericWireType<Patch *>(result);
}

Patch *constructor(emscripten::val value) {
  bool merge_adjacent_hunks = false;
  if (value.as<bool>() && value["mergeAdjacentHunks"].as<bool>()) {
    merge_adjacent_hunks = true;
  }
  return new Patch(merge_adjacent_hunks);
}

vector<uint8_t> serialize(Patch const &patch) {
  vector<uint8_t> output;
  Serializer serializer(output);
  patch.serialize(serializer);
  return output;
}

Patch *compose(vector<Patch const *> const &patches) {
  return new Patch(patches);
}

Patch *deserialize(const vector<uint8_t> &bytes) {
  Deserializer deserializer(bytes);
  return new Patch(deserializer);
}

template <typename T>
void hunk_set_noop(Patch::Hunk & hunk, T const &) {}

EMSCRIPTEN_BINDINGS(Patch) {
  emscripten::class_<Patch>("Patch")
    .constructor<>()
    .constructor<emscripten::val>(WRAP_STATIC(&constructor), emscripten::allow_raw_pointers())
    .function("splice", WRAP_OVERLOAD(&Patch::splice, bool (Patch::*)(Point, Point, Point)))
    .function("splice", WRAP_OVERLOAD(&Patch::splice, bool (Patch::*)(Point, Point, Point, std::unique_ptr<Text>, std::unique_ptr<Text>)))
    .function("spliceOld", WRAP(&Patch::splice_old))
    .function("copy", WRAP(&Patch::copy))
    .function("invert", WRAP(&Patch::invert))
    .function("getHunks", WRAP(&Patch::get_hunks))
    .function("getHunksInNewRange", WRAP_OVERLOAD(&Patch::get_hunks_in_new_range, std::vector<Patch::Hunk> (Patch::*)(Point, Point)))
    .function("getHunksInNewRange", WRAP_OVERLOAD(&Patch::get_hunks_in_new_range, std::vector<Patch::Hunk> (Patch::*)(Point, Point, bool)))
    .function("getHunksInOldRange", WRAP(&Patch::get_hunks_in_old_range))
    .function("getHunkCount", WRAP(&Patch::get_hunk_count))
    .function("hunkForOldPosition", WRAP(&Patch::hunk_for_old_position))
    .function("hunkForNewPosition", WRAP(&Patch::hunk_for_new_position))
    .function("rebalance", WRAP(&Patch::rebalance))
    .function("serialize", WRAP(&serialize))
    .class_function("compose", WRAP_STATIC(&compose), emscripten::allow_raw_pointers())
    .class_function("deserialize", WRAP_STATIC(&deserialize), emscripten::allow_raw_pointers());

  emscripten::value_object<Patch::Hunk>("Hunk")
    .field("oldStart", WRAP_FIELD(Patch::Hunk, old_start))
    .field("oldEnd", WRAP_FIELD(Patch::Hunk, old_end))
    .field("newStart", WRAP_FIELD(Patch::Hunk, new_start))
    .field("newEnd", WRAP_FIELD(Patch::Hunk, new_end))
    .field("oldText", WRAP_FIELD(Patch::Hunk, old_text))
    .field("newText", WRAP_FIELD(Patch::Hunk, new_text));
}
<commit_msg>Get emscripten patch binding compiling again<commit_after>#include <memory>
#include <vector>
#include "auto-wrap.h"
#include "patch.h"
#include <emscripten/bind.h>
#include <emscripten/val.h>

using std::runtime_error;
using std::string;
using std::vector;

template <>
inline Patch const *emscripten::val::as<Patch const *>(void) const {
  using namespace emscripten;
  using namespace internal;

  EM_DESTRUCTORS destructors;
  EM_GENERIC_WIRE_TYPE result = _emval_as(
    handle,
    TypeID<AllowedRawPointer<Patch const>>::get(),
    &destructors
  );
  DestructorsRunner destructors_runner(destructors);

  return fromGenericWireType<Patch *>(result);
}

Patch *constructor(emscripten::val value) {
  bool merge_adjacent_changes = false;
  if (value.as<bool>() && value["mergeAdjacentChanges"].as<bool>()) {
    merge_adjacent_changes = true;
  }
  return new Patch(merge_adjacent_changes);
}

vector<uint8_t> serialize(Patch const &patch) {
  vector<uint8_t> output;
  Serializer serializer(output);
  patch.serialize(serializer);
  return output;
}

Patch *compose(vector<Patch const *> const &patches) {
  return new Patch(patches);
}

Patch *deserialize(const vector<uint8_t> &bytes) {
  Deserializer deserializer(bytes);
  return new Patch(deserializer);
}

void splice(Patch &patch, PointWrapper start, PointWrapper deleted_extent, PointWrapper inserted_extent) {
  bool result = patch.splice(
    start,
    deleted_extent,
    inserted_extent
  );
  if (!result) throw runtime_error("Can't splice into a frozen patch");
}

void splice_with_text(Patch &patch, PointWrapper start, PointWrapper deleted_extent, PointWrapper inserted_extent,
                      const string &deleted_text, const string &inserted_text) {
  bool result = patch.splice(
    start,
    deleted_extent,
    inserted_extent,
    Text(deleted_text.begin(), deleted_text.end()),
    Text(inserted_text.begin(), inserted_text.end())
  );
  if (!result) throw runtime_error("Can't splice into a frozen patch");
}

template <typename T>
void change_set_noop(Patch::Change &change, T const &) {}

EMSCRIPTEN_BINDINGS(Patch) {
  emscripten::class_<Patch>("Patch")
    .constructor<>()
    .constructor<emscripten::val>(WRAP_STATIC(&constructor), emscripten::allow_raw_pointers())
    .function("splice", splice)
    .function("splice", splice_with_text)
    .function("spliceOld", WRAP(&Patch::splice_old))
    .function("copy", WRAP(&Patch::copy))
    .function("invert", WRAP(&Patch::invert))
    .function("getChanges", WRAP(&Patch::get_changes))
    .function("getChangesInNewRange", WRAP_OVERLOAD(&Patch::get_changes_in_new_range, std::vector<Patch::Change> (Patch::*)(Point, Point, bool)))
    .function("getChangesInOldRange", WRAP(&Patch::get_changes_in_old_range))
    .function("getChangeCount", WRAP(&Patch::get_change_count))
    .function("changeForOldPosition", WRAP(&Patch::change_for_old_position))
    .function("changeForNewPosition", WRAP(&Patch::change_for_new_position))
    .function("rebalance", WRAP(&Patch::rebalance))
    .function("serialize", WRAP(&serialize))
    .class_function("compose", WRAP_STATIC(&compose), emscripten::allow_raw_pointers())
    .class_function("deserialize", WRAP_STATIC(&deserialize), emscripten::allow_raw_pointers());

  emscripten::value_object<Patch::Change>("Change")
    .field("oldStart", WRAP_FIELD(Patch::Change, old_start))
    .field("oldEnd", WRAP_FIELD(Patch::Change, old_end))
    .field("newStart", WRAP_FIELD(Patch::Change, new_start))
    .field("newEnd", WRAP_FIELD(Patch::Change, new_end))
    .field("oldText", WRAP_FIELD(Patch::Change, old_text))
    .field("newText", WRAP_FIELD(Patch::Change, new_text));
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <set>

using namespace std;

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

  ifstream file;
  file.open(argv[1]);

  string line;
  vector<vector <string> > source;
  set<string> dict;

  bool split = false;
  count i = 0;

  while(getline(file, line)) {

    if (line.compare("END OF INPUT") == 0) {
      split = true;
    }

    if (split) {
      dict.push(line);
    }

    else {
      source.push_back(vector <string>);
      sorce[i].push_back(line);
      i++;
    }
  }

  for (int j = 0; j < i; j++) {

  }

  return 0;
}
<commit_msg>fixes, read errything right, now 4 logic<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <vector>

using namespace std;

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

  ifstream file;
  file.open(argv[1]);

  string line;
  vector<vector <string> > source;
  set<string> dict;

  bool split = false;
  int i = 0;

  while(getline(file, line)) {

    if (line.compare("END OF INPUT") == 0) {
      split = true;
    }

    if (split) {
      dict.insert(line);
    }

    else {
      source.push_back(vector<string>());
      source[i].push_back(line);
      i++;
    }
  }

  for(int row = 0; row < i; row++) {

    for(int col = 0; col < source[row].size(); col++) {

    }

    //substitute

    //add

    //subtract

    cout << source[row].size() - 1 << endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "Math/Polynomial.h"
#include "Math/Derivator.h"
#include "Math/IFunction.h"
#include "Math/Functor.h"
#include "Math/WrappedFunction.h"
#include "Math/WrappedParamFunction.h"
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>

#ifdef HAVE_ROOTLIBS

#include "TStopwatch.h"
#include "TF1.h"
#include "Math/WrappedTF1.h"
#include "Math/WrappedMultiTF1.h"
#include "Math/DistFunc.h"

#endif

const double ERRORLIMIT = 1E-5;

typedef double ( * FP ) ( double, void * );
typedef double ( * FP2 ) ( double );

double myfunc ( double x, void * ) {

  return std::pow( x, 1.5);
}

double myfunc2 ( double x) {
  return std::pow( x, 1.5);
}

int testDerivation() {

   int status = 0;

  // Derivative of an IGenFunction
  // Works when compiled c++, compiled ACLiC, interpreted by CINT
  ROOT::Math::Polynomial *f1 = new ROOT::Math::Polynomial(2);

  std::vector<double> p(3);
  p[0] = 2;
  p[1] = 3;
  p[2] = 4;
  f1->SetParameters(&p[0]);

  ROOT::Math::Derivator *der = new ROOT::Math::Derivator(*f1);

  double step = 1E-8;
  double x0 = 2;

  der->SetFunction(*f1);
  double result = der->Eval(x0);
  std::cout << "Derivative of function inheriting from IGenFunction f(x) = 2 + 3x + 4x^2 at x = 2" << std::endl;
  std::cout << "Return code:  " << der->Status() << std::endl;
  std::cout << "Result:       " << result << " +/- " << der->Error() << std::endl;
  std::cout << "Exact result: " << f1->Derivative(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(*f1, x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0, step) << std::endl << std::endl;;
  status += fabs(result-f1->Derivative(x0)) > ERRORLIMIT;

  // Derivative of a free function
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  FP f2 = &myfunc;
  der->SetFunction(f2);

  std::cout << "Derivative of a free function f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->EvalCentral(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;

  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->EvalCentral(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // Derivative of a free function wrapped in an IGenFunction
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  ROOT::Math::Functor1D *f3 = new ROOT::Math::Functor1D (&myfunc2);

  std::cout << "Derivative of a free function wrapped in a Functor f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->Eval( *f3, x0) << std::endl;
  der->SetFunction(*f3);
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;
  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->Eval( *f3, x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // tets case when an empty Derivator is used

  ROOT::Math::Derivator der2;
  std::cout << "Tes a derivator without a function" << std::endl;
  std::cout << der2.Eval(1.0) << std::endl;

  // Derivative of a multidim TF1 function

// #ifdef LATER
//   TF2 * f2d = new TF2("f2d","x*x + y*y",-10,10,-10,10);
//   // find gradient at x={1,1}
//   double vx[2] = {1.,2.};
//   ROOT::Math::WrappedTF1 fx(*f2d);

//   std::cout << "Derivative of a  f(x,y) = x^2 + y^2 at x = 1,y=2" << std::endl;
//   std::cout << "df/dx  = " << der->EvalCentral(fx,1.) << std::endl;
//   WrappedFunc fy(*f2d,0,vx);
//   std::cout << "df/dy  = " << der->EvalCentral(fy,2.) << std::endl;
// #endif

  return status;
}

#ifdef HAVE_ROOTLIBS

void testDerivPerf() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances....\n\n";

  ROOT::Math::Polynomial f1(2);
  double p[3] = {2,3,4};
  f1.SetParameters(p);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("pol","pol2",0,10);
  f2.SetParameters(p);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

}

double userFunc(const double *x, const double *y) {
   return std::exp(-x[0]);
}
double userFunc1(double x) { return userFunc(&x, 0); }

double userFunc2(const double * x) { return userFunc(x, 0); }

void testDerivPerfUser() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a User function\n\n";

  ROOT::Math::WrappedFunction<> f1(userFunc1);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("uf",userFunc,0,10,0);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

  //typedef double( * FN ) (const double *, const double * );
  ROOT::Math::WrappedMultiFunction<> f3(userFunc2,1);
  timer.Start();
  s1 = 0;
  double xx[1];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f3,xx,0);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator Multi:\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

double gausFunc( const double * x, const double * p) {
   return p[0] * ROOT::Math::normal_pdf(x[0], p[2], p[1] );
}

void testDerivPerfParam() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a Gaussian Param function\n\n";

   //TF1 gaus("gaus","gaus",-10,10);
   TF1 gaus("gaus",gausFunc,-10,10,3);
  double params[3] = {10,1.,1.};
  gaus.SetParameters(params);

  ROOT::Math::WrappedTF1 f1(gaus);

  TStopwatch timer;
  int n = 300000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     // param derivatives
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,0);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,1);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator (1D) :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  ROOT::Math::WrappedParamFunction<> f2(&gausFunc,1,params,params+3);
  double xx[1];

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,0);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,1);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(ND):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  // test that func parameters have not been changed
  assert( std::fabs(params[0] - gaus.GetParameter(0)) < 1.E-15);
  assert( std::fabs(params[1] - gaus.GetParameter(1)) < 1.E-15);
  assert( std::fabs(params[2] - gaus.GetParameter(2)) < 1.E-15);

  timer.Start();
  s1 = 0;
  double g[3];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     gaus.GradientPar(xx,g,1E-8);
     s1 += g[0];
     s1 += g[1];
     s1 += g[2];
  }
  timer.Stop();
  std::cout << "Time using TF1::ParamGradient:\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

#endif

int main() {

  int status = 0;

  status += testDerivation();

#ifdef HAVE_ROOTLIBS
  testDerivPerf();
  testDerivPerfUser();
  testDerivPerfParam();
#endif

  return status;

}
<commit_msg>Fix a warning<commit_after>#include "Math/Polynomial.h"
#include "Math/Derivator.h"
#include "Math/IFunction.h"
#include "Math/Functor.h"
#include "Math/WrappedFunction.h"
#include "Math/WrappedParamFunction.h"
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>

#ifdef HAVE_ROOTLIBS

#include "TStopwatch.h"
#include "TF1.h"
#include "Math/WrappedTF1.h"
#include "Math/WrappedMultiTF1.h"
#include "Math/DistFunc.h"

#endif

const double ERRORLIMIT = 1E-5;

typedef double ( * FP ) ( double, void * );
typedef double ( * FP2 ) ( double );

double myfunc ( double x, void * ) {

  return std::pow( x, 1.5);
}

double myfunc2 ( double x) {
  return std::pow( x, 1.5);
}

int testDerivation() {

   int status = 0;

  // Derivative of an IGenFunction
  // Works when compiled c++, compiled ACLiC, interpreted by CINT
  ROOT::Math::Polynomial *f1 = new ROOT::Math::Polynomial(2);

  std::vector<double> p(3);
  p[0] = 2;
  p[1] = 3;
  p[2] = 4;
  f1->SetParameters(&p[0]);

  ROOT::Math::Derivator *der = new ROOT::Math::Derivator(*f1);

  double step = 1E-8;
  double x0 = 2;

  der->SetFunction(*f1);
  double result = der->Eval(x0);
  std::cout << "Derivative of function inheriting from IGenFunction f(x) = 2 + 3x + 4x^2 at x = 2" << std::endl;
  std::cout << "Return code:  " << der->Status() << std::endl;
  std::cout << "Result:       " << result << " +/- " << der->Error() << std::endl;
  std::cout << "Exact result: " << f1->Derivative(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(*f1, x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0, step) << std::endl << std::endl;;
  status += fabs(result-f1->Derivative(x0)) > ERRORLIMIT;

  // Derivative of a free function
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  FP f2 = &myfunc;
  der->SetFunction(f2);

  std::cout << "Derivative of a free function f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->EvalCentral(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;

  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->EvalCentral(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // Derivative of a free function wrapped in an IGenFunction
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  ROOT::Math::Functor1D *f3 = new ROOT::Math::Functor1D (&myfunc2);

  std::cout << "Derivative of a free function wrapped in a Functor f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->Eval( *f3, x0) << std::endl;
  der->SetFunction(*f3);
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;
  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->Eval( *f3, x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // tets case when an empty Derivator is used

  ROOT::Math::Derivator der2;
  std::cout << "Tes a derivator without a function" << std::endl;
  std::cout << der2.Eval(1.0) << std::endl;

  // Derivative of a multidim TF1 function

// #ifdef LATER
//   TF2 * f2d = new TF2("f2d","x*x + y*y",-10,10,-10,10);
//   // find gradient at x={1,1}
//   double vx[2] = {1.,2.};
//   ROOT::Math::WrappedTF1 fx(*f2d);

//   std::cout << "Derivative of a  f(x,y) = x^2 + y^2 at x = 1,y=2" << std::endl;
//   std::cout << "df/dx  = " << der->EvalCentral(fx,1.) << std::endl;
//   WrappedFunc fy(*f2d,0,vx);
//   std::cout << "df/dy  = " << der->EvalCentral(fy,2.) << std::endl;
// #endif

  return status;
}

#ifdef HAVE_ROOTLIBS

void testDerivPerf() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances....\n\n";

  ROOT::Math::Polynomial f1(2);
  double p[3] = {2,3,4};
  f1.SetParameters(p);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("pol","pol2",0,10);
  f2.SetParameters(p);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

}

double userFunc(const double *x, const double *) {
   return std::exp(-x[0]);
}
double userFunc1(double x) { return userFunc(&x, 0); }

double userFunc2(const double * x) { return userFunc(x, 0); }

void testDerivPerfUser() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a User function\n\n";

  ROOT::Math::WrappedFunction<> f1(userFunc1);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("uf",userFunc,0,10,0);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

  //typedef double( * FN ) (const double *, const double * );
  ROOT::Math::WrappedMultiFunction<> f3(userFunc2,1);
  timer.Start();
  s1 = 0;
  double xx[1];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f3,xx,0);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator Multi:\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

double gausFunc( const double * x, const double * p) {
   return p[0] * ROOT::Math::normal_pdf(x[0], p[2], p[1] );
}

void testDerivPerfParam() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a Gaussian Param function\n\n";

   //TF1 gaus("gaus","gaus",-10,10);
   TF1 gaus("gaus",gausFunc,-10,10,3);
  double params[3] = {10,1.,1.};
  gaus.SetParameters(params);

  ROOT::Math::WrappedTF1 f1(gaus);

  TStopwatch timer;
  int n = 300000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     // param derivatives
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,0);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,1);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator (1D) :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  ROOT::Math::WrappedParamFunction<> f2(&gausFunc,1,params,params+3);
  double xx[1];

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,0);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,1);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(ND):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  // test that func parameters have not been changed
  assert( std::fabs(params[0] - gaus.GetParameter(0)) < 1.E-15);
  assert( std::fabs(params[1] - gaus.GetParameter(1)) < 1.E-15);
  assert( std::fabs(params[2] - gaus.GetParameter(2)) < 1.E-15);

  timer.Start();
  s1 = 0;
  double g[3];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     gaus.GradientPar(xx,g,1E-8);
     s1 += g[0];
     s1 += g[1];
     s1 += g[2];
  }
  timer.Stop();
  std::cout << "Time using TF1::ParamGradient:\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

#endif

int main() {

  int status = 0;

  status += testDerivation();

#ifdef HAVE_ROOTLIBS
  testDerivPerf();
  testDerivPerfUser();
  testDerivPerfParam();
#endif

  return status;

}
<|endoftext|>


<commit_before>#include "Lifter.h"
#include "../RobotMap.h"
#include "../Commands/ControlLifter.h"

Lifter::Lifter()
	: Subsystem("Lifter")
{
	m_cLiftMotorL = new Talon(LIFTERL);
	m_cLiftMotorR = new Talon(LIFTERR);
	m_cLimitSwitch = new DigitalInput(LIFTERSWITCH);
	m_cEncoderL = new Encoder(ENCODERL_A, ENCODERL_B, false);
	m_cEncoderR = new Encoder(ENCODERR_A, ENCODERR_B, false);
	m_dLifterPosition = 0;
}

Lifter::~Lifter(){
	delete m_cEncoderL;
	delete m_cEncoderR;
	delete m_cLimitSwitch;
	delete m_cLiftMotorL;
	delete m_cLiftMotorR;
}

void Lifter::InitDefaultCommand()
{
	// Set the default command for a subsystem here.
	SetDefaultCommand(new ControlLifter());
}

// Put methods for controlling this subsystem
// here. Call these from Commands.

double Lifter::getLeftSpeed(){
	return m_cLiftMotorL->Get();
}

double Lifter::getRightSpeed(){
	return m_cLiftMotorR->Get();
}
//Keeps motors level
void Lifter::Balance(float fDirection)
{
	m_dEncoderLeftValue = m_cEncoderL->Get();
	m_dEncoderRightValue = m_cEncoderR->Get();
	//Get fraction from difference in encoder values
	//fDirection ensures that difference will be same proportion for all axis values
	//Code will only do something if fDirection is not 0, aka stick is not neutral
	if(fDirection != 0){
		double dRateDifference;
		//prevents divide-by-zero errors in case of encoders at 0
		if((m_dEncoderLeftValue+m_dEncoderRightValue) != 0){
			dRateDifference = fDirection*(m_dEncoderLeftValue-m_dEncoderRightValue)/(m_dEncoderLeftValue+m_dEncoderRightValue);
		}else{
			dRateDifference = 0;
		}

		//compensates for difference in motors using encoder rate difference
		if(fDirection > 0)
		{
			m_cLiftMotorL->SetSpeed(fDirection-dRateDifference);
			m_cLiftMotorR->SetSpeed(fDirection+dRateDifference);
		}
		else if(not m_cLimitSwitch->Get())
		{
			m_cLiftMotorL->SetSpeed(fDirection+dRateDifference);
			m_cLiftMotorR->SetSpeed(fDirection-dRateDifference);
		}
		//reset encoders when lifter is at the bottom
		if(m_cLimitSwitch->Get()){
			m_cEncoderL->Reset();
			m_cEncoderR->Reset();
		}
	}
}
<commit_msg>making a warning go away<commit_after>#include "Lifter.h"
#include "../RobotMap.h"
#include "../Commands/ControlLifter.h"

Lifter::Lifter()
	: Subsystem("Lifter")
{
	m_cLiftMotorL = new Talon(LIFTERL);
	m_cLiftMotorR = new Talon(LIFTERR);
	m_cLimitSwitch = new DigitalInput(LIFTERSWITCH);
	m_cEncoderL = new Encoder(ENCODERL_A, ENCODERL_B, false);
	m_cEncoderR = new Encoder(ENCODERR_A, ENCODERR_B, false);
	m_dLifterPosition = 0;
	m_dEncoderLeftValue=0;
	m_dEncoderRightValue=0;
}

Lifter::~Lifter(){
	delete m_cEncoderL;
	delete m_cEncoderR;
	delete m_cLimitSwitch;
	delete m_cLiftMotorL;
	delete m_cLiftMotorR;
}

void Lifter::InitDefaultCommand()
{
	// Set the default command for a subsystem here.
	SetDefaultCommand(new ControlLifter());
}

// Put methods for controlling this subsystem
// here. Call these from Commands.

double Lifter::getLeftSpeed(){
	return m_cLiftMotorL->Get();
}

double Lifter::getRightSpeed(){
	return m_cLiftMotorR->Get();
}
//Keeps motors level
void Lifter::Balance(float fDirection)
{
	m_dEncoderLeftValue = m_cEncoderL->Get();
	m_dEncoderRightValue = m_cEncoderR->Get();
	//Get fraction from difference in encoder values
	//fDirection ensures that difference will be same proportion for all axis values
	//Code will only do something if fDirection is not 0, aka stick is not neutral
	if(fDirection != 0){
		double dRateDifference;
		//prevents divide-by-zero errors in case of encoders at 0
		if((m_dEncoderLeftValue+m_dEncoderRightValue) != 0){
			dRateDifference = fDirection*(m_dEncoderLeftValue-m_dEncoderRightValue)/(m_dEncoderLeftValue+m_dEncoderRightValue);
		}else{
			dRateDifference = 0;
		}

		//compensates for difference in motors using encoder rate difference
		if(fDirection > 0)
		{
			m_cLiftMotorL->SetSpeed(fDirection-dRateDifference);
			m_cLiftMotorR->SetSpeed(fDirection+dRateDifference);
		}
		else if(not m_cLimitSwitch->Get())
		{
			m_cLiftMotorL->SetSpeed(fDirection+dRateDifference);
			m_cLiftMotorR->SetSpeed(fDirection-dRateDifference);
		}
		//reset encoders when lifter is at the bottom
		if(m_cLimitSwitch->Get()){
			m_cEncoderL->Reset();
			m_cEncoderR->Reset();
		}
	}
}
<|endoftext|>