<commit_before>var TickTock = TickTock || {};

(function () {
    "use strict";

    /**
     * Object providing simple publish-subscribe functionality for the
     * TickTock model.
     */
    TickTock.PubSub = (function () {
        var API = {},
            channels = {},
            ensureChannel = null;

        /**
         * Ensures the named channel has a collection of subscribers.
         *
         * channel - The name of the channel that must have a collection of
         * subscribers.
         */
        ensureChannel = function (channel) {
            channels[channel] = channels[channel] || [];
        };

        /**
         * Publishes the given message across the named channel.
         *
         * channel - The name of the channel to publish the message along.
         * message - The message to pass to subscribing functions.
         */
        API.publish = function (channel, message) {
            var i;
            ensureChannel(channel);

            for (i = 0; i < channels[channel].length; i += 1) {
                channels[channel][i](message);
            }
        };

        /**
         * Adds a subscriber for the named channel.
         *
         * channel - The name of the channel to subscribe to.
         * subscriber - The function subscribing to messages on the named
         * channel.
         */
        API.subscribe = function (channel, subscriber) {
            ensureChannel(channel);
            channels[channel].push(subscriber);
        };

        return API;
    }());

    /**
     * Object encapsulating the functionality of the TickTock timer.
     *
     * Publishes via several channels during execution. Each message is in
     * the format:
     *
     *     { 'elapsed': elapsed, 'length': length }
     *
     * Where 'elapsed' and 'length' are both periods of time in
     * milliseconds. 'elapsed' represents the amount of time that has passed
     * according to the timer, 'length' represents the length of time the
     * timer is running for.
     *
     * Channels published to:
     *
     *  * timeChanged - Published when the internal time is updated
     *  * timerStarted - Published when the timer is started
     *  * timerComplete - Published when the timer has run for its duration
     *  * timerStopped - Published when the timer is stopped
     *  * timerReset - Published when the timer is reset
     */
    TickTock.Timer = (function () {
        var API = {},
            running = false,
            elapsed = 0,
            length = 5 * 1000,
            cycleTime = 20,
            updateTime = null,
            started = null,
            publishMessage = null;

        publishMessage = function (channel, message) {
            message = message || {};
            message.elapsed = message.elapsed || elapsed;
            message.length = message.length || length;

            TickTock.PubSub.publish(channel, message);
        };

        /**
         * Updates the internal time of the timer, publishing messages
         * relating to the change in time as necessary.
         *
         * Will set a timeout to invoke itself again if the timer is still
         * running and has time remaining.
         */
        updateTime = function () {
            var now = null;

            if (running === false) {
                return;
            }

            now = new Date();
            elapsed = now - started;

            if (elapsed >= length) {
                elapsed = length;
                running = false;
                publishMessage('timeChanged');
                publishMessage('timerComplete');
                return;
            }

            publishMessage('timeChanged');
            setTimeout(updateTime, cycleTime);
        };

        /**
         * Starts the timer running.
         *
         * If the timer is has completed then it restarts the timer.
         */
        API.start = function () {
            running = true;

            if (elapsed >= length) {
                elapsed = 0;
            }

            started = new Date() - elapsed;
            updateTime();

            publishMessage('timerStarted');
        };

        /**
         * Stops the timer running.
         */
        API.stop = function () {
            running = false;
            publishMessage('timerStopped');
        };

        /**
         * Resets the timer.
         *
         * Sets the elapsed time to zero. If the timer is currently running
         * it continues running from the new start time.
         */
        API.reset = function () {
            elapsed = 0;
            started = new Date();

            publishMessage('timeChanged');
            publishMessage('timerReset');
        };

        /**
         * Sets the duration of the timer.
         *
         * If the timer is currently running then the timer will continue
         * working towards the new duration.
         *
         * minutes - The number of minutes the timer should run for.
         * seconds - The number of seconds the timer should run for.
         */
        API.setDuration = function (minutes, seconds) {
            var safeElapsed = elapsed;

            minutes = +minutes;
            seconds = +seconds;

            seconds = (minutes * 60) + seconds;
            length = seconds * 1000;

            if (safeElapsed > length) {
                safeElapsed = length;
            }

            publishMessage('timerDurationSet', { 'elapsed': safeElapsed });
        };

        return API;
    }());
}());

/**
 * Function for controlling the interaction of the UI and the TickTock
 * model.
 */
(function ($) {
    "use strict";

    $(function () {
        var progress = $('#progress'),
            body = $('body'),
            timeText = $('#time'),
            startButton = $('#start'),
            stopButton = $('#stop'),
            resetButton = $('#reset'),
            setMinutes = $('#setMinutes'),
            setSeconds = $('#setSeconds'),
            padNumber = null,
            setTime = null;

        /*
        Update the background progress bar whenever the elapsed time changes.
        */
        TickTock.PubSub.subscribe('timeChanged', function (args) {
            progress.css('width', ((args.elapsed / args.length) * 100) + '%');
        });

        /*
        Toggle a class on the body signifying when the timer is running.
        */
        TickTock.PubSub.subscribe('timerStarted', function () {
            body.addClass('playing');
        });
        TickTock.PubSub.subscribe('timerStopped', function () {
            body.removeClass('playing');
        });
        TickTock.PubSub.subscribe('timerComplete', function () {
            body.removeClass('playing');
        });

        /**
         * Returns a string representation of a number padded to two characters
         * with a zero if needed.
         *
         * number - The number to return a padded string representation of.
         */
        padNumber = function (number) {
            var numberDisplay = number.toFixed(0);
            return (numberDisplay.length >= 2) ? numberDisplay : '0' + numberDisplay;
        };

        /*
        Updates the UI element displaying the currently elapsed time.
        */
        TickTock.PubSub.subscribe('timeChanged', function (args) {
            var seconds = args.elapsed / 1000,
                minutes = Math.floor(seconds / 60);

            seconds = seconds - (minutes * 60);

            timeText.text(padNumber(minutes) + ':' + padNumber(seconds));
        });

        /*
        Make clicking the start button start the TickTock timer.
        */
        startButton.click(TickTock.Timer.start);

        /*
        Make clicking the stop button stop the TickTock timer.
        */
        stopButton.click(TickTock.Timer.stop);

        /*
        Make clicking the reset button reset the TickTock timer.
        */
        resetButton.click(TickTock.Timer.reset);

        /*
        Make changing the duration select lists update the TickTock duration.
        */

        setTime = function () {
            TickTock.Timer.setDuration(setMinutes.val(), setSeconds.val());
        };

        setMinutes.change(setTime);
        setSeconds.change(setTime);

        /*
        Initialize the TickTock timer so that it matches the selected values.
        */
        setTime();
    });
}(window.jQuery));
<commit_msg>Documented internal publishMessage function.<commit_after>var TickTock = TickTock || {};

