<commit_before>module.exports = function(grunt) {
  'use strict';

  // require it at the top and pass in the grunt instance
  require('time-grunt')(grunt);

  var path = require('path'),
      cwd =  process.cwd();

  require('load-grunt-config')(
    grunt, {
      configPath: path.join(cwd, 'helpers/grunt/config')
    }
  );

  // load custom tasks
  grunt.loadTasks('helpers/grunt/tasks'); // grunt helloworld
  //grunt.task.run('helloworld');

  //--- grunt tasks

  grunt.registerTask('default', ['clean', 'lintspaces:all', 'newer:jshint']);

  grunt.registerTask('build', function(target) {
    if(target === 'dev') {
      return grunt.task.run([
        'default',
        'copy:dev_tobuild',
        'copy:dev_jstobuild',
        'copy:dev_vendortobuild',
        'cleanempty:build',
        'less:dev'
      ]);

    } else if(target === 'prod') {
      return  grunt.task.run([
        'default',
        'copy:prod_jstobuild',
        'html2js:prod',
        'rewriterequireconfig',
        'requirejs',
        'clean:build',
        'copy:prod_todist',
        'cleanempty:dist',
        'less:prod',
        'htmlmin',
        'imagemin',
        'uglify'
      ]);

    }
  });

  grunt.registerTask('dev', function(target) {
    if(target === 'sync') {

      return grunt.task.run([
        'build:dev',
        'browserSync:dev',
        'watch'
      ]);

    } else if(target === 'syncProxy') {

      return grunt.task.run([
        'build:dev',
        'configureProxies',
        'browserSync:devProxy',
        'watch'
      ]);

    } else if(target === 'proxy') {

      return grunt.task.run([
        'build:dev',
        'configureProxies',
        'connect:devProxy',
        'watch'
      ]);

    }

    return grunt.task.run([
      'build:dev',
      'connect:dev',
      'watch'
    ]);
  });

  grunt.registerTask('dist', function(target) {
    if(target === 'sync') {

      return grunt.task.run([
        'build:prod',
        'browserSync:dist'
      ]);

    } else if(target === 'syncProxy') {

      return grunt.task.run([
        'build:prod',
        'configureProxies',
        'browserSync:distProxy'
      ]);

    } else if(target === 'proxy') {

      return grunt.task.run([
        'build:prod',
        'configureProxies',
        'connect:distProxy'
      ]);

    }

    return grunt.task.run([
      'build:prod',
      'connect:dist'
    ]);
  });

};
<commit_msg>grunt file tools reviewed<commit_after>module.exports = function(grunt) {
  'use strict';

  require('time-grunt')(grunt);

  var path = require('path'),
      cwd =  process.cwd();

  require('load-grunt-config')(
    grunt, {
      configPath: path.join(cwd, 'helpers/grunt/config')
    }
  );

  // load custom tasks
  grunt.loadTasks('helpers/grunt/tasks'); // grunt helloworld
  //grunt.task.run('helloworld');

  //--- grunt tasks

  grunt.registerTask('default', ['clean', 'lintspaces:all', 'newer:jshint']);

  grunt.registerTask('build', function(target) {
    if(target === 'dev') {
      return grunt.task.run([
        'default',
        'copy:dev_tobuild',
        'copy:dev_jstobuild',
        'copy:dev_vendortobuild',
        'cleanempty:build',
        'less:dev'
      ]);

    } else if(target === 'prod') {
      return  grunt.task.run([
        'default',
        'copy:prod_jstobuild',
        'html2js:prod',
        'rewriterequireconfig',
        'requirejs',
        'clean:build',
        'copy:prod_todist',
        'cleanempty:dist',
        'less:prod',
        'htmlmin',
        'imagemin',
        'uglify'
      ]);

    }
  });

  grunt.registerTask('dev', function(target) {
    if(target === 'sync') {

      return grunt.task.run([
        'build:dev',
        'browserSync:dev',
        'watch'
      ]);

    } else if(target === 'syncProxy') {

      return grunt.task.run([
        'build:dev',
        'configureProxies',
        'browserSync:devProxy',
        'watch'
      ]);

    } else if(target === 'proxy') {

      return grunt.task.run([
        'build:dev',
        'configureProxies',
        'connect:devProxy',
        'watch'
      ]);

    }

    return grunt.task.run([
      'build:dev',
      'connect:dev',
      'watch'
    ]);
  });

  grunt.registerTask('dist', function(target) {
    if(target === 'sync') {

      return grunt.task.run([
        'build:prod',
        'browserSync:dist'
      ]);

    } else if(target === 'syncProxy') {

      return grunt.task.run([
        'build:prod',
        'configureProxies',
        'browserSync:distProxy'
      ]);

    } else if(target === 'proxy') {

      return grunt.task.run([
        'build:prod',
        'configureProxies',
        'connect:distProxy'
      ]);

    }

    return grunt.task.run([
      'build:prod',
      'connect:dist'
    ]);
  });

};
<|endoftext|>


<commit_before>(function(){

new Vue({
	 el: "#sheet"

	,data: {

		characterLevel: 0

		,strBase: 0
		,dexBase: 0
		,conBase: 0
		,intBase: 0
		,wisBase: 0
		,chaBase: 0

		,strBonuses: [0]
		,dexBonuses: [0]
		,conBonuses: [0]
		,intBonuses: [0]
		,wisBonuses: [0]
		,chaBonuses: [0]

		,baseHP: 0
		,damage: 0
		,nonlethalDamage: 0
		,hit: 0

		,bab: 0

	}

	,computed: {

		//****** Abilities ******
		 str: function(){
			 return getAbilityTotal(this.strBase, this.strBonuses);
		 }
		,dex: function(){
			 return getAbilityTotal(this.dexBase, this.dexBonuses);
		 }

		,con: function(){
			 return getAbilityTotal(this.conBase, this.conBonuses);
		 }

		,int: function(){
			 return getAbilityTotal(this.intBase, this.intBonuses);
		 }

		,wis: function(){
			 return getAbilityTotal(this.wisBase, this.wisBonuses);
		 }

		,cha: function(){
			 return getAbilityTotal(this.chaBase, this.chaBonuses);
		 }

		//****** Abilities Modifiers ******
		,strMod: function() {
			return modifierFor(this.str);
		}
		,dexMod: function() {
			return modifierFor(this.dex);
		}
		,conMod: function() {
			return modifierFor(this.con);
		}
		,intMod: function() {
			return modifierFor(this.int);
		}
		,wisMod: function() {
			return modifierFor(this.wis);
		}
		,chaMod: function() {
			return modifierFor(this.cha);
		}

		//****** HP ******
		,totalHP: function() {
			return parseInt(this.baseHP) + parseInt(this.characterLevel) * (parseInt(this.conMod));
		}
		,currentHP: function() {
			return this.totalHP - parseInt(this.damage);
		}

		//****** Initiative ******
		,initiative: function(){
			return this.dexMod;
		}

		//****** AC ******
		,AC: function() {
			return 10 + 10 + 3 + 1 + parseInt(this.dexMod);
		}
		,touchAC: function() {
			return 10 + 1 + parseInt(this.dexMod);
		}
		,flatfootedAC: function() {
			return 10 + 10 + 3 + 1;
		}

		//****** Attack ******
		,meleeBonus: function() {
			return parseInt(this.bab) + parseInt(this.strMod);
		}
		,rangedBonus: function() {
			return parseInt(this.bab) + parseInt(this.dexMod);
		}
	}

	,methods: {
		 takeDamage: function(){
			this.damage = parseInt(this.damage) + parseInt(this.hit);
		 }
		,heal: function(){
			var _damage = parseInt(this.damage) - parseInt(this.hit);
			var _nldamage = parseInt(this.nonlethalDamage) - parseInt(this.hit);
			if(_damage > 0){
				this.damage = _damage;
			}else{
				this.damage = 0;
			}
			if(_nldamage > 0){
				this.nonlethalDamage = _nldamage;
			}else{
				this.nonlethalDamage = 0;
			}
		}
		,takeNonlethalDamage: function(){
			this.nonlethalDamage = parseInt(this.nonlethalDamage) + parseInt(this.hit);
		}
		,healNonlethalDamage: function(){
			var _nldamage = parseInt(this.nonlethalDamage) - parseInt(this.hit);
			if(_nldamage > 0){
				this.nonlethalDamage = _nldamage;
			}else{
				this.nonlethalDamage = 0;
			}
		}
	}

});

function modifierFor(ability){
	if(!(ability < 0)){
		return Math.floor( (ability - 10) / 2 );
	}
}

function addSign(number){
	if(number >= 0){
		return "+" + number;
	}
	return number.toString();
}

function getAbilityTotal(base, bonuses) {
	var total = parseInt(base) + bonuses.reduce(function(a,b){return a+b;})
	if(isNaN(total) || total < 0){
		return 0;
	}
	return total;
}

})();<commit_msg>js strict mode on<commit_after>(function(){
"use strict"

new Vue({
	 el: "#sheet"

	,data: {

		characterLevel: 0

		,strBase: 0
		,dexBase: 0
		,conBase: 0
		,intBase: 0
		,wisBase: 0
		,chaBase: 0

		,strBonuses: [0]
		,dexBonuses: [0]
		,conBonuses: [0]
		,intBonuses: [0]
		,wisBonuses: [0]
		,chaBonuses: [0]

		,baseHP: 0
		,damage: 0
		,nonlethalDamage: 0
		,hit: 0

		,bab: 0

	}

	,computed: {

		//****** Abilities ******
		 str: function(){
			 return getAbilityTotal(this.strBase, this.strBonuses);
		 }
		,dex: function(){
			 return getAbilityTotal(this.dexBase, this.dexBonuses);
		 }

		,con: function(){
			 return getAbilityTotal(this.conBase, this.conBonuses);
		 }

		,int: function(){
			 return getAbilityTotal(this.intBase, this.intBonuses);
		 }

		,wis: function(){
			 return getAbilityTotal(this.wisBase, this.wisBonuses);
		 }

		,cha: function(){
			 return getAbilityTotal(this.chaBase, this.chaBonuses);
		 }

		//****** Abilities Modifiers ******
		,strMod: function() {
			return modifierFor(this.str);
		}
		,dexMod: function() {
			return modifierFor(this.dex);
		}
		,conMod: function() {
			return modifierFor(this.con);
		}
		,intMod: function() {
			return modifierFor(this.int);
		}
		,wisMod: function() {
			return modifierFor(this.wis);
		}
		,chaMod: function() {
			return modifierFor(this.cha);
		}

		//****** HP ******
		,totalHP: function() {
			return parseInt(this.baseHP) + parseInt(this.characterLevel) * (parseInt(this.conMod));
		}
		,currentHP: function() {
			return this.totalHP - parseInt(this.damage);
		}

		//****** Initiative ******
		,initiative: function(){
			return this.dexMod;
		}

		//****** AC ******
		,AC: function() {
			return 10 + 10 + 3 + 1 + parseInt(this.dexMod);
		}
		,touchAC: function() {
			return 10 + 1 + parseInt(this.dexMod);
		}
		,flatfootedAC: function() {
			return 10 + 10 + 3 + 1;
		}

		//****** Attack ******
		,meleeBonus: function() {
			return parseInt(this.bab) + parseInt(this.strMod);
		}
		,rangedBonus: function() {
			return parseInt(this.bab) + parseInt(this.dexMod);
		}
	}

	,methods: {
		 takeDamage: function(){
			this.damage = parseInt(this.damage) + parseInt(this.hit);
		 }
		,heal: function(){
			var _damage = parseInt(this.damage) - parseInt(this.hit);
			var _nldamage = parseInt(this.nonlethalDamage) - parseInt(this.hit);
			if(_damage > 0){
				this.damage = _damage;
			}else{
				this.damage = 0;
			}
			if(_nldamage > 0){
				this.nonlethalDamage = _nldamage;
			}else{
				this.nonlethalDamage = 0;
			}
		}
		,takeNonlethalDamage: function(){
			this.nonlethalDamage = parseInt(this.nonlethalDamage) + parseInt(this.hit);
		}
		,healNonlethalDamage: function(){
			var _nldamage = parseInt(this.nonlethalDamage) - parseInt(this.hit);
			if(_nldamage > 0){
				this.nonlethalDamage = _nldamage;
			}else{
				this.nonlethalDamage = 0;
			}
		}
	}

});

function modifierFor(ability){
	if(!(ability < 0)){
		return Math.floor( (ability - 10) / 2 );
	}
}

function addSign(number){
	if(number >= 0){
		return "+" + number;
	}
	return number.toString();
}

function getAbilityTotal(base, bonuses) {
	var total = parseInt(base) + bonuses.reduce(function(a,b){return a+b;})
	if(isNaN(total) || total < 0){
		return 0;
	}
	return total;
}

})();<|endoftext|>


