<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <iostream>
#include <sstream>
#include <memory>

#include "../command.hxx"
#include "../interp.hxx"
#include "../argument.hxx"
#include "../common.hxx"
#include "basic_parsers.hxx"

using namespace std;

namespace tglng {
  template<typename Operator>
  class StringComparison: public Command {
    Operator op;
    auto_ptr<Command> lhs, rhs;

  public:
    StringComparison(Command* left,
                     auto_ptr<Command>& l,
                     auto_ptr<Command>& r)
    : Command(left), lhs(l), rhs(r) {}

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring lstr, rstr;
      if (!interp.exec(lstr, lhs.get()) ||
          !interp.exec(rstr, rhs.get())) return false;

      out = op(lstr,rstr)? L"1" : L"0";
      return true;
    }
  };

  template<typename Operator>
  class StringComparisonParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text,
                              unsigned& offset) {
      auto_ptr<Command> lhs, rhs;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(lhs), a.a(rhs)]) return ParseError;

      out = new StringComparison<Operator>(out, lhs, rhs);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringComparisonParser<equal_to<wstring> > >
  _strequParser(L"str-equ");
  static GlobalBinding<StringComparisonParser<less<wstring> > >
  _strsltParser(L"str-slt");
  static GlobalBinding<StringComparisonParser<greater<wstring> > >
  _strsgtParser(L"str-sgt");

  class StringSearch: public Command {
    auto_ptr<Command> needle, haystack;

  public:
    StringSearch(Command* left,
                 auto_ptr<Command>& n,
                 auto_ptr<Command>& h)
    : Command(left), needle(n), haystack(h)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring ns, hs;
      if (!needle  ->exec(ns, interp)) return false;
      if (!haystack->exec(hs, interp)) return false;

      size_t result = hs.find(ns);
      if (result == wstring::npos)
        //Not found
        out = L"";
      else
        out = intToStr((signed)result);

      return true;
    }
  };

  class StringSearchParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text,
                              unsigned& offset) {
      auto_ptr<Command> needle, haystack;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(needle), a.a(haystack)])
        return ParseError;

      out = new StringSearch(out, needle, haystack);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringSearchParser> _stringSearchParser(L"str-str");

  class StringIndex: public Command {
    auto_ptr<Command> begin, end;
    bool treatEndAsLength;
    AutoSection string;

  public:
    StringIndex(Command* left,
                auto_ptr<Command>& begin_,
                auto_ptr<Command>& end_,
                bool treatEndAsLength_,
                Section string_)
    : Command(left),
      begin(begin_), end(end_),
      treatEndAsLength(treatEndAsLength_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring sb, se, str, strr;
      signed ib, ie;

      //Get the parms
      if (!begin->exec(sb, interp) ||
          (end.get() && !end->exec(se, interp)) ||
          (string.left && !string.left->exec(str, interp)) ||
          (string.right && !string.right->exec(strr, interp)))
        return false;

      //Concat section parts
      str += strr;

      //Convert integers
      if (!parseInteger(ib, sb)) {
        wcerr << L"Invalid integer: " << sb << endl;
        return false;
      }

      if (se.empty())
        //Implicitly one character
        ie = ib+1;
      else {
        if (!parseInteger(ie, se)) {
          wcerr << L"Invalid integer: " << se << endl;
          return false;
        }

        //Add ib if in length mode
        if (treatEndAsLength)
          ie += ib;
      }

      //Negative indices are relative to the end plus one
      if (ib < 0) ib += str.size()+1;
      if (ie < 0) ie += str.size()+1;

      //Clamp indices
      if (ib < 0) ib = 0;
      if (ib > (signed)str.size()) ib = str.size()-1;
      if (ie < ib) ie = ib;
      if (ie > (signed)str.size()) ie = str.size()-1;

      //OK
      out = str.substr(ib, ie-ib);
      return true;
    }
  };

  class StringIndexParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      auto_ptr<Command> begin, end;
      AutoSection string;
      bool length = false;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(begin),
             (-a.x(length, L'.'), a.a(end)) -=
             a.s(string)])
        return ParseError;

      out = new StringIndex(out, begin, end, length, string);
      string.clear(); //Now owned by out
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringIndexParser> _stringIndexParser(L"str-ix");

  class StringClass: public Command {
    //The function to check each character
    int (*is)(int);
    //Whether the range of is is restricted to 0..127
    bool asciiOnly;
    //Whether to negate the check
    bool negate;

    auto_ptr<Command> string;

    /* ISO C says that the char varieties are
     *   int f(int)
     * and the wchar_t are
     *   int f(wint_t).
     *
     * G++ considers the two incompatible (due to different signedness), but
     * that won't affect us. On most systems, sizeof(int) ==
     * sizeof(wint_t). Ensure that is true on this system.
     */
    void checkSizeofIntEqualsSizeofWintT() {
      switch (true) {
      case false:
      case sizeof(int) == sizeof(wint_t):;
      }
    }

  public:
    StringClass(Command* left,
                int (*is_)(int),
                bool asciiOnly_,
                bool negate_,
                auto_ptr<Command>& string_)
    : Command(left),
      is(is_), asciiOnly(asciiOnly_), negate(negate_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring str;
      bool result;
      if (!string->exec(str, interp)) return false;

      if (str.empty()) {
        result = false;
        goto done;
      }

      for (unsigned i = 0; i < str.size(); ++i) {
        wchar_t curr = str[i];
        if ((!negate) ^
            ((!asciiOnly || (curr >= 0 && curr < 128)) &&
             is(curr))) {
          //Character failed
          result = false;
          goto done;
        }
      }

      //All chars passed
      result = true;

      done:
      out = (result? L"1" : L"0");
      return true;
    }
  };

  class StringClassParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      wchar_t clazzch;
      unsigned clazzOffset;
      //The wchar_t functions take a wint_t. An assertion in StringClass
      //ensures that the functions are compatible.
      union {
        int (*a)(int);
        int (*u)(wint_t);
      } clazz;
      bool negate, asciiOnly;
      auto_ptr<Command> string;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.h(clazzch) >> clazzOffset, a.a(string)])
        return ParseError;

      switch (clazzch) {
      case L'l': clazz.u = iswlower, negate = false, asciiOnly = false; break;
      case L'L': clazz.u = iswlower, negate = true , asciiOnly = false; break;
      case L'o': clazz.a = islower , negate = false, asciiOnly = true ; break;
      case L'O': clazz.a = islower , negate = true , asciiOnly = true ; break;
      case L'u': clazz.u = iswupper, negate = false, asciiOnly = false; break;
      case L'U': clazz.u = iswupper, negate = true , asciiOnly = false; break;
      case L'v': clazz.a = isupper , negate = false, asciiOnly = true ; break;
      case L'V': clazz.a = isupper , negate = true , asciiOnly = true ; break;
      case L'a': clazz.u = iswalpha, negate = false, asciiOnly = false; break;
      case L'A': clazz.u = iswalpha, negate = true , asciiOnly = false; break;
      case L'b': clazz.a = isalpha , negate = false, asciiOnly = true ; break;
      case L'B': clazz.a = isalpha , negate = true , asciiOnly = true ; break;
      case L'n': clazz.u = iswalnum, negate = false, asciiOnly = false; break;
      case L'N': clazz.u = iswalnum, negate = true , asciiOnly = false; break;
      case L'm': clazz.a = isalnum , negate = false, asciiOnly = true ; break;
      case L'M': clazz.a = isalnum , negate = true , asciiOnly = true ; break;
      case L'\\':clazz.a = iscntrl , negate = false, asciiOnly = true ; break;
      case L'~': clazz.a = iscntrl , negate = true , asciiOnly = true ; break;
      case L'0': clazz.a = isdigit , negate = false, asciiOnly = true ; break;
      case L'9': clazz.a = isdigit , negate = true , asciiOnly = true ; break;
      case L'x': clazz.a = isxdigit, negate = false, asciiOnly = true ; break;
      case L'X': clazz.a = isxdigit, negate = true , asciiOnly = true ; break;
      case L'.':
      case L'p': clazz.u = iswpunct, negate = false, asciiOnly = false; break;
      case L':':
      case L'P': clazz.u = iswpunct, negate = true , asciiOnly = false; break;
      case L',':
      case L'q': clazz.a = ispunct , negate = false, asciiOnly = true ; break;
      case L';':
      case L'Q': clazz.a = ispunct , negate = true , asciiOnly = true ; break;
      case L's':
      case L'_': clazz.u = iswspace, negate = false, asciiOnly = false; break;
      case L'S':
      case L'#': clazz.u = iswspace, negate = true , asciiOnly = false; break;
      case L'g': clazz.u = iswgraph, negate = false, asciiOnly = false; break;
      case L'G': clazz.u = iswgraph, negate = true , asciiOnly = false; break;
      case L'h': clazz.a = isgraph , negate = false, asciiOnly = true ; break;
      case L'H': clazz.a = isgraph , negate = true , asciiOnly = true ; break;
      case L'r': clazz.u = iswprint, negate = false, asciiOnly = false; break;
      case L'R': clazz.u = iswprint, negate = true , asciiOnly = false; break;
      /* Not 's' since people might expect it to be space. */
      case L't': clazz.a = isprint , negate = false, asciiOnly = true ; break;
      case L'T': clazz.a = isprint , negate = true , asciiOnly = true ; break;

      default:
        interp.error(wstring(L"Unknown character class: ") + clazzch,
                     text, clazzOffset);
        return ParseError;
      }

      //OK
      out = new StringClass(out, clazz.a, asciiOnly, negate, string);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringClassParser> _stringClassParser(L"str-is");

  class StringLength: public UnaryCommand {
  public:
    StringLength(Command* left, auto_ptr<Command>& sub)
    : UnaryCommand(left, sub) {}

    virtual bool exec(wstring& dst, Interpreter& interp) {
      wstring s;
      if (!sub->exec(s, interp)) return false;

      dst = intToStr(s.size());
      return true;
    }
  };

  static GlobalBinding<UnaryCommandParser<StringLength> >
  _stringLengthParser(L"str-len");
}
<commit_msg>Fix string commands using Command::exec instead of Interpreter::exec().<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <iostream>
#include <sstream>
#include <memory>

#include "../command.hxx"
#include "../interp.hxx"
#include "../argument.hxx"
#include "../common.hxx"
#include "basic_parsers.hxx"

using namespace std;

namespace tglng {
  template<typename Operator>
  class StringComparison: public Command {
    Operator op;
    auto_ptr<Command> lhs, rhs;

  public:
    StringComparison(Command* left,
                     auto_ptr<Command>& l,
                     auto_ptr<Command>& r)
    : Command(left), lhs(l), rhs(r) {}

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring lstr, rstr;
      if (!interp.exec(lstr, lhs.get()) ||
          !interp.exec(rstr, rhs.get())) return false;

