<commit_before>
/* Start angularLocalStorage */

var angularLocalStorage = angular.module('LocalStorageModule', []);

// You should set a prefix to avoid overwriting any local storage variables from the rest of your app
// e.g. angularLocalStorage.constant('prefix', 'youAppName');
angularLocalStorage.value('prefix', 'ls');
// Cookie options (usually in case of fallback)
// expiry = Number of days before cookies expire // 0 = Does not expire
// path = The web path the cookie represents
angularLocalStorage.constant('cookie', { expiry:30, path: '/'});
angularLocalStorage.constant('notify', { setItem: true, removeItem: false} );

angularLocalStorage.service('localStorageService', [
  '$rootScope',
  'prefix',
  'cookie',
  'notify',
  function($rootScope, prefix, cookie, notify) {

  // If there is a prefix set in the config lets use that with an appended period for readability
  //var prefix = angularLocalStorage.constant;
  if (prefix.substr(-1)!=='.') {
    prefix = !!prefix ? prefix + '.' : '';
  }

  // Checks the browser to see if local storage is supported
  var browserSupportsLocalStorage = function () {
    try {
        return ('localStorage' in window && window['localStorage'] !== null);
    } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
        return false;
    }
  };

  // Directly adds a value to local storage
  // If local storage is not available in the browser use cookies
  // Example use: localStorageService.add('library','angular');
  var addToLocalStorage = function (key, value) {

    // If this browser does not support local storage use cookies
    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      if (notify.setItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
      }
      return addToCookies(key, value);
    }

    // Let's convert undefined values to null to get the value consistent
    if (typeof value == "undefined") value = null;

    try {
      if (angular.isObject(value) || angular.isArray(value)) {
          value = angular.toJson(value);
      }
      localStorage.setItem(prefix+key, value);
      if (notify.setItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'});
      }
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return addToCookies(key, value);
    }
    return true;
  };

  // Directly get a value from local storage
  // Example use: localStorageService.get('library'); // returns 'angular'
  var getFromLocalStorage = function (key) {
    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      return getFromCookies(key);
    }

    var item = localStorage.getItem(prefix+key);
    if (!item) return null;
    if (item.charAt(0) === "{" || item.charAt(0) === "[") {
        return angular.fromJson(item);
    }
    return item;
  };

  // Remove an item from local storage
  // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
  var removeFromLocalStorage = function (key) {
    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
       if (notify.removeItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
      }
      return removeFromCookies(key);
    }

    try {
      localStorage.removeItem(prefix+key);
      if (notify.removeItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'});
      }
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return removeFromCookies(key);
    }
    return true;
  };

  // Return array of keys for local storage
  // Example use: var keys = localStorageService.keys()
  var getKeysForLocalStorage = function () {

    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      return false;
    }

    var prefixLength = prefix.length;
    var keys = [];
    for (var key in localStorage) {
      // Only return keys that are for this app
      if (key.substr(0,prefixLength) === prefix) {
        try {
          keys.push(key.substr(prefixLength))
        } catch (e) {
          $rootScope.$broadcast('LocalStorageModule.notification.error',e.Description);
          return [];
        }
      }
    }
    return keys;
  };

  // Remove all data for this app from local storage
  // Example use: localStorageService.clearAll();
  // Should be used mostly for development purposes
  var clearAllFromLocalStorage = function () {

    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      return clearAllFromCookies();
    }

    var prefixLength = prefix.length;

    for (var key in localStorage) {
      // Only remove items that are for this app
      if (key.substr(0,prefixLength) === prefix) {
        try {
          removeFromLocalStorage(key.substr(prefixLength));
        } catch (e) {
          $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
          return clearAllFromCookies();
        }
      }
    }
    return true;
  };

  // Checks the browser to see if cookies are supported
  var browserSupportsCookies = function() {
    try {
      return navigator.cookieEnabled ||
        ("cookie" in document && (document.cookie.length > 0 ||
        (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return false;
    }
  };

  // Directly adds a value to cookies
  // Typically used as a fallback is local storage is not available in the browser
  // Example use: localStorageService.cookie.add('library','angular');
  var addToCookies = function (key, value) {

    if (typeof value == "undefined") return false;

    if (!browserSupportsCookies()) {
      $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED');
      return false;
    }

    try {
      var expiry = '', expiryDate = new Date();
      if (value === null) {
        cookie.expiry = -1;
        value = '';
      }
      if (cookie.expiry !== 0) {
        expiryDate.setTime(expiryDate.getTime() + (cookie.expiry*24*60*60*1000));
        expiry = "; expires="+expiryDate.toGMTString();
      }
      if (!!key) {
        document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path;
      }
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return false;
    }
    return true;
  };

  // Directly get a value from a cookie
  // Example use: localStorageService.cookie.get('library'); // returns 'angular'
  var getFromCookies = function (key) {
    if (!browserSupportsCookies()) {
      $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED');
      return false;
    }

    var cookies = document.cookie.split(';');
    for(var i=0;i < cookies.length;i++) {
      var thisCookie = cookies[i];
      while (thisCookie.charAt(0)==' ') {
        thisCookie = thisCookie.substring(1,thisCookie.length);
      }
      if (thisCookie.indexOf(prefix+key+'=') === 0) {
        return decodeURIComponent(thisCookie.substring(prefix.length+key.length+1,thisCookie.length));
      }
    }
    return null;
  };

  var removeFromCookies = function (key) {
    addToCookies(key,null);
  };

  var clearAllFromCookies = function () {
    var thisCookie = null, thisKey = null;
    var prefixLength = prefix.length;
    var cookies = document.cookie.split(';');
    for(var i=0;i < cookies.length;i++) {
      thisCookie = cookies[i];
      while (thisCookie.charAt(0)==' ') {
        thisCookie = thisCookie.substring(1,thisCookie.length);
      }
      key = thisCookie.substring(prefixLength,thisCookie.indexOf('='));
      removeFromCookies(key);
    }
  };

  return {
    isSupported: browserSupportsLocalStorage,
    set: addToLocalStorage,
    add: addToLocalStorage, //DEPRECATED
    get: getFromLocalStorage,
    keys: getKeysForLocalStorage,
    remove: removeFromLocalStorage,
    clearAll: clearAllFromLocalStorage,
    cookie: {
      set: addToCookies,
      add: addToCookies, //DEPRECATED
      get: getFromCookies,
      remove: removeFromCookies,
      clearAll: clearAllFromCookies
    }
  };

}]);
<commit_msg>Fixed notices from JSLint<commit_after>
/* Start angularLocalStorage */

var angularLocalStorage = angular.module('LocalStorageModule', []);

// You should set a prefix to avoid overwriting any local storage variables from the rest of your app
// e.g. angularLocalStorage.constant('prefix', 'youAppName');
angularLocalStorage.value('prefix', 'ls');
// Cookie options (usually in case of fallback)
// expiry = Number of days before cookies expire // 0 = Does not expire
// path = The web path the cookie represents
angularLocalStorage.constant('cookie', { expiry:30, path: '/'});
angularLocalStorage.constant('notify', { setItem: true, removeItem: false} );

