<commit_before>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global require */

(function () {
  'use strict';
  var graph_module = require('org/arangodb/general-graph'),
    ArangoError = require('internal').ArangoError,
    _ = require('underscore'),
    Graph,
    VertexNotFound,
    tryAndHandleArangoError,
    alreadyExists;

  VertexNotFound = function () {
    this.name = 'VertexNotFound';
    this.message = 'The vertex could not be found';
  };
  VertexNotFound.prototype = Error.prototype;

  tryAndHandleArangoError = function (func, errHandler) {
    try {
      func();
    } catch (e) {
      if (e instanceof ArangoError) {
        errHandler();
      } else {
        throw e;
      }
    }
  };

  alreadyExists = function (type, name) {
    return function () {
      require('console').log('%s "%s" already added. Leaving it untouched.', type, name);
    };
  };

  Graph = function (name, appContext) {
    var that = this;
    this.appContext = appContext;

    tryAndHandleArangoError(function () {
      that.graph = graph_module._graph(name);
    }, function () {
      that.graph = graph_module._create(name);
    });
  };

  _.extend(Graph.prototype, {
    extendEdgeDefinitions: function (rawEdgeCollectionName, from, to) {
      var vertexCollections = [ from.collectionName, to.collectionName ],
        edgeCollectionName = this.appContext.collectionName(rawEdgeCollectionName),
        edgeDefinition = graph_module._undirectedRelation(edgeCollectionName, vertexCollections),
        graph = this.graph;

      tryAndHandleArangoError(function () {
        graph._extendEdgeDefinitions(edgeDefinition);
      }, alreadyExists('EdgeDefinition', edgeCollectionName));

      return edgeCollectionName;
    },

    addVertexCollection: function (collectionName) {
      var prefixedCollectionName = this.appContext.collectionName(collectionName),
        graph = this.graph;

      tryAndHandleArangoError(function () {
        graph._addVertexCollection(prefixedCollectionName, true);
      }, alreadyExists('Collection', prefixedCollectionName));

      return this.graph[prefixedCollectionName];
    },

    neighbors: function (id, options) {
      return this.graph._neighbors(id, options);
    },

    edges: function (id, options) {
      return this.graph._vertices(id).edges().restrict(options.edgeCollectionRestriction).toArray();
    },

    removeEdges: function (options) {
      var graph = this.graph,
        vertexId = options.vertexId,
        edgeCollectionName = options.edgeCollectionName,
        edges;

      edges = this.edges(vertexId, {
        edgeCollectionRestriction: [edgeCollectionName],
      });

      _.each(edges, function (edge) {
        graph[edgeCollectionName].remove(edge._id);
      });
    },

    checkIfVerticesExist: function (ids) {
      if (!_.every(ids, this.hasVertex, this)) {
        throw new VertexNotFound();
      }
    },

    hasVertex: function (id) {
      return this.graph._vertices(id).count() > 0;
    },

    createEdge: function (options) {
      var sourceId = options.sourceId,
        destinationId = options.destinationId,
        edgeCollectionName = options.edgeCollectionName,
        edgeCollection = this.graph[edgeCollectionName];

      if (this.graph._edges([ { _from: sourceId, _to: destinationId }, { _from: destinationId, _to: sourceId }]).count() === 0) {
        edgeCollection.save(sourceId, destinationId, {});
      }
    }
  });

  exports.Graph = Graph;
  exports.VertexNotFound = VertexNotFound;
}());
<commit_msg>Refactoring<commit_after>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global require */

(function () {
  'use strict';
  var graph_module = require('org/arangodb/general-graph'),
    ArangoError = require('internal').ArangoError,
    _ = require('underscore'),
    Graph,
    VertexNotFound,
    tryAndHandleArangoError,
    alreadyExists;

  VertexNotFound = function () {
    this.name = 'VertexNotFound';
    this.message = 'The vertex could not be found';
  };
  VertexNotFound.prototype = Error.prototype;

  tryAndHandleArangoError = function (func, errHandler) {
    try {
      func();
    } catch (e) {
      if (e instanceof ArangoError) {
        errHandler();
      } else {
        throw e;
      }
    }
  };

  alreadyExists = function (type, name) {
    return function () {
      require('console').log('%s "%s" already added. Leaving it untouched.', type, name);
    };
  };

  Graph = function (name, appContext) {
    var that = this;
    this.appContext = appContext;

    tryAndHandleArangoError(function () {
      that.graph = graph_module._graph(name);
    }, function () {
      that.graph = graph_module._create(name);
    });
  };

  _.extend(Graph.prototype, {
    extendEdgeDefinitions: function (rawEdgeCollectionName, from, to) {
      var vertexCollections = [ from.collectionName, to.collectionName ],
        edgeCollectionName = this.appContext.collectionName(rawEdgeCollectionName),
        edgeDefinition = graph_module._undirectedRelation(edgeCollectionName, vertexCollections),
        graph = this.graph;

      tryAndHandleArangoError(function () {
        graph._extendEdgeDefinitions(edgeDefinition);
      }, alreadyExists('EdgeDefinition', edgeCollectionName));

      return edgeCollectionName;
    },

    addVertexCollection: function (collectionName) {
      var prefixedCollectionName = this.appContext.collectionName(collectionName),
        graph = this.graph;

      tryAndHandleArangoError(function () {
        graph._addVertexCollection(prefixedCollectionName, true);
      }, alreadyExists('Collection', prefixedCollectionName));

      return this.graph[prefixedCollectionName];
    },

    neighbors: function (id, options) {
      return this.graph._neighbors(id, options);
    },

    edges: function (id, options) {
      return this.graph._vertices(id).edges().restrict(options.edgeCollectionRestriction).toArray();
    },

    removeEdges: function (options) {
      var graph = this.graph,
        vertexId = options.vertexId,
        edgeCollectionName = options.edgeCollectionName,
        edges;

      edges = this.edges(vertexId, {
        edgeCollectionRestriction: [edgeCollectionName],
      });

      _.each(edges, function (edge) {
        graph[edgeCollectionName].remove(edge._id);
      });
    },

    checkIfVerticesExist: function (ids) {
      if (!_.every(ids, this.hasVertex, this)) {
        throw new VertexNotFound();
      }
    },

    hasVertex: function (id) {
      return this.graph._vertices(id).count() > 0;
    },

    areConnected: function (sourceId, destinationId) {
      return this.graph._edges([ { _from: sourceId, _to: destinationId }, { _from: destinationId, _to: sourceId }]).count() > 0;
    },

    createEdge: function (options) {
      var sourceId = options.sourceId,
        destinationId = options.destinationId,
        edgeCollectionName = options.edgeCollectionName,
        edgeCollection = this.graph[edgeCollectionName];

      if (!this.areConnected(sourceId, destinationId)) {
        edgeCollection.save(sourceId, destinationId, {});
      }
    }
  });

  exports.Graph = Graph;
  exports.VertexNotFound = VertexNotFound;
}());
<|endoftext|>


<commit_before>$(function () {
  console.log("directChat script done");

  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=2&pageIndex=1&pageUnit=1&pageSize=10';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {
    directChatAjaxCall(responseData.result);
  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
});

function directChatAjaxCall(jsonData){
  $('#chat-messages').empty(); //패널(div)의 내용 초기화
  var table = "";
  $(jsonData).each(function (chatIndex, chatList){

    table += "
";

    table += "
";
    table += "
" + chatList.writeTime + "
";
    table += "    ";
    table += "      ";
    table += "    ";
    table += "
";
    table += "      ";
    table += "
";
    table += "
";

    table += "
";
    table += "    ";
    table += "
";
    table += "      " + chatList.userId + "";
    table += "
";
    table += "
" + chatList.contentsBody + "
";
    table += "
";
    table += "      " + chatList.hashTags + "";
    table += "
";
    table += "
";
    table += "      <button class='info-box-icon chat-type type-up'>";
    table += "        " + chatList.likeCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-down'>";
    table += "        " + chatList.hateCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "답글";
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "신고";
    table += "      </button>";
    table += "
";

    table += replyChatAjaxCall(chatList);

    table += "
";
    table += "
";

  });
  $('#chat-messages').append(table); //패널에 추가하기
}

function replyChatAjaxCall(chatList){

  console.log("replyChatAjaxCall script done");
  var table = "";
  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=' + chatList.c_id + '&pageIndex=1&pageUnit=1&pageSize=100';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {

    var collection = responseData.result;

    table = "
";
    $(collection).each(function (replyIndex, replyList){

      table += "
";
      table += "
";
      table += "
";
      table += "        ";
      table += "          ";
      table += "        ";
      table += "        " + replyList.userId + "";
      table += "        " + replyList.writeTime + "";
      table += "
";
      table += "
" + replyList.contentsBody + "
";
      table += "
";
      table += "        <button class='info-box-icon chat-type type-up'>" + "좋아요" + replyList.likeCount + "</button>";
      table += "        <button class='info-box-icon chat-type type-reply'>" + "답글 달기" + "</button>";
      table += "
";
      table += "
";
      table += "
";

    });
    table += "
";

  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
  return table;
}

