<commit_before>'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });

var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadNpmTasks('assemble');

  // configurable paths
  var config = {
    app: 'app',
    dist: 'public'
  };

  grunt.initConfig({
    config: config,
    watch: {
      grunt: {
        files: ['Gruntfile.js'],
        options: { reload: true }
      },
      assemble: {
        files: [ '<%= config.app %>/templates/{,*/}*.{hbs,html}' ],
        tasks: [ 'assemble:server' ]
      },
      sass: {
        files: [ '<%= config.app %>/styles/{,*/}*.{scss,sass}' ],
        tasks: [ 'sass:server' ]
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '{.tmp,<%= config.app %>/views}/{,*/}*.html',
          '{.tmp,<%= config.app %>}/styles/{,*/}*.css',
          '{.tmp,<%= config.app %>}/scripts/{,*/}*.js',
          '<%= config.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, config.app)
            ];
          }
        }
      },
// 			test: {
// 				options: {
// 					middleware: function (connect) {
// 						return [
// 							mountFolder(connect, '.tmp'),
// 							mountFolder(connect, 'test')
// 						];
// 					}
// 				}
// 			},
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, config.dist)
            ];
          }
        }
      }
    },
    clean: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.dist %>',
          src: [
            '*'
          ]
        }]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= config.app %>/scripts/{,*/}*.js'
      ]
    },
    assemble: {
      options: {
        layoutdir: '<%= config.app %>/templates/layouts'
      },
      server: {
        options: {
          collections: [{
            name: 'posted',
            inflection: 'post',
            sortby: 'posted',
            sortorder: 'descending'
          }]
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/templates',
          src: '**/*.hbs',
          dest: '.tmp'
        }]
      },
      dist: {
        options: {
          collections: [{
            name: 'posted',
            inflection: 'post',
            sortby: 'posted',
            sortorder: 'descending'
          }]
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/templates',
          src: '**/*.hbs',
          dest: '<%= config.dist %>'
        }]
      }
    },
    sass: {
      dist: {
        files: {
          '.tmp/styles/main.css': '<%= config.app %>/styles/main.scss'
        }
      },
      server: {
        files: {
          '.tmp/styles/main.css': '<%= config.app %>/styles/main.scss'
        }
      }
    },
    rev: {
      dist: {
        files: {
          src: [
            '<%= config.dist %>/scripts/{,*/}*.js',
            '<%= config.dist %>/styles/{,*/}*.css',
            '<%= config.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= config.dist %>/styles/fonts/*'
          ]
        }
      }
    },
    useminPrepare: {
      html: [
        //'<%= config.dist %>/{,*/}*.{html,hbs}'
        '<%= config.dist %>/{,*/}index.html'
      ],
      options: {
        dest: '<%= config.dist %>'
      }
    },
    usemin: {
      html: ['<%= config.dist %>/{,*/}*.html'],
      css: ['<%= config.dist %>/styles/{,*/}*.css'],
      js: ['<%= config.dist %>/scripts/*.js'],
      options: {
        assetsDirs: [
          '<%= config.dist %>',
          '<%= config.dist %>/images'
        ],
        patterns: {
          js: [
            [/(images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm]
          ]
        }
      }
    },
    imagemin: {
      dist: {
        options: {
          cache: false
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= config.dist %>/images'
        }]
      }
    },
    htmlmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= config.dist %>',
          src: ['*.html', 'views/*.html'],
          dest: '<%= config.dist %>'
        }]
      }
    },
    copy: {
      dev: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>/dev',
          dest: '<%= config.dist %>',
          src: [
            'CNAME',
            '*.*'
          ]
        }]
      },
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>',
          dest: '<%= config.dist %>',
          src: [
            'CNAME',
            '*.*',
            //'bower_components/**/*',
            'bower_components/font-awesome/**/*',
            'images/{,*/}*.*',
            'styles/fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= config.dist %>/images',
          src: [
            'generated/*'
          ]
        }]
      }
    },
    concurrent: {
      server: [
        'sass:server',
        'assemble:server'
      ],
// 			test: [
// 				'sass'
// 			],
      dist: [
        'sass:dist',
        'assemble:dist'
      ]
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    },
    ngtemplates: {
      dist: {
        options: {
          usemin: '<%= config.dist %>/scripts/app.js',
          module: 'businessCardMaker'
        },
        cwd: '<%= config.app %>',
        src: 'views/{,*/}*.html',
        dest: '.tmp/scripts/templates.js'
      }
    },
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    'ftp-deploy': {
      development: {
        auth: {
          host: 'server134.web-hosting.com',
          authPath: 'deploy.json',
          authKey: 'namecheap'
        },
        src: '<%= config.dist %>',
        dest: './releases/development/'
      },
      staging: {
        auth: {
          host: 'server134.web-hosting.com',
          authPath: 'deploy.json',
          authKey: 'namecheap'
        },
        src: '<%= config.dist %>',
        dest: './releases/staging/'
      },
      www: {
        auth: {
          host: 'server134.web-hosting.com',
          authPath: 'deploy.json',
          authKey: 'namecheap'
        },
        src: '<%= config.dist %>',
        dest: './releases/www/'
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['default', 'connect:dist:keepalive']);
    }

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

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

  grunt.registerTask('build', [
    'clean:dist',
    'concurrent:dist',
    'imagemin',
    'htmlmin',
    'useminPrepare',
    'ngtemplates',
    'copy:dist',
    'concat',
    'ngAnnotate',
    'cssmin',
    'uglify',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'jshint',
    //'test',
    'build'
  ]);

  grunt.registerTask('deploy', function (target) {

    if (target === 'live') {
      return grunt.task.run([
        'default',
        'ftp-deploy:www'
      ]);
    }

    grunt.task.run([
      'default',
      'copy:dev',
      'ftp-deploy:development',
      'ftp-deploy:staging'
    ]);

  });

};
<commit_msg>Use uglify to drop console statements in the production build.<commit_after>'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });

var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadNpmTasks('assemble');

  // configurable paths
  var config = {
    app: 'app',
    dist: 'public'
  };

  grunt.initConfig({
    config: config,
    watch: {
      grunt: {
        files: ['Gruntfile.js'],
        options: { reload: true }
      },
      assemble: {
        files: [ '<%= config.app %>/templates/{,*/}*.{hbs,html}' ],
        tasks: [ 'assemble:server' ]
      },
      sass: {
        files: [ '<%= config.app %>/styles/{,*/}*.{scss,sass}' ],
        tasks: [ 'sass:server' ]
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '{.tmp,<%= config.app %>/views}/{,*/}*.html',
          '{.tmp,<%= config.app %>}/styles/{,*/}*.css',
          '{.tmp,<%= config.app %>}/scripts/{,*/}*.js',
          '<%= config.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, config.app)
            ];
          }
        }
      },
// 			test: {
// 				options: {
// 					middleware: function (connect) {
// 						return [
// 							mountFolder(connect, '.tmp'),
// 							mountFolder(connect, 'test')
// 						];
// 					}
// 				}
// 			},
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, config.dist)
            ];
          }
        }
      }
    },
    clean: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.dist %>',
          src: [
            '*'
          ]
        }]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= config.app %>/scripts/{,*/}*.js'
      ]
    },
    assemble: {
      options: {
        layoutdir: '<%= config.app %>/templates/layouts'
      },
      server: {
        options: {
          collections: [{
            name: 'posted',
            inflection: 'post',
            sortby: 'posted',
            sortorder: 'descending'
          }]
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/templates',
          src: '**/*.hbs',
          dest: '.tmp'
        }]
      },
      dist: {
        options: {
          collections: [{
            name: 'posted',
            inflection: 'post',
            sortby: 'posted',
            sortorder: 'descending'
          }]
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/templates',
          src: '**/*.hbs',
          dest: '<%= config.dist %>'
        }]
      }
    },
    sass: {
      dist: {
        files: {
          '.tmp/styles/main.css': '<%= config.app %>/styles/main.scss'
        }
      },
      server: {
        files: {
          '.tmp/styles/main.css': '<%= config.app %>/styles/main.scss'
        }
      }
    },
    rev: {
      dist: {
        files: {
          src: [
            '<%= config.dist %>/scripts/{,*/}*.js',
            '<%= config.dist %>/styles/{,*/}*.css',
            '<%= config.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= config.dist %>/styles/fonts/*'
          ]
        }
      }
    },
    useminPrepare: {
      html: [
        //'<%= config.dist %>/{,*/}*.{html,hbs}'
        '<%= config.dist %>/{,*/}index.html'
      ],
      options: {
        dest: '<%= config.dist %>'
      }
    },
    usemin: {
      html: ['<%= config.dist %>/{,*/}*.html'],
      css: ['<%= config.dist %>/styles/{,*/}*.css'],
      js: ['<%= config.dist %>/scripts/*.js'],
      options: {
        assetsDirs: [
          '<%= config.dist %>',
          '<%= config.dist %>/images'
        ],
        patterns: {
          js: [
            [/(images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm]
          ]
        }
      }
    },
    imagemin: {
      dist: {
        options: {
          cache: false
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= config.dist %>/images'
        }]
      }
    },
    htmlmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= config.dist %>',
          src: ['*.html', 'views/*.html'],
          dest: '<%= config.dist %>'
        }]
      }
    },
    copy: {
      dev: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>/dev',
          dest: '<%= config.dist %>',
          src: [
            'CNAME',
            '*.*'
          ]
        }]
      },
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>',
          dest: '<%= config.dist %>',
          src: [
            'CNAME',
            '*.*',
            //'bower_components/**/*',
            'bower_components/font-awesome/**/*',
            'images/{,*/}*.*',
            'styles/fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= config.dist %>/images',
          src: [
            'generated/*'
          ]
        }]
      }
    },
    concurrent: {
      server: [
        'sass:server',
        'assemble:server'
      ],
// 			test: [
// 				'sass'
// 			],
      dist: [
        'sass:dist',
        'assemble:dist'
      ]
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    },
    ngtemplates: {
      dist: {
        options: {
          usemin: '<%= config.dist %>/scripts/app.js',
          module: 'businessCardMaker'
        },
        cwd: '<%= config.app %>',
        src: 'views/{,*/}*.html',
        dest: '.tmp/scripts/templates.js'
      }
    },
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },
    uglify: {
      options: {
        compress: {
          drop_console: true
        }
      }
    },
    'ftp-deploy': {
      development: {
        auth: {
          host: 'server134.web-hosting.com',
          authPath: 'deploy.json',
          authKey: 'namecheap'
        },
        src: '<%= config.dist %>',
        dest: './releases/development/'
      },
      staging: {
        auth: {
          host: 'server134.web-hosting.com',
          authPath: 'deploy.json',
          authKey: 'namecheap'
        },
        src: '<%= config.dist %>',
        dest: './releases/staging/'
      },
      www: {
        auth: {
          host: 'server134.web-hosting.com',
          authPath: 'deploy.json',
          authKey: 'namecheap'
        },
        src: '<%= config.dist %>',
        dest: './releases/www/'
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['default', 'connect:dist:keepalive']);
    }

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

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

  grunt.registerTask('build', [
    'clean:dist',
    'concurrent:dist',
    'imagemin',
    'htmlmin',
    'useminPrepare',
    'ngtemplates',
    'copy:dist',
    'concat',
    'ngAnnotate',
    'cssmin',
    'uglify',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'jshint',
    //'test',
    'build'
  ]);

  grunt.registerTask('deploy', function (target) {

    if (target === 'live') {
      return grunt.task.run([
        'default',
        'ftp-deploy:www'
      ]);
    }

    grunt.task.run([
      'default',
      'copy:dev',
      'ftp-deploy:development',
      'ftp-deploy:staging'
    ]);

  });

};
<|endoftext|>


