<commit_before>(function(angular){
    'use strict';
    var app = angular.module('header.controllers', []);

    app.controller('HeaderCtrl', ['$scope','Notification',
        function ($scope, Notification) {
            $scope.show_notification = true;
            $scope.notifications_loaded = false;
            $scope.notifications = Notification.query(function(res){
                $scope.notifications_loaded = true;
            });
        }
    ]);

    app.filter('actionFilter',function(){
        return function(txt) { // [ação no] tópico tal
            var filtered;
            switch(txt) {
                case 'new_comment':
                    filtered = 'comentou no';
                    break;
                case 'new_topic':
                    filtered = 'criou o';
                    break;
                case 'new_reaction':
                    filtered = 'gostou do';
                    break;
                case 'new_reaction_comment':
                    filtered = 'gostou do comentário no';
                    break;
            }
            return filtered;
        }
    });

    app.filter('dateFilter',function(){
        return function(dt) {
            /*var test = "2016-12-2"+Math.floor(Math.random() * 10)+"T14:58:48.179227Z",
                max = "2016-12-31T20:58:42.346288Z";
            console.log(max+" - "+test)*/
            var past = new Date(dt),
                now = new Date(),
                diff = now.getTime() - past.getTime(),
                labels = {
                    'ano': 31536000000,
                    'mês': 2592000000,
                    'semana': 604800000,
                    'dia': 86400000,
                    'hora': 3600000,
                    'minuto': 6000,
                    'segundo': 1000
                },
                time_int,
                filtered = [];
            angular.forEach(labels,function(val,time_unit){
                time_int = Math.floor(diff/val);
                if(time_int*1000<=val && time_int > 0) {
                    if(time_int > 1) {
                        if(time_unit == "mês") {
                            time_unit = 'meses';
                        }
                        else {
                            time_unit = time_unit+'s';
                        }
                    }
                    filtered.push(time_int+" "+time_unit);
                }
            });
            return filtered[0];
        }
    });

})(window.angular);
<commit_msg>refinando o filtro das notificações e pequenas correções<commit_after>(function(angular){
    'use strict';
    var app = angular.module('header.controllers', []);

    app.controller('HeaderCtrl', ['$scope','Notification',
        function ($scope, Notification) {
            $scope.show_notification = false;
            $scope.notifications_loaded = false;
            $scope.notifications = Notification.query(function(res){
                $scope.notifications_loaded = true;
            });
        }
    ]);

    app.filter('actionFilter',function(){
        return function(txt) { // [ação no] tópico tal
            var filtered;
            switch(txt) {
                case 'new_comment':
                    filtered = 'comentou no';
                    break;
                case 'new_topic':
                    filtered = 'criou o';
                    break;
                case 'new_reaction':
                    filtered = 'gostou do';
                    break;
                case 'new_reaction_comment':
                    filtered = 'gostou de um comentário no';
                    break;
            }
            return filtered;
        }
    });

    app.filter('dateFilter',function(){
        return function(dt) {
            var past = new Date(dt),
                now = new Date(),
                diff = now.getTime() - past.getTime(),
                labels = {
                    'ano': 31536000000,
                    'mês': 2592000000,
                    'semana': 604800000,
                    'dia': 86400000,
                    'hora': 3600000,
                    'minuto': 60000,
                    'segundo': 1000
                },
                time_int,
                filtered = [];
            angular.forEach(labels,function(val,time_unit){
                time_int = Math.floor(diff/val);
                if(diff>=val && time_int > 0) {
                                    console.log(time_int+" "+time_unit)

                    if(time_int > 1) {
                        if(time_unit == "mês") {
                            time_unit = 'meses';
                        }
                        else {
                            time_unit = time_unit+'s';
                        }
                    }
                    filtered.push(time_int+" "+time_unit);
                }
            });
            return filtered[0];
        }
    });

})(window.angular);
<|endoftext|>


<commit_before>'use strict';

var test = require('tape');
var async = require('async');
var json2csv = require('../lib/json2csv');
var parseLdJson = require('../lib/parse-ldjson');
var loadFixtures = require('./helpers/load-fixtures');
var jsonDefault = require('./fixtures/json/default');
var jsonQuotes = require('./fixtures/json/quotes');
var jsonNested = require('./fixtures/json/nested');
var jsonDefaultValue = require('./fixtures/json/defaultValue');
var jsonDefaultValueEmpty = require('./fixtures/json/defaultValueEmpty');
var jsonTrailingBackslash = require('./fixtures/json/trailingBackslash');
var console = require('console');
var csvFixtures = {};

async.parallel(loadFixtures(csvFixtures), function (err) {
  if (err) {
    /*eslint-disable no-console*/
    console.log(err);
    /*eslint-enable no-console*/
  }

  test('should throw if no callback', function (t) {
    t.throws(function () {
      json2csv({
        data: jsonDefault
      });
    }, /Callback is required/);
    t.end();
  });

  test('should error if fieldNames don\'t line up to fields', function (t) {
    json2csv({
      data: jsonDefault,
      field: ['carModel'],
      fieldNames: ['test', 'blah']
    }, function (error, csv) {
      t.equal(error.message, 'fieldNames and fields should be of the same length, if fieldNames is provided.');
      t.notOk(csv);
      t.end();
    });
  });

  test('should parse json to csv', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.default);
      t.end();
    });
  });

  test('should parse json to csv without fields', function (t) {
    json2csv({
      data: jsonDefault
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.default);
      t.end();
    });
  });

  test('should parse json to csv without column title', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      hasCSVColumnTitle: false
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withoutTitle);
      t.end();
    });
  });

  test('should parse data:{} to csv with only column title', function (t) {
    json2csv({
      data: {},
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, '"carModel","price","color"');
      t.end();
    });
  });

  test('should parse data:[null] to csv with only column title', function (t) {
    json2csv({
      data: [null],
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, '"carModel","price","color"');
      t.end();
    });
  });

  test('should output only selected fields', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.selected);
      t.end();
    });
  });

  test('should output not exist field with empty value', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['first not exist field', 'carModel', 'price', 'not exist field', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withNotExistField);
      t.end();
    });
  });

  test('should output reversed order', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['price', 'carModel']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.reversed);
      t.end();
    });
  });

  test('should output a string', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.ok(typeof csv === 'string');
      t.end();
    });
  });

  test('should escape quotes with double quotes', function (t) {
    json2csv({
      data: jsonQuotes,
      fields: ['a string']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.quotes);
      t.end();
    });
  });

  test('should use a custom delimiter when \'quotes\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price'],
      quotes: '\''
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withSimpleQuotes);
      t.end();
    });
  });

  test('should be able to don\'t output quotes when using \'quotes\' property', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price'],
      quotes: ''
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withoutQuotes);
      t.end();
    });
  });

  test('should use a custom delimiter when \'del\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      del: '\t'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.tsv);
      t.end();
    });
  });

  test('should use a custom eol character when \'eol\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      eol: ';'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.eol);
      t.end();
    });
  });

  test('should use a custom eol character when \'newLine\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      newLine: '\r\n'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.newLine);
      t.end();
    });
  });

  test('should name columns as specified in \'fieldNames\' property', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price'],
      fieldNames: ['Car Model', 'Price USD']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.fieldNames);
      t.end();
    });
  });

  test('should output nested properties', function (t) {
    json2csv({
      data: jsonNested,
      fields: ['car.make', 'car.model', 'price', 'color', 'car.ye.ar'],
      fieldNames: ['Make', 'Model', 'Price', 'Color', 'Year']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.nested);
      t.end();
    });
  });

  test('should output default values when missing data', function (t) {
    json2csv({
      data: jsonDefaultValue,
      fields: ['carModel', 'price'],
      defaultValue: 'NULL'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.defaultValue);
      t.end();
    });
  });

  test('should output default values when default value is set to empty string', function (t) {
    json2csv({
      data: jsonDefaultValueEmpty,
      fields: ['carModel', 'price'],
      defaultValue: ''
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.defaultValueEmpty);
      t.end();
    });
  });

  test('should error if params is not an object', function (t) {
    json2csv({
      data: 'not an object',
      field: ['carModel'],
      fieldNames: ['test', 'blah']
    }, function (error, csv) {
      t.equal(error.message, 'params should include "fields" and/or non-empty "data" array of objects');
      t.notOk(csv);
      t.end();
    });
  });

  test('should parse line-delimited JSON', function (t) {
    var input = '{"foo":"bar"}\n{"foo":"qux"}';
    try {
      var parsed = parseLdJson(input);
      t.equal(parsed.length, 2, 'parsed input has correct length');
      t.end();
    } catch(e) {
      t.error(e);
      t.end();
    }
  });

  test('should handle embedded JSON', function (t) {
    json2csv({
      data: {'field1': {embeddedField1: 'embeddedValue1', embeddedField2: 'embeddedValue2'}}
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.embeddedjson);
      t.end();
    });
  });

  test('should flatten embedded JSON', function (t) {
    json2csv({
      data: {'field1': {embeddedField1: 'embeddedValue1', embeddedField2: 'embeddedValue2'}},
      flatten: true
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.flattenedEmbeddedJson);
      t.end();
    });
  });

  test('should process fancy fields option', function (t) {
    json2csv({
      data: [{
        path1: 'hello ',
        path2: 'world!',
        bird: {
          nest1: 'chirp',
          nest2: 'cheep'
        },
        fake: {
          path: 'overrides default'
        }
      }, {
        path1: 'good ',
        path2: 'bye!',
        bird: {
          nest1: 'meep',
          nest2: 'meep'
        }
      }],
      fields: [{
        label: 'PATH1',
        value: 'path1'
      }, {
        label: 'PATH1+PATH2',
        value: function (row) {
          return row.path1+row.path2;
        }
      }, {
        label: 'NEST1',
        value: 'bird.nest1'
      },
      'bird.nest2',
      {
        label: 'nonexistent',
        value: 'fake.path',
        default: 'col specific default value'
      }
      ],
      defaultValue: 'NULL'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.fancyfields);
      t.end();
    });
  });

  test('should parse JSON values with trailing backslashes', function (t) {
    json2csv({
      data: jsonTrailingBackslash,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.trailingBackslash);
      t.end();
    });
  });

  test('should escape " when preceeded by \\', function (t){
    json2csv({
      data: [{field: '\\"'}]
    }, function (error, csv){
      t.error(error);
      t.equal(csv, '"field"\n"\\""');
      t.end();
    });
  });

  test('should format strings to force excel to view the values as strings', function (t) {
    json2csv({
      data: jsonDefault,
      excelStrings:true,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.excelStrings);
      t.end();
    });
  });
});
<commit_msg>remove 'console' require<commit_after>'use strict';

