<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2012-2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// \file
/// Unit Tests for the OsgOctreeRepresentation class.

#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/DataStructures/EmptyData.h"
#include "SurgSim/Graphics/OsgOctreeRepresentation.h"
#include "SurgSim/Math/OctreeShape.h"

#include <gtest/gtest.h>

using SurgSim::Framework::Runtime;
using SurgSim::DataStructures::EmptyData;
using SurgSim::Graphics::OsgOctreeRepresentation;
using SurgSim::Math::OctreeShape;
using SurgSim::Math::Vector3d;

TEST(OsgOctreeRepresentationTests, InitilizationTest)
{
	ASSERT_NO_THROW(std::make_shared<OsgOctreeRepresentation>("Test Octree"));
};

TEST(OsgOctreeRepresentationTests, GetSetUpdateTest)
{
	OctreeShape::NodeType::AxisAlignedBoundingBox boundingBox(Vector3d::Zero(), Vector3d::Ones() * 4.0);
	auto octreeNode = std::make_shared<OctreeShape::NodeType>(boundingBox);
	OctreeShape octreeShape;
	octreeShape.setRootNode(octreeNode);

	auto runtime = std::make_shared<Runtime>();
	auto octreeRepresentation = std::make_shared<OsgOctreeRepresentation>("Test Octree");
	octreeRepresentation->setOctree(octreeShape);

	EXPECT_TRUE(octreeRepresentation->initialize(runtime));
	EXPECT_TRUE(octreeRepresentation->wakeUp());

	// Set the octree after wake up will cause a assertion failure.
	ASSERT_ANY_THROW( { octreeRepresentation->setOctree(octreeShape); } );

	ASSERT_NO_THROW(octreeRepresentation->update(0.1));
}

TEST(OsgOctreeRepresentationTests, SetNodeVisibilityTest)
{
	SurgSim::DataStructures::EmptyData emptyData;

	OctreeShape::NodeType::AxisAlignedBoundingBox boundingBox(Vector3d::Zero(), Vector3d::Ones() * 4.0);
	auto octreeNode = std::make_shared<OctreeShape::NodeType>(boundingBox);
	octreeNode->addData(Vector3d(0.0, 0.0, 0.0), emptyData, 2);
	octreeNode->addData(Vector3d(0.0, 0.0, 1.0), emptyData, 3);

	OctreeShape octreeShape;
	octreeShape.setRootNode(octreeNode);

	auto octreeRepresentation = std::make_shared<OsgOctreeRepresentation>("Test Octree");
	octreeRepresentation->setOctree(octreeShape);

	// Path to leaf node
	SurgSim::DataStructures::OctreePath path;
	path.push_back(0);
	path.push_back(0);
	EXPECT_NO_THROW(octreeRepresentation->setNodeVisible(path, false));

	// Path to internal node
	SurgSim::DataStructures::OctreePath path2;
	path2.push_back(0);
	EXPECT_NO_THROW(octreeRepresentation->setNodeVisible(path2, true));

	// Invalid path
	SurgSim::DataStructures::OctreePath invalidPath;
	invalidPath.push_back(4);
	invalidPath.push_back(1);
	EXPECT_ANY_THROW(octreeRepresentation->setNodeVisible(invalidPath, true));
}<commit_msg>Add UnitTest for setting node visibility when no octree is held.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2012-2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// \file
/// Unit Tests for the OsgOctreeRepresentation class.

#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/DataStructures/EmptyData.h"
#include "SurgSim/Graphics/OsgOctreeRepresentation.h"
#include "SurgSim/Math/OctreeShape.h"

#include <gtest/gtest.h>

using SurgSim::Framework::Runtime;
using SurgSim::DataStructures::EmptyData;
using SurgSim::Graphics::OsgOctreeRepresentation;
using SurgSim::Math::OctreeShape;
using SurgSim::Math::Vector3d;

TEST(OsgOctreeRepresentationTests, InitilizationTest)
{
	ASSERT_NO_THROW(std::make_shared<OsgOctreeRepresentation>("Test Octree"));
};

TEST(OsgOctreeRepresentationTests, GetSetUpdateTest)
{
	OctreeShape::NodeType::AxisAlignedBoundingBox boundingBox(Vector3d::Zero(), Vector3d::Ones() * 4.0);
	auto octreeNode = std::make_shared<OctreeShape::NodeType>(boundingBox);
	OctreeShape octreeShape;
	octreeShape.setRootNode(octreeNode);

	auto runtime = std::make_shared<Runtime>();
	auto octreeRepresentation = std::make_shared<OsgOctreeRepresentation>("Test Octree");
	octreeRepresentation->setOctree(octreeShape);

	EXPECT_TRUE(octreeRepresentation->initialize(runtime));
	EXPECT_TRUE(octreeRepresentation->wakeUp());

	// Set the octree after wake up will cause a assertion failure.
	ASSERT_ANY_THROW( { octreeRepresentation->setOctree(octreeShape); } );

	ASSERT_NO_THROW(octreeRepresentation->update(0.1));
}

TEST(OsgOctreeRepresentationTests, SetNodeVisibilityTest)
{
	SurgSim::DataStructures::EmptyData emptyData;

	OctreeShape::NodeType::AxisAlignedBoundingBox boundingBox(Vector3d::Zero(), Vector3d::Ones() * 4.0);
	auto octreeNode = std::make_shared<OctreeShape::NodeType>(boundingBox);
	octreeNode->addData(Vector3d(0.0, 0.0, 0.0), emptyData, 2);
	octreeNode->addData(Vector3d(0.0, 0.0, 1.0), emptyData, 3);

	OctreeShape octreeShape;
	octreeShape.setRootNode(octreeNode);

	auto octreeRepresentation = std::make_shared<OsgOctreeRepresentation>("Test Octree");

	// Path to leaf node
	SurgSim::DataStructures::OctreePath path;
	path.push_back(0);
	path.push_back(0);

	// Set node visibility when no octree is held by OsgOctreeRepresentation will throw.
	EXPECT_ANY_THROW(octreeRepresentation->setNodeVisible(path, true));

	octreeRepresentation->setOctree(octreeShape);
	EXPECT_NO_THROW(octreeRepresentation->setNodeVisible(path, false));

	// Path to internal node
	SurgSim::DataStructures::OctreePath path2;
	path2.push_back(0);
	EXPECT_NO_THROW(octreeRepresentation->setNodeVisible(path2, true));

	// Invalid path
	SurgSim::DataStructures::OctreePath invalidPath;
	invalidPath.push_back(4);
	invalidPath.push_back(1);
	EXPECT_ANY_THROW(octreeRepresentation->setNodeVisible(invalidPath, true));
}<|endoftext|>


<commit_before>#include "DataLayer.h"
#include <iostream>
#include <vector>
//#include <sqlite3.h>
//#include <sql.h>

DataLayer::DataLayer()
{
    QSqlDatabase m_db;

       m_db = QSqlDatabase::addDatabase("QSQLITE");
       m_db.setDatabaseName("Scientists.sqlite");

       if (!m_db.open())
       {
          qDebug() << "Error: connection with database fail";
       }
       else
       {
          qDebug() << "Database: connection ok";
       }
}

DataLayer::~DataLayer()
{
    if (m_db.isOpen())
    {
        m_db.close();
    }
}

void DataLayer::readAllFromDataBase() const
{
    qDebug() << "Persons in Database: ";
    QSqlQuery query("SELECT * FROM Scientists");
    int idFirstName = query.record().indexOf("FirstName");
    while(query.next())
    {
        QString name = query.value(idFirstName).toString();
        qDebug() << "=====" << name;
    }
}

<commit_msg>computer<commit_after>#include "DataLayer.h"
#include <iostream>
#include <vector>

DataLayer::DataLayer()
{
    QSqlDatabase m_db;

       m_db = QSqlDatabase::addDatabase("QSQLITE");
       m_db.setDatabaseName("Scientists.sqlite");

       if (!m_db.open())
       {
          qDebug() << "Error: connection with database fail";
       }
       else
       {
          qDebug() << "Database: connection ok";
       }
}

DataLayer::~DataLayer()
{
    if (m_db.isOpen())
    {
        m_db.close();
    }
}

void DataLayer::readAllFromDataBase() const
{
    qDebug() << "Persons in Database: ";
    QSqlQuery query("SELECT * FROM scientist");
    int idFirstName = query.record().indexOf("firstname");
    while(query.next())
    {
        QString name = query.value(idFirstName).toString();
        qDebug() << "=====" << name;
        cout << "Hello";
    }
}

<|endoftext|>


<commit_before>#include "musicnetworktestthread.h"
#include "musicobject.h"

#include <QProcess>
#ifdef Q_OS_WIN
# ifdef Q_CC_MINGW
#   include <winsock2.h>
# endif
# include <windows.h>
# include <cstdio>
# include <iphlpapi.h>
#elif defined Q_OS_UNIX
# include <ifaddrs.h>
# include <arpa/inet.h>
#endif

MusicNetworkTestThread::MusicNetworkTestThread(QObject *parent)
    : QThread(parent)
{
    m_run = false;
    m_process = nullptr;
#ifdef Q_OS_UNIX
    setAvailableNewtworkNames(QStringList("eth0"));
#endif
}

MusicNetworkTestThread::~MusicNetworkTestThread()
{
    if(m_process)
    {
        m_process->kill();
    }
    delete m_process;
    stopAndQuitThread();
}

void MusicNetworkTestThread::stopAndQuitThread()
{
    if(isRunning())
    {
        m_run = false;
        wait();
    }
    quit();
}

