<commit_before>(function() {
  'use strict';

  angular
  .module('app.services')
  .controller('Sales', Sales);

  Sales.$inject = ['$scope', '$stateParams', '$filter', '$timeout', 'template', 'mxpostapi', 'kiwiwebapi'];

  function Sales($scope, $stateParams, $filter, $timeout, template, mxpostapi, kiwiwebapi) {
    var vm = this;
    vm.animate = {};
    vm.error = error;
    vm.errors = {};
    vm.form = {};
    vm.geoZip = geoZip;
    vm.getDistricts = getDistricts;
    vm.getMunicipalities = getMunicipalities;
    vm.getZip = getZip;
    vm.reset = reset;
    vm.submit = submit;
    vm.SalesTicket = kiwiwebapi.newKiwiWebResource();
    vm.success = success;
    vm.ticket = {};
    angular.extend(vm.ticket, {
      type: 'Sales',
      step: 'Lead',
      outcome: 'Open'
    });

    activate();

    function activate() {
      console.log('Activating Sales Controller');
      template.get('app/services/sales/language/sales.es.json')
      .then(function(result) {
        vm.text = result;
      })
      .then(template.get('app/services/sales/language/salesform.es.json')
      .then(function(result) {
        vm.inputs = result.inputs;
      }))
      .then(mxpostapi.getStates()
      .$promise
      .then(function(data) {
        vm.states = data.results;
      }))
      .then(function() {
        $scope.app.setTitle(vm.text.title);
        if ($stateParams.service) {
          if ($stateParams.service === 'metromesh') {
            vm.ticket.service = 'Metro Mesh';
          } else {
            vm.ticket.service = $filter('capitalize')($stateParams.service);
          }
        }
      });
    }

    function error() {
      $scope.$emit('stopLoading');
      vm.animate.error = true;
      $timeout(function() {
        vm.animate.errorTitle = true;
      }, 250);
      $timeout(function() {
        vm.animate.errorMessage = true;
      }, 500);
    }

    function getDistricts(state, municipality) {
      $scope.$emit('startLoading');
      mxpostapi.getDistricts(state, municipality)
      .$promise
      .then(function(data) {
        vm.districts = data.results;
        vm.ticket.district = null;
        vm.ticket.zip = null;
        $scope.$emit('stopLoading');
      });
    }

    function getMunicipalities(state) {
      $scope.$emit('startLoading');
      mxpostapi.getMunicipalities(state)
      .$promise
      .then(function(data) {
        vm.municipalities = data.results;
        vm.districts = [];
        vm.ticket.municipality = null;
        vm.ticket.district = null;
        vm.ticket.zip = null;
        $scope.$emit('stopLoading');
      });
    }

    function getZip(district) {
      vm.district = $filter('filter')(vm.districts, {name: district}, true)[0];
      vm.ticket.zip = vm.district.zip;
    }

    function geoZip(zip) {
      vm.errors.zip = false;
      if (vm.form.zip.$invalid) {
        return;
      }
      $scope.$emit('startLoading');
      mxpostapi.geoZip(zip)
      .$promise
      .then(function(data) {
        vm.districts = data.results;
        if (!vm.districts.length) {
          vm.errors.zip = true;
        } else {
          vm.errors.zip = false;
          vm.district = data.results[0];
          mxpostapi.getMunicipalities(vm.district.state)
          .$promise
          .then(function(data) {
            vm.municipalities = data.results;
            vm.ticket.state = vm.district.state;
            vm.ticket.municipality = vm.district.municipality;
            vm.ticket.district = vm.district.name;
            $scope.$emit('stopLoading');
          });
        }
      });
    }

    function reset() {
      vm.animate.success = false;
      vm.animate.error = false;
      vm.animate.errorTitle = false;
      vm.animate.errorMessage = false;
      vm.animate.successTitle = false;
      vm.animate.successMessage = false;
      vm.animate.successTicket = false;
    }

    function submit(ticket) {
      if (vm.form.$valid) {
        $scope.$emit('startLoading');
        var salesTicket = new vm.SalesTicket(ticket);
        salesTicket.$save({class: vm.ticket.type})
        .then(
          function(data) {
            salesTicket.$get({class: vm.ticket.type})
            .then(function(data) {
              angular.extend(vm.ticket, data);
              success();
              console.log(vm.ticket);
            });
          },
          function(data) {
            error();
            console.log(data);
          }
        );
      }
    }

    function success() {
      $scope.$emit('stopLoading');
      vm.animate.success = true;
      $timeout(function() {
        vm.animate.successTitle = true;
      }, 250);
      $timeout(function() {
        vm.animate.successMessage = true;
      }, 500);
      $timeout(function() {
        vm.animate.successTicket = true;
      }, 750);
    }
  }

})();
<commit_msg>Adds default levels.<commit_after>(function() {
  'use strict';

  angular
  .module('app.services')
  .controller('Sales', Sales);

  Sales.$inject = ['$scope', '$stateParams', '$filter', '$timeout', 'template', 'mxpostapi', 'kiwiwebapi'];

  function Sales($scope, $stateParams, $filter, $timeout, template, mxpostapi, kiwiwebapi) {
    var vm = this;
    vm.animate = {};
    vm.error = error;
    vm.errors = {};
    vm.form = {};
    vm.geoZip = geoZip;
    vm.getDistricts = getDistricts;
    vm.getMunicipalities = getMunicipalities;
    vm.getZip = getZip;
    vm.reset = reset;
    vm.submit = submit;
    vm.SalesTicket = kiwiwebapi.newKiwiWebResource();
    vm.success = success;
    vm.ticket = {};
    angular.extend(vm.ticket, {
      type: 'Sales',
      step: 'Lead',
      outcome: 'Open',
      levels: '2'
    });

    activate();

    function activate() {
      console.log('Activating Sales Controller');
      template.get('app/services/sales/language/sales.es.json')
      .then(function(result) {
        vm.text = result;
      })
      .then(template.get('app/services/sales/language/salesform.es.json')
      .then(function(result) {
        vm.inputs = result.inputs;
      }))
      .then(mxpostapi.getStates()
      .$promise
      .then(function(data) {
        vm.states = data.results;
      }))
      .then(function() {
        $scope.app.setTitle(vm.text.title);
        if ($stateParams.service) {
          if ($stateParams.service === 'metromesh') {
            vm.ticket.service = 'Metro Mesh';
          } else {
            vm.ticket.service = $filter('capitalize')($stateParams.service);
          }
        }
      });
    }

    function error() {
      $scope.$emit('stopLoading');
      vm.animate.error = true;
      $timeout(function() {
        vm.animate.errorTitle = true;
      }, 250);
      $timeout(function() {
        vm.animate.errorMessage = true;
      }, 500);
    }

    function getDistricts(state, municipality) {
      $scope.$emit('startLoading');
      mxpostapi.getDistricts(state, municipality)
      .$promise
      .then(function(data) {
        vm.districts = data.results;
        vm.ticket.district = null;
        vm.ticket.zip = null;
        $scope.$emit('stopLoading');
      });
    }

    function getMunicipalities(state) {
      $scope.$emit('startLoading');
      mxpostapi.getMunicipalities(state)
      .$promise
      .then(function(data) {
        vm.municipalities = data.results;
        vm.districts = [];
        vm.ticket.municipality = null;
        vm.ticket.district = null;
        vm.ticket.zip = null;
        $scope.$emit('stopLoading');
      });
    }

    function getZip(district) {
      vm.district = $filter('filter')(vm.districts, {name: district}, true)[0];
      vm.ticket.zip = vm.district.zip;
    }

    function geoZip(zip) {
      vm.errors.zip = false;
      if (vm.form.zip.$invalid) {
        return;
      }
      $scope.$emit('startLoading');
      mxpostapi.geoZip(zip)
      .$promise
      .then(function(data) {
        vm.districts = data.results;
        if (!vm.districts.length) {
          vm.errors.zip = true;
        } else {
          vm.errors.zip = false;
          vm.district = data.results[0];
          mxpostapi.getMunicipalities(vm.district.state)
          .$promise
          .then(function(data) {
            vm.municipalities = data.results;
            vm.ticket.state = vm.district.state;
            vm.ticket.municipality = vm.district.municipality;
            vm.ticket.district = vm.district.name;
            $scope.$emit('stopLoading');
          });
        }
      });
    }

    function reset() {
      vm.animate.success = false;
      vm.animate.error = false;
      vm.animate.errorTitle = false;
      vm.animate.errorMessage = false;
      vm.animate.successTitle = false;
      vm.animate.successMessage = false;
      vm.animate.successTicket = false;
    }

    function submit(ticket) {
      if (vm.form.$valid) {
        $scope.$emit('startLoading');
        var salesTicket = new vm.SalesTicket(ticket);
        salesTicket.$save({class: vm.ticket.type})
        .then(
          function(data) {
            salesTicket.$get({class: vm.ticket.type})
            .then(function(data) {
              angular.extend(vm.ticket, data);
              success();
              console.log(vm.ticket);
            });
          },
          function(data) {
            error();
            console.log(data);
          }
        );
      }
    }

    function success() {
      $scope.$emit('stopLoading');
      vm.animate.success = true;
      $timeout(function() {
        vm.animate.successTitle = true;
      }, 250);
      $timeout(function() {
        vm.animate.successMessage = true;
      }, 500);
      $timeout(function() {
        vm.animate.successTicket = true;
      }, 750);
    }
  }

})();
<|endoftext|>


