<commit_before>'use strict';

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

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

  grunt.event.on('coverage', function(lcovFileContents, done) {
    require('coveralls').handleInput(lcovFileContents, function(err) {
      if (err) {
        return done(err);
      }
      done();
    });
  });

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

  // Make sure upload directory exists
  grunt.task.registerTask('mkdir:upload', 'Task that makes sure upload directory exists.', function () {
    // Get the callback
    var done = this.async();

    grunt.file.mkdir(path.normalize(__dirname + '/modules/users/client/img/profile/uploads'));

    done();
  });

  // Connect to the MongoDB instance and load the models
  grunt.task.registerTask('mongoose', 'Task that connects to the MongoDB instance and loads the application models.', function () {
    // Get the callback
    var done = this.async();

    // Use mongoose configuration
    var mongoose = require('./config/lib/mongoose.js');

    // Connect to database
    mongoose.connect(function (db) {
      done();
    });
  });

  grunt.task.registerTask('server', 'Starting the server', function () {
    // Get the callback
    var done = this.async();

    var path = require('path');
    var app = require(path.resolve('./config/lib/app'));
    var server = app.start(function () {
      done();
    });
  });

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

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

  // Run the project tests
  grunt.registerTask('test', ['env:test', 'lint', 'mkdir:upload', 'copy:localConfig', 'server', 'mochaTest', 'karma:unit']);
  grunt.registerTask('test:server', ['env:test', 'lint', 'server', 'mochaTest']);
  grunt.registerTask('test:client', ['env:test', 'lint', 'server', 'karma:unit']);
  // Run project coverage
  grunt.registerTask('coverage', ['env:test', 'lint', 'mocha_istanbul:coverage']);

  // Run the project in development mode
  grunt.registerTask('default', ['env:dev', 'lint', 'mkdir:upload', 'copy:localConfig', 'concurrent:default']);

  // Run the project in debug mode
  grunt.registerTask('debug', ['env:dev', 'lint', 'mkdir:upload', 'copy:localConfig', 'concurrent:debug']);

  // Run the project in production mode
  grunt.registerTask('prod', ['build', 'env:prod', 'mkdir:upload', 'copy:localConfig', 'concurrent:default']);
};
<commit_msg>format code and add comment<commit_after>'use strict';

// 定义模块依赖
var _ = require('lodash');
var defaultAssets = require('./config/assets/default');
var testAssets = require('./config/assets/test');
var fs = require('fs');
var path = require('path');

module.exports = function (grunt) {
    // 初始化工程配置
    grunt.initConfig({
        // NPM模块依赖
        pkg: grunt.file.readJSON('package.json'),
        // 环境配置（测试/开发/生产）
        env: {
            test: {
                NODE_ENV: 'test'
            },
            dev: {
                NODE_ENV: 'development'
            },
            prod: {
                NODE_ENV: 'production'
            }
        },
        // 监视文件，当CSS和JS代码发生变化时，对代码进行检查，当SCSS
        // 和LESS文件发生变化时，先预编译成CSS代码，再进行CSS代码检查
        watch: {
            serverViews: {
                files: defaultAssets.server.views,
                options: {
                    livereload: true
                }
            },
            serverJS: {
                files: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.allJS),
                tasks: ['jshint'],
                options: {
                    livereload: true
                }
            },
            clientViews: {
                files: defaultAssets.client.views,
                options: {
                    livereload: true
                }
            },
            clientJS: {
                files: defaultAssets.client.js,
                tasks: ['jshint'],
                options: {
                    livereload: true
                }
            },
            clientCSS: {
                files: defaultAssets.client.css,
                tasks: ['csslint'],
                options: {
                    livereload: true
                }
            },
            clientSCSS: {
                files: defaultAssets.client.sass,
                tasks: ['sass', 'csslint'],
                options: {
                    livereload: true
                }
            },
            clientLESS: {
                files: defaultAssets.client.less,
                tasks: ['less', 'csslint'],
                options: {
                    livereload: true
                }
            }
        },
        // 定义服务器端文件监视，如有变化则重启服务器
        nodemon: {
            dev: {
                script: 'server.js',
                options: {
                    nodeArgs: ['--debug'],
                    ext: 'js,html',
                    watch: _.union(
                        defaultAssets.server.gruntConfig,
                        defaultAssets.server.views,
                        defaultAssets.server.allJS,
                        defaultAssets.server.config
                    )
                }
            }
        },
        // 定义并发执行的grunt任务
        concurrent: {
            default: ['nodemon', 'watch'],
            debug: ['nodemon', 'watch', 'node-inspector'],
            options: {
                logConcurrentOutput: true
            }
        },
        // 检查JS代码
        jshint: {
            all: {
                src: _.union(
                    defaultAssets.server.gruntConfig,
                    defaultAssets.server.allJS,
                    defaultAssets.client.js,
                    testAssets.tests.server,
                    testAssets.tests.client,
                    testAssets.tests.e2e
                ),
                options: {
                    jshintrc: true,
                    node: true,
                    mocha: true,
                    jasmine: true
                }
            }
        },
        // 检查CSS代码
        csslint: {
            all: {
                src: defaultAssets.client.css
            },
            options: {
                csslintrc: '.csslintrc'
            }
        },
        // 合并客户端AngularJS代码
        ngAnnotate: {
            production: {
                files: {
                    'public/dist/application.js': defaultAssets.client.js
                }
            }
        },
        // 压缩客户端JS代码，但不混淆变量名
        uglify: {
            production: {
                options: {
                    mangle: false
                },
                files: {
                    'public/dist/application.min.js': 'public/dist/application.js'
                }
            }
        },
        // 压缩客户端CSS代码
        cssmin: {
            combine: {
                files: {
                    'public/dist/application.min.css': defaultAssets.client.css
                }
            }
        },
        // 预编译SASS文件成CSS文件
        sass: {
            dist: {
                files: [{
                    expand: true,
                    src: defaultAssets.client.sass,
                    ext: '.css',
                    rename: function (base, src) {
                        return src.replace('/scss/', '/css/');
                    }
                }]
            }
        },
        // 预编译LESS文件成CSS文件
        less: {
            dist: {
                files: [{
                    expand: true,
                    src: defaultAssets.client.less,
                    ext: '.css',
                    rename: function (base, src) {
                        return src.replace('/less/', '/css/');
                    }
                }]
            }
        },
        // Node调试工具配置
        'node-inspector': {
            custom: {
                options: {
                    'web-port': 1337,
                    'web-host': 'localhost',
                    'debug-port': 5858,
                    'save-live-edit': true,
                    'no-preload': true,
                    'stack-trace-limit': 50,
                    'hidden': []
                }
            }
        },
        // Mocha测试配置
        mochaTest: {
            src: testAssets.tests.server,
            options: {
                reporter: 'spec'
            }
        },
        // Mocha测试覆盖率报告配置
        mocha_istanbul: {
            coverage: {
                src: testAssets.tests.server,
                options: {
                    print: 'detail',
                    coverage: true,
                    require: 'test.js',
                    coverageFolder: 'coverage',
                    reportFormats: ['cobertura','lcovonly'],
                    check: {
                        lines: 40,
                        statements: 40
                    }
                }
            }
        },
        // Karma单元测试配置
        karma: {
            unit: {
                configFile: 'karma.conf.js'
            }
        },
        // Protractor端对端测试配置
        protractor: {
            options: {
                configFile: 'protractor.conf.js',
                keepAlive: true,
                noColor: false
            },
            e2e: {
                options: {
                    args: {}
                }
            }
        },
        // 当本地配置文件local.js不存在时，复制一份本地
        // local.example.js文件作为本地的local.js
        copy: {
            localConfig: {
                src: 'config/env/local.example.js',
                dest: 'config/env/local.js',
                filter: function () {
                    return !fs.existsSync('config/env/local.js');
                }
            }
        }
    });

    // 为Mocha测试覆盖率报告生成事件注册回调
    grunt.event.on('coverage', function(lcovFileContents, done) {
        require('coveralls').handleInput(lcovFileContents, function(err) {
            if (err) {
                return done(err);
            }
            done();
        });
    });

    // 加载grunt任务
    require('load-grunt-tasks')(grunt);

    // 注册mkdir:upload任务，创建upload文件夹
    grunt.task.registerTask('mkdir:upload', 'Task that makes sure upload directory exists.', function () {
        // 获取回调函数
        var done = this.async();
        grunt.file.mkdir(path.normalize(__dirname + '/modules/users/client/img/profile/uploads'));
        done();
    });

    // 注册mongoose任务，连接到MongoDB实例并加载模型
    grunt.task.registerTask('mongoose', 'Task that connects to the MongoDB instance and loads the application models.', function () {
        // 获取回调函数
        var done = this.async();

        var mongoose = require('./config/lib/mongoose.js');
        mongoose.connect(function (db) {
            done();
        });
    });

    // 注册server任务，启动服务器
    grunt.task.registerTask('server', 'Starting the server', function () {
        // 获取回调函数
        var done = this.async();

        var path = require('path');
        var app = require(path.resolve('./config/lib/app'));
        var server = app.start(function () {
            done();
        });
    });

    // 注册lint任务，检查所有CSS和JS文件
    grunt.registerTask('lint', ['sass', 'less', 'jshint', 'csslint']);

    // 注册build任务，检查所有CSS和JS文件并压缩成两个工程文件
    grunt.registerTask('build', ['env:dev', 'lint', 'ngAnnotate', 'uglify', 'cssmin']);

    // 注册test系列任务，运行测试代码，其中：
    // test任务：运行Mocha与Karma测试服务器端
    // test:server：只执行服务器端的Mocha测试
    // test:client：只执行客户器端的Karma测试
    grunt.registerTask('test', ['env:test', 'lint', 'mkdir:upload', 'copy:localConfig', 'server', 'mochaTest', 'karma:unit']);
    grunt.registerTask('test:server', ['env:test', 'lint', 'server', 'mochaTest']);
    grunt.registerTask('test:client', ['env:test', 'lint', 'server', 'karma:unit']);

    // 注册coverage任务，生成测试覆盖率报告
    grunt.registerTask('coverage', ['env:test', 'lint', 'mocha_istanbul:coverage']);

    // 注册default任务，在开发模式下运行整个工程
    grunt.registerTask('default', ['env:dev', 'lint', 'mkdir:upload', 'copy:localConfig', 'concurrent:default']);

    // 注册debug任务，在开发模式下运行整个工程并启动调试工具
    grunt.registerTask('debug', ['env:dev', 'lint', 'mkdir:upload', 'copy:localConfig', 'concurrent:debug']);

    // 注册prod任务，在生产模式下运行整个工程
    grunt.registerTask('prod', ['build', 'env:prod', 'mkdir:upload', 'copy:localConfig', 'concurrent:default']);
};
<|endoftext|>