void MusicNetworkTestThread::setAvailableNewtworkNames(const QStringList &names)
{
    m_names = names;
#ifdef Q_OS_UNIX
    if(m_names.isEmpty())
    {
        return;
    }

    delete m_process;
    m_process = new QProcess(this);
    m_process->setProcessChannelMode(QProcess::MergedChannels);
    connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(outputRecieved()));
    QStringList arguments;
    arguments << m_names.first() << "1";
    m_process->start(MAKE_NETS_AL, arguments);
#endif
}

QStringList MusicNetworkTestThread::getAvailableNewtworkNames() const
{
    return m_names;
}

QStringList MusicNetworkTestThread::getNewtworkNames() const
{
    QStringList names;
#ifdef Q_OS_WIN
    PMIB_IFTABLE m_pTable = nullptr;
    DWORD m_dwAdapters = 0;
    ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
    if(uRetCode == ERROR_NOT_SUPPORTED)
    {
        return names;
    }

    if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
    {
        m_pTable = (PMIB_IFTABLE)new BYTE[65535];
    }

    GetIfTable(m_pTable, &m_dwAdapters, TRUE);
    for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
    {
        MIB_IFROW Row = m_pTable->table[i];
        std::string s(MReinterpret_cast(char const*, Row.bDescr));
        QString qs = QString::fromStdString(s);
        if(Row.dwType == 71 && !names.contains(qs))
        {
            names << QString::fromStdString(s);
        }
    }
    delete[] m_pTable;
#elif defined Q_OS_UNIX
    struct ifaddrs *ifa = nullptr, *ifList;
    if (getifaddrs(&ifList) < 0)
    {
        return QStringList();
    }

    for (ifa = ifList; ifa != nullptr; ifa = ifa->ifa_next)
    {
        if(ifa->ifa_addr->sa_family == AF_INET)
        {
            names << QString(ifa->ifa_name);
        }
    }
    freeifaddrs(ifList);
#endif
    return names;
}

void MusicNetworkTestThread::outputRecieved()
{
    while(m_process->canReadLine())
    {
        QByteArray datas = m_process->readLine();
        QStringList lists = QString(datas).split("|");
        ulong upload = 0,  download = 0;

        if(lists.count() == 3)
        {
            download= lists[1].trimmed().toULong();
            upload  = lists[2].trimmed().toULong();
        }
        emit networkData(upload, download);
    }
}

void MusicNetworkTestThread::start()
{
    m_run = true;
    QThread::start();
}

void MusicNetworkTestThread::run()
{
#ifdef Q_OS_WIN
    PMIB_IFTABLE m_pTable = nullptr;
    DWORD m_dwAdapters = 0;
    ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
    if(uRetCode == ERROR_NOT_SUPPORTED)
    {
        return;
    }

    if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
    {
        m_pTable = (PMIB_IFTABLE)new BYTE[65535];
    }

    DWORD dwLastIn = 0;
    DWORD dwLastOut = 0;
    DWORD dwBandIn = 0;
    DWORD dwBandOut = 0;
    while(m_run)
    {
        GetIfTable(m_pTable, &m_dwAdapters, TRUE);
        DWORD dwInOctets = 0;
        DWORD dwOutOctets = 0;

        for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
        {
            MIB_IFROW Row = m_pTable->table[i];
            std::string s(MReinterpret_cast(char const*, Row.bDescr));
            if(Row.dwType == 71 && m_names.contains(QString::fromStdString(s)))
            {
                dwInOctets += Row.dwInOctets;
                dwOutOctets += Row.dwOutOctets;
            }
        }

        dwBandIn = dwInOctets - dwLastIn;
        dwBandOut = dwOutOctets - dwLastOut;
        if(dwLastIn <= 0)
        {
            dwBandIn = 0;
        }

        if (dwLastOut <= 0)
        {
            dwBandOut = 0;
        }
        dwLastIn = dwInOctets;
        dwLastOut = dwOutOctets;

        emit networkData(dwBandOut, dwBandIn);
        sleep(1);
    }
    delete[] m_pTable;
#endif
}
<commit_msg>fix get all network interface name[948555]<commit_after>#include "musicnetworktestthread.h"
#include "musicobject.h"

#include <QProcess>
#ifdef Q_OS_WIN
# ifdef Q_CC_MINGW
#   include <winsock2.h>
# endif
# include <windows.h>
# include <cstdio>
# include <iphlpapi.h>
#elif defined Q_OS_UNIX
# include <ifaddrs.h>
# include <arpa/inet.h>
#endif

MusicNetworkTestThread::MusicNetworkTestThread(QObject *parent)
    : QThread(parent)
{
    m_run = false;
    m_process = nullptr;
#ifdef Q_OS_UNIX
    setAvailableNewtworkNames(QStringList("eth0"));
#endif
}

MusicNetworkTestThread::~MusicNetworkTestThread()
{
    if(m_process)
    {
        m_process->kill();
    }
    delete m_process;
    stopAndQuitThread();
}

void MusicNetworkTestThread::stopAndQuitThread()
{
    if(isRunning())
    {
        m_run = false;
        wait();
    }
    quit();
}

void MusicNetworkTestThread::setAvailableNewtworkNames(const QStringList &names)
{
    m_names = names;
#ifdef Q_OS_UNIX
    if(m_names.isEmpty())
    {
        return;
    }

    delete m_process;
    m_process = new QProcess(this);
    m_process->setProcessChannelMode(QProcess::MergedChannels);
    connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(outputRecieved()));
    QStringList arguments;
    arguments << m_names.first() << "1";
    m_process->start(MAKE_NETS_AL, arguments);
#endif
}

QStringList MusicNetworkTestThread::getAvailableNewtworkNames() const
{
    return m_names;
}

QStringList MusicNetworkTestThread::getNewtworkNames() const
{
    QStringList names;
#ifdef Q_OS_WIN
    PMIB_IFTABLE m_pTable = nullptr;
    DWORD m_dwAdapters = 0;
    ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
    if(uRetCode == ERROR_NOT_SUPPORTED)
    {
        return names;
    }

    if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
    {
        m_pTable = (PMIB_IFTABLE)new BYTE[65535];
    }

    GetIfTable(m_pTable, &m_dwAdapters, TRUE);
    for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
    {
        MIB_IFROW Row = m_pTable->table[i];
        std::string s(MReinterpret_cast(char const*, Row.bDescr));
        QString qs = QString::fromStdString(s);
        if((Row.dwType == 71 || Row.dwType == 6) && !names.contains(qs))
        {
            names << QString::fromStdString(s);
        }
    }
    delete[] m_pTable;
#elif defined Q_OS_UNIX
    struct ifaddrs *ifa = nullptr, *ifList;
    if (getifaddrs(&ifList) < 0)
    {
        return QStringList();
    }

    for (ifa = ifList; ifa != nullptr; ifa = ifa->ifa_next)
    {
        if(ifa->ifa_addr->sa_family == AF_INET)
        {
            names << QString(ifa->ifa_name);
        }
    }
    freeifaddrs(ifList);
#endif
    return names;
}

void MusicNetworkTestThread::outputRecieved()
{
    while(m_process->canReadLine())
    {
        QByteArray datas = m_process->readLine();
        QStringList lists = QString(datas).split("|");
        ulong upload = 0,  download = 0;

        if(lists.count() == 3)
        {
            download= lists[1].trimmed().toULong();
            upload  = lists[2].trimmed().toULong();
        }
        emit networkData(upload, download);
    }
}

void MusicNetworkTestThread::start()
{
    m_run = true;
    QThread::start();
}

void MusicNetworkTestThread::run()
{
#ifdef Q_OS_WIN
    PMIB_IFTABLE m_pTable = nullptr;
    DWORD m_dwAdapters = 0;
    ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
    if(uRetCode == ERROR_NOT_SUPPORTED)
    {
        return;
    }

    if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
    {
        m_pTable = (PMIB_IFTABLE)new BYTE[65535];
    }

    DWORD dwLastIn = 0;
    DWORD dwLastOut = 0;
    DWORD dwBandIn = 0;
    DWORD dwBandOut = 0;
    while(m_run)
    {
        GetIfTable(m_pTable, &m_dwAdapters, TRUE);
        DWORD dwInOctets = 0;
        DWORD dwOutOctets = 0;

        for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
        {
            MIB_IFROW Row = m_pTable->table[i];
            std::string s(MReinterpret_cast(char const*, Row.bDescr));
            if(Row.dwType == 71 && m_names.contains(QString::fromStdString(s)))
            {
                dwInOctets += Row.dwInOctets;
                dwOutOctets += Row.dwOutOctets;
            }
        }

        dwBandIn = dwInOctets - dwLastIn;
        dwBandOut = dwOutOctets - dwLastOut;
        if(dwLastIn <= 0)
        {
            dwBandIn = 0;
        }

        if (dwLastOut <= 0)
        {
            dwBandOut = 0;
        }
        dwLastIn = dwInOctets;
        dwLastOut = dwOutOctets;

        emit networkData(dwBandOut, dwBandIn);
        sleep(1);
    }
    delete[] m_pTable;
#endif
}
<|endoftext|>


