<commit_before>#include <QWebSocketServer>
#include <QWebSocket>
#include <QDebug>
#include <QFile>
#include <QSslCertificate>
#include <QSslKey>
#include <QThreadPool>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QPointer>

#include "w3cserver.h"
#include "jsonrequestparser.h"
#include "request-handler/processrequesttask.h"
#include "qjsonwebtoken.h"
#include "jwt-utility/visstokenvalidator.h"
#include "VSSSignalinterface/vsssignalinterfaceimpl.h"
#include "VSSSignalinterface/vsssignalinterface.h"
#include "messaging/websocketwrapper.h"
#include "OpenDSHandler/opendshandler.h"

#include "logger.h"

QT_USE_NAMESPACE

class W3CServer;
int W3CServer::m_nrOfClients;
W3CServer::W3CServer(quint16 port,bool usesecureprotocol, QObject *parent) : QObject(parent),
    m_pWebSocketServer(0),
    m_clients(),
    m_secure(usesecureprotocol)
{
    QThreadPool::globalInstance()->setMaxThreadCount(100);

    if (usesecureprotocol)
    {
        m_pWebSocketServer = new QWebSocketServer(QStringLiteral("W3CServer"),
                QWebSocketServer::SecureMode,
                this);
        // m_pWebSocketServer ->
        QSslConfiguration sslConfiguration;

        QFile keyFile(QStringLiteral(":/server.key"));
        QFile certFile(QStringLiteral(":/server.crt"));

        certFile.open(QIODevice::ReadOnly);
        const QByteArray bytes = certFile.readAll();
        QJsonWebToken e;

        TRACE("Server","Certification file length : " + QString::number(bytes.length()));

        QSslCertificate certificate(bytes, QSsl::Pem);

        keyFile.open(QIODevice::ReadOnly);
        const QByteArray passphrase("6610");
        QSslKey sslKey(&keyFile, QSsl::Rsa, QSsl::Pem,QSsl::PrivateKey,passphrase);

        certFile.close();
        keyFile.close();

        sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
        sslConfiguration.setLocalCertificate(certificate);
        sslConfiguration.setPrivateKey(sslKey);
        sslConfiguration.setProtocol(QSsl::TlsV1SslV3);

        m_pWebSocketServer->setSslConfiguration(sslConfiguration);
    }
    else
    {
        m_pWebSocketServer = new QWebSocketServer(QStringLiteral("W3CServer Test"),QWebSocketServer::NonSecureMode,this);

    }
    if (m_pWebSocketServer->listen(QHostAddress::Any, port))
    {
        INFO("Server","W3CServer is listening on port " + QString::number(port));

        //Connect QWebSocketServer newConnection signal with W3cServer slot onNewConnection
        connect(m_pWebSocketServer, &QWebSocketServer::newConnection,this,&W3CServer::onNewConnection);
        //Connect QWebsocketServer signal with W3CServer signal closed
        // connect(m_pWebSocketServer,&QWebSocketServer::closed, this, &W3CServer::closed);
        //SSL error handler
        connect(m_pWebSocketServer, &QWebSocketServer::sslErrors,
                this, &W3CServer::onSslErrors);
    }

    // TODO: select implementation based on application configuration

    const QString vssFile = "/etc/vss_rel_1.json";
    m_vsssInterface = QSharedPointer<VSSSignalInterfaceImpl>(new VSSSignalInterfaceImpl(vssFile));
    m_openDSHandler = QSharedPointer<OpenDSHandler>(new OpenDSHandler());
    connect(m_openDSHandler.data(), &OpenDSHandler::valueChanged, static_cast <VSSSignalInterfaceImpl*>(m_vsssInterface.data()), &VSSSignalInterfaceImpl::updateValue);
}

W3CServer::~W3CServer()
{
    m_pWebSocketServer->close();
    //clean out all connected clients
    qDeleteAll(m_clients.begin(),m_clients.end());
    m_vsssInterface.clear();
}

void W3CServer::onNewConnection()
{
    QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();
    pSocket ->ignoreSslErrors();
    DEBUG("Server","Attemping to connect");

    // Connect socket textMessageReceived signal with server processTextMessage slot
    connect(pSocket, &QWebSocket::textMessageReceived, this, &W3CServer::processTextMessage);
    // Connect socket disconnected signal with server socketDisconnected slot
    connect(pSocket, &QWebSocket::disconnected, this, &W3CServer::socketDisconnected);

    // add socket to list of clients
    m_clients.insert(pSocket, new QMutex());
    W3CServer::m_nrOfClients++;
}

void W3CServer::processTextMessage(const QString& message)
{

    DEBUG("Server","Message received");
    TRACE("Server", message);

    QWebSocket *zeClient = qobject_cast<QWebSocket *> (sender());
    if (m_clients.contains(zeClient))
    {
        // we need a mutex per client .
        QMutex* mutex = m_clients.find(zeClient).value();
        QPointer<WebSocketWrapper> socketWrapper = new WebSocketWrapper(zeClient, mutex);
        startRequestProcess(socketWrapper, message);
    }
    else
    {
        WARNING("Server","Fatal connection error, Websocket client not found.");
    }
}

void W3CServer::socketDisconnected()
{
    QWebSocket *zeClient = qobject_cast<QWebSocket *> (sender());

    DEBUG("Server","Socket disconnected");// : " + zeClient);

    //remove from client list and delete from heap
    if (zeClient)
    {
        m_clients.remove(zeClient);
        zeClient->deleteLater();
        W3CServer::m_nrOfClients--;
    }
}

void W3CServer::onSslErrors(const QList<QSslError> &l)
{
    TRACE("Server","SSL Error occurred."); // Change to WARNING
}

void W3CServer::startRequestProcess(WebSocketWrapper* sw, const QString& message)
{
    ProcessRequestTask* requesttask = new ProcessRequestTask(sw, m_vsssInterface, message, true);
    // QThreadPool takes ownership and deletes 'requesttask' automatically

    if(!QThreadPool::globalInstance()->tryStart(requesttask))
    {
        WARNING("Server","Failed to start thread! Active threads : " + QString::number(QThreadPool::globalInstance()->activeThreadCount()));
        WARNING("Server","Max threads alloved : " + QString::number(QThreadPool::globalInstance()->maxThreadCount()));
    }
    else
    {
        DEBUG("Server","New thread started! Active threads : " + QString::number(QThreadPool::globalInstance()->activeThreadCount()));
    }
}
<commit_msg> testing some flush theories<commit_after>#include <QWebSocketServer>
#include <QWebSocket>
#include <QDebug>
#include <QFile>
#include <QSslCertificate>
#include <QSslKey>
#include <QThreadPool>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QPointer>

#include "w3cserver.h"
#include "jsonrequestparser.h"
#include "request-handler/processrequesttask.h"
#include "qjsonwebtoken.h"
#include "jwt-utility/visstokenvalidator.h"
#include "VSSSignalinterface/vsssignalinterfaceimpl.h"
#include "VSSSignalinterface/vsssignalinterface.h"
#include "messaging/websocketwrapper.h"
#include "OpenDSHandler/opendshandler.h"

#include "logger.h"

QT_USE_NAMESPACE

class W3CServer;
int W3CServer::m_nrOfClients;
W3CServer::W3CServer(quint16 port,bool usesecureprotocol, QObject *parent) : QObject(parent),
    m_pWebSocketServer(0),
    m_clients(),
    m_secure(usesecureprotocol)
{
    QThreadPool::globalInstance()->setMaxThreadCount(100);

    if (usesecureprotocol)
    {
        m_pWebSocketServer = new QWebSocketServer(QStringLiteral("W3CServer"),
                QWebSocketServer::SecureMode,
                this);
        // m_pWebSocketServer ->
        QSslConfiguration sslConfiguration;

        QFile keyFile(QStringLiteral(":/server.key"));
        QFile certFile(QStringLiteral(":/server.crt"));

        certFile.open(QIODevice::ReadOnly);
        const QByteArray bytes = certFile.readAll();
        QJsonWebToken e;

        TRACE("Server","Certification file length : " + QString::number(bytes.length()));

        QSslCertificate certificate(bytes, QSsl::Pem);

        keyFile.open(QIODevice::ReadOnly);
        const QByteArray passphrase("6610");
        QSslKey sslKey(&keyFile, QSsl::Rsa, QSsl::Pem,QSsl::PrivateKey,passphrase);

        certFile.close();
        keyFile.close();

        sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
        sslConfiguration.setLocalCertificate(certificate);
        sslConfiguration.setPrivateKey(sslKey);
        sslConfiguration.setProtocol(QSsl::TlsV1SslV3);

        m_pWebSocketServer->setSslConfiguration(sslConfiguration);
    }
    else
    {
        m_pWebSocketServer = new QWebSocketServer(QStringLiteral("W3CServer Test"),QWebSocketServer::NonSecureMode,this);

    }
    if (m_pWebSocketServer->listen(QHostAddress::Any, port))
    {
        INFO("Server","W3CServer is listening on port " + QString::number(port));

        //Connect QWebSocketServer newConnection signal with W3cServer slot onNewConnection
        connect(m_pWebSocketServer, &QWebSocketServer::newConnection,this,&W3CServer::onNewConnection);
        //Connect QWebsocketServer signal with W3CServer signal closed
        // connect(m_pWebSocketServer,&QWebSocketServer::closed, this, &W3CServer::closed);
        //SSL error handler
        connect(m_pWebSocketServer, &QWebSocketServer::sslErrors,
                this, &W3CServer::onSslErrors);
    }

    // TODO: select implementation based on application configuration

    const QString vssFile = "/etc/vss_rel_1.json";
    m_vsssInterface = QSharedPointer<VSSSignalInterfaceImpl>(new VSSSignalInterfaceImpl(vssFile));
    //m_openDSHandler = QSharedPointer<OpenDSHandler>(new OpenDSHandler());
    //connect(m_openDSHandler.data(), &OpenDSHandler::valueChanged, static_cast <VSSSignalInterfaceImpl*>(m_vsssInterface.data()), &VSSSignalInterfaceImpl::updateValue);
}

W3CServer::~W3CServer()
{
    m_pWebSocketServer->close();
    //clean out all connected clients
    qDeleteAll(m_clients.begin(),m_clients.end());
    m_vsssInterface.clear();
}

void W3CServer::onNewConnection()
{
    QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();
    pSocket ->ignoreSslErrors();
    DEBUG("Server","Attemping to connect");

    // Connect socket textMessageReceived signal with server processTextMessage slot
    connect(pSocket, &QWebSocket::textMessageReceived, this, &W3CServer::processTextMessage);
    // Connect socket disconnected signal with server socketDisconnected slot
    connect(pSocket, &QWebSocket::disconnected, this, &W3CServer::socketDisconnected);

    // add socket to list of clients
    m_clients.insert(pSocket, new QMutex());
    W3CServer::m_nrOfClients++;
}

