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

// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_cache.hpp>
#include <mapnik/svg/marker_cache.hpp>

#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_scanline_u.h"

// stl
#include <string>

namespace mapnik {

struct rasterizer :  agg::rasterizer_scanline_aa<>, boost::noncopyable {};

template <typename T>
void agg_renderer<T>::process(point_symbolizer const& sym,
                              Feature const& feature,
                              proj_transform const& prj_trans)
{
    typedef coord_transform2<CoordTransform,geometry2d> path_type;
    typedef agg::pixfmt_rgba32 pixfmt;
    typedef agg::renderer_base<pixfmt> renderer_base;
    typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid;

    double x;
    double y;
    double z=0;

    std::string filename = path_processor_type::evaluate( *sym.get_filename(), feature);
    boost::optional<mapnik::image_ptr> data;

    if ( filename.empty() )
    {
        // default OGC 4x4 black square
        data = boost::optional<mapnik::image_ptr>(new image_data_32(4,4));
        (*data)->set(0xff000000);
    }
    else if (is_svg(filename))
    {
        // SVG
        boost::optional<path_ptr> marker;
        ras_ptr->reset();
        ras_ptr->gamma(agg::gamma_linear());
        agg::scanline_u8 sl;
        agg::rendering_buffer buf(pixmap_.raw_data(), width_, height_, width_ * 4);
        pixfmt pixf(buf);
        renderer_base renb(pixf);
        renderer_solid ren(renb);
        box2d<double> extent;

        marker = mapnik::marker_cache::instance()->find(filename, true);
        if (marker && *marker)
        {
            double x1, y1, x2, y2;
            (*marker)->bounding_rect(&x1, &y1, &x2, &y2);

            for (unsigned i=0; i<feature.num_geometries(); ++i)
            {
                geometry2d const& geom = feature.get_geometry(i);
                geom.label_position(&x,&y);
                prj_trans.backward(x,y,z);
                t_.forward(&x,&y);

                agg::trans_affine tr;
                boost::array<double,6> const& m = sym.get_transform();
                tr.load_from(&m[0]);

                tr *= agg::trans_affine_translation(x, y);

                tr.transform(&x1,&y1);
                tr.transform(&x2,&y2);

                //extent.init(x - 0.5*(x2-x1), y - 0.5*(y2-y1),
                //          x + 0.5*(x2-x1), y + 0.5*(y2-y1));

                extent.init(x1,y1,x2,y2);
                if (sym.get_allow_overlap() ||
                    detector_.has_placement(extent))
                {

                    (*marker)->render(*ras_ptr, sl, ren, tr, renb.clip_box(), sym.get_opacity());
                    detector_.insert(extent);
                }
            }
        }
    }
    else
    {
        data = mapnik::image_cache::instance()->find(filename,true);
        if ( data )
        {
            for (unsigned i=0;i<feature.num_geometries();++i)
            {
                geometry2d const& geom = feature.get_geometry(i);

                geom.label_position(&x,&y);
                prj_trans.backward(x,y,z);
                t_.forward(&x,&y);
                int w = (*data)->width();
                int h = (*data)->height();
                int px=int(floor(x - 0.5 * w));
                int py=int(floor(y - 0.5 * h));
                box2d<double> label_ext (floor(x - 0.5 * w),
                                         floor(y - 0.5 * h),
                                         ceil (x + 0.5 * w),
                                         ceil (y + 0.5 * h));
                if (sym.get_allow_overlap() ||
                    detector_.has_placement(label_ext))
                {
                    pixmap_.set_rectangle_alpha2(*(*data),px,py,sym.get_opacity());
                    detector_.insert(label_ext);
                }
            }
        }
    }
}

template void agg_renderer<image_32>::process(point_symbolizer const&,
                                              Feature const&,
                                              proj_transform const&);

}

<commit_msg>+ removed commented out lines<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_cache.hpp>
#include <mapnik/svg/marker_cache.hpp>

#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_scanline_u.h"

// stl
#include <string>

namespace mapnik {

struct rasterizer :  agg::rasterizer_scanline_aa<>, boost::noncopyable {};

template <typename T>
void agg_renderer<T>::process(point_symbolizer const& sym,
                              Feature const& feature,
                              proj_transform const& prj_trans)
{
    typedef coord_transform2<CoordTransform,geometry2d> path_type;
    typedef agg::pixfmt_rgba32 pixfmt;
    typedef agg::renderer_base<pixfmt> renderer_base;
    typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid;

    double x;
    double y;
    double z=0;

    std::string filename = path_processor_type::evaluate( *sym.get_filename(), feature);
    boost::optional<mapnik::image_ptr> data;

    if ( filename.empty() )
    {
        // default OGC 4x4 black square
        data = boost::optional<mapnik::image_ptr>(new image_data_32(4,4));
        (*data)->set(0xff000000);
    }
    else if (is_svg(filename))
    {
        // SVG
        boost::optional<path_ptr> marker;
        ras_ptr->reset();
        ras_ptr->gamma(agg::gamma_linear());
        agg::scanline_u8 sl;
        agg::rendering_buffer buf(pixmap_.raw_data(), width_, height_, width_ * 4);
        pixfmt pixf(buf);
        renderer_base renb(pixf);
        renderer_solid ren(renb);
        box2d<double> extent;

        marker = mapnik::marker_cache::instance()->find(filename, true);
        if (marker && *marker)
        {
            double x1, y1, x2, y2;
            (*marker)->bounding_rect(&x1, &y1, &x2, &y2);

            for (unsigned i=0; i<feature.num_geometries(); ++i)
            {
                geometry2d const& geom = feature.get_geometry(i);
                geom.label_position(&x,&y);
                prj_trans.backward(x,y,z);
                t_.forward(&x,&y);

                agg::trans_affine tr;
                boost::array<double,6> const& m = sym.get_transform();
                tr.load_from(&m[0]);

                tr *= agg::trans_affine_translation(x, y);

                tr.transform(&x1,&y1);
                tr.transform(&x2,&y2);

                extent.init(x1,y1,x2,y2);
                if (sym.get_allow_overlap() ||
                    detector_.has_placement(extent))
                {

                    (*marker)->render(*ras_ptr, sl, ren, tr, renb.clip_box(), sym.get_opacity());
                    detector_.insert(extent);
                }
            }
        }
    }
    else
    {
        data = mapnik::image_cache::instance()->find(filename,true);
        if ( data )
        {
            for (unsigned i=0;i<feature.num_geometries();++i)
            {
                geometry2d const& geom = feature.get_geometry(i);

                geom.label_position(&x,&y);
                prj_trans.backward(x,y,z);
                t_.forward(&x,&y);
                int w = (*data)->width();
                int h = (*data)->height();
                int px=int(floor(x - 0.5 * w));
                int py=int(floor(y - 0.5 * h));
                box2d<double> label_ext (floor(x - 0.5 * w),
                                         floor(y - 0.5 * h),
                                         ceil (x + 0.5 * w),
                                         ceil (y + 0.5 * h));
                if (sym.get_allow_overlap() ||
                    detector_.has_placement(label_ext))
                {
                    pixmap_.set_rectangle_alpha2(*(*data),px,py,sym.get_opacity());
                    detector_.insert(label_ext);
                }
            }
        }
    }
}

template void agg_renderer<image_32>::process(point_symbolizer const&,
                                              Feature const&,
                                              proj_transform const&);

}

<|endoftext|>


<commit_before><commit_msg>remove unreachable branch from NN parser<commit_after><|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QtCore>
#include <QtTest/QtTest>

class tst_Headers: public QObject
{
    Q_OBJECT
private slots:
    void initTestCase();

    void privateSlots_data() { allHeadersData(); }
    void privateSlots();

    void macros_data() { allHeadersData(); }
    void macros();

private:
    static QStringList getHeaders(const QString &path);

    void allHeadersData();
    QStringList headers;
    QString qtModuleDir;
};

QStringList tst_Headers::getHeaders(const QString &path)
{
    QStringList result;

    QProcess git;
    git.setWorkingDirectory(path);
    git.start("git", QStringList() << "ls-files");

    // Wait for git to start
    if (!git.waitForStarted())
        qFatal("Error running 'git': %s", qPrintable(git.errorString()));

    // Continue reading the data until EOF reached
    QByteArray data;
    while (git.waitForReadyRead(-1))
        data.append(git.readAll());

    // wait until the process has finished
    if ((git.state() != QProcess::NotRunning) && !git.waitForFinished(30000))
        qFatal("'git ls-files' did not complete within 30 seconds: %s", qPrintable(git.errorString()));

    // Check for the git's exit code
    if (0 != git.exitCode())
        qFatal("Error running 'git ls-files': %s", qPrintable(git.readAllStandardError()));

    // Create a QStringList of files out of the standard output
    QString string(data);
    QStringList entries = string.split( "\n" );

    // We just want to check header files
    entries = entries.filter(QRegExp("\\.h$"));
    entries = entries.filter(QRegExp("^(?!ui_)"));

    // Recreate the whole file path so we can open the file from disk
    foreach (QString entry, entries)
        result += path + "/" + entry;

    return result;
}

void tst_Headers::initTestCase()
{
    qtModuleDir = QString::fromLocal8Bit(qgetenv("QT_MODULE_TO_TEST"));
    if (qtModuleDir.isEmpty()) {
        QSKIP("$QT_MODULE_TO_TEST is unset - nothing to test.  Set QT_MODULE_TO_TEST to the path "
              "of a Qt module to test.");
    }

    if (!qtModuleDir.contains("phonon") && !qtModuleDir.contains("qttools")) {
        QDir dir(qtModuleDir + "/src");
        if (dir.exists())
            headers = getHeaders(dir.absolutePath());

        if (headers.isEmpty()) {
            QSKIP("It seems there are no headers in this module; this test is "
                  "not applicable");
        }
    } else {
        QWARN("Some test functions will be skipped, because we ignore them for phonon and qttools.");
    }
}

