text:
#include <CJArray.h>
#include <CJFunction.h>
#include <CJavaScript.h>
#include <algorithm>

CJArrayTypeP CJArrayType::type_;

CJArrayTypeP
CJArrayType::
instance(CJavaScript *js)
{
  if (! type_) {
    type_ = CJArrayTypeP(new CJArrayType(js));

    type_->init();

    js->addObjectType(type_->name(), type_);

    js->addTypeObject(CJToken::Type::Array, type_);
  }

  return type_;
}

CJArrayType::
CJArrayType(CJavaScript *js) :
 CJObjType(js, CJToken::Type::Array, "Array")
{
}

void
CJArrayType::
init()
{
  addTypeFunction(js_, "from"     );
  addTypeFunction(js_, "isArray"  );
  addTypeFunction(js_, "observe"  ); // obsolete
  addTypeFunction(js_, "of"       );
  addTypeFunction(js_, "unobserve"); // obsolete
  addTypeFunction(js_, "toString" );

  addObjectFunction(js_, "concat"              , type_);
  addObjectFunction(js_, "every"               , type_);
  addObjectFunction(js_, "filter"              , type_);
  addObjectFunction(js_, "forEach"             , type_);
  addObjectFunction(js_, "hasOwnProperty"      , type_); // TODO: move to base class
  addObjectFunction(js_, "indexOf"             , type_);
  addObjectFunction(js_, "join"                , type_);
  addObjectFunction(js_, "lastIndexOf"         , type_);
  addObjectFunction(js_, "map"                 , type_);
  addObjectFunction(js_, "pop"                 , type_);
  addObjectFunction(js_, "propertyIsEnumerable", type_); // TODO: move to base class
  addObjectFunction(js_, "push"                , type_);
  addObjectFunction(js_, "reduce"              , type_);
  addObjectFunction(js_, "reduceRight"         , type_);
  addObjectFunction(js_, "reverse"             , type_);
  addObjectFunction(js_, "shift"               , type_);
  addObjectFunction(js_, "slice"               , type_);
  addObjectFunction(js_, "some"                , type_);
  addObjectFunction(js_, "splice"              , type_);
  addObjectFunction(js_, "sort"                , type_);
  addObjectFunction(js_, "toString"            , type_);
  addObjectFunction(js_, "toLocaleString"      , type_);
  addObjectFunction(js_, "unshift"             , type_);
}

CJValueP
CJArrayType::
execType(CJavaScript *js, const std::string &name, const Values &values)
{
  if (values.size() < 1) {
    js->errorMsg("Invalid number of arguments for " + name);
    return CJValueP();
  }

  // values[0] is CJArrayFunction

  //---

  // type functions
  if      (name == "from") {
    CJValueP value1;

    if (values.size() > 1)
      value1 = values[1];

    if (js->isUndefinedOrNullValue(value1)) {
      js->throwTypeError(value1, "Cannot convert undefined or null to object");
      return CJValueP();
    }

    return createArrayFromValue(js, value1);
  }
  else if (name == "isArray") {
    bool b = false;

    if (values.size() > 1)
      b = (values[1]->type() == CJToken::Type::Array);

    return js->createBoolValue(b);
  }
  else if (name == "observe") {
  }
  else if (name == "of") {
    CJArrayP array = js->createArrayValue();

    for (uint i = 1; i < values.size(); ++i)
      array->addValue(values[i]);

    return array;
  }
  else if (name == "unobserve") {
  }
  else if (name == "toString") {
    return js->createStringValue("function Array() { }");
  }
  else {
    js->errorMsg("Invalid array type function " + name);
  }

  return CJValueP();
}

bool
CJArrayType::
canCreateArrayFromValue(CJValueP value1)
{
  if (value1->hasIndex())
    return true;

  if (value1->hasProperty())
    return true;

  return false;
}

CJArrayP
CJArrayType::
createArrayFromValue(CJavaScript *js, CJValueP value1)
{
  CJArrayP array = js->createArrayValue();

  if      (value1->hasIndex()) {
    long len = value1->length().getValue(0);

    for (long ind = 0; ind < len; ++ind) {
      CJValueP ivalue = value1->indexValue(ind);

      if (ivalue)
        array->addValue(ivalue);
    }

    return array;
  }
  else if (value1->hasProperty()) {
    CJDictionaryP dict1 = CJValue::cast<CJDictionary>(value1);

    COptLong lenValue = value1->length();

    if (lenValue.isValid()) {
      long len = lenValue.getValue(0);

      for (int ind = 0; ind < len; ++ind) {
        std::string istr = std::to_string(ind);

        CJValueP ivalue = value1->propertyValue(istr);

        if (ivalue)
          array->addValue(ivalue);
      }
    }
    else {
      CJValue::KeyNames names = value1->propertyNames();

      for (const auto &ind : names) {
        if (dict1 && ! dict1->isEnumerableProperty(ind))
          continue;

        CJValueP ivalue = value1->propertyValue(ind);

        if (ivalue)
          array->setProperty(js, ind, ivalue);
      }
    }
  }

  return array;
}

