text:
/**
 * @constructor
 * @requires Vex.Flow This parser depends on the VexFlow rendering API.
 *
 * Initialize and return a new VexTab parser. Example usage:
 *
 *   var JUSTIFY_WIDTH = 400;
 *   var CONTEXT = new Vex.Flow.Renderer(
 *      document.getElementById("canvas_id"),
 *      Vex.Flow.Renderer.Backends.CANVAS).getContext();
 *
 *   var parser = new Vex.Flow.VexTab();
 *
 *   try {
 *     parser.parse(vextab_code);
 *     if (parser.isValid()) {
 *       var elements = parser.getElements();
 *
 *       for (var i = 0; i < staves.length; ++i) {
 *         var stave = elements.staves[i];
 *         var voice_notes = elements.tabnotes[i];
 *         var voice_ties = elements.ties[i];
 *
 *         // Draw stave
 *         stave.setWidth(JUSTIFY_WIDTH);
 *         stave.setContext(CONTEXT).draw();
 *
 *         // Draw notes and modifiers.
 *         if (voice_notes) {
 *           Vex.Flow.Formatter.FormatAndDraw(CONTEXT, stave,
 *               voice_notes, JUSTIFY_WIDTH - 20);
 *         }
 *
 *         // Draw ties
 *         for (var j = 0; j < voice_ties.length; ++j) {
 *           voice_ties[j].setContext(CONTEXT).draw();
 *         }
 *       }
 *     }
 *   } catch (e) {
 *      console.log(e.message);
 *   }
 *
 */
Vex.Flow.VexTab = function() {
  this.init();
}

/**
 * Initialize VexTab.
 * @constructor
 */
Vex.Flow.VexTab.prototype.init = function() {
  // The VexFlow elements generated from the VexTab code.
  this.elements = {
    staves: [],
    tabnotes: [],
    notes: [],
    ties: [],
    beams: []
  };

  // Pre-parser state. This is used for error-reporting and
  // element generation.
  this.state = {
    current_line: 0,
    current_stave: -1,
    current_duration: "8",
    has_notation: false,
    has_tab: true,
    beam_start: null
  };

  this.valid = false;         // Valid (parseable) VexTab?
  this.last_error = "";       // Last error message generated.
  this.last_error_line = 0;   // Line number of last error.
  this.height = 0;            // Total height of generated elements.
  this.tuning = new Vex.Flow.Tuning(); // Defaults to standard tuning.
}

/**
 * Returns true if the passed-in code parsed without errors.
 *
 * @return {Boolean} True if code is error-free.
 */
Vex.Flow.VexTab.prototype.isValid = function() { return this.valid; }

/**
 * Returns the generated VexFlow elements. Remember to call #isValid before
 * calling this method.
 *
 * @return {!Object} The generated VexFlow elements.
 */
Vex.Flow.VexTab.prototype.getElements = function() {
  return this.elements;
}

/**
 * @return {Number} The total height (in pixels) of the generated elements.
 */
Vex.Flow.VexTab.prototype.getHeight = function() { return this.height; }

/**
 * This method parses the VexTab code provided, and generates VexFlow
 * elements from it. The elements can be retrieved with the #getElements
 * method.
 *
 * If the parse fails, a Vex.RuntimeError of the type "ParseError" is
 * thrown with the line number and specific error message.
 *
 * Upon success, no exception is thrown and #isValid returns true.
 *
 * @param {String} code The VexTab code to parse.
 */
Vex.Flow.VexTab.prototype.parse = function(code) {
  // Clear elements and initialize parse state
  this.init();

  // Separate code into lines
  var lines = code.split("\n");
  for (var i = 0; i < lines.length; ++i) {
    var line = lines[i];
    this.state.current_line++;
    // Strip leading and trailing spaces
    line = line.replace(/(^\s*)|(\s*$)/gi,"");
    // Skip blank lines
    if (line == "") continue;

    // This line has entropy. Parse it.
    this.parseLine(line);
  }

  this.valid = true;
  this.height += 30;

  return this;
}

/**
 * Throws a Vex.RuntimeError exception with the code set to "ParseError". The
 * error includes the line number and specific error message.
 *
 * @param {String} message The error string.
 * @private
 */
Vex.Flow.VexTab.prototype.parseError = function(message) {
  this.valid = false;
  this.last_error = message;
  this.last_error_line = this.state.current_line;

  // Create and throw the RuntimeError exception.
  var error = new Vex.RERR("ParseError",
      "Line " + this.state.current_line + ": " + message);
  error.line = this.state.current_line;
  throw error;
}

/**
 * A line of VexTab code is essentially structured as:
 *
 *    command [param] [param] ...
 *
 * This function parses out valid commands and executes the
 * relevant sub-parser to work on the parameters.
 *
 * @param {String} line One line of VexTab code.
 * @private
 */
Vex.Flow.VexTab.prototype.parseLine = function(line) {
  // Split line into tokens
  var tokens = line.split(/\s+/);

  // The first token is the command. Run it.
  var command = tokens[0];
  switch(command) {
    // Generate a TAB stave.
    case "tabstave": this.parseTabStave(tokens); break;

    // Parse tab notes.
    case "notes": this.parseNotes(tokens); break;

    // Unrecognized command. Throw an error.
    default: this.parseError("Invalid keyword: " + command);
  }
}

Vex.Flow.VexTab.prototype.parseKeyValue = function(token) {
  var pair = token.split(/\s*=\s*/);
  if (pair.length != 2) this.parseError("Invalid key value pair: " + token);
  return { key: pair[0], value: pair[1] };
}

Vex.Flow.VexTab.prototype.parseTabStave = function(tokens) {
  var has_standard_notation = false;
  var has_tablature = true;
  var has_clef = "treble";
  for (var i = 1; i < tokens.length; ++i) {
    var pair = this.parseKeyValue(tokens[i]);
    if (pair.key.toLowerCase() == "notation") {
      switch (pair.value.toLowerCase()) {
        case "true": has_standard_notation = true; break;
        case "false": has_standard_notation = false; break;
        default: this.parseError(
                     'notation must be "true" or "false": ' + pair.value);
      }
    } else if (pair.key.toLowerCase() == "tablature") {
      switch (pair.value.toLowerCase()) {
        case "true": has_tablature = true; break;
        case "false": has_tablature = false; break;
        default: this.parseError(
                     'tablature must be "true" or "false": ' + pair.value);
      }
    } else if (pair.key.toLowerCase() == "clef") {
      switch (pair.value.toLowerCase()) {
        case "treble": has_clef = "treble"; break;
        case "alto": has_clef = "alto"; break;
        case "bass": has_clef = "bass"; break;
        default: this.parseError(
                     'clef must be "treble", "alto", or "bass": ' + pair.value);
      }
    } else {
      this.parseError("Invalid parameter for tabstave: " + pair.key)
    }
  }

  if (!has_tablature && !has_standard_notation) {
    this.parseError('notation & tablature cannot both be "false"');
  }

  this.genTabStave({ notation: has_standard_notation, tablature: has_tablature, clef: has_clef });
}

/**
 * VexTab notes consists of note-groups separated by spaces. For
 * example:
 *
 *   4-5-6/4 5 | (4/5.5/6.6.7)
 *
 * Each note group is parsed by a recursive-descent parser.
 *
 * @param {Array.<String>} tokens An array of note-groups.
 * @private
 */
Vex.Flow.VexTab.prototype.parseNotes = function(tokens) {
  for (var i = 1; i < tokens.length; ++i) {
    var token = tokens[i];
    switch (token) {
      // Bars are simple. No parsing necessary.
      case "|": this.genBar(); break;

      // Open beam
      case "[": this.parseOpenBeam(); break;

      // Close beam
      case "]": this.parseCloseBeam(); break;

      // Everything else goes through the recdescent toke parser.
      default:
        this.parseToken(tokens[i]);
        this.genElements();
    }
  }

  // Verify that all beams are closed.
  if (this.state.beam_start != null)
    this.parseError("Beam not closed");
}

/**
 * This method is a regular-expression based lexer. Its job is to:
 *
 *    1) Extract the next token.
 *    2) Strip out the remaining string.
 *    3) Keep track of errors (e.g., unexpected EOL, unrecognized token, etc.)
 *
 * The valid tokens are:
 *
 *    "t" - Taps (represented as Annotations in VexFlow)
 *    "s" - Slides (represented as Ties in VexFlow)
 *    "h" - Hammer-ons (represented as Ties in VexFlow)
 *    "p" - Pull-offs (represented as Ties in VexFlow)
 *    "b" - Bends / Open beams
 *    "v" - Soft vibrato
 *    "V" - Harsh vibrato
 *    "-" - Fret separators
 *    "/" - String separator
 *    "(" - Open chord
 *    "." - Note separator inside a chord
 *    ")" - Close chord
 *    ":(\S+)" - Duration
 *    \d+ - A fret or string number
 *
 * @private
 */
Vex.Flow.VexTab.prototype.getNextRegExp = function(re) {
  if (this.parse_state.done)
    this.parseError("Unexpected end of line");

  var match = this.parse_state.str.match(re);

  if (match) {
    this.parse_state.value = match[1];
    this.parse_state.str = match[2];
    if (this.parse_state.str == "") this.parse_state.done = true;
    return true;
  }

  this.parseError("Error parsing notes at: " + this.parse_state.str);
  return false;
}

Vex.Flow.VexTab.prototype.getNextToken = function() {
  return this.getNextRegExp(/^(\d+|[\)\(-tbhpsvV\.\/\|\:])(.*)/);
}

Vex.Flow.VexTab.prototype.getNextDurationToken = function() {
  return this.getNextRegExp(/^([0-9a-z]+|:)(.*)/);
}

/**
 * This is the start of the recdescent grammar for notes-lines. A notes-line
 * can begin with a "(", "t", or a fret number.
 *
 * @param {String} str A notes-line token.
 * @private
 */
Vex.Flow.VexTab.prototype.parseToken = function(str) {
  // Initialize the recursive descent parser state.
  this.parse_state = {
    str: str,                 // The leftover string to parse
    done: false,              // Finished parsing everything?
    expecting_string: false,  // Expecting a string number (as opposed to fret)

    // This keeps track of positions in time. A position can have multipe
    // string-fret combos (incase of chords), or just one.
    positions: [],
    durations: [],
    position_index: -1,
    annotations: [],          // Annotations associated with positions
    bends: [],                // Bends associated with positions
    vibratos: [],             // Vibrations associated with positions
    ties: [],                 // Ties associated with positions
    chord_ties: [],           // Chord ties associated with positions

    inside_bend: false,       // Are we inside a bend
    chord_index: -1          // The current chord index
  };

  var done = false;
  while (!done && this.getNextToken()) {
    switch (this.parse_state.value) {
      case "(": this.parseOpenChord(); break;
      case "t": this.parseTapAnnotation(); break;
      default: this.parseFret();
    }

    done = this.parse_state.done;
  }
}

Vex.Flow.VexTab.validDurations = {
  "w": "w",
  "h": "h",
  "q": "q",
  "8": "8",
  "8d": "8d",
  "16": "16",
  "16d": "16d",
  "32": "32",
  "32d": "32d"
}

/**
 * Parse ":" - Note duration
 *
 * @private
 */
