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

#ifndef _SV_SALMATHUTILS_HXX
    #include <salmathutils.hxx>
#endif

// =======================================================================

// =======================================================================

#define Swap( x, y ) { x ^= y; y ^= x; x ^= y; }

// =======================================================================

// =======================================================================

// Storage free swapping using XOR

void CSwap ( char &rX, char &rY )
{
    Swap( rX, rY );
} // CSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void UCSwap ( unsigned char &rX, unsigned char &rY )
{
    Swap( rX, rY );
} // UCSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void SSwap ( short &rX, short &rY )
{
    Swap( rX, rY );
} // SSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void USSwap ( unsigned short &rX, unsigned short &rY )
{
    Swap( rX, rY );
} // USSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void LSwap ( long &rX, long &rY )
{
    Swap( rX, rY );
} // LSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void ULSwap ( unsigned long &rX, unsigned long &rY )
{
    Swap( rX, rY );
} // ULSwap

// =======================================================================

// =======================================================================

// -----------------------------------------------------------------------
//
// This way of measuring distance is also called the "Manhattan distance."
// Manhattan distance takes advantage of the fact that the sum of the
// lengths of the three components of a 3D vector is a rough approxima-
// tion of the vector's length.
//
// -----------------------------------------------------------------------

unsigned long  Euclidian2Norm ( const LRectCoorVector  pVec )
{
    unsigned long  ndist = 0;

    if ( pVec )
    {
        long           nDX  = 0;
        long           nDY  = 0;
        long           nDZ  = 0;
        unsigned long  nMax = 0;
        unsigned long  nMed = 0;
        unsigned long  nMin = 0;

        // Find |x'-x|, |y'-y|, and |z'-z| from (x,y,z) and (x',y',z')

        nDX = pVec[1].x - pVec[0].x;
        nDY = pVec[1].y - pVec[0].y;
        nDZ = pVec[1].z - pVec[0].z;

        nMax = (unsigned long)abs( nDX );
        nMed = (unsigned long)abs( nDY );
        nMin = (unsigned long)abs( nDZ );

        // Sort them (3 compares, 0-3 swaps)

        if ( nMax < nMed )
        {
            Swap( nMax, nMed );
        } // if

        if ( nMax < nMin )
        {
            Swap( nMax, nMin );
        } // if

        // Approximate Euclidian distance:
        //
        //    d = max + (11/32)*med + (1/4)*min
        //
        // with +/- 8% error, where the exact formulae for d is
        //
        //  || (x',y',z') - (x,y,z) || = { |x'-x|^2 + |y'-y|^2 + |z'-z|^2 }^(1/2)

        ndist = nMax + ( nMin >> 2UL )
                     + ( ( ( nMed << 3UL ) + ( nMed << 1UL ) + nMed ) >> 5UL );
    } // if

    return ndist;
} // RGBDistance

// =======================================================================

// =======================================================================

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.378); FILE MERGED 2006/09/01 17:57:31 kaib 1.4.378.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salmathutils.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 11:44:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _SV_SALMATHUTILS_HXX
    #include <salmathutils.hxx>
#endif

// =======================================================================

// =======================================================================

#define Swap( x, y ) { x ^= y; y ^= x; x ^= y; }

// =======================================================================

// =======================================================================

// Storage free swapping using XOR

void CSwap ( char &rX, char &rY )
{
    Swap( rX, rY );
} // CSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void UCSwap ( unsigned char &rX, unsigned char &rY )
{
    Swap( rX, rY );
} // UCSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void SSwap ( short &rX, short &rY )
{
    Swap( rX, rY );
} // SSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void USSwap ( unsigned short &rX, unsigned short &rY )
{
    Swap( rX, rY );
} // USSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void LSwap ( long &rX, long &rY )
{
    Swap( rX, rY );
} // LSwap

// -----------------------------------------------------------------------

// Storage free swapping using XOR

void ULSwap ( unsigned long &rX, unsigned long &rY )
{
    Swap( rX, rY );
} // ULSwap

// =======================================================================

// =======================================================================

// -----------------------------------------------------------------------
//
// This way of measuring distance is also called the "Manhattan distance."
// Manhattan distance takes advantage of the fact that the sum of the
// lengths of the three components of a 3D vector is a rough approxima-
// tion of the vector's length.
//
// -----------------------------------------------------------------------

unsigned long  Euclidian2Norm ( const LRectCoorVector  pVec )
{
    unsigned long  ndist = 0;

    if ( pVec )
    {
        long           nDX  = 0;
        long           nDY  = 0;
        long           nDZ  = 0;
        unsigned long  nMax = 0;
        unsigned long  nMed = 0;
        unsigned long  nMin = 0;

        // Find |x'-x|, |y'-y|, and |z'-z| from (x,y,z) and (x',y',z')

        nDX = pVec[1].x - pVec[0].x;
        nDY = pVec[1].y - pVec[0].y;
        nDZ = pVec[1].z - pVec[0].z;

        nMax = (unsigned long)abs( nDX );
        nMed = (unsigned long)abs( nDY );
        nMin = (unsigned long)abs( nDZ );

        // Sort them (3 compares, 0-3 swaps)

        if ( nMax < nMed )
        {
            Swap( nMax, nMed );
        } // if

        if ( nMax < nMin )
        {
            Swap( nMax, nMin );
        } // if

        // Approximate Euclidian distance:
        //
        //    d = max + (11/32)*med + (1/4)*min
        //
        // with +/- 8% error, where the exact formulae for d is
        //
        //  || (x',y',z') - (x,y,z) || = { |x'-x|^2 + |y'-y|^2 + |z'-z|^2 }^(1/2)

        ndist = nMax + ( nMin >> 2UL )
                     + ( ( ( nMed << 3UL ) + ( nMed << 1UL ) + nMed ) >> 5UL );
    } // if

    return ndist;
} // RGBDistance

// =======================================================================

// =======================================================================

<|endoftext|>


<commit_before>#include "kernel.h"
#include "geometries.h"
#include "ilwisdata.h"
#include "ellipsoid.h"
#include "geodeticdatum.h"
#include "projection.h"
#include "coordinatesystem.h"
#include "conventionalcoordinatesystem.h"
#include "proj4parameters.h"

using namespace Ilwis;

ConventionalCoordinateSystem::ConventionalCoordinateSystem() : _unit(sUNDEF)
{
}

ConventionalCoordinateSystem::ConventionalCoordinateSystem(const Resource &resource) : CoordinateSystem(resource),_unit(sUNDEF)
{
}

ConventionalCoordinateSystem::~ConventionalCoordinateSystem()
{
    _projection.set(0);
    _ellipsoid.set(0);
}

Coordinate ConventionalCoordinateSystem::coord2coord(const ICoordinateSystem &sourceCs, const Coordinate &crdSource) const
{
    //TODO isLatLon guard doesn't consider latlon cs other than WGS84!
    if (sourceCs->id() == id()) //  the 'real'isEqual test is too expensive here, as this method can be called 100000's of times (resample)
        return crdSource;
    LatLon ll = sourceCs->isLatLon() ? LatLon(crdSource.y,crdSource.x) : sourceCs->coord2latlon(crdSource);
    if ( ll.isValid()) {
        return isLatLon() ? ll : latlon2coord(ll);
    }
    return Coordinate();
}

LatLon ConventionalCoordinateSystem::coord2latlon(const Coordinate &crdSource) const
{
    LatLon pl = _projection->coord2latlon(crdSource);
    if (!pl.isValid())
        return llUNDEF;
    if (abs(pl.lon()) > 90)
        return llUNDEF;
    return pl;
}

Coordinate ConventionalCoordinateSystem::latlon2coord(const LatLon &ll) const
{
    Coordinate xy = _projection->latlon2coord(ll);
    if (xy == crdUNDEF)
        return crdUNDEF;
    return xy;

}

bool ConventionalCoordinateSystem::isEqual(const IlwisObject *obj) const
{
    if ( !obj || !hasType(obj->ilwisType(), itCONVENTIONALCOORDSYSTEM))
        return false;

    if(id() == obj->id())
        return true;

    const ConventionalCoordinateSystem *csy = static_cast<const ConventionalCoordinateSystem *>(obj);
    if ( !csy->isValid())
        return false;

    if ( ellipsoid().isValid() && ellipsoid()->isEqual(csy->ellipsoid())) {
        if ( csy->projection().isValid() && projection().isValid()){ //  special case; in general datums will be checked first
            if (csy->projection()->code() == "longlat" && projection()->code() == "longlat")
                return true;
        }
        if ( datum() && csy->datum()) {
            if  (datum()->code() == csy->datum()->code())
                    return true;
        } else {
            if ( csy->projection().isValid() && projection().isValid()) {
                return csy->projection()->isEqual(projection().ptr());
            }
        }
    }

    return false;
}

bool ConventionalCoordinateSystem::isUnknown() const
{
    return false;
}

bool ConventionalCoordinateSystem::canConvertToLatLon() const
{
    if ( _projection.isValid())    {
        return _projection->canConvertToLatLon();
    }
    return false;
}

bool ConventionalCoordinateSystem::canConvertToCoordinate() const
{
    if ( _projection.isValid())    {
        return _projection->canConvertToCoordinate();
    }
    return false;
}

QString ConventionalCoordinateSystem::toWKT(quint32 spaces) const
{
    QString wkt = "PROJCS[\"" + name() + "\"" + ",";
    QString geocs, proj, ell, datum;
    geocs += QString(" ").repeated(spaces);
    QString ending = spaces == 0 ? "" : "\n";
    if ( _datum){
        geocs += "GEOCS[\"";
        if ( name().indexOf("/") != -1){
            geocs += name().left( name().indexOf("/")).trimmed() + "\"";
        }else
            geocs += name() + "\"";

        datum = _datum->toWKT(spaces * 2);
    }
    QString primm = "PRIMEM[\"Greenwich\",0, AUTHORITY[\"EPSG\",8901\"]],";
    if ( _ellipsoid.isValid()){
        ell = _ellipsoid->toWKT(spaces * 2);
    }
    if ( _projection.isValid())
         proj= _projection->toWKT(spaces * 2) + ",";

    if ( geocs != ""){
        wkt += geocs + (datum !="" ? "," + datum : "") + "," + ell + primm + "]," + ending;
    }else
        wkt += ell + ",";
    wkt += proj;

    if ( _unit != ""){
        wkt += "UNIT[" + _unit + ",1.0]";
    }

    return wkt + "]";
}

QString ConventionalCoordinateSystem::toProj4() const
{
    if ( this->projection().isValid())
        return this->projection()->toProj4();
    else
        return QString("?");
}

QString ConventionalCoordinateSystem::unit() const
{
    return _unit;
}

void ConventionalCoordinateSystem::unit(const QString& unit)
{
    _unit = unit;
}

bool ConventionalCoordinateSystem::isCompatibleWith(const IlwisObject *obj) const
{
    if ( projection().isValid() && obj->isValid())
        return projection()->code() == obj->code();
    return false;
}

const std::unique_ptr<GeodeticDatum>& ConventionalCoordinateSystem::datum() const
{
    return _datum;
}

void ConventionalCoordinateSystem::setDatum(GeodeticDatum *datum)
{
    _datum.reset(datum);
}

