<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global require exports console*/

var SERVICE_NAME = 'isearch';

//This servlet is 'special' and doesn't get registered in the same
//way/place that other servlets do.

//See server.js to find where this 'servlet' handlers gets registered.

//The reason this servlet is 'special' is it doesn't
//have a simple http request handler but uses 'sockjs' (WebSockets).

var websockets = require('./websockets-servlet');
var conf = require('../jsdepend/filesystem').withBaseDir(null);
var extend = require('../jsdepend/utils').extend;
var toRegexp = require('../jsdepend/utils').toRegexp;
var getFileName = require('../jsdepend/utils').getFileName;
var fswalk = require('../jsdepend/fswalk').configure(conf).asynchWalk;
var fileindexer = require('../jsdepend/file-indexer').configure(conf);

var LOG_SOCKET_COUNT = false;
var MAX_RESULTS_DEFAULT = 30; // When this number is reached, then the walker will be paused.

exports.install = function (server) {

	websockets.install(server); // the websockets servlet is a prerequisite. Ensure its installed.

	var openSockets = 0;
	var nextId = 0;

	var sockServer = websockets.createSocket(SERVICE_NAME);
	sockServer.on('connection', function (conn) {
		var id = nextId++; // used for log messages only.

		//opening a websocket connection initiates a search.

		var maxResults = null; // set upon receipt of the initial query
		                // can also be increased by a request for more results.

		if (LOG_SOCKET_COUNT) {
			openSockets++;
			console.log('isearch socket opened ['+openSockets+']');
		}

		var query = null; //The thing we are searching for... set once received via the socket.
		var regexp = null; //the query as a regexp.
		var searchRoot = null; //Set when we have determined/received the search context.
		var options = {};

		var results = {}; //The 'keys' of this map are the results we have already sent to the client.
		var activeWalker = null; //the current walker, allows cancelation if we need to start a brand new walker.
		var resultCount = 0; // Tracks number of results. Used to limit the number of results sent to the client.

		/**
		 * send data to the client. The data sent must be something that can be 'JSON.stringified'.
		 */
		function send(json) {
			conn.write(JSON.stringify(json));
		}

		function addResult(path) {
			if (!results[path]) {
				results[path] = path;
				send({add: [path]});
				resultCount++;
				if (resultCount >= maxResults && activeWalker) {
					activeWalker.pause();
				}
			}
		}
		function revokeResult(path) {
			if (results[path]) {
				delete results[path];
				send({revoke: [path]});
				resultCount--;
			}
		}

		function isMatch(path) {
			var name = getFileName(path);
			return regexp.test(name);
		}

		function startSearch() {
			if (!searchRoot) {
				console.error('Can not start search: the search context is not defined');
			}
			var canceled = false;
			var paused = false; // Intially, set to true when pause is requested. Then when
			                    // work is actually suspended, a 'work' function will be
			                    // stored in here. To resume the work, this function is
			                    // called with no params.

			/**
			 * Given a function that represents 'remaining work'. Either continue the work,
			 * by calling this function. Or store the function for later resuming the work.
			 */
			function pauseOrRun(work) {
				//process.nextTick(work);
				if (paused===true) { // a 'pause' was requested.
					console.log("suspend walking");
					paused = work;
				} else {
					if (!paused) {
						//console.log("continue walking");
						process.nextTick(work);
					} else {
						//Seems like somehow a walker is both running and suspended at the same time. That should not
						//be possible!
						throw "Illegal state: It looks like we still have a function in 'paused' although walker is still running!";
					}
				}
			}

			fswalk(searchRoot,
				/*called for eachFile*/
				function (filepath, k) {
					pauseOrRun(function () {
						//Test for canceled status before matching / adding. This is to
						//make sure we don't accidentally add one more result after a walker has been canceled.
						if (!canceled) {
							if (isMatch(filepath)) {
								addResult(filepath);
							}
						}
						return k(canceled);
					});
				},
				/*called when walk stops*/
				function () {
					if (!canceled) {
						send({done: []});
					}
				}
			);
			return {
				cancel: function () {
					canceled = true;
				},
				pause: function () {
					//If double pausing, take care not to accidentally wipe out a work function that may
					//already be stored in the 'paused' variable.
					paused = paused || true;
				},
				resume: function () {
					if (typeof(paused)==='function') {
						//we have some work to resume
						var work = paused;
						paused = false;
						console.log('Resume walking');
						work();
					} else if (paused) {
						//paused, but we have no work to resume.
						paused = false;
					}
				}
			};
		}

		/**
		 * @param {Query} newQ
		 * @param {Query} oldQ
		 * @return true if and only if results of oldQ should at least include the results of newQ.
		 */
		function isMoreSpecificThan(newQ, oldQ) {
			return newQ.indexOf(oldQ)>=0;
		}

		function cancelActiveWalker() {
			if (activeWalker) {
				activeWalker.cancel();
			}
		}

		var handlers = {
			//initial query and other info needed to setup a search
			query: function (sr, q, opts) {
				if (!query) {
					searchRoot = sr;
					query = q;
					regexp = toRegexp(q);
					options = opts || {};
					maxResults = options.maxResults || MAX_RESULTS_DEFAULT;
					//console.log('search options: '+JSON.stringify(options));
					activeWalker = startSearch();
				} else {
					console.error("multiple queries received on the same /isearch connection");
				}
			},

			//ask for more results: increases maxResults to be at least the current number
			//of results plus 10%
			more: function () {
				if (activeWalker) {
					maxResults = Math.max(maxResults, resultCount * 1.1);
					console.log('maxResults = '+maxResults);
					activeWalker.resume();
				}
			},

			//change the current query, possibly in midrun
			requery: function (q) {
				//console.log('change query '+query+' => ' + q);
				var oldQuery = query;
				query = q;
				regexp = toRegexp(q);
				for (var oldResult in results) {
					if (results.hasOwnProperty(oldResult)) {
						if (isMatch(oldResult)) {
							//still a match... so keep it.
						} else {
							revokeResult(oldResult);
						}
					}
				}
				if (activeWalker) {
					//It is possible, (when typing really fast :-) a query update is received before walker got set.
					//This really means the 'activeWalker hasn't quite started yet so in that case, we we don't need
					//to restart or resume it.
					//Note: this is only possible if starting the activewalker is an 'asynch' thing.
					//Right now it isn't any more, so strictly speaking the if above is not needed and
					//should always be true. Leave it in anyway in case we might go back to
					//needing some asynch work in getting the walker going.
					if (!isMoreSpecificThan(query, oldQuery)) {
						console.log('new query is not an "extension": restarting query');
						//If the query is not more specialized from the oldQuery, we have to restart the search
						//or we risk not getting all matches in the already processed part of the tree.
						cancelActiveWalker();
						activeWalker = startSearch();
					} else {
						if (activeWalker && resultCount<maxResults) {
							//Note: we can get here with activeWalker still null if the the
							//initial query is not started yet. This can happen because we have ascynch
							//code in determining the search context.
							activeWalker.resume();
						}
					}
				}
			}
		};

		/**
		 * Called upon receiving data from the client. The data is already parsed into a
		 * data object once it gets here.
		 */
		function receive(json) {
			for (var p in json) {
				if (json.hasOwnProperty(p)) {
					if (!handlers[p]) {
						console.error('No handler for: ' + JSON.stringify(json));
					} else {
						handlers[p].apply(null, json[p]);
					}
				}
			}
		}
		conn.on('data', function (message) {
			//console.log("isearch ["+id+"] << "+message);
			receive(JSON.parse(message));
		});

		conn.on('close', function () {
			cancelActiveWalker();
			if (LOG_SOCKET_COUNT) {
				openSockets--;
				console.log('isearch socket CLOSED ['+openSockets+']');
			}
		});
	});
	//sockServer.installHandlers(server, {prefix: '/isearch'});

};
<commit_msg>Disable some logging<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global require exports console*/

var SERVICE_NAME = 'isearch';

//This servlet is 'special' and doesn't get registered in the same
//way/place that other servlets do.

//See server.js to find where this 'servlet' handlers gets registered.

//The reason this servlet is 'special' is it doesn't
//have a simple http request handler but uses 'sockjs' (WebSockets).

var websockets = require('./websockets-servlet');
var conf = require('../jsdepend/filesystem').withBaseDir(null);
var extend = require('../jsdepend/utils').extend;
var toRegexp = require('../jsdepend/utils').toRegexp;
var getFileName = require('../jsdepend/utils').getFileName;
var fswalk = require('../jsdepend/fswalk').configure(conf).asynchWalk;
var fileindexer = require('../jsdepend/file-indexer').configure(conf);

var LOG_SOCKET_COUNT = false;
var MAX_RESULTS_DEFAULT = 30; // When this number is reached, then the walker will be paused.