<commit_before>/*
 * Copyright 2013, All Rights Reserved.
 *
 * Code licensed under the BSD License:
 * https://github.com/eduardolundgren/dotfiles/blob/master/LICENSE.md
 *
 * @author Eduardo Lundgren <eduardo.lundgren@gmail.com>
 */

'use strict';

var userhome = require('userhome');

module.exports = function(grunt) {

    grunt.initConfig({

        // -- Bump -------------------------------------------------------------

        bump: {
            options: {
                commit: true,
                commitFiles: ['package.json'],
                commitMessage: 'Release v%VERSION%',
                createTag: true,
                files: ['package.json'],
                push: true,
                pushTo: 'origin',
                tagMessage: '',
                tagName: 'v%VERSION%'
            }
        },

        // -- Config -----------------------------------------------------------

        config: {

            git: {
                path_gitconfig: userhome('.gitconfig'),
                path_gitignore: userhome('.gitignore_global')
            },

            osx: {
                path_osx: userhome('.osx')
            },

            ruby: {
                path_build: userhome('.rbenv/plugins/ruby-build'),
                path_rbenv: userhome('.rbenv')
            },

            zsh: {
                path_oh_my_zsh: userhome('.oh-my-zsh'),
                path_syntax_highlighting: userhome('.oh-my-zsh/custom/plugins/zsh-syntax-highlighting'),
                path_z: userhome('.z'),
                path_zshrc: userhome('.zshrc')
            }

        },

        // -- Prompt -----------------------------------------------------------

        prompt: {
            config: {
                options: {
                    questions: [
                        {
                            config: 'config.osx.computername',
                            default: 'eduardo',
                            message: 'Which computer name would you like to use?'
                        },
                        {
                            config: 'config.osx.hostname',
                            default: 'eduardo',
                            message: 'Which hostname would you like to use?'
                        },
                        {
                            config: 'config.osx.localhostname',
                            default: 'eduardo',
                            message: 'Which local hostname would you like to use?'
                        },
                        {
                            config: 'config.osx.netbiosname',
                            default: 'eduardo',
                            message: 'Which netbios name would you like to use?'
                        },
                        {
                            config: 'config.git.name',
                            default: 'Eduardo Lundgren',
                            message: 'Which Git name would you like to use?'
                        },
                        {
                            config: 'config.git.email',
                            default: 'eduardo.lundgren@liferay.com',
                            message: 'Which Git email would you like to use?'
                        },
                        {
                            config: 'config.editor',
                            default: 'subl',
                            message: 'Which editor would you like to use?'
                        },
                        {
                            config: 'config.zsh.plugins',
                            default: 'ant git history-substring-search z zsh-syntax-highlighting',
                            message: 'Which Oh my zsh! plugins would you like to use (https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins)?'
                        },
                        {
                            config: 'config.zsh.theme_oh_my_zsh',
                            default: 'robbyrussell',
                            message: 'Which Oh my zsh! theme would you like to use (https://github.com/robbyrussell/oh-my-zsh/tree/master/themes)?'
                        }
                    ]
                }
            }
        },

        // -- Clean ------------------------------------------------------------

        clean: {

            all: {
                options: {
                    force: true
                },
                src: [
                    '<%= config.git.path_gitconfig %>',
                    '<%= config.git.path_gitignore %>',
                    '<%= config.osx.path_osx %>',
                    '<%= config.ruby.path_build %>',
                    '<%= config.ruby.path_rbenv %>',
                    '<%= config.zsh.path_syntax_highlighting %>',
                    '<%= config.zsh.path_oh_my_zsh %>',
                    '<%= config.zsh.path_zshrc %>'
                ]
            }

        },

        // -- Templates --------------------------------------------------------

        template: {

            git: {
                options: {
                    data: '<%= config %>'
                },
                files: {
                    '<%= config.git.path_gitconfig %>': ['templates/.gitconfig'],
                    '<%= config.git.path_gitignore %>': ['templates/.gitignore_global']
                }
            },

            osx: {
                options: {
                    data: '<%= config %>'
                },
                files: {
                    '<%= config.osx.path_osx %>': ['templates/.osx']
                }
            },

            zsh: {
                options: {
                    data: '<%= config %>'
                },
                files: {
                    '<%= config.zsh.path_zshrc %>': ['templates/.zshrc']
                }
            }

        },

        // -- Git --------------------------------------------------------------

        gitclone: {

            ruby_rbenv: {
                options: {
                    directory: '<%= config.ruby.path_rbenv %>',
                    repository: 'https://github.com/sstephenson/rbenv.git'
                }
            },

            ruby_build: {
                options: {
                    directory: '<%= config.ruby.path_build %>',
                    repository: 'https://github.com/sstephenson/ruby-build.git'
                }
            },

            oh_my_zsh: {
                options: {
                    directory: '<%= config.zsh.path_oh_my_zsh %>',
                    repository: 'https://github.com/robbyrussell/oh-my-zsh.git'
                }
            },

            zsh_syntax_highlighting: {
                options: {
                    directory: '<%= config.zsh.path_syntax_highlighting %>',
                    repository: 'https://github.com/zsh-users/zsh-syntax-highlighting.git'
                }
            }

        },

        // -- Symbolic links ---------------------------------------------------

        symlink: {

            sublime: {
                dest: '/usr/local/bin/subl',
                relativeSrc: '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl'
            }

        },

        // -- Exec -------------------------------------------------------------

        exec: {

            osx: {
                cmd: 'source <%= config.osx.path_osx %>'
            },

            zsh: {
                cmd: 'chsh -s /bin/zsh'
            },

            z: {
                cmd: 'touch <%= config.zsh.path_z %>'
            },

            node_latest: {
                cmd: 'n latest &> /dev/null'
            },

            node_stable: {
                cmd: 'n stable &> /dev/null'
            },

            ruby_compass: {
                cmd: 'gem install compass'
            },

            ruby_jekyll: {
                cmd: 'gem install jekyll'
            },

            ruby_update: {
                cmd: 'gem update --system'
            }

        }

    });

    grunt.loadNpmTasks('grunt-bump');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-git');
    grunt.loadNpmTasks('grunt-prompt');
    grunt.loadNpmTasks('grunt-symlink');
    grunt.loadNpmTasks('grunt-template');

    grunt.registerTask('setup', ['clean', 'prompt', 'template', 'gitclone', 'exec', 'symlink']);

};<commit_msg>Run grunt task without sudo in order to osx deafults take effect, invoke sudo when necessary<commit_after>/*
 * Copyright 2013, All Rights Reserved.
 *
 * Code licensed under the BSD License:
 * https://github.com/eduardolundgren/dotfiles/blob/master/LICENSE.md
 *
 * @author Eduardo Lundgren <eduardo.lundgren@gmail.com>
 */

'use strict';

var userhome = require('userhome');