<commit_before>// Imports {{{
var _ = require('lodash');
var $ = require('jquery');
var angular = require('angular');
var electron = require('electron');
var Highcharts = require('highcharts');
var moment = require('moment');
// }}}

// User configurable options
var options = {
	chartPeriod: moment.duration(1, 'hour').as('milliseconds'), // How far backwards each chart should log - this period effectvely equals the X axis range
	chartPeriodCleanup: moment.duration(5, 'minutes').as('milliseconds'), // Clean up chart data periodically
	conkieStatsModules: [ // Modules we want Conkie stats to load
		'cpu',
		'dropbox',
		'io', // Also provides 'topIO'
		'memory',
		'net',
		'power',
		'system',
		'temperature',
		'topCPU',
		'topMemory',
	],
	conkieStats: { // Options passed to conkie-stats
		topProcessCount: 5,
		net: {
			ignoreNoIP: true,
			ignoreDevice: ['lo'],
		},
	},
	mainBattery: ['BAT0', 'BAT1'], // Which battery to examine for power info (the first one found gets bound to $scope.stats.battery)
	window: {
		left: -10,
		top: 40,
		width: 240,
		height: 1000,
	},
};

// Code only below this line - here be dragons
// -------------------------------------------

var app = angular.module('app', [
	'highcharts-ng',
]);

// Angular / Filters {{{
/**
* Format a given number of seconds as a human readable duration
* e.g. 65 => '1m 5s'
* @param number value The value to process
* @return string The formatted value
*/
app.filter('duration', function() {
	return function(value) {
		if (!value || !isFinite(value)) return;

		var duration = moment.duration(value, 'seconds');
		if (!duration) return;

		var out = '';

		var hours = duration.hours();
		if (hours) out += hours + 'h ';

		var minutes = duration.minutes();
		if (minutes) out += minutes + 'm ';

		var seconds = duration.seconds();
		if (seconds) out += seconds + 's';

		return out;
	};
});

/**
* Return a formatted number as a file size
* e.g. 0 => 0B, 1024 => 1 kB
* @param mixed value The value to format
* @param boolean forceZero Whether the filter should return '0 B' if it doesnt know what to do
* @return string The formatted value
*/
app.filter('byteSize', function() {
	return function(value, forceZero) {
		if (!value || !isFinite(value)) return (forceZero ? '0 B' : null);

		var exponent;
		var unit;
		var neg = value < 0;
		var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

		if (neg) {
			value = -value;
		}

		if (value < 1) {
			return (neg ? '-' : '') + value + ' B';
		}

		exponent = Math.min(Math.floor(Math.log(value) / Math.log(1000)), units.length - 1);
		value = (value / Math.pow(1000, exponent)).toFixed(2) * 1;
		unit = units[exponent];

		return (neg ? '-' : '') + value + ' ' + unit;
	};
});

/**
* Return a number as a formatted percentage
* @param mixed value The value to format
* @return string The formatted value
*/
app.filter('percent', function() {
	return function(value) {
		if (!value || !isFinite(value)) return '';

		return Math.round(value, 2) + '%';
	};
});

// }}}

/**
* The main Conkie controller
* Each of the data feeds are exposed via the 'stats' structure and correspond to the output of [Conkie-Stats](https://github.com/hash-bang/Conkie-Stats)
*/
app.controller('conkieController', function($scope, $interval, $timeout) {
	// .stats - backend-IPC provided stats object {{{
	$scope.stats = {}; // Stats object (gets updated via IPC)

	electron.ipcRenderer
		// Event: updateStats {{{
		.on('updateStats', function(e, data) {
			$scope.$apply(function() {
				var now = new Date();
				$scope.stats = data;

				// Chart data updates {{{

				// .stats.power {{{
				if ($scope.stats.power) {
					$scope.stats.battery = $scope.stats.power.find(function(dev) {
						return (_.contains(options.mainBattery, dev.device));
					});
					if ($scope.stats.battery) $scope.charts.battery.series[0].data.push([now, $scope.stats.battery.percent]);
				}
				// }}}

				// .stats.io {{{
				if (isFinite($scope.stats.io.totalRead)) $scope.charts.io.series[0].data.push([now, $scope.stats.io.totalRead]);
				// }}}

				// .stats.memory {{{
				if (isFinite($scope.stats.memory.used)) {
					if ($scope.stats.memory.total) $scope.charts.memory.yAxis.max = $scope.stats.memory.total;
					$scope.charts.memory.series[0].data.push([now, $scope.stats.memory.used]);
				}
				// }}}

				// .net {{{
				$scope.stats.net.forEach(function(adapter) {
					var id = adapter.interface; // Use the adapter interface name as the chart name
					// Not seen this adapter before - create a chart object {{{
					if (!$scope.charts[id]) $scope.charts[id] = _.defaultsDeep({
						yAxis: {
							min: 0,
							max: null,
						},
						series: [
							{
								// name: 'Download',
								data: [],
								color: '#FFFFFF',
							},
							{
								name: 'Upload',
								color: '#606060',
								fillColor: 'rgba(144,144,144,0.25)',
								data: [],
							},
						],
					}, $scope.charts.template);
					// }}}
					// Append bandwidth data to the chart {{{
					if (isFinite(adapter.downSpeed)) $scope.charts[id].series[0].data.push([now, adapter.downSpeed]);
					if (isFinite(adapter.upSpeed)) $scope.charts[id].series[1].data.push([now, adapter.upSpeed]);
					// }}}
				});
				// }}}

				// .stats.system {{{
				if (isFinite($scope.stats.system.cpuUsage)) $scope.charts.cpu.series[0].data.push([now, $scope.stats.system.cpuUsage]);
				// }}}

				// META: .stats.netTotal {{{
				$scope.stats.netTotal = $scope.stats.net.reduce(function(total, adapter) {
					if (adapter.downSpeed) total.downSpeed += adapter.downSpeed;
					if (adapter.upSpeed) total.upSpeed += adapter.upSpeed;
					return total;
				}, {
					downSpeed: 0,
					upSpeed: 0,
				});
				// }}}

				// Change the periodStart of each chart {{{
				_.forEach($scope.charts, function(chart, id) {
					chart.options.xAxis.periodStart = new Date(now - options.chartPeriod);
				});
				// }}}
				// }}}

			});
		})
	// }}}
	// Configure conkie-stats to provide us with information {{{
	$timeout(function() {
		electron.ipcRenderer
			.send('statsRegister', options.conkieStatsModules)
	});
	$timeout(function() {
		electron.ipcRenderer
			.send('statsSettings', options.conkieStats);
	});
	// }}}
	// Position the widget {{{
	$timeout(function() {
		electron.ipcRenderer
			.send('setPosition', options.window);
	});
	// }}}
	// Periodically clean up redundent data for all charts {{{
	$interval(function() {
		console.log('CLEAN!');
		var cleanTo = Date.now() - options.chartPeriod;
		_.forEach($scope.charts, function(chart, id) {
			_.forEach(chart.series, function(series, seriesIndex) {
				// Shift all data if the date has fallen off the observed time range
				console.log('CLEAN', id, seriesIndex, series.data);
				series.data = _.dropWhile(series.data, function(d) {
					return (d[0] < cleanTo);
				});
				console.log('CLEANS', id, series.data);
			});
		});
	}, options.chartPeriodCleanup);
	// }}}
	// }}}

	// .time {{{
	$interval(function() {
		$scope.time = moment().format('HH:mm');
	}, 1000);
	// }}}

	// Charts {{{
	$scope.charts = {};
	$scope.charts.template = {
		size: {
			width: 150,
			height: 33,
		},
		options: {
			chart: {
				animation: false,
				borderWidth: 0,
				type: 'area',
				margin: [2, 0, 2, 0],
				backgroundColor: null,
				borderWidth: 0,
				style: {
					border: '1px solid white',
				},
			},
			credits: {
				enabled: false
			},
			title: {
				text: ''
			},
			xAxis: {
				type: 'datetime',
				periodStart: new Date(Date.now() - options.chartPeriod),
				labels: {
					enabled: false
				},
				title: {
					text: null
				},
				startOnTick: false,
				endOnTick: false,
				tickPositions: [],
			},
			yAxis: {
				labels: {
					enabled: false
				},
				title: {
					text: null
				},
				endOnTick: false,
				startOnTick: false,
				tickPositions: [0],
			},
			legend: {
				enabled: false,
			},
			tooltip: {
				enabled: false,
			},
			plotOptions: {
				series: {
					animation: false,
					lineWidth: 1,
					shadow: false,
					states: {
						hover: {
							lineWidth: 1
						}
					},
					marker: {
						radius: 1,
						states: {
							hover: {
								radius: 2
							}
						}
					},
					fillOpacity: 0.25
				},
				column: {
					negativeColor: '#910000',
					borderColor: 'silver'
				},
			},
		},
	};

	$scope.charts.battery = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: 100,
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);

	$scope.charts.memory = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: null, // Gets corrected on next stats cycle
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);

	$scope.charts.cpu = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: 100,
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);

	$scope.charts.io = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: null,
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);
	// }}}
});
<commit_msg>BUGFIX: Default theme using wrong reading for CPU stats<commit_after>// Imports {{{
var _ = require('lodash');
var $ = require('jquery');
var angular = require('angular');
var electron = require('electron');
var Highcharts = require('highcharts');
var moment = require('moment');
// }}}