IEllipsoid ConventionalCoordinateSystem::ellipsoid() const
{
    return _ellipsoid;
}

void ConventionalCoordinateSystem::setEllipsoid(const IEllipsoid &ell)
{
    _ellipsoid = ell;
    if ( _projection.isValid() && ell.isValid()){
        _projection->setParameter(Projection::pvELLCODE,ell->toProj4());
    }
}

bool ConventionalCoordinateSystem::isLatLon() const
{
    return _unit == "degrees";
}

IlwisTypes ConventionalCoordinateSystem::ilwisType() const
{
    return itCONVENTIONALCOORDSYSTEM;
}

bool ConventionalCoordinateSystem::isValid() const
{
    bool ok1 =  _projection.isValid();
    bool ok2 =_ellipsoid.isValid();

    return ok1 && ok2;
}

void ConventionalCoordinateSystem::setProjection(const IProjection &proj)
{
    _projection = proj;
    if ( proj->code().contains("longlat") || proj->code().contains("latlon"))
        _unit = "degrees";
}

IProjection ConventionalCoordinateSystem::projection() const
{
    return _projection;
}

bool ConventionalCoordinateSystem::prepare()
{
    return CoordinateSystem::prepare();
}

bool ConventionalCoordinateSystem::prepare(const QString &parms)
{
    Proj4Parameters proj4(parms);

    QString ell = proj4["ellps"];
    _ellipsoid = new Ellipsoid();
    if ( ell != sUNDEF) {
        _ellipsoid.prepare("code=" + ell);
    } else {
        QString laxis = proj4["a"];
        if ( laxis != sUNDEF) {
            QString saxis = proj4["b"];
            bool ok;
            double a = laxis.toDouble(&ok);
            if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name());
            double b = saxis.toDouble(&ok);
            if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name());

            double f = (a - b) / a;
            QString newName = _ellipsoid->setEllipsoid(a, f);
            _ellipsoid->name(newName);
        }
    }
    if ( proj4.hasDatum()) {
        _datum.reset(new GeodeticDatum());
        if ( proj4["dx"] != sUNDEF) {
            _datum->set7TransformationParameters(proj4["dx"].toDouble(),
                                                 proj4["dy"].toDouble(),
                                                 proj4["dz"].toDouble(),
                                                 proj4["rx"].toDouble(),
                                                 proj4["ry"].toDouble(),
                                                 proj4["rz"].toDouble(),
                                                 proj4["dscale"].toDouble());
        }
    }
    QString code = proj4["proj"];

    if ( code == sUNDEF) {
        kernel()->issues()->log(TR(ERR_INVALID_PROPERTY_FOR_2).arg("projection name", name()));
        return false;
    }
    code = "code=" + code;
    Resource prj = mastercatalog()->name2Resource(code, itPROJECTION);
    if ( !prj.isValid()) {
         return ERROR1(ERR_COULDNT_CREATE_OBJECT_FOR_1,"projection " + code );
    }
    bool ok =_projection.prepare(prj.id());
    _projection->setCoordinateSystem(this);
    if ( _projection.isValid())  {
        ok = _projection->prepare(parms);
    }
    QString unit = proj4["units"];
    if ( ok && (_projection->code().contains("longlat") || _projection->code().contains("latlon") || unit=="?"))
        _unit = "degrees";
    else{
        if ( unit == "m")
            _unit = "meter";
        else
            _unit = "feet";
    }

    return ok;
}

<commit_msg>lon was limited to -90,+90. shoudl of courde be 180,-180<commit_after>#include "kernel.h"
#include "geometries.h"
#include "ilwisdata.h"
#include "ellipsoid.h"
#include "geodeticdatum.h"
#include "projection.h"
#include "coordinatesystem.h"
#include "conventionalcoordinatesystem.h"
#include "proj4parameters.h"

using namespace Ilwis;

ConventionalCoordinateSystem::ConventionalCoordinateSystem() : _unit(sUNDEF)
{
}

ConventionalCoordinateSystem::ConventionalCoordinateSystem(const Resource &resource) : CoordinateSystem(resource),_unit(sUNDEF)
{
}

ConventionalCoordinateSystem::~ConventionalCoordinateSystem()
{
    _projection.set(0);
    _ellipsoid.set(0);
}

Coordinate ConventionalCoordinateSystem::coord2coord(const ICoordinateSystem &sourceCs, const Coordinate &crdSource) const
{
    //TODO isLatLon guard doesn't consider latlon cs other than WGS84!
    if (sourceCs->id() == id()) //  the 'real'isEqual test is too expensive here, as this method can be called 100000's of times (resample)
        return crdSource;
    LatLon ll = sourceCs->isLatLon() ? LatLon(crdSource.y,crdSource.x) : sourceCs->coord2latlon(crdSource);
    if ( ll.isValid()) {
        return isLatLon() ? ll : latlon2coord(ll);
    }
    return Coordinate();
}

LatLon ConventionalCoordinateSystem::coord2latlon(const Coordinate &crdSource) const
{
    LatLon pl = _projection->coord2latlon(crdSource);
    if (!pl.isValid())
        return llUNDEF;
    if (abs(pl.lon()) > 180)
        return llUNDEF;
    return pl;
}

Coordinate ConventionalCoordinateSystem::latlon2coord(const LatLon &ll) const
{
    Coordinate xy = _projection->latlon2coord(ll);
    if (xy == crdUNDEF)
        return crdUNDEF;
    return xy;

}

bool ConventionalCoordinateSystem::isEqual(const IlwisObject *obj) const
{
    if ( !obj || !hasType(obj->ilwisType(), itCONVENTIONALCOORDSYSTEM))
        return false;

    if(id() == obj->id())
        return true;

    const ConventionalCoordinateSystem *csy = static_cast<const ConventionalCoordinateSystem *>(obj);
    if ( !csy->isValid())
        return false;

    if ( ellipsoid().isValid() && ellipsoid()->isEqual(csy->ellipsoid())) {
        if ( csy->projection().isValid() && projection().isValid()){ //  special case; in general datums will be checked first
            if (csy->projection()->code() == "longlat" && projection()->code() == "longlat")
                return true;
        }
        if ( datum() && csy->datum()) {
            if  (datum()->code() == csy->datum()->code())
                    return true;
        } else {
            if ( csy->projection().isValid() && projection().isValid()) {
                return csy->projection()->isEqual(projection().ptr());
            }
        }
    }

    return false;
}

bool ConventionalCoordinateSystem::isUnknown() const
{
    return false;
}

bool ConventionalCoordinateSystem::canConvertToLatLon() const
{
    if ( _projection.isValid())    {
        return _projection->canConvertToLatLon();
    }
    return false;
}

bool ConventionalCoordinateSystem::canConvertToCoordinate() const
{
    if ( _projection.isValid())    {
        return _projection->canConvertToCoordinate();
    }
    return false;
}

QString ConventionalCoordinateSystem::toWKT(quint32 spaces) const
{
    QString wkt = "PROJCS[\"" + name() + "\"" + ",";
    QString geocs, proj, ell, datum;
    geocs += QString(" ").repeated(spaces);
    QString ending = spaces == 0 ? "" : "\n";
    if ( _datum){
        geocs += "GEOCS[\"";
        if ( name().indexOf("/") != -1){
            geocs += name().left( name().indexOf("/")).trimmed() + "\"";
        }else
            geocs += name() + "\"";

        datum = _datum->toWKT(spaces * 2);
    }
    QString primm = "PRIMEM[\"Greenwich\",0, AUTHORITY[\"EPSG\",8901\"]],";
    if ( _ellipsoid.isValid()){
        ell = _ellipsoid->toWKT(spaces * 2);
    }
    if ( _projection.isValid())
         proj= _projection->toWKT(spaces * 2) + ",";

    if ( geocs != ""){
        wkt += geocs + (datum !="" ? "," + datum : "") + "," + ell + primm + "]," + ending;
    }else
        wkt += ell + ",";
    wkt += proj;

    if ( _unit != ""){
        wkt += "UNIT[" + _unit + ",1.0]";
    }

    return wkt + "]";
}

QString ConventionalCoordinateSystem::toProj4() const
{
    if ( this->projection().isValid())
        return this->projection()->toProj4();
    else
        return QString("?");
}

QString ConventionalCoordinateSystem::unit() const
{
    return _unit;
}

void ConventionalCoordinateSystem::unit(const QString& unit)
{
    _unit = unit;
}

bool ConventionalCoordinateSystem::isCompatibleWith(const IlwisObject *obj) const
{
    if ( projection().isValid() && obj->isValid())
        return projection()->code() == obj->code();
    return false;
}

const std::unique_ptr<GeodeticDatum>& ConventionalCoordinateSystem::datum() const
{
    return _datum;
}

void ConventionalCoordinateSystem::setDatum(GeodeticDatum *datum)
{
    _datum.reset(datum);
}

IEllipsoid ConventionalCoordinateSystem::ellipsoid() const
{
    return _ellipsoid;
}

void ConventionalCoordinateSystem::setEllipsoid(const IEllipsoid &ell)
{
    _ellipsoid = ell;
    if ( _projection.isValid() && ell.isValid()){
        _projection->setParameter(Projection::pvELLCODE,ell->toProj4());
    }
}

bool ConventionalCoordinateSystem::isLatLon() const
{
    return _unit == "degrees";
}

IlwisTypes ConventionalCoordinateSystem::ilwisType() const
{
    return itCONVENTIONALCOORDSYSTEM;
}

bool ConventionalCoordinateSystem::isValid() const
{
    bool ok1 =  _projection.isValid();
    bool ok2 =_ellipsoid.isValid();

    return ok1 && ok2;
}

void ConventionalCoordinateSystem::setProjection(const IProjection &proj)
{
    _projection = proj;
    if ( proj->code().contains("longlat") || proj->code().contains("latlon"))
        _unit = "degrees";
}

IProjection ConventionalCoordinateSystem::projection() const
{
    return _projection;
}

bool ConventionalCoordinateSystem::prepare()
{
    return CoordinateSystem::prepare();
}

bool ConventionalCoordinateSystem::prepare(const QString &parms)
{
    Proj4Parameters proj4(parms);

    QString ell = proj4["ellps"];
    _ellipsoid = new Ellipsoid();
    if ( ell != sUNDEF) {
        _ellipsoid.prepare("code=" + ell);
    } else {
        QString laxis = proj4["a"];
        if ( laxis != sUNDEF) {
            QString saxis = proj4["b"];
            bool ok;
            double a = laxis.toDouble(&ok);
            if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name());
            double b = saxis.toDouble(&ok);
            if (!ok) return ERROR2(ERR_INVALID_PROPERTY_FOR_2, "ellipsoid", name());

            double f = (a - b) / a;
            QString newName = _ellipsoid->setEllipsoid(a, f);
            _ellipsoid->name(newName);
        }
    }
    if ( proj4.hasDatum()) {
        _datum.reset(new GeodeticDatum());
        if ( proj4["dx"] != sUNDEF) {
            _datum->set7TransformationParameters(proj4["dx"].toDouble(),
                                                 proj4["dy"].toDouble(),
                                                 proj4["dz"].toDouble(),
                                                 proj4["rx"].toDouble(),
                                                 proj4["ry"].toDouble(),
                                                 proj4["rz"].toDouble(),
                                                 proj4["dscale"].toDouble());
        }
    }
    QString code = proj4["proj"];

    if ( code == sUNDEF) {
        kernel()->issues()->log(TR(ERR_INVALID_PROPERTY_FOR_2).arg("projection name", name()));
        return false;
    }
    code = "code=" + code;
    Resource prj = mastercatalog()->name2Resource(code, itPROJECTION);
    if ( !prj.isValid()) {
         return ERROR1(ERR_COULDNT_CREATE_OBJECT_FOR_1,"projection " + code );
    }
    bool ok =_projection.prepare(prj.id());
    _projection->setCoordinateSystem(this);
    if ( _projection.isValid())  {
        ok = _projection->prepare(parms);
    }
    QString unit = proj4["units"];
    if ( ok && (_projection->code().contains("longlat") || _projection->code().contains("latlon") || unit=="?"))
        _unit = "degrees";
    else{
        if ( unit == "m")
            _unit = "meter";
        else
            _unit = "feet";
    }

    return ok;
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbQtAdapters.h"