void tst_Headers::allHeadersData()
{
    QTest::addColumn<QString>("header");

    if (headers.isEmpty())
        QSKIP("can't find any headers in your $QT_MODULE_TO_TEST/src.");

    foreach (QString hdr, headers) {
        if (hdr.contains("/3rdparty/") || hdr.endsWith("/src/tools/uic/qclass_lib_map.h"))
            continue;

        QTest::newRow(qPrintable(hdr)) << hdr;
    }
}

void tst_Headers::privateSlots()
{
    QFETCH(QString, header);

    if (header.endsWith("/qobjectdefs.h"))
        return;

    QFile f(header);
    QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));

    QStringList content = QString::fromLocal8Bit(f.readAll()).split("\n");
    foreach (QString line, content) {
        if (line.contains("Q_PRIVATE_SLOT("))
            QVERIFY(line.contains("_q_"));
    }
}

void tst_Headers::macros()
{
    QFETCH(QString, header);

    if (header.endsWith("_p.h") || header.endsWith("_pch.h")
        || header.contains("global/qconfig-") || header.endsWith("/qconfig.h")
        || header.contains("/src/tools/") || header.contains("/src/plugins/")
        || header.contains("/src/imports/")
        || header.contains("/src/uitools/")
        || header.endsWith("/qiconset.h") || header.endsWith("/qfeatures.h")
        || header.endsWith("qt_windows.h"))
        return;

    QFile f(header);
    QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));

    QByteArray data = f.readAll();
    QStringList content = QString::fromLocal8Bit(data.replace('\r', "")).split("\n");

    int beginHeader = content.indexOf("QT_BEGIN_HEADER");
    int endHeader = content.lastIndexOf("QT_END_HEADER");

    QVERIFY(beginHeader >= 0);
    QVERIFY(endHeader >= 0);
    QVERIFY(beginHeader < endHeader);

    QVERIFY(content.indexOf(QRegExp("\\bslots\\s*:")) == -1);
    QVERIFY(content.indexOf(QRegExp("\\bsignals\\s*:")) == -1);

    if (header.contains("/sql/drivers/") || header.contains("/arch/qatomic")
        || header.endsWith("qglobal.h")
        || header.endsWith("qwindowdefs_win.h"))
        return;

    int qtmodule = content.indexOf(QRegExp("^QT_MODULE\\(.*\\)$"));
    QVERIFY(qtmodule != -1);
    QVERIFY(qtmodule > beginHeader);
    QVERIFY(qtmodule < endHeader);

    int beginNamespace = content.indexOf("QT_BEGIN_NAMESPACE");
    int endNamespace = content.lastIndexOf("QT_END_NAMESPACE");
    QVERIFY(beginNamespace != -1);
    QVERIFY(endNamespace != -1);
    QVERIFY(beginHeader < beginNamespace);
    QVERIFY(beginNamespace < endNamespace);
    QVERIFY(endNamespace < endHeader);
}

QTEST_MAIN(tst_Headers)
#include "tst_headers.moc"
<commit_msg>tst_headers: Improve signal and slots validation<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QtCore>
#include <QtTest/QtTest>

class tst_Headers: public QObject
{
    Q_OBJECT
private slots:
    void initTestCase();

    void privateSlots_data() { allHeadersData(); }
    void privateSlots();

    void macros_data() { allHeadersData(); }
    void macros();

private:
    static QStringList getHeaders(const QString &path);

    void allHeadersData();
    QStringList headers;
    QString qtModuleDir;
};

QStringList tst_Headers::getHeaders(const QString &path)
{
    QStringList result;

    QProcess git;
    git.setWorkingDirectory(path);
    git.start("git", QStringList() << "ls-files");

    // Wait for git to start
    if (!git.waitForStarted())
        qFatal("Error running 'git': %s", qPrintable(git.errorString()));

    // Continue reading the data until EOF reached
    QByteArray data;
    while (git.waitForReadyRead(-1))
        data.append(git.readAll());

    // wait until the process has finished
    if ((git.state() != QProcess::NotRunning) && !git.waitForFinished(30000))
        qFatal("'git ls-files' did not complete within 30 seconds: %s", qPrintable(git.errorString()));

    // Check for the git's exit code
    if (0 != git.exitCode())
        qFatal("Error running 'git ls-files': %s", qPrintable(git.readAllStandardError()));

    // Create a QStringList of files out of the standard output
    QString string(data);
    QStringList entries = string.split( "\n" );

    // We just want to check header files
    entries = entries.filter(QRegExp("\\.h$"));
    entries = entries.filter(QRegExp("^(?!ui_)"));

    // Recreate the whole file path so we can open the file from disk
    foreach (QString entry, entries)
        result += path + "/" + entry;

    return result;
}

void tst_Headers::initTestCase()
{
    qtModuleDir = QString::fromLocal8Bit(qgetenv("QT_MODULE_TO_TEST"));
    if (qtModuleDir.isEmpty()) {
        QSKIP("$QT_MODULE_TO_TEST is unset - nothing to test.  Set QT_MODULE_TO_TEST to the path "
              "of a Qt module to test.");
    }

    if (!qtModuleDir.contains("phonon") && !qtModuleDir.contains("qttools")) {
        QDir dir(qtModuleDir + "/src");
        if (dir.exists())
            headers = getHeaders(dir.absolutePath());

        if (headers.isEmpty()) {
            QSKIP("It seems there are no headers in this module; this test is "
                  "not applicable");
        }
    } else {
        QWARN("Some test functions will be skipped, because we ignore them for phonon and qttools.");
    }
}

void tst_Headers::allHeadersData()
{
    QTest::addColumn<QString>("header");

    if (headers.isEmpty())
        QSKIP("can't find any headers in your $QT_MODULE_TO_TEST/src.");

    foreach (QString hdr, headers) {
        if (hdr.contains("/3rdparty/") || hdr.endsWith("/src/tools/uic/qclass_lib_map.h"))
            continue;

        QTest::newRow(qPrintable(hdr)) << hdr;
    }
}

void tst_Headers::privateSlots()
{
    QFETCH(QString, header);

    if (header.endsWith("/qobjectdefs.h"))
        return;

    QFile f(header);
    QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));

    QStringList content = QString::fromLocal8Bit(f.readAll()).split("\n");
    foreach (QString line, content) {
        if (line.contains("Q_PRIVATE_SLOT("))
            QVERIFY(line.contains("_q_"));
    }
}

void tst_Headers::macros()
{
    QFETCH(QString, header);

    if (header.endsWith("_p.h") || header.endsWith("_pch.h")
        || header.contains("global/qconfig-") || header.endsWith("/qconfig.h")
        || header.contains("/src/tools/") || header.contains("/src/plugins/")
        || header.contains("/src/imports/")
        || header.contains("/src/uitools/")
        || header.endsWith("/qiconset.h") || header.endsWith("/qfeatures.h")
        || header.endsWith("qt_windows.h"))
        return;

    QFile f(header);
    QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));

    QByteArray data = f.readAll();
    QStringList content = QString::fromLocal8Bit(data.replace('\r', "")).split("\n");

    int beginHeader = content.indexOf("QT_BEGIN_HEADER");
    int endHeader = content.lastIndexOf("QT_END_HEADER");

    QVERIFY(beginHeader >= 0);
    QVERIFY(endHeader >= 0);
    QVERIFY(beginHeader < endHeader);

    // "signals" and "slots" should be banned in public headers
    // headers which use signals/slots wouldn't compile if Qt is configured with QT_NO_KEYWORDS
    QVERIFY2(content.indexOf(QRegExp("\\bslots\\s*:")) == -1, "Header contains `slots' - use `Q_SLOTS' instead!");
    QVERIFY2(content.indexOf(QRegExp("\\bsignals\\s*:")) == -1, "Header contains `signals' - use `Q_SIGNALS' instead!");

    if (header.contains("/sql/drivers/") || header.contains("/arch/qatomic")
        || header.endsWith("qglobal.h")
        || header.endsWith("qwindowdefs_win.h"))
        return;

    int qtmodule = content.indexOf(QRegExp("^QT_MODULE\\(.*\\)$"));
    QVERIFY(qtmodule != -1);
    QVERIFY(qtmodule > beginHeader);
    QVERIFY(qtmodule < endHeader);

    int beginNamespace = content.indexOf("QT_BEGIN_NAMESPACE");
    int endNamespace = content.lastIndexOf("QT_END_NAMESPACE");
    QVERIFY(beginNamespace != -1);
    QVERIFY(endNamespace != -1);
    QVERIFY(beginHeader < beginNamespace);
    QVERIFY(beginNamespace < endNamespace);
    QVERIFY(endNamespace < endHeader);
}

QTEST_MAIN(tst_Headers)
#include "tst_headers.moc"
<|endoftext|>


<commit_before>#include "../kontsevich_graph_series.hpp"
#include "../kontsevich_graph_operator.hpp"
#include "../util/partitions.hpp"
#include "../util/factorial.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <limits>
using namespace std;
using namespace GiNaC;

size_t order = 4;