// User configurable options
var options = {
	chartPeriod: moment.duration(1, 'hour').as('milliseconds'), // How far backwards each chart should log - this period effectvely equals the X axis range
	chartPeriodCleanup: moment.duration(5, 'minutes').as('milliseconds'), // Clean up chart data periodically
	conkieStatsModules: [ // Modules we want Conkie stats to load
		'cpu',
		'dropbox',
		'io', // Also provides 'topIO'
		'memory',
		'net',
		'power',
		'system',
		'temperature',
		'topCPU',
		'topMemory',
	],
	conkieStats: { // Options passed to conkie-stats
		topProcessCount: 5,
		net: {
			ignoreNoIP: true,
			ignoreDevice: ['lo'],
		},
	},
	mainBattery: ['BAT0', 'BAT1'], // Which battery to examine for power info (the first one found gets bound to $scope.stats.battery)
	window: {
		left: -10,
		top: 40,
		width: 240,
		height: 1000,
	},
};

// Code only below this line - here be dragons
// -------------------------------------------

var app = angular.module('app', [
	'highcharts-ng',
]);

// Angular / Filters {{{
/**
* Format a given number of seconds as a human readable duration
* e.g. 65 => '1m 5s'
* @param number value The value to process
* @return string The formatted value
*/
app.filter('duration', function() {
	return function(value) {
		if (!value || !isFinite(value)) return;

		var duration = moment.duration(value, 'seconds');
		if (!duration) return;

		var out = '';

		var hours = duration.hours();
		if (hours) out += hours + 'h ';

		var minutes = duration.minutes();
		if (minutes) out += minutes + 'm ';

		var seconds = duration.seconds();
		if (seconds) out += seconds + 's';

		return out;
	};
});

/**
* Return a formatted number as a file size
* e.g. 0 => 0B, 1024 => 1 kB
* @param mixed value The value to format
* @param boolean forceZero Whether the filter should return '0 B' if it doesnt know what to do
* @return string The formatted value
*/
app.filter('byteSize', function() {
	return function(value, forceZero) {
		if (!value || !isFinite(value)) return (forceZero ? '0 B' : null);

		var exponent;
		var unit;
		var neg = value < 0;
		var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

		if (neg) {
			value = -value;
		}

		if (value < 1) {
			return (neg ? '-' : '') + value + ' B';
		}

		exponent = Math.min(Math.floor(Math.log(value) / Math.log(1000)), units.length - 1);
		value = (value / Math.pow(1000, exponent)).toFixed(2) * 1;
		unit = units[exponent];

		return (neg ? '-' : '') + value + ' ' + unit;
	};
});

/**
* Return a number as a formatted percentage
* @param mixed value The value to format
* @return string The formatted value
*/
app.filter('percent', function() {
	return function(value) {
		if (!value || !isFinite(value)) return '';

		return Math.round(value, 2) + '%';
	};
});

// }}}

/**
* The main Conkie controller
* Each of the data feeds are exposed via the 'stats' structure and correspond to the output of [Conkie-Stats](https://github.com/hash-bang/Conkie-Stats)
*/
app.controller('conkieController', function($scope, $interval, $timeout) {
	// .stats - backend-IPC provided stats object {{{
	$scope.stats = {}; // Stats object (gets updated via IPC)

	electron.ipcRenderer
		// Event: updateStats {{{
		.on('updateStats', function(e, data) {
			$scope.$apply(function() {
				var now = new Date();
				$scope.stats = data;

				// Chart data updates {{{

				// .stats.power {{{
				if ($scope.stats.power) {
					$scope.stats.battery = $scope.stats.power.find(function(dev) {
						return (_.contains(options.mainBattery, dev.device));
					});
					if ($scope.stats.battery) $scope.charts.battery.series[0].data.push([now, $scope.stats.battery.percent]);
				}
				// }}}

				// .stats.io {{{
				if (isFinite($scope.stats.io.totalRead)) $scope.charts.io.series[0].data.push([now, $scope.stats.io.totalRead]);
				// }}}

				// .stats.memory {{{
				if (isFinite($scope.stats.memory.used)) {
					if ($scope.stats.memory.total) $scope.charts.memory.yAxis.max = $scope.stats.memory.total;
					$scope.charts.memory.series[0].data.push([now, $scope.stats.memory.used]);
				}
				// }}}

				// .net {{{
				$scope.stats.net.forEach(function(adapter) {
					var id = adapter.interface; // Use the adapter interface name as the chart name
					// Not seen this adapter before - create a chart object {{{
					if (!$scope.charts[id]) $scope.charts[id] = _.defaultsDeep({
						yAxis: {
							min: 0,
							max: null,
						},
						series: [
							{
								// name: 'Download',
								data: [],
								color: '#FFFFFF',
							},
							{
								name: 'Upload',
								color: '#606060',
								fillColor: 'rgba(144,144,144,0.25)',
								data: [],
							},
						],
					}, $scope.charts.template);
					// }}}
					// Append bandwidth data to the chart {{{
					if (isFinite(adapter.downSpeed)) $scope.charts[id].series[0].data.push([now, adapter.downSpeed]);
					if (isFinite(adapter.upSpeed)) $scope.charts[id].series[1].data.push([now, adapter.upSpeed]);
					// }}}
				});
				// }}}

				// .stats.system {{{
				if (isFinite($scope.stats.cpu.usage)) $scope.charts.cpu.series[0].data.push([now, $scope.stats.cpu.usage]);
				// }}}

				// META: .stats.netTotal {{{
				$scope.stats.netTotal = $scope.stats.net.reduce(function(total, adapter) {
					if (adapter.downSpeed) total.downSpeed += adapter.downSpeed;
					if (adapter.upSpeed) total.upSpeed += adapter.upSpeed;
					return total;
				}, {
					downSpeed: 0,
					upSpeed: 0,
				});
				// }}}

				// Change the periodStart of each chart {{{
				_.forEach($scope.charts, function(chart, id) {
					chart.options.xAxis.periodStart = new Date(now - options.chartPeriod);
				});
				// }}}
				// }}}

			});
		})
	// }}}
	// Configure conkie-stats to provide us with information {{{
	$timeout(function() {
		electron.ipcRenderer
			.send('statsRegister', options.conkieStatsModules)
	});
	$timeout(function() {
		electron.ipcRenderer
			.send('statsSettings', options.conkieStats);
	});
	// }}}
	// Position the widget {{{
	$timeout(function() {
		electron.ipcRenderer
			.send('setPosition', options.window);
	});
	// }}}
	// Periodically clean up redundent data for all charts {{{
	$interval(function() {
		console.log('CLEAN!');
		var cleanTo = Date.now() - options.chartPeriod;
		_.forEach($scope.charts, function(chart, id) {
			_.forEach(chart.series, function(series, seriesIndex) {
				// Shift all data if the date has fallen off the observed time range
				console.log('CLEAN', id, seriesIndex, series.data);
				series.data = _.dropWhile(series.data, function(d) {
					return (d[0] < cleanTo);
				});
				console.log('CLEANS', id, series.data);
			});
		});
	}, options.chartPeriodCleanup);
	// }}}
	// }}}

	// .time {{{
	$interval(function() {
		$scope.time = moment().format('HH:mm');
	}, 1000);
	// }}}

	// Charts {{{
	$scope.charts = {};
	$scope.charts.template = {
		size: {
			width: 150,
			height: 33,
		},
		options: {
			chart: {
				animation: false,
				borderWidth: 0,
				type: 'area',
				margin: [2, 0, 2, 0],
				backgroundColor: null,
				borderWidth: 0,
				style: {
					border: '1px solid white',
				},
			},
			credits: {
				enabled: false
			},
			title: {
				text: ''
			},
			xAxis: {
				type: 'datetime',
				periodStart: new Date(Date.now() - options.chartPeriod),
				labels: {
					enabled: false
				},
				title: {
					text: null
				},
				startOnTick: false,
				endOnTick: false,
				tickPositions: [],
			},
			yAxis: {
				labels: {
					enabled: false
				},
				title: {
					text: null
				},
				endOnTick: false,
				startOnTick: false,
				tickPositions: [0],
			},
			legend: {
				enabled: false,
			},
			tooltip: {
				enabled: false,
			},
			plotOptions: {
				series: {
					animation: false,
					lineWidth: 1,
					shadow: false,
					states: {
						hover: {
							lineWidth: 1
						}
					},
					marker: {
						radius: 1,
						states: {
							hover: {
								radius: 2
							}
						}
					},
					fillOpacity: 0.25
				},
				column: {
					negativeColor: '#910000',
					borderColor: 'silver'
				},
			},
		},
	};

	$scope.charts.battery = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: 100,
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);

	$scope.charts.memory = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: null, // Gets corrected on next stats cycle
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);

	$scope.charts.cpu = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: 100,
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);

	$scope.charts.io = _.defaultsDeep({
		yAxis: {
			min: 0,
			max: null,
		},
		series: [{
			data: [],
			color: '#FFFFFF',
		}],
	}, $scope.charts.template);
	// }}}
});
<|endoftext|>


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

    pkgFile: 'package.json',

    eslint: {
      target: [
        '*.js'
      ]
    },

    conventionalChangelog: {
      release: {
        options: {
          changelogOpts: {
            preset: 'angular'
          }
        },
        src: 'CHANGELOG.md'
      }
    },

    conventionalGithubReleaser: {
      release: {
        options: {
          auth: {
            type: 'oauth',
            token: process.env.GH_TOKEN
          },
          changelogOpts: {
            preset: 'angular'
          }
        }
      }
    },

    bump: {
      options: {
        commitMessage: 'chore: release v%VERSION%',
        pushTo: 'upstream',
        commitFiles: [
          'package.json',
          'CHANGELOG.md'
        ]
      }
    },

    'npm-contributors': {
      options: {
        commitMessage: 'chore: Update contributors'
      }
    }
  })

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

  grunt.registerTask('default', ['eslint'])

  grunt.registerTask('release', 'Bump the version and publish to npm.', function (type) {
    grunt.task.run([
      'npm-contributors',
      'bump:' + (type || 'patch') + ':bump-only',
      'changelog',
      'bump-commit',
      'npm-publish'
    ])
  })
}
<commit_msg>chore: fix release task<commit_after>module.exports = function (grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    pkgFile: 'package.json',

    eslint: {
      target: [
        '*.js'
      ]
    },

    conventionalChangelog: {
      release: {
        options: {
          changelogOpts: {
            preset: 'angular'
          }
        },
        src: 'CHANGELOG.md'
      }
    },

    conventionalGithubReleaser: {
      release: {
        options: {
          auth: {
            type: 'oauth',
            token: process.env.GH_TOKEN
          },
          changelogOpts: {
            preset: 'angular'
          }
        }
      }
    },

    bump: {
      options: {
        commitMessage: 'chore: release v%VERSION%',
        pushTo: 'upstream',
        commitFiles: [
          'package.json',
          'CHANGELOG.md'
        ]
      }
    },

    'npm-contributors': {
      options: {
        commitMessage: 'chore: Update contributors'
      }
    }
  })

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

  grunt.registerTask('default', ['eslint'])

  grunt.registerTask('release', 'Bump the version and publish to npm.', function (type) {
    grunt.task.run([
      'npm-contributors',
      'bump:' + (type || 'patch') + ':bump-only',
      'conventionalChangelog',
      'bump-commit',
      'conventionalGithubReleaser',
      'npm-publish'
    ])
  })
}
<|endoftext|>