      out = op(lstr,rstr)? L"1" : L"0";
      return true;
    }
  };

  template<typename Operator>
  class StringComparisonParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text,
                              unsigned& offset) {
      auto_ptr<Command> lhs, rhs;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(lhs), a.a(rhs)]) return ParseError;

      out = new StringComparison<Operator>(out, lhs, rhs);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringComparisonParser<equal_to<wstring> > >
  _strequParser(L"str-equ");
  static GlobalBinding<StringComparisonParser<less<wstring> > >
  _strsltParser(L"str-slt");
  static GlobalBinding<StringComparisonParser<greater<wstring> > >
  _strsgtParser(L"str-sgt");

  class StringSearch: public Command {
    auto_ptr<Command> needle, haystack;

  public:
    StringSearch(Command* left,
                 auto_ptr<Command>& n,
                 auto_ptr<Command>& h)
    : Command(left), needle(n), haystack(h)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring ns, hs;
      if (!interp.exec(ns, needle  .get())) return false;
      if (!interp.exec(hs, haystack.get())) return false;

      size_t result = hs.find(ns);
      if (result == wstring::npos)
        //Not found
        out = L"";
      else
        out = intToStr((signed)result);

      return true;
    }
  };

  class StringSearchParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text,
                              unsigned& offset) {
      auto_ptr<Command> needle, haystack;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(needle), a.a(haystack)])
        return ParseError;

      out = new StringSearch(out, needle, haystack);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringSearchParser> _stringSearchParser(L"str-str");

  class StringIndex: public Command {
    auto_ptr<Command> begin, end;
    bool treatEndAsLength;
    AutoSection string;

  public:
    StringIndex(Command* left,
                auto_ptr<Command>& begin_,
                auto_ptr<Command>& end_,
                bool treatEndAsLength_,
                Section string_)
    : Command(left),
      begin(begin_), end(end_),
      treatEndAsLength(treatEndAsLength_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring sb, se, str, strr;
      signed ib, ie;

      //Get the parms
      if (!interp.exec(sb, begin.get()) ||
          (end.get() && !interp.exec(se, end.get())) ||
          (string.left && !interp.exec(str, string.left)) ||
          (string.right && !interp.exec(strr, string.right)))
        return false;

      //Concat section parts
      str += strr;

      //Convert integers
      if (!parseInteger(ib, sb)) {
        wcerr << L"Invalid integer: " << sb << endl;
        return false;
      }

      if (se.empty())
        //Implicitly one character
        ie = ib+1;
      else {
        if (!parseInteger(ie, se)) {
          wcerr << L"Invalid integer: " << se << endl;
          return false;
        }

        //Add ib if in length mode
        if (treatEndAsLength)
          ie += ib;
      }

      //Negative indices are relative to the end plus one
      if (ib < 0) ib += str.size()+1;
      if (ie < 0) ie += str.size()+1;

      //Clamp indices
      if (ib < 0) ib = 0;
      if (ib > (signed)str.size()) ib = str.size()-1;
      if (ie < ib) ie = ib;
      if (ie > (signed)str.size()) ie = str.size()-1;

      //OK
      out = str.substr(ib, ie-ib);
      return true;
    }
  };

  class StringIndexParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      auto_ptr<Command> begin, end;
      AutoSection string;
      bool length = false;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.a(begin),
             (-a.x(length, L'.'), a.a(end)) -=
             a.s(string)])
        return ParseError;

      out = new StringIndex(out, begin, end, length, string);
      string.clear(); //Now owned by out
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringIndexParser> _stringIndexParser(L"str-ix");

  class StringClass: public Command {
    //The function to check each character
    int (*is)(int);
    //Whether the range of is is restricted to 0..127
    bool asciiOnly;
    //Whether to negate the check
    bool negate;

    auto_ptr<Command> string;

    /* ISO C says that the char varieties are
     *   int f(int)
     * and the wchar_t are
     *   int f(wint_t).
     *
     * G++ considers the two incompatible (due to different signedness), but
     * that won't affect us. On most systems, sizeof(int) ==
     * sizeof(wint_t). Ensure that is true on this system.
     */
    void checkSizeofIntEqualsSizeofWintT() {
      switch (true) {
      case false:
      case sizeof(int) == sizeof(wint_t):;
      }
    }

  public:
    StringClass(Command* left,
                int (*is_)(int),
                bool asciiOnly_,
                bool negate_,
                auto_ptr<Command>& string_)
    : Command(left),
      is(is_), asciiOnly(asciiOnly_), negate(negate_),
      string(string_)
    { }

    virtual bool exec(wstring& out, Interpreter& interp) {
      wstring str;
      bool result;
      if (!interp.exec(str, string.get())) return false;

      if (str.empty()) {
        result = false;
        goto done;
      }

      for (unsigned i = 0; i < str.size(); ++i) {
        wchar_t curr = str[i];
        if ((!negate) ^
            ((!asciiOnly || (curr >= 0 && curr < 128)) &&
             is(curr))) {
          //Character failed
          result = false;
          goto done;
        }
      }

      //All chars passed
      result = true;

      done:
      out = (result? L"1" : L"0");
      return true;
    }
  };

  class StringClassParser: public CommandParser {
  public:
    virtual ParseResult parse(Interpreter& interp, Command*& out,
                              const wstring& text, unsigned& offset) {
      wchar_t clazzch;
      unsigned clazzOffset;
      //The wchar_t functions take a wint_t. An assertion in StringClass
      //ensures that the functions are compatible.
      union {
        int (*a)(int);
        int (*u)(wint_t);
      } clazz;
      bool negate, asciiOnly;
      auto_ptr<Command> string;
      ArgumentParser a(interp, text, offset, out);
      if (!a[a.h(), a.h(clazzch) >> clazzOffset, a.a(string)])
        return ParseError;

      switch (clazzch) {
      case L'l': clazz.u = iswlower, negate = false, asciiOnly = false; break;
      case L'L': clazz.u = iswlower, negate = true , asciiOnly = false; break;
      case L'o': clazz.a = islower , negate = false, asciiOnly = true ; break;
      case L'O': clazz.a = islower , negate = true , asciiOnly = true ; break;
      case L'u': clazz.u = iswupper, negate = false, asciiOnly = false; break;
      case L'U': clazz.u = iswupper, negate = true , asciiOnly = false; break;
      case L'v': clazz.a = isupper , negate = false, asciiOnly = true ; break;
      case L'V': clazz.a = isupper , negate = true , asciiOnly = true ; break;
      case L'a': clazz.u = iswalpha, negate = false, asciiOnly = false; break;
      case L'A': clazz.u = iswalpha, negate = true , asciiOnly = false; break;
      case L'b': clazz.a = isalpha , negate = false, asciiOnly = true ; break;
      case L'B': clazz.a = isalpha , negate = true , asciiOnly = true ; break;
      case L'n': clazz.u = iswalnum, negate = false, asciiOnly = false; break;
      case L'N': clazz.u = iswalnum, negate = true , asciiOnly = false; break;
      case L'm': clazz.a = isalnum , negate = false, asciiOnly = true ; break;
      case L'M': clazz.a = isalnum , negate = true , asciiOnly = true ; break;
      case L'\\':clazz.a = iscntrl , negate = false, asciiOnly = true ; break;
      case L'~': clazz.a = iscntrl , negate = true , asciiOnly = true ; break;
      case L'0': clazz.a = isdigit , negate = false, asciiOnly = true ; break;
      case L'9': clazz.a = isdigit , negate = true , asciiOnly = true ; break;
      case L'x': clazz.a = isxdigit, negate = false, asciiOnly = true ; break;
      case L'X': clazz.a = isxdigit, negate = true , asciiOnly = true ; break;
      case L'.':
      case L'p': clazz.u = iswpunct, negate = false, asciiOnly = false; break;
      case L':':
      case L'P': clazz.u = iswpunct, negate = true , asciiOnly = false; break;
      case L',':
      case L'q': clazz.a = ispunct , negate = false, asciiOnly = true ; break;
      case L';':
      case L'Q': clazz.a = ispunct , negate = true , asciiOnly = true ; break;
      case L's':
      case L'_': clazz.u = iswspace, negate = false, asciiOnly = false; break;
      case L'S':
      case L'#': clazz.u = iswspace, negate = true , asciiOnly = false; break;
      case L'g': clazz.u = iswgraph, negate = false, asciiOnly = false; break;
      case L'G': clazz.u = iswgraph, negate = true , asciiOnly = false; break;
      case L'h': clazz.a = isgraph , negate = false, asciiOnly = true ; break;
      case L'H': clazz.a = isgraph , negate = true , asciiOnly = true ; break;
      case L'r': clazz.u = iswprint, negate = false, asciiOnly = false; break;
      case L'R': clazz.u = iswprint, negate = true , asciiOnly = false; break;
      /* Not 's' since people might expect it to be space. */
      case L't': clazz.a = isprint , negate = false, asciiOnly = true ; break;
      case L'T': clazz.a = isprint , negate = true , asciiOnly = true ; break;

      default:
        interp.error(wstring(L"Unknown character class: ") + clazzch,
                     text, clazzOffset);
        return ParseError;
      }

      //OK
      out = new StringClass(out, clazz.a, asciiOnly, negate, string);
      return ContinueParsing;
    }
  };

  static GlobalBinding<StringClassParser> _stringClassParser(L"str-is");

  class StringLength: public UnaryCommand {
  public:
    StringLength(Command* left, auto_ptr<Command>& sub)
    : UnaryCommand(left, sub) {}

    virtual bool exec(wstring& dst, Interpreter& interp) {
      wstring s;
      if (!interp.exec(s, sub.get())) return false;

      dst = intToStr(s.size());
      return true;
    }
  };

  static GlobalBinding<UnaryCommandParser<StringLength> >
  _stringLengthParser(L"str-len");
}
<|endoftext|>


<commit_before>/* Copyright (c) 2009 - http://ruinwesen.com/ */

#ifndef ELEKTRON_H__
#define ELEKTRON_H__

#include "WProgram.h"

#include <inttypes.h>

/**
 * \addtogroup Elektron
 *
 * @{
 *
 * \addtogroup elektron_helpers Elektron Helpers
 *
 * @{
 *
 * \file
 * Elektron helper routines and data structures
 **/

/** Store the name of a monomachine machine. **/
typedef struct mnm_machine_name_s {
  char name[11];
  uint8_t id;
} mnm_machine_name_t;

/** Store the name of a machinedrum machine. **/
typedef struct md_machine_name_s {
  char name[7];
  uint8_t id;
} md_machine_name_t;

/** Store the name of a parameter for a machine model. **/
typedef struct model_param_name_s {
  char name[4];
  uint8_t id;
} model_param_name_t;

/** Data structure holding the parameter names for a machine model. **/
typedef struct model_to_param_names_s {
  uint8_t model;
  model_param_name_t *names;
} model_to_param_names_t;

/**
 * Class grouping various helper functions to convert elektron sysex
 * data. These are deprecated and should be replaced by the elektron
 * data encoders.
 **/
