<commit_before>//jscs:disable jsDoc

module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-jscs');
    grunt.loadNpmTasks('grunt-regex-check');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-jsdoc');
    grunt.loadNpmTasks('grunt-babel');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-text-replace');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-mkdir');
    grunt.loadTasks('config/gruntTasks/');

    var gruntOptions = {
        skipTests: (process.env.GRUNT_SKIP_TESTS || false) === 'true'
    };

    console.log(gruntOptions);

    /******************************************
     * GRUNT INIT
     ******************************************/

    grunt.initConfig({
        fileConfigOptions: {
            prodHtml: [ 'target/website/index.html', 'target/website/src/**/*.html', '!target/website/src/main/web/utilities/libraries/**/*.html' ],
            prodFiles: [ 'target/website/index.html', 'target/website/src/**/*.html', 'target/website/src/**/*.js',
                '!target/website/src/main/web/utilities/libraries/**/*.js', '!target/website/src/main/web/utilities/libraries/**/*.html' ]
        },
        /**
         * CHECKSTYLE
         */
        jshint: {
            options: {
                jshintrc: 'config/.jshintrc',
                ignores: [ 'src/main/web/utilities/libraries/**/*.js', 'src/test/web/testUtilities/**/*.js' ],
                globals: {
                    module: true
                },
                reporter:'jslint',
                reporterOutput: 'target/jshint.xml'
            },
            files: [ 'Gruntfile.js', 'src/main/web/**/*.js', 'src/test/web/**/*.js',
                '!src/main/web/utilities/libraries/**/*.js', '!src/test/web/**/*.js', '!src/main/web/sketching/srl/objects/**/*.js' ]
        },
        jscs: {
            src: '<%= jshint.files %>',
            options: {
                config: 'config/jscs.conf.jscsrc',
                reporterOutput: 'target/jscsReport.txt',
                maxErrors: 1000
            }
        },
        /*
         * This module is used to check the existence or the lack of existance of a pattern in the given files
         */
        'regex-check': {
            head: {
                files: {
                    src: [ 'src/main/web/**/*.html', 'src/test/web/**/*.html', '!src/main/web/utilities/libraries/**/*.html',
                        'src/main/web/utilities/libraries/**/*Include.html' ]
                },
                options: {
                    // This looks for the head tag <head>
                    pattern: /<head(\s|(.*lang=.*))*>/g,
                    failIfMissing: true
                }
            }
        },
        /**
         * JSDOC
         */
        jsdoc: {
            dist: {
                src: '<%= jshint.files %>',
                options: {
                    destination: 'doc'
                }
            }
        },
        /**
         * Directory Creation
         */
        mkdir: {
            all: {
                options: {
                    create: [ 'target/unitTest', 'target/screenshots' ]
                }
            }
        },
        /**
         * BUILDERS
         */
        babel: {
            options: {
                sourceMap: true
            },
            all: {
                files: [
                    {
                        expand: true,
                        src: [ 'target/website/src/main/web/**/*.js', '!target/website/src/main/web/utilities/libraries/**/*.js' ],
                        dest: '.'
                    }
                ]
            }
        },
        copy: {
            main: {
                files: [
                    {
                        // copies the website files used in production for prod use
                        expand: true,
                        src: [ 'src/main/web/**', '!src/test/**',

                            // we do not want these copied as they are not meant for production.
                            '!src/**/debug/**' ],
                        dest: 'target/website/'
                    },
                    {
                        // copies other important files that appear in the top level directory
                        expand: true,
                        src: [ 'index.html', 'favicon.ico', 'bower.json' ],
                        dest: 'target/website/'
                    },
                    {
                        // copies the bower components to target
                        expand: true,
                        src: [ 'bower_components/**', '!bower_components/**/test/**', '!bower_components/**/tests/**',
                            '!bower_components/**/examples/**' ],
                        dest: 'target/website/'
                    },
                    {
                        // copies the google app engine directory file
                        expand: true,
                        src: 'app.yaml',
                        dest: 'target/website/'
                    },
                    {
                        // copies the rest of the google app engine files
                        expand: true,
                        src: [ 'testFiles.py', 'main.py' ],
                        dest: 'target/website/'
                    }
                ]
            },
            /**
             * copies the babel polyfill into the bower_components folder
             */
            babel: {
                files: [
                    {
                        expand: false,
                        src: [ 'node_modules/babel-core/browser-polyfill.js' ],
                        dest: 'bower_components/babel-polyfill/browser-polyfill.js',
                        filter: 'isFile'
                    },
                    {
                        expand: false,
                        src: [ 'bower_components/babel-polyfill/.bower.json' ],
                        dest: 'bower_components/babel-polyfill/bower.json',
                        filter: 'isFile'
                    }
                ]
            }
        },
        replace: {
            isUndefined: {
                src: '<%= fileConfigOptions.prodFiles %>',
                overwrite: true,
                replacements: [
                    {
                        // looks for isUndefined(word).
                        from: /isUndefined\((\w+\b)\)/g,
                        to: '(typeof $1 === \'undefined\')'
                    },
                    {
                        from: 'function (typeof object === \'undefined\')',
                        to: 'function isUndefined(object)'
                    }
                ]
            }
        },
    });

    /******************************************
     * UTILITIES
     ******************************************/

    function printTaskGroup() {
        grunt.log.write('\n===========\n=========== Running task group ' + grunt.task.current.name + ' ===========\n===========\n');
    }

    /******************************************
     * TASK WORKFLOW SETUP
     ******************************************/

    // sets up tasks related to creating documentation
    grunt.registerTask('documentation', function() {
        printTaskGroup();
        grunt.task.run([
            'jsdoc'
        ]);
    });

    // Sets up tasks related to setting the system for the rest of the tasks.
    grunt.registerTask('setup', function() {
        printTaskGroup();
        grunt.task.run([
            'mkdir'
        ]);
    });

    // sets up tasks related to checkstyle
    grunt.registerTask('checkstyle', function() {
        printTaskGroup();
        grunt.task.run([
            'jscs',
            'jshint',
            'regex-check'
        ]);
    });

    // sets up tasks related to building the production website
    grunt.registerTask('build', function() {
        printTaskGroup();
        grunt.task.run([
            'setupProd',
            'polyfill'
        ]);
    });

    // Sets up tasks related to setting up the production website.
    grunt.registerTask('setupProd', function() {
        printTaskGroup();
        grunt.task.run([
            'copy:main',
        ]);
    });

    // sets up tasks related to supporting older version of browsers
    grunt.registerTask('polyfill', function() {
        printTaskGroup();
        grunt.task.run([
            'replace:isUndefined'
            // babel is turned off because it is breaking things.
            //'babel'
        ]);
    });

    /******************************************
     * TASK WORKFLOW RUNNING
     ******************************************/

    // 'test'  wait till browsers are better supported
    grunt.registerTask('default', [ 'checkstyle', 'documentation', 'setup', 'build' ]);
};
<commit_msg>working on compiling protobuf files<commit_after>//jscs:disable jsDoc

var pbjs = require('protobufjs/cli/pbjs.js');

