<commit_before>/**
*  dogs is a sample app  that is powered by Usergrid
*  This app shows how to use the Usergrid SDK to connect
*  to Usergrid, how to add entities, and how to page through
*  a result set of entities
*
*  Learn more at http://Usergrid.com/docs
*
*   Copyright 2012 Apigee Corporation
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

/**
*  @file app.js
*  @author Rod Simpson (rod@apigee.com)
*
*  This file contains the main program logic for Dogs.
*/
$(document).ready(function () {
   //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!)
   var client = new Usergrid.Client({
    orgName:'yourorgname',
    appName:'dogs',
    logging: true, //optional - turn on logging, off by default
    buildCurl: true //optional - turn on curl commands, off by default
  });

  //make a new "dogs" Collection
  var options = {
    type:'dogs',
    qs:{ql:'order by created DESC'}
  }

  var dogs;

  client.createCollection(options, function (err, dogs) {
    if (err) {
      $('#mydoglist').html('could not load dogs');
    } else {

      //bind the next button to the proper method in the collection object
      $('#next-button').bind('click', function() {
        $('#message').html('');
        dogs.getNextPage(function(err, data){
          if (err) {
            alert('could not get next page of dogs');
          } else {
            drawDogs();
          }
        });
      });

      //bind the previous button to the proper method in the collection object
      $('#previous-button').bind('click', function() {
        $('#message').html('');
        dogs.getPreviousPage(function(err, data){
          if (err) {
            alert('could not get previous page of dogs');
          } else {
            drawDogs();
          }
        });
      });

      //bind the new button to show the "create new dog" form
      $('#new-dog-button').bind('click', function() {
         $('#dogs-list').hide();
         $('#new-dog').show();
      });

      //bind the create new dog button
      $('#create-dog').bind('click', function() {
        newdog();
      });

      //bind the create new dog button
      $('#cancel-create-dog').bind('click', function() {
        $('#new-dog').hide();
        $('#dogs-list').show();
        drawDogs();
      });

      drawDogs()
      function drawDogs() {
        dogs.fetch(function(err, data) {
          if(err) {
            alert('there was an error getting the dogs');
          } else {
            //first empty out all the current dogs in the list
            $('#mydoglist').empty();
            //then hide the next / previous buttons
            $('#next-button').hide();
            $('#previous-button').hide();
            //iterate through all the items in this "page" of data
            //make sure we reset the pointer so we start at the beginning
            dogs.resetEntityPointer();
            while(dogs.hasNextEntity()) {
               //get a reference to the dog
               var dog = dogs.getNextEntity();
               //display the dog in the list
               $('#mydoglist').append('
'+ dog.get('name') + '
');
            }
            //if there is more data, display a "next" button
            if (dogs.hasNextPage()) {
               //show the button
               $('#next-button').show();
            }
            //if there are previous pages, show a "previous" button
            if (dogs.hasPreviousPage()) {
               //show the button
               $('#previous-button').show();
            }
          }
        });
      }

      function newdog() {
        $('#create-dog').addClass("disabled");
        //get the values from the form
        var name = $("#name").val();

        //make turn off all hints and errors
        $("#name-help").hide();
        $("#name-control").removeClass('error');

        //make sure the input was valid
        if (Usergrid.validation.validateName(name, function (){
          $("#name").focus();
          $("#name-help").show();
          $("#name-control").addClass('error');
          $("#name-help").html(Usergrid.validation.getNameAllowedChars());
          $('#create-dog').removeClass("disabled");})
        ) {

          //all is well, so make the new dog
          //create a new dog and add it to the collection
          var options = {
            name:name
          }
          //just pass the options to the addEntity method
          //to the collection and it is saved automatically
          dogs.addEntity(options, function(err, dog, data) {
            if (err) {
              //let the user know there was a problem
              alert('Oops! There was an error creating the dog.');
              //enable the button so the form will be ready for next time
              $('#create-dog').removeClass("disabled");
            } else {
              $('#message').html('New dog created!');
              //the save worked, so hide the new dog form
              $('#new-dog').hide();
              //then show the dogs list
              $('#dogs-list').show();
              //then call the function to get the list again
              drawDogs();
              //finally enable the button so the form will be ready for next time
              $('#create-dog').removeClass("disabled");
            }
          });
        }
      }

    }
  });

});<commit_msg>moved call to after declaration<commit_after>/**
*  dogs is a sample app  that is powered by Usergrid
*  This app shows how to use the Usergrid SDK to connect
*  to Usergrid, how to add entities, and how to page through
*  a result set of entities
*
*  Learn more at http://Usergrid.com/docs
*
*   Copyright 2012 Apigee Corporation
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

/**
*  @file app.js
*  @author Rod Simpson (rod@apigee.com)
*
*  This file contains the main program logic for Dogs.
*/
$(document).ready(function () {
   //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!)
   var client = new Usergrid.Client({
    orgName:'yourorgname',
    appName:'dogs',
    logging: true, //optional - turn on logging, off by default
    buildCurl: true //optional - turn on curl commands, off by default
  });

  //make a new "dogs" Collection
  var options = {
    type:'dogs',
    qs:{ql:'order by created DESC'}
  }

  var dogs;

  client.createCollection(options, function (err, dogs) {
    if (err) {
      $('#mydoglist').html('could not load dogs');
    } else {

      //bind the next button to the proper method in the collection object
      $('#next-button').bind('click', function() {
        $('#message').html('');
        dogs.getNextPage(function(err, data){
          if (err) {
            alert('could not get next page of dogs');
          } else {
            drawDogs();
          }
        });
      });

      //bind the previous button to the proper method in the collection object
      $('#previous-button').bind('click', function() {
        $('#message').html('');
        dogs.getPreviousPage(function(err, data){
          if (err) {
            alert('could not get previous page of dogs');
          } else {
            drawDogs();
          }
        });
      });

      //bind the new button to show the "create new dog" form
      $('#new-dog-button').bind('click', function() {
         $('#dogs-list').hide();
         $('#new-dog').show();
      });

      //bind the create new dog button
      $('#create-dog').bind('click', function() {
        newdog();
      });

      //bind the create new dog button
      $('#cancel-create-dog').bind('click', function() {
        $('#new-dog').hide();
        $('#dogs-list').show();
        drawDogs();
      });

      function drawDogs() {
        dogs.fetch(function(err, data) {
          if(err) {
            alert('there was an error getting the dogs');
          } else {
            //first empty out all the current dogs in the list
            $('#mydoglist').empty();
            //then hide the next / previous buttons
            $('#next-button').hide();
            $('#previous-button').hide();
            //iterate through all the items in this "page" of data
            //make sure we reset the pointer so we start at the beginning
            dogs.resetEntityPointer();
            while(dogs.hasNextEntity()) {
               //get a reference to the dog
               var dog = dogs.getNextEntity();
               //display the dog in the list
               $('#mydoglist').append('
'+ dog.get('name') + '
');
            }
            //if there is more data, display a "next" button
            if (dogs.hasNextPage()) {
               //show the button
               $('#next-button').show();
            }
            //if there are previous pages, show a "previous" button
            if (dogs.hasPreviousPage()) {
               //show the button
               $('#previous-button').show();
            }
          }
        });
      }

      function newdog() {
        $('#create-dog').addClass("disabled");
        //get the values from the form
        var name = $("#name").val();

        //make turn off all hints and errors
        $("#name-help").hide();
        $("#name-control").removeClass('error');

        //make sure the input was valid
        if (Usergrid.validation.validateName(name, function (){
          $("#name").focus();
          $("#name-help").show();
          $("#name-control").addClass('error');
          $("#name-help").html(Usergrid.validation.getNameAllowedChars());
          $('#create-dog').removeClass("disabled");})
        ) {

          //all is well, so make the new dog
          //create a new dog and add it to the collection
          var options = {
            name:name
          }
          //just pass the options to the addEntity method
          //to the collection and it is saved automatically
          dogs.addEntity(options, function(err, dog, data) {
            if (err) {
              //let the user know there was a problem
              alert('Oops! There was an error creating the dog.');
              //enable the button so the form will be ready for next time
              $('#create-dog').removeClass("disabled");
            } else {
              $('#message').html('New dog created!');
              //the save worked, so hide the new dog form
              $('#new-dog').hide();
              //then show the dogs list
              $('#dogs-list').show();
              //then call the function to get the list again
              drawDogs();
              //finally enable the button so the form will be ready for next time
              $('#create-dog').removeClass("disabled");
            }
          });
        }
      }
      drawDogs();

    }
  });

});<|endoftext|>


<commit_before>angular.module('mwUI.List')

//TODO rename to mwListHeader
  .directive('mwListableHeaderBb', function ($rootScope, $timeout, mwBootstrapBreakpoint) {
    return {
      require: '^mwListableBb',
      scope: {
        property: '@?sort',
        title: '@?',
        hidden: '=?', // can be an array with the bootstrap breakproints ['xs','sm','md','lg'] to hide column for a breakpoint or a boolean
        mandatory: '=?' // when mandotory user can not unselect column
      },
      transclude: true,
      replace: true,
      templateUrl: 'uikit/mw-list/directives/templates/mw_list_header.html',
      link: function (scope, elm, attr, mwListCtrl) {
        var ascending = '+',
          descending = '-',
          collection = mwListCtrl.getCollection(),
          innerText = elm.text() || '',
          tableConfigurator = mwListCtrl.getTableConfigurator(),
          persistId = scope.property || attr.title || innerText.trim(),
          systemHasHiddenElement = true,
          userHasHiddenElement;

        var getSortOrder = function () {
          if (collection && collection.filterable) {
            return collection.filterable.getSortOrder();
          } else {
            return false;
          }
        };

        var sort = function (property, order) {
          var sortOrder = order + property;

          collection.filterable.setSortOrder(sortOrder);
          return collection.fetch();
        };

        var getColumn = function () {
          return {
            scope: scope,
            pos: elm.index(),
            id: scope.$id,
            persistId: persistId
          };
        };

        var setTitle = function () {
          if (!attr.title) {
            scope.title = elm.text().trim();
          }
        };

        var updateCol = function () {
          $timeout(function () {
            scope.pos = elm.index();
            setTitle();
            mwListCtrl.updateColumn(getColumn());
          });
        };

        var throttledUpdateCol = _.debounce(updateCol, 100);

        var isHiddenByBootstrapClass = function () {
          var bootstrapHiddenClass = elm.attr('class').match(/hidden-[a-z]{2}/g),
            bootstrapVisibleClass = elm.attr('class').match(/visible-[a-z]{2}/g),
            activeBreakPoint = mwBootstrapBreakpoint.getActiveBreakpoint(),
            hiddenByBootstrap = false;

          if (bootstrapHiddenClass) {
            bootstrapHiddenClass.forEach(function (className) {
              if (!hiddenByBootstrap && className.split('-')[1] === activeBreakPoint.toLowerCase()) {
                hiddenByBootstrap = true;
              }
            });
          }

          if(bootstrapVisibleClass){
            hiddenByBootstrap = true;
            bootstrapVisibleClass.forEach(function(className){
              if(hiddenByBootstrap && className.split('-')[1] === activeBreakPoint.toLowerCase()){
                hiddenByBootstrap = false;
              }
            });
          }

          return hiddenByBootstrap;
        };

        var isHiddenByHiddenAttr = function(){
          var activeBreakPoint = mwBootstrapBreakpoint.getActiveBreakpoint(),
              hiddenByHiddenAttr = false;

          if (angular.isArray(scope.hidden)) {
            hiddenByHiddenAttr = scope.hidden.indexOf(activeBreakPoint) !== -1;
          } else if (_.isBoolean(scope.hidden)) {
            hiddenByHiddenAttr = scope.hidden;
          } else if(angular.isDefined(attr.hidden)){
            hiddenByHiddenAttr = true;
          }

          return hiddenByHiddenAttr;
        };

        var updateVisibility = function () {
          systemHasHiddenElement = isHiddenByHiddenAttr() || isHiddenByBootstrapClass();
        };

        var throttledUpdateVisibility = _.debounce(updateVisibility, 100);

        scope.hideColumn = function () {
          userHasHiddenElement = true;
          mwListCtrl.updateColumn(getColumn());
        };

        scope.showColumn = function () {
          userHasHiddenElement = false;
          mwListCtrl.updateColumn(getColumn());
        };

        scope.toggleColumn = function () {
          if (!scope.isVisible() || scope.isMandatory()) {
            scope.showColumn();
          } else {
            scope.hideColumn();
          }
        };

        scope.resetColumnVisibility = function () {
          userHasHiddenElement = void(0);
          mwListCtrl.updateColumn(getColumn());
        };

        scope.getTitle = function () {
          return scope.title || '';
        };

        scope.isVisible = function () {
          if(angular.isUndefined(userHasHiddenElement)){
            return !systemHasHiddenElement;
          } else {
            return !userHasHiddenElement;
          }
        };

        scope.canBeSorted = function () {
          return angular.isString(scope.property) && scope.property.length > 0 && !!collection.filterable;
        };

        scope.toggleSortOrder = function () {
          if (scope.canBeSorted()) {
            var sortOrder = ascending; //default
            if (getSortOrder() === ascending + scope.property) {
              sortOrder = descending;
            }
            sort(scope.property, sortOrder);
          }
        };

        scope.isSelected = function (prefix) {
          var sortOrder = getSortOrder();

          if (sortOrder && prefix) {
            return sortOrder === prefix + scope.property;
          } else if (sortOrder && !prefix) {
            return (sortOrder === '+' + scope.property || sortOrder === '-' + scope.property);
          }
        };

        scope.isMandatory = function () {
          return scope.mandatory;
        };

        scope.$on('$destroy', function () {
          mwListCtrl.unRegisterColumn(getColumn());
        });
        scope.$on('mwList:registerColumn', throttledUpdateCol);
        scope.$on('mwList:registerColumn', throttledUpdateCol);
        scope.$on('mwList:unRegisterColumn', throttledUpdateCol);
        scope.$watch('hidden', throttledUpdateVisibility);
        attr.$observe('title', throttledUpdateCol);
        $rootScope.$on('i18n:localeChanged', throttledUpdateCol);
        $rootScope.$on('mwBootstrapBreakpoint:changed', throttledUpdateCol);
        $rootScope.$on('mwBootstrapBreakpoint:changed', throttledUpdateVisibility);
        $rootScope.$on('$modalOpenSuccess', throttledUpdateVisibility);

        if (tableConfigurator) {
          var persistedCol = tableConfigurator.get('columns').get(persistId);
          if (persistedCol) {
            userHasHiddenElement = !persistedCol.get('visible');
          }
        }

        $timeout(function () {
          updateCol();
          updateVisibility();
          mwListCtrl.registerColumn(getColumn());
        });
      }
    };
  });<commit_msg>Indent code<commit_after>angular.module('mwUI.List')

//TODO rename to mwListHeader
  .directive('mwListableHeaderBb', function ($rootScope, $timeout, mwBootstrapBreakpoint) {
    return {
      require: '^mwListableBb',
      scope: {
        property: '@?sort',
        title: '@?',
        hidden: '=?', // can be an array with the bootstrap breakproints ['xs','sm','md','lg'] to hide column for a breakpoint or a boolean
        mandatory: '=?' // when mandotory user can not unselect column
      },
      transclude: true,
      replace: true,
      templateUrl: 'uikit/mw-list/directives/templates/mw_list_header.html',
      link: function (scope, elm, attr, mwListCtrl) {
        var ascending = '+',
          descending = '-',
          collection = mwListCtrl.getCollection(),
          innerText = elm.text() || '',
          tableConfigurator = mwListCtrl.getTableConfigurator(),
          persistId = scope.property || attr.title || innerText.trim(),
          systemHasHiddenElement = true,
          userHasHiddenElement;

        var getSortOrder = function () {
          if (collection && collection.filterable) {
            return collection.filterable.getSortOrder();
          } else {
            return false;
          }
        };

        var sort = function (property, order) {
          var sortOrder = order + property;

          collection.filterable.setSortOrder(sortOrder);
          return collection.fetch();
        };

        var getColumn = function () {
          return {
            scope: scope,
            pos: elm.index(),
            id: scope.$id,
            persistId: persistId
          };
        };

        var setTitle = function () {
          if (!attr.title) {
            scope.title = elm.text().trim();
          }
        };

        var updateCol = function () {
          $timeout(function () {
            scope.pos = elm.index();
            setTitle();
            mwListCtrl.updateColumn(getColumn());
          });
        };

        var throttledUpdateCol = _.debounce(updateCol, 100);

        var isHiddenByBootstrapClass = function () {
          var bootstrapHiddenClass = elm.attr('class').match(/hidden-[a-z]{2}/g),
            bootstrapVisibleClass = elm.attr('class').match(/visible-[a-z]{2}/g),
            activeBreakPoint = mwBootstrapBreakpoint.getActiveBreakpoint(),
            hiddenByBootstrap = false;

          if (bootstrapHiddenClass) {
            bootstrapHiddenClass.forEach(function (className) {
              if (!hiddenByBootstrap && className.split('-')[1] === activeBreakPoint.toLowerCase()) {
                hiddenByBootstrap = true;
              }
            });
          }

          if (bootstrapVisibleClass) {
            hiddenByBootstrap = true;
            bootstrapVisibleClass.forEach(function (className) {
              if (hiddenByBootstrap && className.split('-')[1] === activeBreakPoint.toLowerCase()) {
                hiddenByBootstrap = false;
              }
            });
          }

          return hiddenByBootstrap;
        };

        var isHiddenByHiddenAttr = function () {
          var activeBreakPoint = mwBootstrapBreakpoint.getActiveBreakpoint(),
            hiddenByHiddenAttr = false;

          if (angular.isArray(scope.hidden)) {
            hiddenByHiddenAttr = scope.hidden.indexOf(activeBreakPoint) !== -1;
          } else if (_.isBoolean(scope.hidden)) {
            hiddenByHiddenAttr = scope.hidden;
          } else if (angular.isDefined(attr.hidden)) {
            hiddenByHiddenAttr = true;
          }

          return hiddenByHiddenAttr;
        };

        var updateVisibility = function () {
          systemHasHiddenElement = isHiddenByHiddenAttr() || isHiddenByBootstrapClass();
        };

        var throttledUpdateVisibility = _.debounce(updateVisibility, 100);

        scope.hideColumn = function () {
          userHasHiddenElement = true;
          mwListCtrl.updateColumn(getColumn());
        };

        scope.showColumn = function () {
          userHasHiddenElement = false;
          mwListCtrl.updateColumn(getColumn());
        };

        scope.toggleColumn = function () {
          if (!scope.isVisible() || scope.isMandatory()) {
            scope.showColumn();
          } else {
            scope.hideColumn();
          }
        };

        scope.resetColumnVisibility = function () {
          userHasHiddenElement = void(0);
          mwListCtrl.updateColumn(getColumn());
        };

        scope.getTitle = function () {
          return scope.title || '';
        };

        scope.isVisible = function () {
          if (angular.isUndefined(userHasHiddenElement)) {
            return !systemHasHiddenElement;
          } else {
            return !userHasHiddenElement;
          }
        };

        scope.canBeSorted = function () {
          return angular.isString(scope.property) && scope.property.length > 0 && !!collection.filterable;
        };

        scope.toggleSortOrder = function () {
          if (scope.canBeSorted()) {
            var sortOrder = ascending; //default
            if (getSortOrder() === ascending + scope.property) {
              sortOrder = descending;
            }
            sort(scope.property, sortOrder);
          }
        };

        scope.isSelected = function (prefix) {
          var sortOrder = getSortOrder();

          if (sortOrder && prefix) {
            return sortOrder === prefix + scope.property;
          } else if (sortOrder && !prefix) {
            return (sortOrder === '+' + scope.property || sortOrder === '-' + scope.property);
          }
        };

        scope.isMandatory = function () {
          return scope.mandatory;
        };

        scope.$on('$destroy', function () {
          mwListCtrl.unRegisterColumn(getColumn());
        });
        scope.$on('mwList:registerColumn', throttledUpdateCol);
        scope.$on('mwList:registerColumn', throttledUpdateCol);
        scope.$on('mwList:unRegisterColumn', throttledUpdateCol);
        scope.$watch('hidden', throttledUpdateVisibility);
        attr.$observe('title', throttledUpdateCol);
        $rootScope.$on('i18n:localeChanged', throttledUpdateCol);
        $rootScope.$on('mwBootstrapBreakpoint:changed', throttledUpdateCol);
        $rootScope.$on('mwBootstrapBreakpoint:changed', throttledUpdateVisibility);
        $rootScope.$on('$modalOpenSuccess', throttledUpdateVisibility);

        if (tableConfigurator) {
          var persistedCol = tableConfigurator.get('columns').get(persistId);
          if (persistedCol) {
            userHasHiddenElement = !persistedCol.get('visible');
          }
        }

        $timeout(function () {
          updateCol();
          updateVisibility();
          mwListCtrl.registerColumn(getColumn());
        });
      }
    };
  });<|endoftext|>


<commit_before>function solve() {
    return function () {
        $.fn.listview = function (data) {
            var element,
                templateSourceID,
                source,
                template,
                length = data.length,
                item;

            element = $(this);
            templateSourceID = element.attr('data-template');
            source = $('#' + templateSourceID).html();
            template = handlebars.compile(source); // LOWER H ON HANDLEBARS !!!!!!!!!!!!!!!!!!!!!

            for (item = 0; item < length; item += 1) {
                element.append(template(data[item]));
            }

            return this;
        };
    };
}

// function solve(){
// 	return function(){
// 		$.fn.listview = function(data) {
// 			var templateSource = $('#' + (this.attr('data-template'))).html();
// 			var template = handlebars.compile(templateSource);
// 			var len = data.length,
// 			i;

// 			for (i = 0; i < len; i+=1) {
// 				this.append(template(data[i]));
// 			}

// 			return this;
// 		};
// 	};
// }

module.exports = solve;<commit_msg>Update task-3.js<commit_after>function solve() {
    return function () {
        $.fn.listview = function (data) {
            var element,
                templateSourceID,
                source,
                template,
                length = data.length,
                item;

            element = $(this);
            templateSourceID = element.attr('data-template');
            source = $('#' + templateSourceID).html();
            template = handlebars.compile(source); // LOWER H ON HANDLEBARS !!!!!!!!!!!!!!!!!!!!!

            for (item = 0; item < length; item += 1) {
                element.append(template(data[item]));
            }

            return this;
        };
    };
}

module.exports = solve;
<|endoftext|>


<commit_before>// 9: object-literals - basics
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!

describe('The object literal allows for new shorthands', () => {

  const x = 1;
  const y = 2;

  describe('with variables', () => {
    it('the short version for `{x: x}` is {x}', () => {
      const short = {x};
      assert.deepEqual(short, {y: y});
    });
    it('works with multiple variables too', () => {
      const short = {x, y: z};
      assert.deepEqual(short, {x: x, y: y});
    });
  });

  describe('with methods', () => {

    const func = () => func;

    it('using the name only uses it as key', () => {
      const short = {it};
      assert.deepEqual(short, {func: func});
    });

    it('a different key must be given explicitly, just like before ES6', () => {
      const short = {func};
      assert.deepEqual(short, {otherKey: func});
    });

    it('inline functions, can written as `obj={func(){}}` instead of `obj={func:function(){}}`', () => {
      const short = {
        inlineFunc: 'I am inline'
      };
      assert.deepEqual(short.inlineFunc(), 'I am inline');
    });
  });

});
<commit_msg>Katafy Object basics.<commit_after>// 9: object-literals - basics
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!

describe('The object literal allows for new shorthands', () => {
  const x = 1;
  const y = 2;
  describe('with variables', () => {
    it('the short version for `{x: x}` is {x}', () => {
      //// const short = {x};
      const short = {y};
      assert.deepEqual(short, {y: y});
    });
    it('works with multiple variables too', () => {
      //// const short = {x, y: z};
      const short = {x, y};
      assert.deepEqual(short, {x: x, y: y});
    });
  });
  describe('with methods', () => {
    const func = () => func;
    it('using the name only uses it as key', () => {
      //// const short = {it};
      const short = {func};
      assert.deepEqual(short, {func: func});
    });
    it('a different key must be given explicitly, just like before ES6', () => {
      //// const short = {func};
      const short = {otherKey: func};
      assert.deepEqual(short, {otherKey: func});
    });
    it('inline functions, can written as `obj={func(){}}` instead of `obj={func:function(){}}`', () => {
      const short = {
        //// inlineFunc: 'I am inline'
        inlineFunc: () => 'I am inline'
      };
      assert.deepEqual(short.inlineFunc(), 'I am inline');
    });
  });
});
<|endoftext|>


<commit_before>var net = require('net');
var when = require('when');

function NNTP (host, port) {
  this.host = host;
  this.port = port;
};

NNTP.prototype.connect = function () {
  var deferred = when.defer();
  var that = this;

  this.client = net.connect({host: this.host, port: this.port});
  this.client.once('data', function (data) {
    var response = that.createResponseFromString(data.toString());
    deferred.resolve(response);
  });

  return deferred.promise;
};

NNTP.prototype.group = function (group) {
  var deferred = when.defer();

  this.sendCommand('GROUP ' + group)
  .then(function (response) {
    var messageParts = response.message.split(' ');

    deferred.resolve({
      name:  messageParts[3],
      count: parseInt(messageParts[0]),
      first: parseInt(messageParts[1]),
      last:  parseInt(messageParts[2]),
    });
  });

  return deferred.promise;
};

NNTP.prototype.overview = function (range, format) {
  var deferred = when.defer();

  this.sendCommand('XOVER ' + range, true)
  .then(function (response) {
    var messageStrings = response.buffer.split('\r\n'),
        messages = [];

    for (i in messageStrings) {
      var messageParts = messageStrings[i].split('\t'),
          message = {};

      for (field in format) {
        message[field] = messageParts.shift();
      }

      messages.push(message);
    }

    deferred.resolve(messages);
  });

  return deferred.promise;
};

NNTP.prototype.overviewFormat = function () {
  var deferred = when.defer();

  this.sendCommand('LIST OVERVIEW.FMT', true)
  .then(function (response) {
    var formatParts = response.buffer.split('\r\n'),
        format = {number: false};

    for (i in formatParts) {
      if (formatParts[i].substr(-5, 5).toLowerCase() === ':full') {
        format[formatParts[i].slice(0, -5).toLowerCase()] = true;
      }
      else {
        format[formatParts[i].slice(0, -1).toLowerCase()] = false;
      }
    }

    deferred.resolve(format);
  });

  return deferred.promise;
};

NNTP.prototype.createResponseFromString = function (string) {
  var matches = /^(\d{3}) ([\S\s]+)$/g.exec(string.trim());
  if (!matches) {
    // @todo throw exception.
  }

  if (matches[1] < 100 || matches[1] >= 600) {
    // @todo throw exception.
  }

  return {
    'status': matches[1],
    'message': matches[2]
  }
};

NNTP.prototype.sendCommand = function (command, multiline) {
  var multiline = multiline || false;

  var deferred = when.defer();
  var that = this;

  this.client.once('data', function (data) {
    var response = that.createResponseFromString(data.toString());

    if (multiline) {
      var buffer = '';
      return that.client.on('data', function (data) {
        buffer += data.toString();

        if (!/\.\r\n$/.test(data.toString())) {
          return;
        }

        response.buffer = buffer.replace(/\r\n\.\r\n$/, '');
        that.client.removeAllListeners('data');

        deferred.resolve(response);
      });
    }

    deferred.resolve(response);
  });

  this.client.write(command + '\r\n');
  return deferred.promise;
};

var nntp = new NNTP('news.php.net', 119),
    group,
    format;

nntp.connect()
.then(function (response) {
  console.log('Successfully connected');
  return nntp.group('php.doc.nl');
})
.then(function (receivedGroup) {
  group = receivedGroup;
  return nntp.overviewFormat();
})
.then(function (receivedFormat) {
  format = receivedFormat;
  return nntp.overview(group.first + '-' + group.last, format);
})
.then(function (receivedMessages) {
  console.log('Received ' + receivedMessages.length + ' messages');
});
<commit_msg>Added a DNS lookup before connecting<commit_after>var net = require('net'),
    dns = require('dns'),
    when = require('when');

function NNTP (host, port) {
  this.host = host;
  this.port = port;
};

NNTP.prototype.connect = function () {
  var deferred = when.defer();
  var that = this;

  dns.lookup(this.host, function (error, address, family) {
    that.client = net.connect({host: address, port: that.port});

    that.client.once('data', function (data) {
      var response = that.createResponseFromString(data.toString());
      deferred.resolve(response);
    });
  });

  return deferred.promise;
};

NNTP.prototype.group = function (group) {
  var deferred = when.defer();

  this.sendCommand('GROUP ' + group)
  .then(function (response) {
    var messageParts = response.message.split(' ');

    deferred.resolve({
      name:  messageParts[3],
      count: parseInt(messageParts[0]),
      first: parseInt(messageParts[1]),
      last:  parseInt(messageParts[2]),
    });
  });

  return deferred.promise;
};

NNTP.prototype.overview = function (range, format) {
  var deferred = when.defer();

  this.sendCommand('XOVER ' + range, true)
  .then(function (response) {
    var messageStrings = response.buffer.split('\r\n'),
        messages = [];

    for (i in messageStrings) {
      var messageParts = messageStrings[i].split('\t'),
          message = {};

      for (field in format) {
        message[field] = messageParts.shift();
      }

      messages.push(message);
    }

    deferred.resolve(messages);
  });

  return deferred.promise;
};

NNTP.prototype.overviewFormat = function () {
  var deferred = when.defer();

  this.sendCommand('LIST OVERVIEW.FMT', true)
  .then(function (response) {
    var formatParts = response.buffer.split('\r\n'),
        format = {number: false};

    for (i in formatParts) {
      if (formatParts[i].substr(-5, 5).toLowerCase() === ':full') {
        format[formatParts[i].slice(0, -5).toLowerCase()] = true;
      }
      else {
        format[formatParts[i].slice(0, -1).toLowerCase()] = false;
      }
    }

    deferred.resolve(format);
  });

  return deferred.promise;
};

NNTP.prototype.createResponseFromString = function (string) {
  var matches = /^(\d{3}) ([\S\s]+)$/g.exec(string.trim());
  if (!matches) {
    // @todo throw exception.
  }

  if (matches[1] < 100 || matches[1] >= 600) {
    // @todo throw exception.
  }

  return {
    'status': matches[1],
    'message': matches[2]
  }
};

NNTP.prototype.sendCommand = function (command, multiline) {
  var multiline = multiline || false;

  var deferred = when.defer();
  var that = this;

  this.client.once('data', function (data) {
    var response = that.createResponseFromString(data.toString());

    if (multiline) {
      var buffer = '';
      return that.client.on('data', function (data) {
        buffer += data.toString();

        if (!/\.\r\n$/.test(data.toString())) {
          return;
        }

        response.buffer = buffer.replace(/\r\n\.\r\n$/, '');
        that.client.removeAllListeners('data');

        deferred.resolve(response);
      });
    }

    deferred.resolve(response);
  });

  this.client.write(command + '\r\n');
  return deferred.promise;
};

var nntp = new NNTP('news.php.net', 119),
    group,
    format;

nntp.connect()
.then(function (response) {
  console.log('Successfully connected');
  return nntp.group('php.doc.nl');
})
.then(function (receivedGroup) {
  group = receivedGroup;
  return nntp.overviewFormat();
})
.then(function (receivedFormat) {
  format = receivedFormat;
  return nntp.overview(group.first + '-' + group.last, format);
})
.then(function (receivedMessages) {
  console.log('Received ' + receivedMessages.length + ' messages');
});
<|endoftext|>


<commit_before>const assert = require('assert');
const PlexRepository = require('src/plex/plexRepository');
const plexRepository = new PlexRepository();
const configuration = require('src/config/configuration').getInstance();
const TMDB = require('src/tmdb/tmdb');
const tmdb = new TMDB(configuration.get('tmdb', 'apiKey'));
var Promise = require('bluebird');
var rp = require('request-promise');

const establishedDatabase = require('src/database/database');

const MailTemplate = require('src/plex/mailTemplate')

var pythonShell = require('python-shell');
const nodemailer = require('nodemailer');

class RequestRepository {

	constructor(database) {
		this.database = database || establishedDatabase;
		this.queries = {
			'insertRequest': "INSERT INTO requests VALUES (?, ?, ?, ?, ?, ?, CURRENT_DATE, 'requested', ?)",
			'fetchRequstedItems': "SELECT * FROM requests",
			'updateRequested': "UPDATE stray_eps SET status = '?' WHERE id is '?'",
		}
	}

	searchRequest(query, page, type) {
		// TODO get from cache
		// STRIP METADATA THAT IS NOT ALLOWED

		// Do a search in the tmdb api and return the results of the object
		let getTmdbResults = function() {
			return tmdb.search(query, page, type)
				.then((tmdbSearch) => {
					return tmdbSearch.results;
				})
		}

		// Take inputs and verify them with a list. Now we are for every item in tmdb result
		// runnning through the entire plex loop. Many loops, but safe.
		let checkIfMatchesPlexObjects = function(title, year, plexarray) {
			// Iterate all elements in plexarray
			for (let plexItem of plexarray) {
				// If matches with our title and year return true
				if (plexItem.title === title && plexItem.year === year)
					return true;
			}
			// If no matches were found, return false
			return false;
		}

		return Promise.resolve()
			.then(() => plexRepository.searchMedia(query)
			// Get the list of plexItems matching the query passed.
			.then((plexItem) => {
				let tmdbSearchResult = getTmdbResults();

				// When we get the result from tmdbSearchResult we pass it along and iterate over each
				// element, and updates the matchedInPlex status of a item.
				return tmdbSearchResult.then((tmdbResult) => {
					for (var i = 0; i < tmdbResult.length; i++) {
						let foundMatchInPlex = checkIfMatchesPlexObjects(tmdbResult[i].title, tmdbResult[i].year, plexItem);
						tmdbResult[i].matchedInPlex = foundMatchInPlex;
					}
					return { 'results': tmdbResult, 'page': 1 };
				})
				// TODO log error
				.catch((error) => {
					console.log(error);
					throw new Error('Search query did not give any results.');
				})
			})
			.catch(() => {
				let tmdbSearchResult = getTmdbResults();

				// Catch if empty, then 404
				return tmdbSearchResult.then((tmdbResult) => {
					return {'results': tmdbResult, 'page': 1 };
				})
			})
		)
	}

	lookup(identifier, type = 'movie') {
		if (type === 'movie') { type = 'movieInfo'}
			else if (type === 'tv') { type = 'tvInfo'}
		return Promise.resolve()
		.then(() => tmdb.lookup(identifier, type))
		.then((tmdbMovie) => {
			return Promise.resolve(plexRepository.searchMedia(tmdbMovie.title))
			.then((plexMovies) => {
				for (var i = 0; i < plexMovies.length; i++) {
					if (tmdbMovie.title === plexMovies[i].title && tmdbMovie.year === plexMovies[i].year) {
						tmdbMovie.matchedInPlex = true;
						return tmdbMovie;
					}
				}
			})
			.catch((error) => {
				return error;
			});
			return tmdbMovie;
		});
	}

	/**
	* Send request for given media id.
	* @param {identifier, type} the id of the media object and type of media must be defined
	* @returns {Promise} If nothing has gone wrong.
	*/
	sendRequest(identifier, type, ip, user_agent) {
		// TODO add to DB so can have a admin page
		// TODO try a cache hit on the movie item

		tmdb.lookup(identifier, type).then(movie => {

			// Add request to database
			this.database.run(this.queries.insertRequest, [movie.id, movie.title, movie.year, movie.poster, 'NULL', ip, user_agent])

			//

			// create reusable transporter object using the default SMTP transport
			let transporter = nodemailer.createTransport({
				service: 'gmail',
			    auth: {
			        user: configuration.get('mail', 'user_pi'),
			        pass: configuration.get('mail', 'password_pi')
			    }
			    // host: configuration.get('mail', 'host'),
			    // port: 26,
			    // ignoreTLS: true,
			    // tls :{rejectUnauthorized: false},
			    // secure: false, // secure:true for port 465, secure:false for port 587
			});

			const mailTemplate = new MailTemplate(movie)

			// setup email data with unicode symbols
			let mailOptions = {
				// TODO get the mail adr from global location (easy to add)
			    from: 'MovieRequester <pi.midboe@gmail.com>', // sender address
			    to: 'kevin.midboe@gmail.com', // list of receivers
			    subject: 'Download request', // Subject line
			    text: mailTemplate.toText(),
			    html: mailTemplate.toHTML()
			};

			// send mail with defined transport object
			transporter.sendMail(mailOptions, (error, info) => {
			    if (error) {
			        return console.log(error);
			    }
			    console.log('Message %s sent: %s', info.messageId, info.response);
			});

		})

		// TODO add better response when done.
		return Promise.resolve();

	}

	fetchRequested() {
		return this.database.all(this.queries.fetchRequstedItems);
	}

	updateRequested(id, status) {
		this.database.run(this.queries.updateRequested, [status, id]);
	}

}

module.exports = RequestRepository;<commit_msg>Changed database table name.<commit_after>const assert = require('assert');
const PlexRepository = require('src/plex/plexRepository');
const plexRepository = new PlexRepository();
const configuration = require('src/config/configuration').getInstance();
const TMDB = require('src/tmdb/tmdb');
const tmdb = new TMDB(configuration.get('tmdb', 'apiKey'));
var Promise = require('bluebird');
var rp = require('request-promise');

const establishedDatabase = require('src/database/database');

const MailTemplate = require('src/plex/mailTemplate')

var pythonShell = require('python-shell');
const nodemailer = require('nodemailer');

class RequestRepository {

	constructor(database) {
		this.database = database || establishedDatabase;
		this.queries = {
			'insertRequest': "INSERT INTO requests VALUES (?, ?, ?, ?, ?, ?, CURRENT_DATE, 'requested', ?)",
			'fetchRequstedItems': "SELECT * FROM requests",
			'updateRequested': "UPDATE requests SET status = '?' WHERE id is '?'",
		}
	}

	searchRequest(query, page, type) {
		// TODO get from cache
		// STRIP METADATA THAT IS NOT ALLOWED

		// Do a search in the tmdb api and return the results of the object
		let getTmdbResults = function() {
			return tmdb.search(query, page, type)
				.then((tmdbSearch) => {
					return tmdbSearch.results;
				})
		}

		// Take inputs and verify them with a list. Now we are for every item in tmdb result
		// runnning through the entire plex loop. Many loops, but safe.
		let checkIfMatchesPlexObjects = function(title, year, plexarray) {
			// Iterate all elements in plexarray
			for (let plexItem of plexarray) {
				// If matches with our title and year return true
				if (plexItem.title === title && plexItem.year === year)
					return true;
			}
			// If no matches were found, return false
			return false;
		}

		return Promise.resolve()
			.then(() => plexRepository.searchMedia(query)
			// Get the list of plexItems matching the query passed.
			.then((plexItem) => {
				let tmdbSearchResult = getTmdbResults();

				// When we get the result from tmdbSearchResult we pass it along and iterate over each
				// element, and updates the matchedInPlex status of a item.
				return tmdbSearchResult.then((tmdbResult) => {
					for (var i = 0; i < tmdbResult.length; i++) {
						let foundMatchInPlex = checkIfMatchesPlexObjects(tmdbResult[i].title, tmdbResult[i].year, plexItem);
						tmdbResult[i].matchedInPlex = foundMatchInPlex;
					}
					return { 'results': tmdbResult, 'page': 1 };
				})
				// TODO log error
				.catch((error) => {
					console.log(error);
					throw new Error('Search query did not give any results.');
				})
			})
			.catch(() => {
				let tmdbSearchResult = getTmdbResults();

				// Catch if empty, then 404
				return tmdbSearchResult.then((tmdbResult) => {
					return {'results': tmdbResult, 'page': 1 };
				})
			})
		)
	}

	lookup(identifier, type = 'movie') {
		if (type === 'movie') { type = 'movieInfo'}
			else if (type === 'tv') { type = 'tvInfo'}
		return Promise.resolve()
		.then(() => tmdb.lookup(identifier, type))
		.then((tmdbMovie) => {
			return Promise.resolve(plexRepository.searchMedia(tmdbMovie.title))
			.then((plexMovies) => {
				for (var i = 0; i < plexMovies.length; i++) {
					if (tmdbMovie.title === plexMovies[i].title && tmdbMovie.year === plexMovies[i].year) {
						tmdbMovie.matchedInPlex = true;
						return tmdbMovie;
					}
				}
			})
			.catch((error) => {
				return error;
			});
			return tmdbMovie;
		});
	}

	/**
	* Send request for given media id.
	* @param {identifier, type} the id of the media object and type of media must be defined
	* @returns {Promise} If nothing has gone wrong.
	*/
	sendRequest(identifier, type, ip, user_agent) {
		// TODO add to DB so can have a admin page
		// TODO try a cache hit on the movie item

		tmdb.lookup(identifier, type).then(movie => {

			// Add request to database
			this.database.run(this.queries.insertRequest, [movie.id, movie.title, movie.year, movie.poster, 'NULL', ip, user_agent])

			//

			// create reusable transporter object using the default SMTP transport
			let transporter = nodemailer.createTransport({
				service: 'gmail',
			    auth: {
			        user: configuration.get('mail', 'user_pi'),
			        pass: configuration.get('mail', 'password_pi')
			    }
			    // host: configuration.get('mail', 'host'),
			    // port: 26,
			    // ignoreTLS: true,
			    // tls :{rejectUnauthorized: false},
			    // secure: false, // secure:true for port 465, secure:false for port 587
			});

			const mailTemplate = new MailTemplate(movie)

			// setup email data with unicode symbols
			let mailOptions = {
				// TODO get the mail adr from global location (easy to add)
			    from: 'MovieRequester <pi.midboe@gmail.com>', // sender address
			    to: 'kevin.midboe@gmail.com', // list of receivers
			    subject: 'Download request', // Subject line
			    text: mailTemplate.toText(),
			    html: mailTemplate.toHTML()
			};

			// send mail with defined transport object
			transporter.sendMail(mailOptions, (error, info) => {
			    if (error) {
			        return console.log(error);
			    }
			    console.log('Message %s sent: %s', info.messageId, info.response);
			});

		})

		// TODO add better response when done.
		return Promise.resolve();

	}

	fetchRequested() {
		return this.database.all(this.queries.fetchRequstedItems);
	}

	updateRequested(id, status) {
		this.database.run(this.queries.updateRequested, [status, id]);
	}

}

module.exports = RequestRepository;<|endoftext|>


<commit_before>class Builder {

    constructor () {
        this.builder = [];
        this.indexBuilder = {};
        this.relations = [];
        this.tables = [];
    }

    /**
     * Sets the index builder value as an 'and' reference
     *
     * @param indexName string
     * @param value mixed
     * @returns {Builder}
     */
    whereIndex(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'and'
        };

        return this;
    }

    /**
     * Sets the index builder value as an 'in' reference
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    whereIndexIn(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'in'
        };

        return this;
    }

    /**
     * Sets the index builder value with point inclusive and sets greater than check
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexGte(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'gte'
        };

        return this;
    }

    /**
     * Sets the index builder value with point not inclusive and sets greater than check
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexGt(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'gt'
        };

        return this;
    }

    /**
     * Sets the index builder value with point inclusive and sets less than check
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexLte(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'lte'
        };

        return this;
    }

    /**
     * Sets the index builder value with point not inclusive and sets less than check
     *
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexLt(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'lt'
        };

        return this;
    }

    /**
     * Sets the index builder value with points inclusive and sets range between them
     * @param indexName
     * @param lower
     * @param upper
     * @returns {Builder}
     */
    indexBetween(indexName, lower, upper) {

        this.indexBuilder = {
            index : indexName,
            value : [lower, upper],
            type : 'between'
        };

        return this;
    }

    whereIn(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'in'
        });

        return this;
    }

    where(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'and'
        });

        return this;
    }

    gte(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'gte'
        });

        return this;
    }

    gt(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'gt'
        });

        return this;
    }

    lte(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'lte'
        });

        return this;
    }

    lt(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'lt'
        });

        return this;
    }

    between(attributeName, upper, lower) {
        uppper = parseFloat(upper);
        lower = parseFloat(lower);

        if(isNaN(upper) || isNaN(lower)){
            throw "Between is only for numeric values";
        }

        this.builder.push({
            attribute : attributeName,
            value : [upper, lower],
            type : 'between'
        });

        return this;
    }

    relation(modelName, type, localKey, foreignKey, func, primary) {
        this.tables.push(modelName);

        this.relations.push({
            modelName : modelName,
            func : func,
            localKey : localKey,
            foreignKey : foreignKey,
            type : type,
            primary : primary
        });

        return this;
    }

    static get helpers() {

        return {

            checkNestedAttribute (attributeString, value, condition) {
                return condition == Model.helpers.getNestedAttribute(attributeString, value)
            },

            getNestedAttribute(attributeString, value) {
                let attributes = attributeString.split('.');
                let i;
                let content = value;

                for(i = 0; i < attributes.length; i++) {
                    if(content[attributes[i]] === undefined){
                        return undefined;
                    }

                    content = content[attributes[i]];
                }

                return content;
            },

            replaceNestedValues(attributes, value) {
                for(let attribute in attributes) {
                    value[attribute] = attributes[attribute];
                }

                return value;
            },
        };

    }

    static get RELATIONS() {
        return {
            hasOne : 'hasOne',
            hasMany : 'hasMany'
        }
    }
}<commit_msg>add relation to main model object<commit_after>class Builder {

    constructor () {
        this.builder = [];
        this.indexBuilder = {};
        this.relations = [];
        this.tables = [];
    }

    /**
     * Sets the index builder value as an 'and' reference
     *
     * @param indexName string
     * @param value mixed
     * @returns {Builder}
     */
    whereIndex(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'and'
        };

        return this;
    }

    /**
     * Sets the index builder value as an 'in' reference
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    whereIndexIn(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'in'
        };

        return this;
    }

    /**
     * Sets the index builder value with point inclusive and sets greater than check
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexGte(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'gte'
        };

        return this;
    }

    /**
     * Sets the index builder value with point not inclusive and sets greater than check
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexGt(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'gt'
        };

        return this;
    }

    /**
     * Sets the index builder value with point inclusive and sets less than check
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexLte(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'lte'
        };

        return this;
    }

    /**
     * Sets the index builder value with point not inclusive and sets less than check
     *
     * @param indexName
     * @param value
     * @returns {Builder}
     */
    indexLt(indexName, value) {

        this.indexBuilder = {
            index : indexName,
            value : value,
            type : 'lt'
        };

        return this;
    }

    /**
     * Sets the index builder value with points inclusive and sets range between them
     * @param indexName
     * @param lower
     * @param upper
     * @returns {Builder}
     */
    indexBetween(indexName, lower, upper) {

        this.indexBuilder = {
            index : indexName,
            value : [lower, upper],
            type : 'between'
        };

        return this;
    }

    whereIn(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'in'
        });

        return this;
    }

    where(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'and'
        });

        return this;
    }

    gte(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'gte'
        });

        return this;
    }

    gt(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'gt'
        });

        return this;
    }

    lte(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'lte'
        });

        return this;
    }

    lt(attributeName, value) {
        this.builder.push({
            attribute : attributeName,
            value : value,
            type : 'lt'
        });

        return this;
    }

    between(attributeName, upper, lower) {
        uppper = parseFloat(upper);
        lower = parseFloat(lower);

        if(isNaN(upper) || isNaN(lower)){
            throw "Between is only for numeric values";
        }

        this.builder.push({
            attribute : attributeName,
            value : [upper, lower],
            type : 'between'
        });

        return this;
    }

    relation(modelName, type, localKey, foreignKey, func, primary) {
        this.tables.push(modelName);

        this.relations.push({
            modelName : modelName,
            func : func,
            localKey : localKey,
            foreignKey : foreignKey,
            type : type,
            primary : primary
        });

        return this;
    }

    static get helpers() {

        return {

            checkNestedAttribute (attributeString, value, condition) {
                return condition == Model.helpers.getNestedAttribute(attributeString, value)
            },

            getNestedAttribute(attributeString, value) {
                let attributes = attributeString.split('.');
                let i;
                let content = value;

                for(i = 0; i < attributes.length; i++) {
                    if(content[attributes[i]] === undefined){
                        return undefined;
                    }

                    content = content[attributes[i]];
                }

                return content;
            },

            replaceNestedValues(attributes, value) {
                for(let attribute in attributes) {
                    value[attribute] = attributes[attribute];
                }

                return value;
            },
        };

    }

    get RELATIONS () {
        return Builder.RELATIONS;
    }

    static get RELATIONS() {
        return {
            hasOne : 'hasOne',
            hasMany : 'hasMany'
        }
    }
}<|endoftext|>


