text:
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Date/Time parsing library with locale support.
 */

/**
 * Namespace for locale date/time parsing functions
 */
goog.provide('goog.i18n.DateTimeParse');

goog.require('goog.date');
goog.require('goog.i18n.DateTimeFormat');
goog.require('goog.i18n.DateTimeSymbols');

/**
 * DateTimeParse is for parsing date in a locale-sensitive manner. It allows
 * user to use any customized patterns to parse date-time string under certain
 * locale. Things varies across locales like month name, weekname, field
 * order, etc.
 *
 * This module is the counter-part of DateTimeFormat. They use the same
 * date/time pattern specification, which is borrowed from ICU/JDK.
 *
 * This implementation could parse partial date/time.
 *
 * Time Format Syntax: To specify the time format use a time pattern string.
 * In this pattern, following letters are reserved as pattern letters, which
 * are defined as the following:
 *
 *

 * Symbol   Meaning                 Presentation        Example
 * ------   -------                 ------------        -------
 * G        era designator          (Text)              AD
 * y#       year                    (Number)            1996
 * M        month in year           (Text & Number)     July & 07
 * d        day in month            (Number)            10
 * h        hour in am/pm (1~12)    (Number)            12
 * H        hour in day (0~23)      (Number)            0
 * m        minute in hour          (Number)            30
 * s        second in minute        (Number)            55
 * S        fractional second       (Number)            978
 * E        day of week             (Text)              Tuesday
 * D        day in year             (Number)            189
 * a        am/pm marker            (Text)              PM
 * k        hour in day (1~24)      (Number)            24
 * K        hour in am/pm (0~11)    (Number)            0
 * z        time zone               (Text)              Pacific Standard Time
 * Z        time zone (RFC 822)     (Number)            -0800
 * v        time zone (generic)     (Text)              Pacific Time
 * '        escape for text         (Delimiter)         'Date='
 * ''       single quote            (Literal)           'o''clock'
 *

 *
 * The count of pattern letters determine the format.

 * (Text): 4 or more pattern letters--use full form,
 *         less than 4--use short or abbreviated form if one exists.
 *         In parsing, we will always try long format, then short.

 * (Number): the minimum number of digits.

 * (Text & Number): 3 or over, use text, otherwise use number.

 * Any characters that not in the pattern will be treated as quoted text. For
 * instance, characters like ':', '.', ' ', '#' and '@' will appear in the
 * resulting time text even they are not embraced within single quotes. In our
 * current pattern usage, we didn't use up all letters. But those unused
 * letters are strongly discouraged to be used as quoted text without quote.
 * That's because we may use other letter for pattern in future.

 *
 * Examples Using the US Locale:
 *
 * Format Pattern                         Result
 * --------------                         -------
 * "yyyy.MM.dd G 'at' HH:mm:ss vvvv" ->>  1996.07.10 AD at 15:08:56 Pacific Time
 * "EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
 * "h:mm a"                          ->>  12:08 PM
 * "hh 'o''clock' a, zzzz"           ->>  12 o'clock PM, Pacific Daylight Time
 * "K:mm a, vvv"                     ->>  0:00 PM, PT
 * "yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  01996.July.10 AD 12:08 PM
 *
 *
 When parsing a date string using the abbreviated year pattern ("yy"),
 * DateTimeParse must interpret the abbreviated year relative to some
 * century. It does this by adjusting dates to be within 80 years before and 20
 * years after the time the parse function is called. For example, using a
 * pattern of "MM/dd/yy" and a DateTimeParse instance created on Jan 1, 1997,
 * the string "01/11/12" would be interpreted as Jan 11, 2012 while the string
 * "05/04/64" would be interpreted as May 4, 1964. During parsing, only
 * strings consisting of exactly two digits, as defined by {@link
 * java.lang.Character#isDigit(char)}, will be parsed into the default
 * century. Any other numeric string, such as a one digit string, a three or
 * more digit string will be interpreted as its face value.
 *
 *
 If the year pattern does not have exactly two 'y' characters, the year is
 * interpreted literally, regardless of the number of digits. So using the
 * pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
 *
 *
 When numeric fields abut one another directly, with no intervening
 * delimiter characters, they constitute a run of abutting numeric fields. Such
 * runs are parsed specially. For example, the format "HHmmss" parses the input
 * text "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and
 * fails to parse "1234". In other words, the leftmost field of the run is
 * flexible, while the others keep a fixed width. If the parse fails anywhere in
 * the run, then the leftmost field is shortened by one character, and the
 * entire run is parsed again. This is repeated until either the parse succeeds
 * or the leftmost field is one character in length. If the parse still fails at
 * that point, the parse of the run fails.
 *
 *
 Now timezone parsing only support GMT:hhmm, GMT:+hhmm, GMT:-hhmm
 */

/**
 * Construct a DateTimeParse based on current locale.
 * @param {string|number} pattern pattern specification or pattern type.
 * @constructor
 */
goog.i18n.DateTimeParse = function(pattern) {
  this.patternParts_ = [];
  if (typeof pattern == 'number') {
    this.applyStandardPattern_(pattern);
  } else {
    this.applyPattern_(pattern);
  }
};

/**
 * Number of years prior to now that the century used to
 * disambiguate two digit years will begin
 *
 * @type {number}
 */
goog.i18n.DateTimeParse.ambiguousYearCenturyStart = 80;

/**
 * Apply a pattern to this Parser. The pattern string will be parsed and saved
 * in "compiled" form.
 * Note: this method is somewhat similar to the pattern parsing method in
 *       datetimeformat. If you see something wrong here, you might want
 *       to check the other.
 * @param {string} pattern It describes the format of date string that need to
 *     be parsed.
 * @private
 */
goog.i18n.DateTimeParse.prototype.applyPattern_ = function(pattern) {
  var inQuote = false;
  var buf = '';

  for (var i = 0; i < pattern.length; i++) {
    var ch = pattern.charAt(i);

    // handle space, add literal part (if exist), and add space part
    if (ch == ' ') {
      if (buf.length > 0) {
        this.patternParts_.push({text: buf, count: 0, abutStart: false});
        buf = '';
      }
      this.patternParts_.push({text: ' ', count: 0, abutStart: false});
      while (i < pattern.length - 1 && pattern.charAt(i + 1) == ' ') {
        i++;
      }
    } else if (inQuote) {
      // inside quote, except '', just copy or exit
      if (ch == '\'') {
        if (i + 1 < pattern.length && pattern.charAt(i + 1) == '\'') {
          // quote appeared twice continuously, interpret as one quote.
          buf += '\'';
          i++;
        } else {
          // exit quote
          inQuote = false;
        }
      } else {
        // literal
        buf += ch;
      }
    } else if (goog.i18n.DateTimeParse.PATTERN_CHARS_.indexOf(ch) >= 0) {
      // outside quote, it is a pattern char
      if (buf.length > 0) {
        this.patternParts_.push({text: buf, count: 0, abutStart: false});
        buf = '';
      }
      var count = this.getNextCharCount_(pattern, i);
      this.patternParts_.push({text: ch, count: count, abutStart: false});
      i += count - 1;
    } else if (ch == '\'') {
      // Two consecutive quotes is a quote literal, inside or outside of quotes.
      if (i + 1 < pattern.length && pattern.charAt(i + 1) == '\'') {
        buf += '\'';
        i++;
      } else {
        inQuote = true;
      }
    } else {
      buf += ch;
    }
  }

  if (buf.length > 0) {
    this.patternParts_.push({text: buf, count: 0, abutStart: false});
  }

  this.markAbutStart_();
};

/**
 * Apply a predefined pattern to this Parser.
 * @param {number} formatType A constant used to identified the predefined
 *     pattern string stored in locale repository.
 * @private
 */
goog.i18n.DateTimeParse.prototype.applyStandardPattern_ = function(formatType) {
  var pattern;
  // formatType constants are in consecutive numbers. So it can be used to
  // index array in following way.

  // if type is out of range, default to medium date/time format.
  if (formatType > goog.i18n.DateTimeFormat.Format.SHORT_DATETIME) {
    formatType = goog.i18n.DateTimeFormat.Format.MEDIUM_DATETIME;
  }

  if (formatType < 4) {
    pattern = goog.i18n.DateTimeSymbols.DATEFORMATS[formatType];
  } else if (formatType < 8) {
    pattern = goog.i18n.DateTimeSymbols.TIMEFORMATS[formatType - 4];
  } else {
    pattern = goog.i18n.DateTimeSymbols.DATETIMEFORMATS[formatType - 8];
    pattern = pattern.replace('{1}',
        goog.i18n.DateTimeSymbols.DATEFORMATS[formatType - 8]);
    pattern = pattern.replace('{0}',
        goog.i18n.DateTimeSymbols.TIMEFORMATS[formatType - 8]);
  }
  this.applyPattern_(pattern);
};

/**
 * Parse the given string and fill info into date object. This version does
 * not validate the input.
 * @param {string} text The string being parsed.
 * @param {goog.date.DateLike} date The Date object to hold the parsed date.
 * @param {number=} opt_start The position from where parse should begin.
 * @return {number} How many characters parser advanced.
 */
goog.i18n.DateTimeParse.prototype.parse = function(text, date, opt_start) {
  var start = opt_start || 0;
  return this.internalParse_(text, date, start, false/*validation*/);
};

/**
 * Parse the given string and fill info into date object. This version will
 * validate the input and make sure it is a validate date/time.
 * @param {string} text The string being parsed.
 * @param {goog.date.DateLike} date The Date object to hold the parsed date.
 * @param {number=} opt_start The position from where parse should begin.
 * @return {number} How many characters parser advanced.
 */
goog.i18n.DateTimeParse.prototype.strictParse =
    function(text, date, opt_start) {
  var start = opt_start || 0;
  return this.internalParse_(text, date, start, true/*validation*/);
};

/**
 * Parse the given string and fill info into date object.
 * @param {string} text The string being parsed.
 * @param {goog.date.DateLike} date The Date object to hold the parsed date.
 * @param {number} start The position from where parse should begin.
 * @param {boolean} validation If true, input string need to be a valid
 *     date/time string.
 * @return {number} How many characters parser advanced.
 * @private
 */
