<commit_before>/*
 * Copyright (C) 2010 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "config.h"
#include "platform/weborigin/SchemeRegistry.h"

#include "wtf/MainThread.h"
#include "wtf/text/StringBuilder.h"

namespace blink {

static URLSchemesSet& localURLSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, localSchemes, ());

    if (localSchemes.isEmpty())
        localSchemes.add("file");

    return localSchemes;
}

static URLSchemesSet& displayIsolatedURLSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, displayIsolatedSchemes, ());
    return displayIsolatedSchemes;
}

static URLSchemesSet& secureSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, secureSchemes, ());

    if (secureSchemes.isEmpty()) {
        secureSchemes.add("https");
        secureSchemes.add("about");
        secureSchemes.add("data");
        secureSchemes.add("wss");
    }

    return secureSchemes;
}

static URLSchemesSet& schemesWithUniqueOrigins()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, schemesWithUniqueOrigins, ());

    if (schemesWithUniqueOrigins.isEmpty()) {
        schemesWithUniqueOrigins.add("about");
        schemesWithUniqueOrigins.add("javascript");
        // This is a willful violation of HTML5.
        // See https://bugs.webkit.org/show_bug.cgi?id=11885
        schemesWithUniqueOrigins.add("data");
    }

    return schemesWithUniqueOrigins;
}

static URLSchemesSet& emptyDocumentSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, emptyDocumentSchemes, ());

    if (emptyDocumentSchemes.isEmpty())
        emptyDocumentSchemes.add("about");

    return emptyDocumentSchemes;
}

static HashSet<String>& schemesForbiddenFromDomainRelaxation()
{
    DEFINE_STATIC_LOCAL(HashSet<String>, schemes, ());
    return schemes;
}

static URLSchemesSet& canDisplayOnlyIfCanRequestSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, canDisplayOnlyIfCanRequestSchemes, ());

    if (canDisplayOnlyIfCanRequestSchemes.isEmpty()) {
        canDisplayOnlyIfCanRequestSchemes.add("blob");
        canDisplayOnlyIfCanRequestSchemes.add("filesystem");
    }

    return canDisplayOnlyIfCanRequestSchemes;
}

static URLSchemesSet& notAllowingJavascriptURLsSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, notAllowingJavascriptURLsSchemes, ());
    return notAllowingJavascriptURLsSchemes;
}

void SchemeRegistry::registerURLSchemeAsLocal(const String& scheme)
{
    localURLSchemes().add(scheme);
}

void SchemeRegistry::removeURLSchemeRegisteredAsLocal(const String& scheme)
{
    if (scheme == "file")
        return;
    localURLSchemes().remove(scheme);
}

const URLSchemesSet& SchemeRegistry::localSchemes()
{
    return localURLSchemes();
}

static URLSchemesSet& CORSEnabledSchemes()
{
    // FIXME: http://bugs.webkit.org/show_bug.cgi?id=77160
    DEFINE_STATIC_LOCAL(URLSchemesSet, CORSEnabledSchemes, ());

    if (CORSEnabledSchemes.isEmpty()) {
        CORSEnabledSchemes.add("http");
        CORSEnabledSchemes.add("https");
        CORSEnabledSchemes.add("data");
    }

    return CORSEnabledSchemes;
}

static URLSchemesSet& LegacySchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, LegacySchemes, ());

    if (LegacySchemes.isEmpty()) {
        LegacySchemes.add("ftp");
        LegacySchemes.add("gopher");
    }

    return LegacySchemes;
}

static URLSchemesMap<SchemeRegistry::PolicyAreas>& ContentSecurityPolicyBypassingSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesMap<SchemeRegistry::PolicyAreas>, schemes, ());
    return schemes;
}

bool SchemeRegistry::shouldTreatURLSchemeAsLocal(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return localURLSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsNoAccess(const String& scheme)
{
    schemesWithUniqueOrigins().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsNoAccess(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return schemesWithUniqueOrigins().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsDisplayIsolated(const String& scheme)
{
    displayIsolatedURLSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return displayIsolatedURLSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsSecure(const String& scheme)
{
    secureSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsSecure(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return secureSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsEmptyDocument(const String& scheme)
{
    emptyDocumentSchemes().add(scheme);
}

bool SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return emptyDocumentSchemes().contains(scheme);
}

void SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(bool forbidden, const String& scheme)
{
    if (scheme.isEmpty())
        return;

    if (forbidden)
        schemesForbiddenFromDomainRelaxation().add(scheme);
    else
        schemesForbiddenFromDomainRelaxation().remove(scheme);
}

bool SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return schemesForbiddenFromDomainRelaxation().contains(scheme);
}

bool SchemeRegistry::canDisplayOnlyIfCanRequest(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return canDisplayOnlyIfCanRequestSchemes().contains(scheme);
}

void SchemeRegistry::registerAsCanDisplayOnlyIfCanRequest(const String& scheme)
{
    canDisplayOnlyIfCanRequestSchemes().add(scheme);
}

void SchemeRegistry::registerURLSchemeAsNotAllowingJavascriptURLs(const String& scheme)
{
    notAllowingJavascriptURLsSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return notAllowingJavascriptURLsSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsCORSEnabled(const String& scheme)
{
    CORSEnabledSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return CORSEnabledSchemes().contains(scheme);
}

String SchemeRegistry::listOfCORSEnabledURLSchemes()
{
    StringBuilder builder;
    bool addSeparator = false;
    for (const auto& scheme : CORSEnabledSchemes()) {
        if (addSeparator)
            builder.appendLiteral(", ");
        else
            addSeparator = true;

        builder.append(scheme);
    }
    return builder.toString();
}

void SchemeRegistry::registerURLSchemeAsLegacy(const String& scheme)
{
    LegacySchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsLegacy(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return LegacySchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme, PolicyAreas policyAreas)
{
    ContentSecurityPolicyBypassingSchemes().add(scheme, policyAreas);
}

void SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
{
    ContentSecurityPolicyBypassingSchemes().remove(scheme);
}

bool SchemeRegistry::schemeShouldBypassContentSecurityPolicy(const String& scheme, PolicyAreas policyAreas)
{
    ASSERT(policyAreas != PolicyAreaNone);
    if (scheme.isEmpty() || policyAreas == PolicyAreaNone)
        return false;

    // get() returns 0 (PolicyAreaNone) if there is no entry in the map.
    // Thus by default, schemes do not bypass CSP.
    return (ContentSecurityPolicyBypassingSchemes().get(scheme) & policyAreas) == policyAreas;
}

} // namespace blink
<commit_msg>treat app protocol as local scheme<commit_after>/*
 * Copyright (C) 2010 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "config.h"
#include "platform/weborigin/SchemeRegistry.h"

#include "wtf/MainThread.h"
#include "wtf/text/StringBuilder.h"

namespace blink {

static URLSchemesSet& localURLSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, localSchemes, ());

    if (localSchemes.isEmpty()) {
        localSchemes.add("file");
        localSchemes.add("app");
    }

    return localSchemes;
}

static URLSchemesSet& displayIsolatedURLSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, displayIsolatedSchemes, ());
    return displayIsolatedSchemes;
}

static URLSchemesSet& secureSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, secureSchemes, ());

    if (secureSchemes.isEmpty()) {
        secureSchemes.add("https");
        secureSchemes.add("about");
        secureSchemes.add("data");
        secureSchemes.add("wss");
    }

    return secureSchemes;
}

static URLSchemesSet& schemesWithUniqueOrigins()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, schemesWithUniqueOrigins, ());

    if (schemesWithUniqueOrigins.isEmpty()) {
        schemesWithUniqueOrigins.add("about");
        schemesWithUniqueOrigins.add("javascript");
        // This is a willful violation of HTML5.
        // See https://bugs.webkit.org/show_bug.cgi?id=11885
        schemesWithUniqueOrigins.add("data");
    }

    return schemesWithUniqueOrigins;
}

static URLSchemesSet& emptyDocumentSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, emptyDocumentSchemes, ());

    if (emptyDocumentSchemes.isEmpty())
        emptyDocumentSchemes.add("about");

    return emptyDocumentSchemes;
}

static HashSet<String>& schemesForbiddenFromDomainRelaxation()
{
    DEFINE_STATIC_LOCAL(HashSet<String>, schemes, ());
    return schemes;
}

static URLSchemesSet& canDisplayOnlyIfCanRequestSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, canDisplayOnlyIfCanRequestSchemes, ());

    if (canDisplayOnlyIfCanRequestSchemes.isEmpty()) {
        canDisplayOnlyIfCanRequestSchemes.add("blob");
        canDisplayOnlyIfCanRequestSchemes.add("filesystem");
    }

    return canDisplayOnlyIfCanRequestSchemes;
}

static URLSchemesSet& notAllowingJavascriptURLsSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, notAllowingJavascriptURLsSchemes, ());
    return notAllowingJavascriptURLsSchemes;
}

void SchemeRegistry::registerURLSchemeAsLocal(const String& scheme)
{
    localURLSchemes().add(scheme);
}

void SchemeRegistry::removeURLSchemeRegisteredAsLocal(const String& scheme)
{
    if (scheme == "file")
        return;
    localURLSchemes().remove(scheme);
}

const URLSchemesSet& SchemeRegistry::localSchemes()
{
    return localURLSchemes();
}

static URLSchemesSet& CORSEnabledSchemes()
{
    // FIXME: http://bugs.webkit.org/show_bug.cgi?id=77160
    DEFINE_STATIC_LOCAL(URLSchemesSet, CORSEnabledSchemes, ());

    if (CORSEnabledSchemes.isEmpty()) {
        CORSEnabledSchemes.add("http");
        CORSEnabledSchemes.add("https");
        CORSEnabledSchemes.add("data");
    }

    return CORSEnabledSchemes;
}

static URLSchemesSet& LegacySchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesSet, LegacySchemes, ());

    if (LegacySchemes.isEmpty()) {
        LegacySchemes.add("ftp");
        LegacySchemes.add("gopher");
    }

    return LegacySchemes;
}

static URLSchemesMap<SchemeRegistry::PolicyAreas>& ContentSecurityPolicyBypassingSchemes()
{
    DEFINE_STATIC_LOCAL(URLSchemesMap<SchemeRegistry::PolicyAreas>, schemes, ());
    return schemes;
}

bool SchemeRegistry::shouldTreatURLSchemeAsLocal(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return localURLSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsNoAccess(const String& scheme)
{
    schemesWithUniqueOrigins().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsNoAccess(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return schemesWithUniqueOrigins().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsDisplayIsolated(const String& scheme)
{
    displayIsolatedURLSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return displayIsolatedURLSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsSecure(const String& scheme)
{
    secureSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsSecure(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return secureSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsEmptyDocument(const String& scheme)
{
    emptyDocumentSchemes().add(scheme);
}

bool SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return emptyDocumentSchemes().contains(scheme);
}

void SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(bool forbidden, const String& scheme)
{
    if (scheme.isEmpty())
        return;

    if (forbidden)
        schemesForbiddenFromDomainRelaxation().add(scheme);
    else
        schemesForbiddenFromDomainRelaxation().remove(scheme);
}

bool SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return schemesForbiddenFromDomainRelaxation().contains(scheme);
}

bool SchemeRegistry::canDisplayOnlyIfCanRequest(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return canDisplayOnlyIfCanRequestSchemes().contains(scheme);
}

void SchemeRegistry::registerAsCanDisplayOnlyIfCanRequest(const String& scheme)
{
    canDisplayOnlyIfCanRequestSchemes().add(scheme);
}

void SchemeRegistry::registerURLSchemeAsNotAllowingJavascriptURLs(const String& scheme)
{
    notAllowingJavascriptURLsSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return notAllowingJavascriptURLsSchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsCORSEnabled(const String& scheme)
{
    CORSEnabledSchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return CORSEnabledSchemes().contains(scheme);
}

String SchemeRegistry::listOfCORSEnabledURLSchemes()
{
    StringBuilder builder;
    bool addSeparator = false;
    for (const auto& scheme : CORSEnabledSchemes()) {
        if (addSeparator)
            builder.appendLiteral(", ");
        else
            addSeparator = true;

        builder.append(scheme);
    }
    return builder.toString();
}

void SchemeRegistry::registerURLSchemeAsLegacy(const String& scheme)
{
    LegacySchemes().add(scheme);
}

bool SchemeRegistry::shouldTreatURLSchemeAsLegacy(const String& scheme)
{
    if (scheme.isEmpty())
        return false;
    return LegacySchemes().contains(scheme);
}

void SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme, PolicyAreas policyAreas)
{
    ContentSecurityPolicyBypassingSchemes().add(scheme, policyAreas);
}

void SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
{
    ContentSecurityPolicyBypassingSchemes().remove(scheme);
}

bool SchemeRegistry::schemeShouldBypassContentSecurityPolicy(const String& scheme, PolicyAreas policyAreas)
{
    ASSERT(policyAreas != PolicyAreaNone);
    if (scheme.isEmpty() || policyAreas == PolicyAreaNone)
        return false;

    // get() returns 0 (PolicyAreaNone) if there is no entry in the map.
    // Thus by default, schemes do not bypass CSP.
    return (ContentSecurityPolicyBypassingSchemes().get(scheme) & policyAreas) == policyAreas;
}

} // namespace blink
<|endoftext|>


<commit_before>#include <armadillo>
#include <gnuplot-iostream.h>

using namespace arma;
using namespace std;

namespace ic {

class SOM {
public:
    // Constructores
    SOM(const mat& patrones, pair<int, int> dimensiones);

    // Interfaz
    void entrenar(int nEpocas,
                  double velocidadInicial,
                  double velocidadFinal,
                  int vecindadInicial,
                  int vecindadFinal);
    void graficar(Gnuplot& gp) const;

    // Acceso a miembros
    const field<rowvec>& mapa() const { return m_mapa; };
    const mat& patrones() const { return m_patrones; };

private:
    field<rowvec> m_mapa;
    const mat m_patrones;
};

SOM::SOM(const mat& patrones, pair<int, int> dimensiones)
    : m_patrones{patrones}
{
    m_mapa = field<rowvec>(dimensiones.first, dimensiones.second);

    // Inicializar mapa
    for (unsigned int i = 0; i < m_mapa.n_rows; ++i) {
        for (unsigned int j = 0; j < m_mapa.n_cols; ++j) {
            m_mapa(i, j) = randu<rowvec>(patrones.n_cols) - 0.5;
        }
    }
}

void SOM::entrenar(int nEpocas,
                   double velocidadInicial,
                   double velocidadFinal,
                   int vecindadInicial,
                   int vecindadFinal)
{
    const vec velocidad = linspace(velocidadInicial, velocidadFinal, nEpocas);
    // Redondeamos la vecindad porque necesitamos que tenga valores enteros
    const vec vecindad = round(linspace(vecindadInicial, vecindadFinal, nEpocas));

    for (int epoca = 0; epoca < nEpocas; ++epoca) {
        for (unsigned int n = 0; n < m_patrones.n_rows; ++n) {

            // Buscamos la neurona ganadora
            pair<int, int> coordGanadora;
            double distanciaGanadora = numeric_limits<double>::max();

            for (unsigned int j = 0; j < m_mapa.n_rows; ++j) {
                for (unsigned int k = 0; k < m_mapa.n_cols; ++k) {
                    const double distancia = norm(m_patrones.row(n) - m_mapa(j, k));

                    if (distancia < distanciaGanadora) {
                        distanciaGanadora = distancia;
                        coordGanadora = {j, k};
                    }
                }
            }

            // Adaptación de pesos
            const int maxX = int(m_mapa.n_rows - 1);
            const int maxY = int(m_mapa.n_cols - 1);
            const int xInicial = (coordGanadora.first - vecindad(epoca) < 0) ? 0 : (coordGanadora.first - vecindad(epoca));
            const int xFinal = (coordGanadora.first + vecindad(epoca) > maxX) ? maxX : (coordGanadora.first + vecindad(epoca));
            const int yInicial = (coordGanadora.second - vecindad(epoca) < 0) ? 0 : (coordGanadora.second - vecindad(epoca));
            const int yFinal = (coordGanadora.second + vecindad(epoca) > maxY) ? maxY : (coordGanadora.second + vecindad(epoca));

            for (int x = xInicial; x <= xFinal; ++x) {
                for (int y = yInicial; y <= yFinal; ++y) {
                    m_mapa(x, y) += velocidad(epoca) * (m_patrones.row(n) - m_mapa(x, y));
                }
            }
        }
    }
}

void SOM::graficar(gnuplotio::Gnuplot& gp) const
{
    gp << "set key box opaque width 3" << endl
       << "set xlabel 'x_1' font ',11'" << endl
       << "set ylabel 'x_2' font ',11'" << endl
       << "plot ";
    // Graficar neuronas del mapa
    for (unsigned int x = 0; x < m_mapa.n_rows; ++x) {
        for (unsigned int y = 0; y < m_mapa.n_cols; ++y) {
            gp << gp.file1d(m_mapa(x, y).eval()) << "notitle with points ps 2 pt 1 lt -1 lw 3, ";

            // Graficar conexiones con las vecinas
            if (x != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x - 1, y)).eval()) << "notitle with lines lt -1, ";
            if (x != m_mapa.n_rows - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x + 1, y)).eval()) << "notitle with lines lt -1, ";
            if (y != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x, y - 1)).eval()) << "notitle with lines lt -1, ";
            if (y != m_mapa.n_cols - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x, y + 1)).eval()) << "notitle with lines lt -1, ";
            // Graficar conexiones con las vecinas diagonales
            if (x != 0 && y != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x - 1, y - 1)).eval()) << "notitle with lines lt -1, ";
            if (x != 0 && y != m_mapa.n_cols - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x - 1, y + 1)).eval()) << "notitle with lines lt -1, ";
            if (x != m_mapa.n_rows - 1 && y != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x + 1, y - 1)).eval()) << "notitle with lines lt -1, ";
            if (x != m_mapa.n_rows - 1 && y != m_mapa.n_cols - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x + 1, y + 1)).eval()) << "notitle with lines lt -1, ";
        }
    }

    // Graficar patrones
    gp << gp.file1d(m_patrones) << "title 'Patrones' with points pt 2 ps 1 lt rgb 'blue', "
       << "NaN title 'Neuronas' with points ps 2 pt 1 lt -1 lw 3" << endl;
}
}
<commit_msg>Guia 2 - SOM: Modificaciones cosméticas al código de SOM::graficar()<commit_after>#include <armadillo>
#include <gnuplot-iostream.h>

using namespace arma;
using namespace std;

namespace ic {

class SOM {
public:
    // Constructores
    SOM(const mat& patrones, pair<int, int> dimensiones);

    // Interfaz
    void entrenar(int nEpocas,
                  double velocidadInicial,
                  double velocidadFinal,
                  int vecindadInicial,
                  int vecindadFinal);
    void graficar(Gnuplot& gp) const;

    // Acceso a miembros
    const field<rowvec>& mapa() const { return m_mapa; };
    const mat& patrones() const { return m_patrones; };

private:
    field<rowvec> m_mapa;
    const mat m_patrones;
};

SOM::SOM(const mat& patrones, pair<int, int> dimensiones)
    : m_patrones{patrones}
{
    m_mapa = field<rowvec>(dimensiones.first, dimensiones.second);

    // Inicializar mapa
    for (unsigned int i = 0; i < m_mapa.n_rows; ++i) {
        for (unsigned int j = 0; j < m_mapa.n_cols; ++j) {
            m_mapa(i, j) = randu<rowvec>(patrones.n_cols) - 0.5;
        }
    }
}

void SOM::entrenar(int nEpocas,
                   double velocidadInicial,
                   double velocidadFinal,
                   int vecindadInicial,
                   int vecindadFinal)
{
    const vec velocidad = linspace(velocidadInicial, velocidadFinal, nEpocas);
    // Redondeamos la vecindad porque necesitamos que tenga valores enteros
    const vec vecindad = round(linspace(vecindadInicial, vecindadFinal, nEpocas));

    for (int epoca = 0; epoca < nEpocas; ++epoca) {
        for (unsigned int n = 0; n < m_patrones.n_rows; ++n) {

            // Buscamos la neurona ganadora
            pair<int, int> coordGanadora;
            double distanciaGanadora = numeric_limits<double>::max();

            for (unsigned int j = 0; j < m_mapa.n_rows; ++j) {
                for (unsigned int k = 0; k < m_mapa.n_cols; ++k) {
                    const double distancia = norm(m_patrones.row(n) - m_mapa(j, k));

                    if (distancia < distanciaGanadora) {
                        distanciaGanadora = distancia;
                        coordGanadora = {j, k};
                    }
                }
            }

            // Adaptación de pesos
            const int maxX = int(m_mapa.n_rows - 1);
            const int maxY = int(m_mapa.n_cols - 1);
            const int xInicial = (coordGanadora.first - vecindad(epoca) < 0) ? 0 : (coordGanadora.first - vecindad(epoca));
            const int xFinal = (coordGanadora.first + vecindad(epoca) > maxX) ? maxX : (coordGanadora.first + vecindad(epoca));
            const int yInicial = (coordGanadora.second - vecindad(epoca) < 0) ? 0 : (coordGanadora.second - vecindad(epoca));
            const int yFinal = (coordGanadora.second + vecindad(epoca) > maxY) ? maxY : (coordGanadora.second + vecindad(epoca));

            for (int x = xInicial; x <= xFinal; ++x) {
                for (int y = yInicial; y <= yFinal; ++y) {
                    m_mapa(x, y) += velocidad(epoca) * (m_patrones.row(n) - m_mapa(x, y));
                }
            }
        }
    }
}

void SOM::graficar(Gnuplot& gp) const
{
    gp << "set key box opaque width 3" << endl
       << "set xlabel 'x_1' font ',11'" << endl
       << "set ylabel 'x_2' font ',11'" << endl
       << "plot ";

    // Graficar neuronas del mapa y las conexiones
    for (unsigned int x = 0; x < m_mapa.n_rows; ++x) {
        for (unsigned int y = 0; y < m_mapa.n_cols; ++y) {
            // Graficar la neurona
            gp << gp.file1d(m_mapa(x, y).eval()) << "notitle with points ps 2 pt 1 lt -1 lw 3, ";

            // Graficar conexiones con las vecinas horizontales y verticales
            if (x != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x - 1, y)).eval()) << "notitle with lines lt -1, ";
            if (x != m_mapa.n_rows - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x + 1, y)).eval()) << "notitle with lines lt -1, ";
            if (y != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x, y - 1)).eval()) << "notitle with lines lt -1, ";
            if (y != m_mapa.n_cols - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x, y + 1)).eval()) << "notitle with lines lt -1, ";

            // Graficar conexiones con las vecinas diagonales
            if (x != 0 && y != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x - 1, y - 1)).eval()) << "notitle with lines lt -1, ";
            if (x != 0 && y != m_mapa.n_cols - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x - 1, y + 1)).eval()) << "notitle with lines lt -1, ";
            if (x != m_mapa.n_rows - 1 && y != 0)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x + 1, y - 1)).eval()) << "notitle with lines lt -1, ";
            if (x != m_mapa.n_rows - 1 && y != m_mapa.n_cols - 1)
                gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x + 1, y + 1)).eval()) << "notitle with lines lt -1, ";
        }
    }

    // Graficar patrones
    gp << gp.file1d(m_patrones) << "title 'Patrones' with points pt 2 ps 1 lt rgb 'blue', "
       << "NaN title 'Neuronas' with points ps 2 pt 1 lt -1 lw 3" << endl;
}
}
<|endoftext|>


<commit_before>#include <debugger/impl.h>
#include <debugger/path.h>
#include <base/util/unicode.h>
#include <base/util/dynarray.h>
#include <deque>
#include <regex>

namespace vscode
{
	static bool match_sourcemap(const std::string& srv, std::string& cli, const std::string& srvmatch, const std::string& climatch)
	{
		size_t i = 0;
		for (; i < srvmatch.size(); ++i) {
			if (i >= srv.size()) {
				return false;
			}
			if (path::tochar(srvmatch[i]) == path::tochar(srv[i])) {
				continue;
			}
			return false;
		}
		cli = climatch + srv.substr(i);
		return true;
	}

	void debugger_impl::initialize_pathconvert(config& config)
	{
		sourceMap_.clear();
		auto& sourceMaps = config.get("sourceMaps", rapidjson::kArrayType);
		for (auto& e : sourceMaps.GetArray())
		{
			if (!e.IsArray())
			{
				continue;
			}
			auto eary = e.GetArray();
			if (eary.Size() < 2 || !eary[0].IsString() || !eary[1].IsString())
			{
				continue;
			}
			sourceMap_.push_back(std::make_pair(eary[0].Get<std::string>(), eary[1].Get<std::string>()));
		}
		auto& skipFiles = config.get("skipFiles", rapidjson::kArrayType);
		for (auto& e : skipFiles.GetArray())
		{
			if (!e.IsString())
			{
				continue;
			}
			skipFiles_.push_back(e.Get<std::string>());
		}
		workspaceFolder_ = config.get("workspaceFolder", rapidjson::kStringType).Get<std::string>();
	}

	bool debugger_impl::path_server2client(const std::string& server, std::string& client)
	{
		for (auto& it : skipFiles_)
		{
			if (path::glob_match(it, server))
			{
				return false;
			}
		}

		for (auto& it : sourceMap_)
		{
			if (match_sourcemap(server, client, it.first, it.second))
			{
				return true;
			}
		}
		client = server;
		return true;
	}

	bool debugger_impl::path_source2server(const std::string& source, std::string& server)
	{
		if (custom_) {
			return custom_->path_convert(source, server);
		}
		if (source[0] != '@') {
			return false;
		}
		server = sourceCoding_ == eCoding::utf8
			? source.substr(1)
			: base::a2u(base::strview(source.data() + 1, source.size() - 1))
			;
		return true;
	}

	bool debugger_impl::path_source2client(const std::string& source, std::string& client)
	{
		std::string server;
		return path_source2server(source, server) && path_server2client(server, client);
	}

	bool debugger_impl::path_convert(const std::string& source, std::string& client)
	{
		auto it = source2client_.find(source);
		if (it != source2client_.end()) {
			client = it->second;
			return !client.empty();
		}
		bool ok = path_source2client(source, client);
		source2client_[source] = client;
		return ok;
	}

	std::string debugger_impl::path_exception(const std::string& str)
	{
		if (sourceCoding_ == eCoding::utf8) {
			return str;
		}
		std::regex re(R"(([^\r\n]+)(\:[0-9]+\:[^\r\n]+))");
		std::string res;
		std::smatch m;
		auto it = str.begin();
		for (; std::regex_search(it, str.end(), m, re); it = m[0].second) {
			res += std::string(it, m[0].first);
			res += base::a2u(std::string(m[1].first, m[1].second));
			res += std::string(m[2].first, m[2].second);
		}
		res += std::string(it, str.end());
		return res;
	}

	std::string debugger_impl::path_clientrelative(const std::string& path) {
		if (workspaceFolder_.empty()) {
			return path;
		}
		return path::relative(path, workspaceFolder_, '/');
	}
}
<commit_msg>Revert "转换失败时不改变路径"<commit_after>#include <debugger/impl.h>
#include <debugger/path.h>
#include <base/util/unicode.h>
#include <base/util/dynarray.h>
#include <deque>
#include <regex>

namespace vscode
{
	static bool match_sourcemap(const std::string& srv, std::string& cli, const std::string& srvmatch, const std::string& climatch)
	{
		size_t i = 0;
		for (; i < srvmatch.size(); ++i) {
			if (i >= srv.size()) {
				return false;
			}
			if (path::tochar(srvmatch[i]) == path::tochar(srv[i])) {
				continue;
			}
			return false;
		}
		cli = climatch + srv.substr(i);
		return true;
	}

	void debugger_impl::initialize_pathconvert(config& config)
	{
		sourceMap_.clear();
		auto& sourceMaps = config.get("sourceMaps", rapidjson::kArrayType);
		for (auto& e : sourceMaps.GetArray())
		{
			if (!e.IsArray())
			{
				continue;
			}
			auto eary = e.GetArray();
			if (eary.Size() < 2 || !eary[0].IsString() || !eary[1].IsString())
			{
				continue;
			}
			sourceMap_.push_back(std::make_pair(eary[0].Get<std::string>(), eary[1].Get<std::string>()));
		}
		auto& skipFiles = config.get("skipFiles", rapidjson::kArrayType);
		for (auto& e : skipFiles.GetArray())
		{
			if (!e.IsString())
			{
				continue;
			}
			skipFiles_.push_back(e.Get<std::string>());
		}
		workspaceFolder_ = config.get("workspaceFolder", rapidjson::kStringType).Get<std::string>();
	}

	bool debugger_impl::path_server2client(const std::string& server, std::string& client)
	{
		for (auto& it : skipFiles_)
		{
			if (path::glob_match(it, server))
			{
				return false;
			}
		}

		for (auto& it : sourceMap_)
		{
			if (match_sourcemap(server, client, it.first, it.second))
			{
				return true;
			}
		}
		client = path::normalize(server, '/');
		return true;
	}

	bool debugger_impl::path_source2server(const std::string& source, std::string& server)
	{
		if (custom_) {
			return custom_->path_convert(source, server);
		}
		if (source[0] != '@') {
			return false;
		}
		server = sourceCoding_ == eCoding::utf8
			? source.substr(1)
			: base::a2u(base::strview(source.data() + 1, source.size() - 1))
			;
		return true;
	}

	bool debugger_impl::path_source2client(const std::string& source, std::string& client)
	{
		std::string server;
		return path_source2server(source, server) && path_server2client(server, client);
	}

	bool debugger_impl::path_convert(const std::string& source, std::string& client)
	{
		auto it = source2client_.find(source);
		if (it != source2client_.end()) {
			client = it->second;
			return !client.empty();
		}
		bool ok = path_source2client(source, client);
		source2client_[source] = client;
		return ok;
	}

	std::string debugger_impl::path_exception(const std::string& str)
	{
		if (sourceCoding_ == eCoding::utf8) {
			return str;
		}
		std::regex re(R"(([^\r\n]+)(\:[0-9]+\:[^\r\n]+))");
		std::string res;
		std::smatch m;
		auto it = str.begin();
		for (; std::regex_search(it, str.end(), m, re); it = m[0].second) {
			res += std::string(it, m[0].first);
			res += base::a2u(std::string(m[1].first, m[1].second));
			res += std::string(m[2].first, m[2].second);
		}
		res += std::string(it, str.end());
		return res;
	}

	std::string debugger_impl::path_clientrelative(const std::string& path) {
		if (workspaceFolder_.empty()) {
			return path;
		}
		return path::relative(path, workspaceFolder_, '/');
	}
}
<|endoftext|>


<commit_before><commit_msg>Part: fix missing signal disconnect in TaskFaceColors<commit_after><|endoftext|>


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

#ifndef _MANIFEST_EXPORT_HXX
#include <ManifestExport.hxx>
#endif
#ifndef _ATTRIBUTE_LIST_HXX
#include <AttributeList.hxx>
#endif
#ifndef _MANIFEST_DEFINES_HXX
#include <ManifestDefines.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HXX
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif

using namespace rtl;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::sax;

ManifestExport::ManifestExport(Reference < XDocumentHandler > xHandler,  const Sequence < Sequence < PropertyValue > > &rManList)
{
    const OUString sFileEntryElement    ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) );
    const OUString sManifestElement     ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) );
    const OUString sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) );
    const OUString sAlgorithmElement    ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) );
    const OUString sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) );

    const OUString sCdataAttribute      ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) );
    const OUString sMediaTypeAttribute  ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) );
    const OUString sFullPathAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) );
    const OUString sSizeAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) );
    const OUString sSaltAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) );
    const OUString sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) );
    const OUString sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) );
    const OUString sAlgorithmNameAttribute  ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) );
    const OUString sKeyDerivationNameAttribute  ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) );

    const OUString sFullPathProperty    ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) );
    const OUString sMediaTypeProperty   ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) );
    const OUString sIterationCountProperty  ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) );
    const OUString sSaltProperty        ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) );
    const OUString sInitialisationVectorProperty( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) );
    const OUString sSizeProperty        ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) );

    const OUString sWhiteSpace          ( RTL_CONSTASCII_USTRINGPARAM ( " " ) );
    const OUString sBlowfish            ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) );
    const OUString sPBKDF2              ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) );

    AttributeList * pRootAttrList = new AttributeList;
    pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ),
                                  sCdataAttribute,
                                  OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_NAMESPACE ) ) );

    Reference < XAttributeList > xRootAttrList (pRootAttrList);

    xHandler->startDocument();
    Reference < XExtendedDocumentHandler > xExtHandler ( xHandler, UNO_QUERY );
    if (xExtHandler.is())
    {
        OUString aDocType ( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_DOCTYPE ) );
        xExtHandler->unknown ( aDocType );
    }
    xHandler->ignorableWhitespace ( sWhiteSpace );
    xHandler->startElement( sManifestElement, xRootAttrList );

    const Sequence < PropertyValue > *pSequence = rManList.getConstArray();

    for (sal_uInt32 i = 0, nEnd = rManList.getLength() ; i < nEnd ; i++)
    {
        AttributeList *pAttrList = new AttributeList;
        const PropertyValue *pValue = pSequence->getConstArray();
        OUString aString;
        const PropertyValue *pVector = NULL, *pSalt = NULL, *pIterationCount = NULL;
        for (sal_uInt32 j = 0, nNum = pSequence->getLength(); j < nNum; j++, pValue++)
        {
            if (pValue->Name.equals (sMediaTypeProperty) )
            {
                pValue->Value >>= aString;
                pAttrList->AddAttribute ( sMediaTypeAttribute, sCdataAttribute, aString );
            }
            else if (pValue->Name.equals (sFullPathProperty) )
            {
                pValue->Value >>= aString;
                pAttrList->AddAttribute ( sFullPathAttribute, sCdataAttribute, aString );
            }
            else if (pValue->Name.equals (sSizeProperty) )
            {
                sal_Int32 nSize;
                pValue->Value >>= nSize;
                OUStringBuffer aBuffer;
                aBuffer.append ( nSize );
                pAttrList->AddAttribute ( sSizeAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
            }
            else if (pValue->Name.equals (sInitialisationVectorProperty) )
                pVector = pValue;
            else if (pValue->Name.equals (sSaltProperty) )
                pSalt = pValue;
            else if (pValue->Name.equals (sIterationCountProperty) )
                pIterationCount = pValue;
        }
        Reference < XAttributeList > xAttrList = pAttrList;
        xHandler->ignorableWhitespace ( sWhiteSpace );
        xHandler->startElement( sFileEntryElement , xAttrList);
        if ( pVector && pSalt && pIterationCount )
        {
            AttributeList * pAttrList = new AttributeList;
            Reference < XAttributeList > xAttrList (pAttrList);
            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->startElement( sEncryptionDataElement , xAttrList);

            pAttrList = new AttributeList;
            xAttrList = pAttrList;

            pAttrList->AddAttribute ( sAlgorithmNameAttribute, sCdataAttribute, sBlowfish );

            OUStringBuffer aBuffer;
            Sequence < sal_uInt8 > aSequence;
            pVector->Value >>= aSequence;
            Base64Codec::encodeBase64 ( aBuffer, aSequence );
            pAttrList->AddAttribute ( sInitialisationVectorAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );

            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->startElement( sAlgorithmElement , xAttrList);
            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->endElement( sAlgorithmElement );

            pAttrList = new AttributeList;
            xAttrList = pAttrList;

            pAttrList->AddAttribute ( sKeyDerivationNameAttribute, sCdataAttribute, sPBKDF2 );

            sal_Int32 nCount;
            pIterationCount->Value >>= nCount;
            aBuffer.append (nCount);
            pAttrList->AddAttribute ( sIterationCountAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );

            pSalt->Value >>= aSequence;
            Base64Codec::encodeBase64 ( aBuffer, aSequence );
            pAttrList->AddAttribute ( sSaltAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );

            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->startElement( sKeyDerivationElement , xAttrList);
            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->endElement( sKeyDerivationElement );
            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->endElement( sEncryptionDataElement );
        }
        xHandler->ignorableWhitespace ( sWhiteSpace );
        xHandler->endElement( sFileEntryElement );
        pSequence++;
    }
    xHandler->ignorableWhitespace ( sWhiteSpace );
    xHandler->endElement( sManifestElement );
    xHandler->endDocument();
}
<commit_msg>#90699# Export MD5 of decrypted stream<commit_after>/*************************************************************************
 *
 *  $RCSfile: ManifestExport.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: mtg $ $Date: 2001-09-05 19:21:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#ifndef _MANIFEST_EXPORT_HXX
#include <ManifestExport.hxx>
#endif
#ifndef _ATTRIBUTE_LIST_HXX
#include <AttributeList.hxx>
#endif
#ifndef _MANIFEST_DEFINES_HXX
#include <ManifestDefines.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HXX
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif

using namespace rtl;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::sax;

ManifestExport::ManifestExport(Reference < XDocumentHandler > xHandler,  const Sequence < Sequence < PropertyValue > > &rManList)
{
    const OUString sFileEntryElement    ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) );
    const OUString sManifestElement     ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) );
    const OUString sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) );
    const OUString sAlgorithmElement    ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) );
    const OUString sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) );

    const OUString sCdataAttribute      ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) );
    const OUString sMediaTypeAttribute  ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) );
    const OUString sFullPathAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) );
    const OUString sSizeAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) );
    const OUString sSaltAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) );
    const OUString sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) );
    const OUString sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) );
    const OUString sAlgorithmNameAttribute  ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) );
    const OUString sKeyDerivationNameAttribute  ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) );
    const OUString sChecksumTypeAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) );
    const OUString sChecksumAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM) );

    const OUString sFullPathProperty    ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) );
    const OUString sMediaTypeProperty   ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) );
    const OUString sIterationCountProperty  ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) );
    const OUString sSaltProperty        ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) );
    const OUString sInitialisationVectorProperty( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) );
    const OUString sSizeProperty        ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) );
    const OUString sDigestProperty      ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) );

    const OUString sWhiteSpace          ( RTL_CONSTASCII_USTRINGPARAM ( " " ) );
    const OUString sBlowfish            ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) );
    const OUString sPBKDF2              ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) );
    const OUString sMD5                 ( RTL_CONSTASCII_USTRINGPARAM ( "MD5" ) );

    AttributeList * pRootAttrList = new AttributeList;
    pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ),
                                  sCdataAttribute,
                                  OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_NAMESPACE ) ) );

    Reference < XAttributeList > xRootAttrList (pRootAttrList);

    xHandler->startDocument();
    Reference < XExtendedDocumentHandler > xExtHandler ( xHandler, UNO_QUERY );
    if (xExtHandler.is())
    {
        OUString aDocType ( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_DOCTYPE ) );
        xExtHandler->unknown ( aDocType );
    }
    xHandler->ignorableWhitespace ( sWhiteSpace );
    xHandler->startElement( sManifestElement, xRootAttrList );

    const Sequence < PropertyValue > *pSequence = rManList.getConstArray();

    for (sal_uInt32 i = 0, nEnd = rManList.getLength() ; i < nEnd ; i++)
    {
        AttributeList *pAttrList = new AttributeList;
        const PropertyValue *pValue = pSequence->getConstArray();
        OUString aString;
        const PropertyValue *pVector = NULL, *pSalt = NULL, *pIterationCount = NULL, *pDigest = NULL;
        for (sal_uInt32 j = 0, nNum = pSequence->getLength(); j < nNum; j++, pValue++)
        {
            if (pValue->Name.equals (sMediaTypeProperty) )
            {
                pValue->Value >>= aString;
                pAttrList->AddAttribute ( sMediaTypeAttribute, sCdataAttribute, aString );
            }
            else if (pValue->Name.equals (sFullPathProperty) )
            {
                pValue->Value >>= aString;
                pAttrList->AddAttribute ( sFullPathAttribute, sCdataAttribute, aString );
            }
            else if (pValue->Name.equals (sSizeProperty) )
            {
                sal_Int32 nSize;
                pValue->Value >>= nSize;
                OUStringBuffer aBuffer;
                aBuffer.append ( nSize );
                pAttrList->AddAttribute ( sSizeAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
            }
            else if (pValue->Name.equals (sInitialisationVectorProperty) )
                pVector = pValue;
            else if (pValue->Name.equals (sSaltProperty) )
                pSalt = pValue;
            else if (pValue->Name.equals (sIterationCountProperty) )
                pIterationCount = pValue;
            else if (pValue->Name.equals ( sDigestProperty ) )
                pDigest = pValue;
        }
        xHandler->ignorableWhitespace ( sWhiteSpace );
        Reference < XAttributeList > xAttrList ( pAttrList );
        xHandler->startElement( sFileEntryElement , xAttrList);
        if ( pVector && pSalt && pIterationCount )
        {
            AttributeList * pAttrList = new AttributeList;
            Reference < XAttributeList > xAttrList (pAttrList);
            OUStringBuffer aBuffer;
            Sequence < sal_uInt8 > aSequence;

            xHandler->ignorableWhitespace ( sWhiteSpace );
            if ( pDigest )
            {
                pAttrList->AddAttribute ( sChecksumTypeAttribute, sCdataAttribute, sMD5 );
                pDigest->Value >>= aSequence;
                Base64Codec::encodeBase64 ( aBuffer, aSequence );
                pAttrList->AddAttribute ( sChecksumAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );
            }
            xHandler->startElement( sEncryptionDataElement , xAttrList);

            pAttrList = new AttributeList;
            xAttrList = pAttrList;

            pAttrList->AddAttribute ( sAlgorithmNameAttribute, sCdataAttribute, sBlowfish );

            pVector->Value >>= aSequence;
            Base64Codec::encodeBase64 ( aBuffer, aSequence );
            pAttrList->AddAttribute ( sInitialisationVectorAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );

            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->startElement( sAlgorithmElement , xAttrList);
            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->endElement( sAlgorithmElement );

            pAttrList = new AttributeList;
            xAttrList = pAttrList;

            pAttrList->AddAttribute ( sKeyDerivationNameAttribute, sCdataAttribute, sPBKDF2 );

            sal_Int32 nCount;
            pIterationCount->Value >>= nCount;
            aBuffer.append (nCount);
            pAttrList->AddAttribute ( sIterationCountAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );

            pSalt->Value >>= aSequence;
            Base64Codec::encodeBase64 ( aBuffer, aSequence );
            pAttrList->AddAttribute ( sSaltAttribute, sCdataAttribute, aBuffer.makeStringAndClear() );

            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->startElement( sKeyDerivationElement , xAttrList);
            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->endElement( sKeyDerivationElement );
            xHandler->ignorableWhitespace ( sWhiteSpace );
            xHandler->endElement( sEncryptionDataElement );
        }
        xHandler->ignorableWhitespace ( sWhiteSpace );
        xHandler->endElement( sFileEntryElement );
        pSequence++;
    }
    xHandler->ignorableWhitespace ( sWhiteSpace );
    xHandler->endElement( sManifestElement );
    xHandler->endDocument();
}
<|endoftext|>


<commit_before>/**
 * @cond ___LICENSE___
 *
 * Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @endcond
 */