var test = require('tape');
var async = require('async');
var json2csv = require('../lib/json2csv');
var parseLdJson = require('../lib/parse-ldjson');
var loadFixtures = require('./helpers/load-fixtures');
var jsonDefault = require('./fixtures/json/default');
var jsonQuotes = require('./fixtures/json/quotes');
var jsonNested = require('./fixtures/json/nested');
var jsonDefaultValue = require('./fixtures/json/defaultValue');
var jsonDefaultValueEmpty = require('./fixtures/json/defaultValueEmpty');
var jsonTrailingBackslash = require('./fixtures/json/trailingBackslash');
var csvFixtures = {};

async.parallel(loadFixtures(csvFixtures), function (err) {
  if (err) {
    /*eslint-disable no-console*/
    console.log(err);
    /*eslint-enable no-console*/
  }

  test('should throw if no callback', function (t) {
    t.throws(function () {
      json2csv({
        data: jsonDefault
      });
    }, /Callback is required/);
    t.end();
  });

  test('should error if fieldNames don\'t line up to fields', function (t) {
    json2csv({
      data: jsonDefault,
      field: ['carModel'],
      fieldNames: ['test', 'blah']
    }, function (error, csv) {
      t.equal(error.message, 'fieldNames and fields should be of the same length, if fieldNames is provided.');
      t.notOk(csv);
      t.end();
    });
  });

  test('should parse json to csv', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.default);
      t.end();
    });
  });

  test('should parse json to csv without fields', function (t) {
    json2csv({
      data: jsonDefault
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.default);
      t.end();
    });
  });

  test('should parse json to csv without column title', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      hasCSVColumnTitle: false
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withoutTitle);
      t.end();
    });
  });

  test('should parse data:{} to csv with only column title', function (t) {
    json2csv({
      data: {},
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, '"carModel","price","color"');
      t.end();
    });
  });

  test('should parse data:[null] to csv with only column title', function (t) {
    json2csv({
      data: [null],
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, '"carModel","price","color"');
      t.end();
    });
  });

  test('should output only selected fields', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.selected);
      t.end();
    });
  });

  test('should output not exist field with empty value', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['first not exist field', 'carModel', 'price', 'not exist field', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withNotExistField);
      t.end();
    });
  });

  test('should output reversed order', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['price', 'carModel']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.reversed);
      t.end();
    });
  });

  test('should output a string', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.ok(typeof csv === 'string');
      t.end();
    });
  });

  test('should escape quotes with double quotes', function (t) {
    json2csv({
      data: jsonQuotes,
      fields: ['a string']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.quotes);
      t.end();
    });
  });

  test('should use a custom delimiter when \'quotes\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price'],
      quotes: '\''
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withSimpleQuotes);
      t.end();
    });
  });

  test('should be able to don\'t output quotes when using \'quotes\' property', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price'],
      quotes: ''
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.withoutQuotes);
      t.end();
    });
  });

  test('should use a custom delimiter when \'del\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      del: '\t'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.tsv);
      t.end();
    });
  });

  test('should use a custom eol character when \'eol\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      eol: ';'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.eol);
      t.end();
    });
  });

  test('should use a custom eol character when \'newLine\' property is present', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price', 'color'],
      newLine: '\r\n'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.newLine);
      t.end();
    });
  });

  test('should name columns as specified in \'fieldNames\' property', function (t) {
    json2csv({
      data: jsonDefault,
      fields: ['carModel', 'price'],
      fieldNames: ['Car Model', 'Price USD']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.fieldNames);
      t.end();
    });
  });

  test('should output nested properties', function (t) {
    json2csv({
      data: jsonNested,
      fields: ['car.make', 'car.model', 'price', 'color', 'car.ye.ar'],
      fieldNames: ['Make', 'Model', 'Price', 'Color', 'Year']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.nested);
      t.end();
    });
  });

  test('should output default values when missing data', function (t) {
    json2csv({
      data: jsonDefaultValue,
      fields: ['carModel', 'price'],
      defaultValue: 'NULL'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.defaultValue);
      t.end();
    });
  });

  test('should output default values when default value is set to empty string', function (t) {
    json2csv({
      data: jsonDefaultValueEmpty,
      fields: ['carModel', 'price'],
      defaultValue: ''
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.defaultValueEmpty);
      t.end();
    });
  });

  test('should error if params is not an object', function (t) {
    json2csv({
      data: 'not an object',
      field: ['carModel'],
      fieldNames: ['test', 'blah']
    }, function (error, csv) {
      t.equal(error.message, 'params should include "fields" and/or non-empty "data" array of objects');
      t.notOk(csv);
      t.end();
    });
  });

  test('should parse line-delimited JSON', function (t) {
    var input = '{"foo":"bar"}\n{"foo":"qux"}';
    try {
      var parsed = parseLdJson(input);
      t.equal(parsed.length, 2, 'parsed input has correct length');
      t.end();
    } catch(e) {
      t.error(e);
      t.end();
    }
  });

  test('should handle embedded JSON', function (t) {
    json2csv({
      data: {'field1': {embeddedField1: 'embeddedValue1', embeddedField2: 'embeddedValue2'}}
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.embeddedjson);
      t.end();
    });
  });

  test('should flatten embedded JSON', function (t) {
    json2csv({
      data: {'field1': {embeddedField1: 'embeddedValue1', embeddedField2: 'embeddedValue2'}},
      flatten: true
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.flattenedEmbeddedJson);
      t.end();
    });
  });

  test('should process fancy fields option', function (t) {
    json2csv({
      data: [{
        path1: 'hello ',
        path2: 'world!',
        bird: {
          nest1: 'chirp',
          nest2: 'cheep'
        },
        fake: {
          path: 'overrides default'
        }
      }, {
        path1: 'good ',
        path2: 'bye!',
        bird: {
          nest1: 'meep',
          nest2: 'meep'
        }
      }],
      fields: [{
        label: 'PATH1',
        value: 'path1'
      }, {
        label: 'PATH1+PATH2',
        value: function (row) {
          return row.path1+row.path2;
        }
      }, {
        label: 'NEST1',
        value: 'bird.nest1'
      },
      'bird.nest2',
      {
        label: 'nonexistent',
        value: 'fake.path',
        default: 'col specific default value'
      }
      ],
      defaultValue: 'NULL'
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.fancyfields);
      t.end();
    });
  });

  test('should parse JSON values with trailing backslashes', function (t) {
    json2csv({
      data: jsonTrailingBackslash,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.trailingBackslash);
      t.end();
    });
  });

  test('should escape " when preceeded by \\', function (t){
    json2csv({
      data: [{field: '\\"'}]
    }, function (error, csv){
      t.error(error);
      t.equal(csv, '"field"\n"\\""');
      t.end();
    });
  });

  test('should format strings to force excel to view the values as strings', function (t) {
    json2csv({
      data: jsonDefault,
      excelStrings:true,
      fields: ['carModel', 'price', 'color']
    }, function (error, csv) {
      t.error(error);
      t.equal(csv, csvFixtures.excelStrings);
      t.end();
    });
  });
});
<|endoftext|>


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

'use strict';

var TestCluster = require('./lib/test-cluster.js');

/* Test fail with confusing message if running server.js &
    tests at the same time.
*/

require('./endpoint-logging.js');
require('./health.js');

require('./admin/kill-switch.js');
require('./admin/rate-limiter.js');

require('./child-process/spawn-server.js');

require('./circuits/happy-path.js');
require('./circuits/circuits.js');

require('./clients/process-reporter.js');
require('./clients/statsd.js');
require('./clients/repl.js');
require('./clients/heap-dumps.js');

require('./connections/happy-path.js');
require('./connections/no-body.js');
require('./connections/missing-service-name.js');
require('./connections/invalid-service-name.js');

require('./forward/happy-path.js');
require('./forward/forwarding-to-down-server.js');
require('./forward/forwarding-to-non-existant-service.js');
require('./forward/forwarding-where-entry-node-is-exit-node.js');
require('./forward/forwarding-where-entry-node-is-not-exit-node.js');
require('./forward/thrift.js');
require('./forward/set-k.js');
require('./forward/forwarding-with-tiny-timeout.js');
require('./forward/forwarding-concurrently.js');
require('./forward/forwarding-req-defaults.js');
require('./forward/kill-switch.js');
require('./forward/forwarding-huge-buffer.js');

