text:
define(function(require) {

  'use strict';

  var Event   = require('./event');
  var Female  = require('./female');
  var Male    = require('./male');
  var Seed    = require('./seed');
  var Tile    = require('./tile');

  var requestAnimationFrame = (function() {
    // Use requestAnimationFrame for better animation
    return (
      window.requestAnimationFrame       ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame    ||
      window.oRequestAnimationFrame      ||
      window.msRequestAnimationFrame     ||
      function(callback, element) {
        window.setTimeout(function() {
          callback(+new Date());
        }, 1000 / 60);
      }
    );
  })();

  // WorldJS constructor
  // Define default properties of a world
  var WorldJS = function() {
    // The value of this refers to a newly created world
    var world = this;

    // The world is currently not running
    world.running = false;
    // Trigger once after the world animation was stopped
    world.stopCallback = function() {};

    // Size of the world in pixels
    world.width   = 640;
    world.height  = 360;
    // Prevent objects from drawing outside the world
    world.padding = 10; // 10 pixels from border

    world.canvas = {
      wrapper: false,  // DOM element that wraps the canvas
      context: false   // HTML5 drawing context
    };
    world.sprite = {
      src:   'images/icons.png',
      image: false   // DOM image object of sprite
    };

    // Display mode:
    // - full:  draw seeds based on sprite image
    // - dot:   only draw a single pixel per seed
    // - none:  not draw anything
    world.displayMode = 'full';

    // World contains seeds
    // but only hold a number of total seeds.
    // Data of all seeds will be stored by the Tile module.
    world.totalSeeds = 0;
    // Each seed has an unique id
    world.nextSeedId = 1;

    // Don't draw every frame (tick) if total seeds > this value
    world.maxSafeSeedsForDisplay = 30000;

    // tickPerYear:     indicate one year passed.
    // speed:           running speed of the world,
    //                  affects moving speed and actionInterval of a seed.
    // actionInterval:  indicate how often a seed triggers its main action.
    // By default, actionInterval is as half as tickPerYear,
    // which means a seed triggers its main action twice a year.
    //
    // tickPerYear and speed must be set manually together.
    // Example:
    // tickPerYear      60  30  20  12  10  6
    // speed            1   2   3   5   6   10
    // actionInterval   30  15  10  6   5   3
    //
    // All 3 values are divisibility to avoid extra implements.
    world.tickPerYear = 60;
    world.speed       = 1;
    // actionInterval: see Seed module

    // Used for indicating a year, +1 every frame (tick)
    // Example: tickPerYear = 60
    // tickMod: 0   60  120 180 ...
    // year:    0   1   2   3   ...
    //
    // If tickPerYear is changed to 30:
    // tickMod: 210 240 ...
    // year:    4   5   ...
    world.tickMod = 0;

    // Seeds don't trigger their main actions every frame.
    // Example: In 60 frames, a male only seeks for female twice
    // in 30th frame and 60th frame (actionInterval = 30).
    // To make it's more efficient,
    // main actions of all seeds will be distributed over all frames.
    // Example: male_1 will seek for female in 30th frame, 60th frame...
    //          male_2 will seek for female in 31th frame, 61th frame...
    //
    // distributedTicks has its length equals <tickPerYear - 1>, which means:
    // In every <tickPerYear> frames
    // <tickPerYear - 1> frames are used to trigger main actions of seeds.
    // Last frame is used for other calculations such as statistic
    // or user interface update.
    world.distributedTicks = [];
    for (var i = 0; i < world.tickPerYear - 1; i++) {
      world.distributedTicks.push(0);
    }

    // Used for calculating frames per second
    world.lastTickTime = 0;
    world.fps = 0;

    world.event   = new Event(world);
    world.Female  = Female;
    world.Male    = Male;
    world.tile    = new Tile(world);
  };

  // Insert the world into a HTML wrapper
  // wrapperId: id of an HTML wrapper element
  WorldJS.prototype.init = function(wrapperId) {
    var world = this;

    // Add a canvas that fits size of its wrapper
    var canvas  = document.createElement('canvas');
    var wrapper = document.getElementById(wrapperId);
    // Size of the wrapper is also size of the world
    var width   = wrapper.clientWidth  || world.width;
    var height  = wrapper.clientHeight || world.height;

    world.canvas.wrapper = wrapper;
    world.width  = canvas.width  = width;
    world.height = canvas.height = height;

    wrapper.appendChild(canvas);

    world.canvas.context = canvas.getContext('2d');

    // Load and cache sprite
    var sprite = new Image();
    sprite.src = world.sprite.src;
    world.sprite.image = sprite;

    world.tile.init(width, height);

    return world;
  };

  // Add a seed to the world
  // Seed: seed-based class
  // data: properties of seed
  // return seed
  WorldJS.prototype.addSeed = function(Seed, data) {
    data = data || {};
    var world = this;
    var seed  = new Seed(data);

    world.totalSeeds++;

    // Save a reference of the world where this seed belongs
    seed.world = world;
    // Set an unique id
    seed.id = world.nextSeedId++;

    seed.age = data.age || 0;
    seed.tickCount = (seed.age > 0) ? seed.age * world.tickPerYear : seed.tickCount;

    // Put this seed in a frame which has the lowest number of occupied seeds
    // to avoid a single frame that needs to trigger too many main actions
    var tickIndex = world.getTickIndex();
    world.distributedTicks[tickIndex]++;
    seed.tickIndex = tickIndex;

    seed.tickMod = world.tickMod;
    // By modulusing actionInterval which is as half as tickPerYear by default
    // we have two lowest frames index: 30th (half year passed) and 60th (full year passed)
    // TODO: review the distributed ticks mechanic in different speed
    seed.tickCount += (world.tickMod + seed.tickCount + seed.tickIndex) % seed.actionInterval;
    // stepCount also need to base on seed.tickCount to avoid synchronized jumping
    // among all seeds that appeared in the same time
    seed.stepCount = seed.tickCount;
    seed.moveUntilStep = seed.moveUntilStep ||
      // Move until 2-10 more jumps
      seed.tickCount + world.random(2, 10) * seed.jumpInterval;

    // Set random position
    var position = world.getRandomPosition(seed);
    seed.x = position.x;
    seed.y = position.y;

    // Calculate tile index
    seed.tileIndex = world.tile.getIndex(seed);
    // and cache data of this seed
    world.tile.set(seed);

    world.event.trigger('seedAdded', {
      seed:   seed,
      mother: data.mother || undefined
    });

    return seed;
  };

  // Find the best tick index for this seed
  // return tick index
  WorldJS.prototype.getTickIndex = function() {
    var world = this;
    var distributedTicks = world.distributedTicks;
    var minIndex = 0;
    var minValue = distributedTicks[minIndex];
    for (var i = 0, len = distributedTicks.length; i < len; i++) {
      if (distributedTicks[i] < minValue) {
        minIndex = i;
        minValue = distributedTicks[i];
      }
    }
    return minIndex;
  };

  // Get random position in the world
  // seed:    seed-based instance
  // forced:  always get new value of x and y
  // return   {x, y}
  WorldJS.prototype.getRandomPosition = function(seed, forced) {
    forced = forced || false;
    var world = this;

    var x = (seed.x === false || forced) ?
      world.random(world.padding, world.width - seed.icon.width - world.padding) :
      seed.x;
    var y = (seed.y === false || forced) ?
      world.random(world.padding, world.height - seed.icon.height - world.padding) :
      seed.y;

    return { x: x, y: y };
  };

  // Remove a seed from the world
  // seed: seed-based instance
  WorldJS.prototype.removeSeed = function(seed) {
    var world = this;

    world.totalSeeds--;

    world.event.trigger('seedRemoved', { seed: seed });

    if (seed.relationSeed !== false) {
      // Remove the references
      seed.relationSeed.relationSeed = false;
      seed.relationSeed = false;
    }

    world.tile.rem(seed);

    world.distributedTicks[seed.tickIndex]--;

    return world;
  };

  // Add random seeds to the world
  // count: number of seeds to add
  // data:
  //        minAge, maxAge
  //        types:      array of world.Seed, world.Male, world.Female...
  //        fromBorder: determine which border seeds will appear
  WorldJS.prototype.addSeeds = function(count, data) {
    data = data || {};
    var world   = this;
    var types   = (typeof data.types !== 'undefined')  ? data.types  : [Seed];
    var minAge  = (typeof data.minAge !== 'undefined') ? data.minAge : 15;
    var maxAge  = (typeof data.maxAge !== 'undefined') ? data.maxAge : 20;

    // Add seeds to the world
    for (var i = 0; i < count; i++) {
      // Random age
      var age = world.random(minAge, maxAge);
      var seedData = { x: false, y: false, age: age };

      if (typeof data.fromBorder !== 'undefined') {
        var borders = ['top', 'bottom', 'left', 'right'];
        var border  = (data.fromBorder === 'random') ?
          borders[world.random(0, 3)] : data.fromBorder;
        // Used random number to avoid people appeared in the same edge
        switch (border) {
          case 'top':
            seedData.y = world.random(0, world.padding);
            break;
          case 'bottom':
            seedData.y = world.random(
              world.height - world.padding - 1,
              world.height - 1
            );
            break;
          case 'left':
            seedData.x = world.random(0, world.padding);
            break;
          case 'right':
            seedData.x = world.random(
              world.width - world.padding - 1,
              world.width - 1
            );
            break;
        }
      }
      world.addSeed(types[i % types.length], seedData);
    }

    return world;
  };

  // World process loop
  WorldJS.prototype.run = function(time) {
    var world       = this;
    var context     = world.canvas.context;
    var spriteImage = world.sprite.image;

    // Modulus tickMod by tickPerYear to avoid its value grows too large
    world.tickMod   = (++world.tickMod) % world.tickPerYear;
    var yearPassed  = (world.tickMod === 0);

    // Only draw the world every year instead of every frame if total seeds is too large
    var reDraw = (world.totalSeeds <= world.maxSafeSeedsForDisplay || yearPassed);
    if (reDraw) {
      // Clear canvas
      context.clearRect(0, 0, world.width, world.height);
    }

    var listTile = world.tile.list;
    var maxDisplayedSeeds = world.tile.maxDisplayedSeeds;
    var speed = world.speed;
    for (var i = 0, len = listTile.length; i < len; i++) {
      var seeds = listTile[i];
      var displayedSeeds = 0;
      for (var j = 0, len2 = seeds.length; j < len2; j++) {
        if (seeds[j]) {
          var seed = seeds[j];
          var oldTileIndex = seed.tileIndex;

          // When a seed moves to a different tile, its reference may be inserted into
          // an empty spot of tile array instead of just appending to the array.
          // That reference will possibly be available on next pass of the current loop
          // which could cause a seed ticks twice.
          //
          // Used tickMod to indicate a seed is already ticked in the current loop.
          if (seed.tickMod == world.tickMod) {
            continue;
          }
          seed.tickMod = world.tickMod;

          if (yearPassed) {
            seed.age++;
          }

          if (reDraw) {
            // Don't need to draw too many seeds in a small area of a single tile
            if (displayedSeeds < maxDisplayedSeeds) {
              // Draw current state of the seed
              switch (world.displayMode) {
                case 'full':
                  seed.draw(context, spriteImage);
                  break;
                case 'dot':
                  seed.draw(context, false);
                  break;
                case 'none':
                  break;
              }
              displayedSeeds++;
            }
          }
          // Seed moves around or triggers some actions
          seed.tick(speed);

          // Update tiles if seed moves
          var newTileIndex = world.tile.getIndex(seed);
          if (newTileIndex !== oldTileIndex) {
            // Remove seed reference from old tile
            world.tile.rem(seed);

            // Add seed reference to new tile
            seed.tileIndex = newTileIndex;
            world.tile.set(seed);
          }
        }
      }
    }

    if (yearPassed) {
      world.event.trigger('yearPassed');

      if (world.totalSeeds === 0) {
        // Stop the world
        world.running = false;
        return;
      }
    }

    // Loop animation
    if (world.running) {
      world.fps = 1000 / (time - world.lastTickTime);
      world.lastTickTime = time;

      // Don't know why bind() doesn't work with Grunt/PhantomJS/QUnit
      // requestAnimationFrame(world.run.bind(world));
      requestAnimationFrame(function() { world.run.call(world); });
    } else {
      // Trigger once
      world.stopCallback.call(world);
      world.stopCallback = function() {};
    }

    return world;
  };

  // Start the world
  WorldJS.prototype.start = function() {
    var world = this;

    world.running = true;
    world.run();

    return world;
  };

  // Stop the world
  // callback (optional): callback trigger after the world stopped
  WorldJS.prototype.stop = function(callback) {
    var world = this;

    world.running = false;
    if (typeof callback === 'function') {
      world.stopCallback = callback;
    }

    return world;
  };

  // Generate random number X: min <= X <= max
  // min: min number
  // max: max number
  WorldJS.prototype.random = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  };

  return WorldJS;

});

