<commit_before>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include "sdklayout.hpp"
#include "filesystem.hpp"

#include <qi/application.hpp>
#include <qi/path.hpp>
#include <qi/os.hpp>
#include <qi/qi.hpp>
#include <qi/log.hpp>

#include <boost/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#ifdef _WIN32
  #include <windows.h>
#endif

qiLogCategory("qi.path");

namespace fs = boost::filesystem;

namespace qi
{

  class PrivatePath {
  public:
    PrivatePath(const std::string& unicodePath)
      : path(unicodePath, qi::unicodeFacet())
    {}

    PrivatePath(const fs::path& path)
      : path(path)
    {}

    fs::path path;
  };

  Path::Path(const boost::shared_ptr<PrivatePath>& p)
    : _p(p)
  {}

  Path::Path(const std::string& unicodePath)
    : _p(new PrivatePath(unicodePath))
  {}

  bool Path::isEmpty() const
  {
    return _p->path.empty();
  }

  bool Path::isDir() const
  {
    return fs::is_directory(_p->path);
  }

  bool Path::isRegularFile() const
  {
    return fs::is_regular_file(_p->path);
  }

  std::string Path::extension() const
  {
    return _p->path.extension().string(qi::unicodeFacet());
  }

  Path Path::parent()
  {
    return Path(boost::make_shared<PrivatePath>(_p->path.parent_path()));
  }

  std::string Path::filename() const
  {
    return _p->path.filename().string(qi::unicodeFacet());
  }

  Path Path::absolute()
  {
    return Path(boost::make_shared<PrivatePath>(fs::absolute(_p->path)));
  }

  PathVector Path::files()
  {
    PathVector ret;
    fs::directory_iterator dit(_p->path);

    for (; dit != fs::directory_iterator(); ++dit) {
      if (fs::is_regular_file(*dit))
        ret.push_back(Path(boost::make_shared<PrivatePath>(*dit)));
    }
    return ret;
  }

  PathVector Path::dirs()
  {
    PathVector ret;
    fs::directory_iterator dit(_p->path);

    for (; dit != fs::directory_iterator(); ++dit) {
      if (fs::is_directory(*dit))
        ret.push_back(Path(boost::make_shared<PrivatePath>(*dit)));
    }
    return ret;
  }

  Path Path::operator/(const Path &rhs) const
  {
    return Path(boost::make_shared<PrivatePath>(_p->path / rhs._p->path));
  }

  const Path& Path::operator/=(const Path &rhs) const
  {
    _p->path /= rhs._p->path;
    return *this;
  }

  Path::operator std::string() const
  {
    return _p->path.string(qi::unicodeFacet());
  }

  SDKLayout* gInstance = NULL;
  SDKLayout* getInstance();

  //only needed to make valgrind happy.
  static void cleanupSdkLayout() {
    if (!qi::os::getenv("VALGRIND").empty()) {
      delete gInstance;
      gInstance = 0;
    }
  }

  QI_AT_EXIT(&cleanupSdkLayout);

  namespace path
  {

    boost::filesystem::path absPath(const std::string &pathString)
    {
      boost::filesystem::path path(pathString, qi::unicodeFacet());
      return boost::filesystem::system_complete(path).make_preferred();
    }

    namespace detail {

      void addOptionalSdkPrefix(const char *prefix)
      {
        return getInstance()->addOptionalSdkPrefix(prefix);
      }

      void clearOptionalSdkPrefix()
      {
        return getInstance()->clearOptionalSdkPrefix();
      }

      std::vector<std::string> getSdkPrefixes()
      {
        return getInstance()->getSdkPrefixes();
      }

#ifdef _WIN32
      std::string dosCompatiblePath(const std::string &pathString)
      {
        // Some libs of our toolchain does not support UTF-8 on Windows
        // for Py_SetPythonHome for example, we need to clean path from UTF-8 chars
        // to make it usable.
        // The fix found is to convert path into short DOS 8.3 path
        long length = 0;
        wchar_t* buffer = NULL;
        boost::filesystem::path path(pathString, qi::unicodeFacet());

        // first, get size necessary for wchar_t* buffer
        length = GetShortPathNameW(path.wstring(qi::unicodeFacet()).c_str(), NULL, 0);
        if(length == 0)
        {
          qiLogVerbose() << "Cannot retrieve short path for "
                         << pathString.c_str();
          return std::string();
        }

        // now, get the path compatible DOS 8.3, ASCII compliant
        buffer = new wchar_t[length];
        length = GetShortPathNameW(path.wstring(qi::unicodeFacet()).c_str(), buffer, length);
        if(length == 0)
        {
          qiLogVerbose() << "Cannot retrieve short path for "
                         << pathString.c_str();
          return std::string();
        }

        // whatever the buffer is wchar_t*, all characters inside are ASCII
        boost::filesystem::path shortPath(std::wstring(buffer), qi::unicodeFacet());
        delete [] buffer;

        return shortPath.string(qi::unicodeFacet());
      }
#endif
    }

    std::string sdkPrefix()
    {
      return getInstance()->sdkPrefix();
    }

    std::string findBin(const std::string &name)
    {
      return getInstance()->findBin(name);
    }

    std::string findLib(const std::string &name)
    {
      return getInstance()->findLib(name);
    }

    std::string findConf(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findConf(applicationName, filename);
    }

    std::string findData(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findData(applicationName, filename);
    }

    std::vector<std::string> listData(const std::string &applicationName,
                                      const std::string &pattern)
    {
      return getInstance()->listData(applicationName, pattern);
    }

    std::vector<std::string> confPaths(const std::string &applicationName)
    {
      return getInstance()->confPaths(applicationName);
    }

    std::vector<std::string> dataPaths(const std::string &applicationName)
    {
      return getInstance()->dataPaths(applicationName);
    }

    std::vector<std::string> binPaths()
    {
      return getInstance()->binPaths();
    }

    std::vector<std::string> libPaths()
    {
      return getInstance()->libPaths();
    }

    void setWritablePath(const std::string &path)
    {
      qiLogVerbose() << "Writable path set to " << path;
      getInstance()->setWritablePath(path);
    }

    std::string userWritableDataPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return getInstance()->userWritableDataPath(applicationName, filename);
    }

    std::string userWritableConfPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return qi::getInstance()->userWritableConfPath(applicationName, filename);
    }

    std::string convertToDosPath(const std::string &pathString)
    {
#ifdef _WIN32
      // Windows doesn't natively support unicode path. Returns an ASCII one
      return detail::dosCompatiblePath(pathString);
#else
      // just ignore
      return pathString;
#endif
    }
  }

  SDKLayout* getInstance()
  {
    if (gInstance == NULL) {
      std::string prefix;
      std::string mode;
      const char *program = qi::Application::program();

      if (!program) {
        mode = "error";
      }
      else {
        boost::filesystem::path execPath(program, qi::unicodeFacet());
        if(!boost::filesystem::exists(execPath)) {
          mode = "error";
        }
        else {
          execPath = boost::filesystem::system_complete(execPath).make_preferred();
          prefix = execPath.parent_path().parent_path().string(qi::unicodeFacet());
          if (execPath.parent_path().filename().string(qi::unicodeFacet()) != "bin")
            mode = execPath.parent_path().filename().string(qi::unicodeFacet());
          else
            mode = "";
        }
      }
      gInstance = new SDKLayout(prefix, mode);
    }

    return gInstance;
  }

  namespace {
    _QI_COMMAND_LINE_OPTIONS(
      "Chrooting",
      ("writable-path", value<std::string>()->notifier(&qi::path::setWritablePath), "Set the writable path.")
      )
  }
}
<commit_msg>qi::Path: avoid boost exceptions<commit_after>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include "sdklayout.hpp"
#include "filesystem.hpp"

#include <qi/application.hpp>
#include <qi/path.hpp>
#include <qi/os.hpp>
#include <qi/qi.hpp>
#include <qi/log.hpp>

#include <boost/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#ifdef _WIN32
  #include <windows.h>
#endif

qiLogCategory("qi.path");

namespace fs = boost::filesystem;

namespace qi
{

  class PrivatePath {
  public:
    PrivatePath(const std::string& unicodePath)
      : path(unicodePath, qi::unicodeFacet())
    {}

    PrivatePath(const fs::path& path)
      : path(path)
    {}

    fs::path path;
  };

  Path::Path(const boost::shared_ptr<PrivatePath>& p)
    : _p(p)
  {}

  Path::Path(const std::string& unicodePath)
    : _p(new PrivatePath(unicodePath))
  {}

  bool Path::isEmpty() const
  {
    return _p->path.empty();
  }

  bool Path::isDir() const
  {
    boost::system::error_code ec;
    return fs::is_directory(_p->path, ec);
  }

  bool Path::isRegularFile() const
  {
    boost::system::error_code ec;
    return fs::is_regular_file(_p->path, ec);
  }

  std::string Path::extension() const
  {
    return _p->path.extension().string(qi::unicodeFacet());
  }

  Path Path::parent()
  {
    return Path(boost::make_shared<PrivatePath>(_p->path.parent_path()));
  }

  std::string Path::filename() const
  {
    return _p->path.filename().string(qi::unicodeFacet());
  }

  Path Path::absolute()
  {
    return Path(boost::make_shared<PrivatePath>(fs::absolute(_p->path)));
  }

  PathVector Path::files()
  {
    PathVector ret;
    fs::directory_iterator dit(_p->path);

    for (; dit != fs::directory_iterator(); ++dit) {
      if (fs::is_regular_file(*dit))
        ret.push_back(Path(boost::make_shared<PrivatePath>(*dit)));
    }
    return ret;
  }

  PathVector Path::dirs()
  {
    PathVector ret;
    fs::directory_iterator dit(_p->path);

    for (; dit != fs::directory_iterator(); ++dit) {
      if (fs::is_directory(*dit))
        ret.push_back(Path(boost::make_shared<PrivatePath>(*dit)));
    }
    return ret;
  }

  Path Path::operator/(const Path &rhs) const
  {
    return Path(boost::make_shared<PrivatePath>(_p->path / rhs._p->path));
  }

  const Path& Path::operator/=(const Path &rhs) const
  {
    _p->path /= rhs._p->path;
    return *this;
  }

  Path::operator std::string() const
  {
    return _p->path.string(qi::unicodeFacet());
  }

  SDKLayout* gInstance = NULL;
  SDKLayout* getInstance();

  //only needed to make valgrind happy.
  static void cleanupSdkLayout() {
    if (!qi::os::getenv("VALGRIND").empty()) {
      delete gInstance;
      gInstance = 0;
    }
  }

  QI_AT_EXIT(&cleanupSdkLayout);

  namespace path
  {

    boost::filesystem::path absPath(const std::string &pathString)
    {
      boost::filesystem::path path(pathString, qi::unicodeFacet());
      return boost::filesystem::system_complete(path).make_preferred();
    }

    namespace detail {

      void addOptionalSdkPrefix(const char *prefix)
      {
        return getInstance()->addOptionalSdkPrefix(prefix);
      }