class ElektronHelper {
public:
	/** Convert the sysex into normal data by converting 7 bit values to 8 bit. **/
  static uint16_t ElektronSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);
	/** Convert normal 8-bit into 7-bit sysex data. **/
  static uint16_t ElektronDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);
	/** Convert normal 8-bit data into 7-bit compressed elektron monomachine sysex data. **/
  static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);
	/** Convert compressed monomachine sysex data into normal 8-bit data. **/
  static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);

  static uint16_t to16Bit7(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t *b);
  static uint32_t to32Bit(uint8_t *b);
  static void from16Bit(uint16_t num, uint8_t *b);
  static void from32Bit(uint32_t num, uint8_t *b);
  static uint64_t to64Bit(uint8_t *b);
  static void from64Bit(uint64_t num, uint8_t *b);

	static bool checkSysexChecksum(uint8_t *data, uint16_t len);
	static void calculateSysexChecksum(uint8_t *data, uint16_t len);
};

#include "MNMDataEncoder.hh"
#include "ElektronDataEncoder.hh"

#endif /* ELEKTRON_H__ */
<commit_msg>format<commit_after>/* Copyright (c) 2009 - http://ruinwesen.com/ */

#ifndef ELEKTRON_H__
#define ELEKTRON_H__

#include "WProgram.h"

#include <inttypes.h>

/**
 * \addtogroup Elektron
 *
 * @{
 *
 * \addtogroup elektron_helpers Elektron Helpers
 *
 * @{
 *
 * \file
 * Elektron helper routines and data structures
 **/

/** Store the name of a monomachine machine. **/
typedef struct mnm_machine_name_s {
  char name[11];
  uint8_t id;
} mnm_machine_name_t;

/** Store the name of a machinedrum machine. **/
typedef struct md_machine_name_s {
  char name[7];
  uint8_t id;
} md_machine_name_t;

/** Store the name of a parameter for a machine model. **/
typedef struct model_param_name_s {
  char name[4];
  uint8_t id;
} model_param_name_t;

/** Data structure holding the parameter names for a machine model. **/
typedef struct model_to_param_names_s {
  uint8_t model;
  model_param_name_t *names;
} model_to_param_names_t;

/**
 * Class grouping various helper functions to convert elektron sysex
 * data. These are deprecated and should be replaced by the elektron
 * data encoders.
 **/
class ElektronHelper {
public:
  /** Convert the sysex into normal data by converting 7 bit values to 8 bit. **/
  static uint16_t ElektronSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len);
  /** Convert normal 8-bit into 7-bit sysex data. **/
  static uint16_t ElektronDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len);
  /** Convert normal 8-bit data into 7-bit compressed elektron monomachine sysex data. **/
  static uint16_t MNMDataToSysex(uint8_t *data, uint8_t *sysex, uint16_t len, uint16_t maxLen);
  /** Convert compressed monomachine sysex data into normal 8-bit data. **/
  static uint16_t MNMSysexToData(uint8_t *sysex, uint8_t *data, uint16_t len, uint16_t maxLen);

  static uint16_t to16Bit7(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t b1, uint8_t b2);
  static uint16_t to16Bit(uint8_t *b);
  static uint32_t to32Bit(uint8_t *b);
  static void from16Bit(uint16_t num, uint8_t *b);
  static void from32Bit(uint32_t num, uint8_t *b);
  static uint64_t to64Bit(uint8_t *b);
  static void from64Bit(uint64_t num, uint8_t *b);

  static bool checkSysexChecksum(uint8_t *data, uint16_t len);
  static void calculateSysexChecksum(uint8_t *data, uint16_t len);
};

#include "MNMDataEncoder.hh"
#include "ElektronDataEncoder.hh"

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


<commit_before>#include <iostream.h>
#include "vtkImageViewer.h"
#include "vtkImageReader.h"
#include "vtkImageImport.h"
#include "vtkImageExport.h"

main ()
{
 int i,j,k;

 vtkImageReader *reader = vtkImageReader::New();
 reader->SetDataByteOrderToLittleEndian();
 reader->SetDataExtent(0,255,0,255,1,93);
 reader->SetFilePrefix("../../../vtkdata/fullHead/headsq");
 reader->SetDataMask(0x7fff);

 // create exporter
 vtkImageExport *exporter = vtkImageExport::New();
 exporter->SetInput(reader->GetOutput());
 exporter->ImageLowerLeftOn();

 // get info from exporter and create array to hold data
 int memsize = exporter->GetDataMemorySize();
 int *dimensions = exporter->GetDataDimensions();
 short *data = new short[memsize/sizeof(short)];

 // export the data into the array
 exporter->Export(data);

 /* alternative method for getting data
 short *data = exporter->GetPointerToData();
 */

 // do a little something to the data

 for (i = 0; i < dimensions[2]; i++)
   {
   for (j = 0; j < dimensions[1]; j++)
     {
     for (k = 0; k < dimensions[0]; k++)
       {
       if (k % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 0;
	 }
       if (j % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 1000;
	 }
       }
     }
   }

 // create an importer to read the data back in
 vtkImageImport *importer = vtkImageImport::New();
 importer->SetDataExtent(1,dimensions[0],1,dimensions[1],1,dimensions[2]);
 importer->ImageLowerLeftOn();
 importer->SetDataScalarTypeToShort();
 importer->SetImportVoidPointer(data);

 vtkImageViewer *viewer = vtkImageViewer::New();
 viewer->SetInput(importer->GetOutput());
 viewer->SetZSlice(128);
 viewer->SetColorWindow(2000);
 viewer->SetColorLevel(1000);

 viewer->Render();

 char *dummy;
 cin >> dummy;

 viewer->Delete();
 importer->Delete();
 exporter->Delete();
 reader->Delete();

 delete data;

 return 0;
}
<commit_msg>ENH: instrumented for regression testing.<commit_after>#include <iostream.h>
#include "vtkImageViewer.h"
#include "vtkImageReader.h"
#include "vtkImageImport.h"
#include "vtkImageExport.h"
#include "vtkWindowToImageFilter.h"
#include "vtkPNMWriter.h"

#include "SaveViewerImage.h"

void main( int argc, char *argv[] )
{
 int i,j,k;

 vtkImageReader *reader = vtkImageReader::New();
 reader->SetDataByteOrderToLittleEndian();
 reader->SetDataExtent(0,255,0,255,1,93);
 reader->SetFilePrefix("../../../vtkdata/fullHead/headsq");
 reader->SetDataMask(0x7fff);

 // create exporter
 vtkImageExport *exporter = vtkImageExport::New();
 exporter->SetInput(reader->GetOutput());
 exporter->ImageLowerLeftOn();

 // get info from exporter and create array to hold data
 int memsize = exporter->GetDataMemorySize();
 int *dimensions = exporter->GetDataDimensions();
 short *data = new short[memsize/sizeof(short)];

 // export the data into the array
 exporter->Export(data);

 /* alternative method for getting data
 short *data = exporter->GetPointerToData();
 */

 // do a little something to the data

 for (i = 0; i < dimensions[2]; i++)
   {
   for (j = 0; j < dimensions[1]; j++)
     {
     for (k = 0; k < dimensions[0]; k++)
       {
       if (k % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 0;
	 }
       if (j % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 1000;
	 }
       }
     }
   }

 // create an importer to read the data back in
 vtkImageImport *importer = vtkImageImport::New();
 importer->SetDataExtent(1,dimensions[0],1,dimensions[1],1,dimensions[2]);
 importer->ImageLowerLeftOn();
 importer->SetDataScalarTypeToShort();
 importer->SetImportVoidPointer(data);

 vtkImageViewer *viewer = vtkImageViewer::New();
 viewer->SetInput(importer->GetOutput());
 viewer->SetZSlice(128);
 viewer->SetColorWindow(2000);
 viewer->SetColorLevel(1000);

 viewer->Render();

 SAVEVIEWERIMAGE (viewer);

 char *dummy;
 cin >> dummy;

 viewer->Delete();
 importer->Delete();
 exporter->Delete();
 reader->Delete();

 delete data;

}
<|endoftext|>


<commit_before>#include "parsegtf.hpp"
#include "utility.hpp"

class badline: public std::exception
{
  virtual const char* what() const throw(){
      return "Badly formatted line";
  }
} badline;

using str_vec_iter = std::vector<std::string>::iterator;

struct block_process {
    std::vector <std::string> operator() (str_vec_iter begin, str_vec_iter end, const GTFOptions &options) {
        std::vector <std::string> result_vector;
        for (auto it = begin; it != end ; it++) {
            result_vector.push_back(
                getGTFFields(*it, options)
            );
        }
        return std::move(result_vector);
    }
};

std::vector<std::string> parallel_parse(str_vec_iter begin, str_vec_iter end, const GTFOptions & options) {

    const size_t MIN_SIZE = 10000;

    size_t length = std::distance(begin, end);

    if (length < MIN_SIZE) {
        return block_process() (begin, end, std::ref(options));
    }

    size_t num_threads = std::max((unsigned int)2, std::thread::hardware_concurrency());
    size_t block_size = length / num_threads;

    str_vec_iter current_begin, current_end;
    current_begin = begin;

    std::vector< std::future<std::vector<std::string>>> handle_vector;

    for (size_t i=0 ; i < (num_threads - 1) ; i++) {
        current_end=current_begin;
        std::advance(current_end, block_size);
        handle_vector.push_back(
            std::async(
                std::launch::async, block_process(), current_begin, current_end, std::ref(options)
            )
        );
        current_begin = current_end;
    }

    handle_vector.push_back(
        std::async(
            std::launch::async, block_process(), current_begin, end, std::ref(options)
        )
    );

    std::vector<std::string> final_results;

    std::for_each(handle_vector.begin(), handle_vector.end(), [&final_results](auto &element){
        auto result = element.get();
        std::move(result.begin(), result.end(), std::back_inserter(final_results));
    });

    return std::move(final_results);
}

void readGTFFile(std::istream &input_stream, std::ostream &output_stream,  const GTFOptions& options) {

    const size_t buffer_size = 524'288;
    std::string line;
    string_map att_map;
    std::vector <std::string> line_buffer, result_buffer;
    size_t line_count = 0;

    auto post_data = [&](){
        result_buffer = parallel_parse(
            line_buffer.begin(), line_buffer.end(), options
        );
        std::for_each(result_buffer.begin(), result_buffer.end() , [&output_stream](auto &element){
            output_stream << element;
        });
        line_buffer.clear();
    };

    while (getline(input_stream, line)) {
        line_count++;
        if (line[0] != '#') {
            line_buffer.push_back(std::move(line));
            if (line_buffer.size() >= buffer_size) {
                post_data();
            }
        }
    }
    if (line_buffer.size() > 0) {
        post_data();
    }
}

std::string getGTFFields(const std::string &line, const GTFOptions& options){

    std::vector <std::string> tokens;
    Tokenize(line, tokens, "\t");

    if (tokens.size() < 9) {
        throw badline;
    }

    std::string output("");

    if (options.feature_type.empty() || tokens[2] == options.feature_type) {
        for (size_t index = 0 ; index < options.field_list.size() ; index++) {
            output += tokens[options.field_list[index]];
            output += "\t";
        }
        string_map attribute = ParseGTFAttributes(tokens[8]);

        std::string temp_attribute;
        for(auto &element : options.attribute_list){
            if (options.clean_attributes) {
                temp_attribute = attribute[element];
                StringReplace(temp_attribute, " ", "_");
                output += temp_attribute;
            } else {
                output += attribute[element];
            }
            output += "\t";
        }
        if (!output.empty()) {
            output.pop_back();
            output += "\n";
        }
    }

    return output;
}