require('./hosts/happy-path.js');
require('./hosts/no-body.js');
require('./hosts/missing-service-name.js');
require('./hosts/invalid-service-name.js');

require('./hyperbahn-client/todo.js');
require('./hyperbahn-client/kill-switch.js');
require('./hyperbahn-client/egress-nodes.js');

require('./hyperbahn-client/forward.js')(TestCluster);
require('./hyperbahn-client/advertise.js')(TestCluster);
require('./hyperbahn-client/unadvertise.js')(TestCluster);
require('./hyperbahn-client/hostports.js')(TestCluster);
require('./hyperbahn-client/forward-retry.js')(TestCluster);
require('./hyperbahn-client/hyperbahn-down.js')(TestCluster);
require('./hyperbahn-client/hyperbahn-times-out.js')(TestCluster);
require('./hyperbahn-client/rate-limiter.js')(TestCluster);

require('./larch/errors.js');
require('./larch/larch.js');
require('./larch/reservoir-backend.js');

require('./register/to-connected-node.js');
require('./register/with-ringpop-divergence.js');
require('./register/happy-path.js');
require('./register/validation-errors.js');
require('./register/register-where-entry-node-is-exit-node.js');
require('./register/register-when-exit-node-is-down.js');

require('./time-series/making-requests-with-a-single-busy-hyperbahn-worker.js');
require('./time-series/requesting-a-service-with-spiky-traffic.js');

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

'use strict';

var TestCluster = require('./lib/test-cluster.js');

/* Test fail with confusing message if running server.js &
    tests at the same time.
*/

require('./endpoint-logging.js');
require('./health.js');

require('./admin/kill-switch.js');
require('./admin/rate-limiter.js');

require('./child-process/spawn-server.js');

require('./circuits/happy-path.js');
require('./circuits/circuits.js');

require('./clients/process-reporter.js');
require('./clients/statsd.js');
require('./clients/repl.js');
require('./clients/heap-dumps.js');

require('./connections/happy-path.js');
require('./connections/no-body.js');
require('./connections/missing-service-name.js');
require('./connections/invalid-service-name.js');

require('./forward/happy-path.js');
require('./forward/forwarding-to-down-server.js');
require('./forward/forwarding-to-non-existant-service.js');
require('./forward/forwarding-where-entry-node-is-exit-node.js');
require('./forward/forwarding-where-entry-node-is-not-exit-node.js');
require('./forward/thrift.js');
require('./forward/set-k.js');
require('./forward/forwarding-with-tiny-timeout.js');
require('./forward/forwarding-concurrently.js');
require('./forward/forwarding-req-defaults.js');
require('./forward/kill-switch.js');
require('./forward/forwarding-huge-buffer.js');
require('./forward/forwarding-respects-relay-flags.js');
require('./forward/forwarding-under-membershipchange-is-non-event.js');

require('./hosts/happy-path.js');
require('./hosts/no-body.js');
require('./hosts/missing-service-name.js');
require('./hosts/invalid-service-name.js');

require('./hyperbahn-client/todo.js');
require('./hyperbahn-client/kill-switch.js');
require('./hyperbahn-client/egress-nodes.js');

require('./hyperbahn-client/forward.js')(TestCluster);
require('./hyperbahn-client/advertise.js')(TestCluster);
require('./hyperbahn-client/unadvertise.js')(TestCluster);
require('./hyperbahn-client/hostports.js')(TestCluster);
require('./hyperbahn-client/forward-retry.js')(TestCluster);
require('./hyperbahn-client/hyperbahn-down.js')(TestCluster);
require('./hyperbahn-client/hyperbahn-times-out.js')(TestCluster);
require('./hyperbahn-client/rate-limiter.js')(TestCluster);

require('./larch/errors.js');
require('./larch/larch.js');
require('./larch/reservoir-backend.js');
require('./larch/level-router-backend.js');

require('./register/to-connected-node.js');
require('./register/with-ringpop-divergence.js');
require('./register/happy-path.js');
require('./register/validation-errors.js');
require('./register/register-where-entry-node-is-exit-node.js');
require('./register/register-when-exit-node-is-down.js');

require('./time-series/making-requests-with-a-single-busy-hyperbahn-worker.js');
require('./time-series/requesting-a-service-with-spiky-traffic.js');

require('./trace.js');
require('./remote-config-client.js');
require('./remote-config.js');
require('./rate-limiter.js');
require('./sorted-index-of.js');
<|endoftext|>


<commit_before>
var sinon = require('sinon');
var chai = require('chai');
chai.use(require('sinon-chai'));

var expect = chai.expect;

var Lobby = require('../app/pickups/lobby');
var prefixer = require('../app/etc/prefixer');

describe('lobby class', function() {

  it('should have a prototype', function() {
    expect(Lobby.prototype).to.be.an.instanceof(Object);
  });

  it('should have a create function', function() {
    expect(Lobby.create).to.be.an.instanceof(Function);
  });

  describe('lobby instance', function() {

    it('should have instance properties', function() {
      var lobby = Lobby.create({
        players: {},
        map: 'abc',
        format: 2
      });
      expect(lobby._players).to.deep.equal({});
      expect(lobby._map).to.equal('abc');
      expect(lobby._format).to.equal(2);
      expect(lobby._timeout).to.be.greaterThan(0);
      expect(lobby._finalising).to.equal(false);
      expect(lobby._finaliser).to.be.null;
      expect(lobby._createdAt).to.be.greaterThan(0);

      describe('defauls', function() {
        var lobby = Lobby.create({});
        it('should initialise with default instance properties if no options are given', function() {
          expect(lobby._players).to.deep.equal({});
          expect(lobby._map).to.equal('cp_badlands');
          expect(lobby._format).to.equal(6);
        });
      });
    });

    it('should have instance functions', function() {
      var lobby = Lobby.create({
        players: {},
        map: 'abc',
        format: 2
      });
      expect(lobby.add).to.be.an.instanceof(Function);
      expect(lobby.rem).to.be.an.instanceof(Function);
      expect(lobby.isAdded).to.be.an.instanceof(Function);
      expect(lobby.map).to.be.an.instanceof(Function);
      expect(lobby.format).to.be.an.instanceof(Function);
      expect(lobby.players).to.be.an.instanceof(Function);
      expect(lobby.isFull).to.be.an.instanceof(Function);
    });

    describe('properties', function() {
      describe('_players', function() {
        var lobby = Lobby.create({
          players: {},
          map: 'abc',
          format: 2
        });
        it('should be empty after initialisation', function() {
          expect(lobby._players).to.deep.equal({});
        });
        it('should contain a property after add() is invoked', function() {
          lobby.add('abc');
          expect(lobby.players()).to.contain('abc');
        });
        it('should not contain a property after rem() is invoked', function() {
          lobby.rem('abc');
          expect(lobby.players()).to.not.contain('abc');
        });

        describe('isAdded()', function() {
          var lobby = Lobby.create({
            players: {abcd: 'abcd'},
            map: 'abc',
            format: 2
          });
          it('should contain a property after initialisation', function() {
            expect(lobby.isAdded('abcd')).to.equal(true);
          });
          it('should return false for a non existent property', function() {
            expect(lobby.isAdded('lkjasdflksdabcd')).to.equal(false);
          });

          describe('isFull()', function() {
            var lobby = Lobby.create({
              players: {abcd: 'abcd'},
              map: 'abc',
              format: 2
            });
            it('should return false if the number of player properties is less than twice the value of _format', function() {
              expect(lobby.isFull()).to.equal(false);
            });
          });
        });
      });
      describe('_map', function() {
        var lobby = Lobby.create({
          players: {},
          map: 'abc',
          format: 2
        });
        it('should change after map() is invoked', function() {
          lobby.map('def');
          expect(lobby.map()).to.equal('def');
        });
      });
      describe('_format', function() {
        var lobby = Lobby.create({
          players: {},
          map: 'abc',
          format: 2
        });
        it('should change after format() is invoked', function() {
          lobby.format(5);
          expect(lobby.format()).to.equal(10);
        });
      });
      describe('_timeout', function() {
        var lobby = Lobby.create({
          players: {},
          map: 'abc',
          format: 2,
          timeout: 100
        });
        it('should be equal to the given value if provided at construction time', function() {
          expect(lobby._timeout).to.equal(100);
        });
      });
      describe('_finalising', function() {
        it('should be false until total players is equal to double the value of _format', function() {
          var lobby = Lobby.create({
            players: {},
            map: 'abc',
            format: 2,
            timeout: 100
          });
          lobby.add('1');
          expect(lobby._finalising).to.equal(false);
          lobby.add('2');
          expect(lobby._finalising).to.equal(false);
          lobby.add('3');
          expect(lobby._finalising).to.equal(false);
          lobby.add('4');
          expect(lobby._finalising).to.equal(true);
        });
        it('should remain true if total players becomes less than double the value of _format after becoming double the value of _format', function() {
          var lobby = Lobby.create({
            players: {},
            map: 'abc',
            format: 2,
            timeout: 100
          });
          lobby.add('1');
          expect(lobby._finalising).to.equal(false);
          lobby.add('2');
          expect(lobby._finalising).to.equal(false);
          lobby.add('3');
          expect(lobby._finalising).to.equal(false);
          lobby.add('4');
          expect(lobby._finalising).to.equal(true);
          lobby.rem('4');
          lobby.rem('2');
          lobby.add('a');
          expect(lobby._finalising).to.equal(true);
        });
      });
      describe('_finaliser', function() {
        it('should be null until total players is equal to double the value of _format', function() {
          var lobby = Lobby.create({
            players: {},
            map: 'abc',
            format: 2,
            timeout: 100,
            afterTimeout: function() {}
          });
          expect(lobby._finaliser).to.equal(null);
          lobby.add('1');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('2');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('3');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('4');
          expect(lobby._finaliser).to.be.an.instanceof(Object);
        });
      });
      describe('_afterTimeout', function() {
        it('should be invoked after _timeout milliseconds once total players is equal to double the value of _format', function(done) {
          // this test case could be a little dicey...
          //
          // i'm passing the done callback into `afterTimeout`
          // which will cause the test to fail if it's never
          // invoked.
          //
          var lobby = Lobby.create({
            players: {},
            map: 'abc',
            format: 1,
            timeout: 25,
            afterTimeout: done
          });
          expect(lobby._afterTimeout).to.be.an.instanceof(Function);
          lobby.add('1');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('2');
          expect(lobby._finaliser).to.not.equal(null);
        });
      });
    });
  });
});