module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-jscs');
    grunt.loadNpmTasks('grunt-regex-check');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-jsdoc');
    grunt.loadNpmTasks('grunt-babel');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-text-replace');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-mkdir');

    var gruntOptions = {
        skipTests: (process.env.GRUNT_SKIP_TESTS || false) === 'true'
    };

    console.log(gruntOptions);

    /******************************************
     * GRUNT INIT
     ******************************************/

    grunt.initConfig({
        fileConfigOptions: {
            prodHtml: [ 'target/website/index.html', 'target/website/src/**/*.html', '!target/website/src/main/web/utilities/libraries/**/*.html' ],
            prodFiles: [ 'target/website/index.html', 'target/website/src/**/*.html', 'target/website/src/**/*.js',
                '!target/website/src/main/web/utilities/libraries/**/*.js', '!target/website/src/main/web/utilities/libraries/**/*.html' ]
        },
        /**
         * CHECKSTYLE
         */
        jshint: {
            options: {
                jshintrc: 'config/.jshintrc',
                ignores: [ 'src/main/web/utilities/libraries/**/*.js', 'src/test/web/testUtilities/**/*.js' ],
                globals: {
                    module: true
                },
                reporter:'jslint',
                reporterOutput: 'target/jshint.xml'
            },
            files: [ 'Gruntfile.js', 'src/main/web/**/*.js', 'src/test/web/**/*.js',
                '!src/main/web/utilities/libraries/**/*.js', '!src/test/web/**/*.js', '!src/main/web/sketching/srl/objects/**/*.js' ]
        },
        jscs: {
            src: '<%= jshint.files %>',
            options: {
                config: 'config/jscs.conf.jscsrc',
                reporterOutput: 'target/jscsReport.txt',
                maxErrors: 1000
            }
        },
        /*
         * This module is used to check the existence or the lack of existance of a pattern in the given files
         */
        'regex-check': {
            head: {
                files: {
                    src: [ 'src/main/web/**/*.html', 'src/test/web/**/*.html', '!src/main/web/utilities/libraries/**/*.html',
                        'src/main/web/utilities/libraries/**/*Include.html' ]
                },
                options: {
                    // This looks for the head tag <head>
                    pattern: /<head(\s|(.*lang=.*))*>/g,
                    failIfMissing: true
                }
            }
        },
        /**
         * JSDOC
         */
        jsdoc: {
            dist: {
                src: '<%= jshint.files %>',
                options: {
                    destination: 'doc'
                }
            }
        },
        /**
         * Directory Creation
         */
        mkdir: {
            all: {
                options: {
                    create: [ 'target/unitTest', 'target/screenshots' ]
                }
            }
        },
        /**
         * BUILDERS
         */
        babel: {
            options: {
                sourceMap: true
            },
            all: {
                files: [
                    {
                        expand: true,
                        src: [ 'target/website/src/main/web/**/*.js', '!target/website/src/main/web/utilities/libraries/**/*.js' ],
                        dest: '.'
                    }
                ]
            }
        },
        copy: {
            main: {
                files: [
                    {
                        // copies the website files used in production for prod use
                        expand: true,
                        src: [ 'src/main/web/**', '!src/test/**',

                            // we do not want these copied as they are not meant for production.
                            '!src/**/debug/**' ],
                        dest: 'target/website/'
                    },
                    {
                        // copies other important files that appear in the top level directory
                        expand: true,
                        src: [ 'index.html', 'favicon.ico', 'bower.json' ],
                        dest: 'target/website/'
                    },
                    {
                        // copies the bower components to target
                        expand: true,
                        src: [ 'bower_components/**', '!bower_components/**/test/**', '!bower_components/**/tests/**',
                            '!bower_components/**/examples/**' ],
                        dest: 'target/website/'
                    },
                    {
                        // copies the google app engine directory file
                        expand: true,
                        src: 'app.yaml',
                        dest: 'target/website/'
                    },
                    {
                        // copies the rest of the google app engine files
                        expand: true,
                        src: [ 'testFiles.py', 'main.py' ],
                        dest: 'target/website/'
                    }
                ]
            },
            /**
             * copies the babel polyfill into the bower_components folder
             */
            babel: {
                files: [
                    {
                        expand: false,
                        src: [ 'node_modules/babel-core/browser-polyfill.js' ],
                        dest: 'bower_components/babel-polyfill/browser-polyfill.js',
                        filter: 'isFile'
                    },
                    {
                        expand: false,
                        src: [ 'bower_components/babel-polyfill/.bower.json' ],
                        dest: 'bower_components/babel-polyfill/bower.json',
                        filter: 'isFile'
                    }
                ]
            }
        },
        replace: {
            isUndefined: {
                src: '<%= fileConfigOptions.prodFiles %>',
                overwrite: true,
                replacements: [
                    {
                        // looks for isUndefined(word).
                        from: /isUndefined\((\w+\b)\)/g,
                        to: '(typeof $1 === \'undefined\')'
                    },
                    {
                        from: 'function (typeof object === \'undefined\')',
                        to: 'function isUndefined(object)'
                    }
                ]
            }
        }
    });

    /******************************************
     * UTILITIES
     ******************************************/

    function printTaskGroup() {
        grunt.log.write('\n===========\n=========== Running task group ' + grunt.task.current.name + ' ===========\n===========\n');
    }

    /******************************************
     * TASK WORKFLOW SETUP
     ******************************************/

    // sets up tasks related to creating documentation
    grunt.registerTask('documentation', function() {
        printTaskGroup();
        grunt.task.run([
            'jsdoc'
        ]);
    });

    //jscs:disable
    grunt.registerTask('buildProto', function() {
        var protoFiles = grunt.file.expand([ 'src/**/proto/**/*.proto' ]);
        grunt.log.write('Attempting to compile proto files:');
        grunt.log.write(protoFiles);
        for (var i = 0; i < protoFiles.length; i++) {
            grunt.log.write('cimpiling protofile ' + protoFiles[i]);
            grunt.log.write('');
            var options = [ '--source=proto', '--target=js', '--path=src/main/proto' ];
            var files = [ protoFiles[i] ];
            var args = protoFiles.concat(options);
                // .concat([ '> ' + protoFiles[i].replace('.proto', '.js') ]);
            pbjs.main(args);
        }
    });

    // Sets up tasks related to setting the system for the rest of the tasks.
    grunt.registerTask('setup', function() {
        printTaskGroup();
        grunt.task.run([
            'mkdir'
        ]);
    });

    // sets up tasks related to checkstyle
    grunt.registerTask('checkstyle', function() {
        printTaskGroup();
        grunt.task.run([
            'jscs',
            'jshint',
            'regex-check'
        ]);
    });

    // sets up tasks related to building the production website
    grunt.registerTask('build', function() {
        printTaskGroup();
        grunt.task.run([
            'buildProto',
            'setupProd',
            'polyfill'
        ]);
    });

    // Sets up tasks related to setting up the production website.
    grunt.registerTask('setupProd', function() {
        printTaskGroup();
        grunt.task.run([
            'copy:main'
        ]);
    });

    // sets up tasks related to supporting older version of browsers
    grunt.registerTask('polyfill', function() {
        printTaskGroup();
        grunt.task.run([
            'replace:isUndefined'
            // babel is turned off because it is breaking things.
            //'babel'
        ]);
    });

    /******************************************
     * TASK WORKFLOW RUNNING
     ******************************************/

    // 'test'  wait till browsers are better supported
    grunt.registerTask('default', [ 'checkstyle', 'documentation', 'setup', 'build' ]);
};
<|endoftext|>


<commit_before>import naomi from 'naomi';
import Database from './Database';

naomi.registerEngine('mysql', Database);

export default naomi;
<commit_msg>rm src/index.js; no longer needed<commit_after><|endoftext|>


<commit_before>import React from 'react';

export default function LoadProgressBar(props) {
  return (

  );
}
<commit_msg>Implemented LoadProgressBar Component<commit_after>import React, { PropTypes } from 'react';

const propTypes = {
  duration: PropTypes.number.isRequired,
  buffered: PropTypes.object,
};

// Shows load progress
export default function LoadProgressBar({ buffered, duration }) {
  if (!buffered || !buffered.length) {
    return null;
  }
  let bufferedEnd = buffered.end(buffered.length - 1);
  let style = {};

  if (bufferedEnd > duration) {
    bufferedEnd = duration;
  }

  // get the percent width of a time compared to the total end
  function percentify(time, end) {
    const percent = (time / end) || 0; // no NaN
    return `${((percent >= 1 ? 1 : percent) * 100)}%`;
  }

  // the width of the progress bar
  style.width = percentify(bufferedEnd, duration);

  let parts = [];

  // add child elements to represent the individual buffered time ranges
  for (let i = 0; i < buffered.length; i++) {
    const start = buffered.start(i);
    const end = buffered.end(i);
    // set the percent based on the width of the progress bar (bufferedEnd)
    const part = (
      <div
        style={{
          left: percentify(start, bufferedEnd),
          width: percentify(end - start, bufferedEnd),
        }}
        key={`part-${i}`}
      />
    );
    parts.push(part);
  }

  if (parts.length === 0) {
    parts = null;
  }

  return (

      Loaded: 0%
      {parts}

  );
}