int main()
{
    map< size_t, set<KontsevichGraph> > relevants;
    map<KontsevichGraph, ex> weights;
    cout << "Reading in known graphs and their weights...";
    ifstream weights_file("data/known_weights.txt");
    weights_file.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore first line with column headers
    KontsevichGraph graph;
    int numerator, denominator;
    char slash;
    while (weights_file >> graph >> numerator >> slash >> denominator)
    {
        ex weight = numerator/(ex)denominator;
        weights[graph] = weight;
        relevants[graph.internal()].insert(graph);
    }
    cout << " done." << endl;
    cout << "Listing relevant graphs (prime, positive differential order, nonzero, modulo mirror images) at order " << order << "...";
    cout.flush();
    relevants[order] = KontsevichGraph::graphs(order, 2, true, true,
                    [](KontsevichGraph g) -> bool
                    {
                        return g.positive_differential_order() && g.is_prime() && !g.is_zero();
                    });
    cout << " done." << endl;
    cout << "Making a table of primes and weights...";
    map< size_t, vector<KontsevichGraph> > primes;
    size_t weight_count = 0;
    for (size_t n = 1; n <= order; ++n)
    {
        primes[n].reserve(2*relevants[n].size());
        for (KontsevichGraph g : relevants[n])
        {
            if (n == order)
                weights[g] = symbol("w_" + to_string(weight_count++));
            primes[n].push_back(g);
            KontsevichGraph mirror = g.mirror_image();
            if (g.abs() != mirror.abs())
            {
                weights[mirror] = weights[g];
                if (n % 2 == 1)
                    weights[mirror] *= -1;
                primes[n].push_back(mirror);
            }
        }
    }
    cout << " done." << endl;
    cout << "Constructing star product at order";
    KontsevichGraphSeries<ex> star_product;
    star_product[0] = KontsevichGraphSum<ex> { { 1, KontsevichGraph(0, 2, {}) } };
    for (size_t n = 1; n <= order; ++n)
    {
        cout << " " << n << ",";
        cout.flush();
        ex major_coeff = 1/(ex)factorial(n);
        Partitions partitions(n);
        for (auto partition = partitions.begin(); partition != partitions.end(); ++partition)
        {
            // count multiplicities of parts
            std::map<size_t, std::vector<size_t> > multiplicity;
            for (size_t i = 0; i != (*partition).size(); ++i)
                multiplicity[(*partition)[i]].push_back(i);
            // ignore multiplicity 1
            for (auto part : *partition)
                if (multiplicity[part].size() == 1)
                    multiplicity.erase(part);

            std::vector<size_t> prime_sizes((*partition).size());
            for (size_t i = 0; i != (*partition).size(); ++i)
                prime_sizes[i] = primes[(*partition)[i]].size();
            CartesianProduct decompositions(prime_sizes);
            for (auto decomposition = decompositions.begin(); decomposition != decompositions.end(); ++decomposition)
            {
                bool accept = true;
                for (auto& part : multiplicity)
                {
                    size_t prev = 0;
                    for (auto& idx : part.second) // when drawing from multiple equal sets
                    {
                        size_t current = (*decomposition)[idx];
                        if (current < prev) // accept only non-decreasing indices, to avoid duplicates
                            accept = false;
                        prev = current;
                    }
                }
                if (!accept)
                    continue;

                KontsevichGraph composite(0, 2, {});
                ex coeff = major_coeff;
                for (size_t i = 0; i != (*partition).size(); ++i)
                {
                    composite *= primes[(*partition)[i]][(*decomposition)[i]];
                    coeff *= weights[primes[(*partition)[i]][(*decomposition)[i]]];
                }
                coeff *= composite.multiplicity();
                star_product[n] += KontsevichGraphSum<ex>({ { coeff, composite} });
            }
        }
        // TODO: n is not yet considered a partition of n, so treat it separately for now:
        for (KontsevichGraph prime : primes[n])
        {
            star_product[n] += KontsevichGraphSum<ex>({ { major_coeff * weights[prime] * prime.multiplicity(), prime } });
        }
    }
    cout << " done:" << endl;
    cout << star_product << "\n";
    cout << "Number of terms in star product:\n";
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ": " << star_product[n].size() << " total\n";
        for (std::vector<size_t> indegrees : star_product[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << star_product[n][indegrees].size() << "\n";
        }
    }
    cout << "Computing associator...";
    cout.flush();
    KontsevichGraphSeries<ex> arg = { { 0, { { 1, KontsevichGraph(0, 1, {}) } }} };
    KontsevichGraphSeries<ex> assoc = star_product({ star_product, arg }) - star_product({ arg, star_product });
    cout << endl;
    cout << "Reducing associator...";
    cout.flush();
    assoc.reduce();
    cout << endl;
    cout << "Number of terms in associator:\n";
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ":\n";
        cout << assoc[n].size() << " total\n";
        for (std::vector<size_t> indegrees : assoc[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << assoc[n][indegrees].size() << "\n";
            symbol x("x");
            symbol y("y");
            symbol z("z");
            ex h = 1/4 * pow(x,5)*pow(y,3)*pow(z,4) + pow(y,5)*z*x + pow(z,5)*pow(x,2);
            std::vector<symbol> coords { x, y, z };
            PoissonStructure poisson { coords, { {0, h.diff(z), -h.diff(y)}, {-h.diff(z), 0, h.diff(x) }, { h.diff(y), -h.diff(x), 0 } } };
            cout << evaluate(assoc[n][indegrees], poisson, { pow(x,3)*z*pow(y,2), pow(y,3) + y*pow(x,10), pow(z,4) * y * pow(x,2) }) << "\n";
        }
    }
}
<commit_msg>Print the coefficients of the multivariate polynomial that is the associator (for a star product with variable coefficients at order 4).<commit_after>#include "../kontsevich_graph_series.hpp"
#include "../kontsevich_graph_operator.hpp"
#include "../util/partitions.hpp"
#include "../util/factorial.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <limits>
using namespace std;
using namespace GiNaC;

size_t order = 4;