Vex.Flow.VexTab.prototype.parseDuration = function() {
  this.getNextDurationToken();

  var duration = Vex.Flow.VexTab.validDurations[this.parse_state.value];
  if (duration) {
    this.state.current_duration = duration;
  } else {
    this.parseError("Invalid duration: " + this.parse_state.value);
  }

  if (!this.parse_state.done) {
    this.getNextDurationToken();
    if (this.parse_state.value != ":")
      this.parseError("Unexpected token: " + this.parse_state.str);

    if (!this.parse_state.done)
      this.parseError("Unexpected token: " + this.parse_state.str);
  }
}

/**
 * Parse "(" - Start a chord.
 *
 * @private
 */
Vex.Flow.VexTab.prototype.parseOpenChord = function() {
  // Add a position for this chord.
  this.parse_state.positions.push([]);
  this.parse_state.durations.push(this.state.current_duration);
  this.parse_state.position_index++;

  // Reset the chord-index.
  this.parse_state.chord_index = -1;

  // The next token must be a fret.
  this.getNextToken();
  this.parseChordFret();
}

/**
 * Parse "t" - Tap annotations.
 *
 * @private
 */
Vex.Flow.VexTab.prototype.parseTapAnnotation = function() {
  // Create an annotation and assosiate it with the note in the
  // next position.
  this.parse_state.annotations.push({
      position: this.parse_state.position_index + 1,
      text: "T" });

  // The next token must be a fret.
  this.getNextToken();
  switch (this.parse_state.value) {
    case "(": this.parseOpenChord(); break;
    default: this.parseFret();
  }
}

/**
 * Parse one note in a chord. The note must have a fret and string, and
 * may contain a bend.
 *
 * @private
 */
Vex.Flow.VexTab.prototype.parseChordFret = function() {
  // Extract duration (if available)
  if (this.parse_state.value == ":") {
    this.parseFretDuration();
    this.parse_state.durations[this.parse_state.durations.length - 1] =
      this.state.current_duration;
    if (this.parse_state.done) return;
    this.getNextToken();
  }

  // Do we have a valid fret?
  var fret = this.parse_state.value;
  if (isNaN(parseInt(fret)))
    this.parseError("Invalid fret number: " + fret);

  // The next token can either be a bend or a slash
  this.getNextToken();
  if (this.parse_state.value == "b") {
    // This is a bend, parse it out.
    this.parseChordBend();
  } else if (this.parse_state.value != "/") {
    this.parseError("Expecting / for string number: " + this.parse_state.value);
  }

  // We found a slash, parse out the string number and make sure
  // it's valid.
  this.getNextToken();
  var str = parseInt(this.parse_state.value);
  if (isNaN(parseInt(str)))
    this.parseError("Invalid string number: " + this.parse_state.value);

  // Add current fret-string to current position. Don't create a new
  // position because this is a chord.
  this.parse_state.positions[this.parse_state.position_index].push(
      { fret: fret, str: str });
  this.parse_state.chord_index++;

  // Next token can either be a chord separator ".", or a close chord ")"
  this.getNextToken();
  switch(this.parse_state.value) {
    case ".": this.getNextToken(); this.parseChordFret(); break;
    case ")": this.parseCloseChord(); break;
    default: this.parseError("Unexpected token: " + this.parse_state.value);
  }
}

/**
 * Parse a close chord token ")".
 *
 * @private
 */
Vex.Flow.VexTab.prototype.parseCloseChord = function() {
  // Reset chord index.
  this.chord_index = -1;

  // This is a valid place for parsing to end.
  if (this.parse_state.done) return;

  // There are more tokens. The only legitimate next token can be a
  // vibrato.
  this.getNextToken();
  switch (this.parse_state.value) {
    case "h": this.parseChordTie(); break;
    case "p": this.parseChordTie(); break;
    case "s": this.parseChordTie(); break;
    case "t": this.parseChordTie(); break;
    case "v": this.parseVibrato(); break;
    case "V": this.parseVibrato(); break;
    default: this.parseError("Unexpected token: " + this.parse_state.value);
  }
}

/**
 * Parse bends inside chords.
 * @private
 */
Vex.Flow.VexTab.prototype.parseChordBend = function() {
  // Next token has to be a fret number.
  this.getNextToken();
  var fret = parseInt(this.parse_state.value);
  if (isNaN(fret)) this.parseError("Expecting fret: " + this.parse_state.value);

  // If we're already inside a bend, then mark this as a release, otherwise
  // create a new bendj
  if (this.parse_state.inside_bend) {
    var this_bend = this.parse_state.bends.length - 1;
    // We're actually incrementing a bend count here because we want to
    // be able to support multiple sequential bends on one string.
    this.parse_state.bends[this_bend].count++;
  } else {
    this.parse_state.inside_bend = true;
    this.parse_state.bends.push(
        { position: this.parse_state.position_index, count: 1,
          index: this.parse_state.chord_index + 1, to_fret: fret });
  }

  // Next token can either be another bend, or a slash. (Remember, we're inside
  // a chord, so we can't really do slides or hammer/pulloff unambiguously.)
  this.getNextToken();
  switch (this.parse_state.value) {
    case "b": this.parseChordBend(); break;
    case "/": break;
    default:
      this.parseError("Unexpected token: " + this.parse_state.value);
  }

  this.parse_state.inside_bend = false;
}

/**
 * Parse ":" (note duration) within notes stanza.
 *
 * @private
 */
Vex.Flow.VexTab.prototype.parseFretDuration = function() {
  this.getNextDurationToken();

  var duration = Vex.Flow.VexTab.validDurations[this.parse_state.value];
  if (duration) {
    this.state.current_duration = duration;
  } else {
    this.parseError("Invalid duration: " + this.parse_state.value);
  }

  if (this.parse_state.done) return;

  this.getNextDurationToken();
  if (this.parse_state.value != ":")
    this.parseError("Unexpected token: " + this.parse_state.str);
}

/**
 * Parse fret number (outside a chord context).
 * @private
 */
Vex.Flow.VexTab.prototype.parseFret = function() {
  // Extract duration (if available)
  if (this.parse_state.value == ":") {
    this.parseFretDuration();
    if (this.parse_state.done) return;
    this.getNextToken();
  }

  // Fret number must be valid.
  var str = this.parse_state.value;
  if (isNaN(parseInt(str)))
    this.parseError("Invalid fret number: " + str);

  // Create a new position for this fret/string pair.
  this.parse_state.positions.push([{ fret: str }]);
  this.parse_state.durations.push(this.state.current_duration);
  this.parse_state.position_index++;

  // Extract and parse next token.
  this.getNextToken();
  switch(this.parse_state.value) {
    case "-": this.parseDash(); break;
    case "/": this.parseSlash(); break;
    case "b": this.parseBend(); break;
    case "s": this.parseTie(); break;
    case "t": this.parseTie(); break;
    case "h": this.parseTie(); break;
    case "p": this.parseTie(); break;
    case "v": this.parseFretVibrato(); break;
    case "V": this.parseFretVibrato(); break;
    default: this.parseError("Unexpected token: " + this.parse_state.value);
  }
}

/**
 * Parse dashes.
 * @private
 */
Vex.Flow.VexTab.prototype.parseDash = function() {
  // Dashes break us out of bend contexts
  this.parse_state.inside_bend = false;

  // Dashes are not alloed on strings
  if (this.parse_state.expecting_string)
    this.parseError("No dashes on strings: " + this.parse_state.str);
}

/**
 * Parse vibratos.
 * @private
 */
Vex.Flow.VexTab.prototype.parseVibrato = function() {
  var harsh = false;

  // Capital V means harsh vibrato.
  if (this.parse_state.value == "V") harsh = true;

  var position = this.parse_state.position_index;
  if (this.parse_state.inside_bend) {
    // If we're inside a bend we associate the vibrato with the first
    // fret of the bend
    var count = this.parse_state.bends[this.parse_state.bends.length - 1].count;
    position -= count;
  }

  this.parse_state.vibratos.push({position: position, harsh: harsh});
}

/**
 * Parse vibratos inside a fret context.
 * @private
 */
Vex.Flow.VexTab.prototype.parseFretVibrato = function() {
  this.parseVibrato();
  this.getNextToken();
  switch(this.parse_state.value) {
    case "-": this.parseDash(); break;
    case "s": this.parseTie(); break;
    case "h": this.parseTie(); break;
    case "p": this.parseTie(); break;
    case "t": this.parseTie(); break;
    case "/": this.parseSlash(); break;
    default: this.parseError("Unexpected token: " + this.parse_state.value);
  }
}

/**
 * Parse string separator "/".
 * @private
 */
Vex.Flow.VexTab.prototype.parseSlash = function(str) {
  this.parse_state.inside_bend = false;
  this.parse_state.expecting_string = true;

  // Next token must be a string number
  this.getNextToken();
  this.parseString();
}

/**
 * Parse string number.
 * @private
 */
Vex.Flow.VexTab.prototype.parseString = function() {
  var str = this.parse_state.value;
  if (this.parse_state.positions.length == 0)
    this.parseError("String without frets: " + str);

  // Associate string with all positions in this note-group.
  for (var i = 0; i < this.parse_state.positions.length; ++i) {
    this.parse_state.positions[i][0].str = str;
  }
}

/**
 * Parse ties, hammerons, slides, etc.
 * @private
 */
Vex.Flow.VexTab.prototype.parseTie = function() {
  this.parse_state.inside_bend = false;
  if (this.parse_state.expecting_string)
    this.parseError("Unexpected token on string: " + this.parse_state.str);

  this.parse_state.ties.push({
    position: this.parse_state.position_index,
    index: this.parse_state.chord_index + 1,
    effect: this.parse_state.value.toUpperCase()
  });

  // Next token has to be a fret number.
  this.getNextToken();
  this.parseFret();
}

/**
 * Parse ties, hammerons, slides, etc. in chords.
 * @private
 */
Vex.Flow.VexTab.prototype.parseChordTie = function() {
  this.parse_state.chord_ties.push({
    position: this.parse_state.position_index,
    effect: this.parse_state.value.toUpperCase()
  });

  // Next token has to be a fret number.
  this.getNextToken();
  if (this.parse_state.value != "(")
    this.parseError("Expecting ( after chord ties/slides");
  this.parseOpenChord();
}

/**
 * Parse bends outside a chord context.
 * @private
 */
Vex.Flow.VexTab.prototype.parseBend = function() {
  if (this.parse_state.expecting_string)
    this.parseError("Unexpected token on string: " + this.parse_state.str);

  if (this.parse_state.inside_bend) {
    var this_bend = this.parse_state.bends.length - 1;
    this.parse_state.bends[this_bend].count++;
  } else {
    this.parse_state.inside_bend = true;
    this.parse_state.bends.push(
        { position: this.parse_state.position_index, count: 1, index: 0 });
  }

  // Next token must be a fret.
  this.getNextToken();
  this.parseFret();
}

/**
 * Generate VexFlow elements from current parser state. The elements can
 * be retrieved with #getElements.
 *
 * @private
 */
