<commit_before>/* -*- Mode: C++; c-file-style: "gnu" -*- */
/*
 * Copyright 2014 Waseda University, Sato Laboratory
 *   Author: Jairo Eduardo Lopez <jairo@ruri.waseda.jp>
 *           Zhu Li <philipszhuli1990@ruri.waseda.jp>
 *
 *  nnn-den.h is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  nnn-den.h 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 Affero Public License for more details.
 *
 *  You should have received a copy of the GNU Affero Public License
 *  along with nnn-den.h.  If not, see <http://www.gnu.org/licenses/>.
 */

#include<ns3-dev/ns3/log.h>
#include <ns3-dev/ns3/unused.h>

#include "nnn-den.h"

NS_LOG_COMPONENT_DEFINE ("nnn.DEN");

namespace ns3 {
  namespace nnn{

    DEN::DEN () : NNNPacket (DEN_NNN, Seconds(0))
    , m_poa_type (POA_MAC48)
    , m_poas     (std::vector<Address> ())
    {
    }

    DEN::DEN (Ptr<NNNAddress> name)
    : NNNPacket (DEN_NNN, Seconds(300))
    , m_name     (name)
    , m_poa_type (POA_MAC48)
    , m_poas     (std::vector<Address> ())
    {
    }

    DEN::DEN (const NNNAddress &name)
    : NNNPacket (DEN_NNN, Seconds(300))
    , m_name     (Create<NNNAddress> (name))
    , m_poa_type (POA_MAC48)
    , m_poas     (std::vector<Address> ())
    {
    }

    DEN::DEN (const DEN &den_p)
    : NNNPacket (DEN_NNN, den_p.GetLifetime ())
    , m_name     (Create<NNNAddress> (den_p.GetName()))
    , m_poa_type (den_p.GetPoaType())
    , m_poas (den_p.GetPoas())
    {
      NS_LOG_FUNCTION("DEN correct copy constructor");

      SetWire (den_p.GetWire ());
    }

    const NNNAddress&
    DEN::GetName () const
    {
      if (m_name == 0) throw DENException ();
      return *m_name;
    }

    Ptr<const NNNAddress>
    DEN::GetNamePtr () const
    {
      return m_name;
    }

    void
    DEN::SetName(Ptr<NNNAddress> name)
    {
      m_name = name;
      SetWire (0);
    }

    void
    DEN::SetName (const NNNAddress &name)
    {
      m_name = Create<NNNAddress> (name);
      SetWire (0);
    }

    uint16_t
    DEN::GetPoaType () const
    {
      return m_poa_type;
    }

    void
    DEN::SetPoaType (uint16_t type)
    {
      m_poa_type = type;
    }

    void
    DEN::AddPoa (Address signature)
    {
      m_poas.push_back(signature);
    }

    void
    DEN::AddPoa (std::vector<Address> signatures)
    {
      m_poas.insert(m_poas.end (), signatures.begin (), signatures.end ());
    }

    uint32_t
    DEN::GetNumPoa () const
    {
      return m_poas.size();
    }

    std::vector<Address>
    DEN::GetPoas () const
    {
      return m_poas;
    }

    Address
    DEN::GetOnePoa (uint32_t index) const
    {
      if (index < GetNumPoa ())
	return m_poas[index];
      else
	return Address();
    }

    void
    DEN::Print (std::ostream &os) const
    {
      os << "<DEN>\n";
      os << " <TTL>" << GetLifetime () << "</TTL>\n";
      os << " <Name>" << GetName () << "</Name>\n";
    }

  } // namespace nnn
} // namespace ns3
<commit_msg>Fixing DEN print function<commit_after>/* -*- Mode: C++; c-file-style: "gnu" -*- */
/*
 * Copyright 2014 Waseda University, Sato Laboratory
 *   Author: Jairo Eduardo Lopez <jairo@ruri.waseda.jp>
 *           Zhu Li <philipszhuli1990@ruri.waseda.jp>
 *
 *  nnn-den.h is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  nnn-den.h 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 Affero Public License for more details.
 *
 *  You should have received a copy of the GNU Affero Public License
 *  along with nnn-den.h.  If not, see <http://www.gnu.org/licenses/>.
 */

#include<ns3-dev/ns3/log.h>
#include <ns3-dev/ns3/unused.h>

#include "nnn-den.h"

NS_LOG_COMPONENT_DEFINE ("nnn.DEN");

namespace ns3 {
  namespace nnn{

    DEN::DEN () : NNNPacket (DEN_NNN, Seconds(0))
    , m_poa_type (POA_MAC48)
    , m_poas     (std::vector<Address> ())
    {
    }

    DEN::DEN (Ptr<NNNAddress> name)
    : NNNPacket (DEN_NNN, Seconds(300))
    , m_name     (name)
    , m_poa_type (POA_MAC48)
    , m_poas     (std::vector<Address> ())
    {
    }

    DEN::DEN (const NNNAddress &name)
    : NNNPacket (DEN_NNN, Seconds(300))
    , m_name     (Create<NNNAddress> (name))
    , m_poa_type (POA_MAC48)
    , m_poas     (std::vector<Address> ())
    {
    }

    DEN::DEN (const DEN &den_p)
    : NNNPacket (DEN_NNN, den_p.GetLifetime ())
    , m_name     (Create<NNNAddress> (den_p.GetName()))
    , m_poa_type (den_p.GetPoaType())
    , m_poas (den_p.GetPoas())
    {
      NS_LOG_FUNCTION("DEN correct copy constructor");

      SetWire (den_p.GetWire ());
    }

    const NNNAddress&
    DEN::GetName () const
    {
      if (m_name == 0) throw DENException ();
      return *m_name;
    }

    Ptr<const NNNAddress>
    DEN::GetNamePtr () const
    {
      return m_name;
    }

    void
    DEN::SetName(Ptr<NNNAddress> name)
    {
      m_name = name;
      SetWire (0);
    }

    void
    DEN::SetName (const NNNAddress &name)
    {
      m_name = Create<NNNAddress> (name);
      SetWire (0);
    }

    uint16_t
    DEN::GetPoaType () const
    {
      return m_poa_type;
    }

    void
    DEN::SetPoaType (uint16_t type)
    {
      m_poa_type = type;
    }

    void
    DEN::AddPoa (Address signature)
    {
      m_poas.push_back(signature);
    }

    void
    DEN::AddPoa (std::vector<Address> signatures)
    {
      m_poas.insert(m_poas.end (), signatures.begin (), signatures.end ());
    }

    uint32_t
    DEN::GetNumPoa () const
    {
      return m_poas.size();
    }

    std::vector<Address>
    DEN::GetPoas () const
    {
      return m_poas;
    }

    Address
    DEN::GetOnePoa (uint32_t index) const
    {
      if (index < GetNumPoa ())
	return m_poas[index];
      else
	return Address();
    }

    void
    DEN::Print (std::ostream &os) const
    {
      os << "<DEN>" << std::endl;
      os << "  <TTL>" << GetLifetime () << "</TTL>" << std::endl;
      os << "  <Name>" << GetName () << "</Name>" << std::endl;
      for (int i = 0; i < GetNumPoa (); i++)
	{
	  os << "  <POA" << i << ">" << GetOnePoa(i) << "</POA" << i << ">"<< std::endl;
	}
      os << "</DEN>" << std::endl;
    }

  } // namespace nnn
} // namespace ns3
<|endoftext|>


<commit_before>
#include "../CEpubFile.h"
#include "../../DesktopEditor/common/File.h"
#include "../../DesktopEditor/common/Directory.h"

#include <time.h>
#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::wstring sTmp = NSFile::GetProcessDirectory() + L"/tmp";
    std::wstring sOutputDirectory = NSFile::GetProcessDirectory() + L"/OutputFiles";
    NSDirectory::CreateDirectory(sOutputDirectory);
    NSDirectory::CreateDirectory(sTmp);

    bool bFromHtml = false;
    if (bFromHtml)
    {
        std::wstring sFile = NSFile::GetProcessDirectory() + L"/../../../FromHtmlTest/test3";
        CEpubFile oEpub;
        oEpub.SetTempDirectory(sTmp);
        oEpub.FromHtml(sFile, sOutputDirectory + L"/res.epub");
        NSDirectory::DeleteDirectory(sTmp);
        return 0;
    }

    std::vector<std::wstring> arFiles = NSDirectory::GetFiles(NSFile::GetProcessDirectory() + L"/../../../Files");

    clock_t tTime1 = clock();
    //Русские символы в консоль не выводятся
    for (const std::wstring& sFileName : arFiles)
    {
        clock_t tTimeBegin = clock();

        CEpubFile oEpub;

        if (oEpub.IsEpubFile(sFileName) == S_OK)
        {
            std::wstring sFile = NSFile::GetFileName(sFileName);
            sFile = sFile.substr(0, sFile.rfind(L'.'));

            std::wcout << L"|----------|" << sFile << L"|----------|" << std::endl;

            oEpub.SetTempDirectory(sTmp);
            oEpub.Convert(sFileName, sOutputDirectory + L"/" + sFile + L".docx");
            NSDirectory::DeleteDirectory(sTmp + L"/res/word/media");
//            oEpub.ShowMap();
        }
        else
            std::wcout << sFileName << L" this is not an epub format!" << std::endl;
        clock_t tTimeEnd = clock();

        std::wcout << (double)(tTimeEnd - tTimeBegin) / CLOCKS_PER_SEC << std::endl;
    }

    clock_t tTime2 = clock();

    std::wcout << (double)(tTime2 - tTime1) / CLOCKS_PER_SEC << std::endl;
    NSDirectory::DeleteDirectory(sTmp);

    return 0;
}
<commit_msg>fix epub test<commit_after>
#include "../CEpubFile.h"
#include "../../DesktopEditor/common/File.h"
#include "../../DesktopEditor/common/Directory.h"

#include <time.h>
#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::wstring sTmp = NSFile::GetProcessDirectory() + L"/tmp";
    std::wstring sOutputDirectory = NSFile::GetProcessDirectory() + L"/OutputFiles";
    NSDirectory::CreateDirectory(sOutputDirectory);
    NSDirectory::CreateDirectory(sTmp);

    bool bFromHtml = false;
    if (bFromHtml)
    {
        std::wstring sFile = NSFile::GetProcessDirectory() + L"/../../../FromHtmlTest/test3";
        CEpubFile oEpub;
        oEpub.SetTempDirectory(sTmp);
        oEpub.FromHtml(sFile, sFile, sOutputDirectory + L"/res.epub");
        NSDirectory::DeleteDirectory(sTmp);
        return 0;
    }

    std::vector<std::wstring> arFiles = NSDirectory::GetFiles(NSFile::GetProcessDirectory() + L"/../../../Files");

    clock_t tTime1 = clock();
    //Русские символы в консоль не выводятся
    for (const std::wstring& sFileName : arFiles)
    {
        clock_t tTimeBegin = clock();

        CEpubFile oEpub;

        if (oEpub.IsEpubFile(sFileName) == S_OK)
        {
            std::wstring sFile = NSFile::GetFileName(sFileName);
            sFile = sFile.substr(0, sFile.rfind(L'.'));

            std::wcout << L"|----------|" << sFile << L"|----------|" << std::endl;

            oEpub.SetTempDirectory(sTmp);
            oEpub.Convert(sFileName, sOutputDirectory + L"/" + sFile + L".docx");
            NSDirectory::DeleteDirectory(sTmp + L"/res/word/media");
//            oEpub.ShowMap();
        }
        else
            std::wcout << sFileName << L" this is not an epub format!" << std::endl;
        clock_t tTimeEnd = clock();

        std::wcout << (double)(tTimeEnd - tTimeBegin) / CLOCKS_PER_SEC << std::endl;
    }

    clock_t tTime2 = clock();

    std::wcout << (double)(tTime2 - tTime1) / CLOCKS_PER_SEC << std::endl;
    NSDirectory::DeleteDirectory(sTmp);

    return 0;
}
<|endoftext|>