int main()
{
    map< size_t, set<KontsevichGraph> > relevants;
    map<KontsevichGraph, ex> weights;
    cout << "Reading in known graphs and their weights...";
    ifstream weights_file("data/known_weights.txt");
    weights_file.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore first line with column headers
    KontsevichGraph graph;
    int numerator, denominator;
    char slash;
    while (weights_file >> graph >> numerator >> slash >> denominator)
    {
        ex weight = numerator/(ex)denominator;
        weights[graph] = weight;
        relevants[graph.internal()].insert(graph);
    }
    cout << " done." << endl;
    cout << "Listing relevant graphs (prime, positive differential order, nonzero, modulo mirror images) at order " << order << "...";
    cout.flush();
    relevants[order] = KontsevichGraph::graphs(order, 2, true, true,
                    [](KontsevichGraph g) -> bool
                    {
                        return g.positive_differential_order() && g.is_prime() && !g.is_zero();
                    });
    cout << " done." << endl;
    cout << "Making a table of primes and weights...";
    map< size_t, vector<KontsevichGraph> > primes;
    size_t weight_count = 0;
    for (size_t n = 1; n <= order; ++n)
    {
        primes[n].reserve(2*relevants[n].size());
        for (KontsevichGraph g : relevants[n])
        {
            if (n == order)
                weights[g] = symbol("w_" + to_string(weight_count++));
            primes[n].push_back(g);
            KontsevichGraph mirror = g.mirror_image();
            if (g.abs() != mirror.abs())
            {
                weights[mirror] = weights[g];
                if (n % 2 == 1)
                    weights[mirror] *= -1;
                primes[n].push_back(mirror);
            }
        }
    }
    cout << " done." << endl;
    cout << "Constructing star product at order";
    KontsevichGraphSeries<ex> star_product;
    star_product[0] = KontsevichGraphSum<ex> { { 1, KontsevichGraph(0, 2, {}) } };
    for (size_t n = 1; n <= order; ++n)
    {
        cout << " " << n << ",";
        cout.flush();
        ex major_coeff = 1/(ex)factorial(n);
        Partitions partitions(n);
        for (auto partition = partitions.begin(); partition != partitions.end(); ++partition)
        {
            // count multiplicities of parts
            std::map<size_t, std::vector<size_t> > multiplicity;
            for (size_t i = 0; i != (*partition).size(); ++i)
                multiplicity[(*partition)[i]].push_back(i);
            // ignore multiplicity 1
            for (auto part : *partition)
                if (multiplicity[part].size() == 1)
                    multiplicity.erase(part);

            std::vector<size_t> prime_sizes((*partition).size());
            for (size_t i = 0; i != (*partition).size(); ++i)
                prime_sizes[i] = primes[(*partition)[i]].size();
            CartesianProduct decompositions(prime_sizes);
            for (auto decomposition = decompositions.begin(); decomposition != decompositions.end(); ++decomposition)
            {
                bool accept = true;
                for (auto& part : multiplicity)
                {
                    size_t prev = 0;
                    for (auto& idx : part.second) // when drawing from multiple equal sets
                    {
                        size_t current = (*decomposition)[idx];
                        if (current < prev) // accept only non-decreasing indices, to avoid duplicates
                            accept = false;
                        prev = current;
                    }
                }
                if (!accept)
                    continue;

                KontsevichGraph composite(0, 2, {});
                ex coeff = major_coeff;
                for (size_t i = 0; i != (*partition).size(); ++i)
                {
                    composite *= primes[(*partition)[i]][(*decomposition)[i]];
                    coeff *= weights[primes[(*partition)[i]][(*decomposition)[i]]];
                }
                coeff *= composite.multiplicity();
                star_product[n] += KontsevichGraphSum<ex>({ { coeff, composite} });
            }
        }
        // TODO: n is not yet considered a partition of n, so treat it separately for now:
        for (KontsevichGraph prime : primes[n])
        {
            star_product[n] += KontsevichGraphSum<ex>({ { major_coeff * weights[prime] * prime.multiplicity(), prime } });
        }
    }
    cout << " done:" << endl;
    cout << star_product << "\n";
    cout << "Number of terms in star product:\n";
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ": " << star_product[n].size() << " total\n";
        for (std::vector<size_t> indegrees : star_product[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << star_product[n][indegrees].size() << "\n";
        }
    }
    cout << "Computing associator...";
    cout.flush();
    KontsevichGraphSeries<ex> arg = { { 0, { { 1, KontsevichGraph(0, 1, {}) } }} };
    KontsevichGraphSeries<ex> assoc = star_product({ star_product, arg }) - star_product({ arg, star_product });
    cout << endl;
    cout << "Reducing associator...";
    cout.flush();
    assoc.reduce();
    cout << endl;
    cout << "Number of terms in associator:\n";
    for (size_t n = 0; n <= order; ++n)
    {
        cout << "h^" << n << ":\n";
        cout << assoc[n].size() << " total\n";
        for (std::vector<size_t> indegrees : assoc[n].in_degrees())
        {
            for (size_t j = 0; j != indegrees.size(); ++j)
                cout << indegrees[j] << " ";
            cout << ": " << assoc[n][indegrees].size() << "\n";
            symbol x("x");
            symbol y("y");
            symbol z("z");
            ex h = 1/4 * pow(x,5)*pow(y,3)*pow(z,4) + pow(y,5)*z*x + pow(z,5)*pow(x,2);
            std::vector<symbol> coords { x, y, z };
            PoissonStructure poisson { coords, { {0, h.diff(z), -h.diff(y)}, {-h.diff(z), 0, h.diff(x) }, { h.diff(y), -h.diff(x), 0 } } };
            ex result = evaluate(assoc[n][indegrees], poisson, { pow(x,3)*z*pow(y,2), pow(y,3) + y*pow(x,10), pow(z,4) * y * pow(x,2) }).expand();
            for (int i = 0; i <= result.degree(x); ++i)
            {
                ex result2 = result.coeff(x, i).expand();
                for (int j = 0; j <= result2.degree(y); ++j)
                {
                    ex result3 = result2.coeff(y, j).expand();
                    for (int k = 0; k <= result3.degree(z); ++k)
                    {
                        ex result4 = result3.coeff(z, k).expand();
                        if (result4 != 0)
                            cout << result4 << " == 0\n";
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>/************************************************************************
*
* Copyright (C) 2017 by Peter Harrison. www.micromouseonline.com
*
* 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 l> imitation 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.
*
************************************************************************/

#include "gtest/gtest.h"

#include "maze.h"
#include "mazedata.h"
#include "mazeprinter.h"

class TestMazePrinter : public ::testing::Test {
protected:
  Maze *maze;

  virtual void SetUp() {
    maze = new Maze(16);
    maze->resetToEmptyMaze();

  }

  virtual void TearDown() {
    delete maze;
  }

  virtual void copyClassicMaze(const uint8_t *mazeData) const {
    for (int cell = 0; cell < this->maze->numCells(); ++cell) {
      maze->copyCellFromFileData(cell, mazeData[cell]);
    }
  }
};

/*
 * It is not clear how best to test the results of the libMaze printing
 * except by visual inspection.
 */
TEST_F(TestMazePrinter, PrintForCoverageTesting) {
  //  return;
  //  MazePrinter::printVisitedDirs(libMaze);
  copyClassicMaze(japan2007ef);

  maze->flood(maze->goal());
  MazePrinter::printDirs(maze);
  MazePrinter::printPlain(maze);
  MazePrinter::printCDecl(maze, "julian");
  MazePrinter::printCosts(maze);
  MazePrinter::printVisitedDirs(maze);
}

<commit_msg>disable mazeprinter tests for clarity<commit_after>/************************************************************************
*
* Copyright (C) 2017 by Peter Harrison. www.micromouseonline.com
*
* 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 l> imitation 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.
*
************************************************************************/

#include "gtest/gtest.h"

#include "maze.h"
#include "mazedata.h"
#include "mazeprinter.h"

class TestMazePrinter : public ::testing::Test {
protected:
  Maze *maze;

  virtual void SetUp() {
    maze = new Maze(16);
    maze->resetToEmptyMaze();
  }

  virtual void TearDown() {
    delete maze;
  }

  virtual void copyClassicMaze(const uint8_t *mazeData) const {
    for (int cell = 0; cell < this->maze->numCells(); ++cell) {
      maze->copyCellFromFileData(cell, mazeData[cell]);
    }
  }
};

/*
 * It is not clear how best to test the results of the libMaze printing
 * except by visual inspection.
 */
TEST_F(TestMazePrinter, PrintForCoverageTesting) {
  //  return;
  //  MazePrinter::printVisitedDirs(libMaze);
  copyClassicMaze(japan2007ef);

  maze->flood(maze->goal());
  //  MazePrinter::printDirs(maze);
  //  MazePrinter::printPlain(maze);
  //  MazePrinter::printCDecl(maze, "julian");
  //  MazePrinter::printCosts(maze);
  //  MazePrinter::printVisitedDirs(maze);
}

<|endoftext|>


<commit_before>// Mike Zrimsek
// Computer Graphics
// Homework 2

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <GL/glut.h>

static int WINDOW_WIDTH = 500;
static int WINDOW_HEIGHT = 500;
static double DEGREE_TO_RADIAN = 3.14159/180;

int mainMenuId;
int mainMenuSelection = 0;

static int SQUARE_MENU_SELECTION = 1;
static int CIRCLE_MENU_SELECTION = 2;
static int RUBBERBANDING_CIRCLE_MENU_SELECTION = 3;

int square_x, square_y;
double square_size = 20.0;

double circle_x = 50, circle_y = 50;
double circle_radius = 50;
int circle_change = 7;

double rubber_circle_tracking = 0;
double rubber_circle_start_x, rubber_circle_start_y;
double rubber_circle_end_x, rubber_circle_end_y;

void mainMenu(int value)
{
  mainMenuSelection = value;
  glutPostRedisplay();
}

void createMainMenu()
{
  mainMenuId = glutCreateMenu(mainMenu);
  glutAddMenuEntry("Square", SQUARE_MENU_SELECTION);
  glutAddMenuEntry("Circle", CIRCLE_MENU_SELECTION);
  glutAddMenuEntry("Rubberbanding Circle", RUBBERBANDING_CIRCLE_MENU_SELECTION);
  glutAttachMenu(GLUT_RIGHT_BUTTON);
}

void startMotion(int x, int y)
{
  rubber_circle_tracking = 1;

  rubber_circle_start_x = x;
  rubber_circle_start_y = y;

  rubber_circle_end_x = x;
  rubber_circle_end_y = y;
}

void stopMotion(int x, int y)
{
  rubber_circle_tracking = 0;

  rubber_circle_end_x = x;
  rubber_circle_end_y = y;
}

void mouseCallback(int btn, int state, int x, int y)
{
  if (btn == GLUT_LEFT_BUTTON)
	{
    if (state == GLUT_DOWN) startMotion(x, y);
		if (state == GLUT_UP) stopMotion(x, y);
	}
  glutPostRedisplay();
}

void trackSquareLocation(int x, int y)
{
  square_x = x;
  square_y = WINDOW_HEIGHT - y;
}

void mouseMotionCallback(int x, int y)
{
  if(mainMenuSelection == SQUARE_MENU_SELECTION)
  {
    trackSquareLocation(x, y);
    glColor3f(1.0, 0.0, 0.0);
  }
  if(mainMenuSelection == RUBBERBANDING_CIRCLE_MENU_SELECTION)
  {
    if(rubber_circle_tracking)
    {
      rubber_circle_end_x = x;
      rubber_circle_end_y = WINDOW_HEIGHT - y;
    }
  }
  glutPostRedisplay();
}

void mousePassiveMotionCallback(int x, int y)
{
  if(mainMenuSelection == SQUARE_MENU_SELECTION)
  {
    trackSquareLocation(x, y);
    glColor3f(1.0, 1.0, 0.0);
  }
  glutPostRedisplay();
}

void keyboardCallback(unsigned char key, int x, int y)
{
  switch(key)
  {
    case 27:
      exit(0);
  }
  glutPostRedisplay();
}

void idleCallback()
{
  if(mainMenuSelection == CIRCLE_MENU_SELECTION)
  {
    if(circle_x > WINDOW_WIDTH - circle_radius || circle_y > WINDOW_HEIGHT - circle_radius
    || circle_x < circle_radius || circle_y < circle_radius)
    {
      circle_change *= -1;
    }
    circle_x += circle_change;
    circle_y += circle_change;
  }
  glutPostRedisplay();
}

void drawSquare(int x, int y)
{
  glTranslatef(x, y, 0.0);
  glBegin(GL_POLYGON);
    glVertex2f(square_size, square_size);
    glVertex2f(-square_size, square_size);
    glVertex2f(-square_size, -square_size);
    glVertex2f(+square_size, -square_size);
  glEnd();
}

void drawCircle(double x, double y, double radius)
{
  glBegin(GL_LINE_LOOP);
    for(double i = 0; i < 360; i++)
    {
      double degreeInRadian = i*DEGREE_TO_RADIAN;
      glVertex2f(x+cos(degreeInRadian)*radius, y+sin(degreeInRadian)*radius);
    }
  glEnd();
}

void drawRubberCircle(double x, double y, double radius)
{
  glLineStipple(1, 0xF00F);
	glEnable(GL_LINE_STIPPLE);
	glLineWidth(1.0);
  drawCircle(x, y, radius);
}

void reshapeCallback(int width, int height)
{
	WINDOW_WIDTH = width;
	WINDOW_HEIGHT = height;
}

void displayCallback()
{
  glClearColor(0.0, 0.0, 0.0, 1.0);
	glClear(GL_COLOR_BUFFER_BIT);
  glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

  if(mainMenuSelection == SQUARE_MENU_SELECTION)
  {
    drawSquare(square_x, square_y);
  }
  else if(mainMenuSelection == CIRCLE_MENU_SELECTION)
  {
    glColor3f(0.0, 0.0, 1.0);
    drawCircle(circle_x, circle_y, circle_radius);
  }
  else if(mainMenuSelection == RUBBERBANDING_CIRCLE_MENU_SELECTION)
  {
    double rubber_circle_radius = rubber_circle_end_x - rubber_circle_start_x;
    glColor3f(0.0, 1.0, 0.0);
    if(rubber_circle_tracking)
    {
      drawRubberCircle(rubber_circle_start_x, rubber_circle_start_y, rubber_circle_radius);
    }
    drawCircle(rubber_circle_start_x, rubber_circle_start_y, rubber_circle_radius);
  }
  glutSwapBuffers();
}

int main(int argc, char** argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
  glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
  glutInitWindowPosition(0, 0);
  glutCreateWindow("Homework 2");

  glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0.0, WINDOW_WIDTH, 0.0, WINDOW_HEIGHT, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);

  glClearColor(0.0, 0.0, 0.0, 0.0);
  glClear(GL_COLOR_BUFFER_BIT);
  glutSwapBuffers();

  createMainMenu();
  glutMouseFunc(mouseCallback);
  glutKeyboardFunc(keyboardCallback);
  glutMotionFunc(mouseMotionCallback);
  glutPassiveMotionFunc(mousePassiveMotionCallback);
  glutIdleFunc(idleCallback);
  glutDisplayFunc(displayCallback);
  glutReshapeFunc(reshapeCallback);

  glutMainLoop();
  return 0;
}
<commit_msg>fixed not having dot in middle of rubber circle and fixed offset bug<commit_after>// Mike Zrimsek
// Computer Graphics
// Homework 2

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <GL/glut.h>

static int WINDOW_WIDTH = 500;
static int WINDOW_HEIGHT = 500;
static double DEGREE_TO_RADIAN = 3.14159/180;

int mainMenuId;
int mainMenuSelection = 0;

static int SQUARE_MENU_SELECTION = 1;
static int CIRCLE_MENU_SELECTION = 2;
static int RUBBERBANDING_CIRCLE_MENU_SELECTION = 3;

int square_x, square_y;
double square_size = 20.0;

double circle_x = 50, circle_y = 50;
double circle_radius = 50;
int circle_change = 7;

double rubber_circle_tracking = 0;
double rubber_circle_start_x, rubber_circle_start_y;
double rubber_circle_end_x, rubber_circle_end_y;

void mainMenu(int value)
{
  mainMenuSelection = value;
  glutPostRedisplay();
}

void createMainMenu()
{
  mainMenuId = glutCreateMenu(mainMenu);
  glutAddMenuEntry("Square", SQUARE_MENU_SELECTION);
  glutAddMenuEntry("Circle", CIRCLE_MENU_SELECTION);
  glutAddMenuEntry("Rubberbanding Circle", RUBBERBANDING_CIRCLE_MENU_SELECTION);
  glutAttachMenu(GLUT_RIGHT_BUTTON);
}

void startMotion(int x, int y)
{
  rubber_circle_tracking = 1;

  rubber_circle_start_x = x;
  rubber_circle_start_y = WINDOW_HEIGHT - y;

  rubber_circle_end_x = x;
  rubber_circle_end_y = WINDOW_HEIGHT - y;
}

void stopMotion(int x, int y)
{
  rubber_circle_tracking = 0;

  rubber_circle_end_x = x;
  rubber_circle_end_y = WINDOW_HEIGHT - y;
}

void mouseCallback(int btn, int state, int x, int y)
{
  if (btn == GLUT_LEFT_BUTTON)
	{
    if (state == GLUT_DOWN) startMotion(x, y);
		if (state == GLUT_UP) stopMotion(x, y);
	}
  glutPostRedisplay();
}

void trackSquareLocation(int x, int y)
{
  square_x = x;
  square_y = WINDOW_HEIGHT - y;
}

void mouseMotionCallback(int x, int y)
{
  if(mainMenuSelection == SQUARE_MENU_SELECTION)
  {
    trackSquareLocation(x, y);
    glColor3f(1.0, 0.0, 0.0);
  }
  if(mainMenuSelection == RUBBERBANDING_CIRCLE_MENU_SELECTION)
  {
    if(rubber_circle_tracking)
    {
      rubber_circle_end_x = x;
      rubber_circle_end_y = WINDOW_HEIGHT - y;
    }
  }
  glutPostRedisplay();
}

void mousePassiveMotionCallback(int x, int y)
{
  if(mainMenuSelection == SQUARE_MENU_SELECTION)
  {
    trackSquareLocation(x, y);
    glColor3f(1.0, 1.0, 0.0);
  }
  glutPostRedisplay();
}

void keyboardCallback(unsigned char key, int x, int y)
{
  switch(key)
  {
    case 27:
      exit(0);
  }
  glutPostRedisplay();
}

void idleCallback()
{
  if(mainMenuSelection == CIRCLE_MENU_SELECTION)
  {
    if(circle_x > WINDOW_WIDTH - circle_radius || circle_y > WINDOW_HEIGHT - circle_radius
    || circle_x < circle_radius || circle_y < circle_radius)
    {
      circle_change *= -1;
    }
    circle_x += circle_change;
    circle_y += circle_change;
  }
  glutPostRedisplay();
}

void drawSquare(int x, int y)
{
  glTranslatef(x, y, 0.0);
  glBegin(GL_POLYGON);
    glVertex2f(square_size, square_size);
    glVertex2f(-square_size, square_size);
    glVertex2f(-square_size, -square_size);
    glVertex2f(+square_size, -square_size);
  glEnd();
}

void drawCircle(double x, double y, double radius)
{
  glBegin(GL_LINE_LOOP);
    for(double i = 0; i < 360; i++)
    {
      double degreeInRadian = i*DEGREE_TO_RADIAN;
      glVertex2f(x+cos(degreeInRadian)*radius, y+sin(degreeInRadian)*radius);
    }
  glEnd();
}

void reshapeCallback(int width, int height)
{
	WINDOW_WIDTH = width;
	WINDOW_HEIGHT = height;
}

void displayCallback()
{
  glClearColor(0.0, 0.0, 0.0, 1.0);
	glClear(GL_COLOR_BUFFER_BIT);
  glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

  if(mainMenuSelection == SQUARE_MENU_SELECTION)
  {
    drawSquare(square_x, square_y);
  }
  else if(mainMenuSelection == CIRCLE_MENU_SELECTION)
  {
    glColor3f(0.0, 0.0, 1.0);
    drawCircle(circle_x, circle_y, circle_radius);
  }
  else if(mainMenuSelection == RUBBERBANDING_CIRCLE_MENU_SELECTION)
  {
    double rubber_circle_radius = rubber_circle_end_x - rubber_circle_start_x;
    glColor3f(0.0, 1.0, 0.0);

    drawCircle(rubber_circle_start_x, rubber_circle_start_y, 1);
    if(rubber_circle_tracking)
    {
      drawCircle(rubber_circle_start_x, rubber_circle_start_y, rubber_circle_radius);
    }
    drawCircle(rubber_circle_start_x, rubber_circle_start_y, rubber_circle_radius);
  }
  glutSwapBuffers();
}

int main(int argc, char** argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
  glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
  glutInitWindowPosition(0, 0);
  glutCreateWindow("Homework 2");

  glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0.0, WINDOW_WIDTH, 0.0, WINDOW_HEIGHT, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);

  glClearColor(0.0, 0.0, 0.0, 0.0);
  glClear(GL_COLOR_BUFFER_BIT);
  glutSwapBuffers();

  createMainMenu();
  glutMouseFunc(mouseCallback);
  glutKeyboardFunc(keyboardCallback);
  glutMotionFunc(mouseMotionCallback);
  glutPassiveMotionFunc(mousePassiveMotionCallback);
  glutIdleFunc(idleCallback);
  glutDisplayFunc(displayCallback);
  glutReshapeFunc(reshapeCallback);

  glutMainLoop();
  return 0;
}
<|endoftext|>


<commit_before>#include "ClangAstVisitor.h"

ClangAstVisitor::ClangAstVisitor(Model::Model* model, OOModel::Project* currentProject = nullptr) :
    currentModel_(model) , currentProject_(currentProject)
{
    trMngr_ = new TranslateManager(model,currentProject);
    ooStack.push(currentProject_);
}

ClangAstVisitor::~ClangAstVisitor()
{
    delete trMngr_;
}

bool ClangAstVisitor::TraverseCXXRecordDecl(clang::CXXRecordDecl *rd)
{
    if(llvm::isa<clang::CXXRecordDecl>(rd))
    {
        clang::CXXRecordDecl* recDecl = llvm::cast<clang::CXXRecordDecl>(rd);
        if(recDecl->isClass())
        {
            OOModel::Class* ooClass = trMngr_->insertClass(rd);
            // check if there was an error inserting class
            if(!ooClass) return false;
            currentProject_->classes()->append(ooClass);
            ooStack.push(ooClass);
        }
    }
    return Base::TraverseCXXRecordDecl(rd);
}

bool ClangAstVisitor::TraverseCXXMethodDecl(clang::CXXMethodDecl *methodDecl)
{
    // Constructors not yet handled
    if(llvm::isa<clang::CXXConstructorDecl>(methodDecl))
        return true;
    // translation Manager will insert method in correct class
    OOModel::Method* method = trMngr_->insertMethodDecl(methodDecl);
    if(!method)
    {
        std::cout << "___________ERROR NO OOMODEL::METHOD FOR THIS DECL_______" << std::endl;
        // for now return false to see error (interupts visitor)
        return false;
    }
    // only visit the body if we are at the definition
    if(methodDecl->isThisDeclarationADefinition())
    {
        ooStack.push(method->items());
        TraverseStmt(methodDecl->getBody());
        ooStack.pop();
    }
    return true;
}

bool ClangAstVisitor::TraverseIfStmt(clang::IfStmt *ifStmt)
{
    OOModel::IfStatement* ooIfStmt = new OOModel::IfStatement();
    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        itemList->append(ooIfStmt);
        std::cout << "TRAVERSING IF STMT" << std::endl;
        inBody_ = false;
        TraverseStmt(ifStmt->getCond());
        inBody_ = true;
        ooIfStmt->setCondition(ooExprStack.pop());
        ooStack.push(ooIfStmt->thenBranch());
        TraverseStmt(ifStmt->getThen());
        ooStack.pop();
        ooStack.push(ooIfStmt->elseBranch());
        TraverseStmt(ifStmt->getElse());
        ooStack.pop();
        std::cout << "TRAVERSING IF STMT END" << std::endl;
    }

    return true;
}

bool ClangAstVisitor::TraverseWhileStmt(clang::WhileStmt* wStmt)
{
    OOModel::LoopStatement* ooLoop = new OOModel::LoopStatement();
    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        itemList->append(ooLoop);
        inBody_ = false;
        TraverseStmt(wStmt->getCond());
        inBody_ = true;
        ooLoop->setCondition(ooExprStack.pop());
        ooStack.push(ooLoop->body());
        TraverseStmt(wStmt->getBody());
        ooStack.pop();
    }
    return true;
}

bool ClangAstVisitor::TraverseReturnStmt(clang::ReturnStmt* rStmt)
{
    OOModel::ReturnStatement* ooReturn = new OOModel::ReturnStatement();
    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        itemList->append(ooReturn);
        inBody_ = false;
        TraverseStmt(rStmt->getRetValue());
        inBody_ = true;
        ooReturn->values()->append(ooExprStack.pop());
    }
    return true;
}

bool ClangAstVisitor::TraverseStmt(clang::Stmt *S)
{
    return Base::TraverseStmt(S);
}

bool ClangAstVisitor::VisitStmt(clang::Stmt* S)
{
    //    std::cout << "VISITING STMT" << std::endl;
    //    llvm::errs() << "VISITING STMT" << "\n";
    S->dump();
    return Base::VisitStmt(S);
}

bool ClangAstVisitor::TraverseVarDecl(clang::VarDecl* vd)
{
    std::cout << "Visiting VarDecl " << vd->getNameAsString() <<std::endl;

    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        OOModel::VariableDeclaration* varDecl = trMngr_->insertVar(vd);
        if(vd->getType().getTypePtr()->isArrayType())
        {
            const clang::ArrayType* arrType =  vd->getType().getTypePtr()->getAsArrayTypeUnsafe();
            if(arrType)
            {
                if(llvm::isa<clang::ConstantArrayType>(arrType))
                {
                    const clang::ConstantArrayType* constArr = llvm::dyn_cast<clang::ConstantArrayType>(arrType);
                    std::cout << "Const Array Size: " << constArr->getSize().getLimitedValue() << std::endl;
                }
            }
        }
        else
        {
            OOModel::Expression* type = CppImportUtilities::convertClangType(vd->getType());
            if(type) varDecl->setVarType(type);
        }

        if(vd->hasInit())
        {
            TraverseStmt(vd->getInit());
            varDecl->setInitialValue(ooExprStack.pop());
        }
        itemList->append(varDecl);
    }
    else
    {
        if(!llvm::isa<clang::ParmVarDecl>(vd))
            std::cout << "--->WARNING : THIS VARIABLE IS NOT SUPPORTED : " << vd->getNameAsString() << std::endl;
    }
    return true;
}