void W3CServer::processTextMessage(const QString& message)
{

    DEBUG("Server","Message received");
    TRACE("Server", message);

    QWebSocket *zeClient = qobject_cast<QWebSocket *> (sender());
    if (m_clients.contains(zeClient))
    {
        // we need a mutex per client .
        QMutex* mutex = m_clients.find(zeClient).value();
        QPointer<WebSocketWrapper> socketWrapper = new WebSocketWrapper(zeClient, mutex);
        startRequestProcess(socketWrapper, message);
    }
    else
    {
        WARNING("Server","Fatal connection error, Websocket client not found.");
    }
}

void W3CServer::socketDisconnected()
{
    QWebSocket *zeClient = qobject_cast<QWebSocket *> (sender());

    DEBUG("Server","Socket disconnected");// : " + zeClient);

    //remove from client list and delete from heap
    if (zeClient)
    {
        m_clients.remove(zeClient); //TODO: do we need to call delete in mutex object here ?
        zeClient->deleteLater();
        W3CServer::m_nrOfClients--;
    }
}

void W3CServer::onSslErrors(const QList<QSslError> &l)
{
    TRACE("Server","SSL Error occurred."); // Change to WARNING
}

void W3CServer::startRequestProcess(WebSocketWrapper* sw, const QString& message)
{
    ProcessRequestTask* requesttask = new ProcessRequestTask(sw, m_vsssInterface, message, true);
    // QThreadPool takes ownership and deletes 'requesttask' automatically

    if(!QThreadPool::globalInstance()->tryStart(requesttask))
    {
        WARNING("Server","Failed to start thread! Active threads : " + QString::number(QThreadPool::globalInstance()->activeThreadCount()));
        WARNING("Server","Max threads alloved : " + QString::number(QThreadPool::globalInstance()->maxThreadCount()));
    }
    else
    {
        DEBUG("Server","New thread started! Active threads : " + QString::number(QThreadPool::globalInstance()->activeThreadCount()));
    }
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <memory>

#include<boost/filesystem.hpp>

#include <QMessageBox>
#include <QFileDialog>

#include "logging/Logger.h"
#include "logging/Logging.h"
#include "logging/ConsoleAppender.h"
#include "logging/FileAppender.h"
#include "tilegen/TileGenerator.h"
#include "tilegen/partition/TilePartitionerNoise.h"

MainWindow::MainWindow(QWidget *parent_) :
    QMainWindow(parent_),
    mUi(new Ui::MainWindow),
    mOptionsEditor(new OptionsEditor(this))
{
    mScene = new QGraphicsScene(this);

    mUi->setupUi(this);
    mUi->progressBar->setRange(0, 100);
    mUi->progressBar->setValue(0);

    openOptionsEditor();

    connect(mUi->generateButton, SIGNAL(pressed()), this, SLOT(generate()));
    connect(mUi->comboBox, SIGNAL(activated(const QString&)), this, SLOT(displayTilesetPreview(const QString&)));
    connect(mUi->actionLoadOptions, SIGNAL(triggered()), this, SLOT(loadOptionsFromFile()));
    connect(mUi->actionSaveOutput, SIGNAL(triggered()), this, SLOT(saveOutput()));
    connect(mUi->actionOpenOptionsEditor, SIGNAL(triggered()), this, SLOT(openOptionsEditor()));
}

MainWindow::~MainWindow()
{
    delete mUi;
}

void MainWindow::generate()
{
    if (mTilesetGenerator == nullptr)
    {
        QMessageBox error_message;
        error_message.critical(this, "Error during tileset generation", QString("You have to select options file before clicking 'Generate...' button"));
        return;
    }

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();

    mTilesetGenerator->generate([this](const sf::Texture& output, std::string filename)
    {
        const sf::Image source_image = output.copyToImage();

        const auto basename = filename.substr(filename.rfind('/') + 1);
        const auto qimage = convertSfImageToQImage(source_image);
        mPreviewImages.emplace(std::make_pair(basename,
                                             std::make_pair(filename, std::move(qimage))));
    });

    initializePreviewArea();
    displayTilesetPreview();
}

void MainWindow::saveOutput()
{
    if (mOptionsEditor->useDefaultOuputDir())
    {
        mOptions.relativeOutputDirectory = mOriginalOptions.relativeOutputDirectory;
    }
    else
    {
        QString chosen_path = QFileDialog::getExistingDirectory(this, tr("Select output dir"));
        mOptions.relativeOutputDirectory = chosen_path.toLocal8Bit().constData();
    }

    if (mPreviewImages.empty())
    {
        QMessageBox warning_message;
        warning_message.warning(this, "Warning", QString("You have to generate tileset before saving it"));
        return;
    }

    // set to mOptions.relativeOutputDirectory not part of preview_image filepath,
    // cause it is is used to generate that filepath and it makes
    // modifying output dir for the whole output a lot easier
    const std::string image_dir = mOptions.relativeOutputDirectory;
    boost::filesystem::create_directories(image_dir);
    boost::filesystem::path p(image_dir);
    for (const auto& preview_image : mPreviewImages)
    {
        p.append(preview_image.first);
        if (!preview_image.second.second.save(QString(p.string().c_str())))
        {
            QMessageBox critical_error_message;
            critical_error_message.critical(this, "Error during saving tilesets", QString("Couldn't save tileset image"));
            return;
        }
        p.remove_filename();
    }

    mTilesetGenerator->metaOutput.writeAll(mOptions);

    QMessageBox success_message;
    success_message.information(this, "Saved!", QString("Output has been saved successfully"));
}

void MainWindow::resetOptions()
{
    mOptions = mOriginalOptions;
    mOptionsEditor->setOptions(&mOptions);
}

void MainWindow::loadOptionsFromFile()
{
    QString chosen_path = QFileDialog::getOpenFileName(this,
                                                     tr("Select options file"));
    if (chosen_path.isEmpty())
        return;

    mUi->currentOptionsPath->setText(QString(chosen_path));

    // TODO(hryniuk): make OptionsManager throw custom exception, catch it here
    // and show QMessageBox with a proper error message
    mOptionsManager = std::make_unique<OptionsManager>(chosen_path.toLocal8Bit().constData());
    mOriginalOptions = mOptionsManager->getOptions();

    resetOptions();

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();
    mScene->clear();
}

void MainWindow::displayTilesetPreview(const QString& name)
{
    const QImage preview_image = name.isEmpty() ? (mPreviewImages.begin())->second.second : mPreviewImages.at(name.toLocal8Bit().constData()).second;
    const QPixmap pixmap = QPixmap::fromImage(preview_image);

    mScene->clear();
    mScene->addPixmap(pixmap);
    mScene->setSceneRect(pixmap.rect());
    mUi->tilesetPreview->setScene(mScene);
}

void MainWindow::openOptionsEditor()
{
    mOptionsEditor->show();
    addDockWidget(Qt::RightDockWidgetArea, mOptionsEditor);
}

void MainWindow::initializePreviewArea()
{
    mUi->comboBox->addItems([this]()
    {
        QStringList list;
        for (const auto name : mPreviewImages)
        {
            list << QString(name.first.c_str());
        }
        return list;
    }());
}

QImage MainWindow::convertSfImageToQImage(const sf::Image& source_image)
{

    const sf::Vector2u output_image_size = source_image.getSize();
    QImage output_image(output_image_size.x, output_image_size.y, QImage::Format_RGB32);

    for (int y = 0; y < output_image_size.y; ++y)
    {
        for (int x = 0; x < output_image_size.x; ++x)
        {
            const sf::Color sfml_color = source_image.getPixel(x, y);
            const QColor color{sfml_color.r, sfml_color.g, sfml_color.b, sfml_color.a};
            output_image.setPixel(x, y, color.rgba());
        }
        const int progress_value = 100 * (static_cast<double>(y) / static_cast<double>(output_image_size.y));
        mUi->progressBar->setValue(progress_value);
    }
    mUi->progressBar->setValue(100);

    return output_image;
}

void MainWindow::resetTilesetGenerator()
{
    std::unique_ptr<tilegen::partition::TilePartitionerBase> tileset_partitioner =
        std::make_unique<tilegen::partition::TilePartitionerNoise>(mOptions);

    mTilesetGenerator = std::make_unique<tilegen::TilesetGenerator>(mOptions, std::move(tileset_partitioner));
}
<commit_msg>Fix spelling<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <memory>

#include<boost/filesystem.hpp>

#include <QMessageBox>
#include <QFileDialog>

#include "logging/Logger.h"
#include "logging/Logging.h"
#include "logging/ConsoleAppender.h"
#include "logging/FileAppender.h"
#include "tilegen/TileGenerator.h"
#include "tilegen/partition/TilePartitionerNoise.h"

MainWindow::MainWindow(QWidget *parent_) :
    QMainWindow(parent_),
    mUi(new Ui::MainWindow),
    mOptionsEditor(new OptionsEditor(this))
{
    mScene = new QGraphicsScene(this);

    mUi->setupUi(this);
    mUi->progressBar->setRange(0, 100);
    mUi->progressBar->setValue(0);

    openOptionsEditor();

    connect(mUi->generateButton, SIGNAL(pressed()), this, SLOT(generate()));
    connect(mUi->comboBox, SIGNAL(activated(const QString&)), this, SLOT(displayTilesetPreview(const QString&)));
    connect(mUi->actionLoadOptions, SIGNAL(triggered()), this, SLOT(loadOptionsFromFile()));
    connect(mUi->actionSaveOutput, SIGNAL(triggered()), this, SLOT(saveOutput()));
    connect(mUi->actionOpenOptionsEditor, SIGNAL(triggered()), this, SLOT(openOptionsEditor()));
}

MainWindow::~MainWindow()
{
    delete mUi;
}

void MainWindow::generate()
{
    if (mTilesetGenerator == nullptr)
    {
        QMessageBox error_message;
        error_message.critical(this, "Error during tileset generation", QString("You must select an options file before clicking the 'Generate...' button"));
        return;
    }

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();

    mTilesetGenerator->generate([this](const sf::Texture& output, std::string filename)
    {
        const sf::Image source_image = output.copyToImage();

        const auto basename = filename.substr(filename.rfind('/') + 1);
        const auto qimage = convertSfImageToQImage(source_image);
        mPreviewImages.emplace(std::make_pair(basename,
                                             std::make_pair(filename, std::move(qimage))));
    });

    initializePreviewArea();
    displayTilesetPreview();
}

void MainWindow::saveOutput()
{
    if (mOptionsEditor->useDefaultOuputDir())
    {
        mOptions.relativeOutputDirectory = mOriginalOptions.relativeOutputDirectory;
    }
    else
    {
        QString chosen_path = QFileDialog::getExistingDirectory(this, tr("Select output directory"));
        mOptions.relativeOutputDirectory = chosen_path.toLocal8Bit().constData();
    }

    if (mPreviewImages.empty())
    {
        QMessageBox warning_message;
        warning_message.warning(this, "Warning", QString("You must generate a tileset before saving it"));
        return;
    }

    // set to mOptions.relativeOutputDirectory not part of preview_image filepath,
    // cause it is is used to generate that filepath and it makes
    // modifying output dir for the whole output a lot easier
    const std::string image_dir = mOptions.relativeOutputDirectory;
    boost::filesystem::create_directories(image_dir);
    boost::filesystem::path p(image_dir);
    for (const auto& preview_image : mPreviewImages)
    {
        p.append(preview_image.first);
        if (!preview_image.second.second.save(QString(p.string().c_str())))
        {
            QMessageBox critical_error_message;
            critical_error_message.critical(this, "Error during saving tilesets", QString("Couldn't save tileset image"));
            return;
        }
        p.remove_filename();
    }

    mTilesetGenerator->metaOutput.writeAll(mOptions);

    QMessageBox success_message;
    success_message.information(this, "Saved!", QString("Output has been saved successfully"));
}

void MainWindow::resetOptions()
{
    mOptions = mOriginalOptions;
    mOptionsEditor->setOptions(&mOptions);
}

void MainWindow::loadOptionsFromFile()
{
    QString chosen_path = QFileDialog::getOpenFileName(this,
                                                     tr("Select options file"));
    if (chosen_path.isEmpty())
        return;

    mUi->currentOptionsPath->setText(QString(chosen_path));

    // TODO(hryniuk): make OptionsManager throw custom exception, catch it here
    // and show QMessageBox with a proper error message
    mOptionsManager = std::make_unique<OptionsManager>(chosen_path.toLocal8Bit().constData());
    mOriginalOptions = mOptionsManager->getOptions();

    resetOptions();

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();
    mScene->clear();
}

void MainWindow::displayTilesetPreview(const QString& name)
{
    const QImage preview_image = name.isEmpty() ? (mPreviewImages.begin())->second.second : mPreviewImages.at(name.toLocal8Bit().constData()).second;
    const QPixmap pixmap = QPixmap::fromImage(preview_image);

    mScene->clear();
    mScene->addPixmap(pixmap);
    mScene->setSceneRect(pixmap.rect());
    mUi->tilesetPreview->setScene(mScene);
}

void MainWindow::openOptionsEditor()
{
    mOptionsEditor->show();
    addDockWidget(Qt::RightDockWidgetArea, mOptionsEditor);
}

void MainWindow::initializePreviewArea()
{
    mUi->comboBox->addItems([this]()
    {
        QStringList list;
        for (const auto name : mPreviewImages)
        {
            list << QString(name.first.c_str());
        }
        return list;
    }());
}

QImage MainWindow::convertSfImageToQImage(const sf::Image& source_image)
{

    const sf::Vector2u output_image_size = source_image.getSize();
    QImage output_image(output_image_size.x, output_image_size.y, QImage::Format_RGB32);

    for (int y = 0; y < output_image_size.y; ++y)
    {
        for (int x = 0; x < output_image_size.x; ++x)
        {
            const sf::Color sfml_color = source_image.getPixel(x, y);
            const QColor color{sfml_color.r, sfml_color.g, sfml_color.b, sfml_color.a};
            output_image.setPixel(x, y, color.rgba());
        }
        const int progress_value = 100 * (static_cast<double>(y) / static_cast<double>(output_image_size.y));
        mUi->progressBar->setValue(progress_value);
    }
    mUi->progressBar->setValue(100);

    return output_image;
}

void MainWindow::resetTilesetGenerator()
{
    std::unique_ptr<tilegen::partition::TilePartitionerBase> tileset_partitioner =
        std::make_unique<tilegen::partition::TilePartitionerNoise>(mOptions);

    mTilesetGenerator = std::make_unique<tilegen::TilesetGenerator>(mOptions, std::move(tileset_partitioner));
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <memory>

#include<boost/filesystem.hpp>

#include <QMessageBox>
#include <QFileDialog>

#include "logging/Logger.h"
#include "logging/Logging.h"
#include "logging/ConsoleAppender.h"
#include "logging/FileAppender.h"
#include "tilegen/TileGenerator.h"
#include "tilegen/partition/TilePartitionerNoise.h"

MainWindow::MainWindow(QWidget *parent_) :
    QMainWindow(parent_),
    mUi(new Ui::MainWindow),
    mOptionsEditor(new OptionsEditor(this))
{
    mScene = new QGraphicsScene(this);

    mUi->setupUi(this);
    mUi->progressBar->setRange(0, 100);
    mUi->progressBar->setValue(0);

    openOptionsEditor();

    connect(mUi->generateButton, SIGNAL(pressed()), this, SLOT(generate()));
    connect(mUi->comboBox, SIGNAL(activated(const QString&)), this, SLOT(displayTilesetPreview(const QString&)));
    connect(mUi->actionLoadOptions, SIGNAL(triggered()), this, SLOT(loadOptionsFromFile()));
    connect(mUi->actionSaveOutput, SIGNAL(triggered()), this, SLOT(saveOutput()));
    connect(mUi->actionOpenOptionsEditor, SIGNAL(triggered()), this, SLOT(openOptionsEditor()));
}

MainWindow::~MainWindow()
{
    delete mUi;
}

void MainWindow::generate()
{
    if (mTilesetGenerator == nullptr)
    {
        QMessageBox error_message;
        error_message.critical(this, "Error during tileset generation", QString("You must select an options file before clicking the 'Generate...' button"));
        return;
    }

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();

    mTilesetGenerator->generate([this](const sf::Texture& output, std::string filename)
    {
        const sf::Image source_image = output.copyToImage();

        const auto basename = filename.substr(filename.rfind('/') + 1);
        const auto qimage = convertSfImageToQImage(source_image);
        mPreviewImages.emplace(std::make_pair(basename,
                                             std::make_pair(filename, std::move(qimage))));
    });

    initializePreviewArea();
    displayTilesetPreview();
}

void MainWindow::saveOutput()
{
    if (mOptionsEditor->useDefaultOuputDir())
    {
        mOptions.relativeOutputDirectory = mOriginalOptions.relativeOutputDirectory;
    }
    else
    {
        QString chosen_path = QFileDialog::getExistingDirectory(this, tr("Select output directory"));
        mOptions.relativeOutputDirectory = chosen_path.toLocal8Bit().constData();
    }

    if (mPreviewImages.empty())
    {
        QMessageBox warning_message;
        warning_message.warning(this, "Warning", QString("You must generate a tileset before saving it"));
        return;
    }

    // set to mOptions.relativeOutputDirectory not part of preview_image filepath,
    // cause it is is used to generate that filepath and it makes
    // modifying output dir for the whole output a lot easier
    const std::string image_dir = mOptions.relativeOutputDirectory;
    boost::filesystem::create_directories(image_dir);
    boost::filesystem::path p(image_dir);
    for (const auto& preview_image : mPreviewImages)
    {
        p.append(preview_image.first);
        if (!preview_image.second.second.save(QString(p.string().c_str())))
        {
            QMessageBox critical_error_message;
            critical_error_message.critical(this, "Error during saving tilesets", QString("Couldn't save tileset image"));
            return;
        }
        p.remove_filename();
    }

    mTilesetGenerator->metaOutput.writeAll(mOptions);

    QMessageBox success_message;
    success_message.information(this, "Saved!", QString("Output has been saved successfully"));
}

void MainWindow::resetOptions()
{
    mOptions = mOriginalOptions;
    mOptionsEditor->setOptions(&mOptions);
}

void MainWindow::loadOptionsFromFile()
{
    QString chosen_path = QFileDialog::getOpenFileName(this,
                                                     tr("Select options file"));
    if (chosen_path.isEmpty())
        return;

    mUi->currentOptionsPath->setText(QString(chosen_path));

    // TODO(hryniuk): make OptionsManager throw custom exception, catch it here
    // and show QMessageBox with a proper error message
    mOptionsManager = std::make_unique<OptionsManager>(chosen_path.toLocal8Bit().constData());
    mOriginalOptions = mOptionsManager->getOptions();

    resetOptions();

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();
    mScene->clear();
}

void MainWindow::displayTilesetPreview(const QString& name)
{
    const QImage preview_image = name.isEmpty() ? (mPreviewImages.begin())->second.second : mPreviewImages.at(name.toLocal8Bit().constData()).second;
    const QPixmap pixmap = QPixmap::fromImage(preview_image);

    mScene->clear();
    mScene->addPixmap(pixmap);
    mScene->setSceneRect(pixmap.rect());
    mUi->tilesetPreview->setScene(mScene);
}

void MainWindow::openOptionsEditor()
{
    mOptionsEditor->show();
    addDockWidget(Qt::RightDockWidgetArea, mOptionsEditor);
}

void MainWindow::initializePreviewArea()
{
    mUi->comboBox->addItems([this]()
    {
        QStringList list;
        for (const auto name : mPreviewImages)
        {
            list << QString(name.first.c_str());
        }
        return list;
    }());
}

QImage MainWindow::convertSfImageToQImage(const sf::Image& source_image)
{

    const sf::Vector2u output_image_size = source_image.getSize();
    QImage output_image(output_image_size.x, output_image_size.y, QImage::Format_RGB32);

    for (int y = 0; y < output_image_size.y; ++y)
    {
        for (int x = 0; x < output_image_size.x; ++x)
        {
            const sf::Color sfml_color = source_image.getPixel(x, y);
            const QColor color{sfml_color.r, sfml_color.g, sfml_color.b, sfml_color.a};
            output_image.setPixel(x, y, color.rgba());
        }
        const int progress_value = 100 * (static_cast<double>(y) / static_cast<double>(output_image_size.y));
        mUi->progressBar->setValue(progress_value);
    }
    mUi->progressBar->setValue(100);

    return output_image;
}

void MainWindow::resetTilesetGenerator()
{
    std::unique_ptr<tilegen::partition::TilePartitionerBase> tileset_partitioner =
        std::make_unique<tilegen::partition::TilePartitionerNoise>(mOptions);

    mTilesetGenerator = std::make_unique<tilegen::TilesetGenerator>(mOptions, std::move(tileset_partitioner));
}
<commit_msg>Use boost::filesystem to get filename<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <memory>

#include<boost/filesystem.hpp>

#include <QMessageBox>
#include <QFileDialog>

#include "logging/Logger.h"
#include "logging/Logging.h"
#include "logging/ConsoleAppender.h"
#include "logging/FileAppender.h"
#include "tilegen/TileGenerator.h"
#include "tilegen/partition/TilePartitionerNoise.h"

MainWindow::MainWindow(QWidget *parent_) :
    QMainWindow(parent_),
    mUi(new Ui::MainWindow),
    mOptionsEditor(new OptionsEditor(this))
{
    mScene = new QGraphicsScene(this);

    mUi->setupUi(this);
    mUi->progressBar->setRange(0, 100);
    mUi->progressBar->setValue(0);

    openOptionsEditor();

    connect(mUi->generateButton, SIGNAL(pressed()), this, SLOT(generate()));
    connect(mUi->comboBox, SIGNAL(activated(const QString&)), this, SLOT(displayTilesetPreview(const QString&)));
    connect(mUi->actionLoadOptions, SIGNAL(triggered()), this, SLOT(loadOptionsFromFile()));
    connect(mUi->actionSaveOutput, SIGNAL(triggered()), this, SLOT(saveOutput()));
    connect(mUi->actionOpenOptionsEditor, SIGNAL(triggered()), this, SLOT(openOptionsEditor()));
}

MainWindow::~MainWindow()
{
    delete mUi;
}

void MainWindow::generate()
{
    if (mTilesetGenerator == nullptr)
    {
        QMessageBox error_message;
        error_message.critical(this, "Error during tileset generation", QString("You must select an options file before clicking the 'Generate...' button"));
        return;
    }

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();

    mTilesetGenerator->generate([this](const sf::Texture& output, std::string filepath)
    {
        const sf::Image source_image = output.copyToImage();

        const auto filename = boost::filesystem::path(filepath).filename().string();
        const auto qimage = convertSfImageToQImage(source_image);
        mPreviewImages.emplace(std::make_pair(filename,
                                             std::make_pair(filepath, std::move(qimage))));
    });

    initializePreviewArea();
    displayTilesetPreview();
}

void MainWindow::saveOutput()
{
    if (mOptionsEditor->useDefaultOuputDir())
    {
        mOptions.relativeOutputDirectory = mOriginalOptions.relativeOutputDirectory;
    }
    else
    {
        QString chosen_path = QFileDialog::getExistingDirectory(this, tr("Select output directory"));
        mOptions.relativeOutputDirectory = chosen_path.toLocal8Bit().constData();
    }

    if (mPreviewImages.empty())
    {
        QMessageBox warning_message;
        warning_message.warning(this, "Warning", QString("You must generate a tileset before saving it"));
        return;
    }

    // set to mOptions.relativeOutputDirectory not part of preview_image filepath,
    // cause it is is used to generate that filepath and it makes
    // modifying output dir for the whole output a lot easier
    const std::string image_dir = mOptions.relativeOutputDirectory;
    boost::filesystem::create_directories(image_dir);
    boost::filesystem::path p(image_dir);
    for (const auto& preview_image : mPreviewImages)
    {
        p.append(preview_image.first);
        if (!preview_image.second.second.save(QString(p.string().c_str())))
        {
            QMessageBox critical_error_message;
            critical_error_message.critical(this, "Error during saving tilesets", QString("Couldn't save tileset image"));
            return;
        }
        p.remove_filename();
    }

    mTilesetGenerator->metaOutput.writeAll(mOptions);

    QMessageBox success_message;
    success_message.information(this, "Saved!", QString("Output has been saved successfully"));
}

void MainWindow::resetOptions()
{
    mOptions = mOriginalOptions;
    mOptionsEditor->setOptions(&mOptions);
}

void MainWindow::loadOptionsFromFile()
{
    QString chosen_path = QFileDialog::getOpenFileName(this,
                                                     tr("Select options file"));
    if (chosen_path.isEmpty())
        return;

    mUi->currentOptionsPath->setText(QString(chosen_path));

    // TODO(hryniuk): make OptionsManager throw custom exception, catch it here
    // and show QMessageBox with a proper error message
    mOptionsManager = std::make_unique<OptionsManager>(chosen_path.toLocal8Bit().constData());
    mOriginalOptions = mOptionsManager->getOptions();

    resetOptions();

    resetTilesetGenerator();

    mUi->comboBox->clear();
    mPreviewImages.clear();
    mScene->clear();
}

void MainWindow::displayTilesetPreview(const QString& name)
{
    const QImage preview_image = name.isEmpty() ? (mPreviewImages.begin())->second.second : mPreviewImages.at(name.toLocal8Bit().constData()).second;
    const QPixmap pixmap = QPixmap::fromImage(preview_image);

    mScene->clear();
    mScene->addPixmap(pixmap);
    mScene->setSceneRect(pixmap.rect());
    mUi->tilesetPreview->setScene(mScene);
}

void MainWindow::openOptionsEditor()
{
    mOptionsEditor->show();
    addDockWidget(Qt::RightDockWidgetArea, mOptionsEditor);
}

void MainWindow::initializePreviewArea()
{
    mUi->comboBox->addItems([this]()
    {
        QStringList list;
        for (const auto name : mPreviewImages)
        {
            list << QString(name.first.c_str());
        }
        return list;
    }());
}

QImage MainWindow::convertSfImageToQImage(const sf::Image& source_image)
{

    const sf::Vector2u output_image_size = source_image.getSize();
    QImage output_image(output_image_size.x, output_image_size.y, QImage::Format_RGB32);

    for (int y = 0; y < output_image_size.y; ++y)
    {
        for (int x = 0; x < output_image_size.x; ++x)
        {
            const sf::Color sfml_color = source_image.getPixel(x, y);
            const QColor color{sfml_color.r, sfml_color.g, sfml_color.b, sfml_color.a};
            output_image.setPixel(x, y, color.rgba());
        }
        const int progress_value = 100 * (static_cast<double>(y) / static_cast<double>(output_image_size.y));
        mUi->progressBar->setValue(progress_value);
    }
    mUi->progressBar->setValue(100);

    return output_image;
}

void MainWindow::resetTilesetGenerator()
{
    std::unique_ptr<tilegen::partition::TilePartitionerBase> tileset_partitioner =
        std::make_unique<tilegen::partition::TilePartitionerNoise>(mOptions);

    mTilesetGenerator = std::make_unique<tilegen::TilesetGenerator>(mOptions, std::move(tileset_partitioner));
}
<|endoftext|>


<commit_before>#include "GameManager.h"
#include "Player.h"
#include "ClientSession.h"
#include "LogicContext.h"
#include "HmmoApplication.h"
#include "Match.h"

GameManager* GameManager::instance = nullptr;

GameManager * GameManager::getInstance()
{
	if (instance == nullptr)
		instance = new GameManager();

	return instance;
}

void GameManager::getRandomHeros(std::shared_ptr<Player>& player, OUT std::vector<HeroClass>& classes)
{
	//TODO : ߿ DB ޾ƿ     ְԲ
	classes.clear();
	std::vector<Hero> heros;

	playerMatchMap[player->getId()]->randomHero(player);
	playerMatchMap[player->getId()]->getHeroData(player, heros);

	for (int i = 0; i < 4; i++)
	{
		classes.push_back(heros[i].type);
	}
}

int GameManager::isValidAccount(const char * id, int idLength, const char * password, int pwdLength)
{
	//  üũ - ߿ DB üũϰԲ
	if (strncmp("test", id, idLength) == 0 &&
		strncmp("12345", password, pwdLength) == 0)
	{
		return 0;
	}

	if (strncmp("test2", id, idLength) == 0 &&
		strncmp("12345", password, pwdLength) == 0)
	{
		return 1;
	}

	return -1;
}

void GameManager::addMatchPendingList(std::shared_ptr<Player>& player)
{
	matchPendingList.push_back(player);
}

void GameManager::update()
{
	//match  player 2 ̸̻ ⸦ ϳ
	//ϴ connect  Ǵ
	while (matchPendingList.size() >= 2)
	{
		auto player = matchPendingList.front();
		matchPendingList.pop_front();
		auto player2 = matchPendingList.front();
		matchPendingList.pop_front();

		// κ ߺ ġ   Ǵϰ
		Match* newMatch = new Match(player, player2);

		matchList.push_back(newMatch);
		playerMatchMap[player->getId()] = newMatch;
		playerMatchMap[player2->getId()] = newMatch;

		MatchStart start;
		start.type = Type::MATCH_START;

		auto context = new PacketContext<MatchStart>();
		context->packet = start;
		context->session = player->getSession();
		skylark::postContext(HmmoApplication::getInstance()->getIoPort(), context, 0);

		auto context2 = new PacketContext<MatchStart>();
		context2->packet = start;
		context2->session = player2->getSession();
		skylark::postContext(HmmoApplication::getInstance()->getIoPort(), context2, 0);
	}
}

void GameManager::placeHero(std::shared_ptr<Player>& player, int posNum, Point * points)
{
	playerMatchMap[player->getId()]->placeHero(player, posNum, points);
}
<commit_msg>add turn data<commit_after>#include "GameManager.h"
#include "Player.h"
#include "ClientSession.h"
#include "LogicContext.h"
#include "HmmoApplication.h"
#include "Match.h"

GameManager* GameManager::instance = nullptr;

GameManager * GameManager::getInstance()
{
	if (instance == nullptr)
		instance = new GameManager();

	return instance;
}

void GameManager::getRandomHeros(std::shared_ptr<Player>& player, OUT std::vector<HeroClass>& classes)
{
	//TODO : ߿ DB ޾ƿ     ְԲ
	classes.clear();
	std::vector<Hero> heros;

	playerMatchMap[player->getId()]->randomHero(player);
	playerMatchMap[player->getId()]->getHeroData(player, heros);

	for (int i = 0; i < 4; i++)
	{
		classes.push_back(heros[i].type);
	}
}

int GameManager::isValidAccount(const char * id, int idLength, const char * password, int pwdLength)
{
	//  üũ - ߿ DB üũϰԲ
	if (strncmp("test", id, idLength) == 0 &&
		strncmp("12345", password, pwdLength) == 0)
	{
		return 0;
	}

	if (strncmp("test2", id, idLength) == 0 &&
		strncmp("12345", password, pwdLength) == 0)
	{
		return 1;
	}

	return -1;
}

void GameManager::addMatchPendingList(std::shared_ptr<Player>& player)
{
	matchPendingList.push_back(player);
}

void GameManager::update()
{
	//match  player 2 ̸̻ ⸦ ϳ
	//ϴ connect  Ǵ
	while (matchPendingList.size() >= 2)
	{
		auto player = matchPendingList.front();
		matchPendingList.pop_front();
		auto player2 = matchPendingList.front();
		matchPendingList.pop_front();

		// κ ߺ ġ   Ǵϰ
		Match* newMatch = new Match(player, player2);

		matchList.push_back(newMatch);
		playerMatchMap[player->getId()] = newMatch;
		playerMatchMap[player2->getId()] = newMatch;

		MatchStart start;
		start.type = Type::MATCH_START;
		start.turn = 0;

		auto context = new PacketContext<MatchStart>();
		context->packet = start;
		context->session = player->getSession();
		skylark::postContext(HmmoApplication::getInstance()->getIoPort(), context, 0);

		start.turn = 1;

		auto context2 = new PacketContext<MatchStart>();
		context2->packet = start;
		context2->session = player2->getSession();
		skylark::postContext(HmmoApplication::getInstance()->getIoPort(), context2, 0);
	}
}

void GameManager::placeHero(std::shared_ptr<Player>& player, int posNum, Point * points)
{
	playerMatchMap[player->getId()]->placeHero(player, posNum, points);
}
<|endoftext|>


<commit_before>#ifndef SINGLETEXTEDIT_HH
#define SINGLETEXTEDIT_HH

#include <QTextEdit>
#include <QKeyEvent>

struct SingleTextEdit : QTextEdit {
	SingleTextEdit(QWidget *parent = nullptr) : QTextEdit(parent) {
		setTabChangesFocus(true);
		setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
		setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
		setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
 	}
	void keyPressEvent(QKeyEvent *event) {
		if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
			event->ignore();
		else
			QTextEdit::keyPressEvent(event);
	}
	virtual QSize minimumSizeHint () const {
		return sizeHint();
	}
	virtual QSize sizeHint() const {
		QFontMetrics fm(font());
		int h = qMax(fm.height(), 14) + 4;
		return QSize{100,h};
	}
	void wheelEvent(QWheelEvent *e) {
		e->ignore();
	}
};

#endif /* SINGLETEXTEDIT_HH */
<commit_msg>make SingleTextEdit a Q_OBJECT<commit_after>#ifndef SINGLETEXTEDIT_HH
#define SINGLETEXTEDIT_HH

#include <QTextEdit>
#include <QKeyEvent>

struct SingleTextEdit : QTextEdit {
	SingleTextEdit(QWidget *parent = nullptr) : QTextEdit(parent) {
		setTabChangesFocus(true);
		setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
		setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
		setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
 	}
	virtual void keyPressEvent(QKeyEvent *event) override {
		if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
			event->ignore();
		else
			QTextEdit::keyPressEvent(event);
	}
	virtual QSize minimumSizeHint () const override {
		return sizeHint();
	}
	virtual QSize sizeHint() const override {
		QFontMetrics fm(font());
		int h = qMax(fm.height(), 14) + 4;
		return QSize{100,h};
	}
	virtual void wheelEvent(QWheelEvent *e) override {
		e->ignore();
	}
private:
	Q_OBJECT
};

#endif /* SINGLETEXTEDIT_HH */
<|endoftext|>


<commit_before>/**
 * \file t_LA.cpp
 * \brief
 * \date Oct 13, 2010
 * \author Vernkin Chen
 */
#include <ilplib.hpp>
#include <string>
#include <util/ustring/UString.h>

#include "la_bin_test_def.h"

using namespace std;
using namespace la;
using namespace izenelib::util;

void testTokenizer()
{
    Tokenizer tokenizer;
    string input;
    do {
        cout << "Input ('x' to exit): ";
        getline( cin, input );
        if( input == "x" || input == "X" )
            break;

        UString ustr( input, IO_ENCODING );
        {
            TermList specialTerms;
            TermList primTerms;
            cout << "-------------- tokenize( query, specialTerms, primTerms ) ---------------" << endl;
            tokenizer.tokenize(ustr, specialTerms, primTerms );
            cout << "1.  SPECIAL TERMS" << endl;
            printTermList( specialTerms );
            cout << "2.  Primary TERMS" << endl;
            printTermList( primTerms );
        }

        {
            TermList rawTerms;
            cout << "-------------- tokenizeWhite( query, rawTerms ) ---------------" << endl;
            tokenizer.tokenizeWhite(ustr, rawTerms );
            printTermList( rawTerms );
        }

        {
            TermList primTerms;
            cout << "-------------- tokenize( query, primTerms ) ---------------" << endl;
            tokenizer.tokenize(ustr, primTerms );
            printTermList( primTerms );
        }

    } while( true );
}

void printUsage()
{
    cout << "Usage: ./t_LA [tok | char | cn | en | kr | multi | ngram | matrix | token(token analyzer) | none(empty analyzer)]" << endl;
}

boost::shared_ptr<Analyzer> getCMAAnalyzer()
{
    ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() );
    cana->setLabelMode();
    cana->setAnalysisType(ChineseAnalyzer::minimum_match);
    boost::shared_ptr<Analyzer> cbana( cana );
    return cbana;
}

boost::shared_ptr<Analyzer> getKMAAnalyzer()
{
    KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() );
    kana->setLabelMode();
    boost::shared_ptr<Analyzer> kbana( kana );
    return kbana;
}