module.exports = function(grunt) {

    grunt.initConfig({

        // -- Bump -------------------------------------------------------------

        bump: {
            options: {
                commit: true,
                commitFiles: ['package.json'],
                commitMessage: 'Release v%VERSION%',
                createTag: true,
                files: ['package.json'],
                push: true,
                pushTo: 'origin',
                tagMessage: '',
                tagName: 'v%VERSION%'
            }
        },

        // -- Config -----------------------------------------------------------

        config: {

            git: {
                path_gitconfig: userhome('.gitconfig'),
                path_gitignore: userhome('.gitignore_global')
            },

            osx: {
                path_osx: userhome('.osx')
            },

            ruby: {
                path_build: userhome('.rbenv/plugins/ruby-build'),
                path_rbenv: userhome('.rbenv')
            },

            zsh: {
                path_oh_my_zsh: userhome('.oh-my-zsh'),
                path_syntax_highlighting: userhome('.oh-my-zsh/custom/plugins/zsh-syntax-highlighting'),
                path_z: userhome('.z'),
                path_zshrc: userhome('.zshrc')
            }

        },

        // -- Prompt -----------------------------------------------------------

        prompt: {
            config: {
                options: {
                    questions: [
                        {
                            config: 'config.osx.computername',
                            default: 'eduardo',
                            message: 'Which computer name would you like to use?'
                        },
                        {
                            config: 'config.osx.hostname',
                            default: 'eduardo',
                            message: 'Which hostname would you like to use?'
                        },
                        {
                            config: 'config.osx.localhostname',
                            default: 'eduardo',
                            message: 'Which local hostname would you like to use?'
                        },
                        {
                            config: 'config.osx.netbiosname',
                            default: 'eduardo',
                            message: 'Which netbios name would you like to use?'
                        },
                        {
                            config: 'config.git.name',
                            default: 'Eduardo Lundgren',
                            message: 'Which Git name would you like to use?'
                        },
                        {
                            config: 'config.git.email',
                            default: 'eduardo.lundgren@liferay.com',
                            message: 'Which Git email would you like to use?'
                        },
                        {
                            config: 'config.editor',
                            default: 'subl',
                            message: 'Which editor would you like to use?'
                        },
                        {
                            config: 'config.zsh.plugins',
                            default: 'ant git history-substring-search z zsh-syntax-highlighting',
                            message: 'Which Oh my zsh! plugins would you like to use (https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins)?'
                        },
                        {
                            config: 'config.zsh.theme_oh_my_zsh',
                            default: 'robbyrussell',
                            message: 'Which Oh my zsh! theme would you like to use (https://github.com/robbyrussell/oh-my-zsh/tree/master/themes)?'
                        }
                    ]
                }
            }
        },

        // -- Clean ------------------------------------------------------------

        clean: {

            all: {
                options: {
                    force: true
                },
                src: [
                    '<%= config.git.path_gitconfig %>',
                    '<%= config.git.path_gitignore %>',
                    '<%= config.osx.path_osx %>',
                    '<%= config.ruby.path_build %>',
                    '<%= config.ruby.path_rbenv %>',
                    '<%= config.zsh.path_syntax_highlighting %>',
                    '<%= config.zsh.path_oh_my_zsh %>',
                    '<%= config.zsh.path_zshrc %>'
                ]
            }

        },

        // -- Templates --------------------------------------------------------

        template: {

            git: {
                options: {
                    data: '<%= config %>'
                },
                files: {
                    '<%= config.git.path_gitconfig %>': ['templates/.gitconfig'],
                    '<%= config.git.path_gitignore %>': ['templates/.gitignore_global']
                }
            },

            osx: {
                options: {
                    data: '<%= config %>'
                },
                files: {
                    '<%= config.osx.path_osx %>': ['templates/.osx']
                }
            },

            zsh: {
                options: {
                    data: '<%= config %>'
                },
                files: {
                    '<%= config.zsh.path_zshrc %>': ['templates/.zshrc']
                }
            }

        },

        // -- Git --------------------------------------------------------------

        gitclone: {

            ruby_rbenv: {
                options: {
                    directory: '<%= config.ruby.path_rbenv %>',
                    repository: 'https://github.com/sstephenson/rbenv.git'
                }
            },

            ruby_build: {
                options: {
                    directory: '<%= config.ruby.path_build %>',
                    repository: 'https://github.com/sstephenson/ruby-build.git'
                }
            },

            oh_my_zsh: {
                options: {
                    directory: '<%= config.zsh.path_oh_my_zsh %>',
                    repository: 'https://github.com/robbyrussell/oh-my-zsh.git'
                }
            },

            zsh_syntax_highlighting: {
                options: {
                    directory: '<%= config.zsh.path_syntax_highlighting %>',
                    repository: 'https://github.com/zsh-users/zsh-syntax-highlighting.git'
                }
            }

        },

        // -- Symbolic links ---------------------------------------------------

        symlink: {

            sublime: {
                dest: '/usr/local/bin/subl',
                relativeSrc: '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl'
            }

        },

        // -- Exec -------------------------------------------------------------

        exec: {

            osx: {
                cmd: 'source <%= config.osx.path_osx %>'
            },

            z: {
                cmd: 'touch <%= config.zsh.path_z %>'
            },

            zsh: {
                cmd: 'chsh -s /bin/zsh'
            },

            node_latest: {
                cmd: 'sudo n latest &> /dev/null'
            },

            node_stable: {
                cmd: 'sudo n stable &> /dev/null'
            },

            ruby_compass: {
                cmd: 'sudo gem install compass'
            },

            ruby_jekyll: {
                cmd: 'sudo gem install jekyll'
            },

            ruby_update: {
                cmd: 'sudo gem update --system'
            }

        }

    });

    grunt.loadNpmTasks('grunt-bump');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-git');
    grunt.loadNpmTasks('grunt-prompt');
    grunt.loadNpmTasks('grunt-symlink');
    grunt.loadNpmTasks('grunt-template');

    grunt.registerTask('setup', ['clean', 'prompt', 'template', 'gitclone', 'exec', 'symlink']);

};<|endoftext|>


<commit_before>var matrix = [];
var seed = 42;
var sum = 0;

for (var i = 0; i < 2; i++) {
  var m = [];
  for (var j = 0; j < 512; j++) {
    var r = [];
    for (var k = 0; k < 512; k++) {
      r.push(seed);
      seed *= 25189;
      seed %= 32749;
    }
    m.push(r);
  }
  matrix.push(m);
}
var m = [];
for (var j = 0; j < 512; j++) {
  var r = [];
  for (var k = 0; k < 512; k++) {
    r.push(0);
  }
  m.push(r);
}
matrix.push(m);

for(var i = 0; i < 512; i++)
{
    for(var j = 0; j < 512; j++)
    {
        for(var k = 0; k < 512; k++)
        {
            matrix[2][i][j] += matrix[0][i][k] * matrix[1][k][j];
            matrix[2][i][j] &= 0xFFFF;
        }
        sum += ((i * j) & 0xFF) * matrix[2][i][j];
        sum &= 0xFFFF;
    }
}

if(process.argv.length >= 3)
    console.log(sum);
<commit_msg>Performance improvement of Javascript version of matrix<commit_after>var matrix = [];
var seed = 42;
var sum = 0;

for (var i = 0; i < 3; i++) {
  matrix[i] = new Array(512);
  for (var j = 0; j < 512; j++)
    matrix[i][j] = new Array(512);
}

for (var i = 0; i < 2; i++)
  for (var j = 0; j < 512; j++)
    for (var k = 0; k < 512; k++) {
      matrix[i][j][k] = seed;
      seed *= 25189;
      seed %= 32749;
    }

for (var j = 0; j < 512; j++)
  for (var k = 0; k < 512; k++)
    matrix[2][j][k] = 0;

for(var i = 0; i < 512; i++) {
    for(var j = 0; j < 512; j++) {
        for(var k = 0; k < 512; k++) {
            matrix[2][i][j] += matrix[0][i][k] * matrix[1][k][j];
            matrix[2][i][j] &= 0xFFFF;
        }
        sum += ((i * j) & 0xFF) * matrix[2][i][j];
        sum &= 0xFFFF;
    }
}

if(process.argv.length >= 3)
    console.log(sum);
<|endoftext|>