goog.i18n.DateTimeParse.prototype.internalParse_ =
    function(text, date, start, validation) {
  var cal = new goog.i18n.DateTimeParse.MyDate_();
  var parsePos = [start];

  // For parsing abutting numeric fields. 'abutPat' is the
  // offset into 'pattern' of the first of 2 or more abutting
  // numeric fields. 'abutStart' is the offset into 'text'
  // where parsing the fields begins. 'abutPass' starts off as 0
  // and increments each time we try to parse the fields.
  var abutPat = -1; // If >=0, we are in a run of abutting numeric fields
  var abutStart = 0;
  var abutPass = 0;

  for (var i = 0; i < this.patternParts_.length; i++) {
    if (this.patternParts_[i].count > 0) {
      if (abutPat < 0 && this.patternParts_[i].abutStart) {
        abutPat = i;
        abutStart = start;
        abutPass = 0;
      }

      // Handle fields within a run of abutting numeric fields. Take
      // the pattern "HHmmss" as an example. We will try to parse
      // 2/2/2 characters of the input text, then if that fails,
      // 1/2/2. We only adjust the width of the leftmost field; the
      // others remain fixed. This allows "123456" => 12:34:56, but
      // "12345" => 1:23:45. Likewise, for the pattern "yyyyMMdd" we
      // try 4/2/2, 3/2/2, 2/2/2, and finally 1/2/2.
      if (abutPat >= 0) {
        // If we are at the start of a run of abutting fields, then
        // shorten this field in each pass. If we can't shorten
        // this field any more, then the parse of this set of
        // abutting numeric fields has failed.
        var count = this.patternParts_[i].count;
        if (i == abutPat) {
          count -= abutPass;
          abutPass++;
          if (count == 0) {
            // tried all possible width, fail now
            return 0;
          }
        }

        if (!this.subParse_(text, parsePos, this.patternParts_[i], count,
                            cal)) {
          // If the parse fails anywhere in the run, back up to the
          // start of the run and retry.
          i = abutPat - 1;
          parsePos[0] = abutStart;
          continue;
        }
      }

      // Handle non-numeric fields and non-abutting numeric fields.
      else {
        abutPat = -1;
        if (!this.subParse_(text, parsePos, this.patternParts_[i], 0, cal)) {
          return 0;
        }
      }
    } else {
      // Handle literal pattern characters. These are any
      // quoted characters and non-alphabetic unquoted
      // characters.
      abutPat = -1;
      // A run of white space in the pattern matches a run
      // of white space in the input text.
      if (this.patternParts_[i].text.charAt(0) == ' ') {
        // Advance over run in input text
        var s = parsePos[0];
        this.skipSpace_(text, parsePos);

        // Must see at least one white space char in input
        if (parsePos[0] > s) {
          continue;
        }
      } else if (text.indexOf(this.patternParts_[i].text, parsePos[0]) ==
                 parsePos[0]) {
        parsePos[0] += this.patternParts_[i].text.length;
        continue;
      }
      // We fall through to this point if the match fails
      return 0;
    }
  }

  // return progress
  return cal.calcDate_(date, validation) ? parsePos[0] - start : 0;
};

/**
 * Calculate character repeat count in pattern.
 *
 * @param {string} pattern It describes the format of date string that need to
 *     be parsed.
 * @param {number} start The position of pattern character.
 *
 * @return {number} Repeat count.
 * @private
 */
goog.i18n.DateTimeParse.prototype.getNextCharCount_ =
    function(pattern, start) {
  var ch = pattern.charAt(start);
  var next = start + 1;
  while (next < pattern.length && pattern.charAt(next) == ch) {
    next++;
  }
  return next - start;
};

/**
 * All acceptable pattern characters.
 * @private
 */
goog.i18n.DateTimeParse.PATTERN_CHARS_ = 'GyMdkHmsSEDahKzZvQL';

/**
 * Pattern characters that specify numerical field.
 * @private
 */
goog.i18n.DateTimeParse.NUMERIC_FORMAT_CHARS_ = 'MydhHmsSDkK';

/**
 * Check if the pattern part is a numeric field.
 *
 * @param {Object} part pattern part to be examined.
 *
 * @return {boolean} true if the pattern part is numeric field.
 * @private
 */
goog.i18n.DateTimeParse.prototype.isNumericField_ = function(part) {
  if (part.count <= 0) {
    return false;
  }
  var i = goog.i18n.DateTimeParse.NUMERIC_FORMAT_CHARS_.indexOf(
      part.text.charAt(0));
  return i > 0 || i == 0 && part.count < 3;
};

/**
 * Identify the start of an abutting numeric fields' run. Taking pattern
 * "HHmmss" as an example. It will try to parse 2/2/2 characters of the input
 * text, then if that fails, 1/2/2. We only adjust the width of the leftmost
 * field; the others remain fixed. This allows "123456" => 12:34:56, but
 * "12345" => 1:23:45. Likewise, for the pattern "yyyyMMdd" we try 4/2/2,
 * 3/2/2, 2/2/2, and finally 1/2/2. The first field of connected numeric
 * fields will be marked as abutStart, its width can be reduced to accommodate
 * others.
 *
 * @private
 */
goog.i18n.DateTimeParse.prototype.markAbutStart_ = function() {
  // abut parts are continuous numeric parts. abutStart is the switch
  // point from non-abut to abut
  var abut = false;

  for (var i = 0; i < this.patternParts_.length; i++) {
    if (this.isNumericField_(this.patternParts_[i])) {
      // if next part is not following abut sequence, and isNumericField_
      if (!abut && i + 1 < this.patternParts_.length &&
          this.isNumericField_(this.patternParts_[i + 1])) {
        abut = true;
        this.patternParts_[i].abutStart = true;
      }
    } else {
      abut = false;
    }
  }
};

/**
 * Skip space in the string.
 *
 * @param {string} text input string.
 * @param {Array.<number>} pos where skip start, and return back where the skip
 *     stops.
 * @private
 */
goog.i18n.DateTimeParse.prototype.skipSpace_ = function(text, pos) {
  var m = text.substring(pos[0]).match(/^\s+/);
  if (m) {
    pos[0] += m[0].length;
  }
};

/**
 * Protected method that converts one field of the input string into a
 * numeric field value.
 *
 * @param {string} text the time text to be parsed.
 * @param {Array.<number>} pos Parse position.
 * @param {Object} part the pattern part for this field.
 * @param {number} digitCount when > 0, numeric parsing must obey the count.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object that holds parsed value.
 *
 * @return {boolean} True if it parses successfully.
 * @private
 */
goog.i18n.DateTimeParse.prototype.subParse_ =
    function(text, pos, part, digitCount, cal) {
  this.skipSpace_(text, pos);

  var start = pos[0];
  var ch = part.text.charAt(0);

  // parse integer value if it is a numeric field
  var value = -1;
  if (this.isNumericField_(part)) {
    if (digitCount > 0) {
      if ((start + digitCount) > text.length) {
        return false;
      }
      value = this.parseInt_(
          text.substring(0, start + digitCount), pos);
    } else {
      value = this.parseInt_(text, pos);
    }
  }

  switch (ch) {
    case 'G': // ERA
      cal.era = this.matchString_(text, pos, goog.i18n.DateTimeSymbols.ERAS);
      return true;
    case 'M': // MONTH
    case 'L': // STANDALONEMONTH
      return this.subParseMonth_(text, pos, cal, value);
    case 'E':
      return this.subParseDayOfWeek_(text, pos, cal);
    case 'a': // AM_PM
      cal.ampm = this.matchString_(text, pos, goog.i18n.DateTimeSymbols.AMPMS);
      return true;
    case 'y': // YEAR
      return this.subParseYear_(text, pos, start, value, part, cal);
    case 'Q': // QUARTER
      return this.subParseQuarter_(text, pos, cal, value);
    case 'd': // DATE
      cal.day = value;
      return true;
    case 'S': // FRACTIONAL_SECOND
      return this.subParseFractionalSeconds_(value, pos, start, cal);
    case 'h': // HOUR (1..12)
      if (value == 12) {
        value = 0;
      }
    case 'K': // HOUR (0..11)
    case 'H': // HOUR_OF_DAY (0..23)
    case 'k': // HOUR_OF_DAY (1..24)
      cal.hours = value;
      return true;
    case 'm': // MINUTE
      cal.minutes = value;
      return true;
    case 's': // SECOND
      cal.seconds = value;
      return true;

    case 'z': // ZONE_OFFSET
    case 'Z': // TIMEZONE_RFC
    case 'v': // TIMEZONE_GENERIC
      return this.subparseTimeZoneInGMT_(text, pos, cal);
    default:
      return false;
  }
};

/**
 * Parse year field. Year field is special because
 * 1) two digit year need to be resolved.
 * 2) we allow year to take a sign.
 * 3) year field participate in abut processing.
 *
 * @param {string} text the time text to be parsed.
 * @param {Array.<number>} pos Parse position.
 * @param {number} start where this field start.
 * @param {number} value integer value of year.
 * @param {Object} part the pattern part for this field.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object to hold parsed value.
 *
 * @return {boolean} True if successful.
 * @private
 */
goog.i18n.DateTimeParse.prototype.subParseYear_ =
    function(text, pos, start, value, part, cal) {
  var ch;
  if (value < 0) {
    //possible sign
    ch = text.charAt(pos[0]);
    if (ch != '+' && ch != '-') {
      return false;
    }
    pos[0]++;
    value = this.parseInt_(text, pos);
    if (value < 0) {
      return false;
    }
    if (ch == '-') {
      value = -value;
    }
  }

  // only if 2 digit was actually parsed, and pattern say it has 2 digit.
  if (!ch && pos[0] - start == 2 && part.count == 2) {
    cal.setTwoDigitYear_(value);
  } else {
    cal.year = value;
  }
  return true;
};

/**
 * Parse Month field.
 *
 * @param {string} text the time text to be parsed.
 * @param {Array.<number>} pos Parse position.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object to hold parsed value.
 * @param {number} value numeric value if this field is expressed using
 *      numeric pattern, or -1 if not.
 *
 * @return {boolean} True if parsing successful.
 * @private
 */
goog.i18n.DateTimeParse.prototype.subParseMonth_ =
    function(text, pos, cal, value) {
  // when month is symbols, i.e., MMM, MMMM, LLL or LLLL, value will be -1
  if (value < 0) {
    // Want to be able to parse both short and long forms.
    // Try count == 4 first
    var months = goog.i18n.DateTimeSymbols.MONTHS.concat(
        goog.i18n.DateTimeSymbols.STANDALONEMONTHS).concat(
        goog.i18n.DateTimeSymbols.SHORTMONTHS).concat(
        goog.i18n.DateTimeSymbols.STANDALONESHORTMONTHS);
    value = this.matchString_(text, pos, months);
    if (value < 0) {
      return false;
    }
    // The months variable is multiple of 12, so we have to get the actual
    // month index by modulo 12.
    cal.month = (value % 12);
    return true;
  } else {
    cal.month = value - 1;
    return true;
  }
};