$(function(){

  if (window.localStorage.getItem("chat-simple") != null){
    var messages = window.localStorage.getItem("chat-simple").split(",");
    for (var i = 0; i < messages.length; i++){
      localStorage.removeItem("chat-simple-" + messages[i]);
    }
  }

  var Message = Backbone.Model.extend({

    defaults: function() {
      return {
        text: "empty...",
        order: Messages.nextOrder()
      };
    },

    initialize: function() {
      if (!this.get("text")) {
        this.set({"text": this.defaults().text});
      }
    }

  });

  var MessageList = Backbone.Collection.extend({
    model: Message,
    localStorage: new Backbone.LocalStorage("chat-simple"),
    nextOrder: function() {
      if (!this.length) return 1;
      return this.last().get('order') + 1;
    },
    comparator: function(message) {
      return message.get('order');
    }

  });

  var Messages = new MessageList;

  var MessageView = Backbone.View.extend({

    className: 'chat-message',

    template: _.template($('#message-template').html()),

    initialize: function() {
      this.listenTo(this.model, 'change', this.render);
    },

    // Re-render the titles of the todo item.
    render: function() {
      this.$el.html(this.template(this.model.toJSON()));
      return this;
    }

  });

  var AppView = Backbone.View.extend({

    el: $("#chat"),

    events: {
      "keypress #new-message":  "createOnEnter",
      "click #new-message-btn": "createOnClick"
    },

    initialize: function() {

      this.input = this.$("#new-message");

      this.listenTo(Messages, 'add', this.addOne);
      this.listenTo(Messages, 'all', this.render);

      Messages.fetch();
    },

    addOne: function(message) {
      var view = new MessageView({model: message});

      ////////////////////////////////////////////////////////////////////////////////////////////////////////// ajax
      //ref=10&c_position=0&c_title=test&c_type=default
      var insertChatParamType = 'objectPut';
      var insertChatParam = { ref:10, c_position:0, c_type:'default', c_title: message};
      var insertChatURL = '/api/rivalWar/ROLE_USER/directChat/addNode.do';
      var insertChatType = 'GET';
      var insertChatReturnType = 'json';
      function beforeSendCallback(){ console.log("beforeSendCallback"); }
      function successCallback (insertChatData) {
        console.log(JSON.stringify(insertChatData));
        this.$("#chat-messages").prepend(view.render().el);
      }
      function errorCallback(){ console.log("errorCallback"); }
      function completeCallback(){ console.log("completeCallback"); }
      callAjax(insertChatParamType, insertChatParam, insertChatURL, insertChatType, insertChatReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
      ////////////////////////////////////////////////////////////////////////////////////////////////////////// ajax
    },

    createOnEnter: function(e) {
      if (Messages.length < 10){
        if (e.keyCode != 13) return;
        if (!this.input.val()) return;

        Messages.create({text: this.input.val()});
        this.input.val('');

        var view = this.$("#chat-messages")[0];
        view.scrollTop = view.scrollHeight;
      }
    },

    createOnClick: function(e) {
      if (Messages.length < 10){
        if (!this.input.val()) return;

        Messages.create({text: this.input.val()});
        this.input.val('');

        var view = this.$("#chat-messages")[0];
        view.scrollTop = view.scrollHeight;
      }
    }

  });

  // Finally, we kick things off by creating the **App**.
  var App = new AppView;
});
<commit_msg>[BT] SP-488 #close #time 1h #comment directChat ajaxcall message body 전송. [RV] +review SR @admin<commit_after>$(function () {
  console.log("directChat script done");

  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=2&pageIndex=1&pageUnit=1&pageSize=10';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {
    directChatAjaxCall(responseData.result);
  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
});

function directChatAjaxCall(jsonData){
  $('#chat-messages').empty(); //패널(div)의 내용 초기화
  var table = "";
  $(jsonData).each(function (chatIndex, chatList){

    table += "
";

    table += "
";
    table += "
" + chatList.writeTime + "
";
    table += "    ";
    table += "      ";
    table += "    ";
    table += "
";
    table += "      ";
    table += "
";
    table += "
";

    table += "
";
    table += "    ";
    table += "
";
    table += "      " + chatList.userId + "";
    table += "
";
    table += "
" + chatList.contentsBody + "
";
    table += "
";
    table += "      " + chatList.hashTags + "";
    table += "
";
    table += "
";
    table += "      <button class='info-box-icon chat-type type-up'>";
    table += "        " + chatList.likeCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-down'>";
    table += "        " + chatList.hateCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "답글";
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "신고";
    table += "      </button>";
    table += "
";

    table += replyChatAjaxCall(chatList);

    table += "
";
    table += "
";

  });
  $('#chat-messages').append(table); //패널에 추가하기
}

function replyChatAjaxCall(chatList){

  console.log("replyChatAjaxCall script done");
  var table = "";
  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=' + chatList.c_id + '&pageIndex=1&pageUnit=1&pageSize=100';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {

    var collection = responseData.result;

    table = "
";
    $(collection).each(function (replyIndex, replyList){

      table += "
";
      table += "
";
      table += "
";
      table += "        ";
      table += "          ";
      table += "        ";
      table += "        " + replyList.userId + "";
      table += "        " + replyList.writeTime + "";
      table += "
";
      table += "
" + replyList.contentsBody + "
";
      table += "
";
      table += "        <button class='info-box-icon chat-type type-up'>" + "좋아요" + replyList.likeCount + "</button>";
      table += "        <button class='info-box-icon chat-type type-reply'>" + "답글 달기" + "</button>";
      table += "
";
      table += "
";
      table += "
";

    });
    table += "
";

  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
  return table;
}