<commit_before>#include "Tab.h"

#include "UIContext.h"

Tab::Tab() {

}

Tab::~Tab() {

}

DLGPROC Tab::TabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    unsigned short nCode, ctrlId;

    switch (message) {
    case WM_INITDIALOG:
        _hWnd = hDlg;
        Initialize();
        LoadSettings();
        return FALSE;

    case WM_COMMAND:
        PropSheet_Changed(GetParent(hDlg), NULL);
        nCode = HIWORD(wParam);
        ctrlId = LOWORD(wParam);
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Command(nCode);
        } else {
            return FALSE;
        }

    case WM_NOTIFY:
        NMHDR *nHdr = (NMHDR *) lParam;
        ctrlId = nHdr->idFrom;
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Notification(nHdr);
        } else {
            return FALSE;
        }
    }

    return FALSE;
}<commit_msg>Remove UIContext dependency<commit_after>#include "Tab.h"

Tab::Tab() {

}

Tab::~Tab() {

}

DLGPROC Tab::TabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    unsigned short nCode, ctrlId;

    switch (message) {
    case WM_INITDIALOG:
        _hWnd = hDlg;
        Initialize();
        LoadSettings();
        return FALSE;

    case WM_COMMAND:
        PropSheet_Changed(GetParent(hDlg), NULL);
        nCode = HIWORD(wParam);
        ctrlId = LOWORD(wParam);
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Command(nCode);
        } else {
            return FALSE;
        }

    case WM_NOTIFY:
        NMHDR *nHdr = (NMHDR *) lParam;
        ctrlId = nHdr->idFrom;
        if (_controlMap.count(ctrlId) > 0) {
            return _controlMap[ctrlId]->Notification(nHdr);
        } else {
            return FALSE;
        }
    }

    return FALSE;
}<|endoftext|>


<commit_before>/* LiteSQL - Date and time classes
 *
 * The list of contributors at http://litesql.sf.net/
 *
 * See LICENSE for copyright information. */
#include "litesql/datetime.hpp"
#include "litesql/split.hpp"
#include "compatibility.hpp"
#include <time.h>
#include <cstdio>

using namespace std;

namespace litesql {

TimeStruct::TimeStruct(time_t t) {
    if (!t)
        t = time(NULL);
    localtime_r(&t, &mytm);
}
int TimeStruct::day() const {
    return mytm.tm_mday;
}
int TimeStruct::dayOfWeek() const {
    return mytm.tm_wday;
}
int TimeStruct::dayOfYear() const {
    return mytm.tm_yday;
}
int TimeStruct::month() const {
    return mytm.tm_mon + 1;
}
int TimeStruct::year() const {
    return mytm.tm_year + 1900;
}
int TimeStruct::hour() const {
    return mytm.tm_hour;
}
int TimeStruct::min() const {
    return mytm.tm_min;
}
int TimeStruct::sec() const {
    return mytm.tm_sec;
}
time_t TimeStruct::timeStamp() const {
    return mktime(const_cast<struct tm*>(&mytm));
}
TimeStruct&  TimeStruct::setDay(int day) {
    mytm.tm_mday = day;
    return *this;
}
TimeStruct& TimeStruct::setMonth(int month) {
    mytm.tm_mon = month - 1;
    return *this;
}
TimeStruct& TimeStruct::setYear(int year) {
    mytm.tm_year = year - 1900;
    return *this;
}
TimeStruct& TimeStruct::setHour(int hour) {
    mytm.tm_hour = hour;
    return *this;
}
TimeStruct& TimeStruct::setMin(int min) {
    mytm.tm_min = min;
    return *this;
}
TimeStruct& TimeStruct::setSec(int sec) {
    mytm.tm_sec = sec;
    return *this;
}
TimeStruct& TimeStruct::setTimeStamp(time_t t) {
    localtime_r(&t, &mytm);
    return *this;
}

Date::Date(time_t t) : value(t) {
    if (value == 0)
        value = time(NULL);
}
Date::Date(int day, int month, int year) {
    value = TimeStruct().setDay(day).setMonth(month).setYear(year)
        .timeStamp();
}
int Date::day() const {
    return TimeStruct(value).day();
}
int Date::dayOfWeek() const {
    return TimeStruct(value).dayOfWeek();
}
int Date::month() const {
    return TimeStruct(value).month();
}
int Date::year() const {
    return TimeStruct(value).year();
}
time_t Date::timeStamp() const {
    return value;
}
TimeStruct Date::timeStruct() const {
    return TimeStruct(value);
}
Date& Date::setDay(int d) {
    value = TimeStruct(value).setDay(d).timeStamp();
    return *this;
}
Date& Date::setMonth(int m) {
    value = TimeStruct(value).setMonth(m).timeStamp();
    return *this;
}
Date& Date::setYear(int y) {
    value = TimeStruct(value).setYear(y).timeStamp();
    return *this;
}
Date& Date::setTimeStamp(time_t t) {
    value = t;
    return *this;
}
string Date::asString(string format) const {
    if (format == "%u") {
        char buf[32];
        snprintf(buf, 32, "%lu", value);
        return buf;
    }
    Split data(format, "%");
    TimeStruct ts(value);
    string res = data[0];
    for (size_t i = 1; i < data.size(); i++) {
        string rest = data[i].substr(1, data[i].size());
        switch(data[i][0]) {
        case 'd':
            res += toString(ts.day()) + rest;
            break;
        case 'm':
            res += toString(ts.month()) + rest;
            break;
        case 'y':
            res += toString(ts.year()) + rest;
        }
    }
    return res;
}
Time::Time(int secs) : value(secs) {
}
Time::Time(int hour, int min, int sec) {
    value = hour * 3600 + min * 60 + sec;
}
int Time::hour() const {
    return value / 3600;
}
int Time::min() const {
    return (value / 60) % 60;
}
int Time::sec() const {
    return value % 60;
}
int Time::secs() const {
    return value;
}
Time& Time::setHour(int h) {
    value = h * 3600 + min() * 60 + sec();
    return *this;
}
Time& Time::setMin(int m) {
    value = hour() * 3600 + m * 60 + sec();
    return *this;
}
Time& Time::setSec(int s) {
    value = hour() * 3600 + min() * 60 + s;
    return *this;
}
Time& Time::setSecs(int secs) {
    value = secs;
    return *this;
}
string Time::asString(string format) const {
    if (format == "%u") {
        char buf[32];
        snprintf(buf, 32, "%d", value);
        return buf;
    }
    Split data(format, "%");
    string res = data[0];
    for (size_t i = 1; i < data.size(); i++) {
        string rest = data[i].substr(1, data[i].size());
        switch(data[i][0]) {
        case 'h':
            res += toString(hour()) + rest;
            break;
        case 'M':
            if (min() < 10)
                res += "0";
            res += toString(min()) + rest;
            break;
        case 's':
            if (sec() < 10)
                res += "0";
            res += toString(sec()) + rest;
        }
    }
    return res;
}
DateTime::DateTime(time_t t) {
    value =  (t==0) ? time(NULL) : t;
}
int DateTime::hour() const {
    return TimeStruct(value).hour();
}
int DateTime::min() const {
    return TimeStruct(value).min();
}
int DateTime::sec() const {
    return TimeStruct(value).sec();
}
time_t DateTime::timeStamp() const {
    return TimeStruct(value).timeStamp();
}
TimeStruct DateTime::timeStruct() const {
    return TimeStruct(value);
}
DateTime& DateTime::setDay(int d) {
    value = TimeStruct(value).setDay(d).timeStamp();
    return *this;
}
DateTime& DateTime::setMonth(int m) {
    value = TimeStruct(value).setMonth(m).timeStamp();
    return *this;
}
DateTime& DateTime::setYear(int y) {
    value = TimeStruct(value).setYear(y).timeStamp();
    return *this;
}
DateTime& DateTime::setHour(int h) {
    value = TimeStruct(value).setHour(h).timeStamp();
    return *this;
}
DateTime& DateTime::setMin(int m) {
    value = TimeStruct(value).setMin(m).timeStamp();
    return *this;
}
DateTime& DateTime::setSec(int s) {
    value = TimeStruct(value).setSec(s).timeStamp();
    return *this;
}
string DateTime::asString(string format) const {
    if (format == "%u") {
        char buf[32];
        snprintf(buf, 32, "%lu", value);
        return buf;
    }
    Split data(format, "%");
    TimeStruct ts(value);
    string res = data[0];
    for (size_t i = 1; i < data.size(); i++) {
        string rest = data[i].substr(1, data[i].size());
        switch(data[i][0]) {
        case 'd':
            res += toString(ts.day()) + rest;
            break;
        case 'm':
            res += toString(ts.month()) + rest;
            break;
        case 'y':
            res += toString(ts.year()) + rest;
            break;
        case 'h':
            res += toString(ts.hour()) + rest;
            break;
        case 'M':
            if (ts.min() < 10)
                res += "0";
            res += toString(ts.min()) + rest;
            break;
        case 's':
            if (ts.sec() < 10)
                res += "0";
            res += toString(ts.sec()) + rest;
            break;
        }
    }
    return res;
}
template <>
Date convert<const string&, Date>(const string& value) {
    return Date(atoi(value));
}
template <>
Time convert<const string&, Time>(const string& value) {
    return Time(atoi(value));
}
template <>
DateTime convert<const string&, DateTime>(const string& value) {
    return DateTime(atoi(value));
}
template <>
Date convert<int, Date>(int value) {
    return Date(value);
}
template <>
Time convert<int, Time>(int value) {
    return Time(value);
}
template <>
DateTime convert<int, DateTime>(int value) {
    return DateTime(value);
}

template <>
DateTime convert<long long, DateTime>(long long value) {
    return DateTime(value);
}

template <>
DateTime convert<time_t, DateTime>(time_t value) {
    return DateTime(value);
}

template <>
std::string convert<const Date&, std::string>(const Date& value) {
    return toString(value.timeStamp());
}
template <>
std::string convert<const Time&, std::string>(const Time& value) {
    return toString(value.secs());
}
template <>
std::string convert<const DateTime&, std::string>(const DateTime& value) {
    return toString(value.timeStamp());
}

ostream& operator << (ostream& os, const Date& d) {
    return os << d.asString();
}
ostream& operator << (ostream& os, const Time& d) {
    return os << d.asString();
}
ostream& operator << (ostream& os, const DateTime& d) {
    return os << d.asString();
}
}
<commit_msg>Have convert<> work for int16/32/64, instead of ambigous types<commit_after>/* LiteSQL - Date and time classes
 *
 * The list of contributors at http://litesql.sf.net/
 *
 * See LICENSE for copyright information. */