<commit_before>var asciidoc = {  // Namespace.

/////////////////////////////////////////////////////////////////////
// Table Of Contents generator
/////////////////////////////////////////////////////////////////////

/* Author: Mihai Bazon, September 2002
 * http://students.infoiasi.ro/~mishoo
 *
 * Table Of Content generator
 * Version: 0.6
 * Modified to accomodate the bootstrap backend with themes
 *
 * Feel free to use this script under the terms of the GNU General Public
 * License, as long as you do not remove or alter this notice.
 */

 /* modified by Troy D. Hanson, September 2006. License: GPL */
 /* modified by Stuart Rackham, 2006, 2009. License: GPL */
 /* modified by Dan Allen, 2012. License: GPL */
 /* modified by Laurent Laville, 2012. License: GPL */

// toclevels = 1..4.
toc: function (toclevels) {

  function getText(el) {
    var text = "";
    for (var i = el.firstChild; i != null; i = i.nextSibling) {
      if (i.nodeType == 3 /* Node.TEXT_NODE */) // IE doesn't speak constants.
        text += i.data;
      else if (i.firstChild != null)
        text += getText(i);
    }
    return text;
  }

  function TocEntry(el, text, toclevel) {
    this.element = el;
    this.text = text;
    this.toclevel = toclevel;
  }

  function tocEntries(el, toclevels) {
    var result = new Array;
    var re = new RegExp('[hH]([1-'+(toclevels)+'])');
    // Function that scans the DOM tree for header elements (the DOM2
    // nodeIterator API would be a better technique but not supported by all
    // browsers).
    var iterate = function (el) {
      for (var i = el.firstChild; i != null; i = i.nextSibling) {
        if (i.nodeType == 1 /* Node.ELEMENT_NODE */) {
          var mo = re.exec(i.tagName);
          if (mo && (i.getAttribute("class") || i.getAttribute("className")) != "loose") {
            result[result.length] = new TocEntry(i, getText(i), mo[1]-1);
          }
          iterate(i);
        }
      }
    }
    iterate(el);
    return result;
  }

  var toc = document.getElementById("toc");
  if (!toc) {
    return;
  }

  // Delete existing TOC entries in case we're reloading the TOC.
  var tocEntriesToRemove = [];
  var i;
  for (i = 0; i < toc.childNodes.length; i++) {
    var entry = toc.childNodes[i];
    if (entry.nodeName.toLowerCase() == 'div'
     && entry.getAttribute("class")
     && entry.getAttribute("class").match(/^toclevel/))
      tocEntriesToRemove.push(entry);
  }
  for (i = 0; i < tocEntriesToRemove.length; i++) {
    toc.removeChild(tocEntriesToRemove[i]);
  }

  // Rebuild TOC entries.
  var entries = tocEntries(document.getElementById("content"), toclevels);
  for (var i = 0; i < entries.length; ++i) {
    var entry = entries[i];
    if (entry.element.id == "") {
      var sec = entry.element.parentNode;
      if (sec.nodeName.toLowerCase() != 'section') {
        sec = sec.parentNode;
      }
      if (sec.nodeName.toLowerCase() == 'section' && sec.id != "") {
        entry.element.id = sec.id;
      }
      else {
        entry.element.id = "toc_" + i;
      }
    }
    var sidebar = document.getElementById("sidebar");
    var a = document.createElement("a");
    a.href = "#" + entry.element.id;
    var img = document.createElement("i");
    if (sidebar.getAttribute('class').match(/pull-right/)) {
        img.className = 'icon-chevron-left';
    } else {
        img.className = 'icon-chevron-right';
    }
    a.appendChild(img);
    a.appendChild(document.createTextNode(entry.text));
    var li = document.createElement("li");
    li.appendChild(a);
    //li.className = "toclevel" + entry.toclevel;
    toc.appendChild(li);
  }
  if (entries.length == 0)
    toc.parentNode.removeChild(toc);
},

/////////////////////////////////////////////////////////////////////
// Footnotes generator
/////////////////////////////////////////////////////////////////////

/* Based on footnote generation code from:
 * http://www.brandspankingnew.net/archive/2005/07/format_footnote.html
 */

footnotes: function () {
  // Delete existing footnote entries in case we're reloading the footnodes.
  var i;
  var noteholder = document.getElementById("footnotes");
  if (!noteholder) {
    return;
  }
  var entriesToRemove = [];
  for (i = 0; i < noteholder.childNodes.length; i++) {
    var entry = noteholder.childNodes[i];
    if (entry.nodeName.toLowerCase() == 'div' && entry.getAttribute("class") == "footnote")
      entriesToRemove.push(entry);
  }
  for (i = 0; i < entriesToRemove.length; i++) {
    noteholder.removeChild(entriesToRemove[i]);
  }

  // Rebuild footnote entries.
  var cont = document.getElementById("content");
  var spans = cont.getElementsByTagName("span");
  var refs = {};
  var n = 0;
  for (i=0; i<spans.length; i++) {
    if (spans[i].className == "footnote") {
      n++;
      var note = spans[i].getAttribute("data-note");
      if (!note) {
        // Use [\s\S] in place of . so multi-line matches work.
        // Because JavaScript has no s (dotall) regex flag.
        note = spans[i].innerHTML.match(/\s*\[([\s\S]*)]\s*/)[1];
        spans[i].innerHTML =
          "[" + n + "]";
        spans[i].setAttribute("data-note", note);
      }
      noteholder.innerHTML +=
        "
" +
        "" +
        n + ". " + note + "
";
      var id =spans[i].getAttribute("id");
      if (id != null) refs["#"+id] = n;
    }
  }
  if (n == 0)
    noteholder.parentNode.removeChild(noteholder);
  else {
    // Process footnoterefs.
    for (i=0; i<spans.length; i++) {
      if (spans[i].className == "footnoteref") {
        var href = spans[i].getElementsByTagName("a")[0].getAttribute("href");
        href = href.match(/#.*/)[0];  // Because IE return full URL.
        n = refs[href];
        spans[i].innerHTML =
          "[" + n + "]";
      }
    }
  }
},

install: function(toclevels) {
  var timerId;

  function reinstall() {
    asciidoc.footnotes();
    if (toclevels) {
      asciidoc.toc(toclevels);
    }
  }

  function reinstallAndRemoveTimer() {
    clearInterval(timerId);
    reinstall();
  }

  timerId = setInterval(reinstall, 500);
  if (document.addEventListener)
    document.addEventListener("DOMContentLoaded", reinstallAndRemoveTimer, false);
  else
    window.onload = reinstallAndRemoveTimer;
}

}
<commit_msg>remove hack for TOC, support now the default AsciiDoc distribution<commit_after>var asciidoc = {  // Namespace.

/////////////////////////////////////////////////////////////////////
// Table Of Contents generator
/////////////////////////////////////////////////////////////////////

/* Author: Mihai Bazon, September 2002
 * http://students.infoiasi.ro/~mishoo
 *
 * Table Of Content generator
 * Version: 0.4
 *
 * Feel free to use this script under the terms of the GNU General Public
 * License, as long as you do not remove or alter this notice.
 */

 /* modified by Troy D. Hanson, September 2006. License: GPL */
 /* modified by Stuart Rackham, 2006, 2009. License: GPL */

// toclevels = 1..4.
toc: function (toclevels) {

  function getText(el) {
    var text = "";
    for (var i = el.firstChild; i != null; i = i.nextSibling) {
      if (i.nodeType == 3 /* Node.TEXT_NODE */) // IE doesn't speak constants.
        text += i.data;
      else if (i.firstChild != null)
        text += getText(i);
    }
    return text;
  }

  function TocEntry(el, text, toclevel) {
    this.element = el;
    this.text = text;
    this.toclevel = toclevel;
  }

  function tocEntries(el, toclevels) {
    var result = new Array;
    var re = new RegExp('[hH]([1-'+(toclevels+1)+'])');
    // Function that scans the DOM tree for header elements (the DOM2
    // nodeIterator API would be a better technique but not supported by all
    // browsers).
    var iterate = function (el) {
      for (var i = el.firstChild; i != null; i = i.nextSibling) {
        if (i.nodeType == 1 /* Node.ELEMENT_NODE */) {
          var mo = re.exec(i.tagName);
          if (mo && (i.getAttribute("class") || i.getAttribute("className")) != "float") {
            result[result.length] = new TocEntry(i, getText(i), mo[1]-1);
          }
          iterate(i);
        }
      }
    }
    iterate(el);
    return result;
  }

  var toc = document.getElementById("toc");
  if (!toc) {
    return;
  }

  // Delete existing TOC entries in case we're reloading the TOC.
  var tocEntriesToRemove = [];
  var i;
  for (i = 0; i < toc.childNodes.length; i++) {
    var entry = toc.childNodes[i];
    if (entry.nodeName.toLowerCase() == 'div'
     && entry.getAttribute("class")
     && entry.getAttribute("class").match(/^toclevel/))
      tocEntriesToRemove.push(entry);
  }
  for (i = 0; i < tocEntriesToRemove.length; i++) {
    toc.removeChild(tocEntriesToRemove[i]);
  }

  // Rebuild TOC entries.
  var entries = tocEntries(document.getElementById("content"), toclevels);
  for (var i = 0; i < entries.length; ++i) {
    var entry = entries[i];
    if (entry.element.id == "")
      entry.element.id = "_toc_" + i;
    var a = document.createElement("a");
    a.href = "#" + entry.element.id;
    a.appendChild(document.createTextNode(entry.text));
    var div = document.createElement("div");
    div.appendChild(a);
    div.className = "toclevel" + entry.toclevel;
    toc.appendChild(div);
  }
  if (entries.length == 0)
    toc.parentNode.removeChild(toc);
},

/////////////////////////////////////////////////////////////////////
// Footnotes generator
/////////////////////////////////////////////////////////////////////

/* Based on footnote generation code from:
 * http://www.brandspankingnew.net/archive/2005/07/format_footnote.html
 */

footnotes: function () {
  // Delete existing footnote entries in case we're reloading the footnodes.
  var i;
  var noteholder = document.getElementById("footnotes");
  if (!noteholder) {
    return;
  }
  var entriesToRemove = [];
  for (i = 0; i < noteholder.childNodes.length; i++) {
    var entry = noteholder.childNodes[i];
    if (entry.nodeName.toLowerCase() == 'div' && entry.getAttribute("class") == "footnote")
      entriesToRemove.push(entry);
  }
  for (i = 0; i < entriesToRemove.length; i++) {
    noteholder.removeChild(entriesToRemove[i]);
  }

  // Rebuild footnote entries.
  var cont = document.getElementById("content");
  var spans = cont.getElementsByTagName("span");
  var refs = {};
  var n = 0;
  for (i=0; i<spans.length; i++) {
    if (spans[i].className == "footnote") {
      n++;
      var note = spans[i].getAttribute("data-note");
      if (!note) {
        // Use [\s\S] in place of . so multi-line matches work.
        // Because JavaScript has no s (dotall) regex flag.
        note = spans[i].innerHTML.match(/\s*\[([\s\S]*)]\s*/)[1];
        spans[i].innerHTML =
          "[" + n + "]";
        spans[i].setAttribute("data-note", note);
      }
      noteholder.innerHTML +=
        "
" +
        "" +
        n + ". " + note + "
";
      var id =spans[i].getAttribute("id");
      if (id != null) refs["#"+id] = n;
    }
  }
  if (n == 0)
    noteholder.parentNode.removeChild(noteholder);
  else {
    // Process footnoterefs.
    for (i=0; i<spans.length; i++) {
      if (spans[i].className == "footnoteref") {
        var href = spans[i].getElementsByTagName("a")[0].getAttribute("href");
        href = href.match(/#.*/)[0];  // Because IE return full URL.
        n = refs[href];
        spans[i].innerHTML =
          "[" + n + "]";
      }
    }
  }
},

install: function(toclevels) {
  var timerId;

  function reinstall() {
    asciidoc.footnotes();
    if (toclevels) {
      asciidoc.toc(toclevels);
    }
  }

  function reinstallAndRemoveTimer() {
    clearInterval(timerId);
    reinstall();
  }

  timerId = setInterval(reinstall, 500);
  if (document.addEventListener)
    document.addEventListener("DOMContentLoaded", reinstallAndRemoveTimer, false);
  else
    window.onload = reinstallAndRemoveTimer;
}

}
<|endoftext|>


<commit_before>// Rapid Prototype: of data-driven-templates
// a bit of a mess due to trying out a bunch of techniques...
// based on http://onehungrymind.com/angularjs-dynamic-templates/
// also see (for a good overview of angular)  http://stephanebegaudeau.tumblr.com/post/48776908163/everything-you-need-to-understand-to-start-with
// look into loading templates via https://github.com/requirejs/text or angular.$templateCache
// or https://npmjs.org/package/grunt-angular-templates per (simpulton September 7, 2013 at 12:52 pm)
//

var app = angular.module('ddtApp', ['ngSanitize']);

// sortable directive uses JQueryUI to manage the sorting by drag&drop
app.directive('sortable', function() {
  return {
    // A = attribute, E = Element, C = Class and M = HTML Comment
    restrict:'A',
    link: function(scope, element, attrs) {
			var start;
			var dragStart = function(e, ui) {
				start = ui.item.index();
			};
			var dragEnd = function(e, ui) {
				var end = ui.item.index();
				scope.content.items.splice(end, 0, scope.content.items.splice(start, 1)[0]);
				scope.$apply();
			};
			$(element).sortable({
				start: dragStart,
				update: dragEnd
			});
			$(element).disableSelection();
    }
  };
});

// data driven templates with two way data binding while being se recursivly...
app.directive('drivenTemplate', function ($compile, $templateCache) {
  // gets html given a name and an edit_mode
  var getTemplate = function(viewType, edit_mode) {
	  var suffix = (edit_mode)? "_edit": "";
    return $templateCache.get(viewType + suffix + ".html");
  };

  var linker = function(scope, element, attrs) {
    scope.$watch("edit_mode", function() {
      var isArr = angular.isArray(scope.content);
      var isObj = angular.isObject(scope.content);
      var t = typeof scope.content;
      if (isArr) {
        t = 'array';
        scope.items = scope.content;
      }
      if (isObj) {
        scope.elements = scope.content;
      }

      element.html(getTemplate(t, scope.edit_mode));
      $compile(element.contents())(scope);
    });
  };

  return {
    restrict: "A",
    replace: true,
    link: linker,
    scope: {
        content:'=content'
    }
  };
});

function demoCtrl($scope, $http) { "use strict";
  $http.get('json_feed.json').success(function(data) {
		$scope.content = data;
	});

  $scope.stringify_content = function () {
    return JSON.stringify($scope.content, null, ' ');
  };

  $scope.add_content = function () {
    $scope.content.items.unshift({"view_template": "section", "title": "A New First Section",
      "narrative": "Lorem ipsum nan nan-nan nan-nan nahh dolor sit amet, consectetur adipiscing elit."
    });
  };
}

<commit_msg>condensing<commit_after>// Rapid Prototype: of data-driven-templates
// a bit of a mess due to trying out a bunch of techniques...
// based on http://onehungrymind.com/angularjs-dynamic-templates/
// also see (for a good overview of angular)  http://stephanebegaudeau.tumblr.com/post/48776908163/everything-you-need-to-understand-to-start-with
// look into loading templates via https://github.com/requirejs/text or angular.$templateCache
// or https://npmjs.org/package/grunt-angular-templates per (simpulton September 7, 2013 at 12:52 pm)
//

var app = angular.module('ddtApp', ['ngSanitize']);

// sortable directive uses JQueryUI to manage the sorting by drag&drop
app.directive('sortable', function() {
  return {
    // A = attribute, E = Element, C = Class and M = HTML Comment
    restrict:'A',
    link: function(scope, element, attrs) {
			var start;
			var dragStart = function(e, ui) {
				start = ui.item.index();
			};
			var dragEnd = function(e, ui) {
				var end = ui.item.index();
				scope.content.items.splice(end, 0, scope.content.items.splice(start, 1)[0]);
				scope.$apply();
			};
			$(element).sortable({
				start: dragStart,
				update: dragEnd
			});
			$(element).disableSelection();
    }
  };
});

// data driven templates with two way data binding while being se recursivly...
app.directive('drivenTemplate', function ($compile, $templateCache) {
  // gets html given a name and an edit_mode
  var getTemplate = function(viewType, edit_mode) {
	  var suffix = (edit_mode)? "_edit": "";
    return $templateCache.get(viewType + suffix + ".html");
  };

  var linker = function(scope, element, attrs) {
    scope.$watch("edit_mode", function() {
      var isArr = angular.isArray(scope.content);
      var isObj = angular.isObject(scope.content);
      var t = typeof scope.content;
      if (isArr) {
        t = 'array';
        scope.items = scope.content;
      }
      if (isObj) {
        scope.elements = scope.content;
      }

      element.html(getTemplate(t, scope.edit_mode));
      $compile(element.contents())(scope);
    });
    scope.$watch("content", function() {
      $compile(element.contents())(scope);
    });
  };

  return {
    restrict: "A",
    replace: true,
    link: linker,
    scope: {
        content:'=content'
    }
  };
});

function demoCtrl($scope, $http) { "use strict";
  $http.get('json_feed.json').success(function(data) {
		$scope.content = data;
	});

  $scope.stringify_content = function () {
    return JSON.stringify($scope.content, null, ' ');
  };

  $scope.add_content = function () {
    $scope.content.items.unshift({"view_template": "section", "title": "A New First Section",
      "narrative": "Lorem ipsum nan nan-nan nan-nan nahh dolor sit amet, consectetur adipiscing elit."
    });
  };
}

<|endoftext|>


<commit_before>/* test/device_routes_test.js -- test Device routes
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

var expect = require('expect.js');
var Device = require('../models/device');
var Routes = require('../routes/device');
var router = require('./support/router');

var deviceAttrs = {
  name: "Some device",
};

describe('Device routes', function() {
  var device, count;
  before(function(done) {
    Factory.create('device', 26, function (l) {
      device = l[0];
      Device.count(function (err, c) {
        if (err) throw err;
        count = c;
        done();
      });
    });
  });

  var operator;
  before(function(done) {
    Factory.create('user', function (u) { operator = u; done(); });
  });

  var admin;
  before(function(done) {
    Factory.create('admin', function (a) { admin = a; done(); });
  });

  describe("#load", function() {
    it("should find by id and assign device to req", function(done) {
      var req = { },
      id = device._id;

      Routes.load(req, {}, function() {
        expect(req.device.toJSON()).to.eql(device.toJSON());
        done();
      }, id);
    });

    it("should respond with not found code", function(done) {
      var res = {
        send: function(code) {
          expect(code).to.eql(404);
          done();
        }
      };
      Routes.load({}, res, null, 0);
    });
  });

  describe("#show", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.show, req, res);
    });

    describe("when operator logged in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should return 404 if no device", function(done) {
        var res = {
          locals: {},
          send: function(code) {
            expect(code).to.be(404);
            done();
          },
        };
        router(Routes.show, req, res);
      });

      it("should return only accessible fields", function(done) {
        var res = {
          locals: {},
          json_ng: function(dev) {
            expect(Object.keys(dev)).to.eql(['_id', 'name']);
            expect(dev._id).to.eql(device._id);
            expect(dev.name).to.eql(device.name);
            done();
          },
        };
        req.device = device;
        req.device.some_field = true;
        router(Routes.show, req, res);
      });
    });
  });

  describe("#update", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.update, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should deny non-admins", function(done) {
        res = {
          locals: {},
          send: function(code) {
            expect(code).to.eql(403);
            done();
          },
        };
        router(Routes.update, req, res);
      });
    });

    describe("when administrator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: admin._id } };
      });

      it("should fail", function(done) {
        var res = {
          locals: {},
          json: function(code) {
            expect(code).to.eql(500);
            done();
          },
        };
        req.body = {
          name: "Some name",
        };
        req.device = device;
        router(Routes.update, req, res);
      });
    });
  });

  describe("#index", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
        req.query = {};
        res = {
          locals: {},
        };
      });

      it("should retrieve first page if not specified", function(done) {
        res.json_ng = function(devices) {
          expect(devices.length).to.be(26);
          expect(devices[25].count).to.be(count);
          done();
        };
        router(Routes.index, req, res);
      });

      it("should sort results by name", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        Device.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve requested page", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = 2;
        Device.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve first one if page is less then 1", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = 0;
        Device.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve last one if page is too big", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = 3;
        Device.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });
    });
  });

  describe("#create", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });
  });
});

// vim:ts=2 sts=2 sw=2 et:
<commit_msg>tests: routes: create device authorization<commit_after>/* test/device_routes_test.js -- test Device routes
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

var expect = require('expect.js');
var Device = require('../models/device');
var Routes = require('../routes/device');
var router = require('./support/router');

var deviceAttrs = {
  name: "Some device",
};

describe('Device routes', function() {
  var device, count;
  before(function(done) {
    Factory.create('device', 26, function (l) {
      device = l[0];
      Device.count(function (err, c) {
        if (err) throw err;
        count = c;
        done();
      });
    });
  });

  var operator;
  before(function(done) {
    Factory.create('user', function (u) { operator = u; done(); });
  });

  var admin;
  before(function(done) {
    Factory.create('admin', function (a) { admin = a; done(); });
  });

  describe("#load", function() {
    it("should find by id and assign device to req", function(done) {
      var req = { },
      id = device._id;

      Routes.load(req, {}, function() {
        expect(req.device.toJSON()).to.eql(device.toJSON());
        done();
      }, id);
    });

    it("should respond with not found code", function(done) {
      var res = {
        send: function(code) {
          expect(code).to.eql(404);
          done();
        }
      };
      Routes.load({}, res, null, 0);
    });
  });

  describe("#show", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.show, req, res);
    });

    describe("when operator logged in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should return 404 if no device", function(done) {
        var res = {
          locals: {},
          send: function(code) {
            expect(code).to.be(404);
            done();
          },
        };
        router(Routes.show, req, res);
      });

      it("should return only accessible fields", function(done) {
        var res = {
          locals: {},
          json_ng: function(dev) {
            expect(Object.keys(dev)).to.eql(['_id', 'name']);
            expect(dev._id).to.eql(device._id);
            expect(dev.name).to.eql(device.name);
            done();
          },
        };
        req.device = device;
        req.device.some_field = true;
        router(Routes.show, req, res);
      });
    });
  });

  describe("#update", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.update, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should deny non-admins", function(done) {
        res = {
          locals: {},
          send: function(code) {
            expect(code).to.eql(403);
            done();
          },
        };
        router(Routes.update, req, res);
      });
    });

    describe("when administrator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: admin._id } };
      });

      it("should fail", function(done) {
        var res = {
          locals: {},
          json: function(code) {
            expect(code).to.eql(500);
            done();
          },
        };
        req.body = {
          name: "Some name",
        };
        req.device = device;
        router(Routes.update, req, res);
      });
    });
  });

  describe("#index", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
        req.query = {};
        res = {
          locals: {},
        };
      });

      it("should retrieve first page if not specified", function(done) {
        res.json_ng = function(devices) {
          expect(devices.length).to.be(26);
          expect(devices[25].count).to.be(count);
          done();
        };
        router(Routes.index, req, res);
      });

      it("should sort results by name", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        Device.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve requested page", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = 2;
        Device.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve first one if page is less then 1", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = 0;
        Device.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve last one if page is too big", function(done) {
        var original = [];
        res.json_ng = function(devices) {
          var fetched = devices.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = 3;
        Device.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, devices) {
          original = devices.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });
    });
  });

  describe("#create", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should deny non-admins", function(done) {
        res = {
          locals: {},
          send: function(code) {
            expect(code).to.eql(403);
            done();
          },
        };
        router(Routes.create, req, res);
      });
    });
  });
});

// vim:ts=2 sts=2 sw=2 et:
<|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.

'use strict';

var CollapsedAssert = require('../lib/collapsed-assert.js');
var allocCluster = require('../lib/test-cluster.js');

allocCluster.test('forwarding to a down service', {
    size: 5,
    whitelist: [
        ['info', 'Refreshing service peer affinity']
    ]
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;
    var steve = cluster.remotes.steve;

    cluster.logger.whitelist('info', 'resetting connection');
    cluster.logger.whitelist('warn', 'error while forwarding');
    cluster.logger.whitelist('warn', 'forwarding error frame');

    cluster.checkExitPeers(assert, {
        serviceName: steve.serviceName,
        hostPort: steve.hostPort
    });

    // Close the service to emulate failure.
    steve.destroy();

    bob.clientChannel.request({
        serviceName: steve.serviceName
    }).send('hi', null, JSON.stringify(null), onForwarded);

    function onForwarded(err, resp, arg2, arg3) {
        /*eslint complexity: [2, 15], max-statements: [2, 40] */
        assert.ok(err, 'forward call should fail');

        assert.equal(err.isErrorFrame, true,
            'forwarding err is an error frame');

        cluster.checkExitPeers(assert, {
            serviceName: steve.serviceName,
            hostPort: steve.hostPort,
            disconnectedHostsPorts: [steve.hostPort]
        });

        // TODO make not flake
        // TODO this should not return a could not find service
        // error. The exit node needs to know the difference
        // between service exists & is down vs service does not exist.
        var message = 'unknown service ' + steve.serviceName;
        if (err.message === message) {
            assert.ok(true, 'skipping flaky test');
            return assert.end();
        }

        assert.ok(
            err.message.indexOf('connect ECONNREFUSED') >= 0 ||
            err.message.indexOf('socket closed') === 0 ||
            err.message === 'connect ECONNREFUSED' ||
            err.message === 'This socket has been ended by the other party',
            'expected error to be a socket closed error'
        );

        var logLines = cluster.logger.items();
        var cassert = CollapsedAssert();
        for (var i = 0; i < logLines.length; i++) {
            var logLine = logLines[i];
            var logErr = logLine.meta.error;
            if (logLine.msg === 'forwarding error frame') {
                cassert.equal(logLine.meta.isErrorFrame, true,
                    'expected error frame');
                cassert.equal(logLine.meta.serviceName, 'steve',
                    'expected steve error');
            } else if (logLine.msg === 'Refreshing service peer affinity') {
                cassert.ok(true, 'expected peer affinity refresh');
            } else if (logLine.msg === 'error while forwarding' ||
                       logLine.msg === 'resetting connection') {
                if (logLine.msg === 'error while forwarding') {
                    cassert.equal(logLine.levelName, 'warn');
                } else if (logLine.msg === 'resetting connection') {
                    cassert.equal(logLine.levelName, 'info');
                }

                var expectedAddr =
                    logErr.socketRemoteAddr === steve.hostPort;
                // if (!expectedAddr) console.error('WRU', steve.hostPort, logErr);
                cassert.ok(expectedAddr, 'expected exception to steve');

                var expectedType =
                    logErr.fullType === 'tchannel.socket~!~error.wrapped-io.connect.ECONNREFUSED' ||
                    logErr.fullType === 'tchannel.socket~!~error.wrapped-io.read.ECONNRESET';
                if (!expectedType) {
                    assert.comment('unexpected error type ' + logErr.fullType);
                }
                cassert.ok(expectedType, 'Expected exception to be network error');
            } else {
                cassert.ok(false, 'unexpected log line');
            }
        }
        cassert.report(assert, 'logs should be correct');

        assert.end();
    }
});
<commit_msg>test/forward/forwarding-to-down-server: don't sweat the complexity<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.