      void clearOptionalSdkPrefix()
      {
        return getInstance()->clearOptionalSdkPrefix();
      }

      std::vector<std::string> getSdkPrefixes()
      {
        return getInstance()->getSdkPrefixes();
      }

#ifdef _WIN32
      std::string dosCompatiblePath(const std::string &pathString)
      {
        // Some libs of our toolchain does not support UTF-8 on Windows
        // for Py_SetPythonHome for example, we need to clean path from UTF-8 chars
        // to make it usable.
        // The fix found is to convert path into short DOS 8.3 path
        long length = 0;
        wchar_t* buffer = NULL;
        boost::filesystem::path path(pathString, qi::unicodeFacet());

        // first, get size necessary for wchar_t* buffer
        length = GetShortPathNameW(path.wstring(qi::unicodeFacet()).c_str(), NULL, 0);
        if(length == 0)
        {
          qiLogVerbose() << "Cannot retrieve short path for "
                         << pathString.c_str();
          return std::string();
        }

        // now, get the path compatible DOS 8.3, ASCII compliant
        buffer = new wchar_t[length];
        length = GetShortPathNameW(path.wstring(qi::unicodeFacet()).c_str(), buffer, length);
        if(length == 0)
        {
          qiLogVerbose() << "Cannot retrieve short path for "
                         << pathString.c_str();
          return std::string();
        }

        // whatever the buffer is wchar_t*, all characters inside are ASCII
        boost::filesystem::path shortPath(std::wstring(buffer), qi::unicodeFacet());
        delete [] buffer;

        return shortPath.string(qi::unicodeFacet());
      }
#endif
    }

    std::string sdkPrefix()
    {
      return getInstance()->sdkPrefix();
    }

    std::string findBin(const std::string &name)
    {
      return getInstance()->findBin(name);
    }

    std::string findLib(const std::string &name)
    {
      return getInstance()->findLib(name);
    }

    std::string findConf(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findConf(applicationName, filename);
    }

    std::string findData(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findData(applicationName, filename);
    }

    std::vector<std::string> listData(const std::string &applicationName,
                                      const std::string &pattern)
    {
      return getInstance()->listData(applicationName, pattern);
    }

    std::vector<std::string> confPaths(const std::string &applicationName)
    {
      return getInstance()->confPaths(applicationName);
    }

    std::vector<std::string> dataPaths(const std::string &applicationName)
    {
      return getInstance()->dataPaths(applicationName);
    }

    std::vector<std::string> binPaths()
    {
      return getInstance()->binPaths();
    }

    std::vector<std::string> libPaths()
    {
      return getInstance()->libPaths();
    }

    void setWritablePath(const std::string &path)
    {
      qiLogVerbose() << "Writable path set to " << path;
      getInstance()->setWritablePath(path);
    }

    std::string userWritableDataPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return getInstance()->userWritableDataPath(applicationName, filename);
    }

    std::string userWritableConfPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return qi::getInstance()->userWritableConfPath(applicationName, filename);
    }

    std::string convertToDosPath(const std::string &pathString)
    {
#ifdef _WIN32
      // Windows doesn't natively support unicode path. Returns an ASCII one
      return detail::dosCompatiblePath(pathString);
#else
      // just ignore
      return pathString;
#endif
    }
  }

  SDKLayout* getInstance()
  {
    if (gInstance == NULL) {
      std::string prefix;
      std::string mode;
      const char *program = qi::Application::program();

      if (!program) {
        mode = "error";
      }
      else {
        boost::filesystem::path execPath(program, qi::unicodeFacet());
        if(!boost::filesystem::exists(execPath)) {
          mode = "error";
        }
        else {
          execPath = boost::filesystem::system_complete(execPath).make_preferred();
          prefix = execPath.parent_path().parent_path().string(qi::unicodeFacet());
          if (execPath.parent_path().filename().string(qi::unicodeFacet()) != "bin")
            mode = execPath.parent_path().filename().string(qi::unicodeFacet());
          else
            mode = "";
        }
      }
      gInstance = new SDKLayout(prefix, mode);
    }

    return gInstance;
  }

  namespace {
    _QI_COMMAND_LINE_OPTIONS(
      "Chrooting",
      ("writable-path", value<std::string>()->notifier(&qi::path::setWritablePath), "Set the writable path.")
      )
  }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[50]={0};

void Init(){

	p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;

	return ;
}

int a[30]={0};
int count1;
int m;
int add(int cur,int i){

	int sum=0;

	REP(j,0,m-2){
		sum+=a[cur-j];
	}
	sum+=i;
	if(p[sum]==1){
		return 1;
	}
	else{
		return 0;
	}

}
int n;

int dfs(int cur){
	REP(i,0,9){
		//print(i);
		if(add(cur,i)){
			//print(i);
			if(cur==n+5){
				count1++;
			}else{
				a[cur++]=i;
				dfs(cur);
			}

		}
	}
}
void Solve(){
	scanf("%d%d",&n,&m);
	dfs(5);
	cout<<count1<<endl;
	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj18025.in","r",stdin);
#endif

 	int t;
 	scanf("%d",&t);
 	while(t--)
	Init(),Solve();
	return 0;
}<commit_msg>update uoj18025<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[50]={0};

void Init(){

	p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;

	return ;
}

int a[30]={0};
int count1;
int m;
int add(int cur,int i){

	int sum=0;

	REP(j,0,m-2){
		sum+=a[cur-j];
	}
	sum+=i;
	if(p[sum]==1){
		return 1;
	}
	else{
		return 0;
	}

}
int n;

int dfs(int cur){
	REP(i,0,9){
		//print(i);
		if(add(cur,i)){
			//print(i);
			if(cur==n+5){
				REP(j,0,20){
					cout<<a[i]<<" ";
				}
				cout<<endl;
				count1++;
			}else{
				a[cur++]=i;
				dfs(cur);
			}

		}
	}
}
void Solve(){
	scanf("%d%d",&n,&m);
	dfs(5);
	cout<<count1<<endl;
	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj18025.in","r",stdin);
#endif

 	int t;
 	scanf("%d",&t);
 	while(t--)
	Init(),Solve();
	return 0;
}<|endoftext|>


<commit_before>#include <MEII/Classification/RealTimeMultiClassifier.hpp>
#include <MEL/Math/Functions.hpp>
#include <MEII/SignalProcessing/SignalProcessingFunctions.hpp>
#include <MEII/Classification/LinearDiscriminantAnalysis.hpp>
#include <MEL/Logging/Log.hpp>

#include <MEL/Logging/DataLogger.hpp>

using namespace mel;

namespace meii {

    RealTimeMultiClassifier::RealTimeMultiClassifier(std::size_t class_count, std::size_t sample_dimension, Time sample_period, Time classification_period, Time feature_period, Time classification_overlap) :
		class_count_(class_count < 2 ? 2 : class_count),
        sample_dim_(sample_dimension),
        Ts_(sample_period),
        classification_window_size_(sample_period < classification_period ? (std::size_t)((unsigned)std::round(classification_period.as_seconds() / sample_period.as_seconds())) : 1),
        feature_window_size_(sample_period < feature_period ? (std::size_t)((unsigned)std::round(feature_period.as_seconds() / sample_period.as_seconds())) : 1),
        pred_counter_(0),
        pred_spacing_(classification_overlap > classification_period ? 1 : (std::size_t)((unsigned)std::round((classification_period.as_seconds() - classification_overlap.as_seconds()) / sample_period.as_seconds()))),
        classification_buffer_(classification_window_size_),
        sample_buffer_(feature_window_size_),
        training_data_(class_count_),
        feature_data_(class_count_),
        feature_dim_(get_feature_dim()),
        w_(class_count_),
        w_0_(class_count_),
        y_(class_count_),
        p_(class_count_),
        trained_(false)
    {}

    bool RealTimeMultiClassifier::update(std::vector<double> sample) {
        if (!trained_)
            return false;
        if (sample.size() != sample_dim_) {
            LOG(Error) << "Incorrect size for sample given to update() in RealTimeMultiClassifier";
            return false;
        }

        sample_buffer_.push_back(sample);
        if (!sample_buffer_.full())
            return false;

        x_ = feature_extraction(sample_buffer_.get_vector());

        y_ = w_0_;
        for (std::size_t i = 0; i < class_count_; ++i) {
            for (std::size_t j = 0; j < feature_dim_; ++j) {
                y_[i] += w_[i][j] * x_[j];
            }
        }

        for (std::size_t i = 0; i < class_count_; ++i) {
            p_[i] = softmax(y_, i);
        }
        classification_buffer_.push_back(p_);
        if (++pred_counter_ == classification_window_size_)
            pred_counter_ = 0;
        if (classification_buffer_.full() && (pred_counter_ % pred_spacing_ == 0)) {
            pred_class_ = classification_heuristic(downsample(classification_buffer_.get_vector(), feature_window_size_));
        }
        return true;
    }

    bool RealTimeMultiClassifier::add_training_data(std::size_t class_label, const std::vector<std::vector<double>>& class_data) {
		if (class_label >= class_count_) {
            LOG(Warning) << "Invalid class label provided. Training data was not added.";
            return false;
        }
        training_data_[class_label].insert(training_data_[class_label].end(), class_data.begin(), class_data.end());
		LOG(Verbose) << "Added training data to RealTimeMultiClassifier for class " << class_label << ". This class now has " << training_data_[class_label].size() << " samples of training data.";
        return true;
    }

    bool RealTimeMultiClassifier::clear_training_data(std::size_t class_label) {
        if (class_label >= class_count_) {
            LOG(Warning) << "Invalid class label provided. Training data was not cleared.";
            return false;
        }
        training_data_[class_label].clear();
        return true;
    }

    bool RealTimeMultiClassifier::train() {
        for (std::size_t i = 0; i < class_count_; ++i) {
            if (training_data_[i].empty()) {
                LOG(Warning) << "Must collect training data for all classes before calling RealTimeMultiClassifier::train(). Training was aborted.";
                return trained_ = false;
            }
        }

        std::vector<std::vector<std::vector<double>>> binned_data;
        for (std::size_t i = 0; i < class_count_; ++i) {
            binned_data = bin_signal(training_data_[i], feature_window_size_);
            feature_data_[i].resize(binned_data.size());
            for (std::size_t j = 0; j < binned_data.size(); ++j) {
                feature_data_[i][j] = feature_extraction(binned_data[j]);
            }
        }
        if (!multi_linear_discriminant_model(feature_data_, w_, w_0_, 1.0))
            return trained_ = false;

        return trained_ = true;
    }

	void RealTimeMultiClassifier::compute_features() {
		std::vector<std::vector<std::vector<double>>> binned_data;
		for (std::size_t i = 0; i < class_count_; ++i) {
			if (training_data_[i].size() < feature_window_size_) {
				LOG(Warning) << "Not enough training data was provided for class " << i << " when calling RealTimeMultiClassifier::compute_features().";
			}
			else {
				binned_data = bin_signal(training_data_[i], feature_window_size_);
				feature_data_[i].resize(binned_data.size());
				for (std::size_t j = 0; j < binned_data.size(); ++j) {
					feature_data_[i][j] = feature_extraction(binned_data[j]);
				}
			}
		}
	}

