<commit_before>/*
 * Authors: Isaac Zylstra and Victor Norman @ Calvin College, Grand Rapids, MI.
 * Contact: vtn2@calvin.edu
 */

(function(ext) {

    //The variable that will hold the json to be read from
    var jsonObject = null;

    //The scale applied to the kinect data to make it map to the canvas better.
    var xScale = 240;
    var yScale = 180;
    var zScale = 200;

    //The status of the kinect
    var status = 0;

    //alert letting the user know what needs to be done before loading the extension.
    alert("BEFORE CLICKING OK: Make sure the kinect is connected and your JSON websocket server has started");

    console.log("connecting to server ..");

    // create a new websocket and connect
    window.ws = new WebSocket('ws://localhost:8181/');

    // when data is comming from the server, this method is called
    ws.onmessage = function (evt) {
        jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        console.log('.. connection open');
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
    };

    // Cleanup function when the extension is unloaded
    ext._shutdown = function()
    {
    window.ws.close();
    };

    // Reports status of kinect
    ext._getStatus = function() {
        if(status == 0)
        {
        return {status: 0, msg: 'Kinect is not connected to Scratch'};
        }
        if(status == 1)
        {
            return {status: 1, msg: 'Kinect is connected, but is not detecting any bodies'};
        }
        if(status == 2)
        {
            return {status: 2, msg: 'Kinect is sending body data'};
        }
    };

        // Block and block menu descriptions
    var descriptor = {
        blocks: [
            ['r', '%m.b %m.j %m.c', 'joints', 'Body 1', 'Head', 'x'],
            ['b', '%m.b %m.d Handstate is %m.h', 'handstate', 'Body 1', 'Left', 'Closed'],
            ['r', '%m.b %m.d Handstate', 'handdebug', 'Body 1', 'Left'], //Comment out of final version.
            ['r', '%m.b id', 'bodyid', 'Body 1'],
            ['b', '%m.b tracked', 'tracked', 'Body 1'],
            ['b', 'connected', 'connected'],
            ['', 'Basic body check', 'basic_body_check'], //Comment out of final version.
            ['', 'Test Block', 'test'], //Comment out of final
            ['', 'Start new local connection', 'local'],
            ['', 'connect to %s', 'ipconnect', '0.0.0.0'],
            ['', 'Close connection', 'closeconn'], //Comment out of final version.
            ['', 'console.log %n', 'write'], //Comment out of final version.
            ['', 'bad only %n', 'writeB'] //Comment out of final version.
        ],

        menus: {
	    j: ['Left Ankle', 'Right Ankle', 'Left Elbow', 'Right Elbow', 'Left Foot', 'Right Foot', 'Left Hand', 'Right Hand', 'Left Hand Tip', 'Right Hand Tip', 'Head', 'Left Hip', 'Right Hip', 'Left Knee', 'Right Knee', 'Neck', 'Left Shoulder', 'Right Shoulder', 'Spine Base', 'Spine Middle', 'Spine Shoulder', 'Left Thumb', 'Right Thumb', 'Left Wrist', 'Right Wrist'],
        b: ['Body 1', 'Body 2', 'Body 3', 'Body 4', 'Body 5', 'Body 6'],
        h: ['Unknown', 'Not Tracked', 'Open', 'Closed', 'Lasso'],
        c: ['x', 'y', 'z'],
        d: ['Left', 'Right']
    }
    };

    //restarts the local connection
    ext.local = function() {
        window.ws.close();
        console.log("connecting to local server ..");
        window.ws = new WebSocket('ws://localhost:8181/');

        // when data is comming from the server, this method is called
        ws.onmessage = function (evt) {
            jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        console.log('.. connection open');
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
    };
    };

    //s: a string containing the ip the user wishes to connect to.
    //Creates a remote connection to s.
    ext.ipconnect = function(string) {
        window.ws.close();
        console.log("connecting to "+string+' ..');
        window.ws = new WebSocket('ws://'+string+':8181/');

        // when data is comming from the server, this method is called
        ws.onmessage = function (evt) {
            jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
        };

        // when the connection is established, this method is called
        ws.onopen = function () {
        console.log('.. connection open');
        };

        // when the connection is closed, this method is called
        ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
        };
    }

    //Closes the current connection
    ext.closeconn = function()
    {
        window.ws.close();
    }

    //m: the number to be written to the console
    //Outputs numeric content to console
    ext.write = function(number){
        console.log(number);
    };

    //m: input to be compared to 0
    //Writes "bad" in console if the input is 0
    ext.writeB = function(number){
        if(number == 0)
        {
            console.log("bad");
        }
    };

    //Checks the body 1 head x coordinate
    //Good for check if any data is getting in from the kinect
    ext.basic_body_check = function() {
        console.log(jsonObject.bodies[0].joints[3].x*xScale);
    };

    //m: the body chosen (Body 1-6)
    //Gives the id of the selected body
    ext.bodyid = function(body)
    {
        switch(body){
            case 'Body 1': return jsonObject.bodies[0].id;
            case 'Body 2': return jsonObject.bodies[1].id;
            case 'Body 3': return jsonObject.bodies[2].id;
            case 'Body 4': return jsonObject.bodies[3].id;
            case 'Body 5': return jsonObject.bodies[4].id;
            case 'Body 6': return jsonObject.bodies[5].id;
        }
    }

    ext.test = function()
    {
        var b = -1;
        var bodyID = jsonObject.bodies[0].id;
        for(i = 0; i < 6; i++)
        {
        //if(bodyID == jsonObject.bodies[i].id)
        //    {
            //b = i;
            b = jsonObject.bodies[0].id;
        //    }
        }
        //console.log(jsonObject.bodies[b].joints[3].x*xScale);
        console.log(b);
    }

        //True if scratch is receiving the kinect (but not necessarily data)
    ext.connected = function()
    {
        if(status == 0){
            return false;
        }

        if(status == 1 || 2){
            return true;
        }
    };

    //m: the body chosen (Body 1-6)
    //True if scratch is receiving the chosen body data
    ext.tracked = function(body)
    {
        var i = -1;
        switch(body){
            case 'Body 1': i = 0;
                break;
            case 'Body 2': i = 1;
                break;
            case 'Body 3': i = 2;
                break;
            case 'Body 4': i = 3;
                break;
            case 'Body 5': i = 4;
                break;
            case 'Body 6': i = 5;
                break;
        }

        return jsonObject.bodies[i].id != 0;
    };

    //l: the body chosen (Body 1-6)
    //d: which handstate (left or right)
    //Outputs the left handstate of the selected body
    ext.handdebug = function(body,direction)
    {
        var i;
        switch(body){
            case 'Body 1': i=0;
                break;
            case 'Body 2': i=1;
                break;
            case 'Body 3': i=2;
                break;
            case 'Body 4': i=3;
                break;
            case 'Body 5': i=4;
                break;
            case 'Body 6': i=5;
                break;
        }

        switch(direction)
        {
            case 'Left': return jsonObject.bodies[i].lhandstate;
            case 'Right': return jsonObject.bodies[i].rhandstate;
        }
    }

    //l: The selected body (Body 1-6)
    //d: Which handstate (left or right)
    //n: The selected handstate (Unknown, Not Tracked, Open, Closed, Lasso)
    //Returns true if the selected bodies left handstate is the same as block selected one.
    ext.handstate = function(body,direction,handstate)
    {
        var i;
        var j;
        switch(body){
            case 'Body 1': i=0;
                break;
            case 'Body 2': i=1;
                break;
            case 'Body 3': i=2;
                break;
            case 'Body 4': i=3;
                break;
            case 'Body 5': i=4;
                break;
            case 'Body 6': i=5;
                break;
        }

        switch(handstate)
        {
            case 'Unknown': j = 0;
                break;
            case 'Not Tracked': j = 1;
                break;
            case 'Open': j = 2;
                break;
            case 'Closed': j = 3;
                break;
            case 'Lasso': j = 4;
                break;
        }

        switch(direction)
        {
            case 'Left': return jsonObject.bodies[i].lhandstate == j;
            case 'Right': return jsonObject.bodies[i].rhandstate == j;
        }
    }

    //l: The body chosen (Body 1-6).
    //k1: The joint chosen (All joint the kinect v2 tracks).
    //x: The chosen coordinate (x, y, or z).
    //Gets the coordinate chosen from the joint chosen from the body chosen
    ext.joints = function(body,joint,coordinate)
    {
        var a = -1;
        var b = -1;

        switch(joint){
            case 'Left Ankle': a=14;
                break;
            case 'Right Ankle': a=18;
                break;
            case 'Left Elbow': a=5;
                break;
            case 'Right Elbow': a=9;
                break;
            case 'Left Foot': a=15;
                break;
            case 'Right Foot': a=19;
                break;
            case 'Left Hand': a=7;
                break;
            case 'Right Hand': a=11;
                break;
            case 'Left Hand Tip': a=21;
                break;
            case 'Right Hand Tip': a=23;
                break;
            case 'Head': a=3;
                break;
            case 'Left Hip': a=12;
                break;
            case 'Right Hip': a=16;
                break;
            case 'Left Knee': a=13;
                break;
            case 'Right Knee': a=17;
                break;
            case 'Neck': a=2;
                break;
            case 'Left Shoulder': a=4;
                break;
            case 'Right Shoulder': a=8;
                break;
            case 'Spine Base': a=0;
                break;
            case 'Spine Middle': a=1;
                break;
            case 'Spine Shoulder': a=20;
                break;
            case 'Left Thumb': a=22;
                break;
            case 'Right Thumb': a=24;
                break;
            case 'Left Wrist': a=6;
                break;
            case 'Right Wrist': a=10;
                break;
        }

        switch(body){
            case 'Body 1': b=0;
                break;
            case 'Body 2': b=1;
                break;
            case 'Body 3': b=2;
                break;
            case 'Body 4': b=3;
                break;
            case 'Body 5': b=4;
                break;
            case 'Body 6': b=5;
                break;
        }

        switch(coordinate){
            case 'x': return jsonObject.bodies[b].joints[a].x*xScale;
            case 'y': return jsonObject.bodies[b].joints[a].y*yScale;
            case 'z': return jsonObject.bodies[b].joints[a].z*zScale;
        }
    }

    // Register the extension
    ScratchExtensions.register('SkelScratch', descriptor, ext);
})({});<commit_msg>dsfafds<commit_after>/*
 * Authors: Isaac Zylstra and Victor Norman @ Calvin College, Grand Rapids, MI.
 * Contact: vtn2@calvin.edu
 */