<commit_before>/*
 * ScratchX extension for WebAudio Oscillator
 *
 * yokobond <koji.yokokawa@yengawa.com>
 */

(function (ext) {
    var audioctx;
    if (typeof (webkitAudioContext) !== "undefined") {
        audioctx = new webkitAudioContext();
    }
    else if (typeof (AudioContext) !== "undefined") {
        audioctx = new AudioContext();
    }

    function Oscillator(waveType, freqValue, gainValue) {
        this.oscillator = audioctx.createOscillator();
        this.gainNode = audioctx.createGain();
        this.oscillator.connect(this.gainNode);
        this.oscillator.type = waveType || 'sine';
        this.oscillator.frequency.value = freqValue || 440;
        this.gainValue = gainValue || 0.5;
        this.gainNode.value = this.gainValue;
        this.isPlaying = false;
    }

    Oscillator.prototype.getType = function () {
        return this.oscillator.type;
    };

    Oscillator.prototype.setType = function (type) {
        this.oscillator.type = type;
        return this;
    };

    Oscillator.prototype.getFrequency = function () {
        return this.oscillator.frequency.value;
    };

    Oscillator.prototype.setFrequency = function (freqValue) {
        this.oscillator.frequency.value = freqValue;
        return this;
    };

    Oscillator.prototype.getGain = function () {
        return this.gainValue;
    };

    Oscillator.prototype.setGain = function (gainValue) {
        this.gainValue = gainValue;
        if (this.isPlaying) {
            this.gainNode.gain.value = gainValue;
        }
        return this;
    };

    Oscillator.prototype.isConnected = function () {
        return (this.gainNode.numberOfOutputs() > 0);
    };

    Oscillator.prototype.connect = function () {
        this.gainNode.connect(audioctx.destination);
        return this;
    };

    Oscillator.prototype.disconnect = function () {
        this.gainNode.disconnect(audioctx.destination);
        return this;
    };

    Oscillator.prototype.start = function () {
        this.oscillator.start();
        return this;
    };

    Oscillator.prototype.stop = function () {
        this.oscillator.stop();
        return this;
    };

    Oscillator.prototype.mute = function () {
        if (!this.isPlaying) return;
        this.setGain(0);
        this.isPlaying = false;
        return this;
    };

    Oscillator.prototype.play = function () {
        this.isPlaying = true;
        this.setGain(this.gainValue);
        return this;
    };

    // initialize oscillators
    var oscs = {};
    var oscNames = ["1", "2", "3", "4"];

    /**
     * return oscillator can be start.
     */
    function getOscillator(oscName) {
        let name = oscName || oscNames[0];
        if (!oscs[oscName]) {
            oscs[oscName] = new Oscillator();
            oscs[oscName].start();
        }
        return oscs[oscName];
    }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function () {
        for (let name of oscNames) {
            oscs[name].stop();
            oscs[name] = null;
        }
    };

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function () {
        return {status: 2, msg: 'Ready'};
    };

    ext.getOscillatorType = function (oscName) {
        return getOscillator(oscName).getType();
    };

    ext.setOscillatorType = function (oscName, type) {
        getOscillator(oscName).setType(type);
    };

    ext.getOscillatorFrequency = function (oscName) {
        return getOscillator(oscName).getFrequency();
    };

    ext.setOscillatorFrequency = function (oscName, freqValue) {
        getOscillator(oscName).setFrequency(freqValue);
    };

    ext.getOscillatorGain = function (oscName) {
        return getOscillator(oscName).getGain();
    };

    ext.setOscillatorGain = function (oscName, gainValue) {
        getOscillator(oscName).setGain(gainValue);
    };

    ext.playOscillator = function (oscName) {
        getOscillator(oscName).play();
    };

    ext.muteOscillator = function (oscName) {
        getOscillator(oscName).mute();
    };

    ext.oscillatorIsPlaying = function (oscName) {
        return getOscillator(oscName).isPlaying;
    };

    ext.muteAllOscillators = function () {
        for (let name of oscNames) {
            ext.muteOscillator(name);
        }
    };

    ext.connectOscillator = function (oscName) {
        getOscillator(oscName).connect();
    };

    ext.disconnectOscillator = function (oscName) {
        if (!oscs[oscName]) return;
        oscs[oscName].disconnect();
    };

    ext.oscillatorIsConnected = function (oscName) {
        if (!oscs[oscName]) return false;
        return oscs[oscName].isConnected();
    };

    ext.disconnectAllOscillators = function () {
        for (let name of oscNames) {
            ext.disconnectOscillator(name);
        }
    };

    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            // Block type, block name, function name
            ['r', 'oscillator %m.oscName is playing', 'oscillatorIsPlaying', oscNames[0]],
            [' ', 'play oscillator %m.oscName', 'playOscillator', oscNames[0]],
            [' ', 'mute oscillator %m.oscName', 'muteOscillator', oscNames[0]],
            ['r', 'oscillator %m.oscName type', 'getOscillatorType', oscNames[0]],
            [' ', 'set oscillator %m.oscName type %m.waveType', 'setOscillatorType', oscNames[0], 'sine'],
            ['r', 'oscillator %m.oscName frequency', 'getOscillatorFrequency', oscNames[0]],
            [' ', 'set oscillator %m.oscName frequency %n', 'setOscillatorFrequency', oscNames[0], 440],
            ['r', 'oscillator %m.oscName gain', 'getOscillatorGain', oscNames[0]],
            [' ', 'set oscillator %m.oscName gain %n', 'setOscillatorGain', oscNames[0], 0.5],
            [' ', 'mute all oscillators', 'muteAllOscillators']
        ],
        menus: {
            oscName: oscNames,
            waveType: ['sine', 'square', 'sawtooth', 'triangle']
        }
    };

    // Register the extension
    ScratchExtensions.register('WebAudio Oscillator', descriptor, ext);
})({});

<commit_msg>Fix to work play/mute.<commit_after>/*
 * ScratchX extension for WebAudio Oscillator
 *
 * yokobond <koji.yokokawa@yengawa.com>
 */

(function (ext) {
    var audioctx;
    if (typeof (webkitAudioContext) !== "undefined") {
        audioctx = new webkitAudioContext();
    }
    else if (typeof (AudioContext) !== "undefined") {
        audioctx = new AudioContext();
    }

    function Oscillator(waveType, freqValue, gainValue) {
        this.oscillator = audioctx.createOscillator();
        this.gainNode = audioctx.createGain();
        this.oscillator.connect(this.gainNode);
        this.oscillator.type = waveType || 'sine';
        this.oscillator.frequency.value = freqValue || 440;
        this.gainValue = gainValue || 0.5;
        this.gainNode.value = this.gainValue;
        this.isPlaying = false;
    }

    Oscillator.prototype.getType = function () {
        return this.oscillator.type;
    };

    Oscillator.prototype.setType = function (type) {
        this.oscillator.type = type;
        return this;
    };

    Oscillator.prototype.getFrequency = function () {
        return this.oscillator.frequency.value;
    };

    Oscillator.prototype.setFrequency = function (freqValue) {
        this.oscillator.frequency.value = freqValue;
        return this;
    };

    Oscillator.prototype.getGain = function () {
        return this.gainValue;
    };

    Oscillator.prototype.setGain = function (gainValue) {
        this.gainValue = gainValue;
        if (this.isPlaying) {
            this.gainNode.gain.value = gainValue;
        }
        return this;
    };

    Oscillator.prototype.isConnected = function () {
        return (this.gainNode.numberOfOutputs() > 0);
    };

    Oscillator.prototype.connect = function () {
        this.gainNode.connect(audioctx.destination);
        return this;
    };

    Oscillator.prototype.disconnect = function () {
        this.gainNode.disconnect(audioctx.destination);
        return this;
    };

    Oscillator.prototype.start = function () {
        this.oscillator.start();
        return this;
    };

    Oscillator.prototype.stop = function () {
        this.oscillator.stop();
        return this;
    };

    Oscillator.prototype.mute = function () {
        if (!this.isPlaying) return;
        this.gainNode.gain.value = 0;
        this.isPlaying = false;
        return this;
    };

    Oscillator.prototype.play = function () {
        this.isPlaying = true;
        this.gainNode.gain.value = this.gainValue;
        return this;
    };

    // initialize oscillators
    var oscs = {};
    var oscNames = ["1", "2", "3", "4"];

    /**
     * return oscillator can be start.
     */
    function getOscillator(oscName) {
        let name = oscName || oscNames[0];
        if (!oscs[oscName]) {
            oscs[oscName] = new Oscillator();
            oscs[oscName].start();
        }
        return oscs[oscName];
    }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function () {
        for (let name of oscNames) {
            oscs[name].stop();
            oscs[name] = null;
        }
    };

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function () {
        return {status: 2, msg: 'Ready'};
    };

    ext.getOscillatorType = function (oscName) {
        return getOscillator(oscName).getType();
    };

    ext.setOscillatorType = function (oscName, type) {
        getOscillator(oscName).setType(type);
    };

    ext.getOscillatorFrequency = function (oscName) {
        return getOscillator(oscName).getFrequency();
    };

    ext.setOscillatorFrequency = function (oscName, freqValue) {
        getOscillator(oscName).setFrequency(freqValue);
    };

    ext.getOscillatorGain = function (oscName) {
        return getOscillator(oscName).getGain();
    };

    ext.setOscillatorGain = function (oscName, gainValue) {
        getOscillator(oscName).setGain(gainValue);
    };

    ext.playOscillator = function (oscName) {
        getOscillator(oscName).play();
    };

    ext.muteOscillator = function (oscName) {
        getOscillator(oscName).mute();
    };

    ext.oscillatorIsPlaying = function (oscName) {
        return getOscillator(oscName).isPlaying;
    };

    ext.muteAllOscillators = function () {
        for (let name of oscNames) {
            ext.muteOscillator(name);
        }
    };

    ext.connectOscillator = function (oscName) {
        getOscillator(oscName).connect();
    };

    ext.disconnectOscillator = function (oscName) {
        if (!oscs[oscName]) return;
        oscs[oscName].disconnect();
    };

    ext.oscillatorIsConnected = function (oscName) {
        if (!oscs[oscName]) return false;
        return oscs[oscName].isConnected();
    };

    ext.disconnectAllOscillators = function () {
        for (let name of oscNames) {
            ext.disconnectOscillator(name);
        }
    };

    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            // Block type, block name, function name
            ['r', 'oscillator %m.oscName is playing', 'oscillatorIsPlaying', oscNames[0]],
            [' ', 'play oscillator %m.oscName', 'playOscillator', oscNames[0]],
            [' ', 'mute oscillator %m.oscName', 'muteOscillator', oscNames[0]],
            ['r', 'oscillator %m.oscName type', 'getOscillatorType', oscNames[0]],
            [' ', 'set oscillator %m.oscName type %m.waveType', 'setOscillatorType', oscNames[0], 'sine'],
            ['r', 'oscillator %m.oscName frequency', 'getOscillatorFrequency', oscNames[0]],
            [' ', 'set oscillator %m.oscName frequency %n', 'setOscillatorFrequency', oscNames[0], 440],
            ['r', 'oscillator %m.oscName gain', 'getOscillatorGain', oscNames[0]],
            [' ', 'set oscillator %m.oscName gain %n', 'setOscillatorGain', oscNames[0], 0.5],
            [' ', 'mute all oscillators', 'muteAllOscillators']
        ],
        menus: {
            oscName: oscNames,
            waveType: ['sine', 'square', 'sawtooth', 'triangle']
        }
    };

    // Register the extension
    ScratchExtensions.register('WebAudio Oscillator', descriptor, ext);
})({});