<commit_before>var _ = require('lodash'),
    combine = require('stream-combiner'),
    loadGulpPlugins = require('gulp-load-plugins'),
    CHECK_PLUGINS,
    PROCESS_PLUGINS;

function getPostCSSPlugins(pluginList, pluginOptions) {
  return _.map(pluginList, function requirePluginWithOptions(plugin) {
    var options = _.get(pluginOptions, plugin);
    return require(plugin)(options);
  });
}

CHECK_PLUGINS = [
  'stylelint',
  'reporter-plus/postcss'
];

PROCESS_PLUGINS = [
  // Sass-style convenience
  'postcss-import',
  'postcss-mixins',
  'postcss-nested',
  'postcss-simple-vars',

  // Reduce calcs, when possible
  'postcss-calc',

  // Grid system
  'lost',

  // Sane loops
  'postcss-each',
  'postcss-for',

  // Additional functions
  'postcss-color-function',

  // New selectors
  'postcss-selector-matches',
  'postcss-selector-not',

  // Some niceties
  'postcss-easings',
  'postcss-clearfix',

  // Browser compat
  'autoprefixer',
  'postcss-pseudoelements',
  'postcss-color-rgba-fallback'
];

module.exports = function buildCSS(options) {
  var gulpPlugins = loadGulpPlugins();

  options = _.defaultsDeep({}, options, {
    doCheck: true,
    doProcessing: true,
    doMinify: false,
    doConcat: false,
    doBanner: false,
    doVersioning: false,
    doSourceMaps: true,

    concatName: 'override_me.css',
    banner: '/* Built: ' + Date.now() + ' */\n',
    mapsDir: '.maps',

    postCSSOptions: {
        parser: require('postcss-scss')
      },
    pluginOptions: {
        stylelint: {
            rules: require('../runcoms/rc.stylelint.json')
          },
        'postcss-import': {
            plugins: [
                require('postcss-discard-comments')
              ],
            transform: function (fileContents) {
                // This allows us to use //-style comments in imported files, since
                // PostCSS-import doesn't allow non-css syntaxes in its parser
                return fileContents.replace(/\/\/\s(.*)\n/g, '/* $1 */\n');
              }
          },
        'postcss-simple-vars': {
            silent: true
          }
      },
    minifyOptions: {
        reduceIdents: false,
        mergeIdents: false,
        discardUnused: false,
        zindex: false
      },
    minifyRenameOptions: {
        extname: '.min.css'
      }
  });

  return combine(_.compact([
      // Checking pipeline
      options.doCheck && gulpPlugins.postcss(
          getPostCSSPlugins(CHECK_PLUGINS, options.pluginOptions),
          options.postCSSOptions
        ),

      // Processing pipeline
      options.doSourceMaps && gulpPlugins.sourcemaps.init(),
      options.doProcessing && gulpPlugins.postcss(
          getPostCSSPlugins(PROCESS_PLUGINS, options.pluginOptions),
          options.postCSSOptions
        ),

      // Productionization pipeline
      options.doMinify && gulpPlugins.cssnano(options.minifyOptions),
      options.doConcat && gulpPlugins.concat(options.concatName),
      options.doBanner && gulpPlugins.header(options.banner),
      options.doVersioning && gulpPlugins.rev(),
      options.doMinify && gulpPlugins.rename(options.minifyRenameOptions),
      options.doSourceMaps && gulpPlugins.sourcemaps.write(options.mapsDir)
  ]));
};
<commit_msg>Use globs and bower deps to resolve css imports<commit_after>var path = require('path'),
    glob = require('glob'),
    _ = require('lodash'),
    combine = require('stream-combiner'),
    loadGulpPlugins = require('gulp-load-plugins'),
    CHECK_PLUGINS,
    PROCESS_PLUGINS;

function getPostCSSPlugins(pluginList, pluginOptions) {
  return _.map(pluginList, function requirePluginWithOptions(plugin) {
    var options = _.get(pluginOptions, plugin);
    return require(plugin)(options);
  });
}

CHECK_PLUGINS = [
  'stylelint',
  'reporter-plus/postcss'
];

PROCESS_PLUGINS = [
  // Sass-style convenience
  'postcss-import',
  'postcss-mixins',
  'postcss-nested',
  'postcss-simple-vars',

  // Reduce calcs, when possible
  'postcss-calc',

  // Grid system
  'lost',

  // Sane loops
  'postcss-each',
  'postcss-for',

  // Additional functions
  'postcss-color-function',

  // New selectors
  'postcss-selector-matches',
  'postcss-selector-not',

  // Some niceties
  'postcss-easings',
  'postcss-clearfix',

  // Browser compat
  'autoprefixer',
  'postcss-pseudoelements',
  'postcss-color-rgba-fallback'
];

