<commit_before>#include <DuiApplicationWindow>
#include <DuiApplication>
#include <QDBusInterface>
#include <QDebug>

#include "lockscreenui.h"
#include "lockscreenbusinesslogic.h"

LockScreenBusinessLogic::LockScreenBusinessLogic() : QObject()
{
    eventEater = new EventEater();

    screenLock = false,
    sleepMode = false;
    isDisabled = false;

    touchPadLocker = new QmLocks();
    //display = new QmDisplayState(); //this should be handled by the displaybusinesslogic

    //toggleDisplayStateListener(true); //this should be handled by the displaybusinesslogic

    toggleSleepMode(false);

    lockUI = new LockScreenUI;
    connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen()));

    dbusIf = new QDBusInterface("org.maemo.dui.NotificationManager", "/systemui",
                                "org.maemo.dui.NotificationManager.MissedEvents",
                                QDBusConnection::sessionBus());
    connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)),
            this, SLOT(updateMissedEventAmounts(int, int, int, int)));
    dbusIf->call(QDBus::NoBlock, QString("missedEventAmountsRequired"));

}

LockScreenBusinessLogic::~LockScreenBusinessLogic()
{
    delete touchPadLocker;
    touchPadLocker = NULL;
    //delete display; //this should be handled by the displaybusinesslogic
    //display = NULL; //this should be handled by the displaybusinesslogic
    delete eventEater;
    eventEater = NULL;
    if (lockUI) {
        delete lockUI;
        lockUI = NULL;
    }
}

void LockScreenBusinessLogic::shortPowerKeyPressOccured()
{
    if(!isDisabled) {
        if(screenLock) {
            if(sleepMode)
                toggleSleepMode(false);
            else
                toggleSleepMode(true);
        }
        else {
            toggleScreenLock(true);
            toggleSleepMode(true);
        }
    }
}

void LockScreenBusinessLogic::toggleScreenLock(bool toggle)
{
    if(!toggle) {
        emit lockScreenOff();
        DuiApplication::instance()->applicationWindow()->hide();
    }
    else {
        DuiApplication::instance()->applicationWindow()->show();
        lockUI->appear();
    }

    screenLock = toggle;
}

//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state)
{
    switch(state) {
        case QmDisplayState::Off:
            //idle timer turns off the display, so we will turn on sleep mode and screen lock
            toggleSleepMode(true);
            toggleScreenLock(true);
        break;
        case QmDisplayState::Dimmed:
            //we turn on the eventeater
            eventEater->toggle(true);
        break;
        case QmDisplayState::On:
            //we trun off the event eater
            eventEater->toggle(false);
        break;
    }

}
*/
void LockScreenBusinessLogic::sleepModeOff()
{
    if(sleepMode)
        toggleSleepMode(false);
}

void LockScreenBusinessLogic::unlockScreen()
{
    toggleScreenLock(false);
}

void LockScreenBusinessLogic::toggleSleepMode(bool toggle)
{
    if(toggle) {
        //we turn on the sleep mode and lock the touchpad + turn off the display
        touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Locked);

        /*
        if(display->get() != QmDisplayState::Off) {
            //we don't need to listen display signals when we change the state by ourself
            toggleDisplayStateListener(false);
            display->set(QmDisplayState::Off);
            toggleDisplayStateListener(true);
        }
        */
    }
    else {
        //we turn off the sleep mode and unlock the touchpad + turn on the display
        touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Unlocked);
        /*
        if(display->get() != QmDisplayState::On) {
            //we don't need to listen display signals when we change the state by ourself
            toggleDisplayStateListener(false);
            display->set(QmDisplayState::On);
            toggleDisplayStateListener(true);
        }
        */
    }
    sleepMode = toggle;
}

//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::toggleDisplayStateListener(bool toggle)
{
    if(toggle)
        connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
            this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
    else
        disconnect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
            this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
}
*/

void LockScreenBusinessLogic::disable(bool disable)
{
    isDisabled = disable;
}

void LockScreenBusinessLogic::updateMissedEventAmounts(int calls, int messages, int emails, int chatMessages)
{
    qDebug() << "LockScreenBusinessLogic::updateMissedEventAmounts(" << calls << ", " << messages << ", " << emails << ", " << chatMessages << ")";
    lockUI->updateMissedEventAmounts(calls, messages, emails, chatMessages);
}
<commit_msg>Some logging added<commit_after>#include <DuiApplicationWindow>
#include <DuiApplication>
#include <QDBusInterface>
#include <QDebug>

#include "lockscreenui.h"
#include "lockscreenbusinesslogic.h"

LockScreenBusinessLogic::LockScreenBusinessLogic() : QObject()
{
    eventEater = new EventEater();

    screenLock = false,
    sleepMode = false;
    isDisabled = false;

    touchPadLocker = new QmLocks();
    //display = new QmDisplayState(); //this should be handled by the displaybusinesslogic

    //toggleDisplayStateListener(true); //this should be handled by the displaybusinesslogic

    toggleSleepMode(false);

    lockUI = new LockScreenUI;
    connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen()));

    dbusIf = new QDBusInterface("org.maemo.dui.NotificationManager", "/systemui",
                                "org.maemo.dui.NotificationManager.MissedEvents",
                                QDBusConnection::sessionBus());
    connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)),
            this, SLOT(updateMissedEventAmounts(int, int, int, int)));
    dbusIf->call(QDBus::NoBlock, QString("missedEventAmountsRequired"));

}

LockScreenBusinessLogic::~LockScreenBusinessLogic()
{
    delete touchPadLocker;
    touchPadLocker = NULL;
    //delete display; //this should be handled by the displaybusinesslogic
    //display = NULL; //this should be handled by the displaybusinesslogic
    delete eventEater;
    eventEater = NULL;
    if (lockUI) {
        delete lockUI;
        lockUI = NULL;
    }
}

void LockScreenBusinessLogic::shortPowerKeyPressOccured()
{
    qDebug() << Q_FUNC_INFO << "isDisabled:" << isDisabled << "screenLock:" << screenLock << "sleepMode:" << sleepMode;

    if(!isDisabled) {
        if(screenLock) {
            if(sleepMode)
                toggleSleepMode(false);
            else
                toggleSleepMode(true);
        }
        else {
            toggleScreenLock(true);
            toggleSleepMode(true);
        }
    }
}

void LockScreenBusinessLogic::toggleScreenLock(bool toggle)
{
    qDebug() << Q_FUNC_INFO << toggle;

    if(!toggle) {
        emit lockScreenOff();
        DuiApplication::instance()->applicationWindow()->hide();
    }
    else {
        DuiApplication::instance()->applicationWindow()->show();
        lockUI->appear();
    }

    screenLock = toggle;
}

//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state)
{
    switch(state) {
        case QmDisplayState::Off:
            //idle timer turns off the display, so we will turn on sleep mode and screen lock
            toggleSleepMode(true);
            toggleScreenLock(true);
        break;
        case QmDisplayState::Dimmed:
            //we turn on the eventeater
            eventEater->toggle(true);
        break;
        case QmDisplayState::On:
            //we trun off the event eater
            eventEater->toggle(false);
        break;
    }

}
*/
void LockScreenBusinessLogic::sleepModeOff()
{
    if(sleepMode)
        toggleSleepMode(false);
}

void LockScreenBusinessLogic::unlockScreen()
{
    toggleScreenLock(false);
}

void LockScreenBusinessLogic::toggleSleepMode(bool toggle)
{
    if(toggle) {
        //we turn on the sleep mode and lock the touchpad + turn off the display
        touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Locked);

        /*
        if(display->get() != QmDisplayState::Off) {
            //we don't need to listen display signals when we change the state by ourself
            toggleDisplayStateListener(false);
            display->set(QmDisplayState::Off);
            toggleDisplayStateListener(true);
        }
        */
    }
    else {
        //we turn off the sleep mode and unlock the touchpad + turn on the display
        touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Unlocked);
        /*
        if(display->get() != QmDisplayState::On) {
            //we don't need to listen display signals when we change the state by ourself
            toggleDisplayStateListener(false);
            display->set(QmDisplayState::On);
            toggleDisplayStateListener(true);
        }
        */
    }
    sleepMode = toggle;
}

//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::toggleDisplayStateListener(bool toggle)
{
    if(toggle)
        connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
            this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
    else
        disconnect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
            this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
}
*/

void LockScreenBusinessLogic::disable(bool disable)
{
    isDisabled = disable;
}