bool ClangAstVisitor::VisitFieldDecl(clang::FieldDecl* fd)
{
    OOModel::Field* field = trMngr_->insertField(fd);
    if(!field)
    {
        std::cout << "ERROR COULDN'T INSERT FIELD NO CURRENT OOCLASS" << std::endl;
        //        return false;
    }
    return true;
}

bool ClangAstVisitor::VisitIntegerLiteral(clang::IntegerLiteral* intLit)
{
    OOModel::IntegerLiteral* ooIntLit = new OOModel::IntegerLiteral();
    ooIntLit->setValue(intLit->getValue().getLimitedValue());
    ooExprStack.push(ooIntLit);

    return true;
}

bool ClangAstVisitor::VisitDeclRefExpr(clang::DeclRefExpr* declRef)
{
    OOModel::ReferenceExpression* refExpr = new OOModel::ReferenceExpression();
    //    if(llvm::isa<clang::VarDecl>(declRef->getDecl()))
    //    {
    //        OOModel::VariableDeclaration* ooVar = trMngr_->getVar(llvm::dyn_cast<clang::VarDecl>(declRef->getDecl()));
    //        if(ooVar) refExpr->setPrefix(ooVar);
    //        else refExpr->setName(QString::fromStdString(declRef->getNameInfo().getName().getAsString()));
    //    }
    //    else
    //    {
    refExpr->setName(QString::fromStdString(declRef->getNameInfo().getName().getAsString()));
    //    }
    ooExprStack.push(refExpr);
    return true;
}

