text:
package com.example.diffusion.app.FreeFormBinaryDiffusion;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;

/**
 * Created by Sam on 15/07/2014.
 */
public class AnimationView extends View {

    /* Instance Variables */
    //drawing path
    private Path sketchPath;
    //drawing and canvas paint
    private Paint sketchPaint, linePaint, canvasPaint;
    //initial colour
    private int sketchingColour, lineColour;

    //canvas
    private Canvas sketchCanvas;
    //canvas bitmap
    private Bitmap canvasBitmap;

    //the size of the points on the grid
    private float pointSize, lineSize, snapshotSize;

    private float[] initialValues, plottingValues, xValues;

    private ArrayList<SnapShotValues> snapshotValues;
    private int[] colours;
    private int positionInColors, numberOfSnapShots;
    private boolean snapShotTaken;
    private boolean linesOn;

    /* Default Constructor */
    public AnimationView(Context context, AttributeSet atts){
        super(context, atts);
        setUpView();
    }//end of constructor

    /* Helper method for the constructor */
    public void setUpView(){

        sketchPath = new Path();//check if this is used
        sketchPaint = new Paint();

        pointSize = 5;
        snapshotSize = 3;

        //set the properties for the sketching (investigate the effects of these)
        sketchingColour = Color.BLACK;
        sketchPaint.setColor(sketchingColour);
        sketchPaint.setAntiAlias(true);
        sketchPaint.setStrokeWidth(pointSize);
        sketchPaint.setStyle(Paint.Style.STROKE);
        sketchPaint.setStrokeJoin(Paint.Join.ROUND);
        sketchPaint.setStrokeCap(Paint.Cap.ROUND);

        canvasPaint = new Paint(Paint.DITHER_FLAG); //used for painting the grid

        //set the properties for the grid
        lineColour = -7829368;
        linePaint = new Paint();
        linePaint.setColor(lineColour);
        lineSize = 2f;
        linePaint.setStrokeWidth(lineSize);
        linePaint.setAlpha(100);

        snapshotValues = new ArrayList<SnapShotValues>();
        colours = new int[11];
        colours[0] = Color.parseColor("#FF0000");
        colours[1] = Color.parseColor("#FF6600");
        colours[2] = Color.parseColor("#FF9900");
        colours[3] = Color.parseColor("#FFCC00");
        colours[4] = Color.parseColor("#669900");
        colours[5] = Color.parseColor("#66FF33");
        colours[6] = Color.parseColor("#33CCFF");
        colours[7] = Color.parseColor("#0066FF");
        colours[8] = Color.parseColor("#9933FF");
        colours[9] = Color.parseColor("#CC00CC");
        colours[10] = Color.parseColor("#FF3399");

        positionInColors = 0;
        numberOfSnapShots = 0;
        snapShotTaken = false;

    }//end of helper method

    /* +++++++++ Getters/Setters ++++++++++++++++++ */
    public void setPlottingValues(float[] values) { this.plottingValues = values; }

    public void setXValues(float[] values){
        this.xValues = values;
    }

    public void setInitialValues(float[] values) { this.initialValues = values.clone(); }

    public float[] getInitialValues(){ return this.initialValues; }

    public void setSnapShotTaken(boolean b) { this.snapShotTaken = b; }

    public void setLinesOn(boolean b) {
        this.linesOn = b;
        invalidate();
    }

    public SnapShotValues getLatestSnapShot(){
        return this.snapshotValues.get(snapshotValues.size()-1);
    }

    public Bitmap getCanvasBitmap(){  //it might be that the bitmap is blank - need to
        return canvasBitmap;
    }

    /* ++++++++++++++++++++++++++++++++++++++++++++ */

    /* Override Methods for the View Class */
     /* Code for handling setting up drawing surface */
    @Override
    public void onSizeChanged(int w, int h, int oldw, int oldh){ //find out when this method gets called when a view gets created
        //view given size
        super.onSizeChanged(w, h, oldw, oldh);

        //initialize the canvas bitmap, and apply this bitmap to the canvas that will hold the drawing
        if(w>0 && h>0){
            canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            sketchCanvas = new Canvas(canvasBitmap);
        }

    }//end of onSizeChanged method

    @Override
    public void onDraw(Canvas canvas){
        canvasBitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888); //see what effect this has
        sketchCanvas = new Canvas(canvasBitmap);

        canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
        canvas.drawPath(sketchPath, sketchPaint);

        //for loop plots the grid lines onto the graph area
//        for (int i = 0; i < canvas.getWidth(); i += (canvas.getWidth() / plottingValues.length)) { //change this to delta x at some point in the future
//            canvas.drawLine(i, 0, i, canvas.getHeight(), linePaint); //changed that to see the effect it has
//        }//end of for  loop

      if(!linesOn){
          //test drawing the points
          for(int i=0; i<plottingValues.length; i++){
              canvas.drawPoint(xValues[i], plottingValues[i], sketchPaint);
          }

          if(snapShotTaken){

              for(int i=0; i<snapshotValues.size(); i++){

                  SnapShotValues ssv = snapshotValues.get(i);
                  sketchPaint.setColor(ssv.getColour());
                  sketchPaint.setStrokeWidth(snapshotSize);

                  for(int j=0; j<ssv.size(); j++){
                      canvas.drawPoint(xValues[j], ssv.getSnapshotValues()[j], sketchPaint);
                  }//end of inner for loop

              }//end of for loop

              sketchPaint.setColor(sketchingColour);
              sketchPaint.setStrokeWidth(pointSize);

          }//end of if snapshot taken

          sketchPaint.setColor(sketchingColour);
      }
        else if(linesOn){

          for(int i=1; i<plottingValues.length; i++){
              canvas.drawLine(
                      xValues[i-1], plottingValues[i-1],
                      xValues[i], plottingValues[i], sketchPaint
              );
          }//end of for loop

          if(snapShotTaken){

              for(int i=0; i<snapshotValues.size(); i++){
                  SnapShotValues ssv = snapshotValues.get(i);
                  sketchPaint.setColor(ssv.getColour());
                  sketchPaint.setStrokeWidth(snapshotSize);

                  for(int j=1; j<ssv.size(); j++){
                      canvas.drawLine(
                              xValues[j-1], ssv.getSnapshotValues()[j-1],
                              xValues[j], ssv.getSnapshotValues()[j], sketchPaint
                      );
                  }
              }

              sketchPaint.setColor(sketchingColour);
              sketchPaint.setStrokeWidth(pointSize);
          }//end of if snapshot taken

      }//end of if/else block

    }//end of onDraw method

    /* Test method for updating the screen with new values */
    public void updateView(){

        //reset the sketching canvas
        sketchCanvas.drawColor(Color.WHITE);

        invalidate();

    }//end of updateView method

    /* Called when a snapshot is taken */
    public void createSnapShot(){

        if(!snapShotTaken) {
            snapShotTaken = true;
        }

        int color = colours[positionInColors];
        if(positionInColors==colours.length-1) positionInColors = 0;
        else positionInColors++;

        snapshotValues.add(new SnapShotValues(plottingValues.clone(), color));
        numberOfSnapShots++;
        invalidate();

    }//end of snapShotTaken method

    /* Called when the animation needs to reset */
    public void restartAnimation(float[] values){
        setPlottingValues(values);
        sketchCanvas.drawColor(Color.WHITE);
        snapshotValues.clear();
        snapShotTaken = false;
        positionInColors = 0;
        invalidate();
    }//end of restart animation method

}//end of class


text:
'use strict';

const { OperationAPI } = require('@terascope/job-components');

class ExampleAPI extends OperationAPI {
    name() {
        return 'ExampleAPI';
    }

    async handle(config) {
        return {
            config,
            say() {
                return 'hello';
            }
        };
    }
}

module.exports = ExampleAPI;

redpajama_set_name: RedPajamaGithub


text:
const assert = require('assert');
const {
  describe,
  it,
  before
} = require('mocha');

const { sequelize } = require('../lib/db');
const entrypoints   = require('../lib/entrypoints');

describe('entrypoints.device-create', function() {
  before(function() {
    this.timeout(3000);
    return sequelize.sync();
  });

  it('yield the newly created device entry', done => {
    const context = { credentials: { key: "testmobile" } };
    entrypoints["device-create"]({}, context)
      .then(device => {
        assert(device);
        assert(device.id);
        assert(device.secret);
        done();
      })
      .catch(done);
  });

  it('rejects a non-mobile application key', done => {
    const context = { credentials: { key: "testbrowser" } };
    entrypoints["device-create"]({}, context)
      .then(() => assert.fail("didn't reject invalid key"),
            () => done())
      .catch(done);
  });

  it('saves the parameters given', done => {
    const context = { credentials: { key: "testmobile" } };
    entrypoints["device-create"]({ nickname: "aaa", avatar: "bbb" }, context)
      .then(device => {
        assert(device);
        assert.equal(device.nickname, "aaa");
        assert.equal(device.avatar, "bbb");
        done();
      })
      .catch(done);
  });
});

describe('entrypoints.device-update-single', function() {
  const context = {
    credentials: {
      key: "testmobile",
      secret: "fake"
    }
  };
  let device;
  before(function() {
    this.timeout(3000);
    return sequelize.sync()
      .then(() => entrypoints["device-create"]({ nickname: "aaa" }, context))
      .then(dev => {
        device = dev;
        context.credentials.deviceId = dev.id;
      });
  });

  it('should fail if the secret given is invalid', done => {
    entrypoints["device-update-single"]({ id: device.id }, context)
      .then(() => assert.fail("didn't reject fake secret"),
            err => {
              if (err.status === 401) return done();
              assert.fail("did't reject fake secret");
            })
      .catch(done);
  });

  it('should update the fields correctly', done => {
    entrypoints["device-update-single"](
      { id: device.id, nickname: "ccc", avatar: "ddd" },
      { credentials: Object.assign(
        {}, context.credentials, { secret: device.secret }) })
      .then(d => {
        assert(d);
        assert.equal(d.nickname, "ccc");
        assert.equal(d.avatar, "ddd");
        assert(!d.secret);
        done();
      })
      .catch(done);
  });

  it('should reject an attempt to update another device', done => {
    entrypoints["device-create"]({ nickname: "aaa" }, context)
      .then(another => entrypoints["device-update-single"](
        { id: another.id, nickname: "ccc", avatar: "ddd" },
        { credentials: Object.assign(
          {}, context.credentials, { secret: device.secret }) })
            .then(() => assert.fail("updated another device"),
                  () => done()))
      .catch(done);
  });
});