exports.install = function (server) {

	websockets.install(server); // the websockets servlet is a prerequisite. Ensure its installed.

	var openSockets = 0;
	var nextId = 0;

	var sockServer = websockets.createSocket(SERVICE_NAME);
	sockServer.on('connection', function (conn) {
		var id = nextId++; // used for log messages only.

		//opening a websocket connection initiates a search.

		var maxResults = null; // set upon receipt of the initial query
		                // can also be increased by a request for more results.

		if (LOG_SOCKET_COUNT) {
			openSockets++;
			console.log('isearch socket opened ['+openSockets+']');
		}

		var query = null; //The thing we are searching for... set once received via the socket.
		var regexp = null; //the query as a regexp.
		var searchRoot = null; //Set when we have determined/received the search context.
		var options = {};

		var results = {}; //The 'keys' of this map are the results we have already sent to the client.
		var activeWalker = null; //the current walker, allows cancelation if we need to start a brand new walker.
		var resultCount = 0; // Tracks number of results. Used to limit the number of results sent to the client.

		/**
		 * send data to the client. The data sent must be something that can be 'JSON.stringified'.
		 */
		function send(json) {
			conn.write(JSON.stringify(json));
		}

		function addResult(path) {
			if (!results[path]) {
				results[path] = path;
				send({add: [path]});
				resultCount++;
				if (resultCount >= maxResults && activeWalker) {
					activeWalker.pause();
				}
			}
		}
		function revokeResult(path) {
			if (results[path]) {
				delete results[path];
				send({revoke: [path]});
				resultCount--;
			}
		}

		function isMatch(path) {
			var name = getFileName(path);
			return regexp.test(name);
		}

		function startSearch() {
			if (!searchRoot) {
				console.error('Can not start search: the search context is not defined');
			}
			var canceled = false;
			var paused = false; // Intially, set to true when pause is requested. Then when
			                    // work is actually suspended, a 'work' function will be
			                    // stored in here. To resume the work, this function is
			                    // called with no params.

			/**
			 * Given a function that represents 'remaining work'. Either continue the work,
			 * by calling this function. Or store the function for later resuming the work.
			 */
			function pauseOrRun(work) {
				//process.nextTick(work);
				if (paused===true) { // a 'pause' was requested.
					//console.log("suspend walking");
					paused = work;
				} else {
					if (!paused) {
						//console.log("continue walking");
						process.nextTick(work);
					} else {
						//Seems like somehow a walker is both running and suspended at the same time. That should not
						//be possible!
						throw "Illegal state: It looks like we still have a function in 'paused' although walker is still running!";
					}
				}
			}

			fswalk(searchRoot,
				/*called for eachFile*/
				function (filepath, k) {
					pauseOrRun(function () {
						//Test for canceled status before matching / adding. This is to
						//make sure we don't accidentally add one more result after a walker has been canceled.
						if (!canceled) {
							if (isMatch(filepath)) {
								addResult(filepath);
							}
						}
						return k(canceled);
					});
				},
				/*called when walk stops*/
				function () {
					if (!canceled) {
						send({done: []});
					}
				}
			);
			return {
				cancel: function () {
					canceled = true;
				},
				pause: function () {
					//If double pausing, take care not to accidentally wipe out a work function that may
					//already be stored in the 'paused' variable.
					paused = paused || true;
				},
				resume: function () {
					if (typeof(paused)==='function') {
						//we have some work to resume
						var work = paused;
						paused = false;
						//console.log('Resume walking');
						work();
					} else if (paused) {
						//paused, but we have no work to resume.
						paused = false;
					}
				}
			};
		}

		/**
		 * @param {Query} newQ
		 * @param {Query} oldQ
		 * @return true if and only if results of oldQ should at least include the results of newQ.
		 */
		function isMoreSpecificThan(newQ, oldQ) {
			return newQ.indexOf(oldQ)>=0;
		}

		function cancelActiveWalker() {
			if (activeWalker) {
				activeWalker.cancel();
			}
		}

		var handlers = {
			//initial query and other info needed to setup a search
			query: function (sr, q, opts) {
				if (!query) {
					searchRoot = sr;
					query = q;
					regexp = toRegexp(q);
					options = opts || {};
					maxResults = options.maxResults || MAX_RESULTS_DEFAULT;
					//console.log('search options: '+JSON.stringify(options));
					activeWalker = startSearch();
				} else {
					console.error("multiple queries received on the same /isearch connection");
				}
			},

			//ask for more results: increases maxResults to be at least the current number
			//of results plus 10%
			more: function () {
				if (activeWalker) {
					maxResults = Math.max(maxResults, resultCount * 1.1);
					console.log('maxResults = '+maxResults);
					activeWalker.resume();
				}
			},

			//change the current query, possibly in midrun
			requery: function (q) {
				//console.log('change query '+query+' => ' + q);
				var oldQuery = query;
				query = q;
				regexp = toRegexp(q);
				for (var oldResult in results) {
					if (results.hasOwnProperty(oldResult)) {
						if (isMatch(oldResult)) {
							//still a match... so keep it.
						} else {
							revokeResult(oldResult);
						}
					}
				}
				if (activeWalker) {
					//It is possible, (when typing really fast :-) a query update is received before walker got set.
					//This really means the 'activeWalker hasn't quite started yet so in that case, we we don't need
					//to restart or resume it.
					//Note: this is only possible if starting the activewalker is an 'asynch' thing.
					//Right now it isn't any more, so strictly speaking the if above is not needed and
					//should always be true. Leave it in anyway in case we might go back to
					//needing some asynch work in getting the walker going.
					if (!isMoreSpecificThan(query, oldQuery)) {
						console.log('new query is not an "extension": restarting query');
						//If the query is not more specialized from the oldQuery, we have to restart the search
						//or we risk not getting all matches in the already processed part of the tree.
						cancelActiveWalker();
						activeWalker = startSearch();
					} else {
						if (activeWalker && resultCount<maxResults) {
							//Note: we can get here with activeWalker still null if the the
							//initial query is not started yet. This can happen because we have ascynch
							//code in determining the search context.
							activeWalker.resume();
						}
					}
				}
			}
		};

		/**
		 * Called upon receiving data from the client. The data is already parsed into a
		 * data object once it gets here.
		 */
		function receive(json) {
			for (var p in json) {
				if (json.hasOwnProperty(p)) {
					if (!handlers[p]) {
						console.error('No handler for: ' + JSON.stringify(json));
					} else {
						handlers[p].apply(null, json[p]);
					}
				}
			}
		}
		conn.on('data', function (message) {
			//console.log("isearch ["+id+"] << "+message);
			receive(JSON.parse(message));
		});

		conn.on('close', function () {
			cancelActiveWalker();
			if (LOG_SOCKET_COUNT) {
				openSockets--;
				console.log('isearch socket CLOSED ['+openSockets+']');
			}
		});
	});
	//sockServer.installHandlers(server, {prefix: '/isearch'});

};
<|endoftext|>


<commit_before>$(document).ready(function(){
  var search_form = $("#searchForm");
  var instr_link = $("#show_search_instructions");
  var instr = $(".search-instructions");
  var search_button = $("#search_button");
  var results_div = $("#searchresults");
  var search_box = $('input[name=searchterms]');
  var search_container = $(".search-box");

  instr_link.toggle(show_help,hide_help);
  search_button.click(search_button_clicked);
  $(window).bind("hashchange", function(){search(extract_search_params());});
  $(window).trigger("hashchange");

  function hide_help(){
    instr.hide();
    instr_link.text("how do I search?")
    search_box.focus().select();
  }
  function show_help(){
    instr.show();
    instr_link.text("hide search help");
    search_box.focus().select();
  }

  function search_results_loaded(){
    var hash = extract_search_params();

    //todo make the search results a js object, load them here after parsing some stuff out
    if (hash.searchterms) {
      highlight_searchterms(hash.searchterms);
    }
    hide_help();

    if (hash.searchterms != null && hash.searchterms != "") {
      search_container.addClass("search-box-small");
    }
    else {
      search_container.removeClass("search-box-small");
    }
    search_container.show();
    search_box.focus().select();
    //update the handlers for the pagination controls, which are returned by the search
    $("select[name=limit]").change(function(){
      $.bbq.pushState({limit:$(this).val(), pagenum:1});
      return false;
    }).chosen();
    $(".pagination-container a").click(function(){
      if (!($(this).hasClass("disabled"))){
        $.bbq.pushState({pagenum:$(this).data("pagenum")});
      }
      return false;
    });
    $("a.search-strategy-show-details").click(function(){
      $(this).siblings().toggle();
      return false;
    })
  }

  function highlight_searchterms(searchterms){
    $('.searchresults-mice').each(function(){
      var $results = $(this);
      var $header = $(this).prev();
      var tokens = $header.attr('data-tokens').split(',');
      $results.find(".mouselist, .mouselistAlt").highlight(tokens,{className: 'highlight-searchterm'});
      $results.find(".lbl").unhighlight({className: 'highlight-searchterm'});
    });

    $("span.highlight-searchterm").parent().parent().each(function(){
      var $element = $(this);
      if($element.is("dt")) {
        if($element.parent().hasClass("mouselist-holderlist")){
          $element.show();
        }
      }
    });
  }

  function search_button_clicked(){
    $.bbq.pushState({searchterms: search_box.val(), pagenum: 1});
    return false;
  }

  function search(search_query){
    var $this = $(this);

    if (window.searchQuery != search_query ) {
      window.searchQuery = search_query;
      _gaq.push(['_trackPageview', window.location.pathname + '?' + window.location.hash.substring(1)]);
      if (search_query.searchterms){
        $("#searchresults-container").fadeOut(50,function(){
          $(this).html("
Searching...
").fadeIn(50,do_search_ajax);
        });
      }
      else {
        do_search_ajax();
      }

    }
    return false;
  }

  function do_search_ajax(){
    $("#searchresults-container").load('search.jsp?' + $.param(window.searchQuery) + ' #searchresults', search_results_loaded);
  }

  function extract_search_params(){
    var hash = $.bbq.getState( );
    var query = $.deparam.querystring();

    if ((hash == null || hash.searchterms == undefined) && query != null && query.searchterms != null) {
      hash.searchterms = query.searchterms;
    }
    if (!hash.limit) hash.limit = 25;
    if (!hash.pagenum) hash.pagenum = 1;

    search_box.val(hash.searchterms);
    $("select[name=limit]").val(hash.limit);
    return hash;
  }

});<commit_msg>Don't select the text, this causes annoying behavior<commit_after>$(document).ready(function(){
  var search_form = $("#searchForm");
  var instr_link = $("#show_search_instructions");
  var instr = $(".search-instructions");
  var search_button = $("#search_button");
  var results_div = $("#searchresults");
  var search_box = $('input[name=searchterms]');
  var search_container = $(".search-box");

  instr_link.toggle(show_help,hide_help);
  search_button.click(search_button_clicked);
  $(window).bind("hashchange", function(){search(extract_search_params());});
  $(window).trigger("hashchange");

  function hide_help(){
    instr.hide();
    instr_link.text("how do I search?")
    search_box.focus();
  }
  function show_help(){
    instr.show();
    instr_link.text("hide search help");
    search_box.focus();
  }

  function search_results_loaded(){
    var hash = extract_search_params();

    //todo make the search results a js object, load them here after parsing some stuff out
    if (hash.searchterms) {
      highlight_searchterms(hash.searchterms);
    }
    hide_help();

    if (hash.searchterms != null && hash.searchterms != "") {
      search_container.addClass("search-box-small");
    }
    else {
      search_container.removeClass("search-box-small");
    }
    search_container.show();
    search_box.focus();
    //update the handlers for the pagination controls, which are returned by the search
    $("select[name=limit]").change(function(){
      $.bbq.pushState({limit:$(this).val(), pagenum:1});
      return false;
    }).chosen();
    $(".pagination-container a").click(function(){
      if (!($(this).hasClass("disabled"))){
        $.bbq.pushState({pagenum:$(this).data("pagenum")});
      }
      return false;
    });
    $("a.search-strategy-show-details").click(function(){
      $(this).siblings().toggle();
      return false;
    })
  }

  function highlight_searchterms(searchterms){
    $('.searchresults-mice').each(function(){
      var $results = $(this);
      var $header = $(this).prev();
      var tokens = $header.attr('data-tokens').split(',');
      $results.find(".mouselist, .mouselistAlt").highlight(tokens,{className: 'highlight-searchterm'});
      $results.find(".lbl").unhighlight({className: 'highlight-searchterm'});
    });

    $("span.highlight-searchterm").parent().parent().each(function(){
      var $element = $(this);
      if($element.is("dt")) {
        if($element.parent().hasClass("mouselist-holderlist")){
          $element.show();
        }
      }
    });
  }

  function search_button_clicked(){
    $.bbq.pushState({searchterms: search_box.val(), pagenum: 1});
    return false;
  }

  function search(search_query){
    var $this = $(this);

    if (window.searchQuery != search_query ) {
      window.searchQuery = search_query;
      _gaq.push(['_trackPageview', window.location.pathname + '?' + window.location.hash.substring(1)]);
      if (search_query.searchterms){
        $("#searchresults-container").fadeOut(50,function(){
          $(this).html("
Searching...
").fadeIn(50,do_search_ajax);
        });
      }
      else {
        do_search_ajax();
      }

    }
    return false;
  }

  function do_search_ajax(){
    $("#searchresults-container").load('search.jsp?' + $.param(window.searchQuery) + ' #searchresults', search_results_loaded);
  }

  function extract_search_params(){
    var hash = $.bbq.getState( );
    var query = $.deparam.querystring();

    if ((hash == null || hash.searchterms == undefined) && query != null && query.searchterms != null) {
      hash.searchterms = query.searchterms;
    }
    if (!hash.limit) hash.limit = 25;
    if (!hash.pagenum) hash.pagenum = 1;

    search_box.val(hash.searchterms);
    $("select[name=limit]").val(hash.limit);
    return hash;
  }

});<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Colour blocks for Blockly.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.Blocks.colour');