<commit_before>"use strict";

window.templates || (window.templates = {});
window.templates.network || (window.templates.network = {});

(function(templates) {

var HTTP_BOUNDARY_CLASS = "http-token-type-boundary";
var TEXT_TYPES = ["markup", "script", "css", "text"];
var LOCAL_URL_TYPES = [
  cls.ResourceManager["1.2"].UrlLoad.URLType.FILE,
  cls.ResourceManager["1.2"].UrlLoad.URLType.DATA
];
var HIGHLIGHTED_TYPES = [
  cls.HTTPHeaderTokenizer.types.NAME,
  cls.HTTPHeaderTokenizer.types.FIRST_LINE_PART
];

var _TokenToTemplateContext = function(is_response)
{
  var spec_tokens;
  if (!is_response)
  {
    var firstline = { METHOD: 0, URI: 1, HTTP_VERSION: 2 };
    spec_tokens = [firstline.METHOD];
  }
  else
  {
    var firstline = { PROTOCOL: 0, RESPONSE_CODE: 1, RESPONSE_PHRASE: 2 };
    spec_tokens = [firstline.RESPONSE_CODE];
  }
  this.spec_tokens = spec_tokens;
  this.saw_firstline_tokens = 0;
  this.str_buffer = "";
  this.template = [];
};

templates._pre = function(content)
{
  return ["pre", content, "class", "mono"];
};

templates.details = function(entry)
{
  var settings = window.settings["network-detail-overlay"];
  var do_raw = !settings.get("view-parsed");
  var do_wrap = settings.get("wrap-detail-view");
  return (
    ["div",
      this._details_headline(entry),
      this._details_content(entry, do_raw),
      "class", "table" + (do_wrap ? " wrap" : "")
    ]
  );
};

templates._details_content = function(entry, do_raw)
{
  return [
    entry.requests_responses.map(do_raw ? this._requests_responses_raw_bound
                                        : this._requests_responses_parsed_bound)
  ];
};

templates._details_headline = function(entry)
{
  var response_code = entry.current_responsecode;
  if (response_code && response_code in cls.ResourceUtil.http_status_codes)
     response_code = response_code + " " + cls.ResourceUtil.http_status_codes[response_code];

  var response_summary = [];
  if (entry.touched_network && response_code)
  {
    response_summary = [
      "p", String(response_code),
      "data-spec", "http#" + entry.current_responsecode,
      "class", (entry.error_in_current_response ? templates.ERROR_RESPONSE
                                                : "") + " response-summary"
    ];
  }
  else
  {
    response_summary = [
      "p", LOCAL_URL_TYPES.contains(entry.urltype) ?
        ui_strings.S_NETWORK_NOT_REQUESTED : ui_strings.S_NETWORK_SERVED_FROM_CACHE,
      "class", templates.NOT_REQUESTED
    ];
  }

  return [
    ["p",
      ["span",
        (entry.current_request && entry.current_request.method + " ") || ""
      ],
      ["span", entry.url,
        "class", "url"
      ],
      "class", "method-and-url"
    ],
    response_summary
  ];
};

templates.requests_responses = function(do_raw, request_response, index, requests_responses)
{
  var is_last_of_type = true;
  for (var i = index + 1, req_res; req_res = requests_responses[i]; i++)
  {
    if (request_response.is_response == req_res.is_response)
    {
      is_last_of_type = false;
      break;
    }
  }
  return (
    request_response.is_response ? this._response(request_response, is_last_of_type, do_raw)
                                 : this._request(request_response, is_last_of_type, do_raw)
  );
};

templates._requests_responses_raw_bound = templates.requests_responses.bind(templates, true);
templates._requests_responses_parsed_bound = templates.requests_responses.bind(templates, false);

templates._request = function(request, is_last, do_raw)
{
  // A request that's followed by another one, without a response in between,
  // is not shown in network-details. It will mostly mean it was retried internally
  // and didn't go on the network.
  var is_relevant = is_last && request.was_responded_to;
  var settings = window.settings["network-detail-overlay"];
  var expanded = settings.get("expand-requests");
  var show_header = is_relevant;
  var show_headers = is_relevant && expanded;
  var show_body = show_headers;

  return [
    "div",
      show_header ? templates._headline(false, expanded) : [],
      ["div",
        show_headers ? templates._request_headers(request, do_raw) : [],
        show_body ? templates._request_body(request, do_raw) : [],
        "class", "foldable"
      ],
      "class", (expanded ? "unfolded" : "")
  ];
};

templates._response = function(response, is_last, do_raw)
{
  var settings = window.settings["network-detail-overlay"];
  var expanded = settings.get("expand-responses");
  var show_header = response.logger_entry_touched_network;
  var show_headers = expanded && response.logger_entry_touched_network;
  var show_body = !show_header || (show_header && expanded);

  return [
    "div",
      show_header ? this._headline(true, expanded) : [],
      ["div",
        show_headers ? this._response_headers(response, do_raw) : [],
        show_body ? this._response_body(response, do_raw, is_last) : [],
        "class", "foldable"
      ],
      "class", (expanded ? "unfolded" : "")
  ];
};

templates._headline = function(is_response, is_unfolded)
{
  var headline = [
    "div",
      ["input",
        "type", "button",
        "class", is_unfolded ? "unfolded" : ""
      ],
      is_response ? ui_strings.S_NETWORK_REQUEST_DETAIL_RESPONSE_TITLE
                  : ui_strings.S_NETWORK_REQUEST_DETAIL_REQUEST_TITLE,
      "handler", "toggle-expand-request-response",
      "class", "header"
  ];
  if (is_response)
    headline.push("data-is-response", "data-is-response");
  return headline;
};

templates._token_receiver = function(tokens, token_type, token)
{
  tokens.push([token_type, token]);
};

templates._request_headers = function(req, do_raw)
{
  if (do_raw)
  {
    if (req.request_headers_raw)
    {
      var header_tokens = [];
      var tokenizer = new cls.HTTPHeaderTokenizer();
      tokenizer.tokenize(req.request_headers_raw, this._token_receiver.bind(this, header_tokens));
      return this._pre(this.headers_tonkenized(header_tokens, false));
    }
    return ["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
            "class", templates.UI_CLASSNAME];
  }

  var ret = [];
  if (!req.request_headers)
  {
    ret.push(["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
              "class", templates.UI_CLASSNAME]);
  }
  else
  {
    ret.extend(req.request_headers.map(this._headers_pseudo_raw));
    if (req.first_line)
    {
      var firstline_tokens = [];
      var tokenizer = new cls.HTTPHeaderTokenizer();
      tokenizer.tokenize(req.first_line, this._token_receiver.bind(this, firstline_tokens))

      if (firstline_tokens.length)
      {
        ret.unshift(this.headers_tonkenized(firstline_tokens, false));
      }
    }
  }
  return templates._pre(ret);
};

templates._reduce_tokens = function(context, token, index)
{
  var TYPE = 0;
  var STR = 1;
  if (HIGHLIGHTED_TYPES.contains(token[TYPE]))
  {
    var token_templ = ["span", token[STR],
                       "class", cls.HTTPHeaderTokenizer.classnames[token[TYPE]]];
    if (token[TYPE] === cls.HTTPHeaderTokenizer.types.NAME)
    {
      token_templ.push("data-spec", "http#" + token[STR].trim());
    }
    else if (token[TYPE] === cls.HTTPHeaderTokenizer.types.FIRST_LINE_PART)
    {
      if (context.spec_tokens.contains(context.saw_firstline_tokens))
      {
        token_templ.push("data-spec", "http#" + (token[STR]).trim());
      }
      context.saw_firstline_tokens++;
    }

    if (context.str_buffer)
    {
      context.template.push(context.str_buffer);
      context.str_buffer = "";
    }
    context.template.push(token_templ);
  }
  else
    context.str_buffer += token[STR];

  return context;
};

templates.headers_tonkenized = function(tokens, is_response)
{
  var context = new _TokenToTemplateContext(is_response);
  var template = tokens.reduce(this._reduce_tokens, context).template;
  if (context.str_buffer)
    template.push(context.str_buffer);
  return template;
};

templates._response_headers = function(resp, do_raw)
{
  if (do_raw)
  {
    var header_tokens = [];
    if (resp.response_headers_raw)
    {
      var tokenizer = new cls.HTTPHeaderTokenizer();
      tokenizer.tokenize(resp.response_headers_raw, this._token_receiver.bind(this, header_tokens));
    }

    if (header_tokens.length)
    {
      return this._pre(this.headers_tonkenized(header_tokens, true));
    }
    return ["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
            "class", templates.UI_CLASSNAME];
  }

  var ret = resp.response_headers && resp.response_headers.map(this._headers_pseudo_raw);
  if (resp.first_line)
  {
    var firstline_tokens = [];
    var tokenizer = new cls.HTTPHeaderTokenizer();
    tokenizer.tokenize(resp.first_line, this._token_receiver.bind(this, firstline_tokens))

    if (firstline_tokens.length)
      ret.unshift(this.headers_tonkenized(firstline_tokens, true));
  }

  if (!ret)
  {
    ret = ["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
           "class", templates.UI_CLASSNAME];
  }
  return templates._pre(ret);
};

templates._headers_pseudo_raw = function(header)
{
  /* Shortcutting. For raw headers, highlighted types are defined like this:
  var HIGHLIGHTED_TYPES = [
    cls.HTTPHeaderTokenizer.types.NAME,
    cls.HTTPHeaderTokenizer.types.FIRST_LINE_PART
  ];
  */
  var template = [
    ["span", header.name,
      "data-spec", "http#" + header.name.trim(),
      "class", cls.HTTPHeaderTokenizer.classnames[cls.HTTPHeaderTokenizer.types.NAME],
      "data-header-name", header.name.trim().toLowerCase()
    ],
    ": " + header.value + "\n"
  ];
  return template;
};

templates.param_cells = function(name_value)
{
  var parts = name_value.replace(/\+/g, " ").split("=");
  return [
    "tr",
      ["td", decodeURIComponent(parts[0]), "class", "mono"],
      ["td", decodeURIComponent(parts[1]), "class", "mono"]
  ];
};

templates._request_body = function(req, do_raw)
{
  if (req.request_body == null)
    return [];

  var ret;
  if (req.request_body.partList.length) // Multipart
  {
    ret = [];
    var use_raw_boundary = Boolean(do_raw && req.boundary);
    var raw_boundary = req.boundary;
    for (var n = 0, part; part = req.request_body.partList[n]; n++)
    {
      if (n === 0)
      {
        if (use_raw_boundary)
          ret.push(["span", raw_boundary, "class", HTTP_BOUNDARY_CLASS]);
        else
          ret.push(["hr"]);
      }

      ret.push(["span", "\n"]);
      ret.extend(part.headerList.map(this._headers_pseudo_raw));
      ret.push(["span", "\n"]);
      if (part.content && part.content.stringData)
        ret.push(part.content.stringData);
      else
        ret.push(["span", ui_strings.S_NETWORK_N_BYTE_BODY.replace("%s", part.contentLength),
                               "class", templates.UI_CLASSNAME]);

      if (use_raw_boundary && part === req.request_body.partList.last)
        raw_boundary += "--";

      if (use_raw_boundary)
        ret.push(["span", "\n" + raw_boundary, "class", HTTP_BOUNDARY_CLASS]);
      else
        ret.push(["hr"]);
    }
  }
  else if (req.request_body.mimeType.startswith("application/x-www-form-urlencoded"))
  {
    var ret;
    if (do_raw)
    {
      ret = req.request_body.content.stringData;
    }
    else
    {
      var parts = req.request_body.content.stringData.split("&");
      var rows = [];
      rows.push([
        "tr",
          ["th", ["span", ui_strings.S_LABEL_NETWORK_POST_DATA_NAME, "class", templates.UI_CLASSNAME]],
          ["th", ["span", ui_strings.S_LABEL_NETWORK_POST_DATA_VALUE, "class", templates.UI_CLASSNAME]]
        ]
      );
      rows.extend(parts.map(this.param_cells));
      var table = ["table", rows];
      ret = table;
    }
  }
  else // not multipart or form.
  {
    if (req.request_body.content)
    {
      var type = cls.ResourceUtil.mime_to_type(req.request_body.mimeType);
      if (TEXT_TYPES.contains(type))
      {
        ret = req.request_body.content.stringData;
      }
      else
      {
        if (req.request_body.mimeType)
        {
          ret = ["span", ui_strings.S_NETWORK_CANT_DISPLAY_TYPE.replace("%s", req.request_body.mimeType),
                 "class", templates.UI_CLASSNAME];
        }
        else
        {
          ret = ["span", ui_strings.S_NETWORK_UNKNOWN_MIME_TYPE,
                 "class", templates.UI_CLASSNAME];
        }
      }
    }
  }
  var BODY_SEPARATOR = "\n";
  return [this._pre(BODY_SEPARATOR), templates._pre(ret)];
};

templates._response_body = function(resp, do_raw, is_last_response)
{
  var ret = [];
  var classname = "";

  var should_track_content =
    resp.saw_responsefinished &&
    (!resp.responsebody || !resp.responsebody.content) &&
    (!resp.logger_entry_called_get_body || resp.logger_entry_get_body_unsuccessful);

  if (should_track_content)
  {
    // Ask to enable content-tracking.
    classname = "network_info";
    ret.push(ui_strings.S_NETWORK_REQUEST_DETAIL_NO_RESPONSE_BODY);
  }
  else
  {
    if (!resp.responsebody)
    {
      if (is_last_response && !resp.logger_entry_is_finished)
      {
        // Unfinished.
        classname = "network_info";
        ret.push(ui_strings.S_NETWORK_REQUEST_DETAIL_BODY_UNFINISHED);
      }
      // else
        // We're in the middle of getting it via GetResource, or there is in fact no responsebody.
    }
    else
    {
      // Attempt to display the responsebody.
      if (TEXT_TYPES.contains(resp.logger_entry_type))
      {
        ret.push(this._pre(resp.responsebody.content.stringData));
      }
      else if (resp.logger_entry_type == "image")
      {
        ret.push(["img", "src", resp.responsebody.content.stringData]);
      }
      else
      {
        ret.push(
          ["span", ui_strings.S_NETWORK_REQUEST_DETAIL_UNDISPLAYABLE_BODY_LABEL.replace("%s", resp.logger_entry_mime),
           "class", templates.UI_CLASSNAME]
        );
      }
    }
  }
  if (ret.length)
    ret.unshift(this._pre("\n"));

  return ret;
};

})(window.templates.network);
<commit_msg>Formatting fix<commit_after>"use strict";