Vex.Flow.VexTab.prototype.genElements = function() {
  // If there's no Tab Stave, generate one.
  if (this.state.current_stave == -1) this.genTabStave();

  // Start by building notes.
  var positions = this.parse_state.positions;
  var durations = this.parse_state.durations;
  var tabnotes = [];
  var notes = [];

  // Associate notes with relevant positions.
  for (var i = 0; i < positions.length; ++i) {
    var position = positions[i];
    var duration = durations[i];

    var tabnote = new Vex.Flow.TabNote(
        {positions: position, duration: duration});
    tabnotes.push({note: tabnote, persist: true});

    if (this.state.has_notation) {
      var keys = [];
      var accidentals = [];

      for (var j = 0; j < position.length; ++j) {
        var notefret = position[j];
        var spec = this.tuning.getNoteForFret(notefret.fret, notefret.str);

        var props = Vex.Flow.keyProperties(spec);
        accidentals.push(props.accidental);
        keys.push(spec);
      }

      var note = new Vex.Flow.StaveNote({ keys: keys, duration: duration });

      for (var j = 0; j < accidentals.length; ++j) {
        var acc = accidentals[j];

        if (acc) {
          note.addAccidental(j, new Vex.Flow.Accidental(accidentals[j]));
        }
      }

      notes.push(note);
    }
  }

  // Add bends.
  var bends = this.parse_state.bends;
  for (var i = 0; i < bends.length; ++i) {
      var bend = bends[i];
      var from_fret = parseInt(positions[bend.position][bend.index].fret);
      var to_fret;

      // Bent notes must not persist in position list.
      if (bends[i].to_fret) {
      to_fret = bends[i].to_fret;
      } else {
      to_fret = parseInt(positions[bend.position + 1][bend.index].fret);

      for (var count = 1; count <= bend.count; ++count) {
          tabnotes[bend.position + count].persist = false;
      }
      }

      var release = false;
      if (bend.count > 1) release = true;

      var bent_note = tabnotes[bend.position].note;

      // Calculate bend amount and annotate appropriately.
      switch (to_fret - from_fret) {
      case 1: bent_note.addModifier(
                  new Vex.Flow.Bend("1/2", release), bend.index); break;
      case 2: bent_note.addModifier(
                  new Vex.Flow.Bend("Full", release), bend.index); break;
      case 3: bent_note.addModifier(
                  new Vex.Flow.Bend("1 1/2", release), bend.index); break;
      case 4: bent_note.addModifier(
                  new Vex.Flow.Bend("2 Steps", release), bend.index); break;
      default: bent_note.addModifier(
                  new Vex.Flow.Bend("Bend to " + to_fret, release), bend.index);
      }
  }

  function persistentPosition(pos) {
    for (var i = pos; i >= 0; --i) {
      if (tabnotes[i].persist == true) return i;
    }
    throw new Vex.RERR("GenError", "Invalid position: " + pos);
  }

  // Add vibratos
  var vibratos = this.parse_state.vibratos;
  for (var i = 0; i < vibratos.length; ++i) {
    var vibrato = vibratos[i];
    tabnotes[vibrato.position].note.addModifier(new Vex.Flow.Vibrato().
      setHarsh(vibrato.harsh));
  }

  // Add annotations
  var annotations = this.parse_state.annotations;
  for (var i = 0; i < annotations.length; ++i) {
    var annotation = annotations[i];
    tabnotes[annotation.position].note.addModifier(
        new Vex.Flow.Annotation(annotation.text));
  }

  // Add ties
  var ties = this.parse_state.ties;
  for (var i = 0; i < ties.length; ++i) {
    var tie = ties[i];
    var effect = null;
    var pos = persistentPosition(tie.position);

    if (this.state.has_tablature) {
      if (tie.effect == "S") {
        // Slides are a special case.
        effect = new Vex.Flow.TabSlide({
          first_note: tabnotes[pos].note,
          last_note: tabnotes[tie.position + 1].note
        });
      } else {
        effect = new Vex.Flow.TabTie({
          first_note: tabnotes[pos].note,
          last_note: tabnotes[tie.position + 1].note
        }, tie.effect);
      }
    }

    if (this.state.has_notation) {
      this.elements.ties[this.state.current_stave].push(
          new Vex.Flow.StaveTie({
            first_note: notes[pos],
            last_note: notes[tie.position + 1]
          }));
    }
    if (effect) this.elements.ties[this.state.current_stave].push(effect);

  }

  // Add chord ties
  var chord_ties = this.parse_state.chord_ties;
  for (var i = 0; i < chord_ties.length; ++i) {
    var tie = chord_ties[i];
    var effect;
    var pos = persistentPosition(tie.position);

    // Organize indices by string number.
    var indices = [];
    for (var p = 0; p < positions[pos].length; ++p) {
      var position = positions[pos][p];
      indices[position.str] = {from: p};
    }
    for (var p = 0; p < positions[tie.position + 1].length; ++p) {
      var position = positions[tie.position + 1][p];
      if (!indices[position.str]) indices[position.str] = {};
      indices[position.str].to = p;
    }

    // Build indices for the ties.
    var first_indices = [];
    var last_indices = [];

    for (var j = 0; j < indices.length; ++j) {
      var index = indices[j];
      if (!index) continue;

      // Ensure that we only have tie notes that have both
      // and from and to fret.
      if (typeof(index.from) == "undefined" ||
          typeof(index.to) == "undefined") continue;

      first_indices.push(index.from);
      last_indices.push(index.to);
    }

    if (this.state.has_tablature) {
      if (tie.effect == "S") {
        // Slides are a special case.
        effect = new Vex.Flow.TabSlide({
          first_note: tabnotes[pos].note,
          last_note: tabnotes[tie.position + 1].note,
          first_indices: first_indices,
          last_indices: last_indices
        });
      } else {
        effect = new Vex.Flow.TabTie({
          first_note: tabnotes[pos].note,
          last_note: tabnotes[tie.position + 1].note,
          first_indices: first_indices,
          last_indices: last_indices
        }, tie.effect);
      }
    }

    if (this.state.has_notation) {
      this.elements.ties[this.state.current_stave].push(
          new Vex.Flow.StaveTie({
            first_note: notes[pos],
            last_note: notes[tie.position + 1],
            first_indices: first_indices,
            last_indices: last_indices
          }));
    }

    this.elements.ties[this.state.current_stave].push(effect);
  }

  // Push tabnotes, skipping non-persistent notes.
  for (var i = 0; i < tabnotes.length; ++i) {
    var note = tabnotes[i];
    if (note.persist) {
      this.elements.tabnotes[this.state.current_stave].push(note.note);
    } else {
      this.elements.tabnotes[this.state.current_stave].push(
          new Vex.Flow.GhostNote(this.state.current_duration));
    }
  }

  // Push notes, skipping non-persistent notes.
  for (var i = 0; i < notes.length; ++i) {
    var note = notes[i];
    this.elements.notes[this.state.current_stave].push(note);
  }
}

/**
 * Generate the tab stave and add it to the element list.
 * @private
 */
Vex.Flow.VexTab.prototype.genTabStave = function(params) {
  var notation = false;
  var tablature = true;
  var clef = "treble";
  if (params) notation = params.notation;
  if (params) tablature = params.tablature;
  if (params) clef = params.clef;

  var notestave = notation ?
    new Vex.Flow.Stave(
        20, this.height, 380).addClef(clef).setNoteStartX(40) :
    null;

  var tabstave = tablature ?
    new Vex.Flow.TabStave(20,
      notation ? notestave.getHeight() + this.height : this.height, 380).
    addTabGlyph().setNoteStartX(40) : null;

  this.elements.staves.push({tab: tabstave, note: notestave});
  this.height += (tablature ? tabstave.getHeight() : null) +
    (notation ? notestave.getHeight() : null);

  this.state.current_stave++;
  this.state.has_notation = notation;
  this.state.has_tablature = tablature;
  this.elements.tabnotes[this.state.current_stave] = [];
  this.elements.notes[this.state.current_stave] = [];
  this.elements.ties[this.state.current_stave] = [];
}

Vex.Flow.VexTab.prototype.parseOpenBeam = function() {
  if (this.state.beam_start != null)
    this.parseError("Beam already open: [");

  this.state.beam_start = this.elements.notes[this.state.current_stave].length;
}

Vex.Flow.VexTab.prototype.parseCloseBeam = function() {
  if (this.state.beam_start == null)
    this.parseError("Can't close beam without openeing: ]");

  var beam_end = this.elements.notes[this.state.current_stave].length;

  if ((beam_end - this.state.beam_start) < 2)
    this.parseError("Must have at least two notes in a beam.");

  var beam_notes = [];

  for (var i = this.state.beam_start; i < beam_end; ++i) {
    beam_notes.push(this.elements.notes[this.state.current_stave][i]);
  }

  this.elements.beams.push(new Vex.Flow.Beam(beam_notes));
  this.state.beam_start = null;
}

/**
 * Generate bar line and add it to the element list.
 * @private
 */