goog.require('Blockly.Blocks');

goog.require('Blockly.constants');

/**
 * Pick a random colour.
 * @return {string} #RRGGBB for random colour.
 */
function randomColour() {
  var num = Math.floor(Math.random() * Math.pow(2, 24));
  return '#' + ('00000' + num.toString(16)).substr(-6);
}

Blockly.Blocks['colour_picker'] = {
  /**
   * Block for colour picker.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "%1",
      "args0": [
        {
          "type": "field_colour_slider",
          "name": "COLOUR",
          "colour": randomColour()
        }
      ],
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "output": "Colour"
    });
  }
};
<commit_msg>Only pick random colors with full saturation and brightness<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Colour blocks for Blockly.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.Blocks.colour');

goog.require('goog.color');

goog.require('Blockly.Blocks');

goog.require('Blockly.constants');

/**
 * Pick a random colour that has full saturation and brightness.
 * @return {string} #RRGGBB for random colour.
 */
function randomColour() {
  return goog.color.hsvToHex(360 * Math.random(), 1, 255);
}

Blockly.Blocks['colour_picker'] = {
  /**
   * Block for colour picker.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "%1",
      "args0": [
        {
          "type": "field_colour_slider",
          "name": "COLOUR",
          "colour": randomColour()
        }
      ],
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "output": "Colour"
    });
  }
};
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';

const Elements = {};

Elements.collection = new Meteor.Collection('Elements');

Elements.types = [
  {humanName: 'Reference object', name: 'referenceObject'},
  {humanName: 'Hierarchy', name: 'hierarchy'},
];

Elements.types.nameToHumanName = (name) => {
  let type = Elements.types.find(function(type) {
    if(type.name === name) {
      return true;
    }
  });
  return type.humanName;
};

Elements.add = function add(parentId, typeName) {
  let elementId = Elements.collection.insert(
    {parentId: parentId, typeName: typeName});
  Elements.collection.update(
    {_id: parentId}, {$addToSet: {childrenIds: elementId}});
};

export default Elements;
<commit_msg>Refactor elements.js<commit_after>import { Meteor } from 'meteor/meteor';

const Elements = {};

Elements.collection = new Meteor.Collection('Elements');

Elements.types = [
  { humanName: 'Reference object', name: 'referenceObject' },
  { humanName: 'Hierarchy', name: 'hierarchy' },
];

Elements.add = function add(parentId, typeName) {
  const elementId = Elements.collection.insert(
    { parentId: parentId, typeName: typeName });
  Elements.collection.update(
    { _id: parentId }, { $addToSet: { childrenIds: elementId } }
  );
  return elementId;
};

Elements.types.nameToHumanName = (name) => {
  const type = Elements.types.find(function(type) {
    if (type.name === name) {
      return true;
    }
  });
  return type.humanName;
};

export default Elements;
<|endoftext|>


<commit_before>// https://dl.dropboxusercontent.com/u/133374/hades.txt
// downloaded at 11/11/2013
// coded by sam@hades
// hades: telnet hades-talker.org 6660

var net = require('net');

var sockets = [];

var port = process.env.PORT || 8888;

var talkername = "Moosville";

/*
 * Cleans the input of carriage return, newline and control characters
 */
function cleanInput(data) {
        var newString = data.toString().replace("[\u0000-\u001f]", "");
        return newString.replace(/(\r\n|\n|\r)/gm,"");
}

/*
 * Method executed when data is received from a socket
 */
function receiveData(socket, data) {

        var cleanData = cleanInput(data);

        if(cleanData.length == 0)
                return;

        console.log("Moo [" + cleanData + "]");

		// TODO: We're just filtering out IAC commands. We should be dealing with them instead...
		// IAC commands
		var IAC = [
			1 , // Telnet IAC - Echo
			3 , // Telnet IAC - Suppress Go Ahead
			5 , // Telnet IAC - Status
			6 , // Telnet IAC - Timing Mark
			24, // Telnet IAC - Terminal Type
			31, // Telnet IAC - Window Size
			32, // Telnet IAC - Window Speed
			33, // Telnet IAC - Remote Flow Control
			34, // Telnet IAC - Linemode
			36  // Telnet IAC - Environment Variables
		];
		if (IAC.indexOf(cleanData.charCodeAt(0)) !== -1) {
			// This is IAC, not an user input
			console.log("Moo: IAC: [" + cleanData.charCodeAt(0) +"]");
		    return;
		}

        if(socket.username == undefined)
        {
                socket.username = cleanData;
                socket.write("\r\n\r\nWelcome " + socket.username + "\r\n");
				return;
        }

        if(cleanData === ".quit") {
                socket.end('Goodbye!\n');
        }
        else {
                for(var i = 0; i<sockets.length; i++) {
                        if (sockets[i] !== socket) {
                                sockets[i].write(socket.username + ": " + data);
                        }
                }
        }
}

/*
 * Method executed when a socket ends
 */
function closeSocket(socket) {
        var i = sockets.indexOf(socket);
        if (i != -1) {
                sockets.splice(i, 1);
        }
}

/*
 * Callback method executed when a new TCP socket is opened.
 */
function newSocket(socket) {
        sockets.push(socket);
        socket.write('Welcome to the '+talkername+'!\r\n\r\nGive me a name:  ');
        socket.on('data', function(data) {
                receiveData(socket, data);
        })
        socket.on('end', function() {
                closeSocket(socket);
        })
}

// Create a new server and provide a callback for when a connection occurs
var server = net.createServer(newSocket);

// Listen on defined port
server.listen(port);
<commit_msg>Userfriendly initialization<commit_after>// https://dl.dropboxusercontent.com/u/133374/hades.txt
// downloaded at 11/11/2013
// coded by sam@hades
// hades: telnet hades-talker.org 6660

var net = require('net');

var sockets = [];

var port = process.env.PORT || 8888;

var talkername = "Moosville";

/*
 * Cleans the input of carriage return, newline and control characters
 */
function cleanInput(data) {
        var newString = data.toString().replace("[\u0000-\u001f]", "");
        return newString.replace(/(\r\n|\n|\r)/gm,"");
}

/*
 * Method executed when data is received from a socket
 */
function receiveData(socket, data) {

        var cleanData = cleanInput(data);

        if(cleanData.length == 0)
                return;

        console.log("Moo [" + cleanData + "]");

		// TODO: We're just filtering out IAC commands. We should be dealing with them instead...
		// IAC commands
		var IAC = [
			1 , // Telnet IAC - Echo
			3 , // Telnet IAC - Suppress Go Ahead
			5 , // Telnet IAC - Status
			6 , // Telnet IAC - Timing Mark
			24, // Telnet IAC - Terminal Type
			31, // Telnet IAC - Window Size
			32, // Telnet IAC - Window Speed
			33, // Telnet IAC - Remote Flow Control
			34, // Telnet IAC - Linemode
			36  // Telnet IAC - Environment Variables
		];
		if (IAC.indexOf(cleanData.charCodeAt(0)) !== -1) {
			// This is IAC, not an user input
			console.log("Moo: IAC: [" + cleanData.charCodeAt(0) +"]");
		    return;
		}

        if(socket.username == undefined)
        {
                socket.username = cleanData;
                socket.write("\r\n\r\nWelcome " + socket.username + "\r\n");
				return;
        }

        if(cleanData === ".quit") {
                socket.end('Goodbye!\n');
        }
        else {
                for(var i = 0; i<sockets.length; i++) {
                        if (sockets[i] !== socket) {
                                sockets[i].write(socket.username + ": " + data);
                        }
                }
        }
}

/*
 * Method executed when a socket ends
 */
function closeSocket(socket) {
        var i = sockets.indexOf(socket);
        if (i != -1) {
                sockets.splice(i, 1);
        }
}

/*
 * Callback method executed when a new TCP socket is opened.
 */
function newSocket(socket) {
        sockets.push(socket);
        socket.write('Welcome to the '+talkername+'!\r\n\r\nGive me a name:  ');
        socket.on('data', function(data) {
                receiveData(socket, data);
        })
        socket.on('end', function() {
                closeSocket(socket);
        })
}

// Create a new server and provide a callback for when a connection occurs
var server = net.createServer(newSocket);

// Listen on defined port
server.listen(port);
console.log(talkername + " initialized on port "+ port);
<|endoftext|>


<commit_before>import restler${spaceForNamedImports} from 'restler'
import config${spaceForNamedImports} from '../config'
import * as commandsHelper${spaceForNamedImports} from '../utils/commands'
import { read, write } from '../utils/files'

const BASE_API_ADDRESS = 'http://mymemory.translated.net/api/get';

function unescapeHtml(text) {
  return text
      .replace("&", "&")
      .replace("<", "<")
      .replace(">", ">")
      .replace(""", '"')
      .replace("'", "'")
      .replace("'", "'");
}

function changeUserData(userId, data) {
  let users = read('users');

  // Find user in store
  let user = users.findIndex(tmpUser => {
    return tmpUser.id == userId;
  });

  // If it's already there!
  if (user !== -1) {
    users[user] = Object.assign(users[user], data);
  } else {
    users.push(Object.assign({id: userId}, data));
  }
  write('users', users);
}

function swapLang(userId) {
  let users = read('users');

  // Find user in store
  let user = users.findIndex(tmpUser => {
    return tmpUser.id == userId;
  });

  // If it's already there!
  if (user !== -1) {
    let src = users[user].source;
    let dst = users[user].destination;
    users[user].source = dst;
    users[user].destination = src;
    write('users', users);
    return `Source and destination languages swapped!
Source: ${dst}
Destination: ${src}`;
  }

  return 'You must set languages first.';
}

export default class Translate {
  static tl(params) {

    let userId = params.userId,
        text = params.params,
        sourceLang = undefined,
        destinationLang = undefined;

    // read src,dest from params
    let lang = text.split(' ').shift();
    if (lang.indexOf(':')) {
      let tmp = lang.split(':');
      if (tmp.length === 2) {
        sourceLang = tmp[0];
        destinationLang = tmp[1];
        text = text.replace(lang + ' ', '');
      }
    }

    if (!destinationLang) {
      // read user config
      let users = read('users');

      let user = users.find(tmpUser => {
        return tmpUser.id === userId;
      });

      // default
      if (!user) {
        sourceLang = 'en';
        destinationLang = 'fa';
      } else {
        sourceLang = user.source;
        destinationLang = user.destination;
      }

    }

    let query = {
      q: text,
      mt: 1,
      langpair: `${sourceLang}|${destinationLang}`
    }
    //console.log(query);

    return new Promise((res, rej) => {
      restler.get(BASE_API_ADDRESS, {
        query: query
      }).on('complete', response => {
        if (response instanceof Error) {
          return rej(response);
        }
        //console.log(response.matches);
        let tl = 'Nothing found. :(';
        let maxQuality = 0;
        let maxMatch = 0;
        if (!response.matches) {
          return rej('Oops!');
        }
        for (let i = 0, max = response.matches.length; i < max; i++) {
          if (response.matches[i].match > maxMatch && response.matches[i].quality > maxQuality) {
            maxQuality = response.matches[i].quality;
            maxMatch = response.matches[i].match;
            tl = response.matches[i].translation;
          }
          if (response.matches[i]['created-by'] === 'MT!' && response.matches[i].match > maxMatch) {
            tl = response.matches[i].translation;
            break;
          }
        }
        return res(unescapeHtml(tl));
      });
    })
  }

  static src(params) {
    let userId = params.userId,
        lang   = params.params;
    changeUserData(userId, {source: lang.trim()});
    return new Promise((res, rej) => {
      res(`Source language changed to ${lang}!`);
    });
  }

  static dest(params) {
    let userId = params.userId,
        lang   = params.params;
    changeUserData(userId, {destination: lang.trim()});
    return new Promise((res, rej) => {
      res(`Destination language changed to ${lang}!`);
    });
  }

  static swp(params) {
    let userId = params.userId;
    return new Promise((res, rej) => {
      res(swapLang(userId));
    });
  }

  static start(params) {
    return this.help(params);
  }

  static help(params) {
    let command = params.params;
    return new Promise((res, rej) => {
      res(commandsHelper.help(command));
    });
  }

  static feedback(params) {
    let user = params.user,
        bot = params.bot,
        message = params.params;
    bot.sendMessage(config.masterId, `New feedback from
${user.first_name || ''} ${user.last_name || ''} @${user.username || ''} <#${user.id}>
${message}`);
    return new Promise((res, rej) => {
      res('Thank you so much for giving us your feedback! ^^');
    })
  }

}
<commit_msg>remove $ char :|<commit_after>import restler{spaceForNamedImports} from 'restler'
import config${spaceForNamedImports} from '../config'
import * as commandsHelper${spaceForNamedImports} from '../utils/commands'
import { read, write } from '../utils/files'

const BASE_API_ADDRESS = 'http://mymemory.translated.net/api/get';

function unescapeHtml(text) {
  return text
      .replace("&", "&")
      .replace("<", "<")
      .replace(">", ">")
      .replace(""", '"')
      .replace("'", "'")
      .replace("'", "'");
}

function changeUserData(userId, data) {
  let users = read('users');

  // Find user in store
  let user = users.findIndex(tmpUser => {
    return tmpUser.id == userId;
  });

  // If it's already there!
  if (user !== -1) {
    users[user] = Object.assign(users[user], data);
  } else {
    users.push(Object.assign({id: userId}, data));
  }
  write('users', users);
}

function swapLang(userId) {
  let users = read('users');

  // Find user in store
  let user = users.findIndex(tmpUser => {
    return tmpUser.id == userId;
  });

  // If it's already there!
  if (user !== -1) {
    let src = users[user].source;
    let dst = users[user].destination;
    users[user].source = dst;
    users[user].destination = src;
    write('users', users);
    return `Source and destination languages swapped!
Source: ${dst}
Destination: ${src}`;
  }

  return 'You must set languages first.';
}

export default class Translate {
  static tl(params) {

    let userId = params.userId,
        text = params.params,
        sourceLang = undefined,
        destinationLang = undefined;

    // read src,dest from params
    let lang = text.split(' ').shift();
    if (lang.indexOf(':')) {
      let tmp = lang.split(':');
      if (tmp.length === 2) {
        sourceLang = tmp[0];
        destinationLang = tmp[1];
        text = text.replace(lang + ' ', '');
      }
    }

    if (!destinationLang) {
      // read user config
      let users = read('users');

      let user = users.find(tmpUser => {
        return tmpUser.id === userId;
      });

      // default
      if (!user) {
        sourceLang = 'en';
        destinationLang = 'fa';
      } else {
        sourceLang = user.source;
        destinationLang = user.destination;
      }

    }

    let query = {
      q: text,
      mt: 1,
      langpair: `${sourceLang}|${destinationLang}`
    }
    //console.log(query);

    return new Promise((res, rej) => {
      restler.get(BASE_API_ADDRESS, {
        query: query
      }).on('complete', response => {
        if (response instanceof Error) {
          return rej(response);
        }
        //console.log(response.matches);
        let tl = 'Nothing found. :(';
        let maxQuality = 0;
        let maxMatch = 0;
        if (!response.matches) {
          return rej('Oops!');
        }
        for (let i = 0, max = response.matches.length; i < max; i++) {
          if (response.matches[i].match > maxMatch && response.matches[i].quality > maxQuality) {
            maxQuality = response.matches[i].quality;
            maxMatch = response.matches[i].match;
            tl = response.matches[i].translation;
          }
          if (response.matches[i]['created-by'] === 'MT!' && response.matches[i].match > maxMatch) {
            tl = response.matches[i].translation;
            break;
          }
        }
        return res(unescapeHtml(tl));
      });
    })
  }

  static src(params) {
    let userId = params.userId,
        lang   = params.params;
    changeUserData(userId, {source: lang.trim()});
    return new Promise((res, rej) => {
      res(`Source language changed to ${lang}!`);
    });
  }

  static dest(params) {
    let userId = params.userId,
        lang   = params.params;
    changeUserData(userId, {destination: lang.trim()});
    return new Promise((res, rej) => {
      res(`Destination language changed to ${lang}!`);
    });
  }

  static swp(params) {
    let userId = params.userId;
    return new Promise((res, rej) => {
      res(swapLang(userId));
    });
  }

  static start(params) {
    return this.help(params);
  }

  static help(params) {
    let command = params.params;
    return new Promise((res, rej) => {
      res(commandsHelper.help(command));
    });
  }

  static feedback(params) {
    let user = params.user,
        bot = params.bot,
        message = params.params;
    bot.sendMessage(config.masterId, `New feedback from
${user.first_name || ''} ${user.last_name || ''} @${user.username || ''} <#${user.id}>
${message}`);
    return new Promise((res, rej) => {
      res('Thank you so much for giving us your feedback! ^^');
    })
  }

}
<|endoftext|>


<commit_before>module.exports = render

var diff = require('./')
var get = require('keyarray-get')
var splitStrings = require('./split-strings')
var splitWords=  require('./split-words')
var treeify = require('./treeify-patch')

function render(a, b) {
  var editTree = treeify(diff(a, b, splitStrings))
  return renderForm(a, editTree) }

function renderForm(form, editTree) {
  var original = form.content.reduce(
    function(returned, element, index) {
      if (typeof element === 'string') {
        returned.push(renderText(element))
        return returned }
      else if (element.hasOwnProperty('form')) {
        return returned.concat(
          renderForm(
            element.form,
            get(editTree, [ 'content', index, 'form' ], [ ]))) }
      else {
        return returned.concat(element) } },
    [ ])
  var editsHere = get(editTree, [ 'content', 'edits' ], [ ])
  return editsHere
    .reduce(
      function(returned, operation) {
        var op = operation.op
        var path = operation.path
        var value = operation.value
        var contentElementIndex = getNth(returned, path[0], true)
        var contentElement = returned[contentElementIndex]
        var splitIndex
        if (op === 'remove') {
          if (path.length === 2) {
            getNth(contentElement.splits, path[1]).del = true }
          else {
            contentElement.del = true } }
        else if (op === 'add') {
          if (path.length === 2) {
            splitIndex = getNth(contentElement.splits, path[1], true)
            contentElement.splits.splice(
              splitIndex, 0,
              { text: value, ins: true }) }
          else {
            if (value.hasOwnProperty('splits')) {
              var rendered = renderSplits(value.splits)
              rendered.ins = true
              returned.splice(contentElementIndex, 0, rendered) }
            else {
              value.ins = true
              returned.splice(contentElementIndex, 0, value) } } }
        else if (op === 'replace') {
          if (path.length === 2) {
            splitIndex = getNth(contentElement.splits, path[1], true)
            var split = contentElement.splits[splitIndex]
            split.del = true
            contentElement.splits.splice(
              splitIndex, 0, { text: value, ins: true }) }
          else {
            value.ins = true
            contentElement.del = true
            returned.splice(contentElementIndex, 0, value) } }
        return original },
      original) }

function renderText(text) {
  return renderSplits(splitWords(text)) }

function renderSplits(splits) {
  return {
    splits: splits.map(function(split) {
      return { text: split } }) } }

function getNth(elements, target, returnIndex) {
  var length = elements.length
  var count = 0
  for (var index = 0; index < length; index++) {
    var element = elements[index]
    if (!element.hasOwnProperty('del')) {
      if (count === target) {
        return ( returnIndex ? index : element ) }
      count++ } }
  return ( index + 1 ) }
<commit_msg>Pull out operation application reduction<commit_after>module.exports = render

var diff = require('./')
var get = require('keyarray-get')
var splitStrings = require('./split-strings')
var splitWords=  require('./split-words')
var treeify = require('./treeify-patch')

function render(a, b) {
  var editTree = treeify(diff(a, b, splitStrings))
  return renderForm(a, editTree) }

function renderForm(form, editTree) {
  var original = form.content.reduce(
    function(returned, element, index) {
      if (typeof element === 'string') {
        returned.push(renderText(element))
        return returned }
      else if (element.hasOwnProperty('form')) {
        return returned.concat(
          renderForm(
            element.form,
            get(editTree, [ 'content', index, 'form' ], [ ]))) }
      else {
        return returned.concat(element) } },
    [ ])
  var editsHere = get(editTree, [ 'content', 'edits' ], [ ])
  return editsHere
    .reduce(applyOperation, original) }

      function applyOperation(returned, operation) {
        var op = operation.op
        var path = operation.path
        var value = operation.value
        var contentElementIndex = getNth(returned, path[0], true)
        var contentElement = returned[contentElementIndex]
        var splitIndex
        if (op === 'remove') {
          if (path.length === 2) {
            getNth(contentElement.splits, path[1]).del = true }
          else {
            contentElement.del = true } }
        else if (op === 'add') {
          if (path.length === 2) {
            splitIndex = getNth(contentElement.splits, path[1], true)
            contentElement.splits.splice(
              splitIndex, 0,
              { text: value, ins: true }) }
          else {
            if (value.hasOwnProperty('splits')) {
              var rendered = renderSplits(value.splits)
              rendered.ins = true
              returned.splice(contentElementIndex, 0, rendered) }
            else {
              value.ins = true
              returned.splice(contentElementIndex, 0, value) } } }
        else if (op === 'replace') {
          if (path.length === 2) {
            splitIndex = getNth(contentElement.splits, path[1], true)
            var split = contentElement.splits[splitIndex]
            split.del = true
            contentElement.splits.splice(
              splitIndex, 0, { text: value, ins: true }) }
          else {
            value.ins = true
            contentElement.del = true
            returned.splice(contentElementIndex, 0, value) } }
        return returned }

function renderText(text) {
  return renderSplits(splitWords(text)) }

function renderSplits(splits) {
  return {
    splits: splits.map(function(split) {
      return { text: split } }) } }

function getNth(elements, target, returnIndex) {
  var length = elements.length
  var count = 0
  for (var index = 0; index < length; index++) {
    var element = elements[index]
    if (!element.hasOwnProperty('del')) {
      if (count === target) {
        return ( returnIndex ? index : element ) }
      count++ } }
  return ( index + 1 ) }
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

module.exports = RepeatRW;

var TypedError = require('error/typed');
var inherits = require('util').inherits;

var LengthResult = require('./base').LengthResult;
var WriteResult = require('./base').WriteResult;
var ReadResult = require('./base').ReadResult;
var BufferRW = require('./base').BufferRW;

var InvalidArgumentError = TypedError({
    type: 'repeatrw.invalid-argument',
    message: 'invalid argument, not an array',
    argType: null,
    argConstructor: null
});

function RepeatRW(countrw, repeatedrw) {
    if (!(this instanceof RepeatRW)) {
        return new RepeatRW(countrw, repeatedrw);
    }
    var self = this;
    self.countrw = countrw;
    self.repeatedrw = repeatedrw;
}
inherits(RepeatRW, BufferRW);

RepeatRW.prototype.byteLength = function byteLength(values) {
    if (!Array.isArray(values)) {
        return LengthResult.error(InvalidArgumentError({
            argType: typeof values,
            argConstructor: values.constructor.name
        }));
    }
    var self = this;
    var res = self.countrw.byteLength(values.length);
    if (res.err) return res;
    for (var i = 0; i < values.length; i++) {
        var partres = self.repeatedrw.byteLength(values[i]);
        if (partres.err) return partres;
        res.length += partres.length;
    }
    return res;
};

RepeatRW.prototype.writeInto = function writeInto(values, buffer, offset) {
    if (!Array.isArray(values)) {
        return WriteResult.error(InvalidArgumentError({
            argType: typeof values,
            argConstructor: values.constructor.name
        }), offset);
    }
    var self = this;
    var res = self.countrw.writeInto(values.length, buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    for (var i = 0; i < values.length; i++) {
        res = self.repeatedrw.writeInto(values[i], buffer, offset);
        if (res.err) return res;
        offset = res.offset;
    }
    return res;
};

RepeatRW.prototype.readFrom = function readFrom(buffer, offset) {
    var self = this;
    var res = self.countrw.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    var count = res.value;
    var values = new Array(count);
    for (var i = 0; i < count; i++) {
        res = self.repeatedrw.readFrom(buffer, offset);
        if (res.err) return res;
        offset = res.offset;
        values[i] = res.value;
    }
    return ReadResult(null, offset, values);
};
<commit_msg>RepeatRW: drop prefix from arg error<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

module.exports = RepeatRW;

var TypedError = require('error/typed');
var inherits = require('util').inherits;

var LengthResult = require('./base').LengthResult;
var WriteResult = require('./base').WriteResult;
var ReadResult = require('./base').ReadResult;
var BufferRW = require('./base').BufferRW;

var InvalidArgumentError = TypedError({
    type: 'invalid-argument',
    message: 'invalid argument, not an array',
    argType: null,
    argConstructor: null
});

function RepeatRW(countrw, repeatedrw) {
    if (!(this instanceof RepeatRW)) {
        return new RepeatRW(countrw, repeatedrw);
    }
    var self = this;
    self.countrw = countrw;
    self.repeatedrw = repeatedrw;
}
inherits(RepeatRW, BufferRW);

RepeatRW.prototype.byteLength = function byteLength(values) {
    if (!Array.isArray(values)) {
        return LengthResult.error(InvalidArgumentError({
            argType: typeof values,
            argConstructor: values.constructor.name
        }));
    }
    var self = this;
    var res = self.countrw.byteLength(values.length);
    if (res.err) return res;
    for (var i = 0; i < values.length; i++) {
        var partres = self.repeatedrw.byteLength(values[i]);
        if (partres.err) return partres;
        res.length += partres.length;
    }
    return res;
};

RepeatRW.prototype.writeInto = function writeInto(values, buffer, offset) {
    if (!Array.isArray(values)) {
        return WriteResult.error(InvalidArgumentError({
            argType: typeof values,
            argConstructor: values.constructor.name
        }), offset);
    }
    var self = this;
    var res = self.countrw.writeInto(values.length, buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    for (var i = 0; i < values.length; i++) {
        res = self.repeatedrw.writeInto(values[i], buffer, offset);
        if (res.err) return res;
        offset = res.offset;
    }
    return res;
};

RepeatRW.prototype.readFrom = function readFrom(buffer, offset) {
    var self = this;
    var res = self.countrw.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    var count = res.value;
    var values = new Array(count);
    for (var i = 0; i < count; i++) {
        res = self.repeatedrw.readFrom(buffer, offset);
        if (res.err) return res;
        offset = res.offset;
        values[i] = res.value;
    }
    return ReadResult(null, offset, values);
};
<|endoftext|>


<commit_before>'use strict';

var homebridge;
var Characteristic;

module.exports = function(pHomebridge) {
  if (pHomebridge && !homebridge) {
    homebridge = pHomebridge;
    Characteristic = homebridge.hap.Characteristic;
  }

  class TemperatureService extends homebridge.hap.Service.TemperatureSensor {
    constructor(accessory) {
      super(accessory.name + " Temperature");
      this.accessory = accessory;

      this.getCharacteristic(Characteristic.CurrentTemperature)
        .on('get', this.getCurrentTemperature.bind(this))
        .eventEnabled = true;

    }

    updateCharacteristics() {
      this.getCharacteristic(Characteristic.CurrentTemperature)
            .updateValue(this.accessory.currentTemperature);
    }

    getCurrentTemperature(callback) {
      this.accessory.refreshData(function(err,data) {
        callback(err, this.accessory.currentTemperature);
      }.bind(this));
    }
  }

  return TemperatureService;
}

/*
  if(stationData.data_type.indexOf('Temperature') > -1) {
    services.push(this.buildTemperatureSensor(accessory, stationData));
  }
*/
<commit_msg>Try to fix negative temps<commit_after>'use strict';

var homebridge;
var Characteristic;

module.exports = function(pHomebridge) {
  if (pHomebridge && !homebridge) {
    homebridge = pHomebridge;
    Characteristic = homebridge.hap.Characteristic;
  }

  class TemperatureService extends homebridge.hap.Service.TemperatureSensor {
    constructor(accessory) {
      super(accessory.name + " Temperature");
      this.accessory = accessory;

      var tmpChar = this.getCharacteristic(Characteristic.CurrentTemperature);
      tmpChar.setProps({ minValue: -100 });
      tmpChar.on('get', this.getCurrentTemperature.bind(this));
      tmpChar.eventEnabled = true;

    }

    updateCharacteristics() {
      this.getCharacteristic(Characteristic.CurrentTemperature)
            .updateValue(this.accessory.currentTemperature);
    }

    getCurrentTemperature(callback) {
      this.accessory.refreshData(function(err,data) {
        callback(err, this.accessory.currentTemperature);
      }.bind(this));
    }
  }

  return TemperatureService;
}

/*
  if(stationData.data_type.indexOf('Temperature') > -1) {
    services.push(this.buildTemperatureSensor(accessory, stationData));
  }
*/
<|endoftext|>


<commit_before>var subs = new SubsManager({
  // cache recent 50 subscriptions
  cacheLimit: 50,
  // expire any subscription after 30 minutes
  expireIn: 30
});
var scrolled = false;

Router.configure({
  layoutTemplate: 'mainLayout',
  // loadingTemplate: 'loading',
  notFoundTemplate: 'notFound',
  onRun: function () {
    console.log('global onRun');
    this.next();
  }
});

Router.onBeforeAction(function () {
  if (!Meteor.loggingIn() && !Meteor.user()) {
    if (Session.get('resetPassword')) {
      this.redirect('/forgot');
    } else {
      this.redirect('/landing');
    }
  } else {
    this.next();
  }
}, { except: ['landing', 'login', 'invite', 'forgotPassword'] });

Router.onBeforeAction(function () {
  if (Meteor.user()) {
    this.redirect('/');
  } else {
    this.next();
  }

}, { only: ['landing', 'login', 'invite'] });

// Router.onBeforeAction(function () {

// }, { only: ['admin'] });

Router.plugin('dataNotFound', { notFoundTemplate: 'notFound' });

Router.onAfterAction(function () {
  if (this.ready()) {
    var hash = window.location.hash.substring(1);

    if (hash && !scrolled) {
      Meteor.defer(function () {
        scrollToId(hash);
        scrolled = true;
      });
    }
  }
});

subs.subscribe('currentUser');

Router.route('/forgot', {
  name: 'forgotPassword'
});
Router.route('/invite', {
  onBeforeAction: function () {
    var self = this;
    var inviterId = self.params.inviter_id;
    var inviteCode = self.params.invite_code;

    Meteor.call('validLink', inviterId, inviteCode, function (error, result) {
      if (!result || error) {
        self.render('notFound');
      } else {
        self.render();
      }
    });

    this.render('loading');
  }
});
Router.route('/login');
Router.route('/landing');

Router.route('/', {
  name: 'home',
  subscriptions: function () {
    return subs.subscribe('topicsList', Session.get('topicsLimit'));
  },
  action: function () {
    if (this.ready() && Meteor.user()) {
      this.render('nav', { to: 'nav' });
      this.render('home');
    }
  },
  data: function () {
    return Topics.find({}, { sort: { 'createdAt': -1 } });
  }
});
Router.route('/topics/:_id', {
  name: 'topic',
  subscriptions: function () {
    return [
      Meteor.subscribe('singleTopic', this.params._id),
      Meteor.subscribe('topicComments', this.params._id, this.params.sort_by)
    ];
  },
  onRun: function () {
    Session.set('currentTab', 'topicComments');
    SessionAmplify.set('showingReplies', []);
    console.log('onRun for topic route');
    this.next();
  },
  action: function () {
    if (this.ready() && Meteor.user()) {
      this.layout('pageLayout');
      this.render();
      this.render('nav', { to: 'nav' });
      this.render('topicButtons', { to: 'pageButtons' });
      this.render('topicHeader', { to: 'pageHeader' });
      this.render('topicNav', { to: 'pageNav' });
    }
  },
  data: function () {
    Session.set('currentTopic', this.params._id);
    return Topics.findOne({ '_id': this.params._id, 'isDeleted': false });
  }
});
Router.route('/users/:_id', {
  name: 'profile',
  subscriptions: function () {
    return Meteor.subscribe('userProfile', this.params._id);
  },
  onRun: function () {
    Session.set('currentTab', 'profileComments');
    console.log('onRun for profile route');
    this.next();
  },
  action: function () {
    if (this.ready() && Meteor.user()) {
      this.layout('pageLayout');
      this.render();
      this.render('nav', { to: 'nav' });
      this.render('profileButtons', { to: 'pageButtons' });
      this.render('profileHeader', { to: 'pageHeader' });
      this.render('profileNav', { to: 'pageNav' });
    }
  },
  data: function () {
    return Meteor.users.findOne(this.params._id);
  }
});
Router.route('/users/:_id/settings', {
  name: 'settings'
});

<commit_msg>Add delay before showing progress<commit_after>var subs = new SubsManager({
  // cache recent 50 subscriptions
  cacheLimit: 50,
  // expire any subscription after 30 minutes
  expireIn: 30
});
var scrolled = false;

Router.configure({
  layoutTemplate: 'mainLayout',
  // loadingTemplate: 'loading',
  notFoundTemplate: 'notFound',
  onRun: function () {
    console.log('global onRun');
    this.next();
  },
  progressDelay: 100 // delay before showing IR progress
});

Router.onBeforeAction(function () {
  if (!Meteor.loggingIn() && !Meteor.user()) {
    if (Session.get('resetPassword')) {
      this.redirect('/forgot');
    } else {
      this.redirect('/landing');
    }
  } else {
    this.next();
  }
}, { except: ['landing', 'login', 'invite', 'forgotPassword'] });

Router.onBeforeAction(function () {
  if (Meteor.user()) {
    this.redirect('/');
  } else {
    this.next();
  }

}, { only: ['landing', 'login', 'invite'] });

// Router.onBeforeAction(function () {

// }, { only: ['admin'] });

Router.plugin('dataNotFound', { notFoundTemplate: 'notFound' });

Router.onAfterAction(function () {
  if (this.ready()) {
    var hash = window.location.hash.substring(1);

    if (hash && !scrolled) {
      Meteor.defer(function () {
        scrollToId(hash);
        scrolled = true;
      });
    }
  }
});

subs.subscribe('currentUser');

Router.route('/forgot', {
  name: 'forgotPassword'
});
Router.route('/invite', {
  onBeforeAction: function () {
    var self = this;
    var inviterId = self.params.inviter_id;
    var inviteCode = self.params.invite_code;

    Meteor.call('validLink', inviterId, inviteCode, function (error, result) {
      if (!result || error) {
        self.render('notFound');
      } else {
        self.render();
      }
    });

    this.render('loading');
  }
});
Router.route('/login');
Router.route('/landing');

Router.route('/', {
  name: 'home',
  subscriptions: function () {
    return subs.subscribe('topicsList', Session.get('topicsLimit'));
  },
  action: function () {
    if (this.ready() && Meteor.user()) {
      this.render('nav', { to: 'nav' });
      this.render('home');
    }
  },
  data: function () {
    return Topics.find({}, { sort: { 'createdAt': -1 } });
  }
});
Router.route('/topics/:_id', {
  name: 'topic',
  subscriptions: function () {
    return [
      Meteor.subscribe('singleTopic', this.params._id),
      Meteor.subscribe('topicComments', this.params._id, this.params.sort_by)
    ];
  },
  onRun: function () {
    Session.set('currentTab', 'topicComments');
    SessionAmplify.set('showingReplies', []);
    console.log('onRun for topic route');
    this.next();
  },
  action: function () {
    if (this.ready() && Meteor.user()) {
      this.layout('pageLayout');
      this.render();
      this.render('nav', { to: 'nav' });
      this.render('topicButtons', { to: 'pageButtons' });
      this.render('topicHeader', { to: 'pageHeader' });
      this.render('topicNav', { to: 'pageNav' });
    }
  },
  data: function () {
    Session.set('currentTopic', this.params._id);
    return Topics.findOne({ '_id': this.params._id, 'isDeleted': false });
  }
});
Router.route('/users/:_id', {
  name: 'profile',
  subscriptions: function () {
    return Meteor.subscribe('userProfile', this.params._id);
  },
  onRun: function () {
    Session.set('currentTab', 'profileComments');
    console.log('onRun for profile route');
    this.next();
  },
  action: function () {
    if (this.ready() && Meteor.user()) {
      this.layout('pageLayout');
      this.render();
      this.render('nav', { to: 'nav' });
      this.render('profileButtons', { to: 'pageButtons' });
      this.render('profileHeader', { to: 'pageHeader' });
      this.render('profileNav', { to: 'pageNav' });
    }
  },
  data: function () {
    return Meteor.users.findOne(this.params._id);
  }
});
Router.route('/users/:_id/settings', {
  name: 'settings'
});

<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All rights reserved.

/**
 *
 * @fileoverview Functions for replaying events by the jsaction
 * Dispatcher.
 */
goog.provide('jsaction.createKeyboardEvent');
goog.provide('jsaction.createMouseEvent');
goog.provide('jsaction.createUiEvent');
goog.provide('jsaction.replayEvent');
goog.provide('jsaction.triggerEvent');

goog.require('goog.asserts');
goog.require('goog.events.EventType');
goog.require('goog.functions');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
goog.require('jsaction');
goog.require('jsaction.EventType');

/**
 * Replays an event.
 * @param {!jsaction.EventInfo} eventInfo The event info record.
 */
jsaction.replayEvent = function(eventInfo) {
  var event = jsaction.createEvent(eventInfo['event'], eventInfo['eventType']);
  jsaction.triggerEvent(eventInfo['targetElement'], event);
};

/**
 * Checks if a given event was triggered by the keyboard.
 * @param {string} eventType The event type.
 * @return {boolean} Whether it's a keyboard event.
 * @private
 */
jsaction.isKeyboardEvent_ = function(eventType) {
  return eventType == goog.events.EventType.KEYPRESS ||
      eventType == goog.events.EventType.KEYDOWN ||
      eventType == goog.events.EventType.KEYUP;
};

/**
 * Checks if a given event was triggered by the mouse.
 * @param {string} eventType The event type.
 * @return {boolean} Whether it's a mouse event.
 * @private
 */
jsaction.isMouseEvent_ = function(eventType) {
  // TODO(ruilopes): Verify if Drag events should be bound here.
  return eventType == goog.events.EventType.CLICK ||
      eventType == goog.events.EventType.DBLCLICK ||
      eventType == goog.events.EventType.MOUSEDOWN ||
      eventType == goog.events.EventType.MOUSEOVER ||
      eventType == goog.events.EventType.MOUSEOUT ||
      eventType == goog.events.EventType.MOUSEMOVE;
};

/**
 * Checks if a given event is a general UI event.
 * @param {string} eventType The event type.
 * @return {boolean} Whether it's a focus event.
 * @private
 */
jsaction.isUiEvent_ = function(eventType) {
  // Almost nobody supports the W3C method of creating FocusEvents.
  // For now, we're going to use the UIEvent as a super-interface.
  return eventType == goog.events.EventType.FOCUS ||
      eventType == goog.events.EventType.BLUR ||
      eventType == goog.events.EventType.FOCUSIN ||
      eventType == goog.events.EventType.FOCUSOUT ||
      eventType == goog.events.EventType.SCROLL;
};

/**
 * Create a whitespace-delineated list of modifier keys that should be
 * considered to be active on the event's key. See details at
 * https://developer.mozilla.org/en/DOM/KeyboardEvent.
 * @param {boolean} alt Alt pressed.
 * @param {boolean} ctrl Control pressed.
 * @param {boolean} meta Command pressed (OSX only).
 * @param {boolean} shift Shift pressed.
 * @return {string} The constructed modifier keys string.
 * @private
 */
jsaction.createKeyboardModifiersList_ = function(alt, ctrl, meta, shift) {
  var keys = [];
  if (alt) {
    keys.push('Alt');
  }
  if (ctrl) {
    keys.push('Control');
  }
  if (meta) {
    keys.push('Meta');
  }
  if (shift) {
    keys.push('Shift');
  }
  return keys.join(' ');
};

/**
 * Creates a UI event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. blur events are handled as focusout
 * @return {!Event} The event object.
 */
jsaction.createUiEvent = function(original, opt_eventType) {
  var event;
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('UIEvent');
    // On IE and Opera < 12, we must provide non-undefined values to
    // initEvent, otherwise it will fail.
    event.initUIEvent(
        opt_eventType || original.type,
        original.bubbles || false,
        original.cancelable || false,
        original.view || window,
        original.detail || 0 //detail
    );
  } else {
    goog.asserts.assert(document.createEventObject);
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
    event.bubbles = original.bubbles || false;
    event.cancelable = original.cancelable || false;
    event.view = original.view || window;
    event.detail = original.detail || 0;
  }
  // Some focus events also have a nullable relatedTarget value which isn't
  // directly supported in the initUIEvent() method.
  event.relatedTarget = original.relatedTarget || null;
  return event;
};

/**
 * Creates a keyboard event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!Event} The event object.
 */
jsaction.createKeyboardEvent = function(original, opt_eventType) {
  var event;
  if (goog.userAgent.OPERA || goog.userAgent.product.SAFARI) {
    // Opera < 12.14 doesn't support DOM Level 3 events in all of its extent.
    // Opera 12.15 supports DOM Level 3 events, but not the initKeyboardEvent
    // used below.
    // Thus, we must fallback to a generic DOM event to trigger a keyboard
    // event.  See details at
    // http://my.opera.com/community/forums/topic.dml?id=185375.
    // TODO(ruilopes): Revisit this once logs show we don't need to support
    // older Opera versions.
    //
    // We also have to fall back to a generic event for Safari, which has the
    // Webkit keyCode bug noted below, but is also incapable of fixing it with
    // Object.defineProperty due to another bug:
    // https://bugs.webkit.org/show_bug.cgi?id=36423
    event = jsaction.createGenericEvent_(original, opt_eventType);
    event.ctrlKey = original.ctrlKey;
    event.altKey = original.altKey;
    event.shiftKey = original.shiftKey;
    event.metaKey = original.metaKey;
    event.keyCode = original.keyCode;
    event.charCode = original.charCode;
    return event;
  }
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('KeyboardEvent');
    if (event.initKeyboardEvent) {
      // W3C DOM Level 3 Events model.
      var modifiers = jsaction.createKeyboardModifiersList_(original.altKey,
          original.ctrlKey, original.metaKey, original.shiftKey);
      event.initKeyboardEvent(
          opt_eventType || original.type,
          true,
          true,
          window,
          original.charCode,
          original.keyCode,
          original.location,
          modifiers,
          original.repeat,
          original.locale);

      // Blink and Webkit have a long-standing bug that causes the 'keyCode' and
      // 'which' properties to always be set to 0 when synthesizing a keyboard
      // event. Details at: https://bugs.webkit.org/show_bug.cgi?id=16735
      // It unfortunately looks like IE9+ also copied this behavior, when they
      // implemented DOM3 events.  We work around it by redefining the noted
      // properties; a simple assignment here would fail because the native
      // properties are readonly.
      if (goog.userAgent.WEBKIT ||
          (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('9.0'))) {
        var keyCodeGetter = goog.functions.constant(original.keyCode);
        Object.defineProperty(event, 'keyCode', {
          get: keyCodeGetter
        });
        Object.defineProperty(event, 'which', {
          get: keyCodeGetter
        });
      }

    } else {
      // Gecko only supports an older/deprecated version from DOM Level 2. See
      // https://developer.mozilla.org/en/DOM/event.initKeyEvent for details.
      goog.asserts.assert(event.initKeyEvent);
      event.initKeyEvent(
          opt_eventType || original.type,
          true,
          true,
          window,
          original.ctrlKey,
          original.altKey,
          original.shiftKey,
          original.metaKey,
          original.keyCode,
          original.charCode);
    }
  } else {
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    goog.asserts.assert(document.createEventObject);
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
    event.repeat = original.repeat;
    event.ctrlKey = original.ctrlKey;
    event.altKey = original.altKey;
    event.shiftKey = original.shiftKey;
    event.metaKey = original.metaKey;
    event.keyCode = original.keyCode;
    event.charCode = original.charCode;
  }
  return event;
};

/**
 * Creates a mouse event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!MouseEvent} The event object.
 */
jsaction.createMouseEvent = function(original, opt_eventType) {
  var event;
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('MouseEvent');
    // On IE and Opera < 12, we must provide non-undefined values to
    // initMouseEvent, otherwise it will fail.
    event.initMouseEvent(
        opt_eventType || original.type,
        true,  // canBubble
        true,  // cancelable
        window,
        original.detail || 1,
        original.screenX || 0,
        original.screenY || 0,
        original.clientX || 0,
        original.clientY || 0,
        original.ctrlKey || false,
        original.altKey || false,
        original.shiftKey || false,
        original.metaKey || false,
        original.button || 0,
        original.relatedTarget || null);

  } else {
    goog.asserts.assert(document.createEventObject);
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
    event.clientX = original.clientX;
    event.clientY = original.clientY;
    event.button = original.button;
    event.detail = original.detail;
    event.ctrlKey = original.ctrlKey;
    event.altKey = original.altKey;
    event.shiftKey = original.shiftKey;
    event.metaKey = original.metaKey;
  }
  return event;
};

/**
 * Creates a generic event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!Event} The event object.
 * @private
 */
jsaction.createGenericEvent_ = function(original, opt_eventType) {
  var event;
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('Event');
    event.initEvent(
        opt_eventType || original.type,
        true,
        true);
  } else {
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    goog.asserts.assert(document.createEventObject);
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
  }
  return event;
};