    bool RealTimeMultiClassifier::set_model(const std::vector<std::vector<double>>& w, const std::vector<double>& w_0) {
        if (w.size() != class_count_) {
            LOG(Warning) << "Classification model size must match the number of classes. Model not set.";
            return trained_ = false;
        }
        if (w_0.size() != class_count_) {
            LOG(Warning) << "Classification model intercept size must match the number of classes. Model not set.";
            return trained_ = false;
        }
        for (std::size_t i = 0; i < class_count_; ++i) {
            if (w[i].size() != feature_dim_) {
                LOG(Warning) << "Classification model inner dimension size must match the size of the sample dimension. Model not set.";
                return trained_ = false;
            }
        }
        w_ = w;
        w_0_ = w_0;
        return trained_ = true;
    }

    std::size_t RealTimeMultiClassifier::get_class() const {
        if (!trained_)
            return class_count_;
        return pred_class_;
    }

    void RealTimeMultiClassifier::get_model(std::vector<std::vector<double>>& w, std::vector<double>& w_0) {
        w = w_;
        w_0 = w_0_;
    }

    std::vector<std::vector<double>> RealTimeMultiClassifier::get_class_training_data(std::size_t class_label) const {
		if (class_label >= class_count_) {
			LOG(Warning) << "Invalid class label provided to RealTimeMultiClassifier::get_class_training_data(). Returning empty vector.";
			return std::vector<std::vector<double>>();
		}
		if (training_data_.empty() || training_data_[class_label].empty()) {
			LOG(Warning) << "No feature data found during call to RealTimeMultiClassifier::get_class_training_data(). Returning empty vector.";
			return std::vector<std::vector<double>>();
		}

		std::vector<std::vector<double>> class_training_data = training_data_[class_label];
		for (std::size_t i = 0; i < class_training_data.size(); ++i) {
			class_training_data[i].push_back(class_label);
		}
		return class_training_data;
    }

    std::vector<std::vector<double>> RealTimeMultiClassifier::get_class_feature_data(std::size_t class_label) const {
        if (class_label >= class_count_) {
            LOG(Warning) << "Invalid class label provided to RealTimeMultiClassifier::get_class_feature_data(). Returning empty vector.";
            return std::vector<std::vector<double>>();
        }
		if (feature_data_.empty() || feature_data_[class_label].empty()) {
			LOG(Warning) << "No feature data found during call to RealTimeMultiClassifier::get_class_feature_data(). Returning empty vector.";
			return std::vector<std::vector<double>>();
		}

		std::vector<std::vector<double>> class_feature_data = feature_data_[class_label];
		for (std::size_t i = 0; i < class_feature_data.size(); ++i) {
			class_feature_data[i].push_back(class_label);
		}
        return class_feature_data;
    }

    bool RealTimeMultiClassifier::is_trained() {
        return trained_;
    }

    std::size_t RealTimeMultiClassifier::get_sample_dim() const {
        return sample_dim_;
    }

    std::size_t RealTimeMultiClassifier::get_feature_dim() const {
        return sample_dim_;
    }

	void RealTimeMultiClassifier::set_class_count(std::size_t class_count) {
		class_count = class_count < 2 ? 2 : class_count;
		if (class_count_ != class_count) {
			class_count_ = class_count;
			training_data_.resize(class_count);
			feature_data_.resize(class_count);
			w_.resize(class_count);
			w_0_.resize(class_count);
			y_.resize(class_count);
			p_.resize(class_count);
			trained_ = false;
		}
	}

    std::vector<double> RealTimeMultiClassifier::feature_extraction(const std::vector<std::vector<double>>& signal) const {
        if (signal.empty()) {
            LOG(Warning) << "Input given to RealTimeMultiClassifier::feature_extraction() is empty. Returning empty vector.";
            return std::vector<double>();
        }
        return signal[0];
    }

    std::size_t RealTimeMultiClassifier::classification_heuristic(const std::vector<std::vector<double>>& probabilities) const {
        return majority_vote(activation_function(probabilities));
    }

    std::vector<std::size_t> RealTimeMultiClassifier::activation_function(const std::vector<std::vector<double>>& probabilities) const {
        std::vector<std::size_t> labels(probabilities.size());
        for (std::size_t i = 0; i < probabilities.size(); ++i) {
            labels[i] = std::distance(probabilities[i].begin(), std::max_element(probabilities[i].begin(), probabilities[i].end()));
        }
        return labels;
    }

    std::size_t RealTimeMultiClassifier::majority_vote(const std::vector<std::size_t>& labels) const {
        std::vector<std::size_t> votes(class_count_, 0);
        for (std::size_t i = 0; i < labels.size(); ++i) {
            votes[labels[i]]++;
        }
        return std::distance(votes.begin(), std::max_element(votes.begin(), votes.end()));
    }

} // namespace meii<commit_msg>updating realtimemulti<commit_after>#include <MEII/Classification/RealTimeMultiClassifier.hpp>
#include <MEL/Math/Functions.hpp>
#include <MEII/SignalProcessing/SignalProcessingFunctions.hpp>
#include <MEII/Classification/LinearDiscriminantAnalysis.hpp>
#include <MEL/Logging/Log.hpp>

#include <MEL/Logging/DataLogger.hpp>

using namespace mel;

namespace meii {

    RealTimeMultiClassifier::RealTimeMultiClassifier(std::size_t class_count, std::size_t sample_dimension, Time sample_period, Time classification_period, Time feature_period, Time classification_overlap) :
		class_count_(class_count < 2 ? 2 : class_count),
        sample_dim_(sample_dimension),
        Ts_(sample_period),
        classification_window_size_(sample_period < classification_period ? (std::size_t)((unsigned)std::round(classification_period.as_seconds() / sample_period.as_seconds())) : 1),
        feature_window_size_(sample_period < feature_period ? (std::size_t)((unsigned)std::round(feature_period.as_seconds() / sample_period.as_seconds())) : 1),
        pred_counter_(0),
        pred_spacing_(classification_overlap > classification_period ? 1 : (std::size_t)((unsigned)std::round((classification_period.as_seconds() - classification_overlap.as_seconds()) / sample_period.as_seconds()))),
        classification_buffer_(classification_window_size_),
        sample_buffer_(feature_window_size_),
        training_data_(class_count_),
        feature_data_(class_count_),
        feature_dim_(get_feature_dim()),
        w_(class_count_),
        w_0_(class_count_),
        y_(class_count_),
        p_(class_count_),
        trained_(false)
    {}

    bool RealTimeMultiClassifier::update(std::vector<double> sample) {
        if (!trained_)
            return false;
        if (sample.size() != sample_dim_) {
            LOG(Error) << "Incorrect size for sample given to update() in RealTimeMultiClassifier";
            return false;
        }

        sample_buffer_.push_back(sample);
        if (!sample_buffer_.full())
            return false;

        x_ = feature_extraction(sample_buffer_.get_vector());

        y_ = w_0_;
        for (std::size_t i = 0; i < class_count_; ++i) {
            for (std::size_t j = 0; j < feature_dim_; ++j) {
                y_[i] += w_[i][j] * x_[j];
            }
        }

        for (std::size_t i = 0; i < class_count_; ++i) {
            p_[i] = softmax(y_, i);
        }
        classification_buffer_.push_back(p_);
        if (++pred_counter_ == classification_window_size_)
            pred_counter_ = 0;
        if (classification_buffer_.full() && (pred_counter_ % pred_spacing_ == 0)) {
            pred_class_ = classification_heuristic(downsample(classification_buffer_.get_vector(), feature_window_size_));
        }
        return true;
    }

    bool RealTimeMultiClassifier::add_training_data(std::size_t class_label, const std::vector<std::vector<double>>& class_data) {
		if (class_label >= class_count_) {
            LOG(Warning) << "Invalid class label provided. Training data was not added.";
            return false;
        }
        training_data_[class_label].insert(training_data_[class_label].end(), class_data.begin(), class_data.end());
		LOG(Verbose) << "Added training data to RealTimeMultiClassifier for class " << class_label << ". This class now has " << training_data_[class_label].size() << " samples of training data.";
        return true;
    }

    bool RealTimeMultiClassifier::clear_training_data(std::size_t class_label) {
        if (class_label >= class_count_) {
            LOG(Warning) << "Invalid class label provided. Training data was not cleared.";
            return false;
        }
        training_data_[class_label].clear();
        return true;
    }

    bool RealTimeMultiClassifier::train() {
        for (std::size_t i = 0; i < class_count_; ++i) {
            if (training_data_[i].empty()) {
                LOG(Warning) << "Must collect training data for all classes before calling RealTimeMultiClassifier::train(). Training was aborted.";
                return trained_ = false;
            }
        }

        std::vector<std::vector<std::vector<double>>> binned_data;
        for (std::size_t i = 0; i < class_count_; ++i) {
            binned_data = bin_signal(training_data_[i], feature_window_size_);
            feature_data_[i].resize(binned_data.size());
            for (std::size_t j = 0; j < binned_data.size(); ++j) {
                feature_data_[i][j] = feature_extraction(binned_data[j]);
            }
        }
        if (!multi_linear_discriminant_model(feature_data_, w_, w_0_, 1.0))
            return trained_ = false;

        return trained_ = true;
    }

	void RealTimeMultiClassifier::compute_features() {
		std::vector<std::vector<std::vector<double>>> binned_data;
		for (std::size_t i = 0; i < class_count_; ++i) {
			if (training_data_[i].size() < feature_window_size_) {
				LOG(Warning) << "Not enough training data was provided for class " << i << " when calling RealTimeMultiClassifier::compute_features().";
			}
			else {
				binned_data = bin_signal(training_data_[i], feature_window_size_);
				feature_data_[i].resize(binned_data.size());
				for (std::size_t j = 0; j < binned_data.size(); ++j) {
					feature_data_[i][j] = feature_extraction(binned_data[j]);
				}
			}
		}
	}

    bool RealTimeMultiClassifier::set_model(const std::vector<std::vector<double>>& w, const std::vector<double>& w_0) {
        if (w.size() != class_count_) {
            LOG(Warning) << "Classification model size must match the number of classes. Model not set.";
            return trained_ = false;
        }
        if (w_0.size() != class_count_) {
            LOG(Warning) << "Classification model intercept size must match the number of classes. Model not set.";
            return trained_ = false;
        }
        for (std::size_t i = 0; i < class_count_; ++i) {
            if (w[i].size() != feature_dim_) {
                LOG(Warning) << "Classification model inner dimension size must match the size of the sample dimension. Model not set.";
                return trained_ = false;
            }
        }
        w_ = w;
        w_0_ = w_0;
        return trained_ = true;
    }

    std::size_t RealTimeMultiClassifier::get_class() const {
        if (!trained_)
            return class_count_;
        return pred_class_;
    }