module.exports = function buildCSS(options) {
  var gulpPlugins = loadGulpPlugins(),
      importIDs = {};

  options = _.defaultsDeep({}, options, {
    doCheck: true,
    doProcessing: true,
    doMinify: false,
    doConcat: false,
    doBanner: false,
    doVersioning: false,
    doSourceMaps: true,

    concatName: 'override_me.css',
    banner: '/* Built: ' + Date.now() + ' */\n',
    mapsDir: '.maps',

    postCSSOptions: {
        parser: require('postcss-scss')
      },
    pluginOptions: {
        stylelint: {
            rules: require('../runcoms/rc.stylelint.json')
          },
        'postcss-import': {
            plugins: [
                require('postcss-discard-comments')
              ],
            transform: function (fileContents) {
                // This allows us to use //-style comments in imported files, since
                // PostCSS-import doesn't allow non-css syntaxes in its parser
                return fileContents.replace(/\/\/\s(.*)\n/g, '/* $1 */\n');
              },
            resolve: function (id, baseDir, options) {
                var files,
                    pattern = id,
                    globOptions = {
                        cwd: options.path[0],
                        nosort: true
                      },
                    bowerSearch;

                if (importIDs[id]) {
                  return importIDs[id];
                }

                // Look for a bower package
                bowerSearch = /^(.+):(.+)$/.exec(id);

                if (!!bowerSearch) {
                  pattern = bowerSearch[2];
                  globOptions.cwd = path.join(options.root, 'bower_components', bowerSearch[1]);
                }

                files = glob.sync(path.join('**', pattern), globOptions);

                if (files.length) {
                  files = _.map(files, function addRoot(filepath) {
                    return path.join(globOptions.cwd, filepath);
                  });

                  importIDs[id] = files;

                  return files;
                } else {
                  return [];
                }
              }
          },
        'postcss-simple-vars': {
            silent: true
          }
      },
    minifyOptions: {
        reduceIdents: false,
        mergeIdents: false,
        discardUnused: false,
        zindex: false
      },
    minifyRenameOptions: {
        extname: '.min.css'
      }
  });

  return combine(_.compact([
      // Checking pipeline
      options.doCheck && gulpPlugins.postcss(
          getPostCSSPlugins(CHECK_PLUGINS, options.pluginOptions),
          options.postCSSOptions
        ),

      // Processing pipeline
      options.doSourceMaps && gulpPlugins.sourcemaps.init(),
      options.doProcessing && gulpPlugins.postcss(
          getPostCSSPlugins(PROCESS_PLUGINS, options.pluginOptions),
          options.postCSSOptions
        ),

      // Productionization pipeline
      options.doMinify && gulpPlugins.cssnano(options.minifyOptions),
      options.doConcat && gulpPlugins.concat(options.concatName),
      options.doBanner && gulpPlugins.header(options.banner),
      options.doVersioning && gulpPlugins.rev(),
      options.doMinify && gulpPlugins.rename(options.minifyRenameOptions),
      options.doSourceMaps && gulpPlugins.sourcemaps.write(options.mapsDir)
  ]));
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2016, b3log.org & hacpai.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *Zephyr：贪吃蛇常量，暂时放在这里
 *
 *严重BUG：
 *如下可以轻易复现：蛇身向右走的时候，迅速按下下（S）和左（A），即弹出失败
 *可能原因：下这个键事件未来得及捕捉就进行了左，于是与蛇身相撞，判定为失败，如果修改了碰撞逻辑，如蛇身和苹果用不同的值
 *可能会出现直接倒退前进的现象。
 *暂时不管
 *
 *TODO：进行包装，否则作用域是全局的可能导致覆盖其他函数或变量
 */
var dir = null;
var lastDir = null
var map = null;
var food = null;
var R = 10; //圆半径或者外接正方形尺寸的一半
var size = 30
var snake = null;
var oMark = document.getElementById('mark_con'); //分数显示框
var isPause = false; //是否暂停
var snakeCanvas = document.getElementById('snakeCanvas').getContext('2d');
var interval = null;
var currTime = 200;
var stepTime = 5;
var baseLen = 6;
var startTime = null;
var endTime = null;
var countTime = null;

function init() {
    dir = {
        x: 0,
        y: 1
    };
    lastDir = {
        x: 0,
        y: 0
    };
    map = new Array();
    food = {
        x: 0,
        y: 0
    };
    snake = new Array();
    setupMap();
    setupSnake();
    drawSnake(1);
    newFood();
    clearInterval(interval);
}

function start() {
    init();
    countTime = 0;
    interval = setInterval(gameRun, currTime);
    startTime = new Date().getTime();
}

function gameRun() {
    countTime += currTime;
    updateSnake();
    drawMap();
    oMark.innerHtml = snake.length - baseLen;
}

//1:snake
//0:nothing
//2:apple
//3:block
function setupMap() {
    for (var x = 1; x <= size; x++) {
        map[x] = new Array();
        for (var y = 1; y <= size; y++) {
            if (x == 1 || x == size || y == 1 || y == size)
                map[x][y] = 3
            else
                map[x][y] = 0
        }
    }
}

function initMap() {
    map = new Array();
    setupMap();
    snakeCanvas.clearRect(0, 0, (size - 1) * 2 * R, (size - 1) * 2 * R);
    for (var x = 1; x <= size; x++) {
        for (var y = 1; y <= size; y++) {
            switch (map[x][y]) {
                case 0:
                    snakeCanvas.strokeStyle = "gray";
                    snakeCanvas.strokeRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 1:
                    snakeCanvas.fillStyle = "black";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 2:
                    snakeCanvas.fillStyle = "red";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 3:
                    snakeCanvas.fillStyle = "gray";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
            }
        }
    }
}

function drawMap() {
    snakeCanvas.clearRect(0, 0, (size - 1) * 2 * R, (size - 1) * 2 * R);
    for (var x = 1; x <= size; x++) {
        for (var y = 1; y <= size; y++) {
            switch (map[x][y]) {
                case 0:
                    snakeCanvas.strokeStyle = "gray";
                    snakeCanvas.strokeRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 1:
                    snakeCanvas.fillStyle = "black";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 2:
                    snakeCanvas.fillStyle = "red";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 3:
                    snakeCanvas.fillStyle = "gray";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
            }
        }
    }
}

function check(x, y) {
    if (map[x][y] != 0)
        return true;//true代表此处有填充p
    else
        return false;
}

function setupSnake() {
    for (var i = 1; i <= 5; i++) {
        snake[i] = {
            x: i + 5,
            y: 7
        };
    }
}

function drawSnake(toggle) {
    for (var i = 1; i < snake.length; i++) {
        map[snake[i].x][snake[i].y] = toggle;
    }
}

function newFood() {
    do {
        food.x = Math.floor(Math.random() * (size - 1) + 1);
        food.y = Math.floor(Math.random() * (size - 1) + 1);
    } while (check(food.x, food.y) == true)
    map[food.x][food.y] = 2;
}

function gameover() {
    endTime = new Date().getTime();
    console.log(endTime - startTime);
    console.log(countTime);
    clearInterval(interval);
    //可以考虑不同分数不同提示
    alert("Game Over! 您的分数是：" + (snake.length - baseLen) + "！哇哦好厉害哟！");
    var requestJSONObject = {
        score: (snake.length - baseLen)
    };
    $.ajax({
        url: Label.servePath + "/activity/eatingSnake/gameOver",
        type: "POST",
        cache: false,
        data: JSON.stringify(requestJSONObject),
        beforeSend: function () {
            var $btn = $("button.green");
            $btn.attr("disabled", "disabled").css("opacity", "0.3").text($btn.text() + 'ing');
        },
        success: function (result, textStatus) {
            alert(result.msg);

            if (result.sc) {
                window.location.reload();
            }
        },
        complete: function () {
            var $btn = $("button.green");
            $btn.removeAttr("disabled").css("opacity", "1").text($btn.text().substr(0, $btn.text().length - 3));
        }
    });
}

function eat() {
    snake[snake.length] = {
        x: snake[1].x,
        y: snake[1].y
    };
    newFood();
    clearInterval(interval);
    if (currTime >= 50)
        currTime = currTime - stepTime;
    interval = setInterval(gameRun, currTime);
}

function updateSnake() {
    lastDir.x = dir.x
    lastDir.y = dir.y
    var targetX = snake[1].x + dir.x,
            targetY = snake[1].y + dir.y;
    if (check(targetX, targetY)) {
        if (targetX == food.x && targetY == food.y) { //eat
            eat();
        } else { //hit
            gameover();
            return;
        }
    }
    drawSnake(0)
    for (var i = snake.length - 1; i >= 2; i--) {
        snake[i].x = snake[i - 1].x
        snake[i].y = snake[i - 1].y
    }
    snake[1].x = targetX
    snake[1].y = targetY

    drawSnake(1)
}

function input(keyCode) {
    switch (keyCode) {
        case 65: //左边
            if (lastDir.x == 0) {
                dir.x = -1;
                dir.y = 0;
            }
            break;
        case 87: //上边
            if (lastDir.y == 0) {
                dir.x = 0;
                dir.y = -1;
            }
            break;
        case 68: //右边
            if (lastDir.x == 0) {
                dir.x = 1;
                dir.y = 0;
            }
            break;
        case 83: //下的
            if (lastDir.y == 0) {
                dir.x = 0;
                dir.y = 1;
            }
            break;
        case 80: //开始/暂停
            if (isPause) {
                interval = setInterval(gameRun, currTime);
                isPause = false;
            } else {
                clearInterval(interval);
                isPause = true;
            }
            break;
    }
}<commit_msg>初始化蛇身速度<commit_after>/*
 * Copyright (c) 2012-2016, b3log.org & hacpai.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *Zephyr：贪吃蛇常量，暂时放在这里
 *
 *严重BUG：
 *如下可以轻易复现：蛇身向右走的时候，迅速按下下（S）和左（A），即弹出失败
 *可能原因：下这个键事件未来得及捕捉就进行了左，于是与蛇身相撞，判定为失败，如果修改了碰撞逻辑，如蛇身和苹果用不同的值
 *可能会出现直接倒退前进的现象。
 *暂时不管
 *
 *TODO：进行包装，否则作用域是全局的可能导致覆盖其他函数或变量
 */
var dir = null;
var lastDir = null
var map = null;
var food = null;
var R = 10; //圆半径或者外接正方形尺寸的一半
var size = 30
var snake = null;
var oMark = document.getElementById('mark_con'); //分数显示框
var isPause = false; //是否暂停
var snakeCanvas = document.getElementById('snakeCanvas').getContext('2d');
var interval = null;
var currTime = 200;
var stepTime = 5;
var baseLen = 6;
var startTime = null;
var endTime = null;
var countTime = null;

function init() {
    dir = {
        x: 0,
        y: 1
    };
    lastDir = {
        x: 0,
        y: 0
    };
    map = new Array();
    food = {
        x: 0,
        y: 0
    };
    currTime = 200;
    snake = new Array();
    setupMap();
    setupSnake();
    drawSnake(1);
    newFood();
    clearInterval(interval);
}

function start() {
    init();
    countTime = 0;
    interval = setInterval(gameRun, currTime);
    startTime = new Date().getTime();
}

function gameRun() {
    countTime += currTime;
    updateSnake();
    drawMap();
    oMark.innerHtml = snake.length - baseLen;
}

//1:snake
//0:nothing
//2:apple
//3:block
function setupMap() {
    for (var x = 1; x <= size; x++) {
        map[x] = new Array();
        for (var y = 1; y <= size; y++) {
            if (x == 1 || x == size || y == 1 || y == size)
                map[x][y] = 3
            else
                map[x][y] = 0
        }
    }
}

function initMap() {
    map = new Array();
    setupMap();
    snakeCanvas.clearRect(0, 0, (size - 1) * 2 * R, (size - 1) * 2 * R);
    for (var x = 1; x <= size; x++) {
        for (var y = 1; y <= size; y++) {
            switch (map[x][y]) {
                case 0:
                    snakeCanvas.strokeStyle = "gray";
                    snakeCanvas.strokeRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 1:
                    snakeCanvas.fillStyle = "black";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 2:
                    snakeCanvas.fillStyle = "red";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 3:
                    snakeCanvas.fillStyle = "gray";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
            }
        }
    }
}

function drawMap() {
    snakeCanvas.clearRect(0, 0, (size - 1) * 2 * R, (size - 1) * 2 * R);
    for (var x = 1; x <= size; x++) {
        for (var y = 1; y <= size; y++) {
            switch (map[x][y]) {
                case 0:
                    snakeCanvas.strokeStyle = "gray";
                    snakeCanvas.strokeRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 1:
                    snakeCanvas.fillStyle = "black";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 2:
                    snakeCanvas.fillStyle = "red";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
                case 3:
                    snakeCanvas.fillStyle = "gray";
                    snakeCanvas.fillRect((x - 1) * 2 * R, (y - 1) * 2 * R, 2 * R, 2 * R);
                    break;
            }
        }
    }
}

function check(x, y) {
    if (map[x][y] != 0)
        return true;//true代表此处有填充p
    else
        return false;
}

function setupSnake() {
    for (var i = 1; i <= 5; i++) {
        snake[i] = {
            x: i + 5,
            y: 7
        };
    }
}

function drawSnake(toggle) {
    for (var i = 1; i < snake.length; i++) {
        map[snake[i].x][snake[i].y] = toggle;
    }
}

function newFood() {
    do {
        food.x = Math.floor(Math.random() * (size - 1) + 1);
        food.y = Math.floor(Math.random() * (size - 1) + 1);
    } while (check(food.x, food.y) == true)
    map[food.x][food.y] = 2;
}

function gameover() {
    endTime = new Date().getTime();
    console.log(endTime - startTime);
    console.log(countTime);
    clearInterval(interval);
    //可以考虑不同分数不同提示
    alert("Game Over! 您的分数是：" + (snake.length - baseLen) + "！哇哦好厉害哟！");
    var requestJSONObject = {
        score: (snake.length - baseLen)
    };
    $.ajax({
        url: Label.servePath + "/activity/eatingSnake/gameOver",
        type: "POST",
        cache: false,
        data: JSON.stringify(requestJSONObject),
        beforeSend: function () {
            var $btn = $("button.green");
            $btn.attr("disabled", "disabled").css("opacity", "0.3").text($btn.text() + 'ing');
        },
        success: function (result, textStatus) {
            alert(result.msg);

            if (result.sc) {
                window.location.reload();
            }
        },
        complete: function () {
            var $btn = $("button.green");
            $btn.removeAttr("disabled").css("opacity", "1").text($btn.text().substr(0, $btn.text().length - 3));
        }
    });
}

function eat() {
    snake[snake.length] = {
        x: snake[1].x,
        y: snake[1].y
    };
    newFood();
    clearInterval(interval);
    if (currTime >= 50)
        currTime = currTime - stepTime;
    interval = setInterval(gameRun, currTime);
}

function updateSnake() {
    lastDir.x = dir.x
    lastDir.y = dir.y
    var targetX = snake[1].x + dir.x,
            targetY = snake[1].y + dir.y;
    if (check(targetX, targetY)) {
        if (targetX == food.x && targetY == food.y) { //eat
            eat();
        } else { //hit
            gameover();
            return;
        }
    }
    drawSnake(0)
    for (var i = snake.length - 1; i >= 2; i--) {
        snake[i].x = snake[i - 1].x
        snake[i].y = snake[i - 1].y
    }
    snake[1].x = targetX
    snake[1].y = targetY

    drawSnake(1)
}

function input(keyCode) {
    switch (keyCode) {
        case 65: //左边
            if (lastDir.x == 0) {
                dir.x = -1;
                dir.y = 0;
            }
            break;
        case 87: //上边
            if (lastDir.y == 0) {
                dir.x = 0;
                dir.y = -1;
            }
            break;
        case 68: //右边
            if (lastDir.x == 0) {
                dir.x = 1;
                dir.y = 0;
            }
            break;
        case 83: //下的
            if (lastDir.y == 0) {
                dir.x = 0;
                dir.y = 1;
            }
            break;
        case 80: //开始/暂停
            if (isPause) {
                interval = setInterval(gameRun, currTime);
                isPause = false;
            } else {
                clearInterval(interval);
                isPause = true;
            }
            break;
    }
}<|endoftext|>


<commit_before>define(module, (exports, require, make) => {

  var qp = require('qp-utility');
  var log = require('qp-library/log');

  function quote(text) { return '"' + text + '"'; }

  make({

    ns: 'qp-library/postgres/schema',

    connection: null,

    grant: function(data, done) {
      this.execute({
        text: [
          [ 'GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA', data.schema, 'TO', data.user ],
          [ 'GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA', data.schema, 'TO', data.user ]
        ],
        done: done
      });
    },

    create_table: function(data, done) {
      this.execute({
        text: [
          'CREATE TABLE', quote(data.table.name), '(',
            qp.map(data.columns, column => {
              var def = column.name;
              if (column.primary) {
                def += ' SERIAL PRIMARY KEY';
              } else {
                def += ' ' + column.type;
                if (column.array) def += '[]';
              }
              return def;
            }).join(', '),
          ')'
        ],
        done: done
      });
    },

    drop_table: function(data, done) {
      this.execute({
        text: [ 'DROP TABLE IF EXISTS', quote(data.table.name) ],
        done: done
      });
    },

    rename_table: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'RENAME TO', data.table.new_name ],
        done: done
      });
    },

    add_column: function() {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'ADD COLUMN', data.column.name, data.column.type ],
        done: done
      });
    },

    remove_column: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'DROP COLUMN', data.column.name ],
        done: done
      });
    },

    change_column: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'ALTER COLUMN', data.column.name, 'TYPE', data.column.type ],
        done: done
      });
    },

    rename_column: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'RENAME COLUMN', data.column.name, 'TO', data.column.new_name ],
        done: done
      });
    },

    add_index: function() { },
    remove_index: function() { },
    add_constraint: function() { },
    remove_constraint: function() { },

    drop_trigger: function(data, done) {
      this.execute({
        text: [ 'DROP TRIGGER IF EXISTS', data.trigger.name, 'ON', data.table.name, 'CASCADE' ],
        done: done
      });
    },

    create_row_modified_procedure: function(data, done) {
      this.execute({
        text: [
          'CREATE OR REPLACE FUNCTION notify_row_modified() RETURNS trigger AS $$',
            'DECLARE',
            '  id bigint;',
            'BEGIN',
            '  IF TG_OP = "INSERT" OR TG_OP = "UPDATE" THEN',
            '    id = NEW.id;',
            '  ELSE',
            '    id = OLD.id;',
            '  END IF;',
            '  PERFORM pg_notify("table_update", json_build_object("table", TG_TABLE_NAME, "id", id, "type", TG_OP)::text);',
            '  RETURN NEW;',
            'END;',
            '$$ LANGUAGE plpgsql;'
        ],
        done: done
      });
    },

    create_triggers: function(data, done) {
      if (qp.empty(data.triggers)) qp.done(done);
      var triggers = qp.map(data.triggers, (trigger) => {
        return this.create_trigger_command({ trigger: trigger, table: data.table });
      });
      this.execute({ text: triggers, done: done });
    },

    create_trigger: function(data, done) {
      this.execute({
        text: this.create_trigger_command(data),
        done: done
      });
    },

    create_trigger_command: function(data) {
      return [
        'CREATE TRIGGER', data.trigger.name, data.trigger.sequence || 'AFTER',
          data.trigger.event, 'ON', data.table.name,
          'FOR EACH', data.trigger.row ? 'ROW' : 'STATEMENT',
          'EXECUTE PROCEDURE', data.trigger.procedure
      ];
    },

    execute: function(config) {
      var done = config.done || qp.noop;
      var cmd = this.prepare(config);
      log(cmd.pg.text);
      this.connection.query(cmd.pg, (error, pg_result) => {
        if (error) { done(error); } else {
          var result = { cmd: cmd };
          done(null, result);
        }
      });
    },

    prepare: function(config) {
      var text = config.text;
      if (qp.is(config.text, 'array')) {
        if (qp.is(config.text[0], 'array')) {
          text = qp.map(config.text, cmd => cmd.join(' ') + ';').join(qp.eol());
        } else {
          text = config.text.join(' ');
        }
      }
      var cmd = { name: config.name, text: text, type: config.type };
      cmd[qp.lower(cmd.type)] = true;
      cmd.pg = { name: cmd.name, text: cmd.text };
      return cmd;
    }

  });

});
<commit_msg>postgres/schema - bugfixes<commit_after>define(module, (exports, require, make) => {

  var qp = require('qp-utility');
  var log = require('qp-library/log');

  function quote(text) { return '"' + text + '"'; }

  make({

    ns: 'qp-library/postgres/schema',

    connection: null,

    grant: function(data, done) {
      this.execute({
        text: [
          [ 'GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA', data.schema, 'TO', data.user ],
          [ 'GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA', data.schema, 'TO', data.user ]
        ],
        done: done
      });
    },

    create_table: function(data, done) {
      this.execute({
        text: [
          'CREATE TABLE', quote(data.table.name), '(',
            qp.map(data.columns, column => {
              var def = column.name;
              if (column.primary) {
                def += ' SERIAL PRIMARY KEY';
              } else {
                def += ' ' + column.type;
                if (column.array) def += '[]';
              }
              return def;
            }).join(', '),
          ')'
        ],
        done: done
      });
    },

    drop_table: function(data, done) {
      this.execute({
        text: [ 'DROP TABLE IF EXISTS', quote(data.table.name) ],
        done: done
      });
    },

    rename_table: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'RENAME TO', data.table.new_name ],
        done: done
      });
    },

    add_column: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'ADD COLUMN', data.column.name, data.column.type ],
        done: done
      });
    },

    remove_column: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'DROP COLUMN', data.column.name ],
        done: done
      });
    },

    change_column: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'ALTER COLUMN', data.column.name, 'TYPE', data.column.type ],
        done: done
      });
    },

    rename_column: function(data, done) {
      this.execute({
        text: [ 'ALTER TABLE', data.table.name, 'RENAME COLUMN', data.column.name, 'TO', data.column.new_name ],
        done: done
      });
    },

    add_index: function() { },
    remove_index: function() { },
    add_constraint: function() { },
    remove_constraint: function() { },

    drop_trigger: function(data, done) {
      this.execute({
        text: [ 'DROP TRIGGER IF EXISTS', data.trigger.name, 'ON', data.table.name, 'CASCADE' ],
        done: done
      });
    },

    create_row_modified_procedure: function(data, done) {
      this.execute({
        text: [
          'CREATE OR REPLACE FUNCTION notify_row_modified() RETURNS trigger AS $$',
            'DECLARE',
            '  id bigint;',
            'BEGIN',
            '  IF TG_OP = \'INSERT\' OR TG_OP = \'UPDATE\' THEN',
            '    id = NEW.id;',
            '  ELSE',
            '    id = OLD.id;',
            '  END IF;',
            '  PERFORM pg_notify(\'row_modified\', json_build_object(\'table\', TG_TABLE_NAME, \'id\', id, \'type\', TG_OP)::text);',
            '  RETURN NEW;',
            'END;',
            '$$ LANGUAGE plpgsql;'
        ],
        done: done
      });
    },

    create_triggers: function(data, done) {
      if (qp.empty(data.triggers)) return done();
      var triggers = qp.map(data.triggers, (trigger) => {
        return this.create_trigger_command({ trigger: trigger, table: data.table });
      });
      this.execute({ text: triggers, done: done });
    },

    create_trigger: function(data, done) {
      this.execute({
        text: this.create_trigger_command(data),
        done: done
      });
    },

    create_trigger_command: function(data) {
      return [
        'CREATE TRIGGER', data.trigger.name, data.trigger.sequence || 'AFTER',
          data.trigger.event, 'ON', data.table.name,
          'FOR EACH', data.trigger.row ? 'ROW' : 'STATEMENT',
          'EXECUTE PROCEDURE', data.trigger.procedure + '()'
      ];
    },

    execute: function(config) {
      var done = config.done || qp.noop;
      var cmd = this.prepare(config);
      log(cmd.pg.text);
      this.connection.query(cmd.pg, (error, pg_result) => {
        if (error) { done(error); } else {
          var result = { cmd: cmd };
          done(null, result);
        }
      });
    },

    prepare: function(config) {
      var text = config.text;
      if (qp.is(config.text, 'array')) {
        if (qp.is(config.text[0], 'array')) {
          text = qp.map(config.text, cmd => cmd.join(' ') + ';').join(qp.eol());
        } else {
          text = config.text.join(' ');
        }
      }
      var cmd = { name: config.name, text: text, type: config.type };
      cmd[qp.lower(cmd.type)] = true;
      cmd.pg = { name: cmd.name, text: cmd.text };
      return cmd;
    }

  });

});
<|endoftext|>


