<commit_before>/**
 * @file Class definition
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GpfClassDefMember*/ // GPF class member definition
/*global _gpfAssert*/ // Assertion method
/*global _gpfAsserts*/ // Multiple assertion method
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*exported _GpfClassDefinition*/ // GPF class definition
/*#endif*/

_gpfErrorDeclare("define/definition/class", {
    "classMemberAlreadyExist":
        "You can't add a member twice"
});

/**
 * Link the class definition to its super one, return member dictionary
 *
 * @param {_GpfClassDefinition} classDef Class definition receiving the link
 * @param {_GpfClassDefinition} superClassDef Class definition to link to
 * @returns {Object} Relevant member dictionary
 */
function _gpfLinkToSuperClassDef (classDef, superClassDef) {
    if (superClassDef) {
        classDef._super = superClassDef;
        return superClassDef._members;
    }
    return {};
}

/**
 * Class definition
 *
 * @param {String} qName Fully qualified class name
 * @param {_GpfClassDefinition} [superClassDef=null] Super class definition
 * @class
 */
function _GpfClassDefinition (qName, superClassDef) {
    _gpfAssert(!superClassDef || superClassDef instanceof _GpfClassDefinition, "Expected a _GpfClassDefinition");
    /*jshint validthis:true*/ // constructor
    this._qName = qName;
    this._members = Object.create(_gpfLinkToSuperClassDef(this, superClassDef));
}

_GpfClassDefinition.prototype = {

    /** Fully qualified class name */
    _qName: "",

    /** @return {String} Class name */
    getName: function () {
        if (-1 !== this._qName.indexOf(".")) {
            return this._qName.split(".").pop();
        }
        return this._qName;
    },

    /** @return {String} Class namespace */
    getNamespace: function () {
        if (-1 !== this._qName.indexOf(".")) {
            var nameArray = this._qName.split(".");
            nameArray.pop();
            return nameArray.join(".");
        }
        return "";
    },

    /** @return {String} Class qualified name (namespace.name) */
    getQualifiedName: function () {
        return this._qName;
    },

    /**
     * Super class definition
     *
     * @type {_GpfClassDefinition}
     */
    _super: null,

    /** Dictionary of members */
    _members: {},

    /**
     * Get a member by its name
     *
     * @param {String} name Member name
     * @return {_GpfClassDefMember|undefined} Member
     */
    getMember: function (name) {
        return this._members[name];
    },

    /**
     * Before adding a member, check that it does not already exist for this class definition
     *
     * @param {String} name Member name
     * @throws {gpf.Error.classMemberAlreadyExist}
     */
    _checkOwnMemberDoesntExist: function (name) {
        if (this._members.hasOwnProperty(name)) {
            throw gpf.Error.classMemberAlreadyExist();
        }
    },

    _checkMemberBeforeAdd: function (member) {
        var name = member.getName(),
            existing;
        this._checkOwnMemberDoesntExist(name);
        existing = this._members[name];
        if (existing) {
            existing.checkOverloadedWith(member);
        }
    },

    /**
     * Add a member
     *
     * @param {_GpfClassDefMember} member Member to add
     * @return {_GpfClassDefinition} Chainable
     */
    addMember: function (member) {
        _gpfAsserts({
            "Expected a _GpfClassDefMember": member instanceof _GpfClassDefMember,
            "Member is already assigned to a class": null === member._classDef
        });
        this._checkMemberBeforeAdd(member);
        this._members[member.getName()] = member;
        member._classDef = this;
        return this;
    }

};

/*#ifndef(UMD)*/

gpf.internals._GpfClassDefinition = _GpfClassDefinition;

/*#endif*/
<commit_msg>Documentation<commit_after>/**
 * @file Class definition
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GpfClassDefMember*/ // GPF class member definition
/*global _gpfAssert*/ // Assertion method
/*global _gpfAsserts*/ // Multiple assertion method
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*exported _GpfClassDefinition*/ // GPF class definition
/*#endif*/

_gpfErrorDeclare("define/definition/class", {
    "classMemberAlreadyExist":
        "You can't add a member twice"
});

/**
 * Link the class definition to the super one
 *
 * @param {_GpfClassDefinition} classDef Class definition receiving the link
 * @param {_GpfClassDefinition} [superClassDef=undefined] Class definition to link to
 * @returns {Object} Member dictionary if superclass provided or an empty object
 */
function _gpfLinkToSuperClassDef (classDef, superClassDef) {
    if (superClassDef) {
        classDef._super = superClassDef;
        return superClassDef._members;
    }
    return {};
}

/**
 * Class definition
 * - Holds a flat dictionary of members (using prototype inheritance)
 *
 * @param {String} qName Fully qualified class name
 * @param {_GpfClassDefinition} [superClassDef=undefined] Super class definition
 * @class
 */
function _GpfClassDefinition (qName, superClassDef) {
    _gpfAssert(!superClassDef || superClassDef instanceof _GpfClassDefinition, "Expected a _GpfClassDefinition");
    /*jshint validthis:true*/ // constructor
    this._qName = qName;
    this._members = Object.create(_gpfLinkToSuperClassDef(this, superClassDef));
}

_GpfClassDefinition.prototype = {

    /** Fully qualified class name */
    _qName: "",

    /** @return {String} Class name */
    getName: function () {
        if (-1 !== this._qName.indexOf(".")) {
            return this._qName.split(".").pop();
        }
        return this._qName;
    },

    /** @return {String} Class namespace */
    getNamespace: function () {
        if (-1 !== this._qName.indexOf(".")) {
            var nameArray = this._qName.split(".");
            nameArray.pop();
            return nameArray.join(".");
        }
        return "";
    },

    /** @return {String} Class qualified name (namespace.name) */
    getQualifiedName: function () {
        return this._qName;
    },

    /**
     * Super class definition
     *
     * @type {_GpfClassDefinition}
     */
    _super: null,

    /** Dictionary of members */
    _members: {},

    /**
     * Get a member by its name
     *
     * @param {String} name Member name
     * @return {_GpfClassDefMember|undefined} Member
     */
    getMember: function (name) {
        return this._members[name];
    },

    /**
     * Before adding a member, check that it does not already exist for this class definition
     *
     * @param {String} name Member name
     * @throws {gpf.Error.classMemberAlreadyExist}
     */
    _checkOwnMemberDoesntExist: function (name) {
        if (this._members.hasOwnProperty(name)) {
            throw gpf.Error.classMemberAlreadyExist();
        }
    },

    _checkMemberBeforeAdd: function (member) {
        var name = member.getName(),
            existing;
        this._checkOwnMemberDoesntExist(name);
        existing = this._members[name];
        if (existing) {
            existing.checkOverloadedWith(member);
        }
    },

    /**
     * Add a member
     *
     * @param {_GpfClassDefMember} member Member to add
     * @return {_GpfClassDefinition} Chainable
     */
    addMember: function (member) {
        _gpfAsserts({
            "Expected a _GpfClassDefMember": member instanceof _GpfClassDefMember,
            "Member is already assigned to a class": null === member._classDef
        });
        this._checkMemberBeforeAdd(member);
        this._members[member.getName()] = member;
        member._classDef = this;
        return this;
    }

};

/*#ifndef(UMD)*/

gpf.internals._GpfClassDefinition = _GpfClassDefinition;

/*#endif*/
<|endoftext|>


<commit_before>define([], function () {
    var ProfileTable = React.createClass({
        getProfileColumn: function(data) {
            result = [];
            for (var i = 0; i < data.length; i++) {
                var className = "profile-table-column-element";
                if (i == 0) {
                    className += " profile-table-column-element-header";
                }
                el =
{data[i]}

                result.push(el);
            }
            return

                {result}

;
        },
        getProgamUsageCountColumns: function(data) {
            var columns = [];
            var sortList = [];
            for (x in data) {
                sortList.push({"value": data[x], "key": x});
            }
            sortList.sort(function(a, b) {
                return a.value > b.value;
            });

            var programs = ["Programs"].concat(sortList.map(function(a) {return a.key}));
            var values = ["Usages"].concat(sortList.map(function(a) {return a.value}));

            columns.push(this.getProfileColumn(programs));
            columns.push(this.getProfileColumn(values));
            return columns;
        },
        render: function() {
            var type = this.props.profileData[0];
            var data = this.props.profileData[1];
            var columns = [];
            // Program Usage Counts
            if (type == 0) {
                columns = this.getProgamUsageCountColumns(data);
            }
            return

                {columns}

;
        }
    });
    return ProfileTable;
});
<commit_msg>Render duplicate program table<commit_after>define([], function () {
    var ProfileTable = React.createClass({
        getProfileColumn: function(data) {
            result = [];
            for (var i = 0; i < data.length; i++) {
                var className = "profile-table-column-element";
                if (i == 0) {
                    className += " profile-table-column-element-header";
                }
                el =
{data[i]}

                result.push(el);
            }
            return

                {result}

;
        },
        getProgamUsageCountColumns: function(data) {
            var columns = [];
            var sortList = [];
            for (x in data) {
                sortList.push({"value": data[x], "key": x});
            }
            sortList.sort(function(a, b) {
                return a.value > b.value;
            });

            var programs = ["Programs"].concat(sortList.map(function(a) {return a.key}));
            var values = ["Usages"].concat(sortList.map(function(a) {return a.value}));

            columns.push(this.getProfileColumn(programs));
            columns.push(this.getProfileColumn(values));
            return columns;
        },
        getDuplicateProgramColumns: function(data) {
            var columns = [];

            var histogram = {};
            for (var i=0; i<data.length; i++) {
                var x = data[i];
                var id = JSON.stringify(x);
                if (id in histogram) {
                    histogram[id] = [histogram[id][0] + 1, x]
                } else {
                    histogram[id] = [1, x]
                }
            }
            console.log(histogram);

            var sortList = []
            for (x in histogram) {
                sortList.push({"value": histogram[x][0], "key": histogram[x][1]});
            }
            sortList.sort(function(a, b) {
                return a.value > b.value;
            });

            var programId = ["Program ID"].concat(sortList.map(function(a) {return a.key.programId}));
            var callLocation = ["Call Location"].concat(sortList.map(function(a) {return a.key.functionName + ":" + a.key.lineNumber}));
            var fileName = ["File Name"].concat(sortList.map(function(a) {return a.key.fileName}));
            var occurences = ["Occurences"].concat(sortList.map(function(a) {return a.value}));

            columns.push(this.getProfileColumn(programId));
            columns.push(this.getProfileColumn(callLocation));
            columns.push(this.getProfileColumn(fileName));
            columns.push(this.getProfileColumn(occurences));
            return columns;
        },
        render: function() {
            var type = this.props.profileData[0];
            var data = this.props.profileData[1];
            var columns = [];
            // Program Usage Counts
            if (type == 0) {
                columns = this.getProgamUsageCountColumns(data);
            } else if (type == 1) {
                columns = this.getDuplicateProgramColumns(data);
            }
            return

                {columns}

;
        }
    });
    return ProfileTable;
});
<|endoftext|>