(function () {
    "use strict";

    /**
     * Object providing simple publish-subscribe functionality for the
     * TickTock model.
     */
    TickTock.PubSub = (function () {
        var API = {},
            channels = {},
            ensureChannel = null;

        /**
         * Ensures the named channel has a collection of subscribers.
         *
         * channel - The name of the channel that must have a collection of
         * subscribers.
         */
        ensureChannel = function (channel) {
            channels[channel] = channels[channel] || [];
        };

        /**
         * Publishes the given message across the named channel.
         *
         * channel - The name of the channel to publish the message along.
         * message - The message to pass to subscribing functions.
         */
        API.publish = function (channel, message) {
            var i;
            ensureChannel(channel);

            for (i = 0; i < channels[channel].length; i += 1) {
                channels[channel][i](message);
            }
        };

        /**
         * Adds a subscriber for the named channel.
         *
         * channel - The name of the channel to subscribe to.
         * subscriber - The function subscribing to messages on the named
         * channel.
         */
        API.subscribe = function (channel, subscriber) {
            ensureChannel(channel);
            channels[channel].push(subscriber);
        };

        return API;
    }());

    /**
     * Object encapsulating the functionality of the TickTock timer.
     *
     * Publishes via several channels during execution. Each message is in
     * the format:
     *
     *     { 'elapsed': elapsed, 'length': length }
     *
     * Where 'elapsed' and 'length' are both periods of time in
     * milliseconds. 'elapsed' represents the amount of time that has passed
     * according to the timer, 'length' represents the length of time the
     * timer is running for.
     *
     * Channels published to:
     *
     *  * timeChanged - Published when the internal time is updated
     *  * timerStarted - Published when the timer is started
     *  * timerComplete - Published when the timer has run for its duration
     *  * timerStopped - Published when the timer is stopped
     *  * timerReset - Published when the timer is reset
     */
    TickTock.Timer = (function () {
        var API = {},
            running = false,
            elapsed = 0,
            length = 5 * 1000,
            cycleTime = 20,
            updateTime = null,
            started = null,
            publishMessage = null;

        /**
         * Publishes a message to the named channel, setting default values on
         * the specified message or creating a message with default values as
         * appropriate.
         *
         * The default values are the current elapsed and timer length for
         * their respective fields if no value is specified.
         *
         * channel - The name of the channel to publish the message to.
         * message - The message to publish containing any non-default values.
         */
        publishMessage = function (channel, message) {
            message = message || {};
            message.elapsed = message.elapsed || elapsed;
            message.length = message.length || length;

            TickTock.PubSub.publish(channel, message);
        };

        /**
         * Updates the internal time of the timer, publishing messages
         * relating to the change in time as necessary.
         *
         * Will set a timeout to invoke itself again if the timer is still
         * running and has time remaining.
         */
        updateTime = function () {
            var now = null;

            if (running === false) {
                return;
            }

            now = new Date();
            elapsed = now - started;

            if (elapsed >= length) {
                elapsed = length;
                running = false;
                publishMessage('timeChanged');
                publishMessage('timerComplete');
                return;
            }

            publishMessage('timeChanged');
            setTimeout(updateTime, cycleTime);
        };

        /**
         * Starts the timer running.
         *
         * If the timer is has completed then it restarts the timer.
         */
        API.start = function () {
            running = true;

            if (elapsed >= length) {
                elapsed = 0;
            }

            started = new Date() - elapsed;
            updateTime();

            publishMessage('timerStarted');
        };

        /**
         * Stops the timer running.
         */
        API.stop = function () {
            running = false;
            publishMessage('timerStopped');
        };

        /**
         * Resets the timer.
         *
         * Sets the elapsed time to zero. If the timer is currently running
         * it continues running from the new start time.
         */
        API.reset = function () {
            elapsed = 0;
            started = new Date();

            publishMessage('timeChanged');
            publishMessage('timerReset');
        };

        /**
         * Sets the duration of the timer.
         *
         * If the timer is currently running then the timer will continue
         * working towards the new duration.
         *
         * minutes - The number of minutes the timer should run for.
         * seconds - The number of seconds the timer should run for.
         */
        API.setDuration = function (minutes, seconds) {
            var safeElapsed = elapsed;

            minutes = +minutes;
            seconds = +seconds;

            seconds = (minutes * 60) + seconds;
            length = seconds * 1000;

            if (safeElapsed > length) {
                safeElapsed = length;
            }

            publishMessage('timerDurationSet', { 'elapsed': safeElapsed });
        };

        return API;
    }());
}());

/**
 * Function for controlling the interaction of the UI and the TickTock
 * model.
 */
(function ($) {
    "use strict";

    $(function () {
        var progress = $('#progress'),
            body = $('body'),
            timeText = $('#time'),
            startButton = $('#start'),
            stopButton = $('#stop'),
            resetButton = $('#reset'),
            setMinutes = $('#setMinutes'),
            setSeconds = $('#setSeconds'),
            padNumber = null,
            setTime = null;

        /*
        Update the background progress bar whenever the elapsed time changes.
        */
        TickTock.PubSub.subscribe('timeChanged', function (args) {
            progress.css('width', ((args.elapsed / args.length) * 100) + '%');
        });

        /*
        Toggle a class on the body signifying when the timer is running.
        */
        TickTock.PubSub.subscribe('timerStarted', function () {
            body.addClass('playing');
        });
        TickTock.PubSub.subscribe('timerStopped', function () {
            body.removeClass('playing');
        });
        TickTock.PubSub.subscribe('timerComplete', function () {
            body.removeClass('playing');
        });

        /**
         * Returns a string representation of a number padded to two characters
         * with a zero if needed.
         *
         * number - The number to return a padded string representation of.
         */
        padNumber = function (number) {
            var numberDisplay = number.toFixed(0);
            return (numberDisplay.length >= 2) ? numberDisplay : '0' + numberDisplay;
        };

        /*
        Updates the UI element displaying the currently elapsed time.
        */
        TickTock.PubSub.subscribe('timeChanged', function (args) {
            var seconds = args.elapsed / 1000,
                minutes = Math.floor(seconds / 60);

            seconds = seconds - (minutes * 60);

            timeText.text(padNumber(minutes) + ':' + padNumber(seconds));
        });

        /*
        Make clicking the start button start the TickTock timer.
        */
        startButton.click(TickTock.Timer.start);

        /*
        Make clicking the stop button stop the TickTock timer.
        */
        stopButton.click(TickTock.Timer.stop);

        /*
        Make clicking the reset button reset the TickTock timer.
        */
        resetButton.click(TickTock.Timer.reset);

        /*
        Make changing the duration select lists update the TickTock duration.
        */

        setTime = function () {
            TickTock.Timer.setDuration(setMinutes.val(), setSeconds.val());
        };

        setMinutes.change(setTime);
        setSeconds.change(setTime);

        /*
        Initialize the TickTock timer so that it matches the selected values.
        */
        setTime();
    });
}(window.jQuery));
<|endoftext|>


<commit_before>javascript: {
  var ap = window.ap;
  var aurl = (function(t) {
    function o(t) {
      if (~t.indexOf("audio_api_unavailable")) {
        var e = t.split("?extra=")[1].split("#"),
          o = "" === e[1] ? "" : a(e[1]);
        if (e = a(e[0]), "string" != typeof o || !e) return t;
        o = o ? o.split(String.fromCharCode(9)) : [];
        for (var s, r, n = o.length; n--;) {
          if (r = o[n].split(String.fromCharCode(11)), s = r.splice(0, 1, e)[0], !l[s]) return t;
          e = l[s].apply(null, r)
        }
        if (e && "http" === e.substr(0, 4)) return e
      }
      return t
    }

    function a(t) {
      if (!t || t.length % 4 == 1) return !1;
      for (var e, i, o = 0, a = 0, s = ""; i = t.charAt(a++);) i = r.indexOf(i), ~i && (e = o % 4 ? 64 * e + i : i, o++ % 4) && (s += String.fromCharCode(255 & e >> (-2 * o & 6)));
      return s
    }

    function s(t, e) {
      var i = t.length,
        o = [];
      if (i) {
        var a = i;
        for (e = Math.abs(e); a--;) o[a] = (e += e * (a + i) / e) % i | 0
      }
      return o
    }
    var r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/=",
      l = {
        v: function(t) {
          return t.split("").reverse().join("")
        },
        r: function(t, e) {
          t = t.split("");
          for (var i, o = r + r, a = t.length; a--;) i = o.indexOf(t[a]), ~i && (t[a] = o.substr(i - e, 1));
          return t.join("")
        },
        s: function(t, e) {
          var i = t.length;
          if (i) {
            var o = s(t, e),
              a = 0;
            for (t = t.split(""); ++a < i;) t[a] = t.splice(o[i - 1 - a], 1, t[a])[0];
            t = t.join("")
          }
          return t
        },
        x: function(t, e) {
          var i = [];
          return e = e.charCodeAt(0), each(t.split(""), function(t, o) {
            i.push(String.fromCharCode(o.charCodeAt(0) ^ e))
          }), i.join("")
        }
      };
    return o(t);
  })(ap._currentAudio[2]);
  var aname = ap._currentAudio[4] + ' - ' + ap._currentAudio[3] + '.mp3';
  console.log('URL: ' + aurl);
  console.log('Title: ' + aname);
  var doc = window.document;
  var link = doc.createElement('a');link.download = aname;link.href = aurl;
  var par = document.body;par.appendChild(link);link.click();par.removeChild(link);
}
<commit_msg>Right downloaded filename. Tested for Firefox.<commit_after>javascript: {

  var ap = window.ap;
  var aurl = (function(t) {
    function o(t) {
      if (~t.indexOf("audio_api_unavailable")) {
        var e = t.split("?extra=")[1].split("#"),
          o = "" === e[1] ? "" : a(e[1]);
        if (e = a(e[0]), "string" != typeof o || !e) return t;
        o = o ? o.split(String.fromCharCode(9)) : [];
        for (var s, r, n = o.length; n--;) {
          if (r = o[n].split(String.fromCharCode(11)), s = r.splice(0, 1, e)[0], !l[s]) return t;
          e = l[s].apply(null, r)
        }
        if (e && "http" === e.substr(0, 4)) return e
      }
      return t
    }

    function a(t) {
      if (!t || t.length % 4 == 1) return !1;
      for (var e, i, o = 0, a = 0, s = ""; i = t.charAt(a++);) i = r.indexOf(i), ~i && (e = o % 4 ? 64 * e + i : i, o++ % 4) && (s += String.fromCharCode(255 & e >> (-2 * o & 6)));
      return s
    }

    function s(t, e) {
      var i = t.length,
        o = [];
      if (i) {
        var a = i;
        for (e = Math.abs(e); a--;) o[a] = (e += e * (a + i) / e) % i | 0
      }
      return o
    }
    var r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/=",
      l = {
        v: function(t) {
          return t.split("").reverse().join("")
        },
        r: function(t, e) {
          t = t.split("");
          for (var i, o = r + r, a = t.length; a--;) i = o.indexOf(t[a]), ~i && (t[a] = o.substr(i - e, 1));
          return t.join("")
        },
        s: function(t, e) {
          var i = t.length;
          if (i) {
            var o = s(t, e),
              a = 0;
            for (t = t.split(""); ++a < i;) t[a] = t.splice(o[i - 1 - a], 1, t[a])[0];
            t = t.join("")
          }
          return t
        },
        x: function(t, e) {
          var i = [];
          return e = e.charCodeAt(0), each(t.split(""), function(t, o) {
            i.push(String.fromCharCode(o.charCodeAt(0) ^ e))
          }), i.join("")
        }
      };
    return o(t);
  })(ap._currentAudio[2]);
  var aname = ap._currentAudio[4] + ' - ' + ap._currentAudio[3] + '.mp3';
  console.log('URL: ' + aurl);
  console.log('Title: ' + aname);
  var xhr = new XMLHttpRequest();
  xhr.open('GET', aurl);
  xhr.onload = function() {
    console.log('Response length: ' + this.response.length);
    var doc = window.document;
    var link = doc.createElement('a');
    link.download = aname;
    link.href = window.URL.createObjectURL(new Blob([this.response], {type: 'audio/mp3'}));
    var par = document.body;par.appendChild(link);link.click();par.removeChild(link);
  }
  xhr.send();
}
<|endoftext|>