#include "litesql/datetime.hpp"
#include "litesql/split.hpp"
#include "compatibility.hpp"
#include <time.h>
#include <cstdio>

using namespace std;

namespace litesql {

TimeStruct::TimeStruct(time_t t) {
    if (!t)
        t = time(NULL);
    localtime_r(&t, &mytm);
}
int TimeStruct::day() const {
    return mytm.tm_mday;
}
int TimeStruct::dayOfWeek() const {
    return mytm.tm_wday;
}
int TimeStruct::dayOfYear() const {
    return mytm.tm_yday;
}
int TimeStruct::month() const {
    return mytm.tm_mon + 1;
}
int TimeStruct::year() const {
    return mytm.tm_year + 1900;
}
int TimeStruct::hour() const {
    return mytm.tm_hour;
}
int TimeStruct::min() const {
    return mytm.tm_min;
}
int TimeStruct::sec() const {
    return mytm.tm_sec;
}
time_t TimeStruct::timeStamp() const {
    return mktime(const_cast<struct tm*>(&mytm));
}
TimeStruct&  TimeStruct::setDay(int day) {
    mytm.tm_mday = day;
    return *this;
}
TimeStruct& TimeStruct::setMonth(int month) {
    mytm.tm_mon = month - 1;
    return *this;
}
TimeStruct& TimeStruct::setYear(int year) {
    mytm.tm_year = year - 1900;
    return *this;
}
TimeStruct& TimeStruct::setHour(int hour) {
    mytm.tm_hour = hour;
    return *this;
}
TimeStruct& TimeStruct::setMin(int min) {
    mytm.tm_min = min;
    return *this;
}
TimeStruct& TimeStruct::setSec(int sec) {
    mytm.tm_sec = sec;
    return *this;
}
TimeStruct& TimeStruct::setTimeStamp(time_t t) {
    localtime_r(&t, &mytm);
    return *this;
}

Date::Date(time_t t) : value(t) {
    if (value == 0)
        value = time(NULL);
}
Date::Date(int day, int month, int year) {
    value = TimeStruct().setDay(day).setMonth(month).setYear(year)
        .timeStamp();
}
int Date::day() const {
    return TimeStruct(value).day();
}
int Date::dayOfWeek() const {
    return TimeStruct(value).dayOfWeek();
}
int Date::month() const {
    return TimeStruct(value).month();
}
int Date::year() const {
    return TimeStruct(value).year();
}
time_t Date::timeStamp() const {
    return value;
}
TimeStruct Date::timeStruct() const {
    return TimeStruct(value);
}
Date& Date::setDay(int d) {
    value = TimeStruct(value).setDay(d).timeStamp();
    return *this;
}
Date& Date::setMonth(int m) {
    value = TimeStruct(value).setMonth(m).timeStamp();
    return *this;
}
Date& Date::setYear(int y) {
    value = TimeStruct(value).setYear(y).timeStamp();
    return *this;
}
Date& Date::setTimeStamp(time_t t) {
    value = t;
    return *this;
}
string Date::asString(string format) const {
    if (format == "%u") {
        char buf[32];
        snprintf(buf, 32, "%lu", value);
        return buf;
    }
    Split data(format, "%");
    TimeStruct ts(value);
    string res = data[0];
    for (size_t i = 1; i < data.size(); i++) {
        string rest = data[i].substr(1, data[i].size());
        switch(data[i][0]) {
        case 'd':
            res += toString(ts.day()) + rest;
            break;
        case 'm':
            res += toString(ts.month()) + rest;
            break;
        case 'y':
            res += toString(ts.year()) + rest;
        }
    }
    return res;
}
Time::Time(int secs) : value(secs) {
}
Time::Time(int hour, int min, int sec) {
    value = hour * 3600 + min * 60 + sec;
}
int Time::hour() const {
    return value / 3600;
}
int Time::min() const {
    return (value / 60) % 60;
}
int Time::sec() const {
    return value % 60;
}
int Time::secs() const {
    return value;
}
Time& Time::setHour(int h) {
    value = h * 3600 + min() * 60 + sec();
    return *this;
}
Time& Time::setMin(int m) {
    value = hour() * 3600 + m * 60 + sec();
    return *this;
}
Time& Time::setSec(int s) {
    value = hour() * 3600 + min() * 60 + s;
    return *this;
}
Time& Time::setSecs(int secs) {
    value = secs;
    return *this;
}
string Time::asString(string format) const {
    if (format == "%u") {
        char buf[32];
        snprintf(buf, 32, "%d", value);
        return buf;
    }
    Split data(format, "%");
    string res = data[0];
    for (size_t i = 1; i < data.size(); i++) {
        string rest = data[i].substr(1, data[i].size());
        switch(data[i][0]) {
        case 'h':
            res += toString(hour()) + rest;
            break;
        case 'M':
            if (min() < 10)
                res += "0";
            res += toString(min()) + rest;
            break;
        case 's':
            if (sec() < 10)
                res += "0";
            res += toString(sec()) + rest;
        }
    }
    return res;
}
DateTime::DateTime(time_t t) {
    value =  (t==0) ? time(NULL) : t;
}
int DateTime::hour() const {
    return TimeStruct(value).hour();
}
int DateTime::min() const {
    return TimeStruct(value).min();
}
int DateTime::sec() const {
    return TimeStruct(value).sec();
}
time_t DateTime::timeStamp() const {
    return TimeStruct(value).timeStamp();
}
TimeStruct DateTime::timeStruct() const {
    return TimeStruct(value);
}
DateTime& DateTime::setDay(int d) {
    value = TimeStruct(value).setDay(d).timeStamp();
    return *this;
}
DateTime& DateTime::setMonth(int m) {
    value = TimeStruct(value).setMonth(m).timeStamp();
    return *this;
}
DateTime& DateTime::setYear(int y) {
    value = TimeStruct(value).setYear(y).timeStamp();
    return *this;
}
DateTime& DateTime::setHour(int h) {
    value = TimeStruct(value).setHour(h).timeStamp();
    return *this;
}
DateTime& DateTime::setMin(int m) {
    value = TimeStruct(value).setMin(m).timeStamp();
    return *this;
}
DateTime& DateTime::setSec(int s) {
    value = TimeStruct(value).setSec(s).timeStamp();
    return *this;
}
string DateTime::asString(string format) const {
    if (format == "%u") {
        char buf[32];
        snprintf(buf, 32, "%lu", value);
        return buf;
    }
    Split data(format, "%");
    TimeStruct ts(value);
    string res = data[0];
    for (size_t i = 1; i < data.size(); i++) {
        string rest = data[i].substr(1, data[i].size());
        switch(data[i][0]) {
        case 'd':
            res += toString(ts.day()) + rest;
            break;
        case 'm':
            res += toString(ts.month()) + rest;
            break;
        case 'y':
            res += toString(ts.year()) + rest;
            break;
        case 'h':
            res += toString(ts.hour()) + rest;
            break;
        case 'M':
            if (ts.min() < 10)
                res += "0";
            res += toString(ts.min()) + rest;
            break;
        case 's':
            if (ts.sec() < 10)
                res += "0";
            res += toString(ts.sec()) + rest;
            break;
        }
    }
    return res;
}
template <>
Date convert<const string&, Date>(const string& value) {
    return Date(atoi(value));
}
template <>
Time convert<const string&, Time>(const string& value) {
    return Time(atoi(value));
}
template <>
DateTime convert<const string&, DateTime>(const string& value) {
    return DateTime(atoi(value));
}
template <>
Date convert<int, Date>(int value) {
    return Date(value);
}
template <>
Time convert<int, Time>(int value) {
    return Time(value);
}
template <>
DateTime convert<int16_t, DateTime>(int16_t value) {
    return DateTime(value);
}

template <>
DateTime convert<int32_t, DateTime>(int32_t value) {
    return DateTime(value);
}

template <>
DateTime convert<int64_t, DateTime>(int64_t value) {
    return DateTime(value);
}

template <>
std::string convert<const Date&, std::string>(const Date& value) {
    return toString(value.timeStamp());
}
template <>
std::string convert<const Time&, std::string>(const Time& value) {
    return toString(value.secs());
}
template <>
std::string convert<const DateTime&, std::string>(const DateTime& value) {
    return toString(value.timeStamp());
}

ostream& operator << (ostream& os, const Date& d) {
    return os << d.asString();
}
ostream& operator << (ostream& os, const Time& d) {
    return os << d.asString();
}
ostream& operator << (ostream& os, const DateTime& d) {
    return os << d.asString();
}
}
<|endoftext|>


<commit_before>#include "client.h"
#include "tests/test.h"
#include "webrequester.h"
#include "measurement/ping/ping.h"
#include "connectiontester.h"
#include "network/requests/requests.h"
#include "scheduler/scheduler.h"
#include "scheduler/schedulermodel.h"
#include "report/reportscheduler.h"
#include "report/reportmodel.h"
#include "settings.h"

#include "qtquick2applicationviewer.h"

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <QUrl>

#ifdef Q_OS_ANDROID
#include "statusbarhelper.h"
#include "androidimageprovider.h"
#include "androidprocessmodel.h"
#else
#include <QApplication>
#include "desktopstatusbarhelper.h"
#endif // Q_OS_ANDROID

class Time : public QObject
{
    Q_OBJECT

public:
    Time(QObject* parent = 0) : QObject(parent) {
    }

    Q_INVOKABLE int restart() {
        return time.restart();
    }

    Q_INVOKABLE int elapsed() const {
        return time.elapsed();
    }

protected:
    QTime time;
};