string_map ParseGTFAttributes(const std::string &line){
    string_map att_map;
    int pos_name = 0;
    int size_name;

    int pos_value = 0;
    int size_value;

    std::string start_delims(" ");
    std::string mid_delims(" \"");
    std::string end_delims(" \";");

    while (true) {
      pos_name = line.find_first_not_of(end_delims,pos_name);
      if (pos_name == -1) break;
      size_name = line.find_first_of(start_delims, pos_name) - pos_name;

      pos_value = pos_name + size_name;
      pos_value = line.find_first_not_of(mid_delims,pos_value);
      if (pos_value == -1) break;
      size_value = line.find_first_of("\"", pos_value) - pos_value;

      att_map[ line.substr(pos_name, size_name) ] = line.substr(pos_value, size_value);
      pos_name = pos_value + size_value;

    }
    return att_map;
}
<commit_msg>Change empty attributes to NA<commit_after>#include "parsegtf.hpp"
#include "utility.hpp"

class badline: public std::exception
{
  virtual const char* what() const throw(){
      return "Badly formatted line";
  }
} badline;

using str_vec_iter = std::vector<std::string>::iterator;

struct block_process {
    std::vector <std::string> operator() (str_vec_iter begin, str_vec_iter end, const GTFOptions &options) {
        std::vector <std::string> result_vector;
        for (auto it = begin; it != end ; it++) {
            result_vector.push_back(
                getGTFFields(*it, options)
            );
        }
        return std::move(result_vector);
    }
};

std::vector<std::string> parallel_parse(str_vec_iter begin, str_vec_iter end, const GTFOptions & options) {

    const size_t MIN_SIZE = 10000;

    size_t length = std::distance(begin, end);

    if (length < MIN_SIZE) {
        return block_process() (begin, end, std::ref(options));
    }

    size_t num_threads = std::max((unsigned int)2, std::thread::hardware_concurrency());
    size_t block_size = length / num_threads;

    str_vec_iter current_begin, current_end;
    current_begin = begin;

    std::vector< std::future<std::vector<std::string>>> handle_vector;

    for (size_t i=0 ; i < (num_threads - 1) ; i++) {
        current_end=current_begin;
        std::advance(current_end, block_size);
        handle_vector.push_back(
            std::async(
                std::launch::async, block_process(), current_begin, current_end, std::ref(options)
            )
        );
        current_begin = current_end;
    }

    handle_vector.push_back(
        std::async(
            std::launch::async, block_process(), current_begin, end, std::ref(options)
        )
    );

    std::vector<std::string> final_results;

    std::for_each(handle_vector.begin(), handle_vector.end(), [&final_results](auto &element){
        auto result = element.get();
        std::move(result.begin(), result.end(), std::back_inserter(final_results));
    });

    return std::move(final_results);
}

void readGTFFile(std::istream &input_stream, std::ostream &output_stream,  const GTFOptions& options) {

    const size_t buffer_size = 524'288;
    std::string line;
    string_map att_map;
    std::vector <std::string> line_buffer, result_buffer;
    size_t line_count = 0;

    auto post_data = [&](){
        result_buffer = parallel_parse(
            line_buffer.begin(), line_buffer.end(), options
        );
        std::for_each(result_buffer.begin(), result_buffer.end() , [&output_stream](auto &element){
            output_stream << element;
        });
        line_buffer.clear();
    };

    while (getline(input_stream, line)) {
        line_count++;
        if (line[0] != '#') {
            line_buffer.push_back(std::move(line));
            if (line_buffer.size() >= buffer_size) {
                post_data();
            }
        }
    }
    if (line_buffer.size() > 0) {
        post_data();
    }
}

std::string getGTFFields(const std::string &line, const GTFOptions& options){

    std::vector <std::string> tokens;
    Tokenize(line, tokens, "\t");

    if (tokens.size() < 9) {
        throw badline;
    }

    std::string output("");

    if (options.feature_type.empty() || tokens[2] == options.feature_type) {
        for (size_t index = 0 ; index < options.field_list.size() ; index++) {
            output += tokens[options.field_list[index]];
            output += "\t";
        }
        string_map attribute = ParseGTFAttributes(tokens[8]);

        std::string temp_attribute;
        for(auto &element : options.attribute_list){
            temp_attribute = attribute[element];
            if (temp_attribute.empty()) {
                temp_attribute = "NA";
            }
            if (options.clean_attributes) {
                StringReplace(temp_attribute, " ", "_");
            }
            output += temp_attribute;
            output += "\t";
        }
        if (!output.empty()) {
            output.pop_back();
            output += "\n";
        }
    }

    return output;
}

string_map ParseGTFAttributes(const std::string &line){
    string_map att_map;
    int pos_name = 0;
    int size_name;

    int pos_value = 0;
    int size_value;

    std::string start_delims(" ");
    std::string mid_delims(" \"");
    std::string end_delims(" \";");

    while (true) {
      pos_name = line.find_first_not_of(end_delims,pos_name);
      if (pos_name == -1) break;
      size_name = line.find_first_of(start_delims, pos_name) - pos_name;

      pos_value = pos_name + size_name;
      pos_value = line.find_first_not_of(mid_delims,pos_value);
      if (pos_value == -1) break;
      size_value = line.find_first_of("\"", pos_value) - pos_value;

      att_map[ line.substr(pos_name, size_name) ] = line.substr(pos_value, size_value);
      pos_name = pos_value + size_value;

    }
    return att_map;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// Path.cpp
// Cross platform file path handling and directory iteration.
//
// File is under the MIT license; see LICENSE for details.
//------------------------------------------------------------------------------
#include "Path.h"

#include <cctype>
#include <cerrno>
#include <fstream>
#include <sstream>
#include <stdexcept>

#if defined(_WIN32)
#include "compat/windows.h"
#else
# include <unistd.h>
# include <dirent.h>
# include <fcntl.h>
#endif
#include <sys/stat.h>

#if defined(__linux)
# include <linux/limits.h>
#else
# include <limits.h>
#endif

namespace slang {

bool Path::exists() const {
#if defined(_WIN32)
    return GetFileAttributesW(wstr().c_str()) != INVALID_FILE_ATTRIBUTES;
#else
    struct stat sb;
    return stat(str().c_str(), &sb) == 0;
#endif
}

size_t Path::fileSize() const {
#if defined(_WIN32)
    struct _stati64 sb;
    if (_wstati64(wstr().c_str(), &sb) != 0)
        throw std::runtime_error("path::file_size(): cannot stat file \"" + str() + "\"!");
#else
    struct stat sb;
    if (stat(str().c_str(), &sb) != 0)
        throw std::runtime_error("path::file_size(): cannot stat file \"" + str() + "\"!");
#endif
    return (size_t)sb.st_size;
}

bool Path::isDirectory() const {
#if defined(_WIN32)
    DWORD result = GetFileAttributesW(wstr().c_str());
    if (result == INVALID_FILE_ATTRIBUTES)
        return false;
    return (result & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
    struct stat sb;
    if (stat(str().c_str(), &sb))
        return false;
    return S_ISDIR(sb.st_mode);
#endif
}

bool Path::isFile() const {
#if defined(_WIN32)
    DWORD attr = GetFileAttributesW(wstr().c_str());
    return (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0);
#else
    struct stat sb;
    if (stat(str().c_str(), &sb))
        return false;
    return S_ISREG(sb.st_mode);
#endif
}

bool Path::readFile(std::vector<char>& buffer) const {
#if defined(_WIN32)
    size_t size;
    try {
        size = fileSize();
    }
    catch (std::runtime_error&) {
        return false;
    }

    // + 1 for null terminator
    buffer.resize((uint32_t)size + 1);
    std::ifstream stream(str(), std::ios::binary);
    stream.read(buffer.data(), size);

    // null-terminate the buffer while we're at it
    buffer[(uint32_t)size] = '\0';

    return stream.good();
#else

    // TODO: report error
    int fd = open(str().c_str(), O_RDONLY | O_CLOEXEC);
    if (fd == -1)
        return false;

    struct stat sb;
    if (fstat(fd, &sb) != 0) {
        close(fd);
        return false;
    }

    posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);

    // TODO: vector does initialization always, which is dumb
    off_t remaining = sb.st_size;
    buffer.resize((size_t)(remaining + 1));
    char* buf = buffer.data();

    while (remaining > 0) {
        ssize_t r = ::read(fd, buf, (size_t)remaining);
        if (r == -1) {
            close(fd);
            return false;
        }
        else if (r == 0) {
            buffer.resize(size_t((buf - buffer.data()) + 1));
            break;
        }
        else {
            buf += r;
            remaining -= r;
        }
    }

    close(fd);
    buffer.back() = '\0';
    return true;

#endif
}

std::string Path::str(PathType type) const {
    std::ostringstream oss;

    if (type == PosixPath && absolute)
        oss << "/";

    for (size_t i = 0; i < elements.size(); ++i) {
        oss << elements[i];
        if (i + 1 < elements.size()) {
            if (type == PosixPath)
                oss << '/';
            else
                oss << '\\';
        }
    }
    return oss.str();
}

void Path::set(const std::string& str, PathType type) {
    pathType = type;
    if (type == WindowsPath) {
        elements = tokenize(str, "/\\");
        absolute = str.size() >= 2 && std::isalpha(str[0]) && str[1] == ':';
    }
    else {
        elements = tokenize(str, "/");
        absolute = !str.empty() && str[0] == '/';
    }
}

Path Path::makeAbsolute(const Path& path) {
#if !defined(_WIN32)
    char temp[PATH_MAX];
    if (realpath(path.str().c_str(), temp) == nullptr)
        throw std::runtime_error("Internal error in realpath(): " + std::string(strerror(errno)));
    return Path(temp);
#else
    std::wstring value = path.wstr();
    std::wstring out(MAX_PATH, '\0');
    DWORD length = GetFullPathNameW(value.c_str(), MAX_PATH, &out[0], nullptr);
    if (length == 0)
        throw std::runtime_error("Internal error in GetFullPathNameW(): " + std::to_string(GetLastError()));
    return Path(out.substr(0, length));
#endif
}

Path Path::getCurrentDirectory() {
#if !defined(_WIN32)
    char temp[PATH_MAX];
    if (::getcwd(temp, PATH_MAX) == nullptr)
        throw std::runtime_error("Internal error in getcwd(): " + std::string(strerror(errno)));
    return Path(temp);
#else
    std::wstring temp(MAX_PATH, '\0');
    if (!_wgetcwd(&temp[0], MAX_PATH))
        throw std::runtime_error("Internal error in _wgetcwd(): " + std::to_string(GetLastError()));
    return Path(temp.c_str());
#endif
}

#if defined(_WIN32)
std::wstring Path::wstr(PathType type) const {
    std::string temp = str(type);
    int size = MultiByteToWideChar(CP_UTF8, 0, &temp[0], (int)temp.size(), NULL, 0);
    std::wstring result(size, 0);
    MultiByteToWideChar(CP_UTF8, 0, &temp[0], (int)temp.size(), &result[0], size);
    return result;
}

void Path::set(const std::wstring& wstring, PathType type) {
    std::string string;
    if (!wstring.empty()) {
        int size = WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(),
                                       NULL, 0, NULL, NULL);
        string.resize(size, 0);
        WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(),
                            &string[0], size, NULL, NULL);
    }
    set(string, type);
}
#endif