/*!
 * world.tile.js
 * Divide a world into tiles.
 * Each tile holds references to all seeds (objects) that currently stay in it.
 *
 * https://github.com/anvoz/world-js
 * Copyright (c) 2013-2014 An Vo - anvo4888@gmail.com
 * Licensed under MIT (http://www.opensource.org/licenses/mit-license.php)
 */

define(function() {

  'use strict';

  // Tile constructor
  // world: instance of WorldJS
  var Tile = function(world) {
    var worldTile = this;

    // Store reference of a world
    worldTile.world = world;

    // Old storage structure:
    // An array contains tiles, each tile is a hashmap:
    // list = [
    //    0: { seedId1: seed1, seedId2: seed2 },  // 1st tile
    //    1: { ... }                              // 2nd tile
    // ]
    // - Pros: Simple add & remove operations
    // - Cons: Iterating large hashmap is much slower than large array
    // http://jsperf.com/fetch-array-vs-object
    //
    // New storage structure:
    // An array contains tiles, each tile is also an array:
    // list = [
    //    0: [ 0: seed1, 1: seed2 ],              // 1st tile
    //    1: [ ... ]                              // 2nd tile
    // ]
    // Retrieve seed by array index.
    // Require new property - seed.tileArrayIndex - to store
    // the location (array index) of the seed in a tile array.
    //
    // For example, base on the list above:
    // seed1.tileArrayIndex = 0, seed2.tileArrayIndex = 1
    // When a seed is removed from tile, that tile's array index is
    // available for inserting a new seed:
    // Tile.rem(seed1);
    // => list = [ 0: [ 0: false, 1: seed2 ], 1: [ ... ] ]
    // The first tile has 1 available array index which is at 0 index.
    // => availableArrayIndexes = [ 0: [0], 1: [] ]
    // Tile.add(seed3);
    // => list = [ 0: [ 0: seed3, 1: seed2 ], 1: [ ... ] ]
    // The first tile doesn't have any available array index
    // => availableArrayIndexes = [ 0: [], 1: [] ]

    // List of tiles,
    // each tile is an array of seeds
    worldTile.list = [];
    // List of available indexes
    // where a new seed can be inserted into
    worldTile.availableArrayIndexes = [];

    // 20 x 20 pixels per tile
    worldTile.size = 20;

    // Only draw 7 seeds each tile
    worldTile.maxDisplayedSeeds = 7;

    // Need to be calculated base on the size of the world
    worldTile.totalTiles  = false;
    worldTile.tilesPerRow = false;
    worldTile.tilesPerCol = false;
  };

  // Divide the world into smaller tiles.
  // Each tile contains a list of seeds that are currently inside.
  // width:   width of the world in pixel
  // height:  height of the world in pixel
  Tile.prototype.init = function(width, height) {
    var worldTile   = this;
    var tileSize    = worldTile.size;
    var tilesPerRow = Math.ceil(height / tileSize);
    var tilesPerCol = Math.ceil(width / tileSize);
    var totalTiles  = tilesPerRow * tilesPerCol;

    worldTile.tilesPerRow = tilesPerRow;
    worldTile.tilesPerCol = tilesPerCol;
    worldTile.totalTiles  = totalTiles;

    // Initialize tiles with an array of empty arrays
    var listTiles = worldTile.list;
    var availableArrayIndexes = worldTile.availableArrayIndexes;
    for (var i = 0; i < totalTiles; i++) {
      listTiles.push([]);
      availableArrayIndexes.push([]);
    }
  };

  // Get tile index
  // seed: instance of Seed
  Tile.prototype.getIndex = function(seed) {
    var tileSize = this.size;
    var x = Math.floor(seed.x / tileSize);
    var y = Math.floor(seed.y / tileSize);
    return x + (y * this.tilesPerCol);
  };

  // Add seed to a tile based on seed.tileIndex.
  // A new tileIndex value of the seed must be calculated
  // before call this function.
  // seed: instance of Seed
  Tile.prototype.set = function(seed) {
    var worldTile = this;
    var tileIndex = seed.tileIndex;
    var tile      = worldTile.list[tileIndex];
    var availableArrayIndexes = worldTile.availableArrayIndexes[tileIndex];

    if (availableArrayIndexes.length > 0) {
      // Add seed to the tile by
      // inserting it into the available array index
      seed.tileArrayIndex = availableArrayIndexes.pop();
      tile[seed.tileArrayIndex] = seed;
    } else {
      // Add seed to the tail of tile array
      seed.tileArrayIndex = tile.length;
      tile.push(seed);
    }
  };

  // Remove seed from the tile where it is currently in
  // seed: instance of Seed
  Tile.prototype.rem = function(seed) {
    var worldTile = this;
    var tileIndex = seed.tileIndex;
    var tileArrayIndex = seed.tileArrayIndex;

    // Set to false instead of delete an array element
    // to avoid holey array which is much slower to access
    // than packed array
    // http://jsperf.com/packed-vs-holey-arrays/10
    worldTile.list[tileIndex][tileArrayIndex] = false;

    // Store new available array index
    // to indicate where new seed can be inserted into later
    worldTile.availableArrayIndexes[tileIndex].push(tileArrayIndex);
  };

  return Tile;

});

/*!
 * world.event.js
 * Register behaviors to take effect when an event occurs
 *
 * https://github.com/anvoz/world-js
 * Copyright (c) 2013-2014 An Vo - anvo4888@gmail.com
 * Licensed under MIT (http://www.opensource.org/licenses/mit-license.php)
 */

define(function() {

  'use strict';

  // Event constructor
  // Initialize events list for a world
  var Event = function(world) {
    var worldEvent = this;

    // Store reference of a world
    worldEvent.world = world;

    // All of the available events must be declared here
    worldEvent.list = {
      // One event can have many actions that are registered by action names
      // Unused actions must be removed manually
      yearPassed:   { /* action: handler */ },
      seedAdded:    {},
      seedRemoved:  {}
    };
  };

  // Add a handler function to an event
  // event:   event name
  // action:  action name
  // handler: handler function
  Event.prototype.add = function(event, action, handler) {
    this.list[event][action] = handler;
  };

  // Remove a handler function from an event
  // event:   event name
  // action:  action name
  Event.prototype.remove = function(event, action) {
    delete this.list[event][action];
  };

  // Trigger an event
  // world: the world that takes effects
  // event: event name
  Event.prototype.trigger = function(event, data) {
    var worldEvent  = this;
    var world       = worldEvent.world;
    var actions     = worldEvent.list[event];

    for (var actionName in actions) {
      if (actions.hasOwnProperty(actionName)) {
        actions[actionName].call(world, data);
      }
    }
  };

  return Event;

});

/*!
 * world.seed.js
 * Define an object that will be added to a world
 * to live and interact with other objects.
 *
 * https://github.com/anvoz/world-js
 * Copyright (c) 2013-2014 An Vo - anvo4888@gmail.com
 * Licensed under MIT (http://www.opensource.org/licenses/mit-license.php)
 */

