<commit_before>$(document).ready(function() {
    var createTable = function(obj) {
      var maxLength = Math.max(Object.keys(obj.vNegTerms).length, Object.keys(obj.negTerms).length, Object.keys(obj.posTerms).length, Object.keys(obj.vPosTerms).length);
      if(maxLength > 4) maxLength = 4;
      returnText = '
' + 'Very Positve Terms' + '	'
      + '' + 'Positve Terms' + '	'
      + '' + 'Negative Terms' + '	'
      + '' + 'Very Negative Terms' + '	'
      + '
';
      for (var i = 0; i < maxLength; i++) {
        returnText += "
 " + Object.keys(obj.vPosTerms)[i] + "	"
        + "" + obj.vPosTerms[Object.keys(obj.vPosTerms)[i]] + '	'
        + "" + Object.keys(obj.posTerms)[i] + "	"
        + "" + obj.posTerms[Object.keys(obj.posTerms)[i]] + '	'
        + "" + Object.keys(obj.negTerms)[i] + "	"
        + "" + obj.negTerms[Object.keys(obj.negTerms)[i]] + '	'
        + '' + Object.keys(obj.vNegTerms)[i] + "	"
        + "" + obj.vNegTerms[Object.keys(obj.vNegTerms)[i]] + '	'
        + '
';
      }
      returnText = returnText.replace(/undefined/g, " ");
      return returnText;
    };
      var path = window.location.pathname;
      var params = path.substring(path.lastIndexOf('/') + 1);
      $.get("/api/lists/" + params, function(list){
        console.log(list); ///list-articles/:id
        console.log(list.title);
        document.title = list.title;
        $("h1 small").text(list.title);
        $("#list-description").text(list.description);
      });
     $.get("/api/list-articles/" + params, function(articles){
        console.log(articles);
        for(a in articles){
          var article = articles[a];
          console.log(article);
          $("#returnlist").append("
" + article.title +"

The sentiment of this text is " + article.sentiment + " (" + article.sentimentValue + ").
"
          + "Here are the words that affect the rating, and their frequency:
"
          + '
'
          + createTable(article)
          + '
' + "
");
        }
      });
    });
<commit_msg>text box edit<commit_after>$(document).ready(function() {
    var createTable = function(obj) {
      var maxLength = Math.max(Object.keys(obj.vNegTerms).length, Object.keys(obj.negTerms).length, Object.keys(obj.posTerms).length, Object.keys(obj.vPosTerms).length);
      if(maxLength > 4) maxLength = 4;
      returnText = '
' + 'Very Positve Terms' + '	'
      + '' + 'Positve Terms' + '	'
      + '' + 'Negative Terms' + '	'
      + '' + 'Very Negative Terms' + '	'
      + '
';
      for (var i = 0; i < maxLength; i++) {
        returnText += "
 " + Object.keys(obj.vPosTerms)[i] + "	"
        + "" + obj.vPosTerms[Object.keys(obj.vPosTerms)[i]] + '	'
        + "" + Object.keys(obj.posTerms)[i] + "	"
        + "" + obj.posTerms[Object.keys(obj.posTerms)[i]] + '	'
        + "" + Object.keys(obj.negTerms)[i] + "	"
        + "" + obj.negTerms[Object.keys(obj.negTerms)[i]] + '	'
        + '' + Object.keys(obj.vNegTerms)[i] + "	"
        + "" + obj.vNegTerms[Object.keys(obj.vNegTerms)[i]] + '	'
        + '
';
      }
      returnText = returnText.replace(/undefined/g, " ");
      return returnText;
    };
      var path = window.location.pathname;
      var params = path.substring(path.lastIndexOf('/') + 1);
      $.get("/api/lists/" + params, function(list){
        console.log(list); ///list-articles/:id
        console.log(list.title);
        document.title = list.title;
        $("h1 small").text(list.title);
        $("#list-description").text(list.description);
      });
     $.get("/api/list-articles/" + params, function(articles){
        console.log(articles);
        for(a in articles){
          var article = articles[a];
          console.log(article);
          $("#returnlist").append("
" + article.title +"

The sentiment of this text is " + article.sentiment + " (" + article.sentimentValue + ").
"
          + "Here are the values and frequencies of words which contributed to the rating:
"
          + '
'
          + createTable(article)
          + '
' + "
");
        }
      });
    });

<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.ar<commit_msg>Fixing a typo added in the last readme update<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.arg<|endoftext|>


<commit_before>var PREFIX = "artist";
var LINK_PREFIX = "link";
var EVENT_URL = "http://api.songkick.com/api/3.0/events.json?apikey=musichackdayboston&artists=";

$(document).ready(function(){
	//
});

function getPaddedDate() {
	var d = new Date();
	var month = zeroPad(d.getMonth() + 1 + "");
	var day = zeroPad(d.getDate() + "");

	var year = d.getFullYear();

	return year + "-" + month + "-" + day;
}

function zeroPad(numStr) {
	if (numStr.length < 2) {
		numStr = "0" + numStr;
	}

	return numStr;
}

function getShows() {
	var name = escape( $("#bandName").val() );
	var url = EVENT_URL + name + "&min_date=" + getPaddedDate() + "&max_date=" + getPaddedDate() + "&jsoncallback=?";

	// add in geolocation
	$("#info").html("
Searching
");

	$.getJSON(url,
	  function(data) {

		$("#info").html("");
		$("#headline").html("");
		$("#support").html("");

		if (!getTonightsShow(data)) {
			return;
		}

		getArtists(data);

	  });
}

function getTonightsShow(data) {
	// get the first event (assuming that artist will not perform more than once per night)
	var e = data.resultsPage.results.event[0];

	if (!e) {
		$("
No shows tonight!
").appendTo("#info");
		return false;
	}

	$("
Link: " + e.displayName + "
").appendTo("#info");

	return true;
}

// todo: check out link

function getArtists(data) {
	var openers = new Array();
	var e = data.resultsPage.results.event[0];

	$("

Support Acts:

").appendTo("#support");
	$("

Headlining Acts:

").appendTo("#headline");

	$(e.performance).each(function(index) {
		var pid = PREFIX + index;
		var str = "
" + this.artist.displayName + "";

		if (this.artist.identifier[0]) {
			var mbid = this.artist.identifier[0].mbid;
			getAudio(mbid, pid);

			str += "";
		} else {
			str += " -- No Musicbrainz ID. Sorry.";
		}

		console.log("closing p...");

		str += "
";

		if (this.billing == "support") {
			$(str).appendTo("#support");
		} else {
			$(str).appendTo("#headline");
		}
	});

	// pass musicbrainz artist id
}

// music brainz id and paragraph id to append to
function getAudio(mbid, pid) {
	var AUDIO_URL = '/artists/' + mbid + '/songs.json';

	// todo: add error checking to request
	var loading = "";

	$.getJSON(AUDIO_URL,
	  function(data) {
		var html = "
";

		$(data).each(function(index) {
			var id = LINK_PREFIX + pid + index;

			html += "
" + this.title + "
";
		});

		html += "
";

		$(html).insertAfter("#"+pid);

		$("#loadingBar").remove();

	  });
}

//
// todo: position player next to current song

function playAudio(url) {
	var player = "
<audio controls preload='auto' autobuffer><source src='" + url + "'/></audio>";
	var close = "X
"

	$("#audioPlayer").html(player + close);

	//console.log("playing " + url + "...");
}

function closePlayer() {
	$("#audioPlayer").html("");
}

var jp = "

play

pause

stop

min volume

max volume

";

function addPlayerTo(elemId, url) {
	// delete the player from the current element if it exists
	if ($("#playerContainer")) {
		$("#playerContainer").remove();
	}

	// Add jPlayer after link
	$(jp).appendTo("#"+elemId);

	// Local copy of jQuery selectors, for performance.
	var jpPlayTime = $("#jplayer_play_time");
	var jpTotalTime = $("#jplayer_total_time");

	$("#jquery_jplayer").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", url).jPlayer("play");
		},
		volume: 50
	})
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime.text($.jPlayer.convertTime(playedTime));
		jpTotalTime.text($.jPlayer.convertTime(totalTime));
	})
	.jPlayer("onSoundComplete", function() {
		this.element.jPlayer("play");
	});
}
<commit_msg>Added error checking to search field<commit_after>var PREFIX = "artist";
var LINK_PREFIX = "link";
var EVENT_URL = "http://api.songkick.com/api/3.0/events.json?apikey=musichackdayboston&artists=";

$(document).ready(function(){
	//
});

function getPaddedDate() {
	var d = new Date();
	var month = zeroPad(d.getMonth() + 1 + "");
	var day = zeroPad(d.getDate() + "");

	var year = d.getFullYear();

	return year + "-" + month + "-" + day;
}

function zeroPad(numStr) {
	if (numStr.length < 2) {
		numStr = "0" + numStr;
	}

	return numStr;
}

function getShows() {
	var name = escape( $("#bandName").val() );
	var url = EVENT_URL + name + "&min_date=" + getPaddedDate() + "&max_date=" + getPaddedDate() + "&jsoncallback=?";

	if (!name) {
		$("#info").html("
Who are you searching for? Please enter an artist!
");
		return;
	}

	// add in geolocation to event url &latitude=30.0&longitude=15.5&artist_name=name

	$("#info").html("
Searching
");

	$.getJSON(url,
	  function(data) {

		$("#info").html("");
		$("#headline").html("");
		$("#support").html("");

		if (!getTonightsShow(data)) {
			$("
No " + $("#bandName").val() + " shows tonight!
").appendTo("#info");
			return;
		}

		getArtists(data);

	  });
}

function getTonightsShow(data) {
	var e = data.resultsPage.results.event;

	// get the first event (assuming that artist will not perform more than once per night)
	if (e == undefined) {
		return false;
	}

	var e = e[0];

	$("
Link: " + e.displayName + "
").appendTo("#info");

	return true;
}

// todo: check out link

function getArtists(data) {
	var openers = new Array();
	var e = data.resultsPage.results.event[0];

	$("

Support Acts:

").appendTo("#support");
	$("

Headlining Acts:

").appendTo("#headline");

	$(e.performance).each(function(index) {
		var pid = PREFIX + index;
		var str = "
" + this.artist.displayName + "";

		if (this.artist.identifier[0]) {
			var mbid = this.artist.identifier[0].mbid;
			getAudio(mbid, pid);

			str += "";
		} else {
			str += " -- No Musicbrainz ID. Sorry.";
		}

		console.log("closing p...");

		str += "
";

		if (this.billing == "support") {
			$(str).appendTo("#support");
		} else {
			$(str).appendTo("#headline");
		}
	});

	// pass musicbrainz artist id
}

// music brainz id and paragraph id to append to
function getAudio(mbid, pid) {
	var AUDIO_URL = '/artists/' + mbid + '/songs.json';

	// todo: add error checking to request
	var loading = "";

	$.getJSON(AUDIO_URL,
	  function(data) {
		var html = "
";

		$(data).each(function(index) {
			var id = LINK_PREFIX + pid + index;

			html += "
" + this.title + "
";
		});

		html += "
";

		$(html).insertAfter("#"+pid);

		$("#loadingBar").remove();

	  });
}

//
// todo: position player next to current song

function playAudio(url) {
	var player = "
<audio controls preload='auto' autobuffer><source src='" + url + "'/></audio>";
	var close = "X
"

	$("#audioPlayer").html(player + close);

	//console.log("playing " + url + "...");
}

function closePlayer() {
	$("#audioPlayer").html("");
}

var jp = "

play

pause

stop

min volume

max volume

";

function addPlayerTo(elemId, url) {
	// delete the player from the current element if it exists
	if ($("#playerContainer")) {
		$("#playerContainer").remove();
	}

	// Add jPlayer after link
	$(jp).appendTo("#"+elemId);

	// Local copy of jQuery selectors, for performance.
	var jpPlayTime = $("#jplayer_play_time");
	var jpTotalTime = $("#jplayer_total_time");

	$("#jquery_jplayer").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", url).jPlayer("play");
		},
		volume: 50
	})
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime.text($.jPlayer.convertTime(playedTime));
		jpTotalTime.text($.jPlayer.convertTime(totalTime));
	})
	.jPlayer("onSoundComplete", function() {
		this.element.jPlayer("play");
	});
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added <commit_msg>Fixing a typo added in the last readme update<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a<|endoftext|>


<commit_before>$.fn.extend({
  animateCSS: function (name) {
    return this.addClass('animated ' + name).one('animationend', function () {
      $(this).removeClass('animated ' + name);
    });
  }
});

var Main = {
  init: function init () {

    this.results = {};
    this.step = 0;

    this
      .shuffle()
      .setDom()
      .listen()
      .setAdBg()
      .showHome();

    return this;
  },

  restart: function restart () {
    location.reload(true);
  },

  shuffle: function shuffleAnswers () {
    $('.page--question').shuffle();
    $('.progress__step').removeClass('progress__step--active');
    return this;
  },

  setDom: function setDom () {
    _.extend(this, {
      $body: $('body'),

      $pages: $('.page'),
      $questions: $('.page--question'),
      $answers: $('.answer'),

      $spinner1: $('#js-spinner-1'),
      $spinner2: $('#js-spinner-2'),

      $progress: $('#js-progress'),
    });

    $.ripple('.button', { duration: .4 });

    return this;
  },

  setAdBg: function setAdBg () {
    var background = store.get('adBg'),
        boy = '/images/ad-bg-1.gif',
        girl = '/images/ad-bg-2.gif';

    store.defaults({ adBg: boy });
    $('.page--ad').css('background-image', 'url(' + background + ')');
    store.set('adBg', background === boy ? girl : boy);

    return this;
  },

  listen: function listen () {
    var self = this;

    this.$answers
      .off('click.answer')
      .on('click.answer', this.selectAnswer.bind(this));

    $('#js-start')
      .off('click.start')
      .on('click.start', function (event) {
        event.preventDefault();
        clearInterval(self.homeInterval);
        setTimeout(self.showAuth.bind(self), 400);
      });

    $('#js-skip')
      .off('click.skip')
      .on('click.skip', function (event) {
        event.preventDefault();
        store.push('users', null);
        self.initQuiz();
      });

    PubSub.subscribe('user:register', function (label, user) {
      store.push('users', user);
      setTimeout(self.initQuiz.bind(self), 400);
    });

    $(document).contextmenu(function (e) {
      e.preventDefault();
    });

    return this;
  },

  tickSpinner: function tickSpinner (config) {
    this.$spinner1
      .find('.spinner__label')
      .html(config.total - config.current)
      .end()
      .find('.spinner__image')
      .shuffle()
      .addClass('hide')
      .eq(config.current)
      .removeClass('hide')
      .animateCSS('bounceIn');

    config.current++;

    return this;
  },

  endSpinner: function endSpinner (timer) {
    clearInterval(timer);
    this.showQuestion(0);
    return this;
  },

  initQuiz: function initQuiz () {
    var config = { total: 3, current: 0, }
        timer = setInterval(function () {
          if (config.current < config.total)
            this.tickSpinner(config);
          else
            this.endSpinner(timer);
        }.bind(this), 1000);

    this
      .showPage(2)
      .tickSpinner(config)
      .nextProgress();

    return this;
  },

  flipSpinner: function flipSpinner (config) {
    this.$spinner2
      .find('.spinner__image')
      .addClass('hide')
      .eq(config.current)
      .removeClass('hide');

    config.current++;

    return this;
  },

  showResult: function showResult (timer) {
    var results = this.results,
        lvl = _.reduce(results, function (memo, num) {
          return memo + num;
        }, 0) / _.size(results)
        name = lvl < 40 ? '30' : lvl < '60' ? '50' : lvl < '80' ? '70' : '90',

        user = _.last(store.get('users'));

    clearInterval(timer);

    store.push('results', {
      user: user,
      answers: results,
      level: Math.round(lvl)
    });

    $('.result__header')
      .hide()
      .filter('.result__header--' + name)
      .show();

    $('.nerdBar__label')
      .text(Math.round(lvl) + '%');

    setTimeout(function () {
      $('.nerdBar__content')
        .height(lvl + '%');
    }, 400);

    if (user)
      $('.result__heading')
        .append(document.createTextNode(' ' + user.nombre));

    this.nextPage();

    setTimeout(function () {
      $('.result__header:visible, .nerdBar').addClass('animated fadeOutUp');
      setTimeout(this.showAd.bind(this), 600);
    }.bind(this), 8400);

    return this;
  },

  endQuiz: function endQuiz () {
    var config = { total: 10, current: 0, }
        timer = setInterval(function () {
          if (config.current < config.total)
            this.flipSpinner(config);
          else
            this.showResult(timer);
        }.bind(this), 250);

    this.$answers
      .filter('.answer--isSelected')
      .find('img')
      .clone()
      .wrap(
        $('<div/>').addClass('spinner__image spinner__image--selected')
      )
      .parent()
      .appendTo(this.$spinner2);

    this
      .nextPage()
      .flipSpinner(config);

    return this;
  },

  getState: function getState () {
    return {
      step: this.step,
      results: this.results
    };
  },

  nextProgress: function nextProgress () {
    var $questions = this.$pages.filter('.page--question'),
        index = this.step - $questions.first().index() + 1;

    this.$progress
    //   .attr('data-length', (index + 1) / $questions.length * 100)
      .find('.progress__step')
      .eq(index)
      .addClass('progress__step--active');

    return this;
  },

  selectAnswer: function selectAnswer (event) {
    var $answer = $(event.target).closest('.answer');

    if ($answer.parent().has('.answer.animated').length)
      return this;

    this
      .setAnswer($answer.data('value'))
      .nextProgress();

    $answer
      .addClass('answer--isSelected')
      .addClass('animated tada')
      .one('animationend', this.nextQuestion.bind(this))
      .siblings()
      .removeClass('answer--isSelected')
      .addClass('animated bounceOut')
      .closest('.page--question')
      .find('.question__predicate')
      .removeClass('animated fadeInDown')
      .animateCSS('fadeOutUp');

    return this;
  },

  setAnswer: function setAnswer (value) {
    var $questions = this.$pages.filter('.page--question'),
        index = this.step - $questions.first().index() + 1;

    this.results[index] = parseInt(value, 10);

    return this;
  },

  showPage: function showPage (index) {
    var $page = this.$pages.hide().eq(index).show();
    this.step = index;

    this.$body
      .removeClass(function (index, name) {
        return (name.match(/(^|\s)page--\S+/g) || []).join(' ');
      })
      .addClass('page--' + $page.data('label'));

    return this;
  },

  nextPage: function nextPage () {
    this.showPage(this.step + 1);
    return this;
  },

  toggleHomeLoading: function toggleHomeLoading () {
    var $page = $('.page--home'),
        $intro = $page.find('.home__show__intro'),
        $after = $page.find('.home__show__after');

    $after.hide();
    $intro.show().find('img').animateCSS('fadeInDown');

    setTimeout(function () {
      $intro.find('img').animateCSS('fadeOutUp').one('animationend', function () {
        $intro.hide();

        $after.show().children().css('animation-delay', function () {
          return $(this).index() * .5 + 's';
        }).animateCSS('fadeInDown');
      });
    }, 5000);
  },

  showHome: function showHome () {
    this.showPage(0);

    this.toggleHomeLoading();
    this.homeInterval = setInterval(this.toggleHomeLoading.bind(this), 15000);

    return this;
  },

  showAd: function showAd () {
    var $page = $('.page--ad'),
        $intro = $page.find('.ad__show__intro'),
        $after = $page.find('.ad__show__after');

    $after.hide();
    $intro.show().children().css('animation-delay', function () {
      return $(this).index() * .5 + 's';
    }).animateCSS('fadeInDown');

    setTimeout(function () {
      $intro.children().addClass('animated fadeOutUp').last().one('animationend', function () {
        $intro.hide();

        $after.show().find('img').animateCSS('fadeInDown');
      });

      setTimeout(function () {
        this.restart();
      }.bind(this), 6000);
    }.bind(this), 4000);

    this.nextPage();
  },

  showAuth: function showAuth () {
    this.showPage(1);
    return this;
  },

  showQuestion: function showQuestion (index) {
    var $question = this.$pages.filter('.page--question').eq(index),
        $answers = $question.find('.answer');

    this.showPage($question.index());

    $answers
      .css('animation-delay', function () {
        return $(this).index() * .25 + 's';
      })
      .animateCSS('flipInY')
      .last()
      .one('animationend', function () {
        $answers.css('animation-delay', '0s');
      });

    return this;
  },

  nextQuestion: function nextQuestion () {
    var step = this.step,
        $questions = this.$pages.filter('.page--question');

    if (step < $questions.last().index())
      this.showQuestion(step - $questions.first().index() + 1);
    else
      this.endQuiz();

    return this;
  }
};

Main.init();
<commit_msg>Store question and answer as indexes may vary<commit_after>$.fn.extend({
  animateCSS: function (name) {
    return this.addClass('animated ' + name).one('animationend', function () {
      $(this).removeClass('animated ' + name);
    });
  }
});

var Main = {
  init: function init () {

    this.results = {};
    this.step = 0;

    this
      .shuffle()
      .setDom()
      .listen()
      .setAdBg()
      .showHome();

    return this;
  },

  restart: function restart () {
    location.reload(true);
  },

  shuffle: function shuffleAnswers () {
    $('.page--question').shuffle();
    $('.progress__step').removeClass('progress__step--active');
    return this;
  },

  setDom: function setDom () {
    _.extend(this, {
      $body: $('body'),

      $pages: $('.page'),
      $questions: $('.page--question'),
      $answers: $('.answer'),

      $spinner1: $('#js-spinner-1'),
      $spinner2: $('#js-spinner-2'),

      $progress: $('#js-progress'),
    });

    $.ripple('.button', { duration: .4 });

    return this;
  },

  setAdBg: function setAdBg () {
    var background = store.get('adBg'),
        boy = '/images/ad-bg-1.gif',
        girl = '/images/ad-bg-2.gif';

    store.defaults({ adBg: boy });
    $('.page--ad').css('background-image', 'url(' + background + ')');
    store.set('adBg', background === boy ? girl : boy);

    return this;
  },

  listen: function listen () {
    var self = this;

    this.$answers
      .off('click.answer')
      .on('click.answer', this.selectAnswer.bind(this));

    $('#js-start')
      .off('click.start')
      .on('click.start', function (event) {
        event.preventDefault();
        clearInterval(self.homeInterval);
        setTimeout(self.showAuth.bind(self), 400);
      });

    $('#js-skip')
      .off('click.skip')
      .on('click.skip', function (event) {
        event.preventDefault();
        store.push('users', null);
        self.initQuiz();
      });

    PubSub.subscribe('user:register', function (label, user) {
      store.push('users', user);
      setTimeout(self.initQuiz.bind(self), 400);
    });

    $(document).contextmenu(function (e) {
      e.preventDefault();
    });

    return this;
  },

  tickSpinner: function tickSpinner (config) {
    this.$spinner1
      .find('.spinner__label')
      .html(config.total - config.current)
      .end()
      .find('.spinner__image')
      .shuffle()
      .addClass('hide')
      .eq(config.current)
      .removeClass('hide')
      .animateCSS('bounceIn');

    config.current++;

    return this;
  },

  endSpinner: function endSpinner (timer) {
    clearInterval(timer);
    this.showQuestion(0);
    return this;
  },

  initQuiz: function initQuiz () {
    var config = { total: 3, current: 0, }
        timer = setInterval(function () {
          if (config.current < config.total)
            this.tickSpinner(config);
          else
            this.endSpinner(timer);
        }.bind(this), 1000);

    this
      .showPage(2)
      .tickSpinner(config)
      .nextProgress();

    return this;
  },

  flipSpinner: function flipSpinner (config) {
    this.$spinner2
      .find('.spinner__image')
      .addClass('hide')
      .eq(config.current)
      .removeClass('hide');

    config.current++;

    return this;
  },

  showResult: function showResult (timer) {
    var results = this.results,
        lvl = _.reduce(results, function (memo, answer) {
          return memo + answer.value;
        }, 0) / _.size(results)
        name = lvl < 40 ? '30' : lvl < '60' ? '50' : lvl < '80' ? '70' : '90',

        user = _.last(store.get('users'));

    clearInterval(timer);

    store.push('results', {
      user: user,
      answers: results,
      level: Math.round(lvl)
    });

    $('.result__header')
      .hide()
      .filter('.result__header--' + name)
      .show();

    $('.nerdBar__label')
      .text(Math.round(lvl) + '%');

    setTimeout(function () {
      $('.nerdBar__content')
        .height(lvl + '%');
    }, 400);

    if (user)
      $('.result__heading')
        .append(document.createTextNode(' ' + user.nombre));

    this.nextPage();

    setTimeout(function () {
      $('.result__header:visible, .nerdBar').addClass('animated fadeOutUp');
      setTimeout(this.showAd.bind(this), 600);
    }.bind(this), 8400);

    return this;
  },

  endQuiz: function endQuiz () {
    var config = { total: 10, current: 0, }
        timer = setInterval(function () {
          if (config.current < config.total)
            this.flipSpinner(config);
          else
            this.showResult(timer);
        }.bind(this), 250);

    this.$answers
      .filter('.answer--isSelected')
      .find('img')
      .clone()
      .wrap(
        $('<div/>').addClass('spinner__image spinner__image--selected')
      )
      .parent()
      .appendTo(this.$spinner2);

    this
      .nextPage()
      .flipSpinner(config);

    return this;
  },

  getState: function getState () {
    return {
      step: this.step,
      results: this.results
    };
  },

  nextProgress: function nextProgress () {
    var $questions = this.$pages.filter('.page--question'),
        index = this.step - $questions.first().index() + 1;

    this.$progress
    //   .attr('data-length', (index + 1) / $questions.length * 100)
      .find('.progress__step')
      .eq(index)
      .addClass('progress__step--active');

    return this;
  },

  selectAnswer: function selectAnswer (event) {
    var $answer = $(event.target).closest('.answer');

    if ($answer.parent().has('.answer.animated').length)
      return this;

    this
      .setAnswer({
        question: $answer.closest('.page--question').find('.question__predicate').text(),
        answer: $answer.find('.answer__title').text(),
        value: parseInt($answer.data('value'), 10)
      })
      .nextProgress();

    $answer
      .addClass('answer--isSelected')
      .addClass('animated tada')
      .one('animationend', this.nextQuestion.bind(this))
      .siblings()
      .removeClass('answer--isSelected')
      .addClass('animated bounceOut')
      .closest('.page--question')
      .find('.question__predicate')
      .removeClass('animated fadeInDown')
      .animateCSS('fadeOutUp');

    return this;
  },

  setAnswer: function setAnswer (answer) {
    var $questions = this.$pages.filter('.page--question'),
        index = this.step - $questions.first().index() + 1;

    this.results[index] = answer;

    return this;
  },

  showPage: function showPage (index) {
    var $page = this.$pages.hide().eq(index).show();
    this.step = index;

    this.$body
      .removeClass(function (index, name) {
        return (name.match(/(^|\s)page--\S+/g) || []).join(' ');
      })
      .addClass('page--' + $page.data('label'));

    return this;
  },

  nextPage: function nextPage () {
    this.showPage(this.step + 1);
    return this;
  },

  toggleHomeLoading: function toggleHomeLoading () {
    var $page = $('.page--home'),
        $intro = $page.find('.home__show__intro'),
        $after = $page.find('.home__show__after');

    $after.hide();
    $intro.show().find('img').animateCSS('fadeInDown');

    setTimeout(function () {
      $intro.find('img').animateCSS('fadeOutUp').one('animationend', function () {
        $intro.hide();

        $after.show().children().css('animation-delay', function () {
          return $(this).index() * .5 + 's';
        }).animateCSS('fadeInDown');
      });
    }, 5000);
  },

  showHome: function showHome () {
    this.showPage(0);

    this.toggleHomeLoading();
    this.homeInterval = setInterval(this.toggleHomeLoading.bind(this), 15000);

    return this;
  },

  showAd: function showAd () {
    var $page = $('.page--ad'),
        $intro = $page.find('.ad__show__intro'),
        $after = $page.find('.ad__show__after');

    $after.hide();
    $intro.show().children().css('animation-delay', function () {
      return $(this).index() * .5 + 's';
    }).animateCSS('fadeInDown');

    setTimeout(function () {
      $intro.children().addClass('animated fadeOutUp').last().one('animationend', function () {
        $intro.hide();

        $after.show().find('img').animateCSS('fadeInDown');
      });

      setTimeout(function () {
        this.restart();
      }.bind(this), 6000);
    }.bind(this), 4000);

    this.nextPage();
  },

  showAuth: function showAuth () {
    this.showPage(1);
    return this;
  },

  showQuestion: function showQuestion (index) {
    var $question = this.$pages.filter('.page--question').eq(index),
        $answers = $question.find('.answer');

    this.showPage($question.index());

    $answers
      .css('animation-delay', function () {
        return $(this).index() * .25 + 's';
      })
      .animateCSS('flipInY')
      .last()
      .one('animationend', function () {
        $answers.css('animation-delay', '0s');
      });

    return this;
  },

  nextQuestion: function nextQuestion () {
    var step = this.step,
        $questions = this.$pages.filter('.page--question');

    if (step < $questions.last().index())
      this.showQuestion(step - $questions.first().index() + 1);
    else
      this.endQuiz();

    return this;
  }
};

Main.init();
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,d<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,da<|endoftext|>


<commit_before>// --------------------------------------------------------------------------------------
// define angular module/app
//var etlog = angular.module('etlog', ['ngRoute']);
var etlog = angular.module('etlog', ['ui.router']);
// --------------------------------------------------------------------------------------
<commit_msg>delete comment<commit_after>// --------------------------------------------------------------------------------------
// define angular module/app
var etlog = angular.module('etlog', ['ui.router']);
// --------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, ou<commit_msg>One more time...<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, out<|endoftext|>


<commit_before>/*global document:true, requirejs:true */
'use strict';

requirejs.config({
  baseUrl: '/javascripts/',
  enforceDefine: true,
  paths: {
    jquery: '/javascripts/jquery'
  }
});

define(['jquery', 'appnet', 'friends', 'user', 'jquery.caret'],
  function($, appnet, friends, user) {
  var body = $('body');
  var url = body.data('url');
  var tabs = body.find('ol.tabs');
  var messages = body.find('ol.messages');
  var write = body.find('.write form');
  var userInfo = body.find('.user-info');
  var overlay = body.find('#overlay');
  var charLimit = body.find('.counter');
  var suggestions = body.find('ol.suggestions');
  var notifications = body.find('#notifications-preview');
  var notificationIcon = body.find('#notifications');
  var win = $(window);
  var doc = $(document);
  var csrf = write.find('input[name="_csrf"]').val();
  var postLoad = false;
  var notificationsDisplay = false;
  var currentMessage;

  var CHAR_MAX = parseInt(body.data('charlimit'), 10);
  var TAB_KEYCODE = 9;
  var ESCAPE_KEYCODE = 27;
  var MESSAGE_LIMIT = 99;

  var resetNotificationDisplay = function() {
    notificationIcon
      .removeClass('on')
      .text(0);
    document.title = 'NoodleApp';
    appnet.resetUnread();
  };

  var resetTab = function(self, callback) {
    self.siblings().removeClass('selected');
    self.addClass('selected');
    callback();
  };

  var checkUrl = function() {
    if (document.location.hash.indexOf('/post/') > -1) {
      var postArray = document.location.hash.split('/post/')[1].split('/');
      var postId = postArray[0];
      var usernameId = postArray[1];
      appnet.showPost(postId, usernameId);
      body.addClass('fixed');
    }
  };

  // Length of actual text that will be posted to app.net
  var getEffectiveLength = function(text) {
    // Same as in markdown-to-entities, but global
    var markdownLinkRegex = /\[([^\]]+)\]\((\S+(?=\)))\)/g;
    return text.replace(markdownLinkRegex, '$1').length;
  };

  var checkCharLimit = function(text) {
    var textLength = getEffectiveLength(text);
    write.find('button').toggleClass('disabled', textLength === 0);
    if (textLength > CHAR_MAX) {
      charLimit.addClass('over');
      charLimit.text('- ' + (textLength - CHAR_MAX));
    } else {
      charLimit.removeClass('over');
      charLimit.text(CHAR_MAX - textLength);
    }
  };

  var updateFeed = function(self, callback) {
    messages.empty();
    resetTab(self, function() {
      callback();
    });
  };

  var closeOverlay = function() {
    window.history.pushState('', '', document.location.href.split('#')[0]);
    overlay.find('.inner-overlay').html('');
    overlay.find('textarea').val('');
    overlay.slideUp(function() {
      body.removeClass('fixed');
    });
  };

  var saveSettings = function(self) {
    var directedFeed = false;
    var mediaOn = false;
    var charLimit = false;

    if (self.hasClass('on')) {
      self.removeClass('on');
    } else {
      self.addClass('on');
    }

    if (overlay.find('#directed-feed').hasClass('on')) {
      directedFeed = true;
    }

    if (overlay.find('#media-on').hasClass('on')) {
      mediaOn = true;
    }

    if (overlay.find('#charlimit').hasClass('on')) {
      charLimit = true;
    }

    user.saveSettings(directedFeed, mediaOn, charLimit, write.find('input[name="_csrf"]').val());
  };

  /* Feed functionality */
  tabs.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('global-feed'):
        updateFeed(self, function() {
          appnet.getGlobalFeed();
        });
        break;

      case self.hasClass('user-posts'):
        updateFeed(self, function() {
          appnet.getUserPosts();
        });
        break;

      case self.hasClass('user-mentions'):
        updateFeed(self, function() {
          appnet.getUserMentions();
        });
        break;

      case self.hasClass('user-starred'):
        updateFeed(self, function() {
          appnet.getUserStarred();
        });
        break;

      default:
        updateFeed(self, function() {
          appnet.getMyFeed();
        });
        break;
    }
  });

  /* Automatic feed loader */
  tabs.find('.selected').click();

  /* Message functionality */
  messages.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('reply'):
        self.closest('.message-item').find('time').click();
        break;

      case self.hasClass('quote'):
        var textarea = self.closest('.dashboard-content').find('textarea');
        textarea.focus();
        write.find('.form-action-wrapper').slideDown('fast');
        textarea.val('"' + self.closest('.message-item').data('original') + '"');
        break;

      case self.hasClass('delete'):
        appnet.deleteMessage(self.closest('.message-item').data('id'), csrf);
        self.closest('li.message-item').fadeOut();
        break;

      case self.hasClass('thread'):
        appnet.showThread(self.closest('.message-item').data('id'));
        body.addClass('fixed');
        break;

      case self.is('#paginated'):
        appnet.getOlderPosts(self.prev().data('id'));
        break;
    }
  });

  var windowHasScrolled = false;
  var scollCheck = setInterval(function () {
    if (windowHasScrolled) {
      var nearBottom = win.scrollTop() > doc.height() - win.height() - 200;
      if (nearBottom) {
        $('#paginated').click();
      }
    }
    windowHasScrolled = false;
  }, 100);

  win.on('scroll', function () {
    windowHasScrolled = true;
  });

  // Overlay functionality
  overlay.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('reply'):
        var messageItem = self.closest('.message-item');
        var mentions = (messageItem.data('mentions') !== '') ? messageItem.data('mentions') + ' ' : '';

        overlay.find('textarea')
          .focus()
          .val('@' + messageItem.data('username') + ' ' + mentions);

        if (parseInt(messageItem.data('replyto'), 10) > 0) {
          overlay.find('.reply_to').val(messageItem.data('replyto'));

        } else {
         overlay.find('.reply_to').val(messageItem.data('id'));
        }
        break;

      case self.hasClass('close'):
        closeOverlay();
        break;

      case self.hasClass('quote'):
        var textarea = overlay.find('textarea');
        textarea.focus();
        overlay.find('.form-action-wrapper').slideDown('fast');
        textarea.val('"' + self.closest('.message-item').data('original') + '"');
        break;
    }
  });

  // General activity for all shared functionality
  body.on('click', function(ev) {
    var self = $(ev.target);

    if (!self.hasClass('writeable')) {
      suggestions.empty();
    }

    if (notificationsDisplay &&
      !(self.is('#notifications-preview') ||
      self.is('#notifications') ||
      self.closest('#notifications-preview').length)) {

      notifications.slideUp();
      notificationsDisplay = false;
    }

    switch (true) {
      case self.hasClass('star'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.find('span').text('Star');
          appnet.unstarMessage(self.closest('.message-item').data('id'), csrf);
        } else {
          self.addClass('on');
          self.find('span').text('Unstar');
          appnet.starMessage(self.closest('.message-item').data('id'), csrf);
        }
        break;

      case self.hasClass('repost'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.find('span').text('Repost');
          appnet.unrepostMessage(self.closest('.message-item').data('id'), csrf);
        } else {
          self.addClass('on');
          self.find('span').text('Unrepost');
          appnet.repostMessage(self.closest('.message-item').data('id'), csrf);
        }
        break;

      case self.is('time'):
        var textarea = overlay.find('textarea');
        var closest = self.closest('.message-item');

        document.location.hash = '/post/' + closest.data('id') +
          '/' + closest.data('username');
        break;

      case self.is('#notifications'):
        var self = $(this);
        resetNotificationDisplay();

        if (!notificationsDisplay) {
          notifications.slideDown();
          notificationsDisplay = true;

        } else {
          notifications.slideUp();
          notificationsDisplay = false;
        }
        break;

      case self.hasClass('tags'):
        ev.preventDefault();
        appnet.showTagged(self.attr('href').split('/tagged/')[1]);
        body.addClass('fixed');
        break;

      case self.is('#settings-link'):
        user.getSettings();
        break;

      case self.is('#charlimit'):
      case self.is('#media-on'):
      case self.is('#directed-feed'):
        saveSettings(self);
        break;

      case self.parent().is('#unread-messages'):
        appnet.clearUnread(self.parent());
        resetNotificationDisplay();
        break;
    }
  });

  var keyCodeToClassName = {
    84: '.thread', // t
    83: '.star', // s
    82: '.reply', // r
    80: '.repost', // p
    81: '.quote'  // q
  };

  var actionKeyCodes = $.map(keyCodeToClassName, function  (val, key) { return (+ key); });

  body.on('keydown', function(ev) {
    var self = $(ev.target);

    if (ev.keyCode === ESCAPE_KEYCODE && body.hasClass('fixed')) {
      closeOverlay();
    }

    switch (true) {
      case self.hasClass('submittable'):
        if (ev.keyCode === 9 || ev.keyCode === 32) {
          // Pressing TAB/space autocompletes to the first user listed.
          var userLi = suggestions.find('li:first');
          if (userLi.length) {
            friends.setUser(userLi, self, self.getCursorPosition());
            suggestions.empty();
            return false;
          }

        } else if (ev.keyCode === 13 && (ev.ctrlKey || ev.metaKey)) {
          self.closest('form').submit();
        }
    }

    if (ev.keyCode === 75 || ev.keyCode === 74) {
      currentMessage = body.find('.message-item.hover');
      if (!currentMessage.length) {
        currentMessage = body.find('.message-item:first');
        currentMessage.addClass('hover');
        return;
      }

      var next;
      if (ev.keyCode === 75) {
        next = currentMessage.prev('.message-item');
      } else {
        next = currentMessage.next('.message-item');
      }

      if (next.length) {
        currentMessage.removeClass('hover');
        next.addClass('hover');
        $(window).scrollTop(next.position().top - 40);
        currentMessage = next;
      }
    }

    if (currentMessage && $.inArray(ev.keyCode, actionKeyCodes) !== -1){
      currentMessage.find(keyCodeToClassName[ev.keyCode]).click();
    }

  });

  /* User functionality */
  userInfo.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('followers'):
        appnet.showFollowers();
        body.addClass('fixed');
        break;

      case self.hasClass('following'):
        appnet.showFollowing();
        body.addClass('fixed');
        break;

      case self.hasClass('follow'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.text('Follow');
          appnet.unfollow(self.parent().data('userid'), self.parent().data('username'), csrf);

        } else {
          self.addClass('on');
          self.text('Unfollow');
          appnet.follow(self.parent().data('userid'), self.parent().data('username'), csrf);
        }
        break;

      case self.hasClass('mute'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.text('Mute');
          appnet.unmute(self.parent().data('userid'), self.parent().data('username'), csrf);

        } else {
          self.addClass('on');
          self.text('Unmute');
          appnet.mute(self.parent().data('userid'), self.parent().data('username'), csrf);
        }
        break;
    }
  });

  checkUrl();

  $(window).bind('hashchange', function() {
    checkUrl();
  });

  /* Notifications */
  notifications.on('click', '.notification-item', function(ev) {
    ev.preventDefault();
    var self = $(this);

    notifications.slideUp();
    appnet.showPost(self.data('postid'), self.data('username'));
    body.addClass('fixed');
  });

  /* Write functionality */

  checkCharLimit(write.find('textarea').val());

  write.find('textarea').focus(function() {
    var self = $(this);
    self.addClass('on');
    charLimit.addClass('on');
    checkCharLimit(self.val());
    self.closest('form').find('.form-action-wrapper').slideDown('fast');
  });

  write.find('textarea').blur(function() {
    var self = $(this);

    charLimit.removeClass('on');

    if (self.val().replace(/\s/, '').length < 1) {
      self.removeClass('on');
      self.closest('form').find('.form-action-wrapper').slideUp('fast');
    }
  });

  // Clear the reply_to id if this is empty
  write.find('textarea').keyup(function(evt) {
    var self = $(this);
    checkCharLimit(self.val());
    friends.getBFFs(self, self.getCursorPosition());
    if (self.val().trim().length === 0) {
      write.find('.reply_to').val('');
    }

  })

  write.submit(function(ev) {
    ev.preventDefault();

    var self = $(this);
    appnet.postMessage(self);
    url = '/my/feed';
    self.find('textarea').val('');
    charLimit.text(CHAR_MAX);
    write.find('.reply_to').val('');
    return false;
  });

  suggestions.on('click', 'li', function() {
    var self = $(this);
    var textarea = self.closest('form').find('textarea');
    friends.setUser(self, textarea, textarea.getCursorPosition());
  });
});
<commit_msg>ignore shortcut keys if typing<commit_after>/*global document:true, requirejs:true */
'use strict';