/**
 * Parse Quarter field.
 *
 * @param {string} text the time text to be parsed.
 * @param {Array.<number>} pos Parse position.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object to hold parsed value.
 * @param {number} value numeric value if this field is expressed using
 *      numeric pattern, or -1 if not.
 *
 * @return {boolean} True if parsing successful.
 * @private
 */
goog.i18n.DateTimeParse.prototype.subParseQuarter_ =
    function(text, pos, cal, value) {
  // value should be -1, since this is a non-numeric field.
  if (value < 0) {
    // Want to be able to parse both short and long forms.
    // Try count == 4 first:
    value = this.matchString_(text, pos, goog.i18n.DateTimeSymbols.QUARTERS);
    if (value < 0) { // count == 4 failed, now try count == 3
      value = this.matchString_(text, pos,
                                goog.i18n.DateTimeSymbols.SHORTQUARTERS);
    }
    if (value < 0) {
      return false;
    }
    cal.month = value * 3;  // First month of quarter.
    cal.day = 1;
    return true;
  }
  return false;
};

/**
 * Parse Day of week field.
 * @param {string} text the time text to be parsed.
 * @param {Array.<number>} pos Parse position.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object to hold parsed value.
 *
 * @return {boolean} True if successful.
 * @private
 */
goog.i18n.DateTimeParse.prototype.subParseDayOfWeek_ =
    function(text, pos, cal) {
  // Handle both short and long forms.
  // Try count == 4 (DDDD) first:
  var value = this.matchString_(text, pos, goog.i18n.DateTimeSymbols.WEEKDAYS);
  if (value < 0) {
    value = this.matchString_(text, pos,
                              goog.i18n.DateTimeSymbols.SHORTWEEKDAYS);
  }
  if (value < 0) {
    return false;
  }
  cal.dayOfWeek = value;
  return true;
};

/**
 * Parse fractional seconds field.
 *
 * @param {number} value parsed numeric value.
 * @param {Array.<number>} pos current parse position.
 * @param {number} start where this field start.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object to hold parsed value.
 *
 * @return {boolean} True if successful.
 * @private
 */
goog.i18n.DateTimeParse.prototype.subParseFractionalSeconds_ =
    function(value, pos, start, cal) {
  // Fractional seconds left-justify
  var len = pos[0] - start;
  cal.milliseconds = len < 3 ? value * Math.pow(10, 3 - len) :
                               Math.round(value / Math.pow(10, len - 3));
  return true;
};

/**
 * Parse GMT type timezone.
 *
 * @param {string} text the time text to be parsed.
 * @param {Array.<number>} pos Parse position.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object to hold parsed value.
 *
 * @return {boolean} True if successful.
 * @private
 */
goog.i18n.DateTimeParse.prototype.subparseTimeZoneInGMT_ =
    function(text, pos, cal) {
  // First try to parse generic forms such as GMT-07:00. Do this first
  // in case localized DateFormatZoneData contains the string "GMT"
  // for a zone; in that case, we don't want to match the first three
  // characters of GMT+/-HH:MM etc.

  // For time zones that have no known names, look for strings
  // of the form:
  //    GMT[+-]hours:minutes or
  //    GMT[+-]hhmm or
  //    GMT.
  if (text.indexOf('GMT', pos[0]) == pos[0]) {
    pos[0] += 3;  // 3 is the length of GMT
    return this.parseTimeZoneOffset_(text, pos, cal);
  }

  // TODO(user): check for named time zones by looking through the locale
  // data from the DateFormatZoneData strings. Should parse both short and long
  // forms.
  // subParseZoneString(text, start, cal);

  // As a last resort, look for numeric timezones of the form
  // [+-]hhmm as specified by RFC 822.  This code is actually
  // a little more permissive than RFC 822.  It will try to do
  // its best with numbers that aren't strictly 4 digits long.
  return this.parseTimeZoneOffset_(text, pos, cal);
};

/**
 * Parse time zone offset.
 *
 * @param {string} text the time text to be parsed.
 * @param {Array.<number>} pos Parse position.
 * @param {goog.i18n.DateTimeParse.MyDate_} cal object to hold parsed value.
 *
 * @return {boolean} True if successful.
 * @private
 */
goog.i18n.DateTimeParse.prototype.parseTimeZoneOffset_ =
    function(text, pos, cal) {
  if (pos[0] >= text.length) {
    cal.tzOffset = 0;
    return true;
  }

  var sign = 1;
  switch (text.charAt(pos[0])) {
    case '-': sign = -1;  // fall through
    case '+': pos[0]++;
  }

  // Look for hours:minutes or hhmm.
  var st = pos[0];
  var value = this.parseInt_(text, pos);
  if (value == 0 && pos[0] == st) {
    return false;
  }

  var offset;
  if (pos[0] < text.length && text.charAt(pos[0]) == ':') {
    // This is the hours:minutes case
    offset = value * 60;
    pos[0]++;
    st = pos[0];
    value = this.parseInt_(text, pos);
    if (value == 0 && pos[0] == st) {
      return false;
    }
    offset += value;
  } else {
    // This is the hhmm case.
    offset = value;
    // Assume "-23".."+23" refers to hours.
    if (offset < 24 && (pos[0] - st) <= 2) {
      offset *= 60;
    } else {
      // todo: this looks questionable, should have more error checking
      offset = offset % 100 + offset / 100 * 60;
    }
  }

  offset *= sign;
  cal.tzOffset = -offset;
  return true;
};

/**
 * Parse a integer string and return integer value.
 *
 * @param {string} text string being parsed.
 * @param {Array.<number>} pos parse position.
 *
 * @return {number} Converted integer value.
 * @private
 */
goog.i18n.DateTimeParse.prototype.parseInt_ = function(text, pos) {
  // Delocalizes the string containing native digits specified by the locale,
  // replaces the native digits with ASCII digits. Leaves other characters.
  // This is the reverse operation of localizeNumbers_ in datetimeformat.js.
  if (goog.i18n.DateTimeSymbols.ZERODIGIT) {
    var parts = [];
    for (var i = pos[0]; i < text.length; i++) {
      var c = text.charCodeAt(i) - goog.i18n.DateTimeSymbols.ZERODIGIT;
      parts.push((0 <= c && c <= 9) ?
          String.fromCharCode(c + 0x30) :
          text.charAt(i));
    }
    text = parts.join('');
  } else {
    text = text.substring(pos[0]);
  }

  var m = text.match(/^\d+/);
  if (!m) {
    return -1;
  }
  pos[0] += m[0].length;
  return parseInt(m[0], 10);
};

/**
 * Attempt to match the text at a given position against an array of strings.
 * Since multiple strings in the array may match (for example, if the array
 * contains "a", "ab", and "abc", all will match the input string "abcd") the
 * longest match is returned.
 *
 * @param {string} text The string to match to.
 * @param {Array.<number>} pos parsing position.
 * @param {Array.<string>} data The string array of matching patterns.
 *
 * @return {number} the new start position if matching succeeded; a negative
 *     number indicating matching failure.
 * @private
 */
goog.i18n.DateTimeParse.prototype.matchString_ = function(text, pos, data) {
  // There may be multiple strings in the data[] array which begin with
  // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
  // We keep track of the longest match, and return that. Note that this
  // unfortunately requires us to test all array elements.
  var bestMatchLength = 0;
  var bestMatch = -1;
  var lower_text = text.substring(pos[0]).toLowerCase();
  for (var i = 0; i < data.length; i++) {
    var len = data[i].length;
    // Always compare if we have no match yet; otherwise only compare
    // against potentially better matches (longer strings).
    if (len > bestMatchLength &&
        lower_text.indexOf(data[i].toLowerCase()) == 0) {
      bestMatch = i;
      bestMatchLength = len;
    }
  }
  if (bestMatch >= 0) {
    pos[0] += bestMatchLength;
  }
  return bestMatch;
};

/**
 * This class hold the intermediate parsing result. After all fields are
 * consumed, final result will be resolved from this class.
 * @constructor
 * @private
 */
goog.i18n.DateTimeParse.MyDate_ = function() {};

/**
 * The date's era.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.era;

/**
 * The date's year.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.year;

/**
 * The date's month.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.month;

/**
 * The date's day of month.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.day;

/**
 * The date's hour.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.hours;

/**
 * The date's before/afternoon denominator.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.ampm;

/**
 * The date's minutes.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.minutes;

/**
 * The date's seconds.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.seconds;

/**
 * The date's milliseconds.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.milliseconds;

/**
 * The date's timezone offset.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.tzOffset;

/**
 * The date's day of week. Sunday is 0, Saturday is 6.
 * @type {?number}
 */
goog.i18n.DateTimeParse.MyDate_.prototype.dayOfWeek;

/**
 * 2 digit year special handling. Assuming for example that the
 * defaultCenturyStart is 6/18/1903. This means that two-digit years will be
 * forced into the range 6/18/1903 to 6/17/2003. As a result, years 00, 01, and
 * 02 correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
 * to 1904, 1905, etc. If the year is 03, then it is 2003 if the
 * other fields specify a date before 6/18, or 1903 if they specify a
 * date afterwards. As a result, 03 is an ambiguous year. All other
 * two-digit years are unambiguous.
 *
 * @param {number} year 2 digit year value before adjustment.
 * @return {number} disambiguated year.
 * @private
 */
goog.i18n.DateTimeParse.MyDate_.prototype.setTwoDigitYear_ = function(year) {
  var now = new Date();
  var defaultCenturyStartYear =
      now.getFullYear() - goog.i18n.DateTimeParse.ambiguousYearCenturyStart;
  var ambiguousTwoDigitYear = defaultCenturyStartYear % 100;
  this.ambiguousYear = (year == ambiguousTwoDigitYear);
  year += Math.floor(defaultCenturyStartYear / 100) * 100 +
      (year < ambiguousTwoDigitYear ? 100 : 0);
  return this.year = year;
};

/**
 * Based on the fields set, fill a Date object. For those fields that not
 * set, use the passed in date object's value.
 *
 * @param {goog.date.DateLike} date Date object to be filled.
 * @param {boolean} validation If true, input string will be checked to make
 *     sure it is valid.
 *
 * @return {boolean} false if fields specify a invalid date.
 * @private
 */