int main( int argc, char** argv )
{
    if( argc < 2 )
    {
        printUsage();
        exit(1);
    }

    string type = argv[1];
    if( type == "tok" )
    {
        testTokenizer();
        exit(0);
    }

    LA la;
    boost::shared_ptr<Analyzer> analyzer;

    if( type == "char" )
    {
        cout << "CharAnalyzer Addition Params: [all | part]" << endl;
        CharAnalyzer* ana = new CharAnalyzer;
        for( int i = 2; i < argc; ++i )
        {
            string arg = argv[i];
            if( arg == "all" )
                ana->setSeparateAll(true);
            else if( arg == "part" )
                ana->setSeparateAll(false);
            else
                cerr << "Invalid Parameter: " << arg << endl;
        }

        analyzer.reset( ana );
    }
    else if( type == "cn" )
    {
        cout << "ChineseAnalyzer Addition Params: [max | min | mmm | min_u] [label | index | stop]" << endl;
        ChineseAnalyzer* ana = new ChineseAnalyzer( getCmaKnowledgePath() );
        ana->setLabelMode();
        ana->setCaseSensitive();
        ana->setAnalysisType(ChineseAnalyzer::minimum_match);

        for( int i = 2; i < argc; ++i )
        {
            string arg = argv[i];
            if( arg == "max" )
                ana->setAnalysisType(ChineseAnalyzer::maximum_match);
            else if( arg == "min" )
                ana->setAnalysisType(ChineseAnalyzer::minimum_match);
            else if( arg == "min_u" )
                ana->setAnalysisType(ChineseAnalyzer::minimum_match_with_unigram);
            else if( arg == "mmm" )
                ana->setAnalysisType(ChineseAnalyzer::maximum_entropy);
            else if( arg == "label" )
                ana->setLabelMode();
            else if( arg == "index" )
                ana->setIndexMode();
            else if( arg == "stop")
                ana->setRemoveStopwords();
            else
                cerr << "Invalid Parameter: " << arg << endl;
        }

        analyzer.reset( ana );
    }
    else if( type == "en" )
    {
        analyzer.reset( new EnglishAnalyzer );
    }
    else if( type == "kr" )
    {
        cout << "KoreanAnalyzer Addition Params: [label | index]" << endl;
        KoreanAnalyzer* ana = new KoreanAnalyzer( getKmaKnowledgePath() );
        ana->setLabelMode();
        for( int i = 2; i < argc; ++i )
        {
            string arg = argv[i];
            if( arg == "label" )
                ana->setLabelMode();
            else if( arg == "index" )
                ana->setIndexMode();
            else
                cerr << "Invalid Parameter: " << arg << endl;
        }
        analyzer.reset( ana );
    }
    else if( type == "multi" )
    {
        ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() );
        cana->setLabelMode();
        cana->setAnalysisType(ChineseAnalyzer::minimum_match);
        boost::shared_ptr<Analyzer> cbana( cana );

        KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() );
        kana->setLabelMode();
        boost::shared_ptr<Analyzer> kbana( kana );

        EnglishAnalyzer* eana = new EnglishAnalyzer;
        boost::shared_ptr<Analyzer> ebana( eana );

        MultiLanguageAnalyzer* mana = new MultiLanguageAnalyzer;
        mana->setDefaultAnalyzer( kbana );
        mana->setAnalyzer( MultiLanguageAnalyzer::CHINESE, cbana );
        mana->setAnalyzer( MultiLanguageAnalyzer::ENGLISH, ebana );

        analyzer.reset( mana );
    }
    else if( type == "ngram" )
    {
        cout << "NGramAnalyzer Addition Params: min max flag" << endl;
        int min = 2;
        int max = 3;
        if( argc > 2 )
            min = atoi( argv[2] );
        if( argc > 3 )
            max = atoi( argv[3] );
        if( min < 1 )
            min = 2;
        if( max < min )
            max = min + 1;
        unsigned int apartFlag = 0;
        if( argc > 4 )
            apartFlag = (unsigned int)atoi( argv[4] );

        cout << "[NGramAnalyzer] min = " << min << ", max = " << max << ", apartFlag = "
                << hex << apartFlag << endl;
        analyzer.reset( new NGramAnalyzer( 2, 3, 1024000, apartFlag ) );
    }
    else if( type == "matrix" )
    {
        analyzer.reset( new MatrixAnalyzer( true, true) );
    }
    else if( type == "token" )
    {
        analyzer.reset( new TokenAnalyzer );
    }
    else if( type == "none" )
    {
        // do nothing
    }
    else
    {
        cerr << "Unknown analyzer type: " << type << endl;
        exit(1);
    }

    bool toHalfWidthString = false;
    for( int i = 2; i < argc; ++i ) {
    	string arg = argv[i];
    	if (arg == "half-width") {
    		toHalfWidthString = true;
    	}
    }

    la.setAnalyzer( analyzer );
    string input;
    do {
        cout << "Input ('x' to exit): ";
        getline( cin, input );
        if( input == "x" || input == "X" )
            break;

        UString ustr( input, IO_ENCODING );

        if ( toHalfWidthString )
        {
			la::convertFull2HalfWidth(ustr);
			string str;
			ustr.convertString(str, UString::UTF_8);
			cout << "==> Input converted full-with chars to half-with :" << str << endl;
        }

        {
            TermList termList;
            cout << "-------------- process( query, termList ) ---------------" << endl;
            la.process( ustr, termList );
            printTermList( termList );

            cout << "-------------- toExpandedString ---------------" << endl;
            UString exp = toExpandedString(termList);
            exp.displayStringInfo(UString::UTF_8, cout);
            cout << endl;
        }

    } while( true );

    return 0;
}
<commit_msg>comments<commit_after>/**
 * \file t_LA.cpp
 * \brief
 * \date Oct 13, 2010
 * \author Vernkin Chen
 */
