text:
#pragma once

#ifndef GEODE_FWKLIB_FWKOBJECTS_H_
#define GEODE_FWKLIB_FWKOBJECTS_H_

#include <chrono>
#include <vector>
#include <list>
#include <map>

#include <errno.h>

#include <ace/OS.h>

#include <geode/Cache.hpp>
#include <geode/Properties.hpp>
#include <geode/ExpirationAction.hpp>
#include <geode/RegionAttributes.hpp>
#include <geode/RegionAttributesFactory.hpp>
#include <geode/PoolManager.hpp>
#include <geode/internal/chrono/duration.hpp>

#include "fwklib/FwkStrCvt.hpp"
#include "fwklib/FwkLog.hpp"

#include "fwklib/GsRandom.hpp"

#include <xercesc/dom/DOM.hpp>

XERCES_CPP_NAMESPACE_USE

using namespace apache::geode::client::testframework;

#define HOSTGROUP_TAG "hostGroup"
#define LOCALFILE_TAG "localFile"
#define DATA_TAG "data"
#define DATASET_TAG "data-set"
#define CLIENTSET_TAG "client-set"
#define TEST_TAG "test"
#define ONEOF_TAG "oneof"
#define LIST_TAG "list"
#define RANGE_TAG "range"
#define SNIPPET_TAG "snippet"
#define REGION_TAG "region"
#define POOL_TAG "pool"
#define TASK_TAG "task"
#define CLIENT_TAG "client"
#define ITEM_TAG "item"
#define REGIONTIMETOLIVE_TAG "region-time-to-live"
#define REGIONIDLETIME_TAG "region-idle-time"
#define ENTRYTIMETOLIVE_TAG "entry-time-to-live"
#define ENTRYIDLETIME_TAG "entry-idle-time"
#define CACHELOADER_TAG "cache-loader"
#define CACHELISTENER_TAG "cache-listener"
#define CACHEWRITER_TAG "cache-writer"
#define PERSISTENCEMANAGER_TAG "persistence-manager"
#define PROPERTIES_TAG "properties"
#define PROPERTY_TAG "property"

#define CLIENT_STATUS_BB "clientStatusBB"

namespace apache {
namespace geode {
namespace client {
namespace testframework {

// ----------------------------------------------------------------------------

#define FWK_SUCCESS 0
#define FWK_WARNING 1
#define FWK_ERROR 2
#define FWK_SEVERE 3

// ----------------------------------------------------------------------------

/** @brief Table of object enumeration data types */
typedef enum eFwkDataType {
  DATA_TYPE_NULL,
  DATA_TYPE_CONTENT,
  DATA_TYPE_LIST,
  DATA_TYPE_ONEOF,
  DATA_TYPE_RANGE,
  DATA_TYPE_SNIPPET
} tFwkDataType;

// ----------------------------------------------------------------------------

class FwkObject {
  std::string m_name;

 public:
  FwkObject() {}
  virtual ~FwkObject() {}

  void setName(std::string name) { m_name = name; }
  const std::string& getName() const { return m_name; }

  /** @brief Get key string */
  virtual const std::string& getKey() const = 0;
  virtual void print() const = 0;
};

// ----------------------------------------------------------------------------

/**
 * @class TFwkSet
 *
 * @brief Framework base data object set template
 */

template <class FWK_OBJECT>
class TFwkSet {
 private:
  std::string m_name;
  bool m_deleteOnClear;
  std::vector<const FWK_OBJECT*> m_vec;

 public:
  TFwkSet() : m_deleteOnClear(true) {}

  ~TFwkSet() { clear(); }

  const std::string& getName() const { return m_name; }

  void setName(std::string name) { m_name = name; }

  void setNoDelete() { m_deleteOnClear = false; }

  /** @brief Prints collection of objects */
  void print() const {
    const FWK_OBJECT* obj = getFirst();
    while (obj != NULL) {
      obj->print();
      obj = getNext(obj);
    }
  }

  /** @brief Find a object in collection
   * @param key Object key to find
   */
  const FWK_OBJECT* find(const std::string& key) const {
    const FWK_OBJECT* obj = NULL;
    int32_t pos = findIdx(key);
    if (pos != -1) {
      obj = m_vec.at(pos);
    }
    return obj;
  }

  /** @brief Get first object in collection */
  const FWK_OBJECT* getFirst() const {
    const FWK_OBJECT* obj = NULL;
    int32_t siz = static_cast<int32_t>(m_vec.size());
    if (siz > 0) {
      return m_vec.at(0);
    }
    return obj;
  }

  /** @brief Get next object in collection */
  const FWK_OBJECT* getNext(const FWK_OBJECT* prev) const {
    const FWK_OBJECT* obj = NULL;
    if (prev == NULL) {
      return getFirst();
    }
    int32_t siz = static_cast<int32_t>(m_vec.size());
    if (siz > 0) {
      const std::string key = prev->getKey();
      int32_t pos = findIdx(key);
      if (++pos < siz) {
        return m_vec.at(pos);
      }
    }
    return obj;
  }

  /** @brief Clears collection of objects */
  void clear() {
    int32_t siz = static_cast<int32_t>(m_vec.size());
    while (siz > 0) {
      const FWK_OBJECT* obj = m_vec.back();
      m_vec.pop_back();
      if (m_deleteOnClear) {
        delete obj;
      }
      siz = static_cast<int32_t>(m_vec.size());
    }
  }

  /** @brief Add an object
   * @param obj Object to add
   */
  void add(const FWK_OBJECT* obj) {
    if (obj != NULL) {
      m_vec.push_back(obj);
    }
  }

  const FWK_OBJECT* at(int32_t idx) const {
    if ((idx < 0) || (idx > size())) return NULL;
    return m_vec.at(idx);
  }

  /** @brief Get count of objects in collection */
  int32_t size() const { return static_cast<int32_t>(m_vec.size()); }

 private:
  int32_t findIdx(const std::string& key) const {
    int32_t idx = -1;
    if (!key.empty()) {
      int32_t pos = 0;
      int32_t max = static_cast<int32_t>(m_vec.size());
      while (pos < max) {
        const FWK_OBJECT* curr = (const FWK_OBJECT*)m_vec.at(pos);
        if (curr->getKey() == key) {
          idx = pos;
          max = -1;
        }
        pos++;
      }
    }
    return idx;
  }
};

// ----------------------------------------------------------------------------

typedef std::vector<std::string> StringVector;

// ----------------------------------------------------------------------------

/** @class XMLStringConverter
 * @brief  This is a simple class that lets us do easy (though not
 * terribly efficient) trancoding of char* data to XMLCh data.
 */
class XMLStringConverter {
 public:
  XMLStringConverter(const char* const toTranscode) {
    m_charForm = NULL;
    // Call the private transcoding method
    m_unicodeForm = XMLString::transcode(toTranscode);
  }

  XMLStringConverter(const XMLCh* toTranscode) {
    m_unicodeForm = NULL;
    m_charForm = XMLString::transcode(toTranscode);
  }

  ~XMLStringConverter() {
    if (m_unicodeForm) XMLString::release(&m_unicodeForm);
    if (m_charForm) XMLString::release(&m_charForm);
  }

  /** @brief  get unicode methods */
  const XMLCh* unicodeForm() const { return m_unicodeForm; }

  /** @brief  get char methods */
  std::string charForm() const {
    std::string sCharForm;
    if (m_charForm) sCharForm = m_charForm;
    return sCharForm;
  }

 private:
  XMLCh* m_unicodeForm;
  char* m_charForm;
};

// ----------------------------------------------------------------------------

/** @brief convert XMLCh to a string */
#define XMLChToStr(str) XMLStringConverter(str).charForm()

/** @brief convert string to XMLCh */
#define StrToXMLCh(str) XMLStringConverter(str).unicodeForm()

// ----------------------------------------------------------------------------

class ActionPair {
  std::string m_libraryName;
  std::string m_libraryFunctionName;

  void setLibraryName(std::string name) { m_libraryName = name; }
  void setLibraryFunctionName(std::string name) {
    m_libraryFunctionName = name;
  }

 public:
  ActionPair(const DOMNode* node);

  const char* getLibraryName() { return m_libraryName.c_str(); }
  const char* getLibraryFunctionName() { return m_libraryFunctionName.c_str(); }
};

// ----------------------------------------------------------------------------

class ExpiryAttributes {
  std::chrono::seconds m_timeout;
  ExpirationAction m_action;

  // TODO GEODE-3136: Consider parser
  void setTimeout(std::string str) {
    m_timeout = std::chrono::seconds(FwkStrCvt::toInt32(str));
  }

  void setAction(std::string action) {
    if (action == "invalidate") {
      m_action = ExpirationAction::INVALIDATE;
    } else if (action == "destroy") {
      m_action = ExpirationAction::DESTROY;
    } else if (action == "local-invalidate") {
      m_action = ExpirationAction::LOCAL_INVALIDATE;
    } else if (action == "local-destroy") {
      m_action = ExpirationAction::LOCAL_DESTROY;
    }
  }

 public:
  ExpiryAttributes(const DOMNode* node);

  ExpirationAction getAction() { return m_action; }
  std::chrono::seconds getTimeout() { return m_timeout; }
};

// ----------------------------------------------------------------------------

class PersistManager {
  std::string m_libraryName;
  std::string m_libraryFunctionName;
  std::shared_ptr<Properties> m_properties;

  void setLibraryName(std::string name) { m_libraryName = name; }
  void setLibraryFunctionName(std::string name) {
    m_libraryFunctionName = name;
  }
  void addProperties(const DOMNode* node);
  void addProperty(const DOMNode* node);

 public:
  PersistManager(const DOMNode* node);
  ~PersistManager() { m_properties = nullptr; }

  const char* getLibraryName() { return m_libraryName.c_str(); }
  const char* getLibraryFunctionName() { return m_libraryFunctionName.c_str(); }
  std::shared_ptr<Properties>& getProperties() { return m_properties; }
};

// ----------------------------------------------------------------------------

class Attributes {
  RegionAttributesFactory m_factory;
  bool m_isLocal;
  bool m_withPool;

  void setCachingEnabled(std::string val) {
    m_factory.setCachingEnabled(FwkStrCvt::toBool(val));
  }