#include "math/mathf.h"

#include <assert.h>
#include <cstdlib>
#include <limits>

#define _USE_MATH_DEFINES
#include <math.h>

F32 Mathf::GetEpsilon()
{
    return std::numeric_limits<F32>::epsilon();
}

F32 Mathf::GetPi()
{
    return ( F32 )M_PI;
}

F32 Mathf::Get2Pi()
{
    return ( F32 )M_PI_2;
}

F32 Mathf::GetSqrt2()
{
    return ( F32 )M_SQRT2;
}

F32 Mathf::GetE()
{
    return ( F32 )M_E;
}

F32 Mathf::GetLog2E()
{
    return ( F32 )M_LOG2E;
}

F32 Mathf::GetLog10E()
{
    return ( F32 )M_LOG10E;
}

F32 Mathf::GetLn2()
{
    return ( F32 )M_LN2;
}

F32 Mathf::GetLn10()
{
    return ( F32 )M_LN10;
}

F32 Mathf::Abs( const F32 f )
{
    return fabsf( f );
}

U32 Mathf::Abs( const U32 f )
{
    return abs( ( int )f );
}

F32 Mathf::Acos( const F32 f )
{
    assert( f >= -1.0f && f <= 1.0f );
    return acosf( f );
}

F32 Mathf::Asin( const F32 f )
{
    assert( f >= -1.0f && f <= 1.0f );
    return asinf( f );
}