'use strict';

/* eslint-disable complexity */ // Didn't need it anyway

var CollapsedAssert = require('../lib/collapsed-assert.js');
var allocCluster = require('../lib/test-cluster.js');

allocCluster.test('forwarding to a down service', {
    size: 5,
    whitelist: [
        ['info', 'Refreshing service peer affinity']
    ]
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;
    var steve = cluster.remotes.steve;

    cluster.logger.whitelist('info', 'resetting connection');
    cluster.logger.whitelist('warn', 'error while forwarding');
    cluster.logger.whitelist('warn', 'forwarding error frame');

    cluster.checkExitPeers(assert, {
        serviceName: steve.serviceName,
        hostPort: steve.hostPort
    });

    // Close the service to emulate failure.
    steve.destroy();

    bob.clientChannel.request({
        serviceName: steve.serviceName
    }).send('hi', null, JSON.stringify(null), onForwarded);

    function onForwarded(err, resp, arg2, arg3) {
        /*eslint complexity: [2, 15], max-statements: [2, 40] */
        assert.ok(err, 'forward call should fail');

        assert.equal(err.isErrorFrame, true,
            'forwarding err is an error frame');

        cluster.checkExitPeers(assert, {
            serviceName: steve.serviceName,
            hostPort: steve.hostPort,
            disconnectedHostsPorts: [steve.hostPort]
        });

        // TODO make not flake
        // TODO this should not return a could not find service
        // error. The exit node needs to know the difference
        // between service exists & is down vs service does not exist.
        var message = 'unknown service ' + steve.serviceName;
        if (err.message === message) {
            assert.ok(true, 'skipping flaky test');
            return assert.end();
        }

        assert.ok(
            err.message.indexOf('connect ECONNREFUSED') >= 0 ||
            err.message.indexOf('socket closed') === 0 ||
            err.message === 'connect ECONNREFUSED' ||
            err.message === 'This socket has been ended by the other party',
            'expected error to be a socket closed error'
        );

        var logLines = cluster.logger.items();
        var cassert = CollapsedAssert();
        for (var i = 0; i < logLines.length; i++) {
            var logLine = logLines[i];
            var logErr = logLine.meta.error;
            if (logLine.msg === 'forwarding error frame') {
                cassert.equal(logLine.meta.isErrorFrame, true,
                    'expected error frame');
                cassert.equal(logLine.meta.serviceName, 'steve',
                    'expected steve error');
            } else if (logLine.msg === 'Refreshing service peer affinity') {
                cassert.ok(true, 'expected peer affinity refresh');
            } else if (logLine.msg === 'error while forwarding' ||
                       logLine.msg === 'resetting connection') {
                if (logLine.msg === 'error while forwarding') {
                    cassert.equal(logLine.levelName, 'warn');
                } else if (logLine.msg === 'resetting connection') {
                    cassert.equal(logLine.levelName, 'info');
                }

                var expectedAddr =
                    logErr.socketRemoteAddr === steve.hostPort;
                // if (!expectedAddr) console.error('WRU', steve.hostPort, logErr);
                cassert.ok(expectedAddr, 'expected exception to steve');

                var expectedType =
                    logErr.fullType === 'tchannel.socket~!~error.wrapped-io.connect.ECONNREFUSED' ||
                    logErr.fullType === 'tchannel.socket~!~error.wrapped-io.read.ECONNRESET';
                if (!expectedType) {
                    assert.comment('unexpected error type ' + logErr.fullType);
                }
                cassert.ok(expectedType, 'Expected exception to be network error');
            } else {
                cassert.ok(false, 'unexpected log line');
            }
        }
        cassert.report(assert, 'logs should be correct');

        assert.end();
    }
});
<|endoftext|>