<commit_before>'use strict';

angular.module('metadatamanagementApp', ['LocalStorageModule', 'tmh.dynamicLocale', 'pascalprecht.translate',
               'ui.bootstrap', // for modal dialogs
    'ngResource', 'ui.router', 'ngCookies', 'ngAria', 'ngCacheBuster', 'ngFileUpload', 'infinite-scroll'])

    .run(function ($rootScope, $location, $window, $http, $state, $translate, Language, Auth, Principal, ENV, VERSION) {
        $rootScope.ENV = ENV;
        $rootScope.VERSION = VERSION;
        $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
            $rootScope.toState = toState;
            $rootScope.toStateParams = toStateParams;

            if (Principal.isIdentityResolved()) {
                Auth.authorize();
            }

            // Update the language
            Language.getCurrent().then(function (language) {
                $translate.use(language);
            });

        });

        $rootScope.$on('$stateChangeSuccess',  function(event, toState, toParams, fromState, fromParams) {
            var titleKey = 'global.title' ;

            // Remember previous state unless we've been redirected to login or we've just
            // reset the state memory after logout. If we're redirected to login, our
            // previousState is already set in the authExpiredInterceptor. If we're going
            // to login directly, we don't want to be sent to some previous state anyway
            if (toState.name != 'login' && $rootScope.previousStateName) {
              $rootScope.previousStateName = fromState.name;
              $rootScope.previousStateParams = fromParams;
            }

            // Set the page title key to the one configured in state or use default one
            if (toState.data.pageTitle) {
                titleKey = toState.data.pageTitle;
            }

            $translate(titleKey).then(function (title) {
                // Change window title with translated one
                $window.document.title = title;
            });

        });

        $rootScope.back = function() {
            // If previous state is 'activate' or do not exist go to 'home'
            if ($rootScope.previousStateName === 'activate' || $state.get($rootScope.previousStateName) === null) {
                $state.go('home');
            } else {
                $state.go($rootScope.previousStateName, $rootScope.previousStateParams);
            }
        };
    })
    .config(function ($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider, $translateProvider, tmhDynamicLocaleProvider, httpRequestInterceptorCacheBusterProvider) {

        //Cache everything except rest api requests
        httpRequestInterceptorCacheBusterProvider.setMatchlist([/.*api.*/, /.*protected.*/], true);

        $urlRouterProvider.otherwise('/');
        $stateProvider.state('site', {
            'abstract': true,
            views: {
                'navbar@': {
                    templateUrl: 'scripts/components/navbar/navbar.html',
                    controller: 'NavbarController'
                }
            },
            resolve: {
                authorize: ['Auth',
                    function (Auth) {
                        return Auth.authorize();
                    }
                ],
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('global');
                }]
            }
        });

        $httpProvider.interceptors.push('errorHandlerInterceptor');
        $httpProvider.interceptors.push('authExpiredInterceptor');
        $httpProvider.interceptors.push('authInterceptor');
        $httpProvider.interceptors.push('notificationInterceptor');

        // Initialize angular-translate
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'i18n/{lang}/{part}.json'
        });

        $translateProvider.preferredLanguage('de');
        $translateProvider.useCookieStorage();
        $translateProvider.useSanitizeValueStrategy('escaped');
        $translateProvider.addInterpolation('$translateMessageFormatInterpolation');

        tmhDynamicLocaleProvider.localeLocationPattern('bower_components/angular-i18n/angular-locale_{{locale}}.js');
        tmhDynamicLocaleProvider.useCookieStorage();
        tmhDynamicLocaleProvider.storageKey('NG_TRANSLATE_LANG_KEY');

    })
    .config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) {
        $urlMatcherFactory.type('boolean', {
            name : 'boolean',
            decode: function(val) { return val == true ? true : val == "true" ? true : false },
            encode: function(val) { return val ? 1 : 0; },
            equals: function(a, b) { return this.is(a) && a === b; },
            is: function(val) { return [true,false,0,1].indexOf(val) >= 0 },
            pattern: /bool|true|0|1/
        });
    }]);;