#include <ilplib.hpp>
#include <string>
#include <util/ustring/UString.h>

#include "la_bin_test_def.h"

using namespace std;
using namespace la;
using namespace izenelib::util;

void testTokenizer()
{
    Tokenizer tokenizer;
    string input;
    do {
        cout << "Input ('x' to exit): ";
        getline( cin, input );
        if( input == "x" || input == "X" )
            break;

        UString ustr( input, IO_ENCODING );
        {
            TermList specialTerms;
            TermList primTerms;
            cout << "-------------- tokenize( query, specialTerms, primTerms ) ---------------" << endl;
            tokenizer.tokenize(ustr, specialTerms, primTerms );
            cout << "1.  SPECIAL TERMS" << endl;
            printTermList( specialTerms );
            cout << "2.  Primary TERMS" << endl;
            printTermList( primTerms );
        }

        {
            TermList rawTerms;
            cout << "-------------- tokenizeWhite( query, rawTerms ) ---------------" << endl;
            tokenizer.tokenizeWhite(ustr, rawTerms );
            printTermList( rawTerms );
        }

        {
            TermList primTerms;
            cout << "-------------- tokenize( query, primTerms ) ---------------" << endl;
            tokenizer.tokenize(ustr, primTerms );
            printTermList( primTerms );
        }

    } while( true );
}