<commit_before>#!/usr/bin/env node
;(function () {
  'use strict';

  /** Load Node modules */
  var exec = require('child_process').exec,
      fs = require('fs'),
      https = require('https'),
      path = require('path'),
      tar = require('../vendor/tar/tar.js'),
      zlib = require('zlib');

  /** The path of the directory that is the base of the repository */
  var basePath = fs.realpathSync(path.join(__dirname, '..'));

  /** The path of the `vendor` directory */
  var vendorPath = path.join(basePath, 'vendor');

  /** The Git object ID of `closure-compiler.tar.gz` */
  var closureId = 'aa29a2ecf6f51d4da5a2a418c0d4ea0e368ee80d';

  /** The Git object ID of `uglifyjs.tar.gz` */
  var uglifyId = '9869c4443fb22598235d1019fcc8245be41e8889';

  /*--------------------------------------------------------------------------*/

  /**
   * Fetches a required `.tar.gz` dependency with the given Git object ID from
   * the Lo-Dash repo on GitHub. The object ID may be obtained by running
   * `git hash-object path/to/dependency.tar.gz`.
   *
   * @private
   * @param {Object} options The options object.
   *
   *  id - The Git object ID of the `.tar.gz` file.
   *  onComplete - The function, invoked with one argument (exception),
   *   called once the extraction has finished.
   *  path - The path of the extraction directory.
   *  title - The dependency's title used in status updates logged to the console.
   */
  function getDependency(options) {
    options || (options = {});

    var onComplete = options.onComplete,
        title = options.title;

    function callback(exception) {
      if (exception) {
        console.error('There was a problem downloading ' + title + '.');
      }
      onComplete(exception);
    }

    console.log('Downloading ' + title + '...');

    https.get({
      'host': 'api.github.com',
      'path': '/repos/bestiejs/lodash/git/blobs/' + options.id,
      'headers': {
        // By default, all GitHub blob API endpoints return a JSON document
        // containing Base64-encoded blob data. Overriding the `Accept` header
        // with the GitHub raw media type returns the blob data directly.
        'Accept': 'application/vnd.github.v3.raw'
      }
    }, function(response) {
      var decompressor = zlib.createUnzip().on('error', callback);

      var parser = new tar.Extract({
        'path': options.path
      })
      .on('end', callback)
      .on('error', callback);

      response.pipe(decompressor).pipe(parser);
    })
    .on('error', callback);
  }

  /*--------------------------------------------------------------------------*/

  exec('npm -g root', function(exception, stdout) {
    if (exception) {
      console.error('There was a problem loading the npm registry.');
      process.exit(1);
    }
    // exit early if not a global install
    if (path.resolve(basePath, '..') != stdout.trim()) {
      return;
    }
    // download the Closure Compiler
    getDependency({
      'title': 'the Closure Compiler',
      'id': closureId,
      'path': vendorPath,
      'onComplete':function(exceptionA) {
        // download UglifyJS
        getDependency({
          'title': 'UglifyJS',
          'id': uglifyId,
          'path': vendorPath,
          'onComplete': function(exceptionB) {
            process.exit(exceptionA || exceptionB ? 1 : 0);
          }
        });
      }
    });
  });
}());
<commit_msg>Cleanup build/post-install.js.<commit_after>#!/usr/bin/env node
;(function () {
  'use strict';

  /** Load Node modules */
  var exec = require('child_process').exec,
      fs = require('fs'),
      https = require('https'),
      path = require('path'),
      tar = require('../vendor/tar/tar.js'),
      zlib = require('zlib');

  /** The path of the directory that is the base of the repository */
  var basePath = fs.realpathSync(path.join(__dirname, '..'));

  /** The path of the `vendor` directory */
  var vendorPath = path.join(basePath, 'vendor');

  /** The Git object ID of `closure-compiler.tar.gz` */
  var closureId = 'aa29a2ecf6f51d4da5a2a418c0d4ea0e368ee80d';

  /** The Git object ID of `uglifyjs.tar.gz` */
  var uglifyId = '9869c4443fb22598235d1019fcc8245be41e8889';

  /*--------------------------------------------------------------------------*/

  /**
   * Fetches a required `.tar.gz` dependency with the given Git object ID from
   * the Lo-Dash repo on GitHub. The object ID may be obtained by running
   * `git hash-object path/to/dependency.tar.gz`.
   *
   * @private
   * @param {Object} options The options object.
   *
   *  id - The Git object ID of the `.tar.gz` file.
   *  onComplete - The function, invoked with one argument (exception),
   *   called once the extraction has finished.
   *  path - The path of the extraction directory.
   *  title - The dependency's title used in status updates logged to the console.
   */
  function getDependency(options) {
    options || (options = {});

    var onComplete = options.onComplete,
        title = options.title;

    function callback(exception) {
      if (exception) {
        console.error('There was a problem downloading ' + title + '.');
      }
      onComplete(exception);
    }

    console.log('Downloading ' + title + '...');

    https.get({
      'host': 'api.github.com',
      'path': '/repos/bestiejs/lodash/git/blobs/' + options.id,
      'headers': {
        // By default, all GitHub blob API endpoints return a JSON document
        // containing Base64-encoded blob data. Overriding the `Accept` header
        // with the GitHub raw media type returns the blob data directly.
        'Accept': 'application/vnd.github.v3.raw'
      }
    }, function(response) {
      var decompressor = zlib.createUnzip(),
          parser = new tar.Extract({ 'path': options.path });

      decompressor.on('error', callback)
      parser.on('end', callback).on('error', callback);
      response.pipe(decompressor).pipe(parser);
    })
    .on('error', callback);
  }

  /*--------------------------------------------------------------------------*/

  exec('npm -g root', function(exception, stdout) {
    if (exception) {
      console.error('There was a problem loading the npm registry.');
      process.exit(1);
    }
    // exit early if not a global install
    if (path.resolve(basePath, '..') != stdout.trim()) {
      return;
    }
    // download the Closure Compiler
    getDependency({
      'title': 'the Closure Compiler',
      'id': closureId,
      'path': vendorPath,
      'onComplete':function(exceptionA) {
        // download UglifyJS
        getDependency({
          'title': 'UglifyJS',
          'id': uglifyId,
          'path': vendorPath,
          'onComplete': function(exceptionB) {
            process.exit(exceptionA || exceptionB ? 1 : 0);
          }
        });
      }
    });
  });
}());
<|endoftext|>


<commit_before>var extend = require('raptor-util/extend');

function ensure(state, propertyName) {
    var proto = state.constructor.prototype;
    if (!(propertyName in proto)) {
        Object.defineProperty(proto, propertyName, {
            get: function() {
                return this.$__raw[propertyName];
            },
            set: function(value) {
                this.$__set(propertyName, value, false /* ensure:false */);
            }
        });
    }
}

function State(widget, initialState) {
    this.$__widget = widget;
    this.$__raw = initialState || {};

    this.$__dirty = false;
    this.$__old = null;
    this.$__changes = null;
    this.$__forced = null; // An object that we use to keep tracking of state properties that were forced to be dirty

    if (initialState) {
        for(var key in initialState) {
            if (initialState[HAS_OWN_PROP](key)) {
                ensure(this, key);
            }
        }
    }

    Object.seal(this);
}

State.prototype = {
    $__reset: function() {
        var self = this;

        self.$__dirty = false;
        self.$__old = null;
        self.$__changes = null;
        self.$__forced = null;
    },

    $__replace: function(newState) {
        var state = this;
        var key;

        var rawState = this.$__raw;

        for (key in rawState) {
            if (!(key in newState)) {
                state.$__set(key, undefined, false /* ensure:false */, false /* forceDirty:false */);
            }
        }

        for (key in newState) {
            state.$__set(key, newState[key], true /* ensure:true */, false /* forceDirty:false */);
        }
    },
    $__set: function(name, value, shouldEnsure, forceDirty) {
        var rawState = this.$__raw;

        if (shouldEnsure) {
            ensure(this, name);
        }

        if (value === null) {
            // Treat null as undefined to simplify our comparison logic
            value = undefined;
        }

        if (forceDirty) {
            var forcedDirtyState = this.$__forced || (this.$__forced = {});
            forcedDirtyState[name] = true;
        } else if (rawState[name] === value) {
            return;
        }

        if (!this.$__dirty) {
            // This is the first time we are modifying the widget state
            // so introduce some properties to do some tracking of
            // changes to the state
            this.$__dirty = true; // Mark the widget state as dirty (i.e. modified)
            this.$__old = rawState;
            this.$__raw = rawState = extend({}, rawState);
            this.$__changes = {};
            this.$__widget.$__queueUpdate();
        }

        this.$__changes[name] = value;

        if (value == null) {
            // Don't store state properties with an undefined or null value
            delete rawState[name];
        } else {
            // Otherwise, store the new value in the widget state
            rawState[name] = value;
        }
    },
    toJSON: function() {
        return this.$__raw;
    }
};

module.exports = State;<commit_msg>fix stupid mistake<commit_after>var extend = require('raptor-util/extend');

function ensure(state, propertyName) {
    var proto = state.constructor.prototype;
    if (!(propertyName in proto)) {
        Object.defineProperty(proto, propertyName, {
            get: function() {
                return this.$__raw[propertyName];
            },
            set: function(value) {
                this.$__set(propertyName, value, false /* ensure:false */);
            }
        });
    }
}

function State(widget, initialState) {
    this.$__widget = widget;
    this.$__raw = initialState || {};

    this.$__dirty = false;
    this.$__old = null;
    this.$__changes = null;
    this.$__forced = null; // An object that we use to keep tracking of state properties that were forced to be dirty

    if (initialState) {
        for(var key in initialState) {
            ensure(this, key);
        }
    }

    Object.seal(this);
}

State.prototype = {
    $__reset: function() {
        var self = this;

        self.$__dirty = false;
        self.$__old = null;
        self.$__changes = null;
        self.$__forced = null;
    },

    $__replace: function(newState) {
        var state = this;
        var key;

        var rawState = this.$__raw;

        for (key in rawState) {
            if (!(key in newState)) {
                state.$__set(key, undefined, false /* ensure:false */, false /* forceDirty:false */);
            }
        }

        for (key in newState) {
            state.$__set(key, newState[key], true /* ensure:true */, false /* forceDirty:false */);
        }
    },
    $__set: function(name, value, shouldEnsure, forceDirty) {
        var rawState = this.$__raw;

        if (shouldEnsure) {
            ensure(this, name);
        }

        if (value === null) {
            // Treat null as undefined to simplify our comparison logic
            value = undefined;
        }

        if (forceDirty) {
            var forcedDirtyState = this.$__forced || (this.$__forced = {});
            forcedDirtyState[name] = true;
        } else if (rawState[name] === value) {
            return;
        }

        if (!this.$__dirty) {
            // This is the first time we are modifying the widget state
            // so introduce some properties to do some tracking of
            // changes to the state
            this.$__dirty = true; // Mark the widget state as dirty (i.e. modified)
            this.$__old = rawState;
            this.$__raw = rawState = extend({}, rawState);
            this.$__changes = {};
            this.$__widget.$__queueUpdate();
        }

        this.$__changes[name] = value;

        if (value == null) {
            // Don't store state properties with an undefined or null value
            delete rawState[name];
        } else {
            // Otherwise, store the new value in the widget state
            rawState[name] = value;
        }
    },
    toJSON: function() {
        return this.$__raw;
    }
};