goog.i18n.DateTimeParse.MyDate_.prototype.calcDate_ =
    function(date, validation) {
  // year 0 is 1 BC, and so on.
  if (this.era != undefined && this.year != undefined &&
      this.era == 0 && this.year > 0) {
    this.year = -(this.year - 1);
  }

  if (this.year != undefined) {
    date.setFullYear(this.year);
  }

  // The setMonth and setDate logic is a little tricky. We need to make sure
  // day of month is smaller enough so that it won't cause a month switch when
  // setting month. For example, if data in date is Nov 30, when month is set
  // to Feb, because there is no Feb 30, JS adjust it to Mar 2. So Feb 12 will
  // become  Mar 12.
  var orgDate = date.getDate();

  // Every month has a 1st day, this can actually be anything less than 29.
  date.setDate(1);

  if (this.month != undefined) {
    date.setMonth(this.month);
  }

  if (this.day != undefined) {
    date.setDate(this.day);
  } else {
    var maxDate =
        goog.date.getNumberOfDaysInMonth(date.getFullYear(), date.getMonth());
    date.setDate(orgDate > maxDate ? maxDate : orgDate);
  }

  if (goog.isFunction(date.setHours)) {
    if (this.hours == undefined) {
      this.hours = date.getHours();
    }
    // adjust ampm
    if (this.ampm != undefined && this.ampm > 0 && this.hours < 12) {
      this.hours += 12;
    }
    date.setHours(this.hours);
  }

  if (goog.isFunction(date.setMinutes) && this.minutes != undefined) {
    date.setMinutes(this.minutes);
  }

  if (goog.isFunction(date.setSeconds) && this.seconds != undefined) {
    date.setSeconds(this.seconds);
  }

  if (goog.isFunction(date.setMilliseconds) &&
      this.milliseconds != undefined) {
    date.setMilliseconds(this.milliseconds);
  }

  // If validation is needed, verify that the uncalculated date fields
  // match the calculated date fields.  We do this before we set the
  // timezone offset, which will skew all of the dates.
  //
  // Don't need to check the day of week as it is guaranteed to be
  // correct or return false below.
  if (validation &&
      (this.year != undefined && this.year != date.getFullYear() ||
       this.month != undefined && this.month != date.getMonth() ||
       this.day != undefined && this.day != date.getDate() ||
       this.hours >= 24 || this.minutes >= 60 || this.seconds >= 60 ||
       this.milliseconds >= 1000)) {
    return false;
  }

  // adjust time zone
  if (this.tzOffset != undefined) {
    var offset = date.getTimezoneOffset();
    date.setTime(date.getTime() + (this.tzOffset - offset) * 60 * 1000);
  }

  // resolve ambiguous year if needed
  if (this.ambiguousYear) { // the two-digit year == the default start year
    var defaultCenturyStart = new Date();
    defaultCenturyStart.setFullYear(
        defaultCenturyStart.getFullYear() -
        goog.i18n.DateTimeParse.ambiguousYearCenturyStart);
    if (date.getTime() < defaultCenturyStart.getTime()) {
      date.setFullYear(defaultCenturyStart.getFullYear() + 100);
    }
  }

  // dayOfWeek, validation only
  if (this.dayOfWeek != undefined) {
    if (this.day == undefined) {
      // adjust to the nearest day of the week
      var adjustment = (7 + this.dayOfWeek - date.getDay()) % 7;
      if (adjustment > 3) {
        adjustment -= 7;
      }
      var orgMonth = date.getMonth();
      date.setDate(date.getDate() + adjustment);

      // don't let it switch month
      if (date.getMonth() != orgMonth) {
        date.setDate(date.getDate() + (adjustment > 0 ? -7 : 7));
      }
    } else if (this.dayOfWeek != date.getDay()) {
      return false;
    }
  }
  return true;
};


text:
{% extends "../layout.html" %}

{% block page_title %}
  Find a career
{% endblock %}

{% block content %}

{% set serviceName = 'Find a career' %}
{% set bannerStyle = 'BETA-style' %}
{% set filterName = 'Salary' %}

{% include "../includes/survey.html" %}

    {% include "../includes/global_header_bar.html" %}

    {% include "../includes/breadcrumb_filters.html" %}

{{filterName}}

Starter salary

Step 3 of 5

Low

Average

High

Experienced salary
(Typically 5+ years)

Low

Average

High

Money is not my main motivation

Continue

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
module Minotaur
  def self.expand_ast(typed_data)
    Expander.new(**typed_data).expand
  end

  class Expander
    def initialize(ast:, functions:, instances:, types:)
      @ast = ast
      @functions = functions
      @instances = instances
      @types = types
      @expanded_types = []
      @expanded_functions = []
      @includes = []
      prepare
    end

    def expand
      expand_types
      expand_functions
      n(:module,
        includes: @includes,
        types: @expanded_types,
        functions: @expanded_functions)
    end

    def expand_types
      @type_nodes.each do |node|
        if node.c_type.generic?
          g = node.c_type.type_args.select { |arg| arg.generic? }.map {
            g.pointer? ? g.base : g }
          ig = comb(g.map { |arg| @instances[arg.base.label] })
          ig.each do |j|
            new_node = node.dup
            new_node.c_type = GenericInstanceType.new(node.c_type,
              node.c_type.type_args.map { |arg| clean_generic(arg, j) })
            new_node.fields.each do |f|
              f.c_type = clean_generic(f.c_type, generic_map)
            end
            @expanded_types << new_node
          end
        else
          @expanded_types << node
        end
      end
    end

    def expand_functions

      @function_nodes.each do |node|
        if node.c_type.generic?
          g = node.c_type.type_args.select { |arg| arg.generic? }.map {
            g.pointer? ? g.base : g }
          ig = comb(g.map { |arg| @instances[arg.base.label] })
          ig.each do |j|
            new_node = node.dup
            new_node.args.each { |arg| arg.c_type = clean_generic(arg.c_type, j) }
            new_node.return_type = clean_generic(node.return_type, j)
            new_node.body.each { |child| clean_node_generic(child, j) }
            @expanded_functions << new_node
          end
        else
          @expanded_functions << node
        end
      end
    end

    def prepare
      @include_nodes, @type_nodes, @function_nodes, main = [], [], [], []
      @ast.children.each do |child|
        if [:include, :include_file].include?(child.kind)
          @include_nodes << child
        elsif [:struct, :enum, :variant].include?(child.kind)
          @type_nodes << child
        elsif [:function].include?(child.kind)
          @function_nodes << child
        else
          main << child
        end
      end
      @function_nodes << n(:function, c_type: GenericInstanceType.new(
                           Builtin::Function, [Builtin::Size, Builtin::CharPtr]), label: :main, args:
                      [n(:arg, c_type: Builtin::Size, label: :argc),
                       n(:arg, c_type: Builtin::CharPtr, label: :argv)],
                     return_type: Builtin::Int,
                     body: main)
    end

    def n(kind, **kwargs)
      Minotaur::n(kind, **kwargs)
    end

  end
end


text:
import subprocess
import boto3
import sys
import configparser
from codecs import open
from os.path import expanduser
import os
import glob
import inquirer
import argparse
import libtmux
import time