int main(int argc, char* argv[])
{
    QCoreApplication::setOrganizationDomain("de.hsaugsburg.informatik");
    QCoreApplication::setOrganizationName("HS Augsburg");
    QCoreApplication::setApplicationName("mPlaneClient");

#ifdef Q_OS_ANDROID
    QGuiApplication app(argc, argv);
#else
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(true);
#endif

    qmlRegisterUncreatableType<AbstractTest>("mplane", 1, 0, "AbstractTest", "abstract class");
    qmlRegisterUncreatableType<Client>("mplane", 1, 0, "Client", "This is a singleton");

    qmlRegisterUncreatableType<Scheduler>("mplane", 1, 0, "Scheduler", "uncreatable type");
    qmlRegisterType<SchedulerModel>("mplane", 1, 0, "SchedulerModel");

    qmlRegisterUncreatableType<ReportScheduler>("mplane", 1, 0, "ReportScheduler", "uncreatable type");
    qmlRegisterType<ReportModel>("mplane", 1, 0, "ReportModel");

    // Common objects
    qmlRegisterType<TimingInformation>("mplane", 1, 0, "TimingInformation");

    // Requests
    qmlRegisterUncreatableType<Request>("mplane", 1, 0, "Request", "abstract class");
    qmlRegisterType<RegisterDeviceRequest>("mplane", 1, 0, "RegisterDeviceRequest");
    qmlRegisterType<ManualRequest>("mplane", 1, 0, "TestRequest");
    qmlRegisterType<UserRegisterRequest>("mplane", 1, 0, "UserRegisterRequest");
    qmlRegisterType<LoginRequest>("mplane", 1, 0, "LoginRequest");
    qmlRegisterType<GetConfigRequest>("mplane", 1, 0, "GetConfigRequest");

    // Responses
    qmlRegisterUncreatableType<Response>("mplane", 1, 0, "Response", "abstract class");
    qmlRegisterType<RegisterUserResponse>("mplane", 1, 0, "UserRegisterResponse");
    qmlRegisterType<LoginResponse>("mplane", 1, 0, "LoginResponse");
    qmlRegisterType<RegisterDeviceResponse>("mplane", 1, 0, "RegisterDeviceResponse");
    qmlRegisterType<GetConfigResponse>("mplane", 1, 0, "GetConfigResponse");

    qmlRegisterType<Settings>("mplane", 1, 0, "Settings");
    qmlRegisterType<WebRequester>("mplane", 1, 0, "WebRequester");
    qmlRegisterType<Ping>("mplane", 1, 0, "Ping");
    qmlRegisterType<ConnectionTester>("mplane", 1, 0, "ConnectionTester");
    qmlRegisterType<ConnectionTesterModel>("mplane", 1, 0, "ConnectionTesterModel");
    qmlRegisterType<Time>("mplane", 1, 0, "Time");

#ifdef Q_OS_ANDROID
    qmlRegisterType<AndroidProcessModel>("mplane", 1, 0, "ProcessModel");
#endif // Q_OS_ANDROID

    QtQuick2ApplicationViewer view;

    QQmlContext* rootContext = view.rootContext();
    rootContext->setContextProperty("client", Client::instance());
#ifdef Q_OS_ANDROID
    view.engine()->addImageProvider("android", new AndroidImageProvider);
    rootContext->setContextProperty("statusBar", new StatusBarHelper(&view));
#else
    rootContext->setContextProperty("statusBar", new DesktopStatusBarHelper(&view));
#endif // Q_OS_ANDROID

    view.setMainQmlFile(QStringLiteral("qml/main.qml"));
    view.showExpanded();

    int returnCode = app.exec();

    // Cleanly shutdown
    Client::instance()->deleteLater();
    QTimer::singleShot(1, &app, SLOT(quit()));
    app.exec();

    return returnCode;
}

#include "main.moc"
<commit_msg>Added QQmlFileSelector to be used.<commit_after>#include "client.h"
#include "tests/test.h"
#include "webrequester.h"
#include "measurement/ping/ping.h"
#include "connectiontester.h"
#include "network/requests/requests.h"
#include "scheduler/scheduler.h"
#include "scheduler/schedulermodel.h"
#include "report/reportscheduler.h"
#include "report/reportmodel.h"
#include "settings.h"

#include "qtquick2applicationviewer.h"

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <QUrl>

#ifdef Q_OS_ANDROID
#include "statusbarhelper.h"
#include "androidimageprovider.h"
#include "androidprocessmodel.h"
#else
#include <QApplication>
#include "desktopstatusbarhelper.h"
#endif // Q_OS_ANDROID

class Time : public QObject
{
    Q_OBJECT

public:
    Time(QObject* parent = 0) : QObject(parent) {
    }

    Q_INVOKABLE int restart() {
        return time.restart();
    }

    Q_INVOKABLE int elapsed() const {
        return time.elapsed();
    }

protected:
    QTime time;
};

int main(int argc, char* argv[])
{
    QCoreApplication::setOrganizationDomain("de.hsaugsburg.informatik");
    QCoreApplication::setOrganizationName("HS Augsburg");
    QCoreApplication::setApplicationName("mPlaneClient");

#ifdef Q_OS_ANDROID
    QGuiApplication app(argc, argv);
#else
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(true);
#endif

    qmlRegisterUncreatableType<AbstractTest>("mplane", 1, 0, "AbstractTest", "abstract class");
    qmlRegisterUncreatableType<Client>("mplane", 1, 0, "Client", "This is a singleton");

    qmlRegisterUncreatableType<Scheduler>("mplane", 1, 0, "Scheduler", "uncreatable type");
    qmlRegisterType<SchedulerModel>("mplane", 1, 0, "SchedulerModel");

    qmlRegisterUncreatableType<ReportScheduler>("mplane", 1, 0, "ReportScheduler", "uncreatable type");
    qmlRegisterType<ReportModel>("mplane", 1, 0, "ReportModel");

    // Common objects
    qmlRegisterType<TimingInformation>("mplane", 1, 0, "TimingInformation");

    // Requests
    qmlRegisterUncreatableType<Request>("mplane", 1, 0, "Request", "abstract class");
    qmlRegisterType<RegisterDeviceRequest>("mplane", 1, 0, "RegisterDeviceRequest");
    qmlRegisterType<ManualRequest>("mplane", 1, 0, "TestRequest");
    qmlRegisterType<UserRegisterRequest>("mplane", 1, 0, "UserRegisterRequest");
    qmlRegisterType<LoginRequest>("mplane", 1, 0, "LoginRequest");
    qmlRegisterType<GetConfigRequest>("mplane", 1, 0, "GetConfigRequest");

    // Responses
    qmlRegisterUncreatableType<Response>("mplane", 1, 0, "Response", "abstract class");
    qmlRegisterType<RegisterUserResponse>("mplane", 1, 0, "UserRegisterResponse");
    qmlRegisterType<LoginResponse>("mplane", 1, 0, "LoginResponse");
    qmlRegisterType<RegisterDeviceResponse>("mplane", 1, 0, "RegisterDeviceResponse");
    qmlRegisterType<GetConfigResponse>("mplane", 1, 0, "GetConfigResponse");

    qmlRegisterType<Settings>("mplane", 1, 0, "Settings");
    qmlRegisterType<WebRequester>("mplane", 1, 0, "WebRequester");
    qmlRegisterType<Ping>("mplane", 1, 0, "Ping");
    qmlRegisterType<ConnectionTester>("mplane", 1, 0, "ConnectionTester");
    qmlRegisterType<ConnectionTesterModel>("mplane", 1, 0, "ConnectionTesterModel");
    qmlRegisterType<Time>("mplane", 1, 0, "Time");

#ifdef Q_OS_ANDROID
    qmlRegisterType<AndroidProcessModel>("mplane", 1, 0, "ProcessModel");
#endif // Q_OS_ANDROID

    QtQuick2ApplicationViewer view;

    QQmlEngine* engine = view.engine();
    // Allow QFileSelector to be automatically applied on qml scripting
    QQmlFileSelector selector;
    engine->setUrlInterceptor(&selector);

    QQmlContext* rootContext = view.rootContext();
    rootContext->setContextProperty("client", Client::instance());
#ifdef Q_OS_ANDROID
    view.engine()->addImageProvider("android", new AndroidImageProvider);
    rootContext->setContextProperty("statusBar", new StatusBarHelper(&view));
#else
    rootContext->setContextProperty("statusBar", new DesktopStatusBarHelper(&view));
#endif // Q_OS_ANDROID

    view.setMainQmlFile(QStringLiteral("qml/main.qml"));
    view.showExpanded();

    int returnCode = app.exec();

    // Cleanly shutdown
    Client::instance()->deleteLater();
    QTimer::singleShot(1, &app, SLOT(quit()));
    app.exec();

    return returnCode;
}

#include "main.moc"
<|endoftext|>


<commit_before>#ifndef FMO_ALGORITHM_HPP
#define FMO_ALGORITHM_HPP

#include <fmo/differentiator.hpp>
#include <fmo/image.hpp>
#include <fmo/pointset.hpp>
#include <functional>
#include <memory>
#include <string>

namespace fmo {
    /// Represents a detection algorithm. Specific algorithms are implemented in different
    /// compilation units as subclasses of this class, and then registered using the
    /// registerFactory() static method. To create a new instance of an algorithm, call the make()
    /// static method.
    struct Algorithm {
        Algorithm() = default;
        Algorithm(const Algorithm&) = delete;
        Algorithm& operator=(const Algorithm&) = delete;
        virtual ~Algorithm() {}
        struct Config;

        /// Type of a function that produces an Algorithm instance.
        using Factory = std::function<std::unique_ptr<Algorithm>(const Config&, Format, Dims)>;

        /// Configuration settings determining the properties of a new Algorithm instance. Pass the
        /// object into the make() static method.
        struct Config {
            // parameters pertinent to "median" algorithms

            /// Name of the algorithm.
            std::string name;
            /// Configuration regarding creation of difference images.
            Differentiator::Config diff;
            /// Strips that are close to each other will be considered as part of the same connected
            /// component. This value is relative to image height. Used only in "median" algorithms.
            float maxGapX;
            /// Strips will be ignored unless they are at a distance from other strips in the image.
            /// This value is relative to image height.
            float minGapY;
            /// Maximum image height for processing. The input image will be downscaled by a factor
            /// of 2 until its height is less or equal to the specified value.
            int maxImageHeight;
            /// Strips that have less than this number of pixels in the downscaled image will be
            /// ignored.
            int minStripHeight;
            /// Candidate objects that have less than this number of strips will be ignored. Used
            /// only in "median" algorithms.
            int minStripsInObject;
            /// Candidate objects will be discarded if the area of strips contained within is small.
            /// This value is relative to the area of the objects convex hull. Used only in "median"
            /// algorithms.
            float minStripArea;
            /// Candidate objects will be discarded if their shape is too round. The aspect ratio
            /// must be greater than the specified value. Used only in "median" algorithms.
            float minAspect;
            /// Objects cannot be matched if the ratio of their aspect ratios exceeds this value.
            float matchAspectMax;
            /// Objects cannot be matched if the ratio of their areas exceeds this value.
            float matchAreaMax;
            /// Objects cannot be matched if their distance (weighted by their average length)
            /// exceeds this value.
            float matchDistanceMax;
            /// Objects cannot be matched if they do not lie on a line. The sine of the greater
            /// angle must not exceed this value.
            float matchAngleMax;
            /// The weight of aspect ratio comparison when matching objects.
            float matchAspectWeight;
            /// The weight of area comparison when matching objects.
            float matchAreaWeight;
            /// The weight of mutual distance when matching objects.
            float matchDistanceWeight;
            /// The weight of mutual angle when matching objects.
            float matchAngleWeight;
            /// Candidate object will be discarded if the location of its centerpoint is too far
            /// from the expected location. This value is relative to object length.
            float selectMaxError;

            // legacy parameters