module.exports = State;<|endoftext|>


<commit_before>app.controller('UserCtrl',['$rootScope','UserModel', function($rootScope,UserModel) {
  var self = this;

  UserModel.findAll();

  //var userFindAllSuccess = $rootScope.$on('user:find_all_success', function(event, data) { findAllSuccess(data);  });
  //var userFindAllError = $rootScope.$on('user:find_all_error', function(event, data) { findAllError(data); });

  // Event Listener
  $rootScope.$on('user:find_all_success', function(event, data) { findAllSuccess(data);  });
  $rootScope.$on('user:find_all_error', function(event, data) { findAllError(data); });
  $rootScope.$on('user:find_success', function(event, data) { findSuccess(data);  });
  $rootScope.$on('user:find_error', function(event, data) { findError(data); });
  $rootScope.$on('user:create_success', function(event, data) { createSuccess(data);  });
  $rootScope.$on('user:create_error', function(event, data) { createError(data); });
  $rootScope.$on('user:update_success', function(event, data) { updateSuccess(data);  });
  $rootScope.$on('user:update_error', function(event, data) { updateError(data); });
  $rootScope.$on('user:remove_success', function(event, data) { updateSuccess(data);  });
  $rootScope.$on('user:remove_error', function(event, data) { updateError(data); });

  var find = function(id) {
    return UserModel.find(id);
  }

  // List
  self.view = function(id) {
    self.user = find(id);
  }
  self.edit = function(id) {
    self.user = find(id);
  }
  self.remove = function(id) {
    UserModel.remove(id);
  }

  // Form
  self.roles = [
    {label: 'Gerente', value: 'manager'},
    {label: 'Avaliador', value: 'measurer'}
  ];
  self.submit = function() {
    if (self.user.hasOwnProperty('id')) {
      UserModel.update(self.user);
    } else {
      UserModel.create(self.user);
    }
  }

  // Event Dispatcher
  var findAllSuccess = function(data) {
    self.users = data;
  }
  var findAllError = function(data) {
    console.warn(data);
  }
  var findSuccess = function(data) {
    self.user = data;
  }
  var findError = function(data) {
    console.warn(data);
  }
  var createSuccess = function(data) {
    self.users.push(data);
  }
  var createError = function(data) {
    console.warn(data);
  }
  var updateSuccess = function(data) {
    UserModel.findAll();
  }
  var updateError = function(data) {
    console.warn(data);
  }
  var removeSuccess = function(data) {
    UserModel.findAll();
  }
  var removeError = function(data) {
    console.warn(data);
  }

  //$rootScope.$on('$destroy', userFindAllSuccess, userFindAllError, console.log('destroy'));
}])<commit_msg>crud complete<commit_after>app.controller('UserCtrl',['$rootScope','UserModel', function($rootScope,UserModel) {
  var self = this;

  UserModel.findAll();

  //var userFindAllSuccess = $rootScope.$on('user:find_all_success', function(event, data) { findAllSuccess(data);  });
  //var userFindAllError = $rootScope.$on('user:find_all_error', function(event, data) { findAllError(data); });

  // Event Listener
  $rootScope.$on('user:find_all_success', function(event, data) { this._findAllSuccess(data);  });
  $rootScope.$on('user:find_all_error', function(event, data) { this._findAllError(data); });
  $rootScope.$on('user:find_success', function(event, data) { this._findSuccess(data);  });
  $rootScope.$on('user:find_error', function(event, data) { this._findError(data); });
  $rootScope.$on('user:create_success', function(event, data) { this._createSuccess(data);  });
  $rootScope.$on('user:create_error', function(event, data) { this._createError(data); });
  $rootScope.$on('user:update_success', function(event, data) { this._updateSuccess(data);  });
  $rootScope.$on('user:update_error', function(event, data) { this._updateError(data); });
  $rootScope.$on('user:remove_success', function(event, data) { this._updateSuccess(data);  });
  $rootScope.$on('user:remove_error', function(event, data) { this._updateError(data); });

  var find = function(id) {
    return UserModel.find(id);
  }

  // List
  self.view = function(id) {
    self.user = find(id);
  }
  self.edit = function(id) {
    self.user = find(id);
  }
  self.remove = function(id) {
    UserModel.remove(id);
  }

  // Form
  self.roles = [
    {label: 'Gerente', value: 'manager'},
    {label: 'Avaliador', value: 'measurer'}
  ];
  self.submit = function() {
    if (self.user.hasOwnProperty('id')) {
      UserModel.update(self.user);
    } else {
      UserModel.create(self.user);
    }
  }

  // Event Dispatcher
  _findAllSuccess = function(data) {
    self.users = data;
  }
  _findAllError = function(data) {
    console.warn(data);
  }
  _findSuccess = function(data) {
    self.user = data;
  }
  _findError = function(data) {
    console.warn(data);
  }
  _createSuccess = function(data) {
    self.users.push(data);
  }
  _createError = function(data) {
    console.warn(data);
  }
  _updateSuccess = function(data) {
    UserModel.findAll();
  }
  _updateError = function(data) {
    console.warn(data);
  }
  _removeSuccess = function(data) {
    UserModel.findAll();
  }
  _removeError = function(data) {
    console.warn(data);
  }

  //$rootScope.$on('$destroy', userFindAllSuccess, userFindAllError, console.log('destroy'));
}])<|endoftext|>


<commit_before>var React    = window.React = require('react'), // assign it to window for react chrome extension
    classNames = require('classnames'),
    App = {};

var Constants = {
    DownloadCountBatch: 100,
    NpmSearchInitialSize: 500
}

var OfficialPlugin = React.createClass({
    render: function() {
        return (

        );
    }
});

var PlatformButton = React.createClass({
    onClick: function() {
        var appInstance = React.render(<App />, document.getElementById('container'));
        appInstance.addCondition("platform:" + this.props.platform);
    },
    render: function() {
        return (

 {this.props.platform}

        );
    }
});

var SupportedPlatforms = React.createClass({
    getInitialState: function() {
        return {
            moreClicked: false
        };
    },
    onClick: function() {
        this.setState({
            moreClicked: true
        });
    },
    render: function() {
        var keywords = this.props.keywords;
        var sortedMajorPlatforms = [{present:false, text: "Android"}, {present:false, text: "iOS"}, {present:false, text: "Windows"}, {present:false, text: "Blackberry10"}];
        var majorPlatformsSupported = [];
        var otherPlatformsSupported = [];
        // remove windows8 & windows dupe
        if (keywords.indexOf('cordova-windows') > -1 && keywords.indexOf('cordova-windows8') > -1) {
            keywords.splice(keywords.indexOf('cordova-windows8'), 1);
        }
        keywords.forEach(function(keyword) {
            switch (keyword) {
                case 'cordova-firefoxos':
                    otherPlatformsSupported.push(<PlatformButton platform="FirefoxOS" />);
                    break;
                case 'cordova-android':
                    sortedMajorPlatforms[0].present = true;
                    break;
                case 'cordova-amazon-fireos':
                    otherPlatformsSupported.push(<PlatformButton platform="FireOS" />);
                    break;
                case 'cordova-ubuntu':
                    otherPlatformsSupported.push(<PlatformButton platform="Ubuntu" />);
                    break;
                case 'cordova-ios':
                    sortedMajorPlatforms[1].present = true;
                    break;
                case 'cordova-blackberry10':
                    sortedMajorPlatforms[3].present = true;
                    break;
                case 'cordova-wp8':
                    otherPlatformsSupported.push(<PlatformButton platform="Windows Phone 8" />);
                    break;
                case 'cordova-windows8':
                case 'cordova-windows':
                    sortedMajorPlatforms[2].present = true;
                    break;
                case 'cordova-browser':
                    otherPlatformsSupported.push(<PlatformButton platform="Browser" />);
                    break;
            }
        });

        sortedMajorPlatforms.forEach(function(platform) {
            if(platform.present) {
                majorPlatformsSupported.push(<PlatformButton platform={platform.text} />)
            }
        });
        while(majorPlatformsSupported.length < 4 && otherPlatformsSupported.length > 0) {
            majorPlatformsSupported.push(otherPlatformsSupported.shift());
        }

        var moreButton;
        if(otherPlatformsSupported.length > 0 && !this.state.moreClicked) {
            moreButton =
...

        }
        if (!this.state.moreClicked) {
            otherPlatformsSupported = null;
        }
        return (

                {majorPlatformsSupported}
                {moreButton}
                {otherPlatformsSupported}

        );
    }
});