<commit_msg>#74 trying to fix the translation error<commit_after>'use strict';

angular.module('metadatamanagementApp', ['LocalStorageModule', 'tmh.dynamicLocale', 'pascalprecht.translate',
               'ui.bootstrap', // for modal dialogs
    'ngResource', 'ui.router', 'ngCookies', 'ngAria', 'ngCacheBuster', 'ngFileUpload', 'infinite-scroll'])

    .run(function ($rootScope, $location, $window, $http, $state, $translate, Language, Auth, Principal, ENV, VERSION) {
        $rootScope.ENV = ENV;
        $rootScope.VERSION = VERSION;
        $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
            $rootScope.toState = toState;
            $rootScope.toStateParams = toStateParams;

            if (Principal.isIdentityResolved()) {
                Auth.authorize();
            }

            // Update the language
            Language.getCurrent().then(function (language) {
                $translate.use(language);
            });

        });

        $rootScope.$on('$stateChangeSuccess',  function(event, toState, toParams, fromState, fromParams) {
            var titleKey = 'global.title' ;

            // Remember previous state unless we've been redirected to login or we've just
            // reset the state memory after logout. If we're redirected to login, our
            // previousState is already set in the authExpiredInterceptor. If we're going
            // to login directly, we don't want to be sent to some previous state anyway
            if (toState.name != 'login' && $rootScope.previousStateName) {
              $rootScope.previousStateName = fromState.name;
              $rootScope.previousStateParams = fromParams;
            }

            // Set the page title key to the one configured in state or use default one
            if (toState.data.pageTitle) {
                titleKey = toState.data.pageTitle;
            }

            $translate(titleKey).then(function (title) {
                // Change window title with translated one
                $window.document.title = title;
            });

        });

        $rootScope.back = function() {
            // If previous state is 'activate' or do not exist go to 'home'
            if ($rootScope.previousStateName === 'activate' || $state.get($rootScope.previousStateName) === null) {
                $state.go('home');
            } else {
                $state.go($rootScope.previousStateName, $rootScope.previousStateParams);
            }
        };
    })
    .config(function ($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider, $translateProvider, tmhDynamicLocaleProvider, httpRequestInterceptorCacheBusterProvider) {

        //Cache everything except rest api requests
        httpRequestInterceptorCacheBusterProvider.setMatchlist([/.*api.*/, /.*protected.*/], true);

        $urlRouterProvider.otherwise('/');
        $stateProvider.state('site', {
            'abstract': true,
            views: {
                'navbar@': {
                    templateUrl: 'scripts/components/navbar/navbar.html',
                    controller: 'NavbarController'
                }
            },
            resolve: {
                authorize: ['Auth',
                    function (Auth) {
                        return Auth.authorize();
                    }
                ],
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('global');
                }]
            }
        });

        $httpProvider.interceptors.push('errorHandlerInterceptor');
        $httpProvider.interceptors.push('authExpiredInterceptor');
        $httpProvider.interceptors.push('authInterceptor');
        $httpProvider.interceptors.push('notificationInterceptor');

        // Initialize angular-translate
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'i18n/{lang}/{part}.json'
        });

        $translateProvider.preferredLanguage('en');
        $translateProvider.useCookieStorage();
        $translateProvider.useSanitizeValueStrategy('escaped');
        $translateProvider.addInterpolation('$translateMessageFormatInterpolation');

        tmhDynamicLocaleProvider.localeLocationPattern('bower_components/angular-i18n/angular-locale_{{locale}}.js');
        tmhDynamicLocaleProvider.useCookieStorage();
        tmhDynamicLocaleProvider.storageKey('NG_TRANSLATE_LANG_KEY');

    })
    .config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) {
        $urlMatcherFactory.type('boolean', {
            name : 'boolean',
            decode: function(val) { return val == true ? true : val == "true" ? true : false },
            encode: function(val) { return val ? 1 : 0; },
            equals: function(a, b) { return this.is(a) && a === b; },
            is: function(val) { return [true,false,0,1].indexOf(val) >= 0 },
            pattern: /bool|true|0|1/
        });
    }]);;
<|endoftext|>


<commit_before>var util    = require('util'),
    winston = require('winston');

var Camera,
    stream,
    isStreaming = false;

function Stream( opts ) {
    if ( !(this instanceof Stream) ) {
        return new Stream( opts );
    }

    var required = ['module', 'preview_path', 'preview', 'photo_path', 'photo'];
    for (var i in required) {
       if ('undefined' === typeof opts || 'undefined' === typeof opts[required[i]]) {
           winston.error('Error: raspberry: must define ' + required[i]);
       }
    }

    this.opts = {};
    this.setOpts(opts);
}