<commit_before>$(document).ready(function(){
  var move = 1;
  var play = true;

  $("#board tr td").click(function(){
    if($(this).text() == "" && play) {
      if((move % 2) === 1) {
        $(this).append("X");
      } else {
        $(this).append("O");
      }
      move++;

      if(winnerCheck() != -1 && winnerCheck() !="") {
        if(winnerCheck() === "X"){
          alert("Player 1 wins!");
        } else {
          alert("Player 2 wins!");
        }
        play = false;
      }
    }
  });

  function winnerCheck(){
    var space1 = $("#board tr:nth-child(1) td:nth-child(1)").text();
    var space2 = $("#board tr:nth-child(1) td:nth-child(2)").text();
    var space3 = $("#board tr:nth-child(1) td:nth-child(3)").text();
    var space4 = $("#board tr:nth-child(2) td:nth-child(1)").text();
    var space5 = $("#board tr:nth-child(2) td:nth-child(2)").text();
    var space6 = $("#board tr:nth-child(2) td:nth-child(3)").text();
    var space7 = $("#board tr:nth-child(3) td:nth-child(1)").text();
    var space8 = $("#board tr:nth-child(3) td:nth-child(2)").text();
    var space9 = $("#board tr:nth-child(3) td:nth-child(3)").text();
    // check rows
    if      ((space1==space2) && (space2==space3)) { return space3; }
    else if ((space4==space5) && (space5==space6)) { return space6; }
    else if ((space7==space8) && (space8==space9)) { return space9; }
    // check columns
    else if ((space1==space4) && (space4==space7)) { return space7; }
    else if ((space2==space5) && (space5==space8)) { return space8; }
    else if ((space3==space6) && (space6==space9)) { return space9; }
    // check diagonals
    else if ((space1==space5) && (space5==space9)) { return space9; }
    else if ((space3==space5) && (space5==space7)) { return space7; }
    // no winner
    return -1;
  }

  $('#replay').click(function() {
    location.reload();
  });

});

<commit_msg>update equal sign syntax<commit_after>$(document).ready(function(){
  var move = 1;
  var play = true;

  $("#board tr td").click(function(){
    if($(this).text() === "" && play) {
      if((move % 2) === 1) {
        $(this).append("X");
      } else {
        $(this).append("O");
      }
      move++;

      if(winnerCheck() !== -1 && winnerCheck() !== "") {
        if(winnerCheck() === "X"){
          alert("Player 1 wins!");
        } else {
          alert("Player 2 wins!");
        }
        play = false;
      }
    }
  });

  function winnerCheck(){
    var space1 = $("#board tr:nth-child(1) td:nth-child(1)").text();
    var space2 = $("#board tr:nth-child(1) td:nth-child(2)").text();
    var space3 = $("#board tr:nth-child(1) td:nth-child(3)").text();
    var space4 = $("#board tr:nth-child(2) td:nth-child(1)").text();
    var space5 = $("#board tr:nth-child(2) td:nth-child(2)").text();
    var space6 = $("#board tr:nth-child(2) td:nth-child(3)").text();
    var space7 = $("#board tr:nth-child(3) td:nth-child(1)").text();
    var space8 = $("#board tr:nth-child(3) td:nth-child(2)").text();
    var space9 = $("#board tr:nth-child(3) td:nth-child(3)").text();
    // check rows
    if      ((space1==space2) && (space2==space3)) { return space3; }
    else if ((space4==space5) && (space5==space6)) { return space6; }
    else if ((space7==space8) && (space8==space9)) { return space9; }
    // check columns
    else if ((space1==space4) && (space4==space7)) { return space7; }
    else if ((space2==space5) && (space5==space8)) { return space8; }
    else if ((space3==space6) && (space6==space9)) { return space9; }
    // check diagonals
    else if ((space1==space5) && (space5==space9)) { return space9; }
    else if ((space3==space5) && (space5==space7)) { return space7; }
    // no winner
    return -1;
  }

  $('#replay').click(function() {
    location.reload();
  });

});

<|endoftext|>


<commit_before>//Color Value
function getRandomColor(){
	var rgb = [0, 0, 0];
	for(var  i = 0; i < 3; i++){
		rgb[i] = Math.floor((Math.random() * 255) + 1);
	}
	var color = "rgb("+rgb[0]+","+rgb[1]+","+rgb[2]+")";
	return color;
}
//Shape
function getCircle(){
	if (Math.random() > 0.5){
		return "100px";
	} else {
		return "0";
	}
}
var createdTime,
	clickedTime,
	reactionTime;
function makeShape(){
	var s = document.getElementById("shape");
	//Timestamp
	createdTime = Date.now();
	var x = Math.random();
	x = x * 5000;
	//Change Position
	var py = Math.random();
	py = py * 720;
	var px = Math.random();
	px = px * 1280;
	//Shape Creation
	setTimeout(function(){
		s.style.display = "block";
		s.style.borderRadius = getCircle();
		s.style.backgroundColor = getRandomColor();
		s.style.top = py+"px";
		s.style.left = px+"px";
	}, x);
}
document.getElementById("shape").onclick=function(){
	clickedTime = Date.now();
	reactionTime = (clickedTime - createdTime) / 1000;
	document.getElementById("time").innerHTML = reactionTime;
	this.style.display="none";
	makeShape();
}
makeShape();
<commit_msg>Update script.js<commit_after>//Color Value
function getRandomColor(){
	var rgb = [0, 0, 0];
	for(var  i = 0; i < 3; i++){
		rgb[i] = Math.floor((Math.random() * 255) + 1);
	}
	var color = "rgb("+rgb[0]+","+rgb[1]+","+rgb[2]+")";
	return color;
}
//Shape
function getCircle(){
	if (Math.random() > 0.5){
		return "100px";
	} else {
		return "0";
	}
}
var createdTime,
	clickedTime,
	reactionTime;