var SearchBar = React.createClass({
    handleChange: function() {
        this.props.onUserInput(
            this.refs.filterTextInput.getDOMNode().value
        )
    },
    render: function() {
        return (

                    <input
                        className="searchBox"
                        type="search"
                        autoComplete="off"
                        placeholder={this.props.placeHolderText}
                        value={this.props.filterText}
                        ref="filterTextInput"
                        onChange={this.handleChange}
                    />

        );
    }
});

var Plugin = React.createClass({
    render: function() {
        var license = this.props.plugin.license;
        if (license && license.length > 1) {
            license = license[0];
        }
        var downloadField;

        var classes = classNames({
            'pluginCard': true,
            'featuredPlugin': this.props.plugin.isOfficial,
            'row': true
        });

        if(this.props.plugin.downloadCount) {
            var downloadCount = this.props.plugin.downloadCount.toLocaleString();
            downloadField =
 {downloadCount} downloads last month
;
        }
        return (

{this.props.plugin.name}

                            v{this.props.plugin.version}
                             by
                            {this.props.plugin.author}

{this.props.plugin.description}

                        <SupportedPlatforms keywords={this.props.plugin.keywords}/>

License: {license}

                            {downloadField}

Last updated {this.props.plugin.modified} days ago

        )
    }
});

var timer=null;

window.addEventListener('popstate', function(e) {
    if(e.state) {
        var appInstance = React.render(<App />, document.getElementById('container'));
        appInstance.loadFilterText(e.state.filterText);
    }
});

var PluginList = React.createClass({

    contains: function(values, pluginInfo) {
        var allValuesPresent = true;
        if(values.length == 0) {
            return allValuesPresent;
        }
        if(!pluginInfo) {
            return false;
        }
        values.forEach(function(value) {
            var valuePresent = false;
            for(var index=0; index < pluginInfo.length; index++) {
                if(pluginInfo[index] && pluginInfo[index].toLowerCase().indexOf(value) > -1) {
                    valuePresent = true;
                }
            }
            if(!valuePresent) {
                allValuesPresent = false;
            }
        });
        return allValuesPresent;
    },
    populateFilters: function(filterText)
    {
        var searchStrings = filterText.split(" ");
        var filters = [];
        filters['platforms'] = [];
        filters['authors'] = [];
        filters['licenses'] = [];
        filters['searchWords'] = [];

        searchStrings.forEach(function(searchString) {
            var keywords = searchString.split(":");
            if(keywords.length == 1) {
                var param = keywords[0].trim();
                if(param) {
                    filters['searchWords'].push(param);
                }
            }
            else if(keywords[1].trim()) {
                var param = keywords[1].trim();
                switch(keywords[0]) {
                    case 'platform':
                        filters['platforms'].push(param);
                        break;
                    case 'author':
                        filters['authors'].push(param);
                        break;
                    case 'license':
                        filters['licenses'].push(param);
                        break;
                    default:
                        filters['searchWords'].push(searchString);
                }
            }
            else {
                filters['searchWords'].push(searchString);
            }
        });
        return filters;
    },
    render: function() {
        var plugins = [],
            filterText = this.props.filterText.toLowerCase();

        var delay = (function(){
          return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
          };
        })();

        delay(function(){
                    window.history.pushState({"filterText":filterText}, "", "?q=" + filterText);
            }, 2000 );

        var filters = this.populateFilters(filterText);

        this.props.plugins.forEach(function(plugin) {
            var fullPluginText = plugin.name.concat(plugin.author, plugin.keywords, plugin.license, plugin.description);
            if(this.contains(filters['platforms'], plugin.keywords)
                && this.contains(filters['authors'], plugin.author)
                && this.contains(filters['licenses'], plugin.license)
                && this.contains(filters['searchWords'], fullPluginText)) {
                    plugins.push(<Plugin plugin={plugin} key={plugin.author + plugin.name}/>);
            }
        }.bind(this));
        return (

                    {plugins}

        );
    }
});

var App = React.createClass({
    getInitialState: function() {
        return {
            plugins: [],
            filterText: '',
            placeHolderText: 'Loading...'
        };
    },
    handleUserInput: function(filterText) {
        this.setState({
            filterText: filterText
        });
    },
    addCondition: function(condition) {
        this.setState(function(previousState, currentProps) {
            if(previousState.filterText.indexOf(condition) > -1) {
                return {
                    filterText: previousState.filterText,
                    plugins: previousState.plugins
                };
            }
            else {
                return {
                    filterText: previousState.filterText.trim() + ' ' + condition + ' ',
                    plugins: previousState.plugins
                };
            }
        });
    },
    loadFilterText : function(filterText) {
        this.setState(function(previousState, currentProps) {
            return {
                filterText: filterText,
                plugins: previousState.plugins
            };
        });
    },
    getURLParameter : function(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)
            ||[,""])[1].replace(/\+/g, '%20'))||null;
    },

    componentDidMount: function() {
        var plugins = [],
            officialPlugins = require('./official-plugins.json').plugins,
            blacklistedPlugins = require('./blacklisted-plugins.json').plugins,
            pluginCount = 0,
            self = this,
            queryHost = "http://npmsearch.com/query",
            queryFields = "fields=name,keywords,license,description,author,modified,homepage,version",
            queryKeywords = "q=keywords:%22ecosystem:cordova%22",
            queryInitialSize = Constants.NpmSearchInitialSize;

        xhrRequest(queryHost + "?" + queryFields + "&" + queryKeywords + "&size=" + queryInitialSize + "&start=0", function(xhrResult) {
            plugins = xhrResult.results;
            pluginCount = xhrResult.total;
            if (pluginCount <= queryInitialSize) {
                processPlugins.bind(self, officialPlugins, plugins)();
            } else {
                xhrRequest(queryHost + "?" + queryFields + "&" + queryKeywords + "&size=" + (pluginCount - queryInitialSize) + "&start=" + queryInitialSize, function(xhrResult) {
                        plugins = [].concat(plugins, xhrResult.results);
                        processPlugins.bind(self, officialPlugins, plugins)();
                }, function() { console.log('xhr err'); });
            }
        }, function() { console.log('xhr err'); });

        var getDownloadCount = function(plugins, that) {
            var packageNames = "";
            for(var index=0; index < plugins.length; index++) {
                packageNames += plugins[index].name + ",";
                if(index % Constants.DownloadCountBatch === 0 || index === plugins.length -1) {
                    xhrRequest("https://api.npmjs.org/downloads/point/last-month/" + packageNames, function(xhrResult) {
                        plugins.forEach(function(plugin) {
                            if(xhrResult[plugin.name])
                                plugin.downloadCount = xhrResult[plugin.name].downloads;
                        });
                        that.setState({
                            plugins: plugins
                        });
                    }.bind(self), function() { console.log('xhr err'); });
                    packageNames = "";
                }
            }
        }

        function processPlugins(officialPlugins, plugins) {
            var pluginCount = plugins.length,
                dateNow = new Date(),
                oneDay = 1000*60*60*24;

            officialPlugins.forEach(function(plugin) {
                for (var i = 0; i < plugins.length; i++) {
                    // Check if plugin name is in official list
                    if (plugins[i].name[0] === plugin) {
                        plugins[i].isOfficial = true;
                        return;
                    }
                };
            });

            for(var i = plugins.length -1; i >= 0 ; i--)
            {
                for(var j = 0; j < blacklistedPlugins.length; j++)
                {
                    if(plugins[i].name[0] === blacklistedPlugins[j])
                    {
                        plugins.splice(i, 1);
                        break;
                    }
                }
            }

            for (var i = 0; i < plugins.length; i++) {
                // Calculate last time plugin is modified (in days)
                plugins[i].modified = Math.ceil((dateNow - new Date(plugins[i].modified)) / oneDay);
            };

            if (this.isMounted()) {
                var q = this.getURLParameter('q');
                if(q) {
                    this.setState({
                        plugins: plugins,
                        filterText: q
                    });
                }
                else {
                    this.setState({
                        plugins: plugins,
                        placeHolderText: 'Search ' + pluginCount + ' plugins...'
                    });
                }
                getDownloadCount(plugins,this);
            }
        }
    },

    render: function() {
        return (

Search Cordova Plugins

                    <SearchBar
                        filterText={this.state.filterText}
                        placeHolderText={this.state.placeHolderText}
                        onUserInput={this.handleUserInput}
                    />

                    <PluginList
                        plugins={this.state.plugins}
                        filterText={this.state.filterText}
                    />

        );
    }
});

App.start = function() {
    React.render(<App />, document.getElementById('container'));
};

function xhrRequest(url, success, fail) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE ) {
            if(xhr.status == 200){
                success(JSON.parse(xhr.responseText));
                return;
            } else {
                fail();
                return;
            }
        }
    }.bind(this)
    xhr.open("GET", url, true);
    xhr.send();
}

module.exports = window.App = App;
<commit_msg>Make plugin data model immutable and improve perf by implementing shouldComponentUpdate callback. Make helper functions static.. This closes #26<commit_after>var React    = window.React = require('react'), // assign it to window for react chrome extension
    classNames = require('classnames'),
    App = {};

var Constants = {
    DownloadCountBatch: 100,
    NpmSearchInitialSize: 500
}

var OfficialPlugin = React.createClass({
    render: function() {
        return (

        );
    }
});

var PlatformButton = React.createClass({
    onClick: function() {
        var appInstance = React.render(<App />, document.getElementById('container'));
        appInstance.addCondition("platform:" + this.props.platform);
    },
    render: function() {
        return (

 {this.props.platform}

        );
    }
});