<commit_before>/*
  File: cfvmain.cpp
  Notes:
  - Look at the backside of this page for the questions pertaining this work
*/
#include "cfloatvector.h"
int main()
{
  // 1. Create two CFloatVectors `first_list` and `second_list` with capacities 5 and 10.
  CFloatVector first_list(5);
  CFloatVector second_list(10);

  // 2. Push the values `1.0 1.0 2.0 3.0 5.0` to the back of `first_list` (in the order presented)

  first_list.push_back(1.0);
  first_list.push_back(1.0);
  first_list.push_back(2.0);
  first_list.push_back(3.0);
  first_list.push_back(5.0);

  // 3. Push the seven even numbers from 2 to 14 to the back of `second_list` (in increasing order)
  for(float i = 2.0; i <= 14.0; i+=2.0)
  {
    second_list.push_back(i);
  }

  // 4. Copy the contents of `second_list` to a new CFloatVector called `third_list`
  CFloatVector third_list(second_list);

  // 5. Push the value `2.718` to the back of `first_list`
  first_list.push_back(2.718);

  // 6. Print the contents of `first_list`, `second_list`, and `third_list`
  cout << "First list:\n";
  first_list.print_contents();
  cout << "Second list:\n";
  second_list.print_contents();
  cout << "Third list:\n";
  third_list.print_contents();

  // 7. Print the last element of each list
  cout << "first_list's last element: "    << first_list.at(third_list.size()-1)
       << "\nsecond_list's last element: " << second_list.at(third_list.size()-1)
       << "\nthird_list's last_element: "  << third_list.at(third_list.size()-1)
       << endl;

  // 8. Using the methods of CFloatVector, print if `first_list` is empty, what the size and max
  //    capacity of `second_list` is, and if `third_list` is full
  cout << "First list is empty: "  << first_list.is_empty()
       << "\nSecond list's size: " << second_list.size()
       << "\nSecond list's capacity: " << second_list.max_size()
       << "\nThird list is full: " << (third_list.size() == third_list.max_size()) << endl;

  // 9. Clear `second_list` and `third_list`, and pop the back of `first_list` twice
  second_list.clear();
  third_list.clear();
  first_list.pop_back();
  first_list.pop_back();

  // 10. Print the contents of each list again
  cout << "First list:\n";
  first_list.print_contents();
  cout << "Second list:\n";
  second_list.print_contents();
  cout << "Third list:\n";
  third_list.print_contents();
  return 0;
}

/*
  Questions/Problems:
  1. Fill out cfloatvector.h and cfvmain.cpp if you have not yet.

  ANSWER: Check this file and cfloatvector.h in the solutions folder.

  2. On the right of each line that produces output, write out what its output would be.

  ANSWER: Check out output.md in the solutions folder.

  3. In cfvmain.cpp, are any includes required? If so, which? Explain your answer.

  ANSWER: `#include "cfloatvector.h" is required because we need it to actually use the class. The header
          file `cfloatvector.h` already has `#include <iostream>` in it, so any refernces to iostream in the
          main file are covered already.

  4. What methods, if any, would you consider useful to include with CFloatVector?

  Examples:
  - is_full(): see if list is full
  - front(): get first element
  - back(): get last element
  - append(CFloatVector): append (i.e. add to end) another CFloatVector to another (if capable)

  5. Give an example of how implementing the default constructor may look like.

  CFloatVector::CFloatVector() : CAPACITY(100) // set default capacity to 100 or some arbitrary value
  {
    count = 0;
  }

*/
<commit_msg>remove bad worksheet<commit_after><|endoftext|>


<commit_before>/* Generated file, do not edit */

#ifndef CXXTEST_RUNNING
#define CXXTEST_RUNNING
#endif

#define _CXXTEST_HAVE_STD
#include <cxxtest/TestListener.h>
#include <cxxtest/TestTracker.h>
#include <cxxtest/TestRunner.h>
#include <cxxtest/RealDescriptions.h>
#include <cxxtest/TestMain.h>
#include <cxxtest/ParenPrinter.h>

int main( int argc, char *argv[] ) {
 int status;
    CxxTest::ParenPrinter tmp;
    CxxTest::RealWorldDescription::_worldName = "cxxtest";
    status = CxxTest::Main< CxxTest::ParenPrinter >( tmp, argc, argv );
    return status;
}
bool suite_VMTestSuite_init = false;
#include "C:\Users\Anton Jansson\Documents\GitHub\StackJIT\tests\vm-test.h"

static VMTestSuite suite_VMTestSuite;

static CxxTest::List Tests_VMTestSuite = { 0, 0 };
CxxTest::StaticSuiteDescription suiteDescription_VMTestSuite( "../../tests/vm-test.h", 97, "VMTestSuite", suite_VMTestSuite, Tests_VMTestSuite );

static class TestDescription_suite_VMTestSuite_testBasic : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testBasic() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 99, "testBasic" ) {}
 void runTest() { suite_VMTestSuite.testBasic(); }
} testDescription_suite_VMTestSuite_testBasic;

static class TestDescription_suite_VMTestSuite_testStack : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testStack() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 119, "testStack" ) {}
 void runTest() { suite_VMTestSuite.testStack(); }
} testDescription_suite_VMTestSuite_testStack;

static class TestDescription_suite_VMTestSuite_testCall : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testCall() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 127, "testCall" ) {}
 void runTest() { suite_VMTestSuite.testCall(); }
} testDescription_suite_VMTestSuite_testCall;

static class TestDescription_suite_VMTestSuite_testComparison : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testComparison() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 159, "testComparison" ) {}
 void runTest() { suite_VMTestSuite.testComparison(); }
} testDescription_suite_VMTestSuite_testComparison;

static class TestDescription_suite_VMTestSuite_testBranch : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testBranch() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 181, "testBranch" ) {}
 void runTest() { suite_VMTestSuite.testBranch(); }
} testDescription_suite_VMTestSuite_testBranch;

static class TestDescription_suite_VMTestSuite_testString : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testString() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 223, "testString" ) {}
 void runTest() { suite_VMTestSuite.testString(); }
} testDescription_suite_VMTestSuite_testString;

static class TestDescription_suite_VMTestSuite_testArray : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testArray() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 228, "testArray" ) {}
 void runTest() { suite_VMTestSuite.testArray(); }
} testDescription_suite_VMTestSuite_testArray;

static class TestDescription_suite_VMTestSuite_testClasses : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testClasses() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 240, "testClasses" ) {}
 void runTest() { suite_VMTestSuite.testClasses(); }
} testDescription_suite_VMTestSuite_testClasses;

static class TestDescription_suite_VMTestSuite_testException : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testException() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 271, "testException" ) {}
 void runTest() { suite_VMTestSuite.testException(); }
} testDescription_suite_VMTestSuite_testException;

static class TestDescription_suite_VMTestSuite_testGC : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testGC() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 286, "testGC" ) {}
 void runTest() { suite_VMTestSuite.testGC(); }
} testDescription_suite_VMTestSuite_testGC;

static class TestDescription_suite_VMTestSuite_testFunction : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testFunction() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 302, "testFunction" ) {}
 void runTest() { suite_VMTestSuite.testFunction(); }
} testDescription_suite_VMTestSuite_testFunction;

static class TestDescription_suite_VMTestSuite_testInvalid : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testInvalid() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 313, "testInvalid" ) {}
 void runTest() { suite_VMTestSuite.testInvalid(); }
} testDescription_suite_VMTestSuite_testInvalid;

static class TestDescription_suite_VMTestSuite_testLibrary : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testLibrary() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 324, "testLibrary" ) {}
 void runTest() { suite_VMTestSuite.testLibrary(); }
} testDescription_suite_VMTestSuite_testLibrary;

static class TestDescription_suite_VMTestSuite_testAttributes : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testAttributes() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 374, "testAttributes" ) {}
 void runTest() { suite_VMTestSuite.testAttributes(); }
} testDescription_suite_VMTestSuite_testAttributes;

static class TestDescription_suite_VMTestSuite_testLazy : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testLazy() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 379, "testLazy" ) {}
 void runTest() { suite_VMTestSuite.testLazy(); }
} testDescription_suite_VMTestSuite_testLazy;

#include <cxxtest/Root.cpp>
const char* CxxTest::RealWorldDescription::_worldName = "cxxtest";
<commit_msg>Updated tests.<commit_after>/* Generated file, do not edit */

#ifndef CXXTEST_RUNNING
#define CXXTEST_RUNNING
#endif

#define _CXXTEST_HAVE_STD
#include <cxxtest/TestListener.h>
#include <cxxtest/TestTracker.h>
#include <cxxtest/TestRunner.h>
#include <cxxtest/RealDescriptions.h>
#include <cxxtest/TestMain.h>
#include <cxxtest/ParenPrinter.h>

int main( int argc, char *argv[] ) {
 int status;
    CxxTest::ParenPrinter tmp;
    CxxTest::RealWorldDescription::_worldName = "cxxtest";
    status = CxxTest::Main< CxxTest::ParenPrinter >( tmp, argc, argv );
    return status;
}
bool suite_VMTestSuite_init = false;
#include "C:\Users\Anton Jansson\Documents\GitHub\StackJIT\tests\vm-test.h"

static VMTestSuite suite_VMTestSuite;

static CxxTest::List Tests_VMTestSuite = { 0, 0 };
CxxTest::StaticSuiteDescription suiteDescription_VMTestSuite( "../../tests/vm-test.h", 78, "VMTestSuite", suite_VMTestSuite, Tests_VMTestSuite );

static class TestDescription_suite_VMTestSuite_testBasic : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testBasic() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 80, "testBasic" ) {}
 void runTest() { suite_VMTestSuite.testBasic(); }
} testDescription_suite_VMTestSuite_testBasic;

static class TestDescription_suite_VMTestSuite_testStack : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testStack() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 100, "testStack" ) {}
 void runTest() { suite_VMTestSuite.testStack(); }
} testDescription_suite_VMTestSuite_testStack;

static class TestDescription_suite_VMTestSuite_testCall : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testCall() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 108, "testCall" ) {}
 void runTest() { suite_VMTestSuite.testCall(); }
} testDescription_suite_VMTestSuite_testCall;

static class TestDescription_suite_VMTestSuite_testComparison : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testComparison() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 140, "testComparison" ) {}
 void runTest() { suite_VMTestSuite.testComparison(); }
} testDescription_suite_VMTestSuite_testComparison;

static class TestDescription_suite_VMTestSuite_testBranch : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testBranch() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 162, "testBranch" ) {}
 void runTest() { suite_VMTestSuite.testBranch(); }
} testDescription_suite_VMTestSuite_testBranch;