<commit_before>var filemanager = new function(){
	var isBrowser = !window.require;
	var isLocal = !isBrowser;

	var fs, path, md5file, modloader, modList;
	var md5Loaded = false;

	this.initialize = function(mloader){
		modloader = mloader;

		if(isLocal){
			fs = require('fs');
			md5file = require('md5-file');
			path = require('path');

			_createDirectories();
		} else {
			_loadScript('js/2.5.3-crypto-md5.js', function(){ //ccloader/js/2.5.3-crypto-md5.js
				md5Loaded = true;
			}, document);
			modList = JSON.parse(this.getResource('mods.json'));
		}
	}
	this.loadMod = function(file, onModLoaded){
        _loadScript(file, onModLoaded, modloader.frame.contentDocument);
	}
	this.getTableName = function(callback){
		_getHash('assets/js/game.compiled.js', callback);
	}
	this.getDefintionHash = function(callback){
		_getHash('ccloader/data/definitions.db', callback);
	}
	this.getModDefintionHash = function(def, callback){
		_getHash(def, callback);
	}
	this.getAllModsFiles = function(folder){
        return _getResources(folder, '/package.json');
	};
	this.tableExists = function(table){
		if(!table)
			return false;

		return _resourceExists('ccloader/data/' + table);
	}
	this.modTableExists = function(table){
		if(!table)
			return false;

		return _resourceExists(table);
	}
	this.getResource = function(resource){
		try{
			if(isLocal)
				return fs.readFileSync(resource, 'utf-8');
			else {
                var req = new XMLHttpRequest();
                req.open('GET', '/' + resource, false);
                req.send(null);

                if(req.status === 200) {
                    return req.responseText;
                } else {
                    return undefined;
                }
			}
		}catch(e){
			return undefined;
		}
	}
	this.saveTable = function(tableName, table, hash){
		if(!hash){
			this.getDefintionHash(function(hash){
				filemanager.saveTable(tableName, table, hash)
			});
			return;
		}

		if(isLocal) {
			try {
				fs.mkdirSync(path.dirname('ccloader/data/' + tableName), function(err){});
			} catch(e) {}
			fs.writeFileSync('ccloader/data/' + tableName, JSON.stringify({hash: hash, db: table}), 'utf-8');
		}
	}
	this.loadTable = function(tableName, hash){
		var text = filemanager.getResource('ccloader/data/' + tableName);
		if(!text)
			return undefined;

		var json = JSON.parse(text);
		var table = new Db("");

		if(!json || !json.hash)
			return undefined;

		if(hash && hash != json.hash)
			return undefined;

		table.data = json.db.data;
		return table;
	}

    function _getResources(folder, ending){
		if(!folder)
			folder = 'assets/mods/';

		if(isLocal)
			return _getResourcesLocal(folder, ending);
		else {
			var results = [];
			for(var i in modList){
				if(_resourceExists('assets/mods/' + modList[i] + ending)){
					results.push('mods/' + modList[i] + ending);
				}
			}
			return results;
		}
    }
    function _getHash(file, callback) {
		if(isLocal) {
            return md5file(file, function(err, hash){
                callback(hash + '.table');
            });
        } else {
            if(!md5Loaded){
                setTimeout(this.getTableName, 100, callback);
            } else {
                callback(Crypto.MD5(filemanager.getResource(file)) + '.table');
            }
        }
    }
	function _resourceExists(resource){
		if(isLocal){
			try{
				fs.statSync(resource);
				return true;
			} catch(e) {
				return false;
			}
		} else {
			try{
				var req = new XMLHttpRequest();
				req.open('HEAD', '/' + resource, false);
				req.send();
				return req.status != 404;
			}catch(e){
				return false;
			}
		}
	}
	function _loadScript(url, callback, doc){
		var script = document.createElement("script");
		script.onload = callback;
		script.type = "text/javascript";
		script.src = url;
		doc.body.appendChild(script);
	}
	function _getResourcesLocal(folder, ending){
		var results = [];

		if(isLocal) {
			try{
				fs.readdirSync(folder).forEach(function(file) {
					try{
						file = folder + '/' + file;

						if (_isDirectory(file)) {
							var innerResults = _getResourcesLocal(file, ending);
							results = results.concat(innerResults);
						} else if(file.endsWith(ending)){
							results.push(file);
						}
					} catch(e) { }
				});
			} catch(e) { }
		}

		return results;
	}
	function _isDirectory(file){
		var stat = fs.statSync(file);
		return stat && stat.isDirectory();
	}
	function _createDirectories(){
		if(isLocal){
            fs.mkdir('ccloader/data/assets', function(err){
                fs.mkdir('ccloader/dataccloader/data', function(err){
                    fs.mkdir('ccloader/dataccloader/data/assets', function(err){
                        fs.mkdir('ccloader/dataccloader/data/assets/mods', function(err){

                        });
                    });
                });
            });
		}
	}
};<commit_msg>Fixed mod paths for browser<commit_after>var filemanager = new function(){
	var isBrowser = !window.require;
	var isLocal = !isBrowser;

	var fs, path, md5file, modloader, modList;
	var md5Loaded = false;

	this.initialize = function(mloader){
		modloader = mloader;

		if(isLocal){
			fs = require('fs');
			md5file = require('md5-file');
			path = require('path');

			_createDirectories();
		} else {
			_loadScript('js/2.5.3-crypto-md5.js', function(){ //ccloader/js/2.5.3-crypto-md5.js
				md5Loaded = true;
			}, document);
			modList = JSON.parse(this.getResource('mods.json'));
		}
	}
	this.loadMod = function(file, onModLoaded){
        _loadScript(file, onModLoaded, modloader.frame.contentDocument);
	}
	this.getTableName = function(callback){
		_getHash('assets/js/game.compiled.js', callback);
	}
	this.getDefintionHash = function(callback){
		_getHash('ccloader/data/definitions.db', callback);
	}
	this.getModDefintionHash = function(def, callback){
		_getHash(def, callback);
	}
	this.getAllModsFiles = function(folder){
        return _getResources(folder, '/package.json');
	};
	this.tableExists = function(table){
		if(!table)
			return false;

		return _resourceExists('ccloader/data/' + table);
	}
	this.modTableExists = function(table){
		if(!table)
			return false;

		return _resourceExists(table);
	}
	this.getResource = function(resource){
		try{
			if(isLocal)
				return fs.readFileSync(resource, 'utf-8');
			else {
                var req = new XMLHttpRequest();
                req.open('GET', '/' + resource, false);
                req.send(null);

                if(req.status === 200) {
                    return req.responseText;
                } else {
                    return undefined;
                }
			}
		}catch(e){
			return undefined;
		}
	}
	this.saveTable = function(tableName, table, hash){
		if(!hash){
			this.getDefintionHash(function(hash){
				filemanager.saveTable(tableName, table, hash)
			});
			return;
		}

		if(isLocal) {
			try {
				fs.mkdirSync(path.dirname('ccloader/data/' + tableName), function(err){});
			} catch(e) {}
			fs.writeFileSync('ccloader/data/' + tableName, JSON.stringify({hash: hash, db: table}), 'utf-8');
		}
	}
	this.loadTable = function(tableName, hash){
		var text = filemanager.getResource('ccloader/data/' + tableName);
		if(!text)
			return undefined;

		var json = JSON.parse(text);
		var table = new Db("");

		if(!json || !json.hash)
			return undefined;

		if(hash && hash != json.hash)
			return undefined;

		table.data = json.db.data;
		return table;
	}

    function _getResources(folder, ending){
		if(!folder)
			folder = 'assets/mods/';

		if(isLocal)
			return _getResourcesLocal(folder, ending);
		else {
			var results = [];
			for(var i in modList){
				if(_resourceExists('assets/mods/' + modList[i] + ending)){
					results.push('assets/mods/' + modList[i] + ending);
				}
			}
			return results;
		}
    }
    function _getHash(file, callback) {
		if(isLocal) {
            return md5file(file, function(err, hash){
                callback(hash + '.table');
            });
        } else {
            if(!md5Loaded){
                setTimeout(this.getTableName, 100, callback);
            } else {
                callback(Crypto.MD5(filemanager.getResource(file)) + '.table');
            }
        }
    }
	function _resourceExists(resource){
		if(isLocal){
			try{
				fs.statSync(resource);
				return true;
			} catch(e) {
				return false;
			}
		} else {
			try{
				var req = new XMLHttpRequest();
				req.open('HEAD', '/' + resource, false);
				req.send();
				return req.status != 404;
			}catch(e){
				return false;
			}
		}
	}
	function _loadScript(url, callback, doc){
		var script = document.createElement("script");
		script.onload = callback;
		script.type = "text/javascript";
		script.src = url;
		doc.body.appendChild(script);
	}
	function _getResourcesLocal(folder, ending){
		var results = [];

		if(isLocal) {
			try{
				fs.readdirSync(folder).forEach(function(file) {
					try{
						file = folder + '/' + file;

						if (_isDirectory(file)) {
							var innerResults = _getResourcesLocal(file, ending);
							results = results.concat(innerResults);
						} else if(file.endsWith(ending)){
							results.push(file);
						}
					} catch(e) { }
				});
			} catch(e) { }
		}

		return results;
	}
	function _isDirectory(file){
		var stat = fs.statSync(file);
		return stat && stat.isDirectory();
	}
	function _createDirectories(){
		if(isLocal){
            fs.mkdir('ccloader/data/assets', function(err){
                fs.mkdir('ccloader/dataccloader/data', function(err){
                    fs.mkdir('ccloader/dataccloader/data/assets', function(err){
                        fs.mkdir('ccloader/dataccloader/data/assets/mods', function(err){

                        });
                    });
                });
            });
		}
	}
};<|endoftext|>


<commit_before>students.$inject = ['$http'];

function students ($http) {
	const url = 'http://fiasps.unitec.edu:' + PORT + '/api/Students';

	const service = {
		get: get,
		getHours: getHours,
		getAccountId: getAccountId,
		getSectionHours: getSectionHours
	};

	return service;

	function get (successCallback, errorCallback) {
        $http.get(url).then(successCallback)
            .catch(errorCallback);
	}

	function getHours(accountId, successCallback, errorCallback) {
		$http.get(url + '/' + accountId + '/Hour').then(successCallback)
			.catch(errorCallback);

		// return $http.get(url + '/' + accountId + '/Hour').then(function(response) {
		// 	return response.data;
		// });
	}

	function getAccountId(successCallback, errorCallback){
				$http.get(url + '/Me').then(successCallback)
						.catch(errorCallback);
	}

	function getSectionHours(accountId, successCallback, errorCallback){
				$http.get(url + '/'+accountId+'/SectionHours').then(successCallback)
						.catch(errorCallback);
	}

}

module.exports = { name: 'students', srvc: students };
<commit_msg>Get parsed excel API call<commit_after>students.$inject = ['$http', '$q'];

