text:
<?php

namespace Zend\Math\BigInteger\Adapter;

use Zend\Math\BigInteger\Exception;

/**
 * Bcmath extension adapter
 */
class Bcmath implements AdapterInterface
{
    /**
     * Constructor
     * Sets Bcmath scale factor to zero
     */
    public function __construct()
    {
        bcscale(0);
    }

    /**
     * Create string representing big integer in decimal form from arbitrary integer format
     *
     * @param  string $operand
     * @param  int|null $base
     * @return bool|string
     */
    public function init($operand, $base = null)
    {
        $sign    = (strpos($operand, '-') === 0) ? '-' : '';
        $operand = ltrim($operand, '-+');

        if (null === $base) {
            // decimal
            if (preg_match('#^([1-9][0-9]*)$#', $operand, $m)) {
                $base    = 10;
                $operand = $m[1];
            // octal
            } elseif (preg_match('#^(0[0-7]+)$#', $operand, $m)) {
                $base    = 8;
                $operand = $m[1];
            // hex
            } elseif (preg_match('#^(?:0x)?([0-9a-f]+)$#', strtolower($operand), $m)) {
                $base    = 16;
                $operand = $m[1];
            // scientific notation
            } elseif (preg_match('#^([1-9]?\.?[0-9]+)[eE]\+?([0-9]+)$#', $operand, $m)) {
                $base    = 10;
                $operand = bcmul($m[1], bcpow('10', $m[2]));
            } else {
                return false;
            }
        }

        if ($base != 10) {
            $operand = $this->baseConvert($operand, $base, 10);
        }

        $prod = bcmul($operand, '1');
        if (bccomp($operand, $prod) !== 0) {
            return false;
        }

        return $sign . $operand;
    }

    /**
     * Add two big integers
     *
     * @param  string $leftOperand
     * @param  string $rightOperand
     * @return string
     */
    public function add($leftOperand, $rightOperand)
    {
        return bcadd($leftOperand, $rightOperand);
    }

    /**
     * Subtract two big integers
     *
     * @param  string $leftOperand
     * @param  string $rightOperand
     * @return string
     */
    public function sub($leftOperand, $rightOperand)
    {
        return bcsub($leftOperand, $rightOperand);
    }

    /**
     * Multiply two big integers
     *
     * @param string $leftOperand
     * @param string $rightOperand
     * @return string
     */
    public function mul($leftOperand, $rightOperand)
    {
        return bcmul($leftOperand, $rightOperand);
    }

    /**
     * Divide two big integers and return integer part result.
     * Raises exception if the divisor is zero.
     *
     * @param string $leftOperand
     * @param string $rightOperand
     * @return string
     * @throws Exception\DivisionByZeroException
     */
    public function div($leftOperand, $rightOperand)
    {
        if ($rightOperand == 0) {
            throw new Exception\DivisionByZeroException(
                "Division by zero; divisor = {$rightOperand}"
            );
        }

        $result = bcdiv($leftOperand, $rightOperand);

        return $result;
    }

    /**
     * Raise a big integers to another
     *
     * @param  string $operand
     * @param  string $exp
     * @return string
     */
    public function pow($operand, $exp)
    {
        return bcpow($operand, $exp);
    }

    /**
     * Get the square root of a big integer
     *
     * @param  string $operand
     * @return string
     */
    public function sqrt($operand)
    {
        return bcsqrt($operand);
    }

    /**
     * Get absolute value of a big integer
     *
     * @param  string $operand
     * @return string
     */
    public function abs($operand)
    {
        return ltrim($operand, '-');
    }

    /**
     * Get modulus of a big integer
     *
     * @param  string $leftOperand
     * @param  string $rightOperand
     * @return string
     */
    public function mod($leftOperand, $rightOperand)
    {
        return bcmod($leftOperand, $rightOperand);
    }

    /**
     * Raise a big integer to another, reduced by a specified modulus
     *
     * @param  string $leftOperand
     * @param  string $rightOperand
     * @param  string $modulus
     * @return string
     */
    public function powmod($leftOperand, $rightOperand, $modulus)
    {
        return bcpowmod($leftOperand, $rightOperand, $modulus);
    }

    /**
     * Compare two big integers and returns result as an integer where
     * Returns < 0 if leftOperand is less than rightOperand;
     * > 0 if leftOperand is greater than rightOperand, and 0 if they are equal.
     *
     * @param  string $leftOperand
     * @param  string $rightOperand
     * @return int
     */
    public function comp($leftOperand, $rightOperand)
    {
        return bccomp($leftOperand, $rightOperand);
    }

    /**
     * Convert big integer into it's binary number representation
     *
     * @param  string $operand
     * @param  bool $twoc return in two's complement form
     * @return string
     */
    public function intToBin($operand, $twoc = false)
    {
        $nb = chr(0);
        $isNegative = (strpos($operand, '-') === 0) ? true : false;
        $operand    = ltrim($operand, '+-0');

        if (empty($operand)) {
            return $nb;
        }

        if ($isNegative && $twoc) {
            $operand = bcsub($operand, '1');
        }

        $bytes = '';
        while (bccomp($operand, '0', 0) > 0) {
            $temp    = bcmod($operand, '16777216');
            $bytes   = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $bytes;
            $operand = bcdiv($operand, '16777216');
        }
        $bytes = ltrim($bytes, $nb);

        if ($twoc) {
            if (ord($bytes[0]) & 0x80) {
                $bytes = $nb . $bytes;
            }
            return $isNegative ? ~$bytes : $bytes;
        }

        return $bytes;
    }

    /**
     * Convert big integer into it's binary number representation
     *
     * @param  string $bytes
     * @param  bool   $twoc whether binary number is in twos' complement form
     * @return string
     */
    public function binToInt($bytes, $twoc = false)
    {
        $isNegative = ((ord($bytes[0]) & 0x80) && $twoc);

        if ($isNegative) {
            $bytes = ~$bytes;
        }

        $len = (strlen($bytes) + 3) & 0xfffffffc;
        $bytes = str_pad($bytes, $len, chr(0), STR_PAD_LEFT);

        $result = '0';
        for ($i = 0; $i < $len; $i += 4) {
            $result = bcmul($result, '4294967296'); // 2**32
            $result = bcadd($result, 0x1000000 * ord($bytes[$i]) +
                    ((ord($bytes[$i + 1]) << 16) |
                     (ord($bytes[$i + 2]) << 8) |
                      ord($bytes[$i + 3])));
        }

        if ($isNegative) {
            $result = bcsub('-' . $result, '1');
        }

        return $result;
    }

    /**
     * Base conversion. Bases 2..62 are supported
     *
     * @param  string $operand
     * @param  int    $fromBase
     * @param  int    $toBase
     * @return string
     * @throws Exception\InvalidArgumentException
     */
    public function baseConvert($operand, $fromBase, $toBase = 10)
    {
        if ($fromBase == $toBase) {
            return $operand;
        }

        if ($fromBase < 2 || $fromBase > 62) {
            throw new Exception\InvalidArgumentException(
                "Unsupported base: {$fromBase}, should be 2..62"
            );
        }
        if ($toBase < 2 || $toBase > 62) {
            throw new Exception\InvalidArgumentException(
                "Unsupported base: {$toBase}, should be 2..62"
            );
        }

        $sign    = (strpos($operand, '-') === 0) ? '-' : '';
        $operand = ltrim($operand, '-+');

        $chars = self::BASE62_ALPHABET;

        // convert to decimal
        if ($fromBase == 10) {
            $decimal = $operand;
        } else {
            $decimal = '0';
            for ($i = 0, $len  = strlen($operand); $i < $len; $i++) {
                $decimal = bcmul($decimal, $fromBase);
                $decimal = bcadd($decimal, strpos($chars, $operand[$i]));
            }
        }

        if ($toBase == 10) {
            return $decimal;
        }

        // convert decimal to base
        $result = '';
        do {
            $remainder = bcmod($decimal, $toBase);
            $decimal   = bcdiv($decimal, $toBase);
            $result    = $chars[$remainder] . $result;
        } while (bccomp($decimal, '0'));

        return $sign . $result;
    }
}


text:
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

const {
  Timer: TimerWrap,
  setupTimers,
} = process.binding('timer_wrap');
const L = require('internal/linkedlist');
const {
  async_id_symbol,
  trigger_async_id_symbol,
  Timeout,
  initAsyncResource,
  validateTimerDuration
} = require('internal/timers');
const internalUtil = require('internal/util');
const { createPromise, promiseResolve } = process.binding('util');
const assert = require('assert');
const util = require('util');
const { ERR_INVALID_CALLBACK } = require('internal/errors').codes;
const debug = util.debuglog('timer');
const {
  destroyHooksExist,
  // The needed emit*() functions.
  emitBefore,
  emitAfter,
  emitDestroy
} = require('internal/async_hooks');

// *Must* match Environment::ImmediateInfo::Fields in src/env.h.
const kCount = 0;
const kRefCount = 1;
const kHasOutstanding = 2;

const [immediateInfo, toggleImmediateRef] =
  setupTimers(processImmediate, processTimers);

const kRefed = Symbol('refed');

// HOW and WHY the timers implementation works the way it does.
//
// Timers are crucial to Node.js. Internally, any TCP I/O connection creates a
// timer so that we can time out of connections. Additionally, many user
// libraries and applications also use timers. As such there may be a
// significantly large amount of timeouts scheduled at any given time.
// Therefore, it is very important that the timers implementation is performant
// and efficient.
//
// Note: It is suggested you first read through the lib/internal/linkedlist.js
// linked list implementation, since timers depend on it extensively. It can be
// somewhat counter-intuitive at first, as it is not actually a class. Instead,
// it is a set of helpers that operate on an existing object.
//
// In order to be as performant as possible, the architecture and data
// structures are designed so that they are optimized to handle the following
// use cases as efficiently as possible:

// - Adding a new timer. (insert)
// - Removing an existing timer. (remove)
// - Handling a timer timing out. (timeout)
//
// Whenever possible, the implementation tries to make the complexity of these
// operations as close to constant-time as possible.
// (So that performance is not impacted by the number of scheduled timers.)
//
// Object maps are kept which contain linked lists keyed by their duration in
// milliseconds.
// The linked lists within also have some meta-properties, one of which is a
// TimerWrap C++ handle, which makes the call after the duration to process the
// list it is attached to.
//
/* eslint-disable node-core/non-ascii-character */
//
// ╔════ > Object Map
// ║
// ╠══
// ║ refedLists: { '40': { }, '320': { etc } } (keys of millisecond duration)
// ╚══          ┌─────────┘
//              │
// ╔══          │
// ║ TimersList { _idleNext: { }, _idlePrev: (self), _timer: (TimerWrap) }
// ║         ┌────────────────┘
// ║    ╔══  │                              ^
// ║    ║    { _idleNext: { },  _idlePrev: { }, _onTimeout: (callback) }
// ║    ║      ┌───────────┘
// ║    ║      │                                  ^
// ║    ║      { _idleNext: { etc },  _idlePrev: { }, _onTimeout: (callback) }
// ╠══  ╠══
// ║    ║
// ║    ╚════ >  Actual JavaScript timeouts
// ║
// ╚════ > Linked List
//
/* eslint-enable node-core/non-ascii-character */
//
// With this, virtually constant-time insertion (append), removal, and timeout
// is possible in the JavaScript layer. Any one list of timers is able to be
// sorted by just appending to it because all timers within share the same
// duration. Therefore, any timer added later will always have been scheduled to
// timeout later, thus only needing to be appended.
// Removal from an object-property linked list is also virtually constant-time
// as can be seen in the lib/internal/linkedlist.js implementation.
// Timeouts only need to process any timers currently due to expire, which will
// always be at the beginning of the list for reasons stated above. Any timers
// after the first one encountered that does not yet need to timeout will also
// always be due to timeout at a later time.
//
// Less-than constant time operations are thus contained in two places:
// TimerWrap's backing libuv timers implementation (a performant heap-based
// queue), and the object map lookup of a specific list by the duration of
// timers within (or creation of a new list).
// However, these operations combined have shown to be trivial in comparison to
// other alternative timers architectures.

// Object maps containing linked lists of timers, keyed and sorted by their
// duration in milliseconds.
//
// The difference between these two objects is that the former contains timers
// that will keep the process open if they are the only thing left, while the
// latter will not.
//
// - key = time in milliseconds
// - value = linked list
const refedLists = Object.create(null);
const unrefedLists = Object.create(null);

// Schedule or re-schedule a timer.
// The item must have been enroll()'d first.
const active = exports.active = function(item) {
  insert(item, false);
};

// Internal APIs that need timeouts should use `_unrefActive()` instead of
// `active()` so that they do not unnecessarily keep the process open.
exports._unrefActive = function(item) {
  insert(item, true);
};

// The underlying logic for scheduling or re-scheduling a timer.
//
// Appends a timer onto the end of an existing timers list, or creates a new
// TimerWrap backed list if one does not already exist for the specified timeout
// duration.
function insert(item, unrefed, start) {
  const msecs = item._idleTimeout;
  if (msecs < 0 || msecs === undefined) return;

  if (typeof start === 'number') {
    item._idleStart = start;
  } else {
    item._idleStart = TimerWrap.now();
  }

  const lists = unrefed === true ? unrefedLists : refedLists;

  // Use an existing list if there is one, otherwise we need to make a new one.
  var list = lists[msecs];
  if (list === undefined) {
    debug('no %d list was found in insert, creating a new one', msecs);
    lists[msecs] = list = new TimersList(msecs, unrefed);
  }

  if (!item[async_id_symbol] || item._destroyed) {
    item._destroyed = false;
    initAsyncResource(item, 'Timeout');
  }

  L.append(list, item);
  assert(!L.isEmpty(list)); // list is not empty
}

function TimersList(msecs, unrefed) {
  this._idleNext = this; // Create the list with the linkedlist properties to
  this._idlePrev = this; // prevent any unnecessary hidden class changes.
  this._unrefed = unrefed;
  this.msecs = msecs;

  const timer = this._timer = new TimerWrap();
  timer._list = this;

  if (unrefed === true)
    timer.unref();
  timer.start(msecs);
}

function processTimers(now) {
  if (this.owner)
    return unrefdHandle(this.owner, now);
  return listOnTimeout(this, now);
}

function listOnTimeout(handle, now) {
  const list = handle._list;
  const msecs = list.msecs;

  debug('timeout callback %d', msecs);
  debug('now: %d', now);

  var diff, timer;
  while (timer = L.peek(list)) {
    diff = now - timer._idleStart;

    // Check if this loop iteration is too early for the next timer.
    // This happens if there are more timers scheduled for later in the list.
    if (diff < msecs) {
      var timeRemaining = msecs - (TimerWrap.now() - timer._idleStart);
      if (timeRemaining <= 0) {
        timeRemaining = 1;
      }
      handle.start(timeRemaining);
      debug('%d list wait because diff is %d', msecs, diff);
      return true;
    }

    // The actual logic for when a timeout happens.

    L.remove(timer);
    assert(timer !== L.peek(list));

    if (!timer._onTimeout) {
      if (destroyHooksExist() && !timer._destroyed &&
            typeof timer[async_id_symbol] === 'number') {
        emitDestroy(timer[async_id_symbol]);
        timer._destroyed = true;
      }
      continue;
    }

    tryOnTimeout(timer);
  }

  // If `L.peek(list)` returned nothing, the list was either empty or we have
  // called all of the timer timeouts.
  // As such, we can remove the list and clean up the TimerWrap C++ handle.
  debug('%d list empty', msecs);
  assert(L.isEmpty(list));

  // Either refedLists[msecs] or unrefedLists[msecs] may have been removed and
  // recreated since the reference to `list` was created. Make sure they're
  // the same instance of the list before destroying.
  if (list._unrefed === true && list === unrefedLists[msecs]) {
    delete unrefedLists[msecs];
  } else if (list === refedLists[msecs]) {
    delete refedLists[msecs];
  }

  // Do not close the underlying handle if its ownership has changed
  // (e.g it was unrefed in its callback).
  if (!handle.owner)
    handle.close();

  return true;
}

// An optimization so that the try/finally only de-optimizes (since at least v8
// 4.7) what is in this smaller function.
function tryOnTimeout(timer, start) {
  timer._called = true;
  const timerAsyncId = (typeof timer[async_id_symbol] === 'number') ?
    timer[async_id_symbol] : null;
  var threw = true;
  if (timerAsyncId !== null)
    emitBefore(timerAsyncId, timer[trigger_async_id_symbol]);
  try {
    ontimeout(timer, start);
    threw = false;
  } finally {
    if (timerAsyncId !== null) {
      if (!threw)
        emitAfter(timerAsyncId);
      if ((threw || !timer._repeat) && destroyHooksExist() &&
          !timer._destroyed) {
        emitDestroy(timerAsyncId);
        timer._destroyed = true;
      }
    }
  }
}

// A convenience function for re-using TimerWrap handles more easily.
//
// This mostly exists to fix https://github.com/nodejs/node/issues/1264.
// Handles in libuv take at least one `uv_run` to be registered as unreferenced.
// Re-using an existing handle allows us to skip that, so that a second `uv_run`
// will return no active handles, even when running `setTimeout(fn).unref()`.
function reuse(item) {
  L.remove(item);

  const list = refedLists[item._idleTimeout];
  // if empty - reuse the watcher
  if (list !== undefined && L.isEmpty(list)) {
    debug('reuse hit');
    list._timer.stop();
    delete refedLists[item._idleTimeout];
    return list._timer;
  }

  return null;
}

// Remove a timer. Cancels the timeout and resets the relevant timer properties.
function unenroll(item) {
  // Fewer checks may be possible, but these cover everything.
  if (destroyHooksExist() &&
      typeof item[async_id_symbol] === 'number' &&
      !item._destroyed) {
    emitDestroy(item[async_id_symbol]);
    item._destroyed = true;
  }

  const handle = reuse(item);
  if (handle !== null) {
    debug('unenroll: list empty');
    handle.close();
  }
  // if active is called later, then we want to make sure not to insert again
  item._idleTimeout = -1;
}

exports.unenroll = util.deprecate(unenroll,
                                  'timers.unenroll() is deprecated. ' +
                                  'Please use clearTimeout instead.',
                                  'DEP0096');

// Make a regular object able to act as a timer by setting some properties.
// This function does not start the timer, see `active()`.
// Using existing objects as timers slightly reduces object overhead.
function enroll(item, msecs) {
  msecs = validateTimerDuration(msecs);

  // if this item was already in a list somewhere
  // then we should unenroll it from that
  if (item._idleNext) unenroll(item);

  L.init(item);
  item._idleTimeout = msecs;
}

exports.enroll = util.deprecate(enroll,
                                'timers.enroll() is deprecated. ' +
                                'Please use setTimeout instead.',
                                'DEP0095');

/*
 * DOM-style timers
 */

function setTimeout(callback, after, arg1, arg2, arg3) {
  if (typeof callback !== 'function') {
    throw new ERR_INVALID_CALLBACK();
  }

  var i, args;
  switch (arguments.length) {
    // fast cases
    case 1:
    case 2:
      break;
    case 3:
      args = [arg1];
      break;
    case 4:
      args = [arg1, arg2];
      break;
    default:
      args = [arg1, arg2, arg3];
      for (i = 5; i < arguments.length; i++) {
        // extend array dynamically, makes .apply run much faster in v6.0.0
        args[i - 2] = arguments[i];
      }
      break;
  }

  const timeout = new Timeout(callback, after, args, false, false);
  active(timeout);

  return timeout;
}

setTimeout[internalUtil.promisify.custom] = function(after, value) {
  const promise = createPromise();
  const timeout = new Timeout(promise, after, [value], false, false);
  active(timeout);

  return promise;
};

exports.setTimeout = setTimeout;

function ontimeout(timer, start) {
  const args = timer._timerArgs;
  if (typeof timer._onTimeout !== 'function')
    return promiseResolve(timer._onTimeout, args[0]);
  if (start === undefined && timer._repeat)
    start = TimerWrap.now();
  if (!args)
    timer._onTimeout();
  else
    Reflect.apply(timer._onTimeout, timer, args);
  if (timer._repeat)
    rearm(timer, start);
}

function rearm(timer, start = TimerWrap.now()) {
  // // Do not re-arm unenroll'd or closed timers.
  if (timer._idleTimeout === -1) return;

  // If timer is unref'd (or was - it's permanently removed from the list.)
  if (timer._handle && timer instanceof Timeout) {
    timer._handle.start(timer._repeat);
  } else {
    timer._idleTimeout = timer._repeat;

    const duration = TimerWrap.now() - start;
    if (duration >= timer._repeat) {
      // If callback duration >= timer._repeat,
      // add 1 ms to avoid blocking eventloop
      insert(timer, false, start + duration - timer._repeat + 1);
    } else {
      insert(timer, false, start);
    }
  }
}

const clearTimeout = exports.clearTimeout = function clearTimeout(timer) {
  if (timer && timer._onTimeout) {
    timer._onTimeout = null;
    if (timer instanceof Timeout) {
      timer.close(); // for after === 0
    } else {
      unenroll(timer);
    }
  }
};