#include <cassert>

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

namespace otb
{
/*
  TRANSLATOR otb::QtAdapters

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */
/*****************************************************************************/
QString
GetExistingDirectory( QWidget * p,
		      const QString& caption,
		      const QString& dir,
		      QFileDialog::Options options )
{
  QString path(
    QFileDialog::getExistingDirectory(
      p,
      caption,
      dir,
      options
    )
  );

  if( !path.isNull() )
    SetWorkingDir( path );

  return path;
}

/*****************************************************************************/
QString
GetOpenFileName( QWidget * p,
		 const QString& caption,
		 const QString& dir,
		 const QString& filter,
		 QString* selectedFilter,
		 QFileDialog::Options options )
{
  QString filename(
    QFileDialog::getOpenFileName(
      p,
      caption,
      dir,
      filter,
      selectedFilter,
      options
    )
  );

  if( !filename.isNull() )
    SetWorkingDir( filename );

  return filename;
}

/*****************************************************************************/
QStringList
GetOpenFileNames( QWidget * p,
		  const QString & caption,
		  const QString & dir,
		  const QString & filter,
		  QString * selectedFilter,
		  QFileDialog::Options options )
{
  QStringList filenames(
    QFileDialog::getOpenFileNames(
      p,
      caption,
      dir,
      filter,
      selectedFilter,
      options
    )
  );

  if( !filenames.isEmpty() )
    SetWorkingDir( filenames.back() );

  return filenames;
}

/*****************************************************************************/
QString
GetSaveFileName( QWidget * p,
		 const QString & caption,
		 const QString & dir,
		 const QString & filter,
		 QString * selectedFilter,
		 QFileDialog::Options options )
{
  QString filename(
    QFileDialog::getSaveFileName(
      p,
      caption,
      dir,
      filter,
      selectedFilter,
      options
    )
  );

  if( !filename.isNull() )
    SetWorkingDir( filename );

  return filename;
}

/*****************************************************************************/
QString
GetWorkingDir()
{
  return QDir::currentPath();
}

/*****************************************************************************/
bool
SetWorkingDir( const QString & filepath )
{
  assert( !filepath.isEmpty() );

  QFileInfo finfo( filepath );

  return QDir::setCurrent(
    finfo.isDir()
    ? filepath
    : finfo.path()
  );
}

} // end namespace 'otb'
<commit_msg>BUG: MANTIS-1180: Added caption to open/save file-dialogs (QtAdapters).<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbQtAdapters.h"

#include <cassert>

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

namespace otb
{
/*
  TRANSLATOR otb::QtAdapters

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */
/*****************************************************************************/
QString
GetExistingDirectory( QWidget * p,
		      const QString& caption,
		      const QString& dir,
		      QFileDialog::Options options )
{
  QString path(
    QFileDialog::getExistingDirectory(
      p,
      caption.isEmpty()
      ? QObject::tr( "Select directory..." )
      : caption,
      dir,
      options
    )
  );

  if( !path.isNull() )
    SetWorkingDir( path );

  return path;
}

/*****************************************************************************/
QString
GetOpenFileName( QWidget * p,
		 const QString& caption,
		 const QString& dir,
		 const QString& filter,
		 QString* selectedFilter,
		 QFileDialog::Options options )
{
  QString filename(
    QFileDialog::getOpenFileName(
      p,
      caption.isEmpty()
      ? QObject::tr( "Open file..." )
      : caption,
      dir,
      filter,
      selectedFilter,
      options
    )
  );

  if( !filename.isNull() )
    SetWorkingDir( filename );

  return filename;
}

/*****************************************************************************/
QStringList
GetOpenFileNames( QWidget * p,
		  const QString & caption,
		  const QString & dir,
		  const QString & filter,
		  QString * selectedFilter,
		  QFileDialog::Options options )
{
  QStringList filenames(
    QFileDialog::getOpenFileNames(
      p,
      caption.isEmpty()
      ? QObject::tr( "Open file..." )
      : caption,
      dir,
      filter,
      selectedFilter,
      options
    )
  );

  if( !filenames.isEmpty() )
    SetWorkingDir( filenames.back() );

  return filenames;
}

/*****************************************************************************/
QString
GetSaveFileName( QWidget * p,
		 const QString & caption,
		 const QString & dir,
		 const QString & filter,
		 QString * selectedFilter,
		 QFileDialog::Options options )
{
  QString filename(
    QFileDialog::getSaveFileName(
      p,
      caption.isEmpty()
      ? QObject::tr( "Save file..." )
      : caption,
      dir,
      filter,
      selectedFilter,
      options
    )
  );

  if( !filename.isNull() )
    SetWorkingDir( filename );

  return filename;
}

/*****************************************************************************/
QString
GetWorkingDir()
{
  return QDir::currentPath();
}

/*****************************************************************************/
bool
SetWorkingDir( const QString & filepath )
{
  assert( !filepath.isEmpty() );

  QFileInfo finfo( filepath );

  return QDir::setCurrent(
    finfo.isDir()
    ? filepath
    : finfo.path()
  );
}

} // end namespace 'otb'
<|endoftext|>


<commit_before>/*
 * SSL/TLS configuration.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "ssl_factory.hxx"
#include "ssl_config.hxx"
#include "ssl_domain.hxx"
#include "Unique.hxx"
#include "Name.hxx"
#include "Util.hxx"
#include "util/AllocatedString.hxx"
#include "util/Error.hxx"

#include <inline/compiler.h>

#include <openssl/ssl.h>
#include <openssl/err.h>

#include <algorithm>

#include <assert.h>

struct SslCertKey {
    UniqueSSL_CTX ssl_ctx;

    AllocatedString<> common_name = nullptr;
    size_t cn_length;

    SslCertKey() = default;

    SslCertKey(SslCertKey &&other) = default;
    SslCertKey &operator=(SslCertKey &&other) = default;

    bool LoadClient(Error &error);

    bool LoadServer(const SslConfig &parent_config,
                    const SslCertKeyConfig &config, Error &error);

    void CacheCommonName(X509_NAME *subject) {
        common_name = NidToString(*subject, NID_commonName);
        if (common_name != nullptr)
            cn_length = strlen(common_name.c_str());
    }

    void CacheCommonName(X509 *cert) {
        assert(common_name == nullptr);

        X509_NAME *subject = X509_get_subject_name(cert);
        if (subject != nullptr)
            CacheCommonName(subject);
    }

    gcc_pure
    bool MatchCommonName(const char *host_name, size_t hn_length) const;

    UniqueSSL Make() const {
        return UniqueSSL(SSL_new(ssl_ctx.get()));
    }

    void Apply(SSL *ssl) const {
        SSL_set_SSL_CTX(ssl, ssl_ctx.get());
    }

    unsigned Flush(long tm);
};

struct SslFactory {
    std::vector<SslCertKey> cert_key;

    const bool server;

    explicit SslFactory(bool _server)
        :server(_server) {}

    bool EnableSNI(Error &error);

    UniqueSSL Make();

    unsigned Flush(long tm);
};

static int
verify_callback(int ok, gcc_unused X509_STORE_CTX *ctx)
{
    return ok;
}

static bool
load_certs_keys(SslFactory &factory, const SslConfig &config,
                Error &error)
{
    factory.cert_key.reserve(config.cert_key.size());

    for (const auto &c : config.cert_key) {
        SslCertKey ck;
        if (!ck.LoadServer(config, c, error))
            return false;

        factory.cert_key.emplace_back(std::move(ck));
    }

    return true;
}

static bool
apply_server_config(SSL_CTX *ssl_ctx, const SslConfig &config,
                    const SslCertKeyConfig &cert_key,
                    Error &error)
{
    ERR_clear_error();

    if (SSL_CTX_use_RSAPrivateKey_file(ssl_ctx,
                                       cert_key.key_file.c_str(),
                                       SSL_FILETYPE_PEM) != 1) {
        ERR_print_errors_fp(stderr);
        error.Format(ssl_domain, "Failed to load key file %s",
                     cert_key.key_file.c_str());
        return false;
    }

    if (SSL_CTX_use_certificate_chain_file(ssl_ctx,
                                           cert_key.cert_file.c_str()) != 1) {
        ERR_print_errors_fp(stderr);
        error.Format(ssl_domain, "Failed to load certificate file %s",
                     cert_key.cert_file.c_str());
        return false;
    }

    if (!config.ca_cert_file.empty()) {
        if (SSL_CTX_load_verify_locations(ssl_ctx,
                                          config.ca_cert_file.c_str(),
                                          nullptr) != 1) {
            error.Format(ssl_domain, "Failed to load CA certificate file %s",
                         config.ca_cert_file.c_str());
            return false;
        }

        /* send all certificates from this file to the client (list of
           acceptable CA certificates) */

        STACK_OF(X509_NAME) *list =
            SSL_load_client_CA_file(config.ca_cert_file.c_str());
        if (list == nullptr) {
            error.Format(ssl_domain,
                         "Failed to load CA certificate list from file %s",
                         config.ca_cert_file.c_str());
            return false;
        }

        SSL_CTX_set_client_CA_list(ssl_ctx, list);
    }

    if (config.verify != SslVerify::NO) {
        /* enable client certificates */
        int mode = SSL_VERIFY_PEER;

        if (config.verify == SslVerify::YES)
            mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;

        SSL_CTX_set_verify(ssl_ctx, mode, verify_callback);
    }

    return true;
}

inline bool
SslCertKey::MatchCommonName(const char *host_name, size_t hn_length) const
{
    if (common_name == nullptr)
        return false;

    if (strcmp(host_name, common_name.c_str()) == 0)
        return true;

    if (common_name[0] == '*' && common_name[1] == '.' &&
        common_name[2] != 0) {
        if (hn_length >= cn_length &&
            /* match only one segment (no dots) */
            memchr(host_name, '.', hn_length - cn_length + 1) == nullptr &&
            memcmp(host_name + hn_length - cn_length + 1,
                   common_name.c_str() + 1, cn_length - 1) == 0)
            return true;
    }

    return false;
}