function makeShape(){
	var s = document.getElementById("shape");
	//Timestamp
	var x = Math.random();
	x = x * 5000;
	//Change Position
	var py = Math.random();
	py = py * 720;
	var px = Math.random();
	px = px * 1280;
	//Shape Creation
	setTimeout(function(){
		s.style.display = "block";
		createdTime = Date.now();
		s.style.borderRadius = getCircle();
		s.style.backgroundColor = getRandomColor();
		s.style.top = py+"px";
		s.style.left = px+"px";
	}, x);
}
document.getElementById("shape").onclick=function(){
	clickedTime = Date.now();
	reactionTime = (clickedTime - createdTime) / 1000;
	document.getElementById("time").innerHTML = reactionTime;
	this.style.display="none";
	makeShape();
}
makeShape();
<|endoftext|>


<commit_before>function makeBox(id){
	var x = Math.random();
	x = x * 5000;
	setTimeout(function(){ document.getElementById("box").style.display = "block";}, x);
}

document.getElementById("box").onclick=function(){
	this.style.display="none";
	makeBox();
}

makeBox();
<commit_msg>Update script.js<commit_after>var createdTime,
	clickedTime,
	reactionTime;

function makeBox(){
	//Timestamp
	createdTime = Date.now();
	var x = Math.random();
	x = x * 5000;
	//Color Value
	var rgb = [0, 0, 0];
	for(var  i = 0; i < 3; i++){
		rgb[i] = Math.floor((Math.random() * 255) + 1);
	}
	var color = "rgb("+rgb[0]+","+rgb[1]+","+rgb[2]+")";
	//Shape Creation
	document.getElementById("box").style.backgroundColor = color;
	setTimeout(function(){ document.getElementById("box").style.display = "block";}, x);
}

document.getElementById("box").onclick=function(){
	clickedTime = Date.now();
	reactionTime = (clickedTime - createdTime) / 1000;
	document.getElementById("time").innerHTML = reactionTime;
	this.style.display="none";
	makeBox();
}

makeBox();
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;
const AndreasSefzig = "[AndreasSefzig] ";
const EmpfangsBot =   "[EmpfangsBot] ";
const BeratungsBot =  "[BeratungsBot] ";
const KreationsBot =  "[KreationsBot] ";
const TechnikBot =    "[TechnikBot] ";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(AndreasSefzig+'Nicht so schnell bitte...'),
        receive: () => 'processing'
    },

 // -------------------------
 // Start
 // -------------------------

 // 3 Welcome Whispers
 // https://app.smooch.io/apps/571777938ea8c63e0057cc1f/whispers

 // Übergabe an Register
    start: {
        receive: () => 'register'
    },

 // -------------------------
 // Onboarding
 // -------------------------

    name: {

        receive: (bot, message) => {

            var antwort = message.text.trim().toUpperCase();
            var name_falsch = "";
            var dann = "";

            if (antwort == "--JA")   {

               bot.say(EmpfangsBot+'Ich kenne Sie nun als');
               name_falsch == "nein";
               dann = "register";

            }
            if (antwort == "--NEIN") {

               name_falsch == "ja";
               dann = "vorname";

            }
            if (antwort == "--BOT") {

               name_falsch == "";
               dann = "register";

            }

            return bot.setProp('name_falsch', name_falsch)
            .then(() => dann);
        }
    },

    vorname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'),

        receive: (bot, message) => {

            var vorname = message.text;

            return bot.setProp('vorname', vorname)
            .then(() => bot.say(EmpfangsBot+`${vorname}, prima.`))
            .then(() => 'nachname');

        }
    },

    nachname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen?'),

        receive: (bot, message) => {

            var nachname = message.text;
            bot.setProp('nachname', nachname)

            return bot.getProp('vorname')
            .then((vorname) => bot.say(EmpfangsBot+`Sie heissen ${vorname} ${nachname}, ist das richtig?`))
            .then((vorname) => bot.say(EmpfangsBot+`Bitte bestätigen Sie, indem Sie --ja oder --nein schreiben!`))
            .then(() => 'name');

        }
    },

 // -------------------------
 // Register
 // -------------------------

    register: {
        receive: (bot, message) => {

         // Befehl normalisieren
            var befehl = message.text.trim().toUpperCase();

         // Nächster Schritt default
            var dann = "register";

         // System
            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot+'--empfang '
                                                              +'\n○ --kreation '
                                                              +'\n○ --beratung '
                                                              +'\n○ --technik '
                                                              +'\n○ --sefzig '); }

         // Bots
            if (~befehl.indexOf("--EMPFANG"))         { bot.say(EmpfangsBot+'Empfang 1');
                                                        bot.say(EmpfangsBot+'Empfang 2');
                                                        bot.say(EmpfangsBot+'Empfang 3');
                                                        dann = "empfang"; }

         // Vorlage
            if  (~befehl.indexOf("--VORLAGE"))        { bot.say(EmpfangsBot+'Text: Vorlage.'); }

         // Register Antwort
            return bot.setProp('register', 'gesprochen')
            .then(() => dann);
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<commit_msg>Onboarding<commit_after>'use strict';