LoadProgressBar.propTypes = propTypes;
<|endoftext|>


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

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    banner: '/* <%= pkg.name %> <%= pkg.version %> <%= grunt.template.today("yyyy-mm-dd h:MM") %> */\n',
    pouch : '<script type="text/javascript" src="../../../pouchdb/dist/pouchdb.min.js"></script>\n',
    lowla : '<script type="text/javascript" src="../../../lowladb/dist/lowladb.min.js"></script>\n',

    /*clean the output folder*/
    clean:{
      build : {
        src : ["dist"]
      },
      tmp : {
        src : ["dist/xcomponents-tmp.js", "dist/templates.js"]
      }

    },

    /*concat xc js source files*/
    concat: {
      js1 : {
        options: { banner: '<%= banner %>' },
        src: [
          'src/*.js',
          '!src/xc-main.js'
        ],
        dest: 'dist/xcomponents-tmp.js'
      },
      js2 : {
        src: [
          'src/xc-main.js',
          'dist/xcomponents-tmp.js',
          'dist/templates.js'
        ],
        dest: 'dist/xcomponents.js'
      },
      'js-libs' : {
        src : [
          'bower_components/angular/angular.min.js',
          'bower_components/angular-resource/angular-resource.min.js',
          'bower_components/angular-animate/angular-animate.min.js',
          'bower_components/angular-sanitize/angular-sanitize.min.js',
          'bower_components/angular-route/angular-route.min.js',
          'bower_components/angular-cookies/angular-cookies.min.js',
          'bower_components/angular-bootstrap/ui-bootstrap.min.js',
          'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js'

        ],
        dest : 'dist/libs-angular.js'

      }

    },

    /*create Angular JS files from the partials (html files)*/
    html2js : {
      options: {
      },
      main: {
        src: ['src/*.html'],
        dest: 'dist/templates.js'
      }
    },

    copy: {
      all: {
        files: [
          {expand: true, src: ['src/css/*'], dest: 'dist/css/', filter: 'isFile', flatten: true},
          {expand: true, src: ['src/includes/*'], dest: 'dist/includes/', filter: 'isFile', flatten: true},
          {expand: true, src: ['src/js/*'], dest: 'dist/js/', filter: 'isFile', flatten: true},
        ]
      }
    },

   replace: {
      pouch: {
        src: ['dist/includes/includes.html'],
        dest: 'dist/includes/includes-pouch.html',
        replacements: [{
          from: '<!-- include:pouch -->',
          to: '' + grunt.config('pouch')
        }]
      },
      lowla: {
        src: ['dist/includes/includes.html'],
        dest: 'dist/includes/includes-lowla.html',
        replacements: [{
          from: '<!-- include:lowla -->',
          to: '' + grunt.config('lowla')
        }]
      }
    },

    watch : {

      scripts: {
        files: ['Gruntfile.js', 'src/**/*.js', 'src/**/*.html', 'src/**/*.css'],
        tasks: ['default'],
        options: {
          spawn: false,
        }
      }
    },

    uglify: {
      build: {
        files: {
          'dist/xcomponents.min.js': ['dist/xcomponents.js']
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-html2js');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-text-replace');

  // Default task(s).
  grunt.registerTask('default', [
    'clean:build',
    'html2js',
    'concat:js1',
    'concat:js2',
    'concat:js-libs',
    'copy:all',
    'replace:pouch',
    'replace:lowla',
    'uglify:build',
    'clean:tmp',
   ]);

};<commit_msg>bug fix in gruntfile (invalid file reference)<commit_after>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    banner: '/* <%= pkg.name %> <%= pkg.version %> <%= grunt.template.today("yyyy-mm-dd h:MM") %> */\n',
    pouch : '<script type="text/javascript" src="../../../pouchdb/dist/pouchdb.min.js"></script>\n',
    lowla : '<script type="text/javascript" src="../../../lowladb/dist/lowladb.min.js"></script>\n',

    /*clean the output folder*/
    clean:{
      build : {
        src : ["dist"]
      },
      tmp : {
        src : ["dist/xcomponents-tmp.js", "dist/templates.js"]
      }

    },

    /*concat xc js source files*/
    concat: {
      js1 : {
        options: { banner: '<%= banner %>' },
        src: [
          'src/*.js',
          '!src/main.js'
        ],
        dest: 'dist/xcomponents-tmp.js'
      },
      js2 : {
        src: [
          'src/main.js',
          'dist/xcomponents-tmp.js',
          'dist/templates.js'
        ],
        dest: 'dist/xcomponents.js'
      },
      'js-libs' : {
        src : [
          'bower_components/angular/angular.min.js',
          'bower_components/angular-resource/angular-resource.min.js',
          'bower_components/angular-animate/angular-animate.min.js',
          'bower_components/angular-sanitize/angular-sanitize.min.js',
          'bower_components/angular-route/angular-route.min.js',
          'bower_components/angular-cookies/angular-cookies.min.js',
          'bower_components/angular-bootstrap/ui-bootstrap.min.js',
          'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js'

        ],
        dest : 'dist/libs-angular.js'

      }

    },

    /*create Angular JS files from the partials (html files)*/
    html2js : {
      options: {
      },
      main: {
        src: ['src/*.html'],
        dest: 'dist/templates.js'
      }
    },

    copy: {
      all: {
        files: [
          {expand: true, src: ['src/css/*'], dest: 'dist/css/', filter: 'isFile', flatten: true},
          {expand: true, src: ['src/includes/*'], dest: 'dist/includes/', filter: 'isFile', flatten: true},
          {expand: true, src: ['src/js/*'], dest: 'dist/js/', filter: 'isFile', flatten: true},
        ]
      }
    },

   replace: {
      pouch: {
        src: ['dist/includes/includes.html'],
        dest: 'dist/includes/includes-pouch.html',
        replacements: [{
          from: '<!-- include:pouch -->',
          to: '' + grunt.config('pouch')
        }]
      },
      lowla: {
        src: ['dist/includes/includes.html'],
        dest: 'dist/includes/includes-lowla.html',
        replacements: [{
          from: '<!-- include:lowla -->',
          to: '' + grunt.config('lowla')
        }]
      }
    },

    watch : {

      scripts: {
        files: ['Gruntfile.js', 'src/**/*.js', 'src/**/*.html', 'src/**/*.css'],
        tasks: ['default'],
        options: {
          spawn: false,
        }
      }
    },

    uglify: {
      build: {
        files: {
          'dist/xcomponents.min.js': ['dist/xcomponents.js']
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-html2js');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-text-replace');

  // Default task(s).
  grunt.registerTask('default', [
    'clean:build',
    'html2js',
    'concat:js1',
    'concat:js2',
    'concat:js-libs',
    'copy:all',
    'replace:pouch',
    'replace:lowla',
    'uglify:build',
    'clean:tmp',
   ]);

};<|endoftext|>


<commit_before>module.exports = function(grunt) {
  var browserify = require('browserify-middleware');

  grunt.initConfig({
    coffeelint: {
      app: ['src/**/*.coffee'],
      specs: ['spec/**/*.coffee'],
      options: grunt.file.readJSON('.coffeelint.json')
    },

    coffee: {
      compile: {
        expand: true,
        cwd: 'src',
        src: ['**/*.coffee'],
        dest: 'lib',
        ext: '.js'
      }
    },

    browserify: {
      compile: {
        src: 'lib/index.js',
        dest: 'field-kit.js',
        options: {
          standalone: 'FieldKit',
          debug: false
        }
      }
    },

    uglify: {
      'field-kit.min.js': [ 'field-kit.js' ]
    },

    qunit: {
      all: {
        options: {
          urls: [
            'http://localhost:<%= connect.test.options.port %>/test'
          ]
        }
      }
    },

    connect: {
      test: {
        options: {
          port: process.env.PORT || 8000,
          base: '.',
          middleware: function(connect, options, middlewares) {
            var lib = browserify('./lib/index.js', grunt.config.get('browserify.compile.options'));
            var setup = browserify('./test/test_helper.js', { debug: false });

            middlewares.push(function(req, res, next) {
              switch (req.url) {
                case '/test/setup.js':
                  setup(req, res, next);
                  break;

                case '/test/all.js':
                  res.writeHead(200, { 'Content-Type': 'application/javascript' });
                  grunt.file.expand('test/**/*_test.js').forEach(function(path) {
                    res.write(grunt.file.read(path));
                  });
                  res.end();
                  break;

                case '/lib/field-kit.js':
                  lib(req, res, next);
                  break;

                default:
                  next();
                  break;
              }
            });

            return middlewares;
          }
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-coffeelint');
  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.registerTask('default', ['test']);
  grunt.registerTask('test', ['coffeelint', 'coffee', 'browserify', 'connect:test', 'qunit', 'uglify']);
  grunt.registerTask('develop', ['connect:test:keepalive']);
};
<commit_msg>Copy .js files from src to lib.<commit_after>module.exports = function(grunt) {
  var browserify = require('browserify-middleware');

  grunt.initConfig({
    coffeelint: {
      app: ['src/**/*.coffee'],
      specs: ['spec/**/*.coffee'],
      options: grunt.file.readJSON('.coffeelint.json')
    },

    coffee: {
      compile: {
        expand: true,
        cwd: 'src',
        src: ['**/*.coffee'],
        dest: 'lib',
        ext: '.js'
      }
    },

    copy: {
      source: {
        expand: true,
        cwd: 'src',
        src: ['**/*.js'],
        dest: 'lib'
      }
    },

    browserify: {
      compile: {
        src: 'lib/index.js',
        dest: 'field-kit.js',
        options: {
          standalone: 'FieldKit',
          debug: false
        }
      }
    },

    uglify: {
      'field-kit.min.js': [ 'field-kit.js' ]
    },

    qunit: {
      all: {
        options: {
          urls: [
            'http://localhost:<%= connect.test.options.port %>/test'
          ]
        }
      }
    },

    connect: {
      test: {
        options: {
          port: process.env.PORT || 8000,
          base: '.',
          middleware: function(connect, options, middlewares) {
            var lib = browserify('./lib/index.js', grunt.config.get('browserify.compile.options'));
            var setup = browserify('./test/test_helper.js', { debug: false });

            middlewares.push(function(req, res, next) {
              switch (req.url) {
                case '/test/setup.js':
                  setup(req, res, next);
                  break;

                case '/test/all.js':
                  res.writeHead(200, { 'Content-Type': 'application/javascript' });
                  grunt.file.expand('test/**/*_test.js').forEach(function(path) {
                    res.write(grunt.file.read(path));
                  });
                  res.end();
                  break;

                case '/lib/field-kit.js':
                  lib(req, res, next);
                  break;

                default:
                  next();
                  break;
              }
            });

            return middlewares;
          }
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-coffeelint');
  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.registerTask('default', ['test']);
  grunt.registerTask('test', ['coffeelint', 'coffee', 'copy', 'browserify', 'connect:test', 'qunit', 'uglify']);
  grunt.registerTask('develop', ['connect:test:keepalive']);
};
<|endoftext|>


<commit_before>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

import AbilityTracker from 'parser/shared/modules/AbilityTracker';

import Analyzer from 'parser/core/Analyzer';

class Icefury extends Analyzer {
  static dependencies = {
    abilityTracker: AbilityTracker,
  };

  empoweredFrostShockCasts = 0;

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTalent(SPELLS.ICEFURY_TALENT.id);
  }

  on_byPlayer_cast(event) {
    if (this.selectedCombatant.hasBuff(SPELLS.ICEFURY_TALENT.id)) {
      if (event.ability.guid === SPELLS.FROST_SHOCK.id) {
        this.empoweredFrostShockCasts++;
      }
    }
  }

  get suggestionThresholds() {
    return {
      actual: this.empoweredFrostShockCasts / this.abilityTracker.getAbility(SPELLS.ICEFURY_TALENT.id).casts,
      isLessThan: {
        minor: 4,
        average: 3.5,
        major: 3,
      },
      style: 'decimal',
    };
  }

  suggestions(when) {
    when(this.suggestionThresholds).addSuggestion((suggest, actual) => {
      return suggest(<>You should fully utilize your <SpellLink id={SPELLS.ICEFURY_TALENT.id} /> casts by casting 4 <SpellLink id={SPELLS.FROST_SHOCK.id} />s before the <SpellLink id={SPELLS.ICEFURY_TALENT.id} /> buff expires. Pay attention to the remaining duration of the buff to ensure you have time to use all of the stacks.</>)
      .icon(SPELLS.ICEFURY_TALENT.icon)
      .actual(<>On average, only {actual.toFixed(2)} <SpellLink id={SPELLS.ICEFURY_TALENT.id} />(s) stacks were consumed with  <SpellLink id={SPELLS.FROST_SHOCK.id} /> casts before <SpellLink id={SPELLS.ICEFURY_TALENT.id} /> buff expired.</>)
      .recommended(<>It's recommended to always consume all 4 stacks.</>);
    });
  }
}

export default Icefury;
<commit_msg>use new event listener format<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

import Events from 'parser/core/Events';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';

class Icefury extends Analyzer {
  static dependencies = {
    abilityTracker: AbilityTracker,
  };

  empoweredFrostShockCasts = 0;

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTalent(SPELLS.ICEFURY_TALENT.id);

    if (!this.active) {
      return;
    }

    this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.FROST_SHOCK), this.onFrostShockCast);
  }

  onFrostShockCast(event) {
    if (this.selectedCombatant.hasBuff(SPELLS.ICEFURY_TALENT.id)) {
      this.empoweredFrostShockCasts++;
    }
  }

  get suggestionThresholds() {
    return {
      actual: this.empoweredFrostShockCasts / this.abilityTracker.getAbility(SPELLS.ICEFURY_TALENT.id).casts,
      isLessThan: {
        minor: 4,
        average: 3.5,
        major: 3,
      },
      style: 'decimal',
    };
  }

  suggestions(when) {
    when(this.suggestionThresholds).addSuggestion((suggest, actual) => {
      return suggest(<>You should fully utilize your <SpellLink id={SPELLS.ICEFURY_TALENT.id} /> casts by casting 4 <SpellLink id={SPELLS.FROST_SHOCK.id} />s before the <SpellLink id={SPELLS.ICEFURY_TALENT.id} /> buff expires. Pay attention to the remaining duration of the buff to ensure you have time to use all of the stacks.</>)
      .icon(SPELLS.ICEFURY_TALENT.icon)
      .actual(<>On average, only {actual.toFixed(2)} <SpellLink id={SPELLS.ICEFURY_TALENT.id} />(s) stacks were consumed with  <SpellLink id={SPELLS.FROST_SHOCK.id} /> casts before <SpellLink id={SPELLS.ICEFURY_TALENT.id} /> buff expired.</>)
      .recommended(<>It's recommended to always consume all 4 stacks.</>);
    });
  }
}

export default Icefury;
<|endoftext|>


<commit_before>// Generated on 2015-07-14 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: 'bower_components/bootstrap/dist',
          src: 'fonts/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'copy:styles'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>解决grunt下的font awesome的问题<commit_after>// Generated on 2015-07-14 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: 'bower_components/bootstrap/dist',
          src: 'fonts/*',
          dest: '<%= yeoman.dist %>'
        }, {
          expand: true,
          cwd: 'bower_components/font-awesome',
          src: 'fonts/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'copy:styles'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>var container;

var camera, controls, scene, renderer, axes;

var cross;

var particleSystem;
var particles;
var particleCount;

init();
animate();

function init()
{

	camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 1000 );
	camera.position.x = 0;
	camera.position.y = -100;
	camera.position.z = 20;

	camera.lookAt(new THREE.Vector3( 1, 0, 0 ));

	controls = new THREE.TrackballControls( camera );

	controls.rotateSpeed = 1.0;
	controls.zoomSpeed = 1.2;
	controls.panSpeed = 0.8;

	controls.noZoom = false;
	controls.noPan = false;

	controls.staticMoving = true;
	controls.dynamicDampingFactor = 0.3;

	controls.keys = [ 65, 83, 68 ];

	controls.addEventListener( 'change', render );

	// world

	scene = new THREE.Scene();
	scene.fog = new THREE.FogExp2( 0x000000, 0.002 );

	axes = buildAxes( 10 );
	scene.add( axes );

	//x,y,z    x largeur y longeur, zhauteur
	var mountain1 = [10, 10, 20];
	var mountain2 = [20, 0, 20];

	var geometry = new THREE.PlaneGeometry( 100, 100, 100, 100 );

	geometry.vertices = generateMountain(geometry.vertices, mountain1, 100);

	var material = new THREE.MeshBasicMaterial({color: 0xcccccc, wireframe: true});
	var plane = new THREE.Mesh( geometry, material );
	scene.add( plane );
/**********************************************************/
/**********************************************************/
particleCount = 58000;
particles = new THREE.Geometry();
var pMaterial = new THREE.PointCloudMaterial({
  color: 0xFFFFFF,
  size: 1,
  map: THREE.ImageUtils.loadTexture(
    "water.png"
  )
});

// now create the individual particles
for (var p = 0; p < particleCount; p++)
{
	// create a particle with random
	// position values, -250 -> 250
	var pX = Math.random() * 100 - 50;
	var pY = Math.random() * 100 - 50;
	var pZ = 25;
	var particle = new THREE.Vector3(pX, pY, pZ);
	particle.velocity = new THREE.Vector3(0, 0, -0.5);
	// add it to the geometry
	particles.vertices.push(particle);
}

// create the particle system
particleSystem = new THREE.PointCloud( particles, pMaterial);
particleSystem.sortParticles = true;
particleSystem.geometry.verticesNeedUpdate = true;
// add it to the scene
scene.add(particleSystem);

/**********************************************************/
/**********************************************************/

	// lights

	light = new THREE.DirectionalLight( 0xffffff );
	light.position.set( 1, 1, 1 );
	scene.add( light );

	light = new THREE.DirectionalLight( 0x002288 );
	light.position.set( -1, -1, -1 );
	scene.add( light );

	light = new THREE.AmbientLight( 0x222222 );
	scene.add( light );

	// renderer

	renderer = new THREE.WebGLRenderer( { antialias: false } );
	renderer.setClearColor( scene.fog.color );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );

	container = document.body;
	container.appendChild( renderer.domElement );

	window.addEventListener( 'resize', onWindowResize, false );

	render();
}

function onWindowResize()
{
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );

	controls.handleResize();

	render();
}

function animate()
{
	requestAnimationFrame( animate );
	controls.update();
	render();
}

function render()
{
	var pCount = 100;

	while (pCount--) {

		// get the particle
		var particle = particles.vertices[pCount];
		// check if we need to reset
		if (particle.z < 0)
		{
			particle.z = 200;
		}
		particle.velocity.z -= Math.random() * .1;
		particle.z -= 1;
	}
	// particleSystem.geometry.__dirtyVertices = true;
	renderer.render( scene, camera );
}

function buildAxes( length )
{
        var axes = new THREE.Object3D();

        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( length, 0, 0 ), 0xFF0000, false ) ); // +X
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( -length, 0, 0 ), 0xFF0000, true) ); // -X
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, length, 0 ), 0x00FF00, false ) ); // +Y
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, -length, 0 ), 0x00FF00, true ) ); // -Y
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, length ), 0x0000FF, false ) ); // +Z
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, -length ), 0x0000FF, true ) ); // -Z

        return axes;

}