void LockScreenBusinessLogic::updateMissedEventAmounts(int calls, int messages, int emails, int chatMessages)
{
    qDebug() << "LockScreenBusinessLogic::updateMissedEventAmounts(" << calls << ", " << messages << ", " << emails << ", " << chatMessages << ")";
    lockUI->updateMissedEventAmounts(calls, messages, emails, chatMessages);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "nanotree.h"

class NanoTreeUnitTest : public QObject
{
    Q_OBJECT

private:
    NanoTree buildBasic();
    NanoTree buildComplex();

private slots:
    void keyValue1();
    void keyValue2();
    void keys();
};

NanoTree NanoTreeUnitTest::buildBasic()
{
    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    QVariantList tree;
    tree << QVariant(param1);
    tree << QVariant(param2);

    return NanoTree(tree);
}

NanoTree NanoTreeUnitTest::buildComplex()
{
    QVariantList params;
    params << QVariant("params");

    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    params << QVariant(param1);
    params << QVariant(param2);

    QVariantList doc;
    doc << QVariant("doc");
    doc << QVariant("documentation");

    QVariantList tree;
    tree << QVariant(params);
    tree << QVariant(doc);

    return NanoTree(tree);
}

void NanoTreeUnitTest::keyValue1()
{
    NanoTree tree = buildBasic();
    QCOMPARE(tree.keyValue("param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("param2").toString(), QString("value2"));
}

void NanoTreeUnitTest::keyValue2()
{
    NanoTree tree = buildComplex();
    QCOMPARE(tree.keyValue("params", "param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("params", "param2").toString(), QString("value2"));
    QCOMPARE(tree.keyValue("doc").toString(), QString("documentation"));
}

void NanoTreeUnitTest::keys()
{
    NanoTree tree = buildComplex();
    QStringList lst1 = tree.keys();

    QCOMPARE(lst1.size(), 2);
    QVERIFY(lst1.contains("params"));
    QVERIFY(lst1.contains("doc"));

    QStringList lst2 = tree.keyNode("params").keys();
    QCOMPARE(lst2.size(), 2);
    QVERIFY(lst2.contains("param1"));
    QVERIFY(lst2.contains("param2"));

    QStringList lst3 = tree.keyNode("doc").keys();
    QCOMPARE(lst3.size(), 0);
}

#include "nanotreeunittest.moc"
QTEST_MAIN(NanoTreeUnitTest);
<commit_msg>keySub tests.<commit_after>/*
 * Copyright (C) 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "nanotree.h"

class NanoTreeUnitTest : public QObject
{
    Q_OBJECT

private:
    NanoTree buildBasic();
    NanoTree buildComplex();

private slots:
    void keyValue1();
    void keyValue2();
    void keys();
    void keySub();
};

NanoTree NanoTreeUnitTest::buildBasic()
{
    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    QVariantList tree;
    tree << QVariant(param1);
    tree << QVariant(param2);

    return NanoTree(tree);
}

NanoTree NanoTreeUnitTest::buildComplex()
{
    QVariantList params;
    params << QVariant("params");

    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    params << QVariant(param1);
    params << QVariant(param2);

    QVariantList doc;
    doc << QVariant("doc");
    doc << QVariant("documentation");

    QVariantList tree;
    tree << QVariant(params);
    tree << QVariant(doc);

    return NanoTree(tree);
}

void NanoTreeUnitTest::keyValue1()
{
    NanoTree tree = buildBasic();
    QCOMPARE(tree.keyValue("param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("param2").toString(), QString("value2"));
}

void NanoTreeUnitTest::keyValue2()
{
    NanoTree tree = buildComplex();
    QCOMPARE(tree.keyValue("params", "param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("params", "param2").toString(), QString("value2"));
    QCOMPARE(tree.keyValue("doc").toString(), QString("documentation"));
}

void NanoTreeUnitTest::keys()
{
    NanoTree tree = buildComplex();
    QStringList lst1 = tree.keys();

    QCOMPARE(lst1.size(), 2);
    QVERIFY(lst1.contains("params"));
    QVERIFY(lst1.contains("doc"));

    QStringList lst2 = tree.keyNode("params").keys();
    QCOMPARE(lst2.size(), 2);
    QVERIFY(lst2.contains("param1"));
    QVERIFY(lst2.contains("param2"));

    QStringList lst3 = tree.keyNode("doc").keys();
    QCOMPARE(lst3.size(), 0);
}

void NanoTreeUnitTest::keySub()
{
    NanoTree tree1 = buildBasic();
    NanoTree sub1 = tree1.keySub("param1");
    QVERIFY(sub1.type() == QVariant::List);
    QCOMPARE(sub1.toList().size(), 1);
    QCOMPARE(sub1.toList().at(0).toString(), QString("value1"));

    NanoTree tree2 = buildComplex();
    NanoTree sub2 = tree2.keySub("params");
    QVERIFY(sub2.type() == QVariant::List);
    QCOMPARE(sub2.toList().size(), 2);
    QCOMPARE(sub2.keyValue("param1").toString(), QString("value1"));
}

#include "nanotreeunittest.moc"
QTEST_MAIN(NanoTreeUnitTest);
<|endoftext|>


<commit_before>#include "MMAcquisition.h"
#include "../MMDevice/ImageMetadata.h"
#include "boost/foreach.hpp"

///////////////////////////////////
// MMAquisitionEngine::ImageTask //
///////////////////////////////////

ImageTask::ImageTask(MMAcquisitionEngine * eng, ImageRequest imageRequest) {
   eng_ = eng;
   imageRequest_ = imageRequest;
   type = IMAGE;
}

void ImageTask::run() {
   if (!eng_->StopHasBeenRequested())
      updatePosition();
   if (!eng_->StopHasBeenRequested())
      updateSlice();
   if (!eng_->StopHasBeenRequested())
      updateChannel();
   if (!eng_->StopHasBeenRequested())
      wait();
   if (!eng_->StopHasBeenRequested())
      autofocus();
   if (!eng_->StopHasBeenRequested())
      acquireImage();

}

void ImageTask::updateSlice() {
   double chanZOffset = 0;
   double sliceZ;

   if (imageRequest_.useChannel)
      chanZOffset = imageRequest_.channel.zOffset;

   if (imageRequest_.useSlice)
      sliceZ = imageRequest_.slicePosition;
   else
      eng_->coreCallback_->GetFocusPosition(sliceZ);

   if (imageRequest_.useSlice || (chanZOffset != 0)) {
      eng_->coreCallback_->SetFocusPosition(sliceZ + chanZOffset);
      eng_->core_->logMessage("z position set\n");
   }
}

void ImageTask::updatePosition() {
   if (imageRequest_.usePosition) {
      map<string, double>::iterator it1;

      MultiAxisPosition pos = imageRequest_.multiAxisPosition;
      for (it1 = pos.singleAxisPositions.begin(); it1 != pos.singleAxisPositions.end(); ++it1) {
         eng_->core_->setPosition(it1->first.c_str(), it1->second);
      }

      map<string, pair<double, double> >::iterator it2;

      for (it2 = pos.doubleAxisPositions.begin(); it2 != pos.doubleAxisPositions.end(); ++it2) {
         point2D xy = it2->second;
         eng_->core_->setXYPosition(it2->first.c_str(), xy.first, xy.second);
      }
      eng_->core_->logMessage("position set\n");
   }
}

void ImageTask::updateChannel() {
   if (imageRequest_.useChannel) {
      eng_->coreCallback_->SetExposure(imageRequest_.channel.exposure);
      imageRequest_.exposure = imageRequest_.channel.exposure;
      string chanGroup = imageRequest_.channel.group;
      if (chanGroup.size() == 0)
         chanGroup = eng_->core_->getChannelGroup();
      eng_->coreCallback_->SetConfig(chanGroup.c_str(), imageRequest_.channel.name.c_str());
      eng_->core_->logMessage("channel set\n");
   }
}

void ImageTask::wait() {
   if (imageRequest_.useTime) {
      while (!eng_->StopHasBeenRequested() && eng_->lastWakeTime_ > 0) {
         MM::MMTime sleepTime = min(MM::MMTime(10000), (eng_->lastWakeTime_ + imageRequest_.waitTime) - eng_->coreCallback_->GetCurrentMMTime());
         if (sleepTime > MM::MMTime(0, 0))
            eng_->coreCallback_->Sleep(NULL, sleepTime.getMsec());
         else
            break;
      }
      eng_->core_->logMessage("wait finished\n");

      eng_->lastWakeTime_ = eng_->coreCallback_->GetCurrentMMTime();
   }
}

void ImageTask::autofocus() {
   if (imageRequest_.runAutofocus && imageRequest_.channelIndex == 0 && imageRequest_.positionIndex == 0)
      eng_->core_->fullFocus();
}

void ImageTask::acquireImage() {
   int w, h, d;

   if (!eng_->core_->getShutterOpen()) {
      eng_->core_->setShutterOpen(true);
      eng_->core_->logMessage("opened shutter");
   }
   eng_->core_->snapImage();
   eng_->core_->logMessage("snapped image");

   if (imageRequest_.closeShutter) {
      eng_->core_->setShutterOpen(false);
      eng_->core_->logMessage("closed shutter");
   }

   void * img = eng_->core_->getImage(); // Snaps and retrieves image.
   eng_->core_->logMessage("retrieved image");

   Metadata md;
   md.frameData["Slice"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.sliceIndex));
   md.frameData["Channel"] = imageRequest_.channel.name;
   md.frameData["Position"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.positionIndex));
   md.frameData["ChannelIndex"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.channelIndex));
   md.frameData["Frame"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.timeIndex));
   md.frameData["ExposureMs"] = CDeviceUtils::ConvertToString(imageRequest_.exposure);
   if (imageRequest_.usePosition)
      md.frameData["PositionName"] = imageRequest_.multiAxisPosition.name;

   eng_->ApplyDiffPropertyMap(md.frameData);

   eng_->coreCallback_->GetImageDimensions(w, h, d);

   md.frameData["Width"] = CDeviceUtils::ConvertToString(w);
   md.frameData["Height"] = CDeviceUtils::ConvertToString(h);
   md.frameData["Depth"] = CDeviceUtils::ConvertToString(d);

   eng_->coreCallback_->InsertImage(NULL, (const unsigned char *) img, w, h, d, &md);
   eng_->core_->logMessage("Grabbed image.\n");
}

/////////////////////////
// MMAcquisitionEngine //
/////////////////////////

map<string, string> MMAcquisitionEngine::GetCurrentPropertyMap() {
   Configuration config = core_->getSystemStateCache();
   map<string, string> frameData;
   for (unsigned long i = 0; i < config.size(); i++) {
      PropertySetting setting = config.getSetting(i);
      frameData[setting.getDeviceLabel() + "-" + setting.getPropertyName()] = setting.getPropertyValue();
   }
   return frameData;
}

void MMAcquisitionEngine::ApplyDiffPropertyMap(map<string, string> &dest) {
   map<string, string> curMap = GetCurrentPropertyMap();

   pair<string, string> curProp;

   BOOST_FOREACH(curProp, curMap)
   {
      if (initialPropertyMap_[curProp.first] != curProp.second)
         dest[curProp.first] = curProp.second;
   }
}

map<string, string> MMAcquisitionEngine::GetInitPropertyMap() {
   return initialPropertyMap_;
}

Metadata MMAcquisitionEngine::GetInitMetadata() {
   while (!started_)
      coreCallback_->Sleep(NULL, 1);

   Metadata md;
   md.frameData = initialPropertyMap_;
   return md;
}

void MMAcquisitionEngine::Start(AcquisitionSettings acquisitionSettings) {
   defaultExposure_ = core_->getExposure();

   GenerateSequence(acquisitionSettings);

   stopRequested_ = false;
   pauseRequested_ = false;
   finished_ = false;

   initialPropertyMap_ = GetCurrentPropertyMap();

   activate();
   started_ = true;

}

void MMAcquisitionEngine::Run() {
   bool initialAutoshutter = core_->getAutoShutter();
   core_->setAutoShutter(false);

   for (unsigned int i = 0; i < tasks_.size(); ++i) {
      if (stopRequested_)
         break;
      stringstream msg;
      msg << "Task " << i << " started, type " << tasks_[i]->type << ".";
      core_->logMessage(msg.str().c_str());
      tasks_[i]->run();
   }

   core_->setAutoShutter(initialAutoshutter);

   finished_ = true;

}

bool MMAcquisitionEngine::IsFinished() {
   return finished_;
}

void MMAcquisitionEngine::Stop() {
   stopRequested_ = true;
}

void MMAcquisitionEngine::Pause() {
   pauseRequested_ = true;
}

void MMAcquisitionEngine::Resume() {
   pauseRequested_ = false;
}

void MMAcquisitionEngine::Step() {
}

bool MMAcquisitionEngine::StopHasBeenRequested() {
   return stopRequested_;
}

void MMAcquisitionEngine::SetTasks(TaskVector tasks) {
   tasks_ = tasks;
}

void MMAcquisitionEngine::GenerateSequence(AcquisitionSettings acquisitionSettings) {
   ImageRequest imageRequest, lastImageRequest;

   imageRequest.usePosition = (acquisitionSettings.positionList.size() > 0);
   imageRequest.useTime = (acquisitionSettings.timeSeries.size() > 0);
   imageRequest.useChannel = (acquisitionSettings.channelList.size() > 0);
   imageRequest.useSlice = (acquisitionSettings.zStack.size() > 0);

   imageRequest.exposure = defaultExposure_;

   int numPositions = max(1, (int) acquisitionSettings.positionList.size());
   int numFrames = max(1, (int) acquisitionSettings.timeSeries.size());
   int numChannels = max(1, (int) acquisitionSettings.channelList.size());
   int numSlices = max(1, (int) acquisitionSettings.zStack.size());
   int numImages = numPositions * numFrames * numChannels * numSlices;

   for (int imageIndex = 0; imageIndex < (1 + numImages); ++imageIndex) {
      imageRequest.skipImage = false;
      imageRequest.closeShutter = true;

      if (acquisitionSettings.channelsFirst) {
         imageRequest.channelIndex = imageIndex % numChannels;
         imageRequest.sliceIndex = (imageIndex / numChannels) % numSlices;
      } else // slices first
      {
         imageRequest.sliceIndex = imageIndex % numSlices;
         imageRequest.channelIndex = (imageIndex / numSlices) % numChannels;
      }

      if (acquisitionSettings.positionsFirst) {
         imageRequest.positionIndex = (imageIndex / (numChannels * numSlices)) % numPositions;
         imageRequest.timeIndex = (imageIndex / (numChannels * numSlices * numPositions)) % numFrames;
      } else // time first
      {
         imageRequest.timeIndex = (imageIndex / (numChannels * numSlices)) % numFrames;
         imageRequest.positionIndex = (imageIndex / (numChannels * numSlices * numFrames)) % numPositions;
      }

      if (imageRequest.useTime && imageRequest.timeIndex > 0 && imageRequest.positionIndex <= 0 // &&
            && imageRequest.channelIndex <= 0 && imageRequest.sliceIndex <= 0)
         imageRequest.waitTime = MM::MMTime(acquisitionSettings.timeSeries[imageRequest.timeIndex] * 1000);
      else
         imageRequest.waitTime = 0;

      if (imageRequest.usePosition)
         imageRequest.multiAxisPosition = acquisitionSettings.positionList[imageRequest.positionIndex];

      if (imageRequest.useSlice)
         imageRequest.slicePosition = acquisitionSettings.zStack[imageRequest.sliceIndex];

      if (imageRequest.useChannel) {
         imageRequest.channel = acquisitionSettings.channelList[imageRequest.channelIndex];
         if (0 != (imageRequest.timeIndex % (imageRequest.channel.skipFrames + 1)))
            imageRequest.skipImage = true;
      }

      if (imageRequest.useChannel && imageRequest.useSlice) {
         if (!imageRequest.channel.useZStack && ((unsigned) imageRequest.sliceIndex != (acquisitionSettings.zStack.size() - 1) / 2))
            imageRequest.skipImage = true;
      }

      imageRequest.runAutofocus = acquisitionSettings.useAutofocus;
      if (imageRequest.timeIndex > -1) {
         imageRequest.runAutofocus = imageRequest.runAutofocus
               && (0 == (imageRequest.timeIndex % (1 + acquisitionSettings.autofocusSkipFrames)));
      }

      if (imageIndex > 0)
      {
         if (imageRequest.timeIndex == lastImageRequest.timeIndex
               && imageRequest.positionIndex == lastImageRequest.positionIndex) {
            if (acquisitionSettings.keepShutterOpenChannels
                  && !acquisitionSettings.keepShutterOpenSlices) {
               if (imageRequest.sliceIndex == lastImageRequest.sliceIndex)
                  lastImageRequest.closeShutter = false;
            }

            if (acquisitionSettings.keepShutterOpenSlices
                  && !acquisitionSettings.keepShutterOpenChannels) {
               if (imageRequest.channelIndex == lastImageRequest.channelIndex)
                  lastImageRequest.closeShutter = false;
            }

            if (acquisitionSettings.keepShutterOpenSlices
                  && acquisitionSettings.keepShutterOpenChannels) {
               lastImageRequest.closeShutter = false;
            }
         }

         if (!lastImageRequest.skipImage)
            tasks_.push_back(new ImageTask(this, lastImageRequest));
      }

      if (imageIndex == 0 || !imageRequest.skipImage)
         lastImageRequest = imageRequest;
   }
}
<commit_msg>Make core acquisition engine respond to autoshutter.<commit_after>#include "MMAcquisition.h"
#include "../MMDevice/ImageMetadata.h"
#include "boost/foreach.hpp"

///////////////////////////////////
// MMAquisitionEngine::ImageTask //
///////////////////////////////////

ImageTask::ImageTask(MMAcquisitionEngine * eng, ImageRequest imageRequest) {
   eng_ = eng;
   imageRequest_ = imageRequest;
   type = IMAGE;
}

void ImageTask::run() {
   if (!eng_->StopHasBeenRequested())
      updatePosition();
   if (!eng_->StopHasBeenRequested())
      updateSlice();
   if (!eng_->StopHasBeenRequested())
      updateChannel();
   if (!eng_->StopHasBeenRequested())
      wait();
   if (!eng_->StopHasBeenRequested())
      autofocus();
   if (!eng_->StopHasBeenRequested())
      acquireImage();

}

void ImageTask::updateSlice() {
   double chanZOffset = 0;
   double sliceZ;

   if (imageRequest_.useChannel)
      chanZOffset = imageRequest_.channel.zOffset;

   if (imageRequest_.useSlice)
      sliceZ = imageRequest_.slicePosition;
   else
      eng_->coreCallback_->GetFocusPosition(sliceZ);

   if (imageRequest_.useSlice || (chanZOffset != 0)) {
      eng_->coreCallback_->SetFocusPosition(sliceZ + chanZOffset);
      eng_->core_->logMessage("z position set\n");
   }
}

void ImageTask::updatePosition() {
   if (imageRequest_.usePosition) {
      map<string, double>::iterator it1;

      MultiAxisPosition pos = imageRequest_.multiAxisPosition;
      for (it1 = pos.singleAxisPositions.begin(); it1 != pos.singleAxisPositions.end(); ++it1) {
         eng_->core_->setPosition(it1->first.c_str(), it1->second);
      }

      map<string, pair<double, double> >::iterator it2;

      for (it2 = pos.doubleAxisPositions.begin(); it2 != pos.doubleAxisPositions.end(); ++it2) {
         point2D xy = it2->second;
         eng_->core_->setXYPosition(it2->first.c_str(), xy.first, xy.second);
      }
      eng_->core_->logMessage("position set\n");
   }
}

void ImageTask::updateChannel() {
   if (imageRequest_.useChannel) {
      eng_->coreCallback_->SetExposure(imageRequest_.channel.exposure);
      imageRequest_.exposure = imageRequest_.channel.exposure;
      string chanGroup = imageRequest_.channel.group;
      if (chanGroup.size() == 0)
         chanGroup = eng_->core_->getChannelGroup();
      eng_->coreCallback_->SetConfig(chanGroup.c_str(), imageRequest_.channel.name.c_str());
      eng_->core_->logMessage("channel set\n");
   }
}

void ImageTask::wait() {
   if (imageRequest_.useTime) {
      while (!eng_->StopHasBeenRequested() && eng_->lastWakeTime_ > 0) {
         MM::MMTime sleepTime = min(MM::MMTime(10000), (eng_->lastWakeTime_ + imageRequest_.waitTime) - eng_->coreCallback_->GetCurrentMMTime());
         if (sleepTime > MM::MMTime(0, 0))
            eng_->coreCallback_->Sleep(NULL, sleepTime.getMsec());
         else
            break;
      }
      eng_->core_->logMessage("wait finished\n");

      eng_->lastWakeTime_ = eng_->coreCallback_->GetCurrentMMTime();
   }
}

void ImageTask::autofocus() {
   if (imageRequest_.runAutofocus && imageRequest_.channelIndex == 0 && imageRequest_.positionIndex == 0)
      eng_->core_->fullFocus();
}

void ImageTask::acquireImage() {
   int w, h, d;

   if (eng_->core_->getAutoShutter() && !eng_->core_->getShutterOpen()) {
      eng_->core_->setShutterOpen(true);
      eng_->core_->logMessage("opened shutter");
   }
   eng_->core_->snapImage();
   eng_->core_->logMessage("snapped image");

   if (eng_->core_->getAutoShutter() && imageRequest_.closeShutter) {
      eng_->core_->setShutterOpen(false);
      eng_->core_->logMessage("closed shutter");
   }

   void * img = eng_->core_->getImage(); // Snaps and retrieves image.
   eng_->core_->logMessage("retrieved image");

   Metadata md;
   md.frameData["Slice"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.sliceIndex));
   md.frameData["Channel"] = imageRequest_.channel.name;
   md.frameData["Position"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.positionIndex));
   md.frameData["ChannelIndex"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.channelIndex));
   md.frameData["Frame"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.timeIndex));
   md.frameData["ExposureMs"] = CDeviceUtils::ConvertToString(imageRequest_.exposure);
   if (imageRequest_.usePosition)
      md.frameData["PositionName"] = imageRequest_.multiAxisPosition.name;

   eng_->ApplyDiffPropertyMap(md.frameData);

   eng_->coreCallback_->GetImageDimensions(w, h, d);

   md.frameData["Width"] = CDeviceUtils::ConvertToString(w);
   md.frameData["Height"] = CDeviceUtils::ConvertToString(h);
   md.frameData["Depth"] = CDeviceUtils::ConvertToString(d);

   eng_->coreCallback_->InsertImage(NULL, (const unsigned char *) img, w, h, d, &md);
   eng_->core_->logMessage("Grabbed image.\n");
}

/////////////////////////
// MMAcquisitionEngine //
/////////////////////////

map<string, string> MMAcquisitionEngine::GetCurrentPropertyMap() {
   Configuration config = core_->getSystemStateCache();
   map<string, string> frameData;
   for (unsigned long i = 0; i < config.size(); i++) {
      PropertySetting setting = config.getSetting(i);
      frameData[setting.getDeviceLabel() + "-" + setting.getPropertyName()] = setting.getPropertyValue();
   }
   return frameData;
}

void MMAcquisitionEngine::ApplyDiffPropertyMap(map<string, string> &dest) {
   map<string, string> curMap = GetCurrentPropertyMap();

   pair<string, string> curProp;

   BOOST_FOREACH(curProp, curMap)
   {
      if (initialPropertyMap_[curProp.first] != curProp.second)
         dest[curProp.first] = curProp.second;
   }
}

map<string, string> MMAcquisitionEngine::GetInitPropertyMap() {
   return initialPropertyMap_;
}

Metadata MMAcquisitionEngine::GetInitMetadata() {
   while (!started_)
      coreCallback_->Sleep(NULL, 1);

   Metadata md;
   md.frameData = initialPropertyMap_;
   return md;
}

void MMAcquisitionEngine::Start(AcquisitionSettings acquisitionSettings) {
   defaultExposure_ = core_->getExposure();

   GenerateSequence(acquisitionSettings);

   stopRequested_ = false;
   pauseRequested_ = false;
   finished_ = false;

   initialPropertyMap_ = GetCurrentPropertyMap();

   activate();
   started_ = true;

}

void MMAcquisitionEngine::Run() {
   bool initialAutoshutter = core_->getAutoShutter();
   core_->setAutoShutter(false);

   for (unsigned int i = 0; i < tasks_.size(); ++i) {
      if (stopRequested_)
         break;
      stringstream msg;
      msg << "Task " << i << " started, type " << tasks_[i]->type << ".";
      core_->logMessage(msg.str().c_str());
      tasks_[i]->run();
   }

   core_->setAutoShutter(initialAutoshutter);

   finished_ = true;

}

bool MMAcquisitionEngine::IsFinished() {
   return finished_;
}

void MMAcquisitionEngine::Stop() {
   stopRequested_ = true;
}

void MMAcquisitionEngine::Pause() {
   pauseRequested_ = true;
}

void MMAcquisitionEngine::Resume() {
   pauseRequested_ = false;
}

void MMAcquisitionEngine::Step() {
}

bool MMAcquisitionEngine::StopHasBeenRequested() {
   return stopRequested_;
}

void MMAcquisitionEngine::SetTasks(TaskVector tasks) {
   tasks_ = tasks;
}

void MMAcquisitionEngine::GenerateSequence(AcquisitionSettings acquisitionSettings) {
   ImageRequest imageRequest, lastImageRequest;

   imageRequest.usePosition = (acquisitionSettings.positionList.size() > 0);
   imageRequest.useTime = (acquisitionSettings.timeSeries.size() > 0);
   imageRequest.useChannel = (acquisitionSettings.channelList.size() > 0);
   imageRequest.useSlice = (acquisitionSettings.zStack.size() > 0);

   imageRequest.exposure = defaultExposure_;

   int numPositions = max(1, (int) acquisitionSettings.positionList.size());
   int numFrames = max(1, (int) acquisitionSettings.timeSeries.size());
   int numChannels = max(1, (int) acquisitionSettings.channelList.size());
   int numSlices = max(1, (int) acquisitionSettings.zStack.size());
   int numImages = numPositions * numFrames * numChannels * numSlices;

   for (int imageIndex = 0; imageIndex < (1 + numImages); ++imageIndex) {
      imageRequest.skipImage = false;
      imageRequest.closeShutter = true;

      if (acquisitionSettings.channelsFirst) {
         imageRequest.channelIndex = imageIndex % numChannels;
         imageRequest.sliceIndex = (imageIndex / numChannels) % numSlices;
      } else // slices first
      {
         imageRequest.sliceIndex = imageIndex % numSlices;
         imageRequest.channelIndex = (imageIndex / numSlices) % numChannels;
      }

      if (acquisitionSettings.positionsFirst) {
         imageRequest.positionIndex = (imageIndex / (numChannels * numSlices)) % numPositions;
         imageRequest.timeIndex = (imageIndex / (numChannels * numSlices * numPositions)) % numFrames;
      } else // time first
      {
         imageRequest.timeIndex = (imageIndex / (numChannels * numSlices)) % numFrames;
         imageRequest.positionIndex = (imageIndex / (numChannels * numSlices * numFrames)) % numPositions;
      }

      if (imageRequest.useTime && imageRequest.timeIndex > 0 && imageRequest.positionIndex <= 0 // &&
            && imageRequest.channelIndex <= 0 && imageRequest.sliceIndex <= 0)
         imageRequest.waitTime = MM::MMTime(acquisitionSettings.timeSeries[imageRequest.timeIndex] * 1000);
      else
         imageRequest.waitTime = 0;

      if (imageRequest.usePosition)
         imageRequest.multiAxisPosition = acquisitionSettings.positionList[imageRequest.positionIndex];

      if (imageRequest.useSlice)
         imageRequest.slicePosition = acquisitionSettings.zStack[imageRequest.sliceIndex];

      if (imageRequest.useChannel) {
         imageRequest.channel = acquisitionSettings.channelList[imageRequest.channelIndex];
         if (0 != (imageRequest.timeIndex % (imageRequest.channel.skipFrames + 1)))
            imageRequest.skipImage = true;
      }

      if (imageRequest.useChannel && imageRequest.useSlice) {
         if (!imageRequest.channel.useZStack && ((unsigned) imageRequest.sliceIndex != (acquisitionSettings.zStack.size() - 1) / 2))
            imageRequest.skipImage = true;
      }

      imageRequest.runAutofocus = acquisitionSettings.useAutofocus;
      if (imageRequest.timeIndex > -1) {
         imageRequest.runAutofocus = imageRequest.runAutofocus
               && (0 == (imageRequest.timeIndex % (1 + acquisitionSettings.autofocusSkipFrames)));
      }

      if (imageIndex > 0)
      {
         if (imageRequest.timeIndex == lastImageRequest.timeIndex
               && imageRequest.positionIndex == lastImageRequest.positionIndex) {
            if (acquisitionSettings.keepShutterOpenChannels
                  && !acquisitionSettings.keepShutterOpenSlices) {
               if (imageRequest.sliceIndex == lastImageRequest.sliceIndex)
                  lastImageRequest.closeShutter = false;
            }

            if (acquisitionSettings.keepShutterOpenSlices
                  && !acquisitionSettings.keepShutterOpenChannels) {
               if (imageRequest.channelIndex == lastImageRequest.channelIndex)
                  lastImageRequest.closeShutter = false;
            }

            if (acquisitionSettings.keepShutterOpenSlices
                  && acquisitionSettings.keepShutterOpenChannels) {
               lastImageRequest.closeShutter = false;
            }
         }

         if (!lastImageRequest.skipImage)
            tasks_.push_back(new ImageTask(this, lastImageRequest));
      }

      if (imageIndex == 0 || !imageRequest.skipImage)
         lastImageRequest = imageRequest;
   }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or – as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include <sstream>

#include <MQ/Web/Controller.h>
#include <MQ/MQSubsystem.h>

#include <Poco/Util/Application.h>
#include <Poco/NullStream.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>

#include <Poco/JSON/TemplateCache.h>

namespace MQ
{
namespace Web
{

Controller::Controller() : _data(new Poco::JSON::Object())
{
}

Controller::~Controller()
{
}

void Controller::handlePart(const Poco::Net::MessageHeader& header, std::istream& stream)
{
	//TODO
}

void Controller::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	_parameters = parameters;
	_request = &request;
	_response = &response;

	if ( _parameters.size() > 0 )
	{
		_action = _parameters.front();
		_parameters.erase(_parameters.begin());
	}
	else
	{
		_action = getDefaultAction();
	}

	for(std::vector<std::string>::iterator it = _parameters.begin(); it != _parameters.end(); ++it)
	{
		int pos = it->find_first_of(':');
		if ( pos != std::string::npos )
		{
			std::string name = it->substr(0, pos);
			std::string value = it->substr(pos+1);
			_namedParameters[name] = value;
		}
	}

	_form.load(request, request.stream(), *this);

	// Make sure everything is read, otherwise this can result
	// in Bad Request error in the next call.
	Poco::NullOutputStream nos;
	Poco::StreamCopier::copyStream(request.stream(), nos);

	try
	{
		beforeAction();

		if ( response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK
			|| _data->has("error") )
		{
			//TODO: return error template file or json error
		}

		const ActionMap& actions = getActions();
		ActionMap::const_iterator it = actions.find(_action);
		if ( it != actions.end() )
		{
			ActionFn action = it->second;
			(this->*action)();
		}

		afterAction();
	}
	catch(...)
	{
		//TODO: redirect to an error page
	}
}

void Controller::render(const std::string& templateFile)
{
	Poco::JSON::Template::Ptr tpl = Poco::JSON::TemplateCache::instance()->getTemplate(Poco::Path(templateFile));
	poco_assert_dbg(!tpl.isNull());

	_response->setChunkedTransferEncoding(true);
	_response->setContentType("text/html");

	// Don't cache are views
	_response->set("Cache-Control", "no-cache,no-store,must-revalidate");
	_response->set("Pragma", "no-cache");
	_response->set("Expires", "0");

	tpl->render(_data, _response->send());
}

void Controller::render()
{
	_response->setChunkedTransferEncoding(true);
	_response->setContentType("application/json");

	_data->stringify(_response->send());
}

std::string Controller::htmlize(const std::string &str)
{
	std::string::const_iterator it(str.begin());
	std::string::const_iterator end(str.end());
	std::string html;
	for (; it != end; ++it)
	{
		switch (*it)
		{
		case '<': html += "<"; break;
		case '>': html += ">"; break;
		case '"': html += """; break;
		case '&': html += "&"; break;
		default: html += *it; break;
		}
	}
	return html;
}

} } // Namespace MQ::Web
<commit_msg>Send HTTP_INTERNAL_SERVER error when we can't render a template<commit_after>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or – as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include <sstream>

#include <MQ/Web/Controller.h>
#include <MQ/MQSubsystem.h>

#include <Poco/Util/Application.h>
#include <Poco/NullStream.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>

#include <Poco/JSON/TemplateCache.h>

namespace MQ
{
namespace Web
{

Controller::Controller() : _data(new Poco::JSON::Object())
{
}

Controller::~Controller()
{
}

void Controller::handlePart(const Poco::Net::MessageHeader& header, std::istream& stream)
{
	//TODO
}

void Controller::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	_parameters = parameters;
	_request = &request;
	_response = &response;

	if ( _parameters.size() > 0 )
	{
		_action = _parameters.front();
		_parameters.erase(_parameters.begin());
	}
	else
	{
		_action = getDefaultAction();
	}

	for(std::vector<std::string>::iterator it = _parameters.begin(); it != _parameters.end(); ++it)
	{
		int pos = it->find_first_of(':');
		if ( pos != std::string::npos )
		{
			std::string name = it->substr(0, pos);
			std::string value = it->substr(pos+1);
			_namedParameters[name] = value;
		}
	}

	_form.load(request, request.stream(), *this);

	// Make sure everything is read, otherwise this can result
	// in Bad Request error in the next call.
	Poco::NullOutputStream nos;
	Poco::StreamCopier::copyStream(request.stream(), nos);

	try
	{
		beforeAction();

		if ( response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK
			|| _data->has("error") )
		{
			//TODO: return error template file or json error
		}

		const ActionMap& actions = getActions();
		ActionMap::const_iterator it = actions.find(_action);
		if ( it != actions.end() )
		{
			ActionFn action = it->second;
			(this->*action)();
		}

		afterAction();
	}
	catch(...)
	{
		//TODO: redirect to an error page
	}
}

void Controller::render(const std::string& templateFile)
{
	Poco::JSON::Template::Ptr tpl;
	try
	{
		tpl = Poco::JSON::TemplateCache::instance()->getTemplate(Poco::Path(templateFile));
		_response->setChunkedTransferEncoding(true);
		_response->setContentType("text/html");

		// Don't cache are views
		_response->set("Cache-Control", "no-cache,no-store,must-revalidate");
		_response->set("Pragma", "no-cache");
		_response->set("Expires", "0");

		tpl->render(_data, _response->send());
	}
	catch(Poco::FileNotFoundException&)
	{
		poco_error_f1(Poco::Logger::get("mq.web"), "Can't render template %s", templateFile);
		//TODO: redirect to an error page
		_response->setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, "Can't render template. Please check the MQWeb configuration.");
		_response->send();
	}
}

void Controller::render()
{
	_response->setChunkedTransferEncoding(true);
	_response->setContentType("application/json");

	_data->stringify(_response->send());
}

std::string Controller::htmlize(const std::string &str)
{
	std::string::const_iterator it(str.begin());
	std::string::const_iterator end(str.end());
	std::string html;
	for (; it != end; ++it)
	{
		switch (*it)
		{
		case '<': html += "<"; break;
		case '>': html += ">"; break;
		case '"': html += """; break;
		case '&': html += "&"; break;
		default: html += *it; break;
		}
	}
	return html;
}

} } // Namespace MQ::Web
<|endoftext|>


<commit_before>/*
 *            Copyright 2009-2019 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 writingraph, 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 <list>

#include <votca/tools/graph.h>
#include <votca/tools/graph_bf_visitor.h>
#include <votca/tools/graph_df_visitor.h>
#include <votca/tools/graphalgorithm.h>
#include <votca/tools/graphvisitor.h>

using namespace std;

namespace votca {
namespace tools {

/**********************
 * Internal Functions *
 **********************/

list<int> vectorToList_(vector<int> values) {
  list<int> values_list;
  copy(values.begin(), values.end(), back_inserter(values_list));
  return values_list;
}

vector<Edge> edgeSetToVector_(set<Edge> edges) {
  vector<Edge> edges_vector;
  copy(edges.begin(), edges.end(), back_inserter(edges_vector));
  return edges_vector;
}

/********************
 * Public Functions *
 ********************/
bool singleNetwork(Graph& graph, GraphVisitor& graph_visitor) {
  exploreGraph(graph, graph_visitor);
  return graph_visitor.getExploredVertices().size() ==
             graph.getVertices().size() &&
         graph.getIsolatedNodes().size() == 0;
}

std::set<Edge> exploreBranch(Graph g, int starting_vertex, const Edge& edge) {
  // Check if the starting vertex is in the graph
  if (!g.vertexExist(starting_vertex)) {
    throw invalid_argument(
        "Cannot explore a branch of the graph when the "
        "exploration is started from a vertex that does not exist within the "
        "graph.");
  }
  if (!g.edgeExist(edge)) {
    throw invalid_argument(
        "Edge does not exist in the graph so exploration of"
        " the graph branch cannot continue");
  }
  if (!edge.contains(starting_vertex)) {
    throw invalid_argument(
        "The edge determining which branch to explore does "
        "not contain the starting vertex.");
  }

  set<Edge> branch_edges;
  if (edge.getEndPoint1() == edge.getEndPoint2()) {
    branch_edges.insert(edge);
    return branch_edges;
  }
  Graph_BF_Visitor gv_breadth_first;
  GraphNode gn;
  pair<int, GraphNode> pr_gn(starting_vertex, gn);
  gv_breadth_first.exploreNode(pr_gn, g);
  gv_breadth_first.setStartingVertex(edge.getOtherEndPoint(starting_vertex));
  gv_breadth_first.initialize(g);

  branch_edges.insert(edge);
  while (!gv_breadth_first.queEmpty()) {
    Edge ed = gv_breadth_first.nextEdge(g);
    branch_edges.insert(ed);
    gv_breadth_first.exec(g, ed);
  }

  vector<Edge> neigh_edges = g.getNeighEdges(starting_vertex);
  for (Edge& ed : neigh_edges) {
    int neigh_vertex = ed.getOtherEndPoint(starting_vertex);
    if (neigh_vertex != starting_vertex) {
      if (gv_breadth_first.vertexExplored(neigh_vertex)) {
        branch_edges.insert(ed);
      }
    }
  }

  return branch_edges;
}

ReducedGraph reduceGraph(Graph graph) {

  /****************************
   * Internal Function Class
   ****************************/

  /**
   * \brief This class is to help keep track of which vertices have and have not
   * been explored.
   *
   * It is only used within the function and hence the encapsulation, it is not
   * a public class and is not meant to be.
   **/
  class ExplorationRecord {
   private:
    unordered_map<int, std::pair<bool, int>> vertex_explored_;
    size_t unexplored_vertex_count_;

   public:
    ExplorationRecord(unordered_map<int, std::pair<bool, int>> vertex_explored)
        : vertex_explored_(vertex_explored),
          unexplored_vertex_count_(vertex_explored.size()){};

    void explore(int vertex) {
      vertex_explored_[vertex].first = true;
      --unexplored_vertex_count_;
    }

    bool unexploredVerticesExist() { return unexplored_vertex_count_ > 0; }

    int getUnexploredVertex() {

      vector<int> remaining_unexplored;
      for (const pair<int, pair<bool, int>>& vertex_record : vertex_explored_) {
        bool vertex_explored = vertex_record.second.first;
        if (!vertex_explored) {
          int degree = vertex_record.second.second;
          if (degree > 2) {
            return vertex_record.first;
          }
          remaining_unexplored.push_back(vertex_record.first);
        }
      }

      // Search tips next
      for (const int& vertex : remaining_unexplored) {
        if (vertex_explored_[vertex].second == 1) {
          return vertex;
        }
      }

      // Finally if there are no tips or junctions left we will return a vertex
      // of degree 2 if one exists
      for (const int& vertex : remaining_unexplored) {
        if (!vertex_explored_[vertex].first) return vertex;
      }

      throw runtime_error(
          "You cannot get an unexplored vertex as they have all"
          " been explored.");
    }
  };  // Class ExplorationRecord

  unordered_map<int, pair<bool, int>> unexplored_vertices;
  vector<int> vertices = graph.getVertices();
  for (const int& vertex : vertices) {
    unexplored_vertices[vertex] =
        pair<bool, int>(false, graph.getDegree(vertex));
  }

  ExplorationRecord exploration_record(unexplored_vertices);

  vector<vector<int>> chains;

  while (exploration_record.unexploredVerticesExist()) {
    Graph_DF_Visitor graph_visitor;
    int starting_vertex = exploration_record.getUnexploredVertex();
    exploration_record.explore(starting_vertex);
    graph_visitor.setStartingVertex(starting_vertex);
    graph_visitor.initialize(graph);

    vector<int> chain{starting_vertex};
    int old_vertex = starting_vertex;
    bool new_chain = false;
    while (!graph_visitor.queEmpty()) {
      Edge edge = graph_visitor.nextEdge(graph);
      vector<int> unexplored_vertex = graph_visitor.getUnexploredVertex(edge);

      if (new_chain) {
        if (unexplored_vertex.size() == 0) {
          old_vertex = edge.getEndPoint1();
          chain.push_back(old_vertex);
          new_chain = false;
        } else {
          old_vertex = edge.getOtherEndPoint(unexplored_vertex.at(0));
          chain.push_back(old_vertex);
          new_chain = false;
        }
      }
      int new_vertex = edge.getOtherEndPoint(old_vertex);
      if (unexplored_vertex.size() == 0) {
        chain.push_back(new_vertex);
        chains.push_back(chain);
        chain.clear();
        new_chain = true;
      } else if (graph.getDegree(new_vertex) == 1) {
        chain.push_back(new_vertex);
        chains.push_back(chain);
        chain.clear();
        exploration_record.explore(new_vertex);
        new_chain = true;
      } else if (graph.getDegree(new_vertex) > 2) {
        chain.push_back(new_vertex);
        chains.push_back(chain);
        chain.clear();
        exploration_record.explore(new_vertex);
        new_chain = true;
      } else if (unexplored_vertex.size() == 1) {
        chain.push_back(new_vertex);
        old_vertex = new_vertex;
        exploration_record.explore(new_vertex);
      }

      graph_visitor.exec(graph, edge);
    }
  }
  vector<ReducedEdge> reduced_edges;
  for (vector<int> chain : chains) {
    ReducedEdge reduced_edge(chain);
    reduced_edges.push_back(reduced_edge);
  }

  ReducedGraph reduced_g(reduced_edges);
  auto nodes_graph = graph.getNodes();
  reduced_g.copyNodes(graph);
  auto nodes_reduced_g = reduced_g.getNodes();
  return reduced_g;
}

vector<Graph> decoupleIsolatedSubGraphs(Graph graph) {

  cout << "Calling decoupleIsolatedSubGraphs" << endl;
  list<int> vertices_list = vectorToList_(graph.getVertices());
  vector<Graph> subGraphs;
  Graph_BF_Visitor graph_visitor_breadth_first;
  graph_visitor_breadth_first.setStartingVertex(vertices_list.front());
  if (singleNetwork(graph, graph_visitor_breadth_first)) {
    cout << "Is considered a single network " << endl;
    subGraphs.push_back(graph);
    return subGraphs;
  }

  list<int>::iterator vertices_iterator = vertices_list.begin();
  while (vertices_iterator != vertices_list.end()) {
    unordered_map<int, GraphNode> sub_graph_nodes;
    Graph_BF_Visitor graph_visitor_breadth_first;
    graph_visitor_breadth_first.setStartingVertex(*vertices_iterator);
    exploreGraph(graph, graph_visitor_breadth_first);
    ++vertices_iterator;
    set<int> sub_graph_explored_vertices =
        graph_visitor_breadth_first.getExploredVertices();
    set<Edge> sub_graph_edges;

    set<int>::iterator sub_graph_vertex_it =
        sub_graph_explored_vertices.begin();

    // Means it is an isolated node

    while (sub_graph_vertex_it != sub_graph_explored_vertices.end()) {
      if (*vertices_iterator == *sub_graph_vertex_it) {
        ++vertices_iterator;
      }

      vertices_list.remove(*sub_graph_vertex_it);

      vector<Edge> sub_graph_neigh_edges =
          graph.getNeighEdges(*sub_graph_vertex_it);
      for (const Edge sub_graph_edge : sub_graph_neigh_edges) {
        cout << "Getting edge " << sub_graph_edge << endl;
        sub_graph_edges.insert(sub_graph_edge);
      }
      cout << "Getting node " << *sub_graph_vertex_it << endl;
      sub_graph_nodes[*sub_graph_vertex_it] =
          graph.getNode(*sub_graph_vertex_it);
      ++sub_graph_vertex_it;
    }
    cout << "End of subgraph " << endl;
    vector<Edge> sub_graph_vector_edges = edgeSetToVector_(sub_graph_edges);
    Graph graph_temp(sub_graph_vector_edges, sub_graph_nodes);
    subGraphs.push_back(graph_temp);
  }
  return subGraphs;
}

void exploreGraph(Graph& graph, GraphVisitor& graph_visitor) {

  if (!graph.vertexExist(graph_visitor.getStartingVertex())) {
    string err = "Cannot explore graph starting at vertex " +
                 to_string(graph_visitor.getStartingVertex()) +
                 " because it does not exist in the "
                 "graph. You can change the starting vertex by using the "
                 "setStartingVertex method of the visitor instance.";
    throw invalid_argument(err);
  }
  // Create a list of all vertices and determine if they have all been
  // explored when the visitor que is empty
  graph_visitor.initialize(graph);
  while (!graph_visitor.queEmpty()) {
    Edge edge = graph_visitor.nextEdge(graph);
    graph_visitor.exec(graph, edge);
  }
}
}  // namespace tools
}  // namespace votca
<commit_msg>removed cout from graph algorithm files<commit_after>/*
 *            Copyright 2009-2019 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 writingraph, 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 <list>

#include <votca/tools/graph.h>
#include <votca/tools/graph_bf_visitor.h>
#include <votca/tools/graph_df_visitor.h>
#include <votca/tools/graphalgorithm.h>
#include <votca/tools/graphvisitor.h>

using namespace std;

namespace votca {
namespace tools {

/**********************
 * Internal Functions *
 **********************/

list<int> vectorToList_(vector<int> values) {
  list<int> values_list;
  copy(values.begin(), values.end(), back_inserter(values_list));
  return values_list;
}

vector<Edge> edgeSetToVector_(set<Edge> edges) {
  vector<Edge> edges_vector;
  copy(edges.begin(), edges.end(), back_inserter(edges_vector));
  return edges_vector;
}

/********************
 * Public Functions *
 ********************/
bool singleNetwork(Graph& graph, GraphVisitor& graph_visitor) {
  exploreGraph(graph, graph_visitor);
  return graph_visitor.getExploredVertices().size() ==
             graph.getVertices().size() &&
         graph.getIsolatedNodes().size() == 0;
}

std::set<Edge> exploreBranch(Graph g, int starting_vertex, const Edge& edge) {
  // Check if the starting vertex is in the graph
  if (!g.vertexExist(starting_vertex)) {
    throw invalid_argument(
        "Cannot explore a branch of the graph when the "
        "exploration is started from a vertex that does not exist within the "
        "graph.");
  }
  if (!g.edgeExist(edge)) {
    throw invalid_argument(
        "Edge does not exist in the graph so exploration of"
        " the graph branch cannot continue");
  }
  if (!edge.contains(starting_vertex)) {
    throw invalid_argument(
        "The edge determining which branch to explore does "
        "not contain the starting vertex.");
  }

  set<Edge> branch_edges;
  if (edge.getEndPoint1() == edge.getEndPoint2()) {
    branch_edges.insert(edge);
    return branch_edges;
  }
  Graph_BF_Visitor gv_breadth_first;
  GraphNode gn;
  pair<int, GraphNode> pr_gn(starting_vertex, gn);
  gv_breadth_first.exploreNode(pr_gn, g);
  gv_breadth_first.setStartingVertex(edge.getOtherEndPoint(starting_vertex));
  gv_breadth_first.initialize(g);

  branch_edges.insert(edge);
  while (!gv_breadth_first.queEmpty()) {
    Edge ed = gv_breadth_first.nextEdge(g);
    branch_edges.insert(ed);
    gv_breadth_first.exec(g, ed);
  }

  vector<Edge> neigh_edges = g.getNeighEdges(starting_vertex);
  for (Edge& ed : neigh_edges) {
    int neigh_vertex = ed.getOtherEndPoint(starting_vertex);
    if (neigh_vertex != starting_vertex) {
      if (gv_breadth_first.vertexExplored(neigh_vertex)) {
        branch_edges.insert(ed);
      }
    }
  }

  return branch_edges;
}

ReducedGraph reduceGraph(Graph graph) {

  /****************************
   * Internal Function Class
   ****************************/

  /**
   * \brief This class is to help keep track of which vertices have and have not
   * been explored.
   *
   * It is only used within the function and hence the encapsulation, it is not
   * a public class and is not meant to be.
   **/
  class ExplorationRecord {
   private:
    unordered_map<int, std::pair<bool, int>> vertex_explored_;
    size_t unexplored_vertex_count_;

   public:
    ExplorationRecord(unordered_map<int, std::pair<bool, int>> vertex_explored)
        : vertex_explored_(vertex_explored),
          unexplored_vertex_count_(vertex_explored.size()){};

    void explore(int vertex) {
      vertex_explored_[vertex].first = true;
      --unexplored_vertex_count_;
    }

    bool unexploredVerticesExist() { return unexplored_vertex_count_ > 0; }

    int getUnexploredVertex() {

      vector<int> remaining_unexplored;
      for (const pair<int, pair<bool, int>>& vertex_record : vertex_explored_) {
        bool vertex_explored = vertex_record.second.first;
        if (!vertex_explored) {
          int degree = vertex_record.second.second;
          if (degree > 2) {
            return vertex_record.first;
          }
          remaining_unexplored.push_back(vertex_record.first);
        }
      }

      // Search tips next
      for (const int& vertex : remaining_unexplored) {
        if (vertex_explored_[vertex].second == 1) {
          return vertex;
        }
      }

      // Finally if there are no tips or junctions left we will return a vertex
      // of degree 2 if one exists
      for (const int& vertex : remaining_unexplored) {
        if (!vertex_explored_[vertex].first) return vertex;
      }

      throw runtime_error(
          "You cannot get an unexplored vertex as they have all"
          " been explored.");
    }
  };  // Class ExplorationRecord

  unordered_map<int, pair<bool, int>> unexplored_vertices;
  vector<int> vertices = graph.getVertices();
  for (const int& vertex : vertices) {
    unexplored_vertices[vertex] =
        pair<bool, int>(false, graph.getDegree(vertex));
  }

  ExplorationRecord exploration_record(unexplored_vertices);

  vector<vector<int>> chains;

  while (exploration_record.unexploredVerticesExist()) {
    Graph_DF_Visitor graph_visitor;
    int starting_vertex = exploration_record.getUnexploredVertex();
    exploration_record.explore(starting_vertex);
    graph_visitor.setStartingVertex(starting_vertex);
    graph_visitor.initialize(graph);

    vector<int> chain{starting_vertex};
    int old_vertex = starting_vertex;
    bool new_chain = false;
    while (!graph_visitor.queEmpty()) {
      Edge edge = graph_visitor.nextEdge(graph);
      vector<int> unexplored_vertex = graph_visitor.getUnexploredVertex(edge);

      if (new_chain) {
        if (unexplored_vertex.size() == 0) {
          old_vertex = edge.getEndPoint1();
          chain.push_back(old_vertex);
          new_chain = false;
        } else {
          old_vertex = edge.getOtherEndPoint(unexplored_vertex.at(0));
          chain.push_back(old_vertex);
          new_chain = false;
        }
      }
      int new_vertex = edge.getOtherEndPoint(old_vertex);
      if (unexplored_vertex.size() == 0) {
        chain.push_back(new_vertex);
        chains.push_back(chain);
        chain.clear();
        new_chain = true;
      } else if (graph.getDegree(new_vertex) == 1) {
        chain.push_back(new_vertex);
        chains.push_back(chain);
        chain.clear();
        exploration_record.explore(new_vertex);
        new_chain = true;
      } else if (graph.getDegree(new_vertex) > 2) {
        chain.push_back(new_vertex);
        chains.push_back(chain);
        chain.clear();
        exploration_record.explore(new_vertex);
        new_chain = true;
      } else if (unexplored_vertex.size() == 1) {
        chain.push_back(new_vertex);
        old_vertex = new_vertex;
        exploration_record.explore(new_vertex);
      }

      graph_visitor.exec(graph, edge);
    }
  }
  vector<ReducedEdge> reduced_edges;
  for (vector<int> chain : chains) {
    ReducedEdge reduced_edge(chain);
    reduced_edges.push_back(reduced_edge);
  }

  ReducedGraph reduced_g(reduced_edges);
  auto nodes_graph = graph.getNodes();
  reduced_g.copyNodes(graph);
  auto nodes_reduced_g = reduced_g.getNodes();
  return reduced_g;
}

vector<Graph> decoupleIsolatedSubGraphs(Graph graph) {

  list<int> vertices_list = vectorToList_(graph.getVertices());
  vector<Graph> subGraphs;
  Graph_BF_Visitor graph_visitor_breadth_first;
  graph_visitor_breadth_first.setStartingVertex(vertices_list.front());
  if (singleNetwork(graph, graph_visitor_breadth_first)) {
    subGraphs.push_back(graph);
    return subGraphs;
  }

  list<int>::iterator vertices_iterator = vertices_list.begin();
  while (vertices_iterator != vertices_list.end()) {
    unordered_map<int, GraphNode> sub_graph_nodes;
    Graph_BF_Visitor graph_visitor_breadth_first;
    graph_visitor_breadth_first.setStartingVertex(*vertices_iterator);
    exploreGraph(graph, graph_visitor_breadth_first);
    ++vertices_iterator;
    set<int> sub_graph_explored_vertices =
        graph_visitor_breadth_first.getExploredVertices();
    set<Edge> sub_graph_edges;

    set<int>::iterator sub_graph_vertex_it =
        sub_graph_explored_vertices.begin();

    // Means it is an isolated node

    while (sub_graph_vertex_it != sub_graph_explored_vertices.end()) {
      if (*vertices_iterator == *sub_graph_vertex_it) {
        ++vertices_iterator;
      }

      vertices_list.remove(*sub_graph_vertex_it);

      vector<Edge> sub_graph_neigh_edges =
          graph.getNeighEdges(*sub_graph_vertex_it);
      for (const Edge sub_graph_edge : sub_graph_neigh_edges) {
        sub_graph_edges.insert(sub_graph_edge);
      }
      sub_graph_nodes[*sub_graph_vertex_it] =
          graph.getNode(*sub_graph_vertex_it);
      ++sub_graph_vertex_it;
    }
    vector<Edge> sub_graph_vector_edges = edgeSetToVector_(sub_graph_edges);
    Graph graph_temp(sub_graph_vector_edges, sub_graph_nodes);
    subGraphs.push_back(graph_temp);
  }
  return subGraphs;
}

void exploreGraph(Graph& graph, GraphVisitor& graph_visitor) {

  if (!graph.vertexExist(graph_visitor.getStartingVertex())) {
    string err = "Cannot explore graph starting at vertex " +
                 to_string(graph_visitor.getStartingVertex()) +
                 " because it does not exist in the "
                 "graph. You can change the starting vertex by using the "
                 "setStartingVertex method of the visitor instance.";
    throw invalid_argument(err);
  }
  // Create a list of all vertices and determine if they have all been
  // explored when the visitor que is empty
  graph_visitor.initialize(graph);
  while (!graph_visitor.queEmpty()) {
    Edge edge = graph_visitor.nextEdge(graph);
    graph_visitor.exec(graph, edge);
  }
}
}  // namespace tools
}  // namespace votca
<|endoftext|>


<commit_before>#include "data-student.hpp"
using namespace std;

Semester::Semester() {
	period = 0;
}
Semester::Semester(int p) {
	period = p;
}

void Student::init(string n, int s, int g, string m) {
	name = n;
	startingYear = s;
	gradutationYear = g;
	parseMajors(m);
}

Student::Student() {
	init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
	int startYear = stringToInt(s), endYear = stringToInt(e);
	init(n, startYear, endYear, m);
}
Student::Student(string fn) {
	ifstream infile;
	infile.open(fn.c_str());
}

void Student::parseMajors(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
		string str = removeStartingText(*i, " ");
		Major m = Major(str);
		majors.push_back(m);
	}
}