bool ClangAstVisitor::shouldUseDataRecursionFor(clang::Stmt *S)
{
    // -unused var
    S->getStmtClass();
    return false;
}

bool ClangAstVisitor::TraverseBinaryOp(clang::BinaryOperator* binOp)
{
    OOModel::BinaryOperation::OperatorTypes ooOperatorType = CppImportUtilities::convertClangOpcode(binOp->getOpcode());
    OOModel::BinaryOperation* ooBinOp = new OOModel::BinaryOperation();
    bool inBody = inBody_;
    inBody_ = false;
    ooBinOp->setOp(ooOperatorType);
    TraverseStmt(binOp->getLHS());
    ooBinOp->setLeft(ooExprStack.pop());
    TraverseStmt(binOp->getRHS());
    ooBinOp->setRight(ooExprStack.pop());

    if(inBody)
    {
        OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
        if(itemList) itemList->append(ooBinOp);
        else std::cout << "ERROR INSERT BINOP" << std::endl;
    }
    else
        ooExprStack.push(ooBinOp);
    inBody_ = inBody;
    return true;
}

bool ClangAstVisitor::TraverseAssignment(clang::BinaryOperator *binOp)
{
    OOModel::AssignmentExpression::AssignmentTypes ooOperatorType = CppImportUtilities::convertClangAssignOpcode(binOp->getOpcode());
    OOModel::AssignmentExpression* ooBinOp = new OOModel::AssignmentExpression();
    bool inBody = inBody_;
    inBody_ = false;
    ooBinOp->setOp(ooOperatorType);
    TraverseStmt(binOp->getLHS());
    ooBinOp->setLeft(ooExprStack.pop());
    TraverseStmt(binOp->getRHS());
    ooBinOp->setRight(ooExprStack.pop());

    if(inBody)
    {
        OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
        if(itemList) itemList->append(ooBinOp);
        else std::cout << "ERROR INSERT BINOP" << std::endl;
    }
    else
        ooExprStack.push(ooBinOp);
    inBody_ = inBody;
    return true;
}
<commit_msg>removed unneeded check which is always true<commit_after>#include "ClangAstVisitor.h"

ClangAstVisitor::ClangAstVisitor(Model::Model* model, OOModel::Project* currentProject = nullptr) :
    currentModel_(model) , currentProject_(currentProject)
{
    trMngr_ = new TranslateManager(model,currentProject);
    ooStack.push(currentProject_);
}

ClangAstVisitor::~ClangAstVisitor()
{
    delete trMngr_;
}

bool ClangAstVisitor::TraverseCXXRecordDecl(clang::CXXRecordDecl *rd)
{
    if(rd->isClass())
    {
        OOModel::Class* ooClass = trMngr_->insertClass(rd);
        // check if there was an error inserting class
        if(!ooClass) return false;
        currentProject_->classes()->append(ooClass);
        ooStack.push(ooClass);
    }
    return Base::TraverseCXXRecordDecl(rd);
}

bool ClangAstVisitor::TraverseCXXMethodDecl(clang::CXXMethodDecl *methodDecl)
{
    // Constructors not yet handled
    if(llvm::isa<clang::CXXConstructorDecl>(methodDecl))
        return true;
    // translation Manager will insert method in correct class
    OOModel::Method* method = trMngr_->insertMethodDecl(methodDecl);
    if(!method)
    {
        std::cout << "___________ERROR NO OOMODEL::METHOD FOR THIS DECL_______" << std::endl;
        // for now return false to see error (interupts visitor)
        return false;
    }
    // only visit the body if we are at the definition
    if(methodDecl->isThisDeclarationADefinition())
    {
        ooStack.push(method->items());
        TraverseStmt(methodDecl->getBody());
        ooStack.pop();
    }
    return true;
}

bool ClangAstVisitor::TraverseIfStmt(clang::IfStmt *ifStmt)
{
    OOModel::IfStatement* ooIfStmt = new OOModel::IfStatement();
    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        itemList->append(ooIfStmt);
        std::cout << "TRAVERSING IF STMT" << std::endl;
        inBody_ = false;
        TraverseStmt(ifStmt->getCond());
        inBody_ = true;
        ooIfStmt->setCondition(ooExprStack.pop());
        ooStack.push(ooIfStmt->thenBranch());
        TraverseStmt(ifStmt->getThen());
        ooStack.pop();
        ooStack.push(ooIfStmt->elseBranch());
        TraverseStmt(ifStmt->getElse());
        ooStack.pop();
        std::cout << "TRAVERSING IF STMT END" << std::endl;
    }

    return true;
}

bool ClangAstVisitor::TraverseWhileStmt(clang::WhileStmt* wStmt)
{
    OOModel::LoopStatement* ooLoop = new OOModel::LoopStatement();
    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        itemList->append(ooLoop);
        inBody_ = false;
        TraverseStmt(wStmt->getCond());
        inBody_ = true;
        ooLoop->setCondition(ooExprStack.pop());
        ooStack.push(ooLoop->body());
        TraverseStmt(wStmt->getBody());
        ooStack.pop();
    }
    return true;
}

bool ClangAstVisitor::TraverseReturnStmt(clang::ReturnStmt* rStmt)
{
    OOModel::ReturnStatement* ooReturn = new OOModel::ReturnStatement();
    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        itemList->append(ooReturn);
        inBody_ = false;
        TraverseStmt(rStmt->getRetValue());
        inBody_ = true;
        ooReturn->values()->append(ooExprStack.pop());
    }
    return true;
}

bool ClangAstVisitor::TraverseStmt(clang::Stmt *S)
{
    return Base::TraverseStmt(S);
}

bool ClangAstVisitor::VisitStmt(clang::Stmt* S)
{
    //    std::cout << "VISITING STMT" << std::endl;
    //    llvm::errs() << "VISITING STMT" << "\n";
    S->dump();
    return Base::VisitStmt(S);
}