describe('prefixer', function() {

  it('should return a blank object if no options are passed', function() {
    var prefixed = prefixer();
    expect(prefixed).to.deep.equal({});
  });

  it('should return an object with keys prefixed by an underscore containing value, writable, configurable and enumerable properties', function() {
    var prefixed = prefixer({test: 'a', test2: 'b'});
    expect(prefixed._test).to.deep.equal({
      value: 'a',
      writable: true,
      configurable: true,
      enumerable: true
    });
    expect(prefixed._test2).to.deep.equal({
      value: 'b',
      writable: true,
      configurable: true,
      enumerable: true
    });
  });
});
<commit_msg>added test cases for lobby additions<commit_after>
var sinon = require('sinon');
var chai = require('chai');
chai.use(require('sinon-chai'));

var expect = chai.expect;

var Lobby = require('../app/pickups/lobby');
var prefixer = require('../app/etc/prefixer');

describe('lobby class', function() {

  it('should have a prototype', function() {
    expect(Lobby.prototype).to.be.an.instanceof(Object);
  });

  it('should have a create function', function() {
    expect(Lobby.create).to.be.an.instanceof(Function);
  });

  describe('lobby instance', function() {

    it('should have instance properties', function() {
      var lobby = Lobby.create({
        players: {},
        map: 'abc',
        format: 2
      });
      expect(lobby._players).to.deep.equal({});
      expect(lobby._map).to.equal('abc');
      expect(lobby._format).to.equal(2);
      expect(lobby._timeout).to.be.greaterThan(0);
      expect(lobby._finalising).to.equal(false);
      expect(lobby._finaliser).to.be.null;
      expect(lobby._createdAt).to.be.greaterThan(0);

      describe('defaults', function() {
        var lobby = Lobby.create({});
        it('should initialise with default instance properties if no options are given', function() {
          expect(lobby._players).to.deep.equal({});
          expect(lobby._map).to.equal('cp_badlands');
          expect(lobby._format).to.equal(6);
        });
      });
    });

    it('should have instance functions', function() {
      var lobby = Lobby.create({
        players: {},
        map: 'abc',
        format: 2
      });
      expect(lobby.add).to.be.an.instanceof(Function);
      expect(lobby.rem).to.be.an.instanceof(Function);
      expect(lobby.isAdded).to.be.an.instanceof(Function);
      expect(lobby.map).to.be.an.instanceof(Function);
      expect(lobby.format).to.be.an.instanceof(Function);
      expect(lobby.players).to.be.an.instanceof(Function);
      expect(lobby.isFull).to.be.an.instanceof(Function);
    });

    describe('properties', function() {
      describe('_players', function() {
        var lobby = Lobby.create();
        it('should be empty after initialisation', function() {
          expect(lobby._players).to.deep.equal({});
        });
        it('should contain a property after add() is invoked', function() {
          lobby.add('abc');
          expect(lobby.players()).to.contain('abc');
        });
        it('should not contain a property after rem() is invoked', function() {
          lobby.rem('abc');
          expect(lobby.players()).to.not.contain('abc');
        });
      });
      describe('isAdded()', function() {
        var lobby = Lobby.create({players: {abcd: 'abcd'}});
        it('should contain a property after initialisation', function() {
          expect(lobby.isAdded('abcd')).to.equal(true);
        });
        it('should return false for a non existent property', function() {
          expect(lobby.isAdded('lkjasdflksdabcd')).to.equal(false);
        });
      });
      describe('isFull()', function() {
        var lobby = Lobby.create({format: 2});
        it('should return false if the number of player properties is less than twice the value of _format', function() {
          expect(lobby.isFull()).to.equal(false);
        });
        it('should return true if the number of player properties is twice the value of _format', function() {
          lobby.add('1');
          lobby.add('2');
          lobby.add('3');
          lobby.add('4');
          expect(lobby.isFull()).to.equal(true);
        });
      });
      describe('_map', function() {
        var lobby = Lobby.create();
        it('should change after map() is invoked', function() {
          lobby.map('def');
          expect(lobby.map()).to.equal('def');
        });
      });
      describe('_format', function() {
        var lobby = Lobby.create({format: 2});
        it('should change after format() is invoked', function() {
          lobby.format(5);
          expect(lobby.format()).to.equal(10);
        });
      });
      describe('_timeout', function() {
        var lobby = Lobby.create({timeout: 100});
        it('should be equal to the given value if provided at construction time', function() {
          expect(lobby._timeout).to.equal(100);
        });
      });
      describe('_finalising', function() {
        it('should be false until total players is equal to double the value of _format', function() {
          var lobby = Lobby.create({format: 2});
          lobby.add('1');
          expect(lobby._finalising).to.equal(false);
          lobby.add('2');
          expect(lobby._finalising).to.equal(false);
          lobby.add('3');
          expect(lobby._finalising).to.equal(false);
          lobby.add('4');
          expect(lobby._finalising).to.equal(true);
        });
        it('should remain true if total players becomes less than double the value of _format after becoming double the value of _format', function() {
          var lobby = Lobby.create({format: 2});
          lobby.add('1');
          expect(lobby._finalising).to.equal(false);
          lobby.add('2');
          expect(lobby._finalising).to.equal(false);
          lobby.add('3');
          expect(lobby._finalising).to.equal(false);
          lobby.add('4');
          expect(lobby._finalising).to.equal(true);
          lobby.rem('4');
          lobby.rem('2');
          lobby.add('a');
          expect(lobby._finalising).to.equal(true);
        });
      });
      describe('_finaliser', function() {
        it('should be null until total players is equal to double the value of _format', function() {
          var lobby = Lobby.create({format: 2});
          expect(lobby._finaliser).to.equal(null);
          lobby.add('1');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('2');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('3');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('4');
          expect(lobby._finaliser).to.be.an.instanceof(Object);
        });
      });
      describe('_starting', function() {
        it('should be invoked after _timeout milliseconds once total players is equal to double the value of _format', function(done) {
          var lobby = Lobby.create({
            format: 1,
            timeout: 25,
            starting: done,
            postponed: done
          });
          lobby.add('1');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('2');
          expect(lobby._finaliser).to.not.equal(null);
        });
      });
      describe('_postponed', function() {
        it('should be invoked after _timeout milliseconds once total players is equal to double the value of _format and subsequently becomes less than double the value of _format', function(done) {
          var lobby = Lobby.create({
            format: 1,
            timeout: 25,
            starting: done,
            postponed: done
          });
          lobby.add('1');
          expect(lobby._finaliser).to.equal(null);
          lobby.add('2');
          expect(lobby._finaliser).to.not.equal(null);
          lobby.rem('2');
        });
      });
    });
  });
});

describe('prefixer', function() {

  it('should return a blank object if no options are passed', function() {
    var prefixed = prefixer();
    expect(prefixed).to.deep.equal({});
  });

  it('should return an object with keys prefixed by an underscore containing value, writable, configurable and enumerable properties', function() {
    var prefixed = prefixer({test: 'a', test2: 'b'});
    expect(prefixed._test).to.deep.equal({
      value: 'a',
      writable: true,
      configurable: true,
      enumerable: true
    });
    expect(prefixed._test2).to.deep.equal({
      value: 'b',
      writable: true,
      configurable: true,
      enumerable: true
    });
  });
});
<|endoftext|>


<commit_before>var Database = require('../lib'),
  db = new Database();

var posts = db.model('posts', {
  title: String,
  layout: {type: String, default: 'post'},
  comments: [Number]
});