define(function() {

  'use strict';

  // Seed constructor
  // data (optional): x, y, icon, relationSeed, tickCount, actionInterval, moveTo
  var Seed = function(data) {
    // The value of this refers to a newly created seed
    var seed = this;

    // Only be set when the seed was successfully added to a world
    seed.world      = false;
    seed.id         = false;
    seed.tileIndex  = false;
    seed.tickIndex  = false;
    seed.tickMod    = false;

    seed.age = data.age || 0;

    // Seed coordinate (top, left)
    seed.x = (typeof data.x === 'undefined') ? false : data.x;
    seed.y = (typeof data.y === 'undefined') ? false : data.y;

    // Define how to draw the seed
    seed.icon = data.icon || { width: 1, height: 1 };
    seed.carrying = data.carrying || false;

    // Relationship of the seed
    seed.relationSeed = data.relationSeed || false;

    // Be default, seed moves around every frame (tickCount++ each frame).
    // Its main actions such as seeking partner or giving birth
    // only trigger every <actionInterval> interval.
    seed.tickCount      = data.tickCount || 0;
    seed.actionInterval = data.actionInterval || 30;

    // stepCount++ only in every tick the seed moves.
    // Seed will move then stop based on the following rule:
    // Keep moving until the <moveUntilStep>th step, then stopped.
    // After stopped, wait until <ageToMoveAgain> age to move around again.
    //
    // jumpInterval: make an animation like jumping when seed moves.
    // A seed only stops after it finished a full jump (landing).
    seed.stepCount      = seed.tickCount;
    seed.jumpInterval   = 20;
    seed.moveUntilStep  = data.moveUntilStep || 0;
    seed.ageToMoveAgain = 0;
    seed.isMoving       = false;

    // Destination coordinate for seed to move to
    seed.moveTo = data.moveTo || false;
  };

  // Display the seed in the world
  Seed.prototype.draw = function(context, spriteImage) {
    var seed = this;

    if (spriteImage === false || seed.icon.width === 1) {
      var width   = (spriteImage !== false) ? seed.icon.width :  1;
      var height  = (spriteImage !== false) ? seed.icon.height : 1;
      context.fillRect(seed.x, seed.y, width, height);
    } else {
      // Handle child-state of the seed
      var icon = (seed.age <= seed.maxChildAge) ? seed.icon.child : seed.icon;

      // Jump instead of slide when seed moves
      // Example:   jumpInterval = 10
      // jumpIndex: 0 1 2 3 4 5 6 7 8 9
      // jumpY:     1 2 3 4 5 4 3 2 1 0
      var jumpInterval  = seed.jumpInterval;
      var halfInterval  = 10;
      var jumpIndex     = seed.stepCount % jumpInterval;
      var jumpY         = (jumpIndex < halfInterval) ?
        jumpIndex + 1 : halfInterval - (jumpIndex % halfInterval) - 1;

      context.drawImage(
        spriteImage,
        icon.x, icon.y,         icon.width, icon.height,
        seed.x, seed.y - jumpY, icon.width, icon.height
      );
      if (seed.carrying !== false && seed.carrying !== 'none') {
        var carrying = seed.carrying;
        context.drawImage(
          spriteImage,
          carrying.x,           carrying.y,                   carrying.width, carrying.height,
          seed.x + carrying.dx, seed.y - jumpY + carrying.dy, carrying.width, carrying.height
        );
      }
    }
  };

  // Get carrying item
  Seed.prototype.getCarryingItem = function(who, when) {
    var seed  = this;
    var world = seed.world;

    if (typeof world.items !== 'undefined') {
      var items = world.items;
      var availableItems = [];
      for (var type in items) {
        var item = items[type];
        if (item.enabled === true && item.who === who && item.when === when) {
          availableItems.push(item.icon);
        }
      }

      var totalAvailableItems = availableItems.length;
      if (totalAvailableItems === 1) {
        return availableItems[0];
      } else if (totalAvailableItems > 1) {
        return availableItems[world.random(0, totalAvailableItems - 1)];
      }
    }

    return false;
  };

  // Update new coordinate of the seed in the world
  // speed: speed of the world
  // beforeMoveCallback: callback function or false
  Seed.prototype.move = function(speed, beforeMoveCallback) {
    var seed    = this;
    var world   = seed.world;
    var random  = world.random;

    // By default, seed keeps moving around the world
    seed.isMoving = true;
    if (!beforeMoveCallback) {
      // Read the comment on seed's constructor for more info
      if (seed.stepCount >= seed.moveUntilStep) {
        if (seed.ageToMoveAgain === 0 || seed.ageToMoveAgain > seed.age) {
          if (seed.ageToMoveAgain === 0) {
            // Don't move much when getting old
            seed.ageToMoveAgain = seed.age + random(2, seed.age);
            seed.carrying = false;
          }
          seed.isMoving = false;
          return;
        } else {
          seed.ageToMoveAgain = 0;
          // Move until 2-10 more jumps
          seed.moveUntilStep = seed.stepCount + random(2, 10) * seed.jumpInterval;
          seed.carrying = false;
        }
      }
    } else {
      beforeMoveCallback.call(seed);
    }

    if (seed.moveTo === false ||
      (seed.moveTo.x === seed.x && seed.moveTo.y === seed.y)
    ) {
      // Make another moveTo coordinate
      seed.moveTo = world.getRandomPosition(seed, true);
    }

    seed.stepCount++;

    // Move in 8-direction to reach moveTo coordinate,
    // <speed> pixels per frame (tick)
    if (seed.x < seed.moveTo.x) {
      seed.x = Math.min(seed.x + speed, seed.moveTo.x);
    } else if (seed.x > seed.moveTo.x) {
      seed.x = Math.max(seed.x - speed, 0);
    }

    if (seed.y < seed.moveTo.y) {
      seed.y = Math.min(seed.y + speed, seed.moveTo.y);
    } else if (seed.y > seed.moveTo.y) {
      seed.y = Math.max(seed.y - speed, 0);
    }
  };

  // Seek neighbour tiles and return the first seed that matches the condition
  // condition: function(candidate) { if (...) return true; } or false
  Seed.prototype.seek = function(condition) {
    var seed = this;
    var tile = seed.world.tile;
    var direction = [
      [0, 0],                             // current tile
      [-1, 0], [1, 0], [0, -1], [0, 1],   // w, e, n, s tile
      [-1, -1], [-1, 1], [1, -1], [1, 1]  // nw, sw, ne, se tile
    ];

    if (!condition) {
      // No filter, return first seed of the current tile
      condition = function(candidate) {
        return (candidate.id != seed.id);
      };
    }

    var tilesPerRow = tile.tilesPerRow;
    var tilesPerCol = tile.tilesPerCol;
    for (var i = 0, len = direction.length; i < len; i++) {
      var thisTileIndex;
      if (i === 0) {
        thisTileIndex = seed.tileIndex;
      } else {
        // Get the neighbour tile
        var row = (seed.tileIndex % tilesPerRow) + direction[i][0];
        var col = Math.floor(seed.tileIndex / tilesPerRow) + direction[i][1];
        if (row >= 0 && row < tilesPerRow && col >= 0 && col < tilesPerCol) {
          thisTileIndex = row + col * tilesPerRow;
        } else {
          // Invalid tile
          continue;
        }
      }
      var seeds = tile.list[thisTileIndex];
      for (var j = 0, len2 = seeds.length; j < len2; j++) {
        if (seeds[j] && seed.id != seeds[j].id) {
          var candidateSeed = seeds[j];
          if (condition.call(seed, candidateSeed)) {
            // Matched candidate
            return candidateSeed;
          }
        }
      }
    }
    return false;
  };

  // Move around every frame (tick)
  // speed: speed of the world
  Seed.prototype.tick = function(speed) {
    var seed = this;
    seed.tickCount++;
    seed.move(speed);
  };

  // Get chance base on age of the seed
  // Example: { range: [1, 5], from: 0.01, to: 0.05 }
  // Age:     1   2   3   4   5
  // Chance:  1%  2%  3%  4%  5%
  Seed.prototype.getChance = function(type) {
    var seed  = this;
    var base  = seed.chances[type];
    var age   = seed.age;

    var i           = 0;
    var fromAge     = 0;
    var fromChance  = 0;
    var delta       = 0;
    while (base[i] && age >= base[i].range[0]) {
      var thisBase  = base[i];
      fromAge       = thisBase.range[0];
      fromChance    = thisBase.from;
      delta = (thisBase.to - thisBase.from) / (thisBase.range[1] - thisBase.range[0]);
      i++;
    }

    return fromChance + (age - fromAge) * delta;
  };

  return Seed;

});

/*!
 * world.male.js
 * Male extends Seed class.
 *
 * https://github.com/anvoz/world-js
 * Copyright (c) 2013-2014 An Vo - anvo4888@gmail.com
 * Licensed under MIT (http://www.opensource.org/licenses/mit-license.php)
 */

define(function(require) {

  'use strict';

  var Seed = require('./seed');

  // Male constructor
  // data (optional): seed data, age, chances
  var Male = function(data) {
    var male = this;

    data.icon = {
      x: 0, y: 0,
      width: 13, height: 20,
      child: { // must define maxChildAge
        x: 26, y: 0,
        width: 11, height: 10
      }
    };

    Seed.call(male, data);

    male.maxChildAge = 15;

    male.chances = data.chances || {
      death: [
        { range: [1, 20],   from: 0.02, to: 0.01 },
        { range: [20, 60],  from: 0.01, to: 0.02 },
        { range: [60, 80],  from: 0.02, to: 0.05 },
        { range: [80, 100], from: 0.05, to: 0.9 }
      ],
      marriage: [
        { range: [15, 30],  from: 0.1,  to: 0.5 },
        { range: [30, 50],  from: 0.5,  to: 0.1 },
        { range: [50, 80],  from: 0.1,  to: 0.01 }
      ]
    };
  };
  Male.prototype = Object.create(Seed.prototype);
  Male.prototype.contructor = Male;

  // Male action in every frame (tick)
  // speed: speed of the world
  Male.prototype.tick = function(speed) {
    var male  = this;
    var world = male.world;

    male.tickCount++;

    var actionInterval = male.actionInterval / speed;
    if (male.tickCount % actionInterval === actionInterval - 1) {
      // Trigger every <actionInterval> ticks
      var deathChance = male.getChance('death');
      if (deathChance > 0 && Math.random() < deathChance) {
        world.removeSeed(male);
        return;
      }

      if (male.relationSeed === false && male.age >= male.chances.marriage[0].range[0]) {
        // Seeking for female
        var marriageChance = male.getChance('marriage');
        if (marriageChance > 0) {
          var failureChance = Math.random();
          if (failureChance < marriageChance) {
            var female = male.seek(function(candidate) {
              var male  = this;
              var world = male.world;
              return (
                candidate instanceof world.Female &&
                candidate.relationSeed === false &&
                // Enough age to give birth
                candidate.age >= candidate.chances.childbirth[0].range[0] &&
                // Failure chance increase (every 10 age difference)
                // if male is younger than female
                (candidate.age <= male.age ||
                  (failureChance * (Math.ceil((candidate.age - male.age) / 10))) < marriageChance)
              );
            });
            if (female !== false) {
              male.relationSeed   = female;
              female.relationSeed = male;

              if (typeof female.totalChildren === 'undefined') {
                // Start record all children of this female
                female.totalChildren = 0;
              }

              // Prevent having children right after married
              female.ageLastBear = female.age + 1;

              male.carrying   = false;
              female.carrying = false;
            }
          }
        }
      }
    }

    if (male.relationSeed !== false) {
      if (male.x === Math.max(0, male.relationSeed.x - 10) && male.y === male.relationSeed.y) {
        return;
      }
      male.move(speed, function() {
        // Men will follow his wife
        var male   = this;
        var female = male.relationSeed;

        male.moveTo.x = Math.max(male.world.padding, female.x - 10);
        male.moveTo.y = female.y;
      });
    } else {
      male.move(speed, false);
    }

    if (male.carrying === false && typeof world.items !== 'undefined') {
      if (Math.random() < 0.2) {
        if (male.age > male.maxChildAge) {
          var who  = (male.relationSeed === false) ? 'man' : 'husband';
          var when = (male.isMoving) ? 'moving' : 'standing';
          male.carrying = male.getCarryingItem(who, when);
        }
      } else {
        male.carrying = 'none';
      }
    }
  };

  return Male;

});

/*!
 * world.female.js
 * Female extends Seed class.
 *
 * https://github.com/anvoz/world-js
 * Copyright (c) 2013-2014 An Vo - anvo4888@gmail.com
 * Licensed under MIT (http://www.opensource.org/licenses/mit-license.php)
 */

define(function(require) {

  'use strict';

  var Seed = require('./seed');

  // Female constructor
  // data (optional): seed data, age, chances
  var Female = function(data) {
    var female = this;

    data.icon = {
      x: 13, y: 0,
      width:  13, height: 20,
      child: { // must define maxChildAge
        x: 26, y: 10,
        width: 11, height: 10
      }
    };

    Seed.call(female, data);

    female.maxChildAge = 15;

    // Total children that she gave birth
    // Need to be set from undefined to 0 right after her first marriage
    female.totalChildren = undefined;
    // The age when she bears her youngest child
    female.ageLastBear = 0;

    female.chances = data.chances || {
      death: [
        { range: [1, 25],   from: 0.02, to: 0.01 },
        { range: [25, 65],  from: 0.01, to: 0.02 },
        { range: [65, 85],  from: 0.02, to: 0.05 },
        { range: [85, 105], from: 0.05, to: 0.9 }
      ],
      childbirth: [
        { range: [15, 25],  from: 0.1, to: 0.25 },
        { range: [25, 50],  from: 0.25, to: 0.1 },
        { range: [50, 70],  from: 0.1, to: 0.001 }
      ]
    };
  };
  Female.prototype = Object.create(Seed.prototype);
  Female.prototype.contructor = Female;

  // Female action in every frame (tick)
  // speed: speed of the world
  Female.prototype.tick = function(speed) {
    var female  = this;
    var world   = female.world;

    female.tickCount++;

    var actionInterval = female.actionInterval / speed;
    if (female.tickCount % actionInterval === actionInterval - 1) {
      // Trigger every <actionInterval> ticks
      var age = female.age;

      var deathChance = female.getChance('death');
      if (deathChance > 0 && Math.random() < deathChance) {
        world.removeSeed(female);
        return;
      }

      if (female.relationSeed !== false && // Is married
        // Enough age to give birth
        age >= female.chances.childbirth[0].range[0] &&
        // Not give birth in the same year
        age > female.ageLastBear
      ) {
        var childBirthChance = female.getChance('childbirth');
        if (childBirthChance > 0 && Math.random() < childBirthChance) {
          // +1 because she has more than 1 chance to give birth every year
          // depended on actionInterval
          female.ageLastBear = age + 1;
          female.totalChildren++;

          var data = {
            x: female.x,
            y: Math.min(
              world.height - 1 - world.padding,
              female.y + Math.floor(female.icon.height / 2)
            ),
            mother: female
          };

          if (Math.random() < 0.5) {
            world.addSeed(world.Male, data);
          } else {
            world.addSeed(world.Female, data);
          }
        }
      }
    }

    female.move(speed, false);

    if (female.carrying === false && typeof world.items !== 'undefined') {
      if (Math.random() < 0.2) {
        if (female.age > female.maxChildAge) {
          var who  = (female.relationSeed === false) ? 'woman' : 'wife';
          var when = (female.isMoving) ? 'moving' : 'standing';
          female.carrying = female.getCarryingItem(who, when);
        }
      } else {
        female.carrying = 'none';
      }
    }
  };

  return Female;

});


