<commit_before>'use strict';

// Module dependencies.
var _ = require('lodash');
var defaultAssets = require('./config/assets/default');
var testAssets = require('./config/assets/test');

module.exports = function(grunt) {
  // Project Configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    env: {
      test: {
        NODE_ENV: 'test',
        src: 'codeaux.env.json'
      },
      dev: {
        NODE_ENV: 'development',
        src: 'codeaux.env.json'
      },
      prod: {
        NODE_ENV: 'production',
        src: 'codeaux.env.json'
      }
    },
    watch: {
      serverViews: {
        files: defaultAssets.server.views,
        options: {
          livereload: true
        }
      },
      serverJS: {
        files: defaultAssets.server.allJS,
        tasks: ['jshint', 'jscs'],
        options: {
          livereload: true
        }
      },
      clientViews: {
        files: defaultAssets.client.views,
        options: {
          livereload: true,
        }
      },
      clientJS: {
        files: defaultAssets.client.js,
        tasks: ['jshint', 'jscs'],
        options: {
          livereload: true
        }
      },
      clientCSS: {
        files: defaultAssets.client.css,
        tasks: ['csslint'],
        options: {
          livereload: true
        }
      },
      clientSCSS: {
        files: defaultAssets.client.sass,
        tasks: ['sass', 'csslint'],
        options: {
          livereload: true
        }
      },
      clientLESS: {
        files: defaultAssets.client.less,
        tasks: ['less', 'csslint'],
        options: {
          livereload: true
        }
      }
    },
    concurrent: {
      default: ['nodemon', 'watch'],
      debug: ['nodemon', 'watch', 'node-inspector'],
      options: {
        logConcurrentOutput: true,
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc',
      },
      all: {
        src: defaultAssets.client.css
      }
    },
    cssmin: {
      combine: {
        files: {
          'public/dist/application.min.css': defaultAssets.client.css
        }
      }
    },
    jscs: {
      all: {
        src: _.union(defaultAssets.server.allJS, defaultAssets.client.js,
                     testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e),
        options: {
          config: '.jscsrc',
          verbose: true
        }
      }
    },
    jshint: {
      all: {
        src: _.union(defaultAssets.server.allJS, defaultAssets.client.js,
                     testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e),
        options: {
          jshintrc: true,
          node: true,
          mocha: true,
          jasmine: true
        }
      }
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js'
      }
    },
    less: {
      dist: {
        files: [{
          expand: true,
          src: defaultAssets.client.less,
          ext: '.css',
          rename: function(base, src) {
            return src.replace('/less/', '/css/');
          }
        }]
      }
    },
    mochaTest: {
      src: testAssets.tests.server,
      options: {
        reporter: 'spec',
        require: 'server.js'
      }
    },
    ngAnnotate: {
      production: {
        files: {
          'public/dist/application.js': defaultAssets.client.js
        }
      }
    },
    nodemon: {
      dev: {
        script: 'server.js',
        options: {
          nodeArgs: ['--debug'],
          ext: 'js,html',
          watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
        }
      }
    },
    'node-inspector': {
      custom: {
        options: {
          'web-port': 1337,
          'web-host': 'localhost',
          'debug-port': 5858,
          'save-live-edit': true,
          'no-preload': true,
          'stack-trace-limit': 50,
          'hidden': []
        }
      }
    },
    protractor: {
      options: {
        configFile: 'protractor.conf.js',
        keepAlive: true,
        noColor: false
      },
      e2e: {
        options: {
          // Target specific arguments.
          args: {}
        }
      }
    },
    sass: {
      dist: {
        files: [{
          expand: true,
          src: defaultAssets.client.sass,
          ext: '.css',
          rename: function(base, src) {
            return src.replace('/scss/', '/css/');
          }
        }]
      }
    },
    uglify: {
      production: {
        options: {
          mangle: false
        },
        files: {
          'public/dist/application.min.js': 'public/dist/application.js'
        }
      }
    }
  });

  // Load NPM tasks
  require('load-grunt-tasks')(grunt);
  // Making grunt default to force in order not to break the project.
  grunt.option('force', true);

  // A Task for loading the configuration object
  grunt.task.registerTask('mongoose', 'Connects to MongoDB instance and loads the application models.', function() {
    // Get callback.
    var callback = this.async();

    // Use mongoose configuration to connect to mongo database.
    var mongoose = require('./config/lib/mongoose.js');
    mongoose.connect(function() {
      callback();
    });
  });

  // Lint CSS and JavaScript files.
  grunt.registerTask('lint', ['sass', 'less', 'jshint', 'csslint', 'jscs']);

  // Build application files and minify them into two production files.
  grunt.registerTask('build', ['env:dev', 'lint', 'ngAnnotate', 'uglify', 'cssmin']);

  // Run application in testing stage.
  grunt.registerTask('test', ['env:test', 'mongoose', 'mochaTest', 'karma:unit']);
  grunt.registerTask('test:server', ['env:test', 'mongoose', 'mochaTest']);
  grunt.registerTask('test:client', ['env:test', 'mongoose', 'karma:unit']);

  // Run application in development stage.
  grunt.registerTask('default', ['env:dev', 'lint', 'concurrent:default']);

  // Run application in debug stage.
  grunt.registerTask('debug', ['env:dev', 'lint', 'concurrent:debug']);

  // Run application in production stage.
  grunt.registerTask('heroku', ['build', 'env:prod', 'concurrent:default']);

  grunt.registerTask('heroku:production', ['build']);
};
<commit_msg>heroku fix.<commit_after>'use strict';

// Module dependencies.
var _ = require('lodash');
var defaultAssets = require('./config/assets/default');
var testAssets = require('./config/assets/test');

module.exports = function(grunt) {
  // Project Configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    env: {
      test: {
        NODE_ENV: 'test',
        src: 'codeaux.env.json'
      },
      dev: {
        NODE_ENV: 'development',
        src: 'codeaux.env.json'
      },
      prod: {
        NODE_ENV: 'production',
        src: 'codeaux.env.json'
      }
    },
    watch: {
      serverViews: {
        files: defaultAssets.server.views,
        options: {
          livereload: true
        }
      },
      serverJS: {
        files: defaultAssets.server.allJS,
        tasks: ['jshint', 'jscs'],
        options: {
          livereload: true
        }
      },
      clientViews: {
        files: defaultAssets.client.views,
        options: {
          livereload: true,
        }
      },
      clientJS: {
        files: defaultAssets.client.js,
        tasks: ['jshint', 'jscs'],
        options: {
          livereload: true
        }
      },
      clientCSS: {
        files: defaultAssets.client.css,
        tasks: ['csslint'],
        options: {
          livereload: true
        }
      },
      clientSCSS: {
        files: defaultAssets.client.sass,
        tasks: ['sass', 'csslint'],
        options: {
          livereload: true
        }
      },
      clientLESS: {
        files: defaultAssets.client.less,
        tasks: ['less', 'csslint'],
        options: {
          livereload: true
        }
      }
    },
    concurrent: {
      default: ['nodemon', 'watch'],
      debug: ['nodemon', 'watch', 'node-inspector'],
      options: {
        logConcurrentOutput: true,
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc',
      },
      all: {
        src: defaultAssets.client.css
      }
    },
    cssmin: {
      combine: {
        files: {
          'public/dist/application.min.css': defaultAssets.client.css
        }
      }
    },
    jscs: {
      all: {
        src: _.union(defaultAssets.server.allJS, defaultAssets.client.js,
                     testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e),
        options: {
          config: '.jscsrc',
          verbose: true
        }
      }
    },
    jshint: {
      all: {
        src: _.union(defaultAssets.server.allJS, defaultAssets.client.js,
                     testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e),
        options: {
          jshintrc: true,
          node: true,
          mocha: true,
          jasmine: true
        }
      }
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js'
      }
    },
    less: {
      dist: {
        files: [{
          expand: true,
          src: defaultAssets.client.less,
          ext: '.css',
          rename: function(base, src) {
            return src.replace('/less/', '/css/');
          }
        }]
      }
    },
    mochaTest: {
      src: testAssets.tests.server,
      options: {
        reporter: 'spec',
        require: 'server.js'
      }
    },
    ngAnnotate: {
      production: {
        files: {
          'public/dist/application.js': defaultAssets.client.js
        }
      }
    },
    nodemon: {
      dev: {
        script: 'server.js',
        options: {
          nodeArgs: ['--debug'],
          ext: 'js,html',
          watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
        }
      }
    },
    'node-inspector': {
      custom: {
        options: {
          'web-port': 1337,
          'web-host': 'localhost',
          'debug-port': 5858,
          'save-live-edit': true,
          'no-preload': true,
          'stack-trace-limit': 50,
          'hidden': []
        }
      }
    },
    protractor: {
      options: {
        configFile: 'protractor.conf.js',
        keepAlive: true,
        noColor: false
      },
      e2e: {
        options: {
          // Target specific arguments.
          args: {}
        }
      }
    },
    sass: {
      dist: {
        files: [{
          expand: true,
          src: defaultAssets.client.sass,
          ext: '.css',
          rename: function(base, src) {
            return src.replace('/scss/', '/css/');
          }
        }]
      }
    },
    uglify: {
      production: {
        options: {
          mangle: false
        },
        files: {
          'public/dist/application.min.js': 'public/dist/application.js'
        }
      }
    }
  });

  // Load NPM tasks
  require('load-grunt-tasks')(grunt);
  // Making grunt default to force in order not to break the project.
  grunt.option('force', true);

  // A Task for loading the configuration object
  grunt.task.registerTask('mongoose', 'Connects to MongoDB instance and loads the application models.', function() {
    // Get callback.
    var callback = this.async();

    // Use mongoose configuration to connect to mongo database.
    var mongoose = require('./config/lib/mongoose.js');
    mongoose.connect(function() {
      callback();
    });
  });

  // Lint CSS and JavaScript files.
  grunt.registerTask('lint', ['sass', 'less', 'jshint', 'csslint', 'jscs']);

  // Build application files and minify them into two production files.
  grunt.registerTask('build', ['env:dev', 'lint', 'ngAnnotate', 'uglify', 'cssmin']);

  // Run application in testing stage.
  grunt.registerTask('test', ['env:test', 'mongoose', 'mochaTest', 'karma:unit']);
  grunt.registerTask('test:server', ['env:test', 'mongoose', 'mochaTest']);
  grunt.registerTask('test:client', ['env:test', 'mongoose', 'karma:unit']);

  // Run application in development stage.
  grunt.registerTask('default', ['env:dev', 'lint', 'concurrent:default']);

  // Run application in debug stage.
  grunt.registerTask('debug', ['env:dev', 'lint', 'concurrent:debug']);

  // Run application in production stage.
  grunt.registerTask('prod', ['build', 'env:prod', 'concurrent:default']);

  grunt.registerTask('heroku:production', ['build']);
};
<|endoftext|>