/**
 * Creates an event object for replaying through the DOM.
 * NOTE(ruilopes): This function is visible just for testing.  Please don't use
 * it outside JsAction internal testing.
 * TODO(ruilopes): Add support for FocusEvent and WheelEvent.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!Event} The event object.
 */
jsaction.createEvent = function(original, opt_eventType) {
  var event;
  var eventType;
  if (original.type == jsaction.EventType.CUSTOM) {
    eventType = jsaction.EventType.CUSTOM;
  } else {
    eventType = opt_eventType || original.type;
  }

  if (jsaction.isKeyboardEvent_(eventType)) {
    event = jsaction.createKeyboardEvent(original, opt_eventType);
  } else if (jsaction.isMouseEvent_(eventType)) {
    event = jsaction.createMouseEvent(original, opt_eventType);
  } else if (jsaction.isUiEvent_(eventType)) {
    event = jsaction.createUiEvent(original, opt_eventType);
  } else if (eventType == jsaction.EventType.CUSTOM) {
    goog.asserts.assert(opt_eventType);
    event = jsaction.createCustomEvent(
        opt_eventType, original['detail']['data']);
  } else {
    // This ensures we don't send an undefined event object to the replayer.
    event = jsaction.createGenericEvent_(original, opt_eventType);
  }
  return event;
};