            /// Connected components that have less than this number of strips will be ignored.
            int minStripsInComponent;
            /// Clusters of connected components that have less than this number of strips will be
            /// ignored.
            int minStripsInCluster;
            /// Minimum length of a cluster relative to its height.
            float minClusterLength;
            /// When forming clusters from connected components, this value determines the
            /// importance of strip height ratio while considering to merge to clusters.
            float heightRatioWeight;
            /// When forming clusters from connected components, this value determines the
            /// importance of mutual distance while considering to merge two clusters.
            float distanceWeight;
            /// When forming clusters from connected components, this value determines the
            /// importance of minimizing gaps while considering to merge two clusters.
            float gapsWeight;
            /// Maximum ratio of strip heights allowed when merging strips from consecutive frames.
            float maxHeightRatioStrips;
            /// This value is compared to the 0.8-quantile divided by the 0.2 quantile of strip
            /// heights in a single connected component. If the fraction exceeds this value, the
            /// component is deemed inconsistent with the constant-height assumption and is
            /// discarded.
            float maxHeightRatioInternal;
            /// When forming clusters from connected components, this is the maximum acceptable
            /// fraction of approximate strip heights. If the approximate strip heights of the two
            /// components being joined differ more than specified by this value, the components
            /// cannot be joined together.
            float maxHeightRatioExternal;
            /// When forming clusters from connected components, this is the maximum acceptable
            /// distance between the component endpoints. This value is relative to approximate
            /// strip height of the smallest component in the clusters being merged.
            float maxDistance;
            /// The maximum fraction of a cluster length that may be covered by gaps between
            /// components.
            float maxGapsLength;
            /// Minimum distance that an object must travel in a single frame. This value is
            /// relative to the length of the path travelled in three frames.
            float minMotion;
            /// Maximum distance that an object may travel in a single frame. This value is relative
            /// to the length of the path travelled in three frames.
            float maxMotion;
            /// When outputting object point set, specifies what resolution should be used. When
            /// using source resolution, additional heavy-weight calculations need to be performed.
            bool pointSetSourceResolution;

            /// Creates a new config instance with default settings.
            Config();
        };

        /// A structure that contains all relevant information about a detected object. The caller
        /// is expected to cache this object and use it with the getObjectDetails() method. The
        /// object contains auxiliary images that may be used by the getObjectDetails() method in
        /// the process of generating object information.
        struct ObjectDetails {
            Bounds bounds1;  ///< bounding box enclosing object locations in T and T-1
            Bounds bounds2;  ///< bounding box enclosing object locations in T-1 and T-2
            PointSet points; ///< point locations
            Image temp1;     ///< object for storing auxiliary image data
            Image temp2;     ///< object for storing auxiliary image data
            Image temp3;     ///< object for storing auxiliary image data
        };

        /// Creates a new instance of an Algorithm. The field config.name is used to determine which
        /// algorithm factory will be used. The factory must have been previously added with the
        /// registerFactory() static method.
        static std::unique_ptr<Algorithm> make(const Config& config, Format format, Dims dims);

        /// Registers an algorithm factory so that it is available via a call to make(). The
        /// provided name will be used as the search key and must be unique.
        static void registerFactory(const std::string& name, const Factory& factory);

        /// Provides the list of currently available factory names, previously added using
        /// registerFactory().
        static std::vector<std::string> listFactories();

        /// To be called every frame, providing the next image for processing. The processing will
        /// take place during the call and might take a long time. The input is received by swapping
        /// the contents of the provided input image with an internal buffer.
        virtual void setInputSwap(Image& input) = 0;

        /// Visualizes the result of detection, returning an image that is useful for debugging
        /// algorithm behavior. The returned image will have BGR format and the same dimensions as
        /// the input image.
        virtual const Image& getDebugImage() = 0;

        /// Determines whether a new object has been found as a result of analyzing the last frame
        /// during a call to setInputSwap(). When this method returns true, the methods
        /// getObjectBounds() and getObjectDetails() may be called to get more information about the
        /// detected object.
        virtual bool haveObject() const = 0;

        /// Provides the bounding box that encloses the detected object. Use the haveObject() method
        /// first to check if an object has been detected in this frame.
        virtual Bounds getObjectBounds() const = 0;

        /// Provides detailed information about the detected object, including a list of object
        /// pixels. Use the haveObject() method first to check if an object has been detected in
        /// this frame.
        virtual void getObjectDetails(ObjectDetails& details) const = 0;
    };
}

#endif // FMO_ALGORITHM_HPP
<commit_msg>Add a new output interface<commit_after>#ifndef FMO_ALGORITHM_HPP
#define FMO_ALGORITHM_HPP

#include <fmo/differentiator.hpp>
#include <fmo/image.hpp>
#include <fmo/pointset.hpp>
#include <functional>
#include <memory>
#include <string>

namespace fmo {
    /// Represents a detection algorithm. Specific algorithms are implemented in different
    /// compilation units as subclasses of this class, and then registered using the
    /// registerFactory() static method. To create a new instance of an algorithm, call the make()
    /// static method.
    struct Algorithm {
        Algorithm() = default;
        Algorithm(const Algorithm&) = delete;
        Algorithm& operator=(const Algorithm&) = delete;
        virtual ~Algorithm() {}
        struct Config;
        struct Detection;

        /// Type of a function that produces an Algorithm instance.
        using Factory = std::function<std::unique_ptr<Algorithm>(const Config&, Format, Dims)>;

        /// Type of result produced by an algorithm instance.
        using Output = std::vector<std::unique_ptr<Detection>>;

        /// Configuration settings determining the properties of a new Algorithm instance. Pass the
        /// object into the make() static method.
        struct Config {
            // parameters pertinent to "median" algorithms

            /// Name of the algorithm.
            std::string name;
            /// Configuration regarding creation of difference images.
            Differentiator::Config diff;
            /// Strips that are close to each other will be considered as part of the same connected
            /// component. This value is relative to image height. Used only in "median" algorithms.
            float maxGapX;
            /// Strips will be ignored unless they are at a distance from other strips in the image.
            /// This value is relative to image height.
            float minGapY;
            /// Maximum image height for processing. The input image will be downscaled by a factor
            /// of 2 until its height is less or equal to the specified value.
            int maxImageHeight;
            /// Strips that have less than this number of pixels in the downscaled image will be
            /// ignored.
            int minStripHeight;
            /// Candidate objects that have less than this number of strips will be ignored. Used
            /// only in "median" algorithms.
            int minStripsInObject;
            /// Candidate objects will be discarded if the area of strips contained within is small.
            /// This value is relative to the area of the objects convex hull. Used only in "median"
            /// algorithms.
            float minStripArea;
            /// Candidate objects will be discarded if their shape is too round. The aspect ratio
            /// must be greater than the specified value. Used only in "median" algorithms.
            float minAspect;
            /// Objects cannot be matched if the ratio of their aspect ratios exceeds this value.
            float matchAspectMax;
            /// Objects cannot be matched if the ratio of their areas exceeds this value.
            float matchAreaMax;
            /// Objects cannot be matched if their distance (weighted by their average length)
            /// exceeds this value.
            float matchDistanceMax;
            /// Objects cannot be matched if they do not lie on a line. The sine of the greater
            /// angle must not exceed this value.
            float matchAngleMax;
            /// The weight of aspect ratio comparison when matching objects.
            float matchAspectWeight;
            /// The weight of area comparison when matching objects.
            float matchAreaWeight;
            /// The weight of mutual distance when matching objects.
            float matchDistanceWeight;
            /// The weight of mutual angle when matching objects.
            float matchAngleWeight;
            /// Candidate object will be discarded if the location of its centerpoint is too far
            /// from the expected location. This value is relative to object length.
            float selectMaxError;

            // legacy parameters

            /// Connected components that have less than this number of strips will be ignored.
            int minStripsInComponent;
            /// Clusters of connected components that have less than this number of strips will be
            /// ignored.
            int minStripsInCluster;
            /// Minimum length of a cluster relative to its height.
            float minClusterLength;
            /// When forming clusters from connected components, this value determines the
            /// importance of strip height ratio while considering to merge to clusters.
            float heightRatioWeight;
            /// When forming clusters from connected components, this value determines the
            /// importance of mutual distance while considering to merge two clusters.
            float distanceWeight;
            /// When forming clusters from connected components, this value determines the
            /// importance of minimizing gaps while considering to merge two clusters.
            float gapsWeight;
            /// Maximum ratio of strip heights allowed when merging strips from consecutive frames.
            float maxHeightRatioStrips;
            /// This value is compared to the 0.8-quantile divided by the 0.2 quantile of strip
            /// heights in a single connected component. If the fraction exceeds this value, the
            /// component is deemed inconsistent with the constant-height assumption and is
            /// discarded.
            float maxHeightRatioInternal;
            /// When forming clusters from connected components, this is the maximum acceptable
            /// fraction of approximate strip heights. If the approximate strip heights of the two
            /// components being joined differ more than specified by this value, the components
            /// cannot be joined together.
            float maxHeightRatioExternal;
            /// When forming clusters from connected components, this is the maximum acceptable
            /// distance between the component endpoints. This value is relative to approximate
            /// strip height of the smallest component in the clusters being merged.
            float maxDistance;
            /// The maximum fraction of a cluster length that may be covered by gaps between
            /// components.
            float maxGapsLength;
            /// Minimum distance that an object must travel in a single frame. This value is
            /// relative to the length of the path travelled in three frames.
            float minMotion;
            /// Maximum distance that an object may travel in a single frame. This value is relative
            /// to the length of the path travelled in three frames.
            float maxMotion;
            /// When outputting object point set, specifies what resolution should be used. When
            /// using source resolution, additional heavy-weight calculations need to be performed.
            bool pointSetSourceResolution;

            /// Creates a new config instance with default settings.
            Config();
        };

        /// A structure that contains all relevant information about a detected object. The caller
        /// is expected to cache this object and use it with the getObjectDetails() method. The
        /// object contains auxiliary images that may be used by the getObjectDetails() method in
        /// the process of generating object information.
        struct ObjectDetails {
            Bounds bounds1;  ///< bounding box enclosing object locations in T and T-1
            Bounds bounds2;  ///< bounding box enclosing object locations in T-1 and T-2
            PointSet points; ///< point locations
            Image temp1;     ///< object for storing auxiliary image data
            Image temp2;     ///< object for storing auxiliary image data
            Image temp3;     ///< object for storing auxiliary image data
        };

        /// A structure that contains all relevant information about a detected object. The user of
        /// the algorithm receives subclasses of this structure using the getOutput() method.
        /// Instances of this class are invalidated by the next call to setInputSwap().
        struct Detection {
            virtual ~Detection() = default;

            /// Constructor variant with the previous center available.
            Detection(Pos center, Pos prevCenter, float radius)
                : mCenter(center), mPrevCenter(prevCenter), mRadius(radius) {}

            /// Constructor variant with the previous center unavailable.
            Detection(Pos center, float radius)
                : mCenter(center), mPrevCenter{-1, -1}, mRadius(radius) {}

            /// Midpoint of the object in the current frame.
            Pos getCenter() const { return mCenter; }

            /// Midpoint of the object in the previous frame. The value might not be available; use
            /// havePrevCenter() to check.
            Pos getPrevCenter() const { return mPrevCenter; }

            /// Checks whether getPrevCenter() may be called.
            bool havePrevCenter() const { return mPrevCenter.x >= 0; }