(function(ext) {

    //The variable that will hold the json to be read from
    var jsonObject = null;

    //The scale applied to the kinect data to make it map to the canvas better.
    var xScale = 240;
    var yScale = 180;
    var zScale = 200;

    //The status of the kinect
    var status = 0;

    //alert letting the user know what needs to be done before loading the extension.
    alert("BEFORE CLICKING OK: Make sure the kinect is connected and your JSON websocket server has started");

    console.log("connecting to server ..");

    // create a new websocket and connect
    window.ws = new WebSocket('ws://localhost:8181/');

    // when data is comming from the server, this method is called
    ws.onmessage = function (evt) {
        jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        console.log('.. connection open');
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
    };

    // Cleanup function when the extension is unloaded
    ext._shutdown = function()
    {
    window.ws.close();
    };

    // Reports status of kinect
    ext._getStatus = function() {
        if(status == 0)
        {
        return {status: 0, msg: 'Kinect is not connected to Scratch'};
        }
        if(status == 1)
        {
            return {status: 1, msg: 'Kinect is connected, but is not detecting any bodies'};
        }
        if(status == 2)
        {
            return {status: 2, msg: 'Kinect is sending body data'};
        }
    };

        // Block and block menu descriptions
    var descriptor = {
        blocks: [
            ['r', '%m.b %m.j %m.c', 'joints', 'Body 1', 'Head', 'x'],
            ['b', '%m.b %m.d Handstate is %m.h', 'handstate', 'Body 1', 'Left', 'Closed'],
            ['r', '%m.b %m.d Handstate', 'handdebug', 'Body 1', 'Left'], //Comment out of final version.
            ['r', '%m.b id', 'bodyid', 'Body 1'],
            ['b', '%m.b tracked', 'tracked', 'Body 1'],
            ['b', 'connected', 'connected'],
            ['', 'Basic body check', 'basic_body_check'], //Comment out of final version.
            ['', 'Test Block', 'test'], //Comment out of final
            ['', 'Start new local connection', 'local'],
            ['', 'connect to %s', 'ipconnect', '0.0.0.0'],
            ['', 'Close connection', 'closeconn'], //Comment out of final version.
            ['', 'console.log %n', 'write'], //Comment out of final version.
            ['', 'bad only %n', 'writeB'] //Comment out of final version.
        ],

        menus: {
	    j: ['Left Ankle', 'Right Ankle', 'Left Elbow', 'Right Elbow', 'Left Foot', 'Right Foot', 'Left Hand', 'Right Hand', 'Left Hand Tip', 'Right Hand Tip', 'Head', 'Left Hip', 'Right Hip', 'Left Knee', 'Right Knee', 'Neck', 'Left Shoulder', 'Right Shoulder', 'Spine Base', 'Spine Middle', 'Spine Shoulder', 'Left Thumb', 'Right Thumb', 'Left Wrist', 'Right Wrist'],
        b: ['Body 1', 'Body 2', 'Body 3', 'Body 4', 'Body 5', 'Body 6'],
        h: ['Unknown', 'Not Tracked', 'Open', 'Closed', 'Lasso'],
        c: ['x', 'y', 'z'],
        d: ['Left', 'Right']
    }
    };

    //restarts the local connection
    ext.local = function() {
        window.ws.close();
        console.log("connecting to local server ..");
        window.ws = new WebSocket('ws://localhost:8181/');

        // when data is comming from the server, this method is called
        ws.onmessage = function (evt) {
            jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        console.log('.. connection open');
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
    };
    };

    //s: a string containing the ip the user wishes to connect to.
    //Creates a remote connection to s.
    ext.ipconnect = function(string) {
        window.ws.close();
        console.log("connecting to "+string+' ..');
        window.ws = new WebSocket('ws://'+string+':8181/');

        // when data is comming from the server, this method is called
        ws.onmessage = function (evt) {
            jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
        };

        // when the connection is established, this method is called
        ws.onopen = function () {
        console.log('.. connection open');
        };

        // when the connection is closed, this method is called
        ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
        };
    }

    //Closes the current connection
    ext.closeconn = function()
    {
        window.ws.close();
    }

    //m: the number to be written to the console
    //Outputs numeric content to console
    ext.write = function(number){
        console.log(number);
    };

    //m: input to be compared to 0
    //Writes "bad" in console if the input is 0
    ext.writeB = function(number){
        if(number == 0)
        {
            console.log("bad");
        }
    };

    //Checks the body 1 head x coordinate
    //Good for check if any data is getting in from the kinect
    ext.basic_body_check = function() {
        console.log(jsonObject.bodies[0].joints[3].x*xScale);
    };

    //m: the body chosen (Body 1-6)
    //Gives the id of the selected body
    ext.bodyid = function(body)
    {
        switch(body){
            case 'Body 1': return jsonObject.bodies[0].id;
            case 'Body 2': return jsonObject.bodies[1].id;
            case 'Body 3': return jsonObject.bodies[2].id;
            case 'Body 4': return jsonObject.bodies[3].id;
            case 'Body 5': return jsonObject.bodies[4].id;
            case 'Body 6': return jsonObject.bodies[5].id;
        }
    }

    ext.test = function()
    {
        var b = -1;
        var bodyID = jsonObject.bodies[0].id;
        for(i = 0; i < 6; i++)
        {
        //if(bodyID == jsonObject.bodies[i].id)
        //    {
            //b = i;
            b = jsonObject.bodies[5].id;
        //    }
        }
        //console.log(jsonObject.bodies[b].joints[3].x*xScale);
        console.log(b);
    }

        //True if scratch is receiving the kinect (but not necessarily data)
    ext.connected = function()
    {
        if(status == 0){
            return false;
        }

        if(status == 1 || 2){
            return true;
        }
    };

    //m: the body chosen (Body 1-6)
    //True if scratch is receiving the chosen body data
    ext.tracked = function(body)
    {
        var i = -1;
        switch(body){
            case 'Body 1': i = 0;
                break;
            case 'Body 2': i = 1;
                break;
            case 'Body 3': i = 2;
                break;
            case 'Body 4': i = 3;
                break;
            case 'Body 5': i = 4;
                break;
            case 'Body 6': i = 5;
                break;
        }

        return jsonObject.bodies[i].id != 0;
    };

    //l: the body chosen (Body 1-6)
    //d: which handstate (left or right)
    //Outputs the left handstate of the selected body
    ext.handdebug = function(body,direction)
    {
        var i;
        switch(body){
            case 'Body 1': i=0;
                break;
            case 'Body 2': i=1;
                break;
            case 'Body 3': i=2;
                break;
            case 'Body 4': i=3;
                break;
            case 'Body 5': i=4;
                break;
            case 'Body 6': i=5;
                break;
        }

        switch(direction)
        {
            case 'Left': return jsonObject.bodies[i].lhandstate;
            case 'Right': return jsonObject.bodies[i].rhandstate;
        }
    }

    //l: The selected body (Body 1-6)
    //d: Which handstate (left or right)
    //n: The selected handstate (Unknown, Not Tracked, Open, Closed, Lasso)
    //Returns true if the selected bodies left handstate is the same as block selected one.
    ext.handstate = function(body,direction,handstate)
    {
        var i;
        var j;
        switch(body){
            case 'Body 1': i=0;
                break;
            case 'Body 2': i=1;
                break;
            case 'Body 3': i=2;
                break;
            case 'Body 4': i=3;
                break;
            case 'Body 5': i=4;
                break;
            case 'Body 6': i=5;
                break;
        }

        switch(handstate)
        {
            case 'Unknown': j = 0;
                break;
            case 'Not Tracked': j = 1;
                break;
            case 'Open': j = 2;
                break;
            case 'Closed': j = 3;
                break;
            case 'Lasso': j = 4;
                break;
        }

        switch(direction)
        {
            case 'Left': return jsonObject.bodies[i].lhandstate == j;
            case 'Right': return jsonObject.bodies[i].rhandstate == j;
        }
    }

    //l: The body chosen (Body 1-6).
    //k1: The joint chosen (All joint the kinect v2 tracks).
    //x: The chosen coordinate (x, y, or z).
    //Gets the coordinate chosen from the joint chosen from the body chosen
    ext.joints = function(body,joint,coordinate)
    {
        var a = -1;
        var b = -1;

        switch(joint){
            case 'Left Ankle': a=14;
                break;
            case 'Right Ankle': a=18;
                break;
            case 'Left Elbow': a=5;
                break;
            case 'Right Elbow': a=9;
                break;
            case 'Left Foot': a=15;
                break;
            case 'Right Foot': a=19;
                break;
            case 'Left Hand': a=7;
                break;
            case 'Right Hand': a=11;
                break;
            case 'Left Hand Tip': a=21;
                break;
            case 'Right Hand Tip': a=23;
                break;
            case 'Head': a=3;
                break;
            case 'Left Hip': a=12;
                break;
            case 'Right Hip': a=16;
                break;
            case 'Left Knee': a=13;
                break;
            case 'Right Knee': a=17;
                break;
            case 'Neck': a=2;
                break;
            case 'Left Shoulder': a=4;
                break;
            case 'Right Shoulder': a=8;
                break;
            case 'Spine Base': a=0;
                break;
            case 'Spine Middle': a=1;
                break;
            case 'Spine Shoulder': a=20;
                break;
            case 'Left Thumb': a=22;
                break;
            case 'Right Thumb': a=24;
                break;
            case 'Left Wrist': a=6;
                break;
            case 'Right Wrist': a=10;
                break;
        }

        switch(body){
            case 'Body 1': b=0;
                break;
            case 'Body 2': b=1;
                break;
            case 'Body 3': b=2;
                break;
            case 'Body 4': b=3;
                break;
            case 'Body 5': b=4;
                break;
            case 'Body 6': b=5;
                break;
        }

        switch(coordinate){
            case 'x': return jsonObject.bodies[b].joints[a].x*xScale;
            case 'y': return jsonObject.bodies[b].joints[a].y*yScale;
            case 'z': return jsonObject.bodies[b].joints[a].z*zScale;
        }
    }

    // Register the extension
    ScratchExtensions.register('SkelScratch', descriptor, ext);
})({});<|endoftext|>