/**
 * Sends an event for replay to the DOM.
 * @param {!EventTarget} target The target for the event.
 * @param {!Event} event The event object.
 * @return {boolean} The return value of the event replay, i.e., whether
 *     preventDefault() was called on it.
 */
jsaction.triggerEvent = function(target, event) {
  if (target.dispatchEvent) {
    return target.dispatchEvent(event);
  } else {
    goog.asserts.assert(target.fireEvent);
    return target.fireEvent('on' + event.type, event);
  }
};
<commit_msg>Use true as the default for bubbling in createUiEvent. This used to be createFocusEvent which by default does not have bubbling, but now that it has a general name, it should have more general defaults.<commit_after>// Copyright 2011 Google Inc. All rights reserved.

/**
 *
 * @fileoverview Functions for replaying events by the jsaction
 * Dispatcher.
 */
goog.provide('jsaction.createKeyboardEvent');
goog.provide('jsaction.createMouseEvent');
goog.provide('jsaction.createUiEvent');
goog.provide('jsaction.replayEvent');
goog.provide('jsaction.triggerEvent');

goog.require('goog.asserts');
goog.require('goog.events.EventType');
goog.require('goog.functions');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
goog.require('jsaction');
goog.require('jsaction.EventType');

/**
 * Replays an event.
 * @param {!jsaction.EventInfo} eventInfo The event info record.
 */