exports.setInterval = function setInterval(callback, repeat, arg1, arg2, arg3) {
  if (typeof callback !== 'function') {
    throw new ERR_INVALID_CALLBACK();
  }

  var i, args;
  switch (arguments.length) {
    // fast cases
    case 1:
    case 2:
      break;
    case 3:
      args = [arg1];
      break;
    case 4:
      args = [arg1, arg2];
      break;
    default:
      args = [arg1, arg2, arg3];
      for (i = 5; i < arguments.length; i++) {
        // extend array dynamically, makes .apply run much faster in v6.0.0
        args[i - 2] = arguments[i];
      }
      break;
  }

  const timeout = new Timeout(callback, repeat, args, true, false);
  active(timeout);

  return timeout;
};

exports.clearInterval = function clearInterval(timer) {
  // clearTimeout and clearInterval can be used to clear timers created from
  // both setTimeout and setInterval, as specified by HTML Living Standard:
  // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  clearTimeout(timer);
};

function unrefdHandle(timer, now) {
  try {
    // Don't attempt to call the callback if it is not a function.
    if (typeof timer._onTimeout === 'function') {
      tryOnTimeout(timer, now);
    }
  } finally {
    // Make sure we clean up if the callback is no longer a function
    // even if the timer is an interval.
    if (!timer._repeat || typeof timer._onTimeout !== 'function') {
      timer.close();
    }
  }

  return true;
}

Timeout.prototype.unref = function() {
  if (this._handle) {
    this._handle.unref();
  } else if (typeof this._onTimeout === 'function') {
    const now = TimerWrap.now();
    if (!this._idleStart) this._idleStart = now;
    var delay = this._idleStart + this._idleTimeout - now;
    if (delay < 0) delay = 0;

    // Prevent running cb again when unref() is called during the same cb
    if (this._called && !this._repeat) {
      unenroll(this);
      return;
    }

    const handle = reuse(this);
    if (handle !== null) {
      handle._list = undefined;
    }

    this._handle = handle || new TimerWrap();
    this._handle.owner = this;
    this._handle.start(delay);
    this._handle.unref();
  }
  return this;
};

Timeout.prototype.ref = function() {
  if (this._handle)
    this._handle.ref();
  return this;
};

Timeout.prototype.close = function() {
  this._onTimeout = null;
  if (this._handle) {
    if (destroyHooksExist() &&
        typeof this[async_id_symbol] === 'number' &&
        !this._destroyed) {
      emitDestroy(this[async_id_symbol]);
      this._destroyed = true;
    }

    this._idleTimeout = -1;
    this._handle.close();
  } else {
    unenroll(this);
  }
  return this;
};

// A linked list for storing `setImmediate()` requests
function ImmediateList() {
  this.head = null;
  this.tail = null;
}

// Appends an item to the end of the linked list, adjusting the current tail's
// previous and next pointers where applicable
ImmediateList.prototype.append = function(item) {
  if (this.tail !== null) {
    this.tail._idleNext = item;
    item._idlePrev = this.tail;
  } else {
    this.head = item;
  }
  this.tail = item;
};

// Removes an item from the linked list, adjusting the pointers of adjacent
// items and the linked list's head or tail pointers as necessary
ImmediateList.prototype.remove = function(item) {
  if (item._idleNext !== null) {
    item._idleNext._idlePrev = item._idlePrev;
  }

  if (item._idlePrev !== null) {
    item._idlePrev._idleNext = item._idleNext;
  }

  if (item === this.head)
    this.head = item._idleNext;
  if (item === this.tail)
    this.tail = item._idlePrev;

  item._idleNext = null;
  item._idlePrev = null;
};

// Create a single linked list instance only once at startup
const immediateQueue = new ImmediateList();

// If an uncaught exception was thrown during execution of immediateQueue,
// this queue will store all remaining Immediates that need to run upon
// resolution of all error handling (if process is still alive).
const outstandingQueue = new ImmediateList();

function processImmediate() {
  const queue = outstandingQueue.head !== null ?
    outstandingQueue : immediateQueue;
  var immediate = queue.head;
  const tail = queue.tail;

  // Clear the linked list early in case new `setImmediate()` calls occur while
  // immediate callbacks are executed
  queue.head = queue.tail = null;

  let count = 0;
  let refCount = 0;

  while (immediate !== null) {
    immediate._destroyed = true;

    const asyncId = immediate[async_id_symbol];
    emitBefore(asyncId, immediate[trigger_async_id_symbol]);

    count++;
    if (immediate[kRefed])
      refCount++;
    immediate[kRefed] = undefined;

    tryOnImmediate(immediate, tail, count, refCount);

    emitAfter(asyncId);

    immediate = immediate._idleNext;
  }

  immediateInfo[kCount] -= count;
  immediateInfo[kRefCount] -= refCount;
  immediateInfo[kHasOutstanding] = 0;
}

// An optimization so that the try/finally only de-optimizes (since at least v8
// 4.7) what is in this smaller function.
function tryOnImmediate(immediate, oldTail, count, refCount) {
  var threw = true;
  try {
    // make the actual call outside the try/finally to allow it to be optimized
    runCallback(immediate);
    threw = false;
  } finally {
    immediate._onImmediate = null;

    if (destroyHooksExist()) {
      emitDestroy(immediate[async_id_symbol]);
    }

    if (threw) {
      immediateInfo[kCount] -= count;
      immediateInfo[kRefCount] -= refCount;

      if (immediate._idleNext !== null) {
        // Handle any remaining Immediates after error handling has resolved,
        // assuming we're still alive to do so.
        outstandingQueue.head = immediate._idleNext;
        outstandingQueue.tail = oldTail;
        immediateInfo[kHasOutstanding] = 1;
      }
    }
  }
}

function runCallback(timer) {
  const argv = timer._argv;
  if (typeof timer._onImmediate !== 'function')
    return promiseResolve(timer._onImmediate, argv[0]);
  if (!argv)
    return timer._onImmediate();
  Reflect.apply(timer._onImmediate, timer, argv);
}

const Immediate = class Immediate {
  constructor(callback, args) {
    this._idleNext = null;
    this._idlePrev = null;
    // this must be set to null first to avoid function tracking
    // on the hidden class, revisit in V8 versions after 6.2
    this._onImmediate = null;
    this._onImmediate = callback;
    this._argv = args;
    this._destroyed = false;
    this[kRefed] = false;

    initAsyncResource(this, 'Immediate');

    this.ref();
    immediateInfo[kCount]++;

    immediateQueue.append(this);
  }

  ref() {
    if (this[kRefed] === false) {
      this[kRefed] = true;
      if (immediateInfo[kRefCount]++ === 0)
        toggleImmediateRef(true);
    }
    return this;
  }

  unref() {
    if (this[kRefed] === true) {
      this[kRefed] = false;
      if (--immediateInfo[kRefCount] === 0)
        toggleImmediateRef(false);
    }
    return this;
  }
};

function setImmediate(callback, arg1, arg2, arg3) {
  if (typeof callback !== 'function') {
    throw new ERR_INVALID_CALLBACK();
  }

  var i, args;
  switch (arguments.length) {
    // fast cases
    case 1:
      break;
    case 2:
      args = [arg1];
      break;
    case 3:
      args = [arg1, arg2];
      break;
    default:
      args = [arg1, arg2, arg3];
      for (i = 4; i < arguments.length; i++) {
        // extend array dynamically, makes .apply run much faster in v6.0.0
        args[i - 1] = arguments[i];
      }
      break;
  }

  return new Immediate(callback, args);
}

setImmediate[internalUtil.promisify.custom] = function(value) {
  const promise = createPromise();
  new Immediate(promise, [value]);
  return promise;
};

exports.setImmediate = setImmediate;

exports.clearImmediate = function clearImmediate(immediate) {
  if (!immediate || immediate._destroyed)
    return;

  immediateInfo[kCount]--;
  immediate._destroyed = true;

  if (immediate[kRefed] && --immediateInfo[kRefCount] === 0)
    toggleImmediateRef(false);
  immediate[kRefed] = undefined;

  if (destroyHooksExist()) {
    emitDestroy(immediate[async_id_symbol]);
  }

  immediate._onImmediate = null;

  immediateQueue.remove(immediate);
};

redpajama_set_name: RedPajamaGithub