window.templates || (window.templates = {});
window.templates.network || (window.templates.network = {});

(function(templates) {

var HTTP_BOUNDARY_CLASS = "http-token-type-boundary";
var TEXT_TYPES = ["markup", "script", "css", "text"];
var LOCAL_URL_TYPES = [
  cls.ResourceManager["1.2"].UrlLoad.URLType.FILE,
  cls.ResourceManager["1.2"].UrlLoad.URLType.DATA
];
var HIGHLIGHTED_TYPES = [
  cls.HTTPHeaderTokenizer.types.NAME,
  cls.HTTPHeaderTokenizer.types.FIRST_LINE_PART
];

var _TokenToTemplateContext = function(is_response)
{
  var spec_tokens;
  if (!is_response)
  {
    var firstline = { METHOD: 0, URI: 1, HTTP_VERSION: 2 };
    spec_tokens = [firstline.METHOD];
  }
  else
  {
    var firstline = { PROTOCOL: 0, RESPONSE_CODE: 1, RESPONSE_PHRASE: 2 };
    spec_tokens = [firstline.RESPONSE_CODE];
  }
  this.spec_tokens = spec_tokens;
  this.saw_firstline_tokens = 0;
  this.str_buffer = "";
  this.template = [];
};

templates._pre = function(content)
{
  return ["pre", content, "class", "mono"];
};

templates.details = function(entry)
{
  var settings = window.settings["network-detail-overlay"];
  var do_raw = !settings.get("view-parsed");
  var do_wrap = settings.get("wrap-detail-view");
  return (
    ["div",
      this._details_headline(entry),
      this._details_content(entry, do_raw),
      "class", "table" + (do_wrap ? " wrap" : "")
    ]
  );
};

templates._details_content = function(entry, do_raw)
{
  return [
    entry.requests_responses.map(do_raw ? this._requests_responses_raw_bound
                                        : this._requests_responses_parsed_bound)
  ];
};

templates._details_headline = function(entry)
{
  var response_code = entry.current_responsecode;
  if (response_code && response_code in cls.ResourceUtil.http_status_codes)
     response_code = response_code + " " + cls.ResourceUtil.http_status_codes[response_code];

  var response_summary = [];
  if (entry.touched_network && response_code)
  {
    response_summary = [
      "p", String(response_code),
      "data-spec", "http#" + entry.current_responsecode,
      "class", (entry.error_in_current_response ? templates.ERROR_RESPONSE
                                                : "") + " response-summary"
    ];
  }
  else
  {
    response_summary = [
      "p", LOCAL_URL_TYPES.contains(entry.urltype) ?
        ui_strings.S_NETWORK_NOT_REQUESTED : ui_strings.S_NETWORK_SERVED_FROM_CACHE,
      "class", templates.NOT_REQUESTED
    ];
  }

  return [
    ["p",
      ["span",
        (entry.current_request && entry.current_request.method + " ") || ""
      ],
      ["span", entry.url,
        "class", "url"
      ],
      "class", "method-and-url"
    ],
    response_summary
  ];
};

templates.requests_responses = function(do_raw, request_response, index, requests_responses)
{
  var is_last_of_type = true;
  for (var i = index + 1, req_res; req_res = requests_responses[i]; i++)
  {
    if (request_response.is_response == req_res.is_response)
    {
      is_last_of_type = false;
      break;
    }
  }
  return (
    request_response.is_response ? this._response(request_response, is_last_of_type, do_raw)
                                 : this._request(request_response, is_last_of_type, do_raw)
  );
};

templates._requests_responses_raw_bound = templates.requests_responses.bind(templates, true);
templates._requests_responses_parsed_bound = templates.requests_responses.bind(templates, false);

templates._request = function(request, is_last, do_raw)
{
  // A request that's followed by another one, without a response in between,
  // is not shown in network-details. It will mostly mean it was retried internally
  // and didn't go on the network.
  var is_relevant = is_last && request.was_responded_to;
  var settings = window.settings["network-detail-overlay"];
  var expanded = settings.get("expand-requests");
  var show_header = is_relevant;
  var show_headers = is_relevant && expanded;
  var show_body = show_headers;

  return [
    "div",
      show_header ? templates._headline(false, expanded) : [],
      ["div",
        show_headers ? templates._request_headers(request, do_raw) : [],
        show_body ? templates._request_body(request, do_raw) : [],
        "class", "foldable"
      ],
      "class", (expanded ? "unfolded" : "")
  ];
};

templates._response = function(response, is_last, do_raw)
{
  var settings = window.settings["network-detail-overlay"];
  var expanded = settings.get("expand-responses");
  var show_header = response.logger_entry_touched_network;
  var show_headers = expanded && response.logger_entry_touched_network;
  var show_body = !show_header || (show_header && expanded);

  return [
    "div",
      show_header ? this._headline(true, expanded) : [],
      ["div",
        show_headers ? this._response_headers(response, do_raw) : [],
        show_body ? this._response_body(response, do_raw, is_last) : [],
        "class", "foldable"
      ],
      "class", (expanded ? "unfolded" : "")
  ];
};

templates._headline = function(is_response, is_unfolded)
{
  var headline = [
    "div",
      ["input",
        "type", "button",
        "class", is_unfolded ? "unfolded" : ""
      ],
      is_response ? ui_strings.S_NETWORK_REQUEST_DETAIL_RESPONSE_TITLE
                  : ui_strings.S_NETWORK_REQUEST_DETAIL_REQUEST_TITLE,
      "handler", "toggle-expand-request-response",
      "class", "header"
  ];
  if (is_response)
    headline.push("data-is-response", "data-is-response");
  return headline;
};

templates._token_receiver = function(tokens, token_type, token)
{
  tokens.push([token_type, token]);
};

templates._request_headers = function(req, do_raw)
{
  if (do_raw)
  {
    if (req.request_headers_raw)
    {
      var header_tokens = [];
      var tokenizer = new cls.HTTPHeaderTokenizer();
      tokenizer.tokenize(req.request_headers_raw, this._token_receiver.bind(this, header_tokens));
      return this._pre(this.headers_tonkenized(header_tokens, false));
    }
    return ["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
            "class", templates.UI_CLASSNAME];
  }

  var ret = [];
  if (!req.request_headers)
  {
    ret.push(["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
              "class", templates.UI_CLASSNAME]);
  }
  else
  {
    ret.extend(req.request_headers.map(this._headers_pseudo_raw));
    if (req.first_line)
    {
      var firstline_tokens = [];
      var tokenizer = new cls.HTTPHeaderTokenizer();
      tokenizer.tokenize(req.first_line, this._token_receiver.bind(this, firstline_tokens))
      if (firstline_tokens.length)
      {
        ret.unshift(this.headers_tonkenized(firstline_tokens, false));
      }
    }
  }
  return templates._pre(ret);
};

templates._reduce_tokens = function(context, token, index)
{
  var TYPE = 0;
  var STR = 1;
  if (HIGHLIGHTED_TYPES.contains(token[TYPE]))
  {
    var token_templ = ["span", token[STR],
                       "class", cls.HTTPHeaderTokenizer.classnames[token[TYPE]]];
    if (token[TYPE] === cls.HTTPHeaderTokenizer.types.NAME)
    {
      token_templ.push("data-spec", "http#" + token[STR].trim());
    }
    else if (token[TYPE] === cls.HTTPHeaderTokenizer.types.FIRST_LINE_PART)
    {
      if (context.spec_tokens.contains(context.saw_firstline_tokens))
      {
        token_templ.push("data-spec", "http#" + (token[STR]).trim());
      }
      context.saw_firstline_tokens++;
    }

    if (context.str_buffer)
    {
      context.template.push(context.str_buffer);
      context.str_buffer = "";
    }
    context.template.push(token_templ);
  }
  else
    context.str_buffer += token[STR];

  return context;
};

templates.headers_tonkenized = function(tokens, is_response)
{
  var context = new _TokenToTemplateContext(is_response);
  var template = tokens.reduce(this._reduce_tokens, context).template;
  if (context.str_buffer)
    template.push(context.str_buffer);
  return template;
};

templates._response_headers = function(resp, do_raw)
{
  if (do_raw)
  {
    var header_tokens = [];
    if (resp.response_headers_raw)
    {
      var tokenizer = new cls.HTTPHeaderTokenizer();
      tokenizer.tokenize(resp.response_headers_raw, this._token_receiver.bind(this, header_tokens));
    }

    if (header_tokens.length)
    {
      return this._pre(this.headers_tonkenized(header_tokens, true));
    }
    return ["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
            "class", templates.UI_CLASSNAME];
  }

  var ret = resp.response_headers && resp.response_headers.map(this._headers_pseudo_raw);
  if (resp.first_line)
  {
    var firstline_tokens = [];
    var tokenizer = new cls.HTTPHeaderTokenizer();
    tokenizer.tokenize(resp.first_line, this._token_receiver.bind(this, firstline_tokens))
    if (firstline_tokens.length)
      ret.unshift(this.headers_tonkenized(firstline_tokens, true));
  }

  if (!ret)
  {
    ret = ["span", ui_strings.S_NETWORK_REQUEST_NO_HEADERS_LABEL,
           "class", templates.UI_CLASSNAME];
  }
  return templates._pre(ret);
};

templates._headers_pseudo_raw = function(header)
{
  /* Shortcutting. For raw headers, highlighted types are defined like this:
  var HIGHLIGHTED_TYPES = [
    cls.HTTPHeaderTokenizer.types.NAME,
    cls.HTTPHeaderTokenizer.types.FIRST_LINE_PART
  ];
  */
  var template = [
    ["span", header.name,
      "data-spec", "http#" + header.name.trim(),
      "class", cls.HTTPHeaderTokenizer.classnames[cls.HTTPHeaderTokenizer.types.NAME],
      "data-header-name", header.name.trim().toLowerCase()
    ],
    ": " + header.value + "\n"
  ];
  return template;
};

templates.param_cells = function(name_value)
{
  var parts = name_value.replace(/\+/g, " ").split("=");
  return [
    "tr",
      ["td", decodeURIComponent(parts[0]), "class", "mono"],
      ["td", decodeURIComponent(parts[1]), "class", "mono"]
  ];
};

templates._request_body = function(req, do_raw)
{
  if (req.request_body == null)
    return [];

  var ret;
  if (req.request_body.partList.length) // Multipart
  {
    ret = [];
    var use_raw_boundary = Boolean(do_raw && req.boundary);
    var raw_boundary = req.boundary;
    for (var n = 0, part; part = req.request_body.partList[n]; n++)
    {
      if (n === 0)
      {
        if (use_raw_boundary)
          ret.push(["span", raw_boundary, "class", HTTP_BOUNDARY_CLASS]);
        else
          ret.push(["hr"]);
      }

      ret.push(["span", "\n"]);
      ret.extend(part.headerList.map(this._headers_pseudo_raw));
      ret.push(["span", "\n"]);
      if (part.content && part.content.stringData)
        ret.push(part.content.stringData);
      else
        ret.push(["span", ui_strings.S_NETWORK_N_BYTE_BODY.replace("%s", part.contentLength),
                               "class", templates.UI_CLASSNAME]);

      if (use_raw_boundary && part === req.request_body.partList.last)
        raw_boundary += "--";

      if (use_raw_boundary)
        ret.push(["span", "\n" + raw_boundary, "class", HTTP_BOUNDARY_CLASS]);
      else
        ret.push(["hr"]);
    }
  }
  else if (req.request_body.mimeType.startswith("application/x-www-form-urlencoded"))
  {
    var ret;
    if (do_raw)
    {
      ret = req.request_body.content.stringData;
    }
    else
    {
      var parts = req.request_body.content.stringData.split("&");
      var rows = [];
      rows.push([
        "tr",
          ["th", ["span", ui_strings.S_LABEL_NETWORK_POST_DATA_NAME, "class", templates.UI_CLASSNAME]],
          ["th", ["span", ui_strings.S_LABEL_NETWORK_POST_DATA_VALUE, "class", templates.UI_CLASSNAME]]
        ]
      );
      rows.extend(parts.map(this.param_cells));
      var table = ["table", rows];
      ret = table;
    }
  }
  else // not multipart or form.
  {
    if (req.request_body.content)
    {
      var type = cls.ResourceUtil.mime_to_type(req.request_body.mimeType);
      if (TEXT_TYPES.contains(type))
      {
        ret = req.request_body.content.stringData;
      }
      else
      {
        if (req.request_body.mimeType)
        {
          ret = ["span", ui_strings.S_NETWORK_CANT_DISPLAY_TYPE.replace("%s", req.request_body.mimeType),
                 "class", templates.UI_CLASSNAME];
        }
        else
        {
          ret = ["span", ui_strings.S_NETWORK_UNKNOWN_MIME_TYPE,
                 "class", templates.UI_CLASSNAME];
        }
      }
    }
  }
  var BODY_SEPARATOR = "\n";
  return [this._pre(BODY_SEPARATOR), templates._pre(ret)];
};

templates._response_body = function(resp, do_raw, is_last_response)
{
  var ret = [];
  var classname = "";

  var should_track_content =
    resp.saw_responsefinished &&
    (!resp.responsebody || !resp.responsebody.content) &&
    (!resp.logger_entry_called_get_body || resp.logger_entry_get_body_unsuccessful);

  if (should_track_content)
  {
    // Ask to enable content-tracking.
    classname = "network_info";
    ret.push(ui_strings.S_NETWORK_REQUEST_DETAIL_NO_RESPONSE_BODY);
  }
  else
  {
    if (!resp.responsebody)
    {
      if (is_last_response && !resp.logger_entry_is_finished)
      {
        // Unfinished.
        classname = "network_info";
        ret.push(ui_strings.S_NETWORK_REQUEST_DETAIL_BODY_UNFINISHED);
      }
      // else
        // We're in the middle of getting it via GetResource, or there is in fact no responsebody.
    }
    else
    {
      // Attempt to display the responsebody.
      if (TEXT_TYPES.contains(resp.logger_entry_type))
      {
        ret.push(this._pre(resp.responsebody.content.stringData));
      }
      else if (resp.logger_entry_type == "image")
      {
        ret.push(["img", "src", resp.responsebody.content.stringData]);
      }
      else
      {
        ret.push(
          ["span", ui_strings.S_NETWORK_REQUEST_DETAIL_UNDISPLAYABLE_BODY_LABEL.replace("%s", resp.logger_entry_mime),
           "class", templates.UI_CLASSNAME]
        );
      }
    }
  }
  if (ret.length)
    ret.unshift(this._pre("\n"));

  return ret;
};

})(window.templates.network);
<|endoftext|>