describe('Model', function(){
  var results = {
    1: {
      title: 'First',
      layout: 'post',
      comments: [],
      _id: 1
    },
    2: {
      title: 'First',
      layout: 'page',
      comments: [1, 2, 3],
      _id: 2
    },
    3: {
      title: 'Second',
      layout: 'post',
      comments: [],
      _id: 3
    },
    default: {
      title: '',
      layout: 'post',
      comments: []
    }
  };

  describe('insert()', function(){
    it('one object', function(done){
      var obj = {
        title: 'First'
      };

      posts.insert(obj, function(item, id){
        item.should.eql(results[1]);
        id.should.eql(1);
        done();
      });
    });

    it('an array including two objects', function(done){
      var arr = [
        {
          title: 'First',
          layout: 'page',
          comments: [1, '2', 3]
        },
        {
          title: 'Second'
        }
      ];

      posts.insert(arr, function(item){
        item[0].should.eql(results[2]);
        item[1].should.eql(results[3]);
        done();
      });
    });
  });

  describe('get()', function(){
    it('one item', function(){
      var item = posts.get(1);
      item.should.eql(results[1]);
    });

    it('an array', function(){
      var arr = posts.get([2, 3]);
      arr[0].should.eql(results[2]);
      arr[1].should.eql(results[3]);
    });

    it('two arguments', function(){
      var arr = posts.get(2, 3);
      arr[0].should.eql(results[2]);
      arr[1].should.eql(results[3]);
    });
  });

  describe('count()', function(){
    it('should equal 3', function(){
      posts.count().should.eql(3);
    });
  });

  describe('length', function(){
    it('should equal 3', function(){
      posts.length.should.eql(3);
    });
  });

  describe('toArray()', function(){
    it('should return an array including all items', function(){
      var arr = posts.toArray();
      for (var i=0, len=arr.length; i<len; i++){
        arr[i].should.eql(results[i + 1]);
      }
    });
  });

  describe('each()', function(){
    it('should iterate over all items', function(){
      posts.each(function(item, i){
        item.should.eql(results[i]);
      });
    });
  });

  describe('first()', function(){
    it('should return the first element', function(){
      var item = posts.first();
      item.should.eql(results[1]);
    });
  });

  describe('last()', function(){
    it('should return the last element', function(){
      var item = posts.last();
      item.should.eql(results[3]);
    });
  });

  describe('eq()', function(){
    it('should return the second element', function(){
      var item = posts.eq(1);
      item.should.eql(results[2]);
    });

    it('should return the last element', function(){
      var item = posts.eq(-1);
      item.should.eql(results[3]);
    });
  });

  describe('slice()', function(){
    it('should return the second element', function(){
      var item = posts.slice(1, 2);
      item._index.should.eql([2]);
    });

    it('should return the last element', function(){
      var item = posts.slice(-1);
      item._index.should.eql([3]);
    });
  });

  describe('limit()', function(){
    it('should return the first two elements', function(){
      var item = posts.limit(2);
      item._index.should.eql([1, 2]);
    });
  });

  describe('skip()', function(){
    it('should skip the first two elements', function(){
      var item = posts.skip(2);
      item._index.should.eql([3]);
    });
  });

  describe('random()', function(){
    it('should shuffle the model', function(){
      var item = posts.random();
      item._index.should.include(1);
      item._index.should.include(2);
      item._index.should.include(3);
    });
  });

  describe('sort()', function(){
    it('ascending', function(){
      var item = posts.sort('title');
      item._index.should.eql([1, 2, 3]);
    });

    it('descending', function(){
      var item = posts.sort('title', -1);
      item._index.should.eql([3, 2, 1]);
    });
  });

  describe('reverse()', function(){
    it('should return a reversed model', function(){
      var item = posts.reverse();
      item._index.should.eql([3, 2, 1]);
    });
  });

  describe('find()', function(){
    it('normal', function(){
      var item = posts.find({layout: 'post'});
      item._index.should.eql([1, 3]);
    });

    it('RegExp', function(){
      var item = posts.find({title: /first/i});
      item._index.should.eql([1, 2]);
    });

    it('$lt', function(){
      var item = posts.find({_id: {$lt: 2}});
      item._index.should.eql([1]);
    });

    it('$lte', function(){
      var item = posts.find({_id: {$lte: 2}});
      item._index.should.eql([1, 2]);
    });

    it('$gt', function(){
      var item = posts.find({_id: {$gt: 2}});
      item._index.should.eql([3]);
    });

    it('$gte', function(){
      var item = posts.find({_id: {$gte: 2}});
      item._index.should.eql([2, 3]);
    });

    it('$length', function(){
      var item = posts.find({comments: {$length: 3}});
      item._index.should.eql([2]);
    });

    it('$in', function(){
      var item = posts.find({comments: {$in: 1}});
      item._index.should.eql([2]);
    });

    it('$nin', function(){
      var item = posts.find({comments: {$nin: 1}});
      item._index.should.eql([1, 3]);
    });

    it('$all', function(){
      var item = posts.find({comments: {$all: [1, 2, 3]}});
      item._index.should.eql([2]);
    });

    it('$exists', function(){
      var item = posts.find({title: {$exists: false}});
      item._index.should.eql([]);
      var item = posts.find({title: {$exists: true}});
      item._index.should.eql([1, 2, 3]);
    });

    it('$ne', function(){
      var item = posts.find({title: {$ne: 'First'}});
      item._index.should.eql([3]);
    });
  });

  describe('replace()', function(){
    it('one item', function(){
      posts.replace(1, {});
      var item = posts.get(1);
      item.should.include(results.default);
    });

    it('all items', function(){
      posts.replace({});
      var item = posts.toArray();
      for (var i=0; i<3; i++){
        item[i].should.include(results.default);
      }
    });
  });

  describe('update()', function(){
    it('one item', function(){
      posts.update(1, {title: 'Third', number: 1});
      var item = posts.get(1);
      item.title.should.eql('Third');
      item.number.should.eql(1);
    });

    it('all items', function(){
      posts.update({ext: false});
      var arr = posts.toArray();
      for (var i=0; i<3; i++){
        arr[i].ext.should.be.false;
      }
    });

    it('$push', function(){
      posts.update(1, {comments: {$push: 1}});
      var item = posts.get(1);
      item.comments.should.eql([1]);
      posts.update(1, {comments: {$push: [2, 3]}});
      var item = posts.get(1);
      item.comments.should.eql([1, 2, 3]);
    });

    it('$pull', function(){
      posts.update(1, {comments: {$pull: 1}});
      var item = posts.get(1);
      item.comments.should.eql([2, 3]);
      posts.update(1, {comments: {$pull: [2, 3]}});
      var item = posts.get(1);
      item.comments.should.eql([]);
    });

    it('$shift', function(){
      posts.update(1, {comments: [1, 2]});
      posts.update(1, {comments: {$shift: 1}});
      var item = posts.get(1);
      item.comments.should.eql([2]);
      posts.update(1, {comments: {$shift: -1}});
      var item = posts.get(1);
      item.comments.should.eql([]);
    });

    it('$pop', function(){
      posts.update(1, {comments: [1, 2]});
      posts.update(1, {comments: {$pop: 1}});
      var item = posts.get(1);
      item.comments.should.eql([1]);
      posts.update(1, {comments: {$pop: -1}});
      var item = posts.get(1);
      item.comments.should.eql([]);
    });

    it('$inc', function(){
      posts.update(1, {num: 1});
      posts.update(1, {num: {$inc: 2}});
      var item = posts.get(1);
      item.num.should.eql(3);
      posts.update(1, {num: {$inc: -2}});
      var item = posts.get(1);
      item.num.should.eql(1);
    });

    it('$dec', function(){
      posts.update(1, {num: 1});
      posts.update(1, {num: {$dec: 2}});
      var item = posts.get(1);
      item.num.should.eql(-1);
      posts.update(1, {num: {$dec: -2}});
      var item = posts.get(1);
      item.num.should.eql(1);
    });
  });

  describe('remove()', function(){
    it('one item', function(){
      posts.remove(1);
      posts._index.should.eql([2, 3]);
      (typeof posts.get(1)).should.eql('undefined');
    });

    it('an array', function(){
      posts.remove([2, 3]);
      posts._index.should.eql([]);
      (typeof posts.get(2)).should.eql('undefined');
      (typeof posts.get(3)).should.eql('undefined');
    });

    it('multiple arguments', function(){
      posts.insert([{}, {}]);
      posts.remove(4, 5);
      posts._index.should.eql([]);
      (typeof posts.get(4)).should.eql('undefined');
      (typeof posts.get(5)).should.eql('undefined');
    });

    it('all items', function(){
      posts.insert([{}, {}, {}]);
      posts.remove();
      posts._index.should.eql([]);
      (typeof posts.get(6)).should.eql('undefined');
      (typeof posts.get(7)).should.eql('undefined');
      (typeof posts.get(8)).should.eql('undefined');
    });
  });
});

describe('Store', function(){
  var obj = {foo: 1, bar: 2},
    store = new db.Store(obj);

  describe('list()', function(){
    it('should return all elements', function(){
      var list = store.list();
      list.should.eql(obj);
    });
  });

  describe('get()', function(){
    it('should return the specific element', function(){
      var item = store.get('foo');
      item.should.eql(1);
    });
  });

  describe('set()', function(){
    it('should update the specific element', function(){
      store.set('foo', 4);
      var item = store.get('foo');
      item.should.eql(4);
    });

    it('should insert a new element', function(){
      store.set('test', 'test');
      var item = store.get('test');
      item.should.eql('test');
    });
  });

  describe('remove()', function(){
    it('should remove the specific element', function(){
      store.remove('test');
      var item = store.get('test');
      (typeof item).should.eql('undefined');
    });
  })
});<commit_msg>Test updated. Added schema test<commit_after>var Database = require('../lib'),
  db = new Database();

var posts = db.model('posts', {
  title: String,
  layout: {type: String, default: 'post'},
  comments: [Number]
});