var SupportedPlatforms = React.createClass({
    getInitialState: function() {
        return {
            moreClicked: false
        };
    },
    onClick: function() {
        this.setState({
            moreClicked: true
        });
    },
    render: function() {
        var keywords = this.props.keywords;
        var sortedMajorPlatforms = [{present:false, text: "Android"}, {present:false, text: "iOS"}, {present:false, text: "Windows"}, {present:false, text: "Blackberry10"}];
        var majorPlatformsSupported = [];
        var otherPlatformsSupported = [];
        // remove windows8 & windows dupe
        if (keywords.indexOf('cordova-windows') > -1 && keywords.indexOf('cordova-windows8') > -1) {
            keywords.splice(keywords.indexOf('cordova-windows8'), 1);
        }
        keywords.forEach(function(keyword) {
            switch (keyword) {
                case 'cordova-firefoxos':
                    otherPlatformsSupported.push(<PlatformButton platform="FirefoxOS" />);
                    break;
                case 'cordova-android':
                    sortedMajorPlatforms[0].present = true;
                    break;
                case 'cordova-amazon-fireos':
                    otherPlatformsSupported.push(<PlatformButton platform="FireOS" />);
                    break;
                case 'cordova-ubuntu':
                    otherPlatformsSupported.push(<PlatformButton platform="Ubuntu" />);
                    break;
                case 'cordova-ios':
                    sortedMajorPlatforms[1].present = true;
                    break;
                case 'cordova-blackberry10':
                    sortedMajorPlatforms[3].present = true;
                    break;
                case 'cordova-wp8':
                    otherPlatformsSupported.push(<PlatformButton platform="Windows Phone 8" />);
                    break;
                case 'cordova-windows8':
                case 'cordova-windows':
                    sortedMajorPlatforms[2].present = true;
                    break;
                case 'cordova-browser':
                    otherPlatformsSupported.push(<PlatformButton platform="Browser" />);
                    break;
            }
        });

        sortedMajorPlatforms.forEach(function(platform) {
            if(platform.present) {
                majorPlatformsSupported.push(<PlatformButton platform={platform.text} />)
            }
        });
        while(majorPlatformsSupported.length < 4 && otherPlatformsSupported.length > 0) {
            majorPlatformsSupported.push(otherPlatformsSupported.shift());
        }

        var moreButton;
        if(otherPlatformsSupported.length > 0 && !this.state.moreClicked) {
            moreButton =
...

        }
        if (!this.state.moreClicked) {
            otherPlatformsSupported = null;
        }
        return (

                {majorPlatformsSupported}
                {moreButton}
                {otherPlatformsSupported}

        );
    }
});

var SearchBar = React.createClass({
    handleChange: function() {
        this.props.onUserInput(
            this.refs.filterTextInput.getDOMNode().value
        )
    },
    render: function() {
        return (

                    <input
                        className="searchBox"
                        type="search"
                        autoComplete="off"
                        placeholder={this.props.placeHolderText}
                        value={this.props.filterText}
                        ref="filterTextInput"
                        onChange={this.handleChange}
                    />

        );
    }
});

var Plugin = React.createClass({
    shouldComponentUpdate: function(nextProps, nextState) {
        return this.props.plugin !== nextProps.plugin;
    },
    render: function() {
        var license = this.props.plugin.license;
        if (license && license.length > 1) {
            license = license[0];
        }
        var downloadField;

        var classes = classNames({
            'pluginCard': true,
            'featuredPlugin': this.props.plugin.isOfficial,
            'row': true
        });

        if(this.props.plugin.downloadCount) {
            var downloadCount = this.props.plugin.downloadCount.toLocaleString();
            downloadField =
 {downloadCount} downloads last month
;
        }
        return (

{this.props.plugin.name}

                            v{this.props.plugin.version}
                             by
                            {this.props.plugin.author}

{this.props.plugin.description}

                        <SupportedPlatforms keywords={this.props.plugin.keywords}/>

License: {license}

                            {downloadField}

Last updated {this.props.plugin.modified} days ago

        )
    }
});

var timer=null;

window.addEventListener('popstate', function(e) {
    if(e.state) {
        var appInstance = React.render(<App />, document.getElementById('container'));
        appInstance.loadFilterText(e.state.filterText);
    }
});

var PluginList = React.createClass({
    statics: {
        contains: function(values, pluginInfo) {
            var allValuesPresent = true;
            if(values.length == 0) {
                return allValuesPresent;
            }
            if(!pluginInfo) {
                return false;
            }
            values.forEach(function(value) {
                var valuePresent = false;
                for(var index=0; index < pluginInfo.length; index++) {
                    if(pluginInfo[index] && pluginInfo[index].toLowerCase().indexOf(value) > -1) {
                        valuePresent = true;
                    }
                }
                if(!valuePresent) {
                    allValuesPresent = false;
                }
            });
            return allValuesPresent;
        },
        populateFilters: function(filterText)
        {
            var searchStrings = filterText.split(" ");
            var filters = [];
            filters['platforms'] = [];
            filters['authors'] = [];
            filters['licenses'] = [];
            filters['searchWords'] = [];

            searchStrings.forEach(function(searchString) {
                var keywords = searchString.split(":");
                if(keywords.length == 1) {
                    var param = keywords[0].trim();
                    if(param) {
                        filters['searchWords'].push(param);
                    }
                }
                else if(keywords[1].trim()) {
                    var param = keywords[1].trim();
                    switch(keywords[0]) {
                        case 'platform':
                            filters['platforms'].push(param);
                            break;
                        case 'author':
                            filters['authors'].push(param);
                            break;
                        case 'license':
                            filters['licenses'].push(param);
                            break;
                        default:
                            filters['searchWords'].push(searchString);
                    }
                }
                else {
                    filters['searchWords'].push(searchString);
                }
            });
            return filters;
        }
    },
    render: function() {
        var plugins = [],
            filterText = this.props.filterText.toLowerCase();

        var delay = (function(){
          return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
          };
        })();

        delay(function(){
                    window.history.pushState({"filterText":filterText}, "", "?q=" + filterText);
            }, 2000 );

        var filters = PluginList.populateFilters(filterText);

        this.props.plugins.forEach(function(plugin) {
            var fullPluginText = plugin.name.concat(plugin.author, plugin.keywords, plugin.license, plugin.description);
            if(PluginList.contains(filters['platforms'], plugin.keywords)
                && PluginList.contains(filters['authors'], plugin.author)
                && PluginList.contains(filters['licenses'], plugin.license)
                && PluginList.contains(filters['searchWords'], fullPluginText)) {
                    plugins.push(<Plugin plugin={plugin} key={plugin.author + plugin.name}/>);
            }
        }.bind(this));
        return (

                    {plugins}

        );
    }
});

var App = React.createClass({
    getInitialState: function() {
        return {
            plugins: [],
            filterText: '',
            placeHolderText: 'Loading...'
        };
    },
    handleUserInput: function(filterText) {
        this.setState({
            filterText: filterText
        });
    },
    addCondition: function(condition) {
        this.setState(function(previousState, currentProps) {
            if(previousState.filterText.indexOf(condition) > -1) {
                return {
                    filterText: previousState.filterText,
                    plugins: previousState.plugins
                };
            }
            else {
                return {
                    filterText: previousState.filterText.trim() + ' ' + condition + ' ',
                    plugins: previousState.plugins
                };
            }
        });
    },
    loadFilterText : function(filterText) {
        this.setState(function(previousState, currentProps) {
            return {
                filterText: filterText,
                plugins: previousState.plugins
            };
        });
    },
    statics: {
        getURLParameter : function(name) {
            return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)
                ||[,""])[1].replace(/\+/g, '%20'))||null;
        },
        shallowCopy: function(src) {
            var dst = {};
            for(var i in src) {
                if(src.hasOwnProperty(i)) {
                    dst[i] = src[i];
                }
            }
            return dst;
        }
    },
    componentDidMount: function() {
        var plugins = [],
            officialPlugins = require('./official-plugins.json').plugins,
            blacklistedPlugins = require('./blacklisted-plugins.json').plugins,
            pluginCount = 0,
            self = this,
            queryHost = "http://npmsearch.com/query",
            queryFields = "fields=name,keywords,license,description,author,modified,homepage,version",
            queryKeywords = "q=keywords:%22ecosystem:cordova%22",
            queryInitialSize = Constants.NpmSearchInitialSize;

        xhrRequest(queryHost + "?" + queryFields + "&" + queryKeywords + "&size=" + queryInitialSize + "&start=0", function(xhrResult) {
            plugins = xhrResult.results;
            pluginCount = xhrResult.total;
            if (pluginCount <= queryInitialSize) {
                processPlugins.bind(self, officialPlugins, plugins)();
            } else {
                xhrRequest(queryHost + "?" + queryFields + "&" + queryKeywords + "&size=" + (pluginCount - queryInitialSize) + "&start=" + queryInitialSize, function(xhrResult) {
                        plugins = [].concat(plugins, xhrResult.results);
                        processPlugins.bind(self, officialPlugins, plugins)();
                }, function() { console.log('xhr err'); });
            }
        }, function() { console.log('xhr err'); });

        var getDownloadCount = function(plugins, that) {
            var packageNames = "";
            for(var index=0; index < plugins.length; index++) {
                packageNames += plugins[index].name + ",";
                if(index % Constants.DownloadCountBatch === 0 || index === plugins.length -1) {
                    xhrRequest("https://api.npmjs.org/downloads/point/last-month/" + packageNames, function(xhrResult) {
                        for(var j = 0; j < plugins.length; j++) {
                            if(xhrResult[plugins[j].name]) {
                                plugins[j] = App.shallowCopy(plugins[j]);
                                plugins[j].downloadCount = xhrResult[plugins[j].name].downloads;
                            }
                        }
                        that.setState({
                            plugins: plugins
                        });
                    }.bind(self), function() { console.log('xhr err'); });
                    packageNames = "";
                }
            }
        }

        function processPlugins(officialPlugins, plugins) {
            var pluginCount = plugins.length,
                dateNow = new Date(),
                oneDay = 1000*60*60*24;

            officialPlugins.forEach(function(plugin) {
                for (var i = 0; i < plugins.length; i++) {
                    // Check if plugin name is in official list
                    if (plugins[i].name[0] === plugin) {
                        plugins[i].isOfficial = true;
                        return;
                    }
                };
            });

            for(var i = plugins.length -1; i >= 0 ; i--)
            {
                for(var j = 0; j < blacklistedPlugins.length; j++)
                {
                    if(plugins[i].name[0] === blacklistedPlugins[j])
                    {
                        plugins.splice(i, 1);
                        break;
                    }
                }
            }

            for (var i = 0; i < plugins.length; i++) {
                // Calculate last time plugin is modified (in days)
                plugins[i].modified = Math.ceil((dateNow - new Date(plugins[i].modified)) / oneDay);
            };

            if (this.isMounted()) {
                var q = App.getURLParameter('q');
                if(q) {
                    this.setState({
                        plugins: plugins,
                        filterText: q
                    });
                }
                else {
                    this.setState({
                        plugins: plugins,
                        placeHolderText: 'Search ' + pluginCount + ' plugins...'
                    });
                }
                getDownloadCount(plugins,this);
            }
        }
    },
    render: function() {
        return (

Search Cordova Plugins

                    <SearchBar
                        filterText={this.state.filterText}
                        placeHolderText={this.state.placeHolderText}
                        onUserInput={this.handleUserInput}
                    />

                    <PluginList
                        plugins={this.state.plugins}
                        filterText={this.state.filterText}
                    />

        );
    }
});