F32 Mathf::Atan( const F32 f )
{
    return atanf( f );
}

F32 Mathf::Atan2( const F32 x, const F32 y )
{
    return atan2f( x, y );
}

F32 Mathf::Cos( const F32 f )
{
    return cosf( f );
}

F32 Mathf::Sin( const F32 f )
{
    return sinf( f );
}

F32 Mathf::Tan( const F32 f )
{
    return tanf( f );
}

F32 Mathf::Exp( const F32 f )
{
    return expf( f );
}

F32 Mathf::Ceil( const F32 f )
{
    return ceilf( f );
}

F32 Mathf::Floor( const F32 f )
{
    return floorf( f );
}

F32 Mathf::Round( const F32 f )
{
    return f >= 0.0 ? f + 0.5f : ( ( f - ( F32 )( S32 )f ) <= -0.5 ? f : f - 0.5f );
}

F32 Mathf::FMod( const F32 f, const F32 m )
{
    return std::fmodf( f, m );
}

F32 Mathf::Log( const F32 f )
{
    assert( f > 0.0f );
    return logf( f );
}

F32 Mathf::Log2( const F32 f )
{
    assert( f > 0.0f );
    return logf( f ) / logf( 2 );
}

U32 Mathf::Log2( U64 n )
{
    static const U32 tab64[64] =
    {
        0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61,
        51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62,
        57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56,
        45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5, 63
    };

    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n |= n >> 32;
    return tab64[( n * 0x03f6eaf2cd271461 ) >> 58];
}