<|endoftext|>


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

  var fs = require('fs');
  require('es6-shim');
  var bower = require('bower');
  var path = require('path');

  var pkgFile = require('./package.json');
  var lyriaConfig = pkgFile.lyriaProject || {};

  var buildPrefix = 'builds';
  var buildVersion = pkgFile.version + '-' + grunt.template.today("yymmdd-HHMMss");
  var buildId = pkgFile.name + '-v' + buildVersion;
  var buildFolder = [buildPrefix, buildId].join('/');

  var libFiles = (fs.existsSync('./lib')) ? fs.readdirSync('./lib') : [];
  var styleFiles = (fs.existsSync('./css')) ? fs.readdirSync('./css') : [];

  var libFilesPriorities = ['almond', 'handlebars', 'fastclick', 'udefine'];

  var templateScripts = {
    development: [],
    production: []
  };
  var templateStyles = [];

  var uglifyLibObject = {};

  for (var i = 0, j = libFiles.length; i < j; i++) {
    (function(iterator) {
      uglifyLibObject[path.join(buildFolder, 'lib', iterator)] = path.join('./lib', iterator);
      if (libFilesPriorities.indexOf(iterator) >= 0) {
        templateScripts.unshift('lib/' + iterator);
      } else {
        templateScripts.push('lib/' + iterator);
      }
    })(libFiles[i]);
  }

  uglifyLibObject[buildFolder + '/js/<%= pkg.name %>.js'] = '<%= concat_sourcemap.dist.dest %>';
  //templateScripts.push('js/<%= pkg.name %>.js');

  for (var k = 0, l = styleFiles.length; k < l; k++) {
    (function(iterator) {
      templateStyles.push('css/' + iterator);
    })(styleFiles[k]);
  }

  grunt.initConfig({
    pkg: pkgFile,
    lyriaConfig: lyriaConfig,
    buildVersion: buildVersion,
    buildFolder: buildFolder,
    concat_sourcemap: {
      options: {
        sourcesContent: true,
        sourceRoot: '/'
      },
      dist: {
        src: ['src/**/*.js'],
        dest: 'js/<%= pkg.name %>.js'
      }
    },
    copy: {
      production: {
        files: [{
          expand: true,
          src: ['assets/**'],
          dest: '<%= buildFolder %>/',
          filter: function(filepath) {
            if ((filepath.indexOf('/scenes') >= 0) || (filepath.indexOf('/prefabs') >= 0)) {
              return false;
            } else {
              return true;
            }
          }
        }, {
          expand: true,
          src: ['css/**'],
          dest: '<%= buildFolder %>/'
        }, {
          expand: true,
          src: ['favicon.ico'],
          dest: '<%= buildFolder %>/'
        }, {
          expand: true,
          src: ['*.png'],
          dest: '<%= buildFolder %>/'
        }]
      }
    },
    template: {
      development: {
        src: 'template.html',
        dest: 'index.html',
        engine: 'handlebars',
        variables: {
          livereload: true,
          scripts: templateScripts.development,
          styles: templateStyles,
          mainModule: pkgFile.name,
          title: '<%= lyriaConfig.title %> (Development build <%= buildVersion %>)',
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      },
      production: {
        src: 'template.html',
        dest: '<%= buildFolder %>/index.html',
        engine: 'handlebars',
        variables: {
          livereload: false,
          scripts: templateScripts.production,
          styles: templateStyles,
          mainModule: pkgFile.name,
          title: lyriaConfig.title,
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      }
    },
    uglify: {
      production: {
        files: uglifyLibObject
      }
    },
    compress: {
      deploy: {
        options: {
          archive: '<%= buildFolder %>.zip'
        },
        files: [{
          cwd: '<%= buildFolder %>/',
          src: ['**'],
          dest: '<%= pkg.name %>/'
        }]
      }
    },
    stylus: {
      options: {
        paths: ['stylus', 'stylus/lyria'],
        urlfunc: 'embedurl',
        import: ['nib', 'asset'],
      },
      development: {
        options: {
          compress: false,
          linenos: true
        },
        files: {
          'css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      },
      production: {
        options: {
          compress: true
        },
        files: {
          '<%= buildFolder %>/css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      }
    },
    csslint: {
      lint: {
        src: ['css/mygame.css']
      }
    },
    jshint: {
      assets: {
        src: ['assets/**/*.js']
      },
      source: {
        src: ['src/**/*.js', '!src/generated/**/*.js']
      }
    },
    watch: {
      options: {
        // Start a live reload server on the default port 35729
        livereload: true,
      },
      stylus: {
        files: 'stylus/**/*.styl',
        tasks: ['stylus:development']
      },
      assetList: {
        files: 'assets/**/*',
        tasks: ['lyriaAssetList']
      },
      scenes: {
        files: 'assets/scenes/*',
        tasks: ['lyriaScene']
      },
      i18nData: {
        files: 'assets/i18n/**/*.json',
        tasks: ['lyriaData']
      },
      template: {
        files: 'template.html',
        tasks: ['bower']
      },
      concat: {
        files: 'src/**/*.js',
        tasks: ['concat_sourcemap']
      }
    },
    lyriaData: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        options: {
          name: 'i18n'
        },
        dest: 'src/generated/i18n.js',
        src: ['assets/i18n/**/*.json']
      }
    },
    lyriaAssetList: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        dest: 'src/generated/assetlist.js',
        src: ['assets/**/*', '!**/README.md'],
        filter: 'isFile'
      }
    },
    lyriaScene: {
      all: {
        options: {
          namespace: '<%= pkg.name %>'
        },
        files: [{
          dest: 'src/generated/scenelist.js',
          src: ['assets/scenes/*'],
          filter: 'isDirectory'
        }]
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  grunt.registerTask('bower', 'Prepares scripts using bower components', function() {
    var done = this.async();

    bower.commands.list({
      paths: true
    }).on('end', function(results) {
      var prepareBowerAsset = function(value) {
        value = path.relative(process.cwd(), value);

        // All forward slashes, please
        value = value.split('\\').join('/');

        if (!value.endsWith('.css')) {

          if (!value.endsWith('.js')) {
            value += '/' + key + '.js';
          }

          uglifyLibObject[path.join(buildFolder, 'lib', path.basename(value))] = value;

          if (libFilesPriorities.indexOf(key) >= 0) {
            templateScripts.development.unshift(value);
          } else {
            templateScripts.development.push(value);
          }

        } else {
          templateStyles.unshift(value);
        }
      };

      for (var key in results) {
        var val = results[key];

        if (val.indexOf(',') >= 0) {
          val = val.split(',');
        }

        if (Array.isArray(val)) {
          if (key === 'handlebars') {
            prepareBowerAsset(val[1]);
          }

          for (var i = 0, j = val.length; i < j; i++) {
            if (((path.extname(val[i]) === '.js') && !val[i].endsWith('.min.js')) || path.extname(val[i]) === '.css') {
              prepareBowerAsset(val[i]);
            }
          }
        } else {
          prepareBowerAsset(val);
        }
      }

      templateScripts.development.push('js/<%= pkg.name %>.js');

      grunt.task.run('template:development');
      done();
    });
  });

  grunt.registerTask('prebuild', 'Task before building the project', ['lyriaScene', 'lyriaAssetList', 'lyriaData', 'concat_sourcemap', 'bower']);
  grunt.registerTask('test', 'Lints JavaScript and CSS files', ['jshint']);

  grunt.registerTask('development', 'Development build', ['prebuild', 'stylus:development']);
  grunt.registerTask('production', 'Production build', ['prebuild', 'bower', 'uglify', 'copy', 'stylus:production', 'template:production']);
  grunt.registerTask('deploy', 'Deploys project', ['production', 'compress:deploy']);

  grunt.registerTask('build', 'Builds the default project', ['development']);
  grunt.registerTask('default', 'Default task', ['development']);

  // The future in order
  grunt.registerTask('observe', 'Default task', ['development', 'watch']);

}; <commit_msg>Updated library task<commit_after>module.exports = function(grunt) {

  var fs = require('fs');
  require('es6-shim');
  var bower = require('bower');
  var path = require('path');

  var pkgFile = require('./package.json');
  var lyriaConfig = pkgFile.lyriaProject || {};

  var buildPrefix = 'builds';
  var buildVersion = pkgFile.version + '-' + grunt.template.today("yymmdd-HHMMss");
  var buildId = pkgFile.name + '-v' + buildVersion;
  var buildFolder = [buildPrefix, buildId].join('/');

  var libFiles = (fs.existsSync('./lib')) ? fs.readdirSync('./lib') : [];
  var styleFiles = (fs.existsSync('./css')) ? fs.readdirSync('./css') : [];

  var libFilesPriorities = ['almond', 'handlebars', 'fastclick', 'udefine'];

  var templateScripts = {
    development: [],
    production: []
  };
  var templateStyles = [];

  var uglifyLibObject = {};

  for (var i = 0, j = libFiles.length; i < j; i++) {
    (function(iterator) {
      uglifyLibObject[path.join(buildFolder, 'lib', iterator)] = path.join('./lib', iterator);
      if (libFilesPriorities.indexOf(iterator) >= 0) {
        templateScripts.unshift('lib/' + iterator);
      } else {
        templateScripts.push('lib/' + iterator);
      }
    })(libFiles[i]);
  }

  uglifyLibObject[buildFolder + '/js/<%= pkg.name %>.js'] = '<%= concat_sourcemap.dist.dest %>';
  //templateScripts.push('js/<%= pkg.name %>.js');

  for (var k = 0, l = styleFiles.length; k < l; k++) {
    (function(iterator) {
      templateStyles.push('css/' + iterator);
    })(styleFiles[k]);
  }

  grunt.initConfig({
    pkg: pkgFile,
    lyriaConfig: lyriaConfig,
    buildVersion: buildVersion,
    buildFolder: buildFolder,
    concat_sourcemap: {
      options: {
        sourcesContent: true,
        sourceRoot: '/'
      },
      dist: {
        src: ['src/**/*.js'],
        dest: 'js/<%= pkg.name %>.js'
      }
    },
    copy: {
      production: {
        files: [{
          expand: true,
          src: ['assets/**'],
          dest: '<%= buildFolder %>/',
          filter: function(filepath) {
            if ((filepath.indexOf('/scenes') >= 0) || (filepath.indexOf('/prefabs') >= 0)) {
              return false;
            } else {
              return true;
            }
          }
        }, {
          expand: true,
          src: ['css/**', 'favicon.ico', '*.png'],
          dest: '<%= buildFolder %>/'
        }]
      }
    },
    template: {
      development: {
        src: 'template.html',
        dest: 'index.html',
        engine: 'handlebars',
        variables: {
          livereload: true,
          scripts: templateScripts.development,
          styles: templateStyles,
          mainModule: pkgFile.name,
          title: '<%= lyriaConfig.title %> (Development build <%= buildVersion %>)',
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      },
      production: {
        src: 'template.html',
        dest: '<%= buildFolder %>/index.html',
        engine: 'handlebars',
        variables: {
          livereload: false,
          scripts: templateScripts.production,
          styles: templateStyles,
          mainModule: pkgFile.name,
          title: lyriaConfig.title,
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      }
    },
    uglify: {
      production: {
        files: uglifyLibObject
      }
    },
    compress: {
      deploy: {
        options: {
          archive: '<%= buildFolder %>.zip'
        },
        files: [{
          cwd: '<%= buildFolder %>/',
          src: ['**'],
          dest: '<%= pkg.name %>/'
        }]
      }
    },
    stylus: {
      options: {
        paths: ['stylus', 'stylus/lyria'],
        urlfunc: 'embedurl',
        import: ['nib', 'asset'],
      },
      development: {
        options: {
          compress: false,
          linenos: true
        },
        files: {
          'css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      },
      production: {
        options: {
          compress: true
        },
        files: {
          '<%= buildFolder %>/css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      }
    },
    csslint: {
      lint: {
        src: ['css/mygame.css']
      }
    },
    jshint: {
      assets: {
        src: ['assets/**/*.js']
      },
      source: {
        src: ['src/**/*.js', '!src/generated/**/*.js']
      }
    },
    watch: {
      options: {
        // Start a live reload server on the default port 35729
        livereload: true,
      },
      stylus: {
        files: 'stylus/**/*.styl',
        tasks: ['stylus:development']
      },
      assetList: {
        files: 'assets/**/*',
        tasks: ['lyriaAssetList']
      },
      scenes: {
        files: 'assets/scenes/*',
        tasks: ['lyriaScene']
      },
      i18nData: {
        files: 'assets/i18n/**/*.json',
        tasks: ['lyriaData']
      },
      template: {
        files: 'template.html',
        tasks: ['bower']
      },
      concat: {
        files: 'src/**/*.js',
        tasks: ['concat_sourcemap']
      }
    },
    lyriaData: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        options: {
          name: 'i18n'
        },
        dest: 'src/generated/i18n.js',
        src: ['assets/i18n/**/*.json']
      }
    },
    lyriaAssetList: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        dest: 'src/generated/assetlist.js',
        src: ['assets/**/*', '!**/README.md'],
        filter: 'isFile'
      }
    },
    lyriaScene: {
      all: {
        options: {
          namespace: '<%= pkg.name %>'
        },
        files: [{
          dest: 'src/generated/scenelist.js',
          src: ['assets/scenes/*'],
          filter: 'isDirectory'
        }]
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  var bowerList = function(done) {
    bower.commands.list({
      paths: true
    }).on('end', function(results) {
      var prepareBowerAsset = function(value) {
        value = path.relative(process.cwd(), value);

        // All forward slashes, please
        value = value.split('\\').join('/');

        if (!value.endsWith('.css')) {

          if (!value.endsWith('.js')) {
            value += '/' + key + '.js';
          }

          var libFile = ['lib', path.basename(value)].join('/');
          var buildLibFile = [buildFolder, libFile].join('/');
          uglifyLibObject[buildLibFile] = value;

          if (libFilesPriorities.indexOf(key) >= 0) {
            templateScripts.development.unshift(value);
            templateScripts.production.unshift(libFile);
          } else {
            templateScripts.development.push(value);
            templateScripts.production.push(libFile);
          }

        } else {
          templateStyles.unshift(value);
        }
      };

      for (var key in results) {
        var val = results[key];

        if (val.indexOf(',') >= 0) {
          val = val.split(',');
        }

        if (Array.isArray(val)) {
          if (key === 'handlebars') {
            prepareBowerAsset(val[1]);
          }

          for (var i = 0, j = val.length; i < j; i++) {
            if (((path.extname(val[i]) === '.js') && !val[i].endsWith('.min.js')) || path.extname(val[i]) === '.css') {
              prepareBowerAsset(val[i]);
            }
          }
        } else {
          prepareBowerAsset(val);
        }
      }

      templateScripts.development.push('js/<%= pkg.name %>.js');
      templateScripts.production.push('js/<%= pkg.name %>.js');

      done();
    });
  };

  grunt.registerTask('bower:development', 'Prepares scripts using bower components', function() {
    var done = this.async();

    bowerList(function() {
      grunt.task.run('template:development');
      done();
    });
  });

  grunt.registerTask('bower:production', 'Prepares scripts using bower components', function() {
    var done = this.async();

    bowerList(function() {
      grunt.task.run('template:production');
      done();
    });
  });

  grunt.registerTask('prebuild', 'Task before building the project', ['lyriaScene', 'lyriaAssetList', 'lyriaData', 'concat_sourcemap']);
  grunt.registerTask('test', 'Lints JavaScript and CSS files', ['jshint']);

  grunt.registerTask('development', 'Development build', ['prebuild', 'bower:development', 'stylus:development']);
  grunt.registerTask('production', 'Production build', ['prebuild', 'bower:production', 'uglify', 'copy', 'stylus:production']);
  grunt.registerTask('deploy', 'Deploys project', ['production', 'compress:deploy']);

  grunt.registerTask('build', 'Builds the default project', ['development']);
  grunt.registerTask('default', 'Default task', ['development']);

  // The future in order
  grunt.registerTask('observe', 'Default task', ['development', 'watch']);

}; <|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {
	// Unified Watch Object
	var watchFiles = {
		serverViews: ['app/views/**/*.*'],
		serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
		clientViews: ['public/modules/**/views/**/*.html'],
		clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
		clientCSS: ['public/modules/**/*.css'],
		mochaTests: ['app/tests/**/*.js']
	};

	// Project Configuration
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		watch: {
			serverViews: {
				files: watchFiles.serverViews,
				options: {
					livereload: true
				}
			},
			serverJS: {
				files: watchFiles.serverJS,
				tasks: ['jshint'],
				options: {
					livereload: true
				}
			},
			clientViews: {
				files: watchFiles.clientViews,
				options: {
					livereload: true,
				}
			},
			clientJS: {
				files: watchFiles.clientJS,
				tasks: ['jshint'],
				options: {
					livereload: true
				}
			},
			clientCSS: {
				files: watchFiles.clientCSS,
				tasks: ['csslint'],
				options: {
					livereload: true
				}
			}
		},
		jshint: {
			all: {
				//src: watchFiles.clientJS.concat(watchFiles.serverJS),
				src: watchFiles.serverJS,
				options: {
					jshintrc: true
				}
			}
		},
		csslint: {
			options: {
				csslintrc: '.csslintrc',
			},
			all: {
				src: watchFiles.clientCSS
			}
		},
		uglify: {
			production: {
				options: {
					mangle: false
				},
				files: {
					'public/dist/application.min.js': 'public/dist/application.js'
				}
			}
		},
		cssmin: {
			combine: {
				files: {
					'public/dist/application.min.css': '<%= applicationCSSFiles %>'
				}
			}
		},
		nodemon: {
			dev: {
				script: 'server.js',
				options: {
					nodeArgs: ['--debug'],
					ext: 'js,html',
					watch: watchFiles.serverViews.concat(watchFiles.serverJS)
				}
			}
		},
		'node-inspector': {
			custom: {
				options: {
					'web-port': 1337,
					'web-host': 'localhost',
					'debug-port': 5858,
					'save-live-edit': true,
					'no-preload': true,
					'stack-trace-limit': 50,
					'hidden': []
				}
			}
		},
		ngAnnotate: {
			production: {
				files: {
					'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
				}
			}
		},
		concurrent: {
			default: ['nodemon', 'watch'],
			debug: ['nodemon', 'watch', 'node-inspector'],
			options: {
				logConcurrentOutput: true,
				limit: 10
			}
		},
		env: {
			test: {
				NODE_ENV: 'test'
			},
			secure: {
				NODE_ENV: 'secure'
			}
		},
		mochaTest: {
			src: watchFiles.mochaTests,
			options: {
				reporter: 'spec',
				require: 'server.js'
			}
		},
		karma: {
			unit: {
				configFile: 'karma.conf.js'
			}
		}
	});

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

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

	// A Task for loading the configuration object
	grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
		var init = require('./config/init')();
		var config = require('./config/config');

		grunt.config.set('applicationJavaScriptFiles', config.assets.js);
		grunt.config.set('applicationCSSFiles', config.assets.css);
	});

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

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

	// Secure task(s).
	grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']);

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

	// Build task(s).
	grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']);

	// Test task.
	grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
<commit_msg>Grunt fix try.<commit_after>'use strict';

module.exports = function(grunt) {
	// Unified Watch Object
	var watchFiles = {
		serverViews: ['app/views/**/*.*'],
		serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
		clientViews: ['public/modules/**/views/**/*.html'],
		clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
		clientCSS: ['public/modules/**/*.css'],
		mochaTests: ['app/tests/**/*.js']
	};

	// Project Configuration
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		watch: {
			serverViews: {
				files: watchFiles.serverViews,
				options: {
					livereload: true
				}
			},
			serverJS: {
				files: watchFiles.serverJS,
				tasks: ['jshint'],
				options: {
					livereload: true
				}
			},
			clientViews: {
				files: watchFiles.clientViews,
				options: {
					livereload: true,
				}
			},
			clientJS: {
				files: watchFiles.clientJS,
				tasks: ['jshint'],
				options: {
					livereload: true
				}
			},
			clientCSS: {
				files: watchFiles.clientCSS,
				tasks: ['csslint'],
				options: {
					livereload: true
				}
			}
		},
		jshint: {
			all: {
				src: watchFiles.clientJS.concat(watchFiles.serverJS),
				//src: watchFiles.serverJS,
				options: {
					jshintrc: true
				}
			}
		},
		csslint: {
			options: {
				csslintrc: '.csslintrc',
			},
			all: {
				src: watchFiles.clientCSS
			}
		},
		uglify: {
			production: {
				options: {
					mangle: false
				},
				files: {
					'public/dist/application.min.js': 'public/dist/application.js'
				}
			}
		},
		cssmin: {
			combine: {
				files: {
					'public/dist/application.min.css': '<%= applicationCSSFiles %>'
				}
			}
		},
		nodemon: {
			dev: {
				script: 'server.js',
				options: {
					nodeArgs: ['--debug'],
					ext: 'js,html',
					watch: watchFiles.serverViews.concat(watchFiles.serverJS)
				}
			}
		},
		'node-inspector': {
			custom: {
				options: {
					'web-port': 1337,
					'web-host': 'localhost',
					'debug-port': 5858,
					'save-live-edit': true,
					'no-preload': true,
					'stack-trace-limit': 50,
					'hidden': []
				}
			}
		},
		ngAnnotate: {
			production: {
				files: {
					'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
				}
			}
		},
		concurrent: {
			default: ['nodemon', 'watch'],
			debug: ['nodemon', 'watch', 'node-inspector'],
			options: {
				logConcurrentOutput: true,
				limit: 10
			}
		},
		env: {
			test: {
				NODE_ENV: 'test'
			},
			secure: {
				NODE_ENV: 'secure'
			}
		},
		mochaTest: {
			src: watchFiles.mochaTests,
			options: {
				reporter: 'spec',
				require: 'server.js'
			}
		},
		karma: {
			unit: {
				configFile: 'karma.conf.js'
			}
		}
	});

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

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

	// A Task for loading the configuration object
	grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
		var init = require('./config/init')();
		var config = require('./config/config');

		grunt.config.set('applicationJavaScriptFiles', config.assets.js);
		grunt.config.set('applicationCSSFiles', config.assets.css);
	});

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

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

	// Secure task(s).
	grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']);

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

	// Build task(s).
	grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']);

	// Test task.
	grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
<|endoftext|>


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

  var lyriaOrigin = 'src/**/*.js';

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      dist: {
        src: [lyriaOrigin],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        report: 'gzip'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    jshint: {
      files: ['gruntfile.js', lyriaOrigin],
      options: {
        loopfunc: true,
        sub: true,
        eqnull: true,
        es5: true
      }
    },
    yuidoc: {
      compile: {
        name: '<%= pkg.name %>',
        description: '<%= pkg.description %>',
        version: '<%= pkg.version %>',
        url: '<%= pkg.homepage %>',
        options: {
          paths: 'src/',
          outdir: 'doc/api'
        }
      }
    },
    less: {
      options: {
        paths: ['style'],
        yuicompress: true
      },
      dist: {
        files: {
          'css/lyria.css': 'style/*.less'
        }
      }
    },
    dependo: {
      targetPath: 'src',
      outputPath: './doc/dependencies',
      format: 'amd'
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-yuidoc');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-dependo');

  grunt.registerTask('test', 'Lints and unit tests', ['jshint']);
  grunt.registerTask('doc', 'Generated documentation', ['yuidoc', 'dependo']);
  grunt.registerTask('default', 'Default task', ['test', 'concat', 'uglify', 'less', 'doc']);

};
<commit_msg>Updated gruntfile to use .jshintrc<commit_after>module.exports = function(grunt) {

  var lyriaOrigin = 'src/**/*.js';

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      dist: {
        src: [lyriaOrigin],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        report: 'gzip'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    jshint: {
      files: ['gruntfile.js', lyriaOrigin],
      options: grunt.file.readJSON('.jshintrc')
    },
    yuidoc: {
      compile: {
        name: '<%= pkg.name %>',
        description: '<%= pkg.description %>',
        version: '<%= pkg.version %>',
        url: '<%= pkg.homepage %>',
        options: {
          paths: 'src/',
          outdir: 'doc/api'
        }
      }
    },
    less: {
      options: {
        paths: ['style'],
        yuicompress: true
      },
      dist: {
        files: {
          'css/lyria.css': 'style/*.less'
        }
      }
    },
    dependo: {
      targetPath: 'src',
      outputPath: './doc/dependencies',
      format: 'amd'
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-yuidoc');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-dependo');

  grunt.registerTask('test', 'Lints and unit tests', ['jshint']);
  grunt.registerTask('doc', 'Generated documentation', ['yuidoc', 'dependo']);
  grunt.registerTask('default', 'Default task', ['test', 'concat', 'uglify', 'less', 'doc']);

};
<|endoftext|>


<commit_before>
module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt)

  grunt.initConfig({
    standard: {
      options: { format: false },
      gruntfile: { src: ['gruntfile.js'] },
      plugin: { src: ['src/**/*.js'] },
      all: { src: ['gruntfile', 'plugin.js'] }
    },
    browserify: {
      plugin: {
        src: 'src/main.js',
        dest: 'dist/plugin.js'
      }
    },
    uglify: {
      dist: {
        files: {
          'plugin.min.js': ['plugin.js']
        }
      }
    },
    bump: {
      options: {
        files: ['package.json', 'bower.json'],
        updateConfigs: [],
        commit: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json', 'bower.json'],
        createTag: true,
        tagName: 'v%VERSION%',
        tagMessage: 'Version %VERSION%',
        push: true,
        pushTo: 'origin',
        gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
        globalReplace: false,
        prereleaseName: false,
        regExp: false
      }
    }
  })

  grunt.registerTask('default', ['standard', 'browserify', 'uglify'])
}
<commit_msg>fix standard task config<commit_after>
module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt)

  grunt.initConfig({
    standard: {
      options: { format: false },
      gruntfile: { src: ['gruntfile.js'] },
      plugin: { src: ['src/**/*.js'] }
    },
    browserify: {
      plugin: {
        src: 'src/main.js',
        dest: 'plugin.js'
      }
    },
    uglify: {
      dist: {
        files: {
          'plugin.min.js': ['plugin.js']
        }
      }
    },
    bump: {
      options: {
        files: ['package.json', 'bower.json'],
        updateConfigs: [],
        commit: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json', 'bower.json'],
        createTag: true,
        tagName: 'v%VERSION%',
        tagMessage: 'Version %VERSION%',
        push: true,
        pushTo: 'origin',
        gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
        globalReplace: false,
        prereleaseName: false,
        regExp: false
      }
    }
  })

  grunt.registerTask('default', ['standard', 'browserify', 'uglify'])
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var webpack = require('webpack');

var mergeWebpackConfig = function (destination) {
  // Load webpackConfig only when using `grunt:webpack`
  // load of grunt tasks is faster
  var webpackConfig = require('./webpack.config');

  return _.merge(destination, webpackConfig, function (a, b) {
    if (_.isArray(a)) {
      return a.concat(b);
    }
  });
};

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    sass: {
      dist: {
        files: {
          'react-datepicker.css' : 'src/stylesheets/datepicker.scss'
        }
      },
      options: {
        sourcemap: 'none',
        style: 'expanded'
      }
    },

    watch: {
      jshint: {
        files: 'src/**/*.js',
        tasks: ['jshint']
      },

      jest: {
        files: ['src/**/*.js', 'test/**/*.js'],
        tasks: ['jest']
      },

      css: {
        files: '**/*.scss',
        tasks: ['sass']
      },

      browserify: {
        files: ['src/**/*.js'],
        tasks: ['browserify']
      }
    },

    scsslint: {
      files: 'src/stylesheets/*.scss',
      options: {
        config: '.scss-lint.yml',
        colorizeOutput: true
      },
    },

    browserify: {
      all: {
        dest: 'react-datepicker.js',
        transform: [
          'reactify',
          'browserify-shim'
        ],
        browserifyOptions: {
          entries: './src/datepicker.js',
          standalone: 'DatePicker',
          bundleExternal: false
        }
      },

      example : {
        dest: 'example/bundle.js',
        browserifyOptions: {
          entries: './example/boot.jsx'
        }
      }
    },

    jshint: {
      all: ['src/**/*.jsx', 'src/**/*.js'],
      options: {
        eqnull: true
      }
    },

    webpack: {
      unmin: mergeWebpackConfig({
        output: {
          filename: 'react-datepicker.js'
        }
      }),
      min: mergeWebpackConfig({
        output: {
          filename: 'react-datepicker.min.js'
        },
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            compressor: {
              warnings: false
            }
          })
        ]
      })
    }
  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-scss-lint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-jsxhint');
  grunt.loadNpmTasks('grunt-webpack');

  grunt.registerTask('default', ['watch', 'scsslint']);
  grunt.registerTask('travis', ['jshint', 'jest', 'scsslint']);

  grunt.registerMultiTask('browserify', require('./grunt/tasks/browserify'));
  grunt.registerTask('jest', require('./grunt/tasks/jest'));
};
<commit_msg>add build task, unmin and min styles<commit_after>'use strict';