<commit_before>var yaja = typeof yaja === 'undefined' ? {} : yaja;
(function (window, yaja, $, undefined) {

var KEY_CODE = {
  BACKSPACE: 8,
  TAB: 9,
  PAUSE_BREAK: 19,
  CAPS_LOCK: 20,
  SCROLL_LOCK: 145,
  IME: 229
};

function App(config) {
  this.config = $.extend({
    // Define default config values here.
    "shortcuts": {
      "run": "Ctrl+Return",
      "pause": "Ctrl+P",
      "reset": "Ctrl+R"
    }
  }, config);
  this._currentLoopId = 0;
  this._input = $('.yaja-input')[0];
  this._$input = $(this._input);
  var output = this._output = $('.yaja-output')[0];
  this._out = {
    print: function (str) {
      output.value += str;
      output.scrollTop = output.scrollHeight;
    }
  };
  this._interpreter = new yaja.Interpreter();
  this._interpreter.setOut(this._out);
  this._bindListeners();
  this._setStatus('Idle');
  this._updateRuler();
  this._updateCodeSize();
  this._configureLayout();
}

App.prototype.run = function () {
  var status = this._getStatus();
  if (status == 'Running') return;
  this._setStatus('Running');
  if (status == 'Idle' || status == 'Terminated') {
    this.clearOutput();
    this._interpreter.setProgram(this._input.value);
  }
  this._startLoop();
};

App.prototype.pause = function () {
  var status = this._getStatus();
  if (status == 'Paused') return;
  this._setStatus('Paused');
  this._stopLoop();
  if (status == 'Idle') this._interpreter.setProgram(this._input.value);
};

App.prototype.reset = function () {
  if (this._getStatus() == 'Reset') return;
  this._setStatus('Reset');
  this._stopLoop();
  this.clearOutput();
  this._interpreter.setProgram(this._input.value);
};

App.prototype.clearOutput = function () {
  this._output.value = '';
};

App.prototype._bindListeners = function () {
  var self = this,
      shortcuts = this.config.shortcuts,
      actions = {
        "run": {
          func: function () { self.run(); return false; },
          htmlClass: ".yaja-run"
        },
        "pause": {
          func: function () { self.pause(); return false; },
          htmlClass: ".yaja-pause"
        },
        "reset": {
          func: function () { self.reset(); return false; },
          htmlClass: ".yaja-reset"
        }
      };
  for (var name in actions) {
    var act = actions[name],
        button = $(act.htmlClass).click(act.func);
    if (shortcuts[name]) {
      button.attr('title', function () {
        return $(this).text().trim() + ' [' + shortcuts[name] + ']';
      });
      $(window).add('textarea').bind('keydown', shortcuts[name], act.func);
    }
  }
  this._$input.keypress(function (e) {
    // In Firefox, special keys also trigger keypress events; so filter them
    var c = e.which;
    if (e.metaKey || e.altKey || e.ctrlKey ||
        c == KEY_CODE.IME || c == 0 || c == KEY_CODE.BACKSPACE ||
        c == KEY_CODE.TAB || c == KEY_CODE.PAUSE_BREAK ||
        c == KEY_CODE.CAPS_LOCK || c == KEY_CODE.SCROLL_LOCK) {
      return;
    }
    return self._convertKeypressToFullWidth(e.which);
  }).keyup(function () {
    self._updateRuler();
    self._updateCodeSize();
  });
};

App.prototype._getStatus = function () {
  return this._status;
};

App.prototype._setStatus = function (status) {
  this._status = status;
  $('.yaja-status').text(status);
};

App.prototype._startLoop = function () {
  var self = this,
      interpreter = this._interpreter,
      // Prevent multiple calls to _startLoop() from creating as many loops
      // as the calls.
      currentLoopId = ++this._currentLoopId,
      loop = function () {
        if (currentLoopId != self._currentLoopId) return;
        if (interpreter.run(10000)) {  // Terminated
          self._setStatus('Terminated');
        } else {
          setTimeout(loop, 0);
        }
      };
  loop();
};

App.prototype._stopLoop = function () {
  ++this._currentLoopId;
};

App.prototype._getFullWidthChar = function (charCode) {
  if (charCode >= 33 && charCode <= 270) {
    return String.fromCharCode(charCode + 65248);
  } else if (charCode == 32) {
    return String.fromCharCode(12288);
  } else {
    return;  // undefined
  }
};

App.prototype._convertKeypressToFullWidth = function (charCode) {
  var fullWidthChar = this._getFullWidthChar(charCode);
  if (fullWidthChar !== undefined) {
    this._$input.replaceSelectedText(fullWidthChar);
    return false;
  }
};

App.prototype._updateRuler = function () {
  var s = this._$input.getSelection(),
      text;
  if (s.start != s.end) {
    text = (s.end - s.start) + ' characters selected';
  } else {
    var index = s.end,
        lines = this._input.value.substr(0, index).split('\n'),
        line = lines.length,
        col = lines[lines.length - 1].length + 1;
    text = 'Line ' + line + ', Column ' + col;
  }
  $('.yaja-ruler').text(text);
};

App.prototype._updateCodeSize = function () {
  var program = this._input.value,
      lines = this._input.value.split('\n'),
      chars = this._input.value.length - (lines.length - 1),
      height = chars == 0 ? 0 : lines.length,
      width = 0;
  for (var i = 0; i < height; ++i) {
    if (lines[i].length > width) width = lines[i].length;
  }
  $('.yaja-code-size').text(width + 'x' + height + ', ' + chars + ' characters');
};

App.prototype._configureLayout = function () {
  $(document).ready(function () {
    $('body').layout({
      spacing_open: 1,
      north: {
        closable: false,
        resizable: false
      },
      center: {
        fxSpeed: "fast",
        childOptions: {
          center: {
            paneSelector: ".ui-layout-upper-center",
            minSize: 100
          },
          south: {
            paneSelector: ".ui-layout-lower-center",
            size: 200,
            minSize: 100
          }
        }
      },
      south: {
        closable: false,
        resizable: false
      }
    });
  });
};

yaja.App = App;

})(window, yaja, jQuery);
<commit_msg>Allow pause in Running state only<commit_after>var yaja = typeof yaja === 'undefined' ? {} : yaja;
(function (window, yaja, $, undefined) {

var KEY_CODE = {
  BACKSPACE: 8,
  TAB: 9,
  PAUSE_BREAK: 19,
  CAPS_LOCK: 20,
  SCROLL_LOCK: 145,
  IME: 229
};

function App(config) {
  this.config = $.extend({
    // Define default config values here.
    "shortcuts": {
      "run": "Ctrl+Return",
      "pause": "Ctrl+P",
      "reset": "Ctrl+R"
    }
  }, config);
  this._currentLoopId = 0;
  this._input = $('.yaja-input')[0];
  this._$input = $(this._input);
  var output = this._output = $('.yaja-output')[0];
  this._out = {
    print: function (str) {
      output.value += str;
      output.scrollTop = output.scrollHeight;
    }
  };
  this._interpreter = new yaja.Interpreter();
  this._interpreter.setOut(this._out);
  this._bindListeners();
  this._setStatus('Idle');
  this._updateRuler();
  this._updateCodeSize();
  this._configureLayout();
}

App.prototype.run = function () {
  var status = this._getStatus();
  if (status == 'Running') return;
  this._setStatus('Running');
  if (status == 'Idle' || status == 'Terminated') {
    this.clearOutput();
    this._interpreter.setProgram(this._input.value);
  }
  this._startLoop();
};

App.prototype.pause = function () {
  var status = this._getStatus();
  if (status != 'Running') return;
  this._setStatus('Paused');
  this._stopLoop();
};

App.prototype.reset = function () {
  if (this._getStatus() == 'Reset') return;
  this._setStatus('Reset');
  this._stopLoop();
  this.clearOutput();
  this._interpreter.setProgram(this._input.value);
};

App.prototype.clearOutput = function () {
  this._output.value = '';
};

App.prototype._bindListeners = function () {
  var self = this,
      shortcuts = this.config.shortcuts,
      actions = {
        "run": {
          func: function () { self.run(); return false; },
          htmlClass: ".yaja-run"
        },
        "pause": {
          func: function () { self.pause(); return false; },
          htmlClass: ".yaja-pause"
        },
        "reset": {
          func: function () { self.reset(); return false; },
          htmlClass: ".yaja-reset"
        }
      };
  for (var name in actions) {
    var act = actions[name],
        button = $(act.htmlClass).click(act.func);
    if (shortcuts[name]) {
      button.attr('title', function () {
        return $(this).text().trim() + ' [' + shortcuts[name] + ']';
      });
      $(window).add('textarea').bind('keydown', shortcuts[name], act.func);
    }
  }
  this._$input.keypress(function (e) {
    // In Firefox, special keys also trigger keypress events; so filter them
    var c = e.which;
    if (e.metaKey || e.altKey || e.ctrlKey ||
        c == KEY_CODE.IME || c == 0 || c == KEY_CODE.BACKSPACE ||
        c == KEY_CODE.TAB || c == KEY_CODE.PAUSE_BREAK ||
        c == KEY_CODE.CAPS_LOCK || c == KEY_CODE.SCROLL_LOCK) {
      return;
    }
    return self._convertKeypressToFullWidth(e.which);
  }).keyup(function () {
    self._updateRuler();
    self._updateCodeSize();
  });
};

App.prototype._getStatus = function () {
  return this._status;
};

App.prototype._setStatus = function (status) {
  this._status = status;
  $('.yaja-status').text(status);
};

App.prototype._startLoop = function () {
  var self = this,
      interpreter = this._interpreter,
      // Prevent multiple calls to _startLoop() from creating as many loops
      // as the calls.
      currentLoopId = ++this._currentLoopId,
      loop = function () {
        if (currentLoopId != self._currentLoopId) return;
        if (interpreter.run(10000)) {  // Terminated
          self._setStatus('Terminated');
        } else {
          setTimeout(loop, 0);
        }
      };
  loop();
};

App.prototype._stopLoop = function () {
  ++this._currentLoopId;
};

App.prototype._getFullWidthChar = function (charCode) {
  if (charCode >= 33 && charCode <= 270) {
    return String.fromCharCode(charCode + 65248);
  } else if (charCode == 32) {
    return String.fromCharCode(12288);
  } else {
    return;  // undefined
  }
};

App.prototype._convertKeypressToFullWidth = function (charCode) {
  var fullWidthChar = this._getFullWidthChar(charCode);
  if (fullWidthChar !== undefined) {
    this._$input.replaceSelectedText(fullWidthChar);
    return false;
  }
};

App.prototype._updateRuler = function () {
  var s = this._$input.getSelection(),
      text;
  if (s.start != s.end) {
    text = (s.end - s.start) + ' characters selected';
  } else {
    var index = s.end,
        lines = this._input.value.substr(0, index).split('\n'),
        line = lines.length,
        col = lines[lines.length - 1].length + 1;
    text = 'Line ' + line + ', Column ' + col;
  }
  $('.yaja-ruler').text(text);
};

App.prototype._updateCodeSize = function () {
  var program = this._input.value,
      lines = this._input.value.split('\n'),
      chars = this._input.value.length - (lines.length - 1),
      height = chars == 0 ? 0 : lines.length,
      width = 0;
  for (var i = 0; i < height; ++i) {
    if (lines[i].length > width) width = lines[i].length;
  }
  $('.yaja-code-size').text(width + 'x' + height + ', ' + chars + ' characters');
};

App.prototype._configureLayout = function () {
  $(document).ready(function () {
    $('body').layout({
      spacing_open: 1,
      north: {
        closable: false,
        resizable: false
      },
      center: {
        fxSpeed: "fast",
        childOptions: {
          center: {
            paneSelector: ".ui-layout-upper-center",
            minSize: 100
          },
          south: {
            paneSelector: ".ui-layout-lower-center",
            size: 200,
            minSize: 100
          }
        }
      },
      south: {
        closable: false,
        resizable: false
      }
    });
  });
};

yaja.App = App;

})(window, yaja, jQuery);
<|endoftext|>