requirejs.config({
  baseUrl: '/javascripts/',
  enforceDefine: true,
  paths: {
    jquery: '/javascripts/jquery'
  }
});

define(['jquery', 'appnet', 'friends', 'user', 'jquery.caret'],
  function($, appnet, friends, user) {
  var body = $('body');
  var url = body.data('url');
  var tabs = body.find('ol.tabs');
  var messages = body.find('ol.messages');
  var write = body.find('.write form');
  var userInfo = body.find('.user-info');
  var overlay = body.find('#overlay');
  var charLimit = body.find('.counter');
  var suggestions = body.find('ol.suggestions');
  var notifications = body.find('#notifications-preview');
  var notificationIcon = body.find('#notifications');
  var win = $(window);
  var doc = $(document);
  var csrf = write.find('input[name="_csrf"]').val();
  var postLoad = false;
  var notificationsDisplay = false;
  var currentMessage;

  var CHAR_MAX = parseInt(body.data('charlimit'), 10);
  var TAB_KEYCODE = 9;
  var ESCAPE_KEYCODE = 27;
  var MESSAGE_LIMIT = 99;

  var resetNotificationDisplay = function() {
    notificationIcon
      .removeClass('on')
      .text(0);
    document.title = 'NoodleApp';
    appnet.resetUnread();
  };

  var resetTab = function(self, callback) {
    self.siblings().removeClass('selected');
    self.addClass('selected');
    callback();
  };

  var checkUrl = function() {
    if (document.location.hash.indexOf('/post/') > -1) {
      var postArray = document.location.hash.split('/post/')[1].split('/');
      var postId = postArray[0];
      var usernameId = postArray[1];
      appnet.showPost(postId, usernameId);
      body.addClass('fixed');
    }
  };

  // Length of actual text that will be posted to app.net
  var getEffectiveLength = function(text) {
    // Same as in markdown-to-entities, but global
    var markdownLinkRegex = /\[([^\]]+)\]\((\S+(?=\)))\)/g;
    return text.replace(markdownLinkRegex, '$1').length;
  };

  var checkCharLimit = function(text) {
    var textLength = getEffectiveLength(text);
    write.find('button').toggleClass('disabled', textLength === 0);
    if (textLength > CHAR_MAX) {
      charLimit.addClass('over');
      charLimit.text('- ' + (textLength - CHAR_MAX));
    } else {
      charLimit.removeClass('over');
      charLimit.text(CHAR_MAX - textLength);
    }
  };

  var updateFeed = function(self, callback) {
    messages.empty();
    resetTab(self, function() {
      callback();
    });
  };

  var closeOverlay = function() {
    window.history.pushState('', '', document.location.href.split('#')[0]);
    overlay.find('.inner-overlay').html('');
    overlay.find('textarea').val('');
    overlay.slideUp(function() {
      body.removeClass('fixed');
    });
  };

  var saveSettings = function(self) {
    var directedFeed = false;
    var mediaOn = false;
    var charLimit = false;

    if (self.hasClass('on')) {
      self.removeClass('on');
    } else {
      self.addClass('on');
    }

    if (overlay.find('#directed-feed').hasClass('on')) {
      directedFeed = true;
    }

    if (overlay.find('#media-on').hasClass('on')) {
      mediaOn = true;
    }

    if (overlay.find('#charlimit').hasClass('on')) {
      charLimit = true;
    }

    user.saveSettings(directedFeed, mediaOn, charLimit, write.find('input[name="_csrf"]').val());
  };

  /* Feed functionality */
  tabs.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('global-feed'):
        updateFeed(self, function() {
          appnet.getGlobalFeed();
        });
        break;

      case self.hasClass('user-posts'):
        updateFeed(self, function() {
          appnet.getUserPosts();
        });
        break;

      case self.hasClass('user-mentions'):
        updateFeed(self, function() {
          appnet.getUserMentions();
        });
        break;

      case self.hasClass('user-starred'):
        updateFeed(self, function() {
          appnet.getUserStarred();
        });
        break;

      default:
        updateFeed(self, function() {
          appnet.getMyFeed();
        });
        break;
    }
  });

  /* Automatic feed loader */
  tabs.find('.selected').click();

  /* Message functionality */
  messages.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('reply'):
        self.closest('.message-item').find('time').click();
        break;

      case self.hasClass('quote'):
        var textarea = self.closest('.dashboard-content').find('textarea');
        textarea.focus();
        write.find('.form-action-wrapper').slideDown('fast');
        textarea.val('"' + self.closest('.message-item').data('original') + '"');
        break;

      case self.hasClass('delete'):
        appnet.deleteMessage(self.closest('.message-item').data('id'), csrf);
        self.closest('li.message-item').fadeOut();
        break;

      case self.hasClass('thread'):
        appnet.showThread(self.closest('.message-item').data('id'));
        body.addClass('fixed');
        break;

      case self.is('#paginated'):
        appnet.getOlderPosts(self.prev().data('id'));
        break;
    }
  });

  var windowHasScrolled = false;
  var scollCheck = setInterval(function () {
    if (windowHasScrolled) {
      var nearBottom = win.scrollTop() > doc.height() - win.height() - 200;
      if (nearBottom) {
        $('#paginated').click();
      }
    }
    windowHasScrolled = false;
  }, 100);

  win.on('scroll', function () {
    windowHasScrolled = true;
  });

  // Overlay functionality
  overlay.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('reply'):
        var messageItem = self.closest('.message-item');
        var mentions = (messageItem.data('mentions') !== '') ? messageItem.data('mentions') + ' ' : '';

        overlay.find('textarea')
          .focus()
          .val('@' + messageItem.data('username') + ' ' + mentions);

        if (parseInt(messageItem.data('replyto'), 10) > 0) {
          overlay.find('.reply_to').val(messageItem.data('replyto'));

        } else {
         overlay.find('.reply_to').val(messageItem.data('id'));
        }
        break;

      case self.hasClass('close'):
        closeOverlay();
        break;

      case self.hasClass('quote'):
        var textarea = overlay.find('textarea');
        textarea.focus();
        overlay.find('.form-action-wrapper').slideDown('fast');
        textarea.val('"' + self.closest('.message-item').data('original') + '"');
        break;
    }
  });

  // General activity for all shared functionality
  body.on('click', function(ev) {
    var self = $(ev.target);

    if (!self.hasClass('writeable')) {
      suggestions.empty();
    }

    if (notificationsDisplay &&
      !(self.is('#notifications-preview') ||
      self.is('#notifications') ||
      self.closest('#notifications-preview').length)) {

      notifications.slideUp();
      notificationsDisplay = false;
    }

    switch (true) {
      case self.hasClass('star'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.find('span').text('Star');
          appnet.unstarMessage(self.closest('.message-item').data('id'), csrf);
        } else {
          self.addClass('on');
          self.find('span').text('Unstar');
          appnet.starMessage(self.closest('.message-item').data('id'), csrf);
        }
        break;

      case self.hasClass('repost'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.find('span').text('Repost');
          appnet.unrepostMessage(self.closest('.message-item').data('id'), csrf);
        } else {
          self.addClass('on');
          self.find('span').text('Unrepost');
          appnet.repostMessage(self.closest('.message-item').data('id'), csrf);
        }
        break;

      case self.is('time'):
        var textarea = overlay.find('textarea');
        var closest = self.closest('.message-item');

        document.location.hash = '/post/' + closest.data('id') +
          '/' + closest.data('username');
        break;

      case self.is('#notifications'):
        var self = $(this);
        resetNotificationDisplay();

        if (!notificationsDisplay) {
          notifications.slideDown();
          notificationsDisplay = true;

        } else {
          notifications.slideUp();
          notificationsDisplay = false;
        }
        break;

      case self.hasClass('tags'):
        ev.preventDefault();
        appnet.showTagged(self.attr('href').split('/tagged/')[1]);
        body.addClass('fixed');
        break;

      case self.is('#settings-link'):
        user.getSettings();
        break;

      case self.is('#charlimit'):
      case self.is('#media-on'):
      case self.is('#directed-feed'):
        saveSettings(self);
        break;

      case self.parent().is('#unread-messages'):
        appnet.clearUnread(self.parent());
        resetNotificationDisplay();
        break;
    }
  });

  var keyCodeToClassName = {
    84: '.thread', // t
    83: '.star', // s
    82: '.reply', // r
    80: '.repost', // p
    81: '.quote'  // q
  };

  var actionKeyCodes = $.map(keyCodeToClassName, function  (val, key) { return (+ key); });

  body.on('keydown', function(ev) {
    var self = $(ev.target);

    if (ev.keyCode === ESCAPE_KEYCODE && body.hasClass('fixed')) {
      closeOverlay();
    }

    switch (true) {
      case self.hasClass('submittable'):
        if (ev.keyCode === 9 || ev.keyCode === 32) {
          // Pressing TAB/space autocompletes to the first user listed.
          var userLi = suggestions.find('li:first');
          if (userLi.length) {
            friends.setUser(userLi, self, self.getCursorPosition());
            suggestions.empty();
            return false;
          }

        } else if (ev.keyCode === 13 && (ev.ctrlKey || ev.metaKey)) {
          self.closest('form').submit();
        }
    }

    if (!self.is('textarea')) {
      if (ev.keyCode === 75 || ev.keyCode === 74) {
        currentMessage = body.find('.message-item.hover');
        if (!currentMessage.length) {
          currentMessage = body.find('.message-item:first');
          currentMessage.addClass('hover');
          return;
        }

        var next;
        if (ev.keyCode === 75) {
          next = currentMessage.prev('.message-item');
        } else {
          next = currentMessage.next('.message-item');
        }

        if (next.length) {
          currentMessage.removeClass('hover');
          next.addClass('hover');
          $(window).scrollTop(next.position().top - 40);
          currentMessage = next;
        }
      }

      if (currentMessage && $.inArray(ev.keyCode, actionKeyCodes) !== -1){
        currentMessage.find(keyCodeToClassName[ev.keyCode]).click();
      }
    }
  });

  /* User functionality */
  userInfo.on('click', function(ev) {
    var self = $(ev.target);

    switch (true) {
      case self.hasClass('followers'):
        appnet.showFollowers();
        body.addClass('fixed');
        break;

      case self.hasClass('following'):
        appnet.showFollowing();
        body.addClass('fixed');
        break;

      case self.hasClass('follow'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.text('Follow');
          appnet.unfollow(self.parent().data('userid'), self.parent().data('username'), csrf);

        } else {
          self.addClass('on');
          self.text('Unfollow');
          appnet.follow(self.parent().data('userid'), self.parent().data('username'), csrf);
        }
        break;

      case self.hasClass('mute'):
        if (self.hasClass('on')) {
          self.removeClass('on');
          self.text('Mute');
          appnet.unmute(self.parent().data('userid'), self.parent().data('username'), csrf);

        } else {
          self.addClass('on');
          self.text('Unmute');
          appnet.mute(self.parent().data('userid'), self.parent().data('username'), csrf);
        }
        break;
    }
  });

  checkUrl();

  $(window).bind('hashchange', function() {
    checkUrl();
  });

  /* Notifications */
  notifications.on('click', '.notification-item', function(ev) {
    ev.preventDefault();
    var self = $(this);

    notifications.slideUp();
    appnet.showPost(self.data('postid'), self.data('username'));
    body.addClass('fixed');
  });

  /* Write functionality */

  checkCharLimit(write.find('textarea').val());

  write.find('textarea').focus(function() {
    var self = $(this);
    self.addClass('on');
    charLimit.addClass('on');
    checkCharLimit(self.val());
    self.closest('form').find('.form-action-wrapper').slideDown('fast');
  });

  write.find('textarea').blur(function() {
    var self = $(this);

    charLimit.removeClass('on');

    if (self.val().replace(/\s/, '').length < 1) {
      self.removeClass('on');
      self.closest('form').find('.form-action-wrapper').slideUp('fast');
    }
  });

  // Clear the reply_to id if this is empty
  write.find('textarea').keyup(function(evt) {
    var self = $(this);
    checkCharLimit(self.val());
    friends.getBFFs(self, self.getCursorPosition());
    if (self.val().trim().length === 0) {
      write.find('.reply_to').val('');
    }

  })

  write.submit(function(ev) {
    ev.preventDefault();

    var self = $(this);
    appnet.postMessage(self);
    url = '/my/feed';
    self.find('textarea').val('');
    charLimit.text(CHAR_MAX);
    write.find('.reply_to').val('');
    return false;
  });

  suggestions.on('click', 'li', function() {
    var self = $(this);
    var textarea = self.closest('form').find('textarea');
    friends.setUser(self, textarea, textarea.getCursorPosition());
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s"<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s",<|endoftext|>


<commit_before>// Initialize our main "module" for attaching JS code
window.ToDeBike = window.ToDeBike || {};

// DOM element that the map will be rendered
ToDeBike.mapCanvasId = 'map-canvas';

// Kick off google maps rendering
ToDeBike.initGoogleMap = function() {
  var mapOptions = {
    center: { lat: -30.0277, lng: -51.1957},
    zoom: 14 /*,
    mapTypeId: google.maps.MapTypeId.SATELLITE*/
  };
  ToDeBike.map = new google.maps.Map(document.getElementById(ToDeBike.mapCanvasId), mapOptions);
}
google.maps.event.addDomListener(window, 'load', ToDeBike.initGoogleMap);

// Add a single marker to the map using the provided coordinates
ToDeBike.addMarker = function(lat, lng, title) {
  new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: ToDeBike.map,
    title: title
  });
};