text:
namespace math
{

///////////////////////////////////////////////////////////////////////////////
// constructors
///////////////////////////////////////////////////////////////////////////////

template <typename T>
rect<T>::rect() : upperLeftCorner (0, 0) , lowerRightCorner(0, 0)
{
}

template <typename T>
rect<T>::rect(T x, T y, T x2, T y2) : upperLeftCorner(x, y), lowerRightCorner(x2, y2)
{
}

template <typename T>
rect<T>::rect(const vec2<T>& upperLeft, const vec2<T>& lowerRight) : upperLeftCorner(upperLeft), lowerRightCorner(lowerRight)
{
}

///////////////////////////////////////////////////////////////////////////////
// methods
///////////////////////////////////////////////////////////////////////////////

template <typename T>
void rect<T>::set(T x, T y, T x2, T y2)
{
	upperLeftCorner = vec2<T>(x, y);
	lowerRightCorner = vec2<T>(x2, y2);
}

template <typename T>
void rect<T>::set(const vec2<T>& upperLeft, const vec2<T>& lowerRight)
{
	upperLeftCorner = upperLeft;
	lowerRightCorner = lowerRight;
}

template <typename T>
void rect<T>::scale(T scale)
{
	upperLeftCorner  *= scale;
	lowerRightCorner *= scale;
}

template <typename T>
T rect<T>::get_area() const
{
return get_width() * get_height();
}

template <typename T>
T rect<T>::get_width() const
{
	return lowerRightCorner.x - upperLeftCorner.x;
}

template <typename T>
T rect<T>::get_height() const
{
	return lowerRightCorner.y - upperLeftCorner.y;
}

template <typename T>
void rect<T>::repair()
{
	if (lowerRightCorner.x < upperLeftCorner.x)
	{
		T t = lowerRightCorner.x;
		lowerRightCorner.x = upperLeftCorner.x;
		upperLeftCorner.x = t;
	}

	if (lowerRightCorner.y < upperLeftCorner.y)
	{
		T t = lowerRightCorner.y;
		lowerRightCorner.y = upperLeftCorner.y;
		upperLeftCorner.y = t;
	}
}

template <typename T>
bool rect<T>::is_valid() const
{
	return ((lowerRightCorner.x >= upperLeftCorner.x)  && (lowerRightCorner.y >= upperLeftCorner.y));
}

template <typename T>
vec2<T> rect<T>::get_center() const
{
	return vec2<T>((upperLeftCorner.x + lowerRightCorner.x) / 2,
		(upperLeftCorner.y + lowerRightCorner.y) / 2);
}

template <typename T>
vec2<T> rect<T>::get_size() const
{
	return vec2<T>(get_width(), get_height());
}

///////////////////////////////////////////////////////////////////////////////
// containment methods
///////////////////////////////////////////////////////////////////////////////

template <typename T>
bool rect<T>::is_point_inside(const vec2<T>& pos) const
{
	return (
		upperLeftCorner.x  <= pos.x && upperLeftCorner.y  <= pos.y &&
		lowerRightCorner.x >= pos.x && lowerRightCorner.y >= pos.y
		);
}

template <typename T>
bool rect<T>::is_rect_collided(const rect<T>& other) const
{
	return (
		lowerRightCorner.y > other.upperLeftCorner.y && upperLeftCorner.y  < other.lowerRightCorner.y  &&
		lowerRightCorner.x > other.upperLeftCorner.x && upperLeftCorner.x  < other.lowerRightCorner.x
		);
}

template <typename T>
void rect<T>::clip_against(const rect<T>& other)
{
	if (other.lowerRightCorner.x < lowerRightCorner.x)
		lowerRightCorner.x = other.lowerRightCorner.x;
	if (other.lowerRightCorner.y < lowerRightCorner.y)
		lowerRightCorner.y = other.lowerRightCorner.y;

	if (other.upperLeftCorner.x > upperLeftCorner.x)
		upperLeftCorner.x = other.upperLeftCorner.x;
	if (other.upperLeftCorner.y > upperLeftCorner.y)
		upperLeftCorner.y = other.upperLeftCorner.y;

	// correct possible invalid rect resulting from clipping
	if (upperLeftCorner.y > lowerRightCorner.y)
		upperLeftCorner.y = lowerRightCorner.y;
	if (upperLeftCorner.x > lowerRightCorner.x)
		upperLeftCorner.x = lowerRightCorner.x;
}

template <typename T>
bool rect<T>::constrain_to(const rect<T>& other)
{
	if (other.get_width() < get_width()  ||  other.get_height() < get_height())
		return false;

	T diff = other.lowerRightCorner.x - lowerRightCorner.x;
	if (diff < 0)
	{
		lowerRightCorner.x += diff;
		upperLeftCorner.x  += diff;
	}

	diff = other.lowerRightCorner.y - lowerRightCorner.y;
	if (diff < 0)
	{
		lowerRightCorner.y += diff;
		upperLeftCorner.y  += diff;
	}

	diff = upperLeftCorner.x - other.upperLeftCorner.x;
	if (diff < 0)
	{
		upperLeftCorner.x  -= diff;
		lowerRightCorner.x -= diff;
	}

	diff = upperLeftCorner.y - other.upperLeftCorner.y;
	if (diff < 0)
	{
		upperLeftCorner.y  -= diff;
		lowerRightCorner.y -= diff;
	}

	return true;
}

template <typename T>
vec2<T> rect<T>::get_closest_point(const vec2<T>& pt) const
{
	vec2<T> result(clamp(pt, upperLeftCorner, lowerRightCorner));
	return result;
}

template <typename T>
void rect<T>::grow(const T& size)
{
	grow(vec2<T>(size));
}

template <typename T>
void rect<T>::grow(const vec2<T>& size)
{
	upperLeftCorner -= size;
	lowerRightCorner += size;
}

template <typename T>
void rect<T>::clamp_to_min(const T& size)
{
	clamp_to_min(vec2<T>(size));
}

template <typename T>
void rect<T>::clamp_to_min(const vec2<T>& minSize)
{
	T curWidth = get_width();
	if (curWidth < minSize.x)
	{
		T widthToGrow = (minSize.x - curWidth) * (T)(0.5);
		upperLeftCorner.x -= widthToGrow;
		lowerRightCorner.x += widthToGrow;
	}

	T curHeight = get_height();
	if (curHeight < minSize.y)
	{
		T heightToGrow = (minSize.y - curHeight) * (T)(0.5);
		upperLeftCorner.y -= heightToGrow;
		lowerRightCorner.y += heightToGrow;
	}
}

template <typename T>
void rect<T>::clamp_to_max(const T& size)
{
	ClampToMax(vec2<T>(size));
}

template <typename T>
void rect<T>::clamp_to_max(const vec2<T>& maxSize)
{
    MATH_ASSERT(maxSize.x >= 0.0f && maxSize.y >= 0.0f);

	T curWidth = get_width();
	if (curWidth > maxSize.x)
	{
		T widthToShrink = (curWidth - maxSize.x) * (T)(0.5);
		upperLeftCorner.x += widthToShrink;
		lowerRightCorner.x -= widthToShrink;
	}

	T curHeight = get_height();
	if (curHeight > maxSize.y)
	{
		T heightToShrink = (curHeight - maxSize.y) * (T)(0.5);
		upperLeftCorner.y += heightToShrink;
		lowerRightCorner.y -= heightToShrink;
	}
}

template <typename T>
void rect<T>::add_internal_point(const vec2<T>& p)
{
	add_internal_point(p.x, p.y);
}

template <typename T>
void rect<T>::add_internal_point(T x, T y)
{
	if (x>lowerRightCorner.x)
		lowerRightCorner.x = x;
	if (y>lowerRightCorner.y)
		lowerRightCorner.y = y;

	if (x<upperLeftCorner.x)
		upperLeftCorner.x = x;
	if (y<upperLeftCorner.y)
		upperLeftCorner.y = y;
}

///////////////////////////////////////////////////////////////////////////////
// operators
///////////////////////////////////////////////////////////////////////////////

template <typename T>
rect<T> rect<T>::operator+(const vec2<T>& pos) const
{
	rect<T> ret(*this);
	return ret+=pos;
}

template <typename T>
rect<T>& rect<T>::operator+=(const vec2<T>& pos)
{
	upperLeftCorner  += pos;
	lowerRightCorner += pos;
	return *this;
}

template <typename T>
rect<T> rect<T>::operator-(const vec2<T>& pos) const
{
	rect<T> ret(*this);
	return ret-=pos;
}

template <typename T>
rect<T> rect<T>::operator*(const T& scale) const
{
	rect<T> ret(upperLeftCorner*scale, lowerRightCorner*scale);
	return ret;
}

template <typename T>
rect<T> rect<T>::operator/(const T& scale) const
{
	rect<T> ret(upperLeftCorner/scale, lowerRightCorner/scale);
	return ret;
}

template <typename T>
rect<T>& rect<T>::operator-=(const vec2<T>& pos)
{
	upperLeftCorner  -= pos;
	lowerRightCorner -= pos;
	return *this;
}

template <typename T>
bool rect<T>::operator==(const rect<T>& other) const
{
	return (upperLeftCorner  == other.upperLeftCorner  &&
		lowerRightCorner == other.lowerRightCorner);
}

template <typename T>
bool rect<T>::operator!=(const rect<T>& other) const
{
	return (upperLeftCorner  != other.upperLeftCorner  ||
		lowerRightCorner != other.lowerRightCorner);
}

template <typename T>
rect<T>& rect<T>::operator+=(const rect<T>& other)
{
	add_internal_point(other.upperLeftCorner);
	add_internal_point(other.lowerRightCorner);
	return *this;
}

template <typename T>
bool rect<T>::operator<(const rect<T>& other) const
{
	return get_area() < other.getArea();
}

}


text:
package com.google.template.soy.basicfunctions;

import com.google.common.collect.ImmutableSet;
import com.google.template.soy.data.SoyLegacyObjectMap;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.internal.ListImpl;
import com.google.template.soy.jbcsrc.restricted.JbcSrcPluginContext;
import com.google.template.soy.jbcsrc.restricted.MethodRef;
import com.google.template.soy.jbcsrc.restricted.SoyExpression;
import com.google.template.soy.jbcsrc.restricted.SoyJbcSrcFunction;
import com.google.template.soy.jssrc.restricted.JsExpr;
import com.google.template.soy.jssrc.restricted.SoyLibraryAssistedJsSrcFunction;
import com.google.template.soy.pysrc.restricted.PyExpr;
import com.google.template.soy.pysrc.restricted.PyListExpr;
import com.google.template.soy.pysrc.restricted.SoyPySrcFunction;
import com.google.template.soy.shared.restricted.Signature;
import com.google.template.soy.shared.restricted.SoyFunctionSignature;
import com.google.template.soy.shared.restricted.SoyJavaFunction;
import com.google.template.soy.shared.restricted.SoyPureFunction;
import com.google.template.soy.shared.restricted.TypedSoyFunction;
import com.google.template.soy.types.IntType;
import com.google.template.soy.types.LegacyObjectMapType;
import com.google.template.soy.types.ListType;
import com.google.template.soy.types.SoyType;
import com.google.template.soy.types.SoyType.Kind;
import com.google.template.soy.types.UnknownType;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Soy function that gets the keys in a map. This method is only used for legacy_object_map. For new
 * map type (proto map and ES6 map in JS), use {@code MapKeysFunction} instead.
 *
 *
This function also supports list input to mimic JS behaviors. In JS, list is also an object,
 * and iterating its keys returns a list of indices.
 *
 *
The keys are returned as a list with no guarantees on the order (may be different on each run
 * or for each backend).
 *
 *
This enables iteration over the keys in a map, e.g. {@code {for $key in keys($myMap)} ...
 * {/for}}
 *
 */
@SoyFunctionSignature(
  name = "keys",
  // TODO(b/70946095): should take a map, or maybe we should add special support in the type
  // checker in order to infer the returned list type
  value = @Signature(returnType = "?", parameterTypes = "?")
)
@Singleton
@SoyPureFunction
public final class KeysFunction extends TypedSoyFunction
    implements SoyJavaFunction,
        SoyLibraryAssistedJsSrcFunction,
        SoyPySrcFunction,
        SoyJbcSrcFunction {

  @Inject
  KeysFunction() {}

  @Override
  public SoyValue computeForJava(List<SoyValue> args) {
    SoyValue arg = args.get(0);

    if (!(arg instanceof SoyLegacyObjectMap)) {
      throw new IllegalArgumentException("Argument to keys() function is not SoyLegacyObjectMap.");
    }

    return ListImpl.forProviderList(BasicFunctionsRuntime.keys((SoyLegacyObjectMap) arg));
  }

  @Override
  public JsExpr computeForJsSrc(List<JsExpr> args) {
    JsExpr arg = args.get(0);

    return new JsExpr("soy.$$getMapKeys(" + arg.getText() + ")", Integer.MAX_VALUE);
  }

  @Override
  public ImmutableSet<String> getRequiredJsLibNames() {
    return ImmutableSet.<String>of("soy");
  }

  @Override
  public PyExpr computeForPySrc(List<PyExpr> args) {
    PyExpr arg = args.get(0);

    return new PyListExpr("(" + arg.getText() + ").keys()", Integer.MAX_VALUE);
  }

  // lazy singleton pattern, allows other backends to avoid the work.
  private static final class JbcSrcMethods {
    static final MethodRef KEYS_FN =
        MethodRef.create(BasicFunctionsRuntime.class, "keys", SoyLegacyObjectMap.class);
  }

  @Override
  public SoyExpression computeForJbcSrc(JbcSrcPluginContext context, List<SoyExpression> args) {
    SoyExpression soyExpression = args.get(0);
    SoyType argType = soyExpression.soyType();
    // TODO(lukes): this logic should live in ResolveExpressionTypesVisitor
    SoyType listElementType;
    if (argType.getKind() == Kind.LEGACY_OBJECT_MAP) {
      listElementType = ((LegacyObjectMapType) argType).getKeyType(); // pretty much just string
    } else if (argType.getKind() == Kind.LIST) {
      listElementType = IntType.getInstance();
    } else {
      listElementType = UnknownType.getInstance();
    }
    return SoyExpression.forList(
        ListType.of(listElementType),
        JbcSrcMethods.KEYS_FN.invoke(soyExpression.box().checkedCast(SoyLegacyObjectMap.class)));
  }
}