<commit_before>/*
[============================== AUTOMATIC RELEASE NOTES ==============================]
|                                                                                |
| When starting grunt release dont update the version of the root package.json        |
| This file is used for automatic updates.                                            |
|                                                                                |
| Edit if after releasing - only update the src/package.json and start your release   |
| process.                                                                            |
|                                                                                |
| Grunt will open the necessary Websites for editing the root package.json and making |
| your releasetag.                                                                    |
|                                                                                |
[=====================================================================================]
*/

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        srcpkg: grunt.file.readJSON('src/package.json'),

        shell: {
            npmInstall: {
                command: 'cd src && npm install'
            },

            devInstall: {
                command: 'mv nwjs-v0.12.0-win-x64 nw && copy cfg\\package.json nw\\package.json && cd nw & npm install'
            },

            devInstallTux32: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-ia32 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            devInstallTux64: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-x64 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            askPackage: {
                command: 'echo "Did you update your src/package.json (v<%= srcpkg.version %>) and are on the Master Branch ?" && pause'
            },

            gitCommit: {
                command: 'git commit -a -m "Release Version <%= srcpkg.version %>"'
            },

            gitTag: {
                command: 'git tag v<%= srcpkg.version %>'
            },

            gitPush: {
                command: 'echo "Press a Key for pushing to github" && pause && git push'
            },

            purgeBuilds: {
                command: 'rm -rf build/SSGL && rm -rf build/RELEASE && rm -rf build/pre'
            }
        },

        open: {
            newRelease: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/releases/new',
            },

            editPackage: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/edit/master/package.json'
            }
        },

        nwjs: {
            win: {
                options: {
                    platforms: ['win'],
                    buildDir: './build',
                    version: 'v0.12.0',
                    winIco: './icons/ssgl1.ico'
                },
                src: ['./build/pre/**/**']
            },

            tux: {
                options: {
                    platforms: ['linux'],
                    buildDir: './build',
                    version: 'v0.12.0'
                },
                src: ['./build/pre/**/**']
            },

            mac: {
                options: {
                    platforms: ['osx64'],
                    buildDir: './build',
                    version: 'v0.12.0',
                    macIcns: './icons/ssgl.icns'
                },
                src: ['./build/pre/**/**']
            }
        },

        curl: {

            mac64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-osx-x64.zip',
                dest: './cache/nwdev.zip'

            },

            win64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-win-x64.zip',
                dest: './cache/nwdev.zip'
            },

            nwdevTux32: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-ia32.tar.gz',
                dest: './cache/nwdev.tar.gz'
            },

            nwdevTux64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-x64.tar.gz',
                dest: './cache/nwdev.tar.gz'
            }
        },

        unzip: {
            nwdev: {
                src: './cache/nwdev.zip',
                dest: './'
            }
        },

        compress: {
            tux32: {
                options: {
                    archive: './build/RELEASE/linux32.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux32/'
                }]
            },

            tux64: {
                options: {
                    archive: './build/RELEASE/linux64.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux64/'
                }]
            },

            win32: {
                options: {
                    archive: './build/RELEASE/win32.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win32/'
                }]
            },

            win64: {
                options: {
                    archive: './build/RELEASE/win64.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win64/'
                }]
            }
        },

        concat: {
            options: {
                separator: '\n\n',
                stripBanners: true,
            },

            dist: {
                src: ['src/app/_mixins.js',
                      'src/app/main.js',
                      'src/app/templates.js',
                      'src/app/controllers/*.js',
                      'src/app/directives/*.js',
                      'src/app/services/**.js'
                ],
                dest: 'build/pre/app.js',
            }
        },

        uglify: {
            options: {
                mangle: false
            },

            build: {
                files: {
                    'build/pre/app.js': ['build/pre/app.js']
                }
            }
        },

        ngtemplates: {
            app: {
                cwd: 'src/',
                src: 'app/templates/*.html',
                dest: 'src/app/templates.js',
                options: {
                    htmlmin: {
                        collapseWhitespace: true,
                        collapseBooleanAttributes: true
                    },

                    bootstrap: function(module, script) {
                        return "app.run(['$templateCache', function($templateCache) {" + "\n" + script + '}]);';
                    }
                }
            }
        },

        copy: {
            main: {
                src: ['index.html', 'package.json', 'node_modules/**', 'app/assets/**', 'app/font/**', 'app/lib/**'],
                cwd: 'src/',
                dest: 'build/pre',
                expand: true
            }
        },

        yuidoc: {
            compile: {
                name: 'Super Shotgun Launcher',
                version: '<%= pkg.version %>',
                url: '<%= pkg.homepage %>',
                options: {
                    paths: './src/app',
                    outdir: './docs',
                    exclude: 'lib'
                }
            }
        }

    });

    // Plugins

    grunt.loadNpmTasks('grunt-nw-builder');
    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-curl');
    grunt.loadNpmTasks('grunt-zip');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-open');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-angular-templates');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('build-js', ['ngtemplates', 'concat', 'uglify', 'copy']);

    grunt.registerTask('build-win', ['build-js', 'nwjs:win']);
    grunt.registerTask('build-linux', ['build-js', 'nwjs:tux']);
    grunt.registerTask('build-mac', ['build-js', 'nwjs:mac']);

    grunt.registerTask('init', ['shell:npmInstall']);

    grunt.registerTask('build-devenv-win', ['curl:win64', 'unzip', 'shell:devInstall']);
    grunt.registerTask('build-devenv-mac', ['curl:mac64', 'unzip', 'shell:devInstall']);

    grunt.registerTask('build-devenv-linux32', ['curl:nwdevTux32', 'shell:devInstallTux32']);
    grunt.registerTask('build-devenv-linux64', ['curl:nwdevTux64', 'shell:devInstallTux64']);

    grunt.registerTask('release', [
        'shell:askPackage',
        'shell:purgeBuilds',
        'build-js',
        'nwjs',
        'compress',
        'shell:gitCommit',
        'open:editPackage',
        'open:newRelease'
    ]);

};<commit_msg>Add devcommands<commit_after>/*
[============================== AUTOMATIC RELEASE NOTES ==============================]
|                                                                                |
| When starting grunt release dont update the version of the root package.json        |
| This file is used for automatic updates.                                            |
|                                                                                |
| Edit if after releasing - only update the src/package.json and start your release   |
| process.                                                                            |
|                                                                                |
| Grunt will open the necessary Websites for editing the root package.json and making |
| your releasetag.                                                                    |
|                                                                                |
[=====================================================================================]
*/

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        srcpkg: grunt.file.readJSON('src/package.json'),

        shell: {
            npmInstall: {
                command: 'cd src && npm install'
            },

            devInstall: {
                command: 'mv nwjs-v0.12.0-win-x64 nw && copy cfg\\package.json nw\\package.json && cd nw & npm install'
            },

            devInstallMac64: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-osx-x64 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            devInstallTux32: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-ia32 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            devInstallTux64: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-x64 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            askPackage: {
                command: 'echo "Did you update your src/package.json (v<%= srcpkg.version %>) and are on the Master Branch ?" && pause'
            },

            gitCommit: {
                command: 'git commit -a -m "Release Version <%= srcpkg.version %>"'
            },

            gitTag: {
                command: 'git tag v<%= srcpkg.version %>'
            },

            gitPush: {
                command: 'echo "Press a Key for pushing to github" && pause && git push'
            },

            purgeBuilds: {
                command: 'rm -rf build/SSGL && rm -rf build/RELEASE && rm -rf build/pre'
            }
        },

        open: {
            newRelease: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/releases/new',
            },

            editPackage: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/edit/master/package.json'
            }
        },

        nwjs: {
            win: {
                options: {
                    platforms: ['win'],
                    buildDir: './build',
                    version: 'v0.12.0',
                    winIco: './icons/ssgl1.ico'
                },
                src: ['./build/pre/**/**']
            },

            tux: {
                options: {
                    platforms: ['linux'],
                    buildDir: './build',
                    version: 'v0.12.0'
                },
                src: ['./build/pre/**/**']
            },

            mac: {
                options: {
                    platforms: ['osx64'],
                    buildDir: './build',
                    version: 'v0.12.0',
                    macIcns: './icons/ssgl.icns'
                },
                src: ['./build/pre/**/**']
            }
        },

        curl: {

            mac64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-osx-x64.zip',
                dest: './cache/nwdev.zip'
            },

            win64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-win-x64.zip',
                dest: './cache/nwdev.zip'
            },

            nwdevTux32: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-ia32.tar.gz',
                dest: './cache/nwdev.tar.gz'
            },

            nwdevTux64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-x64.tar.gz',
                dest: './cache/nwdev.tar.gz'
            }
        },

        unzip: {
            nwdev: {
                src: './cache/nwdev.zip',
                dest: './'
            }
        },

        compress: {
            tux32: {
                options: {
                    archive: './build/RELEASE/linux32.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux32/'
                }]
            },

            tux64: {
                options: {
                    archive: './build/RELEASE/linux64.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux64/'
                }]
            },
            mac64: {

            },

            win32: {
                options: {
                    archive: './build/RELEASE/win32.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win32/'
                }]
            },

            win64: {
                options: {
                    archive: './build/RELEASE/win64.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win64/'
                }]
            }
        },

        concat: {
            options: {
                separator: '\n\n',
                stripBanners: true,
            },

            dist: {
                src: ['src/app/_mixins.js',
                      'src/app/main.js',
                      'src/app/templates.js',
                      'src/app/controllers/*.js',
                      'src/app/directives/*.js',
                      'src/app/services/**.js'
                ],
                dest: 'build/pre/app.js',
            }
        },

        uglify: {
            options: {
                mangle: false
            },

            build: {
                files: {
                    'build/pre/app.js': ['build/pre/app.js']
                }
            }
        },

        ngtemplates: {
            app: {
                cwd: 'src/',
                src: 'app/templates/*.html',
                dest: 'src/app/templates.js',
                options: {
                    htmlmin: {
                        collapseWhitespace: true,
                        collapseBooleanAttributes: true
                    },

                    bootstrap: function(module, script) {
                        return "app.run(['$templateCache', function($templateCache) {" + "\n" + script + '}]);';
                    }
                }
            }
        },

        copy: {
            main: {
                src: ['index.html', 'package.json', 'node_modules/**', 'app/assets/**', 'app/font/**', 'app/lib/**'],
                cwd: 'src/',
                dest: 'build/pre',
                expand: true
            }
        },

        yuidoc: {
            compile: {
                name: 'Super Shotgun Launcher',
                version: '<%= pkg.version %>',
                url: '<%= pkg.homepage %>',
                options: {
                    paths: './src/app',
                    outdir: './docs',
                    exclude: 'lib'
                }
            }
        }

    });

    // Plugins

    grunt.loadNpmTasks('grunt-nw-builder');
    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-curl');
    grunt.loadNpmTasks('grunt-zip');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-open');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-angular-templates');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('build-js', ['ngtemplates', 'concat', 'uglify', 'copy']);

    grunt.registerTask('build-win', ['build-js', 'nwjs:win']);
    grunt.registerTask('build-linux', ['build-js', 'nwjs:tux']);
    grunt.registerTask('build-mac', ['build-js', 'nwjs:mac']);

    grunt.registerTask('init', ['shell:npmInstall']);

    grunt.registerTask('build-devenv-win', ['curl:win64', 'unzip', 'shell:devInstall']);
    grunt.registerTask('build-devenv-mac', ['curl:mac64', 'unzip', 'shell:devInstallMac64']);

    grunt.registerTask('build-devenv-linux32', ['curl:nwdevTux32', 'shell:devInstallTux32']);
    grunt.registerTask('build-devenv-linux64', ['curl:nwdevTux64', 'shell:devInstallTux64']);

    grunt.registerTask('release', [
        'shell:askPackage',
        'shell:purgeBuilds',
        'build-js',
        'nwjs',
        'compress',
        'shell:gitCommit',
        'open:editPackage',
        'open:newRelease'
    ]);

};<|endoftext|>