Vex.Flow.VexTab.prototype.genBar = function() {
  // If there's no Tab Stave, generate one.
  if (this.state.current_stave == -1) this.genTabStave();
  this.elements.tabnotes[this.state.current_stave].push(new Vex.Flow.BarNote());
  this.elements.notes[this.state.current_stave].push(new Vex.Flow.BarNote());
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<problems>
  <problem>
    <file>Npe.java</file>
    <line>15</line>
    <description>Argument 'o' might be null</description>
  </problem>
</problems>

redpajama_set_name: RedPajamaGithub


text:
package co.realtime.plugins.android.cordovapush;

import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;

import ibt.ortc.api.Ortc;
import ibt.ortc.extensibility.OnConnected;
import ibt.ortc.extensibility.OnDisconnected;
import ibt.ortc.extensibility.OnException;
import ibt.ortc.extensibility.OnMessage;
import ibt.ortc.extensibility.OnReconnected;
import ibt.ortc.extensibility.OnReconnecting;
import ibt.ortc.extensibility.OnSubscribed;
import ibt.ortc.extensibility.OnUnsubscribed;
import ibt.ortc.extensibility.OrtcClient;
import ibt.ortc.extensibility.OrtcFactory;

public class OrtcPushPlugin extends CordovaPlugin {

    public static final String TAG = "ORTCPushPlugin";
    public static final String ACTION_CHECK_NOTIFICATIONS = "checkForNotifications";
    public static final String ACTION_SET_ICON = "setApplicationIconBadgeNumber";
    public static final String ACTION_LOG = "log";
    public static final String ACTION_CONNECT = "connect";
    public static final String ACTION_DISCONNECT = "disconnect";
    public static final String ACTION_SUBSCRIBE = "subscribe";
    public static final String ACTION_UNSUBSCRIBE = "unsubscribe";
    public static final String ACTION_CANCEL_NOTIFICATIONS = "cancelAllLocalNotifications";
    public static final String ACTION_SEND_MESSAGE = "send";
    public static final String ACTION_SET_DIALOG_TIME_RANGE = "setDialogTimeRange";
    private OrtcClient client;
    private CallbackContext callback = null;
    private static CordovaWebView gWebView;
    private static Bundle gCachedExtras = null;
    private static boolean gForeground = false;

    @Override
    public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        gForeground = true;
        try {
            Ortc ortc = new Ortc();

            OrtcFactory factory;

            factory = ortc.loadOrtcFactory("IbtRealtimeSJ");

            client = factory.createClient();

            client.setHeartbeatActive(true);

            client.onConnected = new OnConnected() {
                @Override
                public void run(OrtcClient ortcClient) {
                    callback.success();
                }
            };

            client.onDisconnected = new OnDisconnected() {
                @Override
                public void run(OrtcClient ortcClient) {
                    Log.i(TAG,"Disconnected" );
                }
            };

            client.onUnsubscribed = new OnUnsubscribed() {
                @Override
                public void run(OrtcClient ortcClient, String channel) {
                    Log.i(TAG,"Unsubscribed from:" + channel);
                    callback.success();
                }
            };

            client.onSubscribed = new OnSubscribed() {
                @Override
                public void run(OrtcClient ortcClient, String s) {
                    callback.success();
                }
            };

            client.onReconnected = new OnReconnected(){
                @Override
                public void run(OrtcClient sender) {
                    Log.i(TAG, "Reconnected");
                }
            };
            client.onReconnecting = new OnReconnecting(){
                @Override
                public void run(OrtcClient sender) {
                    Log.i(TAG, "Reconnecting");
                }
            };

            client.onException = new OnException() {
                @Override
                public void run(OrtcClient ortcClient, Exception e) {
                    Log.i(TAG,e.toString());
                }
            };

        } catch (Exception e) {
            Log.e(TAG,e.toString());
        }

    }

    @Override
    public void onPause(boolean multitasking) {
        super.onPause(multitasking);
        gForeground = false;
    }

    @Override
    public void onResume(boolean multitasking) {
        super.onResume(multitasking);
        gForeground = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        gForeground = false;
        gWebView = null;
    }

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {

        callback = callbackContext;
        gWebView = this.webView;

        try {
            if (ACTION_LOG.equals(action)) {
                Log.i(TAG,args.get(0).toString());
                callbackContext.success();
                return true;
            }
            else if(ACTION_CONNECT.equals(action)){
                JSONObject arg_object = args.getJSONObject(0);
                client.setClusterUrl(arg_object.getString("url"));
                client.setConnectionMetadata(arg_object.getString("metadata"));
                client.setGoogleProjectId(arg_object.getString("projectId"));
                client.setApplicationContext(this.cordova.getActivity().getApplicationContext());
                client.connect(arg_object.getString("appkey"),arg_object.getString("token"));

                return true;
            }
            else if(ACTION_DISCONNECT.equals(action)){
                client.disconnect();
                return true;
            }
            else if(ACTION_SUBSCRIBE.equals(action)){
                JSONObject arg_object = args.getJSONObject(0);
                String channel = arg_object.getString("channel");
                client.subscribeWithNotifications(channel, true, new OnMessage() {
                    @Override
                    public void run(OrtcClient ortcClient, final String channel, final String message) {
                        cordova.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i(TAG, "Received message:" + message + " from channel: " + channel);

                            }
                        });

                    }
                });
                return true;
            }
            else if(ACTION_UNSUBSCRIBE.equals(action)){
                JSONObject arg_object = args.getJSONObject(0);
                String channel = arg_object.getString("channel");
                client.unsubscribe(channel);
                return true;
            }
            else if(ACTION_CANCEL_NOTIFICATIONS.equals(action)){
                final NotificationManager notificationManager = (NotificationManager) this.cordova.getActivity().getSystemService(this.cordova.getActivity().NOTIFICATION_SERVICE);
                notificationManager.cancelAll();
                callbackContext.success();
                return true;
            }
            else if(ACTION_SEND_MESSAGE.equals(action)){
                JSONObject arg_object = args.getJSONObject(0);
                String channel = arg_object.getString("channel");
                String message = arg_object.getString("message");
                client.send(channel,message);
                return true;
            }
            else if(ACTION_CHECK_NOTIFICATIONS.equals(action)){
                if ( gCachedExtras != null) {
                    Log.v(TAG, "sending cached extras");
                    sendExtras(gCachedExtras);
                    gCachedExtras = null;
                }
                callbackContext.success();
                return true;
            }
            else if(ACTION_SET_ICON.equals(action)){
                Log.i(TAG,"Set icon badge number not implemented in Android");
                callbackContext.success();
                return true;
            }
            else if(ACTION_SET_DIALOG_TIME_RANGE.equals(action)){
                setAlertDialogTimeRange(webView.getContext(), args.getString(0), args.getString(1));
                callbackContext.success();
                return true;
            }
            callbackContext.error("Invalid action");
            return false;
        } catch(Exception e) {
            System.err.println("Exception: " + e.getMessage());
            callbackContext.error(e.getMessage());
            return false;
        }
    }

    private void setAlertDialogTimeRange(Context context, String timeFrom, String timeTo)
    {
        SimpleDateFormat inputParser = new SimpleDateFormat("HH:mm", Locale.US);
        try {
            OutputStream outputStream = context.openFileOutput("config.txt", Context.MODE_PRIVATE);
            outputStream.write((timeFrom + "\r\n").getBytes());
            outputStream.write((timeTo + "\r\n").getBytes());
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean isInForeground()
    {
        return gForeground;
    }

    public static boolean isActive()
    {
        return gWebView != null;
    }

    public static void sendJavascript(JSONObject json) {
        try {
            String send = "";
            String channel = json.getString("channel");
            json.remove("channel");
            try {
                new JSONObject(json.getString("payload"));
                send = String.format("window.plugins.OrtcPushPlugin.receiveRemoteNotification('%s',%s);",channel,json.getString("payload"));
            } catch (JSONException ex) {
                send = String.format("window.plugins.OrtcPushPlugin.receiveRemoteNotification('%s','%s');",channel,json.getString("payload"));
            }

            Log.v(TAG, "sendJavascript: " + send);

            if (gWebView != null) {
                gWebView.sendJavascript(send);
            }
        } catch (Exception e) {
            Log.e(TAG, "sendJavascript: JSON exception");
        }

    }

    public static void sendExtras(Bundle extras)
    {
        if (extras != null) {
            if (gWebView != null) {
                sendJavascript(convertBundleToJson(extras));
            } else {
                Log.v(TAG, "sendExtras: caching extras to send at a later time.");
                gCachedExtras = extras;
            }
        }
    }

    private static JSONObject convertBundleToJson(Bundle extras)
    {
        try
        {
            JSONObject json = new JSONObject();

            if (extras.containsKey("P")){
                json = new JSONObject();
                json.put("payload",extras.getString("P"));
            }
            else{
                String message = extras.getString("M");
                String newMsg = message.substring(message.indexOf("_", message.indexOf("_") + 1)+1);
                json.put("payload",newMsg);
            }

            if (extras.containsKey("C")){
                json.put("channel", extras.getString("C"));
            }
            //Iterator<String> it = extras.keySet().iterator();
            /*while (it.hasNext())
            {
                String key = it.next();
                Object value = extras.get(key);

                if (key.equals("foreground"))
                {
                    json.put(key, extras.getBoolean("foreground"));
                }
                else if (key.equals("C")){
                    json.put("channel", extras.getString("C"));
                }
                if (key.equals("M")) {
                    String message = extras.getString("M");
                    String newMsg = null;
                    String [] parts = message.split("_");
                    if(parts.length > 1){
                        try {
                            JSONObject jsonObject = new JSONObject(parts[parts.length-1]);
                            newMsg = jsonObject.getString("message");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    else{
                        newMsg = message;
                    }
                    //json.put("message", newMsg);
                }
                else if (key.equals("P")){
                    json.put("payload",extras.getString("P"));
                    *//*String payloadString = value.toString();
                    if (payloadString.startsWith("{")) {
                        try {
                             JSONObject payloadJsonObject = new JSONObject(payloadString);
                             Iterator payloadIt = payloadJsonObject.keys();
                             while(payloadIt.hasNext()){
                                   String keyPayload = (String) payloadIt.next();
                                   Object valuePaylod = payloadJsonObject.get(keyPayload);
                                   json.put(keyPayload,valuePaylod);
                                }
                             }
                             catch (Exception e) {
                                   json.put(key, value);
                             }
                     }*//*

                }

            }*/

            Log.v(TAG, "extrasToJSON: " + json.toString());

            return json;
        }
        catch( JSONException e)
        {
            Log.e(TAG, "extrasToJSON: JSON exception");
            return null;
        }

    }

}


text:
package com.hackerearth.codemonk.disjointset;

import java.io.*;
import java.util.StringTokenizer;

import static java.lang.Integer.parseInt;

public class CityAndFiremanVincent
{
    private static BufferedReader reader;
    private static StringTokenizer tokenizer;

    private static int[] parent;
    private static int[] size;
    private static int count;

    private static String next() throws IOException
    {
        while (!tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(
                    reader.readLine());
        }
        return tokenizer.nextToken();
    }

    private static int nextInt() throws IOException
    {
        return parseInt(next());
    }

    private static long nextLong() throws IOException
    {
        return Long.parseLong(next());
    }

    public static void main(String[] args) throws IOException
    {
        reader = new BufferedReader(new InputStreamReader(System.in));
        tokenizer = new StringTokenizer("");
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

        int N = nextInt();
        int K = nextInt();

        count = N;
        parent = new int[N];
        size = new int[N];
        for (int i = 0; i < N; i++) {
            parent[i] = i;
            size[i] = 1;
        }

        int[] E = new int[N];
        for (int n = 0; n < N; n++) {
            E[n] = nextInt();
        }

        for (int k = 0; k < K; k++) {
            int p = nextInt();
            int q = nextInt();
            union(p - 1, q - 1);
        }
        reader.close();
        pw.close();

    }

    public static void union(int p, int q)
    {
        int rootP = find(p);
        int rootQ = find(q);
        if (rootP == rootQ) {
            return;
        }

        if (size[rootP] < size[rootQ]) {
            parent[rootP] = rootQ;
            size[rootQ] += size[rootP];
        } else {
            parent[rootQ] = rootP;
            size[rootP] += size[rootQ];
        }
        count--;
    }

    public static int find(int p)
    {
        while (p != parent[p]) {
            p = parent[p];
        }
        return p;
    }

}


text:
 * Mature map library
 * Strong cross browser and mobile suppport
 * Based on image tiles and standard tile protocols
 * Excellent [API documentation](http://leafletjs.com/reference.html)
 * Great [plugins](http://leafletjs.com/plugins.html)


text:
@implementation UITableViewCell (BaseKit)

////////////////////////////////////////////////////////////////////////////////////////////////////
+ (id)cellForTableView:(UITableView *)tableView {
    NSString *cellID = [self cellIdentifier];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {
        UITableViewCellStyle cellStyle = [self cellStyle];
        cell = [[self alloc] initWithStyle:cellStyle reuseIdentifier:cellID];
    }

    return cell;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
+ (id)cellForTableView:(UITableView *)tableView fromNib:(UINib *)nib {
    NSString *cellID = [self cellIdentifier];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {
        NSArray *nibObjects = [nib instantiateWithOwner:nil options:nil];
        cell = [nibObjects objectAtIndex:0];
    }

    return cell;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
+ (UITableViewCellStyle)cellStyle {
    return UITableViewCellStyleDefault;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
+ (NSString *)cellIdentifier {
    return NSStringFromClass([self class]);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
+ (UINib *)nib {
    NSBundle *classBundle = [NSBundle bundleForClass:[self class]];
    NSString *nibName = [self nibName];

    return [UINib nibWithNibName:nibName bundle:classBundle];
}

////////////////////////////////////////////////////////////////////////////////////////////////////
+ (NSString *)nibName {
    return [self cellIdentifier];
}

@end


text:
<?php
namespace ZenOAuth2;

class GoogleClient extends Client{

	public $host = 'https://www.googleapis.com/';

	public function parseResponse($response){
		if ($this->format === 'json' && $this->decode_json) {
			$json = json_decode($response);		//	解析成对象而不是关联数组
			if ($json !== null)
				return $json;
		}
		return $response;
	}

	protected function _paramsFilter(&$params){
		$params['key'] = $this->access_token;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 1: 119 (1957)

#### Original name
Meliola villaresiana Hansf.

### Remarks
null


text:
/**************************************************************************/
/*                                                                        */
/* IBM eServer i/[Series Virtual Ethernet Device Driver                   */
/* Copyright (C) 2003 IBM Corp.                                           */
/*  Dave Larson (larson1@us.ibm.com)                                      */
/*  Santiago Leon (santil@us.ibm.com)                                     */
/*                                                                        */
/*  This program is free software; you can redistribute it and/or modify  */
/*  it under the terms of the GNU General Public License as published by  */
/*  the Free Software Foundation; either version 2 of the License, or     */
/*  (at your option) any later version.                                   */
/*                                                                        */
/*  This program is distributed in the hope that it will be useful,       */
/*  but WITHOUT ANY WARRANTY; without even the implied warranty of        */
/*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         */
/*  GNU General Public License for more details.                          */
/*                                                                        */
/*  You should have received a copy of the GNU General Public License     */
/*  along with this program; if not, write to the Free Software           */
/*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  */
/*                                                                   USA  */
/*                                                                        */
/**************************************************************************/

#ifndef _IBMVETH_H
#define _IBMVETH_H

/* constants for H_MULTICAST_CTRL */
#define IbmVethMcastReceptionModifyBit     0x80000UL
#define IbmVethMcastReceptionEnableBit     0x20000UL
#define IbmVethMcastFilterModifyBit        0x40000UL
#define IbmVethMcastFilterEnableBit        0x10000UL

#define IbmVethMcastEnableRecv       (IbmVethMcastReceptionModifyBit | IbmVethMcastReceptionEnableBit)
#define IbmVethMcastDisableRecv      (IbmVethMcastReceptionModifyBit)
#define IbmVethMcastEnableFiltering  (IbmVethMcastFilterModifyBit | IbmVethMcastFilterEnableBit)
#define IbmVethMcastDisableFiltering (IbmVethMcastFilterModifyBit)
#define IbmVethMcastAddFilter        0x1UL
#define IbmVethMcastRemoveFilter     0x2UL
#define IbmVethMcastClearFilterTable 0x3UL

#define IBMVETH_ILLAN_PADDED_PKT_CSUM	0x0000000000002000UL
#define IBMVETH_ILLAN_TRUNK_PRI_MASK	0x0000000000000F00UL
#define IBMVETH_ILLAN_IPV6_TCP_CSUM		0x0000000000000004UL
#define IBMVETH_ILLAN_IPV4_TCP_CSUM		0x0000000000000002UL
#define IBMVETH_ILLAN_ACTIVE_TRUNK		0x0000000000000001UL

/* hcall macros */
#define h_register_logical_lan(ua, buflst, rxq, fltlst, mac) \
  plpar_hcall_norets(H_REGISTER_LOGICAL_LAN, ua, buflst, rxq, fltlst, mac)

#define h_free_logical_lan(ua) \
  plpar_hcall_norets(H_FREE_LOGICAL_LAN, ua)

#define h_add_logical_lan_buffer(ua, buf) \
  plpar_hcall_norets(H_ADD_LOGICAL_LAN_BUFFER, ua, buf)

static inline long h_send_logical_lan(unsigned long unit_address,
		unsigned long desc1, unsigned long desc2, unsigned long desc3,
		unsigned long desc4, unsigned long desc5, unsigned long desc6,
		unsigned long corellator_in, unsigned long *corellator_out)
{
	long rc;
	unsigned long retbuf[PLPAR_HCALL9_BUFSIZE];

	rc = plpar_hcall9(H_SEND_LOGICAL_LAN, retbuf, unit_address, desc1,
			desc2, desc3, desc4, desc5, desc6, corellator_in);

	*corellator_out = retbuf[0];

	return rc;
}

static inline long h_illan_attributes(unsigned long unit_address,
				      unsigned long reset_mask, unsigned long set_mask,
				      unsigned long *ret_attributes)
{
	long rc;
	unsigned long retbuf[PLPAR_HCALL_BUFSIZE];

	rc = plpar_hcall(H_ILLAN_ATTRIBUTES, retbuf, unit_address,
			 reset_mask, set_mask);

	*ret_attributes = retbuf[0];

	return rc;
}

#define h_multicast_ctrl(ua, cmd, mac) \
  plpar_hcall_norets(H_MULTICAST_CTRL, ua, cmd, mac)

#define h_change_logical_lan_mac(ua, mac) \
  plpar_hcall_norets(H_CHANGE_LOGICAL_LAN_MAC, ua, mac)

#define IbmVethNumBufferPools 5
#define IBMVETH_IO_ENTITLEMENT_DEFAULT 4243456 /* MTU of 1500 needs 4.2Mb */
#define IBMVETH_BUFF_OH 22 /* Overhead: 14 ethernet header + 8 opaque handle */
#define IBMVETH_MAX_MTU 68
#define IBMVETH_MAX_POOL_COUNT 4096
#define IBMVETH_BUFF_LIST_SIZE 4096
#define IBMVETH_FILT_LIST_SIZE 4096
#define IBMVETH_MAX_BUF_SIZE (1024 * 128)

static int pool_size[] = { 512, 1024 * 2, 1024 * 16, 1024 * 32, 1024 * 64 };
static int pool_count[] = { 256, 768, 256, 256, 256 };
static int pool_active[] = { 1, 1, 0, 0, 0};

#define IBM_VETH_INVALID_MAP ((u16)0xffff)

struct ibmveth_buff_pool {
    u32 size;
    u32 index;
    u32 buff_size;
    u32 threshold;
    atomic_t available;
    u32 consumer_index;
    u32 producer_index;
    u16 *free_map;
    dma_addr_t *dma_addr;
    struct sk_buff **skbuff;
    int active;
    struct kobject kobj;
};

struct ibmveth_rx_q {
    u64        index;
    u64        num_slots;
    u64        toggle;
    dma_addr_t queue_dma;
    u32        queue_len;
    struct ibmveth_rx_q_entry *queue_addr;
};

struct ibmveth_adapter {
    struct vio_dev *vdev;
    struct net_device *netdev;
    struct napi_struct napi;
    struct net_device_stats stats;
    unsigned int mcastFilterSize;
    unsigned long mac_addr;
    void * buffer_list_addr;
    void * filter_list_addr;
    dma_addr_t buffer_list_dma;
    dma_addr_t filter_list_dma;
    struct ibmveth_buff_pool rx_buff_pool[IbmVethNumBufferPools];
    struct ibmveth_rx_q rx_queue;
    int pool_config;
    int rx_csum;
    void *bounce_buffer;
    dma_addr_t bounce_buffer_dma;

    /* adapter specific stats */
    u64 replenish_task_cycles;
    u64 replenish_no_mem;
    u64 replenish_add_buff_failure;
    u64 replenish_add_buff_success;
    u64 rx_invalid_buffer;
    u64 rx_no_buffer;
    u64 tx_map_failed;
    u64 tx_send_failed;
    spinlock_t stats_lock;
};

struct ibmveth_buf_desc_fields {
	u32 flags_len;
#define IBMVETH_BUF_VALID	0x80000000
#define IBMVETH_BUF_TOGGLE	0x40000000
#define IBMVETH_BUF_NO_CSUM	0x02000000
#define IBMVETH_BUF_CSUM_GOOD	0x01000000
#define IBMVETH_BUF_LEN_MASK	0x00FFFFFF
	u32 address;
};

union ibmveth_buf_desc {
    u64 desc;
    struct ibmveth_buf_desc_fields fields;
};

struct ibmveth_rx_q_entry {
	u32 flags_off;
#define IBMVETH_RXQ_TOGGLE		0x80000000
#define IBMVETH_RXQ_TOGGLE_SHIFT	31
#define IBMVETH_RXQ_VALID		0x40000000
#define IBMVETH_RXQ_NO_CSUM		0x02000000
#define IBMVETH_RXQ_CSUM_GOOD		0x01000000
#define IBMVETH_RXQ_OFF_MASK		0x0000FFFF

	u32 length;
	u64 correlator;
};

#endif /* _IBMVETH_H */


text:
namespace phoenix {

static void CheckItem_toggle(GtkCheckMenuItem* gtkCheckMenuItem, CheckItem* self) {
  self->state.checked = gtk_check_menu_item_get_active(gtkCheckMenuItem);
  if(!self->p.locked && self->onToggle) self->onToggle();
}

void pCheckItem::setChecked(bool checked) {
  locked = true;
  gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(widget), checked);
  locked = false;
}

void pCheckItem::setText(string text) {
  gtk_menu_item_set_label(GTK_MENU_ITEM(widget), mnemonic(text));
}

void pCheckItem::constructor() {
  widget = gtk_check_menu_item_new_with_mnemonic("");
  setChecked(checkItem.state.checked);
  setText(checkItem.state.text);
  g_signal_connect(G_OBJECT(widget), "toggled", G_CALLBACK(CheckItem_toggle), (gpointer)&checkItem);
}

void pCheckItem::destructor() {
  gtk_widget_destroy(widget);
}

void pCheckItem::orphan() {
  destructor();
  constructor();
}

}


text:
package com.cognizant.devops.engines.platformengine.modules.correlation;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.cognizant.devops.engines.platformengine.message.core.EngineStatusLogger;
import com.cognizant.devops.engines.platformengine.modules.correlation.model.Correlation;
import com.cognizant.devops.platformcommons.config.ApplicationConfigProvider;
import com.cognizant.devops.platformcommons.config.CorrelationConfig;
import com.cognizant.devops.platformcommons.constants.EngineConstants;
import com.cognizant.devops.platformcommons.constants.PlatformServiceConstants;
import com.cognizant.devops.platformcommons.core.enums.FileDetailsEnum;
import com.cognizant.devops.platformcommons.dal.neo4j.GraphDBHandler;
import com.cognizant.devops.platformcommons.dal.neo4j.GraphResponse;
import com.cognizant.devops.platformcommons.exception.InsightsCustomException;
import com.cognizant.devops.platformdal.correlationConfig.CorrelationConfigDAL;
import com.cognizant.devops.platformdal.correlationConfig.CorrelationConfiguration;
import com.cognizant.devops.platformdal.filemanagement.InsightsConfigFiles;
import com.cognizant.devops.platformdal.filemanagement.InsightsConfigFilesDAL;
import com.cognizant.devops.platformdal.relationshipconfig.RelationshipConfiguration;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;

/**
 * @author Vishal Ganjare (vganjare)
 */
public class CorrelationExecutor {

	public static final String RESULT = "results";
	private static final Logger log = LogManager.getLogger(CorrelationExecutor.class);
	private long maxCorrelationTime;
	private long lastCorrelationTime;
	private long currentCorrelationTime;
	private int dataBatchSize;
	InsightsConfigFilesDAL configFilesDAL = new InsightsConfigFilesDAL();
	private Map<String,String> loggingInfo = new ConcurrentHashMap<>();
	private String jobName = "";

	/**
	 * Correlation execution starting point.
	 */
	public void execute(String jobName) {
		loggingInfo.put(EngineConstants.EXECID, String.valueOf(System.currentTimeMillis()));
		this.jobName = jobName;
		CorrelationConfig correlationConfig = ApplicationConfigProvider.getInstance().getCorrelations();
		if (correlationConfig != null) {
			loadCorrelationConfiguration(correlationConfig);
			List<CorrelationConfiguration> correlations = getRelation();
			if (correlations.isEmpty()) {
				// No information in DB fetch correlation detail from file
				loadCorrelationConfigfromJson(correlations);
			}
			if (correlations.isEmpty()) {
				log.error(" execId={} No Correlation Configuration found in DB as well as in correlation.json",loggingInfo.get(EngineConstants.EXECID));
				return;
			}
			for (CorrelationConfiguration correlation : correlations) {
				loggingInfo.put(EngineConstants.SOURCE_TOOL, String.valueOf(correlation.getSourceToolName()));
				loggingInfo.put(EngineConstants.DESTINATION_TOOL, String.valueOf(correlation.getDestinationToolName()));
				loggingInfo.put(EngineConstants.CORRELATION_NAME, String.valueOf(correlation.getRelationName()));
				log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} Correlation started for {}",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0, correlation.getRelationName());
				if (correlation.isSelfRelation()) {
					continue;
				}
				updateNodesMissingCorrelationFields(correlation);

				loadDestinationDataAndExecuteCorrelation(correlation);

				removeRawLabel(correlation);
				log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} Correlation end for{}",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0, correlation.getRelationName());
			}
		} else {
			log.error(" execId={} correlationName={} sourceTool={} destinationTool={} Correlation configuration is not provided in server-config.json.",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL));
		}
	}

	private void loadDestinationDataAndExecuteCorrelation(CorrelationConfiguration correlation) {
		int availableRecords = 1;
		while (availableRecords > 0) {
			List<JsonObject> sourceDataList = loadDestinationData(correlation);
			availableRecords = sourceDataList.size();
			log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} fetch Destination tool record {}" ,loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),availableRecords);
			if (!sourceDataList.isEmpty()) {
				executeCorrelations(correlation, sourceDataList);
			} else {
				log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} No record found for Correlation of {}" ,loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0, correlation.getRelationName());
			}
		}
	}

	private void loadCorrelationConfigfromJson(List<CorrelationConfiguration> correlations) {
		List<Correlation> correlationsList = loadCorrelationsFromFile();
		if(correlationsList != null && !correlationsList.isEmpty()) {
			convertCorrelationDTO(correlationsList, correlations);
		}
	}
	/**
	 * Update the destination node max time where the correlation fields are
	 * missing.
	 *
	 * @param correlation
	 */
	private void updateNodesMissingCorrelationFields(CorrelationConfiguration correlation) {
		String destinationLabelName = correlation.getDestinationLabelName();
		List<String> destinationFields = Arrays.asList(correlation.getDestinationFields().split("\\s*,\\s*"));
		StringBuilder cypher = new StringBuilder();
		cypher.append("MATCH (destination:RAW:DATA:").append(destinationLabelName).append(") ");
		cypher.append("where destination.maxCorrelationTime IS NULL AND ");
		cypher.append(" ");
		for (String field : destinationFields) {
			cypher.append("coalesce(size(destination.").append(field).append("), 0) = 0 AND ");
		}
		cypher.delete(cypher.length() - 4, cypher.length());
		cypher.append(" WITH distinct destination limit ").append(dataBatchSize).append(" ");
		cypher.append("set destination.maxCorrelationTime=").append(maxCorrelationTime)
				.append(" , destination.correlationTime=").append(maxCorrelationTime).append(" ");
		cypher.append("return count(distinct destination) as count");
		GraphDBHandler dbHandler = new GraphDBHandler();
		try {
			int processedRecords = 1;
			while (processedRecords > 0) {
				long st = System.currentTimeMillis();
				GraphResponse response = dbHandler.executeCypherQuery(cypher.toString());
				processedRecords = response.getJson().get(RESULT).getAsJsonArray().get(0).getAsJsonObject()
						.get("data").getAsJsonArray().get(0).getAsJsonObject().get("row").getAsInt();
				log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} Pre Processed {} {}  records: {} in: {} ms",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),(System.currentTimeMillis() - st),processedRecords,correlation.getDestinationToolName(),destinationLabelName,processedRecords,(System.currentTimeMillis() - st));
			}
		} catch (InsightsCustomException e) {
			log.error(" execId={} correlationName={} sourceTool={} destinationTool={} Error occured while loading the destination data for correlations.",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL), e);
		}
	}

	/**
	 * Identify the destination nodes which are available for building correlations
	 * and load the uuid for source nodes.
	 *
	 * @param destination
	 * @param relName
	 * @return
	 */
	private List<JsonObject> loadDestinationData(CorrelationConfiguration correlation) {
		log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} In loadDestinationData, lastCorrelationTime {} maxCorrelationTime  {} currentCorrelationTime {}",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0,lastCorrelationTime,maxCorrelationTime,currentCorrelationTime);
		List<JsonObject> destinationDataList = new ArrayList<>();

		String destinationLabelName = correlation.getDestinationLabelName();
		List<String> destinationFields = Arrays.asList(correlation.getDestinationFields().split("\\s*,\\s*"));

		StringBuilder cypher = new StringBuilder();
		cypher.append("MATCH (destination:RAW:DATA:").append(destinationLabelName).append(") ");
		cypher.append("where not ((destination) <-[:").append(correlation.getRelationName()).append("]- (:DATA:")
				.append(correlation.getSourceLabelName()).append(")) ");
		cypher.append("AND (destination.correlationTime IS NULL OR ");
		cypher.append("destination.correlationTime < ").append(lastCorrelationTime).append(" ) ");
		cypher.append("AND (");

		for (String field : destinationFields) {
			cypher.append("destination.").append(field).append(" IS NOT NULL OR ");
		}

		cypher.delete(cypher.length() - 3, cypher.length());
		cypher.append(") ");
		cypher.append("WITH distinct destination limit ").append(dataBatchSize).append(" ");
		cypher.append("WITH destination, []  ");
		for (String field : destinationFields) {
			cypher.append(" + CASE ");
			cypher.append(" WHEN destination.").append(field).append(" IS NOT NULL THEN destination.").append(field)
					.append(" ");
			cypher.append(" ELSE [] ");
			cypher.append(" END ");
		}
		cypher.append("as values WITH destination.uuid as uuid, values UNWIND values as value WITH uuid, ");
		cypher.append(" CASE ");
		// If the value contains comma, the split the value
		cypher.append(" WHEN (toString(value) contains \",\") THEN split(value, \",\") ");
		cypher.append(" ELSE value ");
		cypher.append(" END as values ");
		cypher.append("UNWIND values as value WITH uuid, value where value <> \"\" ");
		cypher.append(
				"WITH distinct uuid, collect(distinct value) as values WITH { uuid : uuid, values : values} as data ");
		cypher.append("RETURN collect(data) as data");
		log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} DestinationData {} ", loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0,cypher);

		GraphDBHandler dbHandler = new GraphDBHandler();
		try {

			GraphResponse response = dbHandler.executeCypherQuery(cypher.toString());

			JsonArray rows = response.getJson().get(RESULT).getAsJsonArray().get(0).getAsJsonObject().get("data")
					.getAsJsonArray().get(0).getAsJsonObject().get("row").getAsJsonArray();

			if (rows.isJsonNull() || rows.size() == 0 || rows.get(0).getAsJsonArray().size() == 0) {
				return destinationDataList;
			}
			JsonArray dataArray = rows.get(0).getAsJsonArray();

			for (JsonElement data : dataArray) {
				destinationDataList.add(data.getAsJsonObject());
			}

		} catch (InsightsCustomException e) {
			log.error(" execId={} correlationName={} sourceTool={} destinationTool={} Error occured while loading the destination data for correlations.",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL), e);
		}
		return destinationDataList;
	}

	/**
	 * Execute the correlations for the given set of source and destination nodes.
	 *
	 * @param correlation
	 * @param dataList
	 * @param allowedSourceRelationCount
	 */
	private int executeCorrelations(CorrelationConfiguration correlation, List<JsonObject> dataList) {

		StringBuilder correlationCypher = new StringBuilder();
		String sourceField = correlation.getSourceFields(); // currently, we will support only one source field.

		correlationCypher.append("UNWIND $props as properties ");
		correlationCypher.append("MATCH (destination:DATA:RAW:").append(correlation.getDestinationLabelName())
				.append(" {uuid: properties.uuid}) ");
		correlationCypher.append("set destination.correlationTime=").append(currentCorrelationTime).append(", ");
		correlationCypher.append("destination.maxCorrelationTime=coalesce(destination.maxCorrelationTime, ")
				.append(maxCorrelationTime).append(") WITH destination, properties ");
		correlationCypher.append("MATCH (source:DATA:").append(correlation.getSourceLabelName()).append(") ");
		correlationCypher.append("WHERE source.").append(sourceField).append(" IN properties.values ")
				.append("with source , destination ");
		 correlationCypher.append("MERGE (source) -[r:").append(correlation.getRelationName())
		 .append(" {uuid:(source.uuid+'.'+destination.uuid)} ]-> (destination) ");

		String propertyVal = appendRelationshipProperties(correlation);

		if (!propertyVal.isEmpty()) {
			correlationCypher.append("set ").append(propertyVal).append(" ");
		}

		correlationCypher.append("RETURN count(distinct destination) as count");
		log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} CorrelationExecution Started executeCorrelations {} ",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0, correlationCypher);

		GraphDBHandler dbHandler = new GraphDBHandler();
		JsonObject correlationExecutionResponse;
		int processedRecords = 0;
		try {

			long st = System.currentTimeMillis();

			correlationExecutionResponse = dbHandler.bulkCreateNodes(dataList,correlationCypher.toString());

			log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} CorrelationExecution Response = {} ",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0,correlationExecutionResponse);

			processedRecords = correlationExecutionResponse.get("response").getAsJsonObject().get(RESULT)
					.getAsJsonArray().get(0).getAsJsonObject().get("data").getAsJsonArray().get(0).getAsJsonObject()
					.get("row").getAsInt();
			log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} Processed Records for correlation= {}  ",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),(System.currentTimeMillis() - st),processedRecords,processedRecords);

		} catch (InsightsCustomException e) {
			log.error(" execId={} correlationName={} sourceTool={} destinationTool={} Error occured while executing correlations",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),e);
			EngineStatusLogger.getInstance().createSchedularTaskStatusNode(
					" Error occured while executing correlations for relation " + e.getMessage(),
					PlatformServiceConstants.FAILURE, jobName);
		}
		return processedRecords;
	}
	private String appendRelationshipProperties(CorrelationConfiguration configuration) {

		StringBuilder propertyValueBuilder = new StringBuilder();

		List<RelationshipConfiguration> allRelationshipConfigList = new ArrayList<>(
				configuration.getRelationshipConfig());

		for (RelationshipConfiguration rc : allRelationshipConfigList) {
			String operationName = rc.getOperation();
			if (operationName.equals("DIFF")) {
				String propValue = RelationshipPropertiesUtil.calDiff(rc.getOperationjson());
				propValue = "r." + rc.getFieldValue() + "=" + propValue;
				if (!propertyValueBuilder.toString().isEmpty()) {
					propertyValueBuilder.append(",").append(propValue);
				} else {
					propertyValueBuilder.append(propValue);
				}
			}
			if (operationName.equals("SUM")) {
				String propValue = RelationshipPropertiesUtil.calSUM(rc.getOperationjson());
				propValue = "r." + rc.getFieldValue() + "=" + propValue;
				if (!propertyValueBuilder.toString().isEmpty()) {
					propertyValueBuilder.append(",").append(propValue);
				} else {
					propertyValueBuilder.append(propValue);
				}
			}
		}

		return propertyValueBuilder.toString();
	}

	private int removeRawLabel(CorrelationConfiguration destination) {

		StringBuilder correlationCypher = new StringBuilder();
		correlationCypher.append("MATCH (destination:DATA:RAW:").append(destination.getDestinationLabelName())
				.append(") ");
		correlationCypher.append("where destination.maxCorrelationTime < ").append(currentCorrelationTime).append(" ");
		correlationCypher.append("WITH destination limit ").append(dataBatchSize).append(" ");
		correlationCypher
				.append("remove destination.maxCorrelationTime, destination.correlationTime, destination:RAW ");
		correlationCypher.append("return count(distinct destination) ");

		GraphDBHandler dbHandler = new GraphDBHandler();
		JsonObject correlationExecutionResponse;
		int processedRecords = 1;

		try {
			while (processedRecords > 0) {
				long st = System.currentTimeMillis();
				correlationExecutionResponse = dbHandler.executeCypherQuery(correlationCypher.toString()).getJson();
				log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} CorrelationExecution Response={}",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),0,0,correlationExecutionResponse);
				processedRecords = correlationExecutionResponse.get(RESULT).getAsJsonArray().get(0).getAsJsonObject()
						.get("data").getAsJsonArray().get(0).getAsJsonObject().get("row").getAsInt();
				log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} Processed records for label removal: {}  ms",loggingInfo.get(EngineConstants.EXECID),loggingInfo.get(EngineConstants.CORRELATION_NAME),loggingInfo.get(EngineConstants.SOURCE_TOOL),loggingInfo.get(EngineConstants.DESTINATION_TOOL),(System.currentTimeMillis() - st),processedRecords,processedRecords);
			}
		} catch (InsightsCustomException e) {
			log.error(" Error occured while removing RAW label from tool:{}",destination.getDestinationLabelName(),
					e);
		}

		return processedRecords;
	}

	/**
	 * Load the correlation.json and population Correlations object.
	 *
	 * @return
	 */
	private List<Correlation> loadCorrelationsFromFile() {

		List<Correlation> correlations = null;

		try {

			List<InsightsConfigFiles> configFile = configFilesDAL
					.getAllConfigurationFilesForModule(FileDetailsEnum.FileModule.CORRELATION.name());
			if (configFile != null && !configFile.isEmpty()) {

				String configFileData = new String(configFile.get(0).getFileData(), StandardCharsets.UTF_8);
				Correlation[] correlationArray = new Gson().fromJson(configFileData, Correlation[].class);
				correlations = Arrays.asList(correlationArray);

				EngineStatusLogger.getInstance().createSchedularTaskStatusNode("Correlation.json is successfully loaded.",
						PlatformServiceConstants.SUCCESS, jobName);

				log.debug(" Type=Correlator execId={} correlationName={} sourceTool={} destinationTool={} ProcessingTime={} processedRecords={} Correlation.json is successfully loaded.",loggingInfo.get(EngineConstants.EXECID),"-","-","-",0,0);

			} else {
				log.error(" execId={} Correlation.json not found in DB.",loggingInfo.get(EngineConstants.EXECID));
				EngineStatusLogger.getInstance().createSchedularTaskStatusNode("Correlation.json not found in DB.",
						PlatformServiceConstants.FAILURE, jobName);
			}

		} catch (JsonSyntaxException e) {
			EngineStatusLogger.getInstance().createSchedularTaskStatusNode("Correlation.json is not formatted.",
					PlatformServiceConstants.FAILURE, jobName);
			log.error(" execId={} Correlation.json is not formatted",loggingInfo.get(EngineConstants.EXECID));
		} catch (Exception e) {
			EngineStatusLogger.getInstance().createSchedularTaskStatusNode("Error while loading Correlation.json.",
					PlatformServiceConstants.FAILURE, jobName);
			log.error(" execId={} Exception while loading Correlation.json",loggingInfo.get(EngineConstants.EXECID));
		}

		return correlations;
	}

	private void convertCorrelationDTO(List<Correlation> correlationsJson, List<CorrelationConfiguration> correlations) {

		for (Correlation correlation : correlationsJson) {

			CorrelationConfiguration correlationConfiguration = new CorrelationConfiguration();
			correlationConfiguration.setSourceToolName(correlation.getSource().getToolName());
			correlationConfiguration.setSourceToolCategory(correlation.getSource().getToolCategory());
			if (correlation.getSource().getLabelName().isEmpty()) {
				correlationConfiguration.setSourceLabelName(correlation.getSource().getToolName());
			} else {
				correlationConfiguration.setSourceLabelName(correlation.getSource().getLabelName());
			}
			correlationConfiguration.setSourceFields(String.join(",", correlation.getSource().getFields()));

			correlationConfiguration.setDestinationToolName(correlation.getDestination().getToolName());
			correlationConfiguration.setDestinationToolCategory(correlation.getDestination().getToolCategory());
			if (correlation.getDestination().getLabelName().isEmpty()) {
				correlationConfiguration.setDestinationLabelName(correlation.getDestination().getToolName());
			} else {
				correlationConfiguration.setDestinationLabelName(correlation.getDestination().getLabelName());
			}
			correlationConfiguration.setDestinationFields(String.join(",", correlation.getDestination().getFields()));
			correlationConfiguration.setRelationName(correlation.getRelationName());
			correlations.add(correlationConfiguration);

		}

	}

	private List<CorrelationConfiguration> getRelation() {

		CorrelationConfigDAL correlationConfigDAL = new CorrelationConfigDAL();
		List<CorrelationConfiguration> correlationList = new ArrayList<>();

		try {

			correlationList = correlationConfigDAL.getActiveCorrelations();

		} catch (Exception e) {
			log.error(" execId={} unable to get correlation from database",loggingInfo.get(EngineConstants.EXECID));
			EngineStatusLogger.getInstance().createSchedularTaskStatusNode("unable to get correlation from database",
					PlatformServiceConstants.FAILURE, jobName);
		}

		return correlationList;
	}

	/**
	 * Update the correlation time variables.
	 */
	private void loadCorrelationConfiguration(CorrelationConfig correlations) {
		dataBatchSize = correlations.getBatchSize();
		currentCorrelationTime = System.currentTimeMillis() / 1000;
		maxCorrelationTime = currentCorrelationTime + correlations.getCorrelationWindow() * 60 * 60;
		lastCorrelationTime = currentCorrelationTime - correlations.getCorrelationFrequency() * 60 * 60;
	}

}