template<typename CharType>
static void findFilesImpl(const Path& path, std::vector<Path>& results, const CharType* extension, bool recurse) {
    std::vector<Path> directories;

#if defined(_WIN32)
    WIN32_FIND_DATAW ffd;
    std::wstring base = path.wstr() + L"\\";
    HANDLE hFind = FindFirstFileW((base + L"*").c_str(), &ffd);
    if (hFind == INVALID_HANDLE_VALUE)
        throw std::runtime_error("Internal error in FindFirstFile(): " + std::to_string(GetLastError()));

    do {
        if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
            const wchar_t* ext = wcsrchr(ffd.cFileName, '.');
            if (!extension || (ext && wcscmp(ext, extension) == 0))
                results.emplace_back(base + ffd.cFileName);
        }
        else if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) {
            directories.emplace_back(base + ffd.cFileName);
        }
    } while (FindNextFileW(hFind, &ffd) != 0);

    DWORD dwError = GetLastError();
    if (dwError != ERROR_NO_MORE_FILES)
        throw std::runtime_error("Internal error in FindNextFile(): " + std::to_string(dwError));
    FindClose(hFind);
#else
    DIR* d;
    struct dirent* dir;
    std::string base = path.str();
    if (base.back() != '/')
        base += '/';

    d = opendir(base.c_str());
    if (d) {
        while ((dir = readdir(d))) {
            if (dir->d_type == DT_REG) {
                const char* ext = strrchr(dir->d_name, '.');
                if (!extension || (ext && strcmp(ext, extension) == 0))
                    results.emplace_back(base + dir->d_name);
            }
            else if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0) {
                directories.emplace_back(base + dir->d_name);
            }
        }
        closedir(d);
    }
#endif

    if (recurse) {
        for (const auto& directory : directories)
            findFilesImpl(directory, results, extension, recurse);
    }
}

std::vector<Path> Path::findFiles(const Path& path, string_view extension, bool recurse) {
#if defined(_WIN32)
    std::wstring extensionCheck;
    if (!extension.empty()) {
        int size = MultiByteToWideChar(CP_UTF8, 0, extension.data(), (int)extension.length(), NULL, 0);
        extensionCheck.resize(size, 0);
        MultiByteToWideChar(CP_UTF8, 0, extension.data(), (int)extension.length(), &extensionCheck[0], size);
    }
#else
    std::string extensionCheck { extension };
#endif

    std::vector<Path> results;
    findFilesImpl(path, results, extensionCheck.c_str(), recurse);
    return results;
}

}
<commit_msg>Don't use posix_fadvise on Apple targets<commit_after>//------------------------------------------------------------------------------
// Path.cpp
// Cross platform file path handling and directory iteration.
//
// File is under the MIT license; see LICENSE for details.
//------------------------------------------------------------------------------
#include "Path.h"

#include <cctype>
#include <cerrno>
#include <fstream>
#include <sstream>
#include <stdexcept>

#if defined(_WIN32)
#include "compat/windows.h"
#else
# include <unistd.h>
# include <dirent.h>
# include <fcntl.h>
#endif
#include <sys/stat.h>

#if defined(__linux)
# include <linux/limits.h>
#else
# include <limits.h>
#endif

namespace slang {

bool Path::exists() const {
#if defined(_WIN32)
    return GetFileAttributesW(wstr().c_str()) != INVALID_FILE_ATTRIBUTES;
#else
    struct stat sb;
    return stat(str().c_str(), &sb) == 0;
#endif
}

size_t Path::fileSize() const {
#if defined(_WIN32)
    struct _stati64 sb;
    if (_wstati64(wstr().c_str(), &sb) != 0)
        throw std::runtime_error("path::file_size(): cannot stat file \"" + str() + "\"!");
#else
    struct stat sb;
    if (stat(str().c_str(), &sb) != 0)
        throw std::runtime_error("path::file_size(): cannot stat file \"" + str() + "\"!");
#endif
    return (size_t)sb.st_size;
}

bool Path::isDirectory() const {
#if defined(_WIN32)
    DWORD result = GetFileAttributesW(wstr().c_str());
    if (result == INVALID_FILE_ATTRIBUTES)
        return false;
    return (result & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
    struct stat sb;
    if (stat(str().c_str(), &sb))
        return false;
    return S_ISDIR(sb.st_mode);
#endif
}

bool Path::isFile() const {
#if defined(_WIN32)
    DWORD attr = GetFileAttributesW(wstr().c_str());
    return (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0);
#else
    struct stat sb;
    if (stat(str().c_str(), &sb))
        return false;
    return S_ISREG(sb.st_mode);
#endif
}

bool Path::readFile(std::vector<char>& buffer) const {
#if defined(_WIN32)
    size_t size;
    try {
        size = fileSize();
    }
    catch (std::runtime_error&) {
        return false;
    }

    // + 1 for null terminator
    buffer.resize((uint32_t)size + 1);
    std::ifstream stream(str(), std::ios::binary);
    stream.read(buffer.data(), size);

    // null-terminate the buffer while we're at it
    buffer[(uint32_t)size] = '\0';

    return stream.good();
#else

    // TODO: report error
    int fd = open(str().c_str(), O_RDONLY | O_CLOEXEC);
    if (fd == -1)
        return false;

    struct stat sb;
    if (fstat(fd, &sb) != 0) {
        close(fd);
        return false;
    }

#ifndef __APPLE__
    posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
#endif

    // TODO: vector does initialization always, which is dumb
    off_t remaining = sb.st_size;
    buffer.resize((size_t)(remaining + 1));
    char* buf = buffer.data();

    while (remaining > 0) {
        ssize_t r = ::read(fd, buf, (size_t)remaining);
        if (r == -1) {
            close(fd);
            return false;
        }
        else if (r == 0) {
            buffer.resize(size_t((buf - buffer.data()) + 1));
            break;
        }
        else {
            buf += r;
            remaining -= r;
        }
    }

    close(fd);
    buffer.back() = '\0';
    return true;

#endif
}

std::string Path::str(PathType type) const {
    std::ostringstream oss;

    if (type == PosixPath && absolute)
        oss << "/";

    for (size_t i = 0; i < elements.size(); ++i) {
        oss << elements[i];
        if (i + 1 < elements.size()) {
            if (type == PosixPath)
                oss << '/';
            else
                oss << '\\';
        }
    }
    return oss.str();
}

void Path::set(const std::string& str, PathType type) {
    pathType = type;
    if (type == WindowsPath) {
        elements = tokenize(str, "/\\");
        absolute = str.size() >= 2 && std::isalpha(str[0]) && str[1] == ':';
    }
    else {
        elements = tokenize(str, "/");
        absolute = !str.empty() && str[0] == '/';
    }
}

Path Path::makeAbsolute(const Path& path) {
#if !defined(_WIN32)
    char temp[PATH_MAX];
    if (realpath(path.str().c_str(), temp) == nullptr)
        throw std::runtime_error("Internal error in realpath(): " + std::string(strerror(errno)));
    return Path(temp);
#else
    std::wstring value = path.wstr();
    std::wstring out(MAX_PATH, '\0');
    DWORD length = GetFullPathNameW(value.c_str(), MAX_PATH, &out[0], nullptr);
    if (length == 0)
        throw std::runtime_error("Internal error in GetFullPathNameW(): " + std::to_string(GetLastError()));
    return Path(out.substr(0, length));
#endif
}

Path Path::getCurrentDirectory() {
#if !defined(_WIN32)
    char temp[PATH_MAX];
    if (::getcwd(temp, PATH_MAX) == nullptr)
        throw std::runtime_error("Internal error in getcwd(): " + std::string(strerror(errno)));
    return Path(temp);
#else
    std::wstring temp(MAX_PATH, '\0');
    if (!_wgetcwd(&temp[0], MAX_PATH))
        throw std::runtime_error("Internal error in _wgetcwd(): " + std::to_string(GetLastError()));
    return Path(temp.c_str());
#endif
}

#if defined(_WIN32)
std::wstring Path::wstr(PathType type) const {
    std::string temp = str(type);
    int size = MultiByteToWideChar(CP_UTF8, 0, &temp[0], (int)temp.size(), NULL, 0);
    std::wstring result(size, 0);
    MultiByteToWideChar(CP_UTF8, 0, &temp[0], (int)temp.size(), &result[0], size);
    return result;
}

void Path::set(const std::wstring& wstring, PathType type) {
    std::string string;
    if (!wstring.empty()) {
        int size = WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(),
                                       NULL, 0, NULL, NULL);
        string.resize(size, 0);
        WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(),
                            &string[0], size, NULL, NULL);
    }
    set(string, type);
}
#endif

template<typename CharType>
static void findFilesImpl(const Path& path, std::vector<Path>& results, const CharType* extension, bool recurse) {
    std::vector<Path> directories;

#if defined(_WIN32)
    WIN32_FIND_DATAW ffd;
    std::wstring base = path.wstr() + L"\\";
    HANDLE hFind = FindFirstFileW((base + L"*").c_str(), &ffd);
    if (hFind == INVALID_HANDLE_VALUE)
        throw std::runtime_error("Internal error in FindFirstFile(): " + std::to_string(GetLastError()));

    do {
        if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
            const wchar_t* ext = wcsrchr(ffd.cFileName, '.');
            if (!extension || (ext && wcscmp(ext, extension) == 0))
                results.emplace_back(base + ffd.cFileName);
        }
        else if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) {
            directories.emplace_back(base + ffd.cFileName);
        }
    } while (FindNextFileW(hFind, &ffd) != 0);

    DWORD dwError = GetLastError();
    if (dwError != ERROR_NO_MORE_FILES)
        throw std::runtime_error("Internal error in FindNextFile(): " + std::to_string(dwError));
    FindClose(hFind);
#else
    DIR* d;
    struct dirent* dir;
    std::string base = path.str();
    if (base.back() != '/')
        base += '/';

    d = opendir(base.c_str());
    if (d) {
        while ((dir = readdir(d))) {
            if (dir->d_type == DT_REG) {
                const char* ext = strrchr(dir->d_name, '.');
                if (!extension || (ext && strcmp(ext, extension) == 0))
                    results.emplace_back(base + dir->d_name);
            }
            else if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0) {
                directories.emplace_back(base + dir->d_name);
            }
        }
        closedir(d);
    }