$(function(){

  if (window.localStorage.getItem("chat-simple") != null){
    var messages = window.localStorage.getItem("chat-simple").split(",");
    for (var i = 0; i < messages.length; i++){
      localStorage.removeItem("chat-simple-" + messages[i]);
    }
  }

  var Message = Backbone.Model.extend({

    defaults: function() {
      return {
        text: "empty...",
        order: Messages.nextOrder()
      };
    },

    initialize: function() {
      if (!this.get("text")) {
        this.set({"text": this.defaults().text});
      }
    }

  });

  var MessageList = Backbone.Collection.extend({
    model: Message,
    localStorage: new Backbone.LocalStorage("chat-simple"),
    nextOrder: function() {
      if (!this.length) return 1;
      return this.last().get('order') + 1;
    },
    comparator: function(message) {
      return message.get('order');
    }

  });

  var Messages = new MessageList;

  var MessageView = Backbone.View.extend({

    className: 'chat-message',

    template: _.template($('#message-template').html()),

    initialize: function() {
      this.listenTo(this.model, 'change', this.render);
    },

    // Re-render the titles of the todo item.
    render: function() {
      this.$el.html(this.template(this.model.toJSON()));
      return this;
    }

  });

  var AppView = Backbone.View.extend({

    el: $("#chat"),

    events: {
      "keypress #new-message":  "createOnEnter",
      "click #new-message-btn": "createOnClick"
    },

    initialize: function() {

      this.input = this.$("#new-message");

      this.listenTo(Messages, 'add', this.addOne);
      this.listenTo(Messages, 'all', this.render);

      Messages.fetch();
    },

    addOne: function(message) {
      var view = new MessageView({model: message});

      ////////////////////////////////////////////////////////////////////////////////////////////////////////// ajax
      //ref=10&c_position=0&c_title=test&c_type=default
      var insertChatParamType = 'objectPut';
      var insertChatParam = { ref:10, c_position:0, c_type:'default', c_title: message.get('text')};
      var insertChatURL = '/api/rivalWar/ROLE_USER/directChat/addNode.do';
      var insertChatType = 'GET';
      var insertChatReturnType = 'json';
      function beforeSendCallback(){ console.log("beforeSendCallback"); }
      function successCallback (insertChatData) {
        console.log(JSON.stringify(insertChatData));
        this.$("#chat-messages").prepend(view.render().el);
      }
      function errorCallback(){ console.log("errorCallback"); }
      function completeCallback(){ console.log("completeCallback"); }
      callAjax(insertChatParamType, insertChatParam, insertChatURL, insertChatType, insertChatReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
      ////////////////////////////////////////////////////////////////////////////////////////////////////////// ajax
    },

    createOnEnter: function(e) {
      if (Messages.length < 10){
        if (e.keyCode != 13) return;
        if (!this.input.val()) return;

        Messages.create({text: this.input.val()});
        this.input.val('');

        var view = this.$("#chat-messages")[0];
        view.scrollTop = view.scrollHeight;
      }
    },

    createOnClick: function(e) {
      if (Messages.length < 10){
        if (!this.input.val()) return;

        Messages.create({text: this.input.val()});
        this.input.val('');

        var view = this.$("#chat-messages")[0];
        view.scrollTop = view.scrollHeight;
      }
    }

  });

  // Finally, we kick things off by creating the **App**.
  var App = new AppView;
});
<|endoftext|>


<commit_before>/**
 * ConfigController
 *
 * @description :: Server-side logic for managing configs
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

/**
 * Module dependencies
 */

var Q = require('q');
var json2csv = require('json2csv');

var util = require( 'util' ),
  actionUtil = require( '../blueprints/_util/actionUtil' );

/**
 * Enable sideloading. Edit config/blueprints.js and add:
 *   ember: {
 *     sideload: true
 *   }
 * Defaults to false.
 *
 * @type {Boolean}
 */
var performSideload = (sails.config.blueprints.ember && sails.config.blueprints.ember.sideload);

module.exports = {

	configPartialsOptimize: function (req, res) {
  		var Model = actionUtil.parseModel( req );
		var pk = req.query.id;

		var query = Config.findOne( pk ).populate('candidates');
		query.exec( function found( err, matchingRecord ) {
			if ( err ) return res.serverError( err );
			if ( !matchingRecord ) return res.notFound( 'No record found with the specified `id`.' );

			if ( sails.hooks.pubsub && req.isSocket ) {
			  Model.subscribe( req, matchingRecord );
			  actionUtil.subscribeDeep( req, matchingRecord );
			}

			if (matchingRecord) {

				var candidates = [];
   			 	_.each( matchingRecord.candidates, function ( candidate ) {
   			 		candidates.push(candidate.id);
    		 	} );

				var query = 'SELECT c.order, candivote.id, f.id as `force`, c.id as candidate, sum(candivote.votes) as votes, sum(b.totalVotes) as totalVotes, br.id as borough FROM candivote RIGHT JOIN board b ON candivote.board = b.id LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id LEFT JOIN `force` f ON c.force = f.id where candivote.candidate in (' + candidates.join(',') + ') AND c.id > 0 AND candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' GROUP BY c.id, br.id order by CAST(c.order AS SIGNED);';
				var boardsQuery = 'SELECT candivote.id, b.id as board, c.id as candidate, candivote.votes, b.totalVotes, br.id as borough, b.updatedAt FROM candivote RIGHT JOIN board b ON candivote.board = b.id  LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id  WHERE candivote.candidate in (' + candidates.join(',') + ') AND candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isProvisorio > 0 ORDER BY b.updatedAt DESC, CAST(c.order AS SIGNED) LIMIT ' + matchingRecord.candidates.length * 11 + ';';
				var boardsCertificateQuery = 'SELECT candivote.id, b.id as board, c.id as candidate, candivote.votes, b.totalVotes, br.id as borough, b.updatedAt FROM candivote RIGHT JOIN board b ON candivote.board = b.id  LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id  WHERE candivote.candidate in (' + candidates.join(',') + ') AND candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isCertificate > 0 ORDER BY b.updatedAt DESC, CAST(c.order AS SIGNED) LIMIT ' + matchingRecord.candidates.length * 11 + ';';
				if (req.query.isBoards) {
					if (req.query.isCertificate == "true") {
						query = boardsCertificateQuery;
					} else {
						query = boardsQuery;
					}
				}

				Candivote.query(query, function (err, results) {
					//var totalBoardsQuery = 'SELECT count(b.id) FROM candivote RIGHT JOIN board b ON candivote.board = b.id WHERE candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' GROUP BY candivote.board;';
					var totalBoardsQuery = 'SELECT count(b.id) as total FROM board b LEFT JOIN school s on s.id = b.school where s.town = ' + matchingRecord.town + ';';
					var completedBoardsQuery = 'SELECT count(b.id) FROM candivote RIGHT JOIN board b ON candivote.board = b.id WHERE candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isProvisorio > 0 GROUP BY candivote.board;';
					var completedBoardsCertficateQuery = 'SELECT count(b.id) FROM candivote RIGHT JOIN board b ON candivote.board = b.id WHERE candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isCertificate > 0 GROUP BY candivote.board;';

					if (req.query.isCertificate == "true") {
						completedBoardsQuery = completedBoardsCertficateQuery;
					}
					if (!results) {
						results = [];
					}
					//console.log(totalBoards);
					Candivote.query(totalBoardsQuery, function (err, totalBoards) {
						console.log(totalBoards[0].total);
						Candivote.query(completedBoardsQuery, function (err, completedBoards) {
							res.ok({results: results, meta: {completed: completedBoards.length, total: totalBoards[0].total}});
						});
					});
				});
			}
		});
	},

 	exportCSV: function (req, res) {
	  	var pk = req.query.id;
	  	var schools = req.query.schools;
	  	var boards = req.query.boards;
	  	var groupBy = req.query.groupBy;

	  	Config.findOne( pk ).populate('candidates').exec( function found( err, matchingRecord ) {
	  		if (matchingRecord) {

	  			var candidates = [];
	  			 	_.each( matchingRecord.candidates, function ( candidate ) {
	  			 		candidates.push(candidate.id);
	  		 	} );

	  	 		var query = 'SELECT br.name as barrio, s.name as escuela, b.name as mesa, c.lastName as candidato, f.nombre as "fuerza politica", sum(candivote.votes) as votos FROM candivote RIGHT JOIN board b ON candivote.board = b.id LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id LEFT JOIN `force` f ON c.force = f.id  LEFT JOIN school s on b.school = s.id where ';
	  	 		query += 'candivote.candidate in (' + candidates.join(',') + ') AND c.id > 0 AND ';

	  	 		if (schools) {
	  	 			query += 's.id in (' + schools.join(',') + ') AND c.id > 0 AND ';
	  	 		}

	  	 		if (boards) {
	  	 			query += 'b.id in (' + boards.join(',') + ') AND c.id > 0 AND ';
	  	 		}

	  	 		query += 'candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance);
	  	 		query += ' GROUP BY c.id ';

	  	 		if (groupBy === "school") {
	  	 			query += ', s.id ';
	  	 		} else {
					if (groupBy === "borough") {
						query += ', br.id ';
					} else {
						query += ', b.id ';
					}
	  	 		}

	  	 		query += ' order by br.name, CAST(b.name as SIGNED), CAST(c.order AS SIGNED);';

	  			Candivote.query(query, function (err, results) {
	  	 			var config = {
	  	              fields : ['barrio','escuela', 'mesa', 'candidato', 'fuerza politica', 'votos'],
	  	              data: results
	  	            };

	  	            json2csv(config, function(err, csv) {
	  	              if (err) console.log(err);
	  	              var filename = "mesas.csv";
	  	              res.attachment(filename);
	  	              res.end(csv, 'UTF-8');
	  	            });
	  			});
	  		}
	  	});
 	}
};

<commit_msg>offline<commit_after>/**
 * ConfigController
 *
 * @description :: Server-side logic for managing configs
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

/**
 * Module dependencies
 */

var Q = require('q');
var json2csv = require('json2csv');

var util = require( 'util' ),
  actionUtil = require( '../blueprints/_util/actionUtil' );

/**
 * Enable sideloading. Edit config/blueprints.js and add:
 *   ember: {
 *     sideload: true
 *   }
 * Defaults to false.
 *
 * @type {Boolean}
 */
var performSideload = (sails.config.blueprints.ember && sails.config.blueprints.ember.sideload);

module.exports = {

	configPartialsOptimize: function (req, res) {
  		var Model = actionUtil.parseModel( req );
		var pk = req.query.id;

		var query = Config.findOne( pk ).populate('	candidates');
		query.exec( function found( err, matchingRecord ) {
			if ( err ) return res.serverError( err );
			if ( !matchingRecord ) return res.notFound( 'No record found with the specified `id`.' );

			if ( sails.hooks.pubsub && req.isSocket ) {
			  Model.subscribe( req, matchingRecord );
			  actionUtil.subscribeDeep( req, matchingRecord );
			}

			if (matchingRecord) {

				var candidates = [];
   			 	_.each( matchingRecord.candidates, function ( candidate ) {
   			 		candidates.push(candidate.id);
    		 	} );

				var query = 'SELECT c.order, candivote.id, f.id as `force`, c.id as candidate, sum(candivote.votes) as votes, sum(b.totalVotes) as totalVotes, br.id as borough FROM candivote RIGHT JOIN board b ON candivote.board = b.id LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id LEFT JOIN `force` f ON c.force = f.id where candivote.candidate in (' + candidates.join(',') + ') AND c.id > 0 AND candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' GROUP BY c.id, br.id order by CAST(c.order AS SIGNED);';
				var boardsQuery = 'SELECT candivote.id, b.id as board, c.id as candidate, candivote.votes, b.totalVotes, br.id as borough, b.updatedAt FROM candivote RIGHT JOIN board b ON candivote.board = b.id  LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id  WHERE candivote.candidate in (' + candidates.join(',') + ') AND candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isProvisorio > 0 ORDER BY b.updatedAt DESC, CAST(c.order AS SIGNED) LIMIT ' + matchingRecord.candidates.length * 50 + ';';
				var boardsCertificateQuery = 'SELECT candivote.id, b.id as board, c.id as candidate, candivote.votes, b.totalVotes, br.id as borough, b.updatedAt FROM candivote RIGHT JOIN board b ON candivote.board = b.id  LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id  WHERE candivote.candidate in (' + candidates.join(',') + ') AND candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isCertificate > 0 ORDER BY b.updatedAt DESC, CAST(c.order AS SIGNED) LIMIT ' + matchingRecord.candidates.length * 50 + ';';
				if (req.query.isBoards) {
					if (req.query.isCertificate == "true") {
						query = boardsCertificateQuery;
					} else {
						query = boardsQuery;
					}
				}

				Candivote.query(query, function (err, results) {
					//var totalBoardsQuery = 'SELECT count(b.id) FROM candivote RIGHT JOIN board b ON candivote.board = b.id WHERE candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' GROUP BY candivote.board;';
					var totalBoardsQuery = 'SELECT count(b.id) as total FROM board b LEFT JOIN school s on s.id = b.school where s.town = ' + matchingRecord.town + ';';
					var completedBoardsQuery = 'SELECT count(b.id) FROM candivote RIGHT JOIN board b ON candivote.board = b.id WHERE candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isProvisorio > 0 GROUP BY candivote.board;';
					var completedBoardsCertficateQuery = 'SELECT count(b.id) FROM candivote RIGHT JOIN board b ON candivote.board = b.id WHERE candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance) + ' AND b.isCertificate > 0 GROUP BY candivote.board;';

					console.log(err);
					if (req.query.isCertificate == "true") {
						completedBoardsQuery = completedBoardsCertficateQuery;
					}
					if (!results) {
						results = [];
					}
					//console.log(totalBoards);
					Candivote.query(totalBoardsQuery, function (err, totalBoards) {
						Candivote.query(completedBoardsQuery, function (err, completedBoards) {
							res.ok({results: results, meta: {completed: completedBoards.length, total: totalBoards[0].total}});
						});
					});
				});
			}
		});
	},

 	exportCSV: function (req, res) {
	  	var pk = req.query.id;
	  	var schools = req.query.schools;
	  	var boards = req.query.boards;
	  	var groupBy = req.query.groupBy;

	  	Config.findOne( pk ).populate('candidates').exec( function found( err, matchingRecord ) {
	  		if (matchingRecord) {

	  			var candidates = [];
	  			 	_.each( matchingRecord.candidates, function ( candidate ) {
	  			 		candidates.push(candidate.id);
	  		 	} );

	  	 		var query = 'SELECT br.name as barrio, s.name as escuela, b.name as mesa, c.lastName as candidato, f.nombre as "fuerza politica", sum(candivote.votes) as votos FROM candivote RIGHT JOIN board b ON candivote.board = b.id LEFT JOIN borough br ON candivote.borough = br.id LEFT JOIN candidate c ON candivote.candidate = c.id LEFT JOIN `force` f ON c.force = f.id  LEFT JOIN school s on b.school = s.id where ';
	  	 		query += 'candivote.candidate in (' + candidates.join(',') + ') AND c.id > 0 AND ';

	  	 		if (schools) {
	  	 			query += 's.id in (' + schools.join(',') + ') AND c.id > 0 AND ';
	  	 		}

	  	 		if (boards) {
	  	 			query += 'b.id in (' + boards.join(',') + ') AND c.id > 0 AND ';
	  	 		}

	  	 		query += 'candivote.config = ' + parseInt(req.query.id) + ' AND candivote.instance = ' + parseInt(req.query.instance);
	  	 		query += ' GROUP BY c.id ';

	  	 		if (groupBy === "school") {
	  	 			query += ', s.id ';
	  	 		} else {
					if (groupBy === "borough") {
						query += ', br.id ';
					} else {
						query += ', b.id ';
					}
	  	 		}

	  	 		query += ' order by br.name, CAST(b.name as SIGNED), CAST(c.order AS SIGNED);';

	  			Candivote.query(query, function (err, results) {
	  	 			var config = {
	  	              fields : ['barrio','escuela', 'mesa', 'candidato', 'fuerza politica', 'votos'],
	  	              data: results
	  	            };

	  	            json2csv(config, function(err, csv) {
	  	              if (err) console.log(err);
	  	              var filename = "mesas.csv";
	  	              res.attachment(filename);
	  	              res.end(csv, 'UTF-8');
	  	            });
	  			});
	  		}
	  	});
 	}
};

<|endoftext|>


<commit_before>var config       = require('../config')
if(!config.tasks.html) return

var browserSync  = require('browser-sync')
var data         = require('gulp-data')
var gulp         = require('gulp')
var gulpif       = require('gulp-if')
var handleErrors = require('../lib/handleErrors')
var htmlmin      = require('gulp-htmlmin')
var path         = require('path')
var render       = require('gulp-nunjucks-render')
var fs           = require('fs')

var exclude = path.normalize('!**/{' + config.tasks.html.excludeFolders.join(',') + '}/**')

var paths = {
  src: [path.join(config.root.src, config.tasks.html.src, '/**/*.{' + config.tasks.html.extensions + '}'), exclude],
  dest: path.join(config.root.dest, config.tasks.html.dest),
}

var getData = function(file) {
  var dataPath = path.resolve(config.root.src, config.tasks.html.src, config.tasks.html.dataFile)
  return JSON.parse(fs.readFileSync(dataPath, 'utf8'))
}

var htmlTask = function() {

  return gulp.src(paths.src)
    .pipe(data(getData))
    .on('error', handleErrors)
    .pipe(render({
      path: [path.join(config.root.src, config.tasks.html.src)],
      envOptions: {
        watch: false
      }
    }))
    .on('error', handleErrors)
    .pipe(gulpif(global.production, htmlmin(config.tasks.html.htmlmin)))
    .pipe(gulp.dest(paths.dest))
    .on('end', browserSync.reload)

}

gulp.task('html', htmlTask)
module.exports = htmlTask
<commit_msg>update html task to use pug<commit_after>var config       = require('../config')
if(!config.tasks.html) return

var browserSync  = require('browser-sync')
var data         = require('gulp-data')
var gulp         = require('gulp')
var gulpif       = require('gulp-if')
var handleErrors = require('../lib/handleErrors')
var htmlmin      = require('gulp-htmlmin')
var path         = require('path')
var render       = require('gulp-pug')
var fs           = require('fs')

var exclude = path.normalize('!**/{' + config.tasks.html.excludeFolders.join(',') + '}/**')

var paths = {
  src: [path.join(config.root.src, config.tasks.html.src, '/**/*.{' + config.tasks.html.extensions + '}'), exclude],
  dest: path.join(config.root.dest, config.tasks.html.dest),
}

var getData = function(file) {
  var dataPath = path.resolve(config.root.src, config.tasks.html.src, config.tasks.html.dataFile)
  return JSON.parse(fs.readFileSync(dataPath, 'utf8'))
}

var htmlTask = function() {

  return gulp.src(paths.src)
    .pipe(data(getData))
    .on('error', handleErrors)
    .pipe(render({
      path: [path.join(config.root.src, config.tasks.html.src)],
      envOptions: {
        watch: false
      }
    }))
    .on('error', handleErrors)
    .pipe(gulpif(global.production, htmlmin(config.tasks.html.htmlmin)))
    .pipe(gulp.dest(paths.dest))
    .on('end', browserSync.reload)

}

gulp.task('html', htmlTask)
module.exports = htmlTask
<|endoftext|>


<commit_before>
window.onload = function() {
    function line(ids) {
        first = "|" + ids.map(id => " ![](https://github.com/" + id + ".png?size=117) |").join("")
        second = "|" + ids.map(id => " --- |").join("")
        third = "|" + ids.map(id => "[" + id + "](https://github.com/" + id + ") |").join("")

        return first + "\n" + second + "\n" + third
    }

    function table(input) {
        ids = input.split(",").map(id =>
            id.trim()
        )

        size = 6
        lines = ids.map((e, i) =>
            i % size === 0 ? ids.slice(i, i + size) : null
        ).filter(e => e)

        return lines.map(line).join("\n\n")
    }

    function copyToClipboard(textArea) {
        textArea.select()

        try {
            var successful = document.execCommand('copy')
            var message = successful ? 'copied successfully!' : 'couldn\'t be copied :('
            console.log("Code " + message)
        } catch (err) {
            console.log('Oops, unable to copy');
        }
    }

    new Vue({
        el: '#ids',
        data: {
            input: 'fpg1503, CocoaHeadsBrasil'
        },
        computed: {
            markdown: function() {
                return table(this.input)
            },
            compiledMarkdown: function() {
                tabled = table(this.input)
                return marked(tabled, {
                    sanitize: true
                })
            }
        },
        methods: {
            update: _.debounce(function(e) {
                this.input = e.target.value
            }, 300),
            copy: function(e) {
                copyToClipboard(document.querySelector('#markdown'))
            }
        }
    })

}
<commit_msg>Add missing var decalrations<commit_after>
window.onload = function() {
    function line(ids) {
        var first = "|" + ids.map(id => " ![](https://github.com/" + id + ".png?size=117) |").join("")
        var second = "|" + ids.map(id => " --- |").join("")
        var third = "|" + ids.map(id => "[" + id + "](https://github.com/" + id + ") |").join("")

        return first + "\n" + second + "\n" + third
    }

    function table(input) {
        var ids = input.split(",").map(id =>
            id.trim()
        )

        var size = 6
        var lines = ids.map((e, i) =>
            i % size === 0 ? ids.slice(i, i + size) : null
        ).filter(e => e)

        return lines.map(line).join("\n\n")
    }

    function copyToClipboard(textArea) {
        textArea.select()

        try {
            var successful = document.execCommand('copy')
            var message = successful ? 'copied successfully!' : 'couldn\'t be copied :('
            console.log("Code " + message)
        } catch (err) {
            console.log('Oops, unable to copy');
        }
    }

    new Vue({
        el: '#ids',
        data: {
            input: 'fpg1503, CocoaHeadsBrasil'
        },
        computed: {
            markdown: function() {
                return table(this.input)
            },
            compiledMarkdown: function() {
                tabled = table(this.input)
                return marked(tabled, {
                    sanitize: true
                })
            }
        },
        methods: {
            update: _.debounce(function(e) {
                this.input = e.target.value
            }, 300),
            copy: function(e) {
                copyToClipboard(document.querySelector('#markdown'))
            }
        }
    })

}
<|endoftext|>


<commit_before>//
// this is just a stub for a function you need to implement
//
function getStats(txt) {
    return {
        nChars: nCharsFunc(txt),
        nWords: nWordsFunc(txt),
        nLines: nLinesFunc(txt),
        nNonEmptyLines:  nNonEmptyLinesFuncFunc(txt),
        averageWordLength: averageWordLengthFunc(txt),
        maxLineLength: maxLineLengthFunc(txt),
        palindromes: palindromesFunc(txt),
        longestWords: longestWordsFunc(txt),
        mostFrequentWords: mostFrequentWordsFunc(txt)
    };
}

function nCharsFunc(txt)
{
	return txt.length;
}

function nWordsFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);
	//An array containing each word, a word being an uninterrupted alphanumeric string

	return wordArray.length;
}

function nLinesFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var lineArray = currentString.split(/\n/g||[]);
	return lineArray.length;
}

function nNonEmptyLinesFuncFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var lineArray = currentString.split(/\n/g||[]);

	var nonEmptyLines = 0;

	for (i = 0; i < lineArray.length; i++)
	{//For each line in the array
		var trimmedLine = lineArray[i].trim();	//Remove whitespace

		if (trimmedLine.length != 0)
		{
			nonEmptyLines++;
		}
	}

	return nonEmptyLines;
}

function averageWordLengthFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);

	var letterCount = 0;

	for (i = 0; i < wordArray.length; i++)
	{//For each word in the array, add up the number of letters
		letterCount += wordArray[i].length;
	}

	return letterCount / wordArray.length;
}

function maxLineLengthFunc(txt)
{
	return 33;
}

function palindromesFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);
	var palindromeArray = [];

	for (i = 0; i < wordArray.length; i++)
	{
		var word = wordArray[i];
		var reverseWord = "";

		if (wordArray[i].length < 3)
		{//If the word is too short, skip over it
			continue;
		}

		for (j = wordArray[i].length - 1; j >= 0;j--)
        {//Reverse the letters of the word
			//I'm using wordArray here instead of word because word makes it freeze
			//I'm not sure why
            reverseWord += wordArray[i].charAt(j);
        }

		if (word == reverseWord)
		{
			var uniqueWord = true;
			for (j = 0; j < palindromeArray.length; j++)
			{
				if (palindromeArray[j] == word)
				{//If this word is already in the list
					uniqueWord = false;
				}
			}

			if (uniqueWord)
			{
				palindromeArray.push(word);
			}
		}
	}

	return palindromeArray;
}

function longestWordsFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);

	var longestWord = 0;

	for (i = 0; i < wordArray.length; i++)
	{//For each word in the array, check if it is longer than current longest
		if (wordArray[i].length > longestWord)
		{
			longestWord = wordArray[i].length;
		}
	}

	var longestWordsArray = [];
	var currentWordLength = longestWord;

	while (longestWordsArray.length < 10 && currentWordLength > 0)
	{//While our array of words is still less than 10 words
		//Escape clause if we don't actually have enough words
		var nextArray = [];

		for (i = 0; i < wordArray.length; i++)
		{//Go back through word array and collect all words equal to longest word
			if (wordArray[i].length == currentWordLength)
			{
				var uniqueWord = true;
				for (j = 0; j < nextArray.length; j++)
				{
					if (nextArray[j] == wordArray[i])
					{//If this word is already in the list
						uniqueWord = false;
					}
				}

				if (uniqueWord)
				{
					nextArray.push(wordArray[i]);
				}
			}
		}

		nextArray.sort();	//Sort the elements of the array alphabetically

		var i = 0;
		while (longestWordsArray.length < 10 && i < nextArray.length)
		{//While the array of longest words is still less than 10
			//and we still have words left in the current array of long words
			longestWordsArray.push(nextArray[i]);
			i++;
		}

		currentWordLength--;
	}

	return longestWordsArray;
}

function mostFrequentWordsFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);
	wordArray.sort();	//Sort array of words alphabetically

	var foundWordsArray = [];
	var countArray = [];

	if (wordArray.length == 0)
	{//If no words, return empty array
		return foundWordsArray;
	}

	foundWordsArray.push(wordArray[0]);
	countArray.push(1);

	var sortedIndex = 0;
	for (i = 1; i < wordArray.length; i++)
	{//For each word in the array
		if (wordArray[i] == foundWordsArray[sortedIndex])
		{//If we have more of the same word
			countArray[sortedIndex]++;
		}
		else
		{//Otherwise
			foundWordsArray.push(wordArray[i]);
			countArray.push(1);
			sortedIndex++;
		}
	}

	var returnArray = []
	for (i = 0; i < sortedIndex; i++)
	{
		returnArray.push(foundWordsArray[i] + "(" + countArray[i] + ")");
	}

	return returnArray;
	/*
	var dummyArray = ["hello(7)", "world(1)"];
	return dummyArray;*/
}<commit_msg>dummy value<commit_after>//
// this is just a stub for a function you need to implement
//
function getStats(txt) {
    return {
        nChars: nCharsFunc(txt),
        nWords: nWordsFunc(txt),
        nLines: nLinesFunc(txt),
        nNonEmptyLines:  nNonEmptyLinesFuncFunc(txt),
        averageWordLength: averageWordLengthFunc(txt),
        maxLineLength: maxLineLengthFunc(txt),
        palindromes: palindromesFunc(txt),
        longestWords: longestWordsFunc(txt),
        mostFrequentWords: mostFrequentWordsFunc(txt)
    };
}

function nCharsFunc(txt)
{
	return txt.length;
}

function nWordsFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);
	//An array containing each word, a word being an uninterrupted alphanumeric string

	return wordArray.length;
}

function nLinesFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var lineArray = currentString.split(/\n/g||[]);
	return lineArray.length;
}

function nNonEmptyLinesFuncFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var lineArray = currentString.split(/\n/g||[]);

	var nonEmptyLines = 0;

	for (i = 0; i < lineArray.length; i++)
	{//For each line in the array
		var trimmedLine = lineArray[i].trim();	//Remove whitespace

		if (trimmedLine.length != 0)
		{
			nonEmptyLines++;
		}
	}

	return nonEmptyLines;
}

function averageWordLengthFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);

	var letterCount = 0;

	for (i = 0; i < wordArray.length; i++)
	{//For each word in the array, add up the number of letters
		letterCount += wordArray[i].length;
	}

	return letterCount / wordArray.length;
}

function maxLineLengthFunc(txt)
{
	return 33;
}

function palindromesFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);
	var palindromeArray = [];

	for (i = 0; i < wordArray.length; i++)
	{
		var word = wordArray[i];
		var reverseWord = "";

		if (wordArray[i].length < 3)
		{//If the word is too short, skip over it
			continue;
		}

		for (j = wordArray[i].length - 1; j >= 0;j--)
        {//Reverse the letters of the word
			//I'm using wordArray here instead of word because word makes it freeze
			//I'm not sure why
            reverseWord += wordArray[i].charAt(j);
        }

		if (word == reverseWord)
		{
			var uniqueWord = true;
			for (j = 0; j < palindromeArray.length; j++)
			{
				if (palindromeArray[j] == word)
				{//If this word is already in the list
					uniqueWord = false;
				}
			}

			if (uniqueWord)
			{
				palindromeArray.push(word);
			}
		}
	}

	return palindromeArray;
}

function longestWordsFunc(txt)
{
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);

	var longestWord = 0;

	for (i = 0; i < wordArray.length; i++)
	{//For each word in the array, check if it is longer than current longest
		if (wordArray[i].length > longestWord)
		{
			longestWord = wordArray[i].length;
		}
	}

	var longestWordsArray = [];
	var currentWordLength = longestWord;

	while (longestWordsArray.length < 10 && currentWordLength > 0)
	{//While our array of words is still less than 10 words
		//Escape clause if we don't actually have enough words
		var nextArray = [];

		for (i = 0; i < wordArray.length; i++)
		{//Go back through word array and collect all words equal to longest word
			if (wordArray[i].length == currentWordLength)
			{
				var uniqueWord = true;
				for (j = 0; j < nextArray.length; j++)
				{
					if (nextArray[j] == wordArray[i])
					{//If this word is already in the list
						uniqueWord = false;
					}
				}

				if (uniqueWord)
				{
					nextArray.push(wordArray[i]);
				}
			}
		}

		nextArray.sort();	//Sort the elements of the array alphabetically

		var i = 0;
		while (longestWordsArray.length < 10 && i < nextArray.length)
		{//While the array of longest words is still less than 10
			//and we still have words left in the current array of long words
			longestWordsArray.push(nextArray[i]);
			i++;
		}

		currentWordLength--;
	}

	return longestWordsArray;
}

function mostFrequentWordsFunc(txt)
{/*
	var currentString = txt;
	currentString = currentString.toLowerCase();
	var wordArray = currentString.match(/[a-z0-9]+/g);
	wordArray.sort();	//Sort array of words alphabetically

	var foundWordsArray = [];
	var countArray = [];

	if (wordArray.length == 0)
	{//If no words, return empty array
		return foundWordsArray;
	}

	foundWordsArray.push(wordArray[0]);
	countArray.push(1);

	var sortedIndex = 0;
	for (i = 1; i < wordArray.length; i++)
	{//For each word in the array
		if (wordArray[i] == foundWordsArray[sortedIndex])
		{//If we have more of the same word
			countArray[sortedIndex]++;
		}
		else
		{//Otherwise
			foundWordsArray.push(wordArray[i]);
			countArray.push(1);
			sortedIndex++;
		}
	}

	var returnArray = []
	for (i = 0; i < sortedIndex; i++)
	{
		returnArray.push(foundWordsArray[i] + "(" + countArray[i] + ")");
	}

	return returnArray;
	*/
	var dummyArray = ["hello(7)", "world(1)"];
	return dummyArray;
}<|endoftext|>


<commit_before>/**
 * Bridge proxy
 *
 */

var events = require('events');

/**
 * config options:{
 * 		port:int //only processes with root permissions can listen on privileged ports, ie: sudo node bridgeproxy.js
 * }
 */