text:
import {Autowired, Bean, Context, PostConstruct} from "../context/context";
import {ICellEditorComp, ICellEditorParams} from "./cellEditors/iCellEditor";
import {PopupEditorWrapper} from "./cellEditors/popupEditorWrapper";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {ColDef} from "../entities/colDef";
import {ComponentResolver} from "../components/framework/componentResolver";
import {_, Promise} from "../utils";

@Bean('cellEditorFactory')
export class CellEditorFactory {

    @Autowired('context') private context: Context;
    @Autowired('componentResolver') private componentResolver: ComponentResolver;
    @Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;

    @PostConstruct
    private init(): void {
    }

    public addCellEditor(key: string, cellEditor: {new(): ICellEditorComp}): void {
        console.warn(`ag-grid: since v13.3.1 this method is not supported anymore. If you want to register your own editor check the docs: https://www.ag-grid.com/javascript-grid-cell-editor/`)
    }

    // private registerEditorsFromGridOptions(): void {
    //     let userProvidedCellEditors = this.gridOptionsWrapper.getCellEditors();
    //     _.iterateObject(userProvidedCellEditors, (key: string, cellEditor: {new(): ICellEditor})=> {
    //         this.addCellEditor(key, cellEditor);
    //     });
    // }

    public createCellEditor(column:ColDef, params: ICellEditorParams): Promise<ICellEditorComp> {

        let cellEditorPromise:Promise<ICellEditorComp> = this.componentResolver.createAgGridComponent (
            column,
            params,
            'cellEditor',
            'agCellEditor'
        );
        return cellEditorPromise.map(cellEditor => {

            let isPopup = cellEditor.isPopup && cellEditor.isPopup();

            if (!isPopup) { return cellEditor; }

            if (this.gridOptionsWrapper.isFullRowEdit()) {
                console.warn('ag-Grid: popup cellEditor does not work with fullRowEdit - you cannot use them both ' +
                    '- either turn off fullRowEdit, or stop using popup editors.');
            }

            // if a popup, then we wrap in a popup editor and return the popup
            let popupEditorWrapper = new PopupEditorWrapper(cellEditor);
            this.context.wireBean(popupEditorWrapper);
            popupEditorWrapper.init(params);
            return popupEditorWrapper;
        });
    }

}