CJValueP
CJArrayType::
exec(CJavaScript *js, const std::string &name, const Values &values)
{
  if (values.size() < 1) {
    js->errorMsg("Invalid number of arguments for " + name);
    return CJValueP();
  }

  // support array functions on non-array objects
  CJArrayP  array;
  CJObjectP obj;

  if      (values[0]->isArray())
    array = CJValue::cast<CJArray>(values[0]);
  else if (values[0]->isObject())
    obj = CJValue::cast<CJObject>(values[0]);

  if (! array && ! obj) {
    js->errorMsg("Invalid type for array function " + name);
    return CJValueP();
  }

  // object functions
  if      (name == "concat") {
    // create new array
    CJArrayP array1 = js->createArrayValue();

    int len1 = 0;

    // add all (expanded) values to array
    for (uint i = 0; i < values.size(); ++i) {
      if      (values[i]->isString()) { // special string handling (string has hasIndex() true)
        array1->setIndexValue(len1, values[i]);

        ++len1;
      }
      else if (values[i]->isArray()) {
        CJArrayP array2 = CJValue::cast<CJArray>(values[i]);

        for (const auto &v : array2->indValues()) {
          int ind1 = v.first + len1;

          array1->setIndexValue(ind1, v.second.calcValue(js));
        }

        len1 += array2->length().getValue(0);
      }
      else if (values[i]->hasIndex()) {
        long len = values[i]->length().getValue(0);

        for (long j = 0; j < len; ++j) {
          array1->setIndexValue(len1, values[i]->indexValue(j));

          ++len1;
        }
      }
      else {
        array1->setIndexValue(len1, values[i]);

        ++len1;
      }

      array1->setLength(len1);
    }

    return array1;
  }
  else if (name == "every") {
    // get function
    CJFunctionP fn;

    if (values.size() >= 2) {
      if (values[1]->isFunction())
        fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! fn) {
      js->throwTypeError(values[0], "Missing function for " + name);
      return CJValueP();
    }

    //---

    // get optional this
    CJDictionaryP thisDict;

    if (values.size() >= 3) {
      if (values[2]->isDictionary())
        thisDict = CJValue::cast<CJDictionary>(values[2]);
    }

    //---

    // ensure first value is array
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    // run function on each element
    bool b = true;

    if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
      return CJValueP();

    CJObjType::Values fnValues;

    fnValues.push_back(array);      // this
    fnValues.push_back(CJValueP()); // value
    fnValues.push_back(CJValueP()); // index
    fnValues.push_back(array);      // array

    for (const auto &v : array->indValues()) {
      fnValues[1] = v.second.calcValue(js);
      fnValues[2] = js->createNumberValue(v.first);

      CJValueP res = js->execFunction(fn, fnValues, thisDict);

      if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
        break;

      if (! res->toBoolean()) {
        b = false;
        break;
      }
    }

    //---

    // return every check
    return js->createBoolValue(b);
  }
  else if (name == "filter") {
    // get function
    CJFunctionP fn;

    if (values.size() >= 2) {
      if (values[1]->isFunction())
        fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! fn) {
      js->throwTypeError(values[0], "Missing function for " + name);
      return CJValueP();
    }

    //---

    // get optional this
    CJDictionaryP thisDict;

    if (values.size() >= 3) {
      if (values[2]->isDictionary())
        thisDict = CJValue::cast<CJDictionary>(values[2]);
    }

    //---

    // ensure first value is array
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    // run function on each element
    std::vector<CJValueP> newValues;

    if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
      return CJValueP();

    CJObjType::Values fnValues;

    fnValues.push_back(array);      // this
    fnValues.push_back(CJValueP()); // value
    fnValues.push_back(CJValueP()); // index
    fnValues.push_back(array);      // array

    for (const auto &v : array->indValues()) {
      fnValues[1] = v.second.calcValue(js);
      fnValues[2] = js->createNumberValue(v.first);

      CJValueP res = js->execFunction(fn, fnValues, thisDict);

      if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
        break;

      if (res->toBoolean())
        newValues.push_back(fnValues[1]);
    }

    //---

    // return filtered values
    CJArrayP array1 = js->createArrayValue();

    array1->setValues(newValues);

    return array1;
  }
  else if (name == "forEach") {
    // get function
    CJFunctionP fn;

    if (values.size() >= 2) {
      if (values[1]->isFunction())
        fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! fn) {
      js->throwTypeError(values[0], "Missing function for " + name);
      return CJValueP();
    }

    //---

    // get optional this
    CJDictionaryP thisDict;

    if (values.size() >= 3) {
      if (values[2]->isDictionary())
        thisDict = CJValue::cast<CJDictionary>(values[2]);
    }

    //---

    // ensure first value is array
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    // run function on each element
    if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
      return CJValueP();

    CJObjType::Values fnValues;

    fnValues.push_back(array);      // this
    fnValues.push_back(CJValueP()); // value
    fnValues.push_back(CJValueP()); // index
    fnValues.push_back(array);      // array

    for (const auto &v : array->indValues()) {
      fnValues[1] = v.second.calcValue(js);
      fnValues[2] = js->createNumberValue(v.first);

      CJValueP res = js->execFunction(fn, fnValues, thisDict);

      if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
        break;
    }

    //---

    // return undefined
    return js->createUndefinedValue();
  }
  else if (name == "indexOf") {
    // get search value
    CJValueP search;

    if (values.size() >= 2)
      search = values[1];

    if (! search)
      return js->createNumberValue(-1L);

    //---

    // get input array
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    long start = 0;
    long len   = array->length().getValue(0);

    //---

    // get start index
    if (values.size() >= 3) {
      COptLong optStart = values[2]->toInteger();

      if (! optStart.isValid()) {
        js->throwTypeError(values[0], "Invalid start index for " + name);
        return CJValueP();
      }

      start = optStart.getValue(0);

      if (start < 0)
        start = len + start;

      if (start >= len)
        return js->createNumberValue(-1L);

      start = CJUtil::clamp(start, 0L, len - 1);
    }

    //---

    // search
    for (long i = start; i < len; ++i) {
      COptInt cmp = js->cmp(array->indexValue(i), search);

      if (cmp.isValid() && cmp.getValue() == 0)
        return js->createNumberValue(long(i));
    }

    return js->createNumberValue(-1L);
  }
  else if (name == "join") {
    std::string jstr = ",";

    if (values.size() > 1)
      jstr = values[1]->toString();

    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    std::string str;

    long len = array->length().getValue(0);

    for (long i = 0; i < len; ++i) {
      if (i > 0)
        str += jstr;

      if (array->indexValue(i))
        str += array->indexValue(i)->toString();
    }

    return js->createStringValue(str);
  }
  else if (name == "lastIndexOf") {
    CJValueP search;

    if (values.size() >= 2)
      search = values[1];

    if (! search)
      return js->createNumberValue(-1L);

    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    long len   = array->length().getValue(0);
    long start = len - 1;

    if (values.size() >= 3) {
      start = values[2]->toInteger().getValue(0);

      if (start < 0)
        start = len + start;

      if (start < 0)
        return js->createNumberValue(-1L);

      start = CJUtil::clamp(start, 0L, len - 1);
    }

    for (long i = start; i >= 0; --i) {
      CJValueP v = array->indexValue(i);

      COptInt cmp;

      if (v)
        cmp = js->cmp(v, search);

      if (cmp.isValid() && cmp.getValue() == 0)
        return js->createNumberValue(long(i));
    }

    return js->createNumberValue(-1L);
  }
  else if (name == "map") {
    // get function
    CJFunctionP fn;

    if (values.size() >= 2) {
      if (values[1]->isFunction())
        fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! fn) {
      js->throwTypeError(values[0], "Missing function for " + name);
      return CJValueP();
    }

    //---

    // get optional this
    CJDictionaryP thisDict;

    if (values.size() >= 3) {
      if (values[2]->isDictionary())
        thisDict = CJValue::cast<CJDictionary>(values[2]);
    }

    if (! thisDict)
      thisDict = array;

    //---

    // ensure first value is array
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    // run function on each element
    CJArray::IndValues newValues;

    if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
      return CJValueP();

    CJObjType::Values fnValues;

    fnValues.push_back(array);      // this
    fnValues.push_back(CJValueP()); // value
    fnValues.push_back(CJValueP()); // index
    fnValues.push_back(array);      // array

    for (const auto &v : array->indValues()) {
      fnValues[1] = v.second.calcValue(js);
      fnValues[2] = js->createNumberValue(v.first);

      CJValueP res;

      if (fnValues[1]) {
        res = js->execFunction(fn, fnValues, thisDict);

        if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
          break;
      }

      newValues[v.first] = CJPropertyValue(res);
    }

    //---

    // return new values
    CJArrayP array1 = js->createArrayValue();

    array1->setValues(newValues, array->length().getValue(0));

    return array1;
  }
  else if (name == "pop") {
    CJValueP res;

    if (array) {
      long len = array->length().getValue(0);

      if (len < 1)
        return js->createUndefinedValue();

      res = array->removeValue();
    }
    else if (obj) {
      COptLong len = obj->length();

      long n = len.getValue(0);

      if (n > 0)
        res = obj->getProperty(js, std::to_string(n - 1));
      else
        res = js->createUndefinedValue();

      if (n > 0)
        obj->setLength(n - 1);
      else
        obj->setLength(0);
    }
    else {
      js->throwTypeError(values[0], "Invalid value type for " + name);
    }

    return res;
  }
  else if (name == "push") {
    long n = 0;

    if      (array) {
      for (uint i = 1; i < values.size(); ++i)
        array->addValue(values[i]);

      n = array->length().getValue(0);
    }
    else if (obj) {
      COptLong len = obj->length();

      n = len.getValue(0);

      for (uint i = 1; i < values.size(); ++i) {
        if (n >= CJUtil::maxInteger() + 1)
          n = 0;

        obj->setProperty(js, std::to_string(n), values[i]);

        ++n;
      }

      obj->setLength(n);
    }
    else {
      js->throwTypeError(values[0], "Invalid value type for " + name);
    }

    return js->createNumberValue(n);
  }
  else if (name == "reduce") {
    // get function
    CJFunctionP fn;

    if (values.size() >= 2) {
      if (values[1]->isFunction())
        fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! fn) {
      js->throwTypeError(values[0], "Missing function for " + name);
      return CJValueP();
    }

    //---

    // get init value
    CJValueP ivalue;
    bool     needInit = true;

    if (values.size() >= 3) {
      ivalue   = values[2];
      needInit = false;
    }

    //---

    // get array to process
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    CJObjType::Values fnValues;

    fnValues.push_back(array);
    fnValues.push_back(ivalue);     // prevValue
    fnValues.push_back(CJValueP()); // curValue
    fnValues.push_back(CJValueP()); // currentIndex
    fnValues.push_back(array);      // array

    for (const auto &v : array->indValues()) {
      if (needInit) {
        fnValues[1] = v.second.calcValue(js);
        needInit = false;
        continue;
      }

      fnValues[2] = v.second.calcValue(js);         // curValue
      fnValues[3] = js->createNumberValue(v.first); // currentIndex

      CJValueP res = fn->exec(js, fnValues);

      if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
        break;

      fnValues[1] = res;
    }

    if (needInit) {
      js->throwTypeError(values[0], "Missing initial value for " + name);
      return CJValueP();
    }

    return fnValues[1];
  }
  else if (name == "reduceRight") {
    // get function
    CJFunctionP fn;

    if (values.size() >= 2) {
      if (values[1]->isFunction())
        fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! fn) {
      js->throwTypeError(values[0], "Missing function for " + name);
      return CJValueP();
    }

    //---

    // get init value
    CJValueP ivalue;
    bool     needInit = true;

    if (values.size() >= 3) {
      ivalue = values[2];
      needInit = false;
    }

    //---

    // get array to process
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    CJObjType::Values fnValues;

    fnValues.push_back(array);
    fnValues.push_back(ivalue);     // prevValue
    fnValues.push_back(CJValueP()); // curValue
    fnValues.push_back(CJValueP()); // currentIndex
    fnValues.push_back(array);      // array

    for (auto p = array->indValues().rbegin(); p != array->indValues().rend(); ++p) {
      if (needInit) {
        fnValues[1] = (*p).second.calcValue(js);
        needInit = false;
        continue;
      }

      fnValues[2] = (*p).second.calcValue(js);         // curValue
      fnValues[3] = js->createNumberValue((*p).first); // currentIndex

      CJValueP res = fn->exec(js, fnValues);

      if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
        break;

      fnValues[1] = res;
    }

    if (needInit) {
      js->throwTypeError(values[0], "Missing initial value for " + name);
      return CJValueP();
    }

    return fnValues[1];
  }
  else if (name == "reverse") {
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    array->reverse();

    return array;
  }
  else if (name == "shift") {
    CJValueP remVal;

    if      (array) {
      long len = array->length().getValue(0);

      if (len >= 1)
        remVal = array->removeFrontValue();
      else
        remVal = js->createUndefinedValue();
    }
    else if (obj) {
      COptLong len = obj->length();

      long n = len.getValue(0);

      if (n >= 1) {
        for (long i = 0; i < n; ++i) {
          std::string ind = std::to_string(i);

          CJValueP val = obj->getProperty(js, ind);

          if (i == 0)
            remVal = val;
          else {
            if (! val) continue;

            std::string ind1 = std::to_string(i - 1);

            obj->setProperty(js, ind1, val);

            obj->deleteProperty(js, ind);
          }
        }
      }
      else
        remVal = js->createUndefinedValue();

      obj->setLength(n - 1);
    }
    else {
      array = createArrayFromValue(js, values[0]);

      long len = array->length().getValue(0);

      if (len >= 1)
        remVal = array->removeFrontValue();
      else
        remVal = js->createUndefinedValue();
    }

    return remVal;
  }
  else if (name == "slice") {
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    long len = array->length().getValue(0);

    long start = 0;
    long end   = len;

    if (values.size() >= 2) {
      COptLong optStart = values[1]->toInteger();

      if (optStart.isValid()) {
        start = optStart.getValue();

        if (start < 0)
          start = len + start;

        start = CJUtil::clamp(start, 0L, len);
      }
    }

    if (values.size() >= 3) {
      COptLong optEnd = values[2]->toInteger();

      if (optEnd.isValid()) {
        end = optEnd.getValue();

        if (end < 0)
          end = len + end;

        end = CJUtil::clamp(end, 0L, len);
      }
    }

    CJArray::IndValues newValues;
    long               newLen = 0;

    for (const auto &v : array->indValues()) {
      long ind = v.first;

      if (ind >= start && ind < end) {
        long ind1 = ind - start;

        newValues[ind1] = v.second;

        newLen = std::max(newLen, ind1 + 1);
      }
    }

    CJArrayP array1 = js->createArrayValue();

    array1->setValues(newValues, newLen);

    return array1;
  }
  else if (name == "some") {
    // get function
    CJFunctionP fn;

    if (values.size() >= 2) {
      if (values[1]->isFunction())
        fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! fn) {
      js->throwTypeError(values[0], "Missing function for " + name);
      return CJValueP();
    }

    //---

    // get optional this
    CJDictionaryP thisDict;

    if (values.size() >= 3) {
      if (values[2]->isDictionary())
        thisDict = CJValue::cast<CJDictionary>(values[2]);
    }

    //---

    // ensure first value is array
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    //---

    // run function on each element
    bool b = false;

    if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
      return CJValueP();

    CJObjType::Values fnValues;

    fnValues.push_back(array);      // this
    fnValues.push_back(CJValueP()); // value
    fnValues.push_back(CJValueP()); // index
    fnValues.push_back(array);      // array

    for (const auto &v : array->indValues()) {
      fnValues[1] = v.second.calcValue(js);
      fnValues[2] = js->createNumberValue(v.first);

      CJValueP res = js->execFunction(fn, fnValues, thisDict);

      if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
        break;

      if (res->toBoolean()) {
        b = true;
        break;
      }
    }

    //---

    // return some check

    return js->createBoolValue(b);
  }
  else if (name == "splice") {
    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    long len = array->length().getValue(0);

    // get start of splice (default to end of array)
    long start = 0;

    if (values.size() >= 2) {
      start = values[1]->toInteger().getValue(0);

      if (start < 0)
        start = len + start;

      start = CJUtil::clamp(start, 0L, len);
    }
    else
      start = len;

    // get number of elements to delete (default to all elements after start)
    long numDel = 0;

    if (values.size() >= 3) {
      numDel = values[2]->toInteger().getValue(0);

      numDel = CJUtil::clamp(numDel, 0L, len);
    }
    else
      numDel = len - start;

    // get number to insert
    long numIns = std::max<long>(values.size() - 3, 0);

    //---

    CJArray::IndValues newValues, remValues;
    long               newLen = 0, remLen = 0;

    for (const auto &v : array->indValues()) {
      long ind = v.first;

      // add values before start
      if      (ind < start) {
        newValues[ind] = v.second;

        newLen = std::max<long>(newLen, ind + 1);
      }
      // add values after start + numDel
      else if (ind >= start + numDel) {
        long ind1 = ind - numDel + numIns;

        newValues[ind1] = v.second;

        newLen = std::max<long>(newLen, ind1 + 1);
      }
      // save removed values
      else {
        long ind1 = ind - start;

        remValues[ind1] = v.second;

        remLen = std::max<long>(remLen, ind1 + 1);
      }
    }

    // insert new values
    for (std::size_t j = 3; j < values.size(); ++j) {
      long ind1 = start + j - 3;

      newValues[ind1] = CJPropertyValue(values[j]);

      newLen = std::max<long>(newLen, ind1 + 1);
    }

    // update array to new values
    array->setValues(newValues, newLen);

    // return array of old values
    CJArrayP array1 = js->createArrayValue();

    array1->setValues(remValues, remLen);

    return array1;
  }
  else if (name == "sort") {
    CJFunctionP fn;

    if (values.size() > 1) {
      if (! values[1]->isFunction()) {
        js->throwTypeError(values[0], "Invalid function for " + name);
        return CJValueP();
      }

      fn = CJValue::cast<CJFunction>(values[1]);
    }

    if (! array)
      array = createArrayFromValue(js, values[0]);

    if (! array) {
      js->throwTypeError(values[0], "Missing array for " + name);
      return CJValueP();
    }

    array->sort(fn);

    return array;
  }
  else if (name == "sum") {
    assert(false);
  }
  else if (name == "toString") {
    CJValueP joinValue;

    if (values[0]->isDictionary()) {
      CJDictionaryP dict = CJValue::cast<CJDictionary>(values[0]);

      joinValue = dict->getProperty(js_, "join");
    }

    if (joinValue) {
      if (joinValue->isFunction()) {
        CJFunctionP joinFn = CJValue::cast<CJFunction>(joinValue);

        Values fnValues = values;

        CJValueP res = js->execFunction(joinFn, fnValues);

        return res;
      }
      else
        return CJObjType::exec(js, name, values);
    }
    else
      return js->createStringValue(values[0]->toString());
  }
  else if (name == "toLocaleString") {
    std::string str;

    if (array) {
      int i = 0;

      for (const auto &v : array->indValues()) {
        if (i > 0)
          str += ",";

        CJValueP value1 = v.second.calcValue(js);

        CJDictionaryP dictVal;

        if (value1 && value1->isDictionary())
          dictVal = CJValue::cast<CJDictionary>(value1);

        if      (dictVal) {
          CJValueP fnValue = dictVal->getProperty(js, "toLocaleString");

          if (fnValue) {
            if (fnValue->isFunction()) {
              CJFunctionBaseP fn = CJValue::cast<CJFunctionBase>(fnValue);

              Values fnValues;

              CJValueP res = js->execFunction(fn, fnValues);

              if (js->getCurrentBlock() && js->getCurrentBlock()->hasError())
                break;

              if (res)
                str += res->toString();
            }
            else {
              js->throwTypeError(values[0], "toLocaleString is not a function for " + name);
              return CJValueP();
            }
          }
          else
            str += dictVal->toString();
        }
        else if (value1) {
          if (value1->type() != CJToken::Type::Undefined &&
              value1->type() != CJToken::Type::Null)
            str += value1->toString();
        }

        ++i;
      }
    }

    return js->createStringValue(str);
  }
  else if (name == "unshift") {
    long numAdd = values.size() - 1;

    long res = 0;

    if      (array) {
      for (long i = numAdd; i >= 1; --i)
        array->addFrontValue(values[i]);

      res = array->length().getValue(0L);
    }
    else if (obj) {
      COptLong len = obj->length();

      if (len.isValid()) {
        long n = len.getValue();

        for (long i = n - 1; i >= 0; --i) {
          std::string ind = std::to_string(i);

          CJPropertyValue data;

          if (obj->getPropertyData(js, ind, data)) {
            std::string ind1 = std::to_string(i + numAdd);

            obj->setProperty(js, ind1, data.calcValue(js));

            if (i >= 0 && i < numAdd) {
              obj->setProperty(js, ind, values[i + 1]);
            }
            else {
              obj->deleteProperty(js, ind);
            }
          }
          else {
            if (i >= 0 && i < numAdd) {
              obj->setProperty(js, ind, values[i + 1]);
            }
          }
        }
      }

      obj->setLength(len.getValue(0) + numAdd);

      res = obj->length().getValue(0L);
    }
    else {
      array = createArrayFromValue(js, values[0]);

      for (size_t i = values.size() - 1; i >= 1; --i)
        array->addFrontValue(values[i]);

      res = array->length().getValue(0L);
    }

    return js->createNumberValue(res);
  }
  else if (name == "propertyIsEnumerable") {
    if (values.size() < 2)
      return js->createBoolValue(false);

    COptLong ind = values[1]->toInteger();

    bool b = false;

    if (array && ind.isValid())
      b = array->isEnumerableIndex(ind.getValue());

    return js->createBoolValue(b);
  }
  else if (name == "hasOwnProperty") {
    if (values.size() < 2)
      return js->createBoolValue(false);

    return js->createBoolValue(js->hasIndexValue(values[0], values[1]));
  }
  else {
    js->errorMsg("Invalid array object function " + name);
  }

  return CJValueP();
}