<commit_before>"use strict";

var
  Socket = require('net').Socket,
  EventEmitter = require('events').EventEmitter,
  Promise = require('a-promise'),
  RedisProto = require('redis-proto'),
  Commands = require('../Dist/Commands.js');
class Redis extends EventEmitter{
  constructor(){
    super();

    let Me = this;
    this.Socket = new Socket();
    this.Socket.on('data', function(Buffer){
      try {
        Buffer = RedisProto.Decode(Buffer.toString());
        if(Me.Expecting) Me.Expecting[0](Buffer);
        else if(Buffer.length === 3 && Buffer[0] === 'message'){
          Me.emit('message', Buffer[1], Buffer[2]);
          Me.emit('message:' + Buffer[1], Buffer[2]);
        }
      } catch (err){
        // Assign new Trace
        err = new Error(err.message);
        if(Me.Expecting) Me.Expecting[1](err);
        else Me.emit('error', err);
      }
      Me.Expecting = null;
    });
    this.Expecting = null;
  }
  connect(Host, Port){
    Host = Host || '127.0.0.1';
    Port = Port || 6379;
    let Me = this;
    return new Promise(function(Resolve){
      Me.Socket.connect(Port, Host, Resolve);
    });
  }
  ref(){ this.Socket.ref() }
  unref(){ this.Socket.unref() }
  close(){ this.Socket.close() }
}
Commands.forEach(function(Entry){
  let Execute = function(){
    Array.prototype.unshift.call(arguments, Entry);
    let Callback = null;
    if(typeof arguments[arguments.length - 1] === 'function'){
      Callback = Array.prototype.pop.call(arguments);
    }
    let Encoded = RedisProto.Encode(arguments);
    let Me = this;
    let MyPromise = new Promise(function(Resolve, Reject){
      Me.Socket.write(Encoded + "\r\n", 'utf8', function(){
        Me.Expecting = [Resolve, Reject];
      });
    });
    if(Callback === null){
      return MyPromise;
    } else {
      MyPromise.then(function(){
        Callback(null, arguments);
      }, function(Error){
        Callback(Error, null);
      });
    }
  };
  Redis.prototype[Entry] = Execute;
  Redis.prototype[Entry.toLowerCase()] = Execute;
});

Redis.prototype.end = Redis.prototype.close;
module.exports = Redis;<commit_msg>:racehorse: Avoid creating a promise object when not required<commit_after>"use strict";

var
  Socket = require('net').Socket,
  EventEmitter = require('events').EventEmitter,
  Promise = require('a-promise'),
  RedisProto = require('redis-proto'),
  Commands = require('../Dist/Commands.js');
class Redis extends EventEmitter{
  constructor(){
    super();

    let Me = this;
    this.Socket = new Socket();
    this.Socket.on('data', function(Buffer){
      try {
        Buffer = RedisProto.Decode(Buffer.toString());
        if(Me.Expecting) Me.Expecting[0](Buffer);
        else if(Buffer.length === 3 && Buffer[0] === 'message'){
          Me.emit('message', Buffer[1], Buffer[2]);
          Me.emit('message:' + Buffer[1], Buffer[2]);
        }
      } catch (err){
        // Assign new Trace
        err = new Error(err.message);
        if(Me.Expecting) Me.Expecting[1](err);
        else Me.emit('error', err);
      }
      Me.Expecting = null;
    });
    this.Expecting = null;
  }
  connect(Host, Port){
    Host = Host || '127.0.0.1';
    Port = Port || 6379;
    let Me = this;
    return new Promise(function(Resolve){
      Me.Socket.connect(Port, Host, Resolve);
    });
  }
  ref(){ this.Socket.ref() }
  unref(){ this.Socket.unref() }
  close(){ this.Socket.close() }
}
Commands.forEach(function(Entry){
  let Execute = function(){
    Array.prototype.unshift.call(arguments, Entry);
    let Callback = null;
    if(typeof arguments[arguments.length - 1] === 'function'){
      Callback = Array.prototype.pop.call(arguments);
    }
    let Encoded = RedisProto.Encode(arguments);
    let Me = this;
    if(Callback === null){
      return new Promise(function(Resolve, Reject){
        Me.Socket.write(Encoded + "\r\n", 'utf8', function(){
          Me.Expecting = [Resolve, Reject];
        });
      });
    } else {
      Me.Socket.write(Encoded + "\r\n", 'utf8', function(){
        Me.Expecting = [function(){
          Callback(null, arguments);
        }, function(Error){
          Callback(Error, null);
        }];
      });
    }
  };
  Redis.prototype[Entry] = Execute;
  Redis.prototype[Entry.toLowerCase()] = Execute;
});

Redis.prototype.end = Redis.prototype.close;
module.exports = Redis;<|endoftext|>


<commit_before><commit_msg>Add real behavior of the library<commit_after>window.onerror = function () {
  var words = 'aie ouille hurt ouch oops boo cry rah huh oh ahen wow poop'.split(' ');
  var rand = Math.floor((Math.random() * words.length));

  console.log(words[rand]);
};
<|endoftext|>