text:
package math_instructions

import (
	"github.com/Frederick-S/jvmgo/instructions/base_instructions"
	"github.com/Frederick-S/jvmgo/runtime_data_area"
)

// lshl
// Shift left long
type LShl struct {
	base_instructions.NoOperandsInstruction
}

func (lShl *LShl) Execute(frame *runtime_data_area.Frame) {
	operandStack := frame.GetOperandStack()
	integerValue := operandStack.PopIntegerValue()
	longValue := operandStack.PopLongValue()
	bitPositions := uint32(integerValue) & 0x3f

	operandStack.PushLongValue(longValue << bitPositions)
}


text:
package bootstrap_utils;

require 5.6.0;

#"use strict" is incompatible with gLucid Perl

use warnings;

# module constructor
BEGIN {
  use Exporter   ();
  our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);

  # set the version for version checking
  $VERSION     = 1.00;
  @ISA         = qw(Exporter);
  @EXPORT      = qw(&get_architecture
                    &is_ubuntu
                    &package_filename
                    &rpm_clean_packages
                    &check_packages
                    &check_spec_files
                    &yum_install_packages
                    &yum_uninstall_packages
                    &rpm_uninstall_packages
                    &rpm_install_packages
                    &debian_install_packages
                    &dpkg_cache_uninstall_packages
                    &dpkg_cache_install_packages
                    );

  %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],

  # your exported package globals go here,
  # as well as any optionally exported functions
  @EXPORT_OK   = qw();
}
our @EXPORT_OK;