const Script = require('smooch-bot').Script;
const AndreasSefzig = "[AndreasSefzig] ";
const EmpfangsBot =   "[EmpfangsBot] ";
const BeratungsBot =  "[BeratungsBot] ";
const KreationsBot =  "[KreationsBot] ";
const TechnikBot =    "[TechnikBot] ";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(AndreasSefzig+'Nicht so schnell bitte...'),
        receive: () => 'processing'
    },

 // -------------------------
 // Start
 // -------------------------

 // 3 Welcome Whispers
 // https://app.smooch.io/apps/571777938ea8c63e0057cc1f/whispers

 // Übergabe an Register
    start: {
        receive: (bot) => {
            return bot.say(SefzigBot+'Start.')
                .then(() => 'vorname'); /* <-- register */
        }
    },

 // -------------------------
 // Onboarding
 // -------------------------

    name: {

        receive: (bot, message) => {

            var antwort = message.text.trim().toUpperCase();
            var name_falsch = "";
            var dann = "";

            if (antwort == "--JA")   {

               bot.say(EmpfangsBot+'Ich kenne Sie nun als');
               name_falsch == "nein";
               dann = "register";

            }
            if (antwort == "--NEIN") {

               name_falsch == "ja";
               dann = "vorname";

            }
            if (antwort == "--BOT") {

               name_falsch == "";
               dann = "register";

            }

            return bot.setProp('name_falsch', name_falsch)
            .then(() => dann);
        }
    },

    vorname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'),

        receive: (bot, message) => {

            var vorname = message.text;

            return bot.setProp('vorname', vorname)
            .then(() => bot.say(EmpfangsBot+`${vorname}, prima.`))
            .then(() => 'nachname');

        }
    },

    nachname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen?'),

        receive: (bot, message) => {

            var nachname = message.text;
            bot.setProp('nachname', nachname)

            return bot.getProp('vorname')
            .then((vorname) => bot.say(EmpfangsBot+`Sie heissen ${vorname} ${nachname}, ist das richtig?`))
            .then((vorname) => bot.say(EmpfangsBot+`Bitte bestätigen Sie, indem Sie --ja oder --nein schreiben!`))
            .then(() => 'name');

        }
    },

 // -------------------------
 // Register
 // -------------------------

    register: {
        receive: (bot, message) => {

         // Befehl normalisieren
            var befehl = message.text.trim().toUpperCase();

         // Nächster Schritt default
            var dann = "register";

         // System
            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot+'--empfang '
                                                              +'\n○ --kreation '
                                                              +'\n○ --beratung '
                                                              +'\n○ --technik '
                                                              +'\n○ --sefzig '); }

         // Bots
            if (~befehl.indexOf("--EMPFANG"))         { bot.say(EmpfangsBot+'Empfang 1');
                                                        bot.say(EmpfangsBot+'Empfang 2');
                                                        bot.say(EmpfangsBot+'Empfang 3');
                                                        dann = "empfang"; }

         // Vorlage
            if  (~befehl.indexOf("--VORLAGE"))        { bot.say(EmpfangsBot+'Text: Vorlage.'); }

         // Register Antwort
            return bot.setProp('register', 'gesprochen')
            .then(() => dann);
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>var whereIsMyBuild = function () {
    var my = {
        width: 960,
        height: 2000,
        jenkinsUrl: "http://localhost:8080",
        startJob: "chain-start",
        updateInterval: 2000,
        renderInterval: 2000
    };

    var data;

    var getQueryVariable = function (variable) {
        var query = window.location.search.substring(1),
            results = query.split("&").map(function (el) {
                return el.split("=")
            }).filter(function (el) {
                return (el[0] == variable);
            }).map(function (el) {
                return el[1];
            });
        return results.length == 0 ? false : results[0];
    };

    var baseBuildNode = {
        getName: function () {
            return this.jobName + " - " + this.revision
        }
    };

    var buildNode = function (jobName, revision, url) {
        var n = Object.create(baseBuildNode);
        n.jobName = jobName;
        n.revision = revision;
        n.url = url;
        n.status = "pending";

        return n;
    };

    var toUpdate = [];

    var renderer = function (conf, data) {
        var my = {};

        var cluster = d3.layout.tree().nodeSize([200, 200]);
        var diagonal = d3.svg.diagonal()
            .projection(function (d) {
                return [d.x, d.y];
            });

        var canvas = d3.select("body").append("svg")
            .attr("width", conf.width)
            .attr("height", conf.height);

        var svg = canvas
            .append("g")
            .attr("transform", "translate(500,300)");

        d3.select(self.frameElement).style("height", conf.height + "px");

        my.renderData = function () {
            var nodes = cluster.nodes(data);
            var links = cluster.links(nodes);

            var link = svg.selectAll(".link")
                .data(links, function (d) {
                    return d.source.getName() + d.target.getName();
                });

            link.enter().insert("path", ".node")
                .attr("class", "link");

            link.transition().attr("d", diagonal);

            link.exit().remove();

            var node = svg.selectAll(".node")
                .data(nodes, function (d) {
                    return d.getName();
                });

            var arc = d3.svg.arc()
                .innerRadius(10)
                .outerRadius(20)
                .startAngle(0)
                .endAngle(Math.PI * 2);

            var parentNode = node.enter().append("g")
                .attr("class", "node");
            parentNode.append("circle")
                .attr("r", 20);
            parentNode.append("path")
                .attr("class", "pending")
                .attr("d", arc);

            var textNode = parentNode.append("a")
                .attr("transform", "rotate(10)")
                .append("text");

            var dxChildren = function () {
                return 40;
            };

            textNode
                .append("tspan")
                .text(function (d) {
                    return d.jobName;
                });

            textNode
                .append("tspan")
                .attr("class", "revision")
                .attr("dy", "1.2em")
                .text(function (d) {
                    return d.revision
                });

            node.selectAll("a")
                .attr("xlink:href", function (d) {
                    return d.url
                });

            node.selectAll("a text tspan")
                .attr("x", "0")
                .attr("dx", dxChildren);

            var circles = node.selectAll("path")
                .attr("class", function (d) {
                    return d.status;
                });

            var blink = function () {
                circles.transition()
                    .duration(1000)
                    .style("opacity", function (d) {
                        return d.status === "pending" ? 0 : 1;
                    })
                    .each("end", function () {
                        d3.select(this)
                            .transition()
                            .duration(1000)
                            .style("opacity", 1)
                            .each("end", blink)
                    })
            };

            blink();

            node.selectAll("a text").transition()
                .attr("dy", 0)
                .style("text-anchor", "start");

            node.selectAll("a text tspan.revision").transition()
                .text(function (d) {
                    return d.revision;
                });

            node.transition().attr("transform", function (d) {
                return "translate(" + d.x + "," + d.y + ")";
            });

            node.exit().remove();
        };

        return my;
    };

    var buildData = function (nodeToUpdate) {
        var jobName = nodeToUpdate.jobName;
        var resultDef = $.Deferred();
        var findRevision = function (envVars) {
            for (var i = 0; i < envVars.length; i++) {
                var env = envVars[i];
                if (env.name === "REV") {
                    return parseInt(env.value, 10);
                }
            }
        };

        var buildKeys =
            "number,url,result,actions[triggeredProjects[name,url],failCount,skipCount,totalCount,urlName],changeSet[items[commitId,author,msg]]";

        var jobRequest = $.getJSON(
            my.jenkinsUrl + "/job/" + jobName +
            "/api/json?tree=url,lastCompletedBuild[" + buildKeys + "]"
        );

        var buildDef = jobRequest.then(function (job) {
            if (nodeToUpdate.url === undefined) {
                nodeToUpdate.url = job.url;
            }
            return job.lastCompletedBuild;
        });

        var getEnvVars = function (build) {
            return build === undefined ? undefined : $.getJSON(build.url +
                "injectedEnvVars/export");
        };
        var getRevision = function (build) {
            if (build === undefined) {
                return undefined;
            }
            return getEnvVars(build).then(function (envVars) {
                return findRevision(envVars.envVars.envVar)
            })
        };
        buildDef.then(getEnvVars);

        var buildForRevision = function (buildDef) {
            return $.when(buildDef, buildDef.then(getRevision)).then(
                function (build, revision) {
                    if (build === undefined) {
                        return undefined;
                    }
                    build.revision = revision;
                    if (revision < nodeToUpdate.revision) {
                        return undefined;
                    } else if (revision === nodeToUpdate.revision) {
                        return build;
                    } else {
                        return buildForRevision($.getJSON(
                                my.jenkinsUrl + "/job/" + jobName + "/" + (build.number - 1) +
                                "/api/json?tree=" + buildKeys)
                            .then(function (build) {
                                return build;
                            })).then(function (previousBuild) {
                            if (previousBuild == undefined) {
                                return build;
                            } else {
                                return previousBuild;
                            }
                        })
                    }
                })
        };

        var getTriggeredProjects = function (build) {
            return build.actions.filter(function (el) {
                return el.triggeredProjects;
            }).map(function (el) {
                return el.triggeredProjects;
            }).reduce(function (a, b) {
                return a.concat(b);
            }, []);
        };

        var getTestResults = function (build) {
            var actions = build.actions;
            var i;
            var action;
            for (i = 0; i < actions.length; i++) {
                action = actions[i];
                if (action.urlName === "testReport") {
                    return action;
                }
            }
            return {
                failCount: 0,
                skipCount: 0,
                totalCount: 0
            };
        };

        buildForRevision(buildDef).then(function (build) {
            if (build == undefined) {
                toUpdate.push(nodeToUpdate);
                resultDef.resolve(nodeToUpdate);
            } else {
                nodeToUpdate.status = build.result.toLowerCase();
                nodeToUpdate.revision = build.revision;
                nodeToUpdate.url = build.url;

                var triggeredProjects = getTriggeredProjects(build);
                var children = $.map(triggeredProjects, function (job) {
                    return buildNode(job.name, nodeToUpdate.revision, job.url);
                });
                var deferreds = $.map(children, function (buildNode) {
                    return buildData(buildNode);
                });

                nodeToUpdate.children = children;

                resultDef.resolve(nodeToUpdate);
            }
        }, function () {
            toUpdate.push(nodeToUpdate);
        });

        return resultDef;
    };

    var updateNext = function () {
        if (toUpdate.length > 0) {
            var current = toUpdate.shift();
            buildData(current);
        }
    };

    my.init = function () {
        data = buildNode(my.startJob, parseInt(getQueryVariable("revision"), 10));
        toUpdate.push(data);

        var r = renderer(this, data);

        updateNext();
        r.renderData();

        setInterval(updateNext, my.updateInterval);

        setInterval(r.renderData, my.renderInterval)
    };

    return my;

}();
<commit_msg>== -> ===<commit_after>var whereIsMyBuild = function () {
    var my = {
        width: 960,
        height: 2000,
        jenkinsUrl: "http://localhost:8080",
        startJob: "chain-start",
        updateInterval: 2000,
        renderInterval: 2000
    };

    var data;

    var getQueryVariable = function (variable) {
        var query = window.location.search.substring(1),
            results = query.split("&").map(function (el) {
                return el.split("=")
            }).filter(function (el) {
                return (el[0] === variable);
            }).map(function (el) {
                return el[1];
            });
        return results.length === 0 ? false : results[0];
    };

    var baseBuildNode = {
        getName: function () {
            return this.jobName + " - " + this.revision
        }
    };

    var buildNode = function (jobName, revision, url) {
        var n = Object.create(baseBuildNode);
        n.jobName = jobName;
        n.revision = revision;
        n.url = url;
        n.status = "pending";

        return n;
    };

    var toUpdate = [];

    var renderer = function (conf, data) {
        var my = {};

        var cluster = d3.layout.tree().nodeSize([200, 200]);
        var diagonal = d3.svg.diagonal()
            .projection(function (d) {
                return [d.x, d.y];
            });

        var canvas = d3.select("body").append("svg")
            .attr("width", conf.width)
            .attr("height", conf.height);

        var svg = canvas
            .append("g")
            .attr("transform", "translate(500,300)");

        d3.select(self.frameElement).style("height", conf.height + "px");

        my.renderData = function () {
            var nodes = cluster.nodes(data);
            var links = cluster.links(nodes);

            var link = svg.selectAll(".link")
                .data(links, function (d) {
                    return d.source.getName() + d.target.getName();
                });

            link.enter().insert("path", ".node")
                .attr("class", "link");

            link.transition().attr("d", diagonal);

            link.exit().remove();

            var node = svg.selectAll(".node")
                .data(nodes, function (d) {
                    return d.getName();
                });

            var arc = d3.svg.arc()
                .innerRadius(10)
                .outerRadius(20)
                .startAngle(0)
                .endAngle(Math.PI * 2);

            var parentNode = node.enter().append("g")
                .attr("class", "node");
            parentNode.append("circle")
                .attr("r", 20);
            parentNode.append("path")
                .attr("class", "pending")
                .attr("d", arc);

            var textNode = parentNode.append("a")
                .attr("transform", "rotate(10)")
                .append("text");

            var dxChildren = function () {
                return 40;
            };

            textNode
                .append("tspan")
                .text(function (d) {
                    return d.jobName;
                });

            textNode
                .append("tspan")
                .attr("class", "revision")
                .attr("dy", "1.2em")
                .text(function (d) {
                    return d.revision
                });

            node.selectAll("a")
                .attr("xlink:href", function (d) {
                    return d.url
                });

            node.selectAll("a text tspan")
                .attr("x", "0")
                .attr("dx", dxChildren);

            var circles = node.selectAll("path")
                .attr("class", function (d) {
                    return d.status;
                });

            var blink = function () {
                circles.transition()
                    .duration(1000)
                    .style("opacity", function (d) {
                        return d.status === "pending" ? 0 : 1;
                    })
                    .each("end", function () {
                        d3.select(this)
                            .transition()
                            .duration(1000)
                            .style("opacity", 1)
                            .each("end", blink)
                    })
            };

            blink();

            node.selectAll("a text").transition()
                .attr("dy", 0)
                .style("text-anchor", "start");

            node.selectAll("a text tspan.revision").transition()
                .text(function (d) {
                    return d.revision;
                });

            node.transition().attr("transform", function (d) {
                return "translate(" + d.x + "," + d.y + ")";
            });

            node.exit().remove();
        };

        return my;
    };

    var buildData = function (nodeToUpdate) {
        var jobName = nodeToUpdate.jobName;
        var resultDef = $.Deferred();
        var findRevision = function (envVars) {
            for (var i = 0; i < envVars.length; i++) {
                var env = envVars[i];
                if (env.name === "REV") {
                    return parseInt(env.value, 10);
                }
            }
        };

        var buildKeys =
            "number,url,result,actions[triggeredProjects[name,url],failCount,skipCount,totalCount,urlName],changeSet[items[commitId,author,msg]]";

        var jobRequest = $.getJSON(
            my.jenkinsUrl + "/job/" + jobName +
            "/api/json?tree=url,lastCompletedBuild[" + buildKeys + "]"
        );

        var buildDef = jobRequest.then(function (job) {
            if (nodeToUpdate.url === undefined) {
                nodeToUpdate.url = job.url;
            }
            return job.lastCompletedBuild;
        });

        var getEnvVars = function (build) {
            return build === undefined ? undefined : $.getJSON(build.url +
                "injectedEnvVars/export");
        };
        var getRevision = function (build) {
            if (build === undefined) {
                return undefined;
            }
            return getEnvVars(build).then(function (envVars) {
                return findRevision(envVars.envVars.envVar)
            })
        };
        buildDef.then(getEnvVars);

        var buildForRevision = function (buildDef) {
            return $.when(buildDef, buildDef.then(getRevision)).then(
                function (build, revision) {
                    if (build === undefined) {
                        return undefined;
                    }
                    build.revision = revision;
                    if (revision < nodeToUpdate.revision) {
                        return undefined;
                    } else if (revision === nodeToUpdate.revision) {
                        return build;
                    } else {
                        return buildForRevision($.getJSON(
                                my.jenkinsUrl + "/job/" + jobName + "/" + (build.number - 1) +
                                "/api/json?tree=" + buildKeys)
                            .then(function (build) {
                                return build;
                            })).then(function (previousBuild) {
                            if (previousBuild === undefined) {
                                return build;
                            } else {
                                return previousBuild;
                            }
                        })
                    }
                })
        };

        var getTriggeredProjects = function (build) {
            return build.actions.filter(function (el) {
                return el.triggeredProjects;
            }).map(function (el) {
                return el.triggeredProjects;
            }).reduce(function (a, b) {
                return a.concat(b);
            }, []);
        };

        var getTestResults = function (build) {
            var actions = build.actions;
            var i;
            var action;
            for (i = 0; i < actions.length; i++) {
                action = actions[i];
                if (action.urlName === "testReport") {
                    return action;
                }
            }
            return {
                failCount: 0,
                skipCount: 0,
                totalCount: 0
            };
        };

        buildForRevision(buildDef).then(function (build) {
            if (build === undefined) {
                toUpdate.push(nodeToUpdate);
                resultDef.resolve(nodeToUpdate);
            } else {
                nodeToUpdate.status = build.result.toLowerCase();
                nodeToUpdate.revision = build.revision;
                nodeToUpdate.url = build.url;

                var triggeredProjects = getTriggeredProjects(build);
                var children = $.map(triggeredProjects, function (job) {
                    return buildNode(job.name, nodeToUpdate.revision, job.url);
                });
                var deferreds = $.map(children, function (buildNode) {
                    return buildData(buildNode);
                });

                nodeToUpdate.children = children;

                resultDef.resolve(nodeToUpdate);
            }
        }, function () {
            toUpdate.push(nodeToUpdate);
        });

        return resultDef;
    };

    var updateNext = function () {
        if (toUpdate.length > 0) {
            var current = toUpdate.shift();
            buildData(current);
        }
    };

    my.init = function () {
        data = buildNode(my.startJob, parseInt(getQueryVariable("revision"), 10));
        toUpdate.push(data);

        var r = renderer(this, data);

        updateNext();
        r.renderData();

        setInterval(updateNext, my.updateInterval);

        setInterval(r.renderData, my.renderInterval)
    };

    return my;

}();
<|endoftext|>