            /// Apparent radius of the object in pixels.
            float getRadius() const { return mRadius; }

            /// Generates coordinates of object pixels and sorts them according to pointSetCompLt().
            virtual void getPoints(PointSet& out) const = 0;

        private:
            Pos mCenter;
            Pos mPrevCenter;
            float mRadius;
        };

        /// Creates a new instance of an Algorithm. The field config.name is used to determine which
        /// algorithm factory will be used. The factory must have been previously added with the
        /// registerFactory() static method.
        static std::unique_ptr<Algorithm> make(const Config& config, Format format, Dims dims);

        /// Registers an algorithm factory so that it is available via a call to make(). The
        /// provided name will be used as the search key and must be unique.
        static void registerFactory(const std::string& name, const Factory& factory);

        /// Provides the list of currently available factory names, previously added using
        /// registerFactory().
        static std::vector<std::string> listFactories();

        /// To be called every frame, providing the next image for processing. The processing will
        /// take place during the call and might take a long time. The input is received by swapping
        /// the contents of the provided input image with an internal buffer.
        virtual void setInputSwap(Image& input) = 0;

        /// To be called every frame, obtaining a list of fast-moving objects that have been
        /// detected this frame. The returned objects (i.e. instances of class Detection) may be
        /// used only before the next call to setInputSwap().
        virtual void getOutput(Output& output) { output.clear(); }

        /// Visualizes the result of detection, returning an image that is useful for debugging
        /// algorithm behavior. The returned image will have BGR format and the same dimensions as
        /// the input image.
        virtual const Image& getDebugImage() = 0;

        /// Determines whether a new object has been found as a result of analyzing the last frame
        /// during a call to setInputSwap(). When this method returns true, the methods
        /// getObjectBounds() and getObjectDetails() may be called to get more information about the
        /// detected object.
        virtual bool haveObject() const = 0;

        /// Provides the bounding box that encloses the detected object. Use the haveObject() method
        /// first to check if an object has been detected in this frame.
        virtual Bounds getObjectBounds() const = 0;

        /// Provides detailed information about the detected object, including a list of object
        /// pixels. Use the haveObject() method first to check if an object has been detected in
        /// this frame.
        virtual void getObjectDetails(ObjectDetails& details) const = 0;
    };
}

#endif // FMO_ALGORITHM_HPP
<|endoftext|>


<commit_before>/** \file kernel_atomic.hpp \brief Atomic (simple) kernel functions */
/*
-------------------------------------------------------------------------
   This file is part of BayesOpt, an efficient C++ library for
   Bayesian optimization.

   Copyright (C) 2011-2013 Ruben Martinez-Cantin <rmcantin@unizar.es>

   BayesOpt is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   BayesOpt 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
*/

#ifndef  _KERNEL_ATOMIC_HPP_
#define  _KERNEL_ATOMIC_HPP_

#include <valarray>
#include "kernel_functors.hpp"
#include "elementwise_ublas.hpp"

namespace bayesopt
{

  /**\addtogroup KernelFunctions */
  //@{

  /** \brief Abstract class for an atomic kernel */
  class AtomicKernel : public Kernel
  {
  public:
    virtual void init(size_t input_dim)
    { n_inputs = input_dim; };

    void setHyperParameters(const vectord &theta)
    {
      if(theta.size() != n_params)
	{
	  FILE_LOG(logERROR) << "Wrong number of kernel hyperparameters";
	  throw std::invalid_argument("Wrong number of kernel hyperparameters");
	}
      params = theta; //TODO: To make enough space. Make it more efficient.
      std::transform(theta.begin(), theta.end(), params.begin(), (double (*)(double)) exp);
      //      params = exp(theta);
    };

    vectord getHyperParameters()
    {
      vectord theta(params.size());
      std::transform(params.begin(), params.end(), theta.begin(), (double (*)(double)) log);
      return theta;
      //  return log(params);
    };
    size_t nHyperParameters() {return n_params;};

    virtual ~AtomicKernel(){};

  protected:
    size_t n_params;
    vectord params;
  };

  //////////////////////////////////////////////////////////////////////////
  /** \brief Constant kernel.
   * Combined with sum and product kernel can be used to scale a kernel
   * or add noise.
   */

  class ConstKernel: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    { return params(0); };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { return 0.0; };
  };

  /** \brief Linear kernel. */
  class LinKernel: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 0;  n_inputs = input_dim; };

    double operator()(const vectord &x1, const vectord &x2)
    {
      assert(x1.size() == x2.size());
      return boost::numeric::ublas::inner_prod(x1,x2);
    };

    // TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false);  return 0.0;   };
  };

  /** \brief Linear kernel. */
  class LinKernelARD: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    {
      assert(x1.size() == x2.size());
      vectord v1 = utils::ublas_elementwise_div(x1, params);
      vectord v2 = utils::ublas_elementwise_div(x2, params);
      return boost::numeric::ublas::inner_prod(v1,v2);
    };

    // TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false); return 0.0;  };
  };

  /** Kernel for categorical data. It measures the hamming distance
   *  between vectors.
   */
  class HammingKernel: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    size_t hammingDistance(const vectori& s1, const vectori& s2)
    {
      size_t hdist = 0;
      vectori::const_iterator i1;
      vectori::const_iterator i2;
      for( i1 = s1.begin(), i2 = s2.begin();
	   i1 < s1.end() && i2 < s2.end();
	   ++i1, ++i2 )
	{
	  hdist += (*i1 == *i2) ? 0 : 1;
	}
      return hdist;
    }

    double operator()(const vectord &x1, const vectord &x2)
    {
      const size_t n = x1.size();
      const double coef = -params(0)/2.0;
      vectori s1(n);
      vectori s2(n);

      for(size_t i=0; i<n; ++i)
	{
	  // We add 0.5 to avoid floating point approximation errors
	  s1(i) = static_cast<int>(x1(i)+0.5);
	  s2(i) = static_cast<int>(x2(i)+0.5);
	}

      const double dist = static_cast<double>(hammingDistance(s1,s2));
      return std::exp(coef*dist*dist);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { return 0.0; };
  };

  ///////////////////////////////////////////////////////////////////////////
  /** \brief Abstract class for isotropic kernel functors */
  class ISOkernel : public AtomicKernel
  {
  public:
    virtual ~ISOkernel(){};

  protected:
    inline double computeWeightedNorm2(const vectord &x1, const vectord &x2)
    {
      assert(n_inputs == x1.size());
      assert(x1.size() == x2.size());
      return norm_2(x1-x2)/params(0);
    };
  };

  /** \brief Abstract class for anisotropic kernel functors.
   * Typically ARD (Automatic Relevance Determination)
   */
  class ARDkernel : public AtomicKernel
  {
  public:
    virtual ~ARDkernel(){};

  protected:
    inline double computeWeightedNorm2(const vectord &x1, const vectord &x2)
    {
      assert(n_inputs == x1.size());
      assert(x1.size() == x2.size());
      assert(x1.size() == params.size());

      vectord xd = x1-x2;
      vectord r = utils::ublas_elementwise_div(xd, params);
      return norm_2(r);
    };
  };

  /** \brief Matern isotropic kernel of 1st order */
  class MaternIso1: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1;  n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    {
      double r = computeWeightedNorm2(x1,x2);
      return exp(-r);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    {
      double r = computeWeightedNorm2(x1,x2);
      return r*exp(-r);
    };
  };

  /** \brief Matern ARD kernel of 1st order */
  class MaternARD1: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim; n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    {
      double r = computeWeightedNorm2(x1,x2);
      return exp(-r);
    };

    //TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false);  return 0.0;  };
  };

  /** \brief Matern kernel of 3rd order */
  class MaternIso3: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(3.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r)*er;
    };

    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    {
      double r = sqrt(3.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return r*r*er;
    };
  };

  /** \brief Matern ARD kernel of 3rd order */
  class MaternARD3: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(3.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r)*er;
    };

    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    {
      assert(false); return 0.0;
    };
  };

  /** \brief Matern isotropic kernel of 5th order */
  class MaternIso5: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(5.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r*(1+r/3))*er;
    };
    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    {
      double r = sqrt(5.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return r*(1+r)/3*r*er;
    };
  };

  /** \brief Matern ARD kernel of 5th order */
  class MaternARD5: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(5.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r*(1+r/3))*er;
    };

    //TODO:
    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    { assert(false); return 0.0; };
  };

  /** Polynomial covariance function*/
  class Polynomial: public AtomicKernel
  {
  public:
    Polynomial(){ mExp = 1; };

    void init(size_t input_dim)
    { n_params = 2;  n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double xx = boost::numeric::ublas::inner_prod(x1,x2);
      return params(0)*params(0) * pow((params(1)+xx),mExp);
    };

    //TODO:
    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    { assert(false); return 0.0; };
  protected:
    size_t mExp;
  };

  class Polynomial2: public Polynomial { public: Polynomial2(){ mExp = 2;};};
  class Polynomial3: public Polynomial { public: Polynomial3(){ mExp = 3;};};
  class Polynomial4: public Polynomial { public: Polynomial4(){ mExp = 4;};};
  class Polynomial5: public Polynomial { public: Polynomial5(){ mExp = 5;};};
  class Polynomial6: public Polynomial { public: Polynomial6(){ mExp = 6;};};
  class Polynomial7: public Polynomial { public: Polynomial7(){ mExp = 7;};};

  /** \brief Square exponential (Gaussian) kernel. Isotropic version. */
  class SEIso: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      return exp(-k/2);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      return exp(-k/2)*k;
    };
  };

  /** \brief Square exponential (Gaussian) kernel. ARD version. */
  class SEArd: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2 )
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      return exp(-k/2);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      double r = (x1(component) - x2(component))/params(component);
      return exp(-k/2)*r*r;
    };
  };

  /** \brief Rational quadratic (Student's t) kernel. Isotropic version. */
  class RQIso: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 2; n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl/(2*params(1));
      return pow(1+k,-params(1));
    };

    // TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false); return 0.0;  };
  };

  //@}

} //namespace bayesopt

#endif
<commit_msg>Solving issue in MSVC 2010<commit_after>/** \file kernel_atomic.hpp \brief Atomic (simple) kernel functions */
/*
-------------------------------------------------------------------------
   This file is part of BayesOpt, an efficient C++ library for
   Bayesian optimization.

   Copyright (C) 2011-2013 Ruben Martinez-Cantin <rmcantin@unizar.es>

   BayesOpt is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   BayesOpt 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
*/

#ifndef  _KERNEL_ATOMIC_HPP_
#define  _KERNEL_ATOMIC_HPP_

#include <valarray>
#include "kernel_functors.hpp"
#include "elementwise_ublas.hpp"

namespace bayesopt
{

  /**\addtogroup KernelFunctions */
  //@{

  /** \brief Abstract class for an atomic kernel */
  class AtomicKernel : public Kernel
  {
  public:
    virtual void init(size_t input_dim)
    { n_inputs = input_dim; };