text:
FactoryGirl.define do
  factory :user do
    email { FFaker::Internet.email }
    password "12341234"
    password_confirmation "12341234"

    factory :admin do
    	credentials { User::credentials[:admin] }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package hudson.plugins.warnings;

import javax.annotation.CheckForNull;
import java.util.List;

import hudson.model.AbstractBuild;
import hudson.plugins.analysis.core.BuildHistory;

/**
 * A build history for warnings results. Picks the right action using the parser group.
 *
 * @author Ulli Hafner
 */
public class WarningsBuildHistory extends BuildHistory {
    private final String group;

    /**
     * Creates a new instance of {@link WarningsBuildHistory}.
     *
     * @param lastFinishedBuild
     *            the last finished build
     * @param group
     *            the parser group
     * @param usePreviousBuildAsReference
     *            determines whether to use the previous build as the reference
     *            build
     * @param useStableBuildAsReference
     *            determines whether only stable builds should be used as
     *            reference builds or not
     */
    public WarningsBuildHistory(final AbstractBuild<?, ?> lastFinishedBuild, @CheckForNull final String group,
            final boolean usePreviousBuildAsReference, final boolean useStableBuildAsReference) {
        super(lastFinishedBuild, WarningsResultAction.class, usePreviousBuildAsReference, useStableBuildAsReference);

        this.group = group;
    }

    @Override
    public WarningsResultAction getResultAction(final AbstractBuild<?, ?> build) {
        List<WarningsResultAction> actions = build.getActions(WarningsResultAction.class);
        if (group != null) {
            for (WarningsResultAction action : actions) {
                if (group.equals(action.getParser())) {
                    return action;
                }
            }
        }
        if (!actions.isEmpty() && actions.get(0).getParser() == null) { // fallback 3.x
            return actions.get(0);
        }
        return null;
    }
}


text:
#ifndef __BYTES_H__
#define __BYTES_H__

#ifdef _WIN32
/* Windows is little endian only */
#define __LITTLE_ENDIAN 1234
#define __BIG_ENDIAN    4321
#define __BYTE_ORDER __LITTLE_ENDIAN
#define __FLOAT_WORD_ORDER __BYTE_ORDER

typedef unsigned char uint8_t;

#else /* !_WIN32 */

#include <sys/param.h>

#if defined(BYTE_ORDER) && !defined(__BYTE_ORDER)
#define __BYTE_ORDER    BYTE_ORDER
#endif

#if defined(BIG_ENDIAN) && !defined(__BIG_ENDIAN)
#define __BIG_ENDIAN	BIG_ENDIAN
#endif

#if defined(LITTLE_ENDIAN) && !defined(__LITTLE_ENDIAN)
#define __LITTLE_ENDIAN	LITTLE_ENDIAN
#endif

#endif /* !_WIN32 */

/* define default endianness */
#ifndef __LITTLE_ENDIAN
#define __LITTLE_ENDIAN	1234
#endif

#ifndef __BIG_ENDIAN
#define __BIG_ENDIAN	4321
#endif

#ifndef __BYTE_ORDER
#warning "Byte order not defined on your system, assuming little endian!"
#define __BYTE_ORDER	__LITTLE_ENDIAN
#endif

/* ok, we assume to have the same float word order and byte order if float word order is not defined */
#ifndef __FLOAT_WORD_ORDER
/* #warning "Float word order not defined, assuming the same as byte order!" */
#define __FLOAT_WORD_ORDER	__BYTE_ORDER
#endif

#if !defined(__BYTE_ORDER) || !defined(__FLOAT_WORD_ORDER)
#error "Undefined byte or float word order!"
#endif

#if __FLOAT_WORD_ORDER != __BIG_ENDIAN && __FLOAT_WORD_ORDER != __LITTLE_ENDIAN
#error "Unknown/unsupported float word order!"
#endif

#if __BYTE_ORDER != __BIG_ENDIAN && __BYTE_ORDER != __LITTLE_ENDIAN
#error "Unknown/unsupported byte order!"
#endif

#endif


text:
module Types where

data ReceiverArgs
  = ReceiverArgs
  { raBsLen :: Int
  , raReportPer :: Int
  }
  deriving (Show)

data SenderArgs
  = SenderArgs
  { saBsLen :: Int
  , saClients :: Int
  , saReportPer :: Int
  }
  deriving (Show)

data TcpArgs
  = TcpArgs
  { taHost :: String
  , taPort :: Int
  , taIsServer :: Bool
  , taSoLinger :: Maybe Int
  , taGracefulShutdown :: Bool
  }
  deriving (Show)


text:
<?php
/**
 * Customer refunded order email
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/customer-refunded-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates/Emails
 * @version 3.7.0
 */

defined( 'ABSPATH' ) || exit;

/*
 * @hooked WC_Emails::email_header() Output the email header
 */
do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<?php /* translators: %s: Customer first name */ ?>

<?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?>

<?php
if ( $partial_refund ) {
	/* translators: %s: Site title */
	printf( esc_html__( 'Your order on %s has been partially refunded. There are more details below for your reference:', 'woocommerce' ), wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ); // phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped
} else {
	/* translators: %s: Site title */
	printf( esc_html__( 'Your order on %s has been refunded. There are more details below for your reference:', 'woocommerce' ), wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ); // phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped
}
?>

<?php

/*
 * @hooked WC_Emails::order_details() Shows the order details table.
 * @hooked WC_Structured_Data::generate_order_data() Generates structured data.
 * @hooked WC_Structured_Data::output_structured_data() Outputs structured data.
 * @since 2.5.0
 */
do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::order_meta() Shows order meta data.
 */
do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::customer_details() Shows customer details
 * @hooked WC_Emails::email_address() Shows email address
 */
do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );

/**
 * Show user-defined additonal content - this is set in each email's settings.
 */
if ( $additional_content ) {
	echo wp_kses_post( wpautop( wptexturize( $additional_content ) ) );
}

/*
 * @hooked WC_Emails::email_footer() Output the email footer
 */
do_action( 'woocommerce_email_footer', $email );


text:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="AppBaseTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

        <!-- toolbar(actionbar)颜色 -->
        <item name="colorPrimary">#222222</item>
        <!-- 状态栏颜色 -->
        <item name="colorPrimaryDark">#3A5FCD</item>
        <item name="android:textColorPrimary">@android:color/white</item>
        <!-- 窗口的背景颜色 -->
        <item name="android:windowBackground">@android:color/white</item>
    </style>

    <style name="AppTheme" parent="@style/AppBaseTheme.Base"></style>

</resources>


text:
CAMPFIRE = {
  :subdomain => 'mysubdomain',
  :email     => 'admin@example.com',
  :password  => 'peanutketchup',
  :room      => 'Main Room'
}
CHANGESET_URL = 'http://trac.example.com/changeset/%s' # %s is the revision number
SVNLOOK       = '/usr/bin/svnlook'

require 'rubygems'
require 'tinder'

campfire = Tinder::Campfire.new CAMPFIRE[:subdomain]
campfire.login CAMPFIRE[:email], CAMPFIRE[:password]
room = campfire.find_room_by_name CAMPFIRE[:room]

if ARGV.size > 1
  revision = ARGV[1]
  path     = ARGV[0]

  author  = `#{SVNLOOK} author -r #{revision} #{path}`
  paths   = `#{SVNLOOK} changed -r #{revision} #{path}`
  log     = `#{SVNLOOK} log -r #{revision} #{path}`
  message = [log, paths].join.strip
  url     = "#{author} commited #{CHANGESET_URL}/#{revision}"

  room.speak url
  room.paste message
else
  room.speak ARGV[0]
end

room.leave
campfire.logout


text:
package org.fest.swing.driver;

import javax.swing.JList;

import org.junit.Test;