U32 Mathf::Log2( U32 f )
{
    U32 s, t;

    t = ( f > 0xffff ) << 4;
    f >>= t;
    s = ( f > 0xff ) << 3;
    f >>= s, t |= s;
    s = ( f > 0xf ) << 2;
    f >>= s, t |= s;
    s = ( f > 0x3 ) << 1;
    f >>= s, t |= s;

    return ( t | ( f >> 1 ) );
}

F32 Mathf::Log10( const F32 f )
{
    assert( f > 0.0f );
    return log10f( f );
}

F32 Mathf::Pow( const F32 base, const F32 exp )
{
    return powf( base, exp );
}

F32 Mathf::Sqrt( const F32 f )
{
    assert( f >= 0.0f );
    return sqrtf( f );
}

F32 Mathf::Square( F32 f )
{
    return f * f;
}

F32 Mathf::Clamp( const F32 f, const F32 min, const F32 max )
{
    return f < min ? min : ( f > max ? max : f );
}

F32 Mathf::RadToDeg( const F32 f )
{
    return f * 180.0f / GetPi();
}

F32 Mathf::DegToRad( const F32 f )
{
    return f * GetPi() / 180.0f;
}

F32 Mathf::Lerp( const F32 a, const F32 b, const F32 t )
{
    return a + ( b - a ) * t;
}