bool Student::hasTakenCourse() {
	return false;
}

void Student::addCourse(const Course& c) {
	// cout << "Hi! I'm addCourse (not courses!!)!" << endl;
	courses.push_back(c);
	// cout << courses.at(courses.size()-1) << endl;
}

void Student::addCourses(string str) {
	// cout << "Hi! I'm addCourses!" << endl;
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
		Course c = Course(*i);
		addCourse(c);
	}
}

ostream& Student::getData(ostream &os) {
	os << name << ", ";
	os << "you are majoring in ";
	for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
		if (i!=majors.end()-1)
			os << *i << ", ";
		else
			os << "and "<< *i;
	}
	os << ", while taking:" << endl;
	for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
		os << *i << endl;
	return os;
}
void Student::display() {
	cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
	os << item.getData(os);
	return os;
}
<commit_msg>… or two, it seems.<commit_after>#include "data-student.hpp"
using namespace std;

Semester::Semester() {
	period = 0;
}
Semester::Semester(int p) {
	period = p;
}

void Student::init(string n, int s, int g, string m) {
	name = n;
	startingYear = s;
	gradutationYear = g;
	parseMajors(m);
}

Student::Student() {
	init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
	int startYear = stringToInt(s), endYear = stringToInt(e);
	init(n, startYear, endYear, m);
}
Student::Student(string fn) {
	ifstream infile;
	infile.open(fn.c_str());
}