var _ = require('lodash');
var webpack = require('webpack');

var mergeWebpackConfig = function (destination) {
  // Load webpackConfig only when using `grunt:webpack`
  // load of grunt tasks is faster
  var webpackConfig = require('./webpack.config');

  return _.merge(destination, webpackConfig, function (a, b) {
    if (_.isArray(a)) {
      return a.concat(b);
    }
  });
};

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    sass: {
      min: {
        files: {
          'dist/react-datepicker.css': 'src/stylesheets/datepicker.scss'
        },
        options: {
          sourcemap: 'none',
          style: 'expanded'
        }
      },
      unmin: {
        files: {
          'dist/react-datepicker.min.css': 'src/stylesheets/datepicker.scss'
        },
        options: {
          sourcemap: 'none',
          style: 'compressed'
        }
      }
    },

    watch: {
      jshint: {
        files: 'src/**/*.js',
        tasks: ['jshint']
      },

      jest: {
        files: ['src/**/*.js', 'test/**/*.js'],
        tasks: ['jest']
      },

      css: {
        files: '**/*.scss',
        tasks: ['sass']
      },

      browserify: {
        files: ['src/**/*.js'],
        tasks: ['browserify']
      }
    },

    scsslint: {
      files: 'src/stylesheets/*.scss',
      options: {
        config: '.scss-lint.yml',
        colorizeOutput: true
      },
    },

    browserify: {
      all: {
        dest: 'react-datepicker.js',
        transform: [
          'reactify',
          'browserify-shim'
        ],
        browserifyOptions: {
          entries: './src/datepicker.js',
          standalone: 'DatePicker',
          bundleExternal: false
        }
      },

      example : {
        dest: 'example/bundle.js',
        browserifyOptions: {
          entries: './example/boot.jsx'
        }
      }
    },

    jshint: {
      all: ['src/**/*.jsx', 'src/**/*.js'],
      options: {
        eqnull: true
      }
    },

    webpack: {
      unmin: mergeWebpackConfig({
        output: {
          filename: 'react-datepicker.js'
        }
      }),
      min: mergeWebpackConfig({
        output: {
          filename: 'react-datepicker.min.js'
        },
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            compressor: {
              warnings: false
            }
          })
        ]
      })
    }
  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-scss-lint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-jsxhint');
  grunt.loadNpmTasks('grunt-webpack');

  grunt.registerTask('default', ['watch', 'scsslint']);
  grunt.registerTask('travis', ['jshint', 'jest', 'scsslint']);
  grunt.registerTask('build', ['jshint', 'scsslint', 'webpack', 'sass']);

  grunt.registerMultiTask('browserify', require('./grunt/tasks/browserify'));
  grunt.registerTask('jest', require('./grunt/tasks/jest'));
};
<|endoftext|>