<commit_before><commit_msg>Add loader for ENV based AppId<commit_after><|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

  // Unified Watch Object
  var watchFiles = {
    //serverViews: ['app/views/**/*.*'],
    serverJS: ['gruntfile.js', 'server.js', 'app/**/*.js', 'config/**/*.js'],
    nodeFiles: ['server.js', 'app/**/*.js'],
    mochaTests: ['./app/tests/_globals.js','app/tests/integration/**/*.js', 'app/tests/unit/**/*.js']
  };

  // Project Configuration
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    meta:{
      reports: '.reports',
      files: watchFiles
    },
    watch: {
      serverJS: {
        files: watchFiles.serverJS,
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      },
    },
    jshint: {
      all: {
        src: watchFiles.serverJS,
        options: {
          jshintrc: true
        }
      }
    },
    nodemon: {
      dev: {
        script: 'server.js',
        options: {
          nodeArgs: ['--debug'],
          ext: 'js,html',
          watch:watchFiles.serverJS
        }
      }
    },
    'node-inspector': {
      custom: {
        options: {
          'web-port': 1337,
          'web-host': 'localhost',
          'debug-port': 5858,
          'save-live-edit': true,
          'no-preload': true,
          'stack-trace-limit': 50,
          'hidden': []
        }
      }
    },
    concurrent: {
      default: ['nodemon', 'watch'],
      debug: ['nodemon', 'watch', 'node-inspector'],
      docs: ['doxx:shell', 'plato'],
      test: ['test:server'],
      options: {
        logConcurrentOutput: true,
        limit: 6
      }
    },
    env: {
      test: {
        NODE_ENV: 'test'
      },
      dev: {
        NODE_ENV: 'development',
        COVERAGE: 'true'
      },
      localdev: {
        NODE_ENV: 'development',
        PORT: 4000
      }
    },
    clean: {
      docs: ['<%= meta.reports %>/docs'],
      coverage: ['<%= meta.reports %>/coverage'],
      istanbul:['<%= meta.reports %>/coverage/server/app', '<%= meta.reports %>/coverage/server/server.js']
    },
    plato: {
      server: {
        options:{
          jshint : grunt.file.readJSON('.jshintrc'),
          exclude: /app\/tests/,
        },
        files: {
          '<%= meta.reports %>/plato/server': ['server.js', 'app/**/*.js']
        }
      }
    },
    bump: {
      options: {
        files: ['package.json'],
        updateConfigs: [],
        commit: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json', 'CHANGELOG.md', 'gruntfile.js'],
        createTag: true,
        tagName: 'v%VERSION%',
        tagMessage: 'Version %VERSION%',
        push: true,
        pushTo: '<%= pkg.repository.url %>',
        gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
        globalReplace: false
      }
    },
    changelog:{
      options: {
        // Task-specific options go here.
      }
    }
  });

  // Load NPM tasks
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);
  require('./config/grunt/customTasks')(grunt);

  // Making grunt default to force in order not to break the project.
  //grunt.option('force', true);

  // Default task(s).
  grunt.registerTask('default', ['lint', 'concurrent:default']);
  grunt.registerTask('serve', ['env:localdev', 'lint', 'concurrent:default']);

  // Debug task.
  grunt.registerTask('debug', ['lint', 'concurrent:debug']);

  // Lint task(s).
  grunt.registerTask('lint', ['jshint']);

  // Test task.
  grunt.registerTask('test', ['setTestEnvVars','clean:coverage', 'lint', 'test:server']);
  grunt.registerTask('test:server', ['istanbul:mocha:cover', 'clean:istanbul']);

  grunt.registerTask('docs', ['clean:docs', 'concurrent:docs' ]);

  //release
  grunt.registerTask('pre-release', ['changelog', 'bump:prerelease']);
  grunt.registerTask('patch-release', ['changelog', 'bump']);
  grunt.registerTask('minor-release', ['changelog', 'bump:minor']);
  grunt.registerTask('major-release', ['changelog', 'bump:major']);

};
<commit_msg>remove livereload from watch task<commit_after>'use strict';