void printUsage()
{
    cout << "Usage: ./t_LA [tok | char | cn | en | kr | multi | ngram | matrix | token(token analyzer) | none(empty analyzer)]" << endl;
}

boost::shared_ptr<Analyzer> getCMAAnalyzer()
{
    ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() );
    cana->setLabelMode();
    cana->setAnalysisType(ChineseAnalyzer::minimum_match);
    boost::shared_ptr<Analyzer> cbana( cana );
    return cbana;
}

boost::shared_ptr<Analyzer> getKMAAnalyzer()
{
    KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() );
    kana->setLabelMode();
    boost::shared_ptr<Analyzer> kbana( kana );
    return kbana;
}

int main( int argc, char** argv )
{
    if( argc < 2 )
    {
        printUsage();
        exit(1);
    }

    string type = argv[1];
    if( type == "tok" )
    {
        testTokenizer();
        exit(0);
    }

    LA la;
    boost::shared_ptr<Analyzer> analyzer;

    if( type == "char" )
    {
        cout << "CharAnalyzer Addition Params: [all | part]" << endl;
        CharAnalyzer* ana = new CharAnalyzer;
        for( int i = 2; i < argc; ++i )
        {
            string arg = argv[i];
            if( arg == "all" )
                ana->setSeparateAll(true);
            else if( arg == "part" )
                ana->setSeparateAll(false);
            else
                cerr << "Invalid Parameter: " << arg << endl;
        }

        analyzer.reset( ana );
    }
    else if( type == "cn" )
    {
        cout << "ChineseAnalyzer Addition Params: [max | min | mmm | min_u] [label | index | stop]" << endl;
        ChineseAnalyzer* ana = new ChineseAnalyzer( getCmaKnowledgePath() );
        ana->setLabelMode();
        ana->setCaseSensitive();
        ana->setAnalysisType(ChineseAnalyzer::minimum_match);

        for( int i = 2; i < argc; ++i )
        {
            string arg = argv[i];
            if( arg == "max" )
                ana->setAnalysisType(ChineseAnalyzer::maximum_match);
            else if( arg == "min" )
                ana->setAnalysisType(ChineseAnalyzer::minimum_match);
            else if( arg == "min_u" )
                ana->setAnalysisType(ChineseAnalyzer::minimum_match_with_unigram);
            else if( arg == "mmm" )
                ana->setAnalysisType(ChineseAnalyzer::maximum_entropy);
            else if( arg == "label" )
                ana->setLabelMode();
            else if( arg == "index" )
                ana->setIndexMode();
            else if( arg == "stop")
                ana->setRemoveStopwords();
            else
                cerr << "Invalid Parameter: " << arg << endl;
        }

        analyzer.reset( ana );
    }
    else if( type == "en" )
    {
        analyzer.reset( new EnglishAnalyzer );
    }
    else if( type == "kr" )
    {
        cout << "KoreanAnalyzer Addition Params: [label | index]" << endl;
        KoreanAnalyzer* ana = new KoreanAnalyzer( getKmaKnowledgePath() );
        ana->setLabelMode();
        for( int i = 2; i < argc; ++i )
        {
            string arg = argv[i];
            if( arg == "label" )
                ana->setLabelMode();
            else if( arg == "index" )
                ana->setIndexMode();
            else
                cerr << "Invalid Parameter: " << arg << endl;
        }
        analyzer.reset( ana );
    }
    else if( type == "multi" )
    {
        ChineseAnalyzer* cana = new ChineseAnalyzer( getCmaKnowledgePath() );
        cana->setLabelMode();
        cana->setAnalysisType(ChineseAnalyzer::minimum_match);
        boost::shared_ptr<Analyzer> cbana( cana );

        KoreanAnalyzer* kana = new KoreanAnalyzer( getKmaKnowledgePath() );
        kana->setLabelMode();
        boost::shared_ptr<Analyzer> kbana( kana );

        EnglishAnalyzer* eana = new EnglishAnalyzer;
        boost::shared_ptr<Analyzer> ebana( eana );

        MultiLanguageAnalyzer* mana = new MultiLanguageAnalyzer;
        mana->setDefaultAnalyzer( kbana );
        mana->setAnalyzer( MultiLanguageAnalyzer::CHINESE, cbana );
        mana->setAnalyzer( MultiLanguageAnalyzer::ENGLISH, ebana );

        analyzer.reset( mana );
    }
    else if( type == "ngram" )
    {
        cout << "NGramAnalyzer Addition Params: min max flag" << endl;
        int min = 2;
        int max = 3;
        if( argc > 2 )
            min = atoi( argv[2] );
        if( argc > 3 )
            max = atoi( argv[3] );
        if( min < 1 )
            min = 2;
        if( max < min )
            max = min + 1;
        unsigned int apartFlag = 0;
        if( argc > 4 )
            apartFlag = (unsigned int)atoi( argv[4] );

        cout << "[NGramAnalyzer] min = " << min << ", max = " << max << ", apartFlag = "
                << hex << apartFlag << endl;
        analyzer.reset( new NGramAnalyzer( 2, 3, 1024000, apartFlag ) );
    }
    else if( type == "matrix" )
    {
        analyzer.reset( new MatrixAnalyzer( true, true) );
    }
    else if( type == "token" )
    {
        analyzer.reset( new TokenAnalyzer );
    }
    else if( type == "none" )
    {
        // do nothing
    }
    else
    {
        cerr << "Unknown analyzer type: " << type << endl;
        exit(1);
    }

    bool toHalfWidthString = false;
    for( int i = 2; i < argc; ++i ) {
    	string arg = argv[i];
    	if (arg == "half-width") {
    		toHalfWidthString = true;
    	}
    }

    la.setAnalyzer( analyzer );
    string input;
    do {
        cout << "Input ('x' to exit): ";
        getline( cin, input );
        if( input == "x" || input == "X" )
            break;

        UString ustr( input, IO_ENCODING );

        if ( toHalfWidthString )
        {
			la::convertFull2HalfWidth(ustr);
			string str;
			ustr.convertString(str, UString::UTF_8);
			cout << "Input (full-with chars are converted to half-with): " << str << endl;
        }

        {
            TermList termList;
            cout << "-------------- process( query, termList ) ---------------" << endl;
            la.process( ustr, termList );
            printTermList( termList );

            cout << "-------------- toExpandedString ---------------" << endl;
            UString exp = toExpandedString(termList);
            exp.displayStringInfo(UString::UTF_8, cout);
            cout << endl;
        }

    } while( true );

    return 0;
}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ExponentialRegressionCurveCalculator.hxx"
#include "macros.hxx"
#include "RegressionCalculationHelper.hxx"