<commit_before>import dopplerFactor from '../src/dopplerFactor'; // eslint-disable-line

describe('Doppler factor', () => {
  it('doppler factor', () => {
    // TODO:
  });
});
<commit_msg>add tests for dopplerFactor<commit_after>import dopplerFactor from '../src/dopplerFactor'; // eslint-disable-line

const earthRadius = 6378.137;

describe('Doppler factor', () => {
  it('without doppler factor', () => {
    // North Pole
    const observerEcf = {
      x: 0,
      y: 0,
      z: earthRadius
    };
    const positionEcf = {
      x: 0,
      y: 0,
      z: earthRadius + 500
    };
    //Escape velocity
    const velocityEcf = {
      x: 7.91,
      y: 0,
      z: 0
    };
    const dopFactor = dopplerFactor(observerEcf, positionEcf, velocityEcf);
    expect(dopFactor).toEqual(1)
  });

  it("special case", () => {
    const observerEcf = {
      x: earthRadius,
      y: 0,
      z: 0
    };
    const positionEcf = {
      x: (earthRadius + 500) * Math.sqrt(2) / 2, // z*sin(45)
      y: (earthRadius + 500) * Math.sqrt(2) / 2, // z*cos(45)
      z: 0
    };
    const velocityEcf = {
      x: 7.91 * Math.sqrt(2) / 2,
      y: 7.91 * Math.sqrt(2) / 2,
      z: 0
    };
    const dopFactor = dopplerFactor(observerEcf, positionEcf, velocityEcf);
    expect(dopFactor).toEqual(1.0000107847789212)
  });
});
<|endoftext|>