static int
ssl_servername_callback(SSL *ssl, gcc_unused int *al,
                        const SslFactory &factory)
{
    const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
    if (host_name == nullptr)
        return SSL_TLSEXT_ERR_OK;

    const size_t length = strlen(host_name);

    /* find the first certificate that matches */

    for (const auto &ck : factory.cert_key) {
        if (ck.MatchCommonName(host_name, length)) {
            /* found it - now use it */
            ck.Apply(ssl);
            break;
        }
    }

    return SSL_TLSEXT_ERR_OK;
}

inline bool
SslFactory::EnableSNI(Error &error)
{
    SSL_CTX *ssl_ctx = cert_key.front().ssl_ctx.get();

    if (!SSL_CTX_set_tlsext_servername_callback(ssl_ctx,
                                                ssl_servername_callback) ||
        !SSL_CTX_set_tlsext_servername_arg(ssl_ctx, this)) {
        error.Format(ssl_domain,
                     "SSL_CTX_set_tlsext_servername_callback() failed");
        return false;
    }

    return true;
}

inline UniqueSSL
SslFactory::Make()
{
    auto ssl = cert_key.front().Make();
    if (ssl == nullptr)
        return nullptr;

    if (server)
        SSL_set_accept_state(ssl.get());
    else
        SSL_set_connect_state(ssl.get());

    return ssl;
}

inline unsigned
SslCertKey::Flush(long tm)
{
    unsigned before = SSL_CTX_sess_number(ssl_ctx.get());
    SSL_CTX_flush_sessions(ssl_ctx.get(), tm);
    unsigned after = SSL_CTX_sess_number(ssl_ctx.get());
    return after < before ? before - after : 0;
}

inline unsigned
SslFactory::Flush(long tm)
{
    unsigned n = 0;
    for (auto &i : cert_key)
        n += i.Flush(tm);
    return n;
}

/**
 * Enable Elliptic curve Diffie-Hellman (ECDH) for perfect forward
 * secrecy.  By default, it OpenSSL disables it.
 */
static bool
enable_ecdh(SSL_CTX *ssl_ctx, Error &error)
{
    /* OpenSSL 1.0.2 will allow this instead:

       SSL_CTX_set_ecdh_auto(ssl_ctx, 1)
    */

    EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    if (ecdh == nullptr) {
        error.Set(ssl_domain, "EC_KEY_new_by_curve_name() failed");
        return false;
    }

    bool success = SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh) == 1;
    EC_KEY_free(ecdh);
    if (!success)
        error.Set(ssl_domain, "SSL_CTX_set_tmp_ecdh() failed");

    return success;
}

static bool
SetupBasicSslCtx(SSL_CTX *ssl_ctx, bool server, Error &error)
{
    long mode = SSL_MODE_ENABLE_PARTIAL_WRITE
        | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
#ifdef SSL_MODE_RELEASE_BUFFERS
    /* requires libssl 1.0.0 */
    mode |= SSL_MODE_RELEASE_BUFFERS;
#endif

    /* without this flag, OpenSSL attempts to verify the whole local
       certificate chain for each connection, which is a waste of CPU
       time */
    mode |= SSL_MODE_NO_AUTO_CHAIN;

    SSL_CTX_set_mode(ssl_ctx, mode);

    if (server && !enable_ecdh(ssl_ctx, error))
        return false;

    /* disable protocols that are known to be insecure */
    SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);

    /* disable weak ciphers */
    SSL_CTX_set_cipher_list(ssl_ctx, "DEFAULT:!EXPORT:!LOW");

    return true;
}

static UniqueSSL_CTX
CreateBasicSslCtx(bool server, Error &error)
{
    ERR_clear_error();

    /* don't be fooled - we want TLS, not SSL - but TLSv1_method()
       will only allow TLSv1.0 and will refuse TLSv1.1 and TLSv1.2;
       only SSLv23_method() supports all (future) TLS protocol
       versions, even if we don't want any SSL at all */
    auto method = server
        ? SSLv23_server_method()
        : SSLv23_client_method();

    UniqueSSL_CTX ssl_ctx(SSL_CTX_new(method));
    if (ssl_ctx == nullptr) {
        ERR_print_errors_fp(stderr);
        error.Format(ssl_domain, "SSL_CTX_new() failed");
        return nullptr;
    }

    if (!SetupBasicSslCtx(ssl_ctx.get(), server, error))
        return nullptr;

    return ssl_ctx;
}

bool
SslCertKey::LoadClient(Error &error)
{
    assert(ssl_ctx == nullptr);

    ssl_ctx = CreateBasicSslCtx(false, error);
    return ssl_ctx != nullptr;
}

bool
SslCertKey::LoadServer(const SslConfig &parent_config,
                       const SslCertKeyConfig &config, Error &error)
{
    assert(ssl_ctx == nullptr);

    ssl_ctx = CreateBasicSslCtx(true, error);
    if (ssl_ctx == nullptr)
        return false;

    assert(!parent_config.cert_key.empty());

    if (!apply_server_config(ssl_ctx.get(), parent_config, config,
                             error))
        return false;

    auto ssl = Make();
    if (ssl == nullptr) {
        error.Format(ssl_domain, "SSL_new() failed");
        return false;
    }

    X509 *cert = SSL_get_certificate(ssl.get());
    EVP_PKEY *key = SSL_get_privatekey(ssl.get());
    if (cert == nullptr || key == nullptr) {
        error.Set(ssl_domain, "No cert/key in SSL_CTX");
        return false;
    }

    if (!MatchModulus(*cert, *key)) {
        error.Format(ssl_domain, "Key '%s' does not match certificate '%s'",
                     config.key_file.c_str(), config.cert_file.c_str());
        return false;
    }

    CacheCommonName(cert);
    return true;
}

SslFactory *
ssl_factory_new(const SslConfig &config,
                bool server,
                Error &error)
{
    assert(!config.cert_key.empty() || !server);

    auto *factory = new SslFactory(server);

    if (server) {
        assert(!config.cert_key.empty());

        if (!load_certs_keys(*factory, config, error)) {
            delete factory;
            return nullptr;
        }
    } else {
        assert(config.cert_key.empty());
        assert(config.ca_cert_file.empty());
        assert(config.verify == SslVerify::NO);

        factory->cert_key.emplace_back();
        if (!factory->cert_key.front().LoadClient(error)) {
            delete factory;
            return nullptr;
        }
    }

    if (factory->cert_key.size() > 1 && !factory->EnableSNI(error)) {
        delete factory;
        return nullptr;
    }

    return factory;
}

void
ssl_factory_free(SslFactory *factory)
{
    delete factory;
}

UniqueSSL
ssl_factory_make(SslFactory &factory)
{
    return factory.Make();
}

unsigned
ssl_factory_flush(SslFactory &factory, long tm)
{
    return factory.Flush(tm);
}
<commit_msg>ssl/factory: rename struct SslCertKey to SslFactoryCertKey<commit_after>/*
 * SSL/TLS configuration.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "ssl_factory.hxx"
#include "ssl_config.hxx"
#include "ssl_domain.hxx"
#include "Unique.hxx"
#include "Name.hxx"
#include "Util.hxx"
#include "util/AllocatedString.hxx"
#include "util/Error.hxx"

#include <inline/compiler.h>

#include <openssl/ssl.h>
#include <openssl/err.h>

#include <algorithm>

#include <assert.h>

struct SslFactoryCertKey {
    UniqueSSL_CTX ssl_ctx;

    AllocatedString<> common_name = nullptr;
    size_t cn_length;

    SslFactoryCertKey() = default;

    SslFactoryCertKey(SslFactoryCertKey &&other) = default;
    SslFactoryCertKey &operator=(SslFactoryCertKey &&other) = default;

    bool LoadClient(Error &error);

    bool LoadServer(const SslConfig &parent_config,
                    const SslCertKeyConfig &config, Error &error);

    void CacheCommonName(X509_NAME *subject) {
        common_name = NidToString(*subject, NID_commonName);
        if (common_name != nullptr)
            cn_length = strlen(common_name.c_str());
    }

    void CacheCommonName(X509 *cert) {
        assert(common_name == nullptr);

        X509_NAME *subject = X509_get_subject_name(cert);
        if (subject != nullptr)
            CacheCommonName(subject);
    }

    gcc_pure
    bool MatchCommonName(const char *host_name, size_t hn_length) const;

    UniqueSSL Make() const {
        return UniqueSSL(SSL_new(ssl_ctx.get()));
    }

    void Apply(SSL *ssl) const {
        SSL_set_SSL_CTX(ssl, ssl_ctx.get());
    }

    unsigned Flush(long tm);
};

struct SslFactory {
    std::vector<SslFactoryCertKey> cert_key;

    const bool server;

    explicit SslFactory(bool _server)
        :server(_server) {}

    bool EnableSNI(Error &error);

    UniqueSSL Make();

    unsigned Flush(long tm);
};

static int
verify_callback(int ok, gcc_unused X509_STORE_CTX *ctx)
{
    return ok;
}

static bool
load_certs_keys(SslFactory &factory, const SslConfig &config,
                Error &error)
{
    factory.cert_key.reserve(config.cert_key.size());

    for (const auto &c : config.cert_key) {
        SslFactoryCertKey ck;
        if (!ck.LoadServer(config, c, error))
            return false;

        factory.cert_key.emplace_back(std::move(ck));
    }

    return true;
}

static bool
apply_server_config(SSL_CTX *ssl_ctx, const SslConfig &config,
                    const SslCertKeyConfig &cert_key,
                    Error &error)
{
    ERR_clear_error();

    if (SSL_CTX_use_RSAPrivateKey_file(ssl_ctx,
                                       cert_key.key_file.c_str(),
                                       SSL_FILETYPE_PEM) != 1) {
        ERR_print_errors_fp(stderr);
        error.Format(ssl_domain, "Failed to load key file %s",
                     cert_key.key_file.c_str());
        return false;
    }

    if (SSL_CTX_use_certificate_chain_file(ssl_ctx,
                                           cert_key.cert_file.c_str()) != 1) {
        ERR_print_errors_fp(stderr);
        error.Format(ssl_domain, "Failed to load certificate file %s",
                     cert_key.cert_file.c_str());
        return false;
    }

    if (!config.ca_cert_file.empty()) {
        if (SSL_CTX_load_verify_locations(ssl_ctx,
                                          config.ca_cert_file.c_str(),
                                          nullptr) != 1) {
            error.Format(ssl_domain, "Failed to load CA certificate file %s",
                         config.ca_cert_file.c_str());
            return false;
        }

        /* send all certificates from this file to the client (list of
           acceptable CA certificates) */

        STACK_OF(X509_NAME) *list =
            SSL_load_client_CA_file(config.ca_cert_file.c_str());
        if (list == nullptr) {
            error.Format(ssl_domain,
                         "Failed to load CA certificate list from file %s",
                         config.ca_cert_file.c_str());
            return false;
        }

        SSL_CTX_set_client_CA_list(ssl_ctx, list);
    }

    if (config.verify != SslVerify::NO) {
        /* enable client certificates */
        int mode = SSL_VERIFY_PEER;

        if (config.verify == SslVerify::YES)
            mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;

        SSL_CTX_set_verify(ssl_ctx, mode, verify_callback);
    }

    return true;
}