function buildAxis( src, dst, colorHex, dashed ) {
	var geom = new THREE.Geometry(),
		mat;

	if(dashed) {
		mat = new THREE.LineDashedMaterial({ linewidth: 3, color: colorHex, dashSize: 3, gapSize: 3 });
	} else {
		mat = new THREE.LineBasicMaterial({ linewidth: 3, color: colorHex });
	}

	geom.vertices.push( src.clone() );
	geom.vertices.push( dst.clone() );
	geom.computeLineDistances(); // This one is SUPER important, otherwise dashed lines will appear as simple plain lines

	var axis = new THREE.Line( geom, mat, THREE.LinePieces );

	return axis;

}

function generateMountain(vertices, mountain, div)
{
	var coefWidth = 1;
	var coefHeight = 0;
	for(var i = 0; i < vertices.length; i++)
	{
		if(vertices[i].x == mountain[0] && vertices[i].y == mountain[1])
		{
			vertices[i].z = 10;
			for ( var deg = 0; deg < 360; deg+= 0.1 )
			{
				for (var dist = 0; dist < mountain[2]; dist+= 0.1)
				{
					var x = Math.round(dist * Math.cos(Math.PI * deg / 180));
					var y = Math.round(dist * Math.sin(Math.PI * deg / 180));

					var tabIndex = i + x *(div+1) + y ;

					var ymid = mountain[2]/2;
					var ampl = mountain[2]/2;

					var heigh = ymid+coefHeight + ampl*coefWidth * Math.cos( Math.PI / mountain[2] * dist );

					if (vertices[tabIndex].z < heigh)
						vertices[tabIndex].z =  heigh;
				}
			}
		}
	}
	return vertices;
}
<commit_msg>moving particles<commit_after>var container;