jsaction.replayEvent = function(eventInfo) {
  var event = jsaction.createEvent(eventInfo['event'], eventInfo['eventType']);
  jsaction.triggerEvent(eventInfo['targetElement'], event);
};

/**
 * Checks if a given event was triggered by the keyboard.
 * @param {string} eventType The event type.
 * @return {boolean} Whether it's a keyboard event.
 * @private
 */
jsaction.isKeyboardEvent_ = function(eventType) {
  return eventType == goog.events.EventType.KEYPRESS ||
      eventType == goog.events.EventType.KEYDOWN ||
      eventType == goog.events.EventType.KEYUP;
};

/**
 * Checks if a given event was triggered by the mouse.
 * @param {string} eventType The event type.
 * @return {boolean} Whether it's a mouse event.
 * @private
 */
jsaction.isMouseEvent_ = function(eventType) {
  // TODO(ruilopes): Verify if Drag events should be bound here.
  return eventType == goog.events.EventType.CLICK ||
      eventType == goog.events.EventType.DBLCLICK ||
      eventType == goog.events.EventType.MOUSEDOWN ||
      eventType == goog.events.EventType.MOUSEOVER ||
      eventType == goog.events.EventType.MOUSEOUT ||
      eventType == goog.events.EventType.MOUSEMOVE;
};