<commit_before>describe("jQuery.sisyphus", function() {
	var sisyphus, targetForm;

	beforeEach( function() {
		loadFixtures('fixtures.html');
		sisyphus = Sisyphus.getInstance();
		sisyphus.setOptions({});
		targetForm = $( "form:first" );
		sisyphus.protect(targetForm);
	} );

	it( "should return same instances", function() {
		var sisyphus1 = Sisyphus.getInstance(),
			sisyphus2 = Sisyphus.getInstance();
		expect(sisyphus1).toEqual(sisyphus2);
	} );

	it( "should have instances with common optins", function() {
		var sisyphus1 = Sisyphus.getInstance(),
			sisyphus2 = Sisyphus.getInstance();
		sisyphus1.setOptions( { timeout: 5 } );
		sisyphus2.setOptions( { timeout: 15 } );
		expect(sisyphus1.options).toEqual(sisyphus2.options);
	} );

	it( "should return false if Local Storage is unavailable", function() {
	  spyOn(sisyphus, 'isLocalStorageAvailable').andCallFake(function() {return false;});
	  expect(sisyphus.protect(targetForm)).toEqual(false);
	} );

	it( "should save textfield data on key input, if options.timeout is not set", function() {
		spyOn( sisyphus, "saveToLocalStorage" );
		$( ":text:first", targetForm ).trigger( "oninput" );
		expect( sisyphus.saveToLocalStorage ).toHaveBeenCalled();
	} );

	it( "should save textarea data on key input, if options.timeout is not set", function() {
		spyOn( sisyphus, "saveToLocalStorage" );
		$( "textarea:first", targetForm ).trigger( "oninput" );
		expect( sisyphus.saveToLocalStorage ).toHaveBeenCalled();
	} );

	it( "should save checkbox data on change", function() {
		spyOn( sisyphus, "saveToLocalStorage" );
		$( ":checkbox:first", targetForm ).trigger( "change" );
		expect( sisyphus.saveToLocalStorage ).toHaveBeenCalled();
	} );

	it( "should save radio data on change", function() {
		spyOn( sisyphus, "saveToLocalStorage" );
		$( ":radio:first", targetForm ).trigger( "change" );
		expect( sisyphus.saveToLocalStorage ).toHaveBeenCalled();
	} );

	it( "should save select's data on change", function() {
		spyOn( sisyphus, "saveToLocalStorage" );
		$( "select:first", targetForm ).trigger( "change" );
		expect( sisyphus.saveToLocalStorage ).toHaveBeenCalled();
	} );

	it( "should fire callback on saving data to Local Storage", function() {
		spyOn( sisyphus.options, "onSaveCallback" );
		sisyphus.saveToLocalStorage( "key", "value" );
		expect(sisyphus.options.onSaveCallback).toHaveBeenCalled();
	} );

	it( "should fire callback on removing data from Local Storage", function() {
		spyOn( sisyphus.options, "onReleaseDataCallback" );
		sisyphus.releaseData( targetForm.attr( "id" ), targetForm.find( ":text" ) );
		expect(sisyphus.options.onReleaseDataCallback).toHaveBeenCalled();
	} );

});
<commit_msg>tests<commit_after>describe("Sisyphus", function() {
	var sisyphus, targetForm;

	beforeEach( function() {
		loadFixtures('fixtures.html');
		sisyphus = Sisyphus.getInstance();
		sisyphus.setOptions({});
		targetForm = $( "form:first" );
		sisyphus.protect(targetForm);
	} );

	it( "should return same instances", function() {
		var sisyphus1 = Sisyphus.getInstance(),
			sisyphus2 = Sisyphus.getInstance();
		expect(sisyphus1).toEqual(sisyphus2);
	} );

	it( "should have instances with common optins", function() {
		var sisyphus1 = Sisyphus.getInstance(),
			sisyphus2 = Sisyphus.getInstance();
		sisyphus1.setOptions( { timeout: 5 } );
		sisyphus2.setOptions( { timeout: 15 } );
		expect(sisyphus1.options).toEqual(sisyphus2.options);
	} );

	it( "should return false if Local Storage is unavailable", function() {
	  spyOn(sisyphus, 'isLocalStorageAvailable').andCallFake(function() {return false;});
	  expect(sisyphus.protect(targetForm)).toEqual(false);
	} );

	it( "should save textfield data on key input, if options.timeout is not set", function() {
		spyOn( sisyphus, "saveToLocalStorage" );
		$( ":text:first", targetForm ).trigger( "oninput" );
		expect( sisyphus.saveToLocalStorage ).toHaveBeenCalled();
	} );

	it( "should not save all data, but textfield only on key input, if options.timeout is not set", function() {
		spyOn( sisyphus, "saveAllData" );
		$( ":text:first", targetForm ).trigger( "oninput" );
		expect( sisyphus.saveAllData.callCount ).toEqual( 0 );
	} );

	it( "should save textarea data on key input, if options.timeout is not set", function() {
		spyOn( sisyphus, "saveToLocalStorage" );
		$( "textarea:first", targetForm ).trigger( "oninput" );
		expect( sisyphus.saveToLocalStorage ).toHaveBeenCalled();
	} );

	it( "should not save all data, but textarea only on key input, if options.timeout is not set", function() {
		spyOn( sisyphus, "saveAllData" );
		$( "textarea:first", targetForm ).trigger( "oninput" );
		expect( sisyphus.saveAllData.callCount ).toEqual( 0 );
	} );

	it( "should save all data on checkbox change", function() {
		spyOn( sisyphus, "saveAllData" );
		$( ":checkbox:first", targetForm ).trigger( "change" );
		expect( sisyphus.saveAllData ).toHaveBeenCalled();
	} );

	it( "should save all data on radio change", function() {
		spyOn( sisyphus, "saveAllData" );
		$( ":radio:first", targetForm ).trigger( "change" );
		expect( sisyphus.saveAllData ).toHaveBeenCalled();
	} );

	it( "should save all data on select change", function() {
		spyOn( sisyphus, "saveAllData" );
		$( "select:first", targetForm ).trigger( "change" );
		expect( sisyphus.saveAllData ).toHaveBeenCalled();
	} );

	it( "should fire callback ONCE on saving all data to Local Storage", function() {
		spyOn( sisyphus.options, "onSaveCallback" );
		sisyphus.saveAllData();
		expect( sisyphus.options.onSaveCallback.callCount ).toEqual( 1 );
	} );

	it( "should fire callback on saving data to Local Storage", function() {
		spyOn( sisyphus.options, "onSaveCallback" );
		sisyphus.saveToLocalStorage( "key", "value" );
		expect(sisyphus.options.onSaveCallback).toHaveBeenCalled();
	} );

	it( "should fire callback on removing data from Local Storage", function() {
		spyOn( sisyphus.options, "onReleaseDataCallback" );
		sisyphus.releaseData( targetForm.attr( "id" ), targetForm.find( ":text" ) );
		expect(sisyphus.options.onReleaseDataCallback).toHaveBeenCalled();
	} );

});
<|endoftext|>


<commit_before>/*
 * Beech Unit Tests
*/
/*jshint         strict : true, browser : false,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, undef : true,
  white  : true
*/
/*globals require, describe, it, expect, jasmine, beforeEach */

var createObjectTreeProcessor = require('../main');

describe("ObjectTreeProcessor", function() {
  'use strict';

  describe("applyToEach", function() {
    var someFunction;
    var collection;
    var processor;
    var processIt;

    beforeEach(function() {
      someFunction = function () {};
      collection = {
        'one' : 1,
        'two' : someFunction,
        'three' : 'A string value'
      };
      processor = createObjectTreeProcessor(collection);
      processIt = jasmine.createSpy();
    });

    it("applies function to each owned member", function() {
      processor.applyToEach(processIt);
      expect(processIt).toHaveBeenCalledWith('one', 1);
      expect(processIt).toHaveBeenCalledWith('two', someFunction);
      expect(processIt).toHaveBeenCalledWith('three', 'A string value');
      expect(processIt.calls.count()).toEqual(3);
    });

    it("returns ObjectTreeProcessor object", function() {
      var result = processor.applyToEach(processIt);
      expect(result).toBe(processor);
    });

    describe("when object-tree is empty", function() {
      beforeEach(function() {
        collection = {};
        processor = createObjectTreeProcessor(collection);
      });
      it("does not apply function", function() {
        processor.applyToEach(processIt);
        expect(processIt).not.toHaveBeenCalled();
      });
      it("returns ObjectTreeProcessor object", function() {
        var result = processor.applyToEach(processIt);
        expect(result).toBe(processor);
      });
    });

    describe("when object-tree is null", function() {
      beforeEach(function() {
        collection = null;
        processor = createObjectTreeProcessor(collection);
      });
      it("does not apply function", function() {
        processor.applyToEach(processIt);
        expect(processIt).not.toHaveBeenCalled();
      });
      it("returns ObjectTreeProcessor object", function() {
        var result = processor.applyToEach(processIt);
        expect(result).toBe(processor);
      });
    });

    describe("when this-pointer provided", function() {
      var thisContextProvided;
      var thisContextInFunction;

      beforeEach(function() {
        thisContextProvided = {a : 'R'};
        thisContextInFunction = undefined;
        processIt = function (key, value) {
	  thisContextInFunction = this;
          this.a +=  value;
        };
        collection = {b : 'OMA'};
        processor = createObjectTreeProcessor(collection);
      });
      it("applies function bound to this-pointer provided", function() {
        processor.applyToEach(processIt, thisContextProvided);
        expect(thisContextInFunction).toBe(thisContextProvided);
        expect(thisContextProvided.a).toEqual('ROMA');
      });
    });

    describe("when this-pointer not provided", function() {
      var thisContextInFunction;

      beforeEach(function() {
        thisContextInFunction = undefined;
        processIt = function (key, value) {
	  thisContextInFunction = this;
        };
        collection = {b : 'OMA'};
        processor = createObjectTreeProcessor(collection);
      });
      it("applies function bound to null-context", function() {
        processor.applyToEach(processIt);
        expect(thisContextInFunction).toBe(null);
      });
    });
  });
});

<commit_msg>Use *this* for shared context<commit_after>/*
 * Beech Unit Tests
*/
/*jshint         strict : true, browser : false,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, undef : true,
  white  : true
*/
/*globals require, describe, it, expect, jasmine, beforeEach */

var createObjectTreeProcessor = require('../main');