<commit_before>//  The calculator pseudoClass represents a four-function calculator.
//  The following both defines and constructs the singleton calculator object.

var calculator = new function(){

//  model pseudoclass is an internal representation of
//  the calculator's state.
//
//  By defining it as a var inside the pseudoclass, it
//  and its properties, and its methods are invisible
//  to the outside world.

    var model = {

        tally : 0, // running total since last clear

        operator : '+', // last operator pressed

        temp : 0, // number, as it entered by user

        isClear : true, // flag indicates whether there has been output

//      The evaluate function performs a computation.
//      First, it performs the stored operation on temp and tally.
//      Then it stores the given operation for the next evaluation.
//
//      Returns the state to show to user.

        evaluate : function(operate){

//          Special condition if there has not been output yet.

            if( this.isClear ){

                this.tally = this.temp;
                this.isClear = false;

            } else {

//              Perform the stored operation on tally and temp

                switch (this.operator){

                    case '+':
                        this.tally += this.temp;
                        break;

                    case '-':
                        this.tally -= this.temp;
                        break;

                    case 'x':
                        this.tally *= this.temp;
                        break;

                    case '/':
                        this.tally /= this.temp;
                        break;

                }
            }

//          In either case, update the display, and prepare for next input

            this.temp = 0; // reset temp
            this.operator = operate; // get ready to perform the given operation

            return this.tally; // user sees result of computation
        },

//      The update function will take string representing a single digit, and
//      append it to what the user has entered so far, both on the screen and
//      internally.
//      Returns the state to show to user.

        update : function(lastDigit){
            this.temp = (10 * this.temp) + parseInt(lastDigit);
            return this.temp; // user sees number entered thus far
        },

//      The reset function clears the calculator's instance variables, and
//      wipes the screen.

        reset : function(){
            this.tally = 0;
            this.operator = '+';
            this.temp = 0;
            this.isClear = true;
            return 0;
        }

    }; // end model

//  view is the representation of the screen.

    var view = {

//      the object holding the output.

        display : {innerHTML : "0"},

//      method to set display to given number

        output : function( val ){

            if( typeof val === 'number' ){

                this.display.innerHTML = val;
            }
        },

//      Sets sets given object to be the new display.
//      Copies the old output into new display.

        setDisplay : function( newScreen ){ // function

            if( typeof newScreen === 'object' ){

                newScreen.innerHTML = this.display.innerHTML;

                this.display = newScreen;
            }
        }
    }; // end view

//  These are the calculator's publicly facing methods.
//  They should be consided the controller.

//  Enter number is called when a user presses a digit, and takes that
//  digit as a param. If possible, enterNumber will pass that digit
//  to the inner calculator's update method.

    this.enterNumber = function(num){

        if( 'update' in model ){

//          Pass response from model's update method to the view
            view.output( model.update(num) );
        }
    };

//  Enter operator is called when a user presses an operator, and takes that
//  operator as a param. If possible, enterOperator will pass that operator
//  to the inner calculator's evaluate method.

    this.enterOperator = function(opp){

        if( 'evaluate' in model ){

//          Pass response from model's evaluate method to the view
            view.output( model.evaluate(opp) );
        }
    };

//  Clear is called when a user presses the clear button, and takes
//  no params. If possible, clear will call the inner calculator's
//  reset method.

    this.clear = function(){

        if( 'reset' in model ){

//          Pass response from model's reset method to the view
            view.output( model.reset() );
        }
    };

//  Set Display takes an object, and set it to be the
//  Calculator's new output field.

    this.setDisplay = function( obj ){

      view.setDisplay(obj);
    };

}; // end calculator definition