//------

CJArray::
CJArray(CJavaScript *js, long n) :
 CJObj(js, CJArrayType::instance(js))
{
  if (n > 0)
    len_ = n;

  addPseudoProperty("length");
}

CJArray::
CJArray(CJavaScript *js, const IndValues &values, long len) :
 CJObj(js, CJArrayType::instance(js)), values_(values), len_(len)
{
  addPseudoProperty("length");
}

CJArray::
CJArray(CJavaScript *js, const std::vector<CJValueP> &values) :
 CJObj(js, CJArrayType::instance(js))
{
  setValues(values);

  addPseudoProperty("length");
}

CJArray::
CJArray(const CJArray &array) :
 CJObj(array), values_(array.values_), len_(array.len_)
{
}

void
CJArray::
setValues(const std::vector<CJValueP> &values)
{
  values_.clear();

  len_ = values.size();

  for (long ind = 0; ind < len_; ++ind)
    values_[ind] = CJPropertyValue(values[ind]);
}

void
CJArray::
setValues(const IndValues &values, long len)
{
  values_ = values;
  len_    = len;
}

std::string
CJArray::
toString() const
{
  auto addValue = [] (std::string &str, long &i, CJValueP value) {
    if (i > 0)
      str += ", ";

    if (value)
      str += value->toString();

    ++i;
  };

  //---

  std::string str;

  long i = 0;

  for (const auto &v : values_) {
    while (i < v.first)
      addValue(str, i, CJValueP());

    addValue(str, i, v.second.calcValue(js_));
  }

  while (i < len_)
    addValue(str, i, CJValueP());

  //---

  for (auto &kv : keyValues()) {
    if (i > 0)
      str += ", ";

    str += "'" + kv.first + "': ";

    CJValueP value1 = kv.second.calcValue(js_);

    if (value1)
      str += value1->toString();
    else
      str += "<null>";

    ++i;
  }

  return str;
}

COptReal
CJArray::
toReal() const
{
  long n = length().getValue(0);

  if      (n == 0)
    return COptReal(0);
  else if (n == 1) {
    CJValueP value = indexValue(0);

    return (value ? COptReal(value->toReal()) : COptReal());
  }
  else
    return COptReal(CJUtil::getNaN());
}

COptLong
CJArray::
toInteger() const
{
  long n = length().getValue(0);

  if      (n == 0)
    return COptLong(0);
  else if (n == 1) {
    CJValueP value = indexValue(0);

    return (value ? COptLong(value->toInteger()) : COptLong());
  }
  else
    return COptLong(0);
}

void
CJArray::
addValue(CJValueP value)
{
  CJPropertyValue propVal(value);

  addValue(propVal);
}

void
CJArray::
addValue(const CJPropertyValue &propVal)
{
  if (len_ + 1 > CJUtil::maxInteger()) {
    js_->throwRangeError(this, "Invalid array length");
    return;
  }

  values_[len_++] = propVal;
}

CJValueP
CJArray::
removeValue()
{
  assert(len_ > 0);

  --len_;

  CJPropertyValue data = values_[len_];

  values_.erase(len_);

  return data.value();
}

void
CJArray::
addFrontValue(CJValueP value)
{
  IndValues newValues;

  for (const auto &v : values_) {
    long ind1 = v.first + 1;

    newValues[ind1] = v.second;
  }

  newValues[0] = CJPropertyValue(value);

  values_ = newValues;

  ++len_;
}

CJValueP
CJArray::
removeFrontValue()
{
  assert(len_ > 0);

  CJPropertyValue remData;

  IndValues newValues;

  for (const auto &v : values_) {
    long ind1 = v.first - 1;

    if (ind1 >= 0)
      newValues[ind1] = v.second;
    else
      remData = v.second;
  }

  values_ = newValues;

  --len_;

  return remData.value();
}

bool
CJArray::
hasIndexValue(long ind) const
{
  if (ind < 0 || ind >= len_)
    return false;

  auto p = values_.find(ind);

  if (p == values_.end())
    return false;

  CJValueP value1 = (*p).second.calcValue(js_);

  return !!value1;
}

CJValueP
CJArray::
indexValue(long ind) const
{
  if (ind < 0 || ind >= len_)
    return CJValueP();

  auto p = values_.find(ind);

  if (p == values_.end())
    return CJValueP();

  CJValueP value = (*p).second.calcValue(js_);

  if (value && value->type() == CJToken::Type::GetterSetter) {
    CJGetterSetterP gs = CJValue::cast<CJGetterSetter>(value);

    CJObjectP obj = CJValue::cast<CJObject>(gs->parent());

    js_->pushThis(obj);

    value = gs->getValue();

    js_->popThis();
  }

  return value;
}

void
CJArray::
setIndexValue(long ind, CJValueP value)
{
  if (ind < 0)
    return;

  if (ind < len_ && ! isWritableIndex(ind))
    return;

  values_[ind].setValue(value);

  len_ = std::max(ind + 1, len_);
}

void
CJArray::
deleteIndexValue(long ind)
{
  assert(ind >= 0 && ind < len_);

  values_.erase(ind);
}