module.exports = function(grunt) {

  // Unified Watch Object
  var watchFiles = {
    //serverViews: ['app/views/**/*.*'],
    serverJS: ['gruntfile.js', 'server.js', 'app/**/*.js', 'config/**/*.js'],
    nodeFiles: ['server.js', 'app/**/*.js'],
    mochaTests: ['./app/tests/_globals.js','app/tests/integration/**/*.js', 'app/tests/unit/**/*.js']
  };

  // Project Configuration
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    meta:{
      reports: '.reports',
      files: watchFiles
    },
    watch: {
      serverJS: {
        files: watchFiles.serverJS,
        tasks: ['jshint']
      },
    },
    jshint: {
      all: {
        src: watchFiles.serverJS,
        options: {
          jshintrc: true
        }
      }
    },
    nodemon: {
      dev: {
        script: 'server.js',
        options: {
          nodeArgs: ['--debug'],
          ext: 'js,html',
          watch:watchFiles.serverJS
        }
      }
    },
    'node-inspector': {
      custom: {
        options: {
          'web-port': 1337,
          'web-host': 'localhost',
          'debug-port': 5858,
          'save-live-edit': true,
          'no-preload': true,
          'stack-trace-limit': 50,
          'hidden': []
        }
      }
    },
    concurrent: {
      default: ['nodemon', 'watch'],
      debug: ['nodemon', 'watch', 'node-inspector'],
      docs: ['doxx:shell', 'plato'],
      test: ['test:server'],
      options: {
        logConcurrentOutput: true,
        limit: 6
      }
    },
    env: {
      test: {
        NODE_ENV: 'test'
      },
      dev: {
        NODE_ENV: 'development',
        COVERAGE: 'true'
      },
      localdev: {
        NODE_ENV: 'development',
        PORT: 4000
      }
    },
    clean: {
      docs: ['<%= meta.reports %>/docs'],
      coverage: ['<%= meta.reports %>/coverage'],
      istanbul:['<%= meta.reports %>/coverage/server/app', '<%= meta.reports %>/coverage/server/server.js']
    },
    plato: {
      server: {
        options:{
          jshint : grunt.file.readJSON('.jshintrc'),
          exclude: /app\/tests/,
        },
        files: {
          '<%= meta.reports %>/plato/server': ['server.js', 'app/**/*.js']
        }
      }
    },
    bump: {
      options: {
        files: ['package.json'],
        updateConfigs: [],
        commit: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json', 'CHANGELOG.md', 'gruntfile.js'],
        createTag: true,
        tagName: 'v%VERSION%',
        tagMessage: 'Version %VERSION%',
        push: true,
        pushTo: '<%= pkg.repository.url %>',
        gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
        globalReplace: false
      }
    },
    changelog:{
      options: {
        // Task-specific options go here.
      }
    }
  });

  // Load NPM tasks
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);
  require('./config/grunt/customTasks')(grunt);

  // Making grunt default to force in order not to break the project.
  //grunt.option('force', true);

  // Default task(s).
  grunt.registerTask('default', ['lint', 'concurrent:default']);
  grunt.registerTask('serve', ['env:localdev', 'lint', 'concurrent:default']);

  // Debug task.
  grunt.registerTask('debug', ['lint', 'concurrent:debug']);

  // Lint task(s).
  grunt.registerTask('lint', ['jshint']);

  // Test task.
  grunt.registerTask('test', ['setTestEnvVars','clean:coverage', 'lint', 'test:server']);
  grunt.registerTask('test:server', ['istanbul:mocha:cover', 'clean:istanbul']);

  grunt.registerTask('docs', ['clean:docs', 'concurrent:docs' ]);

  //release
  grunt.registerTask('pre-release', ['changelog', 'bump:prerelease']);
  grunt.registerTask('patch-release', ['changelog', 'bump']);
  grunt.registerTask('minor-release', ['changelog', 'bump:minor']);
  grunt.registerTask('major-release', ['changelog', 'bump:major']);

};
<|endoftext|>


<commit_before>/*
 @author Raoul Harel
 @license The MIT license (LICENSE.txt)
 @copyright 2015 Raoul Harel
 @url rharel/node-gol-hashlife on GitHub
*/

module.exports = function(grunt) {

  config = {
    pkg: grunt.file.readJSON('package.json'),
    lib_dir: 'lib/',
    test_dir: 'test/',
    dist_dir: 'dist/',
    source_files: [ '<%= lib_dir %>**/*.js' ],
    test_files: '<%= test_dir %>**/*.test.js',

    jshint: {
      all: '<%= lib_dir %>**/*.js'
    },

    clean: {
      release: {
        src: [
          '<%= dist_dir %>**/*.js'
        ]
      }
    },

    mochacli: {
      options: {
        require: ['chai'],
        reporter: 'spec',
        bail: true
      },
      all: '<%= test_dir %>/*.test.js'
    },

    uglify: {
      release: {
        files: {
          '<%= dist_dir %>/bezier.min.js': ['<%= lib_dir %>/bezier.js']
        }
      }
    }
  };

  grunt.registerTask('build', [
    'clean:release',
    'uglify:release'
  ]);
  grunt.registerTask('test', ['mochacli:all']);
  grunt.registerTask('dev', [
    'jshint:all',
    'test'
  ]);
  grunt.registerTask('release', [
    'jshint:all',
    'test',
    'clean:release',
    'uglify:release'
  ]);
  grunt.registerTask('default', 'dev');

  require('load-grunt-tasks')(grunt);

  return grunt.initConfig(config);
};<commit_msg>Fixed github url<commit_after>/**
 * @author Raoul Harel
 * @license The MIT license (LICENSE.txt)
 * @copyright 2015 Raoul Harel
 * @url https://github.com/rharel/node-mutable-bezier
 */

module.exports = function(grunt) {

  config = {
    pkg: grunt.file.readJSON('package.json'),
    lib_dir: 'lib/',
    test_dir: 'test/',
    dist_dir: 'dist/',
    source_files: [ '<%= lib_dir %>**/*.js' ],
    test_files: '<%= test_dir %>**/*.test.js',

    jshint: {
      all: '<%= lib_dir %>**/*.js'
    },

    clean: {
      release: {
        src: [
          '<%= dist_dir %>**/*.js'
        ]
      }
    },

    mochacli: {
      options: {
        require: ['chai'],
        reporter: 'spec',
        bail: true
      },
      all: '<%= test_dir %>/*.test.js'
    },

    uglify: {
      release: {
        files: {
          '<%= dist_dir %>/bezier.min.js': ['<%= lib_dir %>/bezier.js']
        }
      }
    }
  };

  grunt.registerTask('build', [
    'clean:release',
    'uglify:release'
  ]);
  grunt.registerTask('test', ['mochacli:all']);
  grunt.registerTask('dev', [
    'jshint:all',
    'test'
  ]);
  grunt.registerTask('release', [
    'jshint:all',
    'test',
    'clean:release',
    'uglify:release'
  ]);
  grunt.registerTask('default', 'dev');

  require('load-grunt-tasks')(grunt);

  return grunt.initConfig(config);
};<|endoftext|>