/**
 * Tests for {@link JListDriver#requireSelectedItems(JList, int...)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
public class JListDriver_requireSelectedItemsByIndex_withInvalidInput_Test extends JListDriver_withMocks_TestCase {
  @Test(expected = NullPointerException.class)
  public void should_throw_error_if_array_of_indices_is_null() {
    int[] indices = null;
    driver.requireSelectedItems(list, indices);
  }

  @Test(expected = IllegalArgumentException.class)
  public void should_throw_error_if_array_of_indices_is_empty() {
    int[] indices = new int[0];
    driver.requireSelectedItems(list, indices);
  }
}


text:
package com.trein.gtfs.service.runner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.SecurityContext;

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.SynchronousDispatcher;
import org.jboss.resteasy.core.ThreadLocalResteasyProviderFactory;
import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.plugins.server.servlet.ConfigurationBootstrap;
import org.jboss.resteasy.plugins.server.servlet.HttpRequestFactory;
import org.jboss.resteasy.plugins.server.servlet.HttpResponseFactory;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher;
import org.jboss.resteasy.plugins.server.servlet.ServletSecurityContext;
import org.jboss.resteasy.plugins.server.servlet.ServletUtil;
import org.jboss.resteasy.specimpl.ResteasyHttpHeaders;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.Registry;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.ResteasyUriInfo;
import org.jboss.resteasy.util.GetRestful;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class MultipleServletContainerDispatcher {
    protected Dispatcher dispatcher;
    protected ResteasyProviderFactory providerFactory;
    private final static Logger logger = Logger.getLogger(ServletContainerDispatcher.class);
    private String servletMappingPrefix = "";
    protected ResteasyDeployment deployment = null;
    protected HttpRequestFactory requestFactory;
    protected HttpResponseFactory responseFactory;

    public Dispatcher getDispatcher() {
        return this.dispatcher;
    }

    public void init(ServletContext servletContext, ConfigurationBootstrap bootstrap, HttpRequestFactory requestFactory,
            HttpResponseFactory responseFactory) throws ServletException {
        this.requestFactory = requestFactory;
        this.responseFactory = responseFactory;
        ResteasyProviderFactory globalFactory = (ResteasyProviderFactory) servletContext
                .getAttribute(ResteasyProviderFactory.class.getName());
        Dispatcher globalDispatcher = (Dispatcher) servletContext.getAttribute(Dispatcher.class.getName());

        String application = bootstrap.getInitParameter("javax.ws.rs.Application");
        String useGlobalStr = bootstrap.getInitParameter("resteasy.servlet.context.deployment");
        boolean useGlobal = globalFactory != null;
        if (useGlobalStr != null) {
            useGlobal = Boolean.parseBoolean(useGlobalStr);
        }

        // use global is backward compatible with 2.3.x and earlier and will store and/or use the
        // dispatcher and provider factory
        // in the servlet context
        if (useGlobal) {
            this.providerFactory = globalFactory;
            this.dispatcher = globalDispatcher;
            if (((this.providerFactory != null) && (this.dispatcher == null))
                    || ((this.providerFactory == null) && (this.dispatcher != null))) { throw new ServletException(
                    "Unknown state.  You have a Listener messing up what resteasy expects"); }
            // We haven't been initialized by an external entity so bootstrap ourselves
            if (this.providerFactory == null) {
                this.deployment = bootstrap.createDeployment();
                this.deployment.start();

                servletContext.setAttribute(ResteasyProviderFactory.class.getName(), this.deployment.getProviderFactory());
                servletContext.setAttribute(Dispatcher.class.getName(), this.deployment.getDispatcher());
                servletContext.setAttribute(Registry.class.getName(), this.deployment.getRegistry());

                this.dispatcher = this.deployment.getDispatcher();
                this.providerFactory = this.deployment.getProviderFactory();

            } else {
                // ResteasyBootstrap inited us. Check to see if the servlet defines an Application
                // class
                if (application != null) {
                    try {
                        Map contextDataMap = ResteasyProviderFactory.getContextDataMap();
                        contextDataMap.putAll(this.dispatcher.getDefaultContextObjects());
                        Application app = ResteasyDeployment.createApplication(application.trim(), this.dispatcher,
                                this.providerFactory);
                        // push context data so we can inject it
                        processApplication(app);
                    } finally {
                        ResteasyProviderFactory.removeContextDataLevel();
                    }
                }
            }
            this.servletMappingPrefix = bootstrap.getParameter(ResteasyContextParameters.RESTEASY_SERVLET_MAPPING_PREFIX);
            if (this.servletMappingPrefix == null) {
                this.servletMappingPrefix = "";
            }
            this.servletMappingPrefix = this.servletMappingPrefix.trim();
        } else {
            this.deployment = bootstrap.createDeployment();
            this.deployment.start();
            this.dispatcher = this.deployment.getDispatcher();
            this.providerFactory = this.deployment.getProviderFactory();

            this.servletMappingPrefix = bootstrap.getParameter(ResteasyContextParameters.RESTEASY_SERVLET_MAPPING_PREFIX);
            if (this.servletMappingPrefix == null) {
                this.servletMappingPrefix = "";
            }
            this.servletMappingPrefix = this.servletMappingPrefix.trim();
        }
    }

    public void destroy() {
        if (this.deployment != null) {
            this.deployment.stop();
        }
    }

    protected void processApplication(Application config) {
        logger.info("Deploying " + Application.class.getName() + ": " + config.getClass());
        ArrayList<Class> actualResourceClasses = new ArrayList<Class>();
        ArrayList<Class> actualProviderClasses = new ArrayList<Class>();
        ArrayList resources = new ArrayList();
        ArrayList providers = new ArrayList();
        if (config.getClasses() != null) {
            for (Class clazz : config.getClasses()) {
                if (GetRestful.isRootResource(clazz)) {
                    logger.info("Adding class resource " + clazz.getName() + " from Application " + config.getClass());
                    actualResourceClasses.add(clazz);
                } else {
                    logger.info("Adding provider class " + clazz.getName() + " from Application " + config.getClass());
                    actualProviderClasses.add(clazz);
                }
            }
        }
        if (config.getSingletons() != null) {
            for (Object obj : config.getSingletons()) {
                if (GetRestful.isRootResource(obj.getClass())) {
                    logger.info("Adding singleton resource " + obj.getClass().getName() + " from Application "
                            + config.getClass());
                    resources.add(obj);
                } else {
                    logger.info("Adding singleton provider " + obj.getClass().getName() + " from Application "
                            + config.getClass());
                    providers.add(obj);
                }
            }
        }
        for (Class clazz : actualProviderClasses) {
            this.providerFactory.registerProvider(clazz);
        }
        for (Object obj : providers) {
            this.providerFactory.registerProviderInstance(obj);
        }
        for (Class clazz : actualResourceClasses) {
            this.dispatcher.getRegistry().addPerRequestResource(clazz);
        }
        for (Object obj : resources) {
            this.dispatcher.getRegistry().addSingletonResource(obj);
        }
    }

    public void setDispatcher(Dispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    public void service(String httpMethod, HttpServletRequest request, HttpServletResponse response, boolean handleNotFound)
            throws IOException, NotFoundException {
        try {
            // logger.info(httpMethod + " " + request.getRequestURL().toString());
            // logger.info("***PATH: " + request.getRequestURL());
            // classloader/deployment aware RestasyProviderFactory. Used to have request specific
            // ResteasyProviderFactory.getInstance()
            ResteasyProviderFactory defaultInstance = ResteasyProviderFactory.getInstance();
            if (defaultInstance instanceof ThreadLocalResteasyProviderFactory) {
                ThreadLocalResteasyProviderFactory.push(this.providerFactory);
            }
            ResteasyHttpHeaders headers = null;
            ResteasyUriInfo uriInfo = null;
            try {
                headers = ServletUtil.extractHttpHeaders(request);
                String[] prefixes = this.servletMappingPrefix.split(",");

                for (String prefix : prefixes) {
                    if (request.getRequestURL().toString().contains(String.format("%s/", prefix))) {
                        uriInfo = ServletUtil.extractUriInfo(request, prefix);
                        break;
                    }
                }
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                // made it warn so that people can filter this.
                logger.warn("Failed to parse request.", e);
                return;
            }

            HttpResponse theResponse = this.responseFactory.createResteasyHttpResponse(response);
            HttpRequest in = this.requestFactory.createResteasyHttpRequest(httpMethod, request, headers, uriInfo, theResponse,
                    response);

            try {
                ResteasyProviderFactory.pushContext(HttpServletRequest.class, request);
                ResteasyProviderFactory.pushContext(HttpServletResponse.class, response);

                ResteasyProviderFactory.pushContext(SecurityContext.class, new ServletSecurityContext(request));
                if (handleNotFound) {
                    this.dispatcher.invoke(in, theResponse);
                } else {
                    ((SynchronousDispatcher) this.dispatcher).invokePropagateNotFound(in, theResponse);
                }
            } finally {
                ResteasyProviderFactory.clearContextData();
            }
        } finally {
            ResteasyProviderFactory defaultInstance = ResteasyProviderFactory.getInstance();
            if (defaultInstance instanceof ThreadLocalResteasyProviderFactory) {
                ThreadLocalResteasyProviderFactory.pop();
            }

        }
    }
}


text:
package org.collectionspace.services.client;

import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * ContactProxy.java
 *
 * $LastChangedRevision: $
 * $LastChangedDate: $
 */
@Path(ContactClient.SERVICE_PATH_PROXY)
@Produces({"application/xml"})
@Consumes({"application/xml"})
public interface ContactProxy extends CollectionSpaceCommonListPoxProxy {
}


text:
package com.intellij.openapi.util.io;

import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.ArrayUtil;
import com.intellij.util.PairProcessor;
import com.intellij.util.ThreeState;
import com.intellij.util.containers.Convertor;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.*;

public class FileUtilTest {
  private static final char UNIX_SEPARATOR = '/';
  private static final char WINDOWS_SEPARATOR = '\\';

  @Test
  public void toCanonicalPath() {
    assertEquals("", FileUtil.toCanonicalPath(""));
    assertEquals("  ", FileUtil.toCanonicalPath("  "));

    assertEquals("/", FileUtil.toCanonicalPath("/", UNIX_SEPARATOR));
    assertEquals("/", FileUtil.toCanonicalPath("/./", UNIX_SEPARATOR));
    assertEquals("a/b", FileUtil.toCanonicalPath("a/b/", UNIX_SEPARATOR));
    assertEquals("/a/b", FileUtil.toCanonicalPath("/a/////b/", UNIX_SEPARATOR));
    assertEquals("/a/b", FileUtil.toCanonicalPath("/a/././b/", UNIX_SEPARATOR));
    assertEquals("/c", FileUtil.toCanonicalPath("/a/b/../../c", UNIX_SEPARATOR));
    assertEquals("/a", FileUtil.toCanonicalPath("/a/b/..", UNIX_SEPARATOR));
    assertEquals("/a", FileUtil.toCanonicalPath("/a/b/../", UNIX_SEPARATOR));
    assertEquals("/a\\b", FileUtil.toCanonicalPath("/a\\b/", UNIX_SEPARATOR));
    assertEquals("/", FileUtil.toCanonicalPath("/a/../", UNIX_SEPARATOR));
    assertEquals("/", FileUtil.toCanonicalPath("/a/../..", UNIX_SEPARATOR));
    assertEquals("/b", FileUtil.toCanonicalPath("/a/../../b", UNIX_SEPARATOR));
    assertEquals("a...b", FileUtil.toCanonicalPath("a...b", UNIX_SEPARATOR));
    assertEquals("a../b", FileUtil.toCanonicalPath("a../b", UNIX_SEPARATOR));
    assertEquals("a./.b", FileUtil.toCanonicalPath("a./.b", UNIX_SEPARATOR));
    assertEquals("a", FileUtil.toCanonicalPath("a/b/..", UNIX_SEPARATOR));
    assertEquals("a/b", FileUtil.toCanonicalPath("a/b/.", UNIX_SEPARATOR));
    assertEquals("a/b/...", FileUtil.toCanonicalPath("a/b/...", UNIX_SEPARATOR));
    assertEquals("...", FileUtil.toCanonicalPath("...", UNIX_SEPARATOR));
    assertEquals(".local", FileUtil.toCanonicalPath(".local/", UNIX_SEPARATOR));
    assertEquals("file.ext", FileUtil.toCanonicalPath("file.ext", UNIX_SEPARATOR));
    assertEquals("file.", FileUtil.toCanonicalPath("file.", UNIX_SEPARATOR));
    assertEquals("file..", FileUtil.toCanonicalPath("file..", UNIX_SEPARATOR));
    assertEquals("", FileUtil.toCanonicalPath(".", UNIX_SEPARATOR));
    assertEquals("", FileUtil.toCanonicalPath("./", UNIX_SEPARATOR));
    assertEquals("", FileUtil.toCanonicalPath("a/..", UNIX_SEPARATOR));
    assertEquals("b", FileUtil.toCanonicalPath("a/..//b", UNIX_SEPARATOR));
    assertEquals("..", FileUtil.toCanonicalPath("..", UNIX_SEPARATOR));
    assertEquals("..", FileUtil.toCanonicalPath("../", UNIX_SEPARATOR));
    assertEquals("../..", FileUtil.toCanonicalPath("../..", UNIX_SEPARATOR));
    assertEquals("../../..", FileUtil.toCanonicalPath("../../..///./", UNIX_SEPARATOR));
    assertEquals("../a....", FileUtil.toCanonicalPath("../a....//", UNIX_SEPARATOR));
    assertEquals("..", FileUtil.toCanonicalPath("../a..../../", UNIX_SEPARATOR));

    assertEquals("C:/", FileUtil.toCanonicalPath("C:\\", WINDOWS_SEPARATOR));
    assertEquals("a/b", FileUtil.toCanonicalPath("a\\b\\", WINDOWS_SEPARATOR));
    assertEquals("c:/a/b", FileUtil.toCanonicalPath("c:\\a\\\\b\\", WINDOWS_SEPARATOR));
    assertEquals("c:/a/b", FileUtil.toCanonicalPath("c:\\a\\.\\.\\b\\", WINDOWS_SEPARATOR));
    assertEquals("c:/d", FileUtil.toCanonicalPath("c:\\a\\b\\..\\..\\d", WINDOWS_SEPARATOR));
    assertEquals("/a/b", FileUtil.toCanonicalPath("\\a/b\\", WINDOWS_SEPARATOR));
    assertEquals("c:/", FileUtil.toCanonicalPath("c:\\a\\..\\", WINDOWS_SEPARATOR));
    assertEquals("c:/", FileUtil.toCanonicalPath("c:\\a\\..\\..", WINDOWS_SEPARATOR));
    assertEquals("c:/b", FileUtil.toCanonicalPath("c:\\a\\..\\..\\b", WINDOWS_SEPARATOR));
  }