#include <rtl/math.hxx>
#include <rtl/ustrbuf.hxx>

using namespace ::com::sun::star;

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

namespace chart
{

ExponentialRegressionCurveCalculator::ExponentialRegressionCurveCalculator() :
        m_fSlope( 0.0 ),
        m_fIntercept( 0.0 )
{
    ::rtl::math::setNan( & m_fSlope );
    ::rtl::math::setNan( & m_fIntercept );
}

ExponentialRegressionCurveCalculator::~ExponentialRegressionCurveCalculator()
{}

// ____ XRegressionCurveCalculator ____
void SAL_CALL ExponentialRegressionCurveCalculator::recalculateRegression(
    const uno::Sequence< double >& aXValues,
    const uno::Sequence< double >& aYValues )
    throw (uno::RuntimeException)
{
    RegressionCalculationHelper::tDoubleVectorPair aValues(
        RegressionCalculationHelper::cleanup(
            aXValues, aYValues,
            RegressionCalculationHelper::isValidAndYPositive()));

    const size_t nMax = aValues.first.size();
    if( nMax == 0 )
    {
        ::rtl::math::setNan( & m_fSlope );
        ::rtl::math::setNan( & m_fIntercept );
        ::rtl::math::setNan( & m_fCorrelationCoeffitient );
        return;
    }

    double fAverageX = 0.0, fAverageY = 0.0;
    size_t i = 0;
    for( i = 0; i < nMax; ++i )
    {
        fAverageX += aValues.first[i];
        fAverageY += log( aValues.second[i] );
    }

    const double fN = static_cast< double >( nMax );
    fAverageX /= fN;
    fAverageY /= fN;

    double fQx = 0.0, fQy = 0.0, fQxy = 0.0;
    for( i = 0; i < nMax; ++i )
    {
        double fDeltaX = aValues.first[i] - fAverageX;
        double fDeltaY = log( aValues.second[i] ) - fAverageY;

        fQx  += fDeltaX * fDeltaX;
        fQy  += fDeltaY * fDeltaY;
        fQxy += fDeltaX * fDeltaY;
    }

    m_fSlope = fQxy / fQx;
    m_fIntercept = fAverageY - m_fSlope * fAverageX;
    m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy );

    m_fSlope = exp( m_fSlope );
    m_fIntercept = exp( m_fIntercept );
}

double SAL_CALL ExponentialRegressionCurveCalculator::getCurveValue( double x )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    double fResult;
    ::rtl::math::setNan( & fResult );

    if( ! ( ::rtl::math::isNan( m_fSlope ) ||
            ::rtl::math::isNan( m_fIntercept )))
    {
        fResult = m_fIntercept * pow( m_fSlope, x );
    }

    return fResult;
}

uno::Sequence< geometry::RealPoint2D > SAL_CALL ExponentialRegressionCurveCalculator::getCurveValues(
    double min, double max, ::sal_Int32 nPointCount,
    const uno::Reference< chart2::XScaling >& xScalingX,
    const uno::Reference< chart2::XScaling >& xScalingY,
    ::sal_Bool bMaySkipPointsInCalculation )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    if( bMaySkipPointsInCalculation &&
        isLinearScaling( xScalingX ) &&
        isLogarithmicScaling( xScalingY ))
    {
        // optimize result
        uno::Sequence< geometry::RealPoint2D > aResult( 2 );
        aResult[0].X = min;
        aResult[0].Y = this->getCurveValue( min );
        aResult[1].X = max;
        aResult[1].Y = this->getCurveValue( max );

        return aResult;
    }

    return RegressionCurveCalculator::getCurveValues( min, max, nPointCount, xScalingX, xScalingY, bMaySkipPointsInCalculation );
}

OUString ExponentialRegressionCurveCalculator::ImplGetRepresentation(
    const uno::Reference< util::XNumberFormatter >& xNumFormatter,
    ::sal_Int32 nNumberFormatKey ) const
{
    OUStringBuffer aBuf( C2U( "f(x) = " ));

    if( m_fIntercept == 0.0 ||
        m_fSlope == 0.0 )
    {
        aBuf.append( sal_Unicode( '0' ));
    }
    else if( rtl::math::approxEqual( m_fSlope, 1.0 ) )
    {
        aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
    }
    else
    {
        if( ! rtl::math::approxEqual( m_fIntercept, 1.0 ) )
        {
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
            aBuf.append( sal_Unicode( 0x00b7 ));
        }

        if( m_fSlope < 0.0 )
            aBuf.append( sal_Unicode( '(' ));
        aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fSlope ));
        if( m_fSlope < 0.0 )
            aBuf.append( sal_Unicode( ')' ));
        aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "^x" ));
    }

    return aBuf.makeStringAndClear();
}

} //  namespace chart
<commit_msg>INTEGRATION: CWS changefileheader (1.6.60); FILE MERGED 2008/03/28 16:44:22 rt 1.6.60.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ExponentialRegressionCurveCalculator.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ExponentialRegressionCurveCalculator.hxx"
#include "macros.hxx"
#include "RegressionCalculationHelper.hxx"