var camera, controls, scene, renderer, axes;

var cross;

var particleSystem;
var particles;
var particleCount;

var clock = new THREE.Clock();

init();
animate();

function init()
{

	camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 1000 );
	camera.position.x = 0;
	camera.position.y = -100;
	camera.position.z = 20;

	camera.lookAt(new THREE.Vector3( 1, 0, 0 ));

	controls = new THREE.TrackballControls( camera );

	controls.rotateSpeed = 1.0;
	controls.zoomSpeed = 1.2;
	controls.panSpeed = 0.8;

	controls.noZoom = false;
	controls.noPan = false;

	controls.staticMoving = true;
	controls.dynamicDampingFactor = 0.3;

	controls.keys = [ 65, 83, 68 ];

	controls.addEventListener( 'change', render );

	// world

	scene = new THREE.Scene();
	scene.fog = new THREE.FogExp2( 0x000000, 0.002 );

	axes = buildAxes( 10 );
	scene.add( axes );

	//x,y,z    x largeur y longeur, zhauteur
	var mountain1 = [10, 10, 20];
	var mountain2 = [20, 0, 20];

	var geometry = new THREE.PlaneGeometry( 100, 100, 100, 100 );

	geometry.vertices = generateMountain(geometry.vertices, mountain1, 100);

	var material = new THREE.MeshBasicMaterial({color: 0xcccccc, wireframe: true});
	var plane = new THREE.Mesh( geometry, material );
	scene.add( plane );
/**********************************************************/
/**********************************************************/
particleCount = 58000;
particles = new THREE.Geometry();
var pMaterial = new THREE.PointCloudMaterial({
  color: 0xFFFFFF,
  size: 1,
  map: THREE.ImageUtils.loadTexture(
    "water.png"
  )
});

// now create the individual particles
for (var p = 0; p < particleCount; p++)
{
	// create a particle with random
	// position values, -250 -> 250
	var pX = Math.random() * 100 - 50;
	var pY = Math.random() * 100 - 50;
	var pZ = 25;
	var particle = new THREE.Vector3(pX, pY, pZ);
	particle.velocity = new THREE.Vector3(0, 0, -0.5);
	// add it to the geometry
	particles.vertices.push(particle);
}