/**
 * Checks if a given event is a general UI event.
 * @param {string} eventType The event type.
 * @return {boolean} Whether it's a focus event.
 * @private
 */
jsaction.isUiEvent_ = function(eventType) {
  // Almost nobody supports the W3C method of creating FocusEvents.
  // For now, we're going to use the UIEvent as a super-interface.
  return eventType == goog.events.EventType.FOCUS ||
      eventType == goog.events.EventType.BLUR ||
      eventType == goog.events.EventType.FOCUSIN ||
      eventType == goog.events.EventType.FOCUSOUT ||
      eventType == goog.events.EventType.SCROLL;
};

/**
 * Create a whitespace-delineated list of modifier keys that should be
 * considered to be active on the event's key. See details at
 * https://developer.mozilla.org/en/DOM/KeyboardEvent.
 * @param {boolean} alt Alt pressed.
 * @param {boolean} ctrl Control pressed.
 * @param {boolean} meta Command pressed (OSX only).
 * @param {boolean} shift Shift pressed.
 * @return {string} The constructed modifier keys string.
 * @private
 */
jsaction.createKeyboardModifiersList_ = function(alt, ctrl, meta, shift) {
  var keys = [];
  if (alt) {
    keys.push('Alt');
  }
  if (ctrl) {
    keys.push('Control');
  }
  if (meta) {
    keys.push('Meta');
  }
  if (shift) {
    keys.push('Shift');
  }
  return keys.join(' ');
};