describe("ObjectTreeProcessor", function() {
  'use strict';

  describe("applyToEach", function() {

    beforeEach(function() {
      this.someFunction = function () {};
      this.collection = {
        'one' : 1,
        'two' : this.someFunction,
        'three' : 'A string value'
      };
      this.processor = createObjectTreeProcessor(this.collection);
      this.processIt = jasmine.createSpy();
    });

    it("applies function to each owned member", function() {
      this.processor.applyToEach(this.processIt);
      expect(this.processIt).toHaveBeenCalledWith('one', 1);
      expect(this.processIt).toHaveBeenCalledWith('two', this.someFunction);
      expect(this.processIt).toHaveBeenCalledWith('three', 'A string value');
      expect(this.processIt.calls.count()).toEqual(3);
    });

    it("returns ObjectTreeProcessor object", function() {
      var result = this.processor.applyToEach(this.processIt);
      expect(result).toBe(this.processor);
    });

    describe("when object-tree is empty", function() {
      beforeEach(function() {
        this.collection = {};
        this.processor = createObjectTreeProcessor(this.collection);
      });
      it("does not apply function", function() {
        this.processor.applyToEach(this.processIt);
        expect(this.processIt).not.toHaveBeenCalled();
      });
      it("returns ObjectTreeProcessor object", function() {
        var result = this.processor.applyToEach(this.processIt);
        expect(result).toBe(this.processor);
      });
    });

    describe("when object-tree is null", function() {
      beforeEach(function() {
        this.collection = null;
        this.processor = createObjectTreeProcessor(this.collection);
      });
      it("does not apply function", function() {
        this.processor.applyToEach(this.processIt);
        expect(this.processIt).not.toHaveBeenCalled();
      });
      it("returns ObjectTreeProcessor object", function() {
        var result = this.processor.applyToEach(this.processIt);
        expect(result).toBe(this.processor);
      });
    });

    describe("when this-pointer provided", function() {
      var thisContextProvided;
      var thisContextInFunction;

      beforeEach(function() {
        thisContextProvided = {a : 'R'};
        thisContextInFunction = undefined;
        this.processIt = function (key, value) {
	  thisContextInFunction = this;
          this.a +=  value;
        };
        this.collection = {b : 'OMA'};
        this.processor = createObjectTreeProcessor(this.collection);
      });
      it("applies function bound to this-pointer provided", function() {
        this.processor.applyToEach(this.processIt, thisContextProvided);
        expect(thisContextInFunction).toBe(thisContextProvided);
        expect(thisContextProvided.a).toEqual('ROMA');
      });
    });

    describe("when this-pointer not provided", function() {
      var thisContextInFunction;

      beforeEach(function() {
        thisContextInFunction = undefined;
        this.processIt = function (key, value) {
	  thisContextInFunction = this;
        };
        this.collection = {b : 'OMA'};
        this.processor = createObjectTreeProcessor(this.collection);
      });
      it("applies function bound to null-context", function() {
        this.processor.applyToEach(this.processIt);
        expect(thisContextInFunction).toBe(null);
      });
    });
  });
});

<|endoftext|>


<commit_before>(function($) {

    /*!
   * spineless.js - A simple MVC stack without the need of a backbone.
   * https://github.com/heavysixer/spineless
   */
    var Spineless = (typeof module !== "undefined" && module.exports) || {};
    (function(opts) {
        opts.name = "spineless.js";
        opts.version = "0.1.0";
        opts.render = render;
        var that = this;
        var templates = function(method, locals) {
            if (locals !== undefined) {
                locals = $.parseJSON(locals);
            }
            var methods = {
                _default: function() {
                    return $.extend(true, {},
                    locals);
                }
            };
            return (methods.hasOwnProperty(method)) ? methods[method](locals) : methods._default(locals);
        };

        var parseRoute = function(str) {
            var hsh = $.extend(true, {},
            {
                controller: 'application',
                action: 'index'
            });
            while (str.charAt(0) == '/') {
                str = str.substr(1);
            }

            if (str.length > 0) {
                $.each(str.split('/'),
                function(i, e) {
                    if (i === 0) {
                        hsh.controller = e;
                    }
                    if (i === 1) {
                        hsh.action = e;
                    }
                });
            }
            return hsh;
        };

        var renderTemplate = function(view, locals) {
            var name,
            template;
            name = $(view).attr('data-template');
            if (name !== undefined) {
                locals = $(view).attr('data-locals');
                template = $('.templates *[data-template-name=' + name + ']').html();
                view.html($.mustache(template, templates(name, locals)));
            }
        };

        var renderView = function(controller, action, params) {
            var view,
            kontroller;
            kontroller = $(".controller[data-controller=" + controller + "]");
            view = $(".controller[data-controller=" + controller + "] .view[data-action=" + action + "]");
            $('.view.active').removeClass('active');
            $('.controller.active').removeClass('active');
            if ($(".container[data-controller=" + controller + "]") && $(".view[data-action=" + action + "]")) {
                $.each(view.find("*[data-template]"),
                function(i, e) {
                    renderTemplate($(e));
                });
                view.addClass('active');
                kontroller.addClass("active");
            }
        };

        var route = function(element) {
            var url;
            url = element.attr('href') || $(element).attr('data-href');
            var route = parseRoute(url);
            render(route.controller, route.action);
        };

        function render(controller, action, params) {
            $('body').removeClass('rendered');
            $('html,body').animate({
                scrollTop: 0
            },
            1);
            renderView(controller, action, params);
            $('body').attr('data-controller', controller);
            $('body').attr('data-action', action);
            $('body').addClass('rendered');
        }
        function init(options){
          $(document).on('click', '.route',
          function(event) {
              event.preventDefault();
              route($(this));
          });
        }
        init(opts)
    })(Spineless);
    $.spineless = function(controller, action, params) {
        return Spineless;
    };
    $.fn.spineless = function(controller, action, params) {
        return $(this).map(function(i, elm) {
            $.spineless.render(controller, action, params);
        });
    };
})(jQuery);<commit_msg>Remove the node.js centric coding since it is not really built for that paradigm.<commit_after>(function($) {

    /*!
   * spineless.js - A simple MVC stack without the need of a backbone.
   * https://github.com/heavysixer/spineless
   */
    var Spineless = function(options) {
        var opts = (typeof options !== "undefined") || {};
        opts.render = render;
        var that = this;
        var templates = function(method, locals) {
            if (locals !== undefined) {
                locals = $.parseJSON(locals);
            }
            var methods = {
                _default: function() {
                    return $.extend(true, {},
                    locals);
                }
            };
            return (methods.hasOwnProperty(method)) ? methods[method](locals) : methods._default(locals);
        };

        var parseRoute = function(str) {
            var hsh = $.extend(true, {},
            {
                controller: 'application',
                action: 'index'
            });
            while (str.charAt(0) == '/') {
                str = str.substr(1);
            }

            if (str.length > 0) {
                $.each(str.split('/'),
                function(i, e) {
                    if (i === 0) {
                        hsh.controller = e;
                    }
                    if (i === 1) {
                        hsh.action = e;
                    }
                });
            }
            return hsh;
        };

        var renderTemplate = function(view, locals) {
            var name,
            template;
            name = $(view).attr('data-template');
            if (name !== undefined) {
                locals = $(view).attr('data-locals');
                template = $('.templates *[data-template-name=' + name + ']').html();
                view.html($.mustache(template, templates(name, locals)));
            }
        };

        var renderView = function(controller, action, params) {
            var view,
            kontroller;
            kontroller = $(".controller[data-controller=" + controller + "]");
            view = $(".controller[data-controller=" + controller + "] .view[data-action=" + action + "]");
            $('.view.active').removeClass('active');
            $('.controller.active').removeClass('active');
            if ($(".container[data-controller=" + controller + "]") && $(".view[data-action=" + action + "]")) {
                $.each(view.find("*[data-template]"),
                function(i, e) {
                    renderTemplate($(e));
                });
                view.addClass('active');
                kontroller.addClass("active");
            }
        };

        var route = function(element) {
            var url;
            url = element.attr('href') || $(element).attr('data-href');
            var route = parseRoute(url);
            render(route.controller, route.action);
        };

        function render(controller, action, params) {
            $('body').removeClass('rendered');
            $('html,body').animate({
                scrollTop: 0
            },
            1);
            renderView(controller, action, params);
            $('body').attr('data-controller', controller);
            $('body').attr('data-action', action);
            $('body').addClass('rendered');
        }
        function init(options){
          $(document).on('click', '.route',
          function(event) {
              event.preventDefault();
              route($(this));
          });
        }
        init(opts);
        return opts;
    };
    $.spineless = function(opts) {
        return new Spineless(opts);
    };
})(jQuery);<|endoftext|>


<commit_before>//<!--  Contains functions to splatter stuff onto overlay based on game events -->
//

function splatterSplash(x, y, color, size) {

	var splats = [];

	splatterCircle((x + 10), (y + 10), randomSaturate(color), size);
};

function splatterCircle(x, y, color, size) {
	console.log("splatterCircle called");
	overlayCtx.beginPath();
  overlayCtx.arc(x, y, size, 0, 2 * Math.PI, false);
  overlayCtx.fillStyle = color;
  overlayCtx.fill();
};