static class TestDescription_suite_VMTestSuite_testString : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testString() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 204, "testString" ) {}
 void runTest() { suite_VMTestSuite.testString(); }
} testDescription_suite_VMTestSuite_testString;

static class TestDescription_suite_VMTestSuite_testArray : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testArray() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 209, "testArray" ) {}
 void runTest() { suite_VMTestSuite.testArray(); }
} testDescription_suite_VMTestSuite_testArray;

static class TestDescription_suite_VMTestSuite_testClasses : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testClasses() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 221, "testClasses" ) {}
 void runTest() { suite_VMTestSuite.testClasses(); }
} testDescription_suite_VMTestSuite_testClasses;

static class TestDescription_suite_VMTestSuite_testException : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testException() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 252, "testException" ) {}
 void runTest() { suite_VMTestSuite.testException(); }
} testDescription_suite_VMTestSuite_testException;

static class TestDescription_suite_VMTestSuite_testGC : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testGC() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 267, "testGC" ) {}
 void runTest() { suite_VMTestSuite.testGC(); }
} testDescription_suite_VMTestSuite_testGC;

static class TestDescription_suite_VMTestSuite_testFunction : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testFunction() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 283, "testFunction" ) {}
 void runTest() { suite_VMTestSuite.testFunction(); }
} testDescription_suite_VMTestSuite_testFunction;

static class TestDescription_suite_VMTestSuite_testInvalid : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testInvalid() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 294, "testInvalid" ) {}
 void runTest() { suite_VMTestSuite.testInvalid(); }
} testDescription_suite_VMTestSuite_testInvalid;

static class TestDescription_suite_VMTestSuite_testLibrary : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testLibrary() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 305, "testLibrary" ) {}
 void runTest() { suite_VMTestSuite.testLibrary(); }
} testDescription_suite_VMTestSuite_testLibrary;

static class TestDescription_suite_VMTestSuite_testAttributes : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testAttributes() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 355, "testAttributes" ) {}
 void runTest() { suite_VMTestSuite.testAttributes(); }
} testDescription_suite_VMTestSuite_testAttributes;

static class TestDescription_suite_VMTestSuite_testLazy : public CxxTest::RealTestDescription {
public:
 TestDescription_suite_VMTestSuite_testLazy() : CxxTest::RealTestDescription( Tests_VMTestSuite, suiteDescription_VMTestSuite, 360, "testLazy" ) {}
 void runTest() { suite_VMTestSuite.testLazy(); }
} testDescription_suite_VMTestSuite_testLazy;

#include <cxxtest/Root.cpp>
const char* CxxTest::RealWorldDescription::_worldName = "cxxtest";
<|endoftext|>


<commit_before>/**
 * @file neighbor_search.hpp
 * @author Ryan Curtin
 *
 * Defines the NeighborSearch class, which performs an abstract
 * nearest-neighbor-like query on two datasets.
 */
#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_HPP
#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_HPP

#include <mlpack/core.hpp>
#include <vector>
#include <string>

#include <mlpack/core/tree/binary_space_tree.hpp>
#include <mlpack/core/tree/rectangle_tree.hpp>
#include <mlpack/core/tree/binary_space_tree/binary_space_tree.hpp>

#include <mlpack/core/metrics/lmetric.hpp>
#include "neighbor_search_stat.hpp"
#include "sort_policies/nearest_neighbor_sort.hpp"
#include "neighbor_search_rules.hpp"

namespace mlpack {
namespace neighbor /** Neighbor-search routines.  These include
                    * all-nearest-neighbors and all-furthest-neighbors
                    * searches. */ {

/**
 * The NeighborSearch class is a template class for performing distance-based
 * neighbor searches.  It takes a query dataset and a reference dataset (or just
 * a reference dataset) and, for each point in the query dataset, finds the k
 * neighbors in the reference dataset which have the 'best' distance according
 * to a given sorting policy.  A constructor is given which takes only a
 * reference dataset, and if that constructor is used, the given reference
 * dataset is also used as the query dataset.
 *
 * The template parameters SortPolicy and Metric define the sort function used
 * and the metric (distance function) used.  More information on those classes
 * can be found in the NearestNeighborSort class and the kernel::ExampleKernel
 * class.
 *
 * @tparam SortPolicy The sort policy for distances; see NearestNeighborSort.
 * @tparam MetricType The metric to use for computation.
 * @tparam TreeType The tree type to use.
 */
template<typename SortPolicy = NearestNeighborSort,
         typename MetricType = mlpack::metric::SquaredEuclideanDistance,
         typename TreeType = tree::BinarySpaceTree<bound::HRectBound<2>,
             NeighborSearchStat<SortPolicy>>,
         template<typename RuleType> class TraversalType =
             TreeType::template DualTreeTraverser>
class NeighborSearch
{
 public:
  /**
   * Initialize the NeighborSearch object, passing a reference dataset (this is
   * the dataset which is searched).  Optionally, perform the computation in
   * naive mode or single-tree mode.  An initialized distance metric can be
   * given, for cases where the metric has internal data (i.e. the
   * distance::MahalanobisDistance class).
   *
   * This method will copy the matrices to internal copies, which are rearranged
   * during tree-building.  You can avoid this extra copy by pre-constructing
   * the trees and passing them using a diferent constructor.
   *
   * @param referenceSet Set of reference points.
   * @param naive If true, O(n^2) naive search will be used (as opposed to
   *      dual-tree search).  This overrides singleMode (if it is set to true).
   * @param singleMode If true, single-tree search will be used (as opposed to
   *      dual-tree search).
   * @param metric An optional instance of the MetricType class.
   */
  NeighborSearch(const typename TreeType::Mat& referenceSet,
                 const bool naive = false,
                 const bool singleMode = false,
                 const MetricType metric = MetricType());

  /**
   * Initialize the NeighborSearch object with the given pre-constructed
   * reference tree (this is the tree built on the points that will be
   * searched).  Optionally, choose to use single-tree mode.  Naive mode is not
   * available as an option for this constructor.  Additionally, an instantiated
   * distance metric can be given, for cases where the distance metric holds
   * data.
   *
   * There is no copying of the data matrices in this constructor (because
   * tree-building is not necessary), so this is the constructor to use when
   * copies absolutely must be avoided.
   *
   * @note
   * Because tree-building (at least with BinarySpaceTree) modifies the ordering
   * of a matrix, be sure you pass the modified matrix to this object!  In
   * addition, mapping the points of the matrix back to their original indices
   * is not done when this constructor is used.
   * @endnote
   *
   * @param referenceTree Pre-built tree for reference points.
   * @param referenceSet Set of reference points corresponding to referenceTree.
   * @param singleMode Whether single-tree computation should be used (as
   *      opposed to dual-tree computation).
   * @param metric Instantiated distance metric.
   */
  NeighborSearch(TreeType* referenceTree,
                 const bool singleMode = false,
                 const MetricType metric = MetricType());

  /**
   * Delete the NeighborSearch object. The tree is the only member we are
   * responsible for deleting.  The others will take care of themselves.
   */
  ~NeighborSearch();

  /**
   * For each point in the query set, compute the nearest neighbors and store
   * the output in the given matrices.  The matrices will be set to the size of
   * n columns by k rows, where n is the number of points in the query dataset
   * and k is the number of neighbors being searched for.
   *
   * If querySet contains only a few query points, the extra cost of building a
   * tree on the points for dual-tree search may not be warranted, and it may be
   * worthwhile to set singleMode = false (either in the constructor or with
   * SingleMode()).
   *
   * @param querySet Set of query points (can be just one point).
   * @param k Number of neighbors to search for.
   * @param neighbors Matrix storing lists of neighbors for each query point.
   * @param distances Matrix storing distances of neighbors for each query
   *     point.
   */
  void Search(const typename TreeType::Mat& querySet,
              const size_t k,
              arma::Mat<size_t>& neighbors,
              arma::mat& distances);

  /**
   * Given a pre-built query tree, search for the nearest neighbors of each
   * point in the query tree, storing the output in the given matrices.  The
   * matrices will be set to the size of n columns by k rows, where n is the
   * number of points in the query dataset and k is the number of neighbors
   * being searched for.
   *
   * @param queryTree Tree built on query points.
   * @param k Number of neighbors to search for.
   * @param neighbors Matrix storing lists of neighbors for each query point.
   * @param distances Matrix storing distances of neighbors for each query
   *      point.
   */
  void Search(TreeType* queryTree,
              const size_t k,
              arma::Mat<size_t>& neighbors,
              arma::mat& distances);

  /**
   * Search for the nearest neighbors of every point in the reference set.  This
   * is basically equivalent to calling any other overload of Search() with the
   * reference set as the query set; so, this lets you do
   * all-k-nearest-neighbors search.  The results are stored in the given
   * matrices.  The matrices will be set to the size of n columns by k rows,
   * where n is the number of points in the query dataset and k is the number of
   * neighbors being searched for.
   *
   * @param k Number of neighbors to search for.
   * @param neighbors Matrix storing lists of neighbors for each query point.
   * @param distances Matrix storing distances of neighbors for each query
   *      point.
   */
  void Search(const size_t k,
              arma::Mat<size_t>& neighbors,
              arma::mat& distances);

  //! Returns a string representation of this object.
  std::string ToString() const;

  //! Return the total number of base case evaluations performed during
  //! searches.
  size_t BaseCases() const { return baseCases; }
  //! Modify the total number of base case evaluations.
  size_t& BaseCases() { return baseCases; }

  //! Return the number of node combination scores during the search.
  size_t Scores() const { return scores; }
  //! Modify the number of node combination scores.
  size_t& Scores() { return scores; }

  //! Access whether or not search is done in single-tree mode.
  bool SingleMode() const { return singleMode; }
  //! Modify whether or not search is done in single-tree mode.
  bool& SingleMode() { return singleMode; }

 private:
  //! Permutations of reference points during tree building.
  std::vector<size_t> oldFromNewReferences;
  //! Pointer to the root of the reference tree.
  TreeType* referenceTree;
  //! Reference to reference dataset.
  const typename TreeType::Mat& referenceSet;

  //! If true, this object created the trees and is responsible for them.
  bool treeOwner;
  //! Indicates if a separate query set was passed.
  bool hasQuerySet;

  //! Indicates if O(n^2) naive search is being used.
  bool naive;
  //! Indicates if single-tree search is being used (opposed to dual-tree).
  bool singleMode;

  //! Instantiation of metric.
  MetricType metric;

  //! The total number of base cases.
  size_t baseCases;
  //! The total number of scores (applicable for non-naive search).
  size_t scores;

}; // class NeighborSearch

}; // namespace neighbor
}; // namespace mlpack