// create the particle system
particleSystem = new THREE.PointCloud( particles, pMaterial);
particleSystem.sortParticles = true;
particleSystem.geometry.verticesNeedUpdate = true;
// add it to the scene
scene.add(particleSystem);

/**********************************************************/
/**********************************************************/

	// lights

	light = new THREE.DirectionalLight( 0xffffff );
	light.position.set( 1, 1, 1 );
	scene.add( light );

	light = new THREE.DirectionalLight( 0x002288 );
	light.position.set( -1, -1, -1 );
	scene.add( light );

	light = new THREE.AmbientLight( 0x222222 );
	scene.add( light );

	// renderer

	renderer = new THREE.WebGLRenderer( { antialias: false } );
	renderer.setClearColor( scene.fog.color );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );

	container = document.body;
	container.appendChild( renderer.domElement );

	window.addEventListener( 'resize', onWindowResize, false );

	render();
}

function onWindowResize()
{
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );

	controls.handleResize();

	render();
}

function animate()
{
	requestAnimationFrame( animate );
	controls.update();
	render();
}

function render()
{
	// var delta = clock.getDelta()
	// var t = clock.getElapsedTime() * 0.5;
	var pCount = 100;

	while (pCount--) {

		// get the particle
		var particle = particles.vertices[pCount];
		// check if we need to reset
		if (particle.z < 0)
		{
			particle.z = 200;
		}
		particle.velocity.z -= Math.random() * .1;
		particle.z -= 0.01;
	}
	particleSystem.geometry.verticesNeedUpdate = true;
	// particleSystem.geometry.__dirtyVertices = true;
	renderer.render( scene, camera );
}

function buildAxes( length )
{
        var axes = new THREE.Object3D();

        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( length, 0, 0 ), 0xFF0000, false ) ); // +X
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( -length, 0, 0 ), 0xFF0000, true) ); // -X
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, length, 0 ), 0x00FF00, false ) ); // +Y
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, -length, 0 ), 0x00FF00, true ) ); // -Y
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, length ), 0x0000FF, false ) ); // +Z
        axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, -length ), 0x0000FF, true ) ); // -Z

        return axes;

}

function buildAxis( src, dst, colorHex, dashed ) {
	var geom = new THREE.Geometry(),
		mat;

	if(dashed) {
		mat = new THREE.LineDashedMaterial({ linewidth: 3, color: colorHex, dashSize: 3, gapSize: 3 });
	} else {
		mat = new THREE.LineBasicMaterial({ linewidth: 3, color: colorHex });
	}

	geom.vertices.push( src.clone() );
	geom.vertices.push( dst.clone() );
	geom.computeLineDistances(); // This one is SUPER important, otherwise dashed lines will appear as simple plain lines

	var axis = new THREE.Line( geom, mat, THREE.LinePieces );

	return axis;

}