    void RealTimeMultiClassifier::get_model(std::vector<std::vector<double>>& w, std::vector<double>& w_0) {
        w = w_;
        w_0 = w_0_;
    }

    std::vector<std::vector<double>> RealTimeMultiClassifier::get_class_training_data(std::size_t class_label) const {
		if (class_label >= class_count_) {
			LOG(Warning) << "Invalid class label provided to RealTimeMultiClassifier::get_class_training_data(). Returning empty vector.";
			return std::vector<std::vector<double>>();
		}
		if (training_data_.empty() || training_data_[class_label].empty()) {
			LOG(Warning) << "No feature data found during call to RealTimeMultiClassifier::get_class_training_data(). Returning empty vector.";
			return std::vector<std::vector<double>>();
		}

		std::vector<std::vector<double>> class_training_data = training_data_[class_label];
		for (std::size_t i = 0; i < class_training_data.size(); ++i) {
			class_training_data[i].push_back(class_label+1);
		}
		return class_training_data;
    }

    std::vector<std::vector<double>> RealTimeMultiClassifier::get_class_feature_data(std::size_t class_label) const {
        if (class_label >= class_count_) {
            LOG(Warning) << "Invalid class label provided to RealTimeMultiClassifier::get_class_feature_data(). Returning empty vector.";
            return std::vector<std::vector<double>>();
        }
		if (feature_data_.empty() || feature_data_[class_label].empty()) {
			LOG(Warning) << "No feature data found during call to RealTimeMultiClassifier::get_class_feature_data(). Returning empty vector.";
			return std::vector<std::vector<double>>();
		}

		std::vector<std::vector<double>> class_feature_data = feature_data_[class_label];
		for (std::size_t i = 0; i < class_feature_data.size(); ++i) {
			class_feature_data[i].push_back(class_label+1);
		}
        return class_feature_data;
    }

    bool RealTimeMultiClassifier::is_trained() {
        return trained_;
    }

    std::size_t RealTimeMultiClassifier::get_sample_dim() const {
        return sample_dim_;
    }

    std::size_t RealTimeMultiClassifier::get_feature_dim() const {
        return sample_dim_;
    }

	void RealTimeMultiClassifier::set_class_count(std::size_t class_count) {
		class_count = class_count < 2 ? 2 : class_count;
		if (class_count_ != class_count) {
			class_count_ = class_count;
			training_data_.resize(class_count);
			feature_data_.resize(class_count);
			w_.resize(class_count);
			w_0_.resize(class_count);
			y_.resize(class_count);
			p_.resize(class_count);
			trained_ = false;
		}
	}

    std::vector<double> RealTimeMultiClassifier::feature_extraction(const std::vector<std::vector<double>>& signal) const {
        if (signal.empty()) {
            LOG(Warning) << "Input given to RealTimeMultiClassifier::feature_extraction() is empty. Returning empty vector.";
            return std::vector<double>();
        }
        return signal[0];
    }

    std::size_t RealTimeMultiClassifier::classification_heuristic(const std::vector<std::vector<double>>& probabilities) const {
        return majority_vote(activation_function(probabilities));
    }

    std::vector<std::size_t> RealTimeMultiClassifier::activation_function(const std::vector<std::vector<double>>& probabilities) const {
        std::vector<std::size_t> labels(probabilities.size());
        for (std::size_t i = 0; i < probabilities.size(); ++i) {
            labels[i] = std::distance(probabilities[i].begin(), std::max_element(probabilities[i].begin(), probabilities[i].end()));
        }
        return labels;
    }

    std::size_t RealTimeMultiClassifier::majority_vote(const std::vector<std::size_t>& labels) const {
        std::vector<std::size_t> votes(class_count_, 0);
        for (std::size_t i = 0; i < labels.size(); ++i) {
            votes[labels[i]]++;
        }
        return std::distance(votes.begin(), std::max_element(votes.begin(), votes.end()));
    }

} // namespace meii<|endoftext|>


<commit_before>#ifndef VIEWPORT_HPP_INCLUDED
#define VIEWPORT_HPP_INCLUDED

namespace gst
{
    class Resolution;

    class Viewport {
    public:
        Viewport();
        Viewport(Resolution resolution);
        Viewport(unsigned int width, unsigned int height);
        Viewport(int x, int y, unsigned int width, unsigned int height);

        bool operator==(Viewport const & other) const;
        bool operator!=(Viewport const & other) const;

        int get_x() const;
        int get_y() const;
        int get_width() const;
        int get_height() const;
    private:
        int x;
        int y;
        unsigned int width;
        unsigned int height;
    };
}

#endif
<commit_msg>add viewport documentation<commit_after>#ifndef VIEWPORT_HPP_INCLUDED
#define VIEWPORT_HPP_INCLUDED

namespace gst
{
    class Resolution;

    // The responsibility of this class is to describe a viewport shape.
    class Viewport {
    public:
        Viewport();
        Viewport(Resolution resolution);
        Viewport(unsigned int width, unsigned int height);
        Viewport(int x, int y, unsigned int width, unsigned int height);

        // Return true if specified viewport is equal to this viewport, false
        // otherwise.
        bool operator==(Viewport const & other) const;
        // Return true if specified viewport is not equal to this viewport,
        // false otherwise.
        bool operator!=(Viewport const & other) const;

        // Return x component.
        int get_x() const;
        // Return y component.
        int get_y() const;
        // Return width component.
        int get_width() const;
        // Return height component.
        int get_height() const;
    private:
        int x;
        int y;
        unsigned int width;
        unsigned int height;
    };
}

#endif
<|endoftext|>


<commit_before>// Copyright 2014 Toggl Desktop developers.

#include "./workspace.h"

#include <sstream>

namespace kopsik {

std::string Workspace::String() {
  std::stringstream ss;
  ss  << "ID=" << id_
      << " local_id=" << local_id_
      << " name=" << name_;
  return ss.str();
}

void Workspace::SetUID(Poco::UInt64 value) {
  if (uid_ != value) {
    uid_ = value;
    dirty_ = true;
  }
}

void Workspace::SetID(Poco::UInt64 value) {
  if (id_ != value) {
    id_ = value;
    dirty_ = true;
  }
}

void Workspace::SetName(std::string value) {
  if (name_ != value) {
    name_ = value;
    dirty_ = true;
  }
}

void Workspace::SetPremium(const bool value) {
  if (premium_ != value) {
    premium_ = value;
    dirty_ = true;
  }
}

bool CompareWorkspaceByName(Workspace *a, Workspace *b) {
  return (strcmp(a->Name().c_str(), b->Name().c_str()) < 0);
}

}   // namespace kopsik
<commit_msg>Fix strcmp include (lib)<commit_after>// Copyright 2014 Toggl Desktop developers.

#include "./workspace.h"

#include <sstream>
#include <cstring>

namespace kopsik {

std::string Workspace::String() {
  std::stringstream ss;
  ss  << "ID=" << id_
      << " local_id=" << local_id_
      << " name=" << name_;
  return ss.str();
}

void Workspace::SetUID(Poco::UInt64 value) {
  if (uid_ != value) {
    uid_ = value;
    dirty_ = true;
  }
}

void Workspace::SetID(Poco::UInt64 value) {
  if (id_ != value) {
    id_ = value;
    dirty_ = true;
  }
}

void Workspace::SetName(std::string value) {
  if (name_ != value) {
    name_ = value;
    dirty_ = true;
  }
}

void Workspace::SetPremium(const bool value) {
  if (premium_ != value) {
    premium_ = value;
    dirty_ = true;
  }
}

bool CompareWorkspaceByName(Workspace *a, Workspace *b) {
  return (strcmp(a->Name().c_str(), b->Name().c_str()) < 0);
}

}   // namespace kopsik
<|endoftext|>


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

//mapnik
#include <mapnik/xml_tree.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/enumeration.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/gamma_method.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/line_symbolizer.hpp>
#include <mapnik/line_pattern_symbolizer.hpp>
#include <mapnik/polygon_pattern_symbolizer.hpp>
#include <mapnik/point_symbolizer.hpp>
#include <mapnik/markers_symbolizer.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/text_properties.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/raster_colorizer.hpp>

//boost
#include <boost/lexical_cast.hpp>

namespace mapnik
{

template <typename T>
inline boost::optional<T> fast_cast(xml_tree const& tree, std::string const& value)
{
    try
    {
        return boost::lexical_cast<T>(value);
    }
    catch (boost::bad_lexical_cast const& ex)
    {
        return boost::optional<T>();
    }
}

template <>
inline boost::optional<int> fast_cast(xml_tree const& tree, std::string const& value)
{
    int result;
    if (mapnik::util::string2int(value, result))
        return boost::optional<int>(result);
    return boost::optional<int>();
}

template <>
inline boost::optional<double> fast_cast(xml_tree const& tree, std::string const& value)
{
    double result;
    if (mapnik::util::string2double(value, result))
        return boost::optional<double>(result);
    return boost::optional<double>();
}

template <>
inline boost::optional<float> fast_cast(xml_tree const& tree, std::string const& value)
{
    float result;
    if (mapnik::util::string2float(value, result))
        return boost::optional<float>(result);
    return boost::optional<float>();
}

template <>
inline boost::optional<std::string> fast_cast(xml_tree const& tree, std::string const& value)
{
    return value;
}

template <>
inline boost::optional<color> fast_cast(xml_tree const& tree, std::string const& value)
{
    return parse_color(value, tree.color_grammar);
}

template <>
inline boost::optional<expression_ptr> fast_cast(xml_tree const& tree, std::string const& value)
{
    return parse_expression(value, tree.expr_grammar);
}

/****************************************************************************/

class boolean;
template <typename T>
struct name_trait
{
    static std::string name()
    {
        return "<unknown>";
    }
    // missing name_trait for type ...
    // if you get here you are probably using a new type
    // in the XML file. Just add a name trait for the new
    // type below.
    BOOST_STATIC_ASSERT( sizeof(T) == 0 );
};

#define DEFINE_NAME_TRAIT( type, type_name )                            \
    template <>                                                         \
    struct name_trait<type>                                             \
    {                                                                   \
        static std::string name() { return std::string("type ") + type_name; } \
    };

DEFINE_NAME_TRAIT( double, "double")
DEFINE_NAME_TRAIT( float, "float")
DEFINE_NAME_TRAIT( unsigned, "unsigned")
DEFINE_NAME_TRAIT( boolean, "boolean")
#ifdef BIGINT
DEFINE_NAME_TRAIT( mapnik::value_integer, "long long" )
#else
DEFINE_NAME_TRAIT( mapnik::value_integer, "int" )
#endif
DEFINE_NAME_TRAIT( std::string, "string" )
DEFINE_NAME_TRAIT( color, "color" )
DEFINE_NAME_TRAIT(expression_ptr, "expression_ptr" )

template <typename ENUM, int MAX>
struct name_trait< mapnik::enumeration<ENUM, MAX> >
{
    typedef enumeration<ENUM, MAX> Enum;