void Student::parseMajors(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
		string str = removeStartingText(*i, " ");
		Major m = Major(str);
		majors.push_back(m);
	}
}

bool Student::hasTakenCourse() {
	return false;
}

void Student::addCourse(const Course& c) {
	// cout << "Hi! I'm addCourse (not courses!!)!" << endl;
	courses.push_back(c);
	// cout << courses.at(courses.size()-1) << endl;
}

void Student::addCourses(string str) {
	// cout << "Hi! I'm addCourses!" << endl;
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
		// cout << *i << endl;
		Course c = Course(*i);
		addCourse(c);
	}
}

ostream& Student::getData(ostream &os) {
	os << name << ", ";
	os << "you are majoring in ";
	for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
		if (i!=majors.end()-1)
			os << *i << ", ";
		else
			os << "and "<< *i;
	}
	os << ", while taking:" << endl;
	for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
		os << *i << endl;
	return os;
}
void Student::display() {
	cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
	os << item.getData(os);
	return os;
}
<|endoftext|>


<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include "gil.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

  bool listen_on(session& s, int min_, int max_, char const* interface)
  {
      allow_threading_guard guard;
      return s.listen_on(std::make_pair(min_, max_), interface);
  }
  void outgoing_ports(session& s, int _min, int _max)
  {
      allow_threading_guard guard;
      session_settings settings = s.settings();
      settings.outgoing_ports = std::make_pair(_min, _max);
      s.set_settings(settings);
      return;
  }