inline bool
SslFactoryCertKey::MatchCommonName(const char *host_name,
                                   size_t hn_length) const
{
    if (common_name == nullptr)
        return false;

    if (strcmp(host_name, common_name.c_str()) == 0)
        return true;

    if (common_name[0] == '*' && common_name[1] == '.' &&
        common_name[2] != 0) {
        if (hn_length >= cn_length &&
            /* match only one segment (no dots) */
            memchr(host_name, '.', hn_length - cn_length + 1) == nullptr &&
            memcmp(host_name + hn_length - cn_length + 1,
                   common_name.c_str() + 1, cn_length - 1) == 0)
            return true;
    }

    return false;
}

static int
ssl_servername_callback(SSL *ssl, gcc_unused int *al,
                        const SslFactory &factory)
{
    const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
    if (host_name == nullptr)
        return SSL_TLSEXT_ERR_OK;

    const size_t length = strlen(host_name);

    /* find the first certificate that matches */

    for (const auto &ck : factory.cert_key) {
        if (ck.MatchCommonName(host_name, length)) {
            /* found it - now use it */
            ck.Apply(ssl);
            break;
        }
    }

    return SSL_TLSEXT_ERR_OK;
}

inline bool
SslFactory::EnableSNI(Error &error)
{
    SSL_CTX *ssl_ctx = cert_key.front().ssl_ctx.get();

    if (!SSL_CTX_set_tlsext_servername_callback(ssl_ctx,
                                                ssl_servername_callback) ||
        !SSL_CTX_set_tlsext_servername_arg(ssl_ctx, this)) {
        error.Format(ssl_domain,
                     "SSL_CTX_set_tlsext_servername_callback() failed");
        return false;
    }

    return true;
}

inline UniqueSSL
SslFactory::Make()
{
    auto ssl = cert_key.front().Make();
    if (ssl == nullptr)
        return nullptr;

    if (server)
        SSL_set_accept_state(ssl.get());
    else
        SSL_set_connect_state(ssl.get());

    return ssl;
}

inline unsigned
SslFactoryCertKey::Flush(long tm)
{
    unsigned before = SSL_CTX_sess_number(ssl_ctx.get());
    SSL_CTX_flush_sessions(ssl_ctx.get(), tm);
    unsigned after = SSL_CTX_sess_number(ssl_ctx.get());
    return after < before ? before - after : 0;
}

inline unsigned
SslFactory::Flush(long tm)
{
    unsigned n = 0;
    for (auto &i : cert_key)
        n += i.Flush(tm);
    return n;
}

/**
 * Enable Elliptic curve Diffie-Hellman (ECDH) for perfect forward
 * secrecy.  By default, it OpenSSL disables it.
 */
static bool
enable_ecdh(SSL_CTX *ssl_ctx, Error &error)
{
    /* OpenSSL 1.0.2 will allow this instead:

       SSL_CTX_set_ecdh_auto(ssl_ctx, 1)
    */

    EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    if (ecdh == nullptr) {
        error.Set(ssl_domain, "EC_KEY_new_by_curve_name() failed");
        return false;
    }

    bool success = SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh) == 1;
    EC_KEY_free(ecdh);
    if (!success)
        error.Set(ssl_domain, "SSL_CTX_set_tmp_ecdh() failed");

    return success;
}

static bool
SetupBasicSslCtx(SSL_CTX *ssl_ctx, bool server, Error &error)
{
    long mode = SSL_MODE_ENABLE_PARTIAL_WRITE
        | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
#ifdef SSL_MODE_RELEASE_BUFFERS
    /* requires libssl 1.0.0 */
    mode |= SSL_MODE_RELEASE_BUFFERS;
#endif

    /* without this flag, OpenSSL attempts to verify the whole local
       certificate chain for each connection, which is a waste of CPU
       time */
    mode |= SSL_MODE_NO_AUTO_CHAIN;

    SSL_CTX_set_mode(ssl_ctx, mode);

    if (server && !enable_ecdh(ssl_ctx, error))
        return false;

    /* disable protocols that are known to be insecure */
    SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);

    /* disable weak ciphers */
    SSL_CTX_set_cipher_list(ssl_ctx, "DEFAULT:!EXPORT:!LOW");

    return true;
}

static UniqueSSL_CTX
CreateBasicSslCtx(bool server, Error &error)
{
    ERR_clear_error();

    /* don't be fooled - we want TLS, not SSL - but TLSv1_method()
       will only allow TLSv1.0 and will refuse TLSv1.1 and TLSv1.2;
       only SSLv23_method() supports all (future) TLS protocol
       versions, even if we don't want any SSL at all */
    auto method = server
        ? SSLv23_server_method()
        : SSLv23_client_method();

    UniqueSSL_CTX ssl_ctx(SSL_CTX_new(method));
    if (ssl_ctx == nullptr) {
        ERR_print_errors_fp(stderr);
        error.Format(ssl_domain, "SSL_CTX_new() failed");
        return nullptr;
    }

    if (!SetupBasicSslCtx(ssl_ctx.get(), server, error))
        return nullptr;

    return ssl_ctx;
}

bool
SslFactoryCertKey::LoadClient(Error &error)
{
    assert(ssl_ctx == nullptr);

    ssl_ctx = CreateBasicSslCtx(false, error);
    return ssl_ctx != nullptr;
}

bool
SslFactoryCertKey::LoadServer(const SslConfig &parent_config,
                              const SslCertKeyConfig &config,
                              Error &error)
{
    assert(ssl_ctx == nullptr);

    ssl_ctx = CreateBasicSslCtx(true, error);
    if (ssl_ctx == nullptr)
        return false;

    assert(!parent_config.cert_key.empty());

    if (!apply_server_config(ssl_ctx.get(), parent_config, config,
                             error))
        return false;

    auto ssl = Make();
    if (ssl == nullptr) {
        error.Format(ssl_domain, "SSL_new() failed");
        return false;
    }

    X509 *cert = SSL_get_certificate(ssl.get());
    EVP_PKEY *key = SSL_get_privatekey(ssl.get());
    if (cert == nullptr || key == nullptr) {
        error.Set(ssl_domain, "No cert/key in SSL_CTX");
        return false;
    }

    if (!MatchModulus(*cert, *key)) {
        error.Format(ssl_domain, "Key '%s' does not match certificate '%s'",
                     config.key_file.c_str(), config.cert_file.c_str());
        return false;
    }

    CacheCommonName(cert);
    return true;
}

SslFactory *
ssl_factory_new(const SslConfig &config,
                bool server,
                Error &error)
{
    assert(!config.cert_key.empty() || !server);

    auto *factory = new SslFactory(server);

    if (server) {
        assert(!config.cert_key.empty());

        if (!load_certs_keys(*factory, config, error)) {
            delete factory;
            return nullptr;
        }
    } else {
        assert(config.cert_key.empty());
        assert(config.ca_cert_file.empty());
        assert(config.verify == SslVerify::NO);

        factory->cert_key.emplace_back();
        if (!factory->cert_key.front().LoadClient(error)) {
            delete factory;
            return nullptr;
        }
    }

    if (factory->cert_key.size() > 1 && !factory->EnableSNI(error)) {
        delete factory;
        return nullptr;
    }

    return factory;
}

void
ssl_factory_free(SslFactory *factory)
{
    delete factory;
}

UniqueSSL
ssl_factory_make(SslFactory &factory)
{
    return factory.Make();
}

unsigned
ssl_factory_flush(SslFactory &factory, long tm)
{
    return factory.Flush(tm);
}
<|endoftext|>


<commit_before>#include "request.hh"

#include <cstring>
#include <memory>
#include <string_view>

#include <curl/curl.h>

namespace aur {

namespace {

std::string UrlEscape(const std::string_view sv) {
  char* ptr = curl_easy_escape(nullptr, sv.data(), sv.size());
  std::string escaped(ptr);
  free(ptr);

  return escaped;
}

char* AppendUnsafe(char* to, std::string_view from) {
  auto ptr = mempcpy(to, from.data(), from.size());

  return static_cast<char*>(ptr);
}

template <typename... Pieces>
void StrAppend(std::string* out, const Pieces&... args) {
  std::vector<std::string_view> v{args...};

  std::string::size_type append_sz = 0;
  for (const auto& piece : v) {
    append_sz += piece.size();
  }

  auto original_sz = out->size();
  out->resize(original_sz + append_sz);

  char* ptr = out->data() + original_sz;
  for (const auto& piece : v) {
    ptr = AppendUnsafe(ptr, piece);
  }
}

template <typename... Pieces>
std::string StrCat(const Pieces&... args) {
  std::string out;
  StrAppend(&out, args...);
  return out;
}

void QueryParamFormatter(std::string* out,
                         const std::pair<std::string, std::string>& kv) {
  StrAppend(out, kv.first, "=", UrlEscape(kv.second));
}

template <typename Iterator, typename Formatter>
std::string StrJoin(Iterator begin, Iterator end, std::string_view s,
                    Formatter&& f) {
  std::string result;

  std::string_view sep("");
  for (Iterator it = begin; it != end; ++it) {
    result.append(sep.data(), sep.size());
    f(&result, *it);
    sep = s;
  }

  return result;
}

}  // namespace

void RpcRequest::AddArg(const std::string& key, const std::string& value) {
  args_.emplace_back(key, value);
}

std::vector<std::string> RpcRequest::Build(const std::string& baseurl) const {
  std::vector<std::string> requests;

  const auto assemble = [&](std::string_view qs) {
    return StrCat(baseurl, "/rpc?", baseuri_, "&", qs);
  };

  const auto qs =
      StrJoin(args_.begin(), args_.end(), "&", &QueryParamFormatter);

  std::string_view sv(qs);
  while (!sv.empty()) {
    if (sv.size() <= approx_max_length_) {
      requests.push_back(assemble(sv));
      break;
    }

    // Look for an ampersand just under the max allowed length.
    auto n = sv.substr(0, approx_max_length_).find_last_of('&');
    if (n == std::string_view::npos) {
      // Failed, which means we found a single arg which is Too Damn Long. Look
      // for the ampersand just after the length limit and use all of it. This
      // request might fail, but it's bad user input.
      n = sv.substr(approx_max_length_).find_first_of('&');
      if (n == std::string_view::npos) {
        // We're at the end of the querystring. Take the whole thing.
        n = sv.size();
      } else {
        n += approx_max_length_;
      }
    }

    requests.push_back(assemble(sv.substr(0, n)));
    sv.remove_prefix(std::min(sv.length(), n + 1));
  }

  return requests;
}

RpcRequest::RpcRequest(
    const std::vector<std::pair<std::string, std::string>>& base_params,
    long unsigned approx_max_length)
    : baseuri_(StrJoin(base_params.begin(), base_params.end(), "&",
                       &QueryParamFormatter)),
      approx_max_length_(approx_max_length) {}

// static
std::string RawRequest::UrlForTarball(const Package& package) {
  return package.aur_urlpath;
}

// static
std::string RawRequest::UrlForPkgbuild(const Package& package) {
  return StrCat("/cgit/aur.git/plain/PKGBUILD?h=", UrlEscape(package.pkgbase));
}

std::vector<std::string> RawRequest::Build(const std::string& baseurl) const {
  return {StrCat(baseurl, urlpath_)};
}

std::vector<std::string> CloneRequest::Build(const std::string& baseurl) const {
  return {StrCat(baseurl, "/", reponame_)};
}

}  // namespace aur
<commit_msg>hoist span-finding logic into local lambda<commit_after>#include "request.hh"