#include <rtl/math.hxx>
#include <rtl/ustrbuf.hxx>

using namespace ::com::sun::star;

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

namespace chart
{

ExponentialRegressionCurveCalculator::ExponentialRegressionCurveCalculator() :
        m_fSlope( 0.0 ),
        m_fIntercept( 0.0 )
{
    ::rtl::math::setNan( & m_fSlope );
    ::rtl::math::setNan( & m_fIntercept );
}

ExponentialRegressionCurveCalculator::~ExponentialRegressionCurveCalculator()
{}

// ____ XRegressionCurveCalculator ____
void SAL_CALL ExponentialRegressionCurveCalculator::recalculateRegression(
    const uno::Sequence< double >& aXValues,
    const uno::Sequence< double >& aYValues )
    throw (uno::RuntimeException)
{
    RegressionCalculationHelper::tDoubleVectorPair aValues(
        RegressionCalculationHelper::cleanup(
            aXValues, aYValues,
            RegressionCalculationHelper::isValidAndYPositive()));

    const size_t nMax = aValues.first.size();
    if( nMax == 0 )
    {
        ::rtl::math::setNan( & m_fSlope );
        ::rtl::math::setNan( & m_fIntercept );
        ::rtl::math::setNan( & m_fCorrelationCoeffitient );
        return;
    }

    double fAverageX = 0.0, fAverageY = 0.0;
    size_t i = 0;
    for( i = 0; i < nMax; ++i )
    {
        fAverageX += aValues.first[i];
        fAverageY += log( aValues.second[i] );
    }

    const double fN = static_cast< double >( nMax );
    fAverageX /= fN;
    fAverageY /= fN;

    double fQx = 0.0, fQy = 0.0, fQxy = 0.0;
    for( i = 0; i < nMax; ++i )
    {
        double fDeltaX = aValues.first[i] - fAverageX;
        double fDeltaY = log( aValues.second[i] ) - fAverageY;

        fQx  += fDeltaX * fDeltaX;
        fQy  += fDeltaY * fDeltaY;
        fQxy += fDeltaX * fDeltaY;
    }

    m_fSlope = fQxy / fQx;
    m_fIntercept = fAverageY - m_fSlope * fAverageX;
    m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy );

    m_fSlope = exp( m_fSlope );
    m_fIntercept = exp( m_fIntercept );
}

double SAL_CALL ExponentialRegressionCurveCalculator::getCurveValue( double x )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    double fResult;
    ::rtl::math::setNan( & fResult );

    if( ! ( ::rtl::math::isNan( m_fSlope ) ||
            ::rtl::math::isNan( m_fIntercept )))
    {
        fResult = m_fIntercept * pow( m_fSlope, x );
    }

    return fResult;
}

uno::Sequence< geometry::RealPoint2D > SAL_CALL ExponentialRegressionCurveCalculator::getCurveValues(
    double min, double max, ::sal_Int32 nPointCount,
    const uno::Reference< chart2::XScaling >& xScalingX,
    const uno::Reference< chart2::XScaling >& xScalingY,
    ::sal_Bool bMaySkipPointsInCalculation )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    if( bMaySkipPointsInCalculation &&
        isLinearScaling( xScalingX ) &&
        isLogarithmicScaling( xScalingY ))
    {
        // optimize result
        uno::Sequence< geometry::RealPoint2D > aResult( 2 );
        aResult[0].X = min;
        aResult[0].Y = this->getCurveValue( min );
        aResult[1].X = max;
        aResult[1].Y = this->getCurveValue( max );

        return aResult;
    }

    return RegressionCurveCalculator::getCurveValues( min, max, nPointCount, xScalingX, xScalingY, bMaySkipPointsInCalculation );
}

OUString ExponentialRegressionCurveCalculator::ImplGetRepresentation(
    const uno::Reference< util::XNumberFormatter >& xNumFormatter,
    ::sal_Int32 nNumberFormatKey ) const
{
    OUStringBuffer aBuf( C2U( "f(x) = " ));

    if( m_fIntercept == 0.0 ||
        m_fSlope == 0.0 )
    {
        aBuf.append( sal_Unicode( '0' ));
    }
    else if( rtl::math::approxEqual( m_fSlope, 1.0 ) )
    {
        aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
    }
    else
    {
        if( ! rtl::math::approxEqual( m_fIntercept, 1.0 ) )
        {
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
            aBuf.append( sal_Unicode( 0x00b7 ));
        }

        if( m_fSlope < 0.0 )
            aBuf.append( sal_Unicode( '(' ));
        aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fSlope ));
        if( m_fSlope < 0.0 )
            aBuf.append( sal_Unicode( ')' ));
        aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "^x" ));
    }

    return aBuf.makeStringAndClear();
}

} //  namespace chart
<|endoftext|>


<commit_before>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "Piston.h"
#include "ChunkDef.h"
#include "Pickup.h"
#include "Item.h"
#include "Root.h"
#include "ClientHandle.h"
#include "World.h"
#include "BlockID.h"
#include "Server.h"
#include "Blocks/BlockHandler.h"

/*
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
*/

extern bool g_BlockPistonBreakable[];

#define AddDir( x, y, z, dir, amount ) \
	switch (dir) \
	{ \
		case 0: (y)-=(amount); break; \
		case 1: (y)+=(amount); break; \
		case 2: (z)-=(amount); break; \
		case 3: (z)+=(amount); break; \
		case 4: (x)-=(amount); break; \
		case 5: (x)+=(amount); break; \
	}

cPiston::cPiston(cWorld * a_World)
	: m_World(a_World)
{

}

unsigned short cPiston::FirstPassthroughBlock(int pistonX, int pistonY, int pistonZ, char pistonmeta)
{
	unsigned short ret;
	pistonmeta &= 7;
	if (pistonmeta >= 6)
	{
		// Just in case, it shouldn't happen but if it would, it'd case inf loop
		LOGD("cPiston::FirstPassthroughBlock - piston has invalid meta data!\n");
		return 9001;
	}
	BLOCKTYPE currBlock;
	for (ret = 0; ret < 24; ret++)  // push up to 24 blocks
	{
		AddDir( pistonX, pistonY, pistonZ, pistonmeta, 1)
		currBlock = m_World->GetBlock( pistonX, pistonY, pistonZ );
		if ((currBlock == E_BLOCK_BEDROCK) || (currBlock == E_BLOCK_OBSIDIAN) || (currBlock == E_BLOCK_PISTON_EXTENSION))
		{
			return 9001;
		}
		if (g_BlockPistonBreakable[currBlock])
		{
			return ret;
		}
	}
	return 9001;
}

void cPiston::ExtendPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	char isSticky = (char)(pistonBlock == E_BLOCK_STICKY_PISTON) * 8;
	if ( (pistonMeta & 0x8) != 0x0 )
	{
		// Piston already extended, bail out
		return;
	}

	unsigned short dist = FirstPassthroughBlock(pistx, pisty, pistz, pistonMeta);
	if (dist > 9000) return; // too many blocks

	AddDir(pistx, pisty, pistz, pistonMeta & 7, dist + 1)
	BLOCKTYPE currBlock;
	NIBBLETYPE currMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currMeta);
	if (currBlock != E_BLOCK_AIR)
	{
		cBlockHandler * Handler = BlockHandler(currBlock);
		if (Handler->DoesDropOnUnsuitable())
		{
			Handler->DropBlock(m_World, NULL, pistx, pisty, pistz);
		}
	}
	int oldx = pistx, oldy = pisty, oldz = pistz;
	NIBBLETYPE currBlockMeta;
	for (int i = dist + 1; i > 0; i--)
	{
		AddDir(pistx, pisty, pistz, pistonMeta & 7, -1)
		m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currBlockMeta);
		m_World->SetBlock( oldx, oldy, oldz, currBlock, currBlockMeta);
		oldx = pistx;
		oldy = pisty;
		oldz = pistz;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 0, pistonMeta, E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.out", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock( pistx, pisty, pistz, pistonBlock, pistonMeta | 0x8 );

	int extx = pistx;
	int exty = pisty;
	int extz = pistz;

	AddDir(extx, exty, extz, pistonMeta & 7, 1)

	/*
	#ifdef _WIN32
	// Sleeping here will play the piston animation on the client; however, it will block the entire server
	// for the 100 ms, effectively dropping 2 game ticks per piston. This is very bad
		// This needs to be handled using delayed scheduled tasks instead
	Sleep(100);
	#else
	usleep(static_cast<useconds_t>(100)*1000);
	#endif
	*/

	m_World->SetBlock(extx, exty, extz, E_BLOCK_PISTON_EXTENSION, isSticky + pistonMeta & 7);
}

void cPiston::RetractPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	if (pistonMeta <= 6)
	{
		// Already retracted, bail out
		return;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 1, pistonMeta & ~(8), E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.in", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock(pistx, pisty, pistz, pistonBlock, pistonMeta & ~(8));

	AddDir(pistx, pisty, pistz, pistonMeta & 7, 1)
	if (m_World->GetBlock(pistx, pisty, pistz) != E_BLOCK_PISTON_EXTENSION)
	{
		LOGD("%s: Piston without an extension?", __FUNCTION__);
		return;
	}

	if (pistonBlock == E_BLOCK_STICKY_PISTON)
	{
		int tempx = pistx, tempy = pisty, tempz = pistz;
		AddDir( tempx, tempy, tempz, pistonMeta & 7, 1 )
		BLOCKTYPE tempblock;
		NIBBLETYPE tempmeta;
		m_World->GetBlockTypeMeta(tempx, tempy, tempz, tempblock, tempmeta);
		if (
			(tempblock == E_BLOCK_OBSIDIAN) ||
			(tempblock == E_BLOCK_BEDROCK) ||
			(tempblock == E_BLOCK_PISTON_EXTENSION)
		)
		{
			// These cannot be moved by the sticky piston, bail out
			return;
		}
		/*
		#ifdef _WIN32
		// TODO: This code needs replacing
		// Sleeping here will play the piston animation on the client; however, it will block the entire server
		// for the 100 ms, effectively dropping 2 game ticks per piston. This is very bad
		// This needs to be handled using delayed scheduled tasks instead
		Sleep(100);
		#else
		usleep(static_cast<useconds_t>(100)*1000);
		#endif
		*/

		m_World->SetBlock(pistx, pisty, pistz, tempblock, tempmeta);
		m_World->SetBlock(tempx, tempy, tempz, E_BLOCK_AIR, 0);
	}
	else
	{
		/*
		#ifdef _WIN32
		// Sleeping here will play the piston animation on the client; however, it will block the entire server
		// for the 100 ms, effectively dropping 2 game ticks per piston. This is very bad
		// This needs to be handled using delayed scheduled tasks instead
		Sleep(100);
		#else
		usleep(static_cast<useconds_t>(100)*1000);
		#endif
		*/

		m_World->SetBlock(pistx, pisty, pistz, E_BLOCK_AIR, 0);
	}
}