#ifndef TORRENT_DISABLE_DHT
  void add_dht_router(session& s, std::string router_, int port_)
  {
      allow_threading_guard guard;
      return s.add_dht_router(std::make_pair(router_, port_));
  }
#endif

  struct invoke_extension_factory
  {
      invoke_extension_factory(object const& callback)
        : cb(callback)
      {}

      boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
      {
          lock_gil lock;
          return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
      }

      object cb;
  };

  void add_extension(session& s, object const& e)
  {
      allow_threading_guard guard;
      s.add_extension(invoke_extension_factory(e));
  }

#ifndef TORRENT_NO_DEPRECATE
  torrent_handle add_torrent_depr(session& s, torrent_info const& ti
    , boost::filesystem::path const& save, entry const& resume
    , storage_mode_t storage_mode, bool paused)
  {
      allow_threading_guard guard;
      return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);
  }
#endif

  torrent_handle add_torrent(session& s, dict params)
  {
    add_torrent_params p;

    if (params.has_key("ti"))
      p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));

    std::string url;
    if (params.has_key("tracker_url"))
    {
      url = extract<std::string>(params["tracker_url"]);
      p.tracker_url = url.c_str();
    }
    if (params.has_key("info_hash"))
      p.info_hash = extract<sha1_hash>(params["info_hash"]);
    std::string name;
    if (params.has_key("name"))
    {
      name = extract<std::string>(params["name"]);
      p.name = name.c_str();
    }
    p.save_path = fs::path(extract<std::string>(params["save_path"]));

    std::vector<char> resume_buf;
    if (params.has_key("resume_data"))
    {
      std::string resume = extract<std::string>(params["resume_data"]);
      resume_buf.resize(resume.size());
      std::memcpy(&resume_buf[0], &resume[0], resume.size());
      p.resume_data = &resume_buf;
    }
    if (params.has_key("storage_mode"))
        p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
    if (params.has_key("paused"))
       p.paused = params["paused"];
    if (params.has_key("auto_managed"))
       p.auto_managed = params["auto_managed"];
    if (params.has_key("duplicate_is_error"))
       p.duplicate_is_error = params["duplicate_is_error"];
    if (params.has_key("seed_mode"))
       p.seed_mode = params["seed_mode"];
    if (params.has_key("override_resume_data"))
       p.override_resume_data = params["override_resume_data"];

    return s.add_torrent(p);
  }

  void start_natpmp(session& s)
  {
      allow_threading_guard guard;
      s.start_natpmp();
      return;
  }

  void start_upnp(session& s)
  {
      allow_threading_guard guard;
      s.start_upnp();
      return;
  }

  list get_torrents(session& s)
  {
     list ret;
     std::vector<torrent_handle> torrents = s.get_torrents();

     for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
     {
       ret.append(*i);
     }
     return ret;
  }