bool ClangAstVisitor::TraverseVarDecl(clang::VarDecl* vd)
{
    std::cout << "Visiting VarDecl " << vd->getNameAsString() <<std::endl;

    OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
    if(itemList)
    {
        OOModel::VariableDeclaration* varDecl = trMngr_->insertVar(vd);
        if(vd->getType().getTypePtr()->isArrayType())
        {
            const clang::ArrayType* arrType =  vd->getType().getTypePtr()->getAsArrayTypeUnsafe();
            if(arrType)
            {
                if(llvm::isa<clang::ConstantArrayType>(arrType))
                {
                    const clang::ConstantArrayType* constArr = llvm::dyn_cast<clang::ConstantArrayType>(arrType);
                    std::cout << "Const Array Size: " << constArr->getSize().getLimitedValue() << std::endl;
                }
            }
        }
        else
        {
            OOModel::Expression* type = CppImportUtilities::convertClangType(vd->getType());
            if(type) varDecl->setVarType(type);
        }

        if(vd->hasInit())
        {
            TraverseStmt(vd->getInit());
            varDecl->setInitialValue(ooExprStack.pop());
        }
        itemList->append(varDecl);
    }
    else
    {
        if(!llvm::isa<clang::ParmVarDecl>(vd))
            std::cout << "--->WARNING : THIS VARIABLE IS NOT SUPPORTED : " << vd->getNameAsString() << std::endl;
    }
    return true;
}

bool ClangAstVisitor::VisitFieldDecl(clang::FieldDecl* fd)
{
    OOModel::Field* field = trMngr_->insertField(fd);
    if(!field)
    {
        std::cout << "ERROR COULDN'T INSERT FIELD NO CURRENT OOCLASS" << std::endl;
        //        return false;
    }
    return true;
}

bool ClangAstVisitor::VisitIntegerLiteral(clang::IntegerLiteral* intLit)
{
    OOModel::IntegerLiteral* ooIntLit = new OOModel::IntegerLiteral();
    ooIntLit->setValue(intLit->getValue().getLimitedValue());
    ooExprStack.push(ooIntLit);

    return true;
}

bool ClangAstVisitor::VisitDeclRefExpr(clang::DeclRefExpr* declRef)
{
    OOModel::ReferenceExpression* refExpr = new OOModel::ReferenceExpression();
    //    if(llvm::isa<clang::VarDecl>(declRef->getDecl()))
    //    {
    //        OOModel::VariableDeclaration* ooVar = trMngr_->getVar(llvm::dyn_cast<clang::VarDecl>(declRef->getDecl()));
    //        if(ooVar) refExpr->setPrefix(ooVar);
    //        else refExpr->setName(QString::fromStdString(declRef->getNameInfo().getName().getAsString()));
    //    }
    //    else
    //    {
    refExpr->setName(QString::fromStdString(declRef->getNameInfo().getName().getAsString()));
    //    }
    ooExprStack.push(refExpr);
    return true;
}

bool ClangAstVisitor::shouldUseDataRecursionFor(clang::Stmt *S)
{
    // -unused var
    S->getStmtClass();
    return false;
}

bool ClangAstVisitor::TraverseBinaryOp(clang::BinaryOperator* binOp)
{
    OOModel::BinaryOperation::OperatorTypes ooOperatorType = CppImportUtilities::convertClangOpcode(binOp->getOpcode());
    OOModel::BinaryOperation* ooBinOp = new OOModel::BinaryOperation();
    bool inBody = inBody_;
    inBody_ = false;
    ooBinOp->setOp(ooOperatorType);
    TraverseStmt(binOp->getLHS());
    ooBinOp->setLeft(ooExprStack.pop());
    TraverseStmt(binOp->getRHS());
    ooBinOp->setRight(ooExprStack.pop());

    if(inBody)
    {
        OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
        if(itemList) itemList->append(ooBinOp);
        else std::cout << "ERROR INSERT BINOP" << std::endl;
    }
    else
        ooExprStack.push(ooBinOp);
    inBody_ = inBody;
    return true;
}

bool ClangAstVisitor::TraverseAssignment(clang::BinaryOperator *binOp)
{
    OOModel::AssignmentExpression::AssignmentTypes ooOperatorType = CppImportUtilities::convertClangAssignOpcode(binOp->getOpcode());
    OOModel::AssignmentExpression* ooBinOp = new OOModel::AssignmentExpression();
    bool inBody = inBody_;
    inBody_ = false;
    ooBinOp->setOp(ooOperatorType);
    TraverseStmt(binOp->getLHS());
    ooBinOp->setLeft(ooExprStack.pop());
    TraverseStmt(binOp->getRHS());
    ooBinOp->setRight(ooExprStack.pop());

    if(inBody)
    {
        OOModel::StatementItemList* itemList = dynamic_cast<OOModel::StatementItemList*>(ooStack.top());
        if(itemList) itemList->append(ooBinOp);
        else std::cout << "ERROR INSERT BINOP" << std::endl;
    }
    else
        ooExprStack.push(ooBinOp);
    inBody_ = inBody;
    return true;
}
<|endoftext|>


<commit_before>/**
 * @par Licence
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include "DatabaseReader.hpp"

namespace DatabaseReader {

std::vector<City> readCitiesFromFile(std::string databaseFile) {
    std::vector<City> vecOfCities;
    std::ifstream ifs;
    ifs.open(databaseFile, std::ifstream::in);
    std::string line{};

    while(std::getline(ifs, line)) {
        if (line[0] == '#') {
            continue;
	}
        std::vector<std::string> params;
        size_t pos;
        while((pos = line.find(" "))!=std::string::npos) {
            line.replace(line.begin()+pos,line.begin()+pos+1,"");
        }
	    split(line, "|", params);

        City city(params[0], params[1], params[2], params[3], params[4]);
	    vecOfCities.push_back(city);
    }

    return vecOfCities;
}

// TODO: move to separate file? utils perhaps?
void split (std::string str, std::string splitBy, std::vector<std::string>& tokens) {
    tokens.push_back(str);
    std::size_t splitAt;
    std::size_t splitLen = splitBy.size();
    std::string frag;
    while (true) {
        frag = tokens.back();
	splitAt = frag.find(splitBy);
	if (splitAt == std::string::npos) {
            break;
        }
	tokens.back() = frag.substr(0, splitAt);
	tokens.push_back(frag.substr(splitAt+splitLen, frag.size()-(splitAt+splitLen)));
    }
}

}

<commit_msg>Update DatabaseReader.cpp<commit_after>/**
 * @par Licence
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include "DatabaseReader.hpp"

namespace DatabaseReader {

std::vector<City> readCitiesFromFile(std::string databaseFile) {
    std::vector<City> vecOfCities;
    std::ifstream ifs;
    ifs.open(databaseFile, std::ifstream::in);
    std::string line{};

    while(std::getline(ifs, line)) {
        if (line[0] == '#') {
            continue;
	}
        std::vector<std::string> params;
        size_t pos;
        while((pos = line.find(" "))!=std::string::npos) {
            line.replace(line.begin()+pos,line.begin()+pos+1,"");
        }
	split(line, "|", params);

        City city(params[0], params[1], params[2], params[3], params[4]);
	vecOfCities.push_back(city);
    }

    return vecOfCities;
}

// TODO: move to separate file? utils perhaps?
void split (std::string str, std::string splitBy, std::vector<std::string>& tokens) {
    tokens.push_back(str);
    std::size_t splitAt;
    std::size_t splitLen = splitBy.size();
    std::string frag;
    while (true) {
        frag = tokens.back();
	splitAt = frag.find(splitBy);
	if (splitAt == std::string::npos) {
            break;
        }
	tokens.back() = frag.substr(0, splitAt);
	tokens.push_back(frag.substr(splitAt+splitLen, frag.size()-(splitAt+splitLen)));
    }
}

}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 Noel Power<noel.power@suse.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */
#ifndef OOX_OLE_AXBINARYWRITER_HXX
#define OOX_OLE_AXBINARYWRITER_HXX

#include <utility>
#include "oox/helper/binaryoutputstream.hxx"
#include "oox/helper/refvector.hxx"

namespace oox {
namespace ole {
// ============================================================================

/** A wrapper for a binary output stream that supports aligned write operations.

    The implementation does support seeking back the wrapped stream. All
    seeking operations (tell, seekTo, align) are performed relative to the
    position of the wrapped stream at construction time of this wrapper.
    Unlike it's reader class counterpart it is NOT possible to construct this
    wrapper with an unseekable output stream.
 */
class AxAlignedOutputStream : public BinaryOutputStream
{
public:
    explicit            AxAlignedOutputStream( BinaryOutputStream& rOutStrm );

    /** Returns the size of the data this stream represents, if the wrapped
        stream supports the size() operation. */
    virtual sal_Int64   size() const;
    /** Return the current relative stream position (relative to position of
        the wrapped stream at construction time). */
    virtual sal_Int64   tell() const;
    /** Seeks the stream to the passed relative position, if it is behind the
        current position. */
    virtual void        seek( sal_Int64 nPos );
    /** Closes the input stream but not the wrapped stream. */
    virtual void        close();

    /** Reads nBytes bytes to the passed sequence.
        @return  Number of bytes really read. */
    virtual void writeData( const StreamDataSequence& orData, size_t nAtomSize = 1 );
    /** Reads nBytes bytes to the (existing) buffer opMem.
        @return  Number of bytes really read. */
    virtual void   writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 );

    /** Aligns the stream to a multiple of the passed size (relative to the
        position of the wrapped stream at construction time). */
    void                align( size_t nSize );

    void         pad( sal_Int32 nBytes, size_t nAtomSize = 1);
    /** Aligns the stream according to the passed type and reads an atomar value. */
    template< typename Type >
    inline void         writeAligned( Type nVal ) { align( sizeof( Type ) ); writeValue( nVal ); }
    /** Aligns the stream according to the passed type and skips the size of the type. */
    template< typename Type >
    inline void         padAligned() { align( sizeof( Type ) ); pad( sizeof( Type ) ); }

private:
    BinaryOutputStream*  mpOutStrm;           ///< The wrapped input stream.
    sal_Int64           mnStrmPos;          ///< Tracks relative position in the stream.
    sal_Int64           mnStrmSize;         ///< Size of the wrapped stream data.
    sal_Int64           mnWrappedBeginPos;     ///< starting pos or wrapped stream
};

/** A pair of integer values as a property. */
typedef ::std::pair< sal_Int32, sal_Int32 > AxPairData;

/** An array of string values as a property. */
typedef ::std::vector< ::rtl::OUString > AxStringArray;

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

/** Export helper to write simple and complex ActiveX form control properties
    to a binary input stream. */
class AxBinaryPropertyWriter
{
public:
    explicit            AxBinaryPropertyWriter( BinaryOutputStream& rOutStrm, bool b64BitPropFlags = false );