bool Mathf::IsPow2( const U32 n )
{
    return ( !( n & ( n - 1 ) ) && n );
}

U32 Mathf::NextPow2( const U32 x )
{
    U32 y = x - 1;
    y |= y >> 1;
    y |= y >> 2;
    y |= y >> 4;
    y |= y >> 8;
    y |= y >> 16;
    return ++y;
}

bool Mathf::Equal( const F32 a, const F32 b )
{
    return fabs( a - b ) < GetEpsilon();
}
<commit_msg>Fixed namespace<commit_after>/**
 * @cond ___LICENSE___
 *
 * Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @endcond
 */

#include "math/mathf.h"

#include <assert.h>
#include <cstdlib>
#include <limits>

#define _USE_MATH_DEFINES
#include <math.h>

F32 Mathf::GetEpsilon()
{
    return std::numeric_limits<F32>::epsilon();
}

F32 Mathf::GetPi()
{
    return ( F32 )M_PI;
}

F32 Mathf::Get2Pi()
{
    return ( F32 )M_PI_2;
}

F32 Mathf::GetSqrt2()
{
    return ( F32 )M_SQRT2;
}

F32 Mathf::GetE()
{
    return ( F32 )M_E;
}

F32 Mathf::GetLog2E()
{
    return ( F32 )M_LOG2E;
}

F32 Mathf::GetLog10E()
{
    return ( F32 )M_LOG10E;
}

F32 Mathf::GetLn2()
{
    return ( F32 )M_LN2;
}

F32 Mathf::GetLn10()
{
    return ( F32 )M_LN10;
}

F32 Mathf::Abs( const F32 f )
{
    return fabsf( f );
}

U32 Mathf::Abs( const U32 f )
{
    return abs( ( int )f );
}

F32 Mathf::Acos( const F32 f )
{
    assert( f >= -1.0f && f <= 1.0f );
    return acosf( f );
}

F32 Mathf::Asin( const F32 f )
{
    assert( f >= -1.0f && f <= 1.0f );
    return asinf( f );
}