text:
<?php
namespace RESTful\Service;
use RESTful\Base\Service;

/**
 * RESTful - Standalone RESTful server library
 * @author: Daniel Aranda (https://github.com/daniel-aranda/)
 *
 */

class TestService extends Service{

    public function getAdd(){
        return ['works'];
    }

    public function getIndex($id, $comments = null){
        return ['working', $comments];
    }

    public function getNumber(){
        return 5;
    }

}


text:
{% extends "oscar/customer/login_registration.html" %}
{% load currency_filters %}
{% load i18n %}

{% block content %}

        <form id="login_form" action="{{ request.get_full_path }}" method="post" class="form-stacked" >

{% trans 'Log In' %}

            {% csrf_token %}
            {% include "partials/form_fields.html" with form=login_form %}

{% trans "I've forgotten my password" %}

            <button name="login_submit" type="submit" value="Log In" class="btn btn-primary">{% trans 'Log In' %}</button>
        </form>

        <form id="register_form" action="{{ request.get_full_path }}" method="post" class="form-stacked">

{% trans 'Register' %}

            {% csrf_token %}
            {% include "partials/form_fields.html" with form=registration_form %}
            <button name="registration_submit" type="submit" value="Register" class="btn btn-primary js-disable-on-click" data-loading-text="{%trans 'Registering...' %}">{% trans 'Register' %}</button>
        </form>

{% endblock content %}


text:
import os, time
from lib.config import Config
from lib.configs.mesos_config import MesosConfig
from lib.utils import Utils

LOG = MesosConfig.setup(__file__)

def ensure_deb_packaging():
    path = MesosConfig.deb_packaging_repository_dir()
    if os.path.isdir("{}/.git".format(path)):
        LOG.info("Updating sources for {}...".format(MesosConfig.deb_packaging_repository()))
        # TODO: compare given sha and repo sha
        # TODO: if different, reset, pull, checkout
        # TODO: apply patches for deb-packaging, if any...
        LOG.info("Done.")
        return True
    else:
        LOG.info("No sources for {} found. Cloning...".format(MesosConfig.deb_packaging_repository()))
        result = Utils.cmd("cd {} && git clone {} . && git fetch origin && git checkout {}".format(
                                                            path,
                                                            MesosConfig.deb_packaging_repository(),
                                                            MesosConfig.deb_packaging_sha() ))
        if result['ExitCode'] == 0:
            LOG.info("Done.")
            # TODO: apply patches for deb-packaging, if any...
            return True
        else:
            Utils.print_result_error(LOG, "Failed.", result)
            return False

def validate_input():
    mesos_version = MesosConfig.mesos_version()
    operating_system = MesosConfig.operating_system()
    if mesos_version == "":
        Utils.exit_with_cmd_error( __file__, "Mesos version not given. Run with show-releases to see what the available versions are.")
    if operating_system == "":
        Utils.exit_with_cmd_error( __file__, "Operating system not given. Available values: {}".format( str(MesosConfig.supported_operating_systems()) ))
    if not mesos_version in list_releases():
        Utils.exit_with_cmd_error( __file__,
                                   "Mesos version ({}) is not supported. Run with show-releases to see what the available versions are.".format(
                                    mesos_version ))
    if not operating_system in MesosConfig.supported_operating_systems():
        Utils.exit_with_cmd_error( __file__,
                                   "Operating system ({}) is not supported. Available values: {}".format(
                                    operating_system,
                                    str(MesosConfig.supported_operating_systems()) ))
    if operating_system == "osx" and Utils.platform() != "darwin":
        Utils.exit_with_cmd_error( __file__, "Operating system (osx) is only supported when running this program on OS X." )

def list_releases():
    return Utils.list_releases(LOG, MesosConfig.mesos_repository_dir(), MesosConfig.mesos_master_branch())

def validate_osx_dependencies():
    # TODO: implement
    return True

def build_with_docker(build_dir_mesos, build_dir_packaging, packages_dir):
    image_name = "mesos-docker-build-{}".format(MesosConfig.operating_system().replace(":","-"))
    if not Utils.is_docker_image(LOG, image_name):
        LOG.info("Docker image not found. Building...")
        Utils.exit_if_docker_image_not_built( LOG,
                                              MesosConfig.docker_templates_dir(),
                                              MesosConfig.operating_system().replace(":", "\\:"),
                                              image_name )

    mesos_build_command = "docker run -ti -v {}:/mesos-deb-packaging -v {}:/mesos-src {} /bin/bash -c 'cd /mesos-deb-packaging && ./build_mesos --build-version {} --src-dir /mesos-src; exit $?'".format(
                                  build_dir_packaging,
                                  build_dir_mesos,
                                  image_name,
                                  MesosConfig.mesos_build_version() )

    LOG.info("Docker command: {}".format(mesos_build_command))
    LOG.info("Building Mesos {} for {}. This will take a while...".format(MesosConfig.mesos_version(), MesosConfig.operating_system()))

    build_start_time = int(time.time())
    build_status = Utils.cmd(mesos_build_command)
    build_end_time = int(time.time())
    if build_status['ExitCode'] == 0:
        Utils.cmd("mkdir -p {0} && rm -Rf {0}/*".format( packages_dir ))
        Utils.cmd("mv {}/*.deb {}/ 2>/dev/null".format( build_dir_packaging, packages_dir ))
        Utils.cmd("mv {}/*.rpm {}/ 2>/dev/null".format( build_dir_packaging, packages_dir ))
        Utils.cmd("mv {}/*.egg {}/ 2>/dev/null".format( build_dir_packaging, packages_dir ))#
        LOG.info( "Mesos {} for {} built successfully. Build took {} seconds. Output available in {}. Cleaning up...".format(
                    MesosConfig.mesos_version(),
                    MesosConfig.operating_system(),
                    str( build_end_time - build_start_time ),
                    packages_dir ))

        cleanup_command = "rm -rf {}".format(build_dir_mesos)
        result = Utils.cmd(cleanup_command)
        if result['ExitCode'] != 0:
            LOG.error("Failed to cleanup Mesos build temporary directory. Consider exectuing: sudo {}".format(cleanup_command))

        cleanup_command = "rm -rf {}".format(build_dir_packaging)
        result = Utils.cmd(cleanup_command)
        if result['ExitCode'] != 0:
            LOG.error("Failed to cleanup Mesos deb packaging temporary directory. Consider exectuing: sudo {}".format(cleanup_command))
    else:
        LOG.error( "Mesos build failed. Leaving build log and temp directories for inspection. mesos={}; packaging={}".format( build_dir_mesos, build_dir_packaging ) )
        exit(107)

def build_with_osx(build_dir_mesos, build_dir_packaging, packages_dir):
    # TODO: provide correct implementation
    Utils.cmd( "cd {} && ./build_mesos --build-version {} --src-dir {}".format(
                    Config.deb_packaging_repository_dir(),
                    Config.args().mesos_build_version,
                    Config.mesos_repository_dir() ) )

## ----------------------------------------------------------------------------------------------
## OPERATIONS:
## ----------------------------------------------------------------------------------------------

def op_show_releases():
    if Utils.ensure_sources(LOG, MesosConfig.mesos_repository_dir(), MesosConfig.mesos_git_repository()):
        LOG.info("Releases:")
        for line in list_releases():
            if line != "":
                print line

def op_remove_build():
    validate_input()
    if not Utils.confirm("You are about to remove Mesos build for {} {}.".format(
            MesosConfig.mesos_version(),
            MesosConfig.operating_system() )):
        LOG.info("You have cancelled the action.")
        exit(0)
    Utils.cmd("rm -rf {}/{}-{}".format( MesosConfig.packages_dir(),
                                        MesosConfig.mesos_version(),
                                        MesosConfig.operating_system().replace(":", "-")))

def op_remove_mesos_sources():
    if not Utils.confirm("You are about to remove Mesos sources for {}.".format( MesosConfig.mesos_git_repository() )):
        LOG.info("You have cancelled the action.")
        exit(0)
    Utils.cmd("rm -rf {}".format( MesosConfig.mesos_repository_dir() ))

def op_remove_packaging_sources():
    if not Utils.confirm("You are about to remove mesos-deb-packaging sources for {}.".format( MesosConfig.deb_packaging_repository() )):
        LOG.info("You have cancelled the action.")
        exit(0)
    Utils.cmd("rm -rf {}".format( MesosConfig.deb_packaging_repository_dir() ))

def op_check_this_system():
    LOG.info("Checking dependencies:")
    LOG.info(" -> Docker?             : {}".format( "Yes" if Utils.is_docker_available() else "No" ))
    LOG.info(" -> Git?                : {}".format( "Yes" if Utils.is_git_available() else "No" ))
    if Utils.platform() == "darwin":
        LOG.info(" -> Command line tools? : {}".format( "Yes" if Utils.is_xcode_available() else "No" ))
        LOG.info(" -> Java 8?             : {}".format( "Yes" if Utils.is_java_available() else "No" ))
        LOG.info(" -> Maven?              : {}".format( "Yes" if Utils.is_git_available() else "No" ))
        LOG.info(" -> Subversion 1.9.x?   : {}".format( "Yes" if Utils.is_svn_available() else "No" ))
        LOG.info(" -> autoconf?           : {}".format( "Yes" if Utils.is_autoconf_available() else "No" ))
        LOG.info(" -> automake?           : {}".format( "Yes" if Utils.is_automake_available() else "No" ))
        LOG.info(" -> libtool?            : {}".format( "Yes" if Utils.is_libtool_available() else "No" ))
        LOG.info(" -> apr?                : {}".format( "Yes" if Utils.is_apr_available() else "No" ))

def op_docker_image():
    # TODO: implement
    return False