  @Test
  public void isAncestor() throws Exception {
    assertTrue(FileUtil.isAncestor("/", "/a/", true));
    assertTrue(FileUtil.isAncestor("/a/b/c", "/a/b/c/d/e/f", true));
    assertTrue(FileUtil.isAncestor("/a/b/c/", "/a/b/c/d/e/f", true));
    assertFalse(FileUtil.isAncestor("/a/b/c/1", "/a/b/c/2", true));
    assertFalse(FileUtil.isAncestor("/a/b/c/1", "/a/b/c/2", false));
    assertTrue(FileUtil.isAncestor("/a/b/c/", "/a/b/c", false));
    assertTrue(FileUtil.isAncestor("/a///b/c", "/a/b/c/", false));
    assertFalse(FileUtil.isAncestor("/a/b/c/", "/a/./b/c", true));
    assertFalse(FileUtil.isAncestor("/a/b/c", "/a/b/c/", true));
    assertFalse(FileUtil.isAncestor("/a/b/c", "/a/b/cde", true));
    assertFalse(FileUtil.isAncestor("/a/b/c", "/a/b/cde", false));

    assertEquals(SystemInfo.isWindows, FileUtil.isAncestor("c:\\", "C:/a/b/c", true));
    assertEquals(!SystemInfo.isFileSystemCaseSensitive, FileUtil.isAncestor("/a/b/c", "/a/B/c/d", true));
  }

  @Test
  public void testRemoveAncestors() throws Exception {
    final String[] arr = {"/a/b/c", "/a", "/a/b", "/d/e", "/b/c", "/a/d", "/b/c/ttt", "/a/ewq.euq"};
    final String[] expectedResult = {"/a","/b/c","/d/e"};
    @SuppressWarnings("unchecked") final Collection<String> result = FileUtil.removeAncestors(Arrays.asList(arr), Convertor.SELF, PairProcessor.TRUE);
    assertArrayEquals(expectedResult, ArrayUtil.toStringArray(result));
  }

  @Test
  public void testCheckImmediateChildren() throws Exception {
    final String root = "/a";
    final String[] arr = {"/a/b/c", "/a", "/a/b", "/d/e", "/b/c", "/a/d", "/a/b/c/d/e"};
    final ThreeState[] expectedResult = {ThreeState.UNSURE, ThreeState.YES, ThreeState.YES, ThreeState.NO, ThreeState.NO, ThreeState.YES, ThreeState.UNSURE};
    final ThreeState[] expectedResult2 = {ThreeState.UNSURE, ThreeState.NO, ThreeState.YES, ThreeState.NO, ThreeState.NO, ThreeState.YES, ThreeState.UNSURE};

    for (int i = 0; i < arr.length; i++) {
      String s = arr[i];
      final ThreeState state = FileUtil.isAncestorThreeState(root, s, false);
      assertEquals(String.valueOf(i), expectedResult[i], state);
    }

    for (int i = 0; i < arr.length; i++) {
      String s = arr[i];
      final ThreeState state = FileUtil.isAncestorThreeState(root, s, true);
      assertEquals(String.valueOf(i), expectedResult2[i], state);
    }
  }

  @Test
  public void testRepeatableOperation() throws Exception {
    abstract class CountableIOOperation implements FileUtilRt.RepeatableIOOperation<Boolean, IOException> {
      private int count = 0;

      @Override
      public Boolean execute(boolean lastAttempt) throws IOException {
        count++;
        return stop(lastAttempt) ? true : null;
      }

      protected abstract boolean stop(boolean lastAttempt);
    }

    CountableIOOperation successful = new CountableIOOperation() {
      @Override protected boolean stop(boolean lastAttempt) { return true; }
    };
    FileUtilRt.doIOOperation(successful);
    assertEquals(1, successful.count);

    CountableIOOperation failed = new CountableIOOperation() {
      @Override protected boolean stop(boolean lastAttempt) { return false; }
    };
    FileUtilRt.doIOOperation(failed);
    assertEquals(10, failed.count);

    CountableIOOperation lastShot = new CountableIOOperation() {
      @Override protected boolean stop(boolean lastAttempt) { return lastAttempt; }
    };
    FileUtilRt.doIOOperation(lastShot);
    assertEquals(10, lastShot.count);
  }
}


text:
package replication

const (
	//we only support MySQL 5.0.0+ binlog format, maybe???
	MinBinlogVersion = 4
)

var (
	//binlog header [ fe `bin` ]
	BinLogFileHeader []byte = []byte{0xfe, 0x62, 0x69, 0x6e}

	SemiSyncIndicator byte = 0xef
)

const (
	LOG_EVENT_BINLOG_IN_USE_F            uint16 = 0x0001
	LOG_EVENT_FORCED_ROTATE_F            uint16 = 0x0002
	LOG_EVENT_THREAD_SPECIFIC_F          uint16 = 0x0004
	LOG_EVENT_SUPPRESS_USE_F             uint16 = 0x0008
	LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F uint16 = 0x0010
	LOG_EVENT_ARTIFICIAL_F               uint16 = 0x0020
	LOG_EVENT_RELAY_LOG_F                uint16 = 0x0040
	LOG_EVENT_IGNORABLE_F                uint16 = 0x0080
	LOG_EVENT_NO_FILTER_F                uint16 = 0x0100
	LOG_EVENT_MTS_ISOLATE_F              uint16 = 0x0200
)

const (
	BINLOG_DUMP_NEVER_STOP  uint16 = 0x00
	BINLOG_DUMP_NON_BLOCK   uint16 = 0x01
	BINLOG_THROUGH_POSITION uint16 = 0x02
	BINLOG_THROUGH_GTID     uint16 = 0x04
)

const (
	BINLOG_ROW_IMAGE_FULL    = "FULL"
	BINLOG_ROW_IAMGE_MINIMAL = "MINIMAL"
	BINLOG_ROW_IMAGE_NOBLOB  = "NOBLOB"
)

type EventType byte

const (
	UNKNOWN_EVENT EventType = iota
	START_EVENT_V3
	QUERY_EVENT
	STOP_EVENT
	ROTATE_EVENT
	INTVAR_EVENT
	LOAD_EVENT
	SLAVE_EVENT
	CREATE_FILE_EVENT
	APPEND_BLOCK_EVENT
	EXEC_LOAD_EVENT
	DELETE_FILE_EVENT
	NEW_LOAD_EVENT
	RAND_EVENT
	USER_VAR_EVENT
	FORMAT_DESCRIPTION_EVENT
	XID_EVENT
	BEGIN_LOAD_QUERY_EVENT
	EXECUTE_LOAD_QUERY_EVENT
	TABLE_MAP_EVENT
	WRITE_ROWS_EVENTv0
	UPDATE_ROWS_EVENTv0
	DELETE_ROWS_EVENTv0
	WRITE_ROWS_EVENTv1
	UPDATE_ROWS_EVENTv1
	DELETE_ROWS_EVENTv1
	INCIDENT_EVENT
	HEARTBEAT_EVENT
	IGNORABLE_EVENT
	ROWS_QUERY_EVENT
	WRITE_ROWS_EVENTv2
	UPDATE_ROWS_EVENTv2
	DELETE_ROWS_EVENTv2
	GTID_EVENT
	ANONYMOUS_GTID_EVENT
	PREVIOUS_GTIDS_EVENT
)

const (
	// MariaDB event starts from 160
	MARIADB_ANNOTATE_ROWS_EVENT EventType = 160 + iota
	MARIADB_BINLOG_CHECKPOINT_EVENT
	MARIADB_GTID_EVENT
	MARIADB_GTID_LIST_EVENT
)

func (e EventType) String() string {
	switch e {
	case UNKNOWN_EVENT:
		return "UnknownEvent"
	case START_EVENT_V3:
		return "StartEventV3"
	case QUERY_EVENT:
		return "QueryEvent"
	case STOP_EVENT:
		return "StopEvent"
	case ROTATE_EVENT:
		return "RotateEvent"
	case INTVAR_EVENT:
		return "IntVarEvent"
	case LOAD_EVENT:
		return "LoadEvent"
	case SLAVE_EVENT:
		return "SlaveEvent"
	case CREATE_FILE_EVENT:
		return "CreateFileEvent"
	case APPEND_BLOCK_EVENT:
		return "AppendBlockEvent"
	case EXEC_LOAD_EVENT:
		return "ExecLoadEvent"
	case DELETE_FILE_EVENT:
		return "DeleteFileEvent"
	case NEW_LOAD_EVENT:
		return "NewLoadEvent"
	case RAND_EVENT:
		return "RandEvent"
	case USER_VAR_EVENT:
		return "UserVarEvent"
	case FORMAT_DESCRIPTION_EVENT:
		return "FormatDescriptionEvent"
	case XID_EVENT:
		return "XIDEvent"
	case BEGIN_LOAD_QUERY_EVENT:
		return "BeginLoadQueryEvent"
	case EXECUTE_LOAD_QUERY_EVENT:
		return "ExectueLoadQueryEvent"
	case TABLE_MAP_EVENT:
		return "TableMapEvent"
	case WRITE_ROWS_EVENTv0:
		return "WriteRowsEventV0"
	case UPDATE_ROWS_EVENTv0:
		return "UpdateRowsEventV0"
	case DELETE_ROWS_EVENTv0:
		return "DeleteRowsEventV0"
	case WRITE_ROWS_EVENTv1:
		return "WriteRowsEventV1"
	case UPDATE_ROWS_EVENTv1:
		return "UpdateRowsEventV1"
	case DELETE_ROWS_EVENTv1:
		return "DeleteRowsEventV1"
	case INCIDENT_EVENT:
		return "IncidentEvent"
	case HEARTBEAT_EVENT:
		return "HeartbeatEvent"
	case IGNORABLE_EVENT:
		return "IgnorableEvent"
	case ROWS_QUERY_EVENT:
		return "RowsQueryEvent"
	case WRITE_ROWS_EVENTv2:
		return "WriteRowsEventV2"
	case UPDATE_ROWS_EVENTv2:
		return "UpdateRowsEventV2"
	case DELETE_ROWS_EVENTv2:
		return "DeleteRowsEventV2"
	case GTID_EVENT:
		return "GTIDEvent"
	case ANONYMOUS_GTID_EVENT:
		return "AnonymousGTIDEvent"
	case PREVIOUS_GTIDS_EVENT:
		return "PreviousGTIDsEvent"
	case MARIADB_ANNOTATE_ROWS_EVENT:
		return "MariadbAnnotateRowsEvent"
	case MARIADB_BINLOG_CHECKPOINT_EVENT:
		return "MariadbBinLogCheckPointEvent"
	case MARIADB_GTID_EVENT:
		return "MariadbGTIDEvent"
	case MARIADB_GTID_LIST_EVENT:
		return "MariadbGTIDListEvent"

	default:
		return "UnknownEvent"
	}
}

const (
	BINLOG_CHECKSUM_ALG_OFF byte = 0 // Events are without checksum though its generator
	// is checksum-capable New Master (NM).
	BINLOG_CHECKSUM_ALG_CRC32 byte = 1 // CRC32 of zlib algorithm.
	//  BINLOG_CHECKSUM_ALG_ENUM_END,  // the cut line: valid alg range is [1, 0x7f].
	BINLOG_CHECKSUM_ALG_UNDEF byte = 255 // special value to tag undetermined yet checksum
	// or events from checksum-unaware servers
)


text:
Options dictionary gets converted directly to flannel json options blob

# Example
```yaml
  fabric:
    provider: flannel
    options:
      Network: 10.1.0.0/16
    Backend:
      Type: aws-vpc
```


text:
import {QueryCtrl} from 'app/plugins/sdk';
import angular from 'angular';
import _ from 'lodash';
import * as utils from './utils';
import * as metricFunctions from './metricFunctions';
import * as migrations from './migrations';