<commit_before>/*globals MSA */

Handlebars.registerHelper('debug', function(path){
	debugger;
  return 'weird';
});

MSA = SC.Application.create();

MSA.Module = SCUtil.ModelObject.extend({
  name: SCUtil.dataHashProperty,
  image: SCUtil.dataHashProperty,

  // FIXME handle icon property
  defaultDataHash: {
     "xtype": "MySystemContainer",
     "etype": "source",
     "fields": {
        "efficiency": "1"
     }
  }
});

MSA.EnergyType = SCUtil.ModelObject.extend({
  label: SCUtil.dataHashProperty,
  color: SCUtil.dataHashProperty
});

MSA.data = {
   "type": "mysystem2",
   "prompt": "How can you cook an egg?",
   "modules": [
      {
         "name": "burner",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/burner-transp-70.png",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/burner-transp-70.png",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      },
      {
         "name": "egg",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/egg-transp-70.png",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/egg-transp-70.png",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      },
      {
         "name": "pot",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/pot.jpg",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/pot.jpg",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      },
      {
         "name": "water",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/water-70.png",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/water-70.png",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      }
   ],
   "energy_types": [
      {
         "label": "heat",
         "color": "#E97F02"
      }
   ]
}

MSA.modulesController = SCUtil.ModelArray.create({
  content: MSA.data.modules,
  modelType: MSA.Module
});