/**
 * Creates a UI event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. blur events are handled as focusout
 * @return {!Event} The event object.
 */
jsaction.createUiEvent = function(original, opt_eventType) {
  var event;
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('UIEvent');
    // On IE and Opera < 12, we must provide non-undefined values to
    // initEvent, otherwise it will fail.
    event.initUIEvent(
        opt_eventType || original.type,
        goog.isDef(original.bubbles) ? original.bubbles : true,
        original.cancelable || false,
        original.view || window,
        original.detail || 0 //detail
    );
  } else {
    goog.asserts.assert(document.createEventObject);
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
    event.bubbles = goog.isDef(original.bubbles) ? original.bubbles : true;
    event.cancelable = original.cancelable || false;
    event.view = original.view || window;
    event.detail = original.detail || 0;
  }
  // Some focus events also have a nullable relatedTarget value which isn't
  // directly supported in the initUIEvent() method.
  event.relatedTarget = original.relatedTarget || null;
  return event;
};

/**
 * Creates a keyboard event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!Event} The event object.
 */
jsaction.createKeyboardEvent = function(original, opt_eventType) {
  var event;
  if (goog.userAgent.OPERA || goog.userAgent.product.SAFARI) {
    // Opera < 12.14 doesn't support DOM Level 3 events in all of its extent.
    // Opera 12.15 supports DOM Level 3 events, but not the initKeyboardEvent
    // used below.
    // Thus, we must fallback to a generic DOM event to trigger a keyboard
    // event.  See details at
    // http://my.opera.com/community/forums/topic.dml?id=185375.
    // TODO(ruilopes): Revisit this once logs show we don't need to support
    // older Opera versions.
    //
    // We also have to fall back to a generic event for Safari, which has the
    // Webkit keyCode bug noted below, but is also incapable of fixing it with
    // Object.defineProperty due to another bug:
    // https://bugs.webkit.org/show_bug.cgi?id=36423
    event = jsaction.createGenericEvent_(original, opt_eventType);
    event.ctrlKey = original.ctrlKey;
    event.altKey = original.altKey;
    event.shiftKey = original.shiftKey;
    event.metaKey = original.metaKey;
    event.keyCode = original.keyCode;
    event.charCode = original.charCode;
    return event;
  }
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('KeyboardEvent');
    if (event.initKeyboardEvent) {
      // W3C DOM Level 3 Events model.
      var modifiers = jsaction.createKeyboardModifiersList_(original.altKey,
          original.ctrlKey, original.metaKey, original.shiftKey);
      event.initKeyboardEvent(
          opt_eventType || original.type,
          true,
          true,
          window,
          original.charCode,
          original.keyCode,
          original.location,
          modifiers,
          original.repeat,
          original.locale);

      // Blink and Webkit have a long-standing bug that causes the 'keyCode' and
      // 'which' properties to always be set to 0 when synthesizing a keyboard
      // event. Details at: https://bugs.webkit.org/show_bug.cgi?id=16735
      // It unfortunately looks like IE9+ also copied this behavior, when they
      // implemented DOM3 events.  We work around it by redefining the noted
      // properties; a simple assignment here would fail because the native
      // properties are readonly.
      if (goog.userAgent.WEBKIT ||
          (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('9.0'))) {
        var keyCodeGetter = goog.functions.constant(original.keyCode);
        Object.defineProperty(event, 'keyCode', {
          get: keyCodeGetter
        });
        Object.defineProperty(event, 'which', {
          get: keyCodeGetter
        });
      }

    } else {
      // Gecko only supports an older/deprecated version from DOM Level 2. See
      // https://developer.mozilla.org/en/DOM/event.initKeyEvent for details.
      goog.asserts.assert(event.initKeyEvent);
      event.initKeyEvent(
          opt_eventType || original.type,
          true,
          true,
          window,
          original.ctrlKey,
          original.altKey,
          original.shiftKey,
          original.metaKey,
          original.keyCode,
          original.charCode);
    }
  } else {
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    goog.asserts.assert(document.createEventObject);
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
    event.repeat = original.repeat;
    event.ctrlKey = original.ctrlKey;
    event.altKey = original.altKey;
    event.shiftKey = original.shiftKey;
    event.metaKey = original.metaKey;
    event.keyCode = original.keyCode;
    event.charCode = original.charCode;
  }
  return event;
};

/**
 * Creates a mouse event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!MouseEvent} The event object.
 */
jsaction.createMouseEvent = function(original, opt_eventType) {
  var event;
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('MouseEvent');
    // On IE and Opera < 12, we must provide non-undefined values to
    // initMouseEvent, otherwise it will fail.
    event.initMouseEvent(
        opt_eventType || original.type,
        true,  // canBubble
        true,  // cancelable
        window,
        original.detail || 1,
        original.screenX || 0,
        original.screenY || 0,
        original.clientX || 0,
        original.clientY || 0,
        original.ctrlKey || false,
        original.altKey || false,
        original.shiftKey || false,
        original.metaKey || false,
        original.button || 0,
        original.relatedTarget || null);

  } else {
    goog.asserts.assert(document.createEventObject);
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
    event.clientX = original.clientX;
    event.clientY = original.clientY;
    event.button = original.button;
    event.detail = original.detail;
    event.ctrlKey = original.ctrlKey;
    event.altKey = original.altKey;
    event.shiftKey = original.shiftKey;
    event.metaKey = original.metaKey;
  }
  return event;
};

/**
 * Creates a generic event object for replaying through the DOM.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!Event} The event object.
 * @private
 */
jsaction.createGenericEvent_ = function(original, opt_eventType) {
  var event;
  if (document.createEvent) {
    // Event creation as per W3C event model specification.  This codepath
    // is used by most non-IE browsers and also by IE 9 and later.
    event = document.createEvent('Event');
    event.initEvent(
        opt_eventType || original.type,
        true,
        true);
  } else {
    // Older versions of IE (up to version 8) do not support the
    // W3C event model. Use the IE specific function instead.
    goog.asserts.assert(document.createEventObject);
    event = document.createEventObject();
    event.type = opt_eventType || original.type;
  }
  return event;
};

/**
 * Creates an event object for replaying through the DOM.
 * NOTE(ruilopes): This function is visible just for testing.  Please don't use
 * it outside JsAction internal testing.
 * TODO(ruilopes): Add support for FocusEvent and WheelEvent.
 * @param {!Event} original The event to create a new event from.
 * @param {string=} opt_eventType The type this event is being handled as by
 *     jsaction. E.g. a keypress is handled as click in some cases.
 * @return {!Event} The event object.
 */
jsaction.createEvent = function(original, opt_eventType) {
  var event;
  var eventType;
  if (original.type == jsaction.EventType.CUSTOM) {
    eventType = jsaction.EventType.CUSTOM;
  } else {
    eventType = opt_eventType || original.type;
  }

  if (jsaction.isKeyboardEvent_(eventType)) {
    event = jsaction.createKeyboardEvent(original, opt_eventType);
  } else if (jsaction.isMouseEvent_(eventType)) {
    event = jsaction.createMouseEvent(original, opt_eventType);
  } else if (jsaction.isUiEvent_(eventType)) {
    event = jsaction.createUiEvent(original, opt_eventType);
  } else if (eventType == jsaction.EventType.CUSTOM) {
    goog.asserts.assert(opt_eventType);
    event = jsaction.createCustomEvent(
        opt_eventType, original['detail']['data']);
  } else {
    // This ensures we don't send an undefined event object to the replayer.
    event = jsaction.createGenericEvent_(original, opt_eventType);
  }
  return event;
};

/**
 * Sends an event for replay to the DOM.
 * @param {!EventTarget} target The target for the event.
 * @param {!Event} event The event object.
 * @return {boolean} The return value of the event replay, i.e., whether
 *     preventDefault() was called on it.
 */
jsaction.triggerEvent = function(target, event) {
  if (target.dispatchEvent) {
    return target.dispatchEvent(event);
  } else {
    goog.asserts.assert(target.fireEvent);
    return target.fireEvent('on' + event.type, event);
  }
};
<|endoftext|>