    void setHyperParameters(const vectord &theta)
    {
      if(theta.size() != n_params)
	{
	  FILE_LOG(logERROR) << "Wrong number of kernel hyperparameters";
	  throw std::invalid_argument("Wrong number of kernel hyperparameters");
	}
      params = theta; //TODO: To make enough space. Make it more efficient.
      std::transform(theta.begin(), theta.end(), params.begin(), (double (*)(double)) exp);
      //      params = exp(theta);
    };

    vectord getHyperParameters()
    {
      vectord theta(params.size());
      std::transform(params.begin(), params.end(), theta.begin(), (double (*)(double)) log);
      return theta;
      //  return log(params);
    };
    size_t nHyperParameters() {return n_params;};

    virtual ~AtomicKernel(){};

  protected:
    size_t n_params;
    vectord params;
  };

  //////////////////////////////////////////////////////////////////////////
  /** \brief Constant kernel.
   * Combined with sum and product kernel can be used to scale a kernel
   * or add noise.
   */

  class ConstKernel: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    { return params(0); };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { return 0.0; };
  };

  /** \brief Linear kernel. */
  class LinKernel: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 0;  n_inputs = input_dim; };

    double operator()(const vectord &x1, const vectord &x2)
    {
      assert(x1.size() == x2.size());
      return boost::numeric::ublas::inner_prod(x1,x2);
    };

    // TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false);  return 0.0;   };
  };

  /** \brief Linear kernel. */
  class LinKernelARD: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    {
      assert(x1.size() == x2.size());
      vectord v1 = utils::ublas_elementwise_div(x1, params);
      vectord v2 = utils::ublas_elementwise_div(x2, params);
      return boost::numeric::ublas::inner_prod(v1,v2);
    };

    // TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false); return 0.0;  };
  };

  /** Kernel for categorical data. It measures the hamming distance
   *  between vectors.
   */
  class HammingKernel: public AtomicKernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    size_t hammingDistance(const vectori& s1, const vectori& s2)
    {
      size_t hdist = 0;
      vectori::const_iterator i1;
      vectori::const_iterator i2;
      for( i1 = s1.begin(), i2 = s2.begin();
	   i1 < s1.end() && i2 < s2.end();
	   ++i1, ++i2 )
	{
	  hdist += (*i1 == *i2) ? 0 : 1;
	}
      return hdist;
    }

    double operator()(const vectord &x1, const vectord &x2)
    {
      const size_t n = x1.size();
      const double coef = -params(0)/2.0;
      vectori s1(n);
      vectori s2(n);

      for(size_t i=0; i<n; ++i)
	{
	  // We add 0.5 to avoid floating point approximation errors
	  s1(i) = static_cast<int>(x1(i)+0.5);
	  s2(i) = static_cast<int>(x2(i)+0.5);
	}

      const double dist = static_cast<double>(hammingDistance(s1,s2));
      return std::exp(coef*dist*dist);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { return 0.0; };
  };

  ///////////////////////////////////////////////////////////////////////////
  /** \brief Abstract class for isotropic kernel functors */
  class ISOkernel : public AtomicKernel
  {
  public:
    virtual ~ISOkernel(){};

  protected:
    inline double computeWeightedNorm2(const vectord &x1, const vectord &x2)
    {
      assert(n_inputs == x1.size());
      assert(x1.size() == x2.size());
      return norm_2(x1-x2)/params(0);
    };
  };

  /** \brief Abstract class for anisotropic kernel functors.
   * Typically ARD (Automatic Relevance Determination)
   */
  class ARDkernel : public AtomicKernel
  {
  public:
    virtual ~ARDkernel(){};

  protected:
    inline double computeWeightedNorm2(const vectord &x1, const vectord &x2)
    {
      assert(n_inputs == x1.size());
      assert(x1.size() == x2.size());
      assert(x1.size() == params.size());

      vectord xd = x1-x2;
      vectord r = utils::ublas_elementwise_div(xd, params);
      return norm_2(r);
    };
  };

  /** \brief Matern isotropic kernel of 1st order */
  class MaternIso1: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1;  n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    {
      double r = computeWeightedNorm2(x1,x2);
      return exp(-r);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    {
      double r = computeWeightedNorm2(x1,x2);
      return r*exp(-r);
    };
  };

  /** \brief Matern ARD kernel of 1st order */
  class MaternARD1: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim; n_inputs = input_dim;  };

    double operator()(const vectord &x1, const vectord &x2)
    {
      double r = computeWeightedNorm2(x1,x2);
      return exp(-r);
    };

    //TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false);  return 0.0;  };
  };

  /** \brief Matern kernel of 3rd order */
  class MaternIso3: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(3.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r)*er;
    };

    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    {
      double r = sqrt(3.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return r*r*er;
    };
  };

  /** \brief Matern ARD kernel of 3rd order */
  class MaternARD3: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(3.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r)*er;
    };

    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    {
      assert(false); return 0.0;
    };
  };

  /** \brief Matern isotropic kernel of 5th order */
  class MaternIso5: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(5.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r*(1+r/3))*er;
    };
    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    {
      double r = sqrt(5.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return r*(1+r)/3*r*er;
    };
  };

  /** \brief Matern ARD kernel of 5th order */
  class MaternARD5: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double r = sqrt(5.0) * computeWeightedNorm2(x1,x2);
      double er = exp(-r);
      return (1+r*(1+r/3))*er;
    };

    //TODO:
    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    { assert(false); return 0.0; };
  };

  /** Polynomial covariance function*/
  class Polynomial: public AtomicKernel
  {
  public:
    Polynomial(){ mExp = 1; };

    void init(size_t input_dim)
    { n_params = 2;  n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double xx = boost::numeric::ublas::inner_prod(x1,x2);
      return params(0)*params(0) * std::pow((params(1)+xx),static_cast<int>(mExp));
    };

    //TODO:
    double gradient( const vectord &x1, const vectord &x2,
		     size_t component)
    { assert(false); return 0.0; };
  protected:
    size_t mExp;
  };

  class Polynomial2: public Polynomial { public: Polynomial2(){ mExp = 2;};};
  class Polynomial3: public Polynomial { public: Polynomial3(){ mExp = 3;};};
  class Polynomial4: public Polynomial { public: Polynomial4(){ mExp = 4;};};
  class Polynomial5: public Polynomial { public: Polynomial5(){ mExp = 5;};};
  class Polynomial6: public Polynomial { public: Polynomial6(){ mExp = 6;};};
  class Polynomial7: public Polynomial { public: Polynomial7(){ mExp = 7;};};

  /** \brief Square exponential (Gaussian) kernel. Isotropic version. */
  class SEIso: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 1; n_inputs = input_dim;  };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      return exp(-k/2);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      return exp(-k/2)*k;
    };
  };

  /** \brief Square exponential (Gaussian) kernel. ARD version. */
  class SEArd: public ARDkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = input_dim;  n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2 )
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      return exp(-k/2);
    };

    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl;
      double r = (x1(component) - x2(component))/params(component);
      return exp(-k/2)*r*r;
    };
  };

  /** \brief Rational quadratic (Student's t) kernel. Isotropic version. */
  class RQIso: public ISOkernel
  {
  public:
    void init(size_t input_dim)
    { n_params = 2; n_inputs = input_dim; };

    double operator()( const vectord &x1, const vectord &x2)
    {
      double rl = computeWeightedNorm2(x1,x2);
      double k = rl*rl/(2*params(1));
      return std::pow(1+k,-params(1));
    };

    // TODO:
    double gradient(const vectord &x1, const vectord &x2,
		    size_t component)
    { assert(false); return 0.0;  };
  };

  //@}

} //namespace bayesopt

#endif
<|endoftext|>


<commit_before>/*
===============================================================================

  FILE:  laszip.hpp

  CONTENTS:

    Contains LASitem and LASchunk structs as well as the IDs of the currently
    supported entropy coding scheme

  PROGRAMMERS:

    martin.isenburg@gmail.com

  COPYRIGHT:

    (c) 2007-2011, Martin Isenburg, LASSO - tools to catch reality

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  CHANGE HISTORY:

    5 December 2011 -- learns the chunk table if it is missing (e.g. truncated LAZ)
    6 October 2011 -- large file support, ability to read with missing chunk table
    23 June 2011 -- turned on LASzip version 2.0 compressor with chunking
    8 May 2011 -- added an option for variable chunking via chunk()
    23 April 2011 -- changed interface for simplicity and chunking support
    20 March 2011 -- incrementing LASZIP_VERSION to 1.2 for improved compression
    10 January 2011 -- licensing change for LGPL release and liblas integration
    12 December 2010 -- refactored from lasdefinitions after movies with silke

===============================================================================
*/
#ifndef LASZIP_HPP
#define LASZIP_HPP

#if defined(_MSC_VER) && (_MSC_VER < 1300)
#define LZ_WIN32_VC6
typedef __int64   SIGNED_INT64;
#else
typedef long long SIGNED_INT64;
#endif

#if defined(_MSC_VER) && \
    (_MSC_FULL_VER >= 150000000)
#define LASCopyString _strdup
#else
#define LASCopyString strdup
#endif

#define LASZIP_VERSION_MAJOR    2
#define LASZIP_VERSION_MINOR    1
#define LASZIP_VERSION_REVISION 0

#define LASZIP_COMPRESSOR_NONE              0
#define LASZIP_COMPRESSOR_POINTWISE         1
#define LASZIP_COMPRESSOR_POINTWISE_CHUNKED 2
#define LASZIP_COMPRESSOR_TOTAL_NUMBER_OF   3

#define LASZIP_COMPRESSOR_CHUNKED LASZIP_COMPRESSOR_POINTWISE_CHUNKED
#define LASZIP_COMPRESSOR_NOT_CHUNKED LASZIP_COMPRESSOR_POINTWISE

#define LASZIP_COMPRESSOR_DEFAULT LASZIP_COMPRESSOR_CHUNKED

#define LASZIP_CODER_ARITHMETIC             0
#define LASZIP_CODER_TOTAL_NUMBER_OF        1

#define LASZIP_CHUNK_SIZE_DEFAULT           50000

#include "laszipexport.hpp"

class LASZIP_DLL LASitem
{
public:
  enum Type { BYTE = 0, SHORT, INT, LONG, FLOAT, DOUBLE, POINT10, GPSTIME11, RGB12, WAVEPACKET13, POINT14, RGBNIR14 } type;
  unsigned short size;
  unsigned short version;
  bool is_type(LASitem::Type t) const;
  const char* get_name() const;
};

class LASZIP_DLL LASzip
{
public:

  // supported version control
  bool check_compressor(const unsigned short compressor);
  bool check_coder(const unsigned short coder);
  bool check_item(const LASitem* item);
  bool check_items(const unsigned short num_items, const LASitem* items);
  bool check();

  // go back and forth between item array and point type & size
  bool setup(unsigned short* num_items, LASitem** items, const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_NONE);
  bool is_standard(const unsigned short num_items, const LASitem* items, unsigned char* point_type=0, unsigned short* record_length=0);
  bool is_standard(unsigned char* point_type=0, unsigned short* record_length=0);

  // pack to and unpack from VLR
  unsigned char* bytes;
  bool unpack(const unsigned char* bytes, const int num);
  bool pack(unsigned char*& bytes, int& num);