bool
CJArray::
isWritableIndex(long ind) const
{
  if (ind < 0 || ind >= len_)
    return false;

  auto p = values_.find(ind);

  if (p == values_.end())
    return true;

  return (*p).second.isWriteable();
}

void
CJArray::
setWritableIndex(long ind, bool b)
{
  assert(ind >= 0 && ind < len_);

  values_[ind].setWriteable(b);
}

bool
CJArray::
isEnumerableIndex(long ind) const
{
  if (ind < 0 || ind >= len_)
    return false;

  auto p = values_.find(ind);

  if (p == values_.end())
    return false;

  return (*p).second.isEnumerable();
}

void
CJArray::
setEnumerableIndex(long ind, bool b)
{
  assert(ind >= 0 && ind < len_);

  values_[ind].setEnumerable(b);
}

bool
CJArray::
isConfigurableIndex(long ind) const
{
  if (ind < 0 || ind >= len_)
    return false;

  auto p = values_.find(ind);

  if (p == values_.end())
    return true;

  return (*p).second.isConfigurable();
}

void
CJArray::
setConfigurableIndex(long ind, bool b)
{
  assert(ind >= 0 && ind < len_);

  values_[ind].setConfigurable(b);
}

COptLong
CJArray::
length() const
{
  return COptLong(len_);
}

void
CJArray::
setLength(long n)
{
  if (n > CJUtil::maxInteger()) {
    js_->throwRangeError(this, "Invalid array length");
    return;
  }

  if (n < len_) {
    while (len_ > n) {
      --len_;

      values_.erase(len_);
    }
  }
  else
    len_ = n;
}

void
CJArray::
reverse()
{
  for (long i = 0, j = len_ - 1; i < j; ++i, --j)
    std::swap(values_[i], values_[j]);
}

void
CJArray::
sort(CJFunctionP fn)
{
  class Cmp {
   public:
    Cmp(CJavaScript *js, CJFunctionP fn) :
     js_(js), fn_(fn) {
    }

    bool operator()(const CJPropertyValue &v1, const CJPropertyValue &v2) {
      if (! v2.value()) return true;
      if (! v1.value()) return false;

      if (js_->isUndefinedValue(v2.value())) return true;
      if (js_->isUndefinedValue(v1.value())) return false;

      if (! fn_) {
        return (v1.value()->cmp(v2.value().get()) < 0);
      }
      else {
        CJObjType::Values fnValues;

        fnValues.push_back(CJValueP());
        fnValues.push_back(v1.value());
        fnValues.push_back(v2.value());

        CJValueP res = fn_->exec(js_, fnValues);

        if (! res)
          return false;

        return (res->toInteger().getValue(0) < 0);
      }
    }

   private:
    CJavaScript *js_ { 0 };
    CJFunctionP  fn_;
  };

  //---

  Cmp cmp(js_, fn);

  Values values;

  values.reserve(values_.size());

  for (const auto &v : values_)
    values.push_back(v.second);

  std::sort(values.begin(), values.end(), cmp);

  int i = 0;

  for (auto &v : values_) {
    v.second = values[i++];
  }
}

CJValueP
CJArray::
getProperty(CJavaScript *js, const std::string &key) const
{
  if (key == "length")
    return js->createNumberValue(length().getValue(0));

  return CJObj::getProperty(js, key);
}

void
CJArray::
setProperty(CJavaScript *js, const std::string &key, CJValueP value)
{
  if (key == "length") {
    setLength(value->toInteger().getValue(0));
  }
  else
    CJObj::setProperty(js, key, value);
}

CJNameSpace::Names
CJArray::
getPropertyNames(bool /*pseudo*/) const
{
  CJNameSpace::Names names;

  names.push_back("length");

  return names;
}

bool
CJArray::
hasValue(CJValueP value) const
{
  for (const auto &v : values_) {
    if (js_->cmp(v.second.calcValue(js_), value) == 0)
      return true;
  }

  return false;
}

void
CJArray::
print(std::ostream &os) const
{
  auto addValue = [] (std::ostream &os1, long &i, CJValueP value) {
    if (i > 0)
      os1 << ",";

    os1 << " ";

    if (value)
      value->print(os1);

    ++i;
  };

  //---

  os << "[";

  long i = 0;

  for (const auto &v : values_) {
    while (i < v.first)
      addValue(os, i, CJValueP());

    addValue(os, i, v.second.calcValue(js_));
  }

  while (i < len_)
    addValue(os, i, CJValueP());

  //---

  for (auto &kv : keyValues()) {
    if (i > 0)
      os << ",";

    os << " '" << kv.first << "': ";

    CJValueP value1 = kv.second.calcValue(js_);

    if (value1)
      os << *value1;
    else
      os << "<null>";

    ++i;
  }

  //---

  if (i > 0)
    os << " ";

  os << "]";
}


text:
<CartClearResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
  <OperationRequest>
    <HTTPHeaders>
      <Header Name="UserAgent" Value="Python-urllib/2.6"/>
    </HTTPHeaders>
    <RequestId>1KFNEG9YQMAFHBTYZNXY</RequestId>
    <Arguments>
      <Argument Name="AssociateTag" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="CartId" Value="477-4863405-2895915"/>
      <Argument Name="Service" Value="AWSECommerceService"/>
      <Argument Name="AWSAccessKeyId" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="Timestamp" Value="2011-11-13T12:07:43Z"/>
      <Argument Name="Signature" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="Version" Value="2011-08-01"/>
      <Argument Name="HMAC" Value="mVdQMjXrsaGzGd7dKp1bs+E7dko="/>
      <Argument Name="Operation" Value="CartClear"/>
    </Arguments>
    <RequestProcessingTime>0.0380611419677734</RequestProcessingTime>
  </OperationRequest>
  <Cart>
    <Request>
      <IsValid>True</IsValid>
      <CartClearRequest>
        <CartId>477-4863405-2895915</CartId>
        <HMAC>mVdQMjXrsaGzGd7dKp1bs+E7dko=</HMAC>
      </CartClearRequest>
    </Request>
    <CartId>477-4863405-2895915</CartId>
    <HMAC>mVdQMjXrsaGzGd7dKp1bs+E7dko=</HMAC>
    <URLEncodedHMAC>mVdQMjXrsaGzGd7dKp1bs%2BE7dko%3D</URLEncodedHMAC>
  </Cart>
</CartClearResponse>

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>

#include "imapfilter.h"
#include "session.h"
#include "list.h"
#include "pathnames.h"

extern options opts;
extern environment env;
extern unsigned int flags;
extern list *sessions;

static FILE *debugfp = NULL;	/* Pointer to debug file. */
static FILE *logfp = NULL;	/* Pointer to log file. */

char *log_time(void);

/*
 * Print message if in verbose mode.
 */
void
verbose(const char *fmt,...)
{
	va_list args;

	if (!opts.verbose)
		return;

	va_start(args, fmt);
	vprintf(fmt, args);
	fflush(stdout);
	va_end(args);
}

/*
 * Write message to debug file.
 */
void
debug(const char *fmt,...)
{
	va_list args;

	if (!opts.debug || !debugfp)
		return;

	va_start(args, fmt);
	vfprintf(debugfp, fmt, args);
	fflush(debugfp);
	va_end(args);
}

/*
 * Write character to debug file.
 */
void
debugc(char c)
{

	if (!opts.debug || !debugfp)
		return;

	fputc(c, debugfp);
}

/*
 * Print error message and write it into log file.
 */
void
error(const char *fmt,...)
{
	va_list args;

	va_start(args, fmt);
	fprintf(stderr, "imapfilter: ");
	vfprintf(stderr, fmt, args);
	fflush(stderr);
	va_end(args);
	if (logfp) {
		va_start(args, fmt);
		fprintf(logfp, "%s: ", log_time());
		vfprintf(logfp, fmt, args);
		fflush(logfp);
		va_end(args);
	}
}

/*
 * Print error message and exit program.
 */
void
fatal(unsigned int errnum, const char *fmt,...)
{
	va_list args;
	list *l;
	session *s;

	va_start(args, fmt);
	fprintf(stderr, "imapfilter: ");
	vfprintf(stderr, fmt, args);
	fflush(stderr);
	va_end(args);

	if (logfp) {
		va_start(args, fmt);
		fprintf(logfp, "%s: ", log_time());
		vfprintf(logfp, fmt, args);
		fflush(logfp);
		va_end(args);
	}

	for (l = sessions; l; l = l->next) {
		s = l->data;
		close_connection(s);
	}

	close_log();
	close_debug();

	exit(errnum);
}

/*
 * Open temporary debug file and associate a stream with the returned file
 * descriptor.
 */
int
open_debug(void)
{

	if (!opts.debug)
		return 0;

	if (create_file(opts.debug, S_IRUSR | S_IWUSR))
		return 1;

	debugfp = fopen(opts.debug, "w");
	if (debugfp == NULL) {
		error("opening debug file %s: %s\n", opts.debug,
		    strerror(errno));
		return 1;
	}
	return 0;
}

/*
 * Close temporary debug file.
 */
int
close_debug(void)
{

	if (debugfp == NULL)
		return 0;
	else
		return fclose(debugfp);
}

/*
 * Open the file for saving of logging information.
 */
int
open_log(void)
{

	if (opts.log == NULL)
		return 0;

	debug("log file: '%s'\n", opts.log);

	if (create_file(opts.log, S_IRUSR | S_IWUSR))
		return 1;

	logfp = fopen(opts.log, "a");
	if (logfp == NULL) {
		error("opening log file %s: %s\n", opts.log, strerror(errno));
		return 1;
	}
	return 0;
}

/*
 * Close the log file.
 */
int
close_log(void)
{

	if (logfp == NULL)
		return 0;
	else
		return fclose(logfp);
}

/*
 * Return current local time and date.
 */
char *
log_time(void)
{
	char *ct;
	time_t t;

	t = time(NULL);

	ct = ctime(&t);
	*(strchr(ct, '\n')) = '\0';

	return ct;
}


text:
Persistent<FunctionTemplate> Grid::constructor;

void Grid::Initialize(Handle<Object> target) {

    HandleScope scope;

    constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Grid::New));
    constructor->InstanceTemplate()->SetInternalFieldCount(1);
    constructor->SetClassName(String::NewSymbol("Grid"));

    // methods
    NODE_SET_PROTOTYPE_METHOD(constructor, "encodeSync", encodeSync);
    NODE_SET_PROTOTYPE_METHOD(constructor, "encode", encode);
    NODE_SET_PROTOTYPE_METHOD(constructor, "fields", fields);
    NODE_SET_PROTOTYPE_METHOD(constructor, "view", view);
    NODE_SET_PROTOTYPE_METHOD(constructor, "width", width);
    NODE_SET_PROTOTYPE_METHOD(constructor, "height", height);
    NODE_SET_PROTOTYPE_METHOD(constructor, "painted", painted);
    NODE_SET_PROTOTYPE_METHOD(constructor, "clear", clear);
    NODE_SET_PROTOTYPE_METHOD(constructor, "clearSync", clear);
    // properties
    ATTR(constructor, "key", get_prop, set_prop);

    target->Set(String::NewSymbol("Grid"),constructor->GetFunction());