function students ($http, $q) {
	const url = 'http://fiasps.unitec.edu:' + PORT + '/api/Students';

	const service = {
		get: get,
		getHours: getHours,
		getAccountId: getAccountId,
		getSectionHours: getSectionHours,
		getParsedStudentsExcel: getParsedStudentsExcel
	};

	return service;

	function get (successCallback, errorCallback) {
        $http.get(url).then(successCallback)
            .catch(errorCallback);
	}

	function getHours(accountId, successCallback, errorCallback) {
		$http.get(url + '/' + accountId + '/Hour').then(successCallback)
			.catch(errorCallback);

		// return $http.get(url + '/' + accountId + '/Hour').then(function(response) {
		// 	return response.data;
		// });
	}

	function getAccountId(successCallback, errorCallback){
				$http.get(url + '/Me').then(successCallback)
						.catch(errorCallback);
	}

	function getSectionHours(accountId, successCallback, errorCallback){
				$http.get(url + '/'+accountId+'/SectionHours').then(successCallback)
						.catch(errorCallback);
	}

	function getParsedStudentsExcel (data) {
		const deferred = $q.defer();

      	$http.get(url+'/Parse/'+data)
	        .success(response => { deferred.resolve(response.data); })
	        .error(reject => { deferred.reject('No se pudo importar el archivo.'); });

	    return deferred.promise;
	}

}

module.exports = { name: 'students', srvc: students };
<|endoftext|>


<commit_before>var RSVP = require('rsvp');

module.exports = {
  description: 'installs js cookie, which is needed',
  normalizeEntityName: function() {},
  afterInstall: function(options) {
    return RSVP.all([
      this.addBowerPackagesToProject([{name: "js-cookie", target: "~2.0.3"}]),
      this.addPackageToProject("ember-moment", "4.1.0")
    ]);
  }
};
<commit_msg>removed unnecessary blueprint addon packages<commit_after>var RSVP = require('rsvp');

module.exports = {
  description: 'installs js cookie, which is needed',
  normalizeEntityName: function() {}
};
<|endoftext|>


<commit_before>var fs   = require('fs-extra');
var path = require('path');
var mkdirp = require('mkdirp');
var util = require('util');

module.exports = {
  podsDir: '',

  description: 'Generates a style.scss file',

  beforeInstall: function (options) {
      this.podsDir = this._locals(options).fileMap.__path__.replace('/' + options.entity.name, '');
      this.podsDir = this.podsDir.replace(options.entity.name, '');

      if (!options.taskOptions.pod) {
          throw new Error('You must use pods with ember-cli-sass-pods. Run with --pod.');
      }
  },

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function (options) {
      //console.log(util.inspect(options.project, false, null));
      var entity = options.entity;

      addScssToImportFile(entity.name, {
          name: entity.name,
          root: options.project.root,
          podsDir: this.podsDir
      });
  }
};

function addScssToImportFile (name, options) {
      var importFile = options.podsDir ? options.podsDir : 'pods',
          filePath = path.join(options.root, 'app/styles'),
          importScssPath = path.join(filePath, importFile + '.scss'),
          podsDir = options.podsDir ? options.podsDir + '/' : '',
          newLine = '@import "' + podsDir + options.name + '/style";\n',
          source;

      if (!fs.existsSync(filePath)) {
        mkdirp(filePath);
      }

      if (!fs.existsSync(importScssPath)) {
          fs.writeFileSync(importScssPath, newLine, 'utf8');
      } else {
          source = fs.readFileSync(importScssPath, 'utf-8');
          source += newLine;
          fs.writeFileSync(importScssPath, source);
      }
  }
<commit_msg>removing trailing slash or backslash from podsDir<commit_after>var fs   = require('fs-extra');
var path = require('path');
var mkdirp = require('mkdirp');
var util = require('util');

module.exports = {
  podsDir: '',

  description: 'Generates a style.scss file',

  beforeInstall: function (options) {
      this.podsDir = this._locals(options).fileMap.__path__.replace('/' + options.entity.name, '');
      this.podsDir = this.podsDir.replace(options.entity.name, '');

      if (!options.taskOptions.pod) {
          throw new Error('You must use pods with ember-cli-sass-pods. Run with --pod.');
      }
  },

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function (options) {
      //console.log(util.inspect(options.project, false, null));
      var entity = options.entity;

      addScssToImportFile(entity.name, {
          name: entity.name,
          root: options.project.root,
          podsDir: this.podsDir
      });
  }
};

function addScssToImportFile (name, options) {
      var importFile = options.podsDir ? options.podsDir.replace(/(\\|\/)$/, '') : 'pods',
          filePath = path.join(options.root, 'app/styles'),
          importScssPath = path.join(filePath, importFile + '.scss'),
          podsDir = options.podsDir ? importFile + '/' : '',
          newLine = '@import "' + podsDir + options.name + '/style";\n',
          source;

      if (!fs.existsSync(filePath)) {
        mkdirp(filePath);
      }

      if (!fs.existsSync(importScssPath)) {
          fs.writeFileSync(importScssPath, newLine, 'utf8');
      } else {
          source = fs.readFileSync(importScssPath, 'utf-8');
          source += newLine;
          fs.writeFileSync(importScssPath, source);
      }
  }
<|endoftext|>


<commit_before>import * as IncrementalDOM from 'incremental-dom';
import * as skateSymbols from './symbols';
import { shadowDomV0, shadowDomV1 } from '../util/support';
import assign from '../util/assign';

const {
  attr,
  applyProp,
  attributes,
  elementClose,
  elementOpen,
  elementOpenEnd,
  elementOpenStart,
  elementVoid,
  skip,
  symbols,
  text,
} = IncrementalDOM;

const fallbackToV0 = !shadowDomV1 && shadowDomV0;
const applyDefault = attributes[symbols.default];

// Attributes that are not handled by Incremental DOM.
attributes.key = attributes.skip = attributes.statics = function () {};

// Attributes that *must* be set via a property on all elements.
attributes.checked = attributes.className = attributes.disabled = attributes.value = applyProp;

// Default attribute applicator.
attributes[symbols.default] = function (elem, name, value) {
  // Boolean false values should not set attributes at all.
  if (value === false) {
    return;
  }

  // If the skip attribute was specified, skip
  if (name === 'skip' && value) {
    return skip();
  }

  // Custom element properties should be set as properties.
  const props = elem.constructor.props;
  if (props && name in props) {
    return applyProp(elem, name, value);
  }

  // Handle built-in and custom events.
  if (name.indexOf('on') === 0) {
    return name in elem ? applyProp(elem, name, value) : applyEvent(elem, name.substring(2), name, value);
  }

  // Set the select attribute instead of name if it was a <slot> translated to
  // a <content> for v0.
  if (name === 'name' && elem.tagName === 'CONTENT') {
    name = 'select';
    value = `[slot="${value}"]`;
  }

  // Fallback to default IncrementalDOM behaviour.
  applyDefault(elem, name, value);
};

// Adds or removes an event listener for an element.
function applyEvent (elem, ename, name, value) {
  let events = elem.__events;

  if (!events) {
    events = elem.__events = {};
  }

  const eFunc = events[ename];

  // Remove old listener so they don't double up.
  if (eFunc) {
    elem.removeEventListener(ename, eFunc);
  }

  // Bind new listener.
  if (value) {
    elem.addEventListener(ename, events[ename] = value);
  }
}

// Returns the tag name of the element if a custom element constructor was
// provided instead of a string.
function decideIfConstructorOrNot (tname) {
  return typeof tname === 'function' ? tname[skateSymbols.name] : tname;
}

// Returns the correct tag name so we can use <content> instead of <slot> if we
// need to use Shadow DOM V0.
function decideIfContentTagOrNot (tname) {
  return tname === 'slot' && fallbackToV0 ? 'content' : tname;
}

// Patch elementOpen() so that anything that compiles down to Incremental DOM
// gets the special behaviour.
function newElementOpen (...args) {
  args[0] = decideIfConstructorOrNot(decideIfContentTagOrNot(args[0]));
  return elementOpen.apply(null, args);
}

// Patch elementOpenStart() for the same reason we patched elementOpen().
function newElementOpenStart (...args) {
  args[0] = decideIfConstructorOrNot(decideIfContentTagOrNot(args[0]));
  return elementOpenStart.apply(null, args);
}

// Patch elementVoid() for the same reason we patched elementOpen().
function newElementVoid (...args) {
  args[0] = decideIfConstructorOrNot(decideIfContentTagOrNot(args[0]));
  return elementVoid.apply(null, args);
}

// Override Incremental DOM exports.
const newIncrementalDom = assign({}, IncrementalDOM);
Object.defineProperties(newIncrementalDom, {
  attributes,
  elementOpen: { value: newElementOpen },
  elementOpenStart: { value: newElementOpenStart },
  elementVoid: { value: newElementVoid },
});

// Convenience function for declaring an Incremental DOM element using
// hyperscript-style syntax.
export function element (tname, attrs, chren) {
  const atype = typeof attrs;

  if (atype === 'function') {
    chren = attrs;
  }

  if (atype !== 'object') {
    attrs = {};
  }

  // We open the element so we can set attrs after.
  newElementOpenStart(tname, attrs.key, attrs.statics);

  // Delete so special attrs don't actually get set.
  delete attrs.key;
  delete attrs.statics;

  // Set attributes.
  Object.keys(attrs).forEach(name => attr(name, attrs[name]));

  // Close before we render the descendant tree.
  elementOpenEnd();

  const ctype = typeof chren;
  if (ctype === 'function') {
    chren();
  } else if (ctype === 'string' || ctype === 'number') {
    text(chren);
  }

  return elementClose(tname);
}

// We don't have to do anything special for the text funciton; it's just a
// straight export from Incremental DOM.
export { text };

// Re-export Incremental DOM's overridden public API.
export { newIncrementalDom as IncrementalDOM };
<commit_msg>Minor spelling mistake in comment<commit_after>import * as IncrementalDOM from 'incremental-dom';
import * as skateSymbols from './symbols';
import { shadowDomV0, shadowDomV1 } from '../util/support';
import assign from '../util/assign';

const {
  attr,
  applyProp,
  attributes,
  elementClose,
  elementOpen,
  elementOpenEnd,
  elementOpenStart,
  elementVoid,
  skip,
  symbols,
  text,
} = IncrementalDOM;

const fallbackToV0 = !shadowDomV1 && shadowDomV0;
const applyDefault = attributes[symbols.default];

// Attributes that are not handled by Incremental DOM.
attributes.key = attributes.skip = attributes.statics = function () {};

// Attributes that *must* be set via a property on all elements.
attributes.checked = attributes.className = attributes.disabled = attributes.value = applyProp;

// Default attribute applicator.
attributes[symbols.default] = function (elem, name, value) {
  // Boolean false values should not set attributes at all.
  if (value === false) {
    return;
  }

  // If the skip attribute was specified, skip
  if (name === 'skip' && value) {
    return skip();
  }

  // Custom element properties should be set as properties.
  const props = elem.constructor.props;
  if (props && name in props) {
    return applyProp(elem, name, value);
  }

  // Handle built-in and custom events.
  if (name.indexOf('on') === 0) {
    return name in elem ? applyProp(elem, name, value) : applyEvent(elem, name.substring(2), name, value);
  }

  // Set the select attribute instead of name if it was a <slot> translated to
  // a <content> for v0.
  if (name === 'name' && elem.tagName === 'CONTENT') {
    name = 'select';
    value = `[slot="${value}"]`;
  }

  // Fallback to default IncrementalDOM behaviour.
  applyDefault(elem, name, value);
};