  // setup
  bool setup(const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_DEFAULT);
  bool setup(const unsigned short num_items, const LASitem* items, const unsigned short compressor);
  bool set_chunk_size(const unsigned int chunk_size);             /* for compressor only */
  bool request_version(const unsigned short requested_version);   /* for compressor only */

  // in case a function returns false this string describes the problem
  const char* get_error() const;

  // stored in LASzip VLR data section
  unsigned short compressor;
  unsigned short coder;
  unsigned char version_major;
  unsigned char version_minor;
  unsigned short version_revision;
  unsigned int options;
  unsigned int chunk_size;
  SIGNED_INT64 num_points;  /* not mandatory ... -1 if unknown */
  SIGNED_INT64 num_bytes;   /* not mandatory ... -1 if unknown */
  unsigned short num_items;
  LASitem* items;

  LASzip();
  ~LASzip();

private:
  bool return_error(const char* err);
  char* error_string;
};

#endif
<commit_msg>bug fix and update email and company name<commit_after>/*
===============================================================================

  FILE:  laszip.hpp

  CONTENTS:

    Contains LASitem and LASchunk structs as well as the IDs of the currently
    supported entropy coding scheme

  PROGRAMMERS:

    martin.isenburg@rapidlasso.com  -  http://rapidlasso.com

  COPYRIGHT:

    (c) 2007-2013, martin isenburg, rapidlasso - tools to catch reality

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  CHANGE HISTORY:

    29 July 2013 -- reorganized to create an easy-to-use LASzip DLL
    5 December 2011 -- learns the chunk table if it is missing (e.g. truncated LAZ)
    6 October 2011 -- large file support, ability to read with missing chunk table
    23 June 2011 -- turned on LASzip version 2.0 compressor with chunking
    8 May 2011 -- added an option for variable chunking via chunk()
    23 April 2011 -- changed interface for simplicity and chunking support
    20 March 2011 -- incrementing LASZIP_VERSION to 1.2 for improved compression
    10 January 2011 -- licensing change for LGPL release and liblas integration
    12 December 2010 -- refactored from lasdefinitions after movies with silke

===============================================================================
*/
#ifndef LASZIP_HPP
#define LASZIP_HPP

#if defined(_MSC_VER) && (_MSC_VER < 1300)
#define LZ_WIN32_VC6
typedef __int64   SIGNED_INT64;
#else
typedef long long SIGNED_INT64;
#endif

#if defined(_MSC_VER) && \
    (_MSC_FULL_VER >= 150000000)
#define LASCopyString _strdup
#else
#define LASCopyString strdup
#endif

#define LASZIP_VERSION_MAJOR    2
#define LASZIP_VERSION_MINOR    1
#define LASZIP_VERSION_REVISION 1
#define LASZIP_VERSION_BUILD_DATE      130731

#define LASZIP_COMPRESSOR_NONE              0
#define LASZIP_COMPRESSOR_POINTWISE         1
#define LASZIP_COMPRESSOR_POINTWISE_CHUNKED 2
#define LASZIP_COMPRESSOR_TOTAL_NUMBER_OF   3

#define LASZIP_COMPRESSOR_CHUNKED LASZIP_COMPRESSOR_POINTWISE_CHUNKED
#define LASZIP_COMPRESSOR_NOT_CHUNKED LASZIP_COMPRESSOR_POINTWISE

#define LASZIP_COMPRESSOR_DEFAULT LASZIP_COMPRESSOR_CHUNKED

#define LASZIP_CODER_ARITHMETIC             0
#define LASZIP_CODER_TOTAL_NUMBER_OF        1

#define LASZIP_CHUNK_SIZE_DEFAULT           50000

#include "laszipexport.hpp"

class LASZIP_DLL LASitem
{
public:
  enum Type { BYTE = 0, SHORT, INT, LONG, FLOAT, DOUBLE, POINT10, GPSTIME11, RGB12, WAVEPACKET13, POINT14, RGBNIR14 } type;
  unsigned short size;
  unsigned short version;
  bool is_type(LASitem::Type t) const;
  const char* get_name() const;
};

class LASZIP_DLL LASzip
{
public:

  // supported version control
  bool check_compressor(const unsigned short compressor);
  bool check_coder(const unsigned short coder);
  bool check_item(const LASitem* item);
  bool check_items(const unsigned short num_items, const LASitem* items);
  bool check();

  // go back and forth between item array and point type & size
  bool setup(unsigned short* num_items, LASitem** items, const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_NONE);
  bool is_standard(const unsigned short num_items, const LASitem* items, unsigned char* point_type=0, unsigned short* record_length=0);
  bool is_standard(unsigned char* point_type=0, unsigned short* record_length=0);

  // pack to and unpack from VLR
  unsigned char* bytes;
  bool unpack(const unsigned char* bytes, const int num);
  bool pack(unsigned char*& bytes, int& num);

  // setup
  bool setup(const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_DEFAULT);
  bool setup(const unsigned short num_items, const LASitem* items, const unsigned short compressor);
  bool set_chunk_size(const unsigned int chunk_size);             /* for compressor only */
  bool request_version(const unsigned short requested_version);   /* for compressor only */

  // in case a function returns false this string describes the problem
  const char* get_error() const;

  // stored in LASzip VLR data section
  unsigned short compressor;
  unsigned short coder;
  unsigned char version_major;
  unsigned char version_minor;
  unsigned short version_revision;
  unsigned int options;
  unsigned int chunk_size;
  SIGNED_INT64 num_points;  /* not mandatory ... -1 if unknown */
  SIGNED_INT64 num_bytes;   /* not mandatory ... -1 if unknown */
  unsigned short num_items;
  LASitem* items;

  LASzip();
  ~LASzip();

private:
  bool return_error(const char* err);
  char* error_string;
};

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef LIBPORT_TRAITS_HH
# define LIBPORT_TRAITS_HH

# include <boost/tr1/type_traits.hpp>

# include <libport/meta.hh>

namespace libport
{
  namespace traits
  {
    /*------.
    | IsPOD |
    `------*/

    /// Whether 'T' is a POD.
    template <typename T>
    struct IsPOD
    {
      static const bool res = std::tr1::is_pod<T>::value;
    };

    /*---.
    | Id |
    `---*/

    /// Identity
    template <typename T>
    struct Id
    {
      typedef T res;
    };

    /*------.
    | Const |
    `------*/

    /// Constify T
    template <typename T>
    struct Const
    {
      typedef const T res;
    };

    /*----.
    | Ptr |
    `----*/

    /// Make T a pointer
    template <typename T>
    struct Ptr
    {
      typedef T* res;
    };

    /*----.
    | Ref |
    `----*/

    /// Make T a reference
    template <typename T>
    struct Ref
    {
      typedef T& res;
    };

    /*---------.
    | ConstPtr |
    `---------*/

    /// Make T a const pointer
    template <typename T>
    struct ConstPtr
    {
      typedef typename meta::Compose<Ptr, Const>::Res<T>::res res;
    };

    /*---------.
    | ConstRef |
    `---------*/

    /// Make T a const reference
    template <typename T>
    struct ConstRef
    {
      typedef typename meta::Compose<Ref, Const>::Res<T>::res res;
    };

    /*-------------------.
    | Remove reference.  |
    `-------------------*/

    /// Remove reference mark from T.
    template <typename T>
    struct RemoveReference
    {
      typedef T res;
    };

    template <typename T>
    struct RemoveReference<T&>
    {
      typedef T res;
    };

    /// Remove reference mark from T, tr1 style.
    template <typename T>
    struct remove_reference
    {
      typedef T type;
    };

    template <typename T>
    struct remove_reference<T&>
    {
      typedef T type;
    };

    /*---------------.
    | Remove const.  |
    `---------------*/

    /// Remove const mark from T.
    template <typename T>
    struct RemoveConst
    {
      typedef T res;
    };

    template <typename T>
    struct RemoveConst<const T>
    {
      typedef T res;
    };

    /*----.
    | Arg |
    `----*/

    /// Give the best type for passing a T as argument
    /* That is, T if T is a POD, const T& otherwise.
     *
     */
    template <typename T>
    struct Arg
    {
      typedef typename meta::If<IsPOD<T>::res, T, const T&>::res res;
    };
  }
}

#endif
<commit_msg>Traits: add Compose.<commit_after>/*
 * Copyright (C) 2008-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef LIBPORT_TRAITS_HH
# define LIBPORT_TRAITS_HH

# include <boost/tr1/type_traits.hpp>

# include <libport/meta.hh>

namespace libport
{
  namespace traits
  {
    /*------.
    | IsPOD |
    `------*/

    /// Whether 'T' is a POD.
    template <typename T>
    struct IsPOD
    {
      static const bool res = std::tr1::is_pod<T>::value;
    };

    /*---.
    | Id |
    `---*/

    /// Identity
    template <typename T>
    struct Id
    {
      typedef T res;
    };

    /*------.
    | Const |
    `------*/

    /// Constify T
    template <typename T>
    struct Const
    {
      typedef const T res;
    };

    /*----.
    | Ptr |
    `----*/

    /// Make T a pointer
    template <typename T>
    struct Ptr
    {
      typedef T* res;
    };

    /*----.
    | Ref |
    `----*/

    /// Make T a reference
    template <typename T>
    struct Ref
    {
      typedef T& res;
    };

    /*---------.
    | ConstPtr |
    `---------*/

    /// Make T a const pointer
    template <typename T>
    struct ConstPtr
    {
      typedef typename meta::Compose<Ptr, Const>::Res<T>::res res;
    };

    /*---------.
    | ConstRef |
    `---------*/

    /// Make T a const reference
    template <typename T>
    struct ConstRef
    {
      typedef typename meta::Compose<Ref, Const>::Res<T>::res res;
    };

    /*-------------------.
    | Remove reference.  |
    `-------------------*/

    /// Remove reference mark from T.
    template <typename T>
    struct RemoveReference
    {
      typedef T res;
    };

    template <typename T>
    struct RemoveReference<T&>
    {
      typedef T res;
    };

    /// Remove reference mark from T, tr1 style.
    template <typename T>
    struct remove_reference
    {
      typedef T type;
    };

    template <typename T>
    struct remove_reference<T&>
    {
      typedef T type;
    };

    /*---------------.
    | Remove const.  |
    `---------------*/

    /// Remove const mark from T.
    template <typename T>
    struct RemoveConst
    {
      typedef T res;
    };

    template <typename T>
    struct RemoveConst<const T>
    {
      typedef T res;
    };

    /*----.
    | Arg |
    `----*/

    /// Give the best type for passing a T as argument
    /* That is, T if T is a POD, const T& otherwise.
     *
     */
    template <typename T>
    struct Arg
    {
      typedef typename meta::If<IsPOD<T>::res, T, const T&>::res res;
    };

    /*--------.
    | Compose |
    `--------*/

    /// Compose meta functions.
    template <template <typename> class F1, template <typename> class F2>
    struct Compose
    {
      template <typename T>
      struct fun
      {
        typedef typename F1<typename F2<T>::res>::res res;
      };
    };
  }
}

#endif
<|endoftext|>