  void setLoadFactor(std::string val) {
    m_factory.setLoadFactor(FwkStrCvt::toFloat(val));
  }

  void setConcurrencyLevel(std::string val) {
    m_factory.setConcurrencyLevel(
        static_cast<uint8_t>(FwkStrCvt::toInt32(val)));
  }

  void setLruEntriesLimit(std::string val) {
    m_factory.setLruEntriesLimit(FwkStrCvt::toUInt32(val));
  }

  void setInitialCapacity(std::string val) {
    m_factory.setInitialCapacity(FwkStrCvt::toInt32(val));
  }

  void setCloningEnabled(std::string val) {
    m_factory.setCloningEnabled(FwkStrCvt::toBool(val));
  }

  void setRegionTimeToLive(ExpiryAttributes* val) {
    m_factory.setRegionTimeToLive(val->getAction(), val->getTimeout());
    delete val;
  }

  void setRegionIdleTime(ExpiryAttributes* val) {
    m_factory.setRegionIdleTimeout(val->getAction(), val->getTimeout());
    delete val;
  }
  void setEntryTimeToLive(ExpiryAttributes* val) {
    m_factory.setEntryTimeToLive(val->getAction(), val->getTimeout());
    delete val;
  }
  void setEntryIdleTime(ExpiryAttributes* val) {
    m_factory.setEntryIdleTimeout(val->getAction(), val->getTimeout());
    delete val;
  }

  void setCacheLoader(ActionPair* val) {
    m_factory.setCacheLoader(val->getLibraryName(),
                             val->getLibraryFunctionName());
  }

  void setCacheListener(ActionPair* val) {
    m_factory.setCacheListener(val->getLibraryName(),
                               val->getLibraryFunctionName());
  }

  void setCacheWriter(ActionPair* val) {
    m_factory.setCacheWriter(val->getLibraryName(),
                             val->getLibraryFunctionName());
  }
  void setConcurrencyCheckEnabled(std::string val) {
    m_factory.setConcurrencyChecksEnabled(FwkStrCvt::toBool(val));
  }
  void setPersistenceManager(PersistManager* val) {
    m_factory.setPersistenceManager(val->getLibraryName(),
                                    val->getLibraryFunctionName(),
                                    val->getProperties());
  }

  ExpiryAttributes* getExpiryAttributes(const DOMNode* node);

 public:
  Attributes(const DOMNode* node);

  RegionAttributes getAttributes() {
    return m_factory.create();
  }

  void setPoolName(std::string val) {
    if (!val.empty()) {
      m_factory.setPoolName(val.c_str());
      m_withPool = true;
    } else {
      m_factory.setPoolName(val.c_str());
      m_withPool = false;
    }
  }

  bool isLocal() { return m_isLocal; }

  bool isWithPool() { return m_withPool; }
};
// ----------------------------------------------------------------------------

class FwkRegion {
  std::string m_name;
  Attributes* m_attributes;

  void setName(std::string name) { m_name = name; }
  void setAttributes(Attributes* attributes) { m_attributes = attributes; }

 public:
  FwkRegion(const DOMNode* node);
  ~FwkRegion() {
    if (m_attributes != NULL) {
      delete m_attributes;
      m_attributes = NULL;
    }
  }

  const std::string& getName() const { return m_name; }

  Attributes* getAttributes() { return m_attributes; }

  const RegionAttributes getRegionAttributes() const {
    return m_attributes->getAttributes();
  }
  void print() const { FWKINFO("FwkRegion " << m_name); }
};

// ---------------------------------------------------------------------------------

class FwkPool {
  std::string m_name;
  std::shared_ptr<Cache> m_cache;
  PoolManager* m_poolManager;
  PoolFactory m_poolFactory;
  bool m_locators;
  bool m_servers;

  void setName(std::string name) { m_name = name; }
  void setAttributesToFactory(const DOMNode* node);