// Include implementation.
#include "neighbor_search_impl.hpp"

// Include convenience typedefs.
#include "typedef.hpp"

#endif
<commit_msg>Remove unused bool.<commit_after>/**
 * @file neighbor_search.hpp
 * @author Ryan Curtin
 *
 * Defines the NeighborSearch class, which performs an abstract
 * nearest-neighbor-like query on two datasets.
 */
#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_HPP
#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_HPP

#include <mlpack/core.hpp>
#include <vector>
#include <string>

#include <mlpack/core/tree/binary_space_tree.hpp>
#include <mlpack/core/tree/rectangle_tree.hpp>
#include <mlpack/core/tree/binary_space_tree/binary_space_tree.hpp>

#include <mlpack/core/metrics/lmetric.hpp>
#include "neighbor_search_stat.hpp"
#include "sort_policies/nearest_neighbor_sort.hpp"
#include "neighbor_search_rules.hpp"

namespace mlpack {
namespace neighbor /** Neighbor-search routines.  These include
                    * all-nearest-neighbors and all-furthest-neighbors
                    * searches. */ {

/**
 * The NeighborSearch class is a template class for performing distance-based
 * neighbor searches.  It takes a query dataset and a reference dataset (or just
 * a reference dataset) and, for each point in the query dataset, finds the k
 * neighbors in the reference dataset which have the 'best' distance according
 * to a given sorting policy.  A constructor is given which takes only a
 * reference dataset, and if that constructor is used, the given reference
 * dataset is also used as the query dataset.
 *
 * The template parameters SortPolicy and Metric define the sort function used
 * and the metric (distance function) used.  More information on those classes
 * can be found in the NearestNeighborSort class and the kernel::ExampleKernel
 * class.
 *
 * @tparam SortPolicy The sort policy for distances; see NearestNeighborSort.
 * @tparam MetricType The metric to use for computation.
 * @tparam TreeType The tree type to use.
 */
template<typename SortPolicy = NearestNeighborSort,
         typename MetricType = mlpack::metric::SquaredEuclideanDistance,
         typename TreeType = tree::BinarySpaceTree<bound::HRectBound<2>,
             NeighborSearchStat<SortPolicy>>,
         template<typename RuleType> class TraversalType =
             TreeType::template DualTreeTraverser>
class NeighborSearch
{
 public:
  /**
   * Initialize the NeighborSearch object, passing a reference dataset (this is
   * the dataset which is searched).  Optionally, perform the computation in
   * naive mode or single-tree mode.  An initialized distance metric can be
   * given, for cases where the metric has internal data (i.e. the
   * distance::MahalanobisDistance class).
   *
   * This method will copy the matrices to internal copies, which are rearranged
   * during tree-building.  You can avoid this extra copy by pre-constructing
   * the trees and passing them using a diferent constructor.
   *
   * @param referenceSet Set of reference points.
   * @param naive If true, O(n^2) naive search will be used (as opposed to
   *      dual-tree search).  This overrides singleMode (if it is set to true).
   * @param singleMode If true, single-tree search will be used (as opposed to
   *      dual-tree search).
   * @param metric An optional instance of the MetricType class.
   */
  NeighborSearch(const typename TreeType::Mat& referenceSet,
                 const bool naive = false,
                 const bool singleMode = false,
                 const MetricType metric = MetricType());

  /**
   * Initialize the NeighborSearch object with the given pre-constructed
   * reference tree (this is the tree built on the points that will be
   * searched).  Optionally, choose to use single-tree mode.  Naive mode is not
   * available as an option for this constructor.  Additionally, an instantiated
   * distance metric can be given, for cases where the distance metric holds
   * data.
   *
   * There is no copying of the data matrices in this constructor (because
   * tree-building is not necessary), so this is the constructor to use when
   * copies absolutely must be avoided.
   *
   * @note
   * Because tree-building (at least with BinarySpaceTree) modifies the ordering
   * of a matrix, be sure you pass the modified matrix to this object!  In
   * addition, mapping the points of the matrix back to their original indices
   * is not done when this constructor is used.
   * @endnote
   *
   * @param referenceTree Pre-built tree for reference points.
   * @param referenceSet Set of reference points corresponding to referenceTree.
   * @param singleMode Whether single-tree computation should be used (as
   *      opposed to dual-tree computation).
   * @param metric Instantiated distance metric.
   */
  NeighborSearch(TreeType* referenceTree,
                 const bool singleMode = false,
                 const MetricType metric = MetricType());

  /**
   * Delete the NeighborSearch object. The tree is the only member we are
   * responsible for deleting.  The others will take care of themselves.
   */
  ~NeighborSearch();

  /**
   * For each point in the query set, compute the nearest neighbors and store
   * the output in the given matrices.  The matrices will be set to the size of
   * n columns by k rows, where n is the number of points in the query dataset
   * and k is the number of neighbors being searched for.
   *
   * If querySet contains only a few query points, the extra cost of building a
   * tree on the points for dual-tree search may not be warranted, and it may be
   * worthwhile to set singleMode = false (either in the constructor or with
   * SingleMode()).
   *
   * @param querySet Set of query points (can be just one point).
   * @param k Number of neighbors to search for.
   * @param neighbors Matrix storing lists of neighbors for each query point.
   * @param distances Matrix storing distances of neighbors for each query
   *     point.
   */
  void Search(const typename TreeType::Mat& querySet,
              const size_t k,
              arma::Mat<size_t>& neighbors,
              arma::mat& distances);

  /**
   * Given a pre-built query tree, search for the nearest neighbors of each
   * point in the query tree, storing the output in the given matrices.  The
   * matrices will be set to the size of n columns by k rows, where n is the
   * number of points in the query dataset and k is the number of neighbors
   * being searched for.
   *
   * @param queryTree Tree built on query points.
   * @param k Number of neighbors to search for.
   * @param neighbors Matrix storing lists of neighbors for each query point.
   * @param distances Matrix storing distances of neighbors for each query
   *      point.
   */
  void Search(TreeType* queryTree,
              const size_t k,
              arma::Mat<size_t>& neighbors,
              arma::mat& distances);

  /**
   * Search for the nearest neighbors of every point in the reference set.  This
   * is basically equivalent to calling any other overload of Search() with the
   * reference set as the query set; so, this lets you do
   * all-k-nearest-neighbors search.  The results are stored in the given
   * matrices.  The matrices will be set to the size of n columns by k rows,
   * where n is the number of points in the query dataset and k is the number of
   * neighbors being searched for.
   *
   * @param k Number of neighbors to search for.
   * @param neighbors Matrix storing lists of neighbors for each query point.
   * @param distances Matrix storing distances of neighbors for each query
   *      point.
   */
  void Search(const size_t k,
              arma::Mat<size_t>& neighbors,
              arma::mat& distances);

  //! Returns a string representation of this object.
  std::string ToString() const;

  //! Return the total number of base case evaluations performed during
  //! searches.
  size_t BaseCases() const { return baseCases; }
  //! Modify the total number of base case evaluations.
  size_t& BaseCases() { return baseCases; }

  //! Return the number of node combination scores during the search.
  size_t Scores() const { return scores; }
  //! Modify the number of node combination scores.
  size_t& Scores() { return scores; }

  //! Access whether or not search is done in single-tree mode.
  bool SingleMode() const { return singleMode; }
  //! Modify whether or not search is done in single-tree mode.
  bool& SingleMode() { return singleMode; }

 private:
  //! Permutations of reference points during tree building.
  std::vector<size_t> oldFromNewReferences;
  //! Pointer to the root of the reference tree.
  TreeType* referenceTree;
  //! Reference to reference dataset.
  const typename TreeType::Mat& referenceSet;

  //! If true, this object created the trees and is responsible for them.
  bool treeOwner;

  //! Indicates if O(n^2) naive search is being used.
  bool naive;
  //! Indicates if single-tree search is being used (opposed to dual-tree).
  bool singleMode;

  //! Instantiation of metric.
  MetricType metric;

  //! The total number of base cases.
  size_t baseCases;
  //! The total number of scores (applicable for non-naive search).
  size_t scores;

}; // class NeighborSearch

}; // namespace neighbor
}; // namespace mlpack

// Include implementation.
#include "neighbor_search_impl.hpp"

// Include convenience typedefs.
#include "typedef.hpp"

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * 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/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/util/XNumberFormatter.hpp>
#include <com/sun/star/sdbc/ColumnSearch.hpp>
#include <com/sun/star/sdbc/DataType.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#include <com/sun/star/lang/ServiceNotRegisteredException.hpp>
#include <comphelper/sequence.hxx>
#include <com/sun/star/uno/XAggregation.hpp>
#include <comphelper/processfactory.hxx>
#include "dbastrings.hrc"
#include <cppuhelper/typeprovider.hxx>
#include <unotools/configmgr.hxx>
#include <comphelper/types.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/i18n/XLocaleData.hpp>
#include <unotools/syslocale.hxx>
#include <com/sun/star/container/XChild.hpp>
#include <com/sun/star/sdb/SQLFilterOperator.hpp>
#include "querycomposer.hxx"
#include "HelperCollections.hxx"
#include "composertools.hxx"
#include <algorithm>
#include <rtl/logfile.hxx>