# Is this Goobuntu...don't do installs on Debian.
sub is_ubuntu() {
  my $ubuntu = `grep Ubuntu /etc/lsb-release 2> /dev/null`;
  chomp($ubuntu);
  return 1 if ($ubuntu =~ /Ubuntu/);
  return 0;
}

# Determine the architecture of the current machine.
# Either 'i686' for 32 bit machines, or 'x86_64' for 64 bit machines.
sub get_architecture() {
  my $architecture = 'i686';
  my $bits = `getconf LONG_BIT`;
  chomp($bits);
  $architecture = 'x86_64' if ($bits =~ /64/);
  return $architecture;
}

# Package file name.
sub package_filename($$$) {
  my ($arch, $name, $version) = @_;
  my $package = "$arch/$name-$version.$arch.rpm";
  return $package;
}

# Check that packages are there.
sub check_packages($@) {
  my ($path, @packages) = @_;
  my $missing = '';
  foreach my $package_info (@packages) {
    my ($name, $version, $arch) = @{$package_info};
    my $filename = "$path/" . package_filename($arch, $name, $version);
    $missing = "$missing$filename\n" if !-e $filename;
  }

  if ($missing ne '') {
    print("Error: Missing the following packages:\n" . $missing . "\n");
    exit;
  }
  print("Verified all packages in place.\n");
}
# Check that packages are there.
sub rpm_clean_packages($@) {
  my ($path, @packages) = @_;
  foreach my $package_info (@packages) {
    my ($name, $version, $arch) = @{$package_info};
    my $filename = "$path/" . package_filename($arch, $name, $version);
    if ( -e $filename ) {
      print("Removing $filename\n");
      unlink $filename || die("Unable to remove $filename")
    }
  }

  print("all rpms have been removed.\n");
}