//    This is where the setup for the calculator happens. It's all
//    inside an anonymous function, so  the vars and the functions
//    will go away at the end.
//    (But if it defines getElementsByClassName, that will not.)

(function(){

//  First, I will check if document.getElementsByClassName is natifley
//  defined, and define it myself if not.

    checkGetClass();

//  Second, run setup routine, in which page elements are bound to
//  calculator methods.

//  Start by calling the calcuator's init method, passing
//  in an output element to be the display.

    calculator.setDisplay(document.getElementById('out'));

//  Move onto binding the numbers' click
//  event to the calculator's update method.

    var numbers = document.getElementsByClassName('number');

    for (var i = 0; i < numbers.length; i++) {

//      clicking a number will update the display and the temp variable

        numbers[i].onclick = function(){
              calculator.enterNumber(this.value); // this = a number btn
        }
    }

    var operators = document.getElementsByClassName('operator');

    for( var k = 0; k < operators.length; k++){

//      clicking an operator will make the calculator perform an operation.

        operators[k].onclick = function(){
              calculator.enterOperator(this.value); // this = a function btn
        }

    }

//  lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function(){
          calculator.clear();
    }

    function checkGetClass(){

        if (!('getElementsByClassName' in document)){

//         The following implementation is thanks to:
//         http://ejohn.org/blog/getelementsbyclassname-speed-comparison/#js-3

            document.getElementsByClassName = function (searchClass,node,tag) {
                var classElements = new Array();
                if ( node == null )
                    node = document;
                if ( tag == null )
                    tag = '*';
                var els = node.getElementsByTagName(tag);
                var elsLen = els.length;
                var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
                for (i = 0, j = 0; i < elsLen; i++) {
                    if ( pattern.test(els[i].className) ) {
                    classElements[j] = els[i];
                    j++;
                    }
                }
                return classElements;
            };

            // end implementation

      } // end if

    } // end checkGetClass

})(); // end the anonymouse function, and invoke it
<commit_msg>added some semicolons, fixed spelling error<commit_after>//  The calculator pseudoClass represents a four-function calculator.
//  The following both defines and constructs the singleton calculator object.

var calculator = new function(){

//  model pseudoclass is an internal representation of
//  the calculator's state.
//
//  By defining it as a var inside the pseudoclass, it
//  and its properties, and its methods are invisible
//  to the outside world.

    var model = {

        tally : 0, // running total since last clear

        operator : '+', // last operator pressed

        temp : 0, // number, as it entered by user

        isClear : true, // flag indicates whether there has been output

//      The evaluate function performs a computation.
//      First, it performs the stored operation on temp and tally.
//      Then it stores the given operation for the next evaluation.
//
//      Returns the state to show to user.

        evaluate : function(operate){

//          Special condition if there has not been output yet.

            if( this.isClear ){

                this.tally = this.temp;
                this.isClear = false;

            } else {

//              Perform the stored operation on tally and temp

                switch (this.operator){

                    case '+':
                        this.tally += this.temp;
                        break;

                    case '-':
                        this.tally -= this.temp;
                        break;

                    case 'x':
                        this.tally *= this.temp;
                        break;

                    case '/':
                        this.tally /= this.temp;
                        break;

                }
            }

//          In either case, update the display, and prepare for next input

            this.temp = 0; // reset temp
            this.operator = operate; // get ready to perform the given operation

            return this.tally; // user sees result of computation
        },

//      The update function will take string representing a single digit, and
//      append it to what the user has entered so far, both on the screen and
//      internally.
//      Returns the state to show to user.

        update : function(lastDigit){
            this.temp = (10 * this.temp) + parseInt(lastDigit);
            return this.temp; // user sees number entered thus far
        },

//      The reset function clears the calculator's instance variables, and
//      wipes the screen.

        reset : function(){
            this.tally = 0;
            this.operator = '+';
            this.temp = 0;
            this.isClear = true;
            return 0;
        }

    }; // end model

//  view is the representation of the screen.

    var view = {

//      the object holding the output.

        display : {innerHTML : "0"},

//      method to set display to given number

        output : function( val ){

            if( typeof val === 'number' ){

                this.display.innerHTML = val;
            }
        },

//      Sets sets given object to be the new display.
//      Copies the old output into new display.

        setDisplay : function( newScreen ){ // function

            if( typeof newScreen === 'object' ){

                newScreen.innerHTML = this.display.innerHTML;

                this.display = newScreen;
            }
        }
    }; // end view

//  These are the calculator's publicly facing methods.
//  They should be consided the controller.

//  Enter number is called when a user presses a digit, and takes that
//  digit as a param. If possible, enterNumber will pass that digit
//  to the inner calculator's update method.

    this.enterNumber = function(num){

        if( 'update' in model ){

//          Pass response from model's update method to the view
            view.output( model.update(num) );
        }
    };

//  Enter operator is called when a user presses an operator, and takes that
//  operator as a param. If possible, enterOperator will pass that operator
//  to the inner calculator's evaluate method.

    this.enterOperator = function(opp){

        if( 'evaluate' in model ){

//          Pass response from model's evaluate method to the view
            view.output( model.evaluate(opp) );
        }
    };

//  Clear is called when a user presses the clear button, and takes
//  no params. If possible, clear will call the inner calculator's
//  reset method.

    this.clear = function(){

        if( 'reset' in model ){

//          Pass response from model's reset method to the view
            view.output( model.reset() );
        }
    };

//  Set Display takes an object, and set it to be the
//  Calculator's new output field.

    this.setDisplay = function( obj ){

      view.setDisplay(obj);
    };

}; // end calculator definition

//    This is where the setup for the calculator happens. It's all
//    inside an anonymous function, so  the vars and the functions
//    will go away at the end.
//    (But if it defines getElementsByClassName, that will not.)