#ifndef TORRENT_DISABLE_GEO_IP
  bool load_asnum_db(session& s, std::string file)
  {
      allow_threading_guard guard;
      return s.load_asnum_db(file.c_str());
  }

  bool load_country_db(session& s, std::string file)
  {
      allow_threading_guard guard;
      return s.load_country_db(file.c_str());
  }
#endif
} // namespace unnamed

void bind_session()
{
    class_<session_status>("session_status")
        .def_readonly("has_incoming_connections", &session_status::has_incoming_connections)
        .def_readonly("upload_rate", &session_status::upload_rate)
        .def_readonly("download_rate", &session_status::download_rate)
        .def_readonly("payload_upload_rate", &session_status::payload_upload_rate)
        .def_readonly("payload_download_rate", &session_status::payload_download_rate)
        .def_readonly("total_download", &session_status::total_download)
        .def_readonly("total_upload", &session_status::total_upload)
        .def_readonly("total_payload_download", &session_status::total_payload_download)
        .def_readonly("total_payload_upload", &session_status::total_payload_upload)
        .def_readonly("num_peers", &session_status::num_peers)
#ifndef TORRENT_DISABLE_DHT
        .def_readonly("dht_nodes", &session_status::dht_nodes)
        .def_readonly("dht_cache_nodes", &session_status::dht_node_cache)
        .def_readonly("dht_torrents", &session_status::dht_torrents)
#endif
        ;

    enum_<storage_mode_t>("storage_mode_t")
        .value("storage_mode_allocate", storage_mode_allocate)
        .value("storage_mode_sparse", storage_mode_sparse)
        .value("storage_mode_compact", storage_mode_compact)
    ;

    enum_<session::options_t>("options_t")
        .value("none", session::none)
        .value("delete_files", session::delete_files)
    ;

    enum_<session::session_flags_t>("session_flags_t")
        .value("add_default_plugins", session::add_default_plugins)
        .value("start_default_features", session::start_default_features)
    ;

    class_<session, boost::noncopyable>("session", no_init)
        .def(
            init<fingerprint, int>((
                arg("fingerprint")=fingerprint("LT",0,1,0,0)
                , arg("flags")=session::start_default_features | session::add_default_plugins))
        )
        .def(
            "listen_on", &listen_on
          , (arg("min"), "max", arg("interface") = (char const*)0)
        )
        .def("outgoing_ports", &outgoing_ports)
        .def("is_listening", allow_threads(&session::is_listening))
        .def("listen_port", allow_threads(&session::listen_port))
        .def("status", allow_threads(&session::status))
#ifndef TORRENT_DISABLE_DHT
        .def(
            "add_dht_router", &add_dht_router
          , (arg("router"), "port")
        )
        .def("start_dht", allow_threads(&session::start_dht))
        .def("stop_dht", allow_threads(&session::stop_dht))
        .def("dht_state", allow_threads(&session::dht_state))
        .def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
        .def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())