#if MAPNIK_VERSION < 200100
    NODE_MAPNIK_DEFINE_CONSTANT(constructor->GetFunction(), "base_mask", 0);
#else
    NODE_MAPNIK_DEFINE_64_BIT_CONSTANT(constructor->GetFunction(), "base_mask", mapnik::grid::base_mask);
#endif
}

Grid::Grid(unsigned int width, unsigned int height, std::string const& key, unsigned int resolution) :
    ObjectWrap(),
    this_(boost::make_shared<mapnik::grid>(width,height,key,resolution)),
    estimated_size_(width * height) {
#if MAPNIK_VERSION <= 200100
    this_->painted(false);
#endif
    V8::AdjustAmountOfExternalAllocatedMemory(estimated_size_);
}

Grid::~Grid()
{
    V8::AdjustAmountOfExternalAllocatedMemory(-estimated_size_);
}

Handle<Value> Grid::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Grid* g =  static_cast<Grid*>(ptr);
        g->Wrap(args.This());
        return args.This();
    }

    if (args.Length() >= 2)
    {
        if (!args[0]->IsNumber() || !args[1]->IsNumber())
            return ThrowException(Exception::TypeError(
                                      String::New("Grid 'width' and 'height' must be a integers")));

        // defaults
        std::string key("__id__");
        unsigned int resolution = 1;

        if (args.Length() >= 3) {

            if (!args[2]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("optional third arg must be an options object")));
            Local<Object> options = args[2]->ToObject();

            if (options->Has(String::New("key"))) {
                Local<Value> bind_opt = options->Get(String::New("key"));
                if (!bind_opt->IsString())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'key' must be an string")));

                key = TOSTR(bind_opt);
            }
            // TODO - remove, deprecated
            if (options->Has(String::New("resolution"))) {
                Local<Value> bind_opt = options->Get(String::New("resolution"));
                if (!bind_opt->IsNumber())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'resolution' must be an string")));

                resolution = bind_opt->IntegerValue();
            }
        }

        Grid* g = new Grid(args[0]->IntegerValue(),args[1]->IntegerValue(),key,resolution);
        g->Wrap(args.This());
        return args.This();
    }
    else
    {
        return ThrowException(Exception::Error(
                                  String::New("please provide Grid width and height")));
    }
    return Undefined();
}

Handle<Value> Grid::clearSync(const Arguments& args)
{
    HandleScope scope;
#if MAPNIK_VERSION >= 200200
    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());
    g->get()->clear();
#endif
    return Undefined();
}

typedef struct {
    uv_work_t request;
    Grid* g;
    std::string format;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
} clear_grid_baton_t;

Handle<Value> Grid::clear(const Arguments& args)
{
    HandleScope scope;
    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());

    if (args.Length() == 0) {
        return clearSync(args);
    }
    // ensure callback is a function
    Local<Value> callback = args[args.Length()-1];
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));
    clear_grid_baton_t *closure = new clear_grid_baton_t();
    closure->request.data = closure;
    closure->g = g;
    closure->error = false;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Clear, (uv_after_work_cb)EIO_AfterClear);
    g->Ref();
    return Undefined();
}

void Grid::EIO_Clear(uv_work_t* req)
{
#if MAPNIK_VERSION >= 200200
    clear_grid_baton_t *closure = static_cast<clear_grid_baton_t *>(req->data);
    try
    {
        closure->g->get()->clear();
    }
    catch(std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
#endif
}

void Grid::EIO_AfterClear(uv_work_t* req)
{
    HandleScope scope;
    clear_grid_baton_t *closure = static_cast<clear_grid_baton_t *>(req->data);
    TryCatch try_catch;
    if (closure->error)
    {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    else
    {
        Local<Value> argv[2] = { Local<Value>::New(Null()) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    }
    if (try_catch.HasCaught())
    {
        node::FatalException(try_catch);
    }
    closure->g->Unref();
    closure->cb.Dispose();
    delete closure;
}

Handle<Value> Grid::painted(const Arguments& args)
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());
    return scope.Close(Boolean::New(g->get()->painted()));
}

Handle<Value> Grid::width(const Arguments& args)
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());
    return scope.Close(Integer::New(g->get()->width()));
}

Handle<Value> Grid::height(const Arguments& args)
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());
    return scope.Close(Integer::New(g->get()->height()));
}

Handle<Value> Grid::get_prop(Local<String> property,
                             const AccessorInfo& info)
{
    HandleScope scope;
    Grid* g = node::ObjectWrap::Unwrap<Grid>(info.Holder());
    std::string a = TOSTR(property);
    if (a == "key")
        return scope.Close(String::New(g->get()->get_key().c_str()));
    return Undefined();
}

void Grid::set_prop(Local<String> property,
                    Local<Value> value,
                    const AccessorInfo& info)
{
    HandleScope scope;
    Grid* g = node::ObjectWrap::Unwrap<Grid>(info.Holder());
    std::string a = TOSTR(property);
    if (a == "key") {
        if (!value->IsNumber())
            ThrowException(Exception::TypeError(
                               String::New("width must be an integer")));
        g->get()->set_key(TOSTR(value));
    }
}

Handle<Value> Grid::fields(const Arguments& args)
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());
    std::set<std::string> const& a = g->get()->property_names();
    std::set<std::string>::const_iterator itr = a.begin();
    std::set<std::string>::const_iterator end = a.end();
    Local<Array> l = Array::New(a.size());
    int idx = 0;
    for (; itr != end; ++itr)
    {
        std::string name = *itr;
        l->Set(idx, String::New(name.c_str()));
        ++idx;
    }
    return scope.Close(l);

}

Handle<Value> Grid::view(const Arguments& args)
{
    HandleScope scope;

    if ( (args.Length() != 4) || (!args[0]->IsNumber() && !args[1]->IsNumber() && !args[2]->IsNumber() && !args[3]->IsNumber() ))
        return ThrowException(Exception::TypeError(
                                  String::New("requires 4 integer arguments: x, y, width, height")));

    unsigned x = args[0]->IntegerValue();
    unsigned y = args[1]->IntegerValue();
    unsigned w = args[2]->IntegerValue();
    unsigned h = args[3]->IntegerValue();

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());
    return scope.Close(GridView::New(g,x,y,w,h));
}

#if MAPNIK_VERSION >= 200100

Handle<Value> Grid::encodeSync(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
                return ThrowException(Exception::TypeError(
                                          String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    try {

        boost::ptr_vector<uint16_t> lines;
        std::vector<mapnik::grid::lookup_type> key_order;
        node_mapnik::grid2utf<mapnik::grid>(*g->get(),lines,key_order,resolution);

        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }

        mapnik::grid const& grid_type = *g->get();

        // gather feature data
        Local<Object> feature_data = Object::New();
        if (add_features) {
            node_mapnik::write_features<mapnik::grid>(*g->get(),
                                                      feature_data,
                                                      key_order);
        }

        // Create the return hash.
        Local<Object> json = Object::New();
        Local<Array> grid_array = Array::New();
        unsigned array_size = std::ceil(grid_type.width()/static_cast<float>(resolution));
        for (unsigned j=0;j<lines.size();++j)
        {
            grid_array->Set(j,String::New(&lines[j],array_size));
        }
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);
        return json;

    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}

typedef struct {
    uv_work_t request;
    Grid* g;
    std::string format;
    bool error;
    std::string error_name;
    Persistent<Function> cb;
    boost::ptr_vector<uint16_t> lines;
    unsigned int resolution;
    bool add_features;
    std::vector<mapnik::grid::lookup_type> key_order;
} encode_grid_baton_t;

Handle<Value> Grid::encode(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
                return ThrowException(Exception::TypeError(
                                          String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    // ensure callback is a function
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));
    Local<Function> callback = Local<Function>::Cast(args[args.Length()-1]);

    encode_grid_baton_t *closure = new encode_grid_baton_t();
    closure->request.data = closure;
    closure->g = g;
    closure->format = format;
    closure->error = false;
    closure->resolution = resolution;
    closure->add_features = add_features;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    // todo - reserve lines size?
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, (uv_after_work_cb)EIO_AfterEncode);
    g->Ref();
    return Undefined();
}

void Grid::EIO_Encode(uv_work_t* req)
{
    encode_grid_baton_t *closure = static_cast<encode_grid_baton_t *>(req->data);

    try
    {
        node_mapnik::grid2utf<mapnik::grid>(*closure->g->get(),
                                            closure->lines,
                                            closure->key_order,
                                            closure->resolution);
    }
    catch (std::exception const& ex)
    {
        closure->error = true;
        closure->error_name = ex.what();
    }
}

void Grid::EIO_AfterEncode(uv_work_t* req)
{
    HandleScope scope;

    encode_grid_baton_t *closure = static_cast<encode_grid_baton_t *>(req->data);

    TryCatch try_catch;

    if (closure->error) {
        Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
        closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
    } else {

        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(closure->key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = closure->key_order.begin(), i = 0; it < closure->key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }

        mapnik::grid const& grid_type = *closure->g->get();
        // gather feature data
        Local<Object> feature_data = Object::New();
        if (closure->add_features) {
            node_mapnik::write_features<mapnik::grid>(grid_type,
                                                      feature_data,
                                                      closure->key_order);
        }

        // Create the return hash.
        Local<Object> json = Object::New();
        Local<Array> grid_array = Array::New(closure->lines.size());
        unsigned array_size = std::ceil(grid_type.width()/static_cast<float>(closure->resolution));
        for (unsigned j=0;j<closure->lines.size();++j)
        {
            grid_array->Set(j,String::New(&closure->lines[j],array_size));
        }
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);

        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(json) };
        closure->cb->Call(Context::GetCurrent()->Global(), 2, argv);
    }

    if (try_catch.HasCaught()) {
        node::FatalException(try_catch);
    }

    closure->g->Unref();
    closure->cb.Dispose();
    delete closure;
}

#else