F32 Mathf::Atan( const F32 f )
{
    return atanf( f );
}

F32 Mathf::Atan2( const F32 x, const F32 y )
{
    return atan2f( x, y );
}

F32 Mathf::Cos( const F32 f )
{
    return cosf( f );
}

F32 Mathf::Sin( const F32 f )
{
    return sinf( f );
}

F32 Mathf::Tan( const F32 f )
{
    return tanf( f );
}

F32 Mathf::Exp( const F32 f )
{
    return expf( f );
}

F32 Mathf::Ceil( const F32 f )
{
    return ceilf( f );
}

F32 Mathf::Floor( const F32 f )
{
    return floorf( f );
}

F32 Mathf::Round( const F32 f )
{
    return f >= 0.0 ? f + 0.5f : ( ( f - ( F32 )( S32 )f ) <= -0.5 ? f : f - 0.5f );
}

F32 Mathf::FMod( const F32 f, const F32 m )
{
    return fmodf( f, m );
}

F32 Mathf::Log( const F32 f )
{
    assert( f > 0.0f );
    return logf( f );
}

F32 Mathf::Log2( const F32 f )
{
    assert( f > 0.0f );
    return logf( f ) / logf( 2 );
}

U32 Mathf::Log2( U64 n )
{
    static const U32 tab64[64] =
    {
        0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61,
        51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62,
        57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56,
        45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5, 63
    };

    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n |= n >> 32;
    return tab64[( n * 0x03f6eaf2cd271461 ) >> 58];
}

U32 Mathf::Log2( U32 f )
{
    U32 s, t;

    t = ( f > 0xffff ) << 4;
    f >>= t;
    s = ( f > 0xff ) << 3;
    f >>= s, t |= s;
    s = ( f > 0xf ) << 2;
    f >>= s, t |= s;
    s = ( f > 0x3 ) << 1;
    f >>= s, t |= s;

    return ( t | ( f >> 1 ) );
}

F32 Mathf::Log10( const F32 f )
{
    assert( f > 0.0f );
    return log10f( f );
}

F32 Mathf::Pow( const F32 base, const F32 exp )
{
    return powf( base, exp );
}

F32 Mathf::Sqrt( const F32 f )
{
    assert( f >= 0.0f );
    return sqrtf( f );
}

F32 Mathf::Square( F32 f )
{
    return f * f;
}

F32 Mathf::Clamp( const F32 f, const F32 min, const F32 max )
{
    return f < min ? min : ( f > max ? max : f );
}

F32 Mathf::RadToDeg( const F32 f )
{
    return f * 180.0f / GetPi();
}

F32 Mathf::DegToRad( const F32 f )
{
    return f * GetPi() / 180.0f;
}

F32 Mathf::Lerp( const F32 a, const F32 b, const F32 t )
{
    return a + ( b - a ) * t;
}

bool Mathf::IsPow2( const U32 n )
{
    return ( !( n & ( n - 1 ) ) && n );
}

U32 Mathf::NextPow2( const U32 x )
{
    U32 y = x - 1;
    y |= y >> 1;
    y |= y >> 2;
    y |= y >> 4;
    y |= y >> 8;
    y |= y >> 16;
    return ++y;
}