describe('entrypoints.device-fetch-single', function() {
  const context = { credentials: { key: "testmobile" } };
  let device;

  before(function() {
    this.timeout(3000);
    return sequelize.sync()
      .then(() => entrypoints["device-create"]({ nickname: "aaa" }, context))
      .then(dev => {
        device = dev;
      });
  });

  it('should fetch a persistent device', done => {
    entrypoints["device-fetch-single"](
      { id: device.id },
      { credentials: { key: "testbrowser" } })
      .then(dev => {
        assert(dev);
        assert.equal(device.id, dev.id);
        assert.equal(device.nickname, dev.nickname);
        assert(!dev.secret);
        done();
      })
      .catch(done)
  });

  it('should fail to fetch a non-existent device', done => {
    entrypoints["device-fetch-single"](
      { id: "e806811a-f83c-4ce2-bd59-ace57ff3a4ae" },
      { credentials: { key: "testbrowser" } })
      .then(() => assert.fail("didn't fail to find non-existent device"),
            err => {
              if (err.status === 404) return done();
              assert.fail("did't fail to find fake device");
            })
      .catch(done);
  });
});


text:
* Stefan Penner
  * ember-cli, [work on RSVP][1.0-rc4]
* Tom Dale
* Yehuda Katz
  * https://github.com/wycats
* Chad Hietala
  * https://github.com/chadhietala
  * LinkedIn
* Jay Phelps
  * https://github.com/jayphelps
  * Netflix, ember-cli