function randomSaturate(color) {
	var _number = (Math.random() * 100) - 50;
	return tinycolor.saturate(color, _number).toHexString();
};

};<commit_msg>Random analog WIP<commit_after>//<!--  Contains functions to splatter stuff onto overlay based on game events -->
//

function splat(x, y, color, size) {
	this.x = x;
	this.y = y;
	this.color = color;
	this.size = (size * Math.random());

};

function splatterSplash(x, y, color, size) {

	var splats = [];

	splatterCircle((x + 10), (y + 10), randomSaturate(color), size);
};

function splatterCircle(x, y, color, size) {
	console.log("splatterCircle called");
	overlayCtx.beginPath();
  overlayCtx.arc(x, y, size, 0, 2 * Math.PI, false);
  overlayCtx.fillStyle = color;
  overlayCtx.fill();
};

function randomSaturate(color) {
	var _number = (Math.random() * 100) - 50;
	return tinycolor.saturate(color, _number).toHexString();
};

function randomAnalog(color) {

	var _colors = tinycolor.analogous(color, results = 6, slices = 30)
	var _number = to_i((Math.random() * 6));
	console.log(_number);
	console.log(_colors[_number].toHexString());
	return tinycolor.saturate(color, _number).toHexString();
};

function to_i(_value)  {
  // uses Bitwise operator to convert value to int. Allegedly faster than Math methods.
  return _value | 0
};

randomAnalog('green');
randomAnalog('green');
randomAnalog('green');
randomAnalog('green');
randomAnalog('green');
randomAnalog('green');
randomAnalog('green');
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const yt = require('ytdl-core');
const fs = require('fs');
const now = require('performance-now');
const tokens = require('./tokens.json');
const YouTube = require('youtube-node');
const youTube = new YouTube();
youTube.setKey(tokens.yt_token);
const client = new Discord.Client({fetchAllMembers: true})
const userData = JSON.parse(fs.readFileSync('./songs/spotify.json'));
const oauth = 'https://discordapp.com/oauth2/authorize?client_id=224495611741863936&scope=bot&permissions=37088320';

let queue = {};

const commands = {
 'play': (msg) => {
  	if (userData[msg.author.id] === undefined) return msg.reply("You don't have any songs in your playlist! Add some with `" + tokens.prefix + "add`");
  	if (!msg.guild.voiceConnection) return commands.join(msg).then(() => commands.play(msg));

  let dispatcher;

  (function play(song) {
   if (song === undefined) return msg.channel.sendMessage("You don't have any songs in your playlist! Add some with `" + tokens.prefix + "add`").then(() => {

    msg.member.voiceChannel.leave();
   });
   msg.channel.sendMessage(`Playing: **${song.title}** from user: **${msg.author.username}**'s playlist.`);
   dispatcher = msg.guild.voiceConnection.playStream(yt(song.url, {
    audioonly: true
   }) /*, { passes : tokens.passes }*/ );
   let collector = msg.channel.createCollector(m => m);
   collector.on('message', m => {
if (!m.content.startsWith(`${tokens.prefix}`)) {
  msg.channel.sendMessage(" ");
	   }
 if (m.author.bot) {
msg.channel.sendMessage(" ");
	}
if(m.author === client.user) {
msg.channel.sendMessage(" ");
	}
    if (m.content.startsWith(tokens.prefix + 'pause')) {
     msg.channel.sendMessage(':pause_button: Paused.').then(() => {
      dispatcher.pause();
     });
    } else if (m.content.startsWith(tokens.prefix + 'resume')) {
     msg.channel.sendMessage(':play_pause: Resumed.').then(() => {
      dispatcher.resume();
     });
    } else if (m.content.startsWith(tokens.prefix + 'skip')) {
     msg.channel.sendMessage(':arrow_forward: Skipped.').then(() => {
      dispatcher.end();
     });
    } else if (m.content.startsWith(tokens.prefix + 'volume+')) {
     if (Math.round(dispatcher.volume * 50) >= 100) return msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
     dispatcher.setVolume(Math.min((dispatcher.volume * 50 + (2 * (m.content.split('+').length - 1))) / 50, 2));
     msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
    } else if (m.content.startsWith(tokens.prefix + 'volume-')) {
     if (Math.round(dispatcher.volume * 50) <= 0) return msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
     dispatcher.setVolume(Math.max((dispatcher.volume * 50 - (2 * (m.content.split('-').length - 1))) / 50, 0));
     msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
    } else if (m.content.startsWith(tokens.prefix + 'time')) {
     msg.channel.sendMessage(`:clock1: Time: ${Math.floor(dispatcher.time / 60000)}:${Math.floor((dispatcher.time % 60000)/1000) <10 ? '0'+Math.floor((dispatcher.time % 60000)/1000) : Math.floor((dispatcher.time % 60000)/1000)}`);
    }
   });
   dispatcher.on('end', () => {
    collector.stop();
    play(userData[msg.author.id].songs[Math.floor(Math.random() * userData[msg.author.id].songs.length)]);
   });
   dispatcher.on('error', (err) => {
    return msg.channel.sendMessage('error: ' + err).then(() => {
     collector.stop();
     play(userData[msg.author.id].songs[Math.floor(Math.random() * userData[msg.author.id].songs.length)]);
    });
   });
  })(userData[msg.author.id].songs[Math.floor(Math.random() * userData[msg.author.id].songs.length)]);
 },
 'join': (msg) => {
  return new Promise((resolve, reject) => {
  const voiceChannel = msg.member.voiceChannel;
   if (!voiceChannel || voiceChannel.type !== 'voice') return msg.reply(':no_entry_sign: I couldn\'t connect to your voice channel.');
   voiceChannel.join().then(connection => resolve(connection)).catch(err => reject(err));
  });
  msg.channel.sendMessage(":white_check_mark: I've successfully joined your voice channel.");
 },
 'add': (msg) => {
  function addFromUrl(url) {
   msg.channel.sendMessage("*Adding...*");
   if (url == '' || url === undefined) return msg.channel.sendMessage(`You must add a YouTube video url after ${tokens.prefix}add`);
   yt.getInfo(url, (err, info) => {
    if (err) return msg.channel.sendMessage(':no_entry_sign: Invalid YouTube Link: ' + err);
    if (!userData[msg.author.id]) userData[msg.author.id] = {
     songs: []
    };
    userData[msg.author.id].songs.push({
     url: url,
     title: info.title
    });
    let updateValue = JSON.stringify(userData, null, 2);
    fs.writeFileSync('./songs/spotify.json', updateValue);
    msg.channel.sendMessage(`:white_check_mark: Added **${info.title}** to your playlist.`);
   });
  }

  function addFromQuery(query) {
   youTube.search(query, 2, function(error, result) {
    if (error) {
     msg.channel.sendMessage(`:no_entry_sign: **Error:**\n${error}`);
    } else {
     var url = `https://www.youtube.com/watch?v=${result.items[0]["id"].videoId}`;
     addFromUrl(url);
    }
   });
  }

  if (msg.content === tokens.prefix + "add") return;
  var url = msg.content.split(' ')[1];
  if(url.includes("https://youtube.com/playlist") || url.includes("https://www.youtube.com/playlist") || url.includes("http://youtube.com/playlist") || url.includes("http://www.youtube.com/playlist")) return msg.channel.sendMessage(":no_entry_sign: You can't add a Youtube playlist a song.");
  if (url.includes("https://youtube.com/watch") || url.includes("https://www.youtube.com/watch") || url.includes("http://youtube.com/watch") || url.includes("http://www.youtube.com/watch") || url.includes("https://youtu.be/") || url.includes("https://www.youtu.be/") || url.includes("http://youtu.be/") || url.includes("http://www.youtu.be/")) {
   addFromUrl(url);
  } else {
   var query = msg.content.replace(tokens.prefix + 'add', '');
   addFromQuery(query);
  }
 },
 'songs': (msg) => {
  if (!userData[msg.author.id] === undefined) return msg.channel.sendMessage("You don't have any songs in your playlist! Add some with `" + tokens.prefix + "add`");
  let tosend = [];
  userData[msg.author.id].songs.forEach((song, i) => {
   tosend.push(`${i+1}. ${song.title}`);
  });
  msg.channel.sendMessage(`__**${msg.author.username}'s Music Playlist:**__ Currently **${tosend.length}** songs in it ${(tosend.length > 15 ? '*[Only next 15 shown]*' : '')}\n\`\`\`${tosend.slice(0,15).join('\n')}\`\`\``);
 },
 'ping': (msg) => {
  var start = now();
  msg.channel.sendMessage("*Pinging...*").then(msg => {
   var end = now();msg.edit(`Pong! **${(end - start).toFixed(0)}ms**`);
  });
 },
 'help': (msg) => {
  msg.reply("I've sent a list of commands to you. Check your DM's.");
  var help = [
   "Prefix is `s.`",
   "**help** = Sends this message.",
   "**join** = Joins the voice channel you're connected to.",
   "**play** = Starts playing a song in your playlist.",
   "**skip** = Skips the currently playing song.",
   "**pause** = Pauses the currently playing song.",
   "**resume** = Resumes a paused song.",
   "**stop** = Stops the currently playing song and leaves the voice channel.",
   "**volume+[+]** = Increases the volume of a song.",
   "**volume-[-]** = Decreases the volume of a song.",
   "**time** = Displays the play time of the song that's playing.",
   "**add <song>** = Adds the specified song to your custom playlist. *(YouTube videos only)*",
   "**songs** = List's all of your songs.",
   "**invite** = Sends the OAuth link to invite me to your server.",
   "**ping** = Pings the bot.",
   "**connections** = List's the amount of voice channels Spotify is connected to.",
   "**servers** = List's the amount of servers Spotify is on.",
  ];
  msg.author.sendMessage(help);
 },
 'connections': (msg) => {
  msg.channel.sendMessage(`Currently playing music in **${client.voiceConnections.size}** voice channels!`);
 },
 'servers': (msg) => {
  msg.channel.sendMessage(`On **${client.guilds.size}** servers!`);
 },
 'invite': (msg) => {
  msg.channel.sendMessage(`Feel free to invite me using this: ${oauth}`)
 },
 'restart': (msg) => {
  if (!msg.author.id === '193378071141810176') return;
  if (!msg.author.id === '138431969418543104') return;
  msg.channel.sendMessage("```css\nRestarting...```");
  console.log("Restarting...");
  setTimeout(function() {
   console.log(process.exit(0));
  }, 400);
 },
 'stats': (msg) => {
  var start = now();
  let embed = new Discord.RichEmbed();
  msg.channel.sendMessage("```+ Fetching...```")
  .then(msg => {
   var end = now();
   var milliseconds = parseInt((client.uptime % 1000) / 100),
    seconds = parseInt((client.uptime / 1000) % 60),
    minutes = parseInt((client.uptime / (1000 * 60)) % 60),
    hours = parseInt((client.uptime / (1000 * 60 * 60)) % 24);
   hours = (hours < 10) ? "0" + hours : hours;
   minutes = (minutes < 10) ? "0" + minutes : minutes;
   seconds = (seconds < 10) ? "0" + seconds : seconds;
   var uptime = "" + hours + " hours, " + minutes + " minutes and " + seconds + "." + milliseconds + " seconds";
   embed.setColor(0x00FFE1)
   .setAuthor(client.user.username, client.user.avatarURL)
   .setTitle("Spotify Stats:")
   .addField('• Uptime: ', `${uptime}`, true)
   .addField('• Servers: ', `${client.guilds.size}`, true)
   .addField('• Channels: ', `${client.channels.size.toLocaleString()}`, true)
   .addField('• Users: ', `${client.users.size.toLocaleString()}`, true)
   .addField('• Ping: ', `${(end - start).toFixed(0)} MS`, true)
   .addField('• CPU Speed: ', '2.4GHz', true)
   .addField(`• Mem. Usage: `, `${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB`, true)
   msg.channel.sendEmbed(embed);
   return msg.edit('```Done!```');
  }).catch(e => {
   msg.channel.sendMessage(":no_entry_sign: There was an error! Report this please:\n\n" + e);
  });
 }
};