angularLocalStorage.service('localStorageService', [
  '$rootScope',
  'prefix',
  'cookie',
  'notify',
  function($rootScope, prefix, cookie, notify) {

  // If there is a prefix set in the config lets use that with an appended period for readability
  //var prefix = angularLocalStorage.constant;
  if (prefix.substr(-1)!=='.') {
    prefix = !!prefix ? prefix + '.' : '';
  }

  // Checks the browser to see if local storage is supported
  var browserSupportsLocalStorage = function () {
    try {
        return ('localStorage' in window && window['localStorage'] !== null);
    } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
        return false;
    }
  };

  // Directly adds a value to local storage
  // If local storage is not available in the browser use cookies
  // Example use: localStorageService.add('library','angular');
  var addToLocalStorage = function (key, value) {

    // If this browser does not support local storage use cookies
    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      if (notify.setItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
      }
      return addToCookies(key, value);
    }

    // Let's convert undefined values to null to get the value consistent
    if (typeof value == "undefined") {
      value = null;
    }

    try {
      if (angular.isObject(value) || angular.isArray(value)) {
          value = angular.toJson(value);
      }
      localStorage.setItem(prefix+key, value);
      if (notify.setItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'localStorage'});
      }
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return addToCookies(key, value);
    }
    return true;
  };

  // Directly get a value from local storage
  // Example use: localStorageService.get('library'); // returns 'angular'
  var getFromLocalStorage = function (key) {
    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      return getFromCookies(key);
    }

    var item = localStorage.getItem(prefix+key);
    if (!item) {
      return null;
    }
    if (item.charAt(0) === "{" || item.charAt(0) === "[") {
        return angular.fromJson(item);
    }
    return item;
  };

  // Remove an item from local storage
  // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
  var removeFromLocalStorage = function (key) {
    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
       if (notify.removeItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
      }
      return removeFromCookies(key);
    }

    try {
      localStorage.removeItem(prefix+key);
      if (notify.removeItem) {
        $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'localStorage'});
      }
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return removeFromCookies(key);
    }
    return true;
  };

  // Return array of keys for local storage
  // Example use: var keys = localStorageService.keys()
  var getKeysForLocalStorage = function () {

    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      return false;
    }

    var prefixLength = prefix.length;
    var keys = [];
    for (var key in localStorage) {
      // Only return keys that are for this app
      if (key.substr(0,prefixLength) === prefix) {
        try {
          keys.push(key.substr(prefixLength));
        } catch (e) {
          $rootScope.$broadcast('LocalStorageModule.notification.error',e.Description);
          return [];
        }
      }
    }
    return keys;
  };

  // Remove all data for this app from local storage
  // Example use: localStorageService.clearAll();
  // Should be used mostly for development purposes
  var clearAllFromLocalStorage = function () {

    if (!browserSupportsLocalStorage()) {
      $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
      return clearAllFromCookies();
    }

    var prefixLength = prefix.length;

    for (var key in localStorage) {
      // Only remove items that are for this app
      if (key.substr(0,prefixLength) === prefix) {
        try {
          removeFromLocalStorage(key.substr(prefixLength));
        } catch (e) {
          $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
          return clearAllFromCookies();
        }
      }
    }
    return true;
  };

  // Checks the browser to see if cookies are supported
  var browserSupportsCookies = function() {
    try {
      return navigator.cookieEnabled ||
        ("cookie" in document && (document.cookie.length > 0 ||
        (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return false;
    }
  };

  // Directly adds a value to cookies
  // Typically used as a fallback is local storage is not available in the browser
  // Example use: localStorageService.cookie.add('library','angular');
  var addToCookies = function (key, value) {

    if (typeof value == "undefined") {
      return false;
    }

    if (!browserSupportsCookies()) {
      $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED');
      return false;
    }

    try {
      var expiry = '', expiryDate = new Date();
      if (value === null) {
        cookie.expiry = -1;
        value = '';
      }
      if (cookie.expiry !== 0) {
        expiryDate.setTime(expiryDate.getTime() + (cookie.expiry*24*60*60*1000));
        expiry = "; expires="+expiryDate.toGMTString();
      }
      if (!!key) {
        document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + "; path="+cookie.path;
      }
    } catch (e) {
      $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
      return false;
    }
    return true;
  };

  // Directly get a value from a cookie
  // Example use: localStorageService.cookie.get('library'); // returns 'angular'
  var getFromCookies = function (key) {
    if (!browserSupportsCookies()) {
      $rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED');
      return false;
    }

    var cookies = document.cookie.split(';');
    for(var i=0;i < cookies.length;i++) {
      var thisCookie = cookies[i];
      while (thisCookie.charAt(0)==' ') {
        thisCookie = thisCookie.substring(1,thisCookie.length);
      }
      if (thisCookie.indexOf(prefix+key+'=') === 0) {
        return decodeURIComponent(thisCookie.substring(prefix.length+key.length+1,thisCookie.length));
      }
    }
    return null;
  };

  var removeFromCookies = function (key) {
    addToCookies(key,null);
  };

  var clearAllFromCookies = function () {
    var thisCookie = null, thisKey = null;
    var prefixLength = prefix.length;
    var cookies = document.cookie.split(';');
    for(var i=0;i < cookies.length;i++) {
      thisCookie = cookies[i];
      while (thisCookie.charAt(0)==' ') {
        thisCookie = thisCookie.substring(1,thisCookie.length);
      }
      key = thisCookie.substring(prefixLength,thisCookie.indexOf('='));
      removeFromCookies(key);
    }
  };

  return {
    isSupported: browserSupportsLocalStorage,
    set: addToLocalStorage,
    add: addToLocalStorage, //DEPRECATED
    get: getFromLocalStorage,
    keys: getKeysForLocalStorage,
    remove: removeFromLocalStorage,
    clearAll: clearAllFromLocalStorage,
    cookie: {
      set: addToCookies,
      add: addToCookies, //DEPRECATED
      get: getFromCookies,
      remove: removeFromCookies,
      clearAll: clearAllFromCookies
    }
  };

}]);
<|endoftext|>


<commit_before>/* eslint-disable no-octal */
// vim: expandtab:ts=2:sw=2

const
  assert = require('assert'),
  inbandStandardTests = require('./name-inband-standard'),
  tmp = require('../lib/tmp');

describe('tmp', function () {
  describe('dir()', function () {
    it('with invalid template', function (done) {
      tmp.dir({template:'invalid'}, function (err, result) {
        if (!err) return done(new Error('err expected'));
        try {
          assert.equal(err.message, 'Invalid template provided', 'should have thrown the expected error');
        } catch (err2) {
          done(err);
        }
        done();
      });
    });
  });
  describe('file()', function () {
    it('with invalid template', function (done) {
      tmp.file({template:'invalid'}, function (err, result) {
        if (!err) return done(new Error('err expected'));
        try {
          assert.equal(err.message, 'Invalid template provided', 'should have thrown the expected error');
        } catch (err2) {
          done(err);
        }
        done();
      });
    });
  });
});
<commit_msg>Remove unused variable assignment<commit_after>/* eslint-disable no-octal */
// vim: expandtab:ts=2:sw=2

const
  assert = require('assert'),
  inbandStandardTests = require('./name-inband-standard'),
  tmp = require('../lib/tmp');