#include <cstring>
#include <memory>
#include <string_view>

#include <curl/curl.h>

namespace aur {

namespace {

std::string UrlEscape(const std::string_view sv) {
  char* ptr = curl_easy_escape(nullptr, sv.data(), sv.size());
  std::string escaped(ptr);
  free(ptr);

  return escaped;
}

char* AppendUnsafe(char* to, std::string_view from) {
  auto ptr = mempcpy(to, from.data(), from.size());

  return static_cast<char*>(ptr);
}

template <typename... Pieces>
void StrAppend(std::string* out, const Pieces&... args) {
  std::vector<std::string_view> v{args...};

  std::string::size_type append_sz = 0;
  for (const auto& piece : v) {
    append_sz += piece.size();
  }

  auto original_sz = out->size();
  out->resize(original_sz + append_sz);

  char* ptr = out->data() + original_sz;
  for (const auto& piece : v) {
    ptr = AppendUnsafe(ptr, piece);
  }
}

template <typename... Pieces>
std::string StrCat(const Pieces&... args) {
  std::string out;
  StrAppend(&out, args...);
  return out;
}

void QueryParamFormatter(std::string* out,
                         const std::pair<std::string, std::string>& kv) {
  StrAppend(out, kv.first, "=", UrlEscape(kv.second));
}

template <typename Iterator, typename Formatter>
std::string StrJoin(Iterator begin, Iterator end, std::string_view s,
                    Formatter&& f) {
  std::string result;

  std::string_view sep("");
  for (Iterator it = begin; it != end; ++it) {
    result.append(sep.data(), sep.size());
    f(&result, *it);
    sep = s;
  }

  return result;
}

}  // namespace

void RpcRequest::AddArg(const std::string& key, const std::string& value) {
  args_.emplace_back(key, value);
}

std::vector<std::string> RpcRequest::Build(const std::string& baseurl) const {
  const auto next_span = [&](const std::string_view& s) {
    // No chopping needed.
    if (s.size() <= approx_max_length_) {
      return s;
    }

    // Try to chop at the final ampersand before the cutoff length.
    auto n = s.substr(0, approx_max_length_).find_last_of('&');
    if (n != std::string_view::npos) {
      return s.substr(0, n);
    }

    // We found a single arg which is Too Damn Long. Look for the ampersand just
    // after the length limit and use all of it.
    n = s.substr(approx_max_length_).find_first_of('&');
    if (n != std::string_view::npos) {
      return s.substr(0, n + approx_max_length_);
    }

    // We're at the end of the querystring and have no place to chop.
    return s;
  };

  const auto qs =
      StrJoin(args_.begin(), args_.end(), "&", &QueryParamFormatter);
  std::string_view sv(qs);

  std::vector<std::string> requests;
  while (!sv.empty()) {
    const auto span = next_span(sv);

    requests.push_back(StrCat(baseurl, "/rpc?", baseuri_, "&", span));
    sv.remove_prefix(std::min(sv.length(), span.length() + 1));
  }

  return requests;
}

RpcRequest::RpcRequest(
    const std::vector<std::pair<std::string, std::string>>& base_params,
    long unsigned approx_max_length)
    : baseuri_(StrJoin(base_params.begin(), base_params.end(), "&",
                       &QueryParamFormatter)),
      approx_max_length_(approx_max_length) {}

// static
std::string RawRequest::UrlForTarball(const Package& package) {
  return package.aur_urlpath;
}

// static
std::string RawRequest::UrlForPkgbuild(const Package& package) {
  return StrCat("/cgit/aur.git/plain/PKGBUILD?h=", UrlEscape(package.pkgbase));
}

std::vector<std::string> RawRequest::Build(const std::string& baseurl) const {
  return {StrCat(baseurl, urlpath_)};
}

std::vector<std::string> CloneRequest::Build(const std::string& baseurl) const {
  return {StrCat(baseurl, "/", reponame_)};
}

}  // namespace aur
<|endoftext|>


<commit_before><commit_msg>Remove unnecessary includes<commit_after><|endoftext|>


<commit_before>/*
  Copyright (c) 2016 Louis McCarthy
  All rights reserved.

  Licensed under MIT License, see LICENSE for full license text

  parseRawImage.ccp - Loads the raw image binary file and spits out debug info
*/

#include <stdio.h>
#include <stdlib.h>

#define MAX_TRANSFER_SIZE 12677612

int main()
{
    FILE* newFile = fopen("raw.image", "r");
    if (newFile == NULL)
    {
        printf("Failed to open file\n");
        return -1;
    }

    unsigned char* data = (unsigned char*)malloc(MAX_TRANSFER_SIZE);
    size_t result = fread(data, 1, MAX_TRANSFER_SIZE, newFile);
    fclose(newFile);

    printf("Read %lu bytes\n", result);

    int zeroCount = 0;
    int rowCount = 0;
    int thisZeroIndex = 0;
    int lastZeroIndex = 0;
    for (long i=0; i<result; i++)
    {
        if (data[i] == 0x00)
        {
            if (++zeroCount == 18)
            {
                thisZeroIndex = i - 17;
                printf("Found row %d at index 0x%X, which is %d bytes since previous row\n", rowCount++, thisZeroIndex, thisZeroIndex - lastZeroIndex);
                lastZeroIndex = thisZeroIndex;
            }
        }
        else
            zeroCount = 0;
    }
    free(data);
}
<commit_msg>Parse into proper length rows and report glitches<commit_after>/*
  Copyright (c) 2016 Louis McCarthy
  All rights reserved.

  Licensed under MIT License, see LICENSE for full license text

  parseRawImage.ccp - Loads the raw image binary file and spits out debug info
*/

#include <stdio.h>
#include <stdlib.h>

#define MAX_TRANSFER_SIZE 12677612

int main()
{
    FILE* newFile = fopen("raw.image", "r");
    if (newFile == NULL)
    {
        printf("Failed to open file\n");
        return -1;
    }

    unsigned char* data = (unsigned char*)malloc(MAX_TRANSFER_SIZE);
    size_t result = fread(data, 1, MAX_TRANSFER_SIZE, newFile);
    fclose(newFile);

    printf("Read %lu bytes\n", result);

    int zeroCount = 0;
    int rowCount = 0;
    int thisZeroIndex = 0;
    int lastZeroIndex = 0;
    int byteCount = 0;
    for (long i=0; i<result; i++)
    {
        if (++byteCount == 6220)
        {
            byteCount = 0;
            zeroCount = 0;
            printf("...good row\n");
            continue;
        }

        if (data[i] == 0x00)
        {
            if (++zeroCount == 18)
            {
                thisZeroIndex = i - 17;
                if (byteCount == zeroCount)
                {
                    printf("Found row %d at index 0x%X, which is %d bytes since previous row", rowCount++, thisZeroIndex, thisZeroIndex - lastZeroIndex);
                    lastZeroIndex = thisZeroIndex;
                }
                else
                    printf("...glitch...");
                zeroCount = 0; // reset counter so a start byte of value 0x00 doesn't trip this again...
            }
        }
        else
        {
            if (zeroCount > 2 && zeroCount != 18)
                printf("Found %d zeros in a row at location 0x%X\n", zeroCount, i);
            zeroCount = 0;
        }
    }
    free(data);
}
<|endoftext|>


<commit_before><commit_msg>Removed.<commit_after><|endoftext|>


<commit_before>#include "BuckApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "BuckRevision.h" // This file is autogenerated and contains the revision.

// Auxkernels

// Kernels
#include "VariableScaledSource.h"
#include "HomNucleation.h"
#include "HomClusterDiffusion.h"
#include "SinkGrowth.h"
#include "AtomicDiffusion.h"

// Materials
#include "HomNucleationMaterial.h"
#include "AtomicDiffusionCoef.h"

// Postprocessors
#include "GrainBoundaryGasFlux.h"
#include "SumOfPostprocessors.h"
#include "MaterialXeBubbleTester.h"

// User Objects

template<>
InputParameters validParams<BuckApp>()
{
  InputParameters params = validParams<MooseApp>();
  return params;
}

BuckApp::BuckApp(const std::string & name, InputParameters parameters) :
    MooseApp(name, parameters)
{
  srand(processor_id());

  Moose::registerObjects(_factory);
  BuckApp::registerObjects(_factory);

  Moose::associateSyntax(_syntax, _action_factory);
  BuckApp::associateSyntax(_syntax, _action_factory);
}

BuckApp::~BuckApp()
{
}

void
BuckApp::registerApps()
{
  registerApp(BuckApp);
}

void
BuckApp::registerObjects(Factory & factory)
{
  registerKernel(VariableScaledSource);
  registerKernel(HomNucleation);
  registerKernel(HomClusterDiffusion);
  registerKernel(SinkGrowth);
  registerKernel(AtomicDiffusion);

  registerMaterial(HomNucleationMaterial);
  registerMaterial(AtomicDiffusionCoef);

  registerPostprocessor(GrainBoundaryGasFlux);
  registerPostprocessor(SumOfPostprocessors);
  registerPostprocessor(MaterialXeBubbleTester);
}

void
BuckApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
}

void
BuckApp::runInputFile()
{
  printHeader();
  MooseApp::runInputFile();
}

void
BuckApp::printHeader()
{
  Moose::out  << "\n"
              << "\n"
              << "     ______  _     _  ______ _    _      \n"
              << "    (____  \\| |   | |/ _____) |  / )    \n"
              << "     ____)  | |   | | /     | | / /      \n"
              << "    |  __  (| |   | | |     | |< <       \n"
              << "    | |__)  | |___| | \\_____| | \\ \\   \n"
              << "    |______/ \\______|\\______)_|  \\_)  \n"

              << "\n"
              << "\n"
              << "      Bubble and Cluster Kinetics \n"
              << "        Oregon State University   \n"
              << "             Corvallis, OR        \n"
              << "\n"
              << "\n";

  Moose::out << "Input file:   " << _input_filename << "\n"
             << "Input units:  nanometer, gram, second, kelvin, mole\n"
             << "\n"
             << "BUCK version: " << BUCK_REVISION << std::endl
             << std::endl;
}
<commit_msg>Adding support for dynamic multiapps (see https://github.com/idaholab/moose/issues/4643)<commit_after>#include "BuckApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "BuckRevision.h" // This file is autogenerated and contains the revision.

// Auxkernels

// Kernels
#include "VariableScaledSource.h"
#include "HomNucleation.h"
#include "HomClusterDiffusion.h"
#include "SinkGrowth.h"
#include "AtomicDiffusion.h"

// Materials
#include "HomNucleationMaterial.h"
#include "AtomicDiffusionCoef.h"

// Postprocessors
#include "GrainBoundaryGasFlux.h"
#include "SumOfPostprocessors.h"
#include "MaterialXeBubbleTester.h"

// User Objects

template<>
InputParameters validParams<BuckApp>()
{
  InputParameters params = validParams<MooseApp>();
  return params;
}

BuckApp::BuckApp(const std::string & name, InputParameters parameters) :
    MooseApp(name, parameters)
{
  srand(processor_id());

  Moose::registerObjects(_factory);
  BuckApp::registerObjects(_factory);

  Moose::associateSyntax(_syntax, _action_factory);
  BuckApp::associateSyntax(_syntax, _action_factory);
}

BuckApp::~BuckApp()
{
}

extern "C" void BuckApp__registerApps() { BuckApp::registerApps(); }
void
BuckApp::registerApps()
{
  registerApp(BuckApp);
}

void
BuckApp::registerObjects(Factory & factory)
{
  registerKernel(VariableScaledSource);
  registerKernel(HomNucleation);
  registerKernel(HomClusterDiffusion);
  registerKernel(SinkGrowth);
  registerKernel(AtomicDiffusion);

  registerMaterial(HomNucleationMaterial);
  registerMaterial(AtomicDiffusionCoef);

  registerPostprocessor(GrainBoundaryGasFlux);
  registerPostprocessor(SumOfPostprocessors);
  registerPostprocessor(MaterialXeBubbleTester);
}

void
BuckApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
}