<commit_before>angular.module('dqmv').service('apiConnector', ['$http','$q',
    function($http,$q) {

        $http.defaults.headers.common.Authorization = 'Basic anBpcXVldEB4aXRpLmNvbTp3cWF6ZXI='

        var self = this;
        self.apiUrl = "https://apirest.atinternet-solutions.com/data/v2/json/getData?&columns={d_geo_country,m_visits}&sort={-m_visits}&space={s:429023}&period={R:{D:'-1'}}&max-results=10";

        self.getData = function() {

            var request = $http({
                method: "get",
                url: self.apiUrl,
                params: {
                }
            });

            return( request.then( self.handleSuccess, self.handleError ) );
        };

        // I transform the error response, unwrapping the application dta from
        // the API response payload.
        self.handleError = function(response) {

            // The API response from the server should be returned in a
            // normalized format. However, if the request was not handled by the
            // server (or what not handles properly - ex. server error), then we
            // may have to normalize it on our end, as best we can.
            if (
                ! angular.isObject( response.data ) ||
                ! response.data.message
                ) {

                return( $q.reject( "An unknown error occurred." ) );

            }

            // Otherwise, use expected error message.
            return( $q.reject( response.data.message ) );

        };

        // I transform the successful response, unwrapping the application data
        // from the API response payload.
        self.handleSuccess = function (response) {

            return( response.data );

        };

    }
]);
<commit_msg>modif requete<commit_after>angular.module('dqmv').service('apiConnector', ['$http','$q',
    function($http,$q) {

        $http.defaults.headers.common.Authorization = 'Basic anBpcXVldEB4aXRpLmNvbTp3cWF6ZXI='

        var self = this;
        self.apiUrl = "https://apirest.atinternet-solutions.com/data/v2/json/getData?&columns={d_geo_country,m_visits}&sort={-m_visits}&space={s:429023}&period={R:{D:'-1'}}&max-results=10";

        self.getData = function() {

            var request = $http({
                method: "get",
                url: self.apiUrl,
                params: {
                }
            });

            return( request.then( self.handleSuccess, self.handleError ) );
        };

        // I transform the error response, unwrapping the application dta from
        // the API response payload.
        self.handleError = function(response) {

            // The API response from the server should be returned in a
            // normalized format. However, if the request was not handled by the
            // server (or what not handles properly - ex. server error), then we
            // may have to normalize it on our end, as best we can.
            if (
                ! angular.isObject( response.data ) ||
                ! response.data.message
                ) {

                return( $q.reject( "An unknown error occurred." ) );

            }

            // Otherwise, use expected error message.
            return( $q.reject( response.data.message ) );

        };

        // I transform the successful response, unwrapping the application data
        // from the API response payload.
        self.handleSuccess = function (response) {

            return( response.data );

        };

    }
]);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import SideBar from 'react-sidebar';
import map from 'lodash/map';
import './ValidationBar.scss';