using namespace dbaccess;
using namespace dbtools;
using namespace comphelper;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::i18n;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::script;
using namespace ::cppu;
using namespace ::osl;
using namespace ::utl;

DBG_NAME(OQueryComposer)

OQueryComposer::OQueryComposer(const Reference< XConnection>& _xConnection)
 : OSubComponent(m_aMutex,_xConnection)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::OQueryComposer" );
    DBG_CTOR(OQueryComposer,NULL);
    OSL_ENSURE(_xConnection.is()," Connection cant be null!");

    Reference<XMultiServiceFactory> xFac( _xConnection, UNO_QUERY_THROW );
    m_xComposer.set( xFac->createInstance( SERVICE_NAME_SINGLESELECTQUERYCOMPOSER ), UNO_QUERY_THROW );
    m_xComposerHelper.set( xFac->createInstance( SERVICE_NAME_SINGLESELECTQUERYCOMPOSER ), UNO_QUERY_THROW );
}

OQueryComposer::~OQueryComposer()
{
    DBG_DTOR(OQueryComposer,NULL);
}

void SAL_CALL OQueryComposer::disposing()
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::disposing" );
    ::comphelper::disposeComponent(m_xComposerHelper);
    ::comphelper::disposeComponent(m_xComposer);
}

// ::com::sun::star::lang::XTypeProvider
Sequence< Type > SAL_CALL OQueryComposer::getTypes() throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getTypes" );
    return ::comphelper::concatSequences(OSubComponent::getTypes(),OQueryComposer_BASE::getTypes());
}

Sequence< sal_Int8 > SAL_CALL OQueryComposer::getImplementationId() throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getImplementationId" );
    static OImplementationId * pId = 0;
    if (! pId)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex() );
        if (! pId)
        {
            static OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

// com::sun::star::lang::XUnoTunnel
sal_Int64 SAL_CALL OQueryComposer::getSomething( const Sequence< sal_Int8 >& rId ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getSomething" );
    if (rId.getLength() == 16 && 0 == memcmp(getImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )
        return reinterpret_cast<sal_Int64>(this);

    return 0;
}

Any SAL_CALL OQueryComposer::queryInterface( const Type & rType ) throw(RuntimeException)
{
    //RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::queryInterface" );
    Any aRet = OSubComponent::queryInterface(rType);
    if(!aRet.hasValue())
        aRet = OQueryComposer_BASE::queryInterface(rType);
    return aRet;
}

// XServiceInfo
rtl::OUString OQueryComposer::getImplementationName(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getImplementationName" );
    return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.dbaccess.OQueryComposer"));
}

sal_Bool OQueryComposer::supportsService( const ::rtl::OUString& _rServiceName ) throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::supportsService" );
    return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0;
}

Sequence< ::rtl::OUString > OQueryComposer::getSupportedServiceNames(  ) throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getSupportedServiceNames" );
    Sequence< rtl::OUString > aSNS( 1 );
    aSNS[0] = SERVICE_SDB_SQLQUERYCOMPOSER;
    return aSNS;
}

// XSQLQueryComposer
::rtl::OUString SAL_CALL OQueryComposer::getQuery(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getQuery" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    Reference<XPropertySet> xProp(m_xComposer,UNO_QUERY);
    ::rtl::OUString sQuery;
    if ( xProp.is() )
        xProp->getPropertyValue(PROPERTY_ORIGINAL) >>= sQuery;
    return sQuery;
}

void SAL_CALL OQueryComposer::setQuery( const ::rtl::OUString& command ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::setQuery" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    m_aFilters.clear();
    m_xComposer->setQuery(command);
    m_sOrgFilter = m_xComposer->getFilter();
    m_sOrgOrder = m_xComposer->getOrder();
}

::rtl::OUString SAL_CALL OQueryComposer::getComposedQuery(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getComposedQuery" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    MutexGuard aGuard(m_aMutex);

    return m_xComposer->getQuery();
}

::rtl::OUString SAL_CALL OQueryComposer::getFilter(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getFilter" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);
    MutexGuard aGuard(m_aMutex);
    FilterCreator aFilterCreator;
    aFilterCreator = ::std::for_each(m_aFilters.begin(),m_aFilters.end(),aFilterCreator);
    return aFilterCreator.getComposedAndClear();
}

Sequence< Sequence< PropertyValue > > SAL_CALL OQueryComposer::getStructuredFilter(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getStructuredFilter" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    MutexGuard aGuard(m_aMutex);
    return m_xComposer->getStructuredFilter();
}

::rtl::OUString SAL_CALL OQueryComposer::getOrder(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getOrder" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    OrderCreator aOrderCreator;
    aOrderCreator = ::std::for_each(m_aOrders.begin(),m_aOrders.end(),aOrderCreator);
    return aOrderCreator.getComposedAndClear();
}

void SAL_CALL OQueryComposer::appendFilterByColumn( const Reference< XPropertySet >& column ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::appendFilterByColumn" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( m_aMutex );

    m_xComposerHelper->setQuery(getQuery());
    m_xComposerHelper->setFilter(::rtl::OUString());
    m_xComposerHelper->appendFilterByColumn(column, sal_True, SQLFilterOperator::EQUAL);

    FilterCreator aFilterCreator;
    aFilterCreator.append(getFilter());
    aFilterCreator.append(m_xComposerHelper->getFilter());

    setFilter( aFilterCreator.getComposedAndClear() );
}

void SAL_CALL OQueryComposer::appendOrderByColumn( const Reference< XPropertySet >& column, sal_Bool ascending ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::appendOrderByColumn" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( m_aMutex );

    m_xComposerHelper->setQuery(getQuery());
    m_xComposerHelper->setOrder(::rtl::OUString());
    m_xComposerHelper->appendOrderByColumn(column,ascending);

    OrderCreator aOrderCreator;
    aOrderCreator.append(getOrder());
    aOrderCreator.append(m_xComposerHelper->getOrder());

    setOrder(aOrderCreator.getComposedAndClear());
}

void SAL_CALL OQueryComposer::setFilter( const ::rtl::OUString& filter ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::setFilter" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    FilterCreator aFilterCreator;
    aFilterCreator.append(m_sOrgFilter);
    aFilterCreator.append(filter);

    m_aFilters.clear();
    if ( !filter.isEmpty() )
        m_aFilters.push_back(filter);

    m_xComposer->setFilter( aFilterCreator.getComposedAndClear() );
}

void SAL_CALL OQueryComposer::setOrder( const ::rtl::OUString& order ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::setOrder" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );

    OrderCreator aOrderCreator;
    aOrderCreator.append(m_sOrgOrder);
    aOrderCreator.append(order);

    m_aOrders.clear();
    if ( !order.isEmpty() )
        m_aOrders.push_back(order);

    m_xComposer->setOrder(aOrderCreator.getComposedAndClear());
}

// XTablesSupplier
Reference< XNameAccess > SAL_CALL OQueryComposer::getTables(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getTables" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    return Reference<XTablesSupplier>(m_xComposer,UNO_QUERY)->getTables();
}

// XColumnsSupplier
Reference< XNameAccess > SAL_CALL OQueryComposer::getColumns(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getColumns" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    return Reference<XColumnsSupplier>(m_xComposer,UNO_QUERY)->getColumns();
}

Reference< XIndexAccess > SAL_CALL OQueryComposer::getParameters(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getParameters" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    return Reference<XParametersSupplier>(m_xComposer,UNO_QUERY)->getParameters();
}

void SAL_CALL OQueryComposer::acquire() throw()
{
    OSubComponent::acquire();
}

void SAL_CALL OQueryComposer::release() throw()
{
    OSubComponent::release();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>missing system header<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * 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/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <string.h>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/util/XNumberFormatter.hpp>
#include <com/sun/star/sdbc/ColumnSearch.hpp>
#include <com/sun/star/sdbc/DataType.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#include <com/sun/star/lang/ServiceNotRegisteredException.hpp>
#include <comphelper/sequence.hxx>
#include <com/sun/star/uno/XAggregation.hpp>
#include <comphelper/processfactory.hxx>
#include "dbastrings.hrc"
#include <cppuhelper/typeprovider.hxx>
#include <unotools/configmgr.hxx>
#include <comphelper/types.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/i18n/XLocaleData.hpp>
#include <unotools/syslocale.hxx>
#include <com/sun/star/container/XChild.hpp>
#include <com/sun/star/sdb/SQLFilterOperator.hpp>
#include "querycomposer.hxx"
#include "HelperCollections.hxx"
#include "composertools.hxx"
#include <algorithm>
#include <rtl/logfile.hxx>

using namespace dbaccess;
using namespace dbtools;
using namespace comphelper;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::i18n;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::script;
using namespace ::cppu;
using namespace ::osl;
using namespace ::utl;

DBG_NAME(OQueryComposer)

OQueryComposer::OQueryComposer(const Reference< XConnection>& _xConnection)
 : OSubComponent(m_aMutex,_xConnection)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::OQueryComposer" );
    DBG_CTOR(OQueryComposer,NULL);
    OSL_ENSURE(_xConnection.is()," Connection cant be null!");

    Reference<XMultiServiceFactory> xFac( _xConnection, UNO_QUERY_THROW );
    m_xComposer.set( xFac->createInstance( SERVICE_NAME_SINGLESELECTQUERYCOMPOSER ), UNO_QUERY_THROW );
    m_xComposerHelper.set( xFac->createInstance( SERVICE_NAME_SINGLESELECTQUERYCOMPOSER ), UNO_QUERY_THROW );
}