void
BuckApp::runInputFile()
{
  printHeader();
  MooseApp::runInputFile();
}

void
BuckApp::printHeader()
{
  Moose::out  << "\n"
              << "\n"
              << "     ______  _     _  ______ _    _      \n"
              << "    (____  \\| |   | |/ _____) |  / )    \n"
              << "     ____)  | |   | | /     | | / /      \n"
              << "    |  __  (| |   | | |     | |< <       \n"
              << "    | |__)  | |___| | \\_____| | \\ \\   \n"
              << "    |______/ \\______|\\______)_|  \\_)  \n"

              << "\n"
              << "\n"
              << "      Bubble and Cluster Kinetics \n"
              << "        Oregon State University   \n"
              << "             Corvallis, OR        \n"
              << "\n"
              << "\n";

  Moose::out << "Input file:   " << _input_filename << "\n"
             << "Input units:  nanometer, gram, second, kelvin, mole\n"
             << "\n"
             << "BUCK version: " << BUCK_REVISION << std::endl
             << std::endl;
}
<|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file additive_uncorrelated_noise_model.hpp
 * \date July 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__ADDITIVE_UNCORRELATED_NOISE_MODEL_HPP
#define FL__MODEL__ADDITIVE_UNCORRELATED_NOISE_MODEL_HPP

#include <fl/util/types.hpp>
#include <fl/util/traits.hpp>

#include <Eigen/Dense>

namespace fl
{

template <typename NoiseDensity>
class AdditiveUncorrelatedNoiseModel
    : private internal::AdditiveUncorrelatedNoiseModelType
{
public:
    typedef typename NoiseDensity::SecondMoment NoiseMatrix;
public:
    virtual NoiseMatrix noise_matrix_diagonal() const = 0;
    virtual NoiseMatrix noise_covariance_diagonal() const = 0;
};

}

#endif
<commit_msg>interface update<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file additive_uncorrelated_noise_model.hpp
 * \date July 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__ADDITIVE_UNCORRELATED_NOISE_MODEL_HPP
#define FL__MODEL__ADDITIVE_UNCORRELATED_NOISE_MODEL_HPP

#include <fl/util/types.hpp>
#include <fl/util/traits.hpp>

#include <Eigen/Dense>

namespace fl
{

template <typename NoiseDensity>
class AdditiveUncorrelatedNoiseModel
    : private internal::AdditiveUncorrelatedNoiseModelType
{
public:
    typedef typename NoiseDensity::SecondMoment NoiseMatrix;
public:
    virtual NoiseMatrix noise_diagonal_matrix() const = 0;
    virtual NoiseMatrix noise_diagonal_covariance() const = 0;
};

}

#endif
<|endoftext|>


<commit_before>#include "Path.h"

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

const WCHAR NtPathPrefix[] = L"\\\\?\\";
const WCHAR NtOtherPathPrefix[] = L"\\??\\";

LPCWSTR FindSep(LPCWSTR Path)
{
	while (*Path != '/' && *Path != '\\' && *Path != '\0')
		++Path;

	return Path;
}

LPCWSTR CanonizePath(LPCWSTR Path)
{
	if (Path[0] == '\0')
		return Path;

	if (wcsncmp(Path, NtPathPrefix, _countof(NtPathPrefix)-1) == 0)
		return Path; // already NT path

	if (wcsncmp(Path, NtOtherPathPrefix, _countof(NtOtherPathPrefix)-1) == 0)
		return Path; // already NT path

	size_t len = wcslen(Path);

	const WCHAR *src = Path;

	WCHAR *NewPath;
	WCHAR *dst;

	if (Path[0] == L'\\' || Path[0] == L'/')
	{
		// root path ("\foo\bar")

		WCHAR Dir[MAX_PATH];
		DWORD DirLength = GetCurrentDirectoryW(MAX_PATH, Dir);
		if (DirLength == 0)
			return NULL;
		WCHAR Drive = Dir[0];

		NewPath = new WCHAR[(_countof(NtPathPrefix) - 1) + 2 + len + 1];
		if (NewPath == NULL)
			return NULL;
		dst = NewPath;

		wcscpy(dst, NtPathPrefix);
		dst += _countof(NtPathPrefix) - 1;

		*dst = toupper(Drive);
		++dst;
		*dst = ':';
		++dst;
		*dst = '\\';
		++dst;

		src += 1; // skip the first slash
	}
	else if (Path[0] != '\0' && Path[1] == ':')
	{
		// absolute path ("c:\foo\bar")

		NewPath = new WCHAR[(_countof(NtPathPrefix) - 1) + len + 1];
		if (NewPath == NULL)
			return NULL;
		dst = NewPath;

		wcscpy(dst, NtPathPrefix);
		dst += _countof(NtPathPrefix) - 1;

		*dst = toupper(*src);
		++dst;
		*dst = ':';
		++dst;
		*dst = '\\';
		++dst;
		src += 3;
	}
	else
	{
		// relative path

		WCHAR Dir[MAX_PATH];
		DWORD DirLength = GetCurrentDirectoryW(MAX_PATH, Dir); // DirLength does not include NUL
		if (DirLength == 0)
			return NULL;

		NewPath = new WCHAR[(_countof(NtPathPrefix) - 1) + (DirLength) + 1 + len + 1];
		if (NewPath == NULL)
			return NULL;
		dst = NewPath;

		wcscpy(dst, NtPathPrefix);
		dst += _countof(NtPathPrefix) - 1;

		wcscpy(dst, Dir);
		dst += DirLength;

		*dst = L'\\';
		++dst;
	}

	while (*src != '\0')
	{
		LPCWSTR sep = FindSep(src);
		size_t len = sep - src;

		if (sep == src)
		{
			// skip
		}
		else if (wcsncmp(src, L".", len) == 0)
		{
			// skip
		}
		else if (wcsncmp(src, L"..", len) == 0)
		{
			// Move dst cursor:
			//
			// dst = \\?\C:\foo\bar\
			//              ^   ^   ^ cursor
			//              |   |
			//              |   +-new cursor
			//              |
			//              +-NewPath + 7
			//
			// move dst back to the previous backslash
			for (dst -= 2; *dst != L'\\' && dst > NewPath + 7; --dst);
			++dst;
		}
		else
		{
			wcsncpy(dst, src, len);
			dst += len;

			if (*sep != '\0')
			{
				*dst = L'\\'; // append a backslash (never a forward-slash)
				++dst;
			}
		}

		if (*sep == '\0')
			break;
		src = sep + 1;
	}

	*dst = '\0';

	return NewPath;
}
<commit_msg>Pass the CONIN$ and CONOUT$ virtual filenames as-is<commit_after>#include "Path.h"

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

const WCHAR NtPathPrefix[] = L"\\\\?\\";
const WCHAR NtOtherPathPrefix[] = L"\\??\\";

// Pass those as=is
const WCHAR DeviceConin[] = L"CONIN$"; // not a real device, cannot be prefixed by "\\.\"
const WCHAR DeviceConout[] = L"CONOUT$"; // ditto

LPCWSTR FindSep(LPCWSTR Path)
{
	while (*Path != '/' && *Path != '\\' && *Path != '\0')
		++Path;

	return Path;
}

LPCWSTR CanonizePath(LPCWSTR Path)
{
	if (Path[0] == '\0')
		return Path;

	if (wcsnicmp(Path, DeviceConin, _countof(DeviceConin)-1) == 0)
		return Path; // CONIN$

	if (wcsnicmp(Path, DeviceConout, _countof(DeviceConout)-1) == 0)
		return Path; // CONOUT$

	if (wcsncmp(Path, NtPathPrefix, _countof(NtPathPrefix)-1) == 0)
		return Path; // already NT path

	if (wcsncmp(Path, NtOtherPathPrefix, _countof(NtOtherPathPrefix)-1) == 0)
		return Path; // already NT path

	size_t len = wcslen(Path);

	const WCHAR *src = Path;

	WCHAR *NewPath;
	WCHAR *dst;

	if (Path[0] == L'\\' || Path[0] == L'/')
	{
		// root path ("\foo\bar")

		WCHAR Dir[MAX_PATH];
		DWORD DirLength = GetCurrentDirectoryW(MAX_PATH, Dir);
		if (DirLength == 0)
			return NULL;
		WCHAR Drive = Dir[0];

		NewPath = new WCHAR[(_countof(NtPathPrefix) - 1) + 2 + len + 1];
		if (NewPath == NULL)
			return NULL;
		dst = NewPath;

		wcscpy(dst, NtPathPrefix);
		dst += _countof(NtPathPrefix) - 1;

		*dst = toupper(Drive);
		++dst;
		*dst = ':';
		++dst;
		*dst = '\\';
		++dst;

		src += 1; // skip the first slash
	}
	else if (Path[0] != '\0' && Path[1] == ':')
	{
		// absolute path ("c:\foo\bar")

		NewPath = new WCHAR[(_countof(NtPathPrefix) - 1) + len + 1];
		if (NewPath == NULL)
			return NULL;
		dst = NewPath;

		wcscpy(dst, NtPathPrefix);
		dst += _countof(NtPathPrefix) - 1;

		*dst = toupper(*src);
		++dst;
		*dst = ':';
		++dst;
		*dst = '\\';
		++dst;
		src += 3;
	}
	else
	{
		// relative path

		WCHAR Dir[MAX_PATH];
		DWORD DirLength = GetCurrentDirectoryW(MAX_PATH, Dir); // DirLength does not include NUL
		if (DirLength == 0)
			return NULL;

		NewPath = new WCHAR[(_countof(NtPathPrefix) - 1) + (DirLength) + 1 + len + 1];
		if (NewPath == NULL)
			return NULL;
		dst = NewPath;

		wcscpy(dst, NtPathPrefix);
		dst += _countof(NtPathPrefix) - 1;

		wcscpy(dst, Dir);
		dst += DirLength;

		*dst = L'\\';
		++dst;
	}

	while (*src != '\0')
	{
		LPCWSTR sep = FindSep(src);
		size_t len = sep - src;

		if (sep == src)
		{
			// skip
		}
		else if (wcsncmp(src, L".", len) == 0)
		{
			// skip
		}
		else if (wcsncmp(src, L"..", len) == 0)
		{
			// Move dst cursor:
			//
			// dst = \\?\C:\foo\bar\
			//              ^   ^   ^ cursor
			//              |   |
			//              |   +-new cursor
			//              |
			//              +-NewPath + 7
			//
			// move dst back to the previous backslash
			for (dst -= 2; *dst != L'\\' && dst > NewPath + 7; --dst);
			++dst;
		}
		else
		{
			wcsncpy(dst, src, len);
			dst += len;

			if (*sep != '\0')
			{
				*dst = L'\\'; // append a backslash (never a forward-slash)
				++dst;
			}
		}

		if (*sep == '\0')
			break;
		src = sep + 1;
	}

	*dst = '\0';

	return NewPath;
}
<|endoftext|>