#endif
        .def("add_torrent", &add_torrent)
#ifndef TORRENT_NO_DEPRECATE
        .def(
            "add_torrent", &add_torrent_depr
          , (
                arg("resume_data") = entry(),
					 arg("storage_mode") = storage_mode_sparse,
                arg("paused") = false
            )
        )
#endif
        .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
)
        .def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit))
        .def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit))

        .def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit))
        .def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit))

        .def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit))
        .def("download_rate_limit", allow_threads(&session::download_rate_limit))

        .def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit))
        .def("upload_rate_limit", allow_threads(&session::upload_rate_limit))

        .def("set_max_uploads", allow_threads(&session::set_max_uploads))
        .def("set_max_connections", allow_threads(&session::set_max_connections))
        .def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections))
        .def("num_connections", allow_threads(&session::num_connections))
        .def("set_settings", allow_threads(&session::set_settings))
        .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>())
#ifndef TORRENT_DISABLE_ENCRYPTION
        .def("set_pe_settings", allow_threads(&session::set_pe_settings))
        .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
        .def("load_asnum_db", &load_asnum_db)
        .def("load_country_db", &load_country_db)
#endif
        .def("load_state", allow_threads(&session::load_state))
        .def("state", allow_threads(&session::state))
#ifndef TORRENT_NO_DEPRECATE
        .def("set_severity_level", allow_threads(&session::set_severity_level))
#endif
        .def("set_alert_mask", allow_threads(&session::set_alert_mask))
        .def("pop_alert", allow_threads(&session::pop_alert))
        .def("add_extension", &add_extension)
        .def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
        .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
        .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
        .def("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())
        .def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())
        .def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())
        .def("start_upnp", &start_upnp)
        .def("stop_upnp", allow_threads(&session::stop_upnp))
        .def("start_lsd", allow_threads(&session::start_lsd))
        .def("stop_lsd", allow_threads(&session::stop_lsd))
        .def("start_natpmp", &start_natpmp)
        .def("stop_natpmp", allow_threads(&session::stop_natpmp))
        .def("set_ip_filter", allow_threads(&session::set_ip_filter))
        .def("find_torrent", allow_threads(&session::find_torrent))
        .def("get_torrents", &get_torrents)
        .def("pause", allow_threads(&session::pause))
        .def("resume", allow_threads(&session::resume))
        .def("is_paused", allow_threads(&session::is_paused))
        .def("id", allow_threads(&session::id))
        ;

    register_ptr_to_python<std::auto_ptr<alert> >();
}
<commit_msg>Update and clean-up session.cpp in python bindings<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include "gil.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{
    bool listen_on(session& s, int min_, int max_, char const* interface)
    {
        allow_threading_guard guard;
        return s.listen_on(std::make_pair(min_, max_), interface);
    }

    void outgoing_ports(session& s, int _min, int _max)
    {
        allow_threading_guard guard;
        session_settings settings = s.settings();
        settings.outgoing_ports = std::make_pair(_min, _max);
        s.set_settings(settings);
        return;
    }