<commit_before>module.exports = function (grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		jshint: {
			options: {
				camelcase: false,
				indent: 4,
				curly: true,
				eqeqeq: true,
				immed: true,
				latedef: true,
				newcap: true,
				noarg: true,
				quotmark: true,
				sub: true,
				boss: true,
				eqnull: true,
				white: true
			},
			all: ['./gruntfile.js', './src/js/**/*.js']
		},
		/*
		// Needs revision, as does _SpecRunner.html
		jasmine: {
			default: {
				src: './src/js/*.js',
				options: {
					keepRunner: true,
					hostname: '127.0.0.1',
					port: 8003,
					specs: './src/js/spec/*spec.js',
					template: require('grunt-template-jasmine-requirejs'),
					templateOptions: {
						requireConfig: {
							paths: {
								'jquery' : './src/js_test_helpers/jquery-1.7.2',
								'main'	 : './src/js/main'
							}
						}
					}
				}
			}
		},
		connect: {
			desktop: {
				options: {
					hostname: '127.0.0.1',
					keepalive: true,
					port: 8003,
					base: '/../'
				}
			}
		},
		*/
		nwjs: {
			options: {
				// 'win', 'osx', 'linux', etc. See https://github.com/nwjs/nw-builder#manifest-options
				platforms: ['win32'],
				buildDir: './bin',
				version: 'v0.12.3' // Current stable release, 0.13.0 (beta 5 as of 2016-02-09) fails on ffmpegsumo.dll
			},
			src: ['./src/**']
		},
		shell: {
			npm: {
				options: {
					execOptions: {
						cwd: './src'
					}
				},
				command: 'npm install'
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-jasmine');
	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-nw-builder');
	grunt.loadNpmTasks('grunt-shell');

	grunt.registerTask('default', ['shell:npm', 'test', 'build']);
	grunt.registerTask('test',	['jshint']); // HTML Validator, Jasmine, etc. to be added
	grunt.registerTask('build',	['nwjs']);

};
<commit_msg>Notes for later<commit_after>module.exports = function (grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		jshint: {
			options: {
				camelcase: false,
				indent: 4,
				curly: true,
				eqeqeq: true,
				immed: true,
				latedef: true,
				newcap: true,
				noarg: true,
				quotmark: true,
				sub: true,
				boss: true,
				eqnull: true,
				white: true
			},
			all: ['./gruntfile.js', './src/js/**/*.js']
		},
		/*
		// Needs revision, as does _SpecRunner.html
		jasmine: {
			default: {
				src: './src/js/*.js',
				options: {
					keepRunner: true,
					hostname: '127.0.0.1',
					port: 8003,
					specs: './src/js/spec/*spec.js',
					template: require('grunt-template-jasmine-requirejs'),
					templateOptions: {
						requireConfig: {
							paths: {
								'jquery' : './src/js_test_helpers/jquery-1.7.2',
								'main'	 : './src/js/main'
							}
						}
					}
				}
			}
		},
		connect: {
			desktop: {
				options: {
					hostname: '127.0.0.1',
					keepalive: true,
					port: 8003,
					base: '/../'
				}
			}
		},
		*/
		nwjs: {
			options: {
				// 'win', 'osx', 'linux', etc. See https://github.com/nwjs/nw-builder#manifest-options
				platforms: ['win32'],
				buildDir: './bin',
				// winIco
				// macIcns
				version: 'v0.12.3' // Current stable release, 0.13.0 (beta 5 as of 2016-02-09) fails on ffmpegsumo.dll
			},
			src: ['./src/**']
		},
		shell: {
			npm: {
				options: {
					execOptions: {
						cwd: './src'
					}
				},
				command: 'npm install'
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-jasmine');
	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-nw-builder');
	grunt.loadNpmTasks('grunt-shell');

	grunt.registerTask('default', ['shell:npm', 'test', 'build']);
	grunt.registerTask('test',	['jshint']); // HTML Validator, Jasmine, etc. to be added
	grunt.registerTask('build',	['nwjs']);

};
<|endoftext|>


<commit_before>// http://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr
function makeRequest (method, url) {
	return new Promise(function (resolve, reject) {
		var xhr = new XMLHttpRequest();
		xhr.open(method, url);
		xhr.onload = function () {
			if (this.status >= 200 && this.status < 300) {
				resolve({
					respone: xhr.response,
					pageCount: xhr.getResponseHeader("X-Page-Total")
				});
			} else {
				reject({
					status: this.status,
					statusText: xhr.statusText
				});
			}
		};
		xhr.onerror = function () {
			reject({
				status: this.status,
				statusText: xhr.statusText
			});
		};
		xhr.send();
	});
}
// http://stackoverflow.com/questions/8034918/jquery-switch-elements-in-dom
function swapElements(elm1, elm2) {
    var parent1, next1,
        parent2, next2;

    parent1 = elm1.parentNode;
    next1   = elm1.nextSibling;
    parent2 = elm2.parentNode;
    next2   = elm2.nextSibling;

    parent1.insertBefore(elm2, next1);
    parent2.insertBefore(elm1, next2);
}

// My code.
// String constants for constructing GW API requests.
var gwUrlBase = "https://api.guildwars2.com/v2/";
var gwUrlPrices = "commerce/prices";
var gwUrlItems = "items"
var gwUrlIds = "?ids="
var gwUrlPaging = "?page_size=200&page=";

// Current index of priceSpread item.
var pS=0;
// Entry to AJAX code.
$(document).ready(function(){
	// Fetch GW Price data and display two greatest spreads.
	getPrices(displayGreatestSpread);

	// Allow navigation of prices.
	$(".stack.next").on("click",function(){
		$(".stack.current").fadeOut();
		$(this).css("z-index", "1");
		$(this).animate({
			left: '0',
			bottom: $(".stack.current").innerHeight()
		}, stackForwardReset);
	});
	$(".stack.current").on("click",function(){
		$(".stack.next").fadeOut();
		var targetHeight = (60 - $(".stack.next").innerHeight()) + "px";
		$(this).animate({
			left: '75px',
			bottom: targetHeight
		}, stackBackwardReset);
	});
});

function stackForwardReset() {
	$('.stack.current').html($('.stack.next').html());
	$('.stack.current').show();
	$('.stack.next').hide();
	$('.stack.next').css("z-index", '');
	$('.stack.next').css("left", '');
	$('.stack.next').css("bottom", '');
	pS++;
	setSpreadFilters(pS);
}
function stackBackwardReset() {
	$('.stack.next').html($('.stack.current').html());
	$('.stack.next').show();
	$('.stack.current').css("opacity", '.01');
	$('.stack.current').css("left", '');
	$('.stack.current').css("bottom", '');
	pS--;
	setSpreadFilters(pS);
}

//
function displayGreatestSpread(priceSpread) {
  priceSpread = priceSpread.filter(function(currentValue) {
  	return ((currentValue.buys.quantity !== 0) && (currentValue.sells.quantity !== 0));
  });
  priceSpread.forEach(calculateSpread);
  priceSpread.sort(comparePrices);
  getItem(priceSpread[0].id, function(item) {
	  displayItem(item, "#current-item", priceSpread[0]);
  });
  getItem(priceSpread[1].id, function(item) {
	  displayItem(item, "#next-item", priceSpread[1]);
  });
}

function displayItem(item, boxId, tpData) {
  $(boxId + " .item-name").text(item.name);
  $(boxId + " .item-icon").attr("src", item.icon);
  $(boxId + " .item-icon").attr("alt", item.name + "'s Icon");
  if (tpData !== undefined) {
	$(boxId + " .buy-price").text(tpData.buys.unit_price);
	$(boxId + " .sell-price").text(tpData.sells.unit_price);
  }
}

var getPrices = loadPrices();

function loadPrices() {
  var allPages = new Promise(function (resolve, reject) {
    var firstPage = makeRequest("GET", gwUrlBase + gwUrlPrices + gwUrlPaging + 0);
    firstPage.then(function(result){
		if (result.pageCount > 1) {
			var promises = [];
			var priceData = JSON.parse(result.respone);
			for(i = 1; i < result.pageCount; i++) {
				promises.push(makeRequest("GET", gwUrlBase + gwUrlPrices + gwUrlPaging + i));
			}
			var allPromises = Promise.all(promises);
			allPromises.then(function(results) {
				for(i = 0; i < results.length; i++) {
					priceData = priceData.concat(JSON.parse(results[i].respone));
				}
				resolve(priceData);
			}, function(e) {
				reject(e);
			});
		} else {
			resolve(JSON.parse(result.respone));
		}
    }, function(err) {
      reject(err);
    });
  });
  return function(callback) {
    allPages.then(callback);
  };
}

function getItem(id, callback) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var item = JSON.parse(xmlhttp.responseText);
      callback(item[0]);
    }
  };
  xmlhttp.open("GET", gwUrlBase + gwUrlItems + gwUrlIds + id, true);
  xmlhttp.send();
}

function setSpreadFilters(pSIndex) {
	if (pSIndex === undefined) {
		pS = 0;
		pSIndex = 0;
	}
    var goldMax = document.forms["spreadfilters"]["goldmax"].value;
    var silverMax = document.forms["spreadfilters"]["silvermax"].value;
    var goldMin = document.forms["spreadfilters"]["goldmin"].value;
    var silverMin = document.forms["spreadfilters"]["silvermin"].value;
    var goldMaxBuy = document.forms["spreadfilters"]["goldmaxbuy"].value;
    var silverMaxBuy = document.forms["spreadfilters"]["silvermaxbuy"].value;

    var max = (goldMax * 10000 + silverMax * 100);
    var min = (goldMin * 10000 + silverMin * 100);
    var maxBuy = (goldMaxBuy * 10000 + silverMaxBuy * 100)

    if (goldMax == 0 && silverMax == 0) {
    	document.forms["spreadfilters"]["silvermax"].value = 1;
    	silverMax = 1;
    	max = (goldMax * 10000 + silverMax * 100);
    }
    if (max < min) {
    	document.forms["spreadfilters"]["goldmax"].value = goldMin;
    	document.forms["spreadfilters"]["silvermax"].value = silverMin;
    	goldMax = goldMin;
    	silverMax = silverMin;
    	max = (goldMax * 10000 + silverMax * 100);
    }

    getPrices(function(priceSpread) {
    	var filteredSpread = priceSpread.filter(function(currentValue) {
    		return ((currentValue.spread <= max) && (currentValue.spread >= min) &&
    		(currentValue.buys.unit_price <= maxBuy));
    	});
    	filteredSpread.sort(comparePrices);
    	getItem(filteredSpread[pSIndex].id, function(item) {
    		displayItem(item, "#current-item", filteredSpread[pSIndex]);
    		$('.stack.current').fadeIn();
    	});
    	getItem(filteredSpread[pSIndex+1].id, function(item) {
    		displayItem(item, "#next-item", filteredSpread[pSIndex+1]);
    		$('.stack.next').fadeIn();
    	});
    });
}

function calculateSpread(currentValue) {
  currentValue.spread = currentValue.sells.unit_price - currentValue.buys.unit_price;
}

function comparePrices(arr1, arr2) {
  return (arr2.spread - arr1.spread);
}
<commit_msg>Alright, third times the charm.<commit_after>// http://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr
function makeRequest (method, url) {
	return new Promise(function (resolve, reject) {
		var xhr = new XMLHttpRequest();
		xhr.open(method, url);
		xhr.onload = function () {
			if (this.status >= 200 && this.status < 300) {
				resolve({
					respone: xhr.response,
					pageCount: xhr.getResponseHeader("X-Page-Total")
				});
			} else {
				reject({
					status: this.status,
					statusText: xhr.statusText
				});
			}
		};
		xhr.onerror = function () {
			reject({
				status: this.status,
				statusText: xhr.statusText
			});
		};
		xhr.send();
	});
}
// http://stackoverflow.com/questions/8034918/jquery-switch-elements-in-dom
function swapElements(elm1, elm2) {
    var parent1, next1,
        parent2, next2;

    parent1 = elm1.parentNode;
    next1   = elm1.nextSibling;
    parent2 = elm2.parentNode;
    next2   = elm2.nextSibling;

    parent1.insertBefore(elm2, next1);
    parent2.insertBefore(elm1, next2);
}

// My code.
// String constants for constructing GW API requests.
var gwUrlBase = "https://api.guildwars2.com/v2/";
var gwUrlPrices = "commerce/prices";
var gwUrlItems = "items"
var gwUrlIds = "?ids="
var gwUrlPaging = "?page_size=200&page=";

// Current index of priceSpread item.
var pS=0;
// Entry to AJAX code.
$(document).ready(function(){
	// Fetch GW Price data and display two greatest spreads.
	getPrices(displayGreatestSpread);

	// Allow navigation of prices.
	$(".stack.next").on("click",function(){
		$(".stack.current").fadeOut();
		$(this).css("z-index", "1");
		$(this).animate({
			left: '0',
			bottom: $(".stack.current").innerHeight()
		}, stackForwardReset);
	});
	$(".stack.current").on("click",function(){
		$(".stack.next").fadeOut();
		var targetHeight = (60 - $(".stack.next").innerHeight()) + "px";
		$(this).animate({
			left: '75px',
			bottom: targetHeight
		}, stackBackwardReset);
	});
});

function stackForwardReset() {
	$('.stack.current').html($('.stack.next').html());
	$('.stack.current').show();
	$('.stack.next').hide();
	$('.stack.next').css("z-index", '');
	$('.stack.next').css("left", '');
	$('.stack.next').css("bottom", '');
	pS++;
	setSpreadFilters(pS);
}
function stackBackwardReset() {
	$('.stack.next').html($('.stack.current').html());
	$('.stack.next').show();
	$('.stack.current').css("opacity", '.01');
	$('.stack.current').css("left", '');
	$('.stack.current').css("bottom", '');
	pS--;
	setSpreadFilters(pS);
}

//
function displayGreatestSpread(priceSpread) {
  priceSpread = priceSpread.filter(function(currentValue) {
  	return ((currentValue.buys.quantity !== 0) && (currentValue.sells.quantity !== 0));
  });
  priceSpread.forEach(calculateSpread);
  priceSpread.sort(comparePrices);
  getItem(priceSpread[0].id, function(item) {
	  displayItem(item, "#current-item", priceSpread[0]);
  });
  getItem(priceSpread[1].id, function(item) {
	  displayItem(item, "#next-item", priceSpread[1]);
  });
}

function displayItem(item, boxId, tpData) {
  $(boxId + " .item-name").text(item.name);
  $(boxId + " .item-icon").attr("src", item.icon);
  $(boxId + " .item-icon").attr("alt", item.name + "'s Icon");
  if (tpData !== undefined) {
	$(boxId + " .buy-price").text(tpData.buys.unit_price);
	$(boxId + " .sell-price").text(tpData.sells.unit_price);
  }
}

var getPrices = loadPrices();

function loadPrices() {
  var allPages = new Promise(function (resolve, reject) {
    var firstPage = makeRequest("GET", gwUrlBase + gwUrlPrices + gwUrlPaging + 0);
    firstPage.then(function(result){
		if (result.pageCount > 1) {
			var promises = [];
			var priceData = JSON.parse(result.respone);
			for(i = 1; i < result.pageCount; i++) {
				promises.push(makeRequest("GET", gwUrlBase + gwUrlPrices + gwUrlPaging + i));
			}
			var allPromises = Promise.all(promises);
			allPromises.then(function(results) {
				for(i = 0; i < results.length; i++) {
					priceData = priceData.concat(JSON.parse(results[i].respone));
				}
				resolve(priceData);
			}, function(e) {
				reject(e);
			});
		} else {
			resolve(JSON.parse(result.respone));
		}
    }, function(err) {
      reject(err);
    });
  });
  return function(callback) {
    allPages.then(callback);
  };
}

function getItem(id, callback) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var item = JSON.parse(xmlhttp.responseText);
      callback(item[0]);
    }
  };
  xmlhttp.open("GET", gwUrlBase + gwUrlItems + gwUrlIds + id, true);
  xmlhttp.send();
}