<commit_msg>Okay, changed to xoft's partial fix<commit_after>#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "Piston.h"
#include "ChunkDef.h"
#include "Pickup.h"
#include "Item.h"
#include "Root.h"
#include "ClientHandle.h"
#include "World.h"
#include "BlockID.h"
#include "Server.h"
#include "Blocks/BlockHandler.h"

extern bool g_BlockPistonBreakable[];

#define AddDir( x, y, z, dir, amount ) \
	switch (dir) \
	{ \
		case 0: (y)-=(amount); break; \
		case 1: (y)+=(amount); break; \
		case 2: (z)-=(amount); break; \
		case 3: (z)+=(amount); break; \
		case 4: (x)-=(amount); break; \
		case 5: (x)+=(amount); break; \
	}

cPiston::cPiston(cWorld * a_World)
	: m_World(a_World)
{

}

unsigned short cPiston::FirstPassthroughBlock(int pistonX, int pistonY, int pistonZ, char pistonmeta)
{
	unsigned short ret;
	pistonmeta &= 7;
	if (pistonmeta >= 6)
	{
		// Just in case, it shouldn't happen but if it would, it'd case inf loop
		LOGD("cPiston::FirstPassthroughBlock - piston has invalid meta data!\n");
		return 9001;
	}
	BLOCKTYPE currBlock;
	for (ret = 0; ret < 24; ret++)  // push up to 24 blocks
	{
		AddDir( pistonX, pistonY, pistonZ, pistonmeta, 1)
		currBlock = m_World->GetBlock( pistonX, pistonY, pistonZ );
		if ((currBlock == E_BLOCK_BEDROCK) || (currBlock == E_BLOCK_OBSIDIAN) || (currBlock == E_BLOCK_PISTON_EXTENSION))
		{
			return 9001;
		}
		if (g_BlockPistonBreakable[currBlock])
		{
			return ret;
		}
	}
	return 9001;
}

void cPiston::ExtendPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	char isSticky = (char)(pistonBlock == E_BLOCK_STICKY_PISTON) * 8;
	if ( (pistonMeta & 0x8) != 0x0 )
	{
		// Piston already extended, bail out
		return;
	}

	unsigned short dist = FirstPassthroughBlock(pistx, pisty, pistz, pistonMeta);
	if (dist > 9000) return; // too many blocks

	AddDir(pistx, pisty, pistz, pistonMeta & 7, dist + 1)
	BLOCKTYPE currBlock;
	NIBBLETYPE currMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currMeta);
	if (currBlock != E_BLOCK_AIR)
	{
		cBlockHandler * Handler = BlockHandler(currBlock);
		if (Handler->DoesDropOnUnsuitable())
		{
			Handler->DropBlock(m_World, NULL, pistx, pisty, pistz);
		}
	}
	int oldx = pistx, oldy = pisty, oldz = pistz;
	NIBBLETYPE currBlockMeta;
	for (int i = dist + 1; i > 0; i--)
	{
		AddDir(pistx, pisty, pistz, pistonMeta & 7, -1)
		m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currBlockMeta);
		m_World->SetBlock( oldx, oldy, oldz, currBlock, currBlockMeta);
		oldx = pistx;
		oldy = pisty;
		oldz = pistz;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 0, pistonMeta, E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.out", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock( pistx, pisty, pistz, pistonBlock, pistonMeta | 0x8 );

	int extx = pistx;
	int exty = pisty;
	int extz = pistz;

	AddDir(extx, exty, extz, pistonMeta & 7, 1)

	// TODO: This code needs replacing
	// Sleeping here will play the piston animation on the client; however, it will block the entire server
	// for the 100 ms, effectively dropping 2 game ticks per piston. This is very bad
		// This needs to be handled using delayed scheduled tasks instead
	cSleep::MilliSleep(100);

	m_World->SetBlock(extx, exty, extz, E_BLOCK_PISTON_EXTENSION, isSticky + pistonMeta & 7);
}

void cPiston::RetractPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	if (pistonMeta <= 6)
	{
		// Already retracted, bail out
		return;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 1, pistonMeta & ~(8), E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.in", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock(pistx, pisty, pistz, pistonBlock, pistonMeta & ~(8));

	AddDir(pistx, pisty, pistz, pistonMeta & 7, 1)
	if (m_World->GetBlock(pistx, pisty, pistz) != E_BLOCK_PISTON_EXTENSION)
	{
		LOGD("%s: Piston without an extension?", __FUNCTION__);
		return;
	}

	if (pistonBlock == E_BLOCK_STICKY_PISTON)
	{
		int tempx = pistx, tempy = pisty, tempz = pistz;
		AddDir( tempx, tempy, tempz, pistonMeta & 7, 1 )
		BLOCKTYPE tempblock;
		NIBBLETYPE tempmeta;
		m_World->GetBlockTypeMeta(tempx, tempy, tempz, tempblock, tempmeta);
		if (
			(tempblock == E_BLOCK_OBSIDIAN) ||
			(tempblock == E_BLOCK_BEDROCK) ||
			(tempblock == E_BLOCK_PISTON_EXTENSION)
		)
		{
			// These cannot be moved by the sticky piston, bail out
			return;
		}

		// TODO: This code needs replacing
		// Sleeping here will play the piston animation on the client; however, it will block the entire server
		// for the 100 ms, effectively dropping 2 game ticks per piston. This is very bad
		// This needs to be handled using delayed scheduled tasks instead
		cSleep::MilliSleep(100);

		m_World->SetBlock(pistx, pisty, pistz, tempblock, tempmeta);
		m_World->SetBlock(tempx, tempy, tempz, E_BLOCK_AIR, 0);
	}
	else
	{
		// TODO: This code needs replacing
		// Sleeping here will play the piston animation on the client; however, it will block the entire server
		// for the 100 ms, effectively dropping 2 game ticks per piston. This is very bad
		// This needs to be handled using delayed scheduled tasks instead
		cSleep::MilliSleep(100);

		m_World->SetBlock(pistx, pisty, pistz, E_BLOCK_AIR, 0);
	}
}

<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"

#include "TestModule.h"
#include "EC_Dummy.h"
#include <Poco/ClassLibrary.h>
#include "Foundation.h"

namespace Test
{
    TestModule::TestModule() : ModuleInterface_Impl(Foundation::Module::Type_Test)
    {
    }

    TestModule::~TestModule()
    {
    }

    // virtual
    void TestModule::load()
    {
        using namespace Test;
        DECLARE_MODULE_EC(EC_Dummy);

        LOG("System " + name() + " loaded.");
    }

    // virtual
    void TestModule::unload()
    {
        LOG("System " + name() + " unloaded.");
    }

    // virtual
    void TestModule::initialize(Foundation::Framework *framework)
    {
        assert(framework != NULL);
        mFramework = framework;
        mFramework->getServiceManager()->registerService(Foundation::Service::ST_Test, this);

        LOG("System " + name() + " initialized.");
    }

    // virtual
    void TestModule::uninitialize(Foundation::Framework *framework)
    {
        mFramework->getServiceManager()->unregisterService(this);

        assert(mFramework != NULL);
        mFramework = NULL;

        LOG("System " + name() + " uninitialized.");
    }

    // virtual
    void TestModule::update()
    {
        // create new entity
        LOG("Constructing entity with component: " + Test::EC_Dummy::name() + ".");

        Foundation::EntityPtr entity = mFramework->getEntityManager()->createEntity();
        assert (entity.get() != 0 && "Failed to create entity.");

        Foundation::ComponentPtr component = mFramework->getComponentManager()->createComponent(Test::EC_Dummy::name());
        assert (component.get() != 0 && "Failed to create dummy component.");

        entity->addEntityComponent(component);
        component = entity->getComponent(component->_name());
        assert (component.get() != 0 && "Failed to get dummy component from entity.");

        Foundation::TestServiceInterface *test_service = mFramework->getServiceManager()->getService<Foundation::TestServiceInterface>(Foundation::Service::ST_Test);
        assert (test_service != NULL);
        assert (test_service->test());

        mFramework->_exit();
        assert (mFramework->isExiting());
    }
}

using namespace Test;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
   POCO_EXPORT_CLASS(TestModule)
POCO_END_MANIFEST

<commit_msg>Finished renaming modules. After updating to this revision, delete 'modules' directory under 'bin' directory, otherwise certain modules will be loaded several times and the framework asserts!<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"

#include "TestModule.h"
#include "EC_Dummy.h"
#include <Poco/ClassLibrary.h>
#include "Foundation.h"

namespace Test
{
    TestModule::TestModule() : ModuleInterface_Impl(Foundation::Module::Type_Test)
    {
    }

    TestModule::~TestModule()
    {
    }

    // virtual
    void TestModule::load()
    {
        using namespace Test;
        DECLARE_MODULE_EC(EC_Dummy);

        LOG("System " + name() + " loaded.");
    }

    // virtual
    void TestModule::unload()
    {
        LOG("System " + name() + " unloaded.");
    }

    // virtual
    void TestModule::initialize(Foundation::Framework *framework)
    {
        assert(framework != NULL);
        mFramework = framework;
        mFramework->getServiceManager()->registerService(Foundation::Service::ST_Test, this);

        LOG("System " + name() + " initialized.");
    }

    // virtual
    void TestModule::uninitialize(Foundation::Framework *framework)
    {
        mFramework->getServiceManager()->unregisterService(this);

        assert(mFramework != NULL);
        mFramework = NULL;

        LOG("System " + name() + " uninitialized.");
    }

    // virtual
    void TestModule::update()
    {
        // create new entity
        LOG("Constructing entity with component: " + Test::EC_Dummy::name() + ".");

        Foundation::EntityPtr entity = mFramework->getEntityManager()->createEntity();
        assert (entity.get() != 0 && "Failed to create entity.");

        Foundation::ComponentPtr component = mFramework->getComponentManager()->createComponent(Test::EC_Dummy::name());
        assert (component.get() != 0 && "Failed to create dummy component.");

        entity->addEntityComponent(component);
        component = entity->getComponent(component->_name());
        assert (component.get() != 0 && "Failed to get dummy component from entity.");

        Foundation::TestServiceInterface *test_service = mFramework->getServiceManager()->getService<Foundation::TestServiceInterface>(Foundation::Service::ST_Test);
        assert (test_service != NULL);
        assert (test_service->test());

        mFramework->_exit();
        assert (mFramework->isExiting());
    }
}

using namespace Test;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
   POCO_EXPORT_CLASS(TestModule)
POCO_END_MANIFEST
<|endoftext|>