    static std::string name()
    {
        std::string value_list("one of [");
        for (unsigned i = 0; i < Enum::MAX; ++i)
        {
            value_list += Enum::get_string( i );
            if ( i + 1 < Enum::MAX ) value_list += ", ";
        }
        value_list += "]";

        return value_list;
    }
};

/****************************************************************************/

xml_tree::xml_tree(std::string const& encoding)
    : node_(*this, "<root>"),
      file_(),
      tr_(encoding),
      color_grammar(),
      expr_grammar(tr_),
      path_expr_grammar(),
      transform_expr_grammar(expr_grammar),
      image_filters_grammar()
{
    node_.set_processed(true); //root node is always processed
}

void xml_tree::set_filename(std::string fn)
{
    file_ = fn;
}

std::string const& xml_tree::filename() const
{
    return file_;
}

xml_node &xml_tree::root()
{
    return node_;
}

const xml_node &xml_tree::root() const
{
    return node_;
}

/****************************************************************************/
xml_attribute::xml_attribute(std::string const& value_)
    : value(value_), processed(false)
{

}

/****************************************************************************/

node_not_found::node_not_found(std::string const& node_name)
    : node_name_(node_name)
{

}

const char* node_not_found::what() const throw()
{
    return ("Node "+node_name_+ "not found").c_str();
}

node_not_found::~node_not_found() throw()
{

}

attribute_not_found::attribute_not_found(
    std::string const& node_name,
    std::string const& attribute_name)
    :
    node_name_(node_name),
    attribute_name_(attribute_name)
{

}

const char* attribute_not_found::what() const throw()
{
    return ("Attribute '" + attribute_name_ +"' not found in node '"+node_name_+ "'").c_str();
}

attribute_not_found::~attribute_not_found() throw()
{

}

more_than_one_child::more_than_one_child(std::string const& node_name)
    : node_name_(node_name)
{

}

const char* more_than_one_child::what() const throw()
{
    return ("More than one child node in node '" + node_name_ +"'").c_str();
}

more_than_one_child::~more_than_one_child() throw()
{

}

/****************************************************************************/

xml_node::xml_node(xml_tree &tree, std::string const& name, unsigned line, bool is_text)
    : tree_(tree),
      name_(name),
      is_text_(is_text),
      line_(line),
      processed_(false)
{

}

std::string xml_node::xml_text = "<xmltext>";

std::string const& xml_node::name() const
{
    if (!is_text_)
        return name_;
    else
        return xml_text;
}

std::string const& xml_node::text() const
{
    if (is_text_)
    {
        processed_ = true;
        return name_;
    } else
    {
        throw config_error("text() called on non-text node", *this);
    }
}

std::string const& xml_node::filename() const
{
    return tree_.filename();
}

bool xml_node::is_text() const
{
    return is_text_;
}

bool xml_node::is(std::string const& name) const
{
    if (name_ == name)
    {
        processed_ = true;
        return true;
    }
    return false;
}

xml_node &xml_node::add_child(std::string const& name, unsigned line, bool is_text)
{
    children_.push_back(xml_node(tree_, name, line, is_text));
    return children_.back();
}

void xml_node::add_attribute(std::string const& name, std::string const& value)
{
    attributes_.insert(std::make_pair(name,xml_attribute(value)));
}

xml_node::attribute_map const& xml_node::get_attributes() const
{
    return attributes_;
}

void xml_node::set_processed(bool processed) const
{
    processed_ = processed;
}

bool xml_node::processed() const
{
    return processed_;
}

xml_node::const_iterator xml_node::begin() const
{
    return children_.begin();
}

xml_node::const_iterator xml_node::end() const
{
    return children_.end();
}

xml_node & xml_node::get_child(std::string const& name)
{
    std::list<xml_node>::iterator itr = children_.begin();
    std::list<xml_node>::iterator end = children_.end();
    for (; itr != end; itr++)
    {
        if (!(itr->is_text_) && itr->name_ == name)
        {
            itr->set_processed(true);
            return *itr;
        }
    }
    throw node_not_found(name);
}

xml_node const& xml_node::get_child(std::string const& name) const
{
    xml_node const* node = get_opt_child(name);
    if (!node) throw node_not_found(name);
    return *node;
}

xml_node const* xml_node::get_opt_child(std::string const& name) const
{
    const_iterator itr = children_.begin();
    const_iterator end = children_.end();
    for (; itr != end; itr++)
    {
        if (!(itr->is_text_) && itr->name_ == name)
        {
            itr->set_processed(true);
            return &(*itr);
        }
    }
    return 0;
}

bool xml_node::has_child(std::string const& name) const
{
    return get_opt_child(name) != 0;
}

template <typename T>
boost::optional<T> xml_node::get_opt_attr(std::string const& name) const
{
    std::map<std::string, xml_attribute>::const_iterator itr = attributes_.find(name);
    if (itr ==  attributes_.end()) return boost::optional<T>();
    itr->second.processed = true;
    boost::optional<T> result = fast_cast<T>(tree_, itr->second.value);
    if (!result)
    {
        throw config_error(std::string("Failed to parse attribute '") +
                           name + "'. Expected " + name_trait<T>::name() +
                           " but got '" + itr->second.value + "'", *this);
    }
    return result;
}

template <typename T>
T xml_node::get_attr(std::string const& name, T const& default_opt_value) const
{
    boost::optional<T> value = get_opt_attr<T>(name);
    if (value) return *value;
    return default_opt_value;
}

template <typename T>
T xml_node::get_attr(std::string const& name) const
{
    boost::optional<T> value = get_opt_attr<T>(name);
    if (value) return *value;
    throw attribute_not_found(name_, name);
}

std::string xml_node::get_text() const
{
    if (children_.size() == 0)
    {
        if (is_text_)
        {
            return name_;
        } else
        {
            return "";
        }
    }
    if (children_.size() == 1)
    {
        return children_.front().text();
    }
    throw more_than_one_child(name_);
}

template <typename T>
T xml_node::get_value() const
{
    boost::optional<T> result = fast_cast<T>(tree_, get_text());
    if (!result)
    {
        throw config_error(std::string("Failed to parse value. Expected ")
                           + name_trait<T>::name() +
                           " but got '" + get_text() + "'", *this);
    }
    return *result;
}

unsigned xml_node::line() const
{
    return line_;
}

std::string xml_node::line_to_string() const
{
    std::string number;
    util::to_string(number,line_);
    return number;
}

#define compile_get_opt_attr(T) template boost::optional<T> xml_node::get_opt_attr<T>(std::string const&) const
#define compile_get_attr(T) template T xml_node::get_attr<T>(std::string const&) const; template T xml_node::get_attr<T>(std::string const&, T const&) const
#define compile_get_value(T) template T xml_node::get_value<T>() const

compile_get_opt_attr(boolean);
compile_get_opt_attr(std::string);
compile_get_opt_attr(unsigned);
compile_get_opt_attr(mapnik::value_integer);
compile_get_opt_attr(float);
compile_get_opt_attr(double);
compile_get_opt_attr(color);
compile_get_opt_attr(gamma_method_e);
compile_get_opt_attr(line_join_e);
compile_get_opt_attr(line_cap_e);
compile_get_opt_attr(text_transform_e);
compile_get_opt_attr(label_placement_e);
compile_get_opt_attr(vertical_alignment_e);
compile_get_opt_attr(horizontal_alignment_e);
compile_get_opt_attr(justify_alignment_e);
compile_get_opt_attr(expression_ptr);
compile_get_attr(std::string);
compile_get_attr(filter_mode_e);
compile_get_attr(point_placement_e);
compile_get_attr(marker_placement_e);
compile_get_attr(marker_multi_policy_e);
compile_get_attr(pattern_alignment_e);
compile_get_attr(line_rasterizer_e);
compile_get_attr(colorizer_mode);
compile_get_attr(double);
compile_get_value(value_integer);
compile_get_value(double);
compile_get_value(expression_ptr);
} //ns mapnik
<commit_msg>+ fast_cast to mapnik::boolean specialization<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2012 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//mapnik
#include <mapnik/xml_tree.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/enumeration.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/gamma_method.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/line_symbolizer.hpp>
#include <mapnik/line_pattern_symbolizer.hpp>
#include <mapnik/polygon_pattern_symbolizer.hpp>
#include <mapnik/point_symbolizer.hpp>
#include <mapnik/markers_symbolizer.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/text_properties.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/raster_colorizer.hpp>

//boost
#include <boost/lexical_cast.hpp>

namespace mapnik
{

template <typename T>
inline boost::optional<T> fast_cast(xml_tree const& tree, std::string const& value)
{
    try
    {
        return boost::lexical_cast<T>(value);
    }
    catch (boost::bad_lexical_cast const& ex)
    {
        return boost::optional<T>();
    }
}

template <>
inline boost::optional<mapnik::boolean> fast_cast(xml_tree const& tree, std::string const& value)
{
    bool result;
    if (mapnik::util::string2bool(value, result))
        return boost::optional<mapnik::boolean>(result);
    return boost::optional<mapnik::boolean>();
}

template <>
inline boost::optional<int> fast_cast(xml_tree const& tree, std::string const& value)
{
    int result;
    if (mapnik::util::string2int(value, result))
        return boost::optional<int>(result);
    return boost::optional<int>();
}

template <>
inline boost::optional<double> fast_cast(xml_tree const& tree, std::string const& value)
{
    double result;
    if (mapnik::util::string2double(value, result))
        return boost::optional<double>(result);
    return boost::optional<double>();
}

template <>
inline boost::optional<float> fast_cast(xml_tree const& tree, std::string const& value)
{
    float result;
    if (mapnik::util::string2float(value, result))
        return boost::optional<float>(result);
    return boost::optional<float>();
}

template <>
inline boost::optional<std::string> fast_cast(xml_tree const& tree, std::string const& value)
{
    return value;
}

template <>
inline boost::optional<color> fast_cast(xml_tree const& tree, std::string const& value)
{
    return parse_color(value, tree.color_grammar);
}

template <>
inline boost::optional<expression_ptr> fast_cast(xml_tree const& tree, std::string const& value)
{
    return parse_expression(value, tree.expr_grammar);
}

/****************************************************************************/

class boolean;
template <typename T>
struct name_trait
{
    static std::string name()
    {
        return "<unknown>";
    }
    // missing name_trait for type ...
    // if you get here you are probably using a new type
    // in the XML file. Just add a name trait for the new
    // type below.
    BOOST_STATIC_ASSERT( sizeof(T) == 0 );
};

#define DEFINE_NAME_TRAIT( type, type_name )                            \
    template <>                                                         \
    struct name_trait<type>                                             \
    {                                                                   \
        static std::string name() { return std::string("type ") + type_name; } \
    };

DEFINE_NAME_TRAIT( double, "double")
DEFINE_NAME_TRAIT( float, "float")
DEFINE_NAME_TRAIT( unsigned, "unsigned")
DEFINE_NAME_TRAIT( boolean, "boolean")
#ifdef BIGINT
DEFINE_NAME_TRAIT( mapnik::value_integer, "long long" )
#else
DEFINE_NAME_TRAIT( mapnik::value_integer, "int" )
#endif
DEFINE_NAME_TRAIT( std::string, "string" )
DEFINE_NAME_TRAIT( color, "color" )
DEFINE_NAME_TRAIT(expression_ptr, "expression_ptr" )

template <typename ENUM, int MAX>
struct name_trait< mapnik::enumeration<ENUM, MAX> >
{
    typedef enumeration<ENUM, MAX> Enum;