    /** Write an integer property value to the stream, the
        respective flag in the property mask is set. */
    template< typename StreamType, typename DataType >
    inline void         writeIntProperty( DataType& ornValue )
                            { if( startNextProperty() ) maOutStrm.writeAligned< StreamType >( ornValue ); }
    /** Write a boolean property value to the stream, the
        respective flag in the property mask is set. */
    void                writeBoolProperty( bool orbValue, bool bReverse = false );
    /** Write a pair property the stream, the respective flag in
        the property mask is set. */
    void                writePairProperty( AxPairData& orPairData );
    /** Write a string property to the stream, the respective flag
        in the property mask is set. */
    void                writeStringProperty( ::rtl::OUString& orValue, bool bCompressed = true );

    /** Skips the next property clears the respective
        flag in the property mask. */
    inline void         skipProperty() { startNextProperty( true ); }

    /** Final processing, write contents of all complex properties, writes record size */
    bool                finalizeExport();

private:
    bool                ensureValid( bool bCondition = true );
    bool                startNextProperty( bool bSkip = false );

private:
    /** Base class for complex properties such as string, point, size, GUID, picture. */
    struct ComplexProperty
    {
        virtual             ~ComplexProperty();
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm ) = 0;
    };

    /** Complex property for a 32-bit value pair, e.g. point or size. */
    struct PairProperty : public ComplexProperty
    {
        AxPairData&         mrPairData;

        inline explicit     PairProperty( AxPairData& rPairData ) :
                                mrPairData( rPairData ) {}
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm );
    };

    /** Complex property for a string value. */
    struct StringProperty : public ComplexProperty
    {
        ::rtl::OUString&    mrValue;
        sal_uInt32          mnSize;

        inline explicit     StringProperty( ::rtl::OUString& rValue, sal_uInt32 nSize ) :
                                mrValue( rValue ), mnSize( nSize ) {}
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm );
    };

    /** Stream property for a picture or mouse icon. */
    struct PictureProperty : public ComplexProperty
    {
        StreamDataSequence& mrPicData;

        inline explicit     PictureProperty( StreamDataSequence& rPicData ) :
                                mrPicData( rPicData ) {}
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm );
    };

    typedef RefVector< ComplexProperty > ComplexPropVector;

private:
    AxAlignedOutputStream maOutStrm;        ///< The input stream to read from.
    ComplexPropVector   maLargeProps;       ///< Stores info for all used large properties.
    ComplexPropVector   maStreamProps;      ///< Stores info for all used stream data properties.
    AxPairData          maDummyPairData;    ///< Dummy pair for unsupported properties.
    StreamDataSequence  maDummyPicData;     ///< Dummy picture for unsupported properties.
    ::rtl::OUString     maDummyString;      ///< Dummy string for unsupported properties.
    AxStringArray       maDummyStringArray; ///< Dummy string array for unsupported properties.
    sal_Int16           mnBlockSize;
    sal_Int64           mnPropFlagsStart;     ///< pos of Prop flags
    sal_Int64           mnPropFlags;        ///< Flags specifying existing properties.
    sal_Int64           mnNextProp;         ///< Next property to read.
    sal_Int64           mnPropsEnd;         ///< End position of simple/large properties.
    bool                mbValid;            ///< True = stream still valid.
    bool                mb64BitPropFlags;
};

// ============================================================================
} // namespace ole
} // namespace oox

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738777 Uninitialized scalar field => unused member<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 Noel Power<noel.power@suse.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */
#ifndef OOX_OLE_AXBINARYWRITER_HXX
#define OOX_OLE_AXBINARYWRITER_HXX

#include <utility>
#include "oox/helper/binaryoutputstream.hxx"
#include "oox/helper/refvector.hxx"

namespace oox {
namespace ole {
// ============================================================================

/** A wrapper for a binary output stream that supports aligned write operations.

    The implementation does support seeking back the wrapped stream. All
    seeking operations (tell, seekTo, align) are performed relative to the
    position of the wrapped stream at construction time of this wrapper.
    Unlike it's reader class counterpart it is NOT possible to construct this
    wrapper with an unseekable output stream.
 */
class AxAlignedOutputStream : public BinaryOutputStream
{
public:
    explicit            AxAlignedOutputStream( BinaryOutputStream& rOutStrm );

    /** Returns the size of the data this stream represents, if the wrapped
        stream supports the size() operation. */
    virtual sal_Int64   size() const;
    /** Return the current relative stream position (relative to position of
        the wrapped stream at construction time). */
    virtual sal_Int64   tell() const;
    /** Seeks the stream to the passed relative position, if it is behind the
        current position. */
    virtual void        seek( sal_Int64 nPos );
    /** Closes the input stream but not the wrapped stream. */
    virtual void        close();

    /** Reads nBytes bytes to the passed sequence.
        @return  Number of bytes really read. */
    virtual void writeData( const StreamDataSequence& orData, size_t nAtomSize = 1 );
    /** Reads nBytes bytes to the (existing) buffer opMem.
        @return  Number of bytes really read. */
    virtual void   writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 );

    /** Aligns the stream to a multiple of the passed size (relative to the
        position of the wrapped stream at construction time). */
    void                align( size_t nSize );

    void         pad( sal_Int32 nBytes, size_t nAtomSize = 1);
    /** Aligns the stream according to the passed type and reads an atomar value. */
    template< typename Type >
    inline void         writeAligned( Type nVal ) { align( sizeof( Type ) ); writeValue( nVal ); }
    /** Aligns the stream according to the passed type and skips the size of the type. */
    template< typename Type >
    inline void         padAligned() { align( sizeof( Type ) ); pad( sizeof( Type ) ); }

private:
    BinaryOutputStream*  mpOutStrm;           ///< The wrapped input stream.
    sal_Int64           mnStrmPos;          ///< Tracks relative position in the stream.
    sal_Int64           mnStrmSize;         ///< Size of the wrapped stream data.
    sal_Int64           mnWrappedBeginPos;     ///< starting pos or wrapped stream
};

/** A pair of integer values as a property. */
typedef ::std::pair< sal_Int32, sal_Int32 > AxPairData;

/** An array of string values as a property. */
typedef ::std::vector< ::rtl::OUString > AxStringArray;

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

/** Export helper to write simple and complex ActiveX form control properties
    to a binary input stream. */
class AxBinaryPropertyWriter
{
public:
    explicit            AxBinaryPropertyWriter( BinaryOutputStream& rOutStrm, bool b64BitPropFlags = false );

    /** Write an integer property value to the stream, the
        respective flag in the property mask is set. */
    template< typename StreamType, typename DataType >
    inline void         writeIntProperty( DataType& ornValue )
                            { if( startNextProperty() ) maOutStrm.writeAligned< StreamType >( ornValue ); }
    /** Write a boolean property value to the stream, the
        respective flag in the property mask is set. */
    void                writeBoolProperty( bool orbValue, bool bReverse = false );
    /** Write a pair property the stream, the respective flag in
        the property mask is set. */
    void                writePairProperty( AxPairData& orPairData );
    /** Write a string property to the stream, the respective flag
        in the property mask is set. */
    void                writeStringProperty( ::rtl::OUString& orValue, bool bCompressed = true );

    /** Skips the next property clears the respective
        flag in the property mask. */
    inline void         skipProperty() { startNextProperty( true ); }

    /** Final processing, write contents of all complex properties, writes record size */
    bool                finalizeExport();

private:
    bool                ensureValid( bool bCondition = true );
    bool                startNextProperty( bool bSkip = false );

private:
    /** Base class for complex properties such as string, point, size, GUID, picture. */
    struct ComplexProperty
    {
        virtual             ~ComplexProperty();
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm ) = 0;
    };

    /** Complex property for a 32-bit value pair, e.g. point or size. */
    struct PairProperty : public ComplexProperty
    {
        AxPairData&         mrPairData;

        inline explicit     PairProperty( AxPairData& rPairData ) :
                                mrPairData( rPairData ) {}
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm );
    };

    /** Complex property for a string value. */
    struct StringProperty : public ComplexProperty
    {
        ::rtl::OUString&    mrValue;
        sal_uInt32          mnSize;

        inline explicit     StringProperty( ::rtl::OUString& rValue, sal_uInt32 nSize ) :
                                mrValue( rValue ), mnSize( nSize ) {}
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm );
    };

    /** Stream property for a picture or mouse icon. */
    struct PictureProperty : public ComplexProperty
    {
        StreamDataSequence& mrPicData;

        inline explicit     PictureProperty( StreamDataSequence& rPicData ) :
                                mrPicData( rPicData ) {}
        virtual bool        writeProperty( AxAlignedOutputStream& rOutStrm );
    };

    typedef RefVector< ComplexProperty > ComplexPropVector;

private:
    AxAlignedOutputStream maOutStrm;        ///< The input stream to read from.
    ComplexPropVector   maLargeProps;       ///< Stores info for all used large properties.
    ComplexPropVector   maStreamProps;      ///< Stores info for all used stream data properties.
    AxPairData          maDummyPairData;    ///< Dummy pair for unsupported properties.
    StreamDataSequence  maDummyPicData;     ///< Dummy picture for unsupported properties.
    ::rtl::OUString     maDummyString;      ///< Dummy string for unsupported properties.
    AxStringArray       maDummyStringArray; ///< Dummy string array for unsupported properties.
    sal_Int16           mnBlockSize;
    sal_Int64           mnPropFlagsStart;     ///< pos of Prop flags
    sal_Int64           mnPropFlags;        ///< Flags specifying existing properties.
    sal_Int64           mnNextProp;         ///< Next property to read.
    bool                mbValid;            ///< True = stream still valid.
    bool                mb64BitPropFlags;
};

// ============================================================================
} // namespace ole
} // namespace oox

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>