function setSpreadFilters(pSIndex) {
	if (pSIndex === undefined) {
		pS = 0;
		pSIndex = 0;
	}
    var goldMax = document.forms["spreadfilters"]["goldmax"].value;
    var silverMax = document.forms["spreadfilters"]["silvermax"].value;
    var goldMin = document.forms["spreadfilters"]["goldmin"].value;
    var silverMin = document.forms["spreadfilters"]["silvermin"].value;
    var goldMaxBuy = document.forms["spreadfilters"]["goldmaxbuy"].value;
    var silverMaxBuy = document.forms["spreadfilters"]["silvermaxbuy"].value;

    var max = (goldMax * 10000 + silverMax * 100);
    var min = (goldMin * 10000 + silverMin * 100);
    var maxBuy = (goldMaxBuy * 10000 + silverMaxBuy * 100)

    if (goldMax == 0 && silverMax == 0) {
    	document.forms["spreadfilters"]["silvermax"].value = 1;
    	silverMax = 1;
    	max = (goldMax * 10000 + silverMax * 100);
    }
    if (max < min) {
    	document.forms["spreadfilters"]["goldmax"].value = goldMin;
    	document.forms["spreadfilters"]["silvermax"].value = silverMin;
    	goldMax = goldMin;
    	silverMax = silverMin;
    	max = (goldMax * 10000 + silverMax * 100);
    }

    getPrices(function(priceSpread) {
    	var filteredSpread = priceSpread.filter(function(currentValue) {
    		return ((currentValue.spread <= max) && (currentValue.spread >= min) &&
    		(currentValue.buys.unit_price <= maxBuy));
    	});
    	filteredSpread.sort(comparePrices);
    	getItem(filteredSpread[pSIndex].id, function(item) {
    		displayItem(item, "#current-item", filteredSpread[pSIndex]);
			if ($('.stack.current').css("opacity") < 1) {
				$('.stack.current').css("opacity", '');
				$('.stack.current').hide();
			}
    		$('.stack.current').fadeIn();
    	});
    	getItem(filteredSpread[pSIndex+1].id, function(item) {
    		displayItem(item, "#next-item", filteredSpread[pSIndex+1]);
    		$('.stack.next').fadeIn();
    	});
    });
}

function calculateSpread(currentValue) {
  currentValue.spread = currentValue.sells.unit_price - currentValue.buys.unit_price;
}

function comparePrices(arr1, arr2) {
  return (arr2.spread - arr1.spread);
}
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  request = require('request'),
  karmaServer = require('karma').Server,
  fs = require('fs');
var plugins = gulpLoadPlugins();

process.env.NODE_ENV = 'test';

gulp.task('test', ['startServer', 'stopServer']);
gulp.task('startServer', function(done) {
  var promise = require('../server.js');

  promise.then(function(app){done();});
});
gulp.task('stopServer', ['runKarma'], function() {
  process.exit();
});
gulp.task('runMocha', ['startServer'], function () {
  return gulp.src('./packages/**/server/tests/**/*.spec.js', {read: false})
    .pipe(plugins.mocha({
      reporter: 'spec'
    }))
    .on('error', function(error){
      console.error(error);
      this.emit('end');
    });
});
gulp.task('runKarma', ['runMocha'], function (done) {
  request('http://localhost:3001/api/aggregatedassets', function(error, response, body) {
    var aggregatedassets = JSON.parse(body);
    aggregatedassets = processIncludes(aggregatedassets.footer.js);

    var karma = new karmaServer({
      configFile: __dirname + '/../karma.conf.js',
      singleRun: true,
      files: aggregatedassets.concat(['packages/**/public/tests/**/*.js', 'packages/**/public/**/*.html'])
    }, function () {
      done();
    });

    karma.start();
  });
});

function processIncludes(aggregatedAssets) {
  for(var i = 0; i < aggregatedAssets.length; ++i) {
    aggregatedAssets[i] = aggregatedAssets[i].slice(1);
    if(aggregatedAssets[i].indexOf('bower_components/') === -1) {
      var index = aggregatedAssets[i].indexOf('/') + 1;
      aggregatedAssets[i] = aggregatedAssets[i].substring(0, index) + "public/" + aggregatedAssets[i].substring(index);
    }
    try {
      fs.lstatSync(__dirname + '/../packages/core/' + aggregatedAssets[i]);
      aggregatedAssets[i] = 'packages/core/' + aggregatedAssets[i];
      continue;
    } catch(e) {
      // Not a file
    }
    try {
      fs.lstatSync(__dirname + '/../packages/custom/' + aggregatedAssets[i]);
      aggregatedAssets[i] = 'packages/custom/' + aggregatedAssets[i];
    } catch (e) {
      // Not a file
    }
  }
  return aggregatedAssets;
}<commit_msg>Updated to find includes in package added via npm<commit_after>'use strict';

var gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  request = require('request'),
  karmaServer = require('karma').Server,
  fs = require('fs'),
  path = require('path');

var plugins = gulpLoadPlugins();

process.env.NODE_ENV = 'test';

gulp.task('test', ['startServer', 'stopServer']);
gulp.task('startServer', function(done) {
  var promise = require('../server.js');

  promise.then(function(app){done();});
});
gulp.task('stopServer', ['runKarma'], function() {
  process.exit();
});
gulp.task('runMocha', ['startServer'], function () {
  return gulp.src('./packages/**/server/tests/**/*.spec.js', {read: false})
    .pipe(plugins.mocha({
      reporter: 'spec'
    }))
    .on('error', function(error){
      console.error(error);
      this.emit('end');
    });
});
gulp.task('runKarma', ['runMocha'], function (done) {
  request('http://localhost:3001/api/aggregatedassets', function(error, response, body) {
    var aggregatedassets = JSON.parse(body);
    aggregatedassets = processIncludes(aggregatedassets.footer.js);

    var karma = new karmaServer({
      configFile: __dirname + '/../karma.conf.js',
      singleRun: true,
      files: aggregatedassets.concat(['packages/**/public/tests/**/*.js', 'packages/**/public/**/*.html'])
    }, function () {
      done();
    });

    karma.start();
  });
});

function processIncludes(aggregatedAssets) {

  // Process all node_modules, find mean packages, and map directory names
  var dirmap = [];
  var nodemods = __dirname + '/../node_modules';
  fs.readdirSync(nodemods).forEach(function(file) {
    try {
      var data = fs.readFileSync(path.join(nodemods, file, 'mean.json'));
      if (data) {
        var json = JSON.parse(data.toString());
        if (json.name) {
          dirmap[file] = json.name;
        }
      }
    } catch (e) {
      // not a file
    }
  });

  for(var i = 0; i < aggregatedAssets.length; ++i) {
    aggregatedAssets[i] = aggregatedAssets[i].slice(1);
    if(aggregatedAssets[i].indexOf('bower_components/') === -1) {
      var index = aggregatedAssets[i].indexOf('/') + 1;
      var packageName = aggregatedAssets[i].substring(0, index-1);
      var nmIndex = -1;
      for(var dirName in dirmap) {
        if(dirmap[dirName] == packageName) {
          nmIndex = dirName;
          break;
        }
      }
      if(nmIndex === -1) {
        aggregatedAssets[i] = aggregatedAssets[i].substring(0, index) + "public/" + aggregatedAssets[i].substring(index);
      } else {
        aggregatedAssets[i] = 'node_modules/' + nmIndex + '/public/' + aggregatedAssets[i].substring(index);
      }
    }
    try {
      fs.lstatSync(__dirname + '/../packages/core/' + aggregatedAssets[i]);
      aggregatedAssets[i] = 'packages/core/' + aggregatedAssets[i];
      continue;
    } catch(e) {
      // Not a file
    }
    try {
      fs.lstatSync(__dirname + '/../packages/custom/' + aggregatedAssets[i]);
      aggregatedAssets[i] = 'packages/custom/' + aggregatedAssets[i];
    } catch (e) {
      // Not a file
    }
  }
  return aggregatedAssets;
}

function mapFile(dirmap, promise, file, err, data) {
  if(!err) {
    var json = JSON.parse(data.toString());
    if(json.name) {
      dirmap[file] = json.name;
    }
    promise.resolve();
  }
  else {
    promise.resolve();
  }
}<|endoftext|>


<commit_before>var extract = require('i18n-extract');
const fs = require('fs');

var path = '../app/dist/locales/en.json';

fs.writeFile(path, '{}', 'utf8', function(err) {
    if(err) {
        return console.log(err);
    }
    var enLocale = require(path);

    const keys = extract.extractFromFiles(['js/**/*.{js,jsx}'], {
    marker: '__',
    });

    let reports = [];
    reports = reports.concat(extract.findMissing(enLocale, keys));
    reports = reports.concat(extract.findUnused(enLocale, keys));
    reports = reports.concat(extract.findDuplicated(enLocale, keys));

    if (reports.length > 0) {
        fs.readFile(path, 'utf8', function readFileCallback(err, data){
            if (err){
                console.log(err);
            } else {
                localeObj = JSON.parse(data);

                for (var i = 0; i < reports.length; i++) {
                    if (reports[i].type === 'MISSING') {
                        localeObj[reports[i].key] = reports[i].key;
                    } else if (reports[i].type === 'UNUSED') {
                        console.log("Found unused String in en.json, but beware: This may be a String from api.lbry.io, do not blindly delete!")
                        console.log(reports[i]);
                    } else if (reports[i].type == "DUPLICATED") {
                        console.log("Found duplicated String in en.json!")
                        console.log(reports[i]);
                    } else {
                        console.log("Found unknown type of String in en.json!")
                        console.log(reports[i]);
                    }
                }

                var json = JSON.stringify(localeObj, null, '\t'); //convert it back to json
                fs.writeFile(path, json, 'utf8', function callback(err) {
                    if (err) throw err;
                    console.log('It\'s saved!');
                });
            }
        });
    }
});

<commit_msg>update script again<commit_after>var extract = require('i18n-extract');
const fs = require('fs');

var path = '../app/dist/locales/en.json';

fs.writeFile(path, '{}', 'utf8', function(err) {
    if(err) {
        return console.log(err);
    }
    var enLocale = require(path);

    const keys = extract.extractFromFiles(['js/**/*.{js,jsx}'], {
    marker: '__',
    });

    let reports = [];
    reports = reports.concat(extract.findMissing(enLocale, keys));

    if (reports.length > 0) {
        fs.readFile(path, 'utf8', function readFileCallback(err, data){
            if (err){
                console.log(err);
            } else {
                localeObj = JSON.parse(data);

                for (var i = 0; i < reports.length; i++) {
                    // no need to care for other types than MISSING because starting file will always be empty
                    if (reports[i].type === 'MISSING') {
                        localeObj[reports[i].key] = reports[i].key;
                    }
                }

                var json = JSON.stringify(localeObj, null, '\t'); //convert it back to json-string
                fs.writeFile(path, json, 'utf8', function callback(err) {
                    if (err) throw err;
                    console.log('Extracted all strings!');
                });
            }
        });
    }
});

<|endoftext|>


<commit_before>var argp = require ("./lib");
var util = require ("util");

var argv = argp
		.on ("argument", function (argv, argument){
			//console.log (argument);
		})
		.on ("option", function (argv, option, value, long){
			//console.log (option, value, long);
		})
		.configuration ({
			//allowUndefinedOptions: false
			//allowUndefinedArguments: false
		})
		.version ("v0.0.0")
		.email ("a@b.c")
		.description ("Does something magic that I still don't know asd asdasdasdasdas asd asd asasd asda sassda dasd asd")
		.usage ("sdasd ad adasd asdas asd asasas asdas asd asd asdas asd asdas asd asdas")
		.usage ("sdasd ad adasd asdas asd asasas asdas asd asd asdas asd asdas asd asdas asd 123")
		.argument ("asdetertrqweqwe")
		.argument ("qwedfgdfgdfg")
		.argument ("dfgdfgdfg")
		.body (function (body){
			body
					.option ({ short: "a", argument: "NUM", optional: true })
					.text ("some text some text some text some text some text some text some text some text some text some text")
					.option ({ long: "b", argument: "NUM", optional: false, description: "asda sdas asdas asd asd asdasasd asd asd asdas asd adas asdasdas asd asdas asd asd asda asd asdasd asdas asd asd asd asda sd" })
					.option ({ long: "cc", short: "c", description: "cccccccc" })
					.group ("Informational options asd asd adas asdqqwe qwe qeqe qwe qe qwe qwe qwe qwe qqwe qwe")
		})
		.argv ();

console.log (argv);<commit_msg>clean up<commit_after><|endoftext|>


<commit_before>var inherits = require('inherits');

var editdist = require('../lib/editdist');
var GenerativePrompt = require('./generative_prompt');

function PhrasePrompt(options) {
    if (!this instanceof PhrasePrompt) {
        return new PhrasePrompt(options);
    }
    options = options || {};
    this.running = false;
    this.maxErrorPerWord = options.maxErrorPerWord || 1;
    this.repromptDelay = options.repromptDelay || 100;

    GenerativePrompt.call(this, options);

    this.on('expire', this.onPhraseExpired.bind(this));
    this.on('input', this.onInput.bind(this));
    this.on('showdisplay', this.onDisplay.bind(this));
    this.on('settimeout', this.onSetTimeout.bind(this));
    this.on('showinput', this.onShowInput.bind(this));
    this.on('expire', this.onPromptExpire.bind(this));
}

inherits(PhrasePrompt, GenerativePrompt);

PhrasePrompt.prototype.start = function() {
    if (!this.running) {
        this.running = true;
        this.prompt();
    }
};

PhrasePrompt.prototype.stop = function() {
    if (this.running) {
        this.running = false;
        this.expireInput();
    }
};

PhrasePrompt.prototype.emitRecord = function() {
    if (this.record) {
        this.emit('result', this.record);
        this.record = null;
    }
};