  void setFreeConnectionTimeout(std::string val) {
    m_poolFactory.setFreeConnectionTimeout(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setLoadConditioningInterval(std::string val) {
    m_poolFactory.setLoadConditioningInterval(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setSocketBufferSize(std::string val) {
    m_poolFactory.setSocketBufferSize(FwkStrCvt::toInt32(val));
  }

  void setReadTimeout(std::string val) {
    m_poolFactory.setReadTimeout(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setMinConnections(std::string val) {
    m_poolFactory.setMinConnections(FwkStrCvt::toInt32(val));
  }

  void setMaxConnections(std::string val) {
    m_poolFactory.setMaxConnections(FwkStrCvt::toInt32(val));
  }

  void setIdleTimeout(std::string val) {
    m_poolFactory.setIdleTimeout(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setRetryAttempts(std::string val) {
    m_poolFactory.setRetryAttempts(FwkStrCvt::toInt32(val));
  }

  void setPingInterval(std::string val) {
    m_poolFactory.setPingInterval(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setStatisticInterval(std::string val) {
    m_poolFactory.setStatisticInterval(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setServerGroup(std::string val) {
    m_poolFactory.setServerGroup(val.c_str());
  }

  void setSubscriptionEnabled(std::string val) {
    m_poolFactory.setSubscriptionEnabled(FwkStrCvt::toBool(val));
  }

  void setSubscriptionRedundancy(std::string val) {
    m_poolFactory.setSubscriptionRedundancy(FwkStrCvt::toInt32(val));
  }

  void setSubscriptionMessageTrackingTimeout(std::string val) {
    m_poolFactory.setSubscriptionMessageTrackingTimeout(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setSubscriptionAckInterval(std::string val) {
    m_poolFactory.setSubscriptionAckInterval(
        apache::geode::internal::chrono::duration::from_string<
            std::chrono::milliseconds>(val));
  }

  void setThreadLocalConnections(std::string val) {
    m_poolFactory.setThreadLocalConnections(FwkStrCvt::toBool(val));
  }
  void setPRSingleHopEnabled(std::string val) {
    m_poolFactory.setPRSingleHopEnabled(FwkStrCvt::toBool(val));
  }

  void setLocatorsFlag(std::string val) { m_locators = FwkStrCvt::toBool(val); }

  void setServersFlag(std::string val) { m_servers = FwkStrCvt::toBool(val); }

 public:
  FwkPool(const DOMNode* node);
  ~FwkPool() = default;
  bool isPoolWithLocators() { return m_locators; }
  bool isPoolWithServers() { return m_servers; }

  void addLocator(std::string ep) {
    size_t position = ep.find_first_of(":");
    if (position != std::string::npos) {
      std::string hostname = ep.substr(0, position);
      int portnumber = atoi((ep.substr(position + 1)).c_str());
      m_poolFactory.addLocator(hostname.c_str(), portnumber);
    }
  }

  void addServer(std::string ep) {
    FWKINFO("GG: Adding Server EP:" << ep);
    size_t position = ep.find_first_of(":");
    if (position != std::string::npos) {
      std::string hostname = ep.substr(0, position);
      int portnumber = atoi((ep.substr(position + 1)).c_str());
      m_poolFactory.addServer(hostname.c_str(), portnumber);
    }
  }

  //  std::shared_ptr<Pool> createPoolForPerf() { return
  //  m_poolFactory.create(m_name.c_str()); }

  //  std::shared_ptr<Pool> createPool() const {
  //    if (m_name.empty()) {
  //      FWKEXCEPTION("Pool name not specified.");
  //    } else {
  //      return m_poolFactory.create(m_name.c_str());
  //    }
  //    return nullptr;
  //  }
  const std::string& getName() const { return m_name; }
  void print() const { FWKINFO("FwkPool " << m_name); }
};

// ----------------------------------------------------------------------------

class DataSnippet {
  std::string m_name;
  FwkRegion* m_region;
  FwkPool* m_pool;

  void setName(std::string name) { m_name = name; }
  void setRegion(FwkRegion* region) { m_region = region; }
  void setPool(FwkPool* pool) { m_pool = pool; }

 public:
  DataSnippet(const DOMNode* node);
  ~DataSnippet() {
    if (m_region != NULL) {
      delete m_region;
      m_region = NULL;
    }
    if (m_pool != NULL) {
      delete m_pool;
      m_pool = NULL;
    }
  }

  std::string& getName() { return m_name; }
  const FwkRegion* getRegion() const { return m_region; }
  const FwkPool* getPool() const { return m_pool; }
  void print() const {
    FWKINFO("Snippet: " << m_name << " has region: ");
    m_region->print();
  }
};

// ----------------------------------------------------------------------------

class DataOneof {
  StringVector m_values;
  std::string m_empty;

 public:
  DataOneof(const DOMNode* node);

  ~DataOneof() { m_values.clear(); }

  const std::string& getValue() const {
    int32_t maxIdx = static_cast<int32_t>(m_values.size()) - 1;
    if (maxIdx < 0) {
      return m_empty;
    }
    return m_values.at(GsRandom::random(maxIdx));
  }

  void addValue(std::string val) { m_values.push_back(val); }
  void print() const {
    FWKINFO("DataOneof has values:");
    int32_t maxIdx = static_cast<int32_t>(m_values.size()) - 1;
    if (maxIdx < 0) {
      return;
    }
    for (int32_t idx = 0; idx <= maxIdx; idx++) {
      FWKINFO(m_values.at(idx));
    }
  }
};

// ----------------------------------------------------------------------------

typedef std::map<ACE_thread_t, int32_t> TlsMap;
typedef std::map<ACE_thread_t, int32_t>::const_iterator TlsMapIter;

class DataList {
  mutable TlsMap m_map;
  StringVector m_values;
  std::string m_empty;

  const std::string& getFirstListItem(ACE_thread_t tid) const {
    StringVector::const_iterator idx = m_values.begin();
    if (idx != m_values.end()) {
      m_map[tid] = 0;
      return (*idx);
    }
    return m_empty;
  }

  const std::string& getNextListItem(TlsMapIter iter) const {
    int32_t idx = (*iter).second;

    if (++idx >= static_cast<int32_t>(m_values.size())) {
      idx = -1;
    }
    m_map[(*iter).first] = idx;
    if (idx > -1) {
      return m_values.at(idx);
    }
    return m_empty;
  }

 public:
  DataList(const DOMNode* node);

  ~DataList() {
    m_map.clear();
    m_values.clear();
  }

  const std::string& getValue() const {
    ACE_thread_t tid = ACE_OS::thr_self();
    TlsMapIter iter = m_map.find(tid);
    if (iter == m_map.end()) {
      // thread not in map, return the first list item
      return getFirstListItem(tid);
    }
    // We have an iterator, return the next in the list
    return getNextListItem(iter);
  }

  void reset() const { m_map.erase(ACE_OS::thr_self()); }
  void addValue(std::string val) { m_values.push_back(val); }
  void print() const {
    FWKINFO("DataList has values:");
    //        ACE_thread_t maxIdx = static_cast<ACE_thread_t> (m_values.size())
    //        - 1;
    //        if ( maxIdx < 0 ) {
    //          return;
    //        }
    //        for ( ACE_thread_t idx = 0; idx <= maxIdx; idx++ ) {
    //          FWKINFO( m_values.at( idx ) );
    //        }
  }
};

// ----------------------------------------------------------------------------

class DataRange {
  double m_low;
  double m_high;
  std::string m_last;

  void setLow(std::string str) { m_low = FwkStrCvt::toDouble(str); }
  void setHigh(std::string str) { m_high = FwkStrCvt::toDouble(str); }
  void setLow(double low) { m_low = low; }
  void setHigh(double high) { m_high = high; }

 public:
  DataRange(const DOMNode* node);

  const std::string getValue() const {
    return FwkStrCvt(GsRandom::random(m_low, m_high)).asString();
  }
  void print() const {
    FWKINFO("DataRange: low = " << m_low << "  high = " << m_high);
  }
};

// ----------------------------------------------------------------------------

/**
 * @class FwkData
 * @brief Framework Data object
 */
class FwkData : public FwkObject {
 public:
  FwkData(const DOMNode* node);

  ~FwkData() {
    if (m_dataList != NULL) {
      delete m_dataList;
      m_dataList = NULL;
    }
    if (m_dataOneof != NULL) {
      delete m_dataOneof;
      m_dataOneof = NULL;
    }
    if (m_dataRange != NULL) {
      delete m_dataRange;
      m_dataRange = NULL;
    }
    if (m_snippet != NULL) {
      delete m_snippet;
      m_snippet = NULL;
    }
  }

  void setList(const DataList* dataList) {
    m_dataList = dataList;
    m_dataType = DATA_TYPE_LIST;
  }

  void setOneof(const DataOneof* dataOneof) {
    m_dataOneof = dataOneof;
    m_dataType = DATA_TYPE_ONEOF;
  }

  void setContent(std::string content) {
    m_content = content;
    m_dataType = DATA_TYPE_CONTENT;
  }

  void setRange(DataRange* range) {
    m_dataRange = range;
    m_dataType = DATA_TYPE_RANGE;
  }

  void setSnippet(DataSnippet* snippet) {
    m_snippet = snippet;
    m_dataType = DATA_TYPE_SNIPPET;
  }

  const FwkRegion* getSnippet() const {
    if (m_dataType == DATA_TYPE_SNIPPET) {
      return m_snippet->getRegion();
    }
    return NULL;
  }

  const FwkPool* getPoolSnippet() const {
    if (m_dataType == DATA_TYPE_SNIPPET) {
      return m_snippet->getPool();
    }
    return NULL;
  }

  const std::string getValue() const {
    switch (m_dataType) {
      case DATA_TYPE_LIST:
        return m_dataList->getValue();
        break;
      case DATA_TYPE_ONEOF:
        return m_dataOneof->getValue();
        break;
      case DATA_TYPE_RANGE:
        return m_dataRange->getValue();
        break;
      case DATA_TYPE_SNIPPET:
        break;
      default:
        break;
    }
    return m_content;
  }

  const std::string& getContent() const { return m_content; }

  void reset() const {
    if (DATA_TYPE_LIST == m_dataType) {
      m_dataList->reset();
    }
  }

  virtual const std::string& getKey() const { return getName(); }

  void print() const {
    FWKINFO("Data: " << getName() << " has content: ");
    switch (m_dataType) {
      case DATA_TYPE_LIST:
        m_dataList->print();
        break;
      case DATA_TYPE_ONEOF:
        m_dataOneof->print();
        break;
      case DATA_TYPE_RANGE:
        m_dataRange->print();
        break;
      case DATA_TYPE_SNIPPET:
        m_snippet->print();
        break;
      default:
        FWKINFO("Content: " << m_content);
        break;
    }
  }

 private:
  std::string m_content;
  const DataList* m_dataList;
  const DataOneof* m_dataOneof;
  const DataRange* m_dataRange;
  const DataSnippet* m_snippet;

  tFwkDataType m_dataType;
};

// ----------------------------------------------------------------------------

/**
 * @class FwkDataSet
 *
 * @brief Container to hold FwkData objects
 * @see FwkData
 */
class FwkDataSet : public TFwkSet<FwkData> {
 public:
  FwkDataSet() {}
  FwkDataSet(const DOMNode* node);
};

// ----------------------------------------------------------------------------

/**
 * @class FwkClient
 *
 * @brief FwkClient object
 */
class FwkClient : public FwkObject {
 public:
  FwkClient(const DOMNode* node);

  FwkClient(std::string name)
      : m_program(NULL), m_arguments(NULL), m_remaining(false) {
    setName(name);
  }

  ~FwkClient() {
    if (m_program != NULL) {
      free((void*)m_program);
      m_program = NULL;
    }
    if (m_arguments != NULL) {
      free((void*)m_arguments);
      m_arguments = NULL;
    }
  }

  void print() const { FWKINFO("Client: " << getName()); }

  void setProgram(std::string str) {
    if (!str.empty()) m_program = strdup(str.c_str());
  }

  void setArguments(std::string str) {
    if (!str.empty()) m_arguments = strdup(str.c_str());
  }

  void setHost(std::string str) {
    if ((m_host.empty()) && (!str.empty())) m_host = str;
  }

  void setHostGroup(const std::string& grp) { m_hostGroup = grp; }
  const std::string getHostGroup() const { return m_hostGroup; }

  void setRemaining(bool remaining) { m_remaining = remaining; }
  bool getRemaining() const { return m_remaining; }

  const char* getProgram() const { return m_program; }
  const char* getArguments() const { return m_arguments; }
  const std::string& getHost() const { return m_host; }
  virtual const std::string& getKey() const { return getName(); }

 private:
  const char* m_program;
  const char* m_arguments;
  std::string m_hostGroup;
  bool m_remaining;
  std::string m_host;
};

// ----------------------------------------------------------------------------

/**
 * @class FwkClientSet
 *
 * @brief Container to hold FwkClient objects
 * @see FwkClient
 */
class FwkClientSet : public TFwkSet<FwkClient> {
  bool m_exclude;
  int32_t m_count;
  int32_t m_begin;
  std::string m_hostGroup;
  bool m_remaining;

  void addClient(FwkClient* client) { add(client); }

  void setCount(std::string str) { m_count = FwkStrCvt::toInt32(str); }

  void setBegin(std::string str) { m_begin = FwkStrCvt::toInt32(str); }

 public:
  static const std::string m_defaultGroup;

  FwkClientSet()
      : m_exclude(false), m_count(1), m_begin(1), m_remaining(false) {}
  FwkClientSet(const DOMNode* node);

  void setExclude(bool exclude) { m_exclude = exclude; }

  void setExclude(std::string str) { m_exclude = FwkStrCvt::toBool(str); }

  void setHostGroup(const std::string str) { m_hostGroup = str; }

  bool getExclude() const { return m_exclude; }
  int32_t getCount() const { return m_count; }
  int32_t getBegin() const { return m_begin; }
  std::string getHostGroup() const { return m_hostGroup; }

  void setRemaining(bool remaining) { m_remaining = remaining; }
  void setRemaining(std::string str) { m_remaining = FwkStrCvt::toBool(str); }
  bool getRemaining() const { return m_remaining; }

  void print() const {
    FWKINFO("ClientSet exclude: " << getExclude() << "  count: " << getCount()
                                  << "  begin: " << getBegin());
    TFwkSet<FwkClient>::print();
  }
};

// ----------------------------------------------------------------------------

typedef int32_t (*FwkAction)(const char* taskId);

typedef std::list<uint32_t> TaskClientIdxList;

// ----------------------------------------------------------------------------
class FwkTest;

/**
 * @class FwkTask
 *
 * @brief FwkTask object
 */
class FwkTask : public FwkObject {
 public:
  FwkTask(const DOMNode* node);

  ~FwkTask() {
    if (m_clientSet != NULL) {
      delete m_clientSet;
      m_clientSet = NULL;
    }
    if (m_dataSet != NULL) {
      delete m_dataSet;
      m_dataSet = NULL;
    }
    m_clients.clear();
  }

  /** @brief Get number of times task has ran */
  uint32_t getTimesRan() const { return m_timesRan; }

  /** @brief Increment number of times task has ran */
  void incTimesRan() { m_timesRan++; }

  /** @brief reset number of times task has ran to zero*/
  void resetTimesRan() { m_timesRan = 0; }

  /** @brief Get number of threads task should run on */
  int32_t getThreadCount() const { return m_threadCount; }

  /** @brief Is this task to run if test has failures? */
  bool continueOnError() const { return m_continue; }

  /** @brief Get number of times to run task */
  uint32_t getTimesToRun() const { return m_timesToRun; }

  /** @brief Get action string */
  std::string getAction() const { return m_action; }

  /** @brief Get class string */
  std::string getClass() const { return m_class; }

  /** @brief Get container string */
  std::string getContainer() const { return m_container; }

  /** @brief Get seconds to wait */
  uint32_t getWaitTime() const { return m_waitTime; }

  /** @brief Is this task to run parallel with other tasks? */
  bool isParallel() const { return m_parallel; }

  /** brief Get FwkDataSet pointer */
  const FwkDataSet* getDataSet(const char* name) const;

  /** brief Get FwkData pointer */
  const FwkData* getData(const char* name) const;

  /** brief Get char pointer */
  const std::string getStringValue(const char* name) const {
    const FwkData* data = getData(name);
    if (data) {
      return data->getValue();
    }
    return m_empty;
  }

  /** brief Get int32_t seconds in time string */
  int32_t getTimeValue(const char* name) const {
    return FwkStrCvt::toSeconds(getStringValue(name));
  }

  /** brief Get int32_t */
  int32_t getIntValue(const char* name) const {
    return FwkStrCvt::toInt32(getStringValue(name));
  }

  /** brief Get bool */
  bool getBoolValue(const char* name) const {
    return FwkStrCvt::toBool(getStringValue(name));
  }

  /** brief Get char pointer */
  const FwkRegion* getSnippet(const std::string& name) const {
    const FwkRegion* value = NULL;
    const FwkData* data = getData(name.c_str());
    if (data) {
      value = data->getSnippet();
    }
    return value;
  }

  const FwkPool* getPoolSnippet(const std::string& name) const {
    const FwkPool* value = NULL;
    const FwkData* data = getData(name.c_str());
    if (data) {
      value = data->getPoolSnippet();
    }
    return value;
  }

  void resetValue(const char* name) const {
    FwkData* data = const_cast<FwkData*>(getData(name));
    if (data != NULL) data->reset();
  }

  TaskClientIdxList* getTaskClients() { return &m_clients; }

  const std::string& getTaskId() const { return m_id; }

  virtual const std::string& getKey() const { return m_id; }

  void setParent(FwkTest* parent) { m_parent = parent; }

  FwkClientSet* getClientSet() { return m_clientSet; }

  void print() const {
    FWKINFO("Task: " << m_id << "  " << m_container << "  " << m_class << "  "
                     << m_action << "  WaitTime: " << m_waitTime
                     << "  TimesToRun: " << m_timesToRun << "  Threads: "
                     << m_threadCount << "  Parallel: " << m_parallel
                     << "  ContinueOnError: " << m_continue);
    if (m_clientSet != NULL) {
      FWKINFO("Clients: ");
      m_clientSet->print();
    }
    if (m_dataSet != NULL) {
      FWKINFO("Data: ");
      m_dataSet->print();
    }
    FWKINFO("End Task: " << m_id);
  }

  void setKey(int32_t cnt);

  /** @brief Get number of times to run task */
  void setTimesToRun(uint32_t cnt) { m_timesToRun = cnt; }

 private:
  void setAction(std::string action) { m_action = action; }

  void setClass(std::string clas) { m_class = clas; }

  void setContainer(std::string container) { m_container = container; }

  void setWaitTime(std::string waitTime) {
    m_waitTime = FwkStrCvt::toSeconds(waitTime.c_str());
  }

  /** @brief Get number of times to run task */
  void setTimesToRun(std::string str) {
    m_timesToRun = FwkStrCvt::toUInt32(str);
  }

  void setParallel(std::string str) { m_parallel = FwkStrCvt::toBool(str); }

  void setContinueOnError(std::string str) {
    m_continue = FwkStrCvt::toBool(str);
  }

  /** @brief Set number of threads task should run on */
  void setThreadCount(std::string str) {
    m_threadCount = FwkStrCvt::toInt32(str);
  }

  void setDataSet(FwkDataSet* dataSet) {
    if (m_dataSet == NULL) m_dataSet = dataSet;
  }

  /** @brief Add ClientSet
   * @param set ClientSet to add
   */
  void addClientSet(FwkClientSet* set) {
    const FwkClient* client = set->getFirst();
    while (client != NULL) {
      addClient(client);
      client = set->getNext(client);
    }
    if (set->getExclude()) {
      m_clientSet->setExclude(true);
    }
  }

  void addClient(const FwkClient* client) {
    if (m_clientSet == NULL) {
      m_clientSet = new FwkClientSet();
    }
    m_clientSet->add(client);
  }

  void addData(FwkData* data) {
    if (m_dataSet == NULL) {
      m_dataSet = new FwkDataSet();
    }
    m_dataSet->add(data);
  }

  std::string m_action;
  std::string m_class;
  std::string m_container;
  // UNUSED FwkAction m_func;
  uint32_t m_waitTime;
  uint32_t m_timesToRun;
  int32_t m_threadCount;
  bool m_parallel;
  std::string m_id;
  uint32_t m_timesRan;
  bool m_continue;

  FwkClientSet* m_clientSet;
  FwkDataSet* m_dataSet;

  FwkTest* m_parent;

  TaskClientIdxList m_clients;

  std::string m_empty;
};

// ----------------------------------------------------------------------------

/**
 * @class FwkTaskSet
 *
 * @brief Container to hold FwkTask objects
 * @see FwkTask
 */
class FwkTaskSet : public TFwkSet<FwkTask> {};

// ----------------------------------------------------------------------------
class TestDriver;

/**
 * @class FwkTest
 *
 * @brief FwkTest object
 */
class FwkTest : public FwkObject {
 public:
  FwkTest(const DOMNode* node);

  /** brief Get FwkDataSet pointer */
  const FwkDataSet* getDataSet(const char* name) const;

  /** brief Get FwkData pointer */
  const FwkData* getData(const char* name) const;

  /** @brief Get description string */
  const char* getDescription() const { return m_description.c_str(); }

  /** @brief Get wait time */
  uint32_t getWaitTime() const { return m_waitTime; }

  /** @brief Get number of times to run task */
  uint32_t getTimesToRun() const { return m_timesToRun; }

  const FwkTask* getFirst() { return m_taskSet.getFirst(); }

  const FwkTask* getNext(const FwkTask* prev) {
    return m_taskSet.getNext(prev);
  }

  const FwkTask* getTaskById(std::string& id) {
    FwkTask* task = const_cast<FwkTask*>(m_taskSet.getFirst());
    while (task != NULL) {
      if (task->getTaskId() == id) {
        return task;
      }
      task = const_cast<FwkTask*>(m_taskSet.getNext(task));
    }
    return task;
  }

  const FwkTask* find(const char* name) { return m_taskSet.find(name); }

  size_t getCount() const { return m_taskSet.size(); }

  virtual const std::string& getKey() const { return m_id; }

  void print() const {
    FWKINFO("Test: " << m_id << "  " << m_description
                     << "  WaitTime: " << m_waitTime);
    FWKINFO("Tasks: ");
    m_taskSet.print();
    FWKINFO("End Test: " << m_id);
  }

  void setParent(TestDriver* parent) { m_parent = parent; }

  void setKey(int32_t cnt) {
    if (!m_id.empty()) return;
    std::ostringstream ostr;
    ostr << getName() << "::" << cnt;
    m_id = ostr.str();
  }

  /** @brief Get number of times to run task */
  void setTimesToRun(std::string str) {
    m_timesToRun = FwkStrCvt::toUInt32(str);
  }

 private:
  void setWaitTime(std::string waitTime) {
    m_waitTime = FwkStrCvt::toSeconds(waitTime);
  }

  void setDescription(std::string description) { m_description = description; }

  void addTask(FwkTask* task) {
    m_taskSet.add(task);
    task->setParent(this);
  }

  std::string m_id;
  std::string m_description;
  uint32_t m_waitTime;
  uint32_t m_timesToRun;
  FwkTaskSet m_taskSet;
  TestDriver* m_parent;
};

// ----------------------------------------------------------------------------

/**
 * @class FwkTestSet
 *
 * @brief Container to hold FwkTest objects
 * @see FwkTest
 */
class FwkTestSet : public TFwkSet<FwkTest> {};

// ----------------------------------------------------------------------------

class LocalFile : public FwkObject {
  std::string m_description;
  std::string m_content;
  bool m_append;

  void setContent(std::string content) { m_content = content; }
  void setDescription(std::string description) { m_description = description; }
  void setAppend(std::string append) { m_append = FwkStrCvt::toBool(append); }

 public:
  LocalFile(const DOMNode* node);

  const std::string& getContent() const { return m_content; }

  const std::string& getKey() const { return getName(); }

  bool getAppend() const { return m_append; }

  void print() const {
    FWKINFO("LocalFile: " << getName() << " append: " << getAppend()
                          << " has content: " << getContent());
  }
};

// ----------------------------------------------------------------------------

class LocalFileSet : public TFwkSet<LocalFile> {};

// ----------------------------------------------------------------------------

class FwkDomErrorHandler : public DOMErrorHandler {
 public:
  FwkDomErrorHandler() : m_hadErrors(false) {}
  ~FwkDomErrorHandler() = default;

  bool hadErrors() const { return m_hadErrors; }
  bool handleError(const DOMError& domError);
  void resetErrors() { m_hadErrors = false; }

 private:
  bool m_hadErrors;
};

// ----------------------------------------------------------------------------

class TestDriver {
  LocalFileSet m_localFiles;
  FwkDataSet m_data;
  std::map<std::string, FwkDataSet*> m_dataSetMap;
  std::vector<FwkClientSet*> m_clientSets;
  FwkClientSet m_clients;
  FwkTestSet m_tests;
  FwkTaskSet m_tasks;
  std::string m_empty;
  StringVector m_hostGroups;

  void addHostGroup(std::string name) { m_hostGroups.push_back(name); }

  void addLocalFile(LocalFile* file) { m_localFiles.add(file); }

  void addData(FwkData* data) { m_data.add(data); }

  void addDataSet(FwkDataSet* dataSet) {
    m_dataSetMap[dataSet->getName()] = dataSet;
  }

  void addClientSet(FwkClientSet* clientSet) {
    m_clientSets.push_back(clientSet);
    FwkClient* client = const_cast<FwkClient*>(clientSet->getFirst());
    std::string grp = clientSet->getHostGroup();
    bool remaining = clientSet->getRemaining();
    while (client != NULL) {
      client->setHostGroup(grp);
      client->setRemaining(remaining);
      m_clients.add(client);
      client = const_cast<FwkClient*>(clientSet->getNext(client));
    }
  }

  void addTest(FwkTest* test) {
    m_tests.add(test);
    test->setParent(this);
    test->setKey(m_tests.size());
    const FwkTask* task = test->getFirst();
    int32_t cnt = 1;
    while (task != NULL) {
      (const_cast<FwkTask*>(task))->setKey(cnt++);
      m_tasks.add(task);
      task = test->getNext(task);
    }
  }

  void clearClientSets() {
    int32_t siz = static_cast<int32_t>(m_clientSets.size());
    while (siz > 0) {
      const FwkClientSet* obj = m_clientSets.back();
      m_clientSets.pop_back();
      delete obj;
      siz = static_cast<int32_t>(m_clientSets.size());
    }
  }

  void clearDataSets() {
    std::map<std::string, FwkDataSet*>::iterator iter;
    iter = m_dataSetMap.begin();
    while (iter != m_dataSetMap.end()) {
      const FwkDataSet* obj = (*iter).second;
      delete obj;
      m_dataSetMap.erase(iter);
      iter = m_dataSetMap.begin();
    }
  }

  void writeLocalFile(const LocalFile* fil) {
    const char* mode;
    std::string what("write");
    if (fil->getAppend()) {
      mode = "ab";
      what = "append";
    } else {
      mode = "wb";
    }
    errno = 0;
    FILE* out = fopen(fil->getName().c_str(), mode);
    if (out == (FILE*)0) {
      int32_t err = errno;
      FWKEXCEPTION("Unable to open file " << fil->getName() << " with mode: "
                                          << what << " error: " << err);
    }
    FWKDEBUG("Opened local file: " << fil->getName() << " to " << what
                                   << " content::>" << fil->getContent()
                                   << "<::");
    fprintf(out, "%s", fil->getContent().c_str());
    fclose(out);
  }

 public:
  TestDriver(const char* file);
  ~TestDriver() {
    m_clients.setNoDelete();
    m_tasks.setNoDelete();
    clearClientSets();
    clearDataSets();
  }

  void fromXmlNode(const DOMNode* node);

  void writeFiles() {
    const LocalFile* fil = m_localFiles.getFirst();
    //        FILE * out = fopen( "local.files", "wb" );
    while (fil != NULL) {
      writeLocalFile(fil);
      //          fprintf( out, "%s\n", fil->getName().c_str() );
      fil = m_localFiles.getNext(fil);
    }
    //        fclose( out );
  }

  FwkClientSet* getClients() { return &m_clients; }

  const FwkTask* getTaskById(std::string id) {
    const FwkTask* task = m_tasks.getFirst();
    while (task != NULL) {
      if (id == task->getTaskId()) return task;
      task = m_tasks.getNext(task);
    }
    return NULL;
  }

  const StringVector& getHostGroups() { return m_hostGroups; }

  const FwkTest* nextTest(const FwkTest* test) const {
    return m_tests.getNext(test);
  }

  const FwkTest* firstTest() const { return m_tests.getFirst(); }

  const LocalFile* nextLocalFile(const LocalFile* file) const {
    return m_localFiles.getNext(file);
  }

  const LocalFile* firstLocalFile() const { return m_localFiles.getFirst(); }

  /** brief Get FwkDataSet pointer */
  const FwkDataSet* getDataSet(const char* name) const {
    if (name == NULL) return NULL;

    std::map<std::string, FwkDataSet*>::const_iterator iter =
        m_dataSetMap.find(name);

    if (iter != m_dataSetMap.end()) {
      return (*iter).second;
    }
    return NULL;
  }

  /** brief Get FwkData pointer */
  const FwkData* getData(const char* name) const { return m_data.find(name); }

  //      /** brief Get char pointer */
  //      const char * getValue( const char * name ) const {
  //        const char * value = NULL;
  //        const FwkData * data = getData( name );
  //        if ( data ) {
  //          std::string val = data->getValue();
  //          if ( !val.empty() ) {
  //            value = val.c_str();
  //          }
  //        }
  //        return value;
  //      }

  /** brief Get char pointer */
  const std::string getStringValue(const char* name) const {
    const FwkData* data = getData(name);
    if (data) {
      return data->getValue();
    }
    return m_empty;
  }

  /** brief Get int32_t seconds in time string */
  int32_t getTimeValue(const char* name) const {
    return FwkStrCvt::toSeconds(getStringValue(name));
  }

  /** brief Get int32_t */
  int32_t getIntValue(const char* name) const {
    return FwkStrCvt::toInt32(getStringValue(name));
  }

  void print() const {
    FWKINFO("TestDriver:   LocalFiles:");
    m_localFiles.print();
    FWKINFO("TestDriver:   Data:");
    m_data.print();
    FWKINFO("TestDriver:   DataSets: <skipping>");
    FWKINFO("TestDriver:   Clients:");
    m_clients.print();
    FWKINFO("TestDriver:   Tests:");
    m_tests.print();
  }
};

// ----------------------------------------------------------------------------

}  // namespace testframework
}  // namespace client
}  // namespace geode
}  // namespace apache

#endif  // GEODE_FWKLIB_FWKOBJECTS_H_


text:
class ProjectsMailer < ActionMailer::Base
  include ERB::Util
  default :from => "Catarse <system@catarse.me>"

  def start_project_email(about, rewards, links, contact, user, site)
    @about = h(about).gsub("\n", "
").html_safe
    @rewards = h(rewards).gsub("\n", "
").html_safe
    @links = h(links).gsub("\n", "
").html_safe
    @contact = contact
    @user = user
    @site = site
    mail(:to => "projetos@catarse.me", :subject => t('projects_mailer.start_project_email.subject', :name => @user.name))
  end
end

redpajama_set_name: RedPajamaGithub


text:
package mods.ocminecart.client.renderer.item;

import mods.ocminecart.OCMinecart;
import mods.ocminecart.client.renderer.entity.ComputerCartModel;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.IItemRenderer;
import org.lwjgl.opengl.GL11;

public class ComputerCartItemRenderer implements IItemRenderer {

	ResourceLocation texture =  new ResourceLocation(OCMinecart.MODID+":textures/entity/computercart.png");
	ComputerCartModel model = new ComputerCartModel();

	@Override
	public boolean handleRenderType(ItemStack item, ItemRenderType type) {
		switch(type){
		case ENTITY:
			return true;
		case EQUIPPED:
			return true;
		case EQUIPPED_FIRST_PERSON:
			return true;
		case INVENTORY:
			return true;
		default:
			return false;
		}
	}

	@Override
	public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
		if(type==ItemRenderType.ENTITY &&  (helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION)) return true;
		else if(type==ItemRenderType.INVENTORY && helper == ItemRendererHelper.INVENTORY_BLOCK) return true;
		else if(type==ItemRenderType.EQUIPPED_FIRST_PERSON && helper==ItemRendererHelper.BLOCK_3D) return true;
		return false;
	}

	@Override
	public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
		if(type==ItemRenderType.EQUIPPED){
			GL11.glPushMatrix();
			GL11.glRotatef(130.0F,1.0F, 0.0F, 0.0F);
			GL11.glRotatef(-20.0F, 0.0F, 0.0F, 1.0F);
			GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
			GL11.glTranslatef(0.7F, 0F, 0F);
			GL11.glScaled(0.7, 0.7, 0.7);
			Minecraft.getMinecraft().renderEngine.bindTexture(texture);
			model.renderItem(0.0625F);
			GL11.glPopMatrix();
		}
		else if(type==ItemRenderType.ENTITY){
			GL11.glPushMatrix();
			GL11.glRotated(180F, 1F, 0, 0);
			GL11.glScaled(0.7, 0.7, 0.7);
			Minecraft.getMinecraft().renderEngine.bindTexture(texture);
			model.renderItem(0.0625F);
			GL11.glPopMatrix();
		}else if(type==ItemRenderType.INVENTORY){
			GL11.glPushMatrix();
			GL11.glRotatef(180.0F,1.0F, 0.0F, 0.0F);
			Minecraft.getMinecraft().renderEngine.bindTexture(texture);
			model.renderItem(0.0625F);
			GL11.glPopMatrix();
		}
		else if(type==ItemRenderType.EQUIPPED_FIRST_PERSON){
			GL11.glPushMatrix();
			GL11.glRotatef(180.0F,1.0F, 0.0F, 0.0F);
			GL11.glRotatef(-20.0F, 0.0F, 0.0F, 1.0F);
			GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
			GL11.glTranslatef(1F, 0F, 0.5F);
			Minecraft.getMinecraft().renderEngine.bindTexture(texture);
			model.renderItem(0.0625F);
			GL11.glPopMatrix();
		}
	}

}


text:
import QuantLib as ql
from unittest import TestCase
from qtk import Controller, Field as F, QuantLibConverter as qlc, Template as T

class TestModels(TestCase):

    _data = [
        {

        },
        {

        }
    ]
    pass


text:
/**
 * Created by kgrube on 9/5/2018
 */
require('dotenv').config({path: require('path').join(__dirname, '.env.test')});
const assert = require('assert');
const _ = require('lodash');
const PRTG = require('../src/prtg');
const should = require('should');
const mocha = require('mocha');
const {describe} = mocha;

const API_URL = process.env.API_URL;
const USER = process.env.API_USER;
const PASSHASH = process.env.PASSHASH;
const DEVICE_ID = process.env.DEVICE_ID;
const SENSOR_ID = process.env.SENSOR_ID;
const DEBUG = process.env.DEBUG;

const prtg = new PRTG({
  url: API_URL,
  username: USER,
  passhash: PASSHASH,
  debug: DEBUG,
});

describe('PRTG', () => {
  describe('instance', () => {
    it('should be an instance of PRTG', done => {
      assert(prtg instanceof PRTG);
      done();
    });

    describe('should throw an error', () => {
      it('when options is not defined', done => {
        try {
          const p = new PRTG();
        } catch (err) {
          if (err === 'options must be defined') {
            done();
            return;
          }
        }
        done(new Error('options not defined error was not thrown'));
      });

      it('when url is not defined', done => {
        try {
          const p = new PRTG({username: 'blank', passhash: 'blank'});
        } catch (err) {
          if (err === 'options.url must be defined') {
            done();
            return;
          }
        }
        done(new Error('url not defined error was not thrown'));
      });

      it('when username is not defined', done => {
        try {
          const p = new PRTG({passhash: 'blank', url: 'blank'});
        } catch (err) {
          if (err === 'options.username must be defined') {
            done();
            return;
          }
        }
        done(new Error('username not defined error was not thrown'));
      });

      it('when passhash is not defined', done => {
        try {
          const p = new PRTG({username: 'blank', url: 'blank'});
        } catch (err) {
          if (err === 'options.passhash must be defined') {
            done();
            return;
          }
        }
        done(new Error('passhash not defined error was not thrown'));
      });
    });
  });

  describe('#getDefaults()', () => {
    it('should return an object', done => {
      assert(typeof prtg.getDefaults() === 'object');
      done();
    });
    it('should contain httpCodes', done => {
      assert(prtg.getDefaults().httpCodes);
      done();
    });
    it('should contain status', done => {
      assert(prtg.getDefaults().status);
      done();
    });
    it('should contain status Up', done => {
      assert(prtg.getDefaults().status['Up'] === '3');
      done();
    });
    it('should contain status id 3', done => {
      assert(prtg.getDefaults().status['3'] === 'Up');
      done();
    });
  });

  describe('#getStatus()', () => {
    it('should return status Up for id 3', done => {
      assert(prtg.getStatus('Up') === '3');
      done();
    });
  });

  describe('#getSensor()', () => {
    it('should return a sensor object', done => {
      prtg.getSensor(SENSOR_ID)
        .then(sensor => {
          assertSensor(sensor);
          done();
        })
        .catch(err => {
          done(new Error(err));
        });
    });
  });

  describe('#getDeviceSensors', () => {
    it('should return an array of sensors', done => {
      const columns = ['objid', 'probe', 'group', 'device', 'sensor', 'lastvalue', 'type', 'name', 'tags', 'active', 'status', 'grpdev', 'message'];
      prtg.getDeviceSensors(DEVICE_ID, columns)
        .then(sensors => {
          assert(_.isArray(sensors));
          return sensors;
        })
        .then(sensors => {
          sensors.forEach(sensor => {
            assertSensor(sensor);
          });
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#getObjectProperty', () => {
    it('should return the same objid', done => {
      prtg.getObjectProperty(SENSOR_ID, 'objid')
        .then(property => {
          assert(property === SENSOR_ID);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#getSensorStatusId', () => {
    it('should return a valid status id', done => {
      prtg.getSensorStatusId(SENSOR_ID)
        .then(statusId => {
          assert(statusId > 0 && statusId <= 14);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#getDeviceStausId', () => {
    it('should return a valid status id', done => {
      prtg.getDeviceStatusId(DEVICE_ID)
        .then(statusId => {
          assert(statusId > 0 && statusId <= 14);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#getSensors', () => {
    it('should return an array of sensors with no params', done => {
      prtg.getSensors()
        .then(sensors => {
          assert(_.isArray(sensors));
          return sensors;
        })
        .then(sensors => {
          sensors.forEach(sensor => {
            assertSensor(sensor);
          });
          done();
        })
        .catch(err => done(new Error(err)));
    });

    it('should return an array of sensors when filtered', done => {
      const columns = ['objid', 'probe', 'group', 'device', 'sensor', 'lastvalue', 'type', 'name', 'tags', 'active', 'status', 'grpdev', 'message'];
      const filter = {filter_status: [prtg.getDefaults().status['Down'], prtg.getDefaults().status['DownAcknowledged']]};

      prtg.getSensors(columns, filter, DEVICE_ID)
        .then(sensors => {
          assert(_.isArray(sensors));
          return sensors;
        })
        .then(sensors => {
          sensors.forEach(sensor => {
            assertSensor(sensor);
          });
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#getDownOrAckSensors', () => {
    it('should return an array of sensors', done => {
      prtg.getDownOrAckSensors()
        .then(sensors => {
          assert(_.isArray(sensors));
          return sensors;
        })
        .then(sensors => {
          sensors.forEach(sensor => {
            assertSensor(sensor);
          });
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#getSensorTree', () => {
    it('should return a sensor tree', done => {
      prtg.getSensorTree()
        .then(sensorTree => {
          assertGroup(sensorTree);
          done();
        })
        .catch(err => done(new Error(err)));
    }).timeout(10000);
  });

  describe('#simulateSensorError', () => {
    it('should return an empty object', done => {
      prtg.simulateSensorError(SENSOR_ID)
        .then(res => {
          assertEmpty(res);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#pauseSensor', () => {
    it('should return an empty object', done => {
      prtg.pauseSensor(SENSOR_ID, 'Test Pause Sensor')
        .then(res => {
          assertEmpty(res);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#pauseSensorDuration', () => {
    it('should return an empty object', done => {
      prtg.pauseSensorDuration(SENSOR_ID, 'Test Pause Sensor', 5)
        .then(res => {
          assertEmpty(res);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#acknowledgeSensor', () => {
    it('should return an empty object', done => {
      prtg.acknowledgeSensor(SENSOR_ID, 'Test Acknowledge Sensor')
        .then(res => {
          assertEmpty(res);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#acknowledgeSensorDuration', () => {
    it('should return an empty object', done => {
      prtg.acknowledgeSensorDuration(SENSOR_ID, 'Test Acknowledge Sensor', 5)
        .then(res => {
          assertEmpty(res);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });

  describe('#resumeSensor', () => {
    it('should return an empty object', done => {
      prtg.resumeSensor(SENSOR_ID)
        .then(res => {
          assertEmpty(res);
          done();
        })
        .catch(err => done(new Error(err)));
    });
  });
});

after(() => {
  prtg.resumeSensor(SENSOR_ID);
});

function assertSensor(sensor) {
  assert(sensor.name);
  assert(sensor.probename || sensor.probe);
  assert(sensor.statusid || sensor.status);
}

function assertGroup(group) {
  assert(group.name);
  assert(group.id === '0');
  assert(group.url);
  assert(_.isArray(group.probenode));
}

function assertEmpty(obj) {
  assert(Object.keys(obj).length === 0 && obj.constructor === Object);
}


text:
A little script to get meme from [the coding love](http://thecodinglove.com/) and [les joies du code](http://loesjoiesducode.tumblr.com), both the last and a random one.

[![Build Status](https://travis-ci.org/eunomie/hubot-codinglove.png)](https://travis-ci.org/eunomie/hubot-codinglove) [![NPM version](https://badge.fury.io/js/hubot-codinglove.png)](http://badge.fury.io/js/hubot-codinglove)

## Usage

Returns the comment and the gif in all cases.

### The coding love

* `robot [give me some] joy [asshole]`: return a random
* `robot [spread some] love`: return a random
* `robot last joy`: return the last one
* `robot last love`: return the last one

### Les joies du code [fr]

* `robot [donne moi de la] joie [bordel]`: return a random
* `robot {dernière|derniere} joie`: return the last one

## Dependencies

* [cheerio](https://github.com/MatthewMueller/cheerio)
* [he](https://github.com/mathiasbynens/he)

## Installation

Add the package `hubot-codinglove` as a dependency in your Hubot `package.json` file.

    "dependencies": {
      "hubot-codinglove": "0.2.6"
    }

Run the following command to make sure the module is installed.

    $ npm install hubot-codinglove

To enable the script, add the `hubot-codinglove` entry to the `external-scripts.json` file (you may need to create this file).

    ["hubot-codinglove"]


text:
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.websocket.helper;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;

import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
import org.junit.Assert;

import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.is;

public class SafariD00
{
    private static final Logger LOG = Log.getLogger(SafariD00.class);
    private URI uri;
    private SocketAddress endpoint;
    private Socket socket;
    private OutputStream out;
    private InputStream in;

    public SafariD00(URI uri)
    {
        if (LOG instanceof StdErrLog)
        {
            ((StdErrLog)LOG).setLevel(StdErrLog.LEVEL_DEBUG);
        }
        this.uri = uri;
        this.endpoint = new InetSocketAddress(uri.getHost(),uri.getPort());
    }

    /**
     * Open the Socket to the destination endpoint and
     *
     * @return the open java Socket.
     * @throws IOException
     */
    public Socket connect() throws IOException
    {
        LOG.info("Connecting to endpoint: " + endpoint);
        socket = new Socket();
        socket.setTcpNoDelay(true);
        socket.connect(endpoint,1000);

        out = socket.getOutputStream();
        in = socket.getInputStream();

        return socket;
    }

    /**
     * Issue an Http websocket (Draft-0) upgrade request (using an example request captured from OSX/Safari)
     *
     * @throws UnsupportedEncodingException
     */
    public void issueHandshake() throws IOException
    {
        LOG.debug("Issuing Handshake");
        StringBuilder req = new StringBuilder();
        req.append("GET ").append(uri.getPath()).append(" HTTP/1.1\r\n");
        req.append("Upgrade: WebSocket\r\n");
        req.append("Connection: Upgrade\r\n");
        req.append("Host: ").append(uri.getHost()).append(":").append(uri.getPort()).append("\r\n");
        req.append("Origin: http://www.google.com/\r\n");
        req.append("Sec-WebSocket-Key1: 15{ft  :6@87  0 M 5 c901\r\n");
        req.append("Sec-WebSocket-Key2: 3? C;7~0 8   \" 3 2105 6  `_ {\r\n");
        req.append("\r\n");

        LOG.debug("Request:" + req);

        byte reqBytes[] = req.toString().getBytes("UTF-8");
        byte hixieBytes[] = TypeUtil.fromHexString("e739617916c9daf3");
        byte buf[] = new byte[reqBytes.length + hixieBytes.length];
        System.arraycopy(reqBytes,0,buf,0,reqBytes.length);
        System.arraycopy(hixieBytes,0,buf,reqBytes.length,hixieBytes.length);

        // Send HTTP GET Request (with hixie bytes)
        out.write(buf,0,buf.length);
        out.flush();

        socket.setSoTimeout(10000);

        // Read HTTP 101 Upgrade / Handshake Response
        InputStreamReader reader = new InputStreamReader(in);
        StringBuilder respHeaders = new StringBuilder();

        LOG.debug("Reading http headers");
        int crlfs = 0;
        while (true)
        {
            int read = in.read();
            respHeaders.append((char)read);
            if (read == '\r' || read == '\n')
                ++crlfs;
            else
                crlfs = 0;
            if (crlfs == 4)
                break;
        }

        if(respHeaders.toString().startsWith("HTTP/1.1 101 ") == false) {
            String respLine = respHeaders.toString();
            int idx = respLine.indexOf('\r');
            if(idx > 0) {
                respLine = respLine.substring(0,idx);
            }
            LOG.debug("Response Headers: {}",respHeaders.toString());
            throw new IllegalStateException(respLine);
        }

        // Read expected handshake hixie bytes
        byte hixieHandshakeExpected[] = TypeUtil.fromHexString("c7438d956cf611a6af70603e6fa54809");
        byte hixieHandshake[] = new byte[hixieHandshakeExpected.length];
        Assert.assertThat("Hixie handshake buffer size",hixieHandshake.length,is(16));

        LOG.debug("Reading hixie handshake bytes");
        int bytesRead = 0;
        while (bytesRead < hixieHandshake.length)
        {
            int val = in.read();
            if (val >= 0)
            {
                hixieHandshake[bytesRead++] = (byte)val;
            }
        }
        Assert.assertThat("Read hixie handshake bytes",bytesRead,is(hixieHandshake.length));
    }

    public void sendMessage(String... msgs) throws IOException
    {
        int len = 0;
        for (String msg : msgs)
        {
            LOG.debug("sending message: " + msg);
            len += (msg.length() + 2);
        }

        ByteArrayBuffer buf = new ByteArrayBuffer(len);

        for (String msg : msgs)
        {
            buf.put((byte)0x00);
            buf.put(msg.getBytes("UTF-8"));
            buf.put((byte)0xFF);
        }

        out.write(buf.array());
        out.flush();
    }

    public void disconnect() throws IOException
    {
        LOG.debug("disconnect");
        socket.close();
    }
}


text:
#pragma once

#include <vector>
#include <string>
#include <list>
#include <map>
#include <fstream>
#include <sstream>
#if defined(_WIN64) || defined(_WIN32)
#include <io.h>
#include <direct.h>
#define sleep _sleep
#else
#include <sys/io.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif

#include "BarcodeStatisticsRecorder.h"

#ifndef SAFE_DELETE
#define SAFE_DELETE(obj) if(obj!=NULL){ delete obj;obj=NULL;}
#endif

using namespace std;

struct PathInfo
{
	char* name;
	bool isDir;
	const string strDir;
#if defined(_WIN64) || defined(_WIN32)
	_finddata_t findData;
	intptr_t handle;
#else
	struct dirent* pDirent;
	struct stat s_buf;
	DIR* pDir;
#endif
	PathInfo(const string& sDir) :strDir(sDir)
	{}
};

static bool ReadNext(PathInfo& pathInfo)
{
#if defined(_WIN64) || defined(_WIN32)
	if (_findnext(pathInfo.handle, &pathInfo.findData) == 0)
	{
		pathInfo.name = pathInfo.findData.name;
		pathInfo.isDir = ((pathInfo.findData.attrib & _A_SUBDIR) != 0);
		return true;
	}
#else
	pathInfo.pDirent = readdir(pathInfo.pDir);
	if (pathInfo.pDirent != NULL)
	{
		pathInfo.name = pathInfo.pDirent->d_name;
		string strTmpDir = pathInfo.strDir + "/" + pathInfo.name;
		stat(strTmpDir.c_str(), &pathInfo.s_buf);
		pathInfo.isDir = S_ISDIR(pathInfo.s_buf.st_mode);
		return true;
	}
#endif
	return false;
}
static bool OpenDirectory(PathInfo& pathInfo)
{
#if defined(_WIN64) || defined(_WIN32)
	string strTmpDir = pathInfo.strDir + "\\*.*";
	pathInfo.handle = _findfirst(strTmpDir.c_str(), &pathInfo.findData);
	if (pathInfo.handle == -1)
		return false;
	pathInfo.name = pathInfo.findData.name;
	pathInfo.isDir = ((pathInfo.findData.attrib & _A_SUBDIR) != 0);
#else
	stat(pathInfo.strDir.c_str(), &pathInfo.s_buf);
	pathInfo.pDir = opendir(pathInfo.strDir.c_str());
	if (!pathInfo.pDir)
		return false;
	if (!ReadNext(pathInfo))
		return false;
#endif
	return true;
}
static int CloseDirectory(PathInfo& pathInfo)
{
#if defined(_WIN64) || defined(_WIN32)
	return _findclose(pathInfo.handle);
#else
	return closedir(pathInfo.pDir);
#endif
}

class CBarcodeStatisticsRecorder;

class CBarcodeFileReader
{
public:
	CBarcodeFileReader();
	~CBarcodeFileReader();

	typedef enum _emOutputType
	{
		OUTPUT_CONSOLE,
		OUTPUT_FILE,
	}OUTPUT_TYPE;

	typedef enum _enBarcodeFormat {
		ALL_BARCODE,
		ONED_BARCODE,
		CODE39_BARCODE,
		CODE128_BARCODE,
		CODE93_BARCODE,
		CODABAR_BARCODE,
		ITF_BARCODE,
		EAN13_BARCODE,
		EAN8_BARCODE,
		UPC_A_BARCODE,
		UPC_E_BARCODE,
		INDUSTRIAL_25_BARCODE,
		PDF417_BARCODE,
		DATAMATRIX_BARCODE,
		AZTEC_BARCODE,
	}BARCODE_FORMAT;

private:
	typedef enum _enReaderState
	{
		READER_STOPPED,
		READER_RUNNING,
		READER_PAUSE,
	}READER_STATE;

private:
	string	    m_barcodeFilesDir;
	string		m_decodeResultOutputDir;
	OUTPUT_TYPE	m_outputType;
	READER_STATE m_readerState; //0:stopped 1:running 2:pause
protected:
	string	    m_currentOutputFileName;
	CBarcodeStatisticsRecorder* m_pBarcodeStatisticsRecorder;
public:
	void LoadBarcodeFiles(const char *strBarcodeFilesDir);

	void SetOutputType(OUTPUT_TYPE outputType);
	void SetOutputFileDir(const char *strOutputDir);

	virtual void Run();
	void Pause();
	void Stop();
protected:

	virtual bool ReadFileBarcodes(const  string strBarcodeFilePath, CBarcodeStatisticsRecorder::DecodeResultInfo &decodeResultInfo)= 0;

	string GetCurrentTimeString();
	string ToHexString(unsigned char* bytes, const int byteLength);
private:
	void ProcessBarcodeFileRead();
	void ScanBarcodeFilesDir(string dir);
	void CreateOutputFileDir(string strOutputFilePath);
};


text:
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
import autosar
from tests.arxml.common import ARXMLTestClass
import unittest
import warnings
warnings.simplefilter("error", DeprecationWarning)

def _create_packages(ws):

    package=ws.createPackage('DataTypes', role='DataType')
    package.createSubPackage('CompuMethods', role='CompuMethod')
    package.createSubPackage('DataConstrs', role='DataConstraint')
    package.createSubPackage('Units', role='Unit')
    package.createSubPackage('BaseTypes')
    ws.createPackage('Constants', role='Constant')
    ws.createPackage('ComponentTypes', role='ComponentType')
    ws.createPackage('PortInterfaces', role="PortInterface")
    ws.createPackage('ModeDclrGroups', role="ModeDclrGroup")

def _create_base_types(ws):
    basetypes = ws.find('/DataTypes/BaseTypes')
    basetypes.createSwBaseType('boolean', 1, 'BOOLEAN')
    basetypes.createSwBaseType('uint8', 8, nativeDeclaration='uint8')
    basetypes.createSwBaseType('uint16', 16, nativeDeclaration='uint16')
    basetypes.createSwBaseType('uint32', 32, nativeDeclaration='uint32')
    basetypes.createSwBaseType('float32', 32, encoding='IEEE754')
    package = ws.find('DataTypes')
    package.createImplementationDataType('boolean', valueTable=['FALSE','TRUE'], baseTypeRef='/DataTypes/BaseTypes/boolean', typeEmitter='Platform_Type')
    package.createImplementationDataType('uint8', lowerLimit=0, upperLimit=255, baseTypeRef='/DataTypes/BaseTypes/uint8', typeEmitter='Platform_Type')
    package.createImplementationDataType('uint16', lowerLimit=0, upperLimit=65535, baseTypeRef='/DataTypes/BaseTypes/uint16', typeEmitter='Platform_Type')
    package.createImplementationDataType('uint32', lowerLimit=0, upperLimit=4294967295, baseTypeRef='/DataTypes/BaseTypes/uint32', typeEmitter='Platform_Type')
    package.createImplementationDataTypeRef('OffOn_T', implementationTypeRef = '/DataTypes/uint8',
                                                valueTable = ['OffOn_Off',
                                                'OffOn_On',
                                                'OffOn_Error',
                                                'OffOn_NotAvailable'
                                                ])
def _create_test_elements(ws):
    package = ws.find('/Constants')
    package.createConstant('VehicleSpeed_IV', 'uint16', 65535)
    package.createConstant('EngineSpeed_IV', 'uint16', 65535)
    package = ws.find('ModeDclrGroups')
    package.createModeDeclarationGroup('VehicleMode', ["OFF",
                                                       "ACCESSORY",
                                                       "RUN",
                                                       "CRANK"], "OFF")

    package = ws.find('/PortInterfaces')
    package.createSenderReceiverInterface('VehicleSpeed_I', autosar.DataElement('VehicleSpeed', 'uint16'))
    package.createSenderReceiverInterface('EngineSpeed_I', autosar.DataElement('EngineSpeed', 'uint16'))
    package.createSenderReceiverInterface('HeaterPwrStat_I', autosar.DataElement('HeaterPwrStat', 'OffOn_T'))
    portInterface=package.createClientServerInterface('FreeRunningTimer5ms_I', ['GetTime', 'IsTimerElapsed'])
    portInterface['GetTime'].createOutArgument('value', '/DataTypes/uint32')
    portInterface["IsTimerElapsed"].createInArgument("startTime", '/DataTypes/uint32')
    portInterface["IsTimerElapsed"].createInArgument("duration", '/DataTypes/uint32')
    portInterface["IsTimerElapsed"].createOutArgument("result", '/DataTypes/boolean')
    package.createModeSwitchInterface('VehicleMode_I', autosar.mode.ModeGroup('mode', '/ModeDclrGroups/VehicleMode'))

def _init_ws(ws):
    _create_packages(ws)
    _create_base_types(ws)
    _create_test_elements(ws)

class ARXML4PortCreateTest(ARXMLTestClass):

    def test_create_non_queued_receiver_port_single_data_element_direct_comspec1(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        swc1.createRequirePort('VehicleSpeed', 'VehicleSpeed_I', comspec = {'dataElement': 'VehicleSpeed', 'initValueRef': 'VehicleSpeed_IV'})
        file_name = 'ar4_non_queued_receiver_port_single_data_element_direct_comspec1.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)

    def test_create_non_queued_receiver_port_single_data_element_direct_comspec2(self):
        """
        Same as previous test but does not explicitly name the dataElement (should auto-resolve name)
        """
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        swc1.createRequirePort('VehicleSpeed', 'VehicleSpeed_I', comspec = {'initValueRef': 'VehicleSpeed_IV'})
        file_name = 'ar4_non_queued_receiver_port_single_data_element_direct_comspec2.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)

    def test_create_non_queued_provider_port_single_data_element_direct_comspec(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        swc1.createProvidePort('VehicleSpeed', 'VehicleSpeed_I', comspec = {'dataElement': 'VehicleSpeed', 'initValueRef': 'VehicleSpeed_IV'})
        file_name = 'ar4_non_queued_provider_port_single_data_element_direct_comspec.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)

    def test_create_non_queued_receiver_port_single_data_element(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        swc1.createRequirePort('VehicleSpeed', 'VehicleSpeed_I', initValueRef = 'VehicleSpeed_IV')
        file_name = 'ar4_non_queued_receiver_port_single_data_element.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)

    def test_create_mode_require_port(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        port1 = swc1.createRequirePort('VehicleMode', 'VehicleMode_I')
        self.assertEqual(port1.portInterfaceRef, '/PortInterfaces/VehicleMode_I')
        comspec1 = port1.comspec[0]
        comspec1.modeGroupRef = '/PortInterfaces/VehicleMode_I/mode'
        file_name = 'ar4_mode_require_port.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)

    def test_create_mode_provide_port(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        port1 = swc1.createProvidePort('VehicleMode', 'VehicleMode_I', modeGroup="mode", queueLength=1, modeSwitchAckTimeout=10)
        self.assertEqual(port1.portInterfaceRef, '/PortInterfaces/VehicleMode_I')
        file_name = 'ar4_mode_provide_port.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)
        port2 = ws2.find(port1.ref)
        self.assertIsInstance(port2, autosar.port.ProvidePort)
        comspec2 = port2.comspec[0]
        self.assertIsInstance(comspec2, autosar.port.ModeSwitchComSpec)
        self.assertEqual(comspec2.queueLength, 1)
        self.assertEqual(comspec2.modeSwitchAckTimeout, 10)

    def test_create_non_queued_sender_port_single_data_element(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        swc1.createProvidePort('VehicleSpeed', 'VehicleSpeed_I', initValueRef = 'VehicleSpeed_IV')
        file_name = 'ar4_non_queued_sender_port_single_data_element.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)

    def test_create_non_queued_sender_port_single_data_element_with_raw_init_value(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        swc1.createProvidePort('HeaterPwrStat', 'HeaterPwrStat_I', initValue = 'OffOn_NotAvailable')
        file_name = 'ar4_non_queued_sender_port_single_data_element_raw_init_value.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])
        ws2 = autosar.workspace(ws.version_str)
        ws2.loadXML(os.path.join(os.path.dirname(__file__), expected_file))
        swc2 = ws2.find(swc1.ref)
        self.assertIsInstance(swc2, autosar.component.ApplicationSoftwareComponent)

    def test_create_non_queued_receiver_port_containing_single_data_element_with_alive_timeout(self):
        ws = autosar.workspace(version="4.2.2")
        _init_ws(ws)
        package = ws.find('/ComponentTypes')
        swc1 = package.createApplicationSoftwareComponent('MyApplication')
        swc1.createRequirePort('HeaterPwrStat', 'HeaterPwrStat_I', aliveTimeout = 30)
        file_name = 'ar4_non_non_queued_receiver_port_containing_single_data_element_with_alive_timeout.arxml'
        generated_file = os.path.join(self.output_dir, file_name)
        expected_file = os.path.join( 'expected_gen', 'port', file_name)
        self.save_and_check(ws, expected_file, generated_file, ['/ComponentTypes'])

if __name__ == '__main__':
    unittest.main()


text:
package com.certification.foundations.recursions;

class BasicRecursion{
	public static void main(String args[]){
		printHelloCount(10);
	}
	public static void printHelloCount(int count){
		if(count==0){
			return;
		}
		System.out.println("Hello world");
		printHelloCount(count-1);
	}
}


text:
static void test_sample(void)
{
}

TestGroup LibTests = {
    "core.lib", {
        { "sample", PlainTest, test_sample },
        { NULL, PlainTest, NULL }
    }
};


text:
namespace MvcTemplate.Web.Infrastructure.Mapping
{
    public interface IMapTo<T>
        where T : class
    {
    }
}


text:
package message_test

import (
	"bytes"
	"io"
	"log"
	"strings"

	"github.com/emersion/go-message"
)

func ExampleRead() {
	// Let's assume r is an io.Reader that contains a message.
	var r io.Reader

	m, err := message.Read(r)
	if message.IsUnknownCharset(err) {
		// This error is not fatal
		log.Println("Unknown encoding:", err)
	} else if err != nil {
		log.Fatal(err)
	}

	if mr := m.MultipartReader(); mr != nil {
		// This is a multipart message
		log.Println("This is a multipart message containing:")
		for {
			p, err := mr.NextPart()
			if err == io.EOF {
				break
			} else if err != nil {
				log.Fatal(err)
			}

			t, _, _ := p.Header.ContentType()
			log.Println("A part with type", t)
		}
	} else {
		t, _, _ := m.Header.ContentType()
		log.Println("This is a non-multipart message with type", t)
	}
}

func ExampleWriter() {
	var b bytes.Buffer

	var h message.Header
	h.SetContentType("multipart/alternative", nil)
	w, err := message.CreateWriter(&b, h)
	if err != nil {
		log.Fatal(err)
	}

	var h1 message.Header
	h1.SetContentType("text/html", nil)
	w1, err := w.CreatePart(h1)
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w1, "
Hello World!

This is an HTML part.
")
	w1.Close()

	var h2 message.Header
	h2.SetContentType("text/plain", nil)
	w2, err := w.CreatePart(h2)
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w2, "Hello World!\n\nThis is a text part.")
	w2.Close()

	w.Close()

	log.Println(b.String())
}

func Example_transform() {
	// Let's assume r is an io.Reader that contains a message.
	var r io.Reader

	m, err := message.Read(r)
	if message.IsUnknownCharset(err) {
		log.Println("Unknown encoding:", err)
	} else if err != nil {
		log.Fatal(err)
	}

	// We'll add "This message is powered by Go" at the end of each text entity.
	poweredBy := "\n\nThis message is powered by Go."

	var b bytes.Buffer
	w, err := message.CreateWriter(&b, m.Header)
	if err != nil {
		log.Fatal(err)
	}

	// Define a function that transforms message.
	var transform func(w *message.Writer, e *message.Entity) error
	transform = func(w *message.Writer, e *message.Entity) error {
		if mr := e.MultipartReader(); mr != nil {
			// This is a multipart entity, transform each of its parts
			for {
				p, err := mr.NextPart()
				if err == io.EOF {
					break
				} else if err != nil {
					return err
				}

				pw, err := w.CreatePart(p.Header)
				if err != nil {
					return err
				}

				if err := transform(pw, p); err != nil {
					return err
				}

				pw.Close()
			}
			return nil
		} else {
			body := e.Body
			if strings.HasPrefix(m.Header.Get("Content-Type"), "text/") {
				body = io.MultiReader(body, strings.NewReader(poweredBy))
			}
			_, err := io.Copy(w, body)
			return err
		}
	}

	if err := transform(w, m); err != nil {
		log.Fatal(err)
	}
	w.Close()

	log.Println(b.String())
}


text:
FlowExportInfo::FlowExportInfo() :
    flow_(), setup_time_(0), teardown_time_(0), last_modified_time_(0),
    bytes_(0), packets_(0), prev_diff_bytes_(0), prev_diff_packets_(0),
    underlay_source_port_(0), changed_(false),
    tcp_flags_(0), delete_enqueue_time_(0), evict_enqueue_time_(0),
    visit_time_(0), exported_atleast_once_(false) {
}

FlowExportInfo::FlowExportInfo(const FlowEntryPtr &fe) :
    flow_(fe), setup_time_(0), teardown_time_(0), last_modified_time_(0),
    bytes_(0), packets_(0), prev_diff_bytes_(0), prev_diff_packets_(0),
    underlay_source_port_(0), changed_(true),
    tcp_flags_(0), delete_enqueue_time_(0), evict_enqueue_time_(0),
    visit_time_(0), exported_atleast_once_(false) {
}

FlowExportInfo::FlowExportInfo(const FlowEntryPtr &fe, uint64_t setup_time) :
    flow_(fe), setup_time_(setup_time),
    teardown_time_(0), last_modified_time_(setup_time),
    bytes_(0), packets_(0), prev_diff_bytes_(0), prev_diff_packets_(0),
    underlay_source_port_(0), changed_(true),
    tcp_flags_(0), delete_enqueue_time_(0), evict_enqueue_time_(0),
    visit_time_(0), exported_atleast_once_(false) {
}

FlowEntry* FlowExportInfo::reverse_flow() const {
    FlowEntry *rflow = NULL;
    if (flow_.get()) {
        rflow = flow_->reverse_flow_entry();
    }
    return rflow;
}

bool FlowExportInfo::IsActionLog() const {
    uint32_t fe_action = flow_->data().match_p.action_info.action;
    if (fe_action & (1 << TrafficAction::LOG)) {
        return true;
    }
    return false;
}

///////////////////////////////////////////////////////////////////
// APIs used only by UT
//////////////////////////////////////////////////////////////////
void FlowExportInfo::SetActionLog() {
    FlowEntry *fe = flow();
    fe->data().match_p.action_info.action =
        fe->data().match_p.action_info.action | (1 << TrafficAction::LOG);
}