bool Mathf::Equal( const F32 a, const F32 b )
{
    return fabs( a - b ) < GetEpsilon();
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.4  2000/02/06 07:47:28  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.3  2000/02/04 05:46:31  andyh
 * Change offsets and lengths form signed to unsigned
 *
 * Revision 1.2  2000/01/05 01:16:06  andyh
 * DOM Level 2 core, namespace support added.
 *
 * Revision 1.1.1.1  1999/11/09 01:08:53  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:44:14  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#ifndef DOMException_HEADER_GUARD_
#define DOMException_HEADER_GUARD_

#include <util/XML4CDefs.hpp>
#include <dom/DOMString.hpp>

/**
  * Encapsulate a general DOM error or warning.
  *
  *
 The DOM will create and throw an instance of DOMException
  * when an error condition is detected.  Exceptions can occur
  * when an application directly manipulates the DOM document
  * tree that is produced by the parser, or when a document tree
  * is created from scratch using the DOM API.  DOM exceptions will
  * not be generated by the parser while constructing a document
  * tree from an XML source document.
  *
  *
Unlike the other classes in the C++ DOM API, DOM_DOMException
  * is NOT a reference to an underlying implementation class, and
  * does not provide automatic memory management.  Code that catches
  * a DOM exception is responsible for deleting it, or otherwise
  * arranging for its disposal.
  *
  */
class CDOM_EXPORT DOM_DOMException  {
public:
        enum ExceptionCode {
                INDEX_SIZE_ERR       = 1,
                DOMSTRING_SIZE_ERR   = 2,
                HIERARCHY_REQUEST_ERR = 3,
                WRONG_DOCUMENT_ERR   = 4,
                INVALID_CHARACTER_ERR = 5,
                NO_DATA_ALLOWED_ERR  = 6,
                NO_MODIFICATION_ALLOWED_ERR = 7,
                NOT_FOUND_ERR        = 8,
                NOT_SUPPORTED_ERR    = 9,
                INUSE_ATTRIBUTE_ERR  = 10,
                INVALID_STATE_ERR    = 11,
	        	SYNTAX_ERR	     = 12,
        		INVALID_MODIFICATION_ERR    = 13,
        		NAMESPACE_ERR	     = 14,
        		INVALID_ACCESS_ERR   = 15
        };
public:
    /** @name Constructors and assignment operator */
    //@{
    /**
      * Default constructor for DOM_DOMException.
      *
      */
    DOM_DOMException();

    /**
      * Constructor which takes an error code and a message.
      *
      * @param code The error code which indicates the exception
      * @param message The string containing the error message
      */
    DOM_DOMException(short code, const DOMString &message);

    /**
      * Copy constructor.
      *
      * @param other The object to be copied.
      */
    DOM_DOMException(const DOM_DOMException &other);

    //@}
    /** @name Destructor. */
    //@{
	 /**
	  * Destructor for DOM_DOMException.  Applications are responsible
      * for deleting DOM_Exception objects that they catch after they
      * have completed their exception processing.
	  *
	  */
    virtual ~DOM_DOMException();
    //@}

    /** @name Public variables. */
     //@{
	 /**
	  * A code value, from the set defined by the ExceptionCode enum,
      * indicating the type of error that occured.
	  */
   ExceptionCode   code;

	 /**
	  * A string value.  Applications may use this field to hold an error
      *  message.  The field value is not set by the DOM implementation,
      *  meaning that the string will be empty when an exception is first
      *  thrown.
	  */
    DOMString msg;
    //@}

};

#endif

<commit_msg>Added docs for enum<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.5  2000/02/10 19:52:08  abagchi
 * Added docs for enum
 *
 * Revision 1.4  2000/02/06 07:47:28  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.3  2000/02/04 05:46:31  andyh
 * Change offsets and lengths form signed to unsigned
 *
 * Revision 1.2  2000/01/05 01:16:06  andyh
 * DOM Level 2 core, namespace support added.
 *
 * Revision 1.1.1.1  1999/11/09 01:08:53  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:44:14  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#ifndef DOMException_HEADER_GUARD_
#define DOMException_HEADER_GUARD_

#include <util/XML4CDefs.hpp>
#include <dom/DOMString.hpp>

/**
  * Encapsulate a general DOM error or warning.
  *
  *
 The DOM will create and throw an instance of DOMException
  * when an error condition is detected.  Exceptions can occur
  * when an application directly manipulates the DOM document
  * tree that is produced by the parser, or when a document tree
  * is created from scratch using the DOM API.  DOM exceptions will
  * not be generated by the parser while constructing a document
  * tree from an XML source document.
  *
  *
Unlike the other classes in the C++ DOM API, DOM_DOMException
  * is NOT a reference to an underlying implementation class, and
  * does not provide automatic memory management.  Code that catches
  * a DOM exception is responsible for deleting it, or otherwise
  * arranging for its disposal.
  *
  */
class CDOM_EXPORT DOM_DOMException  {
public:
    /** @name Enumerators for DOM Exceptions */
    //@{
        enum ExceptionCode {
                INDEX_SIZE_ERR       = 1,
                DOMSTRING_SIZE_ERR   = 2,
                HIERARCHY_REQUEST_ERR = 3,
                WRONG_DOCUMENT_ERR   = 4,
                INVALID_CHARACTER_ERR = 5,
                NO_DATA_ALLOWED_ERR  = 6,
                NO_MODIFICATION_ALLOWED_ERR = 7,
                NOT_FOUND_ERR        = 8,
                NOT_SUPPORTED_ERR    = 9,
                INUSE_ATTRIBUTE_ERR  = 10,
                INVALID_STATE_ERR    = 11,
	       	SYNTAX_ERR	     = 12,
        	INVALID_MODIFICATION_ERR    = 13,
        	NAMESPACE_ERR	     = 14,
        	INVALID_ACCESS_ERR   = 15
        };
    //@}
public:
    /** @name Constructors and assignment operator */
    //@{
    /**
      * Default constructor for DOM_DOMException.
      *
      */
    DOM_DOMException();

    /**
      * Constructor which takes an error code and a message.
      *
      * @param code The error code which indicates the exception
      * @param message The string containing the error message
      */
    DOM_DOMException(short code, const DOMString &message);

    /**
      * Copy constructor.
      *
      * @param other The object to be copied.
      */
    DOM_DOMException(const DOM_DOMException &other);

    //@}
    /** @name Destructor. */
    //@{
	 /**
	  * Destructor for DOM_DOMException.  Applications are responsible
      * for deleting DOM_Exception objects that they catch after they
      * have completed their exception processing.
	  *
	  */
    virtual ~DOM_DOMException();
    //@}

    /** @name Public variables. */
     //@{
	 /**
	  * A code value, from the set defined by the ExceptionCode enum,
      * indicating the type of error that occured.
	  */
   ExceptionCode   code;

	 /**
	  * A string value.  Applications may use this field to hold an error
      *  message.  The field value is not set by the DOM implementation,
      *  meaning that the string will be empty when an exception is first
      *  thrown.
	  */
    DOMString msg;
    //@}

};

#endif

<|endoftext|>


<commit_before>/* HamiltonianPath.cpp
**
** finds Hamiltonian Path if exists. returns as a list of vertices, which indicates the path from source to the final destination.
** takes AdjacencyMatrix as input.
**
** Note that all vertices number starts from 0 (inclusive), to match with the index numbers of arrays.
**
** worked find in original projects but not tested after extracted to here. (I must check...)
**
** All compiled and tested with g++ 6.2.0 MinGW-W64
**
** MIT License
** Copyright (c) 2017 636F57@GitHub
** See more detail at https://github.com/636F57/Algos/blob/master/LICENSE
*/

#include <cstdlib>
#include <vector>
#include <deque>
#include <iostream>

class HamiltonianPath
{
private:
	struct pathstatus
	{
		int end_vertex;          // current vertex
		std::vector<int> vUsed;  // array to store the previous vertex of when visited, otherwise -1.
		int usedcnt;             // number of used vertecies
	};

public:
	HamiltonianPath(){}
	~HamiltonianPath(){}

	static std::vector<std::vector<int>> getHamiltonianPath(std::vector<std::vector<bool>>& vAdjacencyMatrix, int nStartVertex)
	{
		int nVertexNum = vAdjacencyMatrix.size();

		std::vector<std::vector<int>> vHamiltonianPathList;
		std::vector<int> vTmpHamiltonianPath(nVertexNum);
		std::vector<int> vUsed(nVertexNum, -1);

		vUsed[nStartVertex] = -2;       // previous vertex not available as starting vertex
		pathstatus tmpstatus, currentstatus;
		tmpstatus.end_vertex = nStartVertex;
		tmpstatus.usedcnt = 1;
		tmpstatus.vUsed.assign(vUsed.begin(),vUsed.end());
		std::deque<pathstatus> dqTmpPath({tmpstatus});

		int i, j, nCurrentVertex;

		while (dqTmpPath.size() > 0)
		{
			currentstatus = dqTmpPath.front();
			dqTmpPath.pop_front();
			nCurrentVertex = currentstatus.end_vertex;

			if (currentstatus.usedcnt == nVertexNum)  // Hamiltonian path found.
			{
				vTmpHamiltonianPath[nVertexNum-1] = nCurrentVertex;
				for (i=nVertexNum-2; i>=0; i--)
				{
					vTmpHamiltonianPath[i] = currentstatus.vUsed[vTmpHamiltonianPath[i+1]];
				}
				vHamiltonianPathList.push_back(vTmpHamiltonianPath);
				continue;
			}

			// go to the next vertex which is not used yet
			for (i=0; i<nVertexNum; i++)
			{
				if (vAdjacencyMatrix[nCurrentVertex][i] == false)
					continue;

				if (currentstatus.vUsed[i] != -1)
					continue;

				tmpstatus.end_vertex = i;
				tmpstatus.usedcnt = currentstatus.usedcnt + 1;
				tmpstatus.vUsed.assign(currentstatus.vUsed.begin(), currentstatus.vUsed.end());
				tmpstatus.vUsed[i] = nCurrentVertex;
				dqTmpPath.push_back(tmpstatus);
			}
		}

		return vHamiltonianPathList;
	}
};

int main()   // sample vAdjacencyMatrix is not yet implemented...
{
	std::vector<std::vector<bool>> vAdjacencyMatrix;

	std::vector<std::vector<int>> vHamiltonianPathList  = HamiltonianPath::getHamiltonianPath(vAdjacencyMatrix, 0);

	for (int k=0; k<vHamiltonianPathList.size(); k++)
	{
		for (int j=0; j<vHamiltonianPathList[k].size() - 1; j++)
			std::cout << std::to_string(vHamiltonianPathList[k][j]) + " -> ";

		std::cout << std::to_string(vHamiltonianPathList[k].back()) + "\n";
	}

	return 0;
}<commit_msg>add HamiltonianCycle finder and a sample graph<commit_after>/* HamiltonianPath.cpp
**
** finds Hamiltonian Path if it exists. returns as a list of vertices, which indicates the path from source to the final destination.
** takes AdjacencyMatrix as input.
**
** Note that all vertices number starts from 0 (inclusive), to match with the index numbers of arrays.
**
** worked find in original projects but not tested after extracted to here. (I must check...)
**
** All compiled and tested with g++ 6.2.0 MinGW-W64
**
** MIT License
** Copyright (c) 2017 636F57@GitHub
** See more detail at https://github.com/636F57/Algos/blob/master/LICENSE
*/

#include <cstdlib>
#include <vector>
#include <deque>
#include <iostream>

class HamiltonianPath
{
private:
	struct pathstatus
	{
		int end_vertex;          	// current vertex
		std::vector<int> vVisited;  // array to store the previous vertex of the time when it is visited, otherwise -1.
		int visitedcnt;             // number of visited vertecies
	};

public:
	HamiltonianPath(){}
	~HamiltonianPath(){}

	static std::vector<std::vector<int>> getHamiltonianPath(std::vector<std::vector<bool>>& vAdjacencyMatrix, int nStartVertex)
	{
		int nVertexNum = vAdjacencyMatrix.size();

		std::vector<std::vector<int>> vHamiltonianPathList;
		std::vector<int> vTmpHamiltonianPath(nVertexNum);
		std::vector<int> vVisited(nVertexNum, -1);

		vVisited[nStartVertex] = -2;       // previous vertex not available as starting vertex
		pathstatus tmpstatus, currentstatus;
		tmpstatus.end_vertex = nStartVertex;
		tmpstatus.visitedcnt = 1;
		tmpstatus.vVisited.assign(vVisited.begin(),vVisited.end());
		std::deque<pathstatus> dqTmpPath({tmpstatus});

		int i, j, nCurrentVertex;

		while (dqTmpPath.size() > 0)
		{
			currentstatus = dqTmpPath.front();
			dqTmpPath.pop_front();
			nCurrentVertex = currentstatus.end_vertex;

			if (currentstatus.visitedcnt == nVertexNum)  // Hamiltonian path found.
			{
				vTmpHamiltonianPath[nVertexNum-1] = nCurrentVertex;
				for (i=nVertexNum-2; i>=0; i--)
				{
					vTmpHamiltonianPath[i] = currentstatus.vVisited[vTmpHamiltonianPath[i+1]];
				}
				vHamiltonianPathList.push_back(vTmpHamiltonianPath);
				continue;
			}

			// go to the next vertex which is not visited yet
			for (i=0; i<nVertexNum; i++)
			{
				if (vAdjacencyMatrix[nCurrentVertex][i] == false)
					continue;

				if (currentstatus.vVisited[i] != -1)
					continue;

				tmpstatus.end_vertex = i;
				tmpstatus.visitedcnt = currentstatus.visitedcnt + 1;
				tmpstatus.vVisited.assign(currentstatus.vVisited.begin(), currentstatus.vVisited.end());
				tmpstatus.vVisited[i] = nCurrentVertex;
				dqTmpPath.push_back(tmpstatus);
			}
		}

		return vHamiltonianPathList;
	}

	static std::vector<std::vector<int>> getHamiltonianCycle(std::vector<std::vector<bool>>& vAdjacencyMatrix, int nStartVertex)
	{
		std::vector<std::vector<int>> vHamiltonianCycleList;
		std::vector<std::vector<int>> vHamiltonianPathList = getHamiltonianPath(vAdjacencyMatrix, 0);

		for (int i=0; i<vHamiltonianPathList.size(); i++)
		{
			if (vAdjacencyMatrix[nStartVertex][vHamiltonianPathList[i].back()] == true)
			{
				vHamiltonianPathList[i].push_back(nStartVertex);
				vHamiltonianCycleList.push_back(vHamiltonianPathList[i]);
			}
		}

		return vHamiltonianCycleList;
	}
};

int main()
{
	/* sample graph
	    /| \
	   / |  \
	  / / \  \
	 / /    \  \
	/ /      \  \
    ---       ---
	\ \      /  /
     \ \    /  /
      \  --   /
	   \/	\/
		-----
	*/
	std::vector<std::vector<bool>> vAdjacencyMatrix(10);
	vAdjacencyMatrix[0] = {0,1,0,0,1,1,0,0,0,0};
	vAdjacencyMatrix[1] = {1,0,1,0,0,0,1,0,0,0};
	vAdjacencyMatrix[2] = {0,1,0,1,0,0,0,1,0,0};
	vAdjacencyMatrix[3] = {0,0,1,0,1,0,0,0,1,0};
	vAdjacencyMatrix[4] = {1,0,0,1,0,0,0,0,0,1};
	vAdjacencyMatrix[5] = {1,0,0,0,0,0,1,0,0,1};
	vAdjacencyMatrix[6] = {0,1,0,0,0,1,0,1,0,0};
	vAdjacencyMatrix[7] = {0,0,1,0,0,0,1,0,1,0};
	vAdjacencyMatrix[8] = {0,0,0,1,0,0,0,1,0,1};
	vAdjacencyMatrix[9] = {0,0,0,0,1,1,0,0,1,0};

	std::vector<std::vector<int>> vHamiltonianPathList = HamiltonianPath::getHamiltonianPath(vAdjacencyMatrix, 0);

	std::cout << "Number of Hamiltonian paths : " << std::to_string(vHamiltonianPathList.size()) << "\n";
	for (int k=0; k<vHamiltonianPathList.size(); k++)
	{
		for (int j=0; j<vHamiltonianPathList[k].size() - 1; j++)
			std::cout << std::to_string(vHamiltonianPathList[k][j]) + " -> ";

		std::cout << std::to_string(vHamiltonianPathList[k].back()) + "\n";
	}

	std::vector<std::vector<int>> vHamiltonianCycleList = HamiltonianPath::getHamiltonianCycle(vAdjacencyMatrix, 0 );
	std::cout << "\nNumber of Hamiltonian cycles : " << std::to_string(vHamiltonianCycleList.size()) << "\n";
	for (int k=0; k<vHamiltonianCycleList.size(); k++)
	{
		for (int j=0; j<vHamiltonianCycleList[k].size() - 1; j++)
			std::cout << std::to_string(vHamiltonianCycleList[k][j]) + " -> ";

		std::cout << std::to_string(vHamiltonianCycleList[k].back()) + "\n";
	}

	return 0;
}<|endoftext|>


<commit_before>#include "sdb-antigenic-maps-draw.hh"

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

AntigenicMapsDrawBase::~AntigenicMapsDrawBase()
{
}

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

AntigenicMapsDrawBase* make_antigenic_maps_draw(std::string aChartFilename, Surface& aSurface, Tree& aTree, HzSections& aHzSections, SignaturePageDrawSettings& aSignaturePageDrawSettings, AntigenicMapsDrawSettings& aSettings)
{
    try {
        return new sdb::AntigenicMapsDraw(aSurface, aTree, sdb::read_chart_from_sdb(aChartFilename), aHzSections, aSignaturePageDrawSettings, aSettings);
    }
    catch (ChartReadError& err) {
        std::cerr << "Cannot read sdb chart" << std::endl;
        throw;
    }

} // make_antigenic_maps_draw

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>using ace chart development<commit_after>#include <typeinfo>

#include "acmacs-chart/ace.hh"
#include "sdb-antigenic-maps-draw.hh"

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

AntigenicMapsDrawBase::~AntigenicMapsDrawBase()
{
}

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

AntigenicMapsDrawBase* make_antigenic_maps_draw(std::string aChartFilename, Surface& aSurface, Tree& aTree, HzSections& aHzSections, SignaturePageDrawSettings& aSignaturePageDrawSettings, AntigenicMapsDrawSettings& aSettings)
{
    try {
        auto* chart = import_chart(aChartFilename);
    }
    catch (AceChartReadError& err) {
        std::cerr << "Cannot read ace chart: " << err.what() << std::endl;
        throw;
    }
    try {
        return new sdb::AntigenicMapsDraw(aSurface, aTree, sdb::read_chart_from_sdb(aChartFilename), aHzSections, aSignaturePageDrawSettings, aSettings);
    }
    catch (ChartReadError& err) {
        std::cerr << "Cannot read sdb chart" << std::endl;
        throw;
    }

} // make_antigenic_maps_draw

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before><commit_msg>update animation<commit_after><|endoftext|>


<commit_before>/**
 * \file
 * \author      Alexey Vasilyev <alexa.infra@gmail.com>
 * \copyright   MIT License
 **/
#include "sdlapp.h"

#ifdef OS_WIN
#  define SDL_MAIN_HANDLED
#endif

#include <SDL.h>

#include <iostream>
#include <string>
#include <assert.h>

#include "GL/glew.h"
#include "renderer/statistics.h"

SDLApp::SDLApp()
    : mainwindow_( NULL )
    , run_( true )
    , capture_( false )
    , width_( 640 )
    , height_( 480 )
{
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
    // see SDL_GLprofile enumeration
    // e.g. SDL_GL_CONTEXT_PROFILE_ES2 for GLES
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
    // debug flag
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 );
    SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 );

    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
        std::cout << "Unable to init SDL: " << SDL_GetError() << std::endl;
        assert( false );
    }

    mainwindow_ = SDL_CreateWindow(
                      "SDL Demo",
                      SDL_WINDOWPOS_CENTERED,
                      SDL_WINDOWPOS_CENTERED,
                      width_, height_,
                      SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
                  );
    maincontext_ = SDL_GL_CreateContext( mainwindow_ );
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();

    if ( GLEW_OK != err ) {
        std::cout << glewGetErrorString( err ) << std::endl;
        assert( false );
    }

    if ( !GLEW_VERSION_3_3 ) {
        std::cout << "OpenGL 3.3 is not supported." << std::endl;
        //    assert(false);
    }

    const GLubyte* version = glGetString( GL_VERSION );

    std::cout << "Current OpenGL version: " << version << std::endl;

    assert( glGetError() == GL_NO_ERROR );

    SDL_GL_SetSwapInterval( 1 );

    Stats::init();
}