import './add-metric-function.directive';
import './metric-function-editor.directive';

import './css/query-editor.css!';

export class ZabbixQueryController extends QueryCtrl {

  // ZabbixQueryCtrl constructor
  constructor($scope, $injector, $rootScope, $sce, $q, templateSrv) {

    // Call superclass constructor
    super($scope, $injector);

    this.zabbix = this.datasource.zabbixAPI;
    this.cache = this.datasource.zabbixCache;
    this.$q = $q;

    // Use custom format for template variables
    this.replaceTemplateVars = this.datasource.replaceTemplateVars;
    this.templateSrv = templateSrv;

    this.editorModes = {
      0: {value: 'num', text: 'Metrics', mode: 0},
      1: {value: 'itservice', text: 'IT Services', mode: 1},
      2: {value: 'text', text: 'Text', mode: 2}
    };

    // Map functions for bs-typeahead
    this.getGroupNames = _.partial(getMetricNames, this, 'groupList');
    this.getHostNames = _.partial(getMetricNames, this, 'hostList');
    this.getApplicationNames = _.partial(getMetricNames, this, 'appList');
    this.getItemNames = _.partial(getMetricNames, this, 'itemList');

    // Update metric suggestion when template variable was changed
    $rootScope.$on('template-variable-value-updated', () => this.onVariableChange());

    // Update metrics when item selected from dropdown
    $scope.$on('typeahead-updated', () => {
      this.onTargetBlur();
    });

    this.init = function() {
      var target = this.target;

      // Migrate old targets
      target = migrations.migrate(target);

      var scopeDefaults = {
        metric: {},
        oldTarget: _.cloneDeep(this.target),
        queryOptionsText: this.renderQueryOptionsText()
      };
      _.defaults(this, scopeDefaults);

      // Load default values
      var targetDefaults = {
        mode: 0,
        group: { filter: "" },
        host: { filter: "" },
        application: { filter: "" },
        item: { filter: "" },
        functions: [],
        options: {
          showDisabledItems: false
        }
      };
      _.defaults(target, targetDefaults);

      // Create function instances from saved JSON
      target.functions = _.map(target.functions, function(func) {
        return metricFunctions.createFuncInstance(func.def, func.params);
      });

      if (target.mode === 0 ||
          target.mode === 2) {

        this.downsampleFunctionList = [
          {name: "avg", value: "avg"},
          {name: "min", value: "min"},
          {name: "max", value: "max"}
        ];

        this.initFilters();
      }
      else if (target.mode === 1) {
        this.slaPropertyList = [
          {name: "Status", property: "status"},
          {name: "SLA", property: "sla"},
          {name: "OK time", property: "okTime"},
          {name: "Problem time", property: "problemTime"},
          {name: "Down time", property: "downtimeTime"}
        ];
        this.itserviceList = [{name: "test"}];
        this.updateITServiceList();
      }
    };

    this.init();
  }

  initFilters() {
    var self = this;
    var itemtype = self.editorModes[self.target.mode].value;
    return this.$q.when(this.suggestGroups())
      .then(() => {return self.suggestHosts();})
      .then(() => {return self.suggestApps();})
      .then(() => {return self.suggestItems(itemtype);});
  }

  suggestGroups() {
    var self = this;
    return this.cache.getGroups().then(groups => {
      self.metric.groupList = groups;
      return groups;
    });
  }

  suggestHosts() {
    var self = this;
    var groupFilter = this.replaceTemplateVars(this.target.group.filter);
    return this.datasource.queryProcessor
      .filterGroups(self.metric.groupList, groupFilter)
      .then(groups => {
        var groupids = _.map(groups, 'groupid');
        return self.zabbix
          .getHosts(groupids)
          .then(hosts => {
            self.metric.hostList = hosts;
            return hosts;
          });
      });
  }

  suggestApps() {
    var self = this;
    var hostFilter = this.replaceTemplateVars(this.target.host.filter);
    return this.datasource.queryProcessor
      .filterHosts(self.metric.hostList, hostFilter)
      .then(hosts => {
        var hostids = _.map(hosts, 'hostid');
        return self.zabbix
          .getApps(hostids)
          .then(apps => {
            return self.metric.appList = apps;
          });
      });
  }

  suggestItems(itemtype='num') {
    var self = this;
    var appFilter = this.replaceTemplateVars(this.target.application.filter);
    if (appFilter) {
      // Filter by applications
      return this.datasource.queryProcessor
        .filterApps(self.metric.appList, appFilter)
        .then(apps => {
          var appids = _.map(apps, 'applicationid');
          return self.zabbix
            .getItems(undefined, appids, itemtype)
            .then(items => {
              if (!self.target.options.showDisabledItems) {
                items = _.filter(items, {'status': '0'});
              }
              self.metric.itemList = items;
              return items;
            });
        });
    } else {
      // Return all items belonged to selected hosts
      var hostids = _.map(self.metric.hostList, 'hostid');
      return self.zabbix
        .getItems(hostids, undefined, itemtype)
        .then(items => {
          if (!self.target.options.showDisabledItems) {
            items = _.filter(items, {'status': '0'});
          }
          self.metric.itemList = items;
          return items;
        });
    }
  }

  isRegex(str) {
    return utils.isRegex(str);
  }

  isVariable(str) {
    return utils.isTemplateVariable(str, this.templateSrv.variables);
  }

  onTargetBlur() {
    var newTarget = _.cloneDeep(this.target);
    if (!_.isEqual(this.oldTarget, this.target)) {
      this.oldTarget = newTarget;
      this.targetChanged();
    }
  }

  onVariableChange() {
    if (this.isContainsVariables()) {
      this.targetChanged();
    }
  }

  /**
   * Check query for template variables
   */
  isContainsVariables() {
    var self = this;
    return _.some(self.templateSrv.variables, variable => {
      return _.some(['group', 'host', 'application', 'item'], field => {
        return self.templateSrv.containsVariable(self.target[field].filter, variable.name);
      });
    });
  }

  parseTarget() {
    // Parse target
  }

  // Validate target and set validation info
  validateTarget() {
    // validate
  }

  targetChanged() {
    this.initFilters();
    this.parseTarget();
    this.panelCtrl.refresh();
  }

  addFunction(funcDef) {
    var newFunc = metricFunctions.createFuncInstance(funcDef);
    newFunc.added = true;
    this.target.functions.push(newFunc);

    this.moveAliasFuncLast();

    if (newFunc.params.length && newFunc.added ||
        newFunc.def.params.length === 0) {
      this.targetChanged();
    }
  }

  removeFunction(func) {
    this.target.functions = _.without(this.target.functions, func);
    this.targetChanged();
  }

  moveAliasFuncLast() {
    var aliasFunc = _.find(this.target.functions, function(func) {
      return func.def.name === 'alias' ||
        func.def.name === 'aliasByNode' ||
        func.def.name === 'aliasByMetric';
    });

    if (aliasFunc) {
      this.target.functions = _.without(this.target.functions, aliasFunc);
      this.target.functions.push(aliasFunc);
    }
  }

  toggleQueryOptions() {
    this.showQueryOptions = !this.showQueryOptions;
  }

  onQueryOptionChange() {
    this.queryOptionsText = this.renderQueryOptionsText();
    this.onTargetBlur();
  }

  renderQueryOptionsText() {
    var optionsMap = {
      showDisabledItems: "Show disabled items"
    };
    var options = [];
    _.forOwn(this.target.options, (value, key) => {
      if (value) {
        if (value === true) {
          // Show only option name (if enabled) for boolean options
          options.push(optionsMap[key]);
        } else {
          // Show "option = value" for another options
          options.push(optionsMap[key] + " = " + value);
        }
      }
    });
    return "Options: " + options.join(', ');
  }

  /**
   * Switch query editor to specified mode.
   * Modes:
   *  0 - items
   *  1 - IT services
   *  2 - Text metrics
   */
  switchEditorMode(mode) {
    this.target.mode = mode;
    this.init();
  }

  /////////////////
  // IT Services //
  /////////////////

  /**
   * Update list of IT services
   */
  updateITServiceList() {
    var self = this;
    this.datasource.zabbixAPI.getITService().then(function (iteservices) {
      self.itserviceList = [];
      self.itserviceList = self.itserviceList.concat(iteservices);
    });
  }

  /**
   * Call when IT service is selected.
   */
  selectITService() {
    if (!_.isEqual(this.oldTarget, this.target) && _.isEmpty(this.target.errors)) {
      this.oldTarget = angular.copy(this.target);
      this.panelCtrl.refresh();
    }
  }

}

// Set templateUrl as static property
ZabbixQueryController.templateUrl = 'datasource-zabbix/partials/query.editor.html';

// Get list of metric names for bs-typeahead directive
function getMetricNames(scope, metricList) {
  return _.uniq(_.map(scope.metric[metricList], 'name'));
}


text:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BaseRequestOptions, ResponseOptionsArgs, Http, Response, Request, ResponseOptions, ResponseType, Headers } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

export class RequestResponsePair {
    expectedRequest: {
        url: string;
        headers?: Headers;
        body?: Object;
    }
    response: ResponseOptionsArgs;
}

export class MockHttpFixture {
    private http: Http;
    private mockBackend: MockBackend;

    constructor(hostUrl: string) {
        this.mockBackend = TestBed.get(MockBackend);
        this.http = TestBed.get(Http);
        this.hostUrl = hostUrl;
    }