def apply_packaging_patches(build_dir_packaging):
    ## LOOKUP order:
    #   - <sha>-<mesos-version>-<os-family>-<os-version>
    #   - <sha>-<mesos-version>-<os-family>
    #   - <sha>-<os-family>-<os-version>
    #   - <sha>-<os-family>
    #   - <sha>
    patch_files = [
        "{}/{}-{}-{}.patch".format(
                            MesosConfig.packages_patches_dir(),
                            MesosConfig.deb_packaging_sha(),
                            MesosConfig.mesos_version(),
                            MesosConfig.operating_system().replace(":", "-") ),
        "{}/{}-{}-{}.patch".format(
                            MesosConfig.packages_patches_dir(),
                            MesosConfig.deb_packaging_sha(),
                            MesosConfig.mesos_version(),
                            MesosConfig.operating_system().split(":")[0] ),
        "{}/{}-{}.patch".format(
                            MesosConfig.packages_patches_dir(),
                            MesosConfig.deb_packaging_sha(),
                            MesosConfig.operating_system().replace(":", "-") ),
        "{}/{}-{}.patch".format(
                            MesosConfig.packages_patches_dir(),
                            MesosConfig.deb_packaging_sha(),
                            MesosConfig.operating_system().split(":")[0] ),
        "{}/{}.patch".format(
                            MesosConfig.packages_patches_dir(),
                            MesosConfig.deb_packaging_sha() ) ]
    patch_file_to_use = None
    for patch_file in patch_files:
        if os.path.isfile(patch_file):
            patch_file_to_use = patch_file
            break
    if patch_file_to_use != None:
        LOG.info("Found a patch file {} for mesos-deb-packaging. Applying...".format( patch_file_to_use ))
        result = Utils.cmd("cd {} && git apply {}".format(build_dir_packaging, patch_file_to_use))
        if result['ExitCode'] != 0:
            Utils.print_result_error(LOG, "Patch could not be applied to {}.".format( build_dir_packaging ), result)
            exit(105)
        else:
            LOG.info("Patch applied.")
    else:
        LOG.info("No patches for mesos-deb-packaging {}.".format( MesosConfig.deb_packaging_sha() ))

def apply_mesos_patches(build_dir_mesos):
    ## LOOKUP order:
    #   - <mesos-version>-<os-family>-<os-version>
    #   - <mesos-version>-<os-family>
    #   - <mesos-version>
    patch_files = [
        "{}/{}-{}.patch".format(
                            MesosConfig.mesos_patches_dir(),
                            MesosConfig.mesos_version(),
                            MesosConfig.operating_system().replace(":", "-") ),
        "{}/{}-{}.patch".format(
                            MesosConfig.mesos_patches_dir(),
                            MesosConfig.mesos_version(),
                            MesosConfig.operating_system().split(":")[0] ),
        "{}/{}.patch".format(
                            MesosConfig.mesos_patches_dir(),
                            MesosConfig.mesos_version() ) ]

    patch_file_to_use = None
    for patch_file in patch_files:
        if os.path.isfile(patch_file):
            patch_file_to_use = patch_file
            break

    if patch_file_to_use != None:
        LOG.info("Found a patch file {} for mesos. Applying...".format( patch_file_to_use ))
        result = Utils.cmd("cd {} && git apply {}".format(build_dir_mesos, patch_file_to_use))
        if result['ExitCode'] != 0:
            Utils.print_result_error(LOG, "Patch could not be applied to {}.".format( build_dir_mesos ), result)
            exit(105)
        else:
            LOG.info("Patch applied.")
    else:
        LOG.info("No patches for mesos {}.".format( MesosConfig.deb_packaging_sha() ))

def op_build():

    validate_input()
    if Utils.ensure_sources(LOG, MesosConfig.mesos_repository_dir(), MesosConfig.mesos_git_repository()) and ensure_deb_packaging():

        # create temp work dir:
        build_dir_mesos    = "{}/{}-{}".format( MesosConfig.work_dir(),
                                        MesosConfig.mesos_version(),
                                        MesosConfig.operating_system().replace(":", "-") )
        build_dir_packaging = "{}/{}-{}-packaging".format( MesosConfig.work_dir(),
                                        MesosConfig.mesos_version(),
                                        MesosConfig.operating_system().replace(":", "-") )
        packages_dir        = "{}/{}-{}".format( MesosConfig.packages_dir(),
                                        MesosConfig.mesos_version(),
                                        MesosConfig.operating_system().replace(":", "-") )

        if os.path.exists(packages_dir):
            if not Utils.confirm("Mesos build for {} {} already exists. To rebuild, continue.".format(
                    MesosConfig.mesos_version(),
                    MesosConfig.operating_system() )):
                LOG.info("You have cancelled the action.")
                exit(0)

        build_log_file = "{}.{}.log".format(build_dir_mesos, str(int(time.time())))
        LOG.info("Recording build process to {}.".format(build_log_file))
        Config.set_cmd_log(build_log_file)

        # cleanup old data:
        Utils.cmd("rm -rf {}".format(packages_dir))
        Utils.cmd("rm -rf {}".format(build_dir_mesos))
        Utils.cmd("rm -rf {}".format(build_dir_packaging))

        # copy sources
        LOG.info("Fetching Mesos {} sources...".format(MesosConfig.mesos_git_repository()))
        Utils.cmd("cp -R {} {}".format( MesosConfig.mesos_repository_dir(), build_dir_mesos ))
        Utils.cmd("cp -R {} {}".format( MesosConfig.deb_packaging_repository_dir(), build_dir_packaging ))

        apply_packaging_patches(build_dir_packaging)

        # ensure branch / tag
        Utils.exit_if_git_release_not_set( LOG,
                                           build_dir_mesos,
                                           MesosConfig.mesos_version(),
                                           MesosConfig.mesos_master_branch(),
                                           MesosConfig.mesos_git_repository() )

        apply_mesos_patches(build_dir_mesos)

        # We have the right sources now:
        if MesosConfig.operating_system() == "osx":
            build_with_osx( build_dir_mesos, build_dir_packaging, packages_dir )
        else:
            build_with_docker( build_dir_mesos, build_dir_packaging, packages_dir )

if __name__ == "__main__":

    if "build" == MesosConfig.command(): op_build()
    if "docker" == MesosConfig.command(): op_docker_image()
    if "show-releases" == MesosConfig.command(): op_show_releases()
    if "show-builds" == MesosConfig.command(): Utils.print_builds( LOG, MesosConfig.packages_dir() )
    if "remove-build" == MesosConfig.command(): op_remove_build()
    if "show-mesos-sources" == MesosConfig.command(): Utils.list_sources(MesosConfig.source_dir(), 'mesos')
    if "show-packaging-sources" == MesosConfig.command(): Utils.list_sources(MesosConfig.source_dir(), 'mesos-packaging')
    if "remove-mesos-sources" == MesosConfig.command(): op_remove_mesos_sources()
    if "remove-packaging-sources" == MesosConfig.command(): op_remove_packaging_sources()
    if "check-this-system" == MesosConfig.command(): op_check_this_system()


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'vizu'
require 'rspec'
require 'rspec/autorun'

require 'eventmachine'
require 'em-websocket'
require 'em-http-request'

RSpec.configure do |config|

end


text:
if(typeof(LZCONFIG) === 'undefined'){
  LZCONFIG = {
    'templateUrl': '../views/',
    'ajaxUrl': '/api/',
  };
}

angular.module('lzCricket', [
  'ngAnimate'
])
.constant('appConfig', {
  path: {
    img: 'http://img.litzscore.com/',
  },
  cricket: {
    possibleInnings: ['1', '2', '9'],
    possibleTeams: ['a', 'b'],
  }
})

.service('lzAPI', function($q, $http){

  var LZAPI = function(){

  };

  LZAPI.prototype.getMatch = function(key, sec){
    var def = $q.defer();
    $http({
      url: LZCONFIG.ajaxUrl,// + '/?action=lzmatch',
      method: "POST",
      params: {
        'action': 'lzmatch',
        'key': key,
        'sec': sec
      }
    })
    .success(function(data, status, headers, config){
      if(data && data.data && data.data.card){
        def.resolve(data.data.card);
      }else{
        def.reject(data, status);
      }
    })
    .error(function(data, status, headers, config){
      def.reject(data, status);
    });

    return def.promise;
  };

  return new LZAPI();
})
.directive('lzCricketMatch', function(lzAPI){
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: LZCONFIG.templateUrl + 'lz-cricket-match.html',
    scope: {
      'lzCricketMatch': '@',
      'sec': '@'
    },

    controller: function($scope, $element, $attrs, appConfig, $timeout) {
      $scope.dataStatus = 'loading'; //'ready', 'error'
      $scope.match = null;
      $scope.activeView = null;
      $scope.appConfig = appConfig;

      $scope.teamFlagUrl = function(key){
        if(LZCONFIG['flags'] && LZCONFIG.flags[key]){
          return LZCONFIG.flags[key];
        }else{
          return 'http://img.litzscore.com/flags/' + key + '_s.png'
        }
      }

      function onMatchUpdate(match){

        $scope.match = match;

        var mDate = moment.unix(match.start_date.timestamp);
        var deltaDays = Math.abs(mDate.diff(moment(), 'days'));
        var dateStr = mDate.format("dddd, MMMM Do YYYY, h:mm:ss a");

        if( deltaDays < 7 ){
          dateStr = mDate.calendar();
        }

        match.start_date.show_cal = dateStr;
        match.start_date.starts_in = mDate.fromNow();

        if(Math.abs(mDate.diff(moment(), 'minutes')) < 2){
          match.start_date.starts_in = 'Now';
        }

        if(match.winner_team){
          match.loser_team = (match.winner_team == 'a')?'b':'a';
        }

        match.allInnings = {};
        for(var i=0, b=null; b=match.batting_order[i]; i++){
          var k = b[0] + '_' + b[1];
          match.allInnings[k] = match.innings[k];
          match.allInnings[k].teamKey = b[0];
          match.allInnings[k].inningsNumber = b[1];
        }

        if(!($scope.activeView) && match.batting_order.length > 0){
          $scope.activeView = 'scorecard';
        }else if(!$scope.activeView){
          $scope.activeView = 'overview';
        }

        $scope.dataStatus = 'ready';
        D = match;
        console.log(D);

        $timeout(function(){
          lzAPI.getMatch($scope.lzCricketMatch,
            $scope.sec).then(onMatchUpdate);
        }, 1000 * 30);

      }

      lzAPI.getMatch($scope.lzCricketMatch, $scope.sec).then(
        onMatchUpdate,
        function(er){
          $scope.dataStatus = 'error';
        }
      );

    }

  }
});


text:
<?php

/*
	This displays the "Add Category" form.
*/

// FROM HERE (until below where I say UNTIL HERE) is the intranet user authentication stuff which would need changing

$path = $_SERVER['DOCUMENT_ROOT'] . '/peds/pass/includes/catnetapps.inc';
require_once $path;