client.on('ready', () => {
 client.user.setGame(`Custom playlists! s.help | s.invite`, 'https://www.twitch.tv/imaqtpie');
 console.log('Spotify bot online and ready!');
});

client.on('message', msg => {
 if (!msg.content.startsWith(tokens.prefix)) return;
 if (commands.hasOwnProperty(msg.content.toLowerCase().slice(tokens.prefix.length).split(' ')[0])) commands[msg.content.toLowerCase().slice(tokens.prefix.length).split(' ')[0]](msg);
});
client.login(tokens.d_token);
<commit_msg>Update app.js<commit_after>const Discord = require('discord.js');
const yt = require('ytdl-core');
const fs = require('fs');
const now = require('performance-now');
const tokens = require('./tokens.json');
const YouTube = require('youtube-node');
const youTube = new YouTube();
youTube.setKey(tokens.yt_token);
const client = new Discord.Client({fetchAllMembers: true})
const userData = JSON.parse(fs.readFileSync('./songs/spotify.json'));
const oauth = 'YOUR_DISCORD_BOT_OUATH_LINK';

let queue = {};

const commands = {
 'play': (msg) => {
  	if (userData[msg.author.id] === undefined) return msg.reply("You don't have any songs in your playlist! Add some with `" + tokens.prefix + "add`");
  	if (!msg.guild.voiceConnection) return commands.join(msg).then(() => commands.play(msg));

  let dispatcher;

  (function play(song) {
   if (song === undefined) return msg.channel.sendMessage("You don't have any songs in your playlist! Add some with `" + tokens.prefix + "add`").then(() => {

    msg.member.voiceChannel.leave();
   });
   msg.channel.sendMessage(`Playing: **${song.title}** from user: **${msg.author.username}**'s playlist.`);
   dispatcher = msg.guild.voiceConnection.playStream(yt(song.url, {
    audioonly: true
   }) /*, { passes : tokens.passes }*/ );
   let collector = msg.channel.createCollector(m => m);
   collector.on('message', m => {
if (!m.content.startsWith(`${tokens.prefix}`)) {
  msg.channel.sendMessage(" ");
	   }
 if (m.author.bot) {
msg.channel.sendMessage(" ");
	}
if(m.author === client.user) {
msg.channel.sendMessage(" ");
	}
    if (m.content.startsWith(tokens.prefix + 'pause')) {
     msg.channel.sendMessage(':pause_button: Paused.').then(() => {
      dispatcher.pause();
     });
    } else if (m.content.startsWith(tokens.prefix + 'resume')) {
     msg.channel.sendMessage(':play_pause: Resumed.').then(() => {
      dispatcher.resume();
     });
    } else if (m.content.startsWith(tokens.prefix + 'skip')) {
     msg.channel.sendMessage(':arrow_forward: Skipped.').then(() => {
      dispatcher.end();
     });
    } else if (m.content.startsWith(tokens.prefix + 'volume+')) {
     if (Math.round(dispatcher.volume * 50) >= 100) return msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
     dispatcher.setVolume(Math.min((dispatcher.volume * 50 + (2 * (m.content.split('+').length - 1))) / 50, 2));
     msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
    } else if (m.content.startsWith(tokens.prefix + 'volume-')) {
     if (Math.round(dispatcher.volume * 50) <= 0) return msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
     dispatcher.setVolume(Math.max((dispatcher.volume * 50 - (2 * (m.content.split('-').length - 1))) / 50, 0));
     msg.channel.sendMessage(`:speaker: Volume: ${Math.round(dispatcher.volume*50)}%`);
    } else if (m.content.startsWith(tokens.prefix + 'time')) {
     msg.channel.sendMessage(`:clock1: Time: ${Math.floor(dispatcher.time / 60000)}:${Math.floor((dispatcher.time % 60000)/1000) <10 ? '0'+Math.floor((dispatcher.time % 60000)/1000) : Math.floor((dispatcher.time % 60000)/1000)}`);
    }
   });
   dispatcher.on('end', () => {
    collector.stop();
    play(userData[msg.author.id].songs[Math.floor(Math.random() * userData[msg.author.id].songs.length)]);
   });
   dispatcher.on('error', (err) => {
    return msg.channel.sendMessage('error: ' + err).then(() => {
     collector.stop();
     play(userData[msg.author.id].songs[Math.floor(Math.random() * userData[msg.author.id].songs.length)]);
    });
   });
  })(userData[msg.author.id].songs[Math.floor(Math.random() * userData[msg.author.id].songs.length)]);
 },
 'join': (msg) => {
  return new Promise((resolve, reject) => {
  const voiceChannel = msg.member.voiceChannel;
   if (!voiceChannel || voiceChannel.type !== 'voice') return msg.reply(':no_entry_sign: I couldn\'t connect to your voice channel.');
   voiceChannel.join().then(connection => resolve(connection)).catch(err => reject(err));
  });
  msg.channel.sendMessage(":white_check_mark: I've successfully joined your voice channel.");
 },
 'add': (msg) => {
  function addFromUrl(url) {
   msg.channel.sendMessage("*Adding...*");
   if (url == '' || url === undefined) return msg.channel.sendMessage(`You must add a YouTube video url after ${tokens.prefix}add`);
   yt.getInfo(url, (err, info) => {
    if (err) return msg.channel.sendMessage(':no_entry_sign: Invalid YouTube Link: ' + err);
    if (!userData[msg.author.id]) userData[msg.author.id] = {
     songs: []
    };
    userData[msg.author.id].songs.push({
     url: url,
     title: info.title
    });
    let updateValue = JSON.stringify(userData, null, 2);
    fs.writeFileSync('./songs/spotify.json', updateValue);
    msg.channel.sendMessage(`:white_check_mark: Added **${info.title}** to your playlist.`);
   });
  }

  function addFromQuery(query) {
   youTube.search(query, 2, function(error, result) {
    if (error) {
     msg.channel.sendMessage(`:no_entry_sign: **Error:**\n${error}`);
    } else {
     var url = `https://www.youtube.com/watch?v=${result.items[0]["id"].videoId}`;
     addFromUrl(url);
    }
   });
  }

  if (msg.content === tokens.prefix + "add") return;
  var url = msg.content.split(' ')[1];
  if(url.includes("https://youtube.com/playlist") || url.includes("https://www.youtube.com/playlist") || url.includes("http://youtube.com/playlist") || url.includes("http://www.youtube.com/playlist")) return msg.channel.sendMessage(":no_entry_sign: You can't add a Youtube playlist a song.");
  if (url.includes("https://youtube.com/watch") || url.includes("https://www.youtube.com/watch") || url.includes("http://youtube.com/watch") || url.includes("http://www.youtube.com/watch") || url.includes("https://youtu.be/") || url.includes("https://www.youtu.be/") || url.includes("http://youtu.be/") || url.includes("http://www.youtu.be/")) {
   addFromUrl(url);
  } else {
   var query = msg.content.replace(tokens.prefix + 'add', '');
   addFromQuery(query);
  }
 },
 'songs': (msg) => {
  if (!userData[msg.author.id] === undefined) return msg.channel.sendMessage("You don't have any songs in your playlist! Add some with `" + tokens.prefix + "add`");
  let tosend = [];
  userData[msg.author.id].songs.forEach((song, i) => {
   tosend.push(`${i+1}. ${song.title}`);
  });
  msg.channel.sendMessage(`__**${msg.author.username}'s Music Playlist:**__ Currently **${tosend.length}** songs in it ${(tosend.length > 15 ? '*[Only next 15 shown]*' : '')}\n\`\`\`${tosend.slice(0,15).join('\n')}\`\`\``);
 },
 'ping': (msg) => {
  var start = now();
  msg.channel.sendMessage("*Pinging...*").then(msg => {
   var end = now();msg.edit(`Pong! **${(end - start).toFixed(0)}ms**`);
  });
 },
 'help': (msg) => {
  msg.reply("I've sent a list of commands to you. Check your DM's.");
  var help = [
   "Prefix is `s.`",
   "**help** = Sends this message.",
   "**join** = Joins the voice channel you're connected to.",
   "**play** = Starts playing a song in your playlist.",
   "**skip** = Skips the currently playing song.",
   "**pause** = Pauses the currently playing song.",
   "**resume** = Resumes a paused song.",
   "**stop** = Stops the currently playing song and leaves the voice channel.",
   "**volume+[+]** = Increases the volume of a song.",
   "**volume-[-]** = Decreases the volume of a song.",
   "**time** = Displays the play time of the song that's playing.",
   "**add <song>** = Adds the specified song to your custom playlist. *(YouTube videos only)*",
   "**songs** = List's all of your songs.",
   "**invite** = Sends the OAuth link to invite me to your server.",
   "**ping** = Pings the bot.",
   "**connections** = List's the amount of voice channels Spotify is connected to.",
   "**servers** = List's the amount of servers Spotify is on.",
  ];
  msg.author.sendMessage(help);
 },
 'connections': (msg) => {
  msg.channel.sendMessage(`Currently playing music in **${client.voiceConnections.size}** voice channels!`);
 },
 'servers': (msg) => {
  msg.channel.sendMessage(`On **${client.guilds.size}** servers!`);
 },
 'invite': (msg) => {
  msg.channel.sendMessage(`Feel free to invite me using this: ${oauth}`)
 },
 'restart': (msg) => {
  if (!msg.author.id === '193378071141810176') return;
  if (!msg.author.id === '138431969418543104') return;
  msg.channel.sendMessage("```css\nRestarting...```");
  console.log("Restarting...");
  setTimeout(function() {
   console.log(process.exit(0));
  }, 400);
 },
 'stats': (msg) => {
  var start = now();
  let embed = new Discord.RichEmbed();
  msg.channel.sendMessage("```+ Fetching...```")
  .then(msg => {
   var end = now();
   var milliseconds = parseInt((client.uptime % 1000) / 100),
    seconds = parseInt((client.uptime / 1000) % 60),
    minutes = parseInt((client.uptime / (1000 * 60)) % 60),
    hours = parseInt((client.uptime / (1000 * 60 * 60)) % 24);
   hours = (hours < 10) ? "0" + hours : hours;
   minutes = (minutes < 10) ? "0" + minutes : minutes;
   seconds = (seconds < 10) ? "0" + seconds : seconds;
   var uptime = "" + hours + " hours, " + minutes + " minutes and " + seconds + "." + milliseconds + " seconds";
   embed.setColor(0x00FFE1)
   .setAuthor(client.user.username, client.user.avatarURL)
   .setTitle("Spotify Stats:")
   .addField('• Uptime: ', `${uptime}`, true)
   .addField('• Servers: ', `${client.guilds.size}`, true)
   .addField('• Channels: ', `${client.channels.size.toLocaleString()}`, true)
   .addField('• Users: ', `${client.users.size.toLocaleString()}`, true)
   .addField('• Ping: ', `${(end - start).toFixed(0)} MS`, true)
   .addField('• CPU Speed: ', '2.4GHz', true)
   .addField(`• Mem. Usage: `, `${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB`, true)
   msg.channel.sendEmbed(embed);
   return msg.edit('```Done!```');
  }).catch(e => {
   msg.channel.sendMessage(":no_entry_sign: There was an error! Report this please:\n\n" + e);
  });
 }
};