function generateMountain(vertices, mountain, div)
{
	var coefWidth = 1;
	var coefHeight = 0;
	for(var i = 0; i < vertices.length; i++)
	{
		if(vertices[i].x == mountain[0] && vertices[i].y == mountain[1])
		{
			vertices[i].z = 10;
			for ( var deg = 0; deg < 360; deg+= 0.1 )
			{
				for (var dist = 0; dist < mountain[2]; dist+= 0.1)
				{
					var x = Math.round(dist * Math.cos(Math.PI * deg / 180));
					var y = Math.round(dist * Math.sin(Math.PI * deg / 180));

					var tabIndex = i + x *(div+1) + y ;

					var ymid = mountain[2]/2;
					var ampl = mountain[2]/2;

					var heigh = ymid+coefHeight + ampl*coefWidth * Math.cos( Math.PI / mountain[2] * dist );

					if (vertices[tabIndex].z < heigh)
						vertices[tabIndex].z =  heigh;
				}
			}
		}
	}
	return vertices;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
import http from 'q-io/http';
import fs from 'q-io/fs';
import { exec } from 'child_process';
import os from 'os';

const gitPath = Promise.resolve('git');
const home = process.platform === 'darwin' ? process.env.HOME : process.env.HOMEDRIVE + process.env.HOMEPATH;

const configFileName = '.clonejs';

Promise.resolve(process.argv)
  .then(([, , project, flag]) => {
    if (!project) return readLeeroyConfig();
    else if (flag === '--save') return createLeeroyConfig(project);
    else return project;
  })
  .then(configName => {
    if (!configName) throw new Error('Usage: clone-leeroy CONFIGNAME [--save]');

    console.log(`Getting ${configName}`);
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    return http.read(`https://git/raw/Build/Configuration/master/${configName}.json`)
      .catch(() => {
        throw new Error(`Couldn't download Leeroy config file: ${configName}`);
      });
  })
  .then(data => {
    const config = JSON.parse(data);
    if (!config.submodules) throw new Error(`Leeroy config file is missing 'submodules' configuration.`);
    return config;
  })
  .then(config => {
    const createPromise = createSolutionInfos();
    return createPromise.then(() => {
      const promises = Object.keys(config.submodules).map(name => processSubmodule(name, config));
      return Promise.all(promises);
    });
  })
  .catch(error => {
    console.error('\x1b[31m' + (error.message || `Error: ${error}`) + '\x1b[0m');
    process.exitCode = 1;
  });

function readLeeroyConfig() {
  return fs.read(configFileName)
    .then(content => {
      const settings = JSON.parse(content);
      return settings.leeroyConfig;
    })
    .catch(() => null);
}

function createLeeroyConfig(project) {
  const settings = { leeroyConfig: project };
  return fs.write(configFileName, JSON.stringify(settings))
    .then(() => project);
}

function createSolutionInfos() {
  const solutionInfos = [{
    name: 'SolutionInfo.cs',
    data: `using System.Reflection;

[assembly: AssemblyVersion("9.99.0.0")]
[assembly: AssemblyCompany("Faithlife")]
[assembly: AssemblyCopyright("Copyright 2015 Faithlife")]
[assembly: AssemblyDescription("Local Build")]
`
  },
  {
    name: 'SolutionInfo.h',
    data: `#pragma once

#define ASSEMBLY_VERSION_MAJOR 9
#define ASSEMBLY_VERSION_MINOR 99
#define ASSEMBLY_VERSION_BUILD 0
#define ASSEMBLY_VERSION_MAJOR_MINOR_BUILD 1337
#define ASSEMBLY_VERSION_REVISION 0
#define ASSEMBLY_VERSION_STRING "9.99.0.0"

#define ASSEMBLY_COMPANY "Faithlife"
#define ASSEMBLY_COPYRIGHT "Copyright 2015 Faithlife"
`
  }];

  return Promise.all(solutionInfos.map(info => fs.exists(info.name)
    .then(exists => {
      if (!exists) return fs.write(info.name, info.data);
    })
  ));
}

function processSubmodule(name, config) {
  const branch = config.submodules[name];

  const [owner, repo] = name.split('/');
  const submodule = {
    _logs: [],
    owner,
    repo,
    branch,
    remoteUrl: `git@git:${owner}/${repo}.git`,
    log(message, indent=0) { this._logs = this._logs.concat(message.split(/\r?\n/).map((line) => { return Array(indent + 1).join(' ') + line; })); },
    output() { return this._logs.join(os.EOL); }
  };
  submodule.log(`Processing ${name}`);

  return fs.exists(submodule.repo)
    .then(exists =>
      !exists ?
        clone(submodule) :
        checkRemote(submodule)
          .then(() => fetchOrigin(submodule))
          .then(() => checkBranch(submodule))
          .then(() => pull(submodule))
    )
    .then(() => {
      console.log(submodule.output());
    }).catch(error => {
        submodule.log(error.message || error, 2);
        return Promise.reject(submodule.output());
    });
}

function clone(submodule) {
  submodule.log(`Directory ${submodule.repo} does not exist; cloning it.`, 2);
  return exec_git(`clone --recursive --branch ${submodule.branch} ${submodule.remoteUrl}`, {});
}

function checkRemote(submodule) {
  return exec_git('config --get remote.origin.url', { cwd: submodule.repo })
    .then(currentRemoteUrl => {
      if (currentRemoteUrl !== submodule.remoteUrl) {
        submodule.log(`Changing origin URL from ${currentRemoteUrl} to ${submodule.remoteUrl}`, 2);
        return changeRemoteUrl(submodule);
      }
    });
}

function changeRemoteUrl(submodule) {
  return exec_git('remote rm origin', { cwd: submodule.repo })
    .then(() => exec_git(`remote add origin ${submodule.remoteUrl}`, { cwd: submodule.repo }));
}

function fetchOrigin(submodule) {
  submodule.log('Fetching commits from origin...', 2);
  return exec_git('fetch origin', { cwd: submodule.repo });
}

function checkBranch(submodule) {
  return exec_git('symbolic-ref --short -q HEAD', { cwd: submodule.repo })
    .then(currentBranch => {
      if (currentBranch !== submodule.branch) {
        submodule.log(`Switching branches from ${currentBranch} to ${submodule.branch}`, 2);
        return exec_git(`branch --list -q --no-color ${submodule.branch}`, { cwd: submodule.repo })
          .then(existingTargetBranch => {
            if (existingTargetBranch !== submodule.branch) {
              return exec_git(`checkout -B ${submodule.branch} --track origin/${submodule.branch}`, { cwd: submodule.repo });
            } else {
              return exec_git(`checkout ${submodule.branch}`, { cwd: submodule.repo });
            }
          });
        }
      });
}

function pull(submodule) {
  return exec_git(`pull --rebase origin ${submodule.branch}`, { cwd: submodule.repo })
    .then(pullOutput => Promise.all([pullOutput, exec_git('submodule update --init --recursive', { cwd: submodule.repo })]))
    .then(([pullOutput]) => {
        submodule.log(`${pullOutput}`, 2);
      });
}

function exec_git(args, options) {
  options.env = options.env || {};
  options.env.HOME = home;

  // Might be necessary on Mac OS X to set SSH_AUTH_SOCK if user
  // has configured SSH Agent Forwarding
  // See https://help.github.com/articles/using-ssh-agent-forwarding
  options.env.SSH_AUTH_SOCK = process.env.SSH_AUTH_SOCK;
  return gitPath.then(path =>
    new Promise((resolve, reject) => {
      exec(`${path} ${args}`, options, (error, stdout) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout.toString().trim());
        }
      });
  }));
}
<commit_msg>Support URLs and file paths for reading configs (#6)<commit_after>#!/usr/bin/env node
import http from 'q-io/http';
import fs from 'q-io/fs';
import { exec } from 'child_process';
import os from 'os';

const gitPath = Promise.resolve('git');
const home = process.platform === 'darwin' ? process.env.HOME : process.env.HOMEDRIVE + process.env.HOMEPATH;

const configFileName = '.clonejs';

Promise.resolve(process.argv)
  .then(([, , project, ...flags]) => {
    const parsedFlags = parseFlags(flags);
    if (!project) return readLeeroyConfig();
    else if (parsedFlags.save) return createLeeroyConfig(project);
    else return project;
  })
  .then(project => {
    if (!project) throw new Error('Usage: clone-leeroy [CONFIGNAME, file, url] [--save]');
    return fetchProjectConfiguration(project)
      .catch(() => { throw new Error(`Couldn't get Leeroy config file`); });
  })
  .then(data => {
    const config = JSON.parse(data);
    if (!config.submodules) throw new Error(`Leeroy config file is missing 'submodules' configuration.`);
    return config;
  })
  .then(config => {
    const createPromise = createSolutionInfos();
    return createPromise.then(() => {
      const promises = Object.keys(config.submodules).map(name => processSubmodule(name, config));
      return Promise.all(promises);
    });
  })
  .catch(error => {
    console.error('\x1b[31m' + (error.message || `Error: ${error}`) + '\x1b[0m');
    process.exitCode = 1;
  });

function readLeeroyConfig() {
  return fs.read(configFileName)
    .then(content => {
      const settings = JSON.parse(content);
      return settings.leeroyConfig;
    })
    .catch(() => null);
}

function createLeeroyConfig(project) {
  const settings = { leeroyConfig: project };
  return fs.write(configFileName, JSON.stringify(settings))
    .then(() => project);
}

function createSolutionInfos() {
  const solutionInfos = [{
    name: 'SolutionInfo.cs',
    data: `using System.Reflection;

[assembly: AssemblyVersion("9.99.0.0")]
[assembly: AssemblyCompany("Faithlife")]
[assembly: AssemblyCopyright("Copyright 2015 Faithlife")]
[assembly: AssemblyDescription("Local Build")]
`
  },
  {
    name: 'SolutionInfo.h',
    data: `#pragma once

#define ASSEMBLY_VERSION_MAJOR 9
#define ASSEMBLY_VERSION_MINOR 99
#define ASSEMBLY_VERSION_BUILD 0
#define ASSEMBLY_VERSION_MAJOR_MINOR_BUILD 1337
#define ASSEMBLY_VERSION_REVISION 0
#define ASSEMBLY_VERSION_STRING "9.99.0.0"

#define ASSEMBLY_COMPANY "Faithlife"
#define ASSEMBLY_COPYRIGHT "Copyright 2015 Faithlife"
`
  }];

  return Promise.all(solutionInfos.map(info => fs.exists(info.name)
    .then(exists => {
      if (!exists) return fs.write(info.name, info.data);
    })
  ));
}

function processSubmodule(name, config) {
  const branch = config.submodules[name];

  const [owner, repo] = name.split('/');
  const submodule = {
    _logs: [],
    owner,
    repo,
    branch,
    remoteUrl: `git@git:${owner}/${repo}.git`,
    log(message, indent=0) { this._logs = this._logs.concat(message.split(/\r?\n/).map((line) => { return Array(indent + 1).join(' ') + line; })); },
    output() { return this._logs.join(os.EOL); }
  };
  submodule.log(`Processing ${name}`);

  return fs.exists(submodule.repo)
    .then(exists =>
      !exists ?
        clone(submodule) :
        checkRemote(submodule)
          .then(() => fetchOrigin(submodule))
          .then(() => checkBranch(submodule))
          .then(() => pull(submodule))
    )
    .then(() => {
      console.log(submodule.output());
    }).catch(error => {
        submodule.log(error.message || error, 2);
        return Promise.reject(submodule.output());
    });
}

function clone(submodule) {
  submodule.log(`Directory ${submodule.repo} does not exist; cloning it.`, 2);
  return exec_git(`clone --recursive --branch ${submodule.branch} ${submodule.remoteUrl}`, {});
}

function checkRemote(submodule) {
  return exec_git('config --get remote.origin.url', { cwd: submodule.repo })
    .then(currentRemoteUrl => {
      if (currentRemoteUrl !== submodule.remoteUrl) {
        submodule.log(`Changing origin URL from ${currentRemoteUrl} to ${submodule.remoteUrl}`, 2);
        return changeRemoteUrl(submodule);
      }
    });
}

function changeRemoteUrl(submodule) {
  return exec_git('remote rm origin', { cwd: submodule.repo })
    .then(() => exec_git(`remote add origin ${submodule.remoteUrl}`, { cwd: submodule.repo }));
}

function fetchOrigin(submodule) {
  submodule.log('Fetching commits from origin...', 2);
  return exec_git('fetch origin', { cwd: submodule.repo });
}

function checkBranch(submodule) {
  return exec_git('symbolic-ref --short -q HEAD', { cwd: submodule.repo })
    .then(currentBranch => {
      if (currentBranch !== submodule.branch) {
        submodule.log(`Switching branches from ${currentBranch} to ${submodule.branch}`, 2);
        return exec_git(`branch --list -q --no-color ${submodule.branch}`, { cwd: submodule.repo })
          .then(existingTargetBranch => {
            if (existingTargetBranch !== submodule.branch) {
              return exec_git(`checkout -B ${submodule.branch} --track origin/${submodule.branch}`, { cwd: submodule.repo });
            } else {
              return exec_git(`checkout ${submodule.branch}`, { cwd: submodule.repo });
            }
          });
        }
      });
}

function pull(submodule) {
  return exec_git(`pull --rebase origin ${submodule.branch}`, { cwd: submodule.repo })
    .then(pullOutput => Promise.all([pullOutput, exec_git('submodule update --init --recursive', { cwd: submodule.repo })]))
    .then(([pullOutput]) => {
        submodule.log(`${pullOutput}`, 2);
      });
}

function exec_git(args, options) {
  options.env = options.env || {};
  options.env.HOME = home;

  // Might be necessary on Mac OS X to set SSH_AUTH_SOCK if user
  // has configured SSH Agent Forwarding
  // See https://help.github.com/articles/using-ssh-agent-forwarding
  options.env.SSH_AUTH_SOCK = process.env.SSH_AUTH_SOCK;
  return gitPath.then(path =>
    new Promise((resolve, reject) => {
      exec(`${path} ${args}`, options, (error, stdout) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout.toString().trim());
        }
      });
  }));
}