SDLApp::~SDLApp()
{
    Stats::shutdown();
    SDL_GL_DeleteContext( maincontext_ );
    SDL_DestroyWindow( mainwindow_ );
    SDL_Quit();
}

void SDLApp::Pump()
{
    SDL_PumpEvents();
    SDL_Event event;

    while ( SDL_PollEvent( &event ) ) {
        switch( event.type ) {
        case SDL_QUIT:
            run_ = false;
            break;
        case SDL_MOUSEBUTTONUP:

            if ( event.button.button == SDL_BUTTON_LEFT ) {
                capture_ = false;
                SDL_ShowCursor( 1 );
            }

            break;
        case SDL_MOUSEBUTTONDOWN:

            if ( event.button.button == SDL_BUTTON_LEFT ) {
                capture_ = true;
                SDL_ShowCursor( 0 );
            }

            break;
        case SDL_MOUSEMOTION:

            if ( capture_ ) {
                if ( event.motion.x != width_ / 2. ||
                        event.motion.y != height_ / 2. ) {
                    OnMotion( event.motion.x,
                              event.motion.y,
                              event.motion.xrel,
                              event.motion.yrel );
                    SDL_WarpMouseInWindow( mainwindow_,
                                           width_ / 2, height_ / 2 );
                }
            }

            break;
        case SDL_KEYDOWN:
            OnKeyboardDown( ( u8 )event.key.keysym.sym );
            break;
        case SDL_KEYUP:
            OnKeyboardUp( ( u8 )event.key.keysym.sym );
            break;
        default:
            break;
        }
    }
}

void SDLApp::Run()
{
    Pump();

    while( run_ ) {
        OnFrame();
        Pump();
    }
}

void SDLApp::OnFrame()
{
    /* Swap our back buffer to the front */
    SDL_GL_SwapWindow( mainwindow_ );
    Stats::reset_frame();
}

void SDLApp::OnMotion( i32 x, i32 y, i32 dx, i32 dy )
{
}

void SDLApp::OnReshape( i32 width, i32 height )
{
}
<commit_msg>fix sdl initialization<commit_after>/**
 * \file
 * \author      Alexey Vasilyev <alexa.infra@gmail.com>
 * \copyright   MIT License
 **/
#include "sdlapp.h"

#ifdef OS_WIN
#  define SDL_MAIN_HANDLED
#endif

#include <SDL.h>

#include <iostream>
#include <string>
#include <assert.h>

#include "GL/glew.h"
#include "GL/wglew.h"
#include "renderer/statistics.h"

SDLApp::SDLApp()
    : mainwindow_( NULL )
    , run_( true )
    , capture_( false )
    , width_( 640 )
    , height_( 480 )
{
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
        std::cout << "Unable to init SDL: " << SDL_GetError() << std::endl;
        assert( false );
    }

    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
    // see SDL_GLprofile enumeration
    // e.g. SDL_GL_CONTEXT_PROFILE_ES2 for GLES
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
    // debug flag
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 );
    SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 );

    mainwindow_ = SDL_CreateWindow(
                      "SDL Demo",
                      SDL_WINDOWPOS_CENTERED,
                      SDL_WINDOWPOS_CENTERED,
                      width_, height_,
                      SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
                  );
    maincontext_ = SDL_GL_CreateContext( mainwindow_ );
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();

    if ( GLEW_OK != err ) {
        std::cout << glewGetErrorString( err ) << std::endl;
        assert( false );
    }

    if ( !GLEW_VERSION_3_3 ) {
        std::cout << "OpenGL 3.3 is not supported." << std::endl;
        //    assert(false);
    }

    const GLubyte* version = glGetString( GL_VERSION );

    std::cout << "Current OpenGL version: " << version << std::endl;

    assert( glGetError() == GL_NO_ERROR );

    SDL_GL_SetSwapInterval( 1 );

    Stats::init();
}

SDLApp::~SDLApp()
{
    Stats::shutdown();
    SDL_GL_DeleteContext( maincontext_ );
    SDL_DestroyWindow( mainwindow_ );
    SDL_Quit();
}

void SDLApp::Pump()
{
    SDL_PumpEvents();
    SDL_Event event;

    while ( SDL_PollEvent( &event ) ) {
        switch( event.type ) {
        case SDL_QUIT:
            run_ = false;
            break;
        case SDL_MOUSEBUTTONUP:

            if ( event.button.button == SDL_BUTTON_LEFT ) {
                capture_ = false;
                SDL_ShowCursor( 1 );
            }

            break;
        case SDL_MOUSEBUTTONDOWN:

            if ( event.button.button == SDL_BUTTON_LEFT ) {
                capture_ = true;
                SDL_ShowCursor( 0 );
            }

            break;
        case SDL_MOUSEMOTION:

            if ( capture_ ) {
                if ( event.motion.x != width_ / 2. ||
                        event.motion.y != height_ / 2. ) {
                    OnMotion( event.motion.x,
                              event.motion.y,
                              event.motion.xrel,
                              event.motion.yrel );
                    SDL_WarpMouseInWindow( mainwindow_,
                                           width_ / 2, height_ / 2 );
                }
            }

            break;
        case SDL_KEYDOWN:
            OnKeyboardDown( ( u8 )event.key.keysym.sym );
            break;
        case SDL_KEYUP:
            OnKeyboardUp( ( u8 )event.key.keysym.sym );
            break;
        default:
            break;
        }
    }
}

void SDLApp::Run()
{
    Pump();

    while( run_ ) {
        OnFrame();
        Pump();
    }
}

void SDLApp::OnFrame()
{
    /* Swap our back buffer to the front */
    SDL_GL_SwapWindow( mainwindow_ );
    Stats::reset_frame();
}

void SDLApp::OnMotion( i32 x, i32 y, i32 dx, i32 dy )
{
}

void SDLApp::OnReshape( i32 width, i32 height )
{
}
<|endoftext|>