# Check that packages are there.
sub check_spec_files($@) {
  my ($path, @packages) = @_;
  my $missing = '';
  foreach my $package_info (@packages) {
    my ($name) = @{$package_info};
    my $filename = "$path/SPECS/$name.spec";
    $missing = "$missing$filename\n" if (!(-e $filename));
  }

  if ($missing ne '') {
    print("Error: Missing the following spec files:\n" . $missing . "\n");
    exit;
  }
  print("Verified all packages in place.\n");
}

# YUM install the specified RPM package.
sub yum_install($) {
  my $package = shift;
  print "Installing yum $package\n";
  check_command("yum install $package -y");
}

# YUM uninstall the specified RPM package.
sub yum_uninstall($) {
  my $package = shift;
  print "Removing yum $package\n";
  check_command("yum remove $package -y");
}

# Install the specified YUM packages.
sub yum_install_packages(@) {
 my @yum_packages = @_;
 # Install in the forward order.
 foreach my $package_info (@yum_packages) {
   my ($name) = @{$package_info};
   yum_install($name);
 }
}

# Unnstall the specified YUM packages.
sub yum_uninstall_packages(@) {
  my @yum_packages = @_;

  foreach my $name (@yum_packages) {
    yum_uninstall($name);
  }
}

# Uninstall the specified RPM package.
sub rpm_uninstall($) {
  my ($package) = @_;
  print("Uninstalling $package\n");
  # Check if it's installed first, otherwise
  my $command = "rpm -q $package";
  open(OUT, "$command |") || die("Unable to execute: $command\n");
  while(<OUT>) {
    if (/is not installed/) {
      print("  not installed\n");
      close(OUT);
      return;  # No need to uninstall.
    }
  }
  close(OUT);
  check_command("rpm -e $package");
}

# Check for Command Errors
# Exits with a warning for any detected errors.
# This assumes the command will print to stderr the text "Error:*" or "error:*".
sub check_command($) {
  my ($command) = @_;
  open(COMMAND_OUT, "$command 2>&1 |") || die("Unable to execute: $command\n");
  my $failure = 0;
  while(<COMMAND_OUT>) {
    print($_);
    $failure = 1 if (/^error:/i);
  }
  close(COMMAND_OUT);
  my $result = $? >> 8;  # Check return value of $command, die if not 0.
  if($result)
  {
    print "Command error result of $result: $command\n";
  }
  # BP (08/31/2010): Gets "incorrect format: unknown tag" error
  if($failure)
  {
    print "Failure: $command\n";
  }
}

# Install the specified RPM package.
sub rpm_install($$$$) {
  my ($path, $arch, $name, $version) = @_;
  my $package = "$path/" . package_filename($arch, $name, $version);
  print("Installing $package\n");
  check_command("rpm -i $package");
}

# Install the specified RPM package.
sub rpm_build($$) {
  my ($name, $arch) = @_;
  print("Building spec file: $name\n");
  # Build the binary rpm package (in RPMS)
  check_command("rpmbuild -bb $name");

  # Build the src rpm package in (SRPMS)
  print("Building src.rpm: $name\n");
  check_command("rpmbuild -bs $name");
}

# Uninstall the specified packages
sub rpm_uninstall_packages(@) {
  my @packages = @_;
  # Must uninstall in reverse order...for dependency reasons.
  my @rpackages = reverse(@packages);
  foreach my $package_info (@rpackages) {
    my ($name) = @{$package_info};
    rpm_uninstall($name);
  }
}

# Install the specified RPM packages.
sub rpm_install_packages($@) {
  my ($path, @packages) = @_;
  # Install in the forward order.
  foreach my $package_info (@packages) {
    my ($name, $version, $arch) = @{$package_info};
    rpm_install($path, $arch, $name, $version);
  }
}

# Build and Install the specified RPM packages from spec files.
sub rpm_build_and_install_packages($@) {
  my ($path, @packages) = @_;
  # Install in the forward order.
  foreach my $package_info (@packages) {
    my ($name, $version, $arch, $has_devel) = @{$package_info};
    my $spec_filename = "$path/SPECS/$name.spec";
    rpm_build($spec_filename, $arch);
    rpm_install($path . '/RPMS', $arch, $name, $version);
    rpm_install($path . '/RPMS', $arch, "$name-devel", $version) if ($has_devel);
  }
}

# -----------------------------------------------------------
# Ubuntu dpkg and alien commands for Goobuntu platform
#
# Unnstall the specified cached Debian packages.
sub debian_cache_uninstall_packages(@) {
  my @debian_packages = @_;

  foreach my $name (@debian_packages) {
    debian_uninstall($name);
  }
}

# DPKG uninstall the specified Debian package.
sub debian_uninstall($) {
  my ($package) = @_;
  print("Removing Debian $package\n");
  check_command("dpkg --remove --force-all $package");
}

# DPKG direct install from cache the specified Debian package.
sub debian_cache_install($) {
  my ($package) = @_;
  print("Installing Debian Cache $package\n");
  check_command("apt-get -f install $package");
}

# DPKG install from cache the specified Debian package.
sub debian_install($) {
  my ($debian_package) = @_;
  print("Installing Debian $debian_package\n");
  check_command("dpkg --install $debian_package");
}

# Install the specified Debian cache packages.
sub debian_cache_install_packages(@) {
  my @debian_packages = @_;

  # Install in the forward order.
  foreach my $package_info (@debian_packages) {
    my $name = $package_info->[1];
    debian_cache_install($name) if ($name ne '');
  }
}

# Install the specified RPM package.
sub debian_from_alien_install($$$$) {
  my ($path, $arch, $name, $version) = @_;
  my $rpm_package = "$path/" . package_filename($arch, $name, $version);
  print("Installing $rpm_package via alien\n");
  check_command("alien --scripts -i $rpm_package");
}

# Uninstall the specified packages
sub debian_uninstall_packages(@) {
  my @packages = @_;
  # Must uninstall in reverse order...for dependency reasons.
  my @rpackages = reverse(@packages);
  foreach my $package_info (@rpackages) {
    my ($name) = @{$package_info};
    debian_uninstall($name);
  }
}

# Install the specified RPM packages.
sub debian_install_packages($@) {
  my ($path, @packages) = @_;
  # Install in the forward order.
  foreach my $package_info (@packages) {
    my ($name, $version, $arch) = @{$package_info};
    debian_from_alien_install($path, $arch, $name, $version);
  }
}

END { }       # module clean-up code here (global destructor)

1;  # don't forget to return a true value from the file


text:
package cn.newcapec.function.ecardcity.om.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.codehaus.jackson.map.annotate.JsonSerialize;

import cn.newcapec.framework.core.handler.springDatebind.CustomDateSerializer;
import cn.newcapec.framework.core.model.CommonModel;

/**
 * 客户实体类
 *
 * @author wangjian
 *
 */
@Table(name = "wwww")
@Entity
public class Customer extends CommonModel {
    private static final long serialVersionUID = -7308119212639431688L;

    @Column(name = "address_eeeee", length = 100)
    private String address;

    private String rremark;
    @Column(name = "edit_person_wwww", length = 32)
    private String editPerson;

    /** 生日日期 */
    @JsonSerialize(using = CustomDateSerializer.class)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "birthday")
    private Date birthday;
    /** 编辑日期 */
    @JsonSerialize(using = CustomDateSerializer.class)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "edit_date")
    private Date editDate;
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Column(name = "rremark_fffff", length = 200)
	public String getRremark() {
		return rremark;
	}
	public void setRremark(String rremark) {
		this.rremark = rremark;
	}
	public String getEditPerson() {
		return editPerson;
	}
	public void setEditPerson(String editPerson) {
		this.editPerson = editPerson;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Date getEditDate() {
		return editDate;
	}
	public void setEditDate(Date editDate) {
		this.editDate = editDate;
	}

}


text:
<component name="libraryTable">
  <library name="Maven: org.attoparser:attoparser:2.0.4.RELEASE">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/attoparser/attoparser/2.0.4.RELEASE/attoparser-2.0.4.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/attoparser/attoparser/2.0.4.RELEASE/attoparser-2.0.4.RELEASE-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/attoparser/attoparser/2.0.4.RELEASE/attoparser-2.0.4.RELEASE-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
			ParkAlert

início

mapa

ranking

stats

registar

entrar

					#{form @authenticate()}
						#{ifErrors}

								${errors[0]}

						#{/ifErrors}

				            Username:
				            <input id="username_elm" type="text" name="username" tabindex="1" />

			              	Palavra-chave:
			              	<input type="password" id="password_elm" name="password" tabindex="2" />

			                <input type="submit" value="Entrar" class="freshbutton-blue" tabindex="4" id="toplogin-submit" />

			                esqueci-me da password

			        #{/form}

Login with Facebook

blog | ajuda

ParkAlert ajuda-o com o estacionamento. Copyright ©2012


text:
CREATE TABLE IF NOT EXISTS `express_sessions` (
  `session_id` varchar(255) COLLATE utf8_bin NOT NULL,
  `expires` int(11) unsigned NOT NULL,
  `data` text,
  PRIMARY KEY (`session_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin


text:
require 'gettext/utils'
begin
  require 'gettext/tools/rgettext'
rescue LoadError #version prior to 2.0
  require 'gettext/rgettext'
end

module GettextI18nRails
  module HamlParser
    module_function

    def target?(file)
      File.extname(file) == '.haml'
    end

    def parse(file, msgids = [])
      return msgids unless load_haml
      require 'gettext_i18n_rails/ruby_gettext_extractor'

      text = IO.readlines(file).join

      haml = Haml::Engine.new(text)
      code = haml.precompiled
      return RubyGettextExtractor.parse_string(code, file, msgids)
    end

    def load_haml
      return true if @haml_loaded
      begin
        require "#{::Rails.root.to_s}/vendor/plugins/haml/lib/haml"
      rescue LoadError
        begin
          require 'haml'  # From gem
        rescue LoadError
          puts "A haml file was found, but haml library could not be found, so nothing will be parsed..."
          return false
        end
      end
      @haml_loaded = true
    end
  end
end
GetText::RGetText.add_parser(GettextI18nRails::HamlParser)


text:
module Tramp
  module Model
    class Rule

    include Tramp::Rule::InstanceMethods
    extend  Tramp::Rule::ClassMethods

    end
  end
end