    static std::string name()
    {
        std::string value_list("one of [");
        for (unsigned i = 0; i < Enum::MAX; ++i)
        {
            value_list += Enum::get_string( i );
            if ( i + 1 < Enum::MAX ) value_list += ", ";
        }
        value_list += "]";

        return value_list;
    }
};

/****************************************************************************/

xml_tree::xml_tree(std::string const& encoding)
    : node_(*this, "<root>"),
      file_(),
      tr_(encoding),
      color_grammar(),
      expr_grammar(tr_),
      path_expr_grammar(),
      transform_expr_grammar(expr_grammar),
      image_filters_grammar()
{
    node_.set_processed(true); //root node is always processed
}

void xml_tree::set_filename(std::string fn)
{
    file_ = fn;
}

std::string const& xml_tree::filename() const
{
    return file_;
}

xml_node &xml_tree::root()
{
    return node_;
}

const xml_node &xml_tree::root() const
{
    return node_;
}

/****************************************************************************/
xml_attribute::xml_attribute(std::string const& value_)
    : value(value_), processed(false)
{

}

/****************************************************************************/

node_not_found::node_not_found(std::string const& node_name)
    : node_name_(node_name)
{

}

const char* node_not_found::what() const throw()
{
    return ("Node "+node_name_+ "not found").c_str();
}

node_not_found::~node_not_found() throw()
{

}

attribute_not_found::attribute_not_found(
    std::string const& node_name,
    std::string const& attribute_name)
    :
    node_name_(node_name),
    attribute_name_(attribute_name)
{

}

const char* attribute_not_found::what() const throw()
{
    return ("Attribute '" + attribute_name_ +"' not found in node '"+node_name_+ "'").c_str();
}

attribute_not_found::~attribute_not_found() throw()
{

}

more_than_one_child::more_than_one_child(std::string const& node_name)
    : node_name_(node_name)
{

}

const char* more_than_one_child::what() const throw()
{
    return ("More than one child node in node '" + node_name_ +"'").c_str();
}

more_than_one_child::~more_than_one_child() throw()
{

}

/****************************************************************************/

xml_node::xml_node(xml_tree &tree, std::string const& name, unsigned line, bool is_text)
    : tree_(tree),
      name_(name),
      is_text_(is_text),
      line_(line),
      processed_(false)
{

}

std::string xml_node::xml_text = "<xmltext>";

std::string const& xml_node::name() const
{
    if (!is_text_)
        return name_;
    else
        return xml_text;
}

std::string const& xml_node::text() const
{
    if (is_text_)
    {
        processed_ = true;
        return name_;
    } else
    {
        throw config_error("text() called on non-text node", *this);
    }
}

std::string const& xml_node::filename() const
{
    return tree_.filename();
}

bool xml_node::is_text() const
{
    return is_text_;
}

bool xml_node::is(std::string const& name) const
{
    if (name_ == name)
    {
        processed_ = true;
        return true;
    }
    return false;
}

xml_node &xml_node::add_child(std::string const& name, unsigned line, bool is_text)
{
    children_.push_back(xml_node(tree_, name, line, is_text));
    return children_.back();
}

void xml_node::add_attribute(std::string const& name, std::string const& value)
{
    attributes_.insert(std::make_pair(name,xml_attribute(value)));
}

xml_node::attribute_map const& xml_node::get_attributes() const
{
    return attributes_;
}

void xml_node::set_processed(bool processed) const
{
    processed_ = processed;
}

bool xml_node::processed() const
{
    return processed_;
}

xml_node::const_iterator xml_node::begin() const
{
    return children_.begin();
}

xml_node::const_iterator xml_node::end() const
{
    return children_.end();
}

xml_node & xml_node::get_child(std::string const& name)
{
    std::list<xml_node>::iterator itr = children_.begin();
    std::list<xml_node>::iterator end = children_.end();
    for (; itr != end; itr++)
    {
        if (!(itr->is_text_) && itr->name_ == name)
        {
            itr->set_processed(true);
            return *itr;
        }
    }
    throw node_not_found(name);
}

xml_node const& xml_node::get_child(std::string const& name) const
{
    xml_node const* node = get_opt_child(name);
    if (!node) throw node_not_found(name);
    return *node;
}

xml_node const* xml_node::get_opt_child(std::string const& name) const
{
    const_iterator itr = children_.begin();
    const_iterator end = children_.end();
    for (; itr != end; itr++)
    {
        if (!(itr->is_text_) && itr->name_ == name)
        {
            itr->set_processed(true);
            return &(*itr);
        }
    }
    return 0;
}

bool xml_node::has_child(std::string const& name) const
{
    return get_opt_child(name) != 0;
}

template <typename T>
boost::optional<T> xml_node::get_opt_attr(std::string const& name) const
{
    std::map<std::string, xml_attribute>::const_iterator itr = attributes_.find(name);
    if (itr ==  attributes_.end()) return boost::optional<T>();
    itr->second.processed = true;
    boost::optional<T> result = fast_cast<T>(tree_, itr->second.value);
    if (!result)
    {
        throw config_error(std::string("Failed to parse attribute '") +
                           name + "'. Expected " + name_trait<T>::name() +
                           " but got '" + itr->second.value + "'", *this);
    }
    return result;
}

template <typename T>
T xml_node::get_attr(std::string const& name, T const& default_opt_value) const
{
    boost::optional<T> value = get_opt_attr<T>(name);
    if (value) return *value;
    return default_opt_value;
}

template <typename T>
T xml_node::get_attr(std::string const& name) const
{
    boost::optional<T> value = get_opt_attr<T>(name);
    if (value) return *value;
    throw attribute_not_found(name_, name);
}

std::string xml_node::get_text() const
{
    if (children_.size() == 0)
    {
        if (is_text_)
        {
            return name_;
        } else
        {
            return "";
        }
    }
    if (children_.size() == 1)
    {
        return children_.front().text();
    }
    throw more_than_one_child(name_);
}

template <typename T>
T xml_node::get_value() const
{
    boost::optional<T> result = fast_cast<T>(tree_, get_text());
    if (!result)
    {
        throw config_error(std::string("Failed to parse value. Expected ")
                           + name_trait<T>::name() +
                           " but got '" + get_text() + "'", *this);
    }
    return *result;
}

unsigned xml_node::line() const
{
    return line_;
}

std::string xml_node::line_to_string() const
{
    std::string number;
    util::to_string(number,line_);
    return number;
}

#define compile_get_opt_attr(T) template boost::optional<T> xml_node::get_opt_attr<T>(std::string const&) const
#define compile_get_attr(T) template T xml_node::get_attr<T>(std::string const&) const; template T xml_node::get_attr<T>(std::string const&, T const&) const
#define compile_get_value(T) template T xml_node::get_value<T>() const

compile_get_opt_attr(boolean);
compile_get_opt_attr(std::string);
compile_get_opt_attr(unsigned);
compile_get_opt_attr(mapnik::value_integer);
compile_get_opt_attr(float);
compile_get_opt_attr(double);
compile_get_opt_attr(color);
compile_get_opt_attr(gamma_method_e);
compile_get_opt_attr(line_join_e);
compile_get_opt_attr(line_cap_e);
compile_get_opt_attr(text_transform_e);
compile_get_opt_attr(label_placement_e);
compile_get_opt_attr(vertical_alignment_e);
compile_get_opt_attr(horizontal_alignment_e);
compile_get_opt_attr(justify_alignment_e);
compile_get_opt_attr(expression_ptr);
compile_get_attr(std::string);
compile_get_attr(filter_mode_e);
compile_get_attr(point_placement_e);
compile_get_attr(marker_placement_e);
compile_get_attr(marker_multi_policy_e);
compile_get_attr(pattern_alignment_e);
compile_get_attr(line_rasterizer_e);
compile_get_attr(colorizer_mode);
compile_get_attr(double);
compile_get_value(value_integer);
compile_get_value(double);
compile_get_value(expression_ptr);
} //ns mapnik
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  main.cc
//  yakc app main source.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Synth/Synth.h"
#include "Input/Input.h"
#include "IO/IO.h"
#include "KC85Oryol.h"
#include "Draw.h"
#include "Audio.h"
#if YAKC_UI
#include "ui/UI.h"
#endif
#include "HTTP/HTTPFileSystem.h"

using namespace Oryol;
using namespace yakc;

class YakcApp : public App {
public:
    AppState::Code OnInit();
    AppState::Code OnRunning();
    AppState::Code OnCleanup();
    void handleInput();