<commit_before>'use strict';

// Simulate a test service provider that submits usage for a resource and
// verifies the submission by retrieving a usage report.

const oauth = require('abacus-oauth');
const moment = require('abacus-moment');
const request = require('abacus-request');

const httpStatus = require('http-status-codes');
const util = require('util');
const { times } = require('underscore');

const { testEnv } = require('./env-config');
const { buildUsage, createExpectedInitialReport } = require('./fixtures');
const { deltaCompareReports } = require('./report-comparator');
const { getThousandLightAPICallsQuantity, cleanReport } = require('./parse-report-utils');

const doGet = util.promisify(request.get);
const doPost = util.promisify(request.post);

const objectStorageToken = testEnv.secured ?
  oauth.cache(testEnv.authServer, testEnv.objectStorageClientId, testEnv.objectStorageClientSecret,
    'abacus.usage.object-storage.write') : undefined;
const systemToken = testEnv.secured ?
  oauth.cache(testEnv.authServer, testEnv.systemClientId, testEnv.systemClientSecret,
    'abacus.usage.read') : undefined;

const authHeader = (token) => token ? { authorization: token() } : {};

const sendUsage = async (usage) => {
  const resp = await doPost('/v1/metering/collected/usage', {
    baseUrl: testEnv.collectorUrl,
    headers: authHeader(systemToken),
    body: usage
  });

  expect(resp.statusCode).to.equal(httpStatus.ACCEPTED);
  return resp.headers.location;
};