// Asynchronous loading of accidents involving bikes
ToDeBike.loadAccidents = function(jsonAccidentsPath) {
  $.getJSON(jsonAccidentsPath, function(data) {
    for (var i = 0; i < data.length; i++) {
      ToDeBike.addMarker(data[i].latitude, data[i].longitude, "Acidente");
    }
  });
};<commit_msg>Melhor centralização do mapa para exibição de mais pontos<commit_after>// Initialize our main "module" for attaching JS code
window.ToDeBike = window.ToDeBike || {};

// DOM element that the map will be rendered
ToDeBike.mapCanvasId = 'map-canvas';

// Kick off google maps rendering
ToDeBike.initGoogleMap = function() {
  var mapOptions = {
    center: { lat: -30.0377, lng: -51.1637 },
    zoom: 14
  };
  ToDeBike.map = new google.maps.Map(document.getElementById(ToDeBike.mapCanvasId), mapOptions);
}
google.maps.event.addDomListener(window, 'load', ToDeBike.initGoogleMap);

// Add a single marker to the map using the provided coordinates
ToDeBike.addMarker = function(lat, lng, title) {
  new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: ToDeBike.map,
    title: title
  });
};

// Asynchronous loading of accidents involving bikes
ToDeBike.loadAccidents = function(jsonAccidentsPath) {
  $.getJSON(jsonAccidentsPath, function(data) {
    for (var i = 0; i < data.length; i++) {
      ToDeBike.addMarker(data[i].latitude, data[i].longitude, "Acidente");
    }
  });
};<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {<|endoftext|>


<commit_before>var ShareDB = require('sharedb/lib/client');
var Quill = require('Quill');
var QuillCursors = require('quill-cursors');
var ReconnectingWebSocket = require('reconnectingwebsocket');
var cursors = require('./cursors');
var utils = require('./utils');

ShareDB.types.register(require('rich-text').type);

var shareDBSocket = new ReconnectingWebSocket(((location.protocol === 'https:') ? 'wss' : 'ws') + '://' + window.location.host + '/sharedb');

var shareDBConnection = new ShareDB.Connection(shareDBSocket);

var quill = window.quill = new Quill('#editor', {
  theme: 'snow',
  modules: {
    cursors: {
      autoRegisterListener: false
    },
    history: {
      userOnly: true
    }
  },
  readOnly: true
});

var doc = shareDBConnection.get('documents', 'foobar');

var cursorsModule = quill.getModule('cursors');

doc.subscribe(function(err) {

  if (err) throw err;

  if (!doc.type)
    doc.create([{
      insert: '\n'
    }], 'rich-text');

  // update editor contents
  quill.setContents(doc.data);

  // local -> server
  quill.on('text-change', function(delta, oldDelta, source) {
    if (source == 'user') {

      if (cursors.localConnection.range && cursors.localConnection.range.length) {
        cursors.localConnection.range.index += cursors.localConnection.range.length;
        cursors.localConnection.range.length = 0;
        cursors.update();
      }

      doc.submitOp(delta, {
        source: quill
      }, function(err) {
        if (err)
          console.error('Submit OP returned an error:', err);
      });

      updateUserList();
    }
  });

  cursorsModule.registerTextChangeListener();

  // server -> local
  doc.on('op', function(op, source) {
    if (source !== quill) {
      quill.updateContents(op);
      updateUserList();
    }
  });

  //
  function sendCursorData(range) {
    cursors.localConnection.range = range;
    cursors.update();
  }

  //
  var debouncedSendCursorData = utils.debounce(function() {
    var range = quill.getSelection();

    if (range) {
      console.log('[cursors] Stopped typing, sending a cursor update/refresh.');
      sendCursorData(range);
    }
  }, 1500);

  doc.on('nothing pending', debouncedSendCursorData);

  function updateCursors(source) {
    var activeConnections = {},
      updateAll = Object.keys(cursorsModule.cursors).length == 0;

    cursors.connections.forEach(function(connection) {
      if (connection.id != cursors.localConnection.id) {

        // Update cursor that sent the update, source (or update all if we're initting)
        if ((connection.id == source.id || updateAll) && connection.range) {
          cursorsModule.setCursor(
            connection.id,
            connection.range,
            connection.name,
            connection.color
          );
        }

        // Add to active connections hashtable
        activeConnections[connection.id] = connection;
      }
    });

    // Clear 'disconnected' cursors
    Object.keys(cursorsModule.cursors).forEach(function(cursorId) {
      if (!activeConnections[cursorId]) {
        cursorsModule.removeCursor(cursorId);
      }
    });
  }

  quill.on('selection-change', function(range, oldRange, source) {
    sendCursorData(range);
  });

  document.addEventListener('cursors-update', function(e) {
    // Handle Removed Connections
    e.detail.removedConnections.forEach(function(connection) {
      if (cursorsModule.cursors[connection.id])
        cursorsModule.removeCursor(connection.id);
    });

    updateCursors(e.detail.source);
    updateUserList();
  });

  updateCursors(cursors.localConnection);
});

window.cursors = cursors;

var usernameInputEl = document.getElementById('username-input');
var usersListEl = document.getElementById('users-list');

function updateUserList() {
  // Wipe the slate clean
  usersListEl.innerHTML = null;

  cursors.connections.forEach(function(connection) {
    var userItemEl = document.createElement('li');
    var userNameEl = document.createElement('div');
    var userDataEl = document.createElement('div');

    userNameEl.innerHTML = '' + (connection.name || '(Waiting for username...)') + '';
    userNameEl.classList.add('user-name');

    if (connection.id == cursors.localConnection.id)
      userNameEl.innerHTML += ' (You)';

    if (connection.range) {

      if (connection.id == cursors.localConnection.id)
        connection.range = quill.getSelection();

      userDataEl.innerHTML = [
        '
',
        '
Index: ' + connection.range.index + '
',
        '
Length: ' + connection.range.length + '
',
        '
'
      ].join('');
    } else
      userDataEl.innerHTML = '(Not focusing on editor.)';

    userItemEl.appendChild(userNameEl);
    userItemEl.appendChild(userDataEl);

    userItemEl.style.backgroundColor = connection.color;
    usersListEl.appendChild(userItemEl);
  });
}

usernameInputEl.value = chance.name();
usernameInputEl.focus();
usernameInputEl.select();

document.getElementById('username-form').addEventListener('submit', function(event) {
  cursors.localConnection.name = usernameInputEl.value;
  cursors.update();
  quill.enable();
  document.getElementById('connect-panel').style.display = 'none';
  document.getElementById('users-panel').style.display = 'block';
  event.preventDefault();
  return false;
});

// DEBUG

var sharedbSocketStateEl = document.getElementById('sharedb-socket-state');
var sharedbSocketIndicatorEl = document.getElementById('sharedb-socket-indicator');

shareDBConnection.on('state', function(state, reason) {
  var indicatorColor;

  console.log('[sharedb] New connection state: ' + state + ' Reason: ' + reason);

  sharedbSocketStateEl.innerHTML = state.toString();

  switch (state.toString()) {
    case 'connecting':
      indicatorColor = 'silver';
      break;
    case 'connected':
      indicatorColor = 'lime';
      break;
    case 'disconnected':
    case 'closed':
    case 'stopped':
      indicatorColor = 'red';
      break;
  }

  sharedbSocketIndicatorEl.style.backgroundColor = indicatorColor;
});
<commit_msg>Revert quill library capitalization<commit_after>var ShareDB = require('sharedb/lib/client');
var Quill = require('quill');
var QuillCursors = require('quill-cursors');
var ReconnectingWebSocket = require('reconnectingwebsocket');
var cursors = require('./cursors');
var utils = require('./utils');

ShareDB.types.register(require('rich-text').type);

var shareDBSocket = new ReconnectingWebSocket(((location.protocol === 'https:') ? 'wss' : 'ws') + '://' + window.location.host + '/sharedb');

var shareDBConnection = new ShareDB.Connection(shareDBSocket);

var quill = window.quill = new Quill('#editor', {
  theme: 'snow',
  modules: {
    cursors: {
      autoRegisterListener: false
    },
    history: {
      userOnly: true
    }
  },
  readOnly: true
});

var doc = shareDBConnection.get('documents', 'foobar');

var cursorsModule = quill.getModule('cursors');

doc.subscribe(function(err) {

  if (err) throw err;

  if (!doc.type)
    doc.create([{
      insert: '\n'
    }], 'rich-text');

  // update editor contents
  quill.setContents(doc.data);

  // local -> server
  quill.on('text-change', function(delta, oldDelta, source) {
    if (source == 'user') {

      if (cursors.localConnection.range && cursors.localConnection.range.length) {
        cursors.localConnection.range.index += cursors.localConnection.range.length;
        cursors.localConnection.range.length = 0;
        cursors.update();
      }

      doc.submitOp(delta, {
        source: quill
      }, function(err) {
        if (err)
          console.error('Submit OP returned an error:', err);
      });

      updateUserList();
    }
  });

  cursorsModule.registerTextChangeListener();

  // server -> local
  doc.on('op', function(op, source) {
    if (source !== quill) {
      quill.updateContents(op);
      updateUserList();
    }
  });

  //
  function sendCursorData(range) {
    cursors.localConnection.range = range;
    cursors.update();
  }

  //
  var debouncedSendCursorData = utils.debounce(function() {
    var range = quill.getSelection();

    if (range) {
      console.log('[cursors] Stopped typing, sending a cursor update/refresh.');
      sendCursorData(range);
    }
  }, 1500);

  doc.on('nothing pending', debouncedSendCursorData);

  function updateCursors(source) {
    var activeConnections = {},
      updateAll = Object.keys(cursorsModule.cursors).length == 0;

    cursors.connections.forEach(function(connection) {
      if (connection.id != cursors.localConnection.id) {

        // Update cursor that sent the update, source (or update all if we're initting)
        if ((connection.id == source.id || updateAll) && connection.range) {
          cursorsModule.setCursor(
            connection.id,
            connection.range,
            connection.name,
            connection.color
          );
        }

        // Add to active connections hashtable
        activeConnections[connection.id] = connection;
      }
    });

    // Clear 'disconnected' cursors
    Object.keys(cursorsModule.cursors).forEach(function(cursorId) {
      if (!activeConnections[cursorId]) {
        cursorsModule.removeCursor(cursorId);
      }
    });
  }

  quill.on('selection-change', function(range, oldRange, source) {
    sendCursorData(range);
  });

  document.addEventListener('cursors-update', function(e) {
    // Handle Removed Connections
    e.detail.removedConnections.forEach(function(connection) {
      if (cursorsModule.cursors[connection.id])
        cursorsModule.removeCursor(connection.id);
    });

    updateCursors(e.detail.source);
    updateUserList();
  });

  updateCursors(cursors.localConnection);
});

window.cursors = cursors;

var usernameInputEl = document.getElementById('username-input');
var usersListEl = document.getElementById('users-list');

function updateUserList() {
  // Wipe the slate clean
  usersListEl.innerHTML = null;

  cursors.connections.forEach(function(connection) {
    var userItemEl = document.createElement('li');
    var userNameEl = document.createElement('div');
    var userDataEl = document.createElement('div');

    userNameEl.innerHTML = '' + (connection.name || '(Waiting for username...)') + '';
    userNameEl.classList.add('user-name');

    if (connection.id == cursors.localConnection.id)
      userNameEl.innerHTML += ' (You)';

    if (connection.range) {

      if (connection.id == cursors.localConnection.id)
        connection.range = quill.getSelection();

      userDataEl.innerHTML = [
        '
',
        '
Index: ' + connection.range.index + '
',
        '
Length: ' + connection.range.length + '
',
        '
'
      ].join('');
    } else
      userDataEl.innerHTML = '(Not focusing on editor.)';

    userItemEl.appendChild(userNameEl);
    userItemEl.appendChild(userDataEl);

    userItemEl.style.backgroundColor = connection.color;
    usersListEl.appendChild(userItemEl);
  });
}

usernameInputEl.value = chance.name();
usernameInputEl.focus();
usernameInputEl.select();

document.getElementById('username-form').addEventListener('submit', function(event) {
  cursors.localConnection.name = usernameInputEl.value;
  cursors.update();
  quill.enable();
  document.getElementById('connect-panel').style.display = 'none';
  document.getElementById('users-panel').style.display = 'block';
  event.preventDefault();
  return false;
});

// DEBUG

var sharedbSocketStateEl = document.getElementById('sharedb-socket-state');
var sharedbSocketIndicatorEl = document.getElementById('sharedb-socket-indicator');

shareDBConnection.on('state', function(state, reason) {
  var indicatorColor;

  console.log('[sharedb] New connection state: ' + state + ' Reason: ' + reason);

  sharedbSocketStateEl.innerHTML = state.toString();

  switch (state.toString()) {
    case 'connecting':
      indicatorColor = 'silver';
      break;
    case 'connected':
      indicatorColor = 'lime';
      break;
    case 'disconnected':
    case 'closed':
    case 'stopped':
      indicatorColor = 'red';
      break;
  }

  sharedbSocketIndicatorEl.style.backgroundColor = indicatorColor;
});
<|endoftext|>


<commit_before>// Variables

// Set the variable of the target
var targetWord = $('.target').text();
console.log("the targetWord is " + targetWord);

// Set the variable of the answer
var answerWord = $('.answer').val();
console.log("the value in the answer box is " + answerWord);

// The score
var score = 0;

// The array of random words
var dictionary = [];

// Random words
var wordCollection = "sadly lacey hurst colin finca janey trade lomax louie vhf verny nopal hexyl nasby jane urea donor elam enrol clea epha riel softa epoch focus abut jabir reid aisha foe sulla ava brill food motey wispy jurat gills som drab koppa aoli ainu knies podes cns chiru jowly grace grove ural wirer birse patd ran feme down exult biisk maud rock dan dobby lowl style cliff pipit tiv label crept sinal musca arak bowie ocie ceb aries oater boko grey hover inlay hemin douse ida dmso roca larva typo occur mmhg atty phew luzon ferd right sine dbe pis gal";

dictionary = wordCollection.split(" ");

console.log("the array of random words is " + dictionary);

//Random integer between 0 and 100
var randNum = Math.floor(Math.random()*100);

var randWord = dictionary[randNum];

// When a key in the answer box is pressed, run function.
$('.answer').keyup(updateVals);

$('.answer').keydown(function(e) {
  if(e.which == 13) {
    $('.answer').val("");
  }
});

function updateVals() {
  answerWord = $('.answer').val();
  targetWord = $('.target').text();

  console.log("the value in the answer input is: " + answerWord);

  // If the answer matches the target, run the code within
  if (answerWord === targetWord) {
    // Increase the score by 1
    score++;

    // Generate a new random number
    randNum = Math.floor(Math.random()*100);
    console.log("The random number is " + randNum);
    // Generate a new randomword
    randWord = dictionary[randNum];
    console.log("The random word is " + randWord);

    // Clear the answer box
    $('.answer').val("");
    //Insert the new word into the target box
    $('.target').text(randWord);

  }

  // Write the score into the scoreboard
  $('.score-number').text(score);
}

<commit_msg>random number range adaptive<commit_after>// Variables

// Set the variable of the target
var targetWord = $('.target').text();
console.log("the targetWord is " + targetWord);

// Set the variable of the answer
var answerWord = $('.answer').val();
console.log("the value in the answer box is " + answerWord);

// The score
var score = 0;

// The array of random words
var dictionary = [];

// Random words
var wordCollection = "sadly lacey hurst colin finca janey trade lomax louie vhf verny nopal hexyl nasby jane urea donor elam enrol clea epha riel softa epoch focus abut jabir reid aisha foe sulla ava brill food motey wispy jurat gills som drab koppa aoli ainu knies podes cns chiru jowly grace grove ural wirer birse patd ran feme down exult biisk maud rock dan dobby lowl style cliff pipit tiv label crept sinal musca arak bowie ocie ceb aries oater boko grey hover inlay hemin douse ida dmso roca larva typo occur mmhg atty phew luzon ferd right sine dbe pis gal";

dictionary = wordCollection.split(" ");

console.log("the number of objects " + dictionary.length);

console.log("the array of random words is " + dictionary);

//Random integer between 0 and 100
var randNum = Math.floor(Math.random()*dictionary.length);

var randWord = dictionary[randNum];

// When a key in the answer box is pressed, run function.
$('.answer').keyup(updateVals);

$('.answer').keydown(function(e) {
  if(e.which == 13) {
    $('.answer').val("");
  }
});

function updateVals() {
  answerWord = $('.answer').val();
  targetWord = $('.target').text();

  console.log("the value in the answer input is: " + answerWord);

  // If the answer matches the target, run the code within
  if (answerWord === targetWord) {
    // Increase the score by 1
    score++;

    // Generate a new random number
    randNum = Math.floor(Math.random()*100);
    console.log("The random number is " + randNum);
    // Generate a new randomword
    randWord = dictionary[randNum];
    console.log("The random word is " + randWord);

    // Clear the answer box
    $('.answer').val("");
    //Insert the new word into the target box
    $('.target').text(randWord);

  }

  // Write the score into the scoreboard
  $('.score-number').text(score);
}

<|endoftext|>