// Adds or removes an event listener for an element.
function applyEvent (elem, ename, name, value) {
  let events = elem.__events;

  if (!events) {
    events = elem.__events = {};
  }

  const eFunc = events[ename];

  // Remove old listener so they don't double up.
  if (eFunc) {
    elem.removeEventListener(ename, eFunc);
  }

  // Bind new listener.
  if (value) {
    elem.addEventListener(ename, events[ename] = value);
  }
}

// Returns the tag name of the element if a custom element constructor was
// provided instead of a string.
function decideIfConstructorOrNot (tname) {
  return typeof tname === 'function' ? tname[skateSymbols.name] : tname;
}

// Returns the correct tag name so we can use <content> instead of <slot> if we
// need to use Shadow DOM V0.
function decideIfContentTagOrNot (tname) {
  return tname === 'slot' && fallbackToV0 ? 'content' : tname;
}

// Patch elementOpen() so that anything that compiles down to Incremental DOM
// gets the special behaviour.
function newElementOpen (...args) {
  args[0] = decideIfConstructorOrNot(decideIfContentTagOrNot(args[0]));
  return elementOpen.apply(null, args);
}

// Patch elementOpenStart() for the same reason we patched elementOpen().
function newElementOpenStart (...args) {
  args[0] = decideIfConstructorOrNot(decideIfContentTagOrNot(args[0]));
  return elementOpenStart.apply(null, args);
}

// Patch elementVoid() for the same reason we patched elementOpen().
function newElementVoid (...args) {
  args[0] = decideIfConstructorOrNot(decideIfContentTagOrNot(args[0]));
  return elementVoid.apply(null, args);
}

// Override Incremental DOM exports.
const newIncrementalDom = assign({}, IncrementalDOM);
Object.defineProperties(newIncrementalDom, {
  attributes,
  elementOpen: { value: newElementOpen },
  elementOpenStart: { value: newElementOpenStart },
  elementVoid: { value: newElementVoid },
});

// Convenience function for declaring an Incremental DOM element using
// hyperscript-style syntax.
export function element (tname, attrs, chren) {
  const atype = typeof attrs;

  if (atype === 'function') {
    chren = attrs;
  }

  if (atype !== 'object') {
    attrs = {};
  }

  // We open the element so we can set attrs after.
  newElementOpenStart(tname, attrs.key, attrs.statics);

  // Delete so special attrs don't actually get set.
  delete attrs.key;
  delete attrs.statics;

  // Set attributes.
  Object.keys(attrs).forEach(name => attr(name, attrs[name]));

  // Close before we render the descendant tree.
  elementOpenEnd();

  const ctype = typeof chren;
  if (ctype === 'function') {
    chren();
  } else if (ctype === 'string' || ctype === 'number') {
    text(chren);
  }

  return elementClose(tname);
}

// We don't have to do anything special for the text function; it's just a
// straight export from Incremental DOM.
export { text };

// Re-export Incremental DOM's overridden public API.
export { newIncrementalDom as IncrementalDOM };
<|endoftext|>