describe('Model', function(){
  var results = {
    1: {
      title: 'First',
      layout: 'post',
      comments: [],
      _id: 1
    },
    2: {
      title: 'First',
      layout: 'page',
      comments: [1, 2, 3],
      _id: 2
    },
    3: {
      title: 'Second',
      layout: 'post',
      comments: [],
      _id: 3
    },
    default: {
      title: '',
      layout: 'post',
      comments: []
    }
  };

  describe('insert()', function(){
    it('one object', function(done){
      var obj = {
        title: 'First'
      };

      posts.insert(obj, function(item, id){
        item.should.eql(results[1]);
        id.should.eql(1);
        done();
      });
    });

    it('an array including two objects', function(done){
      var arr = [
        {
          title: 'First',
          layout: 'page',
          comments: [1, '2', 3]
        },
        {
          title: 'Second'
        }
      ];

      posts.insert(arr, function(item){
        item[0].should.eql(results[2]);
        item[1].should.eql(results[3]);
        done();
      });
    });
  });

  describe('get()', function(){
    it('one item', function(){
      var item = posts.get(1);
      item.should.eql(results[1]);
    });

    it('an array', function(){
      var arr = posts.get([2, 3]);
      arr[0].should.eql(results[2]);
      arr[1].should.eql(results[3]);
    });

    it('two arguments', function(){
      var arr = posts.get(2, 3);
      arr[0].should.eql(results[2]);
      arr[1].should.eql(results[3]);
    });
  });

  describe('count()', function(){
    it('equals 3', function(){
      posts.count().should.eql(3);
    });
  });

  describe('length', function(){
    it('equals 3', function(){
      posts.length.should.eql(3);
    });
  });

  describe('toArray()', function(){
    it('returns an array including all items', function(){
      var arr = posts.toArray();
      for (var i=0, len=arr.length; i<len; i++){
        arr[i].should.eql(results[i + 1]);
      }
    });
  });

  describe('each()', function(){
    it('iterates over all items', function(){
      posts.each(function(item, i){
        item.should.eql(results[i]);
      });
    });
  });

  describe('first()', function(){
    it('returns the first element', function(){
      var item = posts.first();
      item.should.eql(results[1]);
    });
  });

  describe('last()', function(){
    it('returns the last element', function(){
      var item = posts.last();
      item.should.eql(results[3]);
    });
  });

  describe('eq()', function(){
    it('returns the second element', function(){
      var item = posts.eq(1);
      item.should.eql(results[2]);
    });

    it('returns the last element', function(){
      var item = posts.eq(-1);
      item.should.eql(results[3]);
    });
  });

  describe('slice()', function(){
    it('returns the second element', function(){
      var item = posts.slice(1, 2);
      item._index.should.eql([2]);
    });

    it('returns the last element', function(){
      var item = posts.slice(-1);
      item._index.should.eql([3]);
    });
  });

  describe('limit()', function(){
    it('returns the first two elements', function(){
      var item = posts.limit(2);
      item._index.should.eql([1, 2]);
    });
  });

  describe('skip()', function(){
    it('skips the first two elements', function(){
      var item = posts.skip(2);
      item._index.should.eql([3]);
    });
  });

  describe('random()', function(){
    it('shuffles the model', function(){
      var item = posts.random();
      item._index.should.include(1);
      item._index.should.include(2);
      item._index.should.include(3);
    });
  });

  describe('sort()', function(){
    it('ascending', function(){
      var item = posts.sort('title');
      item._index.should.eql([1, 2, 3]);
    });

    it('descending', function(){
      var item = posts.sort('title', -1);
      item._index.should.eql([3, 2, 1]);
    });
  });

  describe('reverse()', function(){
    it('returns a reversed model', function(){
      var item = posts.reverse();
      item._index.should.eql([3, 2, 1]);
    });
  });

  describe('find()', function(){
    it('normal', function(){
      var item = posts.find({layout: 'post'});
      item._index.should.eql([1, 3]);
    });

    it('RegExp', function(){
      var item = posts.find({title: /first/i});
      item._index.should.eql([1, 2]);
    });

    it('$lt', function(){
      var item = posts.find({_id: {$lt: 2}});
      item._index.should.eql([1]);
    });

    it('$lte', function(){
      var item = posts.find({_id: {$lte: 2}});
      item._index.should.eql([1, 2]);
    });

    it('$gt', function(){
      var item = posts.find({_id: {$gt: 2}});
      item._index.should.eql([3]);
    });

    it('$gte', function(){
      var item = posts.find({_id: {$gte: 2}});
      item._index.should.eql([2, 3]);
    });

    it('$length', function(){
      var item = posts.find({comments: {$length: 3}});
      item._index.should.eql([2]);
    });

    it('$in', function(){
      var item = posts.find({comments: {$in: 1}});
      item._index.should.eql([2]);
    });

    it('$nin', function(){
      var item = posts.find({comments: {$nin: 1}});
      item._index.should.eql([1, 3]);
    });

    it('$all', function(){
      var item = posts.find({comments: {$all: [1, 2, 3]}});
      item._index.should.eql([2]);
    });

    it('$exists', function(){
      var item = posts.find({title: {$exists: false}});
      item._index.should.eql([]);
      var item = posts.find({title: {$exists: true}});
      item._index.should.eql([1, 2, 3]);
    });

    it('$ne', function(){
      var item = posts.find({title: {$ne: 'First'}});
      item._index.should.eql([3]);
    });
  });

  describe('replace()', function(){
    it('one item', function(){
      posts.replace(1, {});
      var item = posts.get(1);
      item.should.include(results.default);
    });

    it('all items', function(){
      posts.replace({});
      var item = posts.toArray();
      for (var i=0; i<3; i++){
        item[i].should.include(results.default);
      }
    });
  });

  describe('update()', function(){
    it('one item', function(){
      posts.update(1, {title: 'Third', number: 1});
      var item = posts.get(1);
      item.title.should.eql('Third');
      item.number.should.eql(1);
    });

    it('all items', function(){
      posts.update({ext: false});
      var arr = posts.toArray();
      for (var i=0; i<3; i++){
        arr[i].ext.should.be.false;
      }
    });

    it('$push', function(){
      posts.update(1, {comments: {$push: 1}});
      var item = posts.get(1);
      item.comments.should.eql([1]);
      posts.update(1, {comments: {$push: [2, 3]}});
      var item = posts.get(1);
      item.comments.should.eql([1, 2, 3]);
    });

    it('$pull', function(){
      posts.update(1, {comments: {$pull: 1}});
      var item = posts.get(1);
      item.comments.should.eql([2, 3]);
      posts.update(1, {comments: {$pull: [2, 3]}});
      var item = posts.get(1);
      item.comments.should.eql([]);
    });

    it('$shift', function(){
      posts.update(1, {comments: [1, 2]});
      posts.update(1, {comments: {$shift: 1}});
      var item = posts.get(1);
      item.comments.should.eql([2]);
      posts.update(1, {comments: {$shift: -1}});
      var item = posts.get(1);
      item.comments.should.eql([]);
    });

    it('$pop', function(){
      posts.update(1, {comments: [1, 2]});
      posts.update(1, {comments: {$pop: 1}});
      var item = posts.get(1);
      item.comments.should.eql([1]);
      posts.update(1, {comments: {$pop: -1}});
      var item = posts.get(1);
      item.comments.should.eql([]);
    });

    it('$inc', function(){
      posts.update(1, {num: 1});
      posts.update(1, {num: {$inc: 2}});
      var item = posts.get(1);
      item.num.should.eql(3);
      posts.update(1, {num: {$inc: -2}});
      var item = posts.get(1);
      item.num.should.eql(1);
    });

    it('$dec', function(){
      posts.update(1, {num: 1});
      posts.update(1, {num: {$dec: 2}});
      var item = posts.get(1);
      item.num.should.eql(-1);
      posts.update(1, {num: {$dec: -2}});
      var item = posts.get(1);
      item.num.should.eql(1);
    });
  });

  describe('remove()', function(){
    it('one item', function(){
      posts.remove(1);
      posts._index.should.eql([2, 3]);
      (typeof posts.get(1)).should.eql('undefined');
    });

    it('an array', function(){
      posts.remove([2, 3]);
      posts._index.should.eql([]);
      (typeof posts.get(2)).should.eql('undefined');
      (typeof posts.get(3)).should.eql('undefined');
    });

    it('multiple arguments', function(){
      posts.insert([{}, {}]);
      posts.remove(4, 5);
      posts._index.should.eql([]);
      (typeof posts.get(4)).should.eql('undefined');
      (typeof posts.get(5)).should.eql('undefined');
    });

    it('all items', function(){
      posts.insert([{}, {}, {}]);
      posts.remove();
      posts._index.should.eql([]);
      (typeof posts.get(6)).should.eql('undefined');
      (typeof posts.get(7)).should.eql('undefined');
      (typeof posts.get(8)).should.eql('undefined');
    });
  });
});

var schema = new db.Schema({
  first: String,
  last: String
});

schema.virtual('full').get(function(){
  return this.first + ' ' + this.last;
}).set(function(name){
  var arr = name.split(' ');
  this.first = arr[0];
  this.last = arr[1];
});

schema.methods.getAll = function(){
  var obj = {};
  this.each(function(item, id){
    obj[id] = item;
  });
  return obj;
};

var users = db.model('users', schema);
users.insert({first: 'John', last: 'Doe'});

describe('Schema', function(){
  describe('get()', function(){
    it('returns the virtual field', function(){
      var item = users.get(1);
      item.full.should.eql('John Doe');
    });
  });

  describe('set()', function(){
    it('inserts data based on the virtual field', function(){
      users.insert({full: 'Tommy Chen'}, function(item){
        item.should.include({
          first: 'Tommy',
          last: 'Chen',
          full: 'Tommy Chen'
        });
      });
    });
  });

  describe('methods', function(){
    it('getAll', function(){
      var item = users.getAll();
      item.should.eql({
        '1': {
          first: 'John',
          last: 'Doe',
          full: 'John Doe',
          _id: 1
        },
        '2': {
          first: 'Tommy',
          last: 'Chen',
          full: 'Tommy Chen',
          _id: 2
        }
      });
    });
  });
});