PhrasePrompt.prototype.finishRecord = function(force) {
    if (!this.record) return;
    if (this.record.inputShownAt) {
        this.record.elapsed.input = Date.now() - this.record.inputShownAt;
    }
    this.record.forced = force;
    var maxErrorPerWord = this.maxErrorPerWord;
    this.record.maxErrors = this.record.expected.split(/ +/)
        .map(function(word) {return Math.min(maxErrorPerWord, word.length);})
        .reduce(function(a, b) {return a + b;})
        ;
    this.record.correct = this.record.dist <= this.record.maxErrors;
    this.record.finished = this.record.forced || this.record.correct;
};

PhrasePrompt.prototype.prompt = function() {
    this.record = {
        elapsed: {},
        timeout: {}
    };
    GenerativePrompt.prototype.prompt.call(this);
    this.record.expected = this.expected;
    this.record.got = this.got;
    this.record.dist = editdist.lossy(this.got, this.expected);
};

PhrasePrompt.prototype.reprompt = function() {
    if (this.inputing) {
        this.inputElement.disabled = true;
    }
    setTimeout(this.prompt.bind(this), this.repromptDelay);
};

PhrasePrompt.prototype.onSetTimeout = function(kind, time) {
    if (this.record) {
        this.record.timeout[kind] = time;
    }
};

PhrasePrompt.prototype.onDisplay = function() {
    if (this.record && !this.record.displayedAt) {
        this.record.displayedAt = Date.now();
    }
};

PhrasePrompt.prototype.onShowInput = function() {
    this.record.inputShownAt = Date.now();
    if (this.record.displayedAt) {
        if (!this.record.elapsed.display) {
            this.record.elapsed.display = this.record.inputShownAt - this.record.displayedAt;
        }
    }
};

PhrasePrompt.prototype.onPhraseExpired = function() {
    if (this.record) {
        this.finishRecord(true);
        this.record.expired = true;
        this.emitRecord();
    }
};

PhrasePrompt.prototype.onInput = function(force) {
    if (this.record) {
        this.record.got = this.got;
        this.record.dist = editdist(this.got, this.expected);
        this.finishRecord(force);
        if (this.record.finished) {
            this.clearTimer();
            this.emitRecord();
            this.reprompt();
        }
    }
};

PhrasePrompt.prototype.onPromptExpire = function() {
    if (this.running) this.reprompt();
};

module.exports = PhrasePrompt;
<commit_msg>PhrasePrompt: call finishRecord in prompt<commit_after>var inherits = require('inherits');

var editdist = require('../lib/editdist');
var GenerativePrompt = require('./generative_prompt');

function PhrasePrompt(options) {
    if (!this instanceof PhrasePrompt) {
        return new PhrasePrompt(options);
    }
    options = options || {};
    this.running = false;
    this.maxErrorPerWord = options.maxErrorPerWord || 1;
    this.repromptDelay = options.repromptDelay || 100;

    GenerativePrompt.call(this, options);

    this.on('expire', this.onPhraseExpired.bind(this));
    this.on('input', this.onInput.bind(this));
    this.on('showdisplay', this.onDisplay.bind(this));
    this.on('settimeout', this.onSetTimeout.bind(this));
    this.on('showinput', this.onShowInput.bind(this));
    this.on('expire', this.onPromptExpire.bind(this));
}

inherits(PhrasePrompt, GenerativePrompt);

PhrasePrompt.prototype.start = function() {
    if (!this.running) {
        this.running = true;
        this.prompt();
    }
};

PhrasePrompt.prototype.stop = function() {
    if (this.running) {
        this.running = false;
        this.expireInput();
    }
};

PhrasePrompt.prototype.emitRecord = function() {
    if (this.record) {
        this.emit('result', this.record);
        this.record = null;
    }
};

PhrasePrompt.prototype.finishRecord = function(force) {
    if (!this.record) return;
    if (this.record.inputShownAt) {
        this.record.elapsed.input = Date.now() - this.record.inputShownAt;
    }
    this.record.forced = force;
    var maxErrorPerWord = this.maxErrorPerWord;
    this.record.maxErrors = this.record.expected.split(/ +/)
        .map(function(word) {return Math.min(maxErrorPerWord, word.length);})
        .reduce(function(a, b) {return a + b;})
        ;
    this.record.correct = this.record.dist <= this.record.maxErrors;
    this.record.finished = this.record.forced || this.record.correct;
};

PhrasePrompt.prototype.prompt = function() {
    this.record = {
        elapsed: {},
        timeout: {}
    };
    GenerativePrompt.prototype.prompt.call(this);
    this.record.expected = this.expected;
    this.record.got = this.got;
    this.record.dist = editdist.lossy(this.got, this.expected);
    this.finishRecord();
};

PhrasePrompt.prototype.reprompt = function() {
    if (this.inputing) {
        this.inputElement.disabled = true;
    }
    setTimeout(this.prompt.bind(this), this.repromptDelay);
};

PhrasePrompt.prototype.onSetTimeout = function(kind, time) {
    if (this.record) {
        this.record.timeout[kind] = time;
    }
};

PhrasePrompt.prototype.onDisplay = function() {
    if (this.record && !this.record.displayedAt) {
        this.record.displayedAt = Date.now();
    }
};

PhrasePrompt.prototype.onShowInput = function() {
    this.record.inputShownAt = Date.now();
    if (this.record.displayedAt) {
        if (!this.record.elapsed.display) {
            this.record.elapsed.display = this.record.inputShownAt - this.record.displayedAt;
        }
    }
};

PhrasePrompt.prototype.onPhraseExpired = function() {
    if (this.record) {
        this.finishRecord(true);
        this.record.expired = true;
        this.emitRecord();
    }
};

PhrasePrompt.prototype.onInput = function(force) {
    if (this.record) {
        this.record.got = this.got;
        this.record.dist = editdist(this.got, this.expected);
        this.finishRecord(force);
        if (this.record.finished) {
            this.clearTimer();
            this.emitRecord();
            this.reprompt();
        }
    }
};

PhrasePrompt.prototype.onPromptExpire = function() {
    if (this.running) this.reprompt();
};

module.exports = PhrasePrompt;
<|endoftext|>


<commit_before>/*!
 * jQuery UI Mouse @VERSION
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: UI Core
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([
			"jquery",
			"../ie",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
});

return $.widget("ui.mouse", {
	version: "@VERSION",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on("mousedown." + this.widgetName, function(event) {
				return that._mouseDown(event);
			})
			.on("click." + this.widgetName, function(event) {
				if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
					$.removeData(event.target, that.widgetName + ".preventClickEvent");
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off("." + this.widgetName);
		if ( this._mouseMoveDelegate ) {
			this.document
				.off("mousemove." + this.widgetName, this._mouseMoveDelegate)
				.off("mouseup." + this.widgetName, this._mouseUpDelegate);
		}
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = (event.which === 1),
			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				that.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
			$.removeData(event.target, this.widgetName + ".preventClickEvent");
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return that._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return that._mouseUp(event);
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {
			// IE mouseup check - mouseup happened when mouse was out of window
			if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
				return this._mouseUp(event);

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {
				return this._mouseUp( event );
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if (this._mouseStarted) {
			this._mouseStarted = false;

			if (event.target === this._mouseDownEvent.target) {
				$.data(event.target, this.widgetName + ".preventClickEvent", true);
			}

			this._mouseStop(event);
		}

		mouseHandled = false;
		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(/* event */) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(/* event */) {},
	_mouseDrag: function(/* event */) {},
	_mouseStop: function(/* event */) {},
	_mouseCapture: function(/* event */) { return true; }
});

}));
<commit_msg>Mouse: Style updates<commit_after>/*!
 * jQuery UI Mouse @VERSION
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: UI Core
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([
			"jquery",
			"../ie",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
});

return $.widget("ui.mouse", {
	version: "@VERSION",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on("mousedown." + this.widgetName, function(event) {
				return that._mouseDown(event);
			})
			.on("click." + this.widgetName, function(event) {
				if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
					$.removeData(event.target, that.widgetName + ".preventClickEvent");
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off("." + this.widgetName);
		if ( this._mouseMoveDelegate ) {
			this.document
				.off("mousemove." + this.widgetName, this._mouseMoveDelegate)
				.off("mouseup." + this.widgetName, this._mouseUpDelegate);
		}
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = (event.which === 1),
			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				that.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
			$.removeData(event.target, this.widgetName + ".preventClickEvent");
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return that._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return that._mouseUp(event);
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {
			// IE mouseup check - mouseup happened when mouse was out of window
			if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
				return this._mouseUp(event);

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {
				return this._mouseUp( event );
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if (this._mouseStarted) {
			this._mouseStarted = false;

			if (event.target === this._mouseDownEvent.target) {
				$.data(event.target, this.widgetName + ".preventClickEvent", true);
			}

			this._mouseStop(event);
		}

		mouseHandled = false;
		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(/* event */) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(/* event */) {},
	_mouseDrag: function(/* event */) {},
	_mouseStop: function(/* event */) {},
	_mouseCapture: function(/* event */) { return true; }
});

}));
<|endoftext|>