(function(){

//  First, I will check if document.getElementsByClassName is natifley
//  defined, and define it myself if not.

    checkGetClass();

//  Second, run setup routine, in which page elements are bound to
//  calculator methods.

//  Start by calling the calcuator's init method, passing
//  in an output element to be the display.

    calculator.setDisplay(document.getElementById('out'));

//  Move onto binding the numbers' click
//  event to the calculator's update method.

    var numbers = document.getElementsByClassName('number');

    for (var i = 0; i < numbers.length; i++) {

//      clicking a number will update the display and the temp variable

        numbers[i].onclick = function(){
              calculator.enterNumber(this.value); // this = a number btn
        };
    }

    var operators = document.getElementsByClassName('operator');

    for( var k = 0; k < operators.length; k++){

//      clicking an operator will make the calculator perform an operation.

        operators[k].onclick = function(){
              calculator.enterOperator(this.value); // this = a function btn
        };

    }

//  lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function(){
          calculator.clear();
    };

    function checkGetClass(){

        if (!('getElementsByClassName' in document)){

//         The following implementation is thanks to:
//         http://ejohn.org/blog/getelementsbyclassname-speed-comparison/#js-3

            document.getElementsByClassName = function (searchClass,node,tag) {
                var classElements = new Array();
                if ( node == null )
                    node = document;
                if ( tag == null )
                    tag = '*';
                var els = node.getElementsByTagName(tag);
                var elsLen = els.length;
                var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
                for (i = 0, j = 0; i < elsLen; i++) {
                    if ( pattern.test(els[i].className) ) {
                    classElements[j] = els[i];
                    j++;
                    }
                }
                return classElements;
            };

            // end implementation

      } // end if

    } // end checkGetClass

})(); // end the anonymous function, and invoke it
<|endoftext|>


<commit_before>var ws2801 = require('rpi-ws2801'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 100,
    loops: 5, // number of times to run the light loops i.e. for appointments booked
    currentLoop: 0,

    init: function () {

        socket = socket('https://appointments.spruce.me');

        ws2801.connect(this.totalLeds);

        socket.on('connect', function(){
            console.log('connected');
        });

        socket.on('did-book-appointments', function(){
            this.roll();
        }.bind(this));

    },
    //Create a pattern that is every other one
    //Acceptable values for each array are : 0 - 255
    //color: array[red, green, blue] e.g [255,0,0]
    dotted: function (colorOne, colorTwo) {
        _.times(this.totalLeds, function (i) {
            if (i % 2 == 1) {
                ws2801.setColor(i, colorOne);
            }
            else {
                ws2801.setColor(i, colorTwo);
            }
        });
        this.update();

    },
    roll: function() {

        if(this.currentLoop = 0) {
            this.clear();
        }

        console.log('calling roll');
        _(this.totalLeds).times(function(i) {
            setTimeout(function() {
                console.log('setting timeout', i);
                ws2801.setColor(i, [this.randomValue(), this.randomValue(), this.randomValue()]);
                ws2801.update();

                if(i == (this.totalLeds - 1)) {

                    if(this.currentLoop < this.loops) {
                        console.log('incrementing loop', this.currentLoop);
                        this.currentLoop++;
                        this.roll();
                    }
                    else
                    {
                        console.log('filling with white');
                        this.currentLoop = 0;
                        this.allWhite();
                    }
                }

            }.bind(this), 10 * i);
        }.bind(this));

    },
    runner: function () {

            var index = 0,
            i = 1,
            ri = 1,
            r = 0;

        setInterval(function () {

            ws2801.setColor(index, [r, 0, 255]);
            r += ri;
            index += i;
            ws2801.update();

            if (r >= 255 || r <= 0) {
                ri *= -1;
            }

            if (index >= this.totalLeds || index <= 0) {
                i *= -1;
            }
        }, 10);

    },
    // fill(r, g, b)
    // r, g, b: value as hex (0x00 = 0, 0xFF = 255, 0x7F = 127)
    fill: function (color1, color2, color3) {
        ws2801.fill(color1, color2, color3);
        //this.update();d
    },
    allWhite: function() {
        this.fill(255, 255, 255);
        this.update();
    },
    randomValue: function() {
        return Math.random() * (255 - 0) + 0;
    },
    invert: function () {
        ws2801.invert();
    },
    clear: function () {
        ws2801.clear();
    },
    update: function () {
        ws2801.update();
    },
    disconnect: function () {
        ws2801.disconnect();
    }

};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if(args.length > 0) {
    sign.allWhite();

    // We have passed a custom command, lets make sure we call that
    setTimeout(function() {
        sign[args[0]]()
    }, 5000);

}
else
{
    // Sign defaults to
    sign.allWhite();
}
<commit_msg>single equal bug like an amateur<commit_after>var ws2801 = require('rpi-ws2801'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 100,
    loops: 5, // number of times to run the light loops i.e. for appointments booked
    currentLoop: 0,

    init: function () {

        socket = socket('https://appointments.spruce.me');

        ws2801.connect(this.totalLeds);

        socket.on('connect', function(){
            console.log('connected');
        });

        socket.on('did-book-appointments', function(){
            this.roll();
        }.bind(this));

    },
    //Create a pattern that is every other one
    //Acceptable values for each array are : 0 - 255
    //color: array[red, green, blue] e.g [255,0,0]
    dotted: function (colorOne, colorTwo) {
        _.times(this.totalLeds, function (i) {
            if (i % 2 == 1) {
                ws2801.setColor(i, colorOne);
            }
            else {
                ws2801.setColor(i, colorTwo);
            }
        });
        this.update();

    },
    roll: function() {

        if(this.currentLoop == 0) {
            this.clear();
        }

        console.log('calling roll');
        _(this.totalLeds).times(function(i) {
            setTimeout(function() {
                console.log('setting timeout', i);
                ws2801.setColor(i, [this.randomValue(), this.randomValue(), this.randomValue()]);
                ws2801.update();

                if(i == (this.totalLeds - 1)) {

                    if(this.currentLoop < this.loops) {
                        console.log('incrementing loop', this.currentLoop);
                        this.currentLoop++;
                        this.roll();
                    }
                    else
                    {
                        console.log('filling with white');
                        this.currentLoop = 0;
                        this.allWhite();
                    }
                }

            }.bind(this), 10 * i);
        }.bind(this));

    },
    runner: function () {

            var index = 0,
            i = 1,
            ri = 1,
            r = 0;

        setInterval(function () {

            ws2801.setColor(index, [r, 0, 255]);
            r += ri;
            index += i;
            ws2801.update();

            if (r >= 255 || r <= 0) {
                ri *= -1;
            }

            if (index >= this.totalLeds || index <= 0) {
                i *= -1;
            }
        }, 10);

    },
    // fill(r, g, b)
    // r, g, b: value as hex (0x00 = 0, 0xFF = 255, 0x7F = 127)
    fill: function (color1, color2, color3) {
        ws2801.fill(color1, color2, color3);
        //this.update();d
    },
    allWhite: function() {
        this.fill(255, 255, 255);
        this.update();
    },
    randomValue: function() {
        return Math.random() * (255 - 0) + 0;
    },
    invert: function () {
        ws2801.invert();
    },
    clear: function () {
        ws2801.clear();
    },
    update: function () {
        ws2801.update();
    },
    disconnect: function () {
        ws2801.disconnect();
    }

};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if(args.length > 0) {
    sign.allWhite();

    // We have passed a custom command, lets make sure we call that
    setTimeout(function() {
        sign[args[0]]()
    }, 5000);

}
else
{
    // Sign defaults to
    sign.allWhite();
}
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});<commit_msg>Tests<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
},{
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('So you want to learn about Esther? Just say HELLO to get started.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {

            let upperText = message.text.trim().toUpperCase();

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                if (!_.has(scriptRules, upperText)) {
                    return bot.say(`I didn't understand that.`).then(() => 'speak');
                }

                var response = scriptRules[upperText];
                var lines = response.split(/(<img src=\'[^>]*\'\/>)/);

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    if (!line.startsWith("<")) {
                        p = p.then(function() {
                            return bot.say(line);
                        });
                    } else {
                        // p = p.then(function() {
                        //     var start = line.indexOf("'") + 1;
                        //     var end = line.lastIndexOf("'");
                        //     var imageFile = line.substring(start, end);
                        //     return bot.sendImage(imageFile);
                        // });
                    }
                })

                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});<|endoftext|>