Stream.prototype.setOpts = function(opts) {
    this.opts = util._extend(this.opts, opts);
    this.opts.preview.output = this.formatPath(this.opts.preview_path);
    this.opts.photo.output = this.formatPath(this.opts.photo_path);

    if ('undefined' !== typeof opts.module) {
        var module = this.opts.module;
        winston.info('switch to ' + module + ' camera');
        try {
            Camera = require(module);
        } catch (e) {
            Camera = require('../' + module);
        }
    }
};

Stream.prototype.formatPath = function(path) {
    return path
        .replace('%root%', process.cwd())
        .replace('%ts%', new Date().getTime());
};

Stream.prototype.start = function(callback) {
    if (isStreaming) {
        return;
    }
    winston.info('start stream');

    var self = this;
    stream = new Camera(self.opts.preview);
    stream
        .on('change', function(err, date, filename) {
            if ('~' === filename.slice(-1)) {
                return;
            }
            callback.call(this, err, date, filename);
        })
        .start();
    isStreaming = true;
    return true;
};

Stream.prototype.stop = function() {
    winston.info('stop stream');

    stream.stop();
    isStreaming = false;
    return true;
};

Stream.prototype.capture = function(callback) {
    this.stop();
    this.setOpts({}); // update paths

    var self = this;

    winston.info('start capture');
    var capture = new Camera(self.opts.photo);
    capture
        .on('exit', function() {
            callback.call(this, '', new Date().getTime(), self.opts.photo.output);
            self.start(stream.listeners('change')[0]);
        })
        .start();
    return true;
};

module.exports.Stream = Stream;
<commit_msg>Ignore temp files<commit_after>var util    = require('util'),
    winston = require('winston');

var Camera,
    stream,
    isStreaming = false;

function Stream( opts ) {
    if ( !(this instanceof Stream) ) {
        return new Stream( opts );
    }

    var required = ['module', 'preview_path', 'preview', 'photo_path', 'photo'];
    for (var i in required) {
       if ('undefined' === typeof opts || 'undefined' === typeof opts[required[i]]) {
           winston.error('Error: raspberry: must define ' + required[i]);
       }
    }

    this.opts = {};
    this.setOpts(opts);
}

Stream.prototype.setOpts = function(opts) {
    this.opts = util._extend(this.opts, opts);
    this.opts.preview.output = this.formatPath(this.opts.preview_path);
    this.opts.photo.output = this.formatPath(this.opts.photo_path);

    if ('undefined' !== typeof opts.module) {
        var module = this.opts.module;
        winston.info('switch to ' + module + ' camera');
        try {
            Camera = require(module);
        } catch (e) {
            Camera = require('../' + module);
        }
    }
};

Stream.prototype.formatPath = function(path) {
    return path
        .replace('%root%', process.cwd())
        .replace('%ts%', new Date().getTime());
};

Stream.prototype.start = function(callback) {
    if (isStreaming) {
        return;
    }
    winston.info('start stream');

    var self = this;
    stream = new Camera(self.opts.preview);
    stream
        .on('read', function(err, date, filename) {
            if ('~' === filename.slice(-1)) {
                return;
            }
            callback.call(this, err, date, filename);
        })
        .start();
    isStreaming = true;
    return true;
};

Stream.prototype.stop = function() {
    winston.info('stop stream');

    stream.stop();
    isStreaming = false;
    return true;
};

Stream.prototype.capture = function(callback) {
    this.stop();
    this.setOpts({}); // update paths

    var self = this;

    winston.info('start capture');
    var capture = new Camera(self.opts.photo);
    capture
        .on('exit', function() {
            callback.call(this, '', new Date().getTime(), self.opts.photo.output);
            self.start(stream.listeners('change')[0]);
        })
        .start();
    return true;
};

module.exports.Stream = Stream;
<|endoftext|>


<commit_before>import React from 'react';
import { map } from 'lodash';

import Table from '../Table';
import './history-modal.scss';

class HistoryModal extends React.Component {
  constructor() {
    super();

    this.state = {
      quantity: null
    };

    this.onUpdate = this.onUpdate.bind(this);
    this.parseEventData = this.parseEventData.bind(this);
  }

  onUpdate(event) {
    this.setState({ quantity: event.target.value });
  }

  parseEventData(events) {
    var eventsWithChange = [];

    for(var i = 0; i < events.length; i++) {
      var current = events[i];
      var next = events[i+1];

      if (next) {
        if (current.content.quantity != next.content.quantity || current.content.why_participated != next.content.why_participated || current.content.quantity_pending != next.content.quantity_pending) {
          // If there is a difference in the record, add to the log.
          eventsWithChange.push(current);
        }
      }
    }

    // Always include the first event in the response
    // so there is something in the table.
    // @TODO: change this when we start paginating.
    eventsWithChange.push(events[events.length-1]);

    return eventsWithChange;
  }

  render() {
    const signup = this.props.signup;
    const campaign = this.props['campaign'];
    const parsedEvents = this.parseEventData(this.props.signupEvents);

    return (

        ×

Change Quantity

Old Quantity

{signup['quantity']} {campaign['reportback_info']['noun']} {campaign['reportback_info']['verb']}

New Quantity

              <input type="text" onChange={this.onUpdate} className="text-field" placeholder="Enter # here"/>

📖 History 📖

Below shows the 20 most recent changes to the member's signup. This includes changes to the quantity or why. If you need changes beyond the 20 listed here, please reach out to Team Bleed!

        <button className="button -history" disabled={!this.state.quantity} onClick={() => this.props.onUpdate(signup, this.state.quantity)}>Save</button>

    );
  }
}

export default HistoryModal;
<commit_msg>Add proptype validation to HistoryModal<commit_after>import React from 'react';
import { map } from 'lodash';
import PropTypes from 'prop-types';

import Table from '../Table';
import './history-modal.scss';

class HistoryModal extends React.Component {
  constructor() {
    super();

    this.state = {
      quantity: null
    };

    this.onUpdate = this.onUpdate.bind(this);
    this.parseEventData = this.parseEventData.bind(this);
  }

  onUpdate(event) {
    this.setState({ quantity: event.target.value });
  }

  parseEventData(events) {
    var eventsWithChange = [];

    for(var i = 0; i < events.length; i++) {
      var current = events[i];
      var next = events[i+1];

      if (next) {
        if (current.content.quantity != next.content.quantity || current.content.why_participated != next.content.why_participated || current.content.quantity_pending != next.content.quantity_pending) {
          // If there is a difference in the record, add to the log.
          eventsWithChange.push(current);
        }
      }
    }

    // Always include the first event in the response
    // so there is something in the table.
    // @TODO: change this when we start paginating.
    eventsWithChange.push(events[events.length-1]);

    return eventsWithChange;
  }

  render() {
    const signup = this.props.signup;
    const campaign = this.props.campaign;
    const parsedEvents = this.parseEventData(this.props.signupEvents);

    return (

        ×

Change Quantity

Old Quantity

{signup['quantity']} {campaign['reportback_info']['noun']} {campaign['reportback_info']['verb']}

New Quantity

              <input type="text" onChange={this.onUpdate} className="text-field" placeholder="Enter # here"/>

📖 History 📖

Below shows the 20 most recent changes to the member's signup. This includes changes to the quantity or why. If you need changes beyond the 20 listed here, please reach out to Team Bleed!

        <button className="button -history" disabled={!this.state.quantity} onClick={() => this.props.onUpdate(signup, this.state.quantity)}>Save</button>

    );
  }
}

HistoryModal.propTypes = {
  campaign: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  onClose: PropTypes.func.isRequired,
  onUpdate: PropTypes.func.isRequired,
  signup: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  signupEvents: PropTypes.array.isRequired, // eslint-disable-line react/forbid-prop-types
};

export default HistoryModal;
<|endoftext|>