App.start = function() {
    React.render(<App />, document.getElementById('container'));
};

function xhrRequest(url, success, fail) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE ) {
            if(xhr.status == 200){
                success(JSON.parse(xhr.responseText));
                return;
            } else {
                fail();
                return;
            }
        }
    }.bind(this)
    xhr.open("GET", url, true);
    xhr.send();
}

module.exports = window.App = App;
<|endoftext|>


<commit_before>define(function(require, exports, module) {
  "use strict";

  var cc = require("./cc");
  var fn = require("./fn");
  var utils = require("./utils");

  var MulAdd;

  var setup = function(key, func) {
    [cc.Object, Array, Boolean, Date, Function, Number, String].forEach(function(Klass) {
      fn.definePrototypeProperty(Klass, key, func);
    });
  };

  var install = function() {
    setup("__plus__", function() {
      return +this;
    });
    setup("__minus__", function() {
      return -this;
    });
    setup("__add__", function(b) {
      return this + b;
    });
    setup("__sub__", function(b) {
      return this - b;
    });
    setup("__mul__", function(b) {
      return this * b;
    });
    setup("__div__", function(b) {
      return this / b;
    });
    setup("__mod__", function(b) {
      return this % b;
    });
    setup("__and__", function(b) {
      return this && b;
    });
    setup("__or__", function(b) {
      return this || b;
    });
    setup("next", function() {
      return this;
    });

    fn.definePrototypeProperty(String, "__mul__", function(b) {
      if (typeof b === "number") {
        var result = new Array(Math.max(0, b));
        for (var i = 0; i < b; i++) {
          result[i] = this;
        }
        return result.join("");
      } else if (Array.isArray(b)) {
        return b.map(function(b) {
          return this.__mul__(b);
        }, this);
      }
      return this * b;
    });

    fn.definePrototypeProperty(Function, "__mul__", function(b) {
      if (typeof b === "function") {
        var f = this, g = b;
        return function() {
          return f.call(null, g.apply(null, arguments));
        };
      }
      return this * b;
    });

    fn.definePrototypeProperty(String, "__div__", function(b) {
      if (typeof b === "number") {
        return utils.clump(this.split(""), Math.ceil(this.length/b)).map(function(items) {
          return items.join("");
        });
      } else if (Array.isArray(b)) {
        return b.map(function(b) {
          return this.__div__(b);
        }, this);
      }
      return this / b;
    });

    fn.definePrototypeProperty(String, "__mod__", function(b) {
      if (typeof b === "number") {
        return utils.clump(this.split(""), b|0).map(function(items) {
          return items.join("");
        });
      } else if (Array.isArray(b)) {
        return b.map(function(b) {
          return this.__mod__(b);
        }, this);
      }
      return this % b;
    });

    fn.definePrototypeProperty(Number, "madd", fn(function(mul, add) {
      return new MulAdd().init(this, mul, add);
    }).defaults("mul=1,add=0").multiCall().build());

    fn.definePrototypeProperty(Array, "madd", fn(function(mul, add) {
      return utils.flop([this, mul, add]).map(function(items) {
        var _in = items[0], mul = items[1], add = items[2];
        return new MulAdd().init(_in, mul, add);
      });
    }).defaults("mul=1,add=0").multiCall().build());
  };

  cc.once("basic_ops.js", function(payload) {
    MulAdd = payload.MulAdd;
  });

  module.exports = {
    install: install
  };

});
<commit_msg>Added to_i/to_f/to_s/to_a<commit_after>define(function(require, exports, module) {
  "use strict";

  var cc = require("./cc");
  var fn = require("./fn");
  var utils = require("./utils");

  var MulAdd;

  var setup = function(key, func) {
    [cc.Object, Array, Boolean, Date, Function, Number, String].forEach(function(Klass) {
      fn.definePrototypeProperty(Klass, key, func);
    });
  };

  var install = function() {
    setup("__plus__", function() {
      return +this;
    });
    setup("__minus__", function() {
      return -this;
    });
    setup("__add__", function(b) {
      return this + b;
    });
    setup("__sub__", function(b) {
      return this - b;
    });
    setup("__mul__", function(b) {
      return this * b;
    });
    setup("__div__", function(b) {
      return this / b;
    });
    setup("__mod__", function(b) {
      return this % b;
    });
    setup("__and__", function(b) {
      return this && b;
    });
    setup("__or__", function(b) {
      return this || b;
    });
    setup("next", function() {
      return this;
    });
    setup("to_i", function() {
      return this|0;
    });
    setup("to_f", function() {
      return +this;
    });
    setup("to_s", function() {
      return this.toString();
    });
    setup("to_a", function() {
      return [this];
    });

    fn.definePrototypeProperty(String, "__mul__", function(b) {
      if (typeof b === "number") {
        var result = new Array(Math.max(0, b));
        for (var i = 0; i < b; i++) {
          result[i] = this;
        }
        return result.join("");
      } else if (Array.isArray(b)) {
        return b.map(function(b) {
          return this.__mul__(b);
        }, this);
      }
      return this * b;
    });

    fn.definePrototypeProperty(Function, "__mul__", function(b) {
      if (typeof b === "function") {
        var f = this, g = b;
        return function() {
          return f.call(null, g.apply(null, arguments));
        };
      }
      return this * b;
    });

    fn.definePrototypeProperty(String, "__div__", function(b) {
      if (typeof b === "number") {
        return utils.clump(this.split(""), Math.ceil(this.length/b)).map(function(items) {
          return items.join("");
        });
      } else if (Array.isArray(b)) {
        return b.map(function(b) {
          return this.__div__(b);
        }, this);
      }
      return this / b;
    });

    fn.definePrototypeProperty(String, "__mod__", function(b) {
      if (typeof b === "number") {
        return utils.clump(this.split(""), b|0).map(function(items) {
          return items.join("");
        });
      } else if (Array.isArray(b)) {
        return b.map(function(b) {
          return this.__mod__(b);
        }, this);
      }
      return this % b;
    });

    fn.definePrototypeProperty(Number, "madd", fn(function(mul, add) {
      return new MulAdd().init(this, mul, add);
    }).defaults("mul=1,add=0").multiCall().build());

    fn.definePrototypeProperty(Array, "madd", fn(function(mul, add) {
      return utils.flop([this, mul, add]).map(function(items) {
        var _in = items[0], mul = items[1], add = items[2];
        return new MulAdd().init(_in, mul, add);
      });
    }).defaults("mul=1,add=0").multiCall().build());

    fn.definePrototypeProperty(Array, "to_i", function() {
      return this.map(function(x) {
        return x.to_i();
      });
    });
    fn.definePrototypeProperty(Array, "to_f", function() {
      return this.map(function(x) {
        return x.to_f();
      });
    });
    fn.definePrototypeProperty(Array, "to_s", function() {
      return this.map(function(x) {
        return x.to_s();
      });
    });
    fn.definePrototypeProperty(Array, "to_a", function() {
      return this;
    });
  };

  cc.once("basic_ops.js", function(payload) {
    MulAdd = payload.MulAdd;
  });

  module.exports = {
    install: install
  };

});
<|endoftext|>