describe('Store', function(){
  var obj = {foo: 1, bar: 2},
    store = new db.Store(obj);

  describe('list()', function(){
    it('returns all elements', function(){
      var list = store.list();
      list.should.eql(obj);
    });
  });

  describe('get()', function(){
    it('returns the specific element', function(){
      var item = store.get('foo');
      item.should.eql(1);
    });
  });

  describe('set()', function(){
    it('updates the specific element', function(){
      store.set('foo', 4);
      var item = store.get('foo');
      item.should.eql(4);
    });

    it('inserts a new element', function(){
      store.set('test', 'test');
      var item = store.get('test');
      item.should.eql('test');
    });
  });

  describe('remove()', function(){
    it('removes the specific element', function(){
      store.remove('test');
      var item = store.get('test');
      (typeof item).should.eql('undefined');
    });
  })
});<|endoftext|>


<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// TODO: ATTEMPT TO KILL THIS MODULE USING THIRD PARTY LIBRARIES WHEN IPYWIDGETS
// IS CONVERTED TO NODE COMMONJS.
"use strict";

var $ = require("./jquery");

/**
 * http://www.ietf.org/rfc/rfc4122.txt
 */
function uuid() {
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    return s.join("");
}

/**
 * Wrappable Error class
 *
 * The Error class doesn't actually act on `this`.  Instead it always
 * returns a new instance of Error.  Here we capture that instance so we
 * can apply it's properties to `this`.
 */
function WrappedError(message, error){
    var tmp = Error.apply(this, [message]);

    // Copy the properties of the error over to this.
    var properties = Object.getOwnPropertyNames(tmp);
    for (var i = 0; i < properties.length; i++) {
        this[properties[i]] = tmp[properties[i]];
    }

    // Keep a stack of the original error messages.
    if (error instanceof WrappedError) {
        this.error_stack = error.error_stack;
    } else {
        this.error_stack = [error];
    }
    this.error_stack.push(tmp);

    return this;
}
WrappedError.prototype = Object.create(Error.prototype, {});

/**
 * Tries to load a class
 *
 * Tries to load a class from a module using require.js, if a module
 * is specified, otherwise tries to load a class from the global
 * registry, if the global registry is provided.
 */
function loadClass(class_name, module_name, registry) {
    return new Promise(function(resolve, reject) {

        // Try loading the view module using require.js
        if (module_name) {

            // If the module is jupyter-js-widgets, we can just self import.
            var modulePromise;
            if (module_name === 'jupyter-js-widgets') {
                modulePromise = Promise.resolve(require('../'));
            } else {
                modulePromise = new Promise(function(innerResolve, innerReject) {
                    window.require([module_name], function(module) {
                        innerResolve(module);
                    }, innerReject);
                });
            }

            modulePromise.then(function(module) {
                if (module[class_name] === undefined) {
                    reject(new Error('Class '+class_name+' not found in module '+module_name));
                } else {
                    resolve(module[class_name]);
                }
            });
        } else {
            if (registry && registry[class_name]) {
                resolve(registry[class_name]);
            } else {
                reject(new Error('Class '+class_name+' not found in registry '));
            }
        }
    });
}

/**
 * Resolve a promiseful dictionary.
 * Returns a single Promise.
 */
function resolvePromisesDict(d) {
    var keys = Object.keys(d);
    var values = [];
    keys.forEach(function(key) {
        values.push(d[key]);
    });
    return Promise.all(values).then(function(v) {
        d = {};
        for(var i=0; i<keys.length; i++) {
            d[keys[i]] = v[i];
        }
        return d;
    });
}

/**
 * Creates a wrappable Promise rejection function.
 *
 * Creates a function that returns a Promise.reject with a new WrappedError
 * that has the provided message and wraps the original error that
 * caused the promise to reject.
 */
function reject(message, log) {
    return function promiseRejection(error) {
        var wrapped_error = new WrappedError(message, error);
        if (log) console.error(wrapped_error);
        return Promise.reject(wrapped_error);
    };
}

/**
 * Apply MathJax rendering to an element, and optionally set its text
 *
 * If MathJax is not available, make no changes.
 *
 * Returns the output any number of typeset elements as an array or undefined if
 * MathJax was not available.
 *
 * Parameters
 * ----------
 * element: Node, NodeList, or jQuery selection
 * text: option string
 */
function typeset(element, text) {
    if (arguments.length > 1) {
        if (element.length) {
            for (var i = 0; i < element.length; ++i) {
                var el = element[i];
                el.textContent = text;
            }
        } else {
            element.textContent = text;
        }
    }
    if (!window.MathJax) {
      return;
    }
    var output = [];
    if (element.length) {
        for (var i = 0; i < element.length; ++i) {
            var el = element[i];
            output.push(MathJax.Hub.Queue(['Typeset', MathJax.Hub, el]));
        }
    } else {
        output.push(MathJax.Hub.Queue(['Typeset', MathJax.Hub, element]));
    }
    return output;
}

/**
 * escape text to HTML
 */
var escape_html = function (text) {
    return $("<div/>").text(text).html();
};

module.exports = {
    uuid: uuid,
    WrappedError: WrappedError,
    loadClass: loadClass,
    resolvePromisesDict: resolvePromisesDict,
    reject: reject,
    typeset: typeset,
    escape_html: escape_html
};
<commit_msg>Update escape_html function to remove jQuery<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// TODO: ATTEMPT TO KILL THIS MODULE USING THIRD PARTY LIBRARIES WHEN IPYWIDGETS
// IS CONVERTED TO NODE COMMONJS.
"use strict";

/**
 * http://www.ietf.org/rfc/rfc4122.txt
 */
function uuid() {
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    return s.join("");
}

/**
 * Wrappable Error class
 *
 * The Error class doesn't actually act on `this`.  Instead it always
 * returns a new instance of Error.  Here we capture that instance so we
 * can apply it's properties to `this`.
 */
function WrappedError(message, error){
    var tmp = Error.apply(this, [message]);

    // Copy the properties of the error over to this.
    var properties = Object.getOwnPropertyNames(tmp);
    for (var i = 0; i < properties.length; i++) {
        this[properties[i]] = tmp[properties[i]];
    }

    // Keep a stack of the original error messages.
    if (error instanceof WrappedError) {
        this.error_stack = error.error_stack;
    } else {
        this.error_stack = [error];
    }
    this.error_stack.push(tmp);

    return this;
}
WrappedError.prototype = Object.create(Error.prototype, {});

/**
 * Tries to load a class
 *
 * Tries to load a class from a module using require.js, if a module
 * is specified, otherwise tries to load a class from the global
 * registry, if the global registry is provided.
 */
function loadClass(class_name, module_name, registry) {
    return new Promise(function(resolve, reject) {

        // Try loading the view module using require.js
        if (module_name) {

            // If the module is jupyter-js-widgets, we can just self import.
            var modulePromise;
            if (module_name === 'jupyter-js-widgets') {
                modulePromise = Promise.resolve(require('../'));
            } else {
                modulePromise = new Promise(function(innerResolve, innerReject) {
                    window.require([module_name], function(module) {
                        innerResolve(module);
                    }, innerReject);
                });
            }

            modulePromise.then(function(module) {
                if (module[class_name] === undefined) {
                    reject(new Error('Class '+class_name+' not found in module '+module_name));
                } else {
                    resolve(module[class_name]);
                }
            });
        } else {
            if (registry && registry[class_name]) {
                resolve(registry[class_name]);
            } else {
                reject(new Error('Class '+class_name+' not found in registry '));
            }
        }
    });
}

/**
 * Resolve a promiseful dictionary.
 * Returns a single Promise.
 */
function resolvePromisesDict(d) {
    var keys = Object.keys(d);
    var values = [];
    keys.forEach(function(key) {
        values.push(d[key]);
    });
    return Promise.all(values).then(function(v) {
        d = {};
        for(var i=0; i<keys.length; i++) {
            d[keys[i]] = v[i];
        }
        return d;
    });
}

/**
 * Creates a wrappable Promise rejection function.
 *
 * Creates a function that returns a Promise.reject with a new WrappedError
 * that has the provided message and wraps the original error that
 * caused the promise to reject.
 */
function reject(message, log) {
    return function promiseRejection(error) {
        var wrapped_error = new WrappedError(message, error);
        if (log) console.error(wrapped_error);
        return Promise.reject(wrapped_error);
    };
}

/**
 * Apply MathJax rendering to an element, and optionally set its text
 *
 * If MathJax is not available, make no changes.
 *
 * Returns the output any number of typeset elements as an array or undefined if
 * MathJax was not available.
 *
 * Parameters
 * ----------
 * element: Node, NodeList, or jQuery selection
 * text: option string
 */
function typeset(element, text) {
    if (arguments.length > 1) {
        if (element.length) {
            for (var i = 0; i < element.length; ++i) {
                var el = element[i];
                el.textContent = text;
            }
        } else {
            element.textContent = text;
        }
    }
    if (!window.MathJax) {
      return;
    }
    var output = [];
    if (element.length) {
        for (var i = 0; i < element.length; ++i) {
            var el = element[i];
            output.push(MathJax.Hub.Queue(['Typeset', MathJax.Hub, el]));
        }
    } else {
        output.push(MathJax.Hub.Queue(['Typeset', MathJax.Hub, element]));
    }
    return output;
}

/**
 * escape text to HTML
 */