    ubyte last_ascii = 0;
    Id drawState;
    kc85 kc;
    Draw draw;
    Audio audio;
    #if YAKC_UI
    UI ui;
    #endif
};
OryolMain(YakcApp);

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnInit() {

    // setup IO system for loading from webserver
    #if ORYOL_DEBUG
    String baseUrl = "http://localhost:8000/";
    #elif ORYOL_EMSCRIPTEN
    // ok, this is strange, why is the github URL different from Oryol??
    String baseUrl = "http://floooh.github.com/";
    #else
    String baseUrl = "http://floooh.github.com/virtualkc/";
    #endif
    IOSetup ioSetup;
    ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
    ioSetup.Assigns.Add("kcc:", baseUrl);
    IO::Setup(ioSetup);

    // we only need few resources, so don't waste memory
    const int frameSize = 10;
    const int width = 2*frameSize + 2*320;
    const int height = 2*frameSize + 2*256;
    auto gfxSetup = GfxSetup::Window(width, height, "KC85");
    gfxSetup.SetPoolSize(GfxResourceType::Mesh, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Texture, 4);
    gfxSetup.SetPoolSize(GfxResourceType::DrawState, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Shader, 4);
    Gfx::Setup(gfxSetup);
    Input::Setup();
    Input::BeginCaptureText();

    Synth::Setup(SynthSetup());

    #if YAKC_UI
    this->ui.Setup(this->kc);
    #endif
    this->kc.poweron(kc85_model::kc85_3, kc85_caos::caos_3_1);
    this->draw.Setup(gfxSetup, frameSize);
    this->audio.Setup(this->kc);

    // on KC85/3 put a 16kByte module into slot 8 by default, CAOS will initialize
    // this automatically on startup
    // FIXME: find a better way to setup complete computer configs
    this->kc.exp.insert_module(0x08,kc85_module::create_ram(0xF4, 0xC0, 0x4000,
        "M022 EXPANDER RAM",
        "16 KByte RAM expansion module.\n\n"
        "SWITCH [SLOT] 43: map to address 0x4000\n"
        "SWITCH [SLOT] 83: map to address 0x8000\n"
        "SWITCH [SLOT] 00: switch module off\n\n"
        "...where [SLOT] is 08 or 0C"));

    return AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnRunning() {
    Gfx::ApplyDefaultRenderTarget(ClearState::ClearColor(glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)));
    int micro_secs = 1000000 / 60;
    this->handleInput();
    #if YAKC_UI
        this->kc.onframe(this->ui.Settings.cpuSpeed, micro_secs);
        this->draw.fsParams.CRTEffect = this->ui.Settings.crtEffect;
        this->draw.fsParams.ColorTV = this->ui.Settings.colorTV;
        this->draw.fsParams.CRTWarp = glm::vec2(this->ui.Settings.crtWarp);
    #else
        this->kc.onframe(1, micro_secs);
        this->draw.fsParams.CRTEffect = true;
        this->draw.fsParams.ColorTV = true;
        this->draw.fsParams.CRTWarp = glm::vec2(1.0f/64.0f);
    #endif
    this->draw.Render(this->kc);
    Synth::Update();
    #if YAKC_UI
    this->ui.OnFrame(this->kc);
    #endif
    Gfx::CommitFrame();
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnCleanup() {
    this->audio.Discard();
    this->draw.Discard();
    #if YAKC_UI
    this->ui.Discard();
    #endif
    Synth::Discard();
    Input::Discard();
    Gfx::Discard();
    IO::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
void
YakcApp::handleInput() {
    const Keyboard& kbd = Input::Keyboard();
    const Touchpad& touch = Input::Touchpad();

    #if YAKC_UI
    // don't handle KC input if IMGUI has the keyboard focus
    if (ImGui::GetIO().WantCaptureKeyboard) {
        return;
    }
    // toggle UI?
    if (kbd.KeyDown(Key::Tab) || touch.DoubleTapped) {
        this->ui.Toggle();
    }
    #endif

    const wchar_t* text = kbd.CapturedText();
    ubyte ascii = 0;

    // alpha-numerics
    if (text[0] && (text[0] >= 32) && (text[0] < 127)) {
        ascii = (ubyte) text[0];
        // shift is inverted on KC
        if (islower(ascii)) {
            ascii = toupper(ascii);
        }
        else if (isupper(ascii)) {
            ascii = tolower(ascii);
        }
    }
    if ((ascii == 0) && (kbd.AnyKeyPressed())) {
        ascii = this->last_ascii;
    }
    this->last_ascii = ascii;

    // special keys
    struct toAscii {
        Key::Code key;
        ubyte ascii;
    };
    const static toAscii keyTable[] = {
        // FIXME:
        //  HOME, PAGE UP/DOWN, START/END of line, INSERT,
        { Key::Left, 0x08 },
        { Key::Right, 0x09 },
        { Key::Down, 0x0A },
        { Key::Up, 0x0B },
        { Key::Enter, 0x0D },
        { Key::BackSpace, 0x01 },
        { Key::Escape, 0x03 },
        { Key::F1, 0xF1 },
        { Key::F2, 0xF2 },
        { Key::F3, 0xF3 },
        { Key::F4, 0xF4 },
        { Key::F5, 0xF5 },
        { Key::F6, 0xF6 },
        { Key::F7, 0xF7 },
        { Key::F8, 0xF8 },
        { Key::F9, 0xF9 },
        { Key::F10, 0xFA },
        { Key::F11, 0xFB },
        { Key::F12, 0xFC },
    };
    for (const auto& key : keyTable) {
        if (kbd.KeyPressed(key.key)) {
            // special case: shift-backspace clears screen shift-escape is STP
            if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::BackSpace)) {
                ascii = 0x0C;
            }
            else if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::Escape)) {
                ascii = 0x13;
            }
            else {
                ascii = key.ascii;
            }
            break;
        }
    }
    this->kc.put_key(ascii);
}
<commit_msg>Boot into KC85/4 by default<commit_after>//------------------------------------------------------------------------------
//  main.cc
//  yakc app main source.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Synth/Synth.h"
#include "Input/Input.h"
#include "IO/IO.h"
#include "KC85Oryol.h"
#include "Draw.h"
#include "Audio.h"
#if YAKC_UI
#include "ui/UI.h"
#endif
#include "HTTP/HTTPFileSystem.h"

using namespace Oryol;
using namespace yakc;

class YakcApp : public App {
public:
    AppState::Code OnInit();
    AppState::Code OnRunning();
    AppState::Code OnCleanup();
    void handleInput();

    ubyte last_ascii = 0;
    Id drawState;
    kc85 kc;
    Draw draw;
    Audio audio;
    #if YAKC_UI
    UI ui;
    #endif
};
OryolMain(YakcApp);

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnInit() {

    // setup IO system for loading from webserver
    #if ORYOL_DEBUG
    String baseUrl = "http://localhost:8000/";
    #elif ORYOL_EMSCRIPTEN
    // ok, this is strange, why is the github URL different from Oryol??
    String baseUrl = "http://floooh.github.com/";
    #else
    String baseUrl = "http://floooh.github.com/virtualkc/";
    #endif
    IOSetup ioSetup;
    ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
    ioSetup.Assigns.Add("kcc:", baseUrl);
    IO::Setup(ioSetup);

    // we only need few resources, so don't waste memory
    const int frameSize = 10;
    const int width = 2*frameSize + 2*320;
    const int height = 2*frameSize + 2*256;
    auto gfxSetup = GfxSetup::Window(width, height, "KC85");
    gfxSetup.SetPoolSize(GfxResourceType::Mesh, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Texture, 4);
    gfxSetup.SetPoolSize(GfxResourceType::DrawState, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Shader, 4);
    Gfx::Setup(gfxSetup);
    Input::Setup();
    Input::BeginCaptureText();

    Synth::Setup(SynthSetup());

    #if YAKC_UI
    this->ui.Setup(this->kc);
    #endif
    this->kc.poweron(kc85_model::kc85_4, kc85_caos::caos_4_2);
    this->draw.Setup(gfxSetup, frameSize);
    this->audio.Setup(this->kc);

    // on KC85/3 put a 16kByte module into slot 8 by default, CAOS will initialize
    // this automatically on startup
    // FIXME: find a better way to setup complete computer configs
    this->kc.exp.insert_module(0x08,kc85_module::create_ram(0xF4, 0xC0, 0x4000,
        "M022 EXPANDER RAM",
        "16 KByte RAM expansion module.\n\n"
        "SWITCH [SLOT] 43: map to address 0x4000\n"
        "SWITCH [SLOT] 83: map to address 0x8000\n"
        "SWITCH [SLOT] 00: switch module off\n\n"
        "...where [SLOT] is 08 or 0C"));

    return AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnRunning() {
    Gfx::ApplyDefaultRenderTarget(ClearState::ClearColor(glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)));
    int micro_secs = 1000000 / 60;
    this->handleInput();
    #if YAKC_UI
        this->kc.onframe(this->ui.Settings.cpuSpeed, micro_secs);
        this->draw.fsParams.CRTEffect = this->ui.Settings.crtEffect;
        this->draw.fsParams.ColorTV = this->ui.Settings.colorTV;
        this->draw.fsParams.CRTWarp = glm::vec2(this->ui.Settings.crtWarp);
    #else
        this->kc.onframe(1, micro_secs);
        this->draw.fsParams.CRTEffect = true;
        this->draw.fsParams.ColorTV = true;
        this->draw.fsParams.CRTWarp = glm::vec2(1.0f/64.0f);
    #endif
    this->draw.Render(this->kc);
    Synth::Update();
    #if YAKC_UI
    this->ui.OnFrame(this->kc);
    #endif
    Gfx::CommitFrame();
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnCleanup() {
    this->audio.Discard();
    this->draw.Discard();
    #if YAKC_UI
    this->ui.Discard();
    #endif
    Synth::Discard();
    Input::Discard();
    Gfx::Discard();
    IO::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
void
YakcApp::handleInput() {
    const Keyboard& kbd = Input::Keyboard();
    const Touchpad& touch = Input::Touchpad();

    #if YAKC_UI
    // don't handle KC input if IMGUI has the keyboard focus
    if (ImGui::GetIO().WantCaptureKeyboard) {
        return;
    }
    // toggle UI?
    if (kbd.KeyDown(Key::Tab) || touch.DoubleTapped) {
        this->ui.Toggle();
    }
    #endif

    const wchar_t* text = kbd.CapturedText();
    ubyte ascii = 0;

    // alpha-numerics
    if (text[0] && (text[0] >= 32) && (text[0] < 127)) {
        ascii = (ubyte) text[0];
        // shift is inverted on KC
        if (islower(ascii)) {
            ascii = toupper(ascii);
        }
        else if (isupper(ascii)) {
            ascii = tolower(ascii);
        }
    }
    if ((ascii == 0) && (kbd.AnyKeyPressed())) {
        ascii = this->last_ascii;
    }
    this->last_ascii = ascii;

    // special keys
    struct toAscii {
        Key::Code key;
        ubyte ascii;
    };
    const static toAscii keyTable[] = {
        // FIXME:
        //  HOME, PAGE UP/DOWN, START/END of line, INSERT,
        { Key::Left, 0x08 },
        { Key::Right, 0x09 },
        { Key::Down, 0x0A },
        { Key::Up, 0x0B },
        { Key::Enter, 0x0D },
        { Key::BackSpace, 0x01 },
        { Key::Escape, 0x03 },
        { Key::F1, 0xF1 },
        { Key::F2, 0xF2 },
        { Key::F3, 0xF3 },
        { Key::F4, 0xF4 },
        { Key::F5, 0xF5 },
        { Key::F6, 0xF6 },
        { Key::F7, 0xF7 },
        { Key::F8, 0xF8 },
        { Key::F9, 0xF9 },
        { Key::F10, 0xFA },
        { Key::F11, 0xFB },
        { Key::F12, 0xFC },
    };
    for (const auto& key : keyTable) {
        if (kbd.KeyPressed(key.key)) {
            // special case: shift-backspace clears screen shift-escape is STP
            if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::BackSpace)) {
                ascii = 0x0C;
            }
            else if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::Escape)) {
                ascii = 0x13;
            }
            else {
                ascii = key.ascii;
            }
            break;
        }
    }
    this->kc.put_key(ascii);
}
<|endoftext|>


<commit_before>#include "Simulation_BFER_turbo.hpp"

#include <map>
#include <chrono>
#include <vector>
#include <string>
#include <utility>
#include <cstdlib>
#include <algorithm>

#include "Tools/Display/bash_tools.h"

#include "Tools/Factory/Factory_interleaver.hpp"
#include "Tools/Factory/RSC/Factory_encoder_RSC.hpp"
#include "Tools/Factory/Turbo/Factory_encoder_turbo.hpp"
#include "Tools/Factory/Turbo/Factory_scaling_factor.hpp"
#include "Tools/Factory/RSC/Factory_decoder_RSC.hpp"
#include "Tools/Factory/Turbo/Factory_decoder_turbo.hpp"