// instantiate class
$catn= NEW CatnetApps();

$keyid = $catn->getVariable("keyid");
$catn->setUserInfo($keyid);
$catn->dbconnect("catnet",$catn->dbuser,$catn->dbpassword);

// UNTIL HERE - note that this includes the database connection, so that would have to be redone as well

echo "";
?>

<?php
echo "
";

echo "
";
echo "

";
echo "
Add Category
";
echo "

";
echo "
 	Category: <input type='text' id='theCategory'>
";
echo "

";
echo "
		<input type='button' value='Cancel' onClick='hideAddCategory()'>   <input type='button' value='Add Category' onClick='addCategory()'>
";
echo "
";
echo "";
$catn->dbdisconnect();
?>


text:
package org.codehaus.mojo.clirr;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import net.sf.clirr.core.ApiDifference;
import net.sf.clirr.core.MessageTranslator;

import org.codehaus.plexus.util.SelectorUtils;
import org.codehaus.plexus.util.xml.pull.MXParser;
import org.codehaus.plexus.util.xml.pull.XmlPullParser;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

/**
 * A specification of a ignored difference found by Clirr.
 *
 * @author Lukas Krejci
 * @since 2.5
 */
public class Difference
{

    public static class Result
    {
        public static final int MATCHED = 0;

        public static final int NOT_MATCHED = 1;

        public static final int DEFERRED_MATCH = 2;

        public Result( int code, Object differentiator )
        {
            this.code = code;
            this.differentiator = differentiator;
        }

        public static Result notMatched()
        {
            return new Result( NOT_MATCHED, null );
        }

        public static Result matched()
        {
            return new Result( MATCHED, null );
        }

        public static Result deferred( Object differentiator )
        {
            return new Result( DEFERRED_MATCH, differentiator );
        }

        private int code;

        private Object differentiator;

        public int getCode()
        {
            return code;
        }

        public Object getDifferentiator()
        {
            return differentiator;
        }
    }

    private static final MessageTranslator ARGS_EXTRACTOR = new MessageTranslator();
    static
    {
        ARGS_EXTRACTOR.setResourceName( Difference.class.getName() );
    }

    public static Difference[] parseXml( Reader xml )
        throws XmlPullParserException, IOException
    {
        XmlPullParser parser = new MXParser();
        parser.setInput( xml );

        List<Difference> diffs = new ArrayList<Difference>();

        int state = 0;
        int event;
        Difference current = null;
        while ( ( event = parser.next() ) != XmlPullParser.END_DOCUMENT )
        {
            switch ( event )
            {
                case XmlPullParser.START_TAG:
                    switch ( state )
                    {
                        case 0: // start document
                            state = 1;
                            break;
                        case 1: // expect next difference
                            if ( "difference".equals( parser.getName() ) )
                            {
                                current = new Difference();
                                state = 2;
                            }
                            break;
                        case 2: // reading difference
                            String name = parser.getName();
                            String value = parser.nextText().trim();
                            if ( "className".equals( name ) )
                            {
                                current.className = value;
                            }
                            else if ( "differenceType".equals( name ) )
                            {
                                current.differenceType = Integer.parseInt( value );
                            }
                            else if ( "field".equals( name ) )
                            {
                                current.field = value;
                            }
                            else if ( "method".equals( name ) )
                            {
                                current.method = value;
                            }
                            else if ( "from".equals( name ) )
                            {
                                current.from = value;
                            }
                            else if ( "to".equals( name ) )
                            {
                                current.to = value;
                            }
                            else if ( "justification".equals( name ) )
                            {
                                current.justification = value;
                            }
                            break;
                    }
                    break;
                case XmlPullParser.END_TAG:
                    switch ( state )
                    {
                        case 1:
                        case 2:
                            if ( "difference".equals( parser.getName() ) )
                            {
                                diffs.add( current );
                                state = 1;
                            }
                            break;
                    }
            }
        }

        return diffs.toArray( new Difference[diffs.size()] );
    }

    /**
     * See http://clirr.sourceforge.net/clirr-core/exegesis.html for the different codes of differences.
     *

     * Different types of differences require different parameters set (className is always required):
     *

     *
1000 (Increased visibility of a class): no other params but className
     *
1001 (Decreased visibility of a class): no other params but className
     *
2000 (Changed from class to interface): no other params but className
     *
2001 (Changed from interface to class): no other params but className
     *
3001 (Removed final modifier from class): no other params but className
     *
3002 (Added final modifier to effectively final class): no other params but className
     *
3003 (Added final modifier to class): no other params but className
     *
3004 (Removed abstract modifier from class): no other params but className
     *
3005 (Added abstract modifier to class): no other params but className
     *
4000 (Added interface to the set of implemented interfaces): className, to (as a path expression)
     *
4001 (Removed interface from the set of implemented interfaces): className, to (as a path expression)
     *
5000 (Added class to the set of superclasses): className, to (as a path expression)
     *
5001 (Removed class from the set of superclasses): className, to (as a path expression)
     *
6000 (added field): className, field
     *
6001 (removed field): className, field
     *
6002 (field value no longer a compile-time constant): className, field
     *
6003 (value of the compile-time constant changed on a field): className, field
     *
6004 (field type changed): className, field, from, to
     *
6005 (field now non-final): className, field
     *
6006 (field now final): className, field
     *
6007 (field now non-static): className, field
     *
6008 (field now static): className, field
     *
6009 (field more accessible): className, field
     *
6010 (field less accessible): className, field
     *
6011 (removed a constant field): className, field
     *
7000 (method now in superclass): className, method
     *
7001 (method now in interface): className, method
     *
7002 (method removed): className, method
     *
7003 (Method Overide Removed): className, method
     *
7004 (Method Argument Count Changed): className, method
     *
7005 (Method Argument Type changed): className, method, to (to is a full new signature)
     *
7006 (Method Return Type changed): className, method, to (to is just the return type)
     *
7007 (Method has been Deprecated): className, method
     *
7008 (Method has been Undeprecated): className, method
     *
7009 (Method is now Less Accessible): className, method
     *
7010 (Method is now More Accessible): className, method
     *
7011 (Method Added): className, method
     *
7012 (Method Added to Interface): className, method
     *
7013 (Abstract Method Added to Class): className, method
     *
7014 (Method now final): className, method
     *
7015 (Method now non-final): className, method
     *
8000 (Class added): className
     *
8001 (Class removed): className
     *
10000 (Class format version increased): className, from, to (class format version numbers)
     *
10001 (Class format version decreased): className, from, to (class format version numbers)
     *

     *
     * @parameter
     * @required
     */
    private int differenceType;

    /**
     * The name of the class that contains the ignored difference. This can be a path expression.
     *
     * @parameter
     * @required
     */
    private String className;

    /**
     * The name of the field that should be ignored according to the difference type and optionally 'from' and 'to'
     * conditions. This is parameter is a regular expression. Note that this must not contain any type information and
     * only match the field's name. This parameter is an expression (technically a maven path expression).
     *
     * @parameter
     */
    private String field;

    /**
     * The signature of the method that should be ignored according to the {@link #differenceType difference type}. This
     * parameter is an expression (technically a maven path expression).
     *
     * @parameter
     */
    private String method;

    /**
     * The original type of the field (if it is important for the difference type, otherwise can be left out). Note that
     * this parameter is ignored when dealing with methods. This parameter is an expression (technically a maven path
     * expression).
     *
     * @parameter
     */
    private String from;

    /**
     * The "new" type of the field (or method return type) or "new" method signature (if it is important for the
     * difference type, otherwise can be left out). This parameter is an expression (technically a maven path
     * expression).
     *
     * @parameter
     */
    private String to;

    /**
     * The reason why ignoring this difference is deemed OK.
     *
     * @parameter
     * @required
     */
    private String justification;

    public int getDifferenceType()
    {
        return differenceType;
    }

    public void setDifferenceType( int differenceType )
    {
        this.differenceType = differenceType;
    }

    public String getClassName()
    {
        return className;
    }

    public void setClassName( String className )
    {
        this.className = className;
    }

    public String getField()
    {
        return field;
    }

    public void setField( String field )
    {
        this.field = field;
    }

    public String getMethod()
    {
        return method;
    }

    public void setMethod( String method )
    {
        this.method = method;
    }

    public String getFrom()
    {
        return from;
    }

    public void setFrom( String from )
    {
        this.from = from;
    }

    public String getTo()
    {
        return to;
    }

    public void setTo( String to )
    {
        this.to = to;
    }

    public String getJustification()
    {
        return justification;
    }

    public void setJustification( String justification )
    {
        this.justification = justification;
    }