Handle<Value> Grid::encodeSync(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
                return ThrowException(Exception::TypeError(
                                          String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    try {

        Local<Array> grid_array = Array::New();
        std::vector<mapnik::grid::lookup_type> key_order;
        node_mapnik::grid2utf<mapnik::grid>(*g->get(),grid_array,key_order,resolution);

        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }

        // gather feature data
        Local<Object> feature_data = Object::New();
        if (add_features) {
            node_mapnik::write_features<mapnik::grid>(*g->get(),
                                                      feature_data,
                                                      key_order
                );
        }

        // Create the return hash.
        Local<Object> json = Object::New();
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);
        return json;

    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}

// @TODO: convert this to EIO. It's currently doing all the work in the main
// thread, and just provides an async interface.
Handle<Value> Grid::encode(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = node::ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
                return ThrowException(Exception::TypeError(
                                          String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    // ensure callback is a function
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));
    Local<Function> callback = Local<Function>::Cast(args[args.Length()-1]);

    try {

        Local<Array> grid_array = Array::New();
        std::vector<mapnik::grid::lookup_type> key_order;
        node_mapnik::grid2utf<mapnik::grid>(*g->get(),grid_array,key_order,resolution);

        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }

        // gather feature data
        Local<Object> feature_data = Object::New();
        if (add_features) {
            node_mapnik::write_features<mapnik::grid>(*g->get(),
                                                      feature_data,
                                                      key_order
                );
        }

        // Create the return hash.
        Local<Object> json = Object::New();
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);

        TryCatch try_catch;
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(json) };
        callback->Call(Context::GetCurrent()->Global(), 2, argv);
        if (try_catch.HasCaught()) {
            node::FatalException(try_catch);
        }
    }
    catch (std::exception const& ex)
    {
        Local<Value> argv[1] = { Exception::Error(String::New(ex.what())) };
        callback->Call(Context::GetCurrent()->Global(), 1, argv);
    }

    return scope.Close(Undefined());
}

#endif


text:
import gzip
import os
import os.path

def main():
apt_log_path = '/var/log/apt'
dirlist = os.listdir(apt_log_path)
# somehow this dict will magically order all the numerical keys
history_files = {}
for filename in dirlist:
    if filename.startswith('history.log'):
        if filename[len('history.log') + 1:-3] == '':
            file_number = 0
        else:
            file_number = int(filename[len('history.log') + 1:-3])
        history_files[file_number] = filename

installed = []
removed = []

# go through the list of history files in reverse order
for index in history_files:
    filename = history_files[len(history_files) - index - 1]

    if filename.endswith('gz'):
        history_file = gzip.open(os.path.join(apt_log_path, filename))
    else:
        history_file = open(os.path.join(apt_log_path, filename))

    for line in history_file:
        if line.startswith('Commandline'):
            command_words = line.split()[2:]
            if command_words[0].startswith('-'):
                del command_words[0]

            if command_words[0] == 'install':
                for package in command_words[1:]:
                    if package.startswith('-'):
                        continue
                    if package not in installed:
                        installed.append(package)
                    if package in removed:
                        removed.remove(package)

            elif (command_words[0] == 'remove' or
                command_words[0] == 'autoremove'):
                for package in command_words[1:]:
                    if package.startswith('-'):
                        continue
                    if package not in removed:
                        removed.append(package)
                    if package in installed:
                        installed.remove(package)

            '''
                commands.append(line.split()[2])

            if command_words[0] not in commands:
                commands.append(command_words[0])

            for command_word in command_words:
                if command_word.startswith('-'):
                    continue

            if line.split()[2] == 'install':
            elif line.split()[2] == 'remove' or line.split()[2] == 'autoremove':
                commands.append(line.split()[2])
            '''

'''
Commandline: apt-get install gnote
Commandline: apt-get remove footnote
'''

if __name__ == '__main__':
    main()


text:
package kubernetes

import (
	"io/ioutil"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/prometheus/config"

	"github.com/prometheus/common/log"
	"github.com/prometheus/common/model"
	"golang.org/x/net/context"
	"k8s.io/client-go/1.5/kubernetes"
	"k8s.io/client-go/1.5/pkg/api"
	apiv1 "k8s.io/client-go/1.5/pkg/api/v1"
	"k8s.io/client-go/1.5/pkg/util/runtime"
	"k8s.io/client-go/1.5/rest"
	"k8s.io/client-go/1.5/tools/cache"
)

const (
	// kubernetesMetaLabelPrefix is the meta prefix used for all meta labels.
	// in this discovery.
	metaLabelPrefix = model.MetaLabelPrefix + "kubernetes_"
	namespaceLabel  = metaLabelPrefix + "namespace"
)

var (
	eventCount = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "prometheus_sd_kubernetes_events_total",
			Help: "The number of Kubernetes events handled.",
		},
		[]string{"role", "event"},
	)
)

func init() {
	prometheus.MustRegister(eventCount)

	// Initialize metric vectors.
	for _, role := range []string{"endpoints", "node", "pod", "service"} {
		for _, evt := range []string{"add", "delete", "update"} {
			eventCount.WithLabelValues(role, evt)
		}
	}
}

// Kubernetes implements the TargetProvider interface for discovering
// targets from Kubernetes.
type Kubernetes struct {
	client kubernetes.Interface
	role   config.KubernetesRole
	logger log.Logger
}

func init() {
	runtime.ErrorHandlers = []func(error){
		func(err error) {
			log.With("component", "kube_client_runtime").Errorln(err)
		},
	}
}

// New creates a new Kubernetes discovery for the given role.
func New(l log.Logger, conf *config.KubernetesSDConfig) (*Kubernetes, error) {
	var (
		kcfg *rest.Config
		err  error
	)
	if conf.APIServer.URL == nil {
		kcfg, err = rest.InClusterConfig()
		if err != nil {
			return nil, err
		}
	} else {
		token := conf.BearerToken
		if conf.BearerTokenFile != "" {
			bf, err := ioutil.ReadFile(conf.BearerTokenFile)
			if err != nil {
				return nil, err
			}
			token = string(bf)
		}

		kcfg = &rest.Config{
			Host:        conf.APIServer.String(),
			BearerToken: token,
			TLSClientConfig: rest.TLSClientConfig{
				CAFile: conf.TLSConfig.CAFile,
			},
		}
	}
	kcfg.UserAgent = "prometheus/discovery"

	if conf.BasicAuth != nil {
		kcfg.Username = conf.BasicAuth.Username
		kcfg.Password = conf.BasicAuth.Password
	}
	kcfg.TLSClientConfig.CertFile = conf.TLSConfig.CertFile
	kcfg.TLSClientConfig.KeyFile = conf.TLSConfig.KeyFile
	kcfg.Insecure = conf.TLSConfig.InsecureSkipVerify

	c, err := kubernetes.NewForConfig(kcfg)
	if err != nil {
		return nil, err
	}
	return &Kubernetes{
		client: c,
		logger: l,
		role:   conf.Role,
	}, nil
}

const resyncPeriod = 10 * time.Minute

// Run implements the TargetProvider interface.
func (k *Kubernetes) Run(ctx context.Context, ch chan<- []*config.TargetGroup) {
	rclient := k.client.Core().GetRESTClient()

	switch k.role {
	case "endpoints":
		elw := cache.NewListWatchFromClient(rclient, "endpoints", api.NamespaceAll, nil)
		slw := cache.NewListWatchFromClient(rclient, "services", api.NamespaceAll, nil)
		plw := cache.NewListWatchFromClient(rclient, "pods", api.NamespaceAll, nil)
		eps := NewEndpoints(
			k.logger.With("kubernetes_sd", "endpoint"),
			cache.NewSharedInformer(slw, &apiv1.Service{}, resyncPeriod),
			cache.NewSharedInformer(elw, &apiv1.Endpoints{}, resyncPeriod),
			cache.NewSharedInformer(plw, &apiv1.Pod{}, resyncPeriod),
		)
		go eps.endpointsInf.Run(ctx.Done())
		go eps.serviceInf.Run(ctx.Done())
		go eps.podInf.Run(ctx.Done())

		for !eps.serviceInf.HasSynced() {
			time.Sleep(100 * time.Millisecond)
		}
		for !eps.endpointsInf.HasSynced() {
			time.Sleep(100 * time.Millisecond)
		}
		for !eps.podInf.HasSynced() {
			time.Sleep(100 * time.Millisecond)
		}
		eps.Run(ctx, ch)

	case "pod":
		plw := cache.NewListWatchFromClient(rclient, "pods", api.NamespaceAll, nil)
		pod := NewPod(
			k.logger.With("kubernetes_sd", "pod"),
			cache.NewSharedInformer(plw, &apiv1.Pod{}, resyncPeriod),
		)
		go pod.informer.Run(ctx.Done())

		for !pod.informer.HasSynced() {
			time.Sleep(100 * time.Millisecond)
		}
		pod.Run(ctx, ch)

	case "service":
		slw := cache.NewListWatchFromClient(rclient, "services", api.NamespaceAll, nil)
		svc := NewService(
			k.logger.With("kubernetes_sd", "service"),
			cache.NewSharedInformer(slw, &apiv1.Service{}, resyncPeriod),
		)
		go svc.informer.Run(ctx.Done())

		for !svc.informer.HasSynced() {
			time.Sleep(100 * time.Millisecond)
		}
		svc.Run(ctx, ch)

	case "node":
		nlw := cache.NewListWatchFromClient(rclient, "nodes", api.NamespaceAll, nil)
		node := NewNode(
			k.logger.With("kubernetes_sd", "node"),
			cache.NewSharedInformer(nlw, &apiv1.Node{}, resyncPeriod),
		)
		go node.informer.Run(ctx.Done())

		for !node.informer.HasSynced() {
			time.Sleep(100 * time.Millisecond)
		}
		node.Run(ctx, ch)

	default:
		k.logger.Errorf("unknown Kubernetes discovery kind %q", k.role)
	}

	<-ctx.Done()
}

func lv(s string) model.LabelValue {
	return model.LabelValue(s)
}


text:
require "rest-client"

admin = User.find_or_create_by(email: "admin@example.com", type: Admin.name) do |user|
  user.password              = "admin"
  user.password_confirmation = "admin"
  user.save!
end
puts "Create admin user as id: #{admin.id}"
test_user = User.find_or_create_by(email: "test_member@example.com", type: Member.name) do |user|
  user.password              = "test_memeber"
  user.password_confirmation = "test_memeber"
  user.save!
end
puts "Create test member as id: #{test_user.id}"

app = Doorkeeper::Application.find_or_create_by name: "ios",
                                                redirect_uri: "urn:ietf:wg:oauth:2.0:oob"

puts "Create ios app id: #{app.id}"

Journal.where(label: "highlight").first_or_create
puts "Create default journal hightlight"

news_topic = Topic.first_or_create(label: "news")

feed_urls = [
  "http://pitchfork.com/rss/news",
  "http://pitchfork.com/rss/reviews/best/albums",
  "http://pitchfork.com/rss/reviews/best/tracks",
  "http://spincoaster.com/feed"
]

feeds = feed_urls.map do |url|
  puts "Creating #{url}"
  f = Feed.find_or_create_by_url(url)
  puts "Created #{f.id}"
  f