<commit_before>import { ms } from "../../ms.js";
export default function minewarfare(
  sId,
  sIdm1,
  sIdm2,
  bbox,
  symbolSet,
  icn,
  _STD2525
) {
  //Mine Warfare
  if (symbolSet == "36") {
    sId["110000"] = [icn["SU.IC.SEA MINE"]];
    sId["110100"] = [icn["SU.IC.SEA MINE - BOTTOM"]];
    sId["110200"] = [icn["SU.IC.SEA MINE - MOORED"]];
    sId["110300"] = [icn["SU.IC.SEA MINE - FLOATING"]];
    sId["110400"] = [icn["SU.IC.SEA MINE - RISING"]];
    sId["110500"] = [icn["SU.IC.SEA MINE (IN OTHER POSITION)"]];
    sId["110600"] = [icn["SU.IC.SEA MINE - KINGFISHER"]];
    sId["110700"] = [icn["SU.IC.SEA MINE - SMALL OBJECT"]];
    sId["110800"] = [icn["SU.IC.SEA MINE EXERCISE MINE"]];
    sId["110801"] = [icn["SU.IC.SEA MINE EXERCISE MINE - BOTTOM"]];
    sId["110802"] = [icn["SU.IC.SEA MINE EXERCISE MINE - MOORED"]];
    sId["110803"] = [icn["SU.IC.SEA MINE EXERCISE MINE - FLOATING"]];
    sId["110804"] = [icn["SU.IC.SEA MINE EXERCISE MINE - RISING"]];
    sId["110900"] = [icn["SU.IC.SEA MINE NEUTRALIZED"]];
    sId["110901"] = [icn["SU.IC.SEA MINE NEUTRALIZED - BOTTOM"]];
    sId["110902"] = [icn["SU.IC.SEA MINE NEUTRALIZED - MOORED"]];
    sId["110903"] = [icn["SU.IC.SEA MINE NEUTRALIZED - FLOATING"]];
    sId["110904"] = [icn["SU.IC.SEA MINE NEUTRALIZED - RISING"]];
    sId["110905"] = [icn["SU.IC.SEA MINE (IN OTHER POSITION) NEUTRALIZED"]];
    sId["120000"] = [icn["SU.IC.UNEXPLODED EXPLOSIVE ORDNANCE"]];
    sId["130000"] = [icn["SU.IC.SEA MINE DECOY"]];
    sId["130100"] = [icn["SU.IC.SEA MINE DECOY, BOTTOM/GROUND"]];
    sId["130200"] = [icn["SU.IC.SEA MINE DECOY, MOORED"]];
    //sId['140000'] = 'Mine-Like Contact (MILCO)';
    sId["140100"] = [ms._scale(1.3, icn["SU.IC.SEA MINE MILCO"])];
    sId["140101"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
      ])
    ];
    sId["140102"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
      ])
    ];
    sId["140103"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
      ])
    ];
    sId["140104"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
      ])
    ];
    sId["140105"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
      ])
    ];
    sId["140200"] = [icn["SU.IC.SEA MINE MILCO - BOTTOM"]];
    sId["140201"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
    ];
    sId["140202"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
    ];
    sId["140203"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
    ];
    sId["140204"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
    ];
    sId["140205"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
    ];
    sId["140300"] = [icn["SU.IC.SEA MINE MILCO - MOORED"]];
    sId["140301"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
    ];
    sId["140302"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
    ];
    sId["140303"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
    ];
    sId["140304"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
    ];
    sId["140305"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
    ];
    sId["140400"] = [icn["SU.IC.SEA MINE MILCO - FLOATING"]];
    sId["140401"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
    ];
    sId["140402"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
    ];
    sId["140403"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
    ];
    sId["140404"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
    ];
    sId["140405"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
    ];
    sId["150000"] = [ms._scale(1.3, icn["SU.IC.SEA MINE MILEC"])];
    sId["150100"] = [icn["SU.IC.SEA MINE MILEC - BOTTOM"]];
    sId["150200"] = [icn["SU.IC.SEA MINE MILEC - MOORED"]];
    sId["150300"] = [icn["SU.IC.SEA MINE MILEC - FLOATING"]];
    sId["160000"] = [
      ms._scale(1.3, icn["SU.IC.SEA MINE NEGATIVE REACQUISITION"])
    ];
    sId["160100"] = [icn["SU.IC.SEA MINE NEGATIVE REACQUISITION - BOTTOM"]];
    sId["160200"] = [icn["SU.IC.SEA MINE NEGATIVE REACQUISITION - MOORED"]];
    sId["160300"] = [icn["SU.IC.SEA MINE NEGATIVE REACQUISITION - FLOATING"]];
    sId["170000"] = [ms._scale(1.3, icn["SU.IC.SEA MINE GENERAL OBSTRUCTOR"])];
    sId["170100"] = [icn["SU.IC.SEA MINE GENERAL OBSTRUCTOR NEUTRALIZED"]];
    sId["180000"] = [ms._scale(1.3, icn["SU.IC.SEA MINE MINE ANCHOR"])];
    sId["190000"] = [
      ms._scale(1.3, icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT"])
    ];
    sId["190100"] = [icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT - BOTTOM"]];
    sId["190200"] = [icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT - MOORED"]];
    sId["190300"] = [
      icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT - FLOATING"]
    ];
    sId["200000"] = [icn["SU.IC.ENVIRONMENTAL REPORT LOCATION"]];
    sId["210000"] = [icn["SU.IC.DIVE REPORT LOCATION"]];
  }
}
<commit_msg>Add Mine-Like Contact<commit_after>import { ms } from "../../ms.js";
export default function minewarfare(
  sId,
  sIdm1,
  sIdm2,
  bbox,
  symbolSet,
  icn,
  _STD2525
) {
  //Mine Warfare
  if (symbolSet == "36") {
    sId["110000"] = [icn["SU.IC.SEA MINE"]];
    sId["110100"] = [icn["SU.IC.SEA MINE - BOTTOM"]];
    sId["110200"] = [icn["SU.IC.SEA MINE - MOORED"]];
    sId["110300"] = [icn["SU.IC.SEA MINE - FLOATING"]];
    sId["110400"] = [icn["SU.IC.SEA MINE - RISING"]];
    sId["110500"] = [icn["SU.IC.SEA MINE (IN OTHER POSITION)"]];
    sId["110600"] = [icn["SU.IC.SEA MINE - KINGFISHER"]];
    sId["110700"] = [icn["SU.IC.SEA MINE - SMALL OBJECT"]];
    sId["110800"] = [icn["SU.IC.SEA MINE EXERCISE MINE"]];
    sId["110801"] = [icn["SU.IC.SEA MINE EXERCISE MINE - BOTTOM"]];
    sId["110802"] = [icn["SU.IC.SEA MINE EXERCISE MINE - MOORED"]];
    sId["110803"] = [icn["SU.IC.SEA MINE EXERCISE MINE - FLOATING"]];
    sId["110804"] = [icn["SU.IC.SEA MINE EXERCISE MINE - RISING"]];
    sId["110900"] = [icn["SU.IC.SEA MINE NEUTRALIZED"]];
    sId["110901"] = [icn["SU.IC.SEA MINE NEUTRALIZED - BOTTOM"]];
    sId["110902"] = [icn["SU.IC.SEA MINE NEUTRALIZED - MOORED"]];
    sId["110903"] = [icn["SU.IC.SEA MINE NEUTRALIZED - FLOATING"]];
    sId["110904"] = [icn["SU.IC.SEA MINE NEUTRALIZED - RISING"]];
    sId["110905"] = [icn["SU.IC.SEA MINE (IN OTHER POSITION) NEUTRALIZED"]];
    sId["120000"] = [icn["SU.IC.UNEXPLODED EXPLOSIVE ORDNANCE"]];
    sId["130000"] = [icn["SU.IC.SEA MINE DECOY"]];
    sId["130100"] = [icn["SU.IC.SEA MINE DECOY, BOTTOM/GROUND"]];
    sId["130200"] = [icn["SU.IC.SEA MINE DECOY, MOORED"]];
    sId["140000"] = []; //'Mine-Like Contact (MILCO)';
    sId["140100"] = [ms._scale(1.3, icn["SU.IC.SEA MINE MILCO"])];
    sId["140101"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
      ])
    ];
    sId["140102"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
      ])
    ];
    sId["140103"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
      ])
    ];
    sId["140104"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
      ])
    ];
    sId["140105"] = [
      ms._scale(1.3, [
        icn["SU.IC.SEA MINE MILCO"],
        icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
      ])
    ];
    sId["140200"] = [icn["SU.IC.SEA MINE MILCO - BOTTOM"]];
    sId["140201"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
    ];
    sId["140202"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
    ];
    sId["140203"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
    ];
    sId["140204"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
    ];
    sId["140205"] = [
      icn["SU.IC.SEA MINE MILCO - BOTTOM"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
    ];
    sId["140300"] = [icn["SU.IC.SEA MINE MILCO - MOORED"]];
    sId["140301"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
    ];
    sId["140302"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
    ];
    sId["140303"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
    ];
    sId["140304"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
    ];
    sId["140305"] = [
      icn["SU.IC.SEA MINE MILCO - MOORED"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
    ];
    sId["140400"] = [icn["SU.IC.SEA MINE MILCO - FLOATING"]];
    sId["140401"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 1"]
    ];
    sId["140402"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 2"]
    ];
    sId["140403"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 3"]
    ];
    sId["140404"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 4"]
    ];
    sId["140405"] = [
      icn["SU.IC.SEA MINE MILCO - FLOATING"],
      icn["SU.IC.SEA MINE MILCO - GENERAL, CONFIDENCE LEVEL 5"]
    ];
    sId["150000"] = [ms._scale(1.3, icn["SU.IC.SEA MINE MILEC"])];
    sId["150100"] = [icn["SU.IC.SEA MINE MILEC - BOTTOM"]];
    sId["150200"] = [icn["SU.IC.SEA MINE MILEC - MOORED"]];
    sId["150300"] = [icn["SU.IC.SEA MINE MILEC - FLOATING"]];
    sId["160000"] = [
      ms._scale(1.3, icn["SU.IC.SEA MINE NEGATIVE REACQUISITION"])
    ];
    sId["160100"] = [icn["SU.IC.SEA MINE NEGATIVE REACQUISITION - BOTTOM"]];
    sId["160200"] = [icn["SU.IC.SEA MINE NEGATIVE REACQUISITION - MOORED"]];
    sId["160300"] = [icn["SU.IC.SEA MINE NEGATIVE REACQUISITION - FLOATING"]];
    sId["170000"] = [ms._scale(1.3, icn["SU.IC.SEA MINE GENERAL OBSTRUCTOR"])];
    sId["170100"] = [icn["SU.IC.SEA MINE GENERAL OBSTRUCTOR NEUTRALIZED"]];
    sId["180000"] = [ms._scale(1.3, icn["SU.IC.SEA MINE MINE ANCHOR"])];
    sId["190000"] = [
      ms._scale(1.3, icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT"])
    ];
    sId["190100"] = [icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT - BOTTOM"]];
    sId["190200"] = [icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT - MOORED"]];
    sId["190300"] = [
      icn["SU.IC.SEA MINE NON-MINE MINE-LIKE CONTACT - FLOATING"]
    ];
    sId["200000"] = [icn["SU.IC.ENVIRONMENTAL REPORT LOCATION"]];
    sId["210000"] = [icn["SU.IC.DIVE REPORT LOCATION"]];
  }
}
<|endoftext|>


<commit_before>//Define the global variable(s).
var html = "";

//Called when application is started.
function OnStart()
{
	//Create the major components of the application.
	lay = app.CreateLayout( "linear", "VCenter,FillXY" );
	scroll = app.CreateScroller( );
    webView = app.CreateWebView( 1, 1, "IgnoreErrors,NoScrollBars", true );

    //Create the back and forward buttons.
    back = app.CreateButton( "Back" );
    back.SetOnTouch( back_OnTouch );
    forward = app.CreateButton ( "Forward" );
    forward.SetOnTouch( forward_OnTouch );

    //Create the toolbar.
    toolbar = app.CreateLayout( "linear", "horizontal" );
    toolbar.AddChild( back );
    toolbar.AddChild( forward );

	//Create tabs.
    tabs = app.CreateTabs( "RSS Select,Feed", 1, 1, "VCenter" );
    tabs.SetOnChange( tabs_OnChange );
    lay.AddChild( tabs );

    //Define the tab layouts.
    layRSS = tabs.GetLayout( "RSS Select" );
    layFeed = tabs.GetLayout( "Feed" );

    //Create an text edit box for url entry.
	edt = app.CreateTextEdit( "https://news.google.com/news/rss", 0.8 );
	edt.SetMargins( 0, 0.05, 0, 0 );
	layRSS.AddChild( edt );

    //Create a button to send request.
	read = app.CreateButton( "Read RSS Feed", 0.3, 0.1 );
	read.SetMargins( 0, 0.025, 0, 0.025 );
    read.SetOnTouch( read_OnTouch );
    layRSS.AddChild( read );

    //Add the scroller to the webView.
    scroll.AddChild ( webView );

    //Add the scroller and the back button to the feed.
    layFeed.AddChild( toolbar );
    layFeed.AddChild( scroll );

	//Add layout to app.
	app.AddLayout( lay );
}

//Handle tab selection.
function tabs_OnChange( name )
{
    app.ShowPopup( name );
}

//Handle read button press.
function read_OnTouch()
{
    //Send request to remote server.
    var url = edt.GetText();
    app.ShowProgress( "Loading..." );
    request(url);
    tabs.ShowTab( "Feed" );
}

//Handle back button press.
function back_OnTouch()
{   if(webView.CanGoBack)
    {
        webView.Back();
    }
}

//Handle forward button press.
function forward_OnTouch()
{
    if(webView.CanGoForward)
    {
        webView.Forward();
    }
}

//Handle requests.
function request(url)
{
    // Create the GET request and call process().
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() { process(xmlhttp) };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

// Test the data and pass an appropriate response to webView as HTML.
function process(data)
{
    if(data.readyState === 4)
    {
        if(data.status === 200)
        {
            //Gather the XML objects and information about the RSS.
            var rssInfo = data.responseXML.getElementsByTagName("rss");
            var feedInfo = data.responseXML.getElementsByTagName("feed");
            var xmlObjects = data.responseXML;

            //Test to make sure this is indeed RSS and that it is version 2.
            if(rssInfo.length > 0 && rssInfo.item(0) !== 'undefined' && rssInfo.item(0).getAttribute("version") === "2.0")
            {

                //Gather some more detailed information about the feed.
                var feedLength = xmlObjects.getElementsByTagName("item").length;
                var channelTitle = xmlObjects.getElementsByTagName("title").item(0).firstChild.data;
                var channelDescription = xmlObjects.getElementsByTagName("description").item(0).firstChild.data;

                //Add the title and description to the HTML.
                html = html
                    + "
"
                    + channelTitle
                    + "
"
                    + "
"
                    + channelDescription
                    + "
";

                //For each item in the feed, add a linked title and the description to the HTML.
                for (var i = 1; i < feedLength; i ++)
                {
                    var item = xmlObjects.getElementsByTagName("item").item(i);
                    html = html
                        + "
"
                        + item.getElementsByTagName("title").item(0).firstChild.data
                        + "

"
                        + item.getElementsByTagName("description").item(0).firstChild.data
                        + "
";
                }

                //Display the results.
                webView.LoadHtml(html);
                webView.SetSize( 1, 0.6 );
                webView.Show();
                app.HideProgress();
            }
            else if(feedInfo.length > 0 && feedInfo.item(0) !== 'undefined' && feedInfo.item(0).getAttribute("xmlns") === "http://www.w3.org/2005/Atom")
            {
                //Gather the XML objects.
                var xmlObjects = data.responseXML;

                //Gather some information about the feed.
                var feedLength = xmlObjects.getElementsByTagName("entry").length;
                var channelTitle = xmlObjects.getElementsByTagName("title").item(0).firstChild.data;

                //Add the title to the HTML.
                html = html
                    + "
"
                    + channelTitle
                    + "
";

                //For each item in the feed, add a linked title and the description to the HTML.
                for (var i = 1; i < feedLength; i ++)
                {
                    var item = xmlObjects.getElementsByTagName("entry").item(i);
                    html = html
                        + "
"
                        + item.getElementsByTagName("title").item(0).firstChild.data
                        + "

"
                        + item.getElementsByTagName("content").item(0).firstChild.data
                        + "
";
                }

                //Display the results.
                webView.LoadHtml(html);
                webView.SetSize( 1, 0.6 );
                webView.Show();
                app.HideProgress();
            }
            else
            {
                //Tell the user that the RSS was not version 2.0.
                webView.LoadHtml("
RSS version incompatible.
"
                    + "
Please input a RSS Version 2.0 feed or an RSS Atom feed.
");
                webView.SetSize( 1, 0.6 );
                webView.Show();
                app.HideProgress();
            }
        }
        else
        {
            //Tell the user the status of the request.
            webView.LoadHtml("
Status: " + data.status + "
");
            webView.SetSize( 1, 0.6 );
            webView.Show();
            app.HideProgress();
        }
    }
}
<commit_msg>Spacing fixes and webView and html resets added.<commit_after>//Define the global variable(s).
var html = "";

//Called when application is started.
function OnStart()
{
    //Create the major components of the application.
    lay = app.CreateLayout( "linear", "VCenter,FillXY" );
    scroll = app.CreateScroller( );
    webView = app.CreateWebView( 1, 1, "IgnoreErrors,NoScrollBars", true );

    //Create the back and forward buttons.
    back = app.CreateButton( "Back" );
    back.SetOnTouch( back_OnTouch );
    forward = app.CreateButton ( "Forward" );
    forward.SetOnTouch( forward_OnTouch );

    //Create the toolbar.
    toolbar = app.CreateLayout( "linear", "horizontal" );
    toolbar.AddChild( back );
    toolbar.AddChild( forward );

    //Create tabs.
    tabs = app.CreateTabs( "RSS Select,Feed", 1, 1, "VCenter" );
    tabs.SetOnChange( tabs_OnChange );
    lay.AddChild( tabs );

    //Define the tab layouts.
    layRSS = tabs.GetLayout( "RSS Select" );
    layFeed = tabs.GetLayout( "Feed" );

    //Create an text edit box for url entry.
    edt = app.CreateTextEdit( "https://news.google.com/news/rss", 0.8 );
    edt.SetMargins( 0, 0.05, 0, 0 );
    layRSS.AddChild( edt );

    //Create a button to send request.
    read = app.CreateButton( "Read RSS Feed", 0.3, 0.1 );
    read.SetMargins( 0, 0.025, 0, 0.025 );
    read.SetOnTouch( read_OnTouch );
    layRSS.AddChild( read );

    //Add the scroller to the webView.
    scroll.AddChild ( webView );

    //Add the scroller and the back button to the feed.
    layFeed.AddChild( toolbar );
    layFeed.AddChild( scroll );

    //Add layout to app.
    app.AddLayout( lay );
}

//Handle tab selection.
function tabs_OnChange( name )
{
    app.ShowPopup( name );
}

//Handle read button press.
function read_OnTouch()
{
    //Send request to remote server.
    var url = edt.GetText();
    app.ShowProgress( "Loading..." );
    request(url);
    tabs.ShowTab( "Feed" );
}

//Handle back button press.
function back_OnTouch()
{   if(webView.CanGoBack)
    {
        webView.Back();
    }
}

//Handle forward button press.
function forward_OnTouch()
{
    if(webView.CanGoForward)
    {
        webView.Forward();
    }
}

//Handle requests.
function request(url)
{
    // Create the GET request and call process().
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() { process(xmlhttp) };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

// Test the data and pass an appropriate response to webView as HTML.
function process(data)
{
    if(data.readyState === 4)
    {
        if(data.status === 200)
        {
            //Reset the webView.
            webView.ClearHistory();
            webView.Hide();

            //Reset the html variable.
            html = "";

            //Gather the XML objects and information about the RSS.
            var rssInfo = data.responseXML.getElementsByTagName("rss");
            var feedInfo = data.responseXML.getElementsByTagName("feed");
            var xmlObjects = data.responseXML;

            //Test if the RSS is version 2.
            if(rssInfo.length > 0 && rssInfo.item(0) !== 'undefined' && rssInfo.item(0).getAttribute("version") === "2.0")
            {

                //Gather some more detailed information about the feed.
                var feedLength = xmlObjects.getElementsByTagName("item").length;
                var channelTitle = xmlObjects.getElementsByTagName("title").item(0).firstChild.data;
                var channelDescription = xmlObjects.getElementsByTagName("description").item(0).firstChild.data;

                //Add the title and description to the HTML.
                html = html
                    + "
"
                    + channelTitle
                    + "
"
                    + "
"
                    + channelDescription
                    + "
";

                //For each item in the feed, add a linked title and the description to the HTML.
                for (var i = 1; i < feedLength; i ++)
                {
                    var item = xmlObjects.getElementsByTagName("item").item(i);
                    html = html
                        + "
"
                        + item.getElementsByTagName("title").item(0).firstChild.data
                        + "

"
                        + item.getElementsByTagName("description").item(0).firstChild.data
                        + "
";
                }

                //Display the results.
                webView.LoadHtml(html);
                webView.SetSize( 1, 0.6 );
                webView.Show();
                app.HideProgress();
            }
			//Test if the RSS is Atom.
            else if(feedInfo.length > 0 && feedInfo.item(0) !== 'undefined' && feedInfo.item(0).getAttribute("xmlns") === "http://www.w3.org/2005/Atom")
            {
                //Gather the XML objects.
                var xmlObjects = data.responseXML;

                //Gather some information about the feed.
                var feedLength = xmlObjects.getElementsByTagName("entry").length;
                var channelTitle = xmlObjects.getElementsByTagName("title").item(0).firstChild.data;

                //Add the title to the HTML.
                html = html
                    + "
"
                    + channelTitle
                    + "
";

                //For each item in the feed, add a linked title and the description to the HTML.
                for (var i = 1; i < feedLength; i ++)
                {
                    var item = xmlObjects.getElementsByTagName("entry").item(i);
                    html = html
                        + "
"
                        + item.getElementsByTagName("title").item(0).firstChild.data
                        + "

"
                        + item.getElementsByTagName("content").item(0).firstChild.data
                        + "
";
                }

                //Display the results.
                webView.LoadHtml(html);
                webView.SetSize( 1, 0.6 );
                webView.Show();
                app.HideProgress();
            }
            else
            {
                //Tell the user that the RSS was not version 2.0.
                webView.LoadHtml("
RSS version incompatible.
"
                    + "
Please input a RSS Version 2.0 feed or an RSS Atom feed.
");
                webView.SetSize( 1, 0.6 );
                webView.Show();
                app.HideProgress();
            }
        }
        else
        {
            //Tell the user the status of the request.
            webView.LoadHtml("
Status: " + data.status + "
");
            webView.SetSize( 1, 0.6 );
            webView.Show();
            app.HideProgress();
        }
    }
}
<|endoftext|>