function parseFlags(flags) {
  // --save
  const parsedFlags = {};
  for (let flagIndex = 0; flagIndex < (flags || []).length; flagIndex++) {
    const flag = flags[flagIndex];
    const flagName = flag.startsWith('--') ? flag.substring(2) : null;
    if (flagName === 'save') {
      parsedFlags.save = true;
    }
    else {
      parsedFlags[flagName] = flags[++flagIndex];
    }
  }
  return parsedFlags;
}

function fetchProjectConfiguration(projectish) {
  return new Promise( (resolve, reject) => {
    fs.exists(projectish).then( fileExists => {
      if (fileExists)
      {
        fs.read(projectish).then( data => {
          console.log(`Read configuration from ${projectish}`);
          resolve(data);
        });
        return;
      }

      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
      http
        .read(projectish)
        .then(data => {
          console.log(`Read configuration from ${projectish}`);
          resolve(data);
        })
        .catch(() => {
          const url = `https://git/raw/Build/Configuration/master/${projectish}.json`;
          http
            .read(url)
            .then(data => {
              console.log(`Read configuration from ${url}`);
              resolve(data);
            })
            .catch(reject);
        });
    });
  });
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Checkbox from '../checkbox';
import Translation from '../../../behaviours/translation';

/**
 * SelectCheckbox component.
 */
@Translation
class SelectCheckbox extends Component {

    /**
     * Display name.
     */
    static displayName = 'SelectCheckbox';

    /**
     * PropTypes.
     */
    static propTypes = {
        values: PropTypes.array,
        value: PropTypes.array,
        valueKey: PropTypes.string,
        labelKey: PropTypes.string,
        onChange: PropTypes.func,
        legacyOnChange: PropTypes.bool
    };

    /**
     * Default props.
     */
    static defaultProps = {
        values: [], // all values
        value: [], // selected values list
        valueKey: 'value', // key for the displayed value
        labelKey: 'label', // key for the displayed label
        onChange: undefined,
        legacyOnChange: false
    };

    /**
     * Initial state.
     */
    state = {
        selectedValues: this.props.value
    };

    /**
     * React componentWillReceiveProps hook.
     * @param {object} newProps new props.
     */
    componentWillReceiveProps(newProps) {
        if (newProps) {
            this.setState({ selectedValues: newProps.value });
        }
    }

    /**
    * Get the value from the select in the DOM.
    * @return {string} value
    */
    getValue() {
        return this.state.selectedValues;
    }

    /**
     * Handle a change of value.
     * @param  {[type]} key       the key
     * @param  {[type]} newStatus the new status
     */
    _handleCheckboxChange(key, newStatus) {
        const selectedValues = newStatus
            ? this.state.selectedValues.concat([key])
            : this.state.selectedValues.filter(elt => elt !== key);

        if (this.props.onChange && this.props.legacyOnChange) {
            this.props.onChange(key, newStatus);
        } else if (this.props.onChange) {
            this.props.onChange(selectedValues);
        } else {
            this.setState({ selectedValues });
        }
    }

    /**
     * Closure to capture key and checbox status.
     * @param  {[type]} key the key of checkbox
     * @return {[type]} status closure
     */
    _getCheckboxChangeHandler(key) {
        return (status) => {
            this._handleCheckboxChange(key, status);
        };
    }

    /**
     * Render all selection checkbox.
     * @return {ReactDOMNode} list of ReactDomNode
     */
    renderCheckboxes() {
        return this.props.values.map((val, idx) => {
            const value = val[this.props.valueKey];
            const label = val[this.props.labelKey];
            const isChecked = 0 <= this.state.selectedValues.indexOf(value);
            return (
                <Checkbox key={idx} label={this.i18n(label)} onChange={this._getCheckboxChangeHandler(value)} value={isChecked} />
            );
        });
    }

    /**
     * Render.
     * @return {ReactElement} markup.
     */
    render() {
        return (

                {this.renderCheckboxes()}

        );
    }
}

export default SelectCheckbox;
<commit_msg>SelectCheckbox - Making sure selectedValues is an array<commit_after>import React, { Component, PropTypes } from 'react';
import Checkbox from '../checkbox';
import Translation from '../../../behaviours/translation';

/**
 * SelectCheckbox component.
 */
@Translation
class SelectCheckbox extends Component {

    /**
     * Display name.
     */
    static displayName = 'SelectCheckbox';

    /**
     * PropTypes.
     */
    static propTypes = {
        values: PropTypes.array,
        value: PropTypes.array,
        valueKey: PropTypes.string,
        labelKey: PropTypes.string,
        onChange: PropTypes.func,
        legacyOnChange: PropTypes.bool
    };

    /**
     * Default props.
     */
    static defaultProps = {
        values: [], // all values
        value: [], // selected values list
        valueKey: 'value', // key for the displayed value
        labelKey: 'label', // key for the displayed label
        onChange: undefined,
        legacyOnChange: false
    };

    /**
     * Initial state.
     */
    state = {
        selectedValues: this.props.value
    };

    /**
     * React componentWillReceiveProps hook.
     * @param {object} newProps new props.
     */
    componentWillReceiveProps({value}) {
        this.setState({ selectedValues: value || [] });
    }

    /**
    * Get the value from the select in the DOM.
    * @return {string} value
    */
    getValue() {
        return this.state.selectedValues;
    }

    /**
     * Handle a change of value.
     * @param  {[type]} key       the key
     * @param  {[type]} newStatus the new status
     */
    _handleCheckboxChange(key, newStatus) {
        const selectedValues = newStatus
            ? this.state.selectedValues.concat([key])
            : this.state.selectedValues.filter(elt => elt !== key);

        if (this.props.onChange && this.props.legacyOnChange) {
            this.props.onChange(key, newStatus);
        } else if (this.props.onChange) {
            this.props.onChange(selectedValues);
        } else {
            this.setState({ selectedValues });
        }
    }

    /**
     * Closure to capture key and checbox status.
     * @param  {[type]} key the key of checkbox
     * @return {[type]} status closure
     */
    _getCheckboxChangeHandler(key) {
        return (status) => {
            this._handleCheckboxChange(key, status);
        };
    }

    /**
     * Render all selection checkbox.
     * @return {ReactDOMNode} list of ReactDomNode
     */
    renderCheckboxes() {
        return this.props.values.map((val, idx) => {
            const value = val[this.props.valueKey];
            const label = val[this.props.labelKey];
            const isChecked = 0 <= this.state.selectedValues.indexOf(value);
            return (
                <Checkbox key={idx} label={this.i18n(label)} onChange={this._getCheckboxChangeHandler(value)} value={isChecked} />
            );
        });
    }

    /**
     * Render.
     * @return {ReactElement} markup.
     */
    render() {
        return (

                {this.renderCheckboxes()}

        );
    }
}

export default SelectCheckbox;
<|endoftext|>