template <typename B, typename R, typename Q, typename QD>
Simulation_BFER_turbo<B,R,Q,QD>
::Simulation_BFER_turbo(const parameters& params)
: Simulation_BFER<B,R,Q>(params),
  interleaver(params.simulation.n_threads, nullptr),
  sub_encoder(params.simulation.n_threads, nullptr),
  siso       (params.simulation.n_threads, nullptr),
  sf         (params.simulation.n_threads, nullptr)
{
	assert(params.code.N / params.code.K == 3);

	for (auto tid = 0; tid < params.simulation.n_threads; tid++)
	{
		auto seed = this->params.simulation.seed;
		seed += (params.interleaver.type == "UNIFORM") ? tid : 0;

		// build the interleaver for the encoder and the decoder
		interleaver[tid] = Factory_interleaver<short>::build(this->params, this->params.code.K, seed);
		Simulation::check_errors(interleaver[tid], "Interleaver<short>");
	}

	if (!params.simulation.json_path.empty())
	{
		assert(params.simulation.n_threads == 1);
		json_stream.open(params.simulation.json_path.c_str(), std::ios::out | std::ios::trunc);

		json_stream << "[" << std::endl;
	}
}

template <typename B, typename R, typename Q, typename QD>
Simulation_BFER_turbo<B,R,Q,QD>
::~Simulation_BFER_turbo()
{
	release_objects();
	if (json_stream.is_open())
	{
		json_stream << "[{\"stage\": \"end\"}]]" << std::endl;
		json_stream.close();
	}
	for (auto tid = 0; tid < this->params.simulation.n_threads; tid++)
		if (interleaver[tid] != nullptr)
			delete interleaver[tid];
}

template <typename B, typename R, typename Q, typename QD>
void Simulation_BFER_turbo<B,R,Q,QD>
::release_objects()
{
	Simulation_BFER<B,R,Q>::release_objects();

	int tid = 0;
	const int nthr = this->params.simulation.n_threads;
	for (tid = 0; tid < nthr; tid++) if (sub_encoder[tid] != nullptr) { delete sub_encoder[tid]; sub_encoder[tid] = nullptr; }
	for (tid = 0; tid < nthr; tid++) if (siso       [tid] != nullptr) { delete siso       [tid]; siso       [tid] = nullptr; }
	for (tid = 0; tid < nthr; tid++) if (sf         [tid] != nullptr) { delete sf         [tid]; sf         [tid] = nullptr; }
}

template <typename B, typename R, typename Q, typename QD>
void Simulation_BFER_turbo<B,R,Q,QD>
::launch_precompute()
{
}

template <typename B, typename R, typename Q, typename QD>
void Simulation_BFER_turbo<B,R,Q,QD>
::snr_precompute()
{
}

template <typename B, typename R, typename Q, typename QD>
Encoder<B>* Simulation_BFER_turbo<B,R,Q,QD>
::build_encoder(const int tid)
{
	sub_encoder[tid] = Factory_encoder_RSC<B>::build(this->params, 1, json_stream);
	Simulation::check_errors(sub_encoder[tid], "Encoder_RSC_sys<B>");

	if (tid == 0)
		trellis = sub_encoder[tid]->get_trellis();

	Encoder<B>* encoder = nullptr;
	if (this->params.simulation.json_path.empty())
		encoder = Simulation_BFER<B,R,Q>::build_encoder(tid);
	if (encoder == nullptr)
		encoder = Factory_encoder_turbo<B>::build(this->params, interleaver[tid], sub_encoder[tid], sub_encoder[tid]);

	return encoder;
}

template <typename B, typename R, typename Q, typename QD>
Decoder<B,Q>* Simulation_BFER_turbo<B,R,Q,QD>
::build_decoder(const int tid)
{
	sf[tid] = Factory_scaling_factor<Q>::build(this->params);
	Simulation::check_errors(sf[tid], "Scaling_factor<Q>");

	this->barrier(tid);
	siso[tid] = Factory_decoder_RSC<B,Q,QD>::build_siso(this->params, trellis, json_stream);
	Simulation::check_errors(siso[tid], "SISO<Q>");

	if (tid == 0)
		interleaver[tid]->set_n_frames(siso[tid]->get_n_frames());

	return Factory_decoder_turbo<B,Q>::build(this->params, interleaver[tid], siso[tid], siso[tid], sf[tid], this->crc[tid]);
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Simulation_BFER_turbo<B_8,R_8,Q_8,QD_8>;
template class Simulation_BFER_turbo<B_16,R_16,Q_16,QD_16>;
template class Simulation_BFER_turbo<B_32,R_32,Q_32,QD_32>;
template class Simulation_BFER_turbo<B_64,R_64,Q_64,QD_64>;
#else
template class Simulation_BFER_turbo<B,R,Q,QD>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Fix a bug when setting the number of frames to process in the interlevers.<commit_after>#include "Simulation_BFER_turbo.hpp"

#include <map>
#include <chrono>
#include <vector>
#include <string>
#include <utility>
#include <cstdlib>
#include <algorithm>

#include "Tools/Display/bash_tools.h"

#include "Tools/Factory/Factory_interleaver.hpp"
#include "Tools/Factory/RSC/Factory_encoder_RSC.hpp"
#include "Tools/Factory/Turbo/Factory_encoder_turbo.hpp"
#include "Tools/Factory/Turbo/Factory_scaling_factor.hpp"
#include "Tools/Factory/RSC/Factory_decoder_RSC.hpp"
#include "Tools/Factory/Turbo/Factory_decoder_turbo.hpp"

template <typename B, typename R, typename Q, typename QD>
Simulation_BFER_turbo<B,R,Q,QD>
::Simulation_BFER_turbo(const parameters& params)
: Simulation_BFER<B,R,Q>(params),
  interleaver(params.simulation.n_threads, nullptr),
  sub_encoder(params.simulation.n_threads, nullptr),
  siso       (params.simulation.n_threads, nullptr),
  sf         (params.simulation.n_threads, nullptr)
{
	assert(params.code.N / params.code.K == 3);

	for (auto tid = 0; tid < params.simulation.n_threads; tid++)
	{
		auto seed = this->params.simulation.seed;
		seed += (params.interleaver.type == "UNIFORM") ? tid : 0;

		// build the interleaver for the encoder and the decoder
		interleaver[tid] = Factory_interleaver<short>::build(this->params, this->params.code.K, seed);
		Simulation::check_errors(interleaver[tid], "Interleaver<short>");
	}

	if (!params.simulation.json_path.empty())
	{
		assert(params.simulation.n_threads == 1);
		json_stream.open(params.simulation.json_path.c_str(), std::ios::out | std::ios::trunc);

		json_stream << "[" << std::endl;
	}
}

template <typename B, typename R, typename Q, typename QD>
Simulation_BFER_turbo<B,R,Q,QD>
::~Simulation_BFER_turbo()
{
	release_objects();
	if (json_stream.is_open())
	{
		json_stream << "[{\"stage\": \"end\"}]]" << std::endl;
		json_stream.close();
	}
	for (auto tid = 0; tid < this->params.simulation.n_threads; tid++)
		if (interleaver[tid] != nullptr)
			delete interleaver[tid];
}

template <typename B, typename R, typename Q, typename QD>
void Simulation_BFER_turbo<B,R,Q,QD>
::release_objects()
{
	Simulation_BFER<B,R,Q>::release_objects();

	int tid = 0;
	const int nthr = this->params.simulation.n_threads;
	for (tid = 0; tid < nthr; tid++) if (sub_encoder[tid] != nullptr) { delete sub_encoder[tid]; sub_encoder[tid] = nullptr; }
	for (tid = 0; tid < nthr; tid++) if (siso       [tid] != nullptr) { delete siso       [tid]; siso       [tid] = nullptr; }
	for (tid = 0; tid < nthr; tid++) if (sf         [tid] != nullptr) { delete sf         [tid]; sf         [tid] = nullptr; }
}

template <typename B, typename R, typename Q, typename QD>
void Simulation_BFER_turbo<B,R,Q,QD>
::launch_precompute()
{
}

template <typename B, typename R, typename Q, typename QD>
void Simulation_BFER_turbo<B,R,Q,QD>
::snr_precompute()
{
}

template <typename B, typename R, typename Q, typename QD>
Encoder<B>* Simulation_BFER_turbo<B,R,Q,QD>
::build_encoder(const int tid)
{
	sub_encoder[tid] = Factory_encoder_RSC<B>::build(this->params, 1, json_stream);
	Simulation::check_errors(sub_encoder[tid], "Encoder_RSC_sys<B>");

	if (tid == 0)
		trellis = sub_encoder[tid]->get_trellis();

	Encoder<B>* encoder = nullptr;
	if (this->params.simulation.json_path.empty())
		encoder = Simulation_BFER<B,R,Q>::build_encoder(tid);
	if (encoder == nullptr)
		encoder = Factory_encoder_turbo<B>::build(this->params, interleaver[tid], sub_encoder[tid], sub_encoder[tid]);

	return encoder;
}

template <typename B, typename R, typename Q, typename QD>
Decoder<B,Q>* Simulation_BFER_turbo<B,R,Q,QD>
::build_decoder(const int tid)
{
	sf[tid] = Factory_scaling_factor<Q>::build(this->params);
	Simulation::check_errors(sf[tid], "Scaling_factor<Q>");

	this->barrier(tid);
	siso[tid] = Factory_decoder_RSC<B,Q,QD>::build_siso(this->params, trellis, json_stream);
	Simulation::check_errors(siso[tid], "SISO<Q>");

	interleaver[tid]->set_n_frames(siso[tid]->get_n_frames());

	return Factory_decoder_turbo<B,Q>::build(this->params, interleaver[tid], siso[tid], siso[tid], sf[tid], this->crc[tid]);
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Simulation_BFER_turbo<B_8,R_8,Q_8,QD_8>;
template class Simulation_BFER_turbo<B_16,R_16,Q_16,QD_16>;
template class Simulation_BFER_turbo<B_32,R_32,Q_32,QD_32>;
template class Simulation_BFER_turbo<B_64,R_64,Q_64,QD_64>;
#else
template class Simulation_BFER_turbo<B,R,Q,QD>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|>


<commit_before>#ifndef ZS_MEMORY_HH
#define ZS_MEMORY_HH

#include <new>
#include "decl.hh"

void* operator new(size_t, Ptr_tag);
void* operator new[](size_t, Ptr_tag) = delete;

void operator delete(void*, Ptr_tag);
void operator delete[](void*, Ptr_tag) = delete;

#endif // ZS_MEMORY_HH
<commit_msg>added deletor<commit_after>#ifndef ZS_MEMORY_HH
#define ZS_MEMORY_HH

#include <new>
#include <memory>
#include "decl.hh"

void* operator new(size_t, Ptr_tag);
void* operator new[](size_t, Ptr_tag) = delete;

void operator delete(void*, Ptr_tag);
void operator delete[](void*, Ptr_tag) = delete;

// like 'std::default_delete'
template<typename T>
struct zs_memory_delete{
  void operator()(T* p){
    p->~T();
    operator delete(p, to_tag<T>());
  }
};

#endif // ZS_MEMORY_HH
<|endoftext|>