end

news_topic.feeds = feeds


text:
/**********************************************************************/
/* InstallCommon.SQL                                                  */
/*                                                                    */
/* Installs the tables, triggers and stored procedures necessary for  */
/* supporting some features of ASP.Net                                */
/*
** Copyright Microsoft, Inc. 2003
** All Rights Reserved.
*/
/**********************************************************************/

PRINT '---------------------------------------'
PRINT 'Starting execution of InstallCommon.SQL'
PRINT '---------------------------------------'
GO

SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON         -- We don't want (NULL = NULL) == TRUE
GO
SET ANSI_PADDING ON
GO
SET ANSI_NULL_DFLT_ON ON
GO

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

IF (EXISTS (SELECT name
              FROM sys.objects
             WHERE (name = N'aspnet_Setup_RemoveAllRoleMembers')
               AND (type = 'P')))
DROP PROCEDURE [dbo].aspnet_Setup_RemoveAllRoleMembers
GO

CREATE PROCEDURE [dbo].aspnet_Setup_RemoveAllRoleMembers
    @name   sysname
AS
BEGIN
    CREATE TABLE #aspnet_RoleMembers
    (
        Group_name      sysname,
        Group_id        smallint,
        Users_in_group  sysname,
        User_id         smallint
    )

    INSERT INTO #aspnet_RoleMembers
    EXEC sp_helpuser @name

    DECLARE @user_id smallint
    DECLARE @cmd nvarchar(500)
    DECLARE c1 cursor FORWARD_ONLY FOR
        SELECT User_id FROM #aspnet_RoleMembers

    OPEN c1

    FETCH c1 INTO @user_id
    WHILE (@@fetch_status = 0)
    BEGIN
        SET @cmd = 'EXEC sp_droprolemember ' + '''' + @name + ''', ''' + USER_NAME(@user_id) + ''''
        EXEC (@cmd)
        FETCH c1 INTO @user_id
    END

    CLOSE c1
    DEALLOCATE c1
END
GO

/*************************************************************/
/*************************************************************/
/*************************************************************/
-- Create the aspnet_Applications table.

IF (NOT EXISTS (SELECT name
                FROM sys.objects
                WHERE (name = N'aspnet_Applications')
                  AND (type = 'U')))
BEGIN
  PRINT 'Creating the aspnet_Applications table...'
  CREATE TABLE [dbo].aspnet_Applications (
    ApplicationName         nvarchar(256)               NOT NULL UNIQUE,
    LoweredApplicationName  nvarchar(256)               NOT NULL UNIQUE,
    ApplicationId           uniqueidentifier            PRIMARY KEY NONCLUSTERED DEFAULT NEWID(),
    Description             nvarchar(256)       )
  CREATE CLUSTERED INDEX aspnet_Applications_Index ON [dbo].aspnet_Applications(LoweredApplicationName)
END
GO

/*************************************************************/
/*************************************************************/
/*************************************************************/
-- Create the aspnet_Users table
IF (NOT EXISTS (SELECT name
                FROM sys.objects
                WHERE (name = N'aspnet_Users')
                  AND (type = 'U')))
BEGIN
  PRINT 'Creating the aspnet_Users table...'
  CREATE TABLE [dbo].aspnet_Users (
    ApplicationId    uniqueidentifier    NOT NULL FOREIGN KEY REFERENCES [dbo].aspnet_Applications(ApplicationId),
    UserId           uniqueidentifier    NOT NULL PRIMARY KEY NONCLUSTERED DEFAULT NEWID(),
    UserName         nvarchar(256)       NOT NULL,
    LoweredUserName  nvarchar(256)	     NOT NULL,
    MobileAlias      nvarchar(16)        DEFAULT NULL,
    IsAnonymous      bit                 NOT NULL DEFAULT 0,
    LastActivityDate DATETIME            NOT NULL)

   CREATE UNIQUE CLUSTERED INDEX aspnet_Users_Index ON [dbo].aspnet_Users(ApplicationId, LoweredUserName)
   CREATE NONCLUSTERED INDEX aspnet_Users_Index2 ON [dbo].aspnet_Users(ApplicationId, LastActivityDate)
END
GO

/*************************************************************/
/*************************************************************/
/*************************************************************/
-- Create the aspnet_SchemaVersions table
IF (NOT EXISTS (SELECT name
                FROM sys.objects
                WHERE (name = N'aspnet_SchemaVersions')
                  AND (type = 'U')))
BEGIN
  PRINT 'Creating the aspnet_SchemaVersions table...'
  CREATE TABLE [dbo].aspnet_SchemaVersions (
    Feature                  nvarchar(128)  NOT NULL PRIMARY KEY CLUSTERED( Feature, CompatibleSchemaVersion ),
    CompatibleSchemaVersion  nvarchar(128)	NOT NULL,
    IsCurrentVersion         bit            NOT NULL )
END
GO

/*************************************************************/
/*************************************************************/
------------- Create Stored Procedures
/*************************************************************/
/*************************************************************/
-- RegisterSchemaVersion SP

IF (NOT EXISTS (SELECT name
                FROM sys.objects
                WHERE (name = N'aspnet_RegisterSchemaVersion')
                AND (type = 'P')))
    EXEC('CREATE PROCEDURE [dbo].aspnet_RegisterSchemaVersion AS RAISERROR(''Empty aspnet_RegisterSchemaVersion Procedure!!'', 16, 1) WITH SETERROR')
GO

ALTER PROCEDURE [dbo].aspnet_RegisterSchemaVersion
    @Feature                   nvarchar(128),
    @CompatibleSchemaVersion   nvarchar(128),
    @IsCurrentVersion          bit,
    @RemoveIncompatibleSchema  bit
AS
BEGIN
    IF( @RemoveIncompatibleSchema = 1 )
    BEGIN
        DELETE FROM dbo.aspnet_SchemaVersions WHERE Feature = LOWER( @Feature )
    END
    ELSE
    BEGIN
        IF( @IsCurrentVersion = 1 )
        BEGIN
            UPDATE dbo.aspnet_SchemaVersions
            SET IsCurrentVersion = 0
            WHERE Feature = LOWER( @Feature )
        END
    END

    INSERT  dbo.aspnet_SchemaVersions( Feature, CompatibleSchemaVersion, IsCurrentVersion )
    VALUES( LOWER( @Feature ), @CompatibleSchemaVersion, @IsCurrentVersion )
END
GO

DECLARE @command nvarchar(4000)

SET @command = 'GRANT EXECUTE ON [dbo].aspnet_RegisterSchemaVersion TO ' + QUOTENAME(user)
EXEC (@command)
GO

-- Create common schema version
EXEC [dbo].aspnet_RegisterSchemaVersion N'Common', N'1', 1, 1
GO

/*************************************************************/
/*************************************************************/
-- CheckSchemaVersion SP

IF (NOT EXISTS (SELECT name
              FROM sys.objects
             WHERE (name = N'aspnet_CheckSchemaVersion')
               AND (type = 'P')))
   EXEC('CREATE PROCEDURE [dbo].aspnet_CheckSchemaVersion AS RAISERROR(''Empty aspnet_CheckSchemaVersion Procedure!!'', 16, 1) WITH SETERROR')
GO

ALTER PROCEDURE [dbo].aspnet_CheckSchemaVersion
    @Feature                   nvarchar(128),
    @CompatibleSchemaVersion   nvarchar(128)
AS
BEGIN
    IF (EXISTS( SELECT  *
                FROM    dbo.aspnet_SchemaVersions
                WHERE   Feature = LOWER( @Feature ) AND
                        CompatibleSchemaVersion = @CompatibleSchemaVersion ))
        RETURN 0

    RETURN 1
END
GO

/*************************************************************/
/*************************************************************/
-- CreateApplication SP

IF (NOT EXISTS (SELECT name
              FROM sys.objects
             WHERE (name = N'aspnet_Applications_CreateApplication')
               AND (type = 'P')))
EXEC('CREATE PROCEDURE [dbo].aspnet_Applications_CreateApplication AS RAISERROR(''Empty aspnet_Applications_CreateApplication Procedure!!'', 16, 1) WITH SETERROR')
GO

ALTER PROCEDURE [dbo].aspnet_Applications_CreateApplication
    @ApplicationName      nvarchar(256),
    @ApplicationId        uniqueidentifier OUTPUT
AS
BEGIN
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName

    IF(@ApplicationId IS NULL)
    BEGIN
        DECLARE @TranStarted   bit
        SET @TranStarted = 0

        IF( @@TRANCOUNT = 0 )
        BEGIN
	        BEGIN TRANSACTION
	        SET @TranStarted = 1
        END
        ELSE
    	    SET @TranStarted = 0

        SELECT  @ApplicationId = ApplicationId
        FROM dbo.aspnet_Applications WITH (UPDLOCK, HOLDLOCK)
        WHERE LOWER(@ApplicationName) = LoweredApplicationName

        IF(@ApplicationId IS NULL)
        BEGIN
            SELECT  @ApplicationId = NEWID()
            INSERT  dbo.aspnet_Applications (ApplicationId, ApplicationName, LoweredApplicationName)
            VALUES  (@ApplicationId, @ApplicationName, LOWER(@ApplicationName))
        END

        IF( @TranStarted = 1 )
        BEGIN
            IF(@@ERROR = 0)
            BEGIN
	        SET @TranStarted = 0
	        COMMIT TRANSACTION
            END
            ELSE
            BEGIN
                SET @TranStarted = 0
                ROLLBACK TRANSACTION
            END
        END
    END
END
GO

/*************************************************************/
/*************************************************************/
-- UnRegisterSchemaVersion SP

IF (NOT EXISTS (SELECT name
              FROM sys.objects
             WHERE (name = N'aspnet_UnRegisterSchemaVersion')
               AND (type = 'P')))
EXEC('CREATE PROCEDURE [dbo].aspnet_UnRegisterSchemaVersion AS RAISERROR(''Empty aspnet_UnRegisterSchemaVersion Procedure!!'', 16, 1) WITH SETERROR')
GO

ALTER PROCEDURE [dbo].aspnet_UnRegisterSchemaVersion
    @Feature                   nvarchar(128),
    @CompatibleSchemaVersion   nvarchar(128)
AS
BEGIN
    DELETE FROM dbo.aspnet_SchemaVersions
        WHERE   Feature = LOWER(@Feature) AND @CompatibleSchemaVersion = CompatibleSchemaVersion
END
GO

/*************************************************************/
/*************************************************************/
-- CreateUser SP

IF (NOT EXISTS (SELECT name
              FROM sys.objects
             WHERE (name = N'aspnet_Users_CreateUser')
               AND (type = 'P')))