<commit_before>var Viz = React.createClass({
    displayName: "pipeviz-graph",
    render: function() {
        return React.DOM.svg({
            className: "pipeviz",
            width: "100%",
            children: [React.DOM.g({
                id: 'commit-pipeline',
                children: [React.DOM.g({
                    id: 'commitview-edges'
                }), React.DOM.g({
                    id: 'commit-axis',
                    width: this.props.width,
                    height: 30,
                    transform: 'translate(0,' + (this.props.height - 30) + ')'
                })]
            })]
        });
    },
    shouldComponentUpdate: function(nextProps, prevProps) {
        return nextProps.vizdata !== undefined;
    },
    componentDidUpdate: function() {
        // x-coordinate space is the elided diameter as a factor of viewport width
        var selections = {},
            props = this.props,
            tf = createTransforms(props.width, props.height - 30, props.vizdata.ediam, props.vizdata.segments.length);

        // Outer g first
        selections.outerg = d3.select(this.getDOMNode()).select('#commit-pipeline');

        // Vertices
        selections.vertices = selections.outerg.selectAll('.node')
            .data(props.vizdata.vertices, function(d) { return d.ref.id; });

        selections.vertices.exit().transition().remove(); // exit removes vertex
        // tons of stuff to do on enter
        selections.veg = selections.vertices.enter().append('g') // store the enter group and build it up
            .attr('class', function(d) { return 'node ' + d.ref.Typ(); })
            // so we don't transition from 0,0
            .attr('transform', function(d) { return 'translate(' + tf.x(d.x) + ',' + tf.y(d.y) + ')'; })
            // and start from invisible
            .style('opacity', 0);
        selections.veg.append('circle');
        selections.nte = selections.veg.append('text');
        selections.nte.append('tspan') // add vertex label tspan on enter
            .attr('class', 'vtx-label');
        selections.nte.append('tspan') // add commit info tspan on enter and position it
            .attr('dy', "1.4em")
            .attr('x', 0)
            .attr('class', function(d) {
                var output = 'commit-subtext',
                    commit = getCommit(props.graph, d.ref),
                    testState = getTestState(props.graph, commit);
                if (testState !== undefined) {
                    output += ' commit-' + testState;
                }

                return output;
            });

        // now, update
        selections.vertices.transition() // update assigns the position via transform
            .attr('transform', function(d) { return 'translate(' + tf.x(d.x) + ',' + tf.y(d.y) + ')'; })
            .style('opacity', 1);

        // now work within the g for each vtx
        selections.vertices.select('circle').transition()
            .attr('r', function(d) { return d.ref.Typ() === "commit" ? tf.unit()*0.03 : tf.unit()*0.3; });

        // and the info text
        selections.nodetext = selections.vertices.select('text').transition();
        selections.nodetext.select('.vtx-label')
            .text(function(d) { return d.ref.propv("lgroup"); }); // set text value to data from lgroup
        selections.nodetext.select('.commit-subtext') // set the commit text on update
            .text(function(d) { return getCommit(props.graph, d.ref).propv("sha1").slice(0, 7); });

        // Links
        selections.links = selections.outerg.select('#commitview-edges').selectAll('.link')
            .data(props.vizdata.links, function(d) {
                return d[0].ref.id + '-' +  d[1].ref.id;
            });

        selections.links.exit().transition()
            .style('opacity', 0)
            .remove(); // exit removes line
        selections.links.enter().append('line') // enter appends a line
            .attr('class', 'link')
            .style('opacity', 0)
            // set all these initially so that we don't transition from 0,0,0,0
            .attr('x1', function(d) { return tf.x(d[0].x); })
            .attr('y1', function(d) { return tf.y(d[0].y); })
            .attr('x2', function(d) { return tf.x(d[1].x); })
            .attr('y2', function(d) { return tf.y(d[1].y); });

        selections.links.transition() // update sets the line's x and y positions
            .attr('x1', function(d) { return tf.x(d[0].x); })
            .attr('y1', function(d) { return tf.y(d[0].y); })
            .attr('x2', function(d) { return tf.x(d[1].x); })
            .attr('y2', function(d) { return tf.y(d[1].y); })
            .style('opacity', 1);

        // commit elision markers
        selections.elisions = selections.outerg.selectAll('.elision-bar')
            .data(_.map(props.vizdata.elranges, function(range) {
                // creates the same string as what's used in vizdata.xmap
                return range[0] + ' - ' + range[range.length - 1];
            }), _.identity);

        selections.elisions.exit().transition().remove(); // remove on exit
        selections.elisions.enter().append('line')
            .attr('class', 'elision-bar')
            .style('opacity', 0)
            // set all these initially so that we don't transition from 0,0,0,0
            .attr('x1', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y1', 0)
            .attr('x2', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y2', props.height - 30);

        selections.elisions.transition() // update sets x position
            .style('opacity', 1)
            .attr('x1', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y1', 0)
            .attr('x2', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y2', props.height - 30)
            .attr('stroke-width', tf.unit() * 0.007);

        // Commit distance axis
        var xlbls = _.map(_.pairs(props.vizdata.xmap).sort(function(a, b) { return a[1] - b[1]; }), _.head),
            xscale = d3.scale.ordinal()
                .domain(xlbls)
                .range(_.map(xlbls, function(label) {
                    return tf.x(props.vizdata.xmap[label]);
                })),
            xaxis = d3.svg.axis()
                .scale(xscale)
                .orient('bottom')
                .ticks(props.vizdata.ediam);

        d3.select('#commit-axis').transition()
            .call(xaxis);
            //.append('text')
                //.attr('transform', 'translate(' + tf.x(0) + ',-5)')
                //.attr('text-anchor', 'start')
                //.text('distance to root');
    },
});

var VizPrep = React.createClass({
    getDefaultProps: function() {
        return {
            width: 0,
            height: 0,
            graph: pvGraph({id: 0, vertices: []}),
            focalRepo: "",
        };
    },
    shouldComponentUpdate: function(nextProps) {
        // In the graph object, state is invariant with respect to the message id.
        return nextProps.graph.mid !== this.props.graph.mid;
    },
    render: function() {
        //var vizdata = this.extractVizGraph(this.props.focalRepo);
        //return React.createElement(Viz, {width: this.props.width, height: this.props.height, graph: this.props.graph, nodes: vizdata[0].concat(this.state.anchorL, this.state.anchorR), links: vizdata[1], labels: vizdata[2]});
        return React.createElement(Viz, {width: this.props.width, height: this.props.height, graph: this.props.graph, vizdata: extractVizGraph(this.props.graph, this.props.focalRepo)});
    },
});

var InfoBar = React.createClass({
    displayName: 'pipeviz-info',
    render: function() {
        var t = this.props.target,
            cmp = this;

        var outer = {
            id: "infobar",
            children: []
        };

        if (typeof t !== 'object') {
            outer.children = [React.DOM.p({}, "nothing selected")];
            // drop out early for the empty case
            return React.DOM.div(outer);
        }

        // find all linked envs for the logic state
        var linkedContainers = [t.ref()._container]; // parent env
        // env linked through dataset
        if (_.has(t.ref(), 'datasets')) {
            _.forOwn(t.ref().datasets, function(ds) {
                if (_.has(ds.loc, 'hostname')) {
                    linkedContainers.push(cmp.props.pvd.byHostname(ds.loc.hostname));
                }
            });
        }

        linkedContainers = _.uniq(linkedContainers);

        // title for containers
        outer.children.push(React.DOM.h3({}, t.name()));
        // list of containers
        outer.children.push(React.DOM.ul({children: [
            React.DOM.li({children: [
                'Comprises ' + linkedContainers.length + ' env(s), with hostnames:',
                React.DOM.ul({}, _.map(linkedContainers, function(d) {
                    return React.DOM.li({}, d.name());
                }))
            ]}),
            React.DOM.li({}, 'App path: ' + t.ref()._path)
        ]}));

        outer.children.push(React.DOM.h3({}, 'Active commit'));

        var commit = this.props.commits[t.ref().id.commit];
        var sha1line =  'sha1: ' + t.ref().id.commit.slice(0, 7);

        if (_.has(this.props.commitMeta, t.ref().id.commit) &&
            _.has(this.props.commitMeta[t.ref().id.commit], 'testState')) {
            sha1line += ' (' + this.props.commitMeta[t.ref().id.commit].testState + ')';
        }

        var items = [
            sha1line,
            commit.date,
            commit.author,
            '"' + commit.message + '"'
        ];

        outer.children.push(React.DOM.ul({
            children: items.map(function(d) {
                return React.DOM.li({}, d);
            })
        }));
        return React.DOM.div(outer);
    }
});

var ControlBar = React.createClass({
    displayName: 'pipeviz-control',
    render: function() {
        var fc = this.props.filterChange;
        var boxes = this.props.filters.map(function(d) {
            return (<input type="checkbox" checked={d.selected} onChange={fc.bind(this, d.id)}>{d.id}</input>);
        });

        return (
            <div id="controlbar">
                Filters: {boxes}
                Sort by: <input type="checkbox" checked={this.props.commitsort}
                onChange={this.props.csChange}>commits</input>
            </div>
        );
    },
});

var App = React.createClass({
    dispayName: "pipeviz",
    getInitialState: function() {
        return {
            target: undefined,
            opts: {
                revx: false,
                noelide: false,
            },
        }
    }
    getDefaultProps: function() {
        return {
            // TODO uggghhh lol hardcoding
            vizWidth: window.innerWidth * 0.83,
            vizHeight: window.innerHeight - 30,
            graph: pvGraph({id: 0, vertices: []}),
        };
    },
    render: function() {
        return React.createElement("div", {id: "pipeviz"},
                    React.createElement(ControlBar, {this.state.opts}),
                    React.createElement(VizPrep, {width: this.props.vizWidth, height: this.props.vizHeight, graph: this.props.graph, focalRepo: vizExtractor.mostCommonRepo(this.props.graph)})
                    React.createElement(InfoBar, target={this.state.target})
              );
    },
});

var e = React.render(React.createElement(App), document.body);
var genesis = new WebSocket("ws://" + window.location.hostname + ":" + window.location.port + "/sock");
var lastg;
genesis.onmessage = function(m) {
    lastg = pvGraph(JSON.parse(m.data));
    e.setProps({graph: lastg});
};
<commit_msg>Sorta adapt the control bar<commit_after>var Viz = React.createClass({
    displayName: "pipeviz-graph",
    render: function() {
        return React.DOM.svg({
            className: "pipeviz",
            width: "100%",
            children: [React.DOM.g({
                id: 'commit-pipeline',
                children: [React.DOM.g({
                    id: 'commitview-edges'
                }), React.DOM.g({
                    id: 'commit-axis',
                    width: this.props.width,
                    height: 30,
                    transform: 'translate(0,' + (this.props.height - 30) + ')'
                })]
            })]
        });
    },
    shouldComponentUpdate: function(nextProps, prevProps) {
        return nextProps.vizdata !== undefined;
    },
    componentDidUpdate: function() {
        // x-coordinate space is the elided diameter as a factor of viewport width
        var selections = {},
            props = this.props,
            tf = createTransforms(props.width, props.height - 30, props.vizdata.ediam, props.vizdata.segments.length);

        // Outer g first
        selections.outerg = d3.select(this.getDOMNode()).select('#commit-pipeline');

        // Vertices
        selections.vertices = selections.outerg.selectAll('.node')
            .data(props.vizdata.vertices, function(d) { return d.ref.id; });

        selections.vertices.exit().transition().remove(); // exit removes vertex
        // tons of stuff to do on enter
        selections.veg = selections.vertices.enter().append('g') // store the enter group and build it up
            .attr('class', function(d) { return 'node ' + d.ref.Typ(); })
            // so we don't transition from 0,0
            .attr('transform', function(d) { return 'translate(' + tf.x(d.x) + ',' + tf.y(d.y) + ')'; })
            // and start from invisible
            .style('opacity', 0);
        selections.veg.append('circle');
        selections.nte = selections.veg.append('text');
        selections.nte.append('tspan') // add vertex label tspan on enter
            .attr('class', 'vtx-label');
        selections.nte.append('tspan') // add commit info tspan on enter and position it
            .attr('dy', "1.4em")
            .attr('x', 0)
            .attr('class', function(d) {
                var output = 'commit-subtext',
                    commit = getCommit(props.graph, d.ref),
                    testState = getTestState(props.graph, commit);
                if (testState !== undefined) {
                    output += ' commit-' + testState;
                }

                return output;
            });

        // now, update
        selections.vertices.transition() // update assigns the position via transform
            .attr('transform', function(d) { return 'translate(' + tf.x(d.x) + ',' + tf.y(d.y) + ')'; })
            .style('opacity', 1);

        // now work within the g for each vtx
        selections.vertices.select('circle').transition()
            .attr('r', function(d) { return d.ref.Typ() === "commit" ? tf.unit()*0.03 : tf.unit()*0.3; });

        // and the info text
        selections.nodetext = selections.vertices.select('text').transition();
        selections.nodetext.select('.vtx-label')
            .text(function(d) { return d.ref.propv("lgroup"); }); // set text value to data from lgroup
        selections.nodetext.select('.commit-subtext') // set the commit text on update
            .text(function(d) { return getCommit(props.graph, d.ref).propv("sha1").slice(0, 7); });

        // Links
        selections.links = selections.outerg.select('#commitview-edges').selectAll('.link')
            .data(props.vizdata.links, function(d) {
                return d[0].ref.id + '-' +  d[1].ref.id;
            });

        selections.links.exit().transition()
            .style('opacity', 0)
            .remove(); // exit removes line
        selections.links.enter().append('line') // enter appends a line
            .attr('class', 'link')
            .style('opacity', 0)
            // set all these initially so that we don't transition from 0,0,0,0
            .attr('x1', function(d) { return tf.x(d[0].x); })
            .attr('y1', function(d) { return tf.y(d[0].y); })
            .attr('x2', function(d) { return tf.x(d[1].x); })
            .attr('y2', function(d) { return tf.y(d[1].y); });

        selections.links.transition() // update sets the line's x and y positions
            .attr('x1', function(d) { return tf.x(d[0].x); })
            .attr('y1', function(d) { return tf.y(d[0].y); })
            .attr('x2', function(d) { return tf.x(d[1].x); })
            .attr('y2', function(d) { return tf.y(d[1].y); })
            .style('opacity', 1);

        // commit elision markers
        selections.elisions = selections.outerg.selectAll('.elision-bar')
            .data(_.map(props.vizdata.elranges, function(range) {
                // creates the same string as what's used in vizdata.xmap
                return range[0] + ' - ' + range[range.length - 1];
            }), _.identity);

        selections.elisions.exit().transition().remove(); // remove on exit
        selections.elisions.enter().append('line')
            .attr('class', 'elision-bar')
            .style('opacity', 0)
            // set all these initially so that we don't transition from 0,0,0,0
            .attr('x1', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y1', 0)
            .attr('x2', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y2', props.height - 30);

        selections.elisions.transition() // update sets x position
            .style('opacity', 1)
            .attr('x1', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y1', 0)
            .attr('x2', function(d) { return tf.x(props.vizdata.xmap[d]); })
            .attr('y2', props.height - 30)
            .attr('stroke-width', tf.unit() * 0.007);

        // Commit distance axis
        var xlbls = _.map(_.pairs(props.vizdata.xmap).sort(function(a, b) { return a[1] - b[1]; }), _.head),
            xscale = d3.scale.ordinal()
                .domain(xlbls)
                .range(_.map(xlbls, function(label) {
                    return tf.x(props.vizdata.xmap[label]);
                })),
            xaxis = d3.svg.axis()
                .scale(xscale)
                .orient('bottom')
                .ticks(props.vizdata.ediam);

        d3.select('#commit-axis').transition()
            .call(xaxis);
            //.append('text')
                //.attr('transform', 'translate(' + tf.x(0) + ',-5)')
                //.attr('text-anchor', 'start')
                //.text('distance to root');
    },
});

var VizPrep = React.createClass({
    getDefaultProps: function() {
        return {
            width: 0,
            height: 0,
            graph: pvGraph({id: 0, vertices: []}),
            focalRepo: "",
        };
    },
    shouldComponentUpdate: function(nextProps) {
        // In the graph object, state is invariant with respect to the message id.
        return nextProps.graph.mid !== this.props.graph.mid;
    },
    render: function() {
        return React.createElement(Viz, {width: this.props.width, height: this.props.height, graph: this.props.graph, vizdata: extractVizGraph(this.props.graph, this.props.focalRepo)});
    },
});

var InfoBar = React.createClass({
    displayName: 'pipeviz-info',
    render: function() {
        var t = this.props.target,
            cmp = this;

        var outer = {
            id: "infobar",
            children: []
        };

        if (typeof t !== 'object') {
            outer.children = [React.DOM.p({}, "nothing selected")];
            // drop out early for the empty case
            return React.DOM.div(outer);
        }

        // find all linked envs for the logic state
        var linkedContainers = [t.ref()._container]; // parent env
        // env linked through dataset
        if (_.has(t.ref(), 'datasets')) {
            _.forOwn(t.ref().datasets, function(ds) {
                if (_.has(ds.loc, 'hostname')) {
                    linkedContainers.push(cmp.props.pvd.byHostname(ds.loc.hostname));
                }
            });
        }

        linkedContainers = _.uniq(linkedContainers);

        // title for containers
        outer.children.push(React.DOM.h3({}, t.name()));
        // list of containers
        outer.children.push(React.DOM.ul({children: [
            React.DOM.li({children: [
                'Comprises ' + linkedContainers.length + ' env(s), with hostnames:',
                React.DOM.ul({}, _.map(linkedContainers, function(d) {
                    return React.DOM.li({}, d.name());
                }))
            ]}),
            React.DOM.li({}, 'App path: ' + t.ref()._path)
        ]}));

        outer.children.push(React.DOM.h3({}, 'Active commit'));

        var commit = this.props.commits[t.ref().id.commit];
        var sha1line =  'sha1: ' + t.ref().id.commit.slice(0, 7);

        if (_.has(this.props.commitMeta, t.ref().id.commit) &&
            _.has(this.props.commitMeta[t.ref().id.commit], 'testState')) {
            sha1line += ' (' + this.props.commitMeta[t.ref().id.commit].testState + ')';
        }

        var items = [
            sha1line,
            commit.date,
            commit.author,
            '"' + commit.message + '"'
        ];

        outer.children.push(React.DOM.ul({
            children: items.map(function(d) {
                return React.DOM.li({}, d);
            })
        }));
        return React.DOM.div(outer);
    }
});

var ControlBar = React.createClass({
    displayName: 'pipeviz-control',
    render: function() {
        var oc = this.props.changeOpts;
        var boxes = _.map(this.props.opts, function(v, opt) {
            return (<input type="checkbox" checked={v.selected} onChange={oc.bind(this, opt, v)}>{v.label}</input>);
        });

        return (
            <div id="controlbar">
                Options: {boxes}
            </div>
        );
    },
});

var App = React.createClass({
    dispayName: "pipeviz",
    getInitialState: function() {
        return {
            target: undefined,
            opts: {
                revx: {label: "Reverse x positions", selected: false},
                noelide: {label: "No commit elision", selected: false},
            },
        }
    },
    changeOpts: function(opt, v) {
        this.setState({opts: _.merge(this.state.opts, _.zipObject([[opt, v]]))});
    },
    getDefaultProps: function() {
        return {
            // TODO uggghhh lol hardcoding
            vizWidth: window.innerWidth * 0.83,
            vizHeight: window.innerHeight - 30,
            graph: pvGraph({id: 0, vertices: []}),
        };
    },
    render: function() {
        return React.createElement("div", {id: "pipeviz"},
                    React.createElement(ControlBar, {opts: this.state.opts, changeOpts: this.changeOpts}),
                    React.createElement(VizPrep, {width: this.props.vizWidth, height: this.props.vizHeight, graph: this.props.graph, focalRepo: vizExtractor.mostCommonRepo(this.props.graph)}),
                    React.createElement(InfoBar, {target: this.state.target})
              );
    },
});

var e = React.render(React.createElement(App), document.body);
var genesis = new WebSocket("ws://" + window.location.hostname + ":" + window.location.port + "/sock");
var lastg;
genesis.onmessage = function(m) {
    lastg = pvGraph(JSON.parse(m.data));
    e.setProps({graph: lastg});
};
<|endoftext|>


<commit_before>var ansi_up = require('ansi_up')

var htmlErrorContent = `

TITLE

ERROR

`.replace(/\n/g, '')

var renderHTMLError = function(title, content) {
  var formattedContent =
    ansi_up
    .ansi_to_html(content)
    .replace(/"/g, '\\"')
    .split("\n")
    .filter(function(line) {
      return !line.match(/^\[/)
    })
    .join("\n")
    .trim()
    .replace(/\n/g, "\\n")

  var errorContent = htmlErrorContent
    .replace('TITLE', title)
    .replace('ERROR', formattedContent)

  return `document.write("${errorContent}")`
}

var renderCSSError = function(title, content) {
  var formattedContent =
    content.replace(/\n/g, "\\A").replace(/"/g, '\\"')

  return `
    body::before {
      font-family: sans-serif;
      content: "${title}";
      font-weight: bold;
      background: white;
      position: fixed;
      font-size: 24px;
      padding: 40px;
      color: #333;
      right: 0;
      left: 0;
      top: 0;
    }

    body::after {
      content: "${formattedContent}";
      font-family: monospace;
      background: white;
      line-height: 25px;
      white-space: pre;
      position: fixed;
      font-size: 13px;
      display: block;
      color: #333;
      top: 90px;
      bottom: 0;
      right: 0;
      left: 0;
      padding: 40px;
      padding-top: 0;
    }
  `
}

module.exports = {
  renderHTMLError: renderHTMLError,
  renderCSSError: renderCSSError
}
<commit_msg>Fix some errors in rendering errors.<commit_after>var ansi_up = require('ansi_up')

var htmlErrorContent = `

TITLE

ERROR

`.replace(/\n/g, '')

var renderHTMLError = function(title, content) {
  var formattedContent =
    ansi_up
    .ansi_to_html(content)
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')
    .split("\n")
    .filter(function(line) {
      return !line.match(/^\[/)
    })
    .join("\n")
    .trim()
    .replace(/\n/g, "\\n")

  var errorContent = htmlErrorContent
    .replace('TITLE', title)
    .replace('ERROR', formattedContent)

  return `document.write("${errorContent}")`
}

var renderCSSError = function(title, content) {
  var formattedContent =
    content.replace(/\n/g, "\\A").replace(/"/g, '\\"')

  return `
    body::before {
      font-family: sans-serif;
      content: "${title}";
      font-weight: bold;
      background: white;
      position: fixed;
      font-size: 24px;
      padding: 40px;
      color: #333;
      right: 0;
      left: 0;
      top: 0;
    }

    body::after {
      content: "${formattedContent}";
      font-family: monospace;
      background: white;
      line-height: 25px;
      white-space: pre;
      position: fixed;
      font-size: 13px;
      display: block;
      color: #333;
      top: 90px;
      bottom: 0;
      right: 0;
      left: 0;
      padding: 40px;
      padding-top: 0;
    }
  `
}

module.exports = {
  renderHTMLError: renderHTMLError,
  renderCSSError: renderCSSError
}
<|endoftext|>


<commit_before>//= require knockout.min
/*
 */
ko.bindingHandlers.executeOnEnter = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        jQuery(element).keypress(function (event) {
            var keyCode = (event.which ? event.which : event.keyCode);
            if (keyCode === 13) {
                allBindings.get('executeOnEnter').call(bindingContext.$data,event);
                return false;
            }
            return true;
        });
    }
};
<commit_msg>squash: fix knockout-onenter<commit_after>//= require knockout.min
/*
 */
ko.bindingHandlers.executeOnEnter = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var handler = allBindings.get('executeOnEnter');
        jQuery(element).keypress(function (event) {
            var keyCode = (event.which ? event.which : event.keyCode);
            if (keyCode === 13) {
                handler.call(bindingContext.$data,event);
                return false;
            }
            return true;
        });
    }
};
<|endoftext|>


<commit_before>this.addEventListener("install", function (event) {
    event.waitUntil(
        caches.open('v11').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/index.html',
          '/html/emergency.html',
          '/html/js/911.js',
          '/html/js/all_scr.js',
          '/html/js/app.js',
          '/html/js/bootstrap.min.js',
          '/html/js/emergency.js',
          '/html/js/wow.min.js',
          '/html/rs-plugin/js/jquery.themepunch.tools.min.js',
          '/html/rs-plugin/js/jquery.themepunch.revolution.min.js',
          '/html/rs-plugin/assets/timer.png',
          '/html/js/jquery.min.js',
          '/html/js/jquery.parallax-0.2-min.js',
          '/html/css/adaptive.css',
          '/html/css/animate.css',
          '/html/css/bootstrap.css',
          '/html/css/main.css',
          '/html/css/pushy.css',
          '/html/css/font-awesome.css',
          '/html/rs-plugin/css/settings.css',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg',
          '/html/img/start/bg.jpg',
          '/html/font/fontawesome-webfont.woff?v=4.3.0',
          '/html/font/fontawesome-webfont.woff2?v=4.3.0',
          '/html/rs-plugin/font/revicons.woff?5510888',
          '/html/rs-plugin/font/revicons.ttf?5510888',
          '/html/font/fontawesome-webfont.ttf?v=4.3.0'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v11'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request)
    );
});<commit_msg>sw v12<commit_after>this.addEventListener("install", function (event) {
    event.waitUntil(
        caches.open('v12').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/index.html',
          '/html/emergency.html',
          '/html/js/911.js',
          '/html/js/all_scr.js',
          '/html/js/app.js',
          '/html/js/bootstrap.min.js',
          '/html/js/emergency.js',
          '/html/js/wow.min.js',
          '/html/rs-plugin/js/jquery.themepunch.tools.min.js',
          '/html/rs-plugin/js/jquery.themepunch.revolution.min.js',
          '/html/rs-plugin/assets/timer.png',
          '/html/js/jquery.min.js',
          '/html/js/jquery.parallax-0.2-min.js',
          '/html/css/adaptive.css',
          '/html/css/animate.css',
          '/html/css/bootstrap.css',
          '/html/css/main.css',
          '/html/css/pushy.css',
          '/html/css/font-awesome.css',
          '/html/rs-plugin/css/settings.css',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg',
          '/html/img/start/bg.jpg',
          '/html/font/fontawesome-webfont.woff?v=4.3.0',
          '/html/font/fontawesome-webfont.woff2?v=4.3.0',
          '/html/rs-plugin/font/revicons.woff?5510888',
          '/html/rs-plugin/font/revicons.ttf?5510888',
          '/html/font/fontawesome-webfont.ttf?v=4.3.0'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v12'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request)
    );
});<|endoftext|>


<commit_before>$dripBot = (function($, $dripBot) {

	if($dripBot instanceof Object) {
		console.log("Refusing to run two dripBots (this could have unintended side effects).  Please refresh to update.");
		return $dripBot;
	}

	var version = '1.1',
	stage1Pid = -1,
	stage2Pid = -1,
	stage3Pid = -1,
	canBuy = true,
	errorCheckPid = -1,
	errorAlerted = false,
	signupAlerted = false,
	stage = '',
	started = false,
	status = 'Running',
	stopColor = '#e9656d',
	startColor = '#47a447',
	clickerPid = -1,
	clickInterval = 45,
	BPSThreshold = 7 * 1000 * 1000,
	powerups = {},
	timeOfLeaderChange = 0,
	currentLeader = '',
	benevolentLeader = false,
	showPops = false,
	topThing = null;

	var displayBox = '

<button id="dripbot-toggle" class="btn stop" href="#" onclick="$dripBot.stop(); return false;">Stop</button>

Next Purchase:

';

	var clickButton = $('a#btn-addMem'),
	dripButton = $('button#btn-addGlobalMem'),
	modalButton = 'input.vex-dialog-button-primary';

	var checkForError = function() {
		if(!signupAlerted && $('div#signupDlg').is(':visible')) {
			signupAlerted = true;
			alert("Please sign in to continue playing.  After the page is reloaded, make sure to start DripBot again.");
		}
		if(!errorAlerted && $('div#networkError').is(':visible')) {
			errorAlerted = true;
			alert("DripBot has detected that the game errored (way to go, dripstat).  Please refresh your browser and re-run DripBot.");
		}
	}

	var updateTitleText = function() {
		$('#dripbot-title').text('DripBot v' + version + ', Stage ' + stage + ' (Status: ' + status + ')')
	}

	var toggleStopButton = function(started) {
		var color;
		var toggle = $('#dripbot-toggle');
		if(started) {
			color = stopColor;
			toggle.text('Stop');
			toggle.attr("onclick", "$dripBot.stop(); return false;")
		} else {
			color = startColor;
			toggle.text('Start');
			toggle.attr("onclick", "$dripBot.start(); return false")
		}

		toggle.css({
			"background-color": color
		});
	}

	var updateNextPurchase = function(purchase) {
		str = '';
		if(purchase.isUpgrade) {
			str += '(Upgrade) ';
		}
		str += purchase.item.name;
		$('#next-purchase p').text('Next Purchase: ' + str);
	}

	var updateClickInterval = function() {
		$('#click-interval p').text("Clicking every: " + clickInterval + 'ms');
	}

	function OTB(o, upgrade) {
		if(upgrade) {
			this.isUpgrade = true;
			this.item = o;
			if(o.powerup) {
				if(o.powerup.name == 'Cursor') {
					this.bps = o.powerup.totalBps * 0.1 + getClickingBps() * 0.1;
				} else {
					this.bps = o.powerup.totalBps * 0.1;
				}
			}
			this.realPrice = o.price;
			this.price = o.price;
		} else {
			this.isUpgrade = false;
			this.bps = o.currentBps;
			this.item = o;
			this.realPrice = o.currentPrice;
			this.price = o.currentPrice;
		}
		if(getCapacity() < this.realPrice) {
			this.price = (this.realPrice - getCapacity()) * 2 + getCapacity();
		}

		if(! this.item.available) {
			this.timeToPurchase = (this.price - localStats.byteCount) / localStats.bps;
		} else {
			this.timeToPurchase = 0;
		}
	}

	var buyPowerup = function(name) {
		$(powerups[name]).click();
	}

	var getOTBList = function() {
		var powerupsAndUpgrades = []
		localStats.powerUps.slice(0).forEach(function(e) {
			powerupsAndUpgrades.push(new OTB(e, false));
			if(e.upgrades.length) {
				e.upgrades.forEach(function(u) {
					if((!u._purchased) && u._unlocked) {
						powerupsAndUpgrades.push(new OTB(u, true));
					}
				});
			}
		});
		return powerupsAndUpgrades;
	}

	var sortOTBList = function(otbList) {
		return otbList.sort(function(a,b) {
			var sign = 1,
			shorter,
			longer,
			delta;
			if(b.timeToPurchase >= a.timeToPurchase) {
				shorter = a;
				longer = b;
				sign = 1;
			} else {
				shorter = b;
				longer = a;
				sign = -1;
			}
			var delta = longer.timeToPurchase - shorter.timeToPurchase;
			var newLongerPrice = longer.price + shorter.bps * delta;
			return (shorter.price / shorter.bps - newLongerPrice / longer.bps) * sign; // Adjust based on which was shorter.
		});
	}

	var getNewTopThing = function() {
		topThing = null;
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased && u.available) {
				topThing = new OTB(u, true);
			}
		});
		if(topThing == null) {
			topThing = sortOTBList(getOTBList())[0];
		}
		updateNextPurchase(topThing);
		console.log("Next purchase" + (topThing.isUpgrade ? " (upgrade)" : "") + ": " + topThing.item.name);
	}

	var i = 1;
	localStats.powerUps.forEach(function(pu) { powerups[pu.name] = '#pu' + i++; });

	var getLeader = function() {
		return $('div#leaderBoard table tbody').children('tr').first().children('td').eq(1).text();
	}

	var getClickingBps = function() {
		return CoffeeCup.calcBytesPerClick() * 20;
	}

	var clickCup = function() {
		clickButton.click();
	}

	var drip = function() {
		dripButton.click();
	}

	var getBytes = function() {
		return localStats.byteCount;
	}

	var getCapacity = function() {
		return localStats.memoryCapacity;
	}

	var atMaxBytes = function() {
		return getBytes() == getCapacity();
	}

	var getBPS = function() {
		return localStats.bps;
	}

	var atBPSCap = function() {
		return getBPS() >= BPSThreshold;
	}

	var getMyName = function() {
		return networkUser.userName;
	}

	var getSortedUpgradeList = function() {
		var upgrades = [];
		localStats.powerUps.forEach(function(e) {
			e.upgrades.forEach(function(u) {
				if(u._unlocked && ! u._purchased) {
					upgrades.push(u);
				}
			});
		});
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased) {
				upgrades.push(u);
			}
		});

		upgrades.sort(function(a,b) {
			return a.price - b.price;
		});
		return upgrades;
	}

	var buyUpgrade = function(name) {
		// Not thread safe!  If someone else uses the bytes we'll never know.
		var i = 1;
		getSortedUpgradeList().forEach(function(u) {
			if(u.name == name) {
				var upgrade = $('#upg' + i);
				upgrade.click();

				for(var n=0; n<localStats.specialUpgrades.length; n++) {
					if(localStats.specialUpgrades[n].name == name) {
						$(modalButton).click();
						break;
					}
				}
				return true;
			}
			i++;
		});
		return false;
	}

	var setBPSThreshold = function(num) {
		if(num && num > 0) {
			BPSThreshold = num * 1000 * 1000;
		}
		return BPSThreshold;
	}

	var setClickInterval = function(num) {
		if(num && num > 0) {
			clickInterval = num;
		}
		if(clickerPid != -1) {
			clearInterval(clickerPid);
			clickerPid = setInterval(function() { clickCup(); }, clickInterval);
		}
		updateClickInterval();
		return clickInterval;
	}

	var setBenevolentLeader = function(bool) {
		benevolentLeader = bool || false;
		return benevolentLeader;
	}

	var setShowPops = function(bool) {
		showPops = bool || false;
		return showPops;
	}

	var stage1 = function() {
		if(story.state == 6) {
			drip();
		}

		if(story.state == 9) {
			buyPowerup('Cursor');
		}

		if(story.state == 11) {
			buyUpgrade('Enhanced Precision');
		}

		if(story.state == 12) {
			stage = '2';
			console.log("Proceeding to stage 2 (Purchase).");
			clearInterval(stage1Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			updateTitleText();
			return;
		}

		if(story.state != 12 && atMaxBytes()) {
			drip();
		}
	}

	var stage2 = function() {
		if(atBPSCap()) {
			stage = '3';
			console.log("Proceeding to stage 3 (Win).");
			topThing = null;
			clearInterval(stage2Pid);
			stage3Pid = setInterval(function() { stage3(); }, 1000);
			updateTitleText();
			return;
		}

		if(topThing == null) {
			getNewTopThing();
		}

		if(getBytes() >= topThing.realPrice) {
			if(canBuy) {
				if(topThing.isUpgrade) {
					buyUpgrade(topThing.item.name);
				} else {
					buyPowerup(topThing.item.name);
				}
				canBuy = false;
				setTimeout(function() { canBuy = true; }, 800);

				getNewTopThing();
			}
		} else {
			if(getCapacity() < topThing.realPrice) {
				if((getBytes() + getCapacity()) >= topThing.realPrice || atMaxBytes()) {
					drip();
				}
			}
        }
	}

	var stage3 = function() {
		if(!atBPSCap()) {
			stage = '2';
			console.log("Reverting to stage 2 (Purchase).");
			currentLeader = null;
			timeOfLeaderChange = null;
			clearInterval(stage3Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			updateTitleText();
			return;
		}

		var leaderName = getLeader();
		if(!currentLeader) {
			currentLeader = getMyName();
		}

		if (leaderName != getMyName()) {
			if(currentLeader == getMyName()) {
				currentLeader = leaderName;
				timeOfLeaderChange = $.now();
				console.log("As of " + timeOfLeaderChange + " there is one fairer in the land... it is '" + leaderName + "'.");

			} else if(leaderName != currentLeader) {
				console.log("Leader changed from '" + currentLeader + "' to '" + leaderName + "'.");
				currentLeader = leaderName;
			}
			drip();

		} else {
			if (currentLeader != leaderName) {
				currentLeader = leaderName;
				var diffTime = $.time;
				console.log("As of " + $.now() + " you are the fairest of them all (it took " + diffTime + " to recover).");
			}

			if(!benevolentLeader) {
				drip();
			}
		}
	}

	var stop = function() {
		if(!started) {
			return;
		} else {
			started = false;
			status = 'Stopped';
		}
		console.log('Stopping DripBot.');
		clearInterval(stage1Pid);
		clearInterval(stage2Pid);
		clearInterval(stage3Pid);
		clearInterval(clickerPid);
		clearInterval(errorCheckPid);
		stage1Pid = -1;
		stage2Pid = -1;
		stage3Pid = -1;
		clickerPid = -1;
		errorCheckPid = -1;
		updateTitleText();
		toggleStopButton(false);
	}

	var start = function() {
		if(started) {
			return;
		} else {
			started = true;
			status = 'Running';
		}
		console.log('Starting DripBot v' + version + '!');
		if (story.inProgress) {
			console.log("Starting or resuming story.");
			stage = '1';
			stage1Pid = setInterval(function() { stage1(); }, 100);
		} else if(!atBPSCap()) {
			stage = '2';
			console.log("Resuming stage 2 (Purchase).");
			stage2Pid = setInterval(function() { stage2(); }, 500);
		} else {
			stage = '3';
			console.log("Resuming stage 3 (Win).");
			stage3Pid = setInterval(function() { stage3(); }, 1000);
		}
		updateTitleText();
		toggleStopButton(true);
		clickerPid = setInterval(function() { clickCup(); }, clickInterval);
		errorCheckPid = setInterval(function() { checkForError(); }, 2000);
	}

	var restart = function() {
		stop();
		start();
	}

	var init = function() {
		document.hasFocus = function() { return true; };
		AnonymousUserManager.canDrip = function() { return true; };
		popManager.oldNewPop = popManager.newPop;
		popManager.newPop = function(e, t, a) {
			if(showPops || (e.indexOf('addMem') == -1 && e != 'chartContainer')) {
				popManager.oldNewPop(e,t,a);
			}
		}
		$('div#middleColumn').append(displayBox);
		$.getScript('https://raw.github.com/apottere/DripBot/master/dripBot-css.js');
		updateClickInterval();
		clickCup();
		setTimeout(function() { start(); }, 500);
	}

	init();

	return {
		setBPSThreshold: setBPSThreshold,
		setBenevolentLeader: setBenevolentLeader,
		setShowPops: setShowPops,
		setClickInterval: setClickInterval,

		stop: stop,
		start: start,
		restart: restart
	};
}($, (typeof($dripBot) !== 'undefined' ? $dripBot : null)));
<commit_msg>Add pro mode.<commit_after>$dripBot = (function($, $dripBot, isPro) {

	if($dripBot instanceof Object) {
		console.log("Refusing to run two dripBots (this could have unintended side effects).  Please refresh to update.");
		return $dripBot;
	}

	var version = '1.1',
	isDripBotPro = isPro,
	stage1Pid = -1,
	stage2Pid = -1,
	stage3Pid = -1,
	canBuy = true,
	errorCheckPid = -1,
	errorAlerted = false,
	signupAlerted = false,
	stage = '',
	started = false,
	status = 'Running',
	stopColor = '#e9656d',
	startColor = '#47a447',
	clickerPid = -1,
	clickInterval = 45,
	BPSThreshold = 7 * 1000 * 1000,
	powerups = {},
	timeOfLeaderChange = 0,
	currentLeader = '',
	benevolentLeader = false,
	showPops = false,
	topThing = null;

	var displayBox = '

<button id="dripbot-toggle" class="btn stop" href="#" onclick="$dripBot.stop(); return false;">Stop</button>

Next Purchase:

';

	var clickButton = $('a#btn-addMem'),
	dripButton = $('button#btn-addGlobalMem'),
	modalButton = 'input.vex-dialog-button-primary';

	var checkForError = function() {
		if(!signupAlerted && $('div#signupDlg').is(':visible')) {
			signupAlerted = true;
			alert("Please sign in to continue playing.  After the page is reloaded, make sure to start DripBot again.");
		}
		if(!errorAlerted && $('div#networkError').is(':visible')) {
			errorAlerted = true;
			alert("DripBot has detected that the game errored (way to go, dripstat).  Please refresh your browser and re-run DripBot.");
		}
	}

	var updateTitleText = function() {
		$('#dripbot-title').text('DripBot v' + version + (isDripBotPro ? ' Pro' : '') + ', Stage ' + stage + ' (Status: ' + status + ')')
	}

	var toggleStopButton = function(started) {
		var color;
		var toggle = $('#dripbot-toggle');
		if(started) {
			color = stopColor;
			toggle.text('Stop');
			toggle.attr("onclick", "$dripBot.stop(); return false;")
		} else {
			color = startColor;
			toggle.text('Start');
			toggle.attr("onclick", "$dripBot.start(); return false")
		}

		toggle.css({
			"background-color": color
		});
	}

	var updateNextPurchase = function(purchase) {
		str = '';
		if(purchase.isUpgrade) {
			str += '(Upgrade) ';
		}
		str += purchase.item.name;
		$('#next-purchase p').text('Next Purchase: ' + str);
	}

	var updateClickInterval = function() {
		$('#click-interval p').text("Clicking every: " + clickInterval + 'ms');
	}

	function OTB(o, upgrade) {
		if(upgrade) {
			this.isUpgrade = true;
			this.item = o;
			if(o.powerup) {
				if(o.powerup.name == 'Cursor') {
					this.bps = o.powerup.totalBps * 0.1 + getClickingBps() * 0.1;
				} else {
					this.bps = o.powerup.totalBps * 0.1;
				}
			}
			this.realPrice = o.price;
			this.price = o.price;
		} else {
			this.isUpgrade = false;
			this.bps = o.currentBps;
			this.item = o;
			this.realPrice = o.currentPrice;
			this.price = o.currentPrice;
		}
		if(getCapacity() < this.realPrice) {
			this.price = (this.realPrice - getCapacity()) * 2 + getCapacity();
		}

		if(! this.item.available) {
			this.timeToPurchase = (this.price - localStats.byteCount) / localStats.bps;
		} else {
			this.timeToPurchase = 0;
		}
	}

	var buyPowerup = function(name) {
		$(powerups[name]).click();
	}

	var getOTBList = function() {
		var powerupsAndUpgrades = []
		localStats.powerUps.slice(0).forEach(function(e) {
			powerupsAndUpgrades.push(new OTB(e, false));
			if(e.upgrades.length) {
				e.upgrades.forEach(function(u) {
					if((!u._purchased) && u._unlocked) {
						powerupsAndUpgrades.push(new OTB(u, true));
					}
				});
			}
		});
		return powerupsAndUpgrades;
	}

	var sortOTBList = function(otbList) {
		return otbList.sort(function(a,b) {
			var sign = 1,
			shorter,
			longer,
			delta;
			if(b.timeToPurchase >= a.timeToPurchase) {
				shorter = a;
				longer = b;
				sign = 1;
			} else {
				shorter = b;
				longer = a;
				sign = -1;
			}
			var delta = longer.timeToPurchase - shorter.timeToPurchase;
			var newLongerPrice = longer.price + shorter.bps * delta;
			return (shorter.price / shorter.bps - newLongerPrice / longer.bps) * sign; // Adjust based on which was shorter.
		});
	}

	var getNewTopThing = function() {
		topThing = null;
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased && u.available) {
				topThing = new OTB(u, true);
			}
		});
		if(topThing == null) {
			topThing = sortOTBList(getOTBList())[0];
		}
		updateNextPurchase(topThing);
		console.log("Next purchase" + (topThing.isUpgrade ? " (upgrade)" : "") + ": " + topThing.item.name);
	}

	var i = 1;
	localStats.powerUps.forEach(function(pu) { powerups[pu.name] = '#pu' + i++; });

	var getLeader = function() {
		return $('div#leaderBoard table tbody').children('tr').first().children('td').eq(1).text();
	}

	var getClickingBps = function() {
		return CoffeeCup.calcBytesPerClick() * 20;
	}

	var clickCup = function() {
		clickButton.click();
	}

	var drip = function() {
		dripButton.click();
	}

	var getBytes = function() {
		return localStats.byteCount;
	}

	var getCapacity = function() {
		return localStats.memoryCapacity;
	}

	var atMaxBytes = function() {
		return getBytes() == getCapacity();
	}

	var getBPS = function() {
		return localStats.bps;
	}

	var atBPSCap = function() {
		return getBPS() >= BPSThreshold;
	}

	var getMyName = function() {
		return networkUser.userName;
	}

	var getSortedUpgradeList = function() {
		var upgrades = [];
		localStats.powerUps.forEach(function(e) {
			e.upgrades.forEach(function(u) {
				if(u._unlocked && ! u._purchased) {
					upgrades.push(u);
				}
			});
		});
		localStats.specialUpgrades.forEach(function(u) {
			if(!u._purchased) {
				upgrades.push(u);
			}
		});

		upgrades.sort(function(a,b) {
			return a.price - b.price;
		});
		return upgrades;
	}

	var buyUpgrade = function(name) {
		// Not thread safe!  If someone else uses the bytes we'll never know.
		var i = 1;
		getSortedUpgradeList().forEach(function(u) {
			if(u.name == name) {
				var upgrade = $('#upg' + i);
				upgrade.click();

				for(var n=0; n<localStats.specialUpgrades.length; n++) {
					if(localStats.specialUpgrades[n].name == name) {
						$(modalButton).click();
						break;
					}
				}
				return true;
			}
			i++;
		});
		return false;
	}

	var setBPSThreshold = function(num) {
		if(num && num > 0) {
			BPSThreshold = num * 1000 * 1000;
		}
		return BPSThreshold;
	}

	var setClickInterval = function(num) {
		if(num && num > 0) {
			clickInterval = num;
		}
		if(clickerPid != -1) {
			clearInterval(clickerPid);
			clickerPid = setInterval(function() { clickCup(); }, clickInterval);
		}
		updateClickInterval();
		return clickInterval;
	}

	var setBenevolentLeader = function(bool) {
		benevolentLeader = bool || false;
		return benevolentLeader;
	}

	var setShowPops = function(bool) {
		showPops = bool || false;
		return showPops;
	}

	var stage1 = function() {
		if(story.state == 6) {
			drip();
		}

		if(story.state == 9) {
			buyPowerup('Cursor');
		}

		if(story.state == 11) {
			buyUpgrade('Enhanced Precision');
		}

		if(story.state == 12) {
			stage = '2';
			console.log("Proceeding to stage 2 (Purchase).");
			clearInterval(stage1Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			updateTitleText();
			return;
		}

		if(story.state != 12 && atMaxBytes()) {
			drip();
		}
	}

	var stage2 = function() {
		if(atBPSCap()) {
			stage = '3';
			console.log("Proceeding to stage 3 (Win).");
			topThing = null;
			clearInterval(stage2Pid);
			stage3Pid = setInterval(function() { stage3(); }, 1000);
			updateTitleText();
			return;
		}

		if(topThing == null) {
			getNewTopThing();
		}

		if(getBytes() >= topThing.realPrice) {
			if(canBuy) {
				if(topThing.isUpgrade) {
					buyUpgrade(topThing.item.name);
				} else {
					buyPowerup(topThing.item.name);
				}
				canBuy = false;
				setTimeout(function() { canBuy = true; }, 800);

				getNewTopThing();
			}
		} else {
			if(getCapacity() < topThing.realPrice) {
				if((getBytes() + getCapacity()) >= topThing.realPrice || atMaxBytes()) {
					drip();
				}
			}
        }
	}

	var stage3 = function() {
		if(!atBPSCap()) {
			stage = '2';
			console.log("Reverting to stage 2 (Purchase).");
			currentLeader = null;
			timeOfLeaderChange = null;
			clearInterval(stage3Pid);
			stage2Pid = setInterval(function() { stage2(); }, 500);
			updateTitleText();
			return;
		}

		var leaderName = getLeader();
		if(!currentLeader) {
			currentLeader = getMyName();
		}

		if (leaderName != getMyName()) {
			if(currentLeader == getMyName()) {
				currentLeader = leaderName;
				timeOfLeaderChange = $.now();
				console.log("As of " + timeOfLeaderChange + " there is one fairer in the land... it is '" + leaderName + "'.");

			} else if(leaderName != currentLeader) {
				console.log("Leader changed from '" + currentLeader + "' to '" + leaderName + "'.");
				currentLeader = leaderName;
			}
			drip();

		} else {
			if (currentLeader != leaderName) {
				currentLeader = leaderName;
				var diffTime = $.time;
				console.log("As of " + $.now() + " you are the fairest of them all (it took " + diffTime + " to recover).");
			}

			if(!benevolentLeader) {
				drip();
			}
		}
	}

	var stop = function() {
		if(!started) {
			return;
		} else {
			started = false;
			status = 'Stopped';
		}
		console.log('Stopping DripBot.');
		clearInterval(stage1Pid);
		clearInterval(stage2Pid);
		clearInterval(stage3Pid);
		clearInterval(clickerPid);
		clearInterval(errorCheckPid);
		stage1Pid = -1;
		stage2Pid = -1;
		stage3Pid = -1;
		clickerPid = -1;
		errorCheckPid = -1;
		updateTitleText();
		toggleStopButton(false);
	}

	var start = function() {
		if(started) {
			return;
		} else {
			started = true;
			status = 'Running';
		}
		console.log('Starting DripBot v' + version + '!');
		if (story.inProgress) {
			console.log("Starting or resuming story.");
			stage = '1';
			stage1Pid = setInterval(function() { stage1(); }, 100);
		} else if(!atBPSCap()) {
			stage = '2';
			console.log("Resuming stage 2 (Purchase).");
			stage2Pid = setInterval(function() { stage2(); }, 500);
		} else {
			stage = '3';
			console.log("Resuming stage 3 (Win).");
			stage3Pid = setInterval(function() { stage3(); }, 1000);
		}
		updateTitleText();
		toggleStopButton(true);
		clickerPid = setInterval(function() { clickCup(); }, clickInterval);
		errorCheckPid = setInterval(function() { checkForError(); }, 2000);
	}

	var restart = function() {
		stop();
		start();
	}

	var init = function() {
		document.hasFocus = function() { return true; };
		AnonymousUserManager.canDrip = function() { return true; };
		popManager.oldNewPop = popManager.newPop;
		popManager.newPop = function(e, t, a) {
			if(showPops || (e.indexOf('addMem') == -1 && e != 'chartContainer')) {
				popManager.oldNewPop(e,t,a);
			}
		}
		$('div#middleColumn').append(displayBox);
		$.getScript('https://raw.github.com/apottere/DripBot/master/dripBot-css.js');
		updateClickInterval();
		clickCup();
		setTimeout(function() { start(); }, 500);
	}

	init();

	return {
		setBPSThreshold: setBPSThreshold,
		setBenevolentLeader: setBenevolentLeader,
		setShowPops: setShowPops,
		setClickInterval: setClickInterval,

		stop: stop,
		start: start,
		restart: restart
	};
}(
	$,
	(typeof($dripBot) !== 'undefined' ? $dripBot : null),
	(typeof(window.dripBotPro) !== 'undefined' ? window.dripBotPro : false)
));
<|endoftext|>