#ifndef TORRENT_DISABLE_DHT
    void add_dht_router(session& s, std::string router_, int port_)
    {
        allow_threading_guard guard;
        return s.add_dht_router(std::make_pair(router_, port_));
    }
#endif

    struct invoke_extension_factory
    {
        invoke_extension_factory(object const& callback)
            : cb(callback)
        {}

        boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
        {
           lock_gil lock;
           return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
        }

        object cb;
    };

    void add_extension(session& s, object const& e)
    {
        allow_threading_guard guard;
        s.add_extension(invoke_extension_factory(e));
    }

#ifndef TORRENT_NO_DEPRECATE
    torrent_handle add_torrent_depr(session& s, torrent_info const& ti
        , boost::filesystem::path const& save, entry const& resume
        , storage_mode_t storage_mode, bool paused)
    {
        allow_threading_guard guard;
        return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);
    }
#endif

    torrent_handle add_torrent(session& s, dict params)
    {
        add_torrent_params p;

        if (params.has_key("ti"))
            p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));

        std::string url;
        if (params.has_key("tracker_url"))
        {
            url = extract<std::string>(params["tracker_url"]);
            p.tracker_url = url.c_str();
        }
        if (params.has_key("info_hash"))
            p.info_hash = extract<sha1_hash>(params["info_hash"]);
        std::string name;
        if (params.has_key("name"))
        {
            name = extract<std::string>(params["name"]);
            p.name = name.c_str();
        }
        p.save_path = fs::path(extract<std::string>(params["save_path"]));

        std::vector<char> resume_buf;
        if (params.has_key("resume_data"))
        {
            std::string resume = extract<std::string>(params["resume_data"]);
            resume_buf.resize(resume.size());
            std::memcpy(&resume_buf[0], &resume[0], resume.size());
            p.resume_data = &resume_buf;
        }
        if (params.has_key("storage_mode"))
            p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
        if (params.has_key("paused"))
            p.paused = params["paused"];
        if (params.has_key("auto_managed"))
            p.auto_managed = params["auto_managed"];
        if (params.has_key("duplicate_is_error"))
            p.duplicate_is_error = params["duplicate_is_error"];
        if (params.has_key("seed_mode"))
            p.seed_mode = params["seed_mode"];
        if (params.has_key("override_resume_data"))
            p.override_resume_data = params["override_resume_data"];

        return s.add_torrent(p);
    }

    void start_natpmp(session& s)
    {
        allow_threading_guard guard;
        s.start_natpmp();
        return;
    }

    void start_upnp(session& s)
    {
        allow_threading_guard guard;
        s.start_upnp();
        return;
    }

    list get_torrents(session& s)
    {
        list ret;
        std::vector<torrent_handle> torrents = s.get_torrents();

        for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
        {
            ret.append(*i);
        }
        return ret;
    }

#ifndef TORRENT_DISABLE_GEO_IP
    bool load_asnum_db(session& s, std::string file)
    {
        allow_threading_guard guard;
        return s.load_asnum_db(file.c_str());
    }

    bool load_country_db(session& s, std::string file)
    {
        allow_threading_guard guard;
        return s.load_country_db(file.c_str());
    }
#endif
} // namespace unnamed

void bind_session()
{
    class_<session_status>("session_status")
        .def_readonly("has_incoming_connections", &session_status::has_incoming_connections)

        .def_readonly("upload_rate", &session_status::upload_rate)
        .def_readonly("download_rate", &session_status::download_rate)
        .def_readonly("total_download", &session_status::total_download)
        .def_readonly("total_upload", &session_status::total_upload)

        .def_readonly("payload_upload_rate", &session_status::payload_upload_rate)
        .def_readonly("payload_download_rate", &session_status::payload_download_rate)
        .def_readonly("total_payload_download", &session_status::total_payload_download)
        .def_readonly("total_payload_upload", &session_status::total_payload_upload)

        .def_readonly("ip_overhead_upload_rate", &session_status::ip_overhead_upload_rate)
        .def_readonly("ip_overhead_download_rate", &session_status::ip_overhead_download_rate)
        .def_readonly("total_ip_overhead_download", &session_status::total_ip_overhead_download)
        .def_readonly("total_ip_overhead_upload", &session_status::total_ip_overhead_upload)

        .def_readonly("dht_upload_rate", &session_status::dht_upload_rate)
        .def_readonly("dht_download_rate", &session_status::dht_download_rate)
        .def_readonly("total_dht_download", &session_status::total_dht_download)
        .def_readonly("total_dht_upload", &session_status::total_dht_upload)

        .def_readonly("tracker_upload_rate", &session_status::tracker_upload_rate)
        .def_readonly("tracker_download_rate", &session_status::tracker_download_rate)
        .def_readonly("total_tracker_download", &session_status::total_tracker_download)
        .def_readonly("total_tracker_upload", &session_status::total_tracker_upload)

        .def_readonly("total_redundant_bytes", &session_status::total_redundant_bytes)
        .def_readonly("total_failed_bytes", &session_status::total_failed_bytes)

        .def_readonly("num_peers", &session_status::num_peers)
        .def_readonly("num_unchoked", &session_status::num_unchoked)
        .def_readonly("allowed_upload_slots", &session_status::allowed_upload_slots)

        .def_readonly("up_bandwidth_queue", &session_status::up_bandwidth_queue)
        .def_readonly("down_bandwidth_queue", &session_status::down_bandwidth_queue)

        .def_readonly("up_bandwidth_bytes_queue", &session_status::up_bandwidth_bytes_queue)
        .def_readonly("down_bandwidth_bytes_queue", &session_status::down_bandwidth_bytes_queue)

        .def_readonly("optimistic_unchoke_counter", &session_status::optimistic_unchoke_counter)
        .def_readonly("unchoke_counter", &session_status::unchoke_counter)

#ifndef TORRENT_DISABLE_DHT
        .def_readonly("dht_nodes", &session_status::dht_nodes)
        .def_readonly("dht_cache_nodes", &session_status::dht_node_cache)
        .def_readonly("dht_torrents", &session_status::dht_torrents)
        .def_readonly("dht_global_nodes", &session_status::dht_global_nodes)
        .def_readonly("active_requests", &session_status::active_requests)
#endif
        ;

    class_<dht_lookup>("dht_lookup")
        .def_readonly("type", &dht_lookup::type)
        .def_readonly("outstanding_requests", &dht_lookup::outstanding_requests)
        .def_readonly("timeouts", &dht_lookup::timeouts)
        .def_readonly("response", &dht_lookup::responses)
        .def_readonly("branch_factor", &dht_lookup::branch_factor)
    ;

    enum_<storage_mode_t>("storage_mode_t")
        .value("storage_mode_allocate", storage_mode_allocate)
        .value("storage_mode_sparse", storage_mode_sparse)
        .value("storage_mode_compact", storage_mode_compact)
    ;

    enum_<session::options_t>("options_t")
        .value("none", session::none)
        .value("delete_files", session::delete_files)
    ;

    enum_<session::session_flags_t>("session_flags_t")
        .value("add_default_plugins", session::add_default_plugins)
        .value("start_default_features", session::start_default_features)
    ;

    class_<session, boost::noncopyable>("session", no_init)
        .def(
            init<fingerprint, int>((
                arg("fingerprint")=fingerprint("LT",0,1,0,0)
                , arg("flags")=session::start_default_features | session::add_default_plugins))
        )
        .def(
            "listen_on", &listen_on
          , (arg("min"), "max", arg("interface") = (char const*)0)
        )
        .def("outgoing_ports", &outgoing_ports)
        .def("is_listening", allow_threads(&session::is_listening))
        .def("listen_port", allow_threads(&session::listen_port))
        .def("status", allow_threads(&session::status))
#ifndef TORRENT_DISABLE_DHT
        .def(
            "add_dht_router", &add_dht_router
          , (arg("router"), "port")
        )
        .def("start_dht", allow_threads(&session::start_dht))
        .def("stop_dht", allow_threads(&session::stop_dht))
        .def("dht_state", allow_threads(&session::dht_state))
        .def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
        .def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())
#endif
        .def("add_torrent", &add_torrent)
#ifndef TORRENT_NO_DEPRECATE
        .def(
            "add_torrent", &add_torrent_depr
          , (
                arg("resume_data") = entry(),
					 arg("storage_mode") = storage_mode_sparse,
                arg("paused") = false
            )
        )
#endif
        .def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
)
        .def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit))
        .def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit))

        .def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit))
        .def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit))

        .def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit))
        .def("download_rate_limit", allow_threads(&session::download_rate_limit))

        .def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit))
        .def("upload_rate_limit", allow_threads(&session::upload_rate_limit))

        .def("set_max_uploads", allow_threads(&session::set_max_uploads))
        .def("set_max_connections", allow_threads(&session::set_max_connections))
        .def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections))
        .def("num_connections", allow_threads(&session::num_connections))
        .def("set_settings", allow_threads(&session::set_settings))
        .def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>())
#ifndef TORRENT_DISABLE_ENCRYPTION
        .def("set_pe_settings", allow_threads(&session::set_pe_settings))
        .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
        .def("load_asnum_db", &load_asnum_db)
        .def("load_country_db", &load_country_db)
#endif
        .def("load_state", allow_threads(&session::load_state))
        .def("state", allow_threads(&session::state))
#ifndef TORRENT_NO_DEPRECATE
        .def("set_severity_level", allow_threads(&session::set_severity_level))
#endif
        .def("set_alert_mask", allow_threads(&session::set_alert_mask))
        .def("pop_alert", allow_threads(&session::pop_alert))
        .def("add_extension", &add_extension)
        .def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
        .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
        .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
        .def("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())
        .def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())
        .def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())
        .def("start_upnp", &start_upnp)
        .def("stop_upnp", allow_threads(&session::stop_upnp))
        .def("start_lsd", allow_threads(&session::start_lsd))
        .def("stop_lsd", allow_threads(&session::stop_lsd))
        .def("start_natpmp", &start_natpmp)
        .def("stop_natpmp", allow_threads(&session::stop_natpmp))
        .def("set_ip_filter", allow_threads(&session::set_ip_filter))
        .def("find_torrent", allow_threads(&session::find_torrent))
        .def("get_torrents", &get_torrents)
        .def("pause", allow_threads(&session::pause))
        .def("resume", allow_threads(&session::resume))
        .def("is_paused", allow_threads(&session::is_paused))
        .def("id", allow_threads(&session::id))
        ;

    register_ptr_to_python<std::auto_ptr<alert> >();
}
<|endoftext|>