function WSBridgeProxy(config, callback){

	// Simple websocket server
	var me=this;
	events.EventEmitter.call(me);

	var freeServerConnections=[];
	var freeClientConnections=[];

	if(config.server){

		me.server=(new (require('ws').Server)({
			server: config.server
		},function(){

			console.log('bridgeproxy websocket listening on: '+config.port);

			if((typeof callback)=='function'){
				callback();
			}
		}));

		if(config.server&&config.port){
			config.server.listen(config.port, callback);
		}

	}else if(config.port){

		me.server=(new (require('ws').Server)({
			port: config.port
		},function(){

			console.log('bridgeproxy websocket listening on: '+config.port);

			if((typeof callback)=='function'){
				callback();
			}
		}));

	}else{
		throw new Error('Expected server or port, in config');
	}

	me.server.on('connection', function(wsclient){

		if(me._isSocketAttemptingAuth(wsclient)){

			if(me._authorizeSocketAsServerConnection(wsclient, config.basicauth)){
				freeServerConnections.push(wsclient)
				me.emit('server.connect', wsclient);

				var handleServerEarlyDisconnect=function(){
					var i=freeServerConnections.indexOf(wsclient)
					if(i>=0){
						freeServerConnections.splice(i,1);
						console.log('server closed early');
						me.emit('server.close');
					}
				};

				wsclient.on('close', handleServerEarlyDisconnect).on('error', handleServerEarlyDisconnect);

			}else{
				console.log('drop server connection, failed basicauth');
				wsclient.close(3000, 'bridge basic auth attempt invalid');
				return;
			}
		}else{

			freeClientConnections.push(wsclient);
			me.emit('client.connect', wsclient);
			me._bufferSocket(wsclient);

			var handleClientEarlyDisconnect=function(){
				var i=freeClientConnections.indexOf(wsclient)
				if(i>=0){
					freeClientConnections.splice(i,1);
					console.log('client closed early');
					me.emit('client.close');
				}

			};

			wsclient.on('close', handleClientEarlyDisconnect).on('error', handleClientEarlyDisconnect);

		}

		while(freeServerConnections.length&&freeClientConnections.length){

			var server=freeServerConnections.shift();
			var client=freeClientConnections.shift();
			me._connectSockets(server, client);

		}

	}).on('close',function(){

		console.log('bridge server closed');

	}).on('error',function(err){
		throw err;
	});

};

WSBridgeProxy.prototype.__proto__ = events.EventEmitter.prototype;

WSBridgeProxy.prototype._verbose=function(){

}

WSBridgeProxy.prototype._bufferSocket=function(wsclient){
	var me=this;
	if(!me._flushBuffers){

		me._bufferedClients=[];
		me._buffers=[];
		me._handlers=[];

		me._flushBuffers=function(server, client){
			var i=me._bufferedClients.indexOf(client);
			if(me._buffers[i].length){

				me.emit('buffer.flush', wsclient, buffer);

				me._buffers[i].forEach(function(message){
					//client.emit('message', message);
					try{
						console.log('send to server buffered: '+message);
						server.send(message);
					}catch(e){
						console.log('client flush buffer error: '+e.message);
					}
				});

				me.emit('buffer.close', wsclient);
			}

			me._bufferedClients.splice(i,1);
			me._buffers.splice(i,1);
			client.removeListener('message', me._handlers[i]);
			me._handlers.splice(i,1);
		}

		me.on('pair', me._flushBuffers);
	}

	me._bufferedClients.push(wsclient);
	var buffer=[];
	me._buffers.push(buffer);
	var handler=function message(data, flags) {

		if(buffer.length==0){
			me.emit('buffer.create', wsclient);
		}

		buffer.push(data);
		me.emit('buffer', wsclient, data);
	}
	me._handlers.push(handler);
	wsclient.on('message', handler);

};

WSBridgeProxy.prototype._isSocketAttemptingAuth=function(wsclient){
	return (typeof wsclient.upgradeReq.headers.authorization)!='undefined'
};

WSBridgeProxy.prototype._authorizeSocketAsServerConnection=function(wsclient, basicauth){
	var atob=require('atob');
	var b64auth=wsclient.upgradeReq.headers.authorization.split(' ')[1];
	var auth=atob(b64auth);
	if(auth===basicauth){
		return true;
	}else{
		console.log('bridge basic auth attempt invalid: '+b64auth+' = ' +auth+' | '+basicauth)
		return false;
	}
};