import {
  validateTOS,
  validatePhase,
  validateAction,
  validateRecord
} from '../../../utils/validators';

const styles = {
  sidebar: {
    width: 300,
    height: '100%',
    padding: '10px 0 0 20px',
    backgroundColor: 'white',
    zIndex: '99'
  },
  sidebarLink: {
    display: 'block',
    color: '#757575',
    textDecoration: 'none'
  },
  divider: {
    margin: '8px 0',
    height: 1,
    backgroundColor: '#757575'
  },
  content: {
    height: '100%'
  }
};

export class ValidationBar extends Component {
  constructor (props) {
    super(props);
    this.renderContent = this.renderContent.bind(this);
  }

  generateInvalidAttributes (validate, values) {
    const invalidAttributes = validate(values, this.props.attributeTypes);
    const mappedInvalidAttributes = map(invalidAttributes, (item, index) => (

        {'• '}{this.props.attributeTypes[item].name}

    ));

    if (invalidAttributes.length) {
      return (

          {mappedInvalidAttributes}

      );
    }
  }

  generateAttributeSection (validate, element, index) {
    const invalidAttributes = validate(element, this.props.attributeTypes);

    if (invalidAttributes.length) {
      return (

{element.name}

            {map(invalidAttributes, (item, index) => (

                {'• '}{this.props.attributeTypes[item].name}

            ))}

      );
    }
  }

  renderContent () {
    const { selectedTOS } = this.props;

    const invalidTOSAttributes = this.generateInvalidAttributes(validateTOS, selectedTOS);
    const invalidPhaseAttributes = map(selectedTOS.phases, (phase, index) => (
        this.generateAttributeSection(validatePhase, phase, index)));
    const invalidActionAttributes = map(selectedTOS.actions, (action, index) => (
        this.generateAttributeSection(validateAction, action, index)));
    const invalidRecordAttributes = map(selectedTOS.records, (record, index) => (
        this.generateAttributeSection(validateRecord, record, index)));

    if (invalidTOSAttributes ||
        invalidPhaseAttributes > 0 ||
        invalidActionAttributes > 0 ||
        invalidRecordAttributes > 0) {
      return (

Puuttuvat metatiedot

          {invalidTOSAttributes &&

TOS-metatiedot
}
          {invalidTOSAttributes}
          {invalidPhaseAttributes.length > 0 &&

Käsittelyvaiheet
}
          {invalidPhaseAttributes}
          {invalidActionAttributes.length > 0 &&

Toimenpiteet
}
          {invalidActionAttributes}
          {invalidRecordAttributes.length > 0 &&

Asiakirjat
}
          {invalidRecordAttributes}

      );
    }
    return (

    );
  }

  render () {
    const { children, selectedTOS } = this.props;
    const sidebarContent = selectedTOS.id ? this.renderContent() :
;

    return (

        <SideBar
          sidebar={sidebarContent}
          open={this.props.is_open}
          onSetOpen={() => this.props.setValidationVisibility(false)}
          pullRight={true}
          styles={styles}>
          {children}
        </SideBar>

    );
  }
};

ValidationBar.propTypes = {
  attributeTypes: React.PropTypes.object.isRequired,
  children: React.PropTypes.array.isRequired,
  is_open: React.PropTypes.bool.isRequired,
  selectedTOS: React.PropTypes.object.isRequired,
  setValidationVisibility: React.PropTypes.func.isRequired
};

export default ValidationBar;
<commit_msg>Improve attribute section generation by generalization<commit_after>import React, { Component } from 'react';
import SideBar from 'react-sidebar';
import map from 'lodash/map';
import filter from 'lodash/filter';
import './ValidationBar.scss';

import {
  validateTOS,
  validatePhase,
  validateAction,
  validateRecord
} from '../../../utils/validators';

const styles = {
  sidebar: {
    width: 300,
    height: '100%',
    padding: '10px 0 0 20px',
    backgroundColor: 'white',
    zIndex: '99'
  },
  sidebarLink: {
    display: 'block',
    color: '#757575',
    textDecoration: 'none'
  },
  divider: {
    margin: '8px 0',
    height: 1,
    backgroundColor: '#757575'
  },
  content: {
    height: '100%'
  }
};

export class ValidationBar extends Component {
  constructor (props) {
    super(props);
    this.renderContent = this.renderContent.bind(this);
  }

  generateInvalidAttributes (validate, values) {
    const invalidAttributes = validate(values, this.props.attributeTypes);
    const mappedInvalidAttributes = map(invalidAttributes, (item, index) => (

        {'• '}{this.props.attributeTypes[item].name}

    ));

    if (invalidAttributes.length) {
      return (

          {mappedInvalidAttributes}

      );
    }
  }

  generateAttributeSection (validate, elements) {
    const mappedAttributeSections = map(elements, (element, index) => {
      const invalidAttributes = validate(element, this.props.attributeTypes);

      if (invalidAttributes.length) {
        return (

{element.name}

              {map(invalidAttributes, (item, index) => (

                  {'• '}{this.props.attributeTypes[item].name}

              ))}

        );
      }
    });

    return filter(mappedAttributeSections, (section) => (section !== undefined));
  }

  renderContent () {
    const { selectedTOS } = this.props;

    const invalidTOSAttributes = this.generateInvalidAttributes(validateTOS, selectedTOS);
    const invalidPhaseAttributes = this.generateAttributeSection(validatePhase, selectedTOS.phases);
    const invalidActionAttributes = this.generateAttributeSection(validateAction, selectedTOS.actions);
    const invalidRecordAttributes = this.generateAttributeSection(validateRecord, selectedTOS.records);

    if (invalidTOSAttributes ||
        invalidPhaseAttributes > 0 ||
        invalidActionAttributes > 0 ||
        invalidRecordAttributes > 0) {
      return (

Puuttuvat metatiedot

          {invalidTOSAttributes &&

TOS-metatiedot
}
          {invalidTOSAttributes}
          {invalidPhaseAttributes.length > 0 &&

Käsittelyvaiheet
}
          {invalidPhaseAttributes}
          {invalidActionAttributes.length > 0 &&

Toimenpiteet
}
          {invalidActionAttributes}
          {invalidRecordAttributes.length > 0 &&

Asiakirjat
}
          {invalidRecordAttributes}

      );
    }
    return (

    );
  }

  render () {
    const { children, selectedTOS } = this.props;
    const sidebarContent = selectedTOS.id ? this.renderContent() :
;

    return (

        <SideBar
          sidebar={sidebarContent}
          open={this.props.is_open}
          onSetOpen={() => this.props.setValidationVisibility(false)}
          pullRight={true}
          styles={styles}>
          {children}
        </SideBar>

    );
  }
};

ValidationBar.propTypes = {
  attributeTypes: React.PropTypes.object.isRequired,
  children: React.PropTypes.array.isRequired,
  is_open: React.PropTypes.bool.isRequired,
  selectedTOS: React.PropTypes.object.isRequired,
  setValidationVisibility: React.PropTypes.func.isRequired
};

export default ValidationBar;
<|endoftext|>


<commit_before>var API = function(){

};

API.prototype.api_call = function(url, data, callback) {
  $.ajax({
    url: url,
    data: JSON.stringify(data),
    cache: false,
    contentType: 'application/json',
    type: 'POST',
    success: function(data){
      console.log(data);

      if(data.success || data.success == "true"){
        callback(null, data.response);
      } else {
        callback(data.err, null);
      }
    }
  });
}

API.prototype.institute_get_type = function(type){
  var types = {
    0 : 'Институт информационных технологий'
  };

  return types[type];
}

API.prototype.group_get_all = function(callback){
  this.api_call('/api/group/get/all', {}, function(err, res){
    if(err){
      callback(err, null);
    } else {
      callback(null, res);
    }
  });
}