var escape_html = function(text) {
    var esc  = document.createElement('div');
    esc.innerHTML = text;
    return esc.innerHTML;
};

module.exports = {
    uuid: uuid,
    WrappedError: WrappedError,
    loadClass: loadClass,
    resolvePromisesDict: resolvePromisesDict,
    reject: reject,
    typeset: typeset,
    escape_html: escape_html
};
<|endoftext|>


<commit_before>const linebot = require('../index.js');

const bot = linebot({
  channelId: process.env.CHANNEL_ID,
  channelSecret: process.env.CHANNEL_SECRET,
  channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
  verify: true // default=true
});

bot.on('message', function (event) {
  switch (event.message.type) {
    case 'text':
      switch (event.message.text) {
        case 'Me':
          event.source.profile().then(function (profile) {
            return event.reply('Hello ' + profile.displayName + ' ' + profile.userId);
          });
          break;
        case 'Member':
          event.source.member().then(function (member) {
            return event.reply(JSON.stringify(member));
          });
          break;
        case 'Picture':
          event.reply({
            type: 'image',
            originalContentUrl: 'https://d.line-scdn.net/stf/line-lp/family/en-US/190X190_line_me.png',
            previewImageUrl: 'https://d.line-scdn.net/stf/line-lp/family/en-US/190X190_line_me.png'
          });
          break;
        case 'Location':
          event.reply({
            type: 'location',
            title: 'LINE Plus Corporation',
            address: '1 Empire tower, Sathorn, Bangkok 10120, Thailand',
            latitude: 13.7202068,
            longitude: 100.5298698
          });
          break;
        case 'Push':
          bot.push('U17448c796a01b715d293c34810985a4c', ['Hey!', 'สวัสดี ' + String.fromCharCode(0xD83D, 0xDE01)]);
          break;
        case 'Push2':
          bot.push('Cba71ba25dafbd6a1472c655fe22979e2', 'Push to group');
          break;
        case 'Multicast':
          bot.push(['U17448c796a01b715d293c34810985a4c', 'Cba71ba25dafbd6a1472c655fe22979e2'], 'Multicast!');
          break;
        case 'Broadcast':
          bot.broadcast('Broadcast!');
          break;
        case 'Confirm':
          event.reply({
            type: 'template',
            altText: 'this is a confirm template',
            template: {
              type: 'confirm',
              text: 'Are you sure?',
              actions: [{
                type: 'message',
                label: 'Yes',
                text: 'yes'
              }, {
                type: 'message',
                label: 'No',
                text: 'no'
              }]
            }
          });
          break;
        case 'Multiple':
          return event.reply(['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5']);
          break;
        case 'Version':
          event.reply('linebot@' + require('../package.json').version);
          break;
        default:
          event.reply(event.message.text).then(function (data) {
            console.log('Success', data);
          }).catch(function (error) {
            console.log('Error', error);
          });
          break;
      }
      break;
    case 'image':
      event.message.content().then(function (data) {
        const s = data.toString('hex').substring(0, 32);
        return event.reply('Nice picture! ' + s);
      }).catch(function (err) {
        return event.reply(err.toString());
      });
      break;
    case 'video':
      event.reply('Nice video!');
      break;
    case 'audio':
      event.reply('Nice audio!');
      break;
    case 'location':
      event.reply(['That\'s a good location!', 'Lat:' + event.message.latitude, 'Long:' + event.message.longitude]);
      break;
    case 'sticker':
      event.reply({
        type: 'sticker',
        packageId: 1,
        stickerId: 1
      });
      break;
    default:
      event.reply('Unknow message: ' + JSON.stringify(event));
      break;
  }
});

bot.on('follow', function (event) {
  event.reply('follow: ' + event.source.userId);
});

bot.on('unfollow', function (event) {
  event.reply('unfollow: ' + event.source.userId);
});

bot.on('join', function (event) {
  if(event.source.groupId) {
    event.reply('join group: ' + event.source.groupId);
  }
  if(event.source.roomId) {
    event.reply('join room: ' + event.source.roomId);
  }
});

bot.on('leave', function (event) {
  if(event.source.groupId) {
    console.log('leave group: ' + event.source.groupId);
  }
  if(event.source.roomId) {
    console.log('leave room: ' + event.source.roomId);
  }
});

bot.on('memberJoined', function (event) {
  event.source.profile().then(function (profile) {
    if(event.source.type === 'group') {
      event.reply('memberJoined: Welcome to the group.');
    }
    if(event.source.type === 'room') {
      event.reply('memberJoined: Welcome to the room.');
    }
  });
});

bot.on('memberLeft', function (event) {
  console.log('memberLeft: Goodbye.');
});

bot.on('postback', function (event) {
  event.reply('postback: ' + event.postback.data);
});

bot.on('beacon', function (event) {
  event.reply('beacon: ' + event.beacon.hwid);
});

bot.listen('/linewebhook', process.env.PORT || 80, function () {
  console.log('LineBot is running.');
});
<commit_msg>fix: fix eslint issues on demo.js<commit_after>const linebot = require('../index.js');

const bot = linebot({
  channelId: process.env.CHANNEL_ID,
  channelSecret: process.env.CHANNEL_SECRET,
  channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
  verify: true // default=true
});

bot.on('message', function (event) {
  switch (event.message.type) {
    case 'text':
      switch (event.message.text) {
        case 'Me':
          event.source.profile().then(function (profile) {
            return event.reply('Hello ' + profile.displayName + ' ' + profile.userId);
          });
          break;
        case 'Member':
          event.source.member().then(function (member) {
            return event.reply(JSON.stringify(member));
          });
          break;
        case 'Picture':
          event.reply({
            type: 'image',
            originalContentUrl: 'https://d.line-scdn.net/stf/line-lp/family/en-US/190X190_line_me.png',
            previewImageUrl: 'https://d.line-scdn.net/stf/line-lp/family/en-US/190X190_line_me.png'
          });
          break;
        case 'Location':
          event.reply({
            type: 'location',
            title: 'LINE Plus Corporation',
            address: '1 Empire tower, Sathorn, Bangkok 10120, Thailand',
            latitude: 13.7202068,
            longitude: 100.5298698
          });
          break;
        case 'Push':
          bot.push('U17448c796a01b715d293c34810985a4c', ['Hey!', 'สวัสดี ' + String.fromCharCode(0xD83D, 0xDE01)]);
          break;
        case 'Push2':
          bot.push('Cba71ba25dafbd6a1472c655fe22979e2', 'Push to group');
          break;
        case 'Multicast':
          bot.push(['U17448c796a01b715d293c34810985a4c', 'Cba71ba25dafbd6a1472c655fe22979e2'], 'Multicast!');
          break;
        case 'Broadcast':
          bot.broadcast('Broadcast!');
          break;
        case 'Confirm':
          event.reply({
            type: 'template',
            altText: 'this is a confirm template',
            template: {
              type: 'confirm',
              text: 'Are you sure?',
              actions: [{
                type: 'message',
                label: 'Yes',
                text: 'yes'
              }, {
                type: 'message',
                label: 'No',
                text: 'no'
              }]
            }
          });
          break;
        case 'Multiple':
          return event.reply(['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5']);
        case 'Version':
          event.reply('linebot@' + require('../package.json').version);
          break;
        default:
          event.reply(event.message.text).then(function (data) {
            console.log('Success', data);
          }).catch(function (error) {
            console.log('Error', error);
          });
          break;
      }
      break;
    case 'image':
      event.message.content().then(function (data) {
        const s = data.toString('hex').substring(0, 32);
        return event.reply('Nice picture! ' + s);
      }).catch(function (err) {
        return event.reply(err.toString());
      });
      break;
    case 'video':
      event.reply('Nice video!');
      break;
    case 'audio':
      event.reply('Nice audio!');
      break;
    case 'location':
      event.reply(['That\'s a good location!', 'Lat:' + event.message.latitude, 'Long:' + event.message.longitude]);
      break;
    case 'sticker':
      event.reply({
        type: 'sticker',
        packageId: 1,
        stickerId: 1
      });
      break;
    default:
      event.reply('Unknow message: ' + JSON.stringify(event));
      break;
  }
});

bot.on('follow', function (event) {
  event.reply('follow: ' + event.source.userId);
});

bot.on('unfollow', function (event) {
  event.reply('unfollow: ' + event.source.userId);
});

bot.on('join', function (event) {
  if(event.source.groupId) {
    event.reply('join group: ' + event.source.groupId);
  }
  if(event.source.roomId) {
    event.reply('join room: ' + event.source.roomId);
  }
});

bot.on('leave', function (event) {
  if(event.source.groupId) {
    console.log('leave group: ' + event.source.groupId);
  }
  if(event.source.roomId) {
    console.log('leave room: ' + event.source.roomId);
  }
});

bot.on('memberJoined', function (event) {
  event.source.profile().then(function (/*profile*/) {
    if(event.source.type === 'group') {
      event.reply('memberJoined: Welcome to the group.');
    }
    if(event.source.type === 'room') {
      event.reply('memberJoined: Welcome to the room.');
    }
  });
});

bot.on('memberLeft', function (/*event*/) {
  console.log('memberLeft: Goodbye.');
});

bot.on('postback', function (event) {
  event.reply('postback: ' + event.postback.data);
});

bot.on('beacon', function (event) {
  event.reply('beacon: ' + event.beacon.hwid);
});

bot.listen('/linewebhook', process.env.PORT || 80, function () {
  console.log('LineBot is running.');
});
<|endoftext|>