#endif

    if (recurse) {
        for (const auto& directory : directories)
            findFilesImpl(directory, results, extension, recurse);
    }
}

std::vector<Path> Path::findFiles(const Path& path, string_view extension, bool recurse) {
#if defined(_WIN32)
    std::wstring extensionCheck;
    if (!extension.empty()) {
        int size = MultiByteToWideChar(CP_UTF8, 0, extension.data(), (int)extension.length(), NULL, 0);
        extensionCheck.resize(size, 0);
        MultiByteToWideChar(CP_UTF8, 0, extension.data(), (int)extension.length(), &extensionCheck[0], size);
    }
#else
    std::string extensionCheck { extension };
#endif

    std::vector<Path> results;
    findFilesImpl(path, results, extensionCheck.c_str(), recurse);
    return results;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_access_token_store.h"

#include <utility>

#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/common/google_api_key.h"
#include "content/public/browser/geolocation_provider.h"

namespace atom {

namespace {

// Notice that we just combined the api key with the url together here, because
// if we use the standard {url: key} format Chromium would override our key with
// the predefined one in common.gypi of libchromiumcontent, which is empty.
const char* kGeolocationProviderURL =
    "https://www.googleapis.com/geolocation/v1/geolocate?key="
    GOOGLEAPIS_API_KEY;

}  // namespace

AtomAccessTokenStore::AtomAccessTokenStore() {
  content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
}

AtomAccessTokenStore::~AtomAccessTokenStore() {
}

void AtomAccessTokenStore::LoadAccessTokens(
    const LoadAccessTokensCallback& callback) {
  AccessTokenSet access_token_set;

  // Equivelent to access_token_set[kGeolocationProviderURL].
  // Somehow base::string16 is causing compilation errors when used in a pair
  // of std::map on Linux, this can work around it.
  std::pair<GURL, base::string16> token_pair;
  token_pair.first = GURL(kGeolocationProviderURL);
  access_token_set.insert(token_pair);

  auto browser_context = AtomBrowserMainParts::Get()->browser_context();
  callback.Run(access_token_set, browser_context->url_request_context_getter());
}

void AtomAccessTokenStore::SaveAccessToken(const GURL& server_url,
                                           const base::string16& access_token) {
}

}  // namespace atom
<commit_msg>AccessTokenSet -> AccessTokenMap<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_access_token_store.h"

#include <utility>

#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/common/google_api_key.h"
#include "content/public/browser/geolocation_provider.h"

namespace atom {

namespace {

// Notice that we just combined the api key with the url together here, because
// if we use the standard {url: key} format Chromium would override our key with
// the predefined one in common.gypi of libchromiumcontent, which is empty.
const char* kGeolocationProviderURL =
    "https://www.googleapis.com/geolocation/v1/geolocate?key="
    GOOGLEAPIS_API_KEY;

}  // namespace

AtomAccessTokenStore::AtomAccessTokenStore() {
  content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
}

AtomAccessTokenStore::~AtomAccessTokenStore() {
}

void AtomAccessTokenStore::LoadAccessTokens(
    const LoadAccessTokensCallback& callback) {
  AccessTokenMap access_token_map;

  // Equivelent to access_token_map[kGeolocationProviderURL].
  // Somehow base::string16 is causing compilation errors when used in a pair
  // of std::map on Linux, this can work around it.
  std::pair<GURL, base::string16> token_pair;
  token_pair.first = GURL(kGeolocationProviderURL);
  access_token_map.insert(token_pair);

  auto browser_context = AtomBrowserMainParts::Get()->browser_context();
  callback.Run(access_token_map, browser_context->url_request_context_getter());
}

void AtomAccessTokenStore::SaveAccessToken(const GURL& server_url,
                                           const base::string16& access_token) {
}

}  // namespace atom
<|endoftext|>


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

/*************************************************************************
 *
 *    ATTENTION
 *    This file is intended to work inside and outside the StarOffice environment.
 *    Only adaption of file commtypes.hxx should be necessary. Else it is a bug!
 *
 ************************************************************************/

#ifndef _CMDBASESTREAM_HXX_
#define _CMDBASESTREAM_HXX_

#include <automation/commtypes.hxx>
#include "icommstream.hxx"

class CmdBaseStream
{
protected:
    ICommStream* pCommStream;
    CmdBaseStream();
    virtual ~CmdBaseStream();

public:

    void GenError( SmartId *pUId, comm_String *pString );

    void GenReturn( comm_USHORT nRet, comm_ULONG nNr );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_ULONG nNr );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_String *pString );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_BOOL bBool );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_ULONG nNr, comm_String *pString, comm_BOOL bBool );

// MacroRecorder
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_String *pString );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_String *pString, comm_BOOL bBool );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_BOOL bBool );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_ULONG nNr );

    void Read ( comm_USHORT &nNr );
    void Read ( comm_ULONG &nNr );
    void Read (comm_UniChar* &aString, comm_USHORT &nLenInChars );
    void Read ( comm_BOOL &bBool );
    comm_USHORT GetNextType();

    void Write( comm_USHORT nNr );
    void Write( comm_ULONG nNr );
    void Write( const comm_UniChar* aString, comm_USHORT nLenInChars );
    void Write( comm_BOOL bBool );

// Complex Datatypes to be handled system dependent
    virtual void Read ( comm_String *&pString );
    virtual void Read ( SmartId* &pId );

    virtual void Write( comm_String *pString );
    virtual void Write( SmartId* pId );
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.40); FILE MERGED 2008/03/28 16:03:35 rt 1.5.40.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cmdbasestream.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

/*************************************************************************
 *
 *    ATTENTION
 *    This file is intended to work inside and outside the StarOffice environment.
 *    Only adaption of file commtypes.hxx should be necessary. Else it is a bug!
 *
 ************************************************************************/

#ifndef _CMDBASESTREAM_HXX_
#define _CMDBASESTREAM_HXX_

#include <automation/commtypes.hxx>
#include "icommstream.hxx"

class CmdBaseStream
{
protected:
    ICommStream* pCommStream;
    CmdBaseStream();
    virtual ~CmdBaseStream();

public:

    void GenError( SmartId *pUId, comm_String *pString );

    void GenReturn( comm_USHORT nRet, comm_ULONG nNr );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_ULONG nNr );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_String *pString );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_BOOL bBool );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_ULONG nNr, comm_String *pString, comm_BOOL bBool );

// MacroRecorder
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_String *pString );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_String *pString, comm_BOOL bBool );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_BOOL bBool );
    void GenReturn( comm_USHORT nRet, SmartId *pUId, comm_USHORT nMethod, comm_ULONG nNr );

    void Read ( comm_USHORT &nNr );
    void Read ( comm_ULONG &nNr );
    void Read (comm_UniChar* &aString, comm_USHORT &nLenInChars );
    void Read ( comm_BOOL &bBool );
    comm_USHORT GetNextType();

    void Write( comm_USHORT nNr );
    void Write( comm_ULONG nNr );
    void Write( const comm_UniChar* aString, comm_USHORT nLenInChars );
    void Write( comm_BOOL bBool );

// Complex Datatypes to be handled system dependent
    virtual void Read ( comm_String *&pString );
    virtual void Read ( SmartId* &pId );

    virtual void Write( comm_String *pString );
    virtual void Write( SmartId* pId );
};

#endif
<|endoftext|>


<commit_before>/*++++++++++++++++++++INCLUDES+and+Definitions++++++++++++++++++++++++*/

#include <vigra/matlab.hxx>
#include <vigra/labelimage.hxx>
#include <vigra/labelvolume.hxx>
#include <vigra/matlab_FLEXTYPE.hxx>

//this could be a typedef but if you want outType to be the same type as inType then you can just
//set outType to T

using namespace vigra;
using namespace matlab;