API.prototype.schedule_get = function(params, callback){
  if(!params) return callback('Invalid parameter1', null);
  if(!params.institute && params.institute != 0) return callback('Invalid parameter2', null);
  if(!params.term) return callback('Invalid parameter3', null);
  if(!params.group) return callback('Invalid parameter4', null);

  this.api_call('/api/schedule/get', params, function(err, res){
    if(err){
      callback(err, null);
    } else {
      callback(null, res);
    }
  });
}
<commit_msg>Added more institute types<commit_after>var API = function(){

};

API.prototype.api_call = function(url, data, callback) {
  $.ajax({
    url: url,
    data: JSON.stringify(data),
    cache: false,
    contentType: 'application/json',
    type: 'POST',
    success: function(data){
      console.log(data);

      if(data.success || data.success == "true"){
        callback(null, data.response);
      } else {
        callback(data.err, null);
      }
    }
  });
}

API.prototype.institute_get_type = function(type){
  var types = {
    0 : 'Институт информационных технологий',
    1 : 'Физико-технологический институт',
    2 : 'Институт инновационных технологий и государственного управления',
    3 : 'Институт кибернетики'
  };

  return types[type];
}

API.prototype.group_get_all = function(callback){
  this.api_call('/api/group/get/all', {}, function(err, res){
    if(err){
      callback(err, null);
    } else {
      callback(null, res);
    }
  });
}

API.prototype.schedule_get = function(params, callback){
  if(!params) return callback('Invalid parameter1', null);
  if(!params.institute && params.institute != 0) return callback('Invalid parameter2', null);
  if(!params.term) return callback('Invalid parameter3', null);
  if(!params.group) return callback('Invalid parameter4', null);

  this.api_call('/api/schedule/get', params, function(err, res){
    if(err){
      callback(err, null);
    } else {
      callback(null, res);
    }
  });
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var sinon = require('sinon');

var LiveChat = require('../../lib/endpoints/livechat');
var Request = require('../../lib/request');

describe('endpoints/livechat', function () {
    describe('closeSession', function () {
        it('should set the request URL', function () {
            var request = new Request();
            var liveChat;
            var stub;

            stub = sinon.stub(request, 'post', function (url) {
                assert.strictEqual(url, '/livechat/closesession');
            });

            liveChat = new LiveChat(request);
            liveChat.closeSession();

            assert.ok(stub.called);
        });

        it('should set the request body', function () {
            var request = new Request();
            var liveChat;
            var stub;
            var expected = {
                sessionid: 1,
            };

            stub = sinon.stub(request, 'post', function (url, data) {
                assert.deepEqual(data, expected);
            });

            liveChat = new LiveChat(request);
            liveChat.closeSession(expected);

            assert.ok(stub.called);
        });
    });

    describe('getMessages', function () {
        it('should set the request URL', function () {
            var request = new Request();
            var liveChat;
            var stub;

            stub = sinon.stub(request, 'post', function (url) {
                assert.strictEqual(url, '/livechat/getmessages');
            });

            liveChat = new LiveChat(request);
            liveChat.getMessages();

            assert.ok(stub.called);
        });

        it('should set the request body', function () {
            var request = new Request();
            var liveChat;
            var stub;
            var expected = {
                sessionid: 1,
            };

            stub = sinon.stub(request, 'post', function (url, data) {
                assert.deepEqual(data, expected);
            });

            liveChat = new LiveChat(request);
            liveChat.getMessages(expected);

            assert.ok(stub.called);
        });
    });

    describe('newSession', function () {
        it('should set the request URL', function () {
            var request = new Request();
            var liveChat;
            var stub;

            stub = sinon.stub(request, 'post', function (url) {
                assert.strictEqual(url, '/livechat/newsession');
            });

            liveChat = new LiveChat(request);
            liveChat.newSession();

            assert.ok(stub.called);
        });

        it('should set the request body', function () {
            var request = new Request();
            var liveChat;
            var stub;
            var expected = {
                name: 'Jonathan',
            };

            stub = sinon.stub(request, 'post', function (url, data) {
                assert.deepEqual(data, expected);
            });

            liveChat = new LiveChat(request);
            liveChat.newSession(expected);

            assert.ok(stub.called);
        });
    });

    describe('postMessage', function () {
        it('should set the request URL', function () {
            var request = new Request();
            var liveChat;
            var stub;

            stub = sinon.stub(request, 'post', function (url) {
                assert.strictEqual(url, '/livechat/postmessage');
            });

            liveChat = new LiveChat(request);
            liveChat.postMessage();

            assert.ok(stub.called);
        });

        it('should set the request body', function () {
            var request = new Request();
            var liveChat;
            var stub;
            var expected = {
                sessionid: 1,
            };

            stub = sinon.stub(request, 'post', function (url, data) {
                assert.deepEqual(data, expected);
            });

            liveChat = new LiveChat(request);
            liveChat.postMessage(expected);

            assert.ok(stub.called);
        });
    });

    describe('sessionInfo', function () {
        it('should set the request URL', function () {
            var request = new Request();
            var liveChat;
            var stub;

            stub = sinon.stub(request, 'post', function (url) {
                assert.strictEqual(url, '/livechat/sessioninfo');
            });

            liveChat = new LiveChat(request);
            liveChat.sessionInfo();

            assert.ok(stub.called);
        });

        it('should set the request body', function () {
            var request = new Request();
            var liveChat;
            var stub;
            var expected = {
                sessionid: 1,
            };

            stub = sinon.stub(request, 'post', function (url, data) {
                assert.deepEqual(data, expected);
            });

            liveChat = new LiveChat(request);
            liveChat.sessionInfo(expected);

            assert.ok(stub.called);
        });
    });

    describe('status', function () {
        it('should set the request URL', function () {
            var request = new Request();
            var liveChat;
            var stub;

            stub = sinon.stub(request, 'get', function (url) {
                assert.strictEqual(url, '/livechat/status');
            });

            liveChat = new LiveChat(request);
            liveChat.status();

            assert.ok(stub.called);
        });
    });
});
<commit_msg>Rewrite LiveChat tests to ES2015<commit_after>'use strict';

const assert = require('assert');
const sinon = require('sinon');

const LiveChat = require('../../lib/endpoints/livechat');
const Request = require('../../lib/request');

describe('endpoints/livechat', () => {
    describe('closeSession', () => {
        it('should set the request URL', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const stub = sinon.stub(request, 'post', (url) => {
                assert.strictEqual(url, '/livechat/closesession');
            });

            liveChat.closeSession();

            assert.ok(stub.called);
        });

        it('should set the request body', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const expected = {
                sessionid: 1,
            };

            const stub = sinon.stub(request, 'post', (url, data) => {
                assert.deepEqual(data, expected);
            });

            liveChat.closeSession(expected);

            assert.ok(stub.called);
        });
    });

    describe('getMessages', () => {
        it('should set the request URL', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const stub = sinon.stub(request, 'post', (url) => {
                assert.strictEqual(url, '/livechat/getmessages');
            });

            liveChat.getMessages();

            assert.ok(stub.called);
        });

        it('should set the request body', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const expected = {
                sessionid: 1,
            };

            const stub = sinon.stub(request, 'post', (url, data) => {
                assert.deepEqual(data, expected);
            });

            liveChat.getMessages(expected);

            assert.ok(stub.called);
        });
    });

    describe('newSession', () => {
        it('should set the request URL', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const stub = sinon.stub(request, 'post', (url) => {
                assert.strictEqual(url, '/livechat/newsession');
            });

            liveChat.newSession();

            assert.ok(stub.called);
        });

        it('should set the request body', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const expected = {
                name: 'Jonathan',
            };

            const stub = sinon.stub(request, 'post', (url, data) => {
                assert.deepEqual(data, expected);
            });

            liveChat.newSession(expected);

            assert.ok(stub.called);
        });
    });

    describe('postMessage', () => {
        it('should set the request URL', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const stub = sinon.stub(request, 'post', (url) => {
                assert.strictEqual(url, '/livechat/postmessage');
            });

            liveChat.postMessage();

            assert.ok(stub.called);
        });

        it('should set the request body', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const expected = {
                sessionid: 1,
            };

            const stub = sinon.stub(request, 'post', (url, data) => {
                assert.deepEqual(data, expected);
            });

            liveChat.postMessage(expected);

            assert.ok(stub.called);
        });
    });

    describe('sessionInfo', () => {
        it('should set the request URL', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const stub = sinon.stub(request, 'post', (url) => {
                assert.strictEqual(url, '/livechat/sessioninfo');
            });

            liveChat.sessionInfo();

            assert.ok(stub.called);
        });

        it('should set the request body', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const expected = {
                sessionid: 1,
            };

            const stub = sinon.stub(request, 'post', (url, data) => {
                assert.deepEqual(data, expected);
            });

            liveChat.sessionInfo(expected);

            assert.ok(stub.called);
        });
    });

    describe('status', () => {
        it('should set the request URL', () => {
            const request = new Request();
            const liveChat = new LiveChat(request);
            const stub = sinon.stub(request, 'get', (url) => {
                assert.strictEqual(url, '/livechat/status');
            });

            liveChat.status();

            assert.ok(stub.called);
        });
    });
});
<|endoftext|>