<commit_before>#ifndef _itkOpticalFlow_txx
#define _itkOpticalFlow_txx

#include "itkOpticalFlow.h"

namespace itk
{
	//*******************************************
	// Functions definition of Optical Flow Class
	//*******************************************

	//Class Builder
	template< class TInputImage, class TOutputImage>
	OpticalFlow< TInputImage, TOutputImage>
	::OpticalFlow()
	{
		//Number of requaired images to Update
		this->SetNumberOfRequiredInputs( 0 );

		//Default variables values

		if(ImageDimension == 2){
			m_LambdaXY = 6000;
			m_LambdaZ  = 15000;
			m_LambdaW  = 20000;
			m_Iterations = 5;
			m_GaussSeidelIterations = 200;
		}
		else
		{
			m_LambdaXY = 6000;
			m_LambdaZ  = 15000;
			m_LambdaW  = 20000;
			m_Iterations = 5;
			m_GaussSeidelIterations = 200;
		}
		m_Threshold = 1.0;

		//Default Interpolator
		typename DefaultInterpolatorType::Pointer Interp = DefaultInterpolatorType::New();
	  m_Interpolator =  static_cast<InterpolatorType*>( Interp.GetPointer() );
	}

	//********************************************
	//Generate Data   (Main fucntion of the Class)
	//********************************************
	template< class TInputImage, class TOutputImage>
	void OpticalFlow< TInputImage, TOutputImage>
	::GenerateData()
	{

	}

}//namespace itk

#endif
<commit_msg>code optimization of hxx<commit_after>#ifndef _itkOpticalFlow_txx
#define _itkOpticalFlow_txx

#include "itkOpticalFlow.h"

namespace itk
{
	//*******************************************
	// Functions definition of Optical Flow Class
	//*******************************************

	//Class Builder
	template< class TInputImage, class TOutputImage>
	OpticalFlow< TInputImage, TOutputImage>
	::OpticalFlow()
	{
		//Number of requaired images to Update
		this->SetNumberOfRequiredInputs( 0 );

		//Default variables values

		if(ImageDimension == 2){
			m_LambdaXY = 3000;
			m_LambdaZ  = 0;
			m_LambdaW  = 0;
		}
		else
		{
			m_LambdaXY = 6000;
			m_LambdaZ  = 15000;
			m_LambdaW  = 20000;
		}

		m_Iterations = 5;
		m_GaussSeidelIterations = 200;
		m_Threshold = 1.0;

		//Default Interpolator
		typename DefaultInterpolatorType::Pointer Interp = DefaultInterpolatorType::New();
	  m_Interpolator =  static_cast<InterpolatorType*>( Interp.GetPointer() );
	}

	//********************************************
	//Generate Data   (Main fucntion of the Class)
	//********************************************
	template< class TInputImage, class TOutputImage>
	void OpticalFlow< TInputImage, TOutputImage>
	::GenerateData()
	{

	}

}//namespace itk

#endif
<|endoftext|>


<commit_before>#include <vector>
#include <iostream>

#include "utils.hpp"

int shortest_path_dist(vector< vector<int> >);

int main(int argc, char** argv)
{
	if (argc < 2)
	{
		std::cerr << "I needs a file dammit!" << std::endl;
		return 1;
	}
	// well what now?
	// something about an algorithm...
	// oh yes! i think i need to build the distance and pheromones array
	// call shortest path with it
	// then print out the answer

	std::vector< std::vector<int> > dist = read_the_file(argv[1]); // returns a filled distance vector
	std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector

	// start time
	int answer = shortest_path_dist(dist, pheromones)
	// end time

	std::cout << answer << std::endl;
}

// this algorithm has a structure similar to floyds
// so look there for inspiration
// note: a thread pool is the sort of thing desired
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones)
{
	// start all needed threads
	// for each iteration
		// for each ant : IN PARALLEL
			// initialize the ant
			// share distance and pheromone graph for the thread
			// while a tour is not finished
				// choose the next city (eq 1,2)
				// atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without
			// end while // end of ant's travel
			// find the current global best path?
			// atomic: global pheromone update (eq 4)
			// terminate the thread, release resources
		}
		// barrier: all ants
	} // end of iteration
}
<commit_msg>Expanded update explanations.<commit_after>#include <vector>
#include <iostream>

#include "utils.hpp"

int shortest_path_dist(vector< vector<int> >);

int main(int argc, char** argv)
{
	if (argc < 2)
	{
		std::cerr << "I needs a file dammit!" << std::endl;
		return 1;
	}
	// well what now?
	// something about an algorithm...
	// oh yes! i think i need to build the distance and pheromones array
	// call shortest path with it
	// then print out the answer

	std::vector< std::vector<int> > dist = read_the_file(argv[1]); // returns a filled distance vector
	std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector

	// start time
	int answer = shortest_path_dist(dist, pheromones)
	// end time

	std::cout << answer << std::endl;
}

// this algorithm has a structure similar to floyds
// so look there for inspiration
// note: a thread pool is the sort of thing desired
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones)
{
	// start all needed threads
	// for each iteration
		// for each ant : IN PARALLEL
			// initialize the ant
			// share distance and pheromone graph for the thread
			// while a tour is not finished
				// choose the next city (eq 1,2)
				// atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without
			// end while // end of ant's travel
			// atomic: global pheromone update (eq 4)
			// terminate the thread, release resources
		}
		// barrier: all ants
	} // end of iteration
}

/* for updating there are a few possibilities

	1. do not do a local update:
		instead, once done with a tour, do an update for all the paths used for the tour using the global update equation
			where the cost of the 'best path' is the total cost of the tour.
		this ends up being somehthing like a reduce, as everyone wants to update n paths,
			and near the end most of the updates will be happening to the same paths
	2. do the local update and the global update described by the above
	3. do the local update, and then only the master thread will do the global update to the global best path
		this is a problem because now we have to find the best path, which if we knew what it was we would be done
	4. do the local update
		have all the ant's solutions compared and only the one with the best will update the path

	1 or 4 are probably the best options
*/<|endoftext|>


<commit_before><commit_msg>Show backing window instead of empty writer upon an "empty session"<commit_after><|endoftext|>


<commit_before>
/**
 * NNInputSystem.cpp
 * ۼ: ̼
 * ۼ: 2013. 10. 30
 *   : ̼
 * : 2013. 12. 04
 */

#include "NNInputSystem.h"
#include "NNApplication.h"
#include <windows.h>

NNInputSystem* NNInputSystem::mpInstance = nullptr;

NNInputSystem::NNInputSystem()
{
	ZeroMemory( mPrevKeyState, sizeof(mPrevKeyState) );
	ZeroMemory( mNowKeyState, sizeof(mNowKeyState) );
}
NNInputSystem::~NNInputSystem()
{
}

NNInputSystem* NNInputSystem::GetInstance()
{
	if ( mpInstance == nullptr )
	{
		mpInstance = new NNInputSystem();
	}

	return mpInstance;
}
void NNInputSystem::ReleaseInstance()
{
	if ( mpInstance != nullptr )
	{
		delete mpInstance;
		mpInstance = nullptr;
	}
}

void NNInputSystem::UpdateKeyState()
{
	for (int i=0; i<256; i++ )
	{
		mPrevKeyState[i] = mNowKeyState[i];

		if( ::GetKeyState(i) & 0x8000 )
		{
			mNowKeyState[i] = true;
		}
		else
		{
			mNowKeyState[i] = false;
		}
	}
}
KeyState NNInputSystem::GetKeyState( int key )
{
	if ( mPrevKeyState[key] == false && mNowKeyState[key] == true )
	{
		return KEY_DOWN;
	}
	else if ( mPrevKeyState[key] == true && mNowKeyState[key] == true )
	{
		return KEY_PRESSED;
	}
	else if ( mPrevKeyState[key] == true && mNowKeyState[key] == false )
	{
		return KEY_UP;
	}

	return KEY_NOTPRESSED;
}

NNPoint NNInputSystem::GetMousePosition()
{
	POINT pt;
	GetCursorPos( &pt );
	ScreenToClient( NNApplication::GetInstance()->GetHWND(), &pt );

	return NNPoint((float)pt.x,(float)pt.y);
}
<commit_msg>* UpdateKeyState on Window Focus<commit_after>
/**
 * NNInputSystem.cpp
 * ۼ: ̼
 * ۼ: 2013. 10. 30
 *   : ̼
 * : 2013. 12. 04
 */

#include "NNInputSystem.h"
#include "NNApplication.h"
#include <windows.h>

NNInputSystem* NNInputSystem::mpInstance = nullptr;

NNInputSystem::NNInputSystem()
{
	ZeroMemory( mPrevKeyState, sizeof(mPrevKeyState) );
	ZeroMemory( mNowKeyState, sizeof(mNowKeyState) );
}
NNInputSystem::~NNInputSystem()
{
}

NNInputSystem* NNInputSystem::GetInstance()
{
	if ( mpInstance == nullptr )
	{
		mpInstance = new NNInputSystem();
	}

	return mpInstance;
}
void NNInputSystem::ReleaseInstance()
{
	if ( mpInstance != nullptr )
	{
		delete mpInstance;
		mpInstance = nullptr;
	}
}

void NNInputSystem::UpdateKeyState()
{
	if ( GetFocus() == NULL ) return;

	for (int i=0; i<256; i++ )
	{
		mPrevKeyState[i] = mNowKeyState[i];

		if( ::GetKeyState(i) & 0x8000 )
		{
			mNowKeyState[i] = true;
		}
		else
		{
			mNowKeyState[i] = false;
		}
	}
}
KeyState NNInputSystem::GetKeyState( int key )
{
	if ( mPrevKeyState[key] == false && mNowKeyState[key] == true )
	{
		return KEY_DOWN;
	}
	else if ( mPrevKeyState[key] == true && mNowKeyState[key] == true )
	{
		return KEY_PRESSED;
	}
	else if ( mPrevKeyState[key] == true && mNowKeyState[key] == false )
	{
		return KEY_UP;
	}

	return KEY_NOTPRESSED;
}

NNPoint NNInputSystem::GetMousePosition()
{
	POINT pt;
	GetCursorPos( &pt );
	ScreenToClient( NNApplication::GetInstance()->GetHWND(), &pt );

	return NNPoint((float)pt.x,(float)pt.y);
}
<|endoftext|>