* Sam Selikoff
  * https://github.com/samselikoff
  * TED, [future-proof.md](https://gist.github.com/samselikoff/1d7300ce59d216fdaf97)
* Edward Faulkner
  * https://github.com/ef4
  * https://twitter.com/eaf4
  * `ember-browserify`
* Robert Jackson
  * https://github.com/rwjblue
  * DockYard
  * https://dockyard.com/blog/authors/robert-jackson
* Stanley Stuart
  * https://github.com/fivetanley
  * https://twitter.com/fivetanley

[1.0-rc4]: http://emberjs.com/blog/2013/05/28/ember-1-0-rc4.html


text:
package controllers

import play.api.libs.json._
import play.api.mvc.{Action, Controller}
import utils.Utils
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import scala.concurrent.Future

import play.api.libs.functional.syntax._

object Application extends Controller {
  def index = Action {
    Ok(views.html.index("Scala Hack"))
  }

  case class ScalaHacker(source: String, lang: Int, testcases: List[String])
  implicit val reads: Reads[ScalaHacker] = (
    (JsPath \ "source").read[String] and
      (JsPath \ "lang").read[Int] and
      (JsPath \ "testcases").read[List[String]]
    )(ScalaHacker.apply _)

  def hackerrank() = Action.async(parse.json) { implicit request =>
    request.body.validate[ScalaHacker] match {
      case success: JsSuccess[ScalaHacker] => {
        val value = success.get
        Utils.submit(value.source, value.lang, value.testcases)
          .map(wsResponse => Ok(Json.obj("success" -> wsResponse.body)))
      }
      case error: JsError => {
        Future(Ok(Json.obj("failure" -> "Bad Json Format")))
      }
    }
  }
  def test = Action.async {
    val wsResponse = Utils.submit(
      """
        |object Solution {
        | def main(args: Array[String]): Unit = {
        |  print("hello")
        | }
        |}
      """.stripMargin, 15, List("hello"))
    wsResponse.map(wsResponse => {
      Ok(wsResponse.body.toString + " with status: " + wsResponse.status)
    })
  }
}


text:
/**
 * Entitas-ECS definitions for example
 */
declare module entitas.utils {
    /**
     * @class UUID
     */
    class UUID {
        /**
         * Fast UUID generator, RFC4122 version 4 compliant
         * format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
         *
         * @author Jeff Ward (jcward.com).
         * @license MIT license
         * @link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
         **/
        static randomUUID(): string;
    }
}
declare module entitas.utils {
    interface ImmutableBag<E> {
        get(index: number): E;
        size(): number;
        isEmpty(): boolean;
        contains(e: E): boolean;
    }
}
declare module entitas.utils {
    /**
     * Collection type a bit like ArrayList but does not preserve the order of its
     * entities, speedwise it is very good, especially suited for games.
     */
    class Bag<E> extends Array implements ImmutableBag<E> {
        size_: number;
        /**
         * Constructs an empty Bag with the specified initial capacity.
         * Constructs an empty Bag with an initial capacity of 64.
         *
         * @constructor
         * @param capacity the initial capacity of Bag
         */
        constructor(capacity?: number);
        /**
         * Removes the element at the specified position in this Bag. does this by
         * overwriting it was last element then removing last element
         *
         * @param index
         *            the index of element to be removed
         * @return {Object} element that was removed from the Bag
         */
        removeAt(index: number): E;
        /**
         * Removes the first occurrence of the specified element from this Bag, if
         * it is present. If the Bag does not contain the element, it is unchanged.
         * does this by overwriting it was last element then removing last element
         *
         * @param e
         *            element to be removed from this list, if present
         * @return {boolean} true if this list contained the specified element
         */
        remove(e: E): boolean;
        /**
         * Remove and return the last object in the bag.
         *
         * @return {Object} the last object in the bag, null if empty.
         */
        removeLast(): E;
        /**
         * Check if bag contains this element.
         *
         * @param e
         * @return {boolean}
         */
        contains(e: E): boolean;
        /**
         * Removes from this Bag all of its elements that are contained in the
         * specified Bag.
         *
         * @param bag
         *            Bag containing elements to be removed from this Bag
         * @return {boolean} true if this Bag changed as a result of the call
         */
        removeAll(bag: ImmutableBag<E>): boolean;
        /**
         * Returns the element at the specified position in Bag.
         *
         * @param index
         *            index of the element to return
         * @return {Object} the element at the specified position in bag
         */
        get(index: number): E;
        /**
         * Returns the element at the specified position in Bag. This method
         * ensures that the bag grows if the requested index is outside the bounds
         * of the current backing array.
         *
         * @param index
         *      index of the element to return
         *
         * @return {Object} the element at the specified position in bag
         *
         */
        safeGet(index: number): E;
        /**
         * Returns the number of elements in this bag.
         *
         * @return {number} the number of elements in this bag
         */
        size(): number;
        /**
         * Returns the number of elements the bag can hold without growing.
         *
         * @return {number} the number of elements the bag can hold without growing.
         */
        getCapacity(): number;
        /**
         * Checks if the internal storage supports this index.
         *
         * @param index
         * @return {boolean}
         */
        isIndexWithinBounds(index: number): boolean;
        /**
         * Returns true if this list contains no elements.
         *
         * @return {boolean} true if this list contains no elements
         */
        isEmpty(): boolean;
        /**
         * Adds the specified element to the end of this bag. if needed also
         * increases the capacity of the bag.
         *
         * @param e
         *            element to be added to this list
         */
        add(e: E): void;
        /**
         * Set element at specified index in the bag.
         *
         * @param index position of element
         * @param e the element
         */
        set(index: number, e: E): void;
        grow(newCapacity?: number): void;
        ensureCapacity(index: number): void;
        /**
         * Removes all of the elements from this bag. The bag will be empty after
         * this call returns.
         */
        clear(): void;
        /**
         * Add all items into this bag.
         * @param items
         */
        addAll(items: ImmutableBag<E>): void;
    }
}
declare module entitas.utils {
    import Bag = entitas.utils.Bag;
    interface ISignal<T> {
        dispatch(...args: any[]): void;
        add(listener: T): void;
        clear(): void;
        remove(listener: T): void;
    }
    class Signal<T> implements ISignal<T> {
        _listeners: Bag<T>;
        private _context;
        private _alloc;
        active: boolean;
        /**
         *
         * @constructor
         * @param context
         * @param alloc
         */
        constructor(context: any, alloc?: number);
        /**
         * Dispatch event
         *
         * @param $0
         * @param $1
         * @param $2
         * @param $3
         * @param $4
         */
        dispatch($0?: any, $1?: any, $2?: any, $3?: any, $4?: any): void;
        /**
         * Add event listener
         * @param listener
         */
        add(listener: T): void;
        /**
         * Remove event listener
         * @param listener
         */
        remove(listener: T): void;
        /**
         * Clear and reset to original alloc
         */
        clear(): void;
    }
}
declare module entitas.utils {
    class Stopwatch {
        isRunning: boolean;
        startTimeStamp: number;
        elapsed: number;
        static isHighRes: boolean;
        private _elapsed;
        private _startTimeStamp;
        private _isRunning;
        constructor();
        start(): void;
        stop(): void;
        reset(): void;
        static getTimeStamp(): number;
    }
}
declare module entitas {
    interface IComponent {
    }

    class BoundsComponent implements IComponent {
      public radius:number;
    }
    class BulletComponent implements IComponent {
    }
    class ColorAnimationComponent implements IComponent {
      public redMin:number;
      public redMax:number;
      public redSpeed:number;
      public greenMin:number;
      public greenMax:number;
      public greenSpeed:number;
      public blueMin:number;
      public blueMax:number;
      public blueSpeed:number;
      public alphaMin:number;
      public alphaMax:number;
      public alphaSpeed:number;
      public redAnimate:boolean;
      public greenAnimate:boolean;
      public blueAnimate:boolean;
      public alphaAnimate:boolean;
      public repeat:boolean;
    }
    class EnemyComponent implements IComponent {
    }
    class ExpiresComponent implements IComponent {
      public delay:number;
    }
    class FiringComponent implements IComponent {
    }
    class HealthComponent implements IComponent {
      public health:number;
      public maximumHealth:number;
    }
    class ParallaxStarComponent implements IComponent {
    }
    class PlayerComponent implements IComponent {
    }
    class PositionComponent implements IComponent {
      public x:number;
      public y:number;
    }
    class ScaleAnimationComponent implements IComponent {
      public min:number;
      public max:number;
      public speed:number;
      public repeat:boolean;
      public active:boolean;
    }
    class SoundEffectComponent implements IComponent {
      public effect:number;
    }
    class SpriteComponent implements IComponent {
      public layer:number;
      public object:Object;
    }
    class VelocityComponent implements IComponent {
      public x:number;
      public y:number;
    }
    class ScoreComponent implements IComponent {
      public value:number;
    }
    class DestroyComponent implements IComponent {
    }
    class MouseComponent implements IComponent {
      public x:number;
      public y:number;
    }
    class ScaleComponent implements IComponent {
      public x:number;
      public y:number;
    }
    class ResourceComponent implements IComponent {
      public name:string;
    }
    class LayerComponent implements IComponent {
      public ordinal:number;
    }

}
declare module entitas {
    interface IMatcher {
        id: number;
        indices: number[];
        matches(entity: Entity): any;
    }
    interface ICompoundMatcher extends IMatcher {
        allOfIndices: number[];
        anyOfIndices: number[];
        noneOfIndices: number[];
    }
    interface INoneOfMatcher extends ICompoundMatcher {
    }
    interface IAnyOfMatcher extends ICompoundMatcher {
        noneOf(...args: any[]): INoneOfMatcher;
    }
    interface IAllOfMatcher extends ICompoundMatcher {
        anyOf(...args: any[]): IAnyOfMatcher;
        noneOf(...args: any[]): INoneOfMatcher;
    }
}
declare module entitas {
    import Pool = entitas.Pool;
    interface ISystem {
    }
    interface ISetPool {
        setPool(pool: Pool): any;
    }
}
declare module entitas {
    interface IExecuteSystem extends ISystem {
        execute(): any;
    }
}
declare module entitas {
    interface IInitializeSystem extends ISystem {
        initialize(): any;
    }
}
declare module entitas {
    interface IReactiveExecuteSystem extends ISystem {
        execute(entities: Array<Entity>): any;
    }
    interface IMultiReactiveSystem extends IReactiveExecuteSystem {
        triggers: Array<TriggerOnEvent>;
    }
    interface IReactiveSystem extends IReactiveExecuteSystem {
        trigger: TriggerOnEvent;
    }
    interface IEnsureComponents {
        ensureComponents: IMatcher;
    }
    interface IExcludeComponents {
        excludeComponents: IMatcher;
    }
    interface IClearReactiveSystem {
        clearAfterExecute: boolean;
    }
}
declare module entitas {
    class Exception {
        /** @type {string} */
        message: string;
        /**
         * Base exception class
         * @constructot
         * @param message
         */
        constructor(message: any);
        /** @return {string} */
        toString(): string;
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class EntityAlreadyHasComponentException extends Exception {
        /**
         * Entity Already Has Component Exception
         * @constructor
         * @param message
         * @param index
         */
        constructor(message: string, index: number);
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class EntityDoesNotHaveComponentException extends Exception {
        /**
         * Entity Does Not Have Component Exception
         * @constructor
         * @param message
         * @param index
         */
        constructor(message: string, index: number);
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class EntityIsNotEnabledException extends Exception {
        /**
         * Entity Is Not Enabled Exception
         * @constructor
         * @param message
         */
        constructor(message: string);
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class EntityIsAlreadyReleasedException extends Exception {
        /**
         * Entity Is Already Released Exception
         * @constructor
         */
        constructor();
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class SingleEntityException extends Exception {
        /**
         * Single Entity Exception
         * @constructor
         * @param matcher
         */
        constructor(matcher: IMatcher);
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class GroupObserverException extends Exception {
        /**
         * Group Observer Exception
         * @constructor
         * @param message
         */
        constructor(message: string);
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class PoolDoesNotContainEntityException extends Exception {
        /**
         * Pool Does Not Contain Entity Exception
         * @constructor
         * @param entity
         * @param message
         */
        constructor(entity: Entity, message: string);
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class EntityIsNotDestroyedException extends Exception {
        /**
         * Entity Is Not Destroyed Exception
         * @constructor
         * @param message
         */
        constructor(message: string);
    }
}
declare module entitas.exceptions {
    import Exception = entitas.Exception;
    class MatcherException extends Exception {
        /**
         * Matcher Exception
         * @constructor
         * @param matcher
         */
        constructor(matcher: IMatcher);
    }
}
declare module entitas {
    import Entity = entitas.Entity;
    import IAllOfMatcher = entitas.IAllOfMatcher;
    import IAnyOfMatcher = entitas.IAnyOfMatcher;
    import INoneOfMatcher = entitas.INoneOfMatcher;
    import TriggerOnEvent = entitas.TriggerOnEvent;
    module Matcher {
    }
    class Matcher implements IAllOfMatcher, IAnyOfMatcher, INoneOfMatcher {
/** Matcher Extensions for example */
        static _matcherBounds;
        static Bounds: Matcher;
        static _matcherBullet;
        static Bullet: Matcher;
        static _matcherColorAnimation;
        static ColorAnimation: Matcher;
        static _matcherEnemy;
        static Enemy: Matcher;
        static _matcherExpires;
        static Expires: Matcher;
        static _matcherFiring;
        static Firing: Matcher;
        static _matcherHealth;
        static Health: Matcher;
        static _matcherParallaxStar;
        static ParallaxStar: Matcher;
        static _matcherPlayer;
        static Player: Matcher;
        static _matcherPosition;
        static Position: Matcher;
        static _matcherScaleAnimation;
        static ScaleAnimation: Matcher;
        static _matcherSoundEffect;
        static SoundEffect: Matcher;
        static _matcherSprite;
        static Sprite: Matcher;
        static _matcherVelocity;
        static Velocity: Matcher;
        static _matcherScore;
        static Score: Matcher;
        static _matcherDestroy;
        static Destroy: Matcher;
        static _matcherMouse;
        static Mouse: Matcher;
        static _matcherScale;
        static Scale: Matcher;
        static _matcherResource;
        static Resource: Matcher;
        static _matcherLayer;
        static Layer: Matcher;
        /**
         * Get the matcher id
         * @type {number}
         * @name entitas.Matcher#id */
        id: number;
        /**
         * A unique sequential index number assigned to each ,atch
         * @type {number} */
        static uniqueId: number;
        /**
         * A list of the component ordinals that this matches
         * @type {Array<number>}
         * @name entitas.Matcher#indices */
        indices: number[];
        /**
         * A unique sequential index number assigned to each entity at creation
         * @type {number}
         * @name entitas.Matcher#allOfIndices */
        allOfIndices: number[];
        /**
         * A unique sequential index number assigned to each entity at creation
         * @type {number}
         * @name entitas.Matcher#anyOfIndices */
        anyOfIndices: number[];
        /**
         * A unique sequential index number assigned to each entity at creation
         * @type {number}
         * @name entitas.Matcher#noneOfIndices */
        noneOfIndices: number[];
        private _indices;
        _allOfIndices: number[];
        _anyOfIndices: number[];
        _noneOfIndices: number[];
        private _toStringCache;
        private _id;
        /** Extension Points */
        onEntityAdded(): TriggerOnEvent;
        onEntityRemoved(): TriggerOnEvent;
        onEntityAddedOrRemoved(): TriggerOnEvent;
        /**
         * @constructor
         *
         */
        constructor();
        anyOf(...args: Array<IMatcher>): IAnyOfMatcher;
        anyOf(...args: number[]): IAnyOfMatcher;
        noneOf(...args: number[]): INoneOfMatcher;
        noneOf(...args: Array<IMatcher>): INoneOfMatcher;
        /**
         * Check if the entity matches this matcher
         * @param {entitas.Entity} entity
         * @returns {boolean}
         */
        matches(entity: Entity): boolean;
        /**
         * Merge list of component indices
         * @returns {Array<number>}
         */
        mergeIndices(): number[];
        /**
         * toString representation of this matcher
         * @returns {string}
         */
        toString(): string;
        /**
         * Check if the matchers are equal
         * @param {Object} obj
         * @returns {boolean}
         */
        equals(obj: any): boolean;
        /**
         * Check if the lists of component indices are equal
         * @param {Array<number>} list1
         * @param {Array<number>} list2
         * @returns {boolean}
         */
        static equalIndices(i1: number[], i2: number[]): boolean;
        /**
         * Get the set if distinct (non-duplicate) indices from a list
         * @param {Array<number>} indices
         * @returns {Array<number>}
         */
        static distinctIndices(indices: number[]): number[];
        /**
         * Merge all the indices of a set of Matchers
         * @param {Array<IMatcher>} matchers
         * @returns {Array<number>}
         */
        static mergeIndices(matchers: Array<IMatcher>): number[];
        static allOf(...args: number[]): IAllOfMatcher;
        static allOf(...args: Array<IMatcher>): IAllOfMatcher;
        static anyOf(...args: number[]): IAnyOfMatcher;
        static anyOf(...args: Array<IMatcher>): IAnyOfMatcher;
        private static appendIndices(sb, prefix, indexArray);
    }
}
declare module entitas {
    import GroupEventType = entitas.GroupEventType;
    class TriggerOnEvent {
        trigger: IMatcher;
        eventType: GroupEventType;
        /**
         * @constructor
         *
         * @param trigger
         * @param eventType
         */
        constructor(trigger: IMatcher, eventType: GroupEventType);
    }
}
/**
 * entitas ecs
 * @const
 */
declare module entitas {
    import ISignal = entitas.utils.ISignal;
    import IComponent = entitas.IComponent;
    import EntityChanged = Entity.EntityChanged;
    import EntityReleased = Entity.EntityReleased;
    import IEntityChanged = Entity.IEntityChanged;
    import IEntityReleased = Entity.IEntityReleased;
    import ComponentReplaced = Entity.ComponentReplaced;
    module Entity {
        /**
         * Event EntityReleased
         *
         * All references to the entity have been released
         */
        interface EntityReleased {
            (e: Entity): void;
        }
        interface IEntityReleased<T> extends ISignal<T> {
            dispatch(e: Entity): void;
        }
        /**
         * Event EntityChanged
         *
         * The entity has been changed
         **/
        interface EntityChanged {
            (e: Entity, index: number, component: IComponent): void;
        }
        interface IEntityChanged<T> extends ISignal<T> {
            dispatch(e: Entity, index: number, component: IComponent): void;
        }
        /**
         * Event ComponentReplaced
         *
         * A component was replaced
         */
        interface ComponentReplaced {
            (e: Entity, index: number, component: IComponent, replacement: IComponent): void;
        }
        interface IComponentReplaced<T> extends ISignal<T> {
            dispatch(e: Entity, index: number, component: IComponent, replacement: IComponent): void;
        }
    }
    class Entity {
/** Entity Extensions for example */
        static _boundsComponentPool;
        static clearBoundsComponentPool();
        bounds: BoundsComponent;
        hasBounds: boolean;
        addBounds(radius:number);
        replaceBounds(radius:number);
        removeBounds();
        static bulletComponent: BulletComponent;
        isBullet: boolean;
        setBullet(value: boolean);
        static _colorAnimationComponentPool;
        static clearColorAnimationComponentPool();
        colorAnimation: ColorAnimationComponent;
        hasColorAnimation: boolean;
        addColorAnimation(redMin:number, redMax:number, redSpeed:number, greenMin:number, greenMax:number, greenSpeed:number, blueMin:number, blueMax:number, blueSpeed:number, alphaMin:number, alphaMax:number, alphaSpeed:number, redAnimate:boolean, greenAnimate:boolean, blueAnimate:boolean, alphaAnimate:boolean, repeat:boolean);
        replaceColorAnimation(redMin:number, redMax:number, redSpeed:number, greenMin:number, greenMax:number, greenSpeed:number, blueMin:number, blueMax:number, blueSpeed:number, alphaMin:number, alphaMax:number, alphaSpeed:number, redAnimate:boolean, greenAnimate:boolean, blueAnimate:boolean, alphaAnimate:boolean, repeat:boolean);
        removeColorAnimation();
        static enemyComponent: EnemyComponent;
        isEnemy: boolean;
        setEnemy(value: boolean);
        static _expiresComponentPool;
        static clearExpiresComponentPool();
        expires: ExpiresComponent;
        hasExpires: boolean;
        addExpires(delay:number);
        replaceExpires(delay:number);
        removeExpires();
        static firingComponent: FiringComponent;
        isFiring: boolean;
        setFiring(value: boolean);
        static _healthComponentPool;
        static clearHealthComponentPool();
        health: HealthComponent;
        hasHealth: boolean;
        addHealth(health:number, maximumHealth:number);
        replaceHealth(health:number, maximumHealth:number);
        removeHealth();
        static parallaxStarComponent: ParallaxStarComponent;
        isParallaxStar: boolean;
        setParallaxStar(value: boolean);
        static playerComponent: PlayerComponent;
        isPlayer: boolean;
        setPlayer(value: boolean);
        static _positionComponentPool;
        static clearPositionComponentPool();
        position: PositionComponent;
        hasPosition: boolean;
        addPosition(x:number, y:number);
        replacePosition(x:number, y:number);
        removePosition();
        static _scaleAnimationComponentPool;
        static clearScaleAnimationComponentPool();
        scaleAnimation: ScaleAnimationComponent;
        hasScaleAnimation: boolean;
        addScaleAnimation(min:number, max:number, speed:number, repeat:boolean, active:boolean);
        replaceScaleAnimation(min:number, max:number, speed:number, repeat:boolean, active:boolean);
        removeScaleAnimation();
        static _soundEffectComponentPool;
        static clearSoundEffectComponentPool();
        soundEffect: SoundEffectComponent;
        hasSoundEffect: boolean;
        addSoundEffect(effect:number);
        replaceSoundEffect(effect:number);
        removeSoundEffect();
        static _spriteComponentPool;
        static clearSpriteComponentPool();
        sprite: SpriteComponent;
        hasSprite: boolean;
        addSprite(layer:number, object:Object);
        replaceSprite(layer:number, object:Object);
        removeSprite();
        static _velocityComponentPool;
        static clearVelocityComponentPool();
        velocity: VelocityComponent;
        hasVelocity: boolean;
        addVelocity(x:number, y:number);
        replaceVelocity(x:number, y:number);
        removeVelocity();
        static _scoreComponentPool;
        static clearScoreComponentPool();
        score: ScoreComponent;
        hasScore: boolean;
        addScore(value:number);
        replaceScore(value:number);
        removeScore();
        static destroyComponent: DestroyComponent;
        isDestroy: boolean;
        setDestroy(value: boolean);
        static _mouseComponentPool;
        static clearMouseComponentPool();
        mouse: MouseComponent;
        hasMouse: boolean;
        addMouse(x:number, y:number);
        replaceMouse(x:number, y:number);
        removeMouse();
        static _scaleComponentPool;
        static clearScaleComponentPool();
        scale: ScaleComponent;
        hasScale: boolean;
        addScale(x:number, y:number);
        replaceScale(x:number, y:number);
        removeScale();
        static _resourceComponentPool;
        static clearResourceComponentPool();
        resource: ResourceComponent;
        hasResource: boolean;
        addResource(name:string);
        replaceResource(name:string);
        removeResource();
        static _layerComponentPool;
        static clearLayerComponentPool();
        layer: LayerComponent;
        hasLayer: boolean;
        addLayer(ordinal:number);
        replaceLayer(ordinal:number);
        removeLayer();
        /**
         * @static
         * @type {number} */
        static instanceIndex: number;
        /**
         * @static
         * @type {Array<Array<IComponent>>} */
        static alloc: Array<Array<IComponent>>;
        /**
         * @static
         * @type {number} */
        static size: number;
        /**
         * A unique sequential index number assigned to each entity at creation
         * @type {number}
         * @name entitas.Entity#creationIndex */
        creationIndex: number;
        /**
         * Subscribe to Entity Released Event
         * @type {entitas.ISignal} */
        onEntityReleased: IEntityReleased<EntityReleased>;
        /**
         * Subscribe to Component Added Event
         * @type {entitas.ISignal} */
        onComponentAdded: IEntityChanged<EntityChanged>;
        /**
         * Subscribe to Component Removed Event
         * @type {entitas.ISignal} */
        onComponentRemoved: IEntityChanged<EntityChanged>;
        /**
         * Subscribe to Component Replaced Event
         * @type {entitas.ISignal} */
        onComponentReplaced: Entity.IComponentReplaced<ComponentReplaced>;
        /**
         * Entity name
         * @type {string} */
        name: string;
        /**
         *  Entity Id
         * @type {string} */
        id: string;
        /**
         *  Instance index
         * @type {number} */
        instanceIndex: number;
        _creationIndex: number;
        _isEnabled: boolean;
        _components: Array<IComponent>;
        _componentsCache: any;
        _componentIndicesCache: number[];
        _toStringCache: string;
        _refCount: number;
        private _pool;
        private _componentsEnum;
        /**
         * The basic game object. Everything is an entity with components that
         * are added / removed as needed.
         *
         * @param {Object} componentsEnum
         * @param {number} totalComponents
         * @constructor
         */
        constructor(componentsEnum: any, totalComponents?: number);
        static initialize(totalComponents: number, options: any): void;
        /**
         * allocate entity pool
         *
         * @param count number of components
         * @param size max number of entities
         */
        static dim(count: number, size: number): void;
        /**
         * Initialize
         * Extension point to allocate enetity pool.
         *
         * @param {number} totalComponents
         * @returns {Array<entitas.IComponent>}
         */
        initialize(totalComponents: number): Array<IComponent>;
        /**
         * AddComponent
         *
         * @param {number} index
         * @param {entitas.IComponent} component
         * @returns {entitas.Entity}
         */
        addComponent(index: number, component: IComponent): Entity;
        /**
         * RemoveComponent
         *
         * @param {number} index
         * @returns {entitas.Entity}
         */
        removeComponent(index: number): Entity;
        /**
         * ReplaceComponent
         *
         * @param {number} index
         * @param {entitas.IComponent} component
         * @returns {entitas.Entity}
         */
        replaceComponent(index: number, component: IComponent): Entity;
        protected _replaceComponent(index: number, replacement: IComponent): void;
        /**
         * GetComponent
         *
         * @param {number} index
         * @param {entitas.IComponent} component
         */
        getComponent(index: number): IComponent;
        /**
         * GetComponents
         *
         * @returns {Array<entitas.IComponent>}
         */
        getComponents(): IComponent[];
        /**
         * GetComponentIndices
         *
         * @returns {Array<number>}
         */
        getComponentIndices(): number[];
        /**
         * HasComponent
         *
         * @param {number} index
         * @returns {boolean}
         */
        hasComponent(index: number): boolean;
        /**
         * HasComponents
         *
         * @param {Array<number>} indices
         * @returns {boolean}
         */
        hasComponents(indices: number[]): boolean;
        /**
         * HasAnyComponent
         *
         * @param {Array<number>} indices
         * @returns {boolean}
         */
        hasAnyComponent(indices: number[]): boolean;
        /**
         * RemoveAllComponents
         *
         */
        removeAllComponents(): void;
        /**
         * Destroy
         *
         */
        destroy(): void;
        /**
         * ToString
         *
         * @returns {string}
         */
        toString(): string;
        /**
         * AddRef
         *
         * @returns {entitas.Entity}
         */
        addRef(): Entity;
        /**
         * Release
         *
         */
        release(): void;
    }
}
declare module entitas {
    import Entity = entitas.Entity;
    import ISignal = entitas.utils.ISignal;
    import IMatcher = entitas.IMatcher;
    import IComponent = entitas.IComponent;
    import GroupChanged = Group.GroupChanged;
    import GroupUpdated = Group.GroupUpdated;
    import GroupEventType = entitas.GroupEventType;
    /**
     * event delegate boilerplate:
     */
    module Group {
        interface GroupChanged {
            (group: Group, entity: Entity, index: number, component: IComponent): void;
        }
        interface IGroupChanged<T> extends ISignal<T> {
            dispatch(group: Group, entity: Entity, index: number, component: IComponent): void;
        }
        interface GroupUpdated {
            (group: Group, entity: Entity, index: number, component: IComponent, newComponent: IComponent): void;
        }
        interface IGroupUpdated<T> extends ISignal<T> {
            dispatch(group: Group, entity: Entity, index: number, component: IComponent, newComponent: IComponent): void;
        }
    }
    class Group {
        /**
         * Subscribe to Entity Addded events
         * @type {entitas.utils.ISignal} */
        onEntityAdded: Group.IGroupChanged<GroupChanged>;
        /**
         * Subscribe to Entity Removed events
         * @type {entitas.utils.ISignal} */
        onEntityRemoved: Group.IGroupChanged<GroupChanged>;
        /**
         * Subscribe to Entity Updated events
         * @type {entitas.utils.ISignal} */
        onEntityUpdated: Group.IGroupUpdated<GroupUpdated>;
        /**
         * Count the number of entities in this group
         * @type {number}
         * @name entitas.Group#count */
        count: number;
        /**
         * Get the Matcher for this group
         * @type {entitas.IMatcher}
         * @name entitas.Group#matcher */
        matcher: IMatcher;
        private _entities;
        private _matcher;
        _entitiesCache: Array<Entity>;
        _singleEntityCache: Entity;
        _toStringCache: string;
        /**
         * @constructor
         * @param matcher
         */
        constructor(matcher: IMatcher);
        /**
         * Create an Observer for the event type on this group
         * @param eventType
         */
        createObserver(eventType: GroupEventType): GroupObserver;
        /**
         * Handle adding and removing component from the entity without raising events
         * @param entity
         */
        handleEntitySilently(entity: Entity): void;
        /**
         * Handle adding and removing component from the entity and raisieevents
         * @param entity
         * @param index
         * @param component
         */
        handleEntity(entity: Entity, index: number, component: IComponent): void;
        /**
         * Update entity and raise events
         * @param entity
         * @param index
         * @param previousComponent
         * @param newComponent
         */
        updateEntity(entity: Entity, index: number, previousComponent: IComponent, newComponent: IComponent): void;
        /**
         * Add entity without raising events
         * @param entity
         */
        addEntitySilently(entity: Entity): void;
        /**
         * Add entity and raise events
         * @param entity
         * @param index
         * @param component
         */
        addEntity(entity: Entity, index: number, component: IComponent): void;
        /**
         * Remove entity without raising events
         * @param entity
         */
        removeEntitySilently(entity: Entity): void;
        /**
         * Remove entity and raise events
         * @param entity
         * @param index
         * @param component
         */
        removeEntity(entity: Entity, index: number, component: IComponent): void;
        /**
         * Check if group has this entity
         *
         * @param entity
         * @returns boolean
         */
        containsEntity(entity: Entity): boolean;
        /**
         * Get a list of the entities in this group
         *
         * @returns Array<entitas.Entity>
         */
        getEntities(): Entity[];
        /**
         * Gets an entity singleton.
         * If a group has more than 1 entity, this is an error condition.
         *
         * @returns entitas.Entity
         */
        getSingleEntity(): Entity;
        /**
         * Create a string representation for this group:
         *
         *  ex: 'Group(Position)'
         *
         * @returns string
         */
        toString(): string;
    }
}
declare module entitas {
    import Group = entitas.Group;
    import Entity = entitas.Entity;
    import IComponent = entitas.IComponent;
    /**
     * Event Types
     * @readonly
     * @enum {number}
     */
    enum GroupEventType {
        OnEntityAdded = 0,
        OnEntityRemoved = 1,
        OnEntityAddedOrRemoved = 2,
    }
    class GroupObserver {
        /**
         * Entities being observed
         * @type {Object<string,entitas.Entity>}
         * @name entitas.GroupObserver#collectedEntities */
        collectedEntities: {};
        private _collectedEntities;
        protected _groups: Array<Group>;
        protected _eventTypes: Array<GroupEventType>;
        protected _addEntityCache: Group.GroupChanged;
        /**
         * @constructor
         * @param {Array<entitas.Group>} groups
         * @param {number} eventTypes
         */
        constructor(groups: any, eventTypes: any);
        /**
         * Activate events
         */
        activate(): void;
        /**
         * Deavtivate events
         */
        deactivate(): void;
        /**
         * Clear the list of entities
         */
        clearCollectedEntities(): void;
        /**
         * Adds an entity to this observer group
         * @param group
         * @param {entitas.Entity}entity
         * @param index
         * @param {entitas.IComponent}component
         */
        addEntity: (group: Group, entity: Entity, index: number, component: IComponent) => void;
    }
}
declare module entitas {
    import Bag = entitas.utils.Bag;
    import Group = entitas.Group;
    import Entity = entitas.Entity;
    import ISignal = entitas.utils.ISignal;
    import IMatcher = entitas.IMatcher;
    import PoolChanged = Pool.PoolChanged;
    import IComponent = entitas.IComponent;
    import GroupChanged = Pool.GroupChanged;
    /**
     * event delegate boilerplate:
     */
    module Pool {
        /**
         * Event PoolChanged
         *
         * Pool has changed
         */
        interface PoolChanged {
            (pool: Pool, entity: Entity): void;
        }
        interface IPoolChanged<T> extends ISignal<T> {
            dispatch(pool: Pool, entity: Entity): void;
        }
        /**
         * Event GroupChanged
         *
         * Group has changed
         */
        interface GroupChanged {
            (pool: Pool, group: Group): void;
        }
        interface IGroupChanged<T> extends ISignal<T> {
            dispatch(pool: Pool, group: Group): void;
        }
    }
    /**
     * A cached pool of entities and components.
     * The games world.
     */
    class Pool {
/*** Extensions for example.Pool */
        createPlayer():void;
        createBullet(x:number, y:number):void;
        createParticle(x:number, y:number):void;
        createSmallExplosion(x:number, y:number):void;
        createBigExplosion(x:number, y:number):void;
        createEnemy1():void;
        createEnemy2():void;
        createEnemy3():void;
/** Pool Extensions for example */
        scoreEntity: Entity;
        score: ScoreComponent;
        hasScore: boolean;
        setScore(value:number): Entity;
        replaceScore(value:number): Entity;
        removeScore(): void;
        mouseEntity: Entity;
        mouse: MouseComponent;
        hasMouse: boolean;
        setMouse(x:number, y:number): Entity;
        replaceMouse(x:number, y:number): Entity;
        removeMouse(): void;
        firingEntity: Entity;
        isFiring: boolean;
        /**
         * The total number of components in this pool
         * @type {number}
         * @name entitas.Pool#totalComponents */
        totalComponents: number;
        /**
         * Count of active entities
         * @type {number}
         * @name entitas.Pool#count */
        count: number;
        /**
         * Count of entities waiting to be recycled
         * @type {number}
         * @name entitas.Pool#reusableEntitiesCount */
        reusableEntitiesCount: number;
        /**
         * Count of entities that sill have references
         * @type {number}
         * @name entitas.Pool#retainedEntitiesCount */
        retainedEntitiesCount: number;
        /**
         * Subscribe to Entity Created Event
         * @type {entitas.utils.ISignal} */
        onEntityCreated: Pool.IPoolChanged<PoolChanged>;
        /**
         * Subscribe to Entity Will Be Destroyed Event
         * @type {entitas.utils.ISignal} */
        onEntityWillBeDestroyed: Pool.IPoolChanged<PoolChanged>;
        /**
         * Subscribe to Entity Destroyed Event
         * @type {entitas.utils.ISignal} */
        onEntityDestroyed: Pool.IPoolChanged<PoolChanged>;
        /**
         * Subscribe to Group Created Event
         * @type {entitas.utils.ISignal} */
        onGroupCreated: Pool.IGroupChanged<GroupChanged>;
        /**
         * Entity name for debugging
         * @type {string} */
        name: string;
        /**
         * An enum of valid component types
         * @type {Object<string,number>} */
        static componentsEnum: Object;
        /**
         * Count of components
         * @type {number} */
        static totalComponents: number;
        /**
         * Global reference to pool instance
         * @type {entitas.Pool} */
        static instance: Pool;
        _entities: {};
        _groups: {};
        _groupsForIndex: Bag<Bag<Group>>;
        _reusableEntities: Bag<Entity>;
        _retainedEntities: {};
        _componentsEnum: Object;
        _totalComponents: number;
        _creationIndex: number;
        _entitiesCache: Array<Entity>;
        _cachedUpdateGroupsComponentAddedOrRemoved: Entity.EntityChanged;
        _cachedUpdateGroupsComponentReplaced: Entity.ComponentReplaced;
        _cachedOnEntityReleased: Entity.EntityReleased;
        getEntities(matcher: IMatcher): Entity[];
        getEntities(): Entity[];
        createSystem(system: ISystem): any;
        createSystem(system: Function): any;
        /**
         * Set the system pool if supported
         *
         * @static
         * @param {entitas.ISystem} system
         * @param {entitas.Pool} pool
         */
        static setPool(system: ISystem, pool: Pool): void;
        /**
         * @constructor
         * @param {Object} components
         * @param {number} totalComponents
         * @param {number} startCreationIndex
         */
        constructor(components: {}, totalComponents: number, startCreationIndex?: number);
        /**
         * Create a new entity
         * @param {string} name
         * @returns {entitas.Entity}
         */
        createEntity(name: string): Entity;
        /**
         * Destroy an entity
         * @param {entitas.Entity} entity
         */
        destroyEntity(entity: Entity): void;
        /**
         * Destroy All Entities
         */
        destroyAllEntities(): void;
        /**
         * Check if pool has this entity
         *
         * @param {entitas.Entity} entity
         * @returns {boolean}
         */
        hasEntity(entity: Entity): boolean;
        /**
         * Gets all of the entities that match
         *
         * @param {entias.IMatcher} matcher
         * @returns {entitas.Group}
         */
        getGroup(matcher: IMatcher): Group;
        /**
         * @param {entitas.Entity} entity
         * @param {number} index
         * @param {entitas.IComponent} component
         */
        protected updateGroupsComponentAddedOrRemoved: (entity: Entity, index: number, component: IComponent) => void;
        /**
         * @param {entitas.Entity} entity
         * @param {number} index
         * @param {entitas.IComponent} previousComponent
         * @param {entitas.IComponent} newComponent
         */
        protected updateGroupsComponentReplaced: (entity: Entity, index: number, previousComponent: IComponent, newComponent: IComponent) => void;
        /**
         * @param {entitas.Entity} entity
         */
        protected onEntityReleased: (entity: Entity) => void;
    }
}
declare module entitas {
    import IMatcher = entitas.IMatcher;
    import GroupObserver = entitas.GroupObserver;
    import IReactiveSystem = entitas.IReactiveSystem;
    import IMultiReactiveSystem = entitas.IMultiReactiveSystem;
    class ReactiveSystem implements IExecuteSystem {
        /**
         * Get subsystems
         * @type {entitas.IReactiveExecuteSystem}
         * @name entitas.Pool#subsystem */
        subsystem: entitas.IReactiveExecuteSystem;
        private _subsystem;
        _observer: GroupObserver;
        _ensureComponents: IMatcher;
        _excludeComponents: IMatcher;
        _clearAfterExecute: boolean;
        _buffer: Array<Entity>;
        /**
         * @constructor
         *
         * @param pool
         * @param subSystem
         */
        constructor(pool: Pool, subSystem: IReactiveSystem | IMultiReactiveSystem);
        activate(): void;
        deactivate(): void;
        clear(): void;
        /**
         * execute
         */
        execute(): void;
    }
}
declare module entitas {
    import ISystem = entitas.ISystem;
    import IExecuteSystem = entitas.IExecuteSystem;
    import IInitializeSystem = entitas.IInitializeSystem;
    class Systems implements IInitializeSystem, IExecuteSystem {
        protected _initializeSystems: Array<IInitializeSystem>;
        protected _executeSystems: Array<IExecuteSystem>;
        /**
         * @constructor
         *
         */
        constructor();
        add(system: ISystem): any;
        add(system: Function): any;
        /**
         * Initialize Systems
         */
        initialize(): void;
        /**
         * Execute sustems
         */
        execute(): void;
        /**
         * Clear subsystems
         */
        clearReactiveSystems(): void;
    }
}
declare module entitas.viewer {
    /**
     * Profiler class for Pools
     */
    class PoolObserver {
        protected _pool: any;
        name: string;
        Pool: string;
        entities: string;
        reusable: string;
        protected _groups: any;
        /**
         * @constructor
         *
         * @param _pool
         */
        constructor(_pool: any);
    }
}
declare module entitas.viewer {
    /** todo: SystemObserver track time spent in ms by system */
    /**
     * Profiler class for Systems
     */
    class SystemObserver {
        protected _systems: any;
        name: string;
        Systems: string;
        initialize: string;
        execute: string;
        /**
         * @constructor
         *
         * @param _systems
         */
        constructor(_systems: any);
    }
}
declare module entitas.viewer {
    /**
     * Profiler class for Entities
     */
    class EntityBehavior {
        protected obj: any;
        name: string;
        private _name;
        /**
         * @constructor
         *
         * @param obj
         */
        constructor(obj: any);
    }
}
/**
 * Inspired by Unity
 */
declare module entitas.viewer {
    import Pool = entitas.Pool;
    var gui: any;
    /**
     * @class VisualDebugging
     */
    class VisualDebugging {
        static _controllers: any;
        static _entities: any;
        static _pools: any;
        static _systems: any;
        /**
         *
         * @param pool
         */
        static init(pool: Pool): void;
    }
}


text:
package com.datatorrent.contrib.cassandra;

import java.util.HashMap;
import java.util.Map;
import com.datastax.driver.core.CodecRegistry;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.TypeCodec;
import com.datastax.driver.core.UDTValue;
import com.datastax.driver.core.UserType;

/**
  This operator is a concrete implementation of the {@link AbstractUpsertOutputOperator}. This is used
  in unit tests ( refer {@link AbstractUpsertOutputOperatorCodecsTest} to showcase the use cases of:
    => Connectivity options
    => Codecs for uder defined types
    => How to specify null overrides to avoid patterns of read and then set values in a row
    => Collection mutations Add / Remove
    => List placements Append/Prepend if there is a list column
    => Map POJO field names to Cassandra columns if they do not match exactly
    => Specifying TTL
    => Overriding default consistency level set with Connection builder at a tuple level if required
 */
public class UserUpsertOperator extends AbstractUpsertOutputOperator
{
  @Override
  public ConnectionStateManager.ConnectionBuilder withConnectionBuilder()
  {
    return ConnectionStateManager.withNewBuilder()
                .withSeedNodes("localhost")
                .withClusterNameAs("Test Cluster")
                .withDCNameAs("datacenter1")
                .withTableNameAs("users")
                .withKeySpaceNameAs("unittests")
                .withdefaultConsistencyLevel(ConsistencyLevel.LOCAL_ONE);
  }

  @Override
  public Map<String, TypeCodec> getCodecsForUserDefinedTypes()
  {
    Map<String, TypeCodec> allCodecs = new HashMap<>();
    CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();

    UserType addressType = cluster.getMetadata().getKeyspace(getConnectionStateManager().getKeyspaceName())
        .getUserType("address");
    TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
    AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
    allCodecs.put("currentaddress", addressCodec);

    UserType userFullNameType = cluster.getMetadata().getKeyspace(getConnectionStateManager().getKeyspaceName())
        .getUserType("fullname");
    TypeCodec<UDTValue> userFullNameTypeCodec = codecRegistry.codecFor(userFullNameType);
    FullNameCodec fullNameCodec = new FullNameCodec(userFullNameTypeCodec, FullName.class);
    allCodecs.put("username", fullNameCodec);

    return allCodecs;
  }

  @Override
  public Class getPayloadPojoClass()
  {
    return User.class;
  }

  @Override
  protected Map<String, String> getPojoFieldNameToCassandraColumnNameOverride()
  {
    Map<String,String> overridingColMap = new HashMap<>();
    overridingColMap.put("topScores","top_scores");
    return overridingColMap;
  }

  @Override
  boolean reconcileRecord(Object T, long windowId)
  {
    return true;
  }
}


text:
from pylab import *

def load_labels(settings):
    with open('%s/data/ilsvrc12/synset_words.txt' % settings.caffevis_caffe_root) as ff:
        labels = [line.strip() for line in ff.readlines()]
    return labels

def load_trained_net(settings, model_prototxt = None, model_weights = None):
    assert (model_prototxt is None) == (model_weights is None), 'Specify both model_prototxt and model_weights or neither'
    if model_prototxt is None:
        load_dir = '/home/jyosinsk/results/140311_234854_afadfd3_priv_netbase_upgraded/'
        model_prototxt = load_dir + 'deploy_1.prototxt'
        model_weights = load_dir + 'caffe_imagenet_train_iter_450000'

    print 'LOADER: loading net:'
    print '  ', model_prototxt
    print '  ', model_weights

    sys.path.insert(0, os.path.join(settings.caffevis_caffe_root, 'python'))
    import caffe
    if settings.caffevis_mode_gpu:
        caffe.set_mode_gpu()
        print 'CaffeVisApp mode (in main thread):     GPU'
    else:
        caffe.set_mode_cpu()
        print 'CaffeVisApp mode (in main thread):     CPU'

    net = caffe.Classifier(model_prototxt, model_weights)
    #net.set_phase_test()

    return net

def load_imagenet_mean(settings):
    imagenet_mean = np.load(settings.caffevis_caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')
    imagenet_mean = imagenet_mean[:, 14:14+227, 14:14+227]    # (3,256,256) -> (3,227,227) Crop to center 227x227 section
    return imagenet_mean


text:
//
//  CustomView.m
//  橡皮擦练习
//

#import "CustomView.h"
#import "RevealLayer.h"
@interface CustomView()
@property (strong, nonatomic) RevealLayer *revealLayer;
/**<#name#>**/
@property(nonatomic,strong)UIImageView *image;

@end

@implementation CustomView
-(id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;

}
- (void)setup
{
    self.userInteractionEnabled = YES;
    [self setMultipleTouchEnabled:NO];

    self.image = [[UIImageView alloc]initWithFrame:self.bounds];
    [_image setImage:[UIImage imageNamed:@"10957553836910724"]];
    [self addSubview:_image];

    self.revealLayer = [[RevealLayer alloc]init];
    self.revealLayer.frame = self.bounds;
    self.revealLayer.backgroundColor = [[UIColor clearColor] CGColor];
    [self.revealLayer setNeedsDisplay];

    [self.layer addSublayer:self.revealLayer];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];

    [self.revealLayer.drawingPath moveToPoint:location];
    [self.revealLayer setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];

    [self.revealLayer.drawingPath addLineToPoint:location];
    [self.revealLayer setNeedsDisplay];
}@end


text:
cwd=$(pwd)
dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
web="$dir/../src/CVaS.Web"
dal="$dir/../src/CVaS.DAL"

# We have to change directory for dotnet ef to be available
cd $web
echo "dotnet ef --project $dal database update"
dotnet ef --project $dal database update


text:
import java.util.ArrayList;
import java.util.List;

public class Preprocess {
	//load all the contentPreprocess
		public String preprocess(String text){
			List<ContentPreprocess> preprocess_list = new ArrayList<ContentPreprocess>();
			preprocess_list.add(new SpecialCharacterPreprocess());
			preprocess_list.add(new PeriodPreprocess());
			preprocess_list.add(new SpacePreprocess());
			preprocess_list.add(new CasePreprocess());
			for(ContentPreprocess preprocess_rule:preprocess_list){
				text = preprocess_rule.preprocess(text);
			}
			return text;
		}
}


text:
package org.drools.modelcompiler.inlinecast;

import java.util.Collection;
import java.util.List;

import org.drools.modelcompiler.BaseModelTest;
import org.drools.modelcompiler.domain.InternationalAddress;
import org.drools.modelcompiler.domain.Person;
import org.drools.modelcompiler.domain.Result;
import org.junit.Test;
import org.kie.api.runtime.KieSession;

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

public class InlineCastTest extends BaseModelTest {

    public InlineCastTest(RUN_TYPE testRunType ) {
        super( testRunType );
    }

    @Test
    public void testInlineCastThis() {
        String str =
                "import " + Result.class.getCanonicalName() + ";" +
                "import " + Person.class.getCanonicalName() + ";" +
                "rule R when\n" +
                "  $r : Result()\n" +
                "  $o : Object( this#Person.name == \"Mark\" )\n" +
                "then\n" +
                "  $r.setValue(\"Found: \" + $o);\n" +
                "end";

        KieSession ksession = getKieSession( str );

        Result result = new Result();
        ksession.insert( result );

        ksession.insert( "Mark" );
        ksession.insert( new Person( "Mark", 37 ) );
        ksession.insert( new Person( "Mario", 40 ) );
        ksession.fireAllRules();

        assertEquals( "Found: Mark", result.getValue() );
    }

    @Test
    public void testInlineCastProjectionThis() {
        String str =
                "import " + Result.class.getCanonicalName() + ";" +
                "import " + Person.class.getCanonicalName() + ";" +
                "rule R when\n" +
                "  $r : Result()\n" +
                "  $p : Object( $name : this#Person.name )\n" +
                "then\n" +
                "  $r.setValue(\"Found: \" + $name + \" $p class: \" + $p.getClass().getCanonicalName());\n" +
                "end";

        KieSession ksession = getKieSession( str );

        Result result = new Result();
        ksession.insert( result );

        ksession.insert( "Mark" );
        ksession.insert( new Person( "Mark", 37 ) );
        ksession.fireAllRules();

        assertEquals( "Found: Mark $p class: org.drools.modelcompiler.domain.Person", result.getValue() );
    }

    @Test
    public void testInlineCastProjectionThisExplicit() {
        String str =
                "import " + Result.class.getCanonicalName() + ";" +
                "import " + Person.class.getCanonicalName() + ";" +
                "rule R when\n" +
                "  $r : Result()\n" +
                "  $p : Object( this instanceof Person, $name : this#Person.name )\n" +
                "then\n" +
                "  $r.setValue(\"Found: \" + $name + \" $p class: \" + $p.getClass().getCanonicalName());\n" +
                "end";

        KieSession ksession = getKieSession( str );

        Result result = new Result();
        ksession.insert( result );

        ksession.insert( "Mark" );
        ksession.insert( new Person( "Mark", 37 ) );
        ksession.fireAllRules();

        assertEquals( "Found: Mark $p class: org.drools.modelcompiler.domain.Person", result.getValue() );
    }

    public interface DecisionTable extends Expression {
        List<OutputClause> getOutput();
    }

    public interface OutputClause extends DMNElement {

    }

    public interface Expression extends DMNElement {

    }

    public interface DMNElement extends DMNModelInstrumentedBase {

    }

    public interface DMNModelInstrumentedBase {
        DMNModelInstrumentedBase getParent();
    }

    @Test
    public void testExplicitCast() {
        String str =
                "import " + OutputClause.class.getCanonicalName() + "\n;" +
                        "import " + DecisionTable.class.getCanonicalName() + "\n;" +
                        "rule r\n" +
                        "when\n" +
                        "  $oc : OutputClause( parent instanceof DecisionTable, parent.output.size > 1 )\n" +
                        "then\n" +
                        "end\n";

        KieSession ksession = getKieSession( str );

        ksession.fireAllRules();

        assertTrue(true);
    }

    @Test
    public void testInlineCastParent() {
        String str =
                "import " + OutputClause.class.getCanonicalName() + "\n;" +
                        "import " + DecisionTable.class.getCanonicalName() + "\n;" +
                        "rule r\n" +
                        "when\n" +
                        "  $oc : OutputClause( parent#DecisionTable.output.size > 1 )\n" +
                        "then\n" +
                        "end\n";

        KieSession ksession = getKieSession( str );

        ksession.fireAllRules();

        assertTrue(true);
    }

    @Test
    public void testInlineCastProjection() {
        String str = "import " + Person.class.getCanonicalName() + ";" +
                "import " + InternationalAddress.class.getCanonicalName() + ";" +
                "rule R when\n" +
                "  Person( $a : address#InternationalAddress.state )\n" +
                "then\n" +
                "  insert($a);\n" +
                "end";

        KieSession ksession = getKieSession(str);

        Person john = new Person("John", 47);
        InternationalAddress a = new InternationalAddress("address", "Italy");
        john.setAddress(a);

        ksession.insert(john);
        ksession.fireAllRules();

        Collection<String> results = getObjectsIntoList(ksession, String.class);
        assertEquals("Italy", results.iterator().next());
    }

    @Test
    public void testInlineCastProjectionOnMethod() {
        String str = "import " + Person.class.getCanonicalName() + ";" +
                "import " + InternationalAddress.class.getCanonicalName() + ";" +
                "rule R when\n" +
                "  Person( $a : address#InternationalAddress.getState() )\n" +
                "then\n" +
                "  insert($a);\n" +
                "end";

        KieSession ksession = getKieSession(str);

        Person john = new Person("John", 47);
        InternationalAddress a = new InternationalAddress("address", "Italy");
        john.setAddress(a);

        ksession.insert(john);
        ksession.fireAllRules();

        Collection<String> results = getObjectsIntoList(ksession, String.class);
        assertEquals("Italy", results.iterator().next());
    }

    @Test
    public void testInlineCastForAField() {
        String str = "import " + Person.class.getCanonicalName() + ";" +
                     "import " + InternationalAddress.class.getCanonicalName() + ";" +
                     "rule R when\n" +
                     "  $p : Person( address#InternationalAddress.state.length == 5 )\n" +
                     "then\n" +
                     "  insert(\"matched\");\n" +
                     "end";

        KieSession ksession = getKieSession(str);

        Person john = new Person("John", 47);
        InternationalAddress a = new InternationalAddress("address", "Italy");
        john.setAddress(a);

        ksession.insert(john);
        ksession.fireAllRules();

        Collection<String> results = getObjectsIntoList(ksession, String.class);
        assertEquals(1, results.size());
    }

    @Test
    public void testInlineCastForAFieldWithFQN() {
        String str = "import " + Person.class.getCanonicalName() + ";" +
                     "rule R when\n" +
                     "  $p : Person( address#org.drools.modelcompiler.domain.InternationalAddress.state.length == 5 )\n" +
                     "then\n" +
                     "  insert(\"matched\");\n" +
                     "end";

        KieSession ksession = getKieSession(str);

        Person john = new Person("John", 47);
        InternationalAddress a = new InternationalAddress("address", "Italy");
        john.setAddress(a);

        ksession.insert(john);
        ksession.fireAllRules();

        Collection<String> results = getObjectsIntoList(ksession, String.class);
        assertEquals(1, results.size());
    }

    @Test
    public void testInlineCastForAFieldAndMixMethodCall() {
        String str = "import " + Person.class.getCanonicalName() + ";" +
                     "import " + InternationalAddress.class.getCanonicalName() + ";" +
                     "rule R when\n" +
                     "  $p : Person( address#InternationalAddress.getState().length == 5 )\n" +
                     "then\n" +
                     "  insert(\"matched\");\n" +
                     "end";

        KieSession ksession = getKieSession(str);

        Person john = new Person("John", 47);
        InternationalAddress a = new InternationalAddress("address", "Italy");
        john.setAddress(a);

        ksession.insert(john);
        ksession.fireAllRules();

        Collection<String> results = getObjectsIntoList(ksession, String.class);
        assertEquals(1, results.size());
    }

    @Test
    public void testInlineCastSingle() {
        String str = "import " + ICAbstractA.class.getCanonicalName() + ";" +
                "import " + ICAbstractB.class.getCanonicalName() + ";" +
                "import " + ICAbstractC.class.getCanonicalName() + ";" +
                "import " + ICA.class.getCanonicalName() + ";" +
                "import " + ICB.class.getCanonicalName() + ";" +
                "import " + ICC.class.getCanonicalName() + ";" +
                "rule R when\n" +
                "  $a : ICA( someB#ICB.onlyConcrete() == \"Hello\" )\n" + // Notice this is chaining MVEL field accessors, because inlinecast chaining methodcalls does not work even on DRL: getSomeB()#ICB.getSomeD()#ICC.onlyConcrete()
                "then\n" +
                "  insert(\"matched\");\n" +
                "end";

        KieSession ksession = getKieSession(str);

        ICA a = new ICA();
        ICB b = new ICB();
        ICC c = new ICC();
        b.setSomeC(c);
        a.setSomeB(b);

        ksession.insert(a);
        ksession.fireAllRules();

        Collection<String> results = getObjectsIntoList(ksession, String.class);
        assertEquals(1, results.size());
    }

    @Test
    public void testInlineCastMultiple() {
        String str = "import " + ICAbstractA.class.getCanonicalName() + ";" +
                     "import " + ICAbstractB.class.getCanonicalName() + ";" +
                     "import " + ICAbstractC.class.getCanonicalName() + ";" +
                     "import " + ICA.class.getCanonicalName() + ";" +
                     "import " + ICB.class.getCanonicalName() + ";" +
                     "import " + ICC.class.getCanonicalName() + ";" +
                     "rule R when\n" +
                     "  $a : ICA( someB#ICB.someC#ICC.onlyConcrete() == \"Hello\" )\n" + // Notice this is chaining MVEL field accessors, because inlinecast chaining methodcalls does not work even on DRL: getSomeB()#ICB.getSomeD()#ICC.onlyConcrete()
                     "then\n" +
                     "  insert(\"matched\");\n" +
                     "end";

        KieSession ksession = getKieSession(str);

        ICA a = new ICA();
        ICB b = new ICB();
        ICC c = new ICC();
        b.setSomeC(c);
        a.setSomeB(b);

        ksession.insert(a);
        ksession.fireAllRules();

        Collection<String> results = getObjectsIntoList(ksession, String.class);
        assertEquals(1, results.size());
    }
}


text:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _

class UsersConfig(AppConfig):
    name = 'bejmy.users'
    category = 'users'
    verbose_name = _("users")


text:
var ui = {
	clouds: {
		init: function(number) {
			var startTimeout = 0;
			for (var i = 0; i < number; i++) {
				setTimeout(ui.clouds.createCloud, startTimeout);
				startTimeout += 4000 + Math.floor(Math.random() * 5000);
			}
		},

		createCloud: function() {
			var minTopPosition = 40;
			var maxTopPosition = 600;
			var lastTopPosition = 0;

			var cloudContainer = $('');
			var cloud = $('');
			cloud.appendTo(cloudContainer);

			do {
				topPosition = minTopPosition + Math.round(Math.random() * (maxTopPosition - minTopPosition));
			} while (Math.abs(topPosition - lastTopPosition) < 200);
			lastTopPosition = topPosition;

			cloudContainer.css({
				top: topPosition
			});

			cloud.css({
				zoom: Math.random() / 2 + 0.5
			});

			cloudContainer.appendTo("body");

			cloud.animate({
				opacity: Math.random() / 2 + 0.5
			}, 1000);

			var transitionDuration = 20000 + Math.floor(Math.random() * 50000);
			cloudContainer.transition({
				left: $("body").width() - 200,
				duration: transitionDuration,
				easing: "linear"
			});

			setTimeout(function() {
				ui.clouds.destroyCloud(cloud, cloudContainer);
			}, transitionDuration - 1000);
		},

		destroyCloud: function (cloud, container) {
			cloud.animate({
				opacity: 0
			}, 1000, function() {
				container.remove();
				setTimeout(ui.clouds.createCloud, 3000 + Math.floor(Math.random() * 3000));
			});
		}
	},

	verses: {
		init: function() {
 			Parse.initialize("KOilx1x2h0XEDW6G7kbNNwILuvWQpIRCNzC5dIPD", "Trny3PmLIieAPQV79QMiJbP2JKfGoRPl8D3ZERKq");
			ui.verses.template = $("#verseTemplate").html();
			ui.verses.streamPosition = 0;
			ui.verses.perPage = 16;

			// http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
			ui.isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;

			$("#more > a").click(function(e) {
				e.preventDefault();
				ui.verses.streamPosition += ui.verses.perPage;
				ui.verses.fetch();
			});

			var query = new Parse.Query("Tweet");
			query.count({
			  success: function(total) {
					$("#total").html(ui.verses.formatTotal(total));
			  }
			});

			ui.verses.fetch();
		},

		fetch: function(start) {
			var query = new Parse.Query("Tweet");
			query.descending("createdAt");
			query.skip(ui.verses.streamPosition);
			query.limit(ui.verses.perPage);
			query.find({
			  success: function(tweets) {
			  	var verses = [];
			  	tweets.map(function(tweet) {
			  		verses.push({
			  			id: tweet.get("tweet"),
			  			text: tweet.get("text"),
			  			author: tweet.get("author"),
			  			username: tweet.get("username")
			  		})
			  	});

					ui.verses.render(verses);
					$("#more").show();
			  },
			  error: function(object, error) {
					console.log(error);
			  }
			});
		},

		render: function(verses) {
			var versesHtml = '';
			for (var i = 0; i < verses.length; i++) {
				var text = (ui.isSafari) ? verses[i].text : ui.verses.stripEmoji(verses[i].text);
				versesHtml += ui.verses.template.format(verses[i].username, verses[i].id, verses[i].author, text);
			}

			if ($("#verses li").length === 0) {
				$("#verses").html(versesHtml);
			} else {
				$("#verses").animate({
					opacity: 0
				}, 200, function() {
					$("#verses").html(versesHtml);
					$("#verses").animate({
						opacity: 1
					}, 200);
				});
			}
		},

		formatTotal: function(number) {
			number = number.toString();

			var result = [];
			do {
				result.push(number.substr(-3));
				number = number.substr(0, number.length - 3);
			} while (number.length > 0);

			result.reverse();
			return result.join(",");
		},

		stripEmoji: function(text) {
			return text.split("").map(function(c) {
				var charCode = c.charCodeAt(0);
				return (charCode >= 50000) ? '' : c;
			}).join("");
		}
	},

	init: function() {
		ui.clouds.init(5);
		ui.verses.init();
	}
};

$(ui.init);

// http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
if (!String.prototype.format) {
	String.prototype.format = function() {
		var args = arguments;
		return this.replace(/{(\d+)}/g, function(match, number) {
			return (typeof args[number] != 'undefined') ? args[number] : match;
		});
	};
}


text:
describe('Bloodhound', function () {

    function build(o) {
        return new Bloodhound(_.mixin({
            datumTokenizer: datumTokenizer,
            queryTokenizer: queryTokenizer
        }, o || {}));
    }

    beforeEach(function () {
        jasmine.Remote.useMock();
        jasmine.Prefetch.useMock();
        jasmine.Transport.useMock();
        jasmine.PersistentStorage.useMock();
    });

    afterEach(function () {
        clearAjaxRequests();
    });

    describe('#initialize', function () {
        beforeEach(function () {
            this.bloodhound = build({initialize: false});
            spyOn(this.bloodhound, '_initialize').andCallThrough();
        });

        it('should not initialize if intialize option is false', function () {
            expect(this.bloodhound._initialize).not.toHaveBeenCalled();
        });

        it('should not support reinitialization by default', function () {
            var p1, p2;

            p1 = this.bloodhound.initialize();
            p2 = this.bloodhound.initialize();

            expect(p1).toBe(p2);
            expect(this.bloodhound._initialize.callCount).toBe(1);
        });

        it('should reinitialize if reintialize flag is true', function () {
            var p1, p2;

            p1 = this.bloodhound.initialize();
            p2 = this.bloodhound.initialize(true);

            expect(p1).not.toBe(p2);
            expect(this.bloodhound._initialize.callCount).toBe(2);
        });

        it('should clear the index', function () {
            this.bloodhound = build({initialize: false, prefetch: '/prefetch'});
            spyOn(this.bloodhound, 'clear');
            this.bloodhound.initialize();

            expect(this.bloodhound.clear).toHaveBeenCalled();
        });

        it('should load data from prefetch cache if available', function () {
            this.bloodhound = build({initialize: false, prefetch: '/prefetch'});
            this.bloodhound.prefetch.fromCache.andReturn(fixtures.serialized.simple);
            this.bloodhound.initialize();

            expect(this.bloodhound.all()).toEqual(fixtures.data.simple);
            expect(this.bloodhound.prefetch.fromNetwork).not.toHaveBeenCalled();
        });

        it('should load data from prefetch network as fallback', function () {
            this.bloodhound = build({initialize: false, prefetch: '/prefetch'});
            this.bloodhound.prefetch.fromCache.andReturn(null);
            this.bloodhound.prefetch.fromNetwork.andCallFake(fakeFromNetwork);
            this.bloodhound.initialize();

            expect(this.bloodhound.all()).toEqual(fixtures.data.simple);

            function fakeFromNetwork(cb) {
                cb(null, fixtures.data.simple);
            }
        });

        it('should store prefetch network data in the prefetch cache', function () {
            this.bloodhound = build({initialize: false, prefetch: '/prefetch'});
            this.bloodhound.prefetch.fromCache.andReturn(null);
            this.bloodhound.prefetch.fromNetwork.andCallFake(fakeFromNetwork);
            this.bloodhound.initialize();

            expect(this.bloodhound.prefetch.store)
                .toHaveBeenCalledWith(fixtures.serialized.simple);

            function fakeFromNetwork(cb) {
                cb(null, fixtures.data.simple);
            }
        });

        it('should add local after prefetch is loaded', function () {
            this.bloodhound = build({
                initialize: false,
                local: [{foo: 'bar'}],
                prefetch: '/prefetch'
            });
            this.bloodhound.prefetch.fromNetwork.andCallFake(fakeFromNetwork);

            expect(this.bloodhound.all()).toEqual([]);
            this.bloodhound.initialize();
            expect(this.bloodhound.all()).toEqual([{foo: 'bar'}]);

            function fakeFromNetwork(cb) {
                cb(null, []);
            }
        });
    });

    describe('#add', function () {
        it('should add datums to search index', function () {
            var spy = jasmine.createSpy();

            this.bloodhound = build().add(fixtures.data.simple);

            this.bloodhound.search('big', spy);

            expect(spy).toHaveBeenCalledWith([
                {value: 'big'},
                {value: 'bigger'},
                {value: 'biggest'}
            ]);
        });
    });

    describe('#get', function () {
        beforeEach(function () {
            this.bloodhound = build({
                identify: function (d) {
                    return d.value;
                },
                local: fixtures.data.simple
            });
        });

        it('should support array signature', function () {
            expect(this.bloodhound.get(['big', 'bigger'])).toEqual([
                {value: 'big'},
                {value: 'bigger'}
            ]);
        });

        it('should support splat signature', function () {
            expect(this.bloodhound.get('big', 'bigger')).toEqual([
                {value: 'big'},
                {value: 'bigger'}
            ]);
        });

        it('should return nothing for unknown ids', function () {
            expect(this.bloodhound.get('big', 'foo', 'bigger')).toEqual([
                {value: 'big'},
                {value: 'bigger'}
            ]);
        });
    });

    describe('#clear', function () {
        it('should remove all datums to search index', function () {
            var spy = jasmine.createSpy();

            this.bloodhound = build({local: fixtures.data.simple}).clear();

            this.bloodhound.search('big', spy);

            expect(spy).toHaveBeenCalledWith([]);
        });
    });

    describe('#clearPrefetchCache', function () {
        it('should clear persistent storage', function () {
            this.bloodhound = build({prefetch: '/prefetch'}).clearPrefetchCache();
            expect(this.bloodhound.prefetch.clear).toHaveBeenCalled();
        });
    });

    describe('#clearRemoteCache', function () {
        it('should clear remote request cache', function () {
            spyOn(Transport, 'resetCache');
            this.bloodhound = build({remote: '/remote'}).clearRemoteCache();
            expect(Transport.resetCache).toHaveBeenCalled();
        });
    });

    describe('#all', function () {
        it('should return all local results', function () {
            this.bloodhound = build({local: fixtures.data.simple});
            expect(this.bloodhound.all()).toEqual(fixtures.data.simple);
        });
    });

    describe('#search – local', function () {
        it('should return sync matches', function () {
            var spy = jasmine.createSpy();

            this.bloodhound = build({local: fixtures.data.simple});

            this.bloodhound.search('big', spy);

            expect(spy).toHaveBeenCalledWith([
                {value: 'big'},
                {value: 'bigger'},
                {value: 'biggest'}
            ]);
        });
    });

    describe('#search – prefetch', function () {
        it('should return sync matches', function () {
            var spy = jasmine.createSpy();

            this.bloodhound = build({initialize: false, prefetch: '/prefetch'});
            this.bloodhound.prefetch.fromCache.andReturn(fixtures.serialized.simple);
            this.bloodhound.initialize();

            this.bloodhound.search('big', spy);

            expect(spy).toHaveBeenCalledWith([
                {value: 'big'},
                {value: 'bigger'},
                {value: 'biggest'}
            ]);
        });
    });

    describe('#search – remote', function () {
        it('should return async matches', function () {
            var spy = jasmine.createSpy();

            this.bloodhound = build({remote: '/remote'});
            this.bloodhound.remote.get.andCallFake(fakeGet);
            this.bloodhound.search('dog', $.noop, spy);

            expect(spy.callCount).toBe(1);

            function fakeGet(o, cb) {
                cb(fixtures.data.animals);
            }
        });
    });

    describe('#search – integration', function () {
        it('should backfill when local/prefetch is not sufficient', function () {
            var syncSpy, asyncSpy;

            syncSpy = jasmine.createSpy();
            asyncSpy = jasmine.createSpy();

            this.bloodhound = build({
                sufficient: 3,
                local: fixtures.data.simple,
                remote: '/remote'
            });
            this.bloodhound.remote.get.andCallFake(fakeGet);

            this.bloodhound.search('big', syncSpy, asyncSpy);

            expect(syncSpy).toHaveBeenCalledWith([
                {value: 'big'},
                {value: 'bigger'},
                {value: 'biggest'}
            ]);
            expect(asyncSpy).not.toHaveBeenCalled();

            this.bloodhound.search('bigg', syncSpy, asyncSpy);

            expect(syncSpy).toHaveBeenCalledWith([
                {value: 'bigger'},
                {value: 'biggest'}
            ]);
            expect(asyncSpy).toHaveBeenCalledWith(fixtures.data.animals);

            function fakeGet(o, cb) {
                cb(fixtures.data.animals);
            }
        });

        it('should remove duplicates from backfill', function () {
            var syncSpy, asyncSpy;

            syncSpy = jasmine.createSpy();
            asyncSpy = jasmine.createSpy();

            this.bloodhound = build({
                identify: function (d) {
                    return d.value;
                },
                local: fixtures.data.animals,
                remote: '/remote'
            });
            this.bloodhound.remote.get.andCallFake(fakeGet);

            this.bloodhound.search('dog', syncSpy, asyncSpy);

            expect(syncSpy).toHaveBeenCalledWith([{value: 'dog'}]);
            expect(asyncSpy).toHaveBeenCalledWith([
                {value: 'cat'},
                {value: 'moose'}
            ]);

            function fakeGet(o, cb) {
                cb(fixtures.data.animals);
            }
        });
    });

    // helper functions
    // ----------------

    function datumTokenizer(d) {
        return $.trim(d.value).split(/\s+/);
    }

    function queryTokenizer(s) {
        return $.trim(s).split(/\s+/);
    }
});


text:
<?php

namespace GrosLab\LibraryDefaultBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Books
 *
 * @ORM\Table(name="books")
 * @ORM\Entity
 */
class Books
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=100, nullable=false)
     */
    private $title;

    /**
     * @var \Categories
     *
     * @ORM\ManyToOne(targetEntity="Categories", inversedBy="books")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $category;

    /**
     * @var \Readers
     *
     * @ORM\ManyToOne(targetEntity="Readers", inversedBy="books")
     * @ORM\JoinColumn(name="reader_id", referencedColumnName="id")
     */
    private $reader;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Authors", inversedBy="books")
     * @ORM\JoinTable(name="books_authors",
     *   joinColumns={
     *     @ORM\JoinColumn(name="books_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="authors_id", referencedColumnName="id")
     *   }
     * )
     */
    private $authors;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->authors = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set id
     *
     * @param integer $id
     * @return Books
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Books
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set category
     *
     * @param \GrosLab\LibraryDefaultBundle\Entity\Categories $category
     * @return Books
     */
    public function setCategory(\GrosLab\LibraryDefaultBundle\Entity\Categories $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \GrosLab\LibraryDefaultBundle\Entity\Categories
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Add authors
     *
     * @param \GrosLab\LibraryDefaultBundle\Entity\Authors $authors
     * @return Books
     */
    public function addAuthor(\GrosLab\LibraryDefaultBundle\Entity\Authors $authors)
    {
        $this->authors[] = $authors;

        return $this;
    }

    /**
     * Remove authors
     *
     * @param \GrosLab\LibraryDefaultBundle\Entity\Authors $authors
     */
    public function removeAuthor(\GrosLab\LibraryDefaultBundle\Entity\Authors $authors)
    {
        $this->authors->removeElement($authors);
    }

    /**
     * Get authors
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAuthors()
    {
        return $this->authors;
    }

    public function __toString() {
        return $this->title;
    }

    /**
     * Set reader
     *
     * @param \GrosLab\LibraryDefaultBundle\Entity\Readers $reader
     * @return Books
     */
    public function setReader(\GrosLab\LibraryDefaultBundle\Entity\Readers $reader)
    {
        $this->reader = $reader;

        return $this;
    }

    /**
     * Unset reader
     *
     * @return Books
     */
    public function unsetReader()
    {
        $this->reader = null;

        return $this;
    }

    /**
     * Get reader
     *
     * @return \GrosLab\LibraryDefaultBundle\Entity\Readers
     */
    public function getReader()
    {
        return $this->reader;
    }
}