describe('tmp', function () {
  describe('dir()', function () {
    it('with invalid template', function (done) {
      tmp.dir({template:'invalid'}, function (err) {
        if (!err) return done(new Error('err expected'));
        try {
          assert.equal(err.message, 'Invalid template provided', 'should have thrown the expected error');
        } catch (err2) {
          done(err);
        }
        done();
      });
    });
  });
  describe('file()', function () {
    it('with invalid template', function (done) {
      tmp.file({template:'invalid'}, function (err) {
        if (!err) return done(new Error('err expected'));
        try {
          assert.equal(err.message, 'Invalid template provided', 'should have thrown the expected error');
        } catch (err2) {
          done(err);
        }
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>ace.define("ace/snippets/textile",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText = "# Jekyll post header\n\
snippet header\n\
	---\n\
	title: ${1:title}\n\
	layout: post\n\
	date: ${2:date} ${3:hour:minute:second} -05:00\n\
	---\n\
\n\
# Image\n\
snippet img\n\
	!${1:url}(${2:title}):${3:link}!\n\
\n\
# Table\n\
snippet |\n\
	|${1}|${2}\n\
\n\
# Link\n\
snippet link\n\
	\"${1:link text}\":${2:url}\n\
\n\
# Acronym\n\
snippet (\n\
	(${1:Expand acronym})${2}\n\
\n\
# Footnote\n\
snippet fn\n\
	[${1:ref number}] ${3}\n\
\n\
	fn$1. ${2:footnote}\n\
	\n\
";
exports.scope = "textile";

});
<commit_msg>Update tmp/bower_components/ace-builds/src-noconflict/snippets/textile.js<commit_after><|endoftext|>


<commit_before>/*
 * grunt-handlebars-template
 * http://gruntjs.com/
 *
 * Copyright (c) 2013 Bret K. Ikehara
 * Licensed under the MIT license.
 */

var grunt = require('grunt'),
	libdir = __dirname + '/../tasks/lib',
    liboptions = require(libdir + '/options.js'),
    libtemplate = require(libdir + '/template.js'),
    libfilter = require(libdir + '/filter.js'),
    options = liboptions.get(),
    compiler = libtemplate.get(options),
    filter = libfilter.get(grunt, compiler, options);

exports.filter = {
	testHelperPattern: function (test) {
		var files = grunt.file.expand('test/src/*'),
			expectedFiles = {
				'test/src/helper-view-name.hbs': true,
				'test/src/helper-dummy.hbs': true
			};

		helperFiles = filter.pattern(files, options.helperPattern);

		test.expect(2);

		helperFiles.forEach(function(value, index) {
			test.equal(expectedFiles[value], true, "Helper files only");
		});

		test.done();
	},
	testPartialPattern: function (test) {
		var files = grunt.file.expand('test/src/*'),
			expectedFiles = {
				'test/src/partial-list.hbs': true
			};

		helperFiles = filter.pattern(files, options.partialPattern);

		test.expect(1);

		helperFiles.forEach(function(value, index) {
			test.equal(expectedFiles[value], true, "Partial files only");
		});

		test.done();
	},
	testTemplatePattern: function (test) {
		var files = grunt.file.expand('test/src/*'),
			expectedFiles = {
				'test/src/template-greeting-with-external-helper.hbs': true,
				'test/src/template-greeting-with-helper.hbs': true,
				'test/src/template-greeting-with-partial.hbs': true,
				'test/src/template-greeting-without-helper.hbs': true
			};

		helperFiles = filter.pattern(files, options.templatePattern);

		test.expect(4);
		helperFiles.forEach(function(value, index) {
			test.equal(expectedFiles[value], true, "Template files only");
		});

		test.done();
	}
};<commit_msg>Updated the function call name.<commit_after>/*
 * grunt-handlebars-template
 * http://gruntjs.com/
 *
 * Copyright (c) 2013 Bret K. Ikehara
 * Licensed under the MIT license.
 */

var grunt = require('grunt'),
	libdir = __dirname + '/../tasks/lib',
    liboptions = require(libdir + '/options.js'),
    libprecompile = require(libdir + '/precompile.js'),
    libfilter = require(libdir + '/filter.js'),
    options = liboptions.get(),
    precompiler = libprecompile.get(grunt, options),
    filter = libfilter.get(grunt, options);

exports.filter = {
	testHelperPattern: function (test) {
		var files = grunt.file.expand('test/src/*'),
			expectedFiles = {
				'test/src/helper-view-name.hbs': true,
				'test/src/helper-dummy.hbs': true
			};

		helperFiles = filter.match(files, options.helperPattern);

		test.expect(2);

		helperFiles.forEach(function(value, index) {
			test.equal(expectedFiles[value], true, "Helper files only");
		});

		test.done();
	},
	testPartialPattern: function (test) {
		var files = grunt.file.expand('test/src/*'),
			expectedFiles = {
				'test/src/partial-list.hbs': true
			};

		helperFiles = filter.match(files, options.partialPattern);

		test.expect(1);

		helperFiles.forEach(function(value, index) {
			test.equal(expectedFiles[value], true, "Partial files only");
		});

		test.done();
	},
	testTemplatePattern: function (test) {
		var files = grunt.file.expand('test/src/*'),
			expectedFiles = {
				'test/src/template-greeting-with-external-helper.hbs': true,
				'test/src/template-greeting-with-helper.hbs': true,
				'test/src/template-greeting-with-partial.hbs': true,
				'test/src/template-greeting-without-helper.hbs': true
			};

		helperFiles = filter.match(files, options.templatePattern);

		test.expect(4);
		helperFiles.forEach(function(value, index) {
			test.equal(expectedFiles[value], true, "Template files only");
		});

		test.done();
	}
};<|endoftext|>


<commit_before>/*yeoman-test*/
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');
const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');
const chalk = require('chalk');

const basedir = path.join(__dirname, '../generators/app');
const name = 'test projectName';
const description = 'test projectDesc';

describe(chalk.bold.cyan('generator-phaser-h5'), () => {

    let tmpdir;

    beforeEach(() => {
        return helpers.run(basedir)
            .inTmpDir(dir => {
                tmpdir = dir;
            })
            .withPrompts({ projectName: name, projectDesc: description, projectLicense: 'MIT', projectSass: true });
    });

    afterEach(() => fsextra.remove(tmpdir));

    it('creates expected files', () => helpers.then(checkAssets).then(checkConfig).then(checkReadme).then(checkScripts));

    function checkConfig() {
        assert.file([
            'gulpfile.js',
            '.jshintrc'
        ]);
        assert.fileContent([
            ['package.json', `"name": ${JSON.stringify(name)}`],
            ['package.json', `"description": ${JSON.stringify(description)}`]
        ]);
    }

    function checkReadme() {
        assert.fileContent([
            ['README.md', `# [${name}]`],
            ['README.md', `${description}`]
        ]);
    }

    function checkScripts() {
        assert.file([
            'src/assets/js/main.js',
            'src/assets/js/entities/Gesture.js',
            'src/assets/js/entities/MovieClip.js',
            'src/assets/js/entities/VideoConfig.js',
            'src/assets/js/states/boot.js',
            'src/assets/js/states/state1.js',
            'src/assets/js/states/preloader.js'
        ]);
    }

    function checkAssets() {
        // const expected = [
        //     'src/index.html',
        //     'src/LICENSE',
        //     'src/assets/css/sass.scss',
        //     'src/assets/img/favicon.ico'
        // ];
        // const files = expected.map(i => path.join(tmpdir, i));
        assert.file([
            'src/index.html',
            'LICENSE',
            'src/assets/css/sass.scss',
            'src/assets/img/favicon.ico'
        ]);
    }
});<commit_msg>:bug: Fix bug<commit_after>/*yeoman-test*/
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');
const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');
const chalk = require('chalk');

const basedir = path.join(__dirname, '../generators/app');
const name = 'test projectName';
const description = 'test projectDesc';

describe(chalk.bold.cyan('generator-phaser-h5'), () => {

    let tmpdir;

    beforeEach(() => {
        return helpers.run(basedir)
            .inTmpDir(dir => {
                tmpdir = dir;
            })
            .withPrompts({ projectName: name, projectDesc: description, projectLicense: 'MIT', projectSass: true });
    });

    afterEach(() => fsextra.remove(tmpdir));

    it('creates expected files', () => checkAssets().then(checkConfig()).then(checkReadme()).then(checkScripts()));

    function checkConfig() {
        assert.file([
            'gulpfile.js',
            '.jshintrc'
        ]);
        assert.fileContent([
            ['package.json', `"name": ${JSON.stringify(name)}`],
            ['package.json', `"description": ${JSON.stringify(description)}`]
        ]);
    }

    function checkReadme() {
        assert.fileContent([
            ['README.md', `# [${name}]`],
            ['README.md', `${description}`]
        ]);
    }

    function checkScripts() {
        assert.file([
            'src/assets/js/main.js',
            'src/assets/js/entities/Gesture.js',
            'src/assets/js/entities/MovieClip.js',
            'src/assets/js/entities/VideoConfig.js',
            'src/assets/js/states/boot.js',
            'src/assets/js/states/state1.js',
            'src/assets/js/states/preloader.js'
        ]);
    }

    function checkAssets() {
        // const expected = [
        //     'src/index.html',
        //     'src/LICENSE',
        //     'src/assets/css/sass.scss',
        //     'src/assets/img/favicon.ico'
        // ];
        // const files = expected.map(i => path.join(tmpdir, i));
        assert.file([
            'src/index.html',
            'LICENSE',
            'src/assets/css/sass.scss',
            'src/assets/img/favicon.ico'
        ]);
    }
});<|endoftext|>


<commit_before>var run = require('./run.js');
var bodec = require('bodec');
var sha1 = require('git-sha1');
var codec = require('../lib/object-codec.js');

var repo = {};
require('../mixins/mem-db.js')(repo);

var pack = require('./sample-pack.js');
var hashes;

run([
  function setup() {
    require('../mixins/pack-ops.js')(repo);
  },
  function testUnpack(end) {
    repo.unpack(singleStream(pack), {
      onProgress: onProgress
    }, function (err, result) {
      if (err) return end(err);
      hashes = result;
      end();
    });
    function onProgress(progress) {
      console.log(progress);
    }
  },
  function testPack(end) {
    var stream;
    repo.pack(hashes, {}, function (err, result) {
      if (err) return end(err);
      stream = result;
      stream.read(onRead);
    });
    function onRead(err, item) {
      if (err) return end(err);
      console.log(item);
      if (item) stream.read(onRead);
      else end();
    }

  }
]);

function singleStream(item) {
  var done = false;
  return { read: function (callback) {
    if (done) return callback();
    done = true;
    callback(null, item);
  }};

}<commit_msg>Make test quieter<commit_after>var run = require('./run.js');
var bodec = require('bodec');

var repo = {};
require('../mixins/mem-db.js')(repo);

var pack = require('./sample-pack.js');
var hashes;

run([
  function setup() {
    require('../mixins/pack-ops.js')(repo);
  },
  function testUnpack(end) {
    repo.unpack(singleStream(pack), {
      onProgress: onProgress
    }, function (err, result) {
      if (err) return end(err);
      hashes = result;
      end();
    });
    function onProgress(progress) {
      // console.log(progress);
    }
  },
  function testPack(end) {
    var stream;
    var parts = [];
    repo.pack(hashes, {}, function (err, result) {
      if (err) return end(err);
      stream = result;
      stream.read(onRead);
    });
    function onRead(err, chunk) {
      if (err) return end(err);
      // console.log(chunk);
      if (chunk) {
        parts.push(chunk);
        return stream.read(onRead);
      }

      end();
    }

  }
]);

function singleStream(item) {
  var done = false;
  return { read: function (callback) {
    if (done) return callback();
    done = true;
    callback(null, item);
  }};

}<|endoftext|>


<commit_before>'use strict';

process.env.NODE_ENV = 'test';

var should = require('should');
var Manifest = require('../index');
var m = new Manifest();
var content = '';

describe('validate', function () {
  it('should return an invalid manifest object', function () {
    try {
      m.validate(content);
    } catch (err) {
      should.throws(err);
      err.toString().should.equal('Error: Manifest is not in a valid JSON format');
    }
  });

  it('should return an invalid manifest with missing mandatory keys for the marketplace', function () {
    content = '{}';

    try {
      m.validate(content);
    } catch (err) {
      should.throws(err);
      err.toString().should.equal('Error: Manifest is missing mandatory fields: name, description, developer');
    }
  });

  it('should return an invalid manifest with missing mandatory keys for non-marketplace', function () {
    content = '{}';
    m.appType = '';

    try {
      m.validate(content);
    } catch (err) {
      should.throws(err);
      err.toString().should.equal('Error: Manifest is missing mandatory fields: name, description');
    }
  });
});
<commit_msg>rename test<commit_after><|endoftext|>


<commit_before>/**
 * Created by acastillo on 4/8/15.
 */
'use strict';

var Data = require('..');
var FS = require('fs');

function createSpectraData(filename, label, data) {
    var spectrum = Data.NMR.fromJcamp(
        FS.readFileSync(__dirname + filename).toString()
    );
    return spectrum;
};

describe('spectra-data test', function () {
    var nH = 8;
    var spectrum=createSpectraData("/data/ethylvinylether/1h.jdx");
    var peakPicking = spectrum.nmrPeakDetection({"nH":nH, realTop:true, thresholdFactor:1,clean:true,compile:true});
    //console.log(Data.ACS.formater.toACS(peakPicking,{solvent:spectrum.getSolventName()}));
    //console.log(peakPicking);
    it('Known patterns', function () {

        //console.log(Data.ACS.formater.toACS(peakPicking,{solvent:spectrum.getSolventName()}));
        for(var i=0;i<peakPicking.length;i++){
            var signal = peakPicking[i];
            if(Math.abs(signal.delta1-1.308)<0.01){
                signal.multiplicity.should.equal("t");
            }
            if(Math.abs(signal.delta1-3.77)<0.01){
                signal.multiplicity.should.equal("q");
            }
            if(Math.abs(signal.delta1-3.99)<0.01){
                signal.multiplicity.should.equal("dd");
            }
            if(Math.abs(signal.delta1-4.2)<0.01){
                signal.multiplicity.should.equal("dd");
            }
            if(Math.abs(signal.delta1-6.47)<0.01){
                signal.multiplicity.should.equal("dd");
            }
        }
    });

    it('Number of patterns', function(){
        peakPicking.length.should.equal(5);
    });

});

<commit_msg>Test peakPicking.length FAILING<commit_after>/**
 * Created by acastillo on 4/8/15.
 */
'use strict';

var Data = require('..');
var FS = require('fs');

function createSpectraData(filename, label, data) {
    var spectrum = Data.NMR.fromJcamp(
        FS.readFileSync(__dirname + filename).toString()
    );
    return spectrum;
};

describe('spectra-data test', function () {
    var nH = 8;
    var spectrum=createSpectraData("/data/ethylvinylether/1h.jdx");
    var peakPicking = spectrum.nmrPeakDetection({"nH":nH, realTop:true, thresholdFactor:1,clean:true,compile:true});
    //console.log(Data.ACS.formater.toACS(peakPicking,{solvent:spectrum.getSolventName()}));
    //console.log(peakPicking);
    it('Known patterns', function () {

        //console.log(Data.ACS.formater.toACS(peakPicking,{solvent:spectrum.getSolventName()}));
        for(var i=0;i<peakPicking.length;i++){
            var signal = peakPicking[i];
            if(Math.abs(signal.delta1-1.308)<0.01){
                signal.multiplicity.should.equal("t");
            }
            if(Math.abs(signal.delta1-3.77)<0.01){
                signal.multiplicity.should.equal("q");
            }
            if(Math.abs(signal.delta1-3.99)<0.01){
                signal.multiplicity.should.equal("dd");
            }
            if(Math.abs(signal.delta1-4.2)<0.01){
                signal.multiplicity.should.equal("dd");
            }
            if(Math.abs(signal.delta1-6.47)<0.01){
                signal.multiplicity.should.equal("dd");
            }
        }
    });

    /*it('Number of patterns', function(){
        peakPicking.length.should.equal(5);
    });*/

});

<|endoftext|>


<commit_before>'use strict';

// Admins controller
angular.module('admins').controller('AdminsController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'Admins',
	function($scope, $http, $stateParams, $location, Authentication, Admins) {
		$scope.authentication = Authentication;

		if($location.path().search('admin') > 0){
			if (!$scope.authentication.user) {
				$location.path('/');
			}
			else if($scope.authentication.user.roles.length < 2){
				$location.path('/');
			}
		}

		// Create new Admin
		$scope.create = function() {
			// Create new Admin object
			var admin = new Admins ({
				name: this.name
			});

			// Redirect after save
			admin.$save(function(response) {
				$location.path('admins/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Admin Login
		$scope.login = function() {
			$http.post('/admins_login', $scope.loginForm).success(function(response) {
				// If successful we assign the response to the global user model
				$scope.admins = response;

				// And redirect to the index page
				$location.path('admins/cp');
			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		// Remove existing Admin
		$scope.remove = function(admin) {
			if ( admin ) {
				admin.$remove();

				for (var i in $scope.admins) {
					if ($scope.admins [i] === admin) {
						$scope.admins.splice(i, 1);
					}
				}
			} else {
				$scope.admin.$remove(function() {
					$location.path('admins');
				});
			}
		};

		// Update existing Admin
		$scope.update = function() {
			var admin = $scope.admin;

			admin.$update(function() {
				$location.path('admins/' + admin._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Admins
		$scope.find = function() {
			$scope.admins = Admins.query();
		};

		// Admin list of Admins
		$scope.list = function() {
			$http.get('/admins/admin/list').success(function (response){
				$scope.admins = response;
			}).error(function(response){
				$scope.error = response.message;
			});
		};

		// Find existing Admin
		$scope.findOne = function() {
			$scope.admin = Admins.get({
				adminId: $stateParams.adminId
			});
		};

		// Find existing Admin
		$scope.findGds = function() {
			$http.get('/gds').success(function (response){
				$scope.gdss = response;
			})
		};

		// Update existing Gds
		$scope.updateGds = function() {
			var gds = this.gds;
			$http.post('/gds',gds).success(function (response) {
				$scope.success = true;
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// delete Gds From admin list
		$scope.delGds = function() {
			var gdsId = this.gds._id;
			$http.delete('/gds?='+gdsId).success(function (response){
				//$location.path('gdss/'+response._id);
				for (var i in $scope.gdss) {
					if ($scope.gdss [i] === this.gds) {
						$scope.gdss.splice(i, 1);
					}
				}
				$scope.success = true;
			}).error(function(response){
				$scope.error = response.message;
			});
		};
	}
]);
<commit_msg>201510192256<commit_after>'use strict';

// Admins controller
angular.module('admins').controller('AdminsController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'Admins',
	function($scope, $http, $stateParams, $location, Authentication, Admins) {
		$scope.authentication = Authentication;

		if($location.path().search('admin') > 0){
			if (!$scope.authentication.user) {
				$location.path('/');
			}
			else if($scope.authentication.user.roles.length < 2){
				$location.path('/');
			}
		}

		// Create new Admin
		$scope.create = function() {
			// Create new Admin object
			var admin = new Admins ({
				name: this.name
			});

			// Redirect after save
			admin.$save(function(response) {
				$location.path('admins/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Admin Login
		$scope.login = function() {
			$http.post('/admins_login', $scope.loginForm).success(function(response) {
				// If successful we assign the response to the global user model
				$scope.admins = response;

				// And redirect to the index page
				$location.path('admins/cp');
			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		// Remove existing Admin
		$scope.remove = function(admin) {
			if ( admin ) {
				admin.$remove();

				for (var i in $scope.admins) {
					if ($scope.admins [i] === admin) {
						$scope.admins.splice(i, 1);
					}
				}
			} else {
				$scope.admin.$remove(function() {
					$location.path('admins');
				});
			}
		};

		// Update existing Admin
		$scope.update = function() {
			var admin = $scope.admin;

			admin.$update(function() {
				$location.path('admins/' + admin._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Admins
		$scope.find = function() {
			$scope.admins = Admins.query();
		};

		// Admin list of Admins
		$scope.list = function() {
			$http.get('/admins/admin/list').success(function (response){
				$scope.admins = response;
			}).error(function(response){
				$scope.error = response.message;
			});
		};

		// Find existing Admin
		$scope.findOne = function() {
			$scope.admin = Admins.get({
				adminId: $stateParams.adminId
			});
		};

		// Find existing Admin
		$scope.findGds = function() {
			$http.get('/gds').success(function (response){
				$scope.gdss = response;
			})
		};

		// Update existing Gds
		$scope.updateGds = function() {
			var gds = this.gds;
			$http.post('/gds',gds).success(function (response) {
				$scope.success = true;
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// delete Gds From admin list
		$scope.delGds = function() {
			var gds = this.gds;
			$http.delete('/gds?='+gds._id).success(function (response){
				//$location.path('gdss/'+response._id);
				for (var i in $scope.gdss) {
					if ($scope.gdss [i] === gds) {
						$scope.gdss.splice(i, 1);
					}
				}
				$scope.success = true;
			}).error(function(response){
				$scope.error = response.message;
			});
		};
	}
]);
<|endoftext|>


<commit_before>/**
 * Created by wilso_000 on 4/9/2015.
 */
'use strict';

angular.module('core').controller('PictureController', ['$scope',
    function($scope) {
        $scope.pictures = [
            {
                filepath: 'modules/core/img/slider/1.jpg'
            },
            {
                filepath: 'modules/core/img/slider/2.jpg'
            }
        ];

        $scope.picturesbw = [
            {
                filepath: 'modules/core/img/slider/3.jpg'
            },
            {
                filepath: 'modules/core/img/slider/4.jpg'
            }
        ];

        $scope.picturesfaces = [
            {
                filepath: 'modules/core/img/slider/5.jpg'
            },
            {
                filepath: 'modules/core/img/slider/6.jpg'
            }
        ];

    }
]);
<commit_msg>Bug Fixes<commit_after>/**
 * Created by wilso_000 on 4/9/2015.
 */
'use strict';

angular.module('core').controller('PictureController', ['$scope',
    function($scope) {
        $scope.pictures = [
            {
                filepath: 'modules/core/img/slider/1.jpg'
            },
            {
                filepath: 'modules/core/img/slider/2.jpg'
            }
        ];

        $scope.picturesbw = [
            {
                filepath: 'modules/core/img/slider/5.jpg'
            },
            {
                filepath: 'modules/core/img/slider/6.jpg'
            }
        ];

        $scope.picturesfaces = [
            {
                filepath: 'modules/core/img/slider/3.jpg'
            },
            {
                filepath: 'modules/core/img/slider/4.jpg'
            }
        ];

    }
]);
<|endoftext|>


<commit_before>'use strict';

angular.module('issues').controller('IssuesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Issues', '$filter', 'Comments', 'Subjects',
	function($scope, $stateParams, $location, Authentication, Issues, $filter, Comments, Subjects) {
		$scope.authentication = Authentication;

		angular.forEach($scope.authentication.user.roles, function(role, key){
			console.log(role);
			if (role === 'admin'){
				$scope.admin = true;
			} else {
				$scope.admin = false;
			}
		});

		var orderBy = $filter('orderBy');

		$scope.order = function(array, predicate, reverse) {
	    	var sorted = orderBy(array, predicate, reverse);
	    	return sorted;
	  	};

		$scope.create = function() {
			var issue = new Issues({
				title: this.title,
				type: this.type,
				nodeId: this.nodeId,
				subject: this.subject,
				content: this.content,
				permission: $scope.admin ? 'admin' : 'user',
				status: 'open'
			});
			issue.$save(function(response) {
				$location.path('issues');

				$scope.title = '';
				$scope.type = '';
				$scope.nodeId = '';
				$scope.subject = '';
				$scope.content = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.createComment = function() {
			console.log($scope.issue._id);
			var comment = new Comments({
				title: $scope.issue.title,
				content: $scope.commentContent,
				issue: $scope.issue._id
			});
			comment.$save(function(response) {
				console.log(response);
				$location.path('issues/' + $scope.issue._id);

				$scope.commentContent = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.remove = function(issue) {
			if (issue) {
				issue.$remove();

				for (var i in $scope.issues) {
					if ($scope.issues[i] === issue) {
						$scope.issues.splice(i, 1);
					}
				}
			} else {
				$scope.issue.$remove(function() {
					$location.path('issues');
				});
			}
		};

		$scope.update = function() {
			var issue = $scope.issue;

			issue.$update(function() {
				$location.path('issues');
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.find = function() {
			var issuesUser = [];
			Issues.query(function(issues){
				angular.forEach(issues, function(issue, key){
					if (issue.permission === 'user') issuesUser.push(issue);
				});

				$scope.issues = issues;// $scope.admin ? issues : issuesUser;
				console.log($scope.issues);

			});
		};

		$scope.findOne = function() {
			Issues.get({
				issueId: $stateParams.issueId
			}).$promise.then(function(issue){
				$scope.issue = issue;

				if (issue.shortId === '') {
					$scope.issue.shortId = $scope.issue._id.slice(-8);
					$scope.update();
				}

				$scope.showClosed = false;

				if ($scope.issue.status === 'closed') {
					$scope.showClosed = true;
				};

				Comments.query(function(comments){ // filtered based on selected issue
					var commentsObj = [];
					comments = $scope.order(comments, '-created', true);
					angular.forEach(comments, function(comment, key){
						if (comment.issue === issue._id) commentsObj.push(comment);
					});
					$scope.comments = commentsObj;
					console.log($scope.comments);
				});
			});
		};

		$scope.close = function() {
			$scope.issue.status = 'closed';
			$scope.issue.closedBy = $scope.authentication.user.username;
			$scope.issue.closedDate = new Date();;
			$scope.update();
		};

		$scope.open = function() {
			$scope.issue.status = 'open';
			$scope.update();
		};

		$scope.getComments = function() {
	  		Comments.query(function(comments){ // filter based on selected issue
				comments = $scope.order(comments, '-created', true);
				$scope.comments = comments;
				console.log(comments);
			});
	  	};

	  	$scope.getSubjects = function() {
	  		var subjectsObj = {};

	  		Subjects.query(function(subjects){
				subjects = $scope.order(subjects, '-name', true);
				angular.forEach(subjects, function(subject, key){
					if (subject.status === 'active') subjectsObj[subject.name] = subject.subjectCode;
				});
				$scope.subjects = subjectsObj;
				console.log($scope.subjects);
			});
	  	};

	  	$scope.getTypes = function() {
	  		var typesObj = {};

	  		typesObj.Accounting = '1';
	  		typesObj.Bug = '2';
	  		typesObj.Support = '3';
	  		typesObj.Other = '4';
	  		typesObj.Enhancement = '5';
	  		typesObj['Content - Summary'] = '6';
	  		typesObj['Content - Question'] = '7';
	  		typesObj['Content - ASC'] = '8';
	  		typesObj['Content - Help'] = '9';
	  		typesObj['Content - FAQ'] = '10';
	  		typesObj['Content - Other'] = '11';
	  		typesObj['Content - Accounting Recommendation'] = '12';
	  		typesObj['Content - Intermediate Decision'] = '13';

	  		$scope.types = typesObj;
	  		console.log($scope.types);
	  	};

	  	$scope.getLists = function() {
	  		$scope.getSubjects();
	  		$scope.getTypes();
	  	};

	  	$scope.filter = function(filter) {
	  		console.log(filter);
	  	};
	}
]);<commit_msg>reload page after submitting a comment<commit_after>'use strict';

angular.module('issues').controller('IssuesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Issues', '$filter', 'Comments', 'Subjects',
	function($scope, $stateParams, $location, Authentication, Issues, $filter, Comments, Subjects) {
		$scope.authentication = Authentication;

		angular.forEach($scope.authentication.user.roles, function(role, key){
			console.log(role);
			if (role === 'admin'){
				$scope.admin = true;
			} else {
				$scope.admin = false;
			}
		});

		var orderBy = $filter('orderBy');

		$scope.order = function(array, predicate, reverse) {
	    	var sorted = orderBy(array, predicate, reverse);
	    	return sorted;
	  	};

		$scope.create = function() {
			var issue = new Issues({
				title: this.title,
				type: this.type,
				nodeId: this.nodeId,
				subject: this.subject,
				content: this.content,
				permission: $scope.admin ? 'admin' : 'user',
				status: 'open'
			});
			issue.$save(function(response) {
				$location.path('issues');

				$scope.title = '';
				$scope.type = '';
				$scope.nodeId = '';
				$scope.subject = '';
				$scope.content = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.createComment = function() {
			console.log($scope.issue._id);
			var comment = new Comments({
				title: $scope.issue.title,
				content: $scope.commentContent,
				issue: $scope.issue._id
			});
			comment.$save(function(response) {
				console.log(response);
				window.location.reload();

				$scope.commentContent = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.remove = function(issue) {
			if (issue) {
				issue.$remove();

				for (var i in $scope.issues) {
					if ($scope.issues[i] === issue) {
						$scope.issues.splice(i, 1);
					}
				}
			} else {
				$scope.issue.$remove(function() {
					$location.path('issues');
				});
			}
		};

		$scope.update = function() {
			var issue = $scope.issue;

			issue.$update(function() {
				$location.path('issues');
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.find = function() {
			var issuesUser = [];
			Issues.query(function(issues){
				angular.forEach(issues, function(issue, key){
					if (issue.permission === 'user') issuesUser.push(issue);
				});

				$scope.issues = issues;// $scope.admin ? issues : issuesUser;
				console.log($scope.issues);

			});
		};

		$scope.findOne = function() {
			Issues.get({
				issueId: $stateParams.issueId
			}).$promise.then(function(issue){
				$scope.issue = issue;

				if (issue.shortId === '') {
					$scope.issue.shortId = $scope.issue._id.slice(-8);
					$scope.update();
				}

				$scope.showClosed = false;

				if ($scope.issue.status === 'closed') {
					$scope.showClosed = true;
				};

				Comments.query(function(comments){ // filtered based on selected issue
					var commentsObj = [];
					comments = $scope.order(comments, '-created', true);
					angular.forEach(comments, function(comment, key){
						if (comment.issue === issue._id) commentsObj.push(comment);
					});
					$scope.comments = commentsObj;
					console.log($scope.comments);
				});
			});
		};

		$scope.close = function() {
			$scope.issue.status = 'closed';
			$scope.issue.closedBy = $scope.authentication.user.username;
			$scope.issue.closedDate = new Date();;
			$scope.update();
		};

		$scope.open = function() {
			$scope.issue.status = 'open';
			$scope.update();
		};

		$scope.getComments = function() {
	  		Comments.query(function(comments){ // filter based on selected issue
				comments = $scope.order(comments, '-created', true);
				$scope.comments = comments;
				console.log(comments);
			});
	  	};

	  	$scope.getSubjects = function() {
	  		var subjectsObj = {};

	  		Subjects.query(function(subjects){
				subjects = $scope.order(subjects, '-name', true);
				angular.forEach(subjects, function(subject, key){
					if (subject.status === 'active') subjectsObj[subject.name] = subject.subjectCode;
				});
				$scope.subjects = subjectsObj;
				console.log($scope.subjects);
			});
	  	};

	  	$scope.getTypes = function() {
	  		var typesObj = {};

	  		typesObj.Accounting = '1';
	  		typesObj.Bug = '2';
	  		typesObj.Support = '3';
	  		typesObj.Other = '4';
	  		typesObj.Enhancement = '5';
	  		typesObj['Content - Summary'] = '6';
	  		typesObj['Content - Question'] = '7';
	  		typesObj['Content - ASC'] = '8';
	  		typesObj['Content - Help'] = '9';
	  		typesObj['Content - FAQ'] = '10';
	  		typesObj['Content - Other'] = '11';
	  		typesObj['Content - Accounting Recommendation'] = '12';
	  		typesObj['Content - Intermediate Decision'] = '13';

	  		$scope.types = typesObj;
	  		console.log($scope.types);
	  	};

	  	$scope.getLists = function() {
	  		$scope.getSubjects();
	  		$scope.getTypes();
	  	};

	  	$scope.filter = function(filter) {
	  		console.log(filter);
	  	};
	}
]);<|endoftext|>


<commit_before>'use strict';
function check(maxSizeByMb) {
    let fileInput = document.querySelector("input#uploadFile");
    let file = fileInput.files[0];
    if (file.type.startsWith("image") === false) {
        let fileType = file.type || "unknown";
        alert("Can't upload a " + file.type + " type file");
        return false;
    }
    if (file.size > (maxSizeByMb * 1024 * 1024)) {
        let fileSizeByMb = Math.round(file.size / 1024 / 1024 * 100) / 100;
        alert("Max file size is " + maxSizeByMb + " Mb, input file is " + fileSizeByMb.toString() + " Mb");
        return false;
    }
    let imgElement = document.querySelector("img#uploading");
    imgElement.classList.add("show");
    return true;
}
<commit_msg>client side check<commit_after>'use strict';

function isImageType(typeStr) {
    if (typeStr === "") {
        return false;
    }
    if (typeStr.startsWith("image") === false) {
        return false;
    }
    if (typeStr.includes("vnd")) {
        return false;
    }
    let accepted = ["/jpeg", "/bmp", "/gif", "/png"];
    return accepted.some((type) => typeStr.includes(type))
}

function check(maxSizeByMb) {
    let fileInput = document.querySelector("input#uploadFile");
    let file = fileInput.files[0];
    let fileType = file.type
    if (!isImageType(fileType)) {
        fileType = fileType || "unknown";
        alert("Can't upload a " + fileType + " type file");
        return false;
    }
    console.log("Accept a", fileTypem, "file")
    if (file.size > (maxSizeByMb * 1024 * 1024)) {
        let fileSizeByMb = Math.round(file.size / 1024 / 1024 * 100) / 100;
        alert("Max file size is " + maxSizeByMb + " Mb, input file is " + fileSizeByMb.toString() + " Mb");
        return false;
    }
    let imgElement = document.querySelector("img#uploading");
    imgElement.classList.add("show");
    return true;
}
<|endoftext|>


<commit_before>/* Event Emitter */
var util = require('util');
var EventEmitter = require('events').EventEmitter;

/* ZeroMQ */
var zmq = require('zmq')
  , sock = zmq.socket('sub')
  , sock2 = zmq.socket('pub');

//sock2.bindSync('tcp://127.0.0.1:5001');

/* Request */
var request = require('request');

// Mapping from Human Readable names to lagarto assigned ID's
// Not to be confussed with the experimental node ID, which will be unique to the arrangement of each session

// Feeder Devices
var lagartoIDtofeederName = {'7': 'a', '6': 'b', '0': 'c', '0': 'd', '0': 'e',
							'0': 'f', '0': 'g', '0': 'h', '0': 'i', '0': 'j'};

var feederNameToLagartoID = {'a': '7', 'b': '6', 'c': '0', 'd': '0', 'e': '0',
							'f': '0', 'g': '0', 'h': '0', 'i': '0', 'j': '0'};

var lagartoDotReferenceToFeederFunction = {'11.0': 'dropMeat', '17.0': 'perchEvent', '0': 'event'}; // battery, reset etc etc etc

var feederFunctionToLagartoDotReference = {'dropMeat': '11.0', 'perchEvent': '17.0', 'event': '0'}; // battery, reset etc etc etc

// Indicator device
var indicatorToLagartoID = {'indicator1': '39'};
var indicatorFunctionToLagartoDotReference = {'1': '0', '2': '0', '3': '0', '4': '0', '5': '0', '6': '0',
											  '7': '0', '8': '0', '9': '0', '10': '0',};

// The EventEmitter Object that will report events back to the controller
// Like a Meerkat, it is good at keeping watch : )
var Meerkat = function() {

    // we need to store the reference of `this` to `self`, so that we can use the current context in the setTimeout (or any callback) functions
    // using `this` in the setTimeout functions will refer to those funtions, not the Radio class
    var self = this;

    // Connect to Lagarto over ZMQ to subscrbe to events
	sock.connect('tcp://0.0.0.0:5001');
	sock.subscribe('');
	console.log('Subscriber connected to port 5001');

	sock.on('message', function(topic, message) {
	  	console.log('Recieved Message: "%s"', topic);

	  	parsedMessage = String(topic);
	  	jsonMessage = JSON.parse(parsedMessage);
	  	protcolName = jsonMessage['lagarto']['procname'];
	  	httpServer = jsonMessage['lagarto']['httpserver'];
	  	status = jsonMessage['lagarto']['status'];

	  	if (typeof status === "undefined") {
		    console.log("status not defined");
		} else {
			console.log(status);

	  		// Becuase it may contain multple values to status
	  		for (var i=0; i<status.length; i++) {
	  			name = status[i]['name'];
	  			idAndFunction = status[i]['id'].split(".");
	  			id = idAndFunction[0]; //pull out the start
	  			functionID = idAndFunction[1]+"."+idAndFunction[2]; //pull out the end
	  			value = status[i]['value'];

	  			console.log("Event details are:", name, id, functionID, value);

	  			// Hardcoded values - to be removed
			  	//eventType = 'perchEvent2';
			  	//deviceID = 1; // get this from
			  	//perchID = 1;
			  	//value = 'on';

	  			// Did it come from the indicator?
	  			//if (id == indicatorToLagartoID['indicator1']) {

	  			//	eventType = indicatorFunctionToLagartoDotReference[functionID];

	  			//	switch (eventType) {
	  			//		case '':

	  			//			break;
	  			//		case '':

	  			//			break;
	  			//		case '':

	  			//			break;
	  			//		default:

	  			//	}
	  			//}

	  			// Did it come from a feeder node
	  			if (true) { //(feederNameToLagartoID[id]) { // is this device ID mapped to a feeder

	  				eventType = feederFunctionToLagartoDotReference[functionID];
	  				console.log(eventType);

	  				switch (functionID) {
				    	case '17.0': //'perchEvent':
				        	console.log("PerchEvent", id, value);

				        	// Pasrse message, and topic

				        	perchID = id; //set this based on the contents of the message
				        	if (value == 'on') {
				        		self.emit('perchEvent', lagartoIDtofeederName[perchID]);
				        	}

				        	break;
				    	case 'MeatFinishedDropping':
					        console.log("MeatFinishedDropping", deviceID, value);

					        // Pasrse message, and topic

					        feederID = 1; //set this based on the contents of the message
					        self.emit('MeatDropped', feederID)

				        	break;
				    	case 'LightChanged':
					        console.log("LightChanged", lightID);

					        // Pasrse message, and topic

					        lightID = 1; //set this based on the contents of the message
					        self.emit('LightChanged', lightID)

					        break;
				    	case 'BatteryUpdate':
					        console.log("BatteryUpdated", deviceID);

					        // Pasrse message, and topic

					        lightID = 1; //set this based on the contents of the message
					        self.emit('BatteryUpdated', deviceID)

					        break;
				    	default:
					        console.log("unhandled event");

					        perchID = 1; //set this based on the contents of the message
					        self.emit('dunno', perchID);
					}
	  			}

	  		}
	  	}

	  });
		// Reset
		// "{"lagarto":
				//{
				//"status":
					//[{"direction": "out", "name": "Reset_7", "timestamp": "28 May 2015 06:00:17", "value": "on", "location": "SWAP", "type": "bin", "id": "7.12.0"}],
				//"procname": "Lagarto-SWAP",
				//"httpserver": "10.1.1.6:8001"
				//}
			//}"

		// Perch off
		//"{"lagarto":
			//{"status":
				//[{"direction": "inp", "name": "Perch_triggered_7", "timestamp": "28 May 2015 05:59:34", "value": "off", "location": "SWAP", "type": "bin", "id": "7.17.0"}],
			//"procname": "Lagarto-SWAP", "httpserver": "10.1.1.6:8001"}}"

		// Perch event to parse
		//"{"lagarto":
			//{"status":
				//[{"direction": "inp", "name": "Perch_triggered_7", "timestamp": "28 May 2015 05:59:34", "value": "on", "location": "SWAP", "type": "bin", "id": "7.17.0"}],
			//"procname": "Lagarto-SWAP", "httpserver": "10.1.1.6:8001"}}"

    // EventEmitters inherit a single event listener, see it in action
    this.on('newListener', function(listener) {
        console.log('Event Listener: ' + listener);
    });

};

// extend the EventEmitter class using our Meerkat class
util.inherits(Meerkat, EventEmitter);

// Methods to be exported
var exports = module.exports = {};

// we specify that this module is a refrence to the Meerkat class
exports.Meerkat = Meerkat;

// Test method to be removed...
exports.sendMessage = function() {
  console.log('sending a multipart message envelope');
  sock2.send(["{'lagarto': 'hello'}", 'meow!']);
};

//
// Detecting Devices Methods
//
exports.getDevices = function() {

	//Perhaps this should pre cache??

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })
};

exports.getBatteryLife = function() {

	// return all the remaining battery lifes
	// do some in an arrary like
	return currentBattery = [1,1,1,1,1,1,1,1,1,1];
}

//
// Meat Events
//
exports.dropMeat = function(deviceName) {

	// map device name, and the function to below
	deviceID = feederNameToLagartoID[deviceName];
	functionID = feederFunctionToLagartoDotReference['dropMeat']; //maps to 11.0
	deviceAndFunctionID = deviceID + '.' + functionID;
	value = 'true';

	console.log("Dropping Meat on: ", deviceName);
	console.log("Which mapped onto: ", deviceAndFunctionID);

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=' + deviceAndFunctionID + '&value=' + value, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent drop meat command")
      }
    })
};

exports.getRemainingMeat = function(deviceName) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};

//
// Light Events
//
exports.turnLightOn = function(experimentalLightID) {

	deviceID = indicatorToLagartoID['indicator1'];
	functionID = 13.0; //indicatorFunctionToLagartoDotReference[experimentalLightID];

	deviceAndFunctionID = deviceID + '.' + functionID;
	value = experimentalLightID; //or perhaps off / on ??

	console.log("Turning Light on: ", experimentalLightID);
	console.log("Which mapped onto: ", deviceAndFunctionID);

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=' + deviceAndFunctionID + '&value=' + value, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent turn ligh on command")
      }
    })

};

exports.turnLightOff = function(experimentalLightID) {

	deviceID = indicatorToLagartoID['indicator1'];
	functionID = indicatorFunctionToLagartoDotReference[experimentalLightID];
	deviceAndFunctionID = deviceID + '.' + functionID;
	value = 'false'; //or perhaps off / on ??

	console.log("Turning Light off on: ", experimentalLightID);
	console.log("Which mapped onto: ", deviceAndFunctionID);

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=' + deviceAndFunctionID + '&value=' + value, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent turn light off command")
      }
    })

};<commit_msg>testing indicators<commit_after>/* Event Emitter */
var util = require('util');
var EventEmitter = require('events').EventEmitter;

/* ZeroMQ */
var zmq = require('zmq')
  , sock = zmq.socket('sub')
  , sock2 = zmq.socket('pub');

//sock2.bindSync('tcp://127.0.0.1:5001');

/* Request */
var request = require('request');

// Mapping from Human Readable names to lagarto assigned ID's
// Not to be confussed with the experimental node ID, which will be unique to the arrangement of each session

// Feeder Devices
var lagartoIDtofeederName = {'7': 'a', '6': 'b', '0': 'c', '0': 'd', '0': 'e',
							'0': 'f', '0': 'g', '0': 'h', '0': 'i', '0': 'j'};

var feederNameToLagartoID = {'a': '7', 'b': '6', 'c': '0', 'd': '0', 'e': '0',
							'f': '0', 'g': '0', 'h': '0', 'i': '0', 'j': '0'};

var lagartoDotReferenceToFeederFunction = {'11.0': 'dropMeat', '17.0': 'perchEvent', '0': 'event'}; // battery, reset etc etc etc

var feederFunctionToLagartoDotReference = {'dropMeat': '11.0', 'perchEvent': '17.0', 'event': '0'}; // battery, reset etc etc etc

// Indicator device
var indicatorToLagartoID = {'indicator1': '39'};
var indicatorFunctionToLagartoDotReference = {'1': '0', '2': '0', '3': '0', '4': '0', '5': '0', '6': '0',
											  '7': '0', '8': '0', '9': '0', '10': '0',};

// The EventEmitter Object that will report events back to the controller
// Like a Meerkat, it is good at keeping watch : )
var Meerkat = function() {

    // we need to store the reference of `this` to `self`, so that we can use the current context in the setTimeout (or any callback) functions
    // using `this` in the setTimeout functions will refer to those funtions, not the Radio class
    var self = this;

    // Connect to Lagarto over ZMQ to subscrbe to events
	sock.connect('tcp://0.0.0.0:5001');
	sock.subscribe('');
	console.log('Subscriber connected to port 5001');

	sock.on('message', function(topic, message) {
	  	console.log('Recieved Message: "%s"', topic);

	  	parsedMessage = String(topic);
	  	jsonMessage = JSON.parse(parsedMessage);
	  	protcolName = jsonMessage['lagarto']['procname'];
	  	httpServer = jsonMessage['lagarto']['httpserver'];
	  	status = jsonMessage['lagarto']['status'];

	  	if (typeof status === "undefined") {
		    console.log("status not defined");
		} else {
			console.log(status);

	  		// Becuase it may contain multple values to status
	  		for (var i=0; i<status.length; i++) {
	  			name = status[i]['name'];
	  			idAndFunction = status[i]['id'].split(".");
	  			id = idAndFunction[0]; //pull out the start
	  			functionID = idAndFunction[1]+"."+idAndFunction[2]; //pull out the end
	  			value = status[i]['value'];

	  			console.log("Event details are:", name, id, functionID, value);

	  			// Hardcoded values - to be removed
			  	//eventType = 'perchEvent2';
			  	//deviceID = 1; // get this from
			  	//perchID = 1;
			  	//value = 'on';

	  			// Did it come from the indicator?
	  			//if (id == indicatorToLagartoID['indicator1']) {

	  			//	eventType = indicatorFunctionToLagartoDotReference[functionID];

	  			//	switch (eventType) {
	  			//		case '':

	  			//			break;
	  			//		case '':

	  			//			break;
	  			//		case '':

	  			//			break;
	  			//		default:

	  			//	}
	  			//}

	  			// Did it come from a feeder node
	  			if (true) { //(feederNameToLagartoID[id]) { // is this device ID mapped to a feeder

	  				eventType = feederFunctionToLagartoDotReference[functionID];
	  				console.log(eventType);

	  				switch (functionID) {
				    	case '17.0': //'perchEvent':
				        	console.log("PerchEvent", id, value);

				        	// Pasrse message, and topic

				        	perchID = id; //set this based on the contents of the message
				        	if (value == 'on') {
				        		self.emit('perchEvent', lagartoIDtofeederName[perchID]);
				        	}

				        	break;
				    	case 'MeatFinishedDropping':
					        console.log("MeatFinishedDropping", deviceID, value);

					        // Pasrse message, and topic

					        feederID = 1; //set this based on the contents of the message
					        self.emit('MeatDropped', feederID)

				        	break;
				    	case 'LightChanged':
					        console.log("LightChanged", lightID);

					        // Pasrse message, and topic

					        lightID = 1; //set this based on the contents of the message
					        self.emit('LightChanged', lightID)

					        break;
				    	case 'BatteryUpdate':
					        console.log("BatteryUpdated", deviceID);

					        // Pasrse message, and topic

					        lightID = 1; //set this based on the contents of the message
					        self.emit('BatteryUpdated', deviceID)

					        break;
				    	default:
					        console.log("unhandled event");

					        perchID = 1; //set this based on the contents of the message
					        self.emit('dunno', perchID);
					}
	  			}

	  		}
	  	}

	  });
		// Reset
		// "{"lagarto":
				//{
				//"status":
					//[{"direction": "out", "name": "Reset_7", "timestamp": "28 May 2015 06:00:17", "value": "on", "location": "SWAP", "type": "bin", "id": "7.12.0"}],
				//"procname": "Lagarto-SWAP",
				//"httpserver": "10.1.1.6:8001"
				//}
			//}"

		// Perch off
		//"{"lagarto":
			//{"status":
				//[{"direction": "inp", "name": "Perch_triggered_7", "timestamp": "28 May 2015 05:59:34", "value": "off", "location": "SWAP", "type": "bin", "id": "7.17.0"}],
			//"procname": "Lagarto-SWAP", "httpserver": "10.1.1.6:8001"}}"

		// Perch event to parse
		//"{"lagarto":
			//{"status":
				//[{"direction": "inp", "name": "Perch_triggered_7", "timestamp": "28 May 2015 05:59:34", "value": "on", "location": "SWAP", "type": "bin", "id": "7.17.0"}],
			//"procname": "Lagarto-SWAP", "httpserver": "10.1.1.6:8001"}}"

    // EventEmitters inherit a single event listener, see it in action
    this.on('newListener', function(listener) {
        console.log('Event Listener: ' + listener);
    });

};

// extend the EventEmitter class using our Meerkat class
util.inherits(Meerkat, EventEmitter);

// Methods to be exported
var exports = module.exports = {};

// we specify that this module is a refrence to the Meerkat class
exports.Meerkat = Meerkat;

// Test method to be removed...
exports.sendMessage = function() {
  console.log('sending a multipart message envelope');
  sock2.send(["{'lagarto': 'hello'}", 'meow!']);
};

//
// Detecting Devices Methods
//
exports.getDevices = function() {

	//Perhaps this should pre cache??

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })
};

exports.getBatteryLife = function() {

	// return all the remaining battery lifes
	// do some in an arrary like
	return currentBattery = [1,1,1,1,1,1,1,1,1,1];
}

//
// Meat Events
//
exports.dropMeat = function(deviceName) {

	// map device name, and the function to below
	deviceID = feederNameToLagartoID[deviceName];
	functionID = feederFunctionToLagartoDotReference['dropMeat']; //maps to 11.0
	deviceAndFunctionID = deviceID + '.' + functionID;
	value = 'true';

	console.log("Dropping Meat on: ", deviceName);
	console.log("Which mapped onto: ", deviceAndFunctionID);

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=' + deviceAndFunctionID + '&value=' + value, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent drop meat command")
      }
    })
};

exports.getRemainingMeat = function(deviceName) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};

//
// Light Events
//
exports.turnLightOn = function(experimentalLightID) {

	deviceID = indicatorToLagartoID['indicator1'];
	functionID = 13.0; //indicatorFunctionToLagartoDotReference[experimentalLightID];

	deviceAndFunctionID = deviceID + '.' + functionID;
	value = experimentalLightID; //or perhaps off / on ??

	console.log("Turning Light on: ", experimentalLightID);
	console.log("Which mapped onto: ", deviceAndFunctionID);

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=' + deviceAndFunctionID + '&value=' + value, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent turn ligh on command")
      }
    })

};

exports.turnLightOff = function(experimentalLightID) {

	deviceID = indicatorToLagartoID['indicator1'];
	functionID = 14.0; //indicatorFunctionToLagartoDotReference[experimentalLightID];
	deviceAndFunctionID = deviceID + '.' + functionID;
	value = experimentalLightID; //'false'; //or perhaps off / on ??

	console.log("Turning Light off on: ", experimentalLightID);
	console.log("Which mapped onto: ", deviceAndFunctionID);

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=' + deviceAndFunctionID + '&value=' + value, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent turn light off command")
      }
    })

};<|endoftext|>


<commit_before>//display routes

var SerialPort = require("serialport").SerialPort;
var serialPort;

var display_data = {
    displayString: " ",
    textColor: 'orange',
    textFont: 'default'
};

var fonts = {
    'default':      "\s",
    '7by6':         "\s",
    'short':        "\q",
    'shortAndWide': "\\r",
    'wide':         "\\t",
    '7by9':         "\u",
    'extraWide':    "\v",
    'small':        "\w"
};

var effects = {
    'immediate':"\rB\c"
};

var colors = {
    'red':          "\a",
    'brightRed':    "\b",
    'orange':       "\c",
    'brightOrange': "\d",
    'yellow':       "\e",
    'brightYellow': "\f",
    'green':        "\g",
    'brightGreen':  "\h",
    'layerMix':     "\i",
    'brightLayerMix':"\j",
    'verticalMix':  "\k",
    'sawtoothMix':  "\l",
    'greenOnRed':   "\m",
    'redOnGreen':   "\\n",
    'orangeOnRed':  "\o",
    'yellowOnGreen':"\p"
};

function writeDisplay(data, cb) {
    var outStr = "";
    outStr += "~128"; //code number 128
    outStr += "~f01"; //file 01
    outStr += effects['immediate']; //immediate effect
    outStr += fonts[data.textFont]; //font
    outStr += colors[data.textColor]; //color
    outStr += data.displayString; //the string to display
    outStr += '\r\r\r'; //ending
    serialPort.write(outStr, function(err){
        return cb(err);
    });
}

exports.initDisplay = function(options, cb){
    var error = false;
    serialPort = new SerialPort(options.port, {
        baudrate: options.baud
    }, function(err){
        if(err) error = err;
        return cb(error);
    });
    //cb(error);
};

exports.getDisplay = function(req, res, next){
    res.json(display_data);
    return next();
};

exports.putDisplay = function(req, res, next){

};

<commit_msg>added put display ability function<commit_after>//display routes

var SerialPort = require("serialport").SerialPort;
var serialPort;

var display_data = {
    displayString: " ",
    textColor: 'orange',
    textFont: 'default'
};

var fonts = {
    'default':      "\s",
    '7by6':         "\s",
    'short':        "\q",
    'shortAndWide': "\\r",
    'wide':         "\\t",
    '7by9':         "\u",
    'extraWide':    "\v",
    'small':        "\w"
};

var effects = {
    'immediate':"\rB\c"
};

var colors = {
    'red':          "\a",
    'brightRed':    "\b",
    'orange':       "\c",
    'brightOrange': "\d",
    'yellow':       "\e",
    'brightYellow': "\f",
    'green':        "\g",
    'brightGreen':  "\h",
    'layerMix':     "\i",
    'brightLayerMix':"\j",
    'verticalMix':  "\k",
    'sawtoothMix':  "\l",
    'greenOnRed':   "\m",
    'redOnGreen':   "\\n",
    'orangeOnRed':  "\o",
    'yellowOnGreen':"\p"
};

function writeDisplay(data, cb) {
    var outStr = "";
    outStr += "~128"; //code number 128
    outStr += "~f01"; //file 01
    outStr += effects['immediate']; //immediate effect
    outStr += fonts[data.textFont]; //font
    outStr += colors[data.textColor]; //color
    outStr += data.displayString; //the string to display
    outStr += '\r\r\r'; //ending
    serialPort.write(outStr, function(err){
        return cb(err);
    });
}

exports.initDisplay = function(options, cb){
    var error = false;
    serialPort = new SerialPort(options.port, {
        baudrate: options.baud
    }, function(err){
        if(err) error = err;
        return cb(error);
    });
    //cb(error);
};

exports.getDisplay = function(req, res, next){
    res.json(display_data);
    return next();
};

exports.putDisplay = function(req, res, next){
    if(req.params.displayString !== undefined){
        display_data.displayString = req.params.displayString;
    }
    if(req.params.textColor !== undefined){
        display_data.textColor = req.params.textColor;
    }
    if(req.params.textFont !== undefined){
        display_data.textFont = req.params.textFont;
    }
    writeDisplay(display_data, function(err){
        next.ifError(err);
        res.json(200);
        return next();
    });

};

<|endoftext|>


<commit_before>module.exports = function (app) {

    var Friend = require('../models/friend.js');
    var User = require('../models/user.js');

    //GET- GET ALL Friends by Username
    allFriends = function (req, res) {

        console.log("ok populate");
        Friend.find({}, function(err, friend) {

             console.log("ok populate");
             console.log(friend);
            User.populate(friend, {path: "friend"},function(err, friend){
            res.status(200).send(friend);

            console.log(friend);
            });
         });

    };

    //POST - Add Friends
    addFriend = function (req, res) {
        console.log('POST');
        console.log(req.body);
        console.log(req.body.username);
        console.log(req.body.friend);
        console.log('test');
        User.findOne({username: req.body.friend}, function (err, data) {
            console.log(data._id);
            var id_friend = data._id;
            console.log(id_friend);

            var friend = new Friend({
                username: req.body.username,
                friend: id_friend,

            });

            friend.save(function (err, friend) {
                if (err) return res.send(500, err.message);
                res.status(200).json(friend);
            });
        });

    };
    //GET- GET ALL Friends by Username
    findFriends = function (req, res) {

        console.log ("joder");
        console.log (req.params.username);
        Friend.find({username: req.params.username}, function (err, friend) {
            User.populate(friend, {path: "friend"}, function (err, friend) {
                res.status(200).send(friend);
                console.log(friend);
            });
        });
    };

    //DELETE - Delete a User with specified ID
    deleteFriend = function (req, res) {
        return Friend.findById(req.params.id, function (err, friend) {
            console.log('DELETE usuario');
            return friend.remove(function (err) {
                if (!err) {
                    console.log("usuario eliminado");
                    return res.send('');
                } else {
                    console.log(err);
                }
            });
        });
    }

    //endpoints
    app.get('/allfriends', allFriends);
    app.get('/friends/:username', findFriends);
    app.post('/addfriend', addFriend);
    app.delete('/friend/:id', deleteFriend);

}
<commit_msg>Search user new design<commit_after>module.exports = function (app) {

    var Friend = require('../models/friend.js');
    var User = require('../models/user.js');

    //GET- GET ALL Friends by Username
    allFriends = function (req, res) {

        console.log("ok populate");
        Friend.find({}, function(err, friend) {

             console.log("ok populate");
             console.log(friend);
            User.populate(friend, {path: "friend"},function(err, friend){
            res.status(200).send(friend);

            console.log(friend);
            });
         });

    };

    isFriend = function(req,res) {
        console.log("isFRiend");
        User.findOne({username: req.params.friend}, function (err, data) {
            console.log(data._id);
            var id_friend = data._id;
            console.log(id_friend);
            Friend.findOne({username: req.params.username,friend: id_friend}, function(err,data){
                if(data==null){
                    res.send(false);
                }
                else res.send(true);
            });
        });
    }

    //POST - Add Friends
    addFriend = function (req, res) {
        console.log('POST');
        console.log(req.body);
        console.log(req.body.username);
        console.log(req.body.friend);
        console.log('test');
        User.findOne({username: req.body.friend}, function (err, data) {
            console.log(data._id);
            var id_friend = data._id;
            console.log(id_friend);

            var friend = new Friend({
                username: req.body.username,
                friend: id_friend,

            });

            friend.save(function (err, friend) {
                if (err) return res.send(500, err.message);
                res.status(200).json(friend);
            });
        });

    };
    //GET- GET ALL Friends by Username
    findFriends = function (req, res) {

        console.log ("joder");
        console.log (req.params.username);
        Friend.find({username: req.params.username}, function (err, friend) {
            User.populate(friend, {path: "friend"}, function (err, friend) {
                res.status(200).send(friend);
                console.log(friend);
            });
        });
    };

    //DELETE - Delete a User with specified ID
    deleteFriend = function (req, res) {
        return Friend.findById(req.params.id, function (err, friend) {
            console.log('DELETE usuario');
            return friend.remove(function (err) {
                if (!err) {
                    console.log("usuario eliminado");
                    return res.send('');
                } else {
                    console.log(err);
                }
            });
        });
    }

    //endpoints
    app.get('/allfriends', allFriends);
    app.get('/friends/:username', findFriends);
    app.get('/friends/:username/:friend',isFriend);
    app.post('/addfriend', addFriend);
    app.delete('/friend/:id', deleteFriend);

}
<|endoftext|>