OQueryComposer::~OQueryComposer()
{
    DBG_DTOR(OQueryComposer,NULL);
}

void SAL_CALL OQueryComposer::disposing()
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::disposing" );
    ::comphelper::disposeComponent(m_xComposerHelper);
    ::comphelper::disposeComponent(m_xComposer);
}

// ::com::sun::star::lang::XTypeProvider
Sequence< Type > SAL_CALL OQueryComposer::getTypes() throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getTypes" );
    return ::comphelper::concatSequences(OSubComponent::getTypes(),OQueryComposer_BASE::getTypes());
}

Sequence< sal_Int8 > SAL_CALL OQueryComposer::getImplementationId() throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getImplementationId" );
    static OImplementationId * pId = 0;
    if (! pId)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex() );
        if (! pId)
        {
            static OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

// com::sun::star::lang::XUnoTunnel
sal_Int64 SAL_CALL OQueryComposer::getSomething( const Sequence< sal_Int8 >& rId ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getSomething" );
    if (rId.getLength() == 16 && 0 == memcmp(getImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )
        return reinterpret_cast<sal_Int64>(this);

    return 0;
}

Any SAL_CALL OQueryComposer::queryInterface( const Type & rType ) throw(RuntimeException)
{
    //RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::queryInterface" );
    Any aRet = OSubComponent::queryInterface(rType);
    if(!aRet.hasValue())
        aRet = OQueryComposer_BASE::queryInterface(rType);
    return aRet;
}

// XServiceInfo
rtl::OUString OQueryComposer::getImplementationName(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getImplementationName" );
    return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.dbaccess.OQueryComposer"));
}

sal_Bool OQueryComposer::supportsService( const ::rtl::OUString& _rServiceName ) throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::supportsService" );
    return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0;
}

Sequence< ::rtl::OUString > OQueryComposer::getSupportedServiceNames(  ) throw (RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getSupportedServiceNames" );
    Sequence< rtl::OUString > aSNS( 1 );
    aSNS[0] = SERVICE_SDB_SQLQUERYCOMPOSER;
    return aSNS;
}

// XSQLQueryComposer
::rtl::OUString SAL_CALL OQueryComposer::getQuery(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getQuery" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    Reference<XPropertySet> xProp(m_xComposer,UNO_QUERY);
    ::rtl::OUString sQuery;
    if ( xProp.is() )
        xProp->getPropertyValue(PROPERTY_ORIGINAL) >>= sQuery;
    return sQuery;
}

void SAL_CALL OQueryComposer::setQuery( const ::rtl::OUString& command ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::setQuery" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    m_aFilters.clear();
    m_xComposer->setQuery(command);
    m_sOrgFilter = m_xComposer->getFilter();
    m_sOrgOrder = m_xComposer->getOrder();
}

::rtl::OUString SAL_CALL OQueryComposer::getComposedQuery(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getComposedQuery" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    MutexGuard aGuard(m_aMutex);

    return m_xComposer->getQuery();
}

::rtl::OUString SAL_CALL OQueryComposer::getFilter(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getFilter" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);
    MutexGuard aGuard(m_aMutex);
    FilterCreator aFilterCreator;
    aFilterCreator = ::std::for_each(m_aFilters.begin(),m_aFilters.end(),aFilterCreator);
    return aFilterCreator.getComposedAndClear();
}

Sequence< Sequence< PropertyValue > > SAL_CALL OQueryComposer::getStructuredFilter(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getStructuredFilter" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    MutexGuard aGuard(m_aMutex);
    return m_xComposer->getStructuredFilter();
}

::rtl::OUString SAL_CALL OQueryComposer::getOrder(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getOrder" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    OrderCreator aOrderCreator;
    aOrderCreator = ::std::for_each(m_aOrders.begin(),m_aOrders.end(),aOrderCreator);
    return aOrderCreator.getComposedAndClear();
}

void SAL_CALL OQueryComposer::appendFilterByColumn( const Reference< XPropertySet >& column ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::appendFilterByColumn" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( m_aMutex );

    m_xComposerHelper->setQuery(getQuery());
    m_xComposerHelper->setFilter(::rtl::OUString());
    m_xComposerHelper->appendFilterByColumn(column, sal_True, SQLFilterOperator::EQUAL);

    FilterCreator aFilterCreator;
    aFilterCreator.append(getFilter());
    aFilterCreator.append(m_xComposerHelper->getFilter());

    setFilter( aFilterCreator.getComposedAndClear() );
}

void SAL_CALL OQueryComposer::appendOrderByColumn( const Reference< XPropertySet >& column, sal_Bool ascending ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::appendOrderByColumn" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( m_aMutex );

    m_xComposerHelper->setQuery(getQuery());
    m_xComposerHelper->setOrder(::rtl::OUString());
    m_xComposerHelper->appendOrderByColumn(column,ascending);

    OrderCreator aOrderCreator;
    aOrderCreator.append(getOrder());
    aOrderCreator.append(m_xComposerHelper->getOrder());

    setOrder(aOrderCreator.getComposedAndClear());
}

void SAL_CALL OQueryComposer::setFilter( const ::rtl::OUString& filter ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::setFilter" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    FilterCreator aFilterCreator;
    aFilterCreator.append(m_sOrgFilter);
    aFilterCreator.append(filter);

    m_aFilters.clear();
    if ( !filter.isEmpty() )
        m_aFilters.push_back(filter);

    m_xComposer->setFilter( aFilterCreator.getComposedAndClear() );
}

void SAL_CALL OQueryComposer::setOrder( const ::rtl::OUString& order ) throw(SQLException, RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::setOrder" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );

    OrderCreator aOrderCreator;
    aOrderCreator.append(m_sOrgOrder);
    aOrderCreator.append(order);

    m_aOrders.clear();
    if ( !order.isEmpty() )
        m_aOrders.push_back(order);

    m_xComposer->setOrder(aOrderCreator.getComposedAndClear());
}

// XTablesSupplier
Reference< XNameAccess > SAL_CALL OQueryComposer::getTables(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getTables" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    return Reference<XTablesSupplier>(m_xComposer,UNO_QUERY)->getTables();
}

// XColumnsSupplier
Reference< XNameAccess > SAL_CALL OQueryComposer::getColumns(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getColumns" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    return Reference<XColumnsSupplier>(m_xComposer,UNO_QUERY)->getColumns();
}

Reference< XIndexAccess > SAL_CALL OQueryComposer::getParameters(  ) throw(RuntimeException)
{
    RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbaccess", "Ocke.Janssen@sun.com", "OQueryComposer::getParameters" );
    ::connectivity::checkDisposed(OSubComponent::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aMutex );
    return Reference<XParametersSupplier>(m_xComposer,UNO_QUERY)->getParameters();
}

void SAL_CALL OQueryComposer::acquire() throw()
{
    OSubComponent::acquire();
}

void SAL_CALL OQueryComposer::release() throw()
{
    OSubComponent::release();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif

namespace dbaui
{
    class OQueryDesignView;
    class OQueryTextView;
    class OAddTableDlg;
    class OQueryContainerWindow;
    class OQueryViewSwitch
    {
        OQueryDesignView*   m_pDesignView;
        OQueryTextView*     m_pTextView;
    public:
        OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
        virtual ~OQueryViewSwitch();

        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual void copy();
        virtual void cut();
        virtual void paste();
        // clears the whole query
        virtual void clear();
        // set the view readonly or not
        virtual void setReadOnly(sal_Bool _bReadOnly);
        // check if the statement is correct when not returning false
        virtual sal_Bool checkStatement();
        // set the statement for representation
        virtual void setStatement(const ::rtl::OUString& _rsStatement);
        // returns the current sql statement
        virtual ::rtl::OUString getStatement();
        /// late construction
        virtual void Construct();
        virtual void initialize();
        /** show the text or the design view
            @return
                <TRUE/> when all went right otherwise <FALSE/> which implies an aditional
                call of switchView from the controller to restore the old state
        */
        sal_Bool switchView();
        sal_Bool isSlotEnabled(sal_Int32 _nSlotId);
        void     setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);
        void     setNoneVisbleRow(sal_Int32 _nRows);
        // returs the add table dialog from the design view
        OAddTableDlg* getAddTableDialog();
        BOOL IsAddAllowed();
        void zoomTableView(const Fraction& _rFraction);
        void SaveUIConfig();
        void clearDesignView();
        void GetFocus();
        void reset();
        void GrabFocus();

        OQueryDesignView*       getDesignView() const { return m_pDesignView; }
        OQueryContainerWindow*  getContainer() const;

        Window* getActive() const;

        void SetPosSizePixel( Point _rPt,Size _rSize);
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const;
    protected:
        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);
    };
}
#endif // DBAUI_QUERYVIEWSWITCH_HXX

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

#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif

namespace dbaui
{
    class OQueryDesignView;
    class OQueryTextView;
    class OAddTableDlg;
    class OQueryContainerWindow;
    class OQueryViewSwitch
    {
        OQueryDesignView*   m_pDesignView;
        OQueryTextView*     m_pTextView;
        sal_Bool            m_bAddTableDialogWasVisible; // true if so
    public:
        OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
        virtual ~OQueryViewSwitch();

        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual void copy();
        virtual void cut();
        virtual void paste();
        // clears the whole query
        virtual void clear();
        // set the view readonly or not
        virtual void setReadOnly(sal_Bool _bReadOnly);
        // check if the statement is correct when not returning false
        virtual sal_Bool checkStatement();
        // set the statement for representation
        virtual void setStatement(const ::rtl::OUString& _rsStatement);
        // returns the current sql statement
        virtual ::rtl::OUString getStatement();
        /// late construction
        virtual void Construct();
        virtual void initialize();
        /** show the text or the design view
            @return
                <TRUE/> when all went right otherwise <FALSE/> which implies an aditional
                call of switchView from the controller to restore the old state
        */
        sal_Bool switchView();
        sal_Bool isSlotEnabled(sal_Int32 _nSlotId);
        void     setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);
        void     setNoneVisbleRow(sal_Int32 _nRows);
        // returs the add table dialog from the design view
        OAddTableDlg* getAddTableDialog();
        BOOL IsAddAllowed();
        void zoomTableView(const Fraction& _rFraction);
        void SaveUIConfig();
        void clearDesignView();
        void GetFocus();
        void reset();
        void GrabFocus();