EXEC('CREATE PROCEDURE [dbo].aspnet_Users_CreateUser AS RAISERROR(''Empty aspnet_Users_CreateUser Procedure!!'', 16, 1) WITH SETERROR')
GO

ALTER PROCEDURE [dbo].aspnet_Users_CreateUser
    @ApplicationId    uniqueidentifier,
    @UserName         nvarchar(256),
    @IsUserAnonymous  bit,
    @LastActivityDate DATETIME,
    @UserId           uniqueidentifier OUTPUT
AS
BEGIN
    IF( @UserId IS NULL )
        SELECT @UserId = NEWID()
    ELSE
    BEGIN
        IF( EXISTS( SELECT UserId FROM dbo.aspnet_Users
                    WHERE @UserId = UserId ) )
            RETURN -1
    END

    INSERT dbo.aspnet_Users (ApplicationId, UserId, UserName, LoweredUserName, IsAnonymous, LastActivityDate)
    VALUES (@ApplicationId, @UserId, @UserName, LOWER(@UserName), @IsUserAnonymous, @LastActivityDate)

    RETURN 0
END
GO

/*************************************************************/
/*************************************************************/
--- DeleteUser SP

IF (NOT EXISTS (SELECT name
              FROM sys.objects
             WHERE (name = N'aspnet_Users_DeleteUser')
               AND (type = 'P')))
EXEC('CREATE PROCEDURE [dbo].aspnet_Users_DeleteUser AS RAISERROR(''Empty aspnet_Users_DeleteUser Procedure!!'', 16, 1) WITH SETERROR')
GO
ALTER PROCEDURE [dbo].aspnet_Users_DeleteUser
    @ApplicationName  nvarchar(256),
    @UserName         nvarchar(256),
    @TablesToDeleteFrom int,
    @NumTablesDeletedFrom int OUTPUT
AS
BEGIN
    DECLARE @UserId               uniqueidentifier
    SELECT  @UserId               = NULL
    SELECT  @NumTablesDeletedFrom = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
	SET @TranStarted = 0

    DECLARE @ErrorCode   int
    DECLARE @RowCount    int

    SET @ErrorCode = 0
    SET @RowCount  = 0

    SELECT  @UserId = u.UserId
    FROM    dbo.aspnet_Users u, dbo.aspnet_Applications a
    WHERE   u.LoweredUserName       = LOWER(@UserName)
        AND u.ApplicationId         = a.ApplicationId
        AND LOWER(@ApplicationName) = a.LoweredApplicationName

    IF (@UserId IS NULL)
    BEGIN
        GOTO Cleanup
    END

    -- Delete from Membership table if (@TablesToDeleteFrom & 1) is set
    IF ((@TablesToDeleteFrom & 1) <> 0 AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_MembershipUsers') AND (type = 'V'))))
    BEGIN
        DELETE FROM dbo.aspnet_Membership WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
               @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    -- Delete from aspnet_UsersInRoles table if (@TablesToDeleteFrom & 2) is set
    IF ((@TablesToDeleteFrom & 2) <> 0  AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_UsersInRoles') AND (type = 'V'))) )
    BEGIN
        DELETE FROM dbo.aspnet_UsersInRoles WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
                @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    -- Delete from aspnet_Profile table if (@TablesToDeleteFrom & 4) is set
    IF ((@TablesToDeleteFrom & 4) <> 0  AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_Profiles') AND (type = 'V'))) )
    BEGIN
        DELETE FROM dbo.aspnet_Profile WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
                @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    -- Delete from aspnet_PersonalizationPerUser table if (@TablesToDeleteFrom & 8) is set
    IF ((@TablesToDeleteFrom & 8) <> 0  AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_WebPartState_User') AND (type = 'V'))) )
    BEGIN
        DELETE FROM dbo.aspnet_PersonalizationPerUser WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
                @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    -- Delete from aspnet_Users table if (@TablesToDeleteFrom & 1,2,4 & 8) are all set
    IF ((@TablesToDeleteFrom & 1) <> 0 AND
        (@TablesToDeleteFrom & 2) <> 0 AND
        (@TablesToDeleteFrom & 4) <> 0 AND
        (@TablesToDeleteFrom & 8) <> 0 AND
        (EXISTS (SELECT UserId FROM dbo.aspnet_Users WHERE @UserId = UserId)))
    BEGIN
        DELETE FROM dbo.aspnet_Users WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
                @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    IF( @TranStarted = 1 )
    BEGIN
	    SET @TranStarted = 0
	    COMMIT TRANSACTION
    END

    RETURN 0

Cleanup:
    SET @NumTablesDeletedFrom = 0

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
	    ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END
GO

/*************************************************************/
/*************************************************************/
--- aspnet_AnyDataInTables SP

IF (NOT EXISTS (SELECT name
              FROM sys.objects
             WHERE (name = N'aspnet_AnyDataInTables')
               AND (type = 'P')))
EXEC('CREATE PROCEDURE [dbo].aspnet_AnyDataInTables AS RAISERROR(''Empty aspnet_AnyDataInTables Procedure!!'', 16, 1) WITH SETERROR')
GO
ALTER PROCEDURE [dbo].aspnet_AnyDataInTables
    @TablesToCheck int
AS
BEGIN
    -- Check Membership table if (@TablesToCheck & 1) is set
    IF ((@TablesToCheck & 1) <> 0 AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_MembershipUsers') AND (type = 'V'))))
    BEGIN
        IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_Membership))
        BEGIN
            SELECT N'aspnet_Membership'
            RETURN
        END
    END

    -- Check aspnet_Roles table if (@TablesToCheck & 2) is set
    IF ((@TablesToCheck & 2) <> 0  AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_Roles') AND (type = 'V'))) )
    BEGIN
        IF (EXISTS(SELECT TOP 1 RoleId FROM dbo.aspnet_Roles))
        BEGIN
            SELECT N'aspnet_Roles'
            RETURN
        END
    END

    -- Check aspnet_Profile table if (@TablesToCheck & 4) is set
    IF ((@TablesToCheck & 4) <> 0  AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_Profiles') AND (type = 'V'))) )
    BEGIN
        IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_Profile))
        BEGIN
            SELECT N'aspnet_Profile'
            RETURN
        END
    END

    -- Check aspnet_PersonalizationPerUser table if (@TablesToCheck & 8) is set
    IF ((@TablesToCheck & 8) <> 0  AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'vw_aspnet_WebPartState_User') AND (type = 'V'))) )
    BEGIN
        IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_PersonalizationPerUser))
        BEGIN
            SELECT N'aspnet_PersonalizationPerUser'
            RETURN
        END
    END

    -- Check aspnet_PersonalizationPerUser table if (@TablesToCheck & 16) is set
    IF ((@TablesToCheck & 16) <> 0  AND
        (EXISTS (SELECT name FROM sys.objects WHERE (name = N'aspnet_WebEvent_LogEvent') AND (type = 'P'))) )
    BEGIN
        IF (EXISTS(SELECT TOP 1 * FROM dbo.aspnet_WebEvent_Events))
        BEGIN
            SELECT N'aspnet_WebEvent_Events'
            RETURN
        END
    END

    -- Check aspnet_Users table if (@TablesToCheck & 1,2,4 & 8) are all set
    IF ((@TablesToCheck & 1) <> 0 AND
        (@TablesToCheck & 2) <> 0 AND
        (@TablesToCheck & 4) <> 0 AND
        (@TablesToCheck & 8) <> 0 AND
        (@TablesToCheck & 32) <> 0 AND
        (@TablesToCheck & 128) <> 0 AND
        (@TablesToCheck & 256) <> 0 AND
        (@TablesToCheck & 512) <> 0 AND
        (@TablesToCheck & 1024) <> 0)
    BEGIN
        IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_Users))
        BEGIN
            SELECT N'aspnet_Users'
            RETURN
        END
        IF (EXISTS(SELECT TOP 1 ApplicationId FROM dbo.aspnet_Applications))
        BEGIN
            SELECT N'aspnet_Applications'
            RETURN
        END
    END
END
GO

DECLARE @command nvarchar(400)
SET @command = 'GRANT EXECUTE ON [dbo].aspnet_AnyDataInTables TO ' + QUOTENAME(user)
EXEC (@command)
GO

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

IF (NOT EXISTS (SELECT name
                FROM sys.objects
                WHERE (name = N'vw_aspnet_Applications')
                  AND (type = 'V')))
BEGIN
  PRINT 'Creating the vw_aspnet_Applications view...'
  EXEC('
  CREATE VIEW [dbo].[vw_aspnet_Applications]
  AS SELECT [ApplicationName], [LoweredApplicationName], [ApplicationId], [Description]
  FROM [dbo].[aspnet_Applications]
  ')
END

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

IF (NOT EXISTS (SELECT name
                FROM sys.objects
                WHERE (name = N'vw_aspnet_Users')
                  AND (type = 'V')))
BEGIN
  PRINT 'Creating the vw_aspnet_Users view...'
  EXEC('
  CREATE VIEW [dbo].[vw_aspnet_Users]
  AS SELECT [ApplicationId], [UserId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]
  FROM [dbo].[aspnet_Users]
  ')
END

/*************************************************************/
/*************************************************************/
DECLARE @command nvarchar(4000)

SET @command = 'REVOKE EXECUTE ON [dbo].aspnet_RegisterSchemaVersion from ' + QUOTENAME(user)
EXEC (@command)
GO

PRINT '----------------------------------------'
PRINT 'Completed execution of InstallCommon.SQL'
PRINT '----------------------------------------'


text:
const reducer = (state=[]) => {
    return state;
}

export default reducer;


text:
@implementation UAEC2DescribeVPNConnectionsResponse

@synthesize vpnConnections=_vpnConnections;

- (id)init
{
	if (self = [super init])
	{

		[self UA_addAtIndexAdditionalAccessorForSelector:@selector(vpnConnectionAtIndex:) propertyName:@"vpnConnections"];
		[self UA_addAddObjectAdditionalAccessorForSelector:@selector(addVPNConnection:) propertyName:@"vpnConnections"];
	}
	return self;
}

+ (NSString *)XPathPrefix
{
    return @"./ec2:DescribeVpnConnectionsResponse/";
}

+ (NSDictionary *)XMLKeyPathsByPropertyKey
{
    // Start with super's key paths (if there are any)
    NSMutableDictionary *keyPaths = [[UAEC2Response XMLKeyPathsByPropertyKey] mutableCopy];

    [keyPaths addEntriesFromDictionary:
    @{
        @"vpnConnections": @"ec2:vpnConnectionSet/ec2:item"
    }];
    return [keyPaths copy];
}

+ (NSValueTransformer *)vpnConnectionsXMLTransformer
{
  return [NSValueTransformer UAMTL_XMLArrayTransformerWithModelClass:[UAEC2VPNConnection class]];
}

@end

#pragma clang diagnostic pop