MSA.energyTypesController = SCUtil.ModelArray.create({
  content: MSA.data.energy_types,
  modelType: MSA.EnergyType
});

MSA.dataController = SC.Object.create({
  data: function(){
    return JSON.stringify(MSA.data, null, 2);
  }.property('MSA.modulesController.@each.rev', 'MSA.energyTypesController.@each.rev')
})<commit_msg>change behavior based on iframe or not<commit_after>/*globals MSA, SCUtil*/

MSA = SC.Application.create();

MSA.Module = SCUtil.ModelObject.extend({
  name: SCUtil.dataHashProperty,
  image: SCUtil.dataHashProperty,

  // FIXME handle icon property
  defaultDataHash: {
     "xtype": "MySystemContainer",
     "etype": "source",
     "fields": {
        "efficiency": "1"
     }
  }
});

MSA.EnergyType = SCUtil.ModelObject.extend({
  label: SCUtil.dataHashProperty,
  color: SCUtil.dataHashProperty
});

if (top === self) {
  // we are not in iframe so load in some fake data
  MSA.data = {
   "type": "mysystem2",
   "prompt": "How can you cook an egg?",
   "modules": [
      {
         "name": "burner_static",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/burner-transp-70.png",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/burner-transp-70.png",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      },
      {
         "name": "egg",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/egg-transp-70.png",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/egg-transp-70.png",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      },
      {
         "name": "pot",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/pot.jpg",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/pot.jpg",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      },
      {
         "name": "water",
         "icon": "http://dl.dropbox.com/u/73403/mysystem/images/water-70.png",
         "image": "http://dl.dropbox.com/u/73403/mysystem/images/water-70.png",
         "xtype": "MySystemContainer",
         "etype": "source",
         "fields": {
            "efficiency": "1"
         }
      }
   ],
   "energy_types": [
      {
         "label": "heat_static",
         "color": "#E97F02"
      }
   ]
  };
} else {
  // we are in an iframe
  MSA.data = {
    "modules": [],
    "energy_types": []
  };
}

MSA.modulesController = SCUtil.ModelArray.create({
  content: MSA.data.modules,
  modelType: MSA.Module
});

MSA.energyTypesController = SCUtil.ModelArray.create({
  content: MSA.data.energy_types,
  modelType: MSA.EnergyType
});

MSA.dataController = SC.Object.create({
  data: function(){
    return JSON.stringify(MSA.data, null, 2);
  }.property('MSA.modulesController.@each.rev', 'MSA.energyTypesController.@each.rev')
})<|endoftext|>


<commit_before>const Immutable = require('immutable');
const Map = Immutable.Map;
const List = Immutable.List;
const Set = Immutable.Set;

const defaultYear = List([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);

function createDefaultYear(value) {
  return List([value, value, value, value, value, value, value, value, value, value, value, value]);
}

class Timeseries {
  constructor(data) {
    this.data = data || Map();
  }
  set(year, month, value) {
    const newData = this.data.update(year, defaultYear, (months) => months.set(month, value));
    return new Timeseries(newData);
  }
  get(year, month) {
    return this.data.get(year, defaultYear).get(month);
  }
  add(other) {
    const result = this.data.mergeWith((a, b) => a.zipWith((x, y) => x + y, b), other.data);
    return new Timeseries(result);
  }
  getRange(startYear, startMonth, endYear, endMonth, defaultValue) {
    let result = List();
    const defaultValues = defaultValue ? createDefaultYear(defaultValue) : defaultYear;
    let i, j;
    for (let year = startYear; year <= endYear; year++) {
      i = 0;
      j = 11;
      if (year === startYear) {
        i = startMonth;
      }
      if (year === endYear) {
        j = endMonth;
      }
      result = result.concat(this.data.get(year, defaultValues).slice(i, j + 1));
    }
    return result;
  }
}

module.exports = Timeseries;
<commit_msg>Added default value<commit_after>const Immutable = require('immutable');
const Map = Immutable.Map;
const List = Immutable.List;
const Set = Immutable.Set;

const defaultYear = List([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);

class Timeseries {
  constructor(data) {
    this.data = data || Map();
  }
  set(year, month, value) {
    const newData = this.data.update(year, defaultYear, (months) => months.set(month, value));
    return new Timeseries(newData);
  }
  get(year, month) {
    return this.data.get(year, defaultYear).get(month);
  }
  add(other) {
    const result = this.data.mergeWith((a, b) => a.zipWith((x, y) => x + y, b), other.data);
    return new Timeseries(result);
  }
  getRange(startYear, startMonth, endYear, endMonth, defaultValue) {
    let result = List();
    const defaultValues = defaultValue ? this._createDefaultYear(defaultValue) : defaultYear;
    let i, j;
    for (let year = startYear; year <= endYear; year++) {
      i = 0;
      j = 11;
      if (year === startYear) {
        i = startMonth;
      }
      if (year === endYear) {
        j = endMonth;
      }
      result = result.concat(this.data.get(year, defaultValues).slice(i, j + 1));
    }
    return result;
  }
  _createDefaultYear(value) {
    return List([value, value, value, value, value, value, value, value, value, value, value, value]);
  }
}

module.exports = Timeseries;
<|endoftext|>