WSBridgeProxy.prototype._connectSockets=function(wsserver, wsclient){

	var me=this;
	var server=wsserver;
	var client=wsclient;

	var cleanup=function(){
		if(client&&server){
			me.emit('unpair', server, client);
		}
		if(client){
			client=null;
			wsclient.close();

		}
		if(server){
			server=null;
			wsserver.close();
		}

	}

	server.on('message', function(){
		try{
			client.send.call(arguments);
		}catch(e){
			console.log('send to client error: '+e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);
	client.on('message', function(){
		try{
			server.send.call(arguments);
		}catch(e){
			console.log('send to server error: '+e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);

	me.emit('pair', server, client);

}

WSBridgeProxy.prototype.close=function(){

	var me=this;
	me.server.close();

}

module.exports=WSBridgeProxy;

/**
 * can be run directly from the command line. ie: sudo node bridgeproxy.js port username:password
 */

if(process.argv){
	if(!process.argc){
		process.argc=process.argv.length;
	}

	var fs=require('fs');
	fs.realpath(process.argv[1],function(err, p1){

		fs.realpath(__filename,function(err, p2){

			//console.log(p1+' '+p2);

			if(p1===p2){

				console.log(process.argv);

				if(process.argc>=3){
					var opt={port:parseInt(process.argv[2])};
					if(process.argc>3){
						opt.basicauth=process.argv[3];
					}
					new WSBridgeProxy(opt);
				}else{
					new WSBridgeProxy(require('./bridgeproxy.json'));
				}

			}

		});
	});
}

<commit_msg>fix .call(thisArg<commit_after>/**
 * Bridge proxy
 *
 */

var events = require('events');

/**
 * config options:{
 * 		port:int //only processes with root permissions can listen on privileged ports, ie: sudo node bridgeproxy.js
 * }
 */
function WSBridgeProxy(config, callback){

	// Simple websocket server
	var me=this;
	events.EventEmitter.call(me);

	var freeServerConnections=[];
	var freeClientConnections=[];

	if(config.server){

		me.server=(new (require('ws').Server)({
			server: config.server
		},function(){

			console.log('bridgeproxy websocket listening on: '+config.port);

			if((typeof callback)=='function'){
				callback();
			}
		}));

		if(config.server&&config.port){
			config.server.listen(config.port, callback);
		}

	}else if(config.port){

		me.server=(new (require('ws').Server)({
			port: config.port
		},function(){

			console.log('bridgeproxy websocket listening on: '+config.port);

			if((typeof callback)=='function'){
				callback();
			}
		}));

	}else{
		throw new Error('Expected server or port, in config');
	}

	me.server.on('connection', function(wsclient){

		if(me._isSocketAttemptingAuth(wsclient)){

			if(me._authorizeSocketAsServerConnection(wsclient, config.basicauth)){
				freeServerConnections.push(wsclient)
				me.emit('server.connect', wsclient);

				var handleServerEarlyDisconnect=function(){
					var i=freeServerConnections.indexOf(wsclient)
					if(i>=0){
						freeServerConnections.splice(i,1);
						console.log('server closed early');
						me.emit('server.close');
					}
				};

				wsclient.on('close', handleServerEarlyDisconnect).on('error', handleServerEarlyDisconnect);

			}else{
				console.log('drop server connection, failed basicauth');
				wsclient.close(3000, 'bridge basic auth attempt invalid');
				return;
			}
		}else{

			freeClientConnections.push(wsclient);
			me.emit('client.connect', wsclient);
			me._bufferSocket(wsclient);

			var handleClientEarlyDisconnect=function(){
				var i=freeClientConnections.indexOf(wsclient)
				if(i>=0){
					freeClientConnections.splice(i,1);
					console.log('client closed early');
					me.emit('client.close');
				}

			};

			wsclient.on('close', handleClientEarlyDisconnect).on('error', handleClientEarlyDisconnect);

		}

		while(freeServerConnections.length&&freeClientConnections.length){

			var server=freeServerConnections.shift();
			var client=freeClientConnections.shift();
			me._connectSockets(server, client);

		}

	}).on('close',function(){

		console.log('bridge server closed');

	}).on('error',function(err){
		throw err;
	});

};

WSBridgeProxy.prototype.__proto__ = events.EventEmitter.prototype;

WSBridgeProxy.prototype._verbose=function(){

}

WSBridgeProxy.prototype._bufferSocket=function(wsclient){
	var me=this;
	if(!me._flushBuffers){

		me._bufferedClients=[];
		me._buffers=[];
		me._handlers=[];

		me._flushBuffers=function(server, client){
			var i=me._bufferedClients.indexOf(client);
			if(me._buffers[i].length){

				me.emit('buffer.flush', wsclient, buffer);

				me._buffers[i].forEach(function(message){
					//client.emit('message', message);
					try{
						console.log('send to server buffered: '+message);
						server.send(message);
					}catch(e){
						console.log('client flush buffer error: '+e.message);
					}
				});

				me.emit('buffer.close', wsclient);
			}

			me._bufferedClients.splice(i,1);
			me._buffers.splice(i,1);
			client.removeListener('message', me._handlers[i]);
			me._handlers.splice(i,1);
		}

		me.on('pair', me._flushBuffers);
	}

	me._bufferedClients.push(wsclient);
	var buffer=[];
	me._buffers.push(buffer);
	var handler=function message(data, flags) {

		if(buffer.length==0){
			me.emit('buffer.create', wsclient);
		}

		buffer.push(data);
		me.emit('buffer', wsclient, data);
	}
	me._handlers.push(handler);
	wsclient.on('message', handler);

};

WSBridgeProxy.prototype._isSocketAttemptingAuth=function(wsclient){
	return (typeof wsclient.upgradeReq.headers.authorization)!='undefined'
};

WSBridgeProxy.prototype._authorizeSocketAsServerConnection=function(wsclient, basicauth){
	var atob=require('atob');
	var b64auth=wsclient.upgradeReq.headers.authorization.split(' ')[1];
	var auth=atob(b64auth);
	if(auth===basicauth){
		return true;
	}else{
		console.log('bridge basic auth attempt invalid: '+b64auth+' = ' +auth+' | '+basicauth)
		return false;
	}
};

WSBridgeProxy.prototype._connectSockets=function(wsserver, wsclient){

	var me=this;
	var server=wsserver;
	var client=wsclient;

	var cleanup=function(){
		if(client&&server){
			me.emit('unpair', server, client);
		}
		if(client){
			client=null;
			wsclient.close();

		}
		if(server){
			server=null;
			wsserver.close();
		}

	}

	server.on('message', function(){
		try{
			client.send.call(client, arguments);
		}catch(e){
			console.log('send to client error: '+e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);
	client.on('message', function(){
		try{
			server.send.call(server, arguments);
		}catch(e){
			console.log('send to server error: '+e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);

	me.emit('pair', server, client);

}

WSBridgeProxy.prototype.close=function(){

	var me=this;
	me.server.close();

}

module.exports=WSBridgeProxy;

/**
 * can be run directly from the command line. ie: sudo node bridgeproxy.js port username:password
 */

if(process.argv){
	if(!process.argc){
		process.argc=process.argv.length;
	}

	var fs=require('fs');
	fs.realpath(process.argv[1],function(err, p1){

		fs.realpath(__filename,function(err, p2){

			//console.log(p1+' '+p2);

			if(p1===p2){

				console.log(process.argv);

				if(process.argc>=3){
					var opt={port:parseInt(process.argv[2])};
					if(process.argc>3){
						opt.basicauth=process.argv[3];
					}
					new WSBridgeProxy(opt);
				}else{
					new WSBridgeProxy(require('./bridgeproxy.json'));
				}

			}

		});
	});
}

<|endoftext|>


<commit_before>define(["js/data/RestDataSource", "js/data/Model", "js/data/Collection", "underscore"], function (RestDataSource, Model, Collection, _) {

    var SprdDataSource = RestDataSource.inherit('sprd.data.SprdDataSource', {
        defaults: {
            apiKey: null,
            secret: null,
            session: null
        },

        _getConfigurationForResource: function (resource) {

            var parentContext = resource.$context;
            var configuration = this.$dataSourceConfiguration;

            if (parentContext && parentContext.$contextModel) {
                configuration = configuration.getConfigurationForModelClass(parentContext.$contextModel.factory);
            }

            if (resource instanceof Model) {
                return configuration.getConfigurationForModelClass(resource.factory);
            } else if (resource instanceof Collection) {
                return configuration.getConfigurationForModelClass(resource.$modelFactory);
            }

            return null;
        },

        getQueryParameters: function (method, resource) {
            var obj = {};

            if (this.$.locale) {
                obj.locale = this.$.locale;
            }

            var params = _.defaults(obj, this.callBase());

            var configuration,
                apiKey = this.$.apiKey,
                needsSignature;

            // get the configuration only if needed
            configuration = this._getConfigurationForResource(resource);

            if (!configuration) {
                throw new Error("Configuration for resource not found");
            }

            var signatureRequired = configuration.$.signatureRequired,
                apiKeyRequired = configuration.$.apiKeyRequired,
                sessionRequired = configuration.$.sessionRequired;

            needsSignature = signatureRequired || sessionRequired;

            if (this.$.session && sessionRequired) {
                params = _.defaults({
                    // TODO: change session id to token for translation service
                    sessionId: this.$.session.$.id
                });
            }

            if (needsSignature) {
                var secret = this.$.secret;
                var time = Date.now();
                var url = this._buildUriForResource(resource, this.$.endPoint);

                var data = method + " " + url + " " + time + " " + secret;

                params = _.defaults({
                    sig: SprdDataSource.SHA1(data),
                    time: time,
                    apiKey: apiKey
                });
            }

            if (apiKeyRequired || signatureRequired || sessionRequired) {
                params = _.defaults(params, {
                    apiKey: apiKey
                });
            }

            return params;
        }
    });

    SprdDataSource.SHA1 = function (msg) {

        function rotateLeft(n, s) {
            return ( n << s ) | (n >>> (32 - s));
        }

        function cvtHex(val) {
            var str = "";
            var i;
            var v;

            for (i = 7; i >= 0; i--) {
                v = (val >>> (i * 4)) & 0x0f;
                str += v.toString(16);
            }
            return str;
        }

        function utf8Encode(string) {
            string = string.replace(/\r\n/g, "\n");
            var utfText = "";

            for (var n = 0; n < string.length; n++) {

                var c = string.charCodeAt(n);

                if (c < 128) {
                    utfText += String.fromCharCode(c);
                }
                else if ((c > 127) && (c < 2048)) {
                    utfText += String.fromCharCode((c >> 6) | 192);
                    utfText += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utfText += String.fromCharCode((c >> 12) | 224);
                    utfText += String.fromCharCode(((c >> 6) & 63) | 128);
                    utfText += String.fromCharCode((c & 63) | 128);
                }

            }

            return utfText;
        }

        var blockStart;
        var i, j;
        var W = new Array(80);
        var H0 = 0x67452301;
        var H1 = 0xEFCDAB89;
        var H2 = 0x98BADCFE;
        var H3 = 0x10325476;
        var H4 = 0xC3D2E1F0;
        var A, B, C, D, E;
        var temp;

        msg = utf8Encode(msg);

        var msg_len = msg.length;

        var word_array = [];
        for (i = 0; i < msg_len - 3; i += 4) {
            j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
                msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
            word_array.push(j);
        }

        switch (msg_len % 4) {
            case 0:
                i = 0x080000000;
                break;
            case 1:
                i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
                break;

            case 2:
                i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
                break;

            case 3:
                i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
                break;
        }

        word_array.push(i);

        while ((word_array.length % 16) != 14) {
            word_array.push(0);
        }

        word_array.push(msg_len >>> 29);
        word_array.push((msg_len << 3) & 0x0ffffffff);

        for (blockStart = 0; blockStart < word_array.length; blockStart += 16) {

            for (i = 0; i < 16; i++) {
                W[i] = word_array[blockStart + i];
            }

            for (i = 16; i <= 79; i++) {
                W[i] = rotateLeft(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
            }

            A = H0;
            B = H1;
            C = H2;
            D = H3;
            E = H4;

            for (i = 0; i <= 19; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 20; i <= 39; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 40; i <= 59; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 60; i <= 79; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            H0 = (H0 + A) & 0x0ffffffff;
            H1 = (H1 + B) & 0x0ffffffff;
            H2 = (H2 + C) & 0x0ffffffff;
            H3 = (H3 + D) & 0x0ffffffff;
            H4 = (H4 + E) & 0x0ffffffff;

        }

        temp = cvtHex(H0) + cvtHex(H1) + cvtHex(H2) + cvtHex(H3) + cvtHex(H4);
        return temp.toLowerCase();
    };

    return SprdDataSource;
});<commit_msg>fixed params extending in getQueryParameters<commit_after>define(["js/data/RestDataSource", "js/data/Model", "js/data/Collection", "underscore"], function (RestDataSource, Model, Collection, _) {

    var SprdDataSource = RestDataSource.inherit('sprd.data.SprdDataSource', {
        defaults: {
            apiKey: null,
            secret: null,
            session: null
        },

        _getConfigurationForResource: function (resource) {

            var parentContext = resource.$context;
            var configuration = this.$dataSourceConfiguration;

            if (parentContext && parentContext.$contextModel) {
                configuration = configuration.getConfigurationForModelClass(parentContext.$contextModel.factory);
            }

            if (resource instanceof Model) {
                return configuration.getConfigurationForModelClass(resource.factory);
            } else if (resource instanceof Collection) {
                return configuration.getConfigurationForModelClass(resource.$modelFactory);
            }

            return null;
        },

        getQueryParameters: function (method, resource) {
            var obj = {};

            if (this.$.locale) {
                obj.locale = this.$.locale;
            }

            var params = _.defaults(obj, this.callBase());

            var configuration,
                apiKey = this.$.apiKey,
                needsSignature;

            // get the configuration only if needed
            configuration = this._getConfigurationForResource(resource);

            if (!configuration) {
                throw new Error("Configuration for resource not found");
            }

            var signatureRequired = configuration.$.signatureRequired,
                apiKeyRequired = configuration.$.apiKeyRequired,
                sessionRequired = configuration.$.sessionRequired;

            needsSignature = signatureRequired || sessionRequired;

            if (this.$.session && sessionRequired) {
                params = _.defaults(params, {
                    // TODO: change session id to token for translation service
                    sessionId: this.$.session.$.id
                });
            }

            if (needsSignature) {
                var secret = this.$.secret;
                var time = Date.now();
                var url = this._buildUriForResource(resource, this.$.endPoint);

                var data = method + " " + url + " " + time + " " + secret;

                params = _.defaults(params, {
                    sig: SprdDataSource.SHA1(data),
                    time: time,
                    apiKey: apiKey
                });
            }

            if (apiKeyRequired || signatureRequired || sessionRequired) {
                params = _.defaults(params, {
                    apiKey: apiKey
                });
            }

            return params;
        }
    });

    SprdDataSource.SHA1 = function (msg) {

        function rotateLeft(n, s) {
            return ( n << s ) | (n >>> (32 - s));
        }

        function cvtHex(val) {
            var str = "";
            var i;
            var v;

            for (i = 7; i >= 0; i--) {
                v = (val >>> (i * 4)) & 0x0f;
                str += v.toString(16);
            }
            return str;
        }

        function utf8Encode(string) {
            string = string.replace(/\r\n/g, "\n");
            var utfText = "";

            for (var n = 0; n < string.length; n++) {

                var c = string.charCodeAt(n);

                if (c < 128) {
                    utfText += String.fromCharCode(c);
                }
                else if ((c > 127) && (c < 2048)) {
                    utfText += String.fromCharCode((c >> 6) | 192);
                    utfText += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utfText += String.fromCharCode((c >> 12) | 224);
                    utfText += String.fromCharCode(((c >> 6) & 63) | 128);
                    utfText += String.fromCharCode((c & 63) | 128);
                }

            }

            return utfText;
        }

        var blockStart;
        var i, j;
        var W = new Array(80);
        var H0 = 0x67452301;
        var H1 = 0xEFCDAB89;
        var H2 = 0x98BADCFE;
        var H3 = 0x10325476;
        var H4 = 0xC3D2E1F0;
        var A, B, C, D, E;
        var temp;

        msg = utf8Encode(msg);

        var msg_len = msg.length;

        var word_array = [];
        for (i = 0; i < msg_len - 3; i += 4) {
            j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
                msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
            word_array.push(j);
        }

        switch (msg_len % 4) {
            case 0:
                i = 0x080000000;
                break;
            case 1:
                i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
                break;

            case 2:
                i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
                break;

            case 3:
                i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
                break;
        }

        word_array.push(i);

        while ((word_array.length % 16) != 14) {
            word_array.push(0);
        }

        word_array.push(msg_len >>> 29);
        word_array.push((msg_len << 3) & 0x0ffffffff);

        for (blockStart = 0; blockStart < word_array.length; blockStart += 16) {

            for (i = 0; i < 16; i++) {
                W[i] = word_array[blockStart + i];
            }

            for (i = 16; i <= 79; i++) {
                W[i] = rotateLeft(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
            }

            A = H0;
            B = H1;
            C = H2;
            D = H3;
            E = H4;

            for (i = 0; i <= 19; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 20; i <= 39; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 40; i <= 59; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 60; i <= 79; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            H0 = (H0 + A) & 0x0ffffffff;
            H1 = (H1 + B) & 0x0ffffffff;
            H2 = (H2 + C) & 0x0ffffffff;
            H3 = (H3 + D) & 0x0ffffffff;
            H4 = (H4 + E) & 0x0ffffffff;

        }

        temp = cvtHex(H0) + cvtHex(H1) + cvtHex(H2) + cvtHex(H3) + cvtHex(H4);
        return temp.toLowerCase();
    };

    return SprdDataSource;
});<|endoftext|>


<commit_before>var BrowserView = function(args) {
  this.context = document.querySelector('canvas').getContext('2d');
  this.gameBoard = args.gameBoard;
  this.pressed = {
    slide: false,
    drop: false,
    rotate: false
  };

  addEventListener('keydown', this.keyDown.bind(this));
  addEventListener('keyup', this.keyUp.bind(this));
}
BrowserView.prototype.keyDown = function(event) {
  var pressedKey = KEY_CODES[event.keyCode];
  if(pressedKey == 'left' || pressedKey == 'right') {
    event.preventDefault();
    if(this.pressed.slide == false) {
      this.pressed.slide = pressedKey;
      this.handleInput.bind(this).call();
    }
  }
  if(pressedKey == 'down') {
    event.preventDefault();
    if(this.pressed.drop == false) {
      this.pressed.drop = true;
      this.handleInput.bind(this).call();
    }
  }
};
BrowserView.prototype.keyUp = function(event){
  var releasedKey = KEY_CODES[event.keyCode];
  if(releasedKey == 'left' || releasedKey == 'right') {
    event.preventDefault();
    this.pressed.slide = false;
  }
  if(releasedKey == 'down') {
    event.preventDefault();
    this.pressed.drop = false;
    this.gameBoard.cycleDropBlock();
  }
};
BrowserView.prototype.handleInput = function() {
  if(this.pressed.slide) {
    this.gameBoard.slideBlock(this.pressed.slide);
    setTimeout(this.handleInput.bind(this), INPUT_DELAY);
  }
  if(this.pressed.drop) {
    this.gameBoard.cycleDropBlock({quickly: true});
  }
};
BrowserView.prototype.drawBoard = function(board) {
  var context = this.context
  context.lineWidth = 4;
  context.font = BLOCK_FONT;

  board.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      context.fillStyle = CHEMICAL_ELEMENTS[col]['background-color'];
      context.strokeStyle = CHEMICAL_ELEMENTS[col]['border-color'];

      context.fillRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.strokeRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.fillStyle = CHEMICAL_ELEMENTS[col]['color'];
      context.fillText(CHEMICAL_ELEMENTS[col].symbol, (cIndex * BLOCK_SPACING_WIDTH) + (BLOCK_SPACING_WIDTH / 2) - 4, (rIndex * BLOCK_SPACING_HEIGHT) + (BLOCK_SPACING_HEIGHT / 2) + 4);
    });
  });
};
BrowserView.prototype.animate = function(board) {
  var lastTime = null;
  var progress = true;
  var self = this;

  var animate = function(time) {
    if(lastTime) {
      var timeStep = Math.min(time - lastTime, 100) / 1000;
      progress = timeStep < 2000;
    }
    lastTime = time;
    self.drawBoard(board);
    if(progress) {
      requestAnimationFrame(animate);
    }
  }
  requestAnimationFrame(animate);
};
<commit_msg>Update view to call rotateBlock on up arrow key press<commit_after>var BrowserView = function(args) {
  this.context = document.querySelector('canvas').getContext('2d');
  this.gameBoard = args.gameBoard;
  this.pressed = {
    slide: false,
    drop: false,
    rotate: false
  };

  addEventListener('keydown', this.keyDown.bind(this));
  addEventListener('keyup', this.keyUp.bind(this));
}
BrowserView.prototype.keyDown = function(event) {
  var pressedKey = KEY_CODES[event.keyCode];
  if(pressedKey == 'left' || pressedKey == 'right') {
    event.preventDefault();
    if(this.pressed.slide == false) {
      this.pressed.slide = pressedKey;
      this.handleInput.bind(this).call();
    }
  }
  if(pressedKey == 'down') {
    event.preventDefault();
    if(this.pressed.drop == false) {
      this.pressed.drop = true;
      this.handleInput.bind(this).call();
    }
  }
  if(pressedKey == 'up') {
    event.preventDefault();
    if(this.pressed.rotate == false) {
      this.pressed.rotate = true;
      this.handleInput.bind(this).call();
    }
  }
};
BrowserView.prototype.keyUp = function(event){
  var releasedKey = KEY_CODES[event.keyCode];
  if(releasedKey == 'left' || releasedKey == 'right') {
    event.preventDefault();
    this.pressed.slide = false;
  }
  if(releasedKey == 'down') {
    event.preventDefault();
    this.pressed.drop = false;
    this.gameBoard.cycleDropBlock();
  }
  if(releasedKey == 'up') {
    event.preventDefault();
    this.pressed.rotate = false;
  }
};
BrowserView.prototype.handleInput = function() {
  if(this.pressed.slide) {
    this.gameBoard.slideBlock(this.pressed.slide);
    setTimeout(this.handleInput.bind(this), INPUT_DELAY);
  }
  if(this.pressed.drop) {
    this.gameBoard.cycleDropBlock({quickly: true});
  }
  if(this.pressed.rotate) {
    this.gameBoard.rotateBlock('counter');
    setTimeout(this.handleInput.bind(this), INPUT_DELAY);
  }
};
BrowserView.prototype.drawBoard = function(board) {
  var context = this.context
  context.lineWidth = 4;
  context.font = BLOCK_FONT;

  board.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      context.fillStyle = CHEMICAL_ELEMENTS[col]['background-color'];
      context.strokeStyle = CHEMICAL_ELEMENTS[col]['border-color'];

      context.fillRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.strokeRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.fillStyle = CHEMICAL_ELEMENTS[col]['color'];
      context.fillText(CHEMICAL_ELEMENTS[col].symbol, (cIndex * BLOCK_SPACING_WIDTH) + (BLOCK_SPACING_WIDTH / 2) - 4, (rIndex * BLOCK_SPACING_HEIGHT) + (BLOCK_SPACING_HEIGHT / 2) + 4);
    });
  });
};
BrowserView.prototype.animate = function(board) {
  var lastTime = null;
  var progress = true;
  var self = this;

  var animate = function(time) {
    if(lastTime) {
      var timeStep = Math.min(time - lastTime, 100) / 1000;
      progress = timeStep < 2000;
    }
    lastTime = time;
    self.drawBoard(board);
    if(progress) {
      requestAnimationFrame(animate);
    }
  }
  requestAnimationFrame(animate);
};
<|endoftext|>