    public Result matches( ApiDifference apiDiff )
    {
        if ( apiDiff.getMessage().getId() != differenceType )
        {
            return Result.notMatched();
        }

        String affectedClassPath = apiDiff.getAffectedClass().replace( '.', '/' );
        if ( !SelectorUtils.matchPath( className, affectedClassPath, "/", true ) )
        {
            return Result.notMatched();
        }

        switch ( differenceType )
        {
            case 1000:
                return Result.matched();
            case 1001:
                return Result.matched();
            case 2000:
                return Result.matched();
            case 2001:
                return Result.matched();
            case 3000:
                return Result.matched();
            case 3001:
                return Result.matched();
            case 3002:
                return Result.matched();
            case 3003:
                return Result.matched();
            case 3004:
                return Result.matched();
            case 3005:
                return Result.matched();
            case 4000:
                return matches4000( apiDiff ) ? Result.matched() : Result.notMatched();
            case 4001:
                return matches4001( apiDiff ) ? Result.matched() : Result.notMatched();
            case 5000:
                return matches5000( apiDiff ) ? Result.matched() : Result.notMatched();
            case 5001:
                return matches5001( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6000: // added field
                return matches6000( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6001: // removed field
                return matches6001( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6002: // field value no longer a compile-time constant
                return matches6002( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6003: // value of the compile-time constant changed on a field
                return matches6003( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6004: // field type changed
                return matches6004( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6005: // field now non-final
                return matches6005( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6006: // field now final
                return matches6006( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6007: // field now non-static
                return matches6007( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6008: // field now static
                return matches6008( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6009: // field more accessible
                return matches6009( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6010: // field less accessible
                return matches6010( apiDiff ) ? Result.matched() : Result.notMatched();
            case 6011: // removed a constant field
                return matches6011( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7000: // method now in superclass
                return matches7000( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7001: // method now in interface
                return matches7001( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7002: // method removed
                return matches7002( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7003: // Method Overide Removed
                return matches7003( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7004: // Method Argument Count Changed
                return matches7004( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7005: // Method Argument Type changed
                return Result.deferred( getDifferentiatorFor7005( apiDiff ) );
            case 7006: // Method Return Type changed
                return matches7006( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7007: // Method has been Deprecated
                return matches7007( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7008: // Method has been Undeprecated
                return matches7008( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7009: // Method is now Less Accessible
                return matches7009( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7010: // Method is now More Accessible
                return matches7010( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7011: // Method Added
                return matches7011( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7012: // Method Added to Interface
                return matches7012( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7013: // Abstract Method Added to Class
                return matches7013( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7014: // Method now final
                return matches7014( apiDiff ) ? Result.matched() : Result.notMatched();
            case 7015: // Method now non-final
                return matches7015( apiDiff ) ? Result.matched() : Result.notMatched();
            case 8000: // Class added
                return Result.matched();
            case 8001: // Class removed
                return Result.matched();
            case 10000:
                return matches10000( apiDiff ) ? Result.matched() : Result.notMatched();
            case 10001:
                return matches10001( apiDiff ) ? Result.matched() : Result.notMatched();
            default:
                return Result.notMatched();
        }
    }

    public boolean resolveDefferedMatches( List<ApiDifference> defferedApiDifferences )
    {
        if ( differenceType == 7005 )
        {
            return matches7005( defferedApiDifferences );
        }
        else
        {
            return false;
        }
    }

    @Override
    public String toString()
    {
        return "Difference[differenceType=" + differenceType + ", className=" + className + ", field=" + field + ", method=" + method + ", from=" + from + ", to=" + to + "]";
    }

    /**
     * Added interface to the set of implemented interfaces
     */
    private boolean matches4000( ApiDifference apiDiff )
    {
        throwIfMissing( false, false, false, true );

        String newIface = getArgs( apiDiff )[0];
        newIface = newIface.replace( '.', '/' );

        return SelectorUtils.matchPath( to, newIface, "/", true );
    }

    /**
     * Removed interface from the set of implemented interfaces
     */
    private boolean matches4001( ApiDifference apiDiff )
    {
        throwIfMissing( false, false, false, true );

        String removedIface = getArgs( apiDiff )[0];
        removedIface = removedIface.replace( '.', '/' );

        return SelectorUtils.matchPath( to, removedIface, "/", true );
    }

    /**
     * Added class to the set of superclasses
     */
    private boolean matches5000( ApiDifference apiDiff )
    {
        throwIfMissing( false, false, false, true );

        String newSuperclass = getArgs( apiDiff )[0];
        newSuperclass = newSuperclass.replace( '.', '/' );

        return SelectorUtils.matchPath( to, newSuperclass, "/", true );
    }

    /**
     * Removed class from the set of superclasses
     */
    private boolean matches5001( ApiDifference apiDiff )
    {
        throwIfMissing( false, false, false, true );

        String removedSuperclass = getArgs( apiDiff )[0];
        removedSuperclass = removedSuperclass.replace( '.', '/' );

        return SelectorUtils.matchPath( to, removedSuperclass, "/", true );
    }

    /**
     * added field
     */
    private boolean matches6000( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * removed field
     */
    private boolean matches6001( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * field value no longer a compile-time constant
     */
    private boolean matches6002( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * value of the compile-time constant changed on a field
     */
    private boolean matches6003( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * field type changed
     */
    private boolean matches6004( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, true, true );

        if ( !SelectorUtils.matchPath( field, apiDiff.getAffectedField() ) )
        {
            return false;
        }

        String[] args = getArgs( apiDiff );
        String diffFrom = args[0];
        String diffTo = args[1];

        return SelectorUtils.matchPath( from, diffFrom ) && SelectorUtils.matchPath( to, diffTo );
    }

    /**
     * field now non-final
     */
    private boolean matches6005( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * field now final
     */
    private boolean matches6006( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * field now non-static
     */
    private boolean matches6007( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * field now static
     */
    private boolean matches6008( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * field more accessible
     */
    private boolean matches6009( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * field less accessible
     */
    private boolean matches6010( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * removed a constant field
     */
    private boolean matches6011( ApiDifference apiDiff )
    {
        throwIfMissing( true, false, false, false );
        return SelectorUtils.matchPath( field, apiDiff.getAffectedField() );
    }

    /**
     * method now in superclass
     */
    private boolean matches7000( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * method now in interface
     */
    private boolean matches7001( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * method removed
     */
    private boolean matches7002( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method Overide Removed
     */
    private boolean matches7003( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method Argument Count Changed
     */
    private boolean matches7004( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    private Object getDifferentiatorFor7005( ApiDifference apiDiff )
    {
        return apiDiff.getAffectedClass() + apiDiff.getAffectedMethod();
    }

    /**
     * Method Argument Type changed
     */
    private boolean matches7005( List<ApiDifference> apiDiffs )
    {
        throwIfMissing( false, true, false, true );

        ApiDifference firstDiff = apiDiffs.get( 0 );
        String methodSig = removeVisibilityFromMethodSignature( firstDiff );
        if ( !SelectorUtils.matchPath( method, methodSig ) )
        {
            return false;
        }

        String newMethodSig = getNewMethodSignature( methodSig, apiDiffs );
        return SelectorUtils.matchPath( to, newMethodSig );
    }

    public static String getNewMethodSignature( String methodSig, List<ApiDifference> apiDiffs )
    {
      String newMethodSig = methodSig;
      for ( ApiDifference apiDiff : apiDiffs )
      {
          String[] args = getArgs( apiDiff );

          // 1-based
          int idx = Integer.parseInt( args[0] ) - 1;
          String diffNewType = args[1];

          // construct the new full method signature
          newMethodSig = replaceNthArgumentType( newMethodSig, idx, diffNewType );
      }
      return newMethodSig;
    }

    /**
     * Method Return Type changed
     */
    private boolean matches7006( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, true );

        String methodSig = removeVisibilityFromMethodSignature( apiDiff );
        if ( !SelectorUtils.matchPath( method, methodSig ) )
        {
            return false;
        }

        String newRetType = getArgs( apiDiff )[0];

        return SelectorUtils.matchPath( to, newRetType );
    }

    /**
     * Method has been Deprecated
     */
    private boolean matches7007( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method has been Undeprecated
     */
    private boolean matches7008( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method is now Less Accessible
     */
    private boolean matches7009( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method is now More Accessible
     */
    private boolean matches7010( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method Added
     */
    private boolean matches7011( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method Added to Interface
     */
    private boolean matches7012( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Abstract Method Added to Class
     */
    private boolean matches7013( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method now final
     */
    private boolean matches7014( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Method now non-final
     */
    private boolean matches7015( ApiDifference apiDiff )
    {
        throwIfMissing( false, true, false, false );
        return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) );
    }

    /**
     * Class format version increased
     */
    private boolean matches10000( ApiDifference apiDiff )
    {
        throwIfMissing( false, false, true, true );

        int fromVersion = 0;
        int toVersion = 0;
        try
        {
            fromVersion = Integer.parseInt( from );
        }
        catch ( NumberFormatException e )
        {
            throw new IllegalArgumentException( "Failed to parse the \"from\" parameter as a number for " + this );
        }

        try
        {
            toVersion = Integer.parseInt( to );
        }
        catch ( NumberFormatException e )
        {
            throw new IllegalArgumentException( "Failed to parse the \"to\" parameter as a number for " + this );
        }

        String[] args = getArgs( apiDiff );

        int reportedOld = Integer.parseInt( args[0] );
        int reportedNew = Integer.parseInt( args[1] );

        return fromVersion == reportedOld && toVersion == reportedNew;
    }

    /**
     * Class format version decreased
     */
    private boolean matches10001( ApiDifference apiDiff )
    {
        throwIfMissing( false, false, true, true );

        int fromVersion = 0;
        int toVersion = 0;
        try
        {
            fromVersion = Integer.parseInt( from );
        }
        catch ( NumberFormatException e )
        {
            throw new IllegalArgumentException( "Failed to parse the \"from\" parameter as a number for " + this );
        }

        try
        {
            toVersion = Integer.parseInt( to );
        }
        catch ( NumberFormatException e )
        {
            throw new IllegalArgumentException( "Failed to parse the \"to\" parameter as a number for " + this );
        }

        String[] args = getArgs( apiDiff );

        int reportedOld = Integer.parseInt( args[0] );
        int reportedNew = Integer.parseInt( args[1] );

        return fromVersion == reportedOld && toVersion == reportedNew;
    }

    private static String[] getArgs( ApiDifference apiDiff )
    {
        String args = apiDiff.getReport( ARGS_EXTRACTOR );
        return args.split( "&" );
    }

    private void throwIfMissing( boolean field, boolean method, boolean from, boolean to )
    {
        boolean doThrow =
            ( field && this.field == null ) || ( method && this.method == null ) || ( from && this.from == null )
                || ( to && this.to == null );

        if ( doThrow )
        {
            StringBuilder message = new StringBuilder( "The following parameters are missing: " );
            if ( field && this.field == null )
            {
                message.append( "field, " );
            }

            if ( method && this.method == null )
            {
                message.append( "method, " );
            }

            if ( from && this.from == null )
            {
                message.append( "from, " );
            }

            if ( to && this.to == null )
            {
                message.append( "to, " );
            }

            message.replace( message.length() - 2, message.length(), "" );

            message.append( " on " ).append( this );

            throw new IllegalArgumentException( message.toString() );
        }
    }

    private static String replaceNthArgumentType( String signature, int idx, String newType )
    {
        int openParIdx = signature.indexOf( '(' );
        int closeParIdx = signature.indexOf( ')' );

        if ( openParIdx < 0 || closeParIdx < 0 )
        {
            throw new IllegalArgumentException( "Invalid method signature found in the API difference report: "
                + signature );
        }

        StringBuilder bld = new StringBuilder();
        bld.append( signature, 0, openParIdx ).append( '(' );

        int commaIdx = openParIdx + 1;
        int paramIdx = 0;
        while ( true )
        {
            int nextCommaIdx = signature.indexOf( ',', commaIdx );

            if ( nextCommaIdx < 0 )
            {
                break;
            }

            String type = paramIdx == idx ? newType : signature.substring( commaIdx, nextCommaIdx );

            bld.append( type.trim() );
            bld.append( ", " );

            commaIdx = nextCommaIdx + 1;
            paramIdx++;

        }

        if ( paramIdx == idx )
        {
            bld.append( newType );
        }
        else
        {
            bld.append( signature, commaIdx + 1, closeParIdx );
        }

        bld.append( ")" );

        return bld.toString();
    }

    private String removeVisibilityFromMethodSignature( ApiDifference apiDiff )
    {
        String methodSig = apiDiff.getAffectedMethod();
        if ( methodSig == null )
        {
            return null;
        }

        int spaceIdx = methodSig.indexOf( ' ' );
        if ( spaceIdx < 0 )
        {
            return methodSig;
        }
        else
        {
            return methodSig.substring( spaceIdx + 1 );
        }
    }
}