//#define RN_DEBUG
#define cP3_(a, b , c) cP3<a, b, c>::value
template <class T>
void vigraMain(matlab::OutputArray outputs, matlab::InputArray inputs){

    /***************************************************************************************************
    **              INIT PART                                                                         **
    ****************************************************************************************************/
    MultiArrayView<3,T>     in3D        =       inputs.getMultiArray<3,T>(0, Required());
    BasicImageView<T>       in          =       makeBasicImageView(in3D.bindOuter(0));
    int                     numOfDim    =       inputs.getDimOfInput(0, Required());

    int                     v2Dconn[2]  =       {8, 4};
    int                     v3Dconn[2]  =       {26, 6};
    int                     connectivity=       inputs.getScalarVals2D3D<int>("conn", v_default(8,26,numOfDim),
                                                                                v2Dconn, v2Dconn+2,
                                                                                v3Dconn, v3Dconn+2,
                                                                                numOfDim);
    /*{
        if(numOfDim == 2 && connectivity!= 8 && connectivity != 4)
            mexErrMsgTxt("Connectivity for 2D data must be 8 or 4");
        else if(numOfDim == 3 && connectivity!= 26 && connectivity != 6)
            mexErrMsgTxt("Connectivity for 3D data must be 26 or 6");
    }*/

    bool                    hasBackground;
    T                       backgroundValue = inputs.getScalar<T>("backgroundValue", v_optional(hasBackground));

    MultiArrayView<3,T>     out3D           = outputs.createMultiArray      <3,T>   (0, v_required(), in3D.shape());
    BasicImageView<T>       out(out3D.data(), in3D.shape(0), in3D.shape(1));

    int                     max_region_label = (hasBackground == true)? 1: 0;

    /***************************************************************************************************
    **              CODE PART                                                                         **
    ****************************************************************************************************/
    #ifdef RN_DEBUG
    mexPrintf("---%d---%d---%d---", max_region_label, numOfDim, connectivity);
    #endif
    switch(cantorPair(hasBackground , numOfDim, connectivity)){
        //cP is the templated version o f the cantorPair function first value is Dimension of Inputimage, second the connectivity setting
        //Code is basically the code on the VIGRA-reference page
        case cP3_(0, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 8");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), true);
            break;
        case cP3_(0, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 4");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), false);
            break;
        case cP3_(0, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 26");
            #endif
            max_region_label = labelVolumeSix(srcMultiArrayRange(in3D), destMultiArray(out3D));
            break;
        case cP3_(0, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 6");
            #endif
            max_region_label = labelVolume(srcMultiArrayRange(in3D), destMultiArray(out3D), NeighborCode3DTwentySix());
            break;
        case cP3_(1, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 8");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), true, backgroundValue);
            break;
        case cP3_(1, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 4");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), false, backgroundValue);
            break;
        case cP3_(1, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 26");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DSix(), backgroundValue);
            break;
        case cP3_(1, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 6");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DTwentySix(), backgroundValue);
            break;
        default:
            mexErrMsgTxt("Something went wrong");
    }

    outputs.createScalar<int> (1, v_optional(), max_region_label);
}

/***************************************************************************************************
**           VIGRA GATEWAY                                                                        **
****************************************************************************************************/
void vigraMexFunction(vigra::matlab::OutputArray outputs, vigra::matlab::InputArray inputs)
{
    /*
    FLEXIBLE_TYPE_START(0, in);
        ALLOW_D;
    FLEXIBLE_TYPE_END;
    */

    //mxClassID inClass;
    //FLEX_TYPE(inClass, 0, in);
    switch(inputs.typeOf(0))
    {
        ALLOW_FD
	ALLOW_UINT_8_64
	ALLOW_INT_8_64
        default:
	    mexErrMsgTxt("Type of input 0 not supported");
    }
}

/*+++++++++++++++++++++++MexEntryFunc++++++++++++++++++++++++++++++++*/
/* Gatewayfunction - see matlab.hxx for details.
/* if a certain class is NOT supported - you will have to copy the
/* body of the callMexFunctor function and edit it here.
/* Supports (u)int[8|16|32|64], float and double.
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/** MATLAB
function D = vigraConnectedComponents(inputArray)
function D = vigraConnectedComponents(inputArray, options);

D = vigraConnectedComponents(inputArray) performs connected components labeling
        using the default options.
D = vigraConnectedComponents(inputImage, options)  does the same with user options.

inputArray - a 2D or 3D array of numeric type

options    - is a struct with the following possible fields:
    'conn':            The neighborhood to be used
                       2D: 4 (default) or  8
                       3D: 6 (default) or 26
    'backgroundValue': Specify the value of a background region not to be labeled (will be labeled 0
                       in the result array, even when it doesn't form a single connected component).
                       If this option in not present, the entire image/volume will be labeled.

Usage:
    opt = struct('conn', 8);
    out = vigraConnectedComponents(in, opt);

*/
<commit_msg>added typedef for outtype<commit_after>/*++++++++++++++++++++INCLUDES+and+Definitions++++++++++++++++++++++++*/

#include <vigra/matlab.hxx>
#include <vigra/labelimage.hxx>
#include <vigra/labelvolume.hxx>
#include <vigra/matlab_FLEXTYPE.hxx>

//this could be a typedef but if you want outType to be the same type as inType then you can just
//set outType to T

using namespace vigra;
using namespace matlab;

//#define RN_DEBUG
#define cP3_(a, b , c) cP3<a, b, c>::value
template <class T>
void vigraMain(matlab::OutputArray outputs, matlab::InputArray inputs){

    /***************************************************************************************************
    **              INIT PART                                                                         **
    ***************************************************************************************************/
    typedef UInt32 OutputType
    MultiArrayView<3,T>     in3D        =       inputs.getMultiArray<3,T>(0, Required());
    BasicImageView<T>       in          =       makeBasicImageView(in3D.bindOuter(0));
    int                     numOfDim    =       inputs.getDimOfInput(0, Required());

    int                     v2Dconn[2]  =       {8, 4};
    int                     v3Dconn[2]  =       {26, 6};
    int                     connectivity=       inputs.getScalarVals2D3D<int>("conn", v_default(8,26,numOfDim),
                                                                                v2Dconn, v2Dconn+2,
                                                                                v3Dconn, v3Dconn+2,
                                                                                numOfDim);
    /*{
        if(numOfDim == 2 && connectivity!= 8 && connectivity != 4)
            mexErrMsgTxt("Connectivity for 2D data must be 8 or 4");
        else if(numOfDim == 3 && connectivity!= 26 && connectivity != 6)
            mexErrMsgTxt("Connectivity for 3D data must be 26 or 6");
    }*/

    bool                    hasBackground;
    T                       backgroundValue = inputs.getScalar<T>("backgroundValue", v_optional(hasBackground));

    MultiArrayView<3,outputType>     out3D           = outputs.createMultiArray      <3,outputType>   (0, v_required(), in3D.shape());
    BasicImageView<outputType>       out(out3D.data(), in3D.shape(0), in3D.shape(1));

    int                     max_region_label = (hasBackground == true)? 1: 0;

    /***************************************************************************************************
    **              CODE PART                                                                         **
    ****************************************************************************************************/
    #ifdef RN_DEBUG
    mexPrintf("---%d---%d---%d---", max_region_label, numOfDim, connectivity);
    #endif
    switch(cantorPair(hasBackground , numOfDim, connectivity)){
        //cP is the templated version o f the cantorPair function first value is Dimension of Inputimage, second the connectivity setting
        //Code is basically the code on the VIGRA-reference page
        case cP3_(0, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 8");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), true);
            break;
        case cP3_(0, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 4");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), false);
            break;
        case cP3_(0, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 26");
            #endif
            max_region_label = labelVolumeSix(srcMultiArrayRange(in3D), destMultiArray(out3D));
            break;
        case cP3_(0, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 6");
            #endif
            max_region_label = labelVolume(srcMultiArrayRange(in3D), destMultiArray(out3D), NeighborCode3DTwentySix());
            break;
        case cP3_(1, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 8");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), true, backgroundValue);
            break;
        case cP3_(1, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 4");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), false, backgroundValue);
            break;
        case cP3_(1, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 26");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DSix(), backgroundValue);
            break;
        case cP3_(1, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 6");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DTwentySix(), backgroundValue);
            break;
        default:
            mexErrMsgTxt("Something went wrong");
    }

    outputs.createScalar<int> (1, v_optional(), max_region_label);
}

/***************************************************************************************************
**           VIGRA GATEWAY                                                                        **
****************************************************************************************************/
void vigraMexFunction(vigra::matlab::OutputArray outputs, vigra::matlab::InputArray inputs)
{
    /*
    FLEXIBLE_TYPE_START(0, in);
        ALLOW_D;
    FLEXIBLE_TYPE_END;
    */

    //mxClassID inClass;
    //FLEX_TYPE(inClass, 0, in);
    switch(inputs.typeOf(0))
    {
        ALLOW_FD
	ALLOW_UINT_8_64
	ALLOW_INT_8_64
        default:
	    mexErrMsgTxt("Type of input 0 not supported");
    }
}

/*+++++++++++++++++++++++MexEntryFunc++++++++++++++++++++++++++++++++*/
/* Gatewayfunction - see matlab.hxx for details.
/* if a certain class is NOT supported - you will have to copy the
/* body of the callMexFunctor function and edit it here.
/* Supports (u)int[8|16|32|64], float and double.
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/** MATLAB
function D = vigraConnectedComponents(inputArray)
function D = vigraConnectedComponents(inputArray, options);

D = vigraConnectedComponents(inputArray) performs connected components labeling
        using the default options.
D = vigraConnectedComponents(inputImage, options)  does the same with user options.

inputArray - a 2D or 3D array of numeric type

options    - is a struct with the following possible fields:
    'conn':            The neighborhood to be used
                       2D: 4 (default) or  8
                       3D: 6 (default) or 26
    'backgroundValue': Specify the value of a background region not to be labeled (will be labeled 0
                       in the result array, even when it doesn't form a single connected component).
                       If this option in not present, the entire image/volume will be labeled.

Usage:
    opt = struct('conn', 8);
    out = vigraConnectedComponents(in, opt);

*/
<|endoftext|>


<commit_before>#if !defined(HAVE_CORECLR) && !defined(HAVE_NATIVECLR)
#error "CoreCLR and/or a native .NET runtime (native .NET on Windows or Mono on Linux) must be installed in order for Edge.js to compile."
#endif

#include "edge_common.h"

#ifdef HAVE_CORECLR
#include "../CoreCLREmbedding/edge.h"
#endif
#ifdef HAVE_NATIVECLR
#ifdef EDGE_PLATFORM_WINDOWS
#include "../dotnet/edge.h"
#else
#include "../mono/edge.h"
#endif
#endif

BOOL debugMode;
BOOL enableScriptIgnoreAttribute;
BOOL enableMarshalEnumAsInt;

NAN_METHOD(initializeClrFunc)
{
#ifdef HAVE_NATIVECLR
#ifdef HAVE_CORECLR
	if (HasEnvironmentVariable("EDGE_USE_CORECLR"))
	{
		CoreClrFunc::Initialize(info);
	}

#endif
	ClrFunc::Initialize(info);
#else
	CoreClrFunc::Initialize(info);
#endif
}

#ifdef EDGE_PLATFORM_WINDOWS
#pragma unmanaged
#endif
NAN_MODULE_INIT(init)
{
    debugMode = HasEnvironmentVariable("EDGE_DEBUG");
    DBG("edge::init");

    V8SynchronizationContext::Initialize();
    CallbackHelper::Initialize();

#ifdef HAVE_CORECLR
    if (FAILED(CoreClrEmbedding::Initialize(debugMode)))
	{
		DBG("Error occurred during CoreCLR initialization");
		return;
	}
#else
#ifndef EDGE_PLATFORM_WINDOWS
    MonoEmbedding::Initialize();
#endif
#endif

    enableScriptIgnoreAttribute = HasEnvironmentVariable("EDGE_ENABLE_SCRIPTIGNOREATTRIBUTE");
    enableMarshalEnumAsInt = HasEnvironmentVariable("EDGE_MARSHAL_ENUM_AS_INT");
    Nan::Set(target,
        Nan::New<v8::String>("initializeClrFunc").ToLocalChecked(),
        Nan::GetFunction(Nan::New<v8::FunctionTemplate>(initializeClrFunc)).ToLocalChecked());
}

#ifdef EDGE_PLATFORM_WINDOWS
#pragma unmanaged
#endif
bool HasEnvironmentVariable(const char* variableName)
{
#ifdef EDGE_PLATFORM_WINDOWS
    return 0 < GetEnvironmentVariable(variableName, NULL, 0);
#else
    return getenv(variableName) != NULL;
#endif
}

#ifdef EDGE_PLATFORM_WINDOWS
#pragma unmanaged
#endif
#ifdef HAVE_CORECLR
        #if NODE_MAJOR_VERSION >= 18
		NAN_MODULE_WORKER_ENABLED(edge_coreclr, init)
	#else
		NODE_MODULE(edge_coreclr, init)
	#endif
#else
	#if NODE_MAJOR_VERSION >= 18
		NAN_MODULE_WORKER_ENABLED(edge_nativeclr, init)
	#else
		NODE_MODULE(edge_nativeclr, init)
	#endif
#endif

// vim: ts=4 sw=4 et:
<commit_msg>Fixing an issue with NodeJs 18.x: https://github.com/agracio/edge-js/issues/163<commit_after>#if !defined(HAVE_CORECLR) && !defined(HAVE_NATIVECLR)
#error "CoreCLR and/or a native .NET runtime (native .NET on Windows or Mono on Linux) must be installed in order for Edge.js to compile."
#endif

#include "edge_common.h"

#ifdef HAVE_CORECLR
#include "../CoreCLREmbedding/edge.h"
#endif
#ifdef HAVE_NATIVECLR
#ifdef EDGE_PLATFORM_WINDOWS
#include "../dotnet/edge.h"
#else
#include "../mono/edge.h"
#endif
#endif

BOOL debugMode;
BOOL enableScriptIgnoreAttribute;
BOOL enableMarshalEnumAsInt;

NAN_METHOD(initializeClrFunc)
{
#ifdef HAVE_NATIVECLR
#ifdef HAVE_CORECLR
	if (HasEnvironmentVariable("EDGE_USE_CORECLR"))
	{
		CoreClrFunc::Initialize(info);
	}

#endif
	ClrFunc::Initialize(info);
#else
	CoreClrFunc::Initialize(info);
#endif
}

#ifdef EDGE_PLATFORM_WINDOWS
#pragma unmanaged
#endif
NAN_MODULE_INIT(init)
{
    debugMode = HasEnvironmentVariable("EDGE_DEBUG");
    DBG("edge::init");

    V8SynchronizationContext::Initialize();
    CallbackHelper::Initialize();

#ifdef HAVE_CORECLR
    if (FAILED(CoreClrEmbedding::Initialize(debugMode)))
	{
		DBG("Error occurred during CoreCLR initialization");
		return;
	}
#else
#ifndef EDGE_PLATFORM_WINDOWS
    MonoEmbedding::Initialize();
#endif
#endif

    enableScriptIgnoreAttribute = HasEnvironmentVariable("EDGE_ENABLE_SCRIPTIGNOREATTRIBUTE");
    enableMarshalEnumAsInt = HasEnvironmentVariable("EDGE_MARSHAL_ENUM_AS_INT");
    Nan::Set(target,
        Nan::New<v8::String>("initializeClrFunc").ToLocalChecked(),
        Nan::GetFunction(Nan::New<v8::FunctionTemplate>(initializeClrFunc)).ToLocalChecked());
}

#ifdef EDGE_PLATFORM_WINDOWS
#pragma unmanaged
#endif
bool HasEnvironmentVariable(const char* variableName)
{
#ifdef EDGE_PLATFORM_WINDOWS
    return 0 < GetEnvironmentVariable(variableName, NULL, 0);
#else
    return getenv(variableName) != NULL;
#endif
}

#ifdef EDGE_PLATFORM_WINDOWS
#pragma unmanaged
#endif
#ifdef HAVE_CORECLR
        #if NODE_MAJOR_VERSION >= 10
		NAN_MODULE_WORKER_ENABLED(edge_coreclr, init)
	#else
		NODE_MODULE(edge_coreclr, init)
	#endif
#else
	#if NODE_MAJOR_VERSION >= 10
		NAN_MODULE_WORKER_ENABLED(edge_nativeclr, init)
	#else
		NODE_MODULE(edge_nativeclr, init)
	#endif
#endif

// vim: ts=4 sw=4 et:
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <vector>

#include <mesos/resources.hpp>

#include <stout/foreach.hpp>
#include <stout/protobuf.hpp>
#include <stout/stringify.hpp>

#include "common/attributes.hpp"
#include "common/http.hpp"

#include "messages/messages.hpp"

using std::vector;

namespace mesos {

// TODO(bmahler): Kill these in favor of automatic Proto->JSON
// Conversion (when it becomes available).

JSON::Object model(const Resources& resources)
{
  JSON::Object object;
  object.values["cpus"] = 0;
  object.values["mem"] = 0;
  object.values["disk"] = 0;

  const Option<double>& cpus = resources.cpus();
  if (cpus.isSome()) {
    object.values["cpus"] = cpus.get();
  }

  const Option<Bytes>& mem = resources.mem();
  if (mem.isSome()) {
    object.values["mem"] = mem.get().megabytes();
  }

  const Option<Bytes>& disk = resources.disk();
  if (disk.isSome()) {
    object.values["disk"] = disk.get().megabytes();
  }

  const Option<Value::Ranges>& ports = resources.ports();
  if (ports.isSome()) {
    object.values["ports"] = stringify(ports.get());
  }

  return object;
}

JSON::Object model(const Attributes& attributes)
{
  JSON::Object object;

  foreach (const Attribute& attribute, attributes) {
    switch (attribute.type()) {
      case Value::SCALAR:
        object.values[attribute.name()] = attribute.scalar().value();
        break;
      case Value::RANGES:
        object.values[attribute.name()] = stringify(attribute.ranges());
        break;
      case Value::SET:
        object.values[attribute.name()] = stringify(attribute.set());
        break;
      case Value::TEXT:
        object.values[attribute.name()] = attribute.text().value();
        break;
      default:
        LOG(FATAL) << "Unexpected Value type: " << attribute.type();
        break;
    }
  }

  return object;
}

// Returns a JSON object modeled on a TaskStatus.
JSON::Object model(const TaskStatus& status)
{
  JSON::Object object;
  object.values["state"] = TaskState_Name(status.state());
  object.values["timestamp"] = status.timestamp();

  return object;
}

// TODO(bmahler): Expose the executor name / source.
JSON::Object model(const Task& task)
{
  JSON::Object object;
  object.values["id"] = task.task_id().value();
  object.values["name"] = task.name();
  object.values["framework_id"] = task.framework_id().value();

  if (task.has_executor_id()) {
    object.values["executor_id"] = task.executor_id().value();
  } else {
    object.values["executor_id"] = "";
  }

  object.values["slave_id"] = task.slave_id().value();
  object.values["state"] = TaskState_Name(task.state());
  object.values["resources"] = model(task.resources());

  JSON::Array array;
  foreach (const TaskStatus& status, task.statuses()) {
    array.values.push_back(model(status));
  }
  object.values["statuses"] = array;

  JSON::Array labels;
  if (task.has_labels()) {
    foreach (const Label& label, task.labels().labels()) {
      labels.values.push_back(JSON::Protobuf(label));
    }
  }
  object.values["labels"] = labels;

  if (task.has_discovery()) {
    object.values["discovery"] = JSON::Protobuf(task.discovery());
  }

  return object;
}

// TODO(bmahler): Expose the executor name / source.
JSON::Object model(
    const TaskInfo& task,
    const FrameworkID& frameworkId,
    const TaskState& state,
    const vector<TaskStatus>& statuses)
{
  JSON::Object object;
  object.values["id"] = task.task_id().value();
  object.values["name"] = task.name();
  object.values["framework_id"] = frameworkId.value();

  if (task.has_executor()) {
    object.values["executor_id"] = task.executor().executor_id().value();
  } else {
    object.values["executor_id"] = "";
  }

  object.values["slave_id"] = task.slave_id().value();
  object.values["state"] = TaskState_Name(state);
  object.values["resources"] = model(task.resources());

  JSON::Array array;
  foreach (const TaskStatus& status, statuses) {
    array.values.push_back(model(status));
  }
  object.values["statuses"] = array;

  JSON::Array labels;
  if (task.has_labels()) {
    foreach (const Label& label, task.labels().labels()) {
      labels.values.push_back(JSON::Protobuf(label));
    }
  }
  object.values["labels"] = labels;

  if (task.has_discovery()) {
    object.values["discovery"] = JSON::Protobuf(task.discovery());
  }

  return object;
}

}  // namespace mesos {
<commit_msg>Included all resources in state endpoint.<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <vector>

#include <mesos/resources.hpp>

#include <stout/foreach.hpp>
#include <stout/protobuf.hpp>
#include <stout/stringify.hpp>

#include "common/attributes.hpp"
#include "common/http.hpp"

#include "messages/messages.hpp"

using std::vector;

namespace mesos {

// TODO(bmahler): Kill these in favor of automatic Proto->JSON
// Conversion (when it becomes available).

JSON::Object model(const Resources& resources)
{
  JSON::Object object;
  object.values["cpus"] = 0;
  object.values["mem"] = 0;
  object.values["disk"] = 0;

  foreach (const Resource& resource, resources)
  {
    switch(resource.type())
    {
      case Value::SCALAR:
        object.values[resource.name()] = resource.scalar().value();
        break;
      case Value::RANGES:
        object.values[resource.name()] = stringify(resource.ranges());
        break;
      case Value::SET:
        object.values[resource.name()] = stringify(resource.set());
        break;
      default:
        LOG(FATAL) << "Unexpected Value type: " << resource.type();
    }
  }

  return object;
}

JSON::Object model(const Attributes& attributes)
{
  JSON::Object object;

  foreach (const Attribute& attribute, attributes) {
    switch (attribute.type()) {
      case Value::SCALAR:
        object.values[attribute.name()] = attribute.scalar().value();
        break;
      case Value::RANGES:
        object.values[attribute.name()] = stringify(attribute.ranges());
        break;
      case Value::SET:
        object.values[attribute.name()] = stringify(attribute.set());
        break;
      case Value::TEXT:
        object.values[attribute.name()] = attribute.text().value();
        break;
      default:
        LOG(FATAL) << "Unexpected Value type: " << attribute.type();
        break;
    }
  }

  return object;
}

// Returns a JSON object modeled on a TaskStatus.
JSON::Object model(const TaskStatus& status)
{
  JSON::Object object;
  object.values["state"] = TaskState_Name(status.state());
  object.values["timestamp"] = status.timestamp();

  return object;
}

// TODO(bmahler): Expose the executor name / source.
JSON::Object model(const Task& task)
{
  JSON::Object object;
  object.values["id"] = task.task_id().value();
  object.values["name"] = task.name();
  object.values["framework_id"] = task.framework_id().value();

  if (task.has_executor_id()) {
    object.values["executor_id"] = task.executor_id().value();
  } else {
    object.values["executor_id"] = "";
  }

  object.values["slave_id"] = task.slave_id().value();
  object.values["state"] = TaskState_Name(task.state());
  object.values["resources"] = model(task.resources());

  JSON::Array array;
  foreach (const TaskStatus& status, task.statuses()) {
    array.values.push_back(model(status));
  }
  object.values["statuses"] = array;

  JSON::Array labels;
  if (task.has_labels()) {
    foreach (const Label& label, task.labels().labels()) {
      labels.values.push_back(JSON::Protobuf(label));
    }
  }
  object.values["labels"] = labels;

  if (task.has_discovery()) {
    object.values["discovery"] = JSON::Protobuf(task.discovery());
  }

  return object;
}

// TODO(bmahler): Expose the executor name / source.
JSON::Object model(
    const TaskInfo& task,
    const FrameworkID& frameworkId,
    const TaskState& state,
    const vector<TaskStatus>& statuses)
{
  JSON::Object object;
  object.values["id"] = task.task_id().value();
  object.values["name"] = task.name();
  object.values["framework_id"] = frameworkId.value();

  if (task.has_executor()) {
    object.values["executor_id"] = task.executor().executor_id().value();
  } else {
    object.values["executor_id"] = "";
  }

  object.values["slave_id"] = task.slave_id().value();
  object.values["state"] = TaskState_Name(state);
  object.values["resources"] = model(task.resources());

  JSON::Array array;
  foreach (const TaskStatus& status, statuses) {
    array.values.push_back(model(status));
  }
  object.values["statuses"] = array;

  JSON::Array labels;
  if (task.has_labels()) {
    foreach (const Label& label, task.labels().labels()) {
      labels.values.push_back(JSON::Protobuf(label));
    }
  }
  object.values["labels"] = labels;

  if (task.has_discovery()) {
    object.values["discovery"] = JSON::Protobuf(task.discovery());
  }

  return object;
}

}  // namespace mesos {
<|endoftext|>