    public static getModuleProviders(): any[] {
        return [
            {
                provide: Http, useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
                    return new Http(backend, options);
                }, deps: [MockBackend, BaseRequestOptions]
            },
            MockBackend, BaseRequestOptions];
    }

    private hostUrl: string;

    private getFullUrl(relativeUrl: string): string {
        return this.hostUrl.concat(relativeUrl);
    }

    configureResponses(...requestResponsePairs: RequestResponsePair[]) {
        var index = 0;
        this.mockBackend.connections.subscribe((connection: MockConnection) => {
            var pair: RequestResponsePair = requestResponsePairs[index];
            index++;
            expect(connection.request.url).toEqual(this.getFullUrl(pair.expectedRequest.url));
            connection.mockRespond(new Response(new ResponseOptions(pair.response)));
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<item>
<userName>shieldwatch</userName>
<passWord>test123</passWord>
<dataProcessFor>1</dataProcessFor>
<Company FormType='5498'>
<PayerInfo>
<TIN>56679988</TIN>
<Year>2015</Year>
<TypeOfTIN>4</TypeOfTIN>
<TransferAgentIndicator>0</TransferAgentIndicator>
<CompanyName>ABC Company</CompanyName>
<CompanyNameLine2>ABC Company</CompanyNameLine2>
<CompanyAddress>123 Some Street</CompanyAddress>
<City>Some City</City>
<State>ST</State>
<Zipcode>123445</Zipcode>
<Phone>8152264352</Phone>
</PayerInfo>
<Recipient id="11">
<PayeeTIN>374476543</PayeeTIN>
<PayeeTypeOfTIN>1</PayeeTypeOfTIN>
<PayeeName>RONALDO TRUEDOE</PayeeName>
<PayeeName2>RE</PayeeName2>
<PayeeAddr>111 S PALMTREE CT</PayeeAddr>
<PayeeCity>SOMECITY</PayeeCity>
<PayeeState>OK</PayeeState>
<PayeeZipcode>743451111</PayeeZipcode>
<Box1>452.67</Box1>
<Box2>125.51</Box2>
<AcctNumber>0245896005</AcctNumber>
<EmployeeContrib>2500.00</EmployeeContrib>
<TotalContribReturnYr>2500.00</TotalContribReturnYr>
<FairMarketValue>5000.00</FairMarketValue>
<ArcherMSAInd>true</ArcherMSAInd>
</Recipient>
</Company>
</item>
</gwx:DataPacket>


text:
package se.kth.csc.kmr.conserve.core;

import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import se.kth.csc.kmr.conserve.Application;
import se.kth.csc.kmr.conserve.Concept;
import se.kth.csc.kmr.conserve.Contemp;
import se.kth.csc.kmr.conserve.Guard;
import se.kth.csc.kmr.conserve.Initializer;
import se.kth.csc.kmr.conserve.Listener;
import se.kth.csc.kmr.conserve.Request;
import se.kth.csc.kmr.conserve.Responder;
import se.kth.csc.kmr.conserve.data.jpa.JPAConserve;
import se.kth.csc.kmr.conserve.iface.jaxrs.RequestImpl;

import com.google.inject.Binder;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.MapBinder;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Names;

@Singleton
public class Contapp implements Application {

	private static Logger log = LoggerFactory.getLogger(Contapp.class);

	@Inject
	private Injector injector;

	@Inject
	private Map<UUID, Responder> responderMap;

	@Inject
	private Map<UUID, Guard> guardMap;

	@Inject
	private Map<UUID, Listener> listenerMap;

	private volatile boolean isSetUp = false;

	private volatile boolean isSettingUp = false;

	@Override
	public boolean isSetUp() {
		return isSetUp;
	}

	@Override
	public boolean isSettingUp() {
		return isSettingUp;
	}

	@Override
	public synchronized void setUp(Request request) {
		if (isSetUp) {
			return;
		}
		isSettingUp = true;
		Contemp conserve = injector.getInstance(Contemp.class);
		((JPAConserve) conserve).replicate();
		Set<Initializer> initializers = injector.getInstance(Key
				.get(new TypeLiteral<Set<Initializer>>() {
				}));
		for (Initializer i : initializers) {
			log.info("Initializing: " + i);
			i.initialize(request);
			conserve.endEntry();
		}
		for (Responder r : responderMap.values()) {
			log.info("Initializing responder: " + r);
			r.initialize(request);
			conserve.endEntry();
		}
		for (Guard g : guardMap.values()) {
			log.info("Initializing guard: " + g);
			g.initialize(request);
			conserve.endEntry();
		}
		for (Listener l : listenerMap.values()) {
			log.info("Initializing listener: " + l);
			l.initialize(request);
			conserve.endEntry();
		}
		isSetUp = true;
		isSettingUp = false;
	}

	@Override
	public UUID getRootUuid(Request request) {
		String baseUri = ((RequestImpl) request).getUriInfo().getBaseUri()
				.toString();
		Contemp conserve = injector.getInstance(Contemp.class);
		Concept domain = conserve.getConcept(conserve.getRootUuid(), baseUri);
		if (domain != null
				&& ConserveTerms.hasService.equals(domain.getPredicate())) {
			return domain.getUuid();
		} else {
			throw new IllegalArgumentException("This domain does not exist: "
					+ baseUri);
		}
	}

	public static MapBinder<UUID, Responder> newResponderBinder(Binder binder) {
		return MapBinder.newMapBinder(binder, UUID.class, Responder.class);
	}

	public static MapBinder<UUID, Guard> newGuardBinder(Binder binder) {
		return MapBinder.newMapBinder(binder, UUID.class, Guard.class);
	}

	public static MapBinder<UUID, Listener> newListenerBinder(Binder binder) {
		return MapBinder.newMapBinder(binder, UUID.class, Listener.class)
				.permitDuplicates();
	}

	public static Multibinder<Initializer> newInitializerBinder(Binder binder) {
		return Multibinder.newSetBinder(binder, Initializer.class);
	}

	public static Multibinder<UUID> newTopicBinder(Binder binder) {
		return Multibinder.newSetBinder(binder, UUID.class,
				Names.named("contemp-global-topics"));
	}

	public static MapBinder<String, String> newNamespaceBinder(Binder binder) {
		return MapBinder.newMapBinder(binder, String.class, String.class,
				Names.named("contemp-namespaces"));
	}

}


text:
<?php session_start(); ?>

<?php
/**
 * barcode_label_output
 *
 * PHP version 5.3.3
 *
 * Output labels grabbed from WMS API and allow user to print.
 */
$barcodes         = '';
$barcodeCount     = '';
$labelStart       = '';
$printPocketLabel = '';

if (isset($_REQUEST['barcodes']) === true && $_REQUEST['barcodes'] !== '') {
    $barcodes     = $_REQUEST['barcodes'];
    $barcodeCount = count($barcodes);
    $tmp          = '';

    for ($i = 0; $i < $barcodeCount; $i++) {
        $tmp .= $barcodes[$i];
    }
}

if (isset($_REQUEST['print_pocket_label']) === true && $_REQUEST['print_pocket_label'] !== '') {
    $printPocketLabel = $_REQUEST['print_pocket_label'];
}

if (isset($_REQUEST['label_start']) === true
    && is_numeric($_REQUEST['label_start']) === true
    && $_REQUEST['label_start'] > 0
    && $_REQUEST['label_start'] < 9
) {
    $labelStart = $_REQUEST['label_start'];
}

$_SESSION['saved_form'] = $_REQUEST;

$printArray = array();

require_once '../lib/quicklabels.php';
// Store all spine labels and pocket label counterparts in new, combined array.
for ($x = 0; $x < $barcodeCount; $x++) {
    if ($barcodes[$x] !== '') {
        $printArray[] = quicklabels($barcodes[$x], $printPocketLabel[$x]);
    }
}

// Add empty rows to print_array to start print on specified label.
if (isset($labelStart) === true && $labelStart !== '') {
    for ($x = 1; $x < $labelStart; $x++) {
        array_unshift($printArray, array(' ', ' '));
    }
}
require 'edited.php';
$labelRow   = '';
$labelPage  = '';
$printCount = count($printArray);
// Build labels using divs.
for ($x = 0; $x < $printCount; $x++) {
    $labelRow .= '
'."\n";
    if (isset($printArray[$x][0]) === true && $printArray[$x][0] !== '') {
        $cnumVal = $printArray[$x][0];

    } else {
        $cnumVal = ' ';
    }

    if (isset($printArray[$x][1]) === true && $printArray[$x][1] !== '') {
        $pocketVal = $printArray[$x][1];
    } else {
        $pocketVal = ' ';
    }

    $labelRow .= '

'.$cnumVal.'

'."\n";
    $labelRow .= '

'.$pocketVal.'

'."\n";

    $labelRow .= "
\n";
    if (($x % 2) === 0) {
        $labelRow .= '
&nbsp
';
    }

    // Test whether we have eight labels for 2-col printing, or are on the last label.
    if ((($x + 1) % 8 === 0) || ($x + 1) >= count($printArray)) {
        $labelPage .= '
'.$labelRow.'
'."\n";
        $labelRow   = '';
    }
    $_SESSION['cnumVal'] = preg_replace(array('#
#i', '#<\/div\s*/?>#i', '#
#i'),array("\n","",""), $cnumVal);
    $cnumVal = $_SESSION['cnumVal'];
}//end for

//Store print array for FPDF to print from
$_SESSION['printArray'] = $printArray;
$_SESSION['cnumVal'] = $cnumVal;
?>

Print Labels

            <input type="radio" name="printer" value="laser" checked="checked"/>Print PDF

<?php
echo "
$labelPage
";
?>


text:
package eventmaster

import (
	"fmt"
	"html/template"
	"path/filepath"
	"sync"
)

// TemplateGetter defines what needs to be implemented to be able to fetch
// templates for use by a Site.
type TemplateGetter interface {
	Get(name string) (*template.Template, error)
}

// Disk keeps track of the location of the root directory of the template
// directory.
type Disk struct {
	Root string
}

// Get attempts to merge the requested name+.html with base.html found at root.
func (d Disk) Get(name string) (*template.Template, error) {
	p := filepath.Join(d.Root, name)
	return template.New("main.html").Funcs(funcMap).ParseFiles(p, filepath.Join(d.Root, "main.html"))
}

// AssetTemplate pulls templates from an assetfs.
type AssetTemplate struct {
	sync.RWMutex
	Asset func(name string) ([]byte, error)

	cache map[string]*template.Template
}

// NewAssetTemplate returns a ready-to-use AssetTemplate.
func NewAssetTemplate(asset func(string) ([]byte, error)) *AssetTemplate {
	return &AssetTemplate{
		Asset: asset,
		cache: map[string]*template.Template{},
	}
}

// Get attempts to merge the requested name+.html with base.html found at root.
func (at *AssetTemplate) Get(name string) (*template.Template, error) {
	at.RLock()
	if t, ok := at.cache[name]; ok {
		at.RUnlock()
		return t, nil
	}
	at.RUnlock()

	base, err := at.Asset("templates/main.html")
	if err != nil {
		return nil, fmt.Errorf("could not get base contents: %v", err)
	}
	page, err := at.Asset(fmt.Sprintf("templates/%s", name))
	if err != nil {
		return nil, fmt.Errorf("could not get base contents: %v", err)
	}

	t, err := template.New(name).Funcs(funcMap).Parse(string(base))
	if err != nil {
		return t, fmt.Errorf("parsing base: %v", err)
	}
	t, err = t.Parse(string(page))
	if err != nil {
		return t, fmt.Errorf("parsing specific page %s: %v", name, err)
	}

	at.Lock()
	at.cache[name] = t
	at.Unlock()

	return t, nil
}


text:
<?php
// declare(strict_types = 1);
namespace Nooper;

class Token {

	/**
	 * Properties
	 */
	protected $app_id;
	protected $app_secret;
	protected $operate_url = 'https://api.weixin.qq.com/cgi-bin/token';

	/**
	 * public void function __construct(?string $app_id = null, ?string $app_secret = null)
	 */
	public function __construct(string $app_id = null, string $app_secret = null) {
		$this->app_id = $app_id ?? get_config('app_id');
		$this->app_secret = $app_secret ?? get_config('app_secret');
	}

	/**
	 * public void function __destruct(void)
	 */
	function __destruct() {
		// echo '-end-';
	}

	/**
	 * public boolean function write(void)
	 */
	public function write(): bool {
		$qry_params = ['grant_type'=>'client_credential', 'appid'=>$this->app_id, 'secret'=>$this->app_secret];
		$mmc = new Mimicry();
		$helper = new Translator();
		try{
			$json_datas = $helper->parse_json($mmc->get($this->operate_url, $qry_params));
		}catch(\Exception $err){
			return false;
		}
		$token = $json_datas['access_token'] ?? null;
		$expire_seconds = $json_datas['expires_in'] ?? null;
		if($token && $expire_seconds){
			$mysql = new Mysql('access_tokens');
			$datas = $mysql->field(['row_num'=>'count(*)'])->select();
			$write_datas = ['string'=>$token, 'expire_seconds'=>$expire_seconds, 'create_time'=>get_now_timestamp()];
			$end = $datas && $datas[0]['row_num'] > 0 ? $mysql->modify($write_datas) : $mysql->add($write_datas);
			return $end > 0 ? true : false;
		}
		return false;
	}

	/**
	 * public string function read(boolean $deep = true)
	 */
	public function read(bool $deep = true): string {
		$mysql = new Mysql('access_tokens');
		$datas = $mysql->field(['*'])->limit(1)->select();
		if($datas){
			list('string'=>$string, 'expire_seconds'=>$expire_seconds, 'create_time'=>$create_time)=$datas[0];
			$now = get_now_timestamp();
			if(($now - $create_time) > ($expire_seconds - 600)){
				if(!$deep) return null;
				return $this->write() ? $this->read(false) : null;
			}else
				return $string;
		}else{
			if(!$deep) return null;
			return $this->write() ? $this->read(false) : null;
		}
	}
	//
}