const retrieveReport = async (orgID) => {
  const resp = await doGet('/v1/metering/organizations/:organization_id/aggregated/usage', {
    baseUrl: testEnv.reportingUrl,
    headers: authHeader(systemToken),
    organization_id: orgID
  });

  expect(resp.statusCode).to.equal(httpStatus.OK);
  return resp.body;
};

describe('process usage smoke test', function() {
  const testOrgID = 'us-south:a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27';
  let currentReport;

  setEventuallyPollingInterval(testEnv.pollInterval);
  setEventuallyTimeout(testEnv.totalTimeout);

  before(async() => {
    if(testEnv.secured) {
      const startObjectStorageToken = util.promisify(objectStorageToken.start);
      const startSystemToken = util.promisify(systemToken.start);

      await startObjectStorageToken();
      await startSystemToken();
    }

    console.log('\n%s: Retrieving current report', moment.utc().toDate());
    await eventually(async () => {
      currentReport = await retrieveReport(testOrgID);
    });
  });

  it('submits usage for a sample resource and retrieves an aggregated usage report', async function() {
    const timeout = Math.max(testEnv.totalTimeout, 40000) + 2000;
    const now = moment.now();
    const processingDeadline = now + timeout;
    const bytesInGigabyte = 1073741824;

    const quantites = {
      lightAPICalls: 1000,
      heavyAPICalls: 100,
      storage: bytesInGigabyte
    };

    setEventuallyPollingInterval(testEnv.pollInterval);
    setEventuallyTimeout(timeout);

    this.timeout(timeout);
    console.log('Test will run until %s', moment.utc(processingDeadline).toDate());

    console.log('Submitting 10 GB, 1000 light API calls, 100 heavy API calls %d times', testEnv.usageDocumentsCount);
    const sendUsageTasks = [];
    times(testEnv.usageDocumentsCount, (n) => {
      sendUsageTasks.push(sendUsage(buildUsage(testOrgID, now + n, quantites)));
    });
    await Promise.all(sendUsageTasks);
    console.log('\n%s: Usage documets have been sent successfully', moment.utc().toDate());

    console.log('\n%s: Retrieving usage report', moment.utc().toDate());
    await eventually(async () => {
      const updatedReport = await retrieveReport(testOrgID);
      const processedDocs = getThousandLightAPICallsQuantity(currentReport);

      expect(getThousandLightAPICallsQuantity(updatedReport)).to.equal(processedDocs + testEnv.usageDocumentsCount);

      // quantity and summary fields have the same values
      const expectedValues = {
        lightAPICalls: (testEnv.usageDocumentsCount * quantites.lightAPICalls) / 1000,
        heavyAPICalls: testEnv.usageDocumentsCount * quantites.heavyAPICalls,
        // accumulate function is defined as max
        storage: quantites.storage / bytesInGigabyte
      };

      if(!processedDocs)
        expect(cleanReport(updatedReport)).to.deep.equal(createExpectedInitialReport(
          testOrgID, expectedValues, expectedValues));
      else
        deltaCompareReports(cleanReport(updatedReport), currentReport, expectedValues, expectedValues);
    });
  });
});
<commit_msg>Use object storage token when sending usages (#1091)<commit_after>'use strict';

// Simulate a test service provider that submits usage for a resource and
// verifies the submission by retrieving a usage report.

const oauth = require('abacus-oauth');
const moment = require('abacus-moment');
const request = require('abacus-request');

const httpStatus = require('http-status-codes');
const util = require('util');
const { times } = require('underscore');

const { testEnv } = require('./env-config');
const { buildUsage, createExpectedInitialReport } = require('./fixtures');
const { deltaCompareReports } = require('./report-comparator');
const { getThousandLightAPICallsQuantity, cleanReport } = require('./parse-report-utils');

const doGet = util.promisify(request.get);
const doPost = util.promisify(request.post);

const objectStorageToken = testEnv.secured ?
  oauth.cache(testEnv.authServer, testEnv.objectStorageClientId, testEnv.objectStorageClientSecret,
    'abacus.usage.object-storage.write') : undefined;
const systemToken = testEnv.secured ?
  oauth.cache(testEnv.authServer, testEnv.systemClientId, testEnv.systemClientSecret,
    'abacus.usage.read') : undefined;

const authHeader = (token) => token ? { authorization: token() } : {};

const sendUsage = async (usage) => {
  const resp = await doPost('/v1/metering/collected/usage', {
    baseUrl: testEnv.collectorUrl,
    headers: authHeader(objectStorageToken),
    body: usage
  });

  expect(resp.statusCode).to.equal(httpStatus.ACCEPTED);
  return resp.headers.location;
};

const retrieveReport = async (orgID) => {
  const resp = await doGet('/v1/metering/organizations/:organization_id/aggregated/usage', {
    baseUrl: testEnv.reportingUrl,
    headers: authHeader(systemToken),
    organization_id: orgID
  });

  expect(resp.statusCode).to.equal(httpStatus.OK);
  return resp.body;
};

describe('process usage smoke test', function() {
  const testOrgID = 'us-south:a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27';
  let currentReport;

  setEventuallyPollingInterval(testEnv.pollInterval);
  setEventuallyTimeout(testEnv.totalTimeout);

  before(async() => {
    if(testEnv.secured) {
      const startObjectStorageToken = util.promisify(objectStorageToken.start);
      const startSystemToken = util.promisify(systemToken.start);

      await startObjectStorageToken();
      await startSystemToken();
    }

    console.log('\n%s: Retrieving current report', moment.utc().toDate());
    await eventually(async () => {
      currentReport = await retrieveReport(testOrgID);
    });
  });

  it('submits usage for a sample resource and retrieves an aggregated usage report', async function() {
    const timeout = Math.max(testEnv.totalTimeout, 40000) + 2000;
    const now = moment.now();
    const processingDeadline = now + timeout;
    const bytesInGigabyte = 1073741824;

    const quantites = {
      lightAPICalls: 1000,
      heavyAPICalls: 100,
      storage: bytesInGigabyte
    };

    setEventuallyPollingInterval(testEnv.pollInterval);
    setEventuallyTimeout(timeout);

    this.timeout(timeout);
    console.log('Test will run until %s', moment.utc(processingDeadline).toDate());

    console.log('Submitting 10 GB, 1000 light API calls, 100 heavy API calls %d times', testEnv.usageDocumentsCount);
    const sendUsageTasks = [];
    times(testEnv.usageDocumentsCount, (n) => {
      sendUsageTasks.push(sendUsage(buildUsage(testOrgID, now + n, quantites)));
    });
    await Promise.all(sendUsageTasks);
    console.log('\n%s: Usage documets have been sent successfully', moment.utc().toDate());

    console.log('\n%s: Retrieving usage report', moment.utc().toDate());
    await eventually(async () => {
      const updatedReport = await retrieveReport(testOrgID);
      const processedDocs = getThousandLightAPICallsQuantity(currentReport);

      expect(getThousandLightAPICallsQuantity(updatedReport)).to.equal(processedDocs + testEnv.usageDocumentsCount);

      // quantity and summary fields have the same values
      const expectedValues = {
        lightAPICalls: (testEnv.usageDocumentsCount * quantites.lightAPICalls) / 1000,
        heavyAPICalls: testEnv.usageDocumentsCount * quantites.heavyAPICalls,
        // accumulate function is defined as max
        storage: quantites.storage / bytesInGigabyte
      };

      if(!processedDocs)
        expect(cleanReport(updatedReport)).to.deep.equal(createExpectedInitialReport(
          testOrgID, expectedValues, expectedValues));
      else
        deltaCompareReports(cleanReport(updatedReport), currentReport, expectedValues, expectedValues);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Controller for the settings legal screen
 *
 * @class Controllers.settings.legal
 * @uses core
 */
var APP = require("core");

var CONFIG = arguments[0];

/**
 * Initializes the controller
 */
$.init = function() {
	APP.log("debug", "settings_legal.init | " + JSON.stringify(CONFIG));

	$.container.url = CONFIG.url;
	$.container.scalesPageToFit = true;
	$.container.willHandleTouches = false;

	$.NavigationBar.setBackgroundColor(APP.Settings.colors.primary);
	$.NavigationBar.setTitle(CONFIG.title);

	$.NavigationBar.showBack(function(_event) {
		APP.removeChild({
			modal: true
			animation: APP.AnimationStyle.SlideLeft
		});
	});
};

// Kick off the init
$.init();<commit_msg>no message<commit_after>/**
 * Controller for the settings legal screen
 *
 * @class Controllers.settings.legal
 * @uses core
 */
var APP = require("core");

var CONFIG = arguments[0];

/**
 * Initializes the controller
 */
$.init = function() {
	APP.log("debug", "settings_legal.init | " + JSON.stringify(CONFIG));

	$.container.url = CONFIG.url;
	$.container.scalesPageToFit = true;
	$.container.willHandleTouches = false;

	$.NavigationBar.setBackgroundColor(APP.Settings.colors.primary);
	$.NavigationBar.setTitle(CONFIG.title);

	$.NavigationBar.showBack(function(_event) {
		APP.removeChild({
			modal: true,
			animation: APP.AnimationStyle.SlideLeft
		});
	});
};

// Kick off the init
$.init();<|endoftext|>