class Connector:
  def __init__(self, connection_name, profile):

    self.hosts_folder = expanduser("~")
    print(self.hosts_folder)
    self.profile = profile
    self.directory_to_save = self.hosts_folder+'/.ec2ssh/hosts/'
    if not os.path.exists(self.directory_to_save):
      os.makedirs(self.directory_to_save)

    if connection_name != None:
      self.connection_name = connection_name
      self.config = self.read_config(connection_name)
      if self.config != False:
        self.port = self.config['Connection']['connection_port']
        self.region_name = self.config['Connection']['region']

  def open_tmux(self,selects,connection_name, region, profile, port):
    server = libtmux.Server()
    session = server.list_sessions()[0]
    print(session)

    window = session.new_window(attach=True, window_name=connection_name+str(round(time.time() * 1000)))

    instances = len(selects)
    print(instances)
    print(instances % 2 == 0)

    if instances % 2 == 0:
      count = 1
    else:
      count = 0

    while (count < instances):
       window.split_window()
       window.select_layout('tiled')
       count += 1

    selection = 1
    for pane in window.list_panes():
      pane.send_keys('ec2ssh connect -n {} -p {}'.format(connection_name,profile))
      pane.send_keys(str(selection))
      selection += 1

    window.set_window_option('synchronize-panes', True)

  def printMenu(self):
    print (30 * '-')
    print ("   M A I N - M E N U")
    print (30 * '-')
    print ("1. Direct Connect")
    print ("2. Pass from Bastion Host")
    print ("3. Autoscaling")
    print (30 * '-')

  def read_config(self,host):
    if os.path.isfile(self.directory_to_save+host+'.ini'):
      config = configparser.ConfigParser()
      config.sections()
      config.read(self.directory_to_save+host+'.ini')
      return(config);
    else:
      return False

  def query_yes_no(self,question, default="yes"):
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")

  def addConfig(self):
    config = configparser.ConfigParser()
    self.printMenu()
    valid_choise=0
    usr_input = ''
    while usr_input not in ['1', '2', '3']:
      if valid_choise :
        print("Not Valid Choise")
      valid_choise=1
      usr_input = input("Input: ")

    config['Connection']= {}

    config['Connection']['region'] = input('Specify a Region:\n-> ')
    config['Connection']['connection_port'] = input('Specify a connection port (for direct or for Bastion):\n-> ')
    config['Connection']['profile'] = input('Specify which AWS profile use:\n-> ')
    if not config['Connection']['profile']:
        config['Connection']['profile'] = 'default'

    if usr_input == "1":
      config['Connection']['type'] = "direct"
      config['EC2INSTANCE'] = {}
      config['EC2INSTANCE']['pem_path'] = input('Enter a keyPair EC2 file path (absolute path):\n-> ')
      config['EC2INSTANCE']['user'] = input('Enter a EC2 user (default "ec2-user"):\n-> ')
      config['EC2INSTANCE']['ec2_instance_id'] = input('Enter a EC2 Instance ID:\n-> ')

      if not config['EC2INSTANCE']['user']:
        config['EC2INSTANCE']['user'] = 'ec2-user'

    elif usr_input == "2":
      config['Connection']['type'] = "bastion"
      config['EC2INSTANCE'] = {}
      config['EC2INSTANCE']['pem_path'] = input('Enter a keyPair EC2 file path (absolute path):\n-> ')
      config['EC2INSTANCE']['user'] = input('Enter a EC2 user (default "ec2-user"):\n-> ')
      config['EC2INSTANCE']['ec2_instance_id'] = input('Enter a EC2 Instance ID:\n-> ')
      config['BASTIONHOST'] = {}
      config['BASTIONHOST']['b_pem_path'] = input('Enter a Bastion pem file path (absolute path):\n-> ')
      config['BASTIONHOST']['b_user'] = input('Enter a Bastion user:\n-> ')
      config['BASTIONHOST']['b_ec2_instance_id'] = input('Enter a Bastion Instance ID:\n-> ')

      if not config['EC2INSTANCE']['user']:
        config['EC2INSTANCE']['user'] = 'ec2-user'

    elif usr_input == "3":
      config['Connection']['type'] = "asg"
      config['ASG'] = {}
      config['ASG']['pem_path'] = input('Enter a pem file path (absolute path):\n-> ')
      config['ASG']['user'] = input('Enter a user (default "ec2-user"):\n-> ')
      config['ASG']['name'] = input('Enter a ASG Name ID:\n-> ')

      if not config['ASG']['user']:
        config['ASG']['user'] = 'ec2-user'

      questions = self.query_yes_no("ASG allow ssh only from Bastion Host?")

      if questions == True:
        config['BASTIONHOST'] = {}
        config['BASTIONHOST']['b_pem_path'] = input('Enter a Bastion pem file path (absolute path):\n-> ')
        config['BASTIONHOST']['b_user'] = input('Enter a Bastion user:\n-> ')
        config['BASTIONHOST']['b_ec2_instance_id'] = input('Enter a Bastion Instance ID:\n-> ')

    with open(self.directory_to_save+self.connection_name+'.ini', 'w') as configfile:
      config.write(configfile)

    print("File Config "+self.connection_name+" created")

  def direct_connect(self,ec2_instance_config):
    target = {'key': ec2_instance_config['pem_path'], 'user': ec2_instance_config['user'], 'host': ec2_instance_config['ec2_instance_id']}
    target_ec2 = self.client
    target_response = target_ec2.describe_instances(InstanceIds=[target['host']])
    target_ip = target_response['Reservations'][0]['Instances'][0]['PublicIpAddress']
    subprocess.call("ssh-add {}".format(target['key']), shell=True)
    subprocess.call("ssh {}@{} -p {}".format(target['user'], target_ip, self.port), shell=True)

  def bastion_connect(self,ec2_instance_config,bastion_config):
    target = {'key': ec2_instance_config['pem_path'], 'user': ec2_instance_config['user'], 'host': ec2_instance_config['ec2_instance_id']}
    target_ec2 = self.client
    target_response = target_ec2.describe_instances(InstanceIds=[target['host']])
    bastion = {'key': bastion_config['b_pem_path'], 'user': bastion_config['b_user'], 'host': bastion_config['b_ec2_instance_id']}
    bastion_ec2 = self.client
    bastion_response = bastion_ec2.describe_instances(InstanceIds=[bastion['host']])
    bastion_ip = bastion_response['Reservations'][0]['Instances'][0]['PublicIpAddress']
    target_ip = target_response['Reservations'][0]['Instances'][0]['NetworkInterfaces'][0]['PrivateIpAddress']
    subprocess.call("ssh-add {} {}".format(bastion['key'], target['key']), shell=True)
    subprocess.call("ssh -t -A {}@{} -p {} ssh {}@{}".format(bastion['user'], bastion_ip,self.port, target['user'], target_ip), shell=True)

  def ec2ssh(self):
    self.session = boto3.Session(profile_name=self.profile)
    self.client = self.session.client('ec2',region_name=self.config['Connection']['region'])
    config = self.read_config(self.connection_name)

    if config['Connection']['type'] == "direct":
      self.direct_connect(config['EC2INSTANCE'])
    elif config['Connection']['type'] == "bastion":
      self.bastion_connect(config['EC2INSTANCE'], config['BASTIONHOST'])
    elif config['Connection']['type'] == "asg":
      print ('Please select an option:')
      print ("   0. All")
      i=1
      selects = {}
      for instance in self.list_instance_in_asg(config['ASG']['name']):
        print ("   "+str(i)+". "+instance['InstanceId']+" - "+instance['LifecycleState'])
        selects[i]=instance['InstanceId']
        i+=1

      config_asg = {}
      choise = input('Enter Value: ')

      if choise != "0":
        config_asg['pem_path']=config['ASG']['pem_path']
        config_asg['user']=config['ASG']['user']
        config_asg['ec2_instance_id']=selects[int(choise)]
        if config.has_section('BASTIONHOST'):
          config_asg_bastion = {}
          config_asg_bastion['b_pem_path']=config['BASTIONHOST']['b_pem_path']
          config_asg_bastion['b_user']=config['BASTIONHOST']['b_user']
          config_asg_bastion['b_ec2_instance_id']=config['BASTIONHOST']['b_ec2_instance_id']
          self.bastion_connect(config_asg, config_asg_bastion)
        else:
          self.direct_connect(config_asg)
      else:
        self.open_tmux(selects, self.connection_name, self.region_name, self.profile, self.port)

  def list_avaible_connection(self):
    print (30 * '-')

    for file in os.listdir(self.directory_to_save):
      if file.endswith(".ini"):
          name_file = file.replace('.ini','')
          print(" Connection Name: "+name_file)
          config = self.read_config(name_file)
          print(" Type: "+config['Connection']['type'])
          print(" Region Name: "+config['Connection']['region'])
          print(" Connection Port: "+config['Connection']['connection_port'])

          if config['Connection']['type'] == "direct":
            print(" Key Pair: "+config['EC2INSTANCE']['pem_path'])
            print(" User Pair: "+config['EC2INSTANCE']['user'])
            print(" Instance Id Pair: "+config['EC2INSTANCE']['ec2_instance_id'])
          elif config['Connection']['type'] == "bastion":
            print(" Key Pair: "+config['EC2INSTANCE']['pem_path'])
            print(" User Pair: "+config['EC2INSTANCE']['user'])
            print(" Instance Id Pair: "+config['EC2INSTANCE']['ec2_instance_id'])
            print(" Bastion Id: "+config['BASTIONHOST']['b_ec2_instance_id'])
          elif config['Connection']['type'] == "asg":
            print(" Key Pair: "+config['ASG']['pem_path'])
            print(" User Pair: "+config['ASG']['user'])
            print(" ASG Name: "+config['ASG']['name'])
            print(" Bastion Id: "+config['BASTIONHOST']['b_ec2_instance_id'])
      print (30 * '-')

  def list_instance_in_asg(self, asg_name):
    if self.profile!=None:
      asg_client = self.session.client('autoscaling',region_name=self.region_name)
    else:
      asg_client = boto3.client('autoscaling',region_name=self.region_name)
    response = asg_client.describe_auto_scaling_groups(
      AutoScalingGroupNames=[
          asg_name,
      ]
    )
    return response['AutoScalingGroups'][0]['Instances']

  def rm_connecition(self):
    try:
      os.remove(self.directory_to_save+self.connection_name+'.ini')
      print(self.connection_name+" connection was removed!")
    except OSError:
      print(self.connection_name+" connection doesn't exist!")
      pass


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.apache.cassandra.net.MessageOut (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.cassandra.net.MessageOut

Packages that use MessageOut

Package
Description

org.apache.cassandra.db

org.apache.cassandra.net

org.apache.cassandra.repair.messages

org.apache.cassandra.sink

Uses of MessageOut in org.apache.cassandra.db

Methods in org.apache.cassandra.db that return MessageOut

Modifier and Type
Method and Description

abstract MessageOut<? extends AbstractRangeCommand>
AbstractRangeCommand.createMessage()

MessageOut<PagedRangeCommand>
PagedRangeCommand.createMessage()

MessageOut<RangeSliceCommand>
RangeSliceCommand.createMessage()

MessageOut<RangeSliceReply>
RangeSliceReply.createMessage()

MessageOut<ReadCommand>
ReadCommand.createMessage()

MessageOut<RowMutation>
RowMutation.createMessage()

MessageOut
SnapshotCommand.createMessage()

MessageOut<TruncateResponse>
TruncateResponse.createMessage()

MessageOut<Truncation>
Truncation.createMessage()

MessageOut<WriteResponse>
WriteResponse.createMessage()

MessageOut<RowMutation>
RowMutation.createMessage(MessagingService.Verb verb)

MessageOut<CounterMutation>
CounterMutation.makeMutationMessage()

Uses of MessageOut in org.apache.cassandra.net

Fields in org.apache.cassandra.net declared as MessageOut

Modifier and Type
Field and Description

MessageOut
WriteCallbackInfo.sentMessage

Methods in org.apache.cassandra.net that return MessageOut

Modifier and Type
Method and Description

MessageOut<T>
MessageOut.withParameter(java.lang.String key,
             byte[] value)

Methods in org.apache.cassandra.net with parameters of type MessageOut

Modifier and Type
Method and Description

int
MessagingService.addCallback(IAsyncCallback cb,
           MessageOut<? extends IMutation> message,
           java.net.InetAddress to,
           long timeout,
           ConsistencyLevel consistencyLevel,
           boolean allowHints)

int
MessagingService.addCallback(IAsyncCallback cb,
           MessageOut message,
           java.net.InetAddress to,
           long timeout,
           boolean failureCallback)

void
OutboundTcpConnection.enqueue(MessageOut<?> message,
       int id)

OutboundTcpConnection
MessagingService.getConnection(java.net.InetAddress to,
             MessageOut msg)

void
MessagingService.sendOneWay(MessageOut message,
          java.net.InetAddress to)

void
MessagingService.sendOneWay(MessageOut message,
          int id,
          java.net.InetAddress to)

Send a message to a given endpoint.

void
MessagingService.sendReply(MessageOut message,
         int id,
         java.net.InetAddress to)

int
MessagingService.sendRR(MessageOut<? extends IMutation> message,
      java.net.InetAddress to,
      AbstractWriteResponseHandler handler,
      boolean allowHints)

Send a mutation message to a given endpoint.

<T> AsyncOneResponse<T>
MessagingService.sendRR(MessageOut message,
      java.net.InetAddress to)

int
MessagingService.sendRR(MessageOut message,
      java.net.InetAddress to,
      IAsyncCallback cb)

int
MessagingService.sendRR(MessageOut message,
      java.net.InetAddress to,
      IAsyncCallback cb,
      long timeout,
      boolean failureCallback)

Send a non-mutation message to a given endpoint.

int
MessagingService.sendRRWithFailure(MessageOut message,
                 java.net.InetAddress to,
                 IAsyncCallbackWithFailure cb)

Constructors in org.apache.cassandra.net with parameters of type MessageOut

Constructor and Description

WriteCallbackInfo(java.net.InetAddress target,
                 IAsyncCallback callback,
                 MessageOut message,
                 IVersionedSerializer<?> serializer,
                 ConsistencyLevel consistencyLevel,
                 boolean allowHints)

Uses of MessageOut in org.apache.cassandra.repair.messages

Methods in org.apache.cassandra.repair.messages that return MessageOut

Modifier and Type
Method and Description

MessageOut<RepairMessage>
RepairMessage.createMessage()

Uses of MessageOut in org.apache.cassandra.sink

Methods in org.apache.cassandra.sink that return MessageOut

Modifier and Type
Method and Description

MessageOut
IMessageSink.handleMessage(MessageOut message,
             int id,
             java.net.InetAddress to)

Transform or drop an outgoing message

static MessageOut
SinkManager.processOutboundMessage(MessageOut message,
                      int id,
                      java.net.InetAddress to)

Methods in org.apache.cassandra.sink with parameters of type MessageOut

Modifier and Type
Method and Description

MessageOut
IMessageSink.handleMessage(MessageOut message,
             int id,
             java.net.InetAddress to)

Transform or drop an outgoing message

static MessageOut
SinkManager.processOutboundMessage(MessageOut message,
                      int id,
                      java.net.InetAddress to)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
require 'spec_helper'

describe Spree::Address, :type => :model do

  subject { Spree::Address }

  context "aliased attributes" do
    let(:address) { Spree::Address.new firstname: 'Ryan', lastname: 'Bigg'}

    it " first_name" do
      expect(address.first_name).to eq("Ryan")
    end

    it "last_name" do
      expect(address.last_name).to eq("Bigg")
    end
  end

  context "validation" do

    let(:country) { mock_model(Spree::Country, :states => [state], :states_required => true) }
    let(:state) { stub_model(Spree::State, :name => 'maryland', :abbr => 'md') }
    let(:address) { build(:address, :country => country) }

    before do
      allow(country.states).to receive_messages :find_all_by_name_or_abbr => [state]
    end

    context 'address does not require state' do
      before do
        Spree::Config.address_requires_state = false
      end
      it "address_requires_state preference is false" do
        address.state = nil
        address.state_name = nil
        expect(address).to be_valid
      end
    end

    context 'address requires state' do
      before do
        Spree::Config.address_requires_state = true
      end

      it "state_name is not nil and country does not have any states" do
        address.state = nil
        address.state_name = 'alabama'
        expect(address).to be_valid
      end

      it "errors when state_name is nil" do
        address.state_name = nil
        address.state = nil
        expect(address).not_to be_valid
      end

      it "full state name is in state_name and country does contain that state" do
        address.state_name = 'alabama'
        # called by state_validate to set up state_id.
        # Perhaps this should be a before_validation instead?
        expect(address).to be_valid
        expect(address.state).not_to be_nil
        expect(address.state_name).to be_nil
      end

      it "state abbr is in state_name and country does contain that state" do
        address.state_name = state.abbr
        expect(address).to be_valid
        expect(address.state_id).not_to be_nil
        expect(address.state_name).to be_nil
      end

      it "state is entered but country does not contain that state" do
        address.state = state
        address.country = stub_model(Spree::Country, :states_required => true)
        address.valid?
        expect(address.errors["state"]).to eq(['is invalid'])
      end

      it "both state and state_name are entered but country does not contain the state" do
        address.state = state
        address.state_name = 'maryland'
        address.country = stub_model(Spree::Country, :states_required => true)
        expect(address).to be_valid
        expect(address.state_id).to be_nil
      end

      it "both state and state_name are entered and country does contain the state" do
        address.state = state
        address.state_name = 'maryland'
        expect(address).to be_valid
        expect(address.state_name).to be_nil
      end
    end

    it "requires phone" do
      address.phone = ""
      address.valid?
      expect(address.errors["phone"]).to eq(["can't be blank"])
    end

    it "requires zipcode" do
      address.zipcode = ""
      address.valid?
      expect(address.errors['zipcode']).to include("can't be blank")
    end

    context "zipcode validation" do
      it "validates the zipcode" do
        allow(address.country).to receive(:iso).and_return('US')
        address.zipcode = 'abc'
        address.valid?
        expect(address.errors['zipcode']).to include('is invalid')
      end

      context 'does not validate' do
        it 'does not have a country' do
          address.country = nil
          address.valid?
          expect(address.errors['zipcode']).not_to include('is invalid')
        end

        it 'does not have an iso' do
          allow(address.country).to receive(:iso).and_return(nil)
          address.valid?
          expect(address.errors['zipcode']).not_to include('is invalid')
        end

        it 'does not have a zipcode' do
          address.zipcode = ""
          address.valid?
          expect(address.errors['zipcode']).not_to include('is invalid')
        end

        it 'does not have a supported country iso' do
          allow(address.country).to receive(:iso).and_return('BO')
          address.valid?
          expect(address.errors['zipcode']).not_to include('is invalid')
        end
      end
    end

    context "phone not required" do
      before { allow(address).to receive_messages require_phone?: false }

      it "shows no errors when phone is blank" do
        address.phone = ""
        address.valid?
        expect(address.errors[:phone].size).to eq 0
      end
    end

    context "zipcode not required" do
      before { allow(address).to receive_messages require_zipcode?: false }

      it "shows no errors when phone is blank" do
        address.zipcode = ""
        address.valid?
        expect(address.errors[:zipcode].size).to eq 0
      end
    end
  end

  context ".default" do
    context "no user given" do
      let!(:default_country) { create(:country) }

      context 'has a default country' do
        before do
          Spree::Config[:default_country_id] = default_country.id
        end

        it "sets up a new record with Spree::Config[:default_country_id]" do
          expect(Spree::Address.default.country).to eq default_country
        end
      end

      # Regression test for #1142
      it "uses the first available country if :default_country_id is set to an invalid value" do
        Spree::Config[:default_country_id] = "0"
        expect(Spree::Address.default.country).to eq default_country
      end
    end

    context "user given" do
      let(:bill_address) { Spree::Address.new(phone: '123-456-7890') }
      let(:user) { double("User", bill_address: bill_address) }

      it "returns a copy of that user bill address" do
        expect(described_class.default(user).phone).to eq '123-456-7890'
      end

      context 'has no address' do
        let(:bill_address) { nil }

        it "falls back to build default when user has no address" do
          expect(described_class.default(user)).to eq described_class.build_default
        end
      end
    end
  end

  context '#full_name' do
    context 'both first and last names are present' do
      let(:address) { stub_model(Spree::Address, :firstname => 'Michael', :lastname => 'Jackson') }
      specify { expect(address.full_name).to eq('Michael Jackson') }
    end

    context 'first name is blank' do
      let(:address) { stub_model(Spree::Address, :firstname => nil, :lastname => 'Jackson') }
      specify { expect(address.full_name).to eq('Jackson') }
    end

    context 'last name is blank' do
      let(:address) { stub_model(Spree::Address, :firstname => 'Michael', :lastname => nil) }
      specify { expect(address.full_name).to eq('Michael') }
    end

    context 'both first and last names are blank' do
      let(:address) { stub_model(Spree::Address, :firstname => nil, :lastname => nil) }
      specify { expect(address.full_name).to eq('') }
    end

  end

  context '#state_text' do
    context 'state is blank' do
      let(:address) { stub_model(Spree::Address, :state => nil, :state_name => 'virginia') }
      specify { expect(address.state_text).to eq('virginia') }
    end

    context 'both name and abbr is present' do
      let(:state) { stub_model(Spree::State, :name => 'virginia', :abbr => 'va') }
      let(:address) { stub_model(Spree::Address, :state => state) }
      specify { expect(address.state_text).to eq('va') }
    end

    context 'only name is present' do
      let(:state) { stub_model(Spree::State, :name => 'virginia', :abbr => nil) }
      let(:address) { stub_model(Spree::Address, :state => state) }
      specify { expect(address.state_text).to eq('virginia') }
    end
  end

  context '#requires_phone' do
    subject { described_class.new }

    it { is_expected.to be_require_phone  }
  end
end


text:
//
//  NBPhoneNumberDesc.m
//  libPhoneNumber
//
//

#import "NBPhoneNumberDesc.h"
#import "NSArray+NBAdditions.h"

@implementation NBPhoneNumberDesc

@synthesize nationalNumberPattern, possibleNumberPattern, exampleNumber;

- (id)initWithData:(id)data
{
    self = [self init];

    if (self && data != nil && [data isKindOfClass:[NSArray class]])
    {
        /* 2 */ self.nationalNumberPattern = [data safeObjectAtIndex:2];
        /* 3 */ self.possibleNumberPattern = [data safeObjectAtIndex:3];
        /* 6 */ self.exampleNumber = [data safeObjectAtIndex:6];
    }

    return self;
}

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

    if (self)
    {
    }

    return self;
}