        OQueryDesignView*       getDesignView() const { return m_pDesignView; }
        OQueryContainerWindow*  getContainer() const;

        Window* getActive() const;

        void SetPosSizePixel( Point _rPt,Size _rSize);
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const;
    protected:
        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);
    };
}
#endif // DBAUI_QUERYVIEWSWITCH_HXX

<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <iostream>
#include "gmxtopologyreader.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#if GMX == 50
        #include <gromacs/legacyheaders/statutil.h>
        #include <gromacs/legacyheaders/typedefs.h>
        #include <gromacs/legacyheaders/smalloc.h>
        #include <gromacs/legacyheaders/vec.h>
        #include <gromacs/legacyheaders/copyrite.h>
        #include <gromacs/legacyheaders/statutil.h>
        #include <gromacs/legacyheaders/tpxio.h>
#elif GMX == 45
        #include <gromacs/statutil.h>
        #include <gromacs/typedefs.h>
        #include <gromacs/smalloc.h>
        #include <gromacs/vec.h>
        #include <gromacs/copyrite.h>
        #include <gromacs/statutil.h>
        #include <gromacs/tpxio.h>
#elif GMX == 40
    extern "C"
    {
        #include <statutil.h>
        #include <typedefs.h>
        #include <smalloc.h>
        #include <vec.h>
        #include <copyrite.h>
        #include <statutil.h>
        #include <tpxio.h>
    }
#else
#error Unsupported GMX version
#endif
    // this one is needed because of bool is defined in one of the headers included by gmx
    #undef bool

namespace votca { namespace csg {

bool GMXTopologyReader::ReadTopology(string file, Topology &top)
{
    gmx_mtop_t mtop;

    int natoms;
    // cleanup topology to store new data
    top.Cleanup();
    set_program_name("VOTCA");

#if GMX == 50
    t_inputrec ir;
    ::matrix gbox;

    (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop);
#elif GMX == 45
    t_inputrec ir;
    ::matrix gbox;
    (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop);
#elif GMX == 40
    int sss;   // wtf is this
    ::real    ttt,lll; // wtf is this
    (void)read_tpx((char *)file.c_str(),&sss,&ttt,&lll,NULL,NULL,&natoms,NULL,NULL,NULL,&mtop);
#else
#error Unsupported GMX version
#endif

    int count=0;
    for(int iblock=0; iblock<mtop.nmolblock; ++iblock)
        count+=mtop.molblock[iblock].nmol;

    if(count != mtop.mols.nr  ) {
        throw runtime_error("gromacs topology contains inconsistency in molecule definitons\n\n"
                "A possible reason is an outdated .tpr file. Please rerun grompp to generate a new tpr file.\n"
                "If the problem remains or "
                "you're missing the files to rerun grompp,\n contact the votca mailing list for a solution.");
    }

    for(int iblock=0; iblock<mtop.nmolblock; ++iblock) {
        gmx_moltype_t *mol
                = &(mtop.moltype[mtop.molblock[iblock].type]);

        string molname =  *(mol->name);

        int res_offset = top.ResidueCount();

        t_atoms *atoms=&(mol->atoms);

        for(int i=0; i < atoms->nres; i++) {
#if GMX == 50
                top.CreateResidue(*(atoms->resinfo[i].name));
#elif GMX == 45
                top.CreateResidue(*(atoms->resinfo[i].name));
#elif GMX == 40
                top.CreateResidue(*(atoms->resname[i]));
#else
#error Unsupported GMX version
#endif
        }

        int ifirstatom = 0;
        for(int imol=0; imol<mtop.molblock[iblock].nmol; ++imol) {
            Molecule *mi = top.CreateMolecule(molname);

            // read the atoms
            for(int iatom=0; iatom<mtop.molblock[iblock].natoms_mol; iatom++) {
                t_atom *a = &(atoms->atom[iatom]);

                // read exclusions
                t_blocka * excl = &(mol->excls);
                // insert exclusions
                list<int> excl_list;
                for(int k=excl->index[iatom]; k<excl->index[iatom+1]; k++) {
                    excl_list.push_back(excl->a[k]+ifirstatom);
                }
                top.InsertExclusion(iatom, excl_list);

                BeadType *type = top.GetOrCreateBeadType(*(atoms->atomtype[iatom]));
#if GMX == 50
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q);
#elif GMX == 45
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q);
#elif GMX == 40
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resnr, a->m, a->q);
#else
#error Unsupported GMX version
#endif

                stringstream nm;
                nm << bead->getResnr() + 1 << ":" <<  top.getResidue(res_offset + bead->getResnr())->getName() << ":" << bead->getName();
                mi->AddBead(bead, nm.str());
            }
            ifirstatom+=mtop.molblock[iblock].natoms_mol;
        }
    }

    return true;
}

}}
<commit_msg>fixed bug when reading exclusions from tpr<commit_after>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <iostream>
#include "gmxtopologyreader.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#if GMX == 50
        #include <gromacs/legacyheaders/statutil.h>
        #include <gromacs/legacyheaders/typedefs.h>
        #include <gromacs/legacyheaders/smalloc.h>
        #include <gromacs/legacyheaders/vec.h>
        #include <gromacs/legacyheaders/copyrite.h>
        #include <gromacs/legacyheaders/statutil.h>
        #include <gromacs/legacyheaders/tpxio.h>
#elif GMX == 45
        #include <gromacs/statutil.h>
        #include <gromacs/typedefs.h>
        #include <gromacs/smalloc.h>
        #include <gromacs/vec.h>
        #include <gromacs/copyrite.h>
        #include <gromacs/statutil.h>
        #include <gromacs/tpxio.h>
#elif GMX == 40
    extern "C"
    {
        #include <statutil.h>
        #include <typedefs.h>
        #include <smalloc.h>
        #include <vec.h>
        #include <copyrite.h>
        #include <statutil.h>
        #include <tpxio.h>
    }
#else
#error Unsupported GMX version
#endif
    // this one is needed because of bool is defined in one of the headers included by gmx
    #undef bool

namespace votca { namespace csg {

bool GMXTopologyReader::ReadTopology(string file, Topology &top)
{
    gmx_mtop_t mtop;

    int natoms;
    // cleanup topology to store new data
    top.Cleanup();
    set_program_name("VOTCA");

#if GMX == 50
    t_inputrec ir;
    ::matrix gbox;

    (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop);
#elif GMX == 45
    t_inputrec ir;
    ::matrix gbox;
    (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop);
#elif GMX == 40
    int sss;   // wtf is this
    ::real    ttt,lll; // wtf is this
    (void)read_tpx((char *)file.c_str(),&sss,&ttt,&lll,NULL,NULL,&natoms,NULL,NULL,NULL,&mtop);
#else
#error Unsupported GMX version
#endif

    int count=0;
    for(int iblock=0; iblock<mtop.nmolblock; ++iblock)
        count+=mtop.molblock[iblock].nmol;

    if(count != mtop.mols.nr  ) {
        throw runtime_error("gromacs topology contains inconsistency in molecule definitons\n\n"
                "A possible reason is an outdated .tpr file. Please rerun grompp to generate a new tpr file.\n"
                "If the problem remains or "
                "you're missing the files to rerun grompp,\n contact the votca mailing list for a solution.");
    }

    for(int iblock=0; iblock<mtop.nmolblock; ++iblock) {
        gmx_moltype_t *mol
                = &(mtop.moltype[mtop.molblock[iblock].type]);

        string molname =  *(mol->name);

        int res_offset = top.ResidueCount();

        t_atoms *atoms=&(mol->atoms);

        for(int i=0; i < atoms->nres; i++) {
#if GMX == 50
                top.CreateResidue(*(atoms->resinfo[i].name));
#elif GMX == 45
                top.CreateResidue(*(atoms->resinfo[i].name));
#elif GMX == 40
                top.CreateResidue(*(atoms->resname[i]));
#else
#error Unsupported GMX version
#endif
        }

        int ifirstatom = 0;
        for(int imol=0; imol<mtop.molblock[iblock].nmol; ++imol) {
            Molecule *mi = top.CreateMolecule(molname);

            // read the atoms
            for(int iatom=0; iatom<mtop.molblock[iblock].natoms_mol; iatom++) {
                t_atom *a = &(atoms->atom[iatom]);

                // read exclusions
                t_blocka * excl = &(mol->excls);
                // insert exclusions
                list<int> excl_list;
                for(int k=excl->index[iatom]; k<excl->index[iatom+1]; k++) {
                    excl_list.push_back(excl->a[k]+ifirstatom);
                }
                top.InsertExclusion(iatom+ifirstatom, excl_list);

                BeadType *type = top.GetOrCreateBeadType(*(atoms->atomtype[iatom]));
#if GMX == 50
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q);
#elif GMX == 45
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q);
#elif GMX == 40
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resnr, a->m, a->q);
#else
#error Unsupported GMX version
#endif

                stringstream nm;
                nm << bead->getResnr() + 1 << ":" <<  top.getResidue(res_offset + bead->getResnr())->getName() << ":" << bead->getName();
                mi->AddBead(bead, nm.str());
            }
            ifirstatom+=mtop.molblock[iblock].natoms_mol;
        }
    }

    return true;
}

}}
<|endoftext|>