client.on('ready', () => {
 client.user.setGame(`Custom playlists! s.help | s.invite`, 'https://www.twitch.tv/imaqtpie');
 console.log('Spotify bot online and ready!');
});

client.on('message', msg => {
 if (!msg.content.startsWith(tokens.prefix)) return;
 if (commands.hasOwnProperty(msg.content.toLowerCase().slice(tokens.prefix.length).split(' ')[0])) commands[msg.content.toLowerCase().slice(tokens.prefix.length).split(' ')[0]](msg);
});
client.login(tokens.d_token);
<|endoftext|>


<commit_before>'use strict';
let BreadcrumbsService = require('./BreadcrumbsService');
let testUrl;
let $locationMock = {
  absUrl() {
    return testUrl;
  },
  host() {
    return "localhost";
  },
  search() {
    return { q: testUrl.split('q=')[1]};
  }
};

let $rootScopeMock = {
  $on(event, callback) {
    callback.call({}, event, testUrl);
  }
};

let $windowMock = {
  document: {}
};

describe("BreadcrumbsService", function () {
  beforeEach(function () {
    testUrl = "http://localhost";
  });

  it("should handle home start", function () {
    testUrl += "/home";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
  });

  it("should handle home route", function () {
    testUrl += "/home/search";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/home/search');
  });

  it("should handle app start", function () {
    testUrl += "/dataset";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/dataset');
  });

  it("should handle app route", function () {
    testUrl += "/dataset/someid";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/dataset');
    breadcrumbsService.breadcrumbs[2].should.have.property('href','/dataset/someid');
  });

  it("should handle query", function () {
    testUrl += "/home?q=lol";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('text','"lol"');
  });

  it("should return to app route when on a document ", function(){
    testUrl += "/ny-alesund/a8c8dfd0-f42e-403e-a913-5f35fabe6caf";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/ny-alesund');
    breadcrumbsService.breadcrumbs[2].should.have.property('text','a8c8dfd0-f42e-403e-a913-5f35fabe6caf');
  });
});
<commit_msg>Breadcrumbs on mobile<commit_after>'use strict';
let BreadcrumbsService = require('./BreadcrumbsService');
let testUrl;
let $locationMock = {
  absUrl() {
    return testUrl;
  },
  host() {
    return "localhost";
  },
  search() {
    return { q: testUrl.split('q=')[1]};
  }
};

let $rootScopeMock = {
  $on(event, callback) {
    callback.call({}, event, testUrl);
  }
};

let $windowMock = {
  document: {}
};

describe("BreadcrumbsService", function () {
  beforeEach(function () {
    testUrl = "http://localhost";
  });

  it("should handle home start", function () {
    testUrl += "/home";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
  });

  it("should handle home route", function () {
    testUrl += "/home/search";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/home/search');
  });

  it("should handle app start", function () {
    testUrl += "/dataset";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/dataset');
  });

  it("should handle app route", function () {
    testUrl += "/dataset/someid";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/dataset');
    breadcrumbsService.breadcrumbs[2].should.have.property('href','/dataset/someid');
  });

  it("should handle query", function () {
    testUrl += "/home?q=lol";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('text','"lol"');
  });

  it("should return to app route when on a document ", function(){
    testUrl += "/ny-alesund/a8c8dfd0-f42e-403e-a913-5f35fabe6caf";
    let breadcrumbsService = new BreadcrumbsService($locationMock, $rootScopeMock, $windowMock);
    breadcrumbsService.breadcrumbs[0].should.have.property('href','/home');
    breadcrumbsService.breadcrumbs[1].should.have.property('href','/ny-alesund');
    breadcrumbsService.breadcrumbs[2].should.have.property('text','a8c8dfd0');
  });
});
<|endoftext|>