- (id)initWithCoder:(NSCoder*)coder
{
    if (self = [super init])
    {
        self.nationalNumberPattern = [coder decodeObjectForKey:@"nationalNumberPattern"];
        self.possibleNumberPattern = [coder decodeObjectForKey:@"possibleNumberPattern"];
        self.exampleNumber = [coder decodeObjectForKey:@"exampleNumber"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder*)coder
{
    [coder encodeObject:self.nationalNumberPattern forKey:@"nationalNumberPattern"];
    [coder encodeObject:self.possibleNumberPattern forKey:@"possibleNumberPattern"];
    [coder encodeObject:self.exampleNumber forKey:@"exampleNumber"];
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"nationalNumberPattern[%@] possibleNumberPattern[%@] exampleNumber[%@]", self.nationalNumberPattern, self.possibleNumberPattern, self.exampleNumber];
}

- (id)copyWithZone:(NSZone *)zone
{
	NBPhoneNumberDesc *phoneDescCopy = [[NBPhoneNumberDesc allocWithZone:zone] init];

    phoneDescCopy.nationalNumberPattern = [self.nationalNumberPattern copy];
    phoneDescCopy.possibleNumberPattern = [self.possibleNumberPattern copy];
    phoneDescCopy.exampleNumber = [self.exampleNumber copy];

	return phoneDescCopy;
}

- (BOOL)isEqual:(id)object
{
    if ([object isKindOfClass:[NBPhoneNumberDesc class]] == NO)
        return NO;

    NBPhoneNumberDesc *other = object;
    return [self.nationalNumberPattern isEqual:other.nationalNumberPattern] &&
        [self.possibleNumberPattern isEqual:other.possibleNumberPattern] &&
        [self.exampleNumber isEqual:other.exampleNumber];
}

@end


text:
<button
  *ngIf="!trigger.text"
  mat-icon-button
  id="{{ trigger.id }}"
  [matMenuTriggerFor]="menu.childMenu"
>
  <mat-icon
    *ngIf="trigger.svgIcon"
    [class]="trigger.iconClasses"
    [svgIcon]="trigger.svgIcon"
  ></mat-icon>
  <mat-icon *ngIf="trigger.icon" [class]="trigger.iconClasses">{{
    trigger.icon
  }}</mat-icon>
</button>
<button
  *ngIf="trigger.text"
  mat-button
  id="{{ trigger.id }}"
  [matMenuTriggerFor]="menu.childMenu"
>
  <mat-icon
    *ngIf="trigger.svgIcon"
    [class]="trigger.iconClasses"
    [svgIcon]="trigger.svgIcon"
  ></mat-icon>
  <mat-icon *ngIf="trigger.icon" [class]="trigger.iconClasses">{{
    trigger.icon
  }}</mat-icon>
  <span *ngIf="trigger.text">
    {{ trigger.text }}
  </span>
</button>

<td-dynamic-menu-item
  #menu
  [items]="items"
  (itemClicked)="emitClicked($event)"
></td-dynamic-menu-item>


text:
#ifndef HIPE_X86_H
#define HIPE_X86_H

#ifndef __has_builtin
# define __has_builtin(x) 0
#endif

static __inline__ void
hipe_flush_icache_range(void *address, unsigned int nbytes)
{
    void* end = (char*)address + nbytes;

#if ERTS_AT_LEAST_GCC_VSN__(4, 3, 0) || __has_builtin(__builtin___clear_cache)
    __builtin___clear_cache(address, end);
#elif defined(__clang__)
    void __clear_cache(void *start, void *end);
    __clear_cache(address, end);
#else
# warning "Don't know how to flush instruction cache"
#endif
}

static __inline__ void hipe_flush_icache_word(void *address)
{
    hipe_flush_icache_range(address, sizeof(void*));
}

/* for stack descriptor hash lookup */
#define HIPE_RA_LSR_COUNT	0	/* all bits are significant */

/* for hipe_bifs_{read,write}_{s,u}32 */
static __inline__ int hipe_word32_address_ok(void *address)
{
    return 1;
}

/* Native stack growth direction. */
#define HIPE_NSTACK_GROWS_DOWN

#define hipe_arch_name	am_x86

extern void nbif_inc_stack_0(void);
#ifndef NO_FPE_SIGNALS
extern void nbif_handle_fp_exception(void);
#endif

#endif /* HIPE_X86_H */


text:
* normal db module
    * can create exported public type User
    * *can* create internal UserDaoImpl because of `opens` in [module-info.java](https://github.com/codetojoy/talk_maritimedevcon_java_9_modules/blob/master/eg_03_2_java_9_open_module/src/com.acme.bids.db/module-info.java)

* main code [here](https://github.com/codetojoy/talk_maritimedevcon_java_9_modules/blob/master/eg_03_2_java_9_open_module/src/com.acme.bids.service/com/acme/bids/service/impl/UserServiceImpl.java)

### Validation

* 20-MAY-2017 - confirmed b170
* confirmed, b169, b167

### Execution Steps

* `./build_and_run.sh`


text:
package net.geforcemods.securitycraft.util;

import net.geforcemods.securitycraft.blockentities.InventoryScannerBlockEntity;
import net.geforcemods.securitycraft.blocks.InventoryScannerBlock;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.contents.TranslatableContents;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.alchemy.Potion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraftforge.registries.ForgeRegistries;

public class Utils {
	public static final Style GRAY_STYLE = Style.EMPTY.withColor(ChatFormatting.GRAY);
	public static final Component INVENTORY_TEXT = Utils.localize("container.inventory");

	/**
	 * Removes the last character in the given String. <p>
	 */
	public static String removeLastChar(String line) {
		if (line == null || line.isEmpty())
			return "";

		return line.substring(0, line.length() - 1);
	}

	public static Component getFormattedCoordinates(BlockPos pos) {
		return Component.translatable("messages.securitycraft:formattedCoordinates", pos.getX(), pos.getY(), pos.getZ());
	}

	public static void setISinTEAppropriately(Level level, BlockPos pos, NonNullList<ItemStack> contents) {
		InventoryScannerBlockEntity connectedScanner = InventoryScannerBlock.getConnectedInventoryScanner(level, pos);

		if (connectedScanner == null)
			return;

		connectedScanner.setContents(contents);
	}

	/**
	 * Localizes a String with the given format
	 *
	 * @param key The string to localize (aka the identifier in the .lang file)
	 * @param params The parameters to insert into the String ala String.format
	 * @return The localized String
	 */
	public static MutableComponent localize(String key, Object... params) {
		for (int i = 0; i < params.length; i++) {
			if (params[i] instanceof Component component && component.getContents() instanceof TranslatableContents translatableContents)
				params[i] = localize(translatableContents.getKey(), translatableContents.getArgs());
			else if (params[i] instanceof BlockPos pos)
				params[i] = getFormattedCoordinates(pos);
		}

		return Component.translatable(key, params);
	}

	public static ResourceLocation getRegistryName(Block block) {
		return ForgeRegistries.BLOCKS.getKey(block);
	}

	public static ResourceLocation getRegistryName(EntityType<?> entityType) {
		return ForgeRegistries.ENTITY_TYPES.getKey(entityType);
	}

	public static ResourceLocation getRegistryName(Item item) {
		return ForgeRegistries.ITEMS.getKey(item);
	}

	public static ResourceLocation getRegistryName(Potion potion) {
		return ForgeRegistries.POTIONS.getKey(potion);
	}
}


text:
namespace mobagen {
  class MeshRenderer : public Component {
  public:
    MeshRenderer(std::shared_ptr<Mesh> mesh, std::shared_ptr<Material> material);

    virtual ~MeshRenderer(void);

    virtual void render(Shader *shader);

    void setMaterial(std::shared_ptr<Material> material);

    std::shared_ptr<Material> getMaterial();

    void setMesh(std::shared_ptr<Mesh> mesh);

    std::shared_ptr<Mesh> getMesh();

    inline virtual const char *getType(void) { return "MESH_RENDERER"; }

  private:
    std::shared_ptr<Mesh> m_mesh;
    std::shared_ptr<Material> m_material;
  };
}


text:
iD.ui.ViewOnOSM = function(context) {
    var id;

    function viewOnOSM(selection) {
        var entity = context.entity(id);

        selection.style('display', entity.isNew() ? 'none' : null);

        var $link = selection.selectAll('.view-on-osm')
            .data([0]);

        var $enter = $link.enter().append('a')
            .attr('class', 'view-on-osm')
            .attr('target', '_blank');

        $enter.append('span')
            .attr('class', 'icon icon-pre-text out-link');

        $enter.append('span')
            .text(t('inspector.view_on_osm'));

        $link.attr('href', context.connection().entityURL(entity));
    }

    viewOnOSM.entityID = function(_) {
        if (!arguments.length) return id;
        id = _;
        return viewOnOSM;
    };

    return viewOnOSM;
};


text:
use python::{Python, PythonObject, ToPythonPointer};
use conversion::ToPyObject;
use objects::{PyObject, PyTuple, PyDict};
use err::{PyResult, result_from_owned_ptr};
use ffi;
use std::ffi::CStr;
use std::borrow::Cow;

/// Represents a reference to a Python type object.
pub struct PyType(PyObject);

pyobject_newtype!(PyType, PyType_Check, PyType_Type);

impl PyType {
    /// Retrieves the underlying FFI pointer associated with this Python object.
    #[inline]
    pub fn as_type_ptr(&self) -> *mut ffi::PyTypeObject {
        self.0.as_ptr() as *mut ffi::PyTypeObject
    }

    /// Retrieves the PyType instance for the given FFI pointer.
    /// This increments the reference count on the type object.
    /// Undefined behavior if the pointer is NULL or invalid.
    #[inline]
    pub unsafe fn from_type_ptr(py: Python, p: *mut ffi::PyTypeObject) -> PyType {
        PyObject::from_borrowed_ptr(py, p as *mut ffi::PyObject).unchecked_cast_into::<PyType>()
    }

    /// Gets the name of the PyType.
    pub fn name<'a>(&'a self, _py: Python<'a>) -> Cow<'a, str> {
        unsafe {
            CStr::from_ptr((*self.as_type_ptr()).tp_name).to_string_lossy()
        }
    }

    /// Return true if `self` is a subtype of `b`.
    #[inline]
    pub fn is_subtype_of(&self, _: Python, b : &PyType) -> bool {
        unsafe { ffi::PyType_IsSubtype(self.as_type_ptr(), b.as_type_ptr()) != 0 }
    }

    /// Return true if `obj` is an instance of `self`.
    #[inline]
    pub fn is_instance(&self, _: Python, obj : &PyObject) -> bool {
        unsafe { ffi::PyObject_TypeCheck(obj.as_ptr(), self.as_type_ptr()) != 0 }
    }

    /// Calls the type object, thus creating a new instance.
    /// This is equivalent to the Python expression: `self(*args, **kwargs)`
    #[inline]
    pub fn call<A>(&self, py: Python, args: A, kwargs: Option<&PyDict>) -> PyResult<PyObject>
        where A: ToPyObject<ObjectType=PyTuple>
    {
        args.with_borrowed_ptr(py, |args| unsafe {
            result_from_owned_ptr(py, ffi::PyObject_Call(self.0.as_ptr(), args, kwargs.as_ptr()))
        })
    }
}

impl PartialEq for PyType {
    #[inline]
    fn eq(&self, o : &PyType) -> bool {
        self.as_type_ptr() == o.as_type_ptr()
    }
}
impl Eq for PyType { }


text:
Simple flocking logic demo in client-side Javascript.

    ./deps   # download Javascript libraries
    ./run    # start the server


text:
require 'fileutils'
require 'hirb'
require 'one9/report'
require 'one9/method'
require 'one9/report_method'
require 'one9/spy'
require 'one9/rc'
require 'one9/version'

module One9
  extend self
  attr_accessor :stacks, :config, :dir, :rc
  self.stacks = Hash.new {|h,k| h[k] = [] }
  self.config = {}

  def spy(meth)
    stacks[meth] << caller[1..-1]
  end

  def it
    meths = load_methods
    Spy.setup meths
    Report.later(meths, stacks)
  end

  def load_methods
    # ensure all changes can be loaded
    %w{date time}.each {|e| require e }
    Rc.load File.dirname(__FILE__) + '/one9/defaults.rb'
    Rc.load(rc) if File.exists?(rc)
    Rc.meths
  end

  def dir
    @dir ||= begin
      path = File.expand_path('~/.one9')
      FileUtils.mkdir_p path
      path
    end
  end
end

One9.dir = ENV['ONE9_DIR']
One9.rc = ENV['ONE9_RC'] || File.expand_path('~/.one9rc')


text:
describe("#globValues", function() {
  var util = module.exports;

  it("should pass each glob#sync the root for its current working dir", function() {
    util.globValues({key: ['file1', 'file2']}, 'some root dir');
    expect(glob.sync.calls.argsFor(0)[1].cwd).toBe('some root dir');
    expect(glob.sync.calls.argsFor(1)[1].cwd).toBe('some root dir');
  });

  describe("after being called", function() {
    beforeEach(function() {
      this.fileObj = {
        key: 'files',
        otherKey: ['more files', 'even more files']
      };

      glob.sync = function(files) {
       return [files + ' globbed', files + ' globbed again'];
      };
    });

    it("should expand each file glob in each key", function() {
      expect(util.globValues(this.fileObj)).toEqual({
        key: ['files globbed', 'files globbed again'],
        otherKey: [
          'more files globbed',
          'more files globbed again',
          'even more files globbed',
          'even more files globbed again'
        ]
      });
    });

    it("should not change the file object passed in", function() {
      expect(this.fileObj.key).toBe('files');
    });
  });
});


text:
package org.kie.workbench.common.stunner.client.widgets.presenters.diagram.impl;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.client.widgets.presenters.AbstractCanvasHandlerViewerTest;
import org.kie.workbench.common.stunner.client.widgets.presenters.diagram.DiagramViewer;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.controls.connection.ConnectionAcceptorControl;
import org.kie.workbench.common.stunner.core.client.canvas.controls.containment.ContainmentAcceptorControl;
import org.kie.workbench.common.stunner.core.client.canvas.controls.docking.DockingAcceptorControl;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandManager;
import org.kie.workbench.common.stunner.core.client.session.ClientSession;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.mockito.Mock;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class DiagramEditorTest extends AbstractCanvasHandlerViewerTest {

    @Mock
    DiagramViewer viewer;

    @Mock
    CanvasCommandManager<AbstractCanvasHandler> commandManager;

    @Mock
    ConnectionAcceptorControl<AbstractCanvasHandler> connectionAcceptorControl;

    @Mock
    ContainmentAcceptorControl<AbstractCanvasHandler> containmentAcceptorControl;

    @Mock
    DockingAcceptorControl<AbstractCanvasHandler> dockingAcceptorControl;

    @Mock
    DiagramViewer.DiagramViewerCallback<Diagram> callback;

    private DiagramEditorImpl<Diagram, AbstractCanvasHandler, ClientSession> tested;

    @Before
    @SuppressWarnings("unchecked")
    public void setup() throws Exception {
        super.init();
        when(viewer.getHandler()).thenReturn(canvasHandler);
        doAnswer(invocationOnMock -> {
            when(viewer.getInstance()).thenReturn(diagram);
            final DiagramViewer.DiagramViewerCallback c = (DiagramViewer.DiagramViewerCallback) invocationOnMock.getArguments()[1];
            c.afterCanvasInitialized();
            c.onSuccess();
            return diagram;
        }).when(viewer).open(any(Diagram.class),
                             any(DiagramViewer.DiagramViewerCallback.class));
        doAnswer(invocationOnMock -> {
            when(viewer.getInstance()).thenReturn(null);
            return null;
        }).when(viewer).clear();
        doAnswer(invocationOnMock -> {
            when(viewer.getInstance()).thenReturn(null);
            return null;
        }).when(viewer).destroy();
        this.tested =
                new DiagramEditorImpl<>(viewer,
                                        commandManager,
                                        connectionAcceptorControl,
                                        containmentAcceptorControl,
                                        dockingAcceptorControl);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testOpen() {
        tested.open(diagram,
                    callback);
        assertEquals(diagram,
                     tested.getInstance());
        verify(viewer,
               times(1)).open(eq(diagram),
                              any(DiagramViewer.DiagramViewerCallback.class));
        verify(connectionAcceptorControl,
               times(1)).enable(eq(canvasHandler));
        verify(containmentAcceptorControl,
               times(1)).enable(eq(canvasHandler));
        verify(dockingAcceptorControl,
               times(1)).enable(eq(canvasHandler));
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testScale() {
        tested.open(diagram,
                    callback);
        tested.scale(50,
                     50);
        assertEquals(diagram,
                     tested.getInstance());
        verify(viewer,
               times(1)).scale(50,
                               50);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testClear() {
        tested.open(diagram,
                    callback);
        tested.clear();
        assertNull(tested.getInstance());
        verify(viewer,
               times(1)).clear();
        verify(connectionAcceptorControl,
               times(1)).disable();
        verify(containmentAcceptorControl,
               times(1)).disable();
        verify(dockingAcceptorControl,
               times(1)).disable();
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testDestroy() {
        tested.open(diagram,
                    callback);
        tested.destroy();
        assertNull(tested.getInstance());
        verify(viewer,
               times(1)).destroy();
        verify(connectionAcceptorControl,
               times(1)).disable();
        verify(containmentAcceptorControl,
               times(1)).disable();
        verify(dockingAcceptorControl,
               times(1)).disable();
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vanamco.huvis.modules.pctmainproject;

import com.vanamco.huvis.api.bundlerapi.BundlerService;
import com.vanamco.huvis.modules.toolbox.projectRelated.PCTSettings;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JMenuItem;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.actions.Presenter;
import org.openide.windows.IOProvider;
import org.openide.windows.InputOutput;

/**
 *
 * @author ybrise
 */
/**
 * /** Action to remove a loaded transformation. If no transformation is loaded
 * this action has no effect.
 */
public class PCTActionRemoveTransformation extends AbstractAction implements Presenter.Popup, Runnable {

    private final PCTProject project;

    public PCTActionRemoveTransformation(PCTProject project) {
        this.project = project;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        RequestProcessor processor = new RequestProcessor("Transformation Action", 1, true);
        processor.post(this);
    }

    @NbBundle.Messages("LBL_RemoveTransformation=Remove Transformation")
    @Override
    public JMenuItem getPopupPresenter() {
        JMenuItem result = new JMenuItem(this);

        //Set the menu's label
        result.setText(Bundle.LBL_RemoveTransformation());
        return result;
    }

    @Override
    public void run() {
        BundlerService bundlerService = project.getLookup().lookup(BundlerService.class);
        bundlerService.removeTransformation();
        PCTProject.PCTProjectState state = project.getLookup().lookup(PCTProject.PCTProjectState.class);
        state.removeTransformation();
        InputOutput io_wf = IOProvider.getDefault().getIO(PCTSettings.OUTPUT_REGISTER_WORKFLOW, false);
        io_wf.select();
        io_wf.getOut().print(PCTSettings.timestamp());
        io_wf.getOut().println(" [Transformation] transformation file " + PCTSettings.TRANSFORMATION_FILE_NAME + " unloaded");
    }
}


text:
More info on the competition here: http://aicomp.io/

## Status
Working on qualifying by creating a bot that:
- finds the least-blocked path to the opponent
- moves along that path, dropping bombs as needed

## Future
Use RL to play games against itself


text:
package com.thinkbiganalytics.policy.validation;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * test the {@link LookupValidator}
 */
public class LookupValidatorTest {

    @Test
    public void testValidate() throws Exception {
        LookupValidator validator = new LookupValidator("true", "false");
        assertTrue(validator.validate("true"));
        assertTrue(validator.validate("false"));
        assertFalse(validator.validate("FALSE"));
        assertFalse(validator.validate("none"));
        assertFalse(validator.validate(""));
    }
}


text:
package models_test

import (
	"encoding/base64"
	. "github.com/cloudfoundry/hm9000/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("BasicAuthInfo", func() {
	Describe("basic auth encoding", func() {
		It("should encode the user and password in basic auth form", func() {
			info := BasicAuthInfo{"mcat", "testing"}
			Ω(info.Encode()).Should(Equal("Basic bWNhdDp0ZXN0aW5n"))
		})
	})

	Describe("basic auth decoding", func() {
		Context("when the string is malformed", func() {
			It("should return an error", func() {
				authInfo, err := DecodeBasicAuthInfo("bWNhdDp0ZXN0aW5n")
				Ω(authInfo).Should(BeZero())
				Ω(err).Should(HaveOccurred())

				authInfo, err = DecodeBasicAuthInfo("Basic " + base64.StdEncoding.EncodeToString([]byte("pink-flamingoes")))
				Ω(authInfo).Should(BeZero())
				Ω(err).Should(HaveOccurred())

				authInfo, err = DecodeBasicAuthInfo("Basic " + base64.StdEncoding.EncodeToString([]byte("pink-flamingoes:password:oops")))
				Ω(authInfo).Should(BeZero())
				Ω(err).Should(HaveOccurred())

				authInfo, err = DecodeBasicAuthInfo("Basic " + base64.StdEncoding.EncodeToString([]byte("pink-flamingoes:password")) + " oops")
				Ω(authInfo).Should(BeZero())
				Ω(err).Should(HaveOccurred())
			})
		})

		Context("when all is well", func() {
			It("should decode the user and password and not return an error", func() {
				authInfo, err := DecodeBasicAuthInfo("Basic bWNhdDp0ZXN0aW5n")
				Ω(err).ShouldNot(HaveOccurred())

				Ω(authInfo.User).Should(Equal("mcat"))
				Ω(authInfo.Password).Should(Equal("testing"))
			})
		})
	})
})