<commit_before>

define(['q'], function(Q) {
    'use strict';

    return {
	trackedProcesses: ['catkin_make', 'node_main', 'roscore'],
	sanitizePath: function(path) {
	    return path.replace(/ /g, '\ ');
	},
	getDeviceType: function(host) {
	    return host.deviceId + '+' + host.architecture;
	},
	range: function(lowEnd,highEnd) {
	    var arr = [],
	    c = highEnd - lowEnd + 1;
	    while ( c-- ) {
		arr[c] = highEnd--
	    }
	    return arr;
	},
	testPing: function(ip) {
	    var self = this;
	    var ping = require('ping');
	    return ping.promise.probe(ip)
		.then(function (res) {
		    if (!res.alive)
			throw new String(ip + ' is not reachable.');
		    return true;
		});
	},
	testSSH: function(ip, user) {
	    var self = this;
	    return self.executeOnHost(['echo "hello"'], ip, user)
		.then(function () {
		    return true;
		})
		.catch(function (err) {
		    throw new String(user.name + '@' + ip + ' not SSH-able: ' + err);
		});
	},
	testArchOS: function(arch, os, ip, user) {
	    var self = this;
	    return self.executeOnHost(['uname -om'], ip, user)
		.then(function (output) {
		    var correctArch = output.stdout.indexOf(arch) > -1;
		    var correctOS = output.stdout.indexOf(os) > -1;
		    if (!correctArch) {
			throw new String('host ' + ip + ':' + arch +
					 ' has incorrect architecture: '+ output.stdout);
		    }
		    if (!correctOS) {
			throw new String('host ' + ip + ':' + os +
					 ' has incorrect OS: '+ output.stdout);
		    }
		    return true;
		});
	},
	testDeviceId: function(deviceId, deviceIdCommand, ip, user) {
	    var self = this;
	    var cmds = [deviceIdCommand];
	    return self.executeOnHost(cmds, ip, user)
		.then(function (output) {
		    var correctDeviceId = output.stdout.indexOf(deviceId) > -1;
		    if (!correctDeviceId) {
			throw new String('host ' + ip + ':' + deviceId +
					 ' has incorrect deviceId: '+ output.stdout);
		    }
		    return true;
		});
	},
	isFree: function(ip, user) {
	    var self = this;
	    var tasks = self.trackedProcesses.map(function(procName) {
		return self.getPidOnHost(procName, ip, user);
	    });
	    return Q.all(tasks)
		.then(function(outputs) {
		    outputs.forEach(function (output) {
			if (output.stdout) {
			    throw new String(ip + ' is already running: ' + output.stdout);
			};
		    });
		    return true;
		});
	},
	getAvailability: function(host, checkTasks) {
	    var self = this;
	    if (checkTasks === undefined)
		checkTasks = true;
	    // test IP connectivity
	    var tasks = Object.keys(host.interfaces).map(function(index) {
		var intf = host.interfaces[index];
		return self.testPing(intf.ip)
		    .then(function() {
			var userTasks = Object.keys(host.users).map(function(index) {
			    var user = host.users[index];
			    self.logger.info('testing ' + user.name + ' on ' + intf.ip);
			    return self.testSSH(intf.ip, user)
				.then(function() {
				    return user;
				});
			});
			return Q.any(userTasks);
		    })
		    .then(function(user) {
			self.logger.info(intf.ip + ' got valid user: ' + user.name);
			return self.testArchOS(host.architecture, host.os, intf.ip, user)
			    .then(function() {
				return self.testDeviceId(host.deviceId, host.deviceIdCommand, intf.ip, user);
			    })
			    .then(function() {
				if (checkTasks)
				    return self.isFree(intf.ip, user)
				else
				    return [];
			    })
			    .then(function() {
				return {host: host, intf:intf, user:user};
			    });
		    })
		    .catch(function(err) {
			self.logger.error(err);
		    });
	    });
	    return Q.all(tasks);
	},
	getAvailableHosts: function(hosts, checkTasks) {
	    var self = this;
	    if (checkTasks === undefined)
		checkTasks = true;
	    var tasks = Object.keys(hosts).map(function(index) {
		var host = hosts[index];
		return self.getAvailability(host, checkTasks);
	    });
	    return Q.all(tasks)
		.then(function(availArray) {
		    var hostsUp = [];
		    for (var i=0; i < availArray.length; i++) {
			if (availArray[i][0])
			    hostsUp.push(availArray[i][0]);
		    }
		    return hostsUp;
		});
	},
	executeOnHost: function(cmds, ip, user, cb_message, cb_complete, cb_processing, cb_error) {
	    var self = this;
	    var ssh2shell = require('ssh2shell');
	    var output = {
		user: user,
		ip: ip,
		stdout: ''
	    };

	    var host = {
		server: {
		    host: ip,
		    port: 22,
		    userName: user.name,
		    privateKey: require('fs').readFileSync(user.key)
		},
		commands: cmds,
		idleTimeOut: 10000,
		msg: {
		    send: function( message ) {
			if (cb_message)
			    cb_message(message);
		    }
		},
		onCommandProcessing: function( command, response, sshObj, stream ) {
		    if (cb_processing) {
			cb_processing(command, response);
		    }
		},
		onCommandComplete: function( command, response, sshObj ) {
		    if (cb_complete) {
			self.logger.info(command);
			self.logger.info(response);
			//cb_complete(command, response);
		    }
		},
		onCommandTimeout: function( command, response, sshObj, stream, connection) {
		    // pass through, we don't want to time out
		},
		onEnd: function( sessionText, sshObj ) {
		    var stdout = sessionText;
		    stdout = stdout.replace('Connected to '+ip,'');
		    stdout = stdout.replace(new RegExp(user.name + '@.+\$'), '');
		    output.stdout = stdout;
		}
	    };
	    var ssh = new ssh2shell(host);
	    /*
	      ssh.on ("error", function(err, type, close, cb) {
	      reject(err + ' on ' + user.name + '@' + ip);
	      if (cb_error)
	      cb_error(err, type, close, cb);
	      });
	    */
	    var deferred = Q.defer();
	    ssh.on("close", function(hadError) {
		if (hadError) {
		    deferred.reject();
		}
		else {
		    deferred.resolve(output);
		}
	    });
	    ssh.connect();
	    return deferred.promise;
	},
	parseMakePercentOutput: function(output) {
	    var regex = /[0-9]+%/gm;
	    var match = null;
	    var retVals = [];
	    while (match = regex.exec(output)) {
		var percent = parseInt(new String(match).replace('%',''), 10);
		retVals.push(percent);
	    }
	    return retVals;
	},
	parseMakeErrorOutput: function(output) {
	    var regex = /([^:^\n]+):(\d+):(\d+):\s(\w+\s*\w*):\s(.+)\n(\s+)(.*)\s+\^+/gm;
	    var match = null;
	    var retVals = [];
	    while (match = regex.exec(output)) {
		retVals.push({
		    filename:       match[1].replace(self.gen_dir + '/src/', ''),
		    packageName:    filename.split('/')[0],
		    line:           parseInt(match[2]),
		    column:         parseInt(match[3]),
		    type:           match[4],
		    text:           match[5],
		    codeWhitespace: match[6],
		    code:           match[7],
		    adjustedColumn: column - codeWhitespace.length
		});
	    }
	    return retVals;
	},
	parsePsAuxOutput: function(output) {
	    return output;
	},
	mkdirRemote: function(dir, ip, user) {
	    var self = this;
	    dir = self.sanitizePath(dir);
	    return self.executeOnHost(['mkdir -p ' + dir],
				      ip,
				      user);
	},
	copyToHost: function(from, to, ip, user) {
	    var self = this;
	    var client = require('scp2');
	    from = self.sanitizePath(from);
	    to = self.sanitizePath(to);
	    var deferred = Q.defer();
	    client.scp(from, {
		host: ip,
		username: user.name,
		privateKey: require('fs').readFileSync(user.key),
		path: to
	    }, function(err) {
		if (err)
		    deferred.reject(err);
		else
		    deferred.resolve();
	    });
	    return deferred.promise;
	},
	copyFromHost: function(from, to, ip, user) {
	    var self = this;
	    from = self.sanitizePath(from);
	    to = self.sanitizePath(to);
	    var url = require('url'),
	    path = require('path'),
	    fs = require('fs'),
	    unzip = require('unzip'),
	    fstream = require('fstream'),
	    child_process = require('child_process');

	    var local = to;
	    var remote = user.name + '@' + ip + ':' + from;

	    var scp = 'scp -o StrictHostKeyChecking=no -i ' + user.key + ' -r ' + remote + ' ' + local;

	    var deferred = Q.defer();

	    var child = child_process.exec(scp, function(err, stdout, stderr) {
		if (err) {
		    deferred.reject(err);
		}
		else {
		    deferred.resolve('copied ' + remote + ' into ' + local);
		}
	    });
	    return deferred.promise;
	},
	getPidOnHost: function(procName, ip, user, stdout_cb, stderr_cb) {
	    var self = this;
	    var cmd = 'ps aux | grep -v grep | grep ' + procName;
	    return self.executeOnHost([cmd], ip, user)
		.then(function(output) {
		    output.stdout = output.stdout.replace(cmd, '').match(procName);
		    return output;
		});
	},
	wgetAndUnzipLibrary: function(file_url, dir) {
	    var self = this,
	    var url = require('url'),
	    path = require('path'),
	    fs = require('fs'),
	    unzip = require('unzip'),
	    fstream = require('fstream'),
	    child_process = require('child_process');
	    dir = self.sanitizePath(dir);
	    // extract the file name
	    var file_name = url.parse(file_url).pathname.split('/').pop();

	    var final_dir = path.join(process.cwd(), dir).toString();
	    var final_file = path.join(final_dir, file_name);

	    // compose the wget command; -O is output file
	    var wget = 'wget --no-check-certificate -P ' + dir + ' ' + file_url;

	    var deferred = Q.defer();

	    // excute wget using child_process' exec function
	    var child = child_process.exec(wget, function(err, stdout, stderr) {
		if (err) {
		    deferred.reject(err);
		}
		else {
		    var fname = path.join(dir,file_name);
		    var readStream = fs.createReadStream(fname);
		    var writeStream = fstream.Writer(dir);
		    if (readStream == undefined || writeStream == undefined) {
			deferred.reject("Couldn't open " + dir + " or " + fname);
			return;
		    }
		    readStream
			.pipe(unzip.Parse())
			.pipe(writeStream);
		    fs.unlink(fname);
		    deferred.resolve('downloaded and unzipped ' + file_name + ' into ' + dir);
		}
	    });
	    return deferred.promise;
	}
    }
});
<commit_msg>fixed line ending.<commit_after>

define(['q'], function(Q) {
    'use strict';

    return {
	trackedProcesses: ['catkin_make', 'node_main', 'roscore'],
	sanitizePath: function(path) {
	    return path.replace(/ /g, '\ ');
	},
	getDeviceType: function(host) {
	    return host.deviceId + '+' + host.architecture;
	},
	range: function(lowEnd,highEnd) {
	    var arr = [],
	    c = highEnd - lowEnd + 1;
	    while ( c-- ) {
		arr[c] = highEnd--
	    }
	    return arr;
	},
	testPing: function(ip) {
	    var self = this;
	    var ping = require('ping');
	    return ping.promise.probe(ip)
		.then(function (res) {
		    if (!res.alive)
			throw new String(ip + ' is not reachable.');
		    return true;
		});
	},
	testSSH: function(ip, user) {
	    var self = this;
	    return self.executeOnHost(['echo "hello"'], ip, user)
		.then(function () {
		    return true;
		})
		.catch(function (err) {
		    throw new String(user.name + '@' + ip + ' not SSH-able: ' + err);
		});
	},
	testArchOS: function(arch, os, ip, user) {
	    var self = this;
	    return self.executeOnHost(['uname -om'], ip, user)
		.then(function (output) {
		    var correctArch = output.stdout.indexOf(arch) > -1;
		    var correctOS = output.stdout.indexOf(os) > -1;
		    if (!correctArch) {
			throw new String('host ' + ip + ':' + arch +
					 ' has incorrect architecture: '+ output.stdout);
		    }
		    if (!correctOS) {
			throw new String('host ' + ip + ':' + os +
					 ' has incorrect OS: '+ output.stdout);
		    }
		    return true;
		});
	},
	testDeviceId: function(deviceId, deviceIdCommand, ip, user) {
	    var self = this;
	    var cmds = [deviceIdCommand];
	    return self.executeOnHost(cmds, ip, user)
		.then(function (output) {
		    var correctDeviceId = output.stdout.indexOf(deviceId) > -1;
		    if (!correctDeviceId) {
			throw new String('host ' + ip + ':' + deviceId +
					 ' has incorrect deviceId: '+ output.stdout);
		    }
		    return true;
		});
	},
	isFree: function(ip, user) {
	    var self = this;
	    var tasks = self.trackedProcesses.map(function(procName) {
		return self.getPidOnHost(procName, ip, user);
	    });
	    return Q.all(tasks)
		.then(function(outputs) {
		    outputs.forEach(function (output) {
			if (output.stdout) {
			    throw new String(ip + ' is already running: ' + output.stdout);
			};
		    });
		    return true;
		});
	},
	getAvailability: function(host, checkTasks) {
	    var self = this;
	    if (checkTasks === undefined)
		checkTasks = true;
	    // test IP connectivity
	    var tasks = Object.keys(host.interfaces).map(function(index) {
		var intf = host.interfaces[index];
		return self.testPing(intf.ip)
		    .then(function() {
			var userTasks = Object.keys(host.users).map(function(index) {
			    var user = host.users[index];
			    self.logger.info('testing ' + user.name + ' on ' + intf.ip);
			    return self.testSSH(intf.ip, user)
				.then(function() {
				    return user;
				});
			});
			return Q.any(userTasks);
		    })
		    .then(function(user) {
			self.logger.info(intf.ip + ' got valid user: ' + user.name);
			return self.testArchOS(host.architecture, host.os, intf.ip, user)
			    .then(function() {
				return self.testDeviceId(host.deviceId, host.deviceIdCommand, intf.ip, user);
			    })
			    .then(function() {
				if (checkTasks)
				    return self.isFree(intf.ip, user)
				else
				    return [];
			    })
			    .then(function() {
				return {host: host, intf:intf, user:user};
			    });
		    })
		    .catch(function(err) {
			self.logger.error(err);
		    });
	    });
	    return Q.all(tasks);
	},
	getAvailableHosts: function(hosts, checkTasks) {
	    var self = this;
	    if (checkTasks === undefined)
		checkTasks = true;
	    var tasks = Object.keys(hosts).map(function(index) {
		var host = hosts[index];
		return self.getAvailability(host, checkTasks);
	    });
	    return Q.all(tasks)
		.then(function(availArray) {
		    var hostsUp = [];
		    for (var i=0; i < availArray.length; i++) {
			if (availArray[i][0])
			    hostsUp.push(availArray[i][0]);
		    }
		    return hostsUp;
		});
	},
	executeOnHost: function(cmds, ip, user, cb_message, cb_complete, cb_processing, cb_error) {
	    var self = this;
	    var ssh2shell = require('ssh2shell');
	    var output = {
		user: user,
		ip: ip,
		stdout: ''
	    };

	    var host = {
		server: {
		    host: ip,
		    port: 22,
		    userName: user.name,
		    privateKey: require('fs').readFileSync(user.key)
		},
		commands: cmds,
		idleTimeOut: 10000,
		msg: {
		    send: function( message ) {
			if (cb_message)
			    cb_message(message);
		    }
		},
		onCommandProcessing: function( command, response, sshObj, stream ) {
		    if (cb_processing) {
			cb_processing(command, response);
		    }
		},
		onCommandComplete: function( command, response, sshObj ) {
		    if (cb_complete) {
			self.logger.info(command);
			self.logger.info(response);
			//cb_complete(command, response);
		    }
		},
		onCommandTimeout: function( command, response, sshObj, stream, connection) {
		    // pass through, we don't want to time out
		},
		onEnd: function( sessionText, sshObj ) {
		    var stdout = sessionText;
		    stdout = stdout.replace('Connected to '+ip,'');
		    stdout = stdout.replace(new RegExp(user.name + '@.+\$'), '');
		    output.stdout = stdout;
		}
	    };
	    var ssh = new ssh2shell(host);
	    /*
	      ssh.on ("error", function(err, type, close, cb) {
	      reject(err + ' on ' + user.name + '@' + ip);
	      if (cb_error)
	      cb_error(err, type, close, cb);
	      });
	    */
	    var deferred = Q.defer();
	    ssh.on("close", function(hadError) {
		if (hadError) {
		    deferred.reject();
		}
		else {
		    deferred.resolve(output);
		}
	    });
	    ssh.connect();
	    return deferred.promise;
	},
	parseMakePercentOutput: function(output) {
	    var regex = /[0-9]+%/gm;
	    var match = null;
	    var retVals = [];
	    while (match = regex.exec(output)) {
		var percent = parseInt(new String(match).replace('%',''), 10);
		retVals.push(percent);
	    }
	    return retVals;
	},
	parseMakeErrorOutput: function(output) {
	    var regex = /([^:^\n]+):(\d+):(\d+):\s(\w+\s*\w*):\s(.+)\n(\s+)(.*)\s+\^+/gm;
	    var match = null;
	    var retVals = [];
	    while (match = regex.exec(output)) {
		retVals.push({
		    filename:       match[1].replace(self.gen_dir + '/src/', ''),
		    packageName:    filename.split('/')[0],
		    line:           parseInt(match[2]),
		    column:         parseInt(match[3]),
		    type:           match[4],
		    text:           match[5],
		    codeWhitespace: match[6],
		    code:           match[7],
		    adjustedColumn: column - codeWhitespace.length
		});
	    }
	    return retVals;
	},
	parsePsAuxOutput: function(output) {
	    return output;
	},
	mkdirRemote: function(dir, ip, user) {
	    var self = this;
	    dir = self.sanitizePath(dir);
	    return self.executeOnHost(['mkdir -p ' + dir],
				      ip,
				      user);
	},
	copyToHost: function(from, to, ip, user) {
	    var self = this;
	    var client = require('scp2');
	    from = self.sanitizePath(from);
	    to = self.sanitizePath(to);
	    var deferred = Q.defer();
	    client.scp(from, {
		host: ip,
		username: user.name,
		privateKey: require('fs').readFileSync(user.key),
		path: to
	    }, function(err) {
		if (err)
		    deferred.reject(err);
		else
		    deferred.resolve();
	    });
	    return deferred.promise;
	},
	copyFromHost: function(from, to, ip, user) {
	    var self = this;
	    from = self.sanitizePath(from);
	    to = self.sanitizePath(to);
	    var url = require('url'),
	    path = require('path'),
	    fs = require('fs'),
	    unzip = require('unzip'),
	    fstream = require('fstream'),
	    child_process = require('child_process');

	    var local = to;
	    var remote = user.name + '@' + ip + ':' + from;

	    var scp = 'scp -o StrictHostKeyChecking=no -i ' + user.key + ' -r ' + remote + ' ' + local;

	    var deferred = Q.defer();

	    var child = child_process.exec(scp, function(err, stdout, stderr) {
		if (err) {
		    deferred.reject(err);
		}
		else {
		    deferred.resolve('copied ' + remote + ' into ' + local);
		}
	    });
	    return deferred.promise;
	},
	getPidOnHost: function(procName, ip, user, stdout_cb, stderr_cb) {
	    var self = this;
	    var cmd = 'ps aux | grep -v grep | grep ' + procName;
	    return self.executeOnHost([cmd], ip, user)
		.then(function(output) {
		    output.stdout = output.stdout.replace(cmd, '').match(procName);
		    return output;
		});
	},
	wgetAndUnzipLibrary: function(file_url, dir) {
	    var self = this;
	    var url = require('url'),
	    path = require('path'),
	    fs = require('fs'),
	    unzip = require('unzip'),
	    fstream = require('fstream'),
	    child_process = require('child_process');
	    dir = self.sanitizePath(dir);
	    // extract the file name
	    var file_name = url.parse(file_url).pathname.split('/').pop();

	    var final_dir = path.join(process.cwd(), dir).toString();
	    var final_file = path.join(final_dir, file_name);

	    // compose the wget command; -O is output file
	    var wget = 'wget --no-check-certificate -P ' + dir + ' ' + file_url;

	    var deferred = Q.defer();

	    // excute wget using child_process' exec function
	    var child = child_process.exec(wget, function(err, stdout, stderr) {
		if (err) {
		    deferred.reject(err);
		}
		else {
		    var fname = path.join(dir,file_name);
		    var readStream = fs.createReadStream(fname);
		    var writeStream = fstream.Writer(dir);
		    if (readStream == undefined || writeStream == undefined) {
			deferred.reject("Couldn't open " + dir + " or " + fname);
			return;
		    }
		    readStream
			.pipe(unzip.Parse())
			.pipe(writeStream);
		    fs.unlink(fname);
		    deferred.resolve('downloaded and unzipped ' + file_name + ' into ' + dir);
		}
	    });
	    return deferred.promise;
	}
    }
});
<|endoftext|>


<commit_before>let { type, rangeCheck, repeat } = require("../utility");
let Vector = require("./Vector");

module.exports = class Matrix {

  constructor(columns, rows, data) {
    this.columns = columns;
    this.rows    = rows;
    this.data    = data;
  }

  static create(m) {
    let columns = null;
    let rows = 0;
    let data = [ ];
    for (let row of m) {
      let rowLength = 0;
      for (let element of row) {
        if (typeof element != "number")
          throw new Error(`Expected number, got '${ type(element) }'`)
        data.push(element);
        rowLength++;
      }
      if (columns == null) columns = rowLength;
      else if (rowLength != columns)
        throw new Error(`Row lengths don't match (${ rowLength } != ${ columns })`);
      rows++;
    }
    if ((rows == 0) || (columns == 0))
      throw new Error("Matrix must have at least one element");
    return new Matrix(columns, rows, data);
  }

  static zero(columns, rows = columns) {
    if ((columns <= 0) || (rows <= 0))
      throw new Error(`Invalid matrix dimensions (${ columns },${ rows })`);
    let data = new Array(columns * rows);
    return new Matrix(columns, rows, data);
  }

  static identity(size) {
    let matrix = Matrix.zero(size);
    for (let i = 0; i < size; i++)
      matrix.set(i, i, 1);
    return matrix;
  }

  static translation(...v) {
    let matrix = Matrix.identity(v.length - 1);
    for (let i = 0; i < v.length; i++)
      matrix.set(i, matrix.rows - 1, v[i]);
    return matrix;
  }

  static scale(...v) {
    let matrix = Matrix.identity(v.length - 1);
    for (let i = 0; i < v.length; i++)
      matrix.set(i, i, v[i]);
    return matrix;
  }

  static lookAt(eye, center, up) {
    let z = eye.subtract(center).normalize();
    let x = up.cross(z).normalize();
    let y = z.cross(x).normalize();

    let m = Matrix.identity(4);
    m.setRow(0, ...repeat(x, 3));
    m.setRow(1, ...repeat(y, 3));
    m.setRow(2, ...repeat(z, 3));

    let t = Matrix.identity(4);
    t.setColumn(3, ...eye.negate());

    return m.multiply(t);
  }

  static frustum(left, right, bottom, top, znear, zfar) {
    let X = 2 * znear / (right - left);
    let Y = 2 * znear / (top - bottom);
    let A = (right + left) / (right - left);
    let B = (top + bottom) / (top - bottom);
    let C = -(zfar + znear) / (zfar - znear);
    let D = -2 * zfar * znear / (zfar - znear);

    return Matrix.create(
      [[ X, 0,  A, 0 ]
       [ 0, Y,  B, 0 ]
       [ 0, 0,  C, D ]
       [ 0, 0, -1, 0 ]]);
  }

  static perspective(fovy, aspect, znear, zfar) {
    let ymax = znear * Math.tan(fovy * Math.PI / 360.0);
    let ymin = -ymax;
    let xmin = ymin * aspect;
    let xmax = ymax * aspect;

    return Matrix.frustum(xmin, xmax, ymin, ymax, znear, zfar);
  };

  static ortho(left, right, bottom, top, znear, zfar) {
    let tx = -(right + left) / (right - left);
    let ty = -(top + bottom) / (top - bottom);
    let tz = -(zfar + znear) / (zfar - znear);

    return Matrix.create(
      [[ 2 / (right - left), 0, 0, 0 ]
      [ 0, 2 / (top - bottom), 0, 0 ]
      [ 0, 0, -2 / (zfar - znear), 0 ]
      [ tx, ty, tz, 1 ]]);
  };

  get size() { return [ this.columns, this.rows ]; }

  get elements() { return this.elements[Symbol.iterator]; }

  _index(i, j) { return (i + j * this.columns); }

  _indexWithCheck(i, j) {
    if (!rangeCheck(i, 0, this.rows - 1) ||
        !rangeCheck(j, 0, this.columns - 1))
      throw new Error(`[${ i },${ j }] is not a valid index in Matrix of size (${ this.size.join(",") })`);
    return this._index(i, j);
  }

  get(i, j) { return this.data[this._indexWithCheck(i, j)]; }

  set(i, j, v) { this.data[this._indexWithCheck(i, j)] = v; }

  * row(row) {
    if (!rangeCheck(row, 0, this.rows - 1))
      throw new Error(`Row ${ row } is not valid in Matrix of size (${ this.size.join(",") })`);
    for (let i = 0; i < this.columns; i++)
      yield this.data[this._index(i, row)];
  }

  * column(column) {
    if (!rangeCheck(column, 0, this.columns - 1))
      throw new Error(`Column ${ column } is not valid in Matrix of size (${ this.size.join(",") })`);
    for (let i = 0; i < this.rows; i++)
      yield this.data[this._index(column, i)];
  }

  setRow(row, ...v) {
    v = Vector.toVector(v, true);
    if (!rangeCheck(row, 0, this.rows - 1))
      throw new Error(`Row ${ row } is not valid in Matrix of size (${ this.size.join(",") })`);
    if (v.length > this.columns)
      throw new Error(`Can't put ${ v.length } values into a matrix with ${ this.columns } columns`);
    for (let i = 0; i < this.columns; i++)
      this.data[this._index(i, row)] = v[i];
  }

  setColumn(column, ...v) {
    v = Vector.toVector(v, true);
    if (!rangeCheck(column, 0, this.columns - 1))
      throw new Error(`Columns ${ column } is not valid in Matrix of size (${ this.size.join(",") })`);
    if (v.length > this.rows)
      throw new Error(`Can't put ${ v.length } values into a matrix with ${ this.rows } rows`);
    for (let i = 0; i < this.rows; i++)
      this.data[this._index(column, i)] = v[i];
  }

  clone() { return new Matrix(this.columns, this.rows, this.data.slice(0)); }

};
<commit_msg>Fix some Matrix stuff, rename .data to .elements<commit_after>let { type, rangeCheck, repeat } = require("../utility");
let Vector = require("./Vector");

let makeInvalidMatrixSizeError = function(m, what) {
  return new Error(`${ what } is not valid in Matrix of size (${ m.columns },${ m.rows })`)
};

module.exports = class Matrix {

  constructor(columns, rows, elements) {
    this.columns  = columns;
    this.rows     = rows;
    this.elements = elements;
  }

  static create(m) {
    let columns = null;
    let rows = 0;
    let elements = [ ];
    for (let row of m) {
      let rowLength = 0;
      for (let element of row) {
        if (typeof element != "number")
          throw new Error(`Expected number, got '${ type(element) }'`)
        elements.push(element);
        rowLength++;
      }
      if (columns == null) columns = rowLength;
      else if (rowLength != columns)
        throw new Error(`Row lengths don't match (${ rowLength } != ${ columns })`);
      rows++;
    }
    if ((rows < 1) || (columns < 1))
      throw new Error(`Invalid matrix dimensions (${ columns },${ rows })`);
    return new Matrix(columns, rows, elements);
  }

  static zero(columns, rows = columns) {
    if ((columns < 1) || (rows < 1))
      throw new Error(`Invalid matrix dimensions (${ columns },${ rows })`);
    let elements = new Array(columns * rows);
    return new Matrix(columns, rows, elements);
  }

  static identity(size) {
    let matrix = Matrix.zero(size);
    for (let i = 0; i < size; i++)
      matrix.set(i, i, 1);
    return matrix;
  }

  static translation(...v) {
    let matrix = Matrix.identity(v.length + 1);
    matrix.setColumn(matrix.rows - 1, v);
    return matrix;
  }

  static scale(...v) {
    let matrix = Matrix.identity(v.length + 1);
    for (let i = 0; i < v.length; i++)
      matrix.set(i, i, v[i]);
    return matrix;
  }

  static lookAt(eye, center, up) {
    let z = eye.subtract(center).normalize();
    let x = up.cross(z).normalize();
    let y = z.cross(x).normalize();

    let m = Matrix.identity(4);
    m.setRow(0, ...repeat(x, 3));
    m.setRow(1, ...repeat(y, 3));
    m.setRow(2, ...repeat(z, 3));

    let t = Matrix.identity(4);
    t.setColumn(3, ...eye.negate());

    return m.multiply(t);
  }

  static frustum(left, right, bottom, top, znear, zfar) {
    let X = 2 * znear / (right - left);
    let Y = 2 * znear / (top - bottom);
    let A = (right + left) / (right - left);
    let B = (top + bottom) / (top - bottom);
    let C = -(zfar + znear) / (zfar - znear);
    let D = -2 * zfar * znear / (zfar - znear);

    return Matrix.create(
      [[ X, 0,  A, 0 ],
       [ 0, Y,  B, 0 ],
       [ 0, 0,  C, D ],
       [ 0, 0, -1, 0 ]]);
  }

  static perspective(fovy, aspect, znear, zfar) {
    let ymax = znear * Math.tan(fovy * Math.PI / 360.0);
    let ymin = -ymax;
    let xmin = ymin * aspect;
    let xmax = ymax * aspect;

    return Matrix.frustum(xmin, xmax, ymin, ymax, znear, zfar);
  };

  static ortho(left, right, bottom, top, znear, zfar) {
    let tx = -(right + left) / (right - left);
    let ty = -(top + bottom) / (top - bottom);
    let tz = -(zfar + znear) / (zfar - znear);

    return Matrix.create(
      [[ 2 / (right - left), 0, 0, 0 ],
       [ 0, 2 / (top - bottom), 0, 0 ],
       [ 0, 0, -2 / (zfar - znear), 0 ],
       [ tx, ty, tz, 1 ]]);
  };

  get dimensions() { return [ this.columns, this.rows ]; }

  _index(i, j) { return (i + j * this.columns); }

  _indexWithCheck(i, j) {
    if (!rangeCheck(i, 0, this.rows - 1) ||
        !rangeCheck(j, 0, this.columns - 1))
      throw makeInvalidMatrixSizeError(this, `Index [${ i },${ j }]`);
    return this._index(i, j);
  }

  get(i, j) { return this.elements[this._indexWithCheck(i, j)]; }

  set(i, j, v) { this.elements[this._indexWithCheck(i, j)] = v; }

  * row(row) {
    if (!rangeCheck(row, 0, this.rows - 1))
      throw makeInvalidMatrixSizeError(this, `Row ${ row }`);
    for (let i = 0; i < this.columns; i++)
      yield this.elements[this._index(i, row)];
  }

  * column(column) {
    if (!rangeCheck(column, 0, this.columns - 1))
      throw makeInvalidMatrixSizeError(this, `Column ${ column }`);
    for (let i = 0; i < this.rows; i++)
      yield this.elements[this._index(column, i)];
  }

  setRow(row, ...v) {
    v = Vector.toVector(v, true);
    if (!rangeCheck(row, 0, this.rows - 1))
      throw makeInvalidMatrixSizeError(this, `Row ${ row }`);
    if (v.dimensions > this.columns)
      throw new Error(`Can't put ${ v.length } values into a matrix with ${ this.columns } columns`);
    for (let i = 0; i < this.columns; i++)
      this.elements[this._index(i, row)] = v[i];
  }

  setColumn(column, ...v) {
    v = Vector.toVector(v, true);
    if (!rangeCheck(column, 0, this.columns - 1))
      throw makeInvalidMatrixSizeError(this, `Column ${ column }`);
    if (v.dimensions > this.rows)
      throw new Error(`Can't put ${ v.length } values into a matrix with ${ this.rows } rows`);
    for (let i = 0; i < this.rows; i++)
      this.elements[this._index(column, i)] = v[i];
  }

  clone() { return new Matrix(this.columns, this.rows, this.elements.slice(0)); }

};
<|endoftext|>


<commit_before>let { type, rangeCheck,
      repeat, any, map, zip,
      aggregate, sum, join } = require("../utility");

let makeIncompatibleVectorsError = function(a, b, what) {
  return new Error(`Can't ${ what } two vectors of dimensions ${ a.dimensions } and ${ b.dimensions }`);
};

module.exports = class Vector {

  constructor(elements) {
    this.elements = elements;
  }

  static create(...elements) {
    if (elements.length < 2)
      throw new Error("Vector must have at least 2 dimensions");
    if (any(elements, e => (typeof e != "number")))
      throw new Error(`Attempting to create Vector with non-number elements ([${ join(map(elements, type), ", ") }])`)
    return new Vector(elements);
  }

  static zero(dimensions) {
    return Vector.create(...repeat(0, dimensions)); }

  static one(dimensions) {
    return Vector.create(...repeat(1, dimensions)); }

  static unit(dimensions, unitDim) {
    if (!rangeCheck(unitDim, 0, dimensions - 1))
      throw new Error("unitDim is out of range")
    let v = Vector.zero(dimensions);
    v.elements[unitDim] = 1;
    return v;
  }

  static toVector(obj, inspectArray = false) {
    if (obj instanceof Vector) return obj;
    if (obj instanceof Array) {
      if (obj.length == 1) {
        if (obj[0] instanceof Vector) return obj[0];
        if (obj[0] instanceof Array) return Vector.create(...obj[0]);
      }
      return Vector.create(...obj);
    }
    throw new Error(`Can't convert object of type ${ type(obj) } to Vector`);
  }

  get dimensions() { return this.elements.length; }

  get lengthSqr() { return sum(map(this, e => e * e)); }

  get length() { return Math.sqrt(this.lengthSqr); }

  get sum() { return aggregate(this, (a, b) => a + b); }

  get product() { return aggregate(this, (a, b) => a * b); }

  clone() { return new Vector(this.elements.slice(0)); }

  negate() { return Vector.create(...map(this, e => -e)); }

  normalize() {
    let l = this.length;
    return ((l == 0) ? Vector.zero(this.dimensions)
                     : Vector.create(...map(this, e => e / l)));
  }

  multiply(f) { return Vector.create(...map(this, e => e * f)); }

  add(...v) {
    v = Vector.toVector(v, true);
    if (this.dimensions != v.dimensions)
      throw makeIncompatibleVectorsError(this, v, "add");
    return Vector.create(...zip(this, v, (a, b) => a + b));
  }

  subtract(...v) {
    v = Vector.toVector(v, true);
    if (this.dimensions != v.dimensions)
      throw makeIncompatibleVectorsError(this, v, "subtract");
    return Vector.create(...zip(this, v, (a, b) => a - b));
  }

  dot(...v) {
    v = Vector.toVector(v, true);
    if (this.dimensions != v.dimensions)
      throw makeIncompatibleVectorsError(this, v, "dot");
    return sum(zip(this, v, (a, b) => a * b));
  }

  cross(...v) {
    v = Vector.toVector(v, true);
    if ((this.dimensions != 3) || (v.dimensions != 3))
      throw makeIncompatibleVectorsError(this, v, "cross");
    let [ x, y, z ] = this;
    let [ a, b, c ] = v;
    return Vector.create((y * c) - (z * b),
                         (z * a) - (x * c),
                         (x * b) - (y * a));
  }

  [Symbol.iterator]() { return this.elements[Symbol.iterator](); }

  toString() { return `[${ this.elements.join(", ") }]`; }

};
<commit_msg>Update Vector<commit_after>let { type, rangeCheck,
      repeat, any, map, zip,
      aggregate, sum, join } = require("../utility");

let makeIncompatibleVectorsError = function(a, b, what) {
  return new Error(`Can't ${ what } two vectors of dimensions ${ a.dimensions } and ${ b.dimensions }`);
};

module.exports = class Vector {

  constructor(elements) {
    this.elements = elements;
  }

  static create(...elements) {
    if (elements.length < 1)
      throw new Error("Vector must have at least 1 dimension");
    if (any(elements, e => (typeof e != "number")))
      throw new Error(`Attempting to create Vector with non-number elements ([${ join(map(elements, type), ", ") }])`)
    return new Vector(elements);
  }

  static zero(dimensions) {
    return Vector.create(...repeat(0, dimensions)); }

  static one(dimensions) {
    return Vector.create(...repeat(1, dimensions)); }

  static unit(dimensions, unitDim) {
    if (!rangeCheck(unitDim, 0, dimensions - 1))
      throw new Error("unitDim is out of range")
    let v = Vector.zero(dimensions);
    v.elements[unitDim] = 1;
    return v;
  }

  static toVector(obj, inspectArray = false) {
    if (obj instanceof Vector) return obj;
    if (obj instanceof Array) {
      if (obj.length == 1) {
        if (obj[0] instanceof Vector) return obj[0];
        if (obj[0] instanceof Array) return Vector.create(...obj[0]);
      }
      return Vector.create(...obj);
    }
    throw new Error(`Can't convert object of type ${ type(obj) } to Vector`);
  }

  get dimensions() { return this.elements.length; }

  get lengthSqr() { return sum(map(this, e => e * e)); }

  get length() { return Math.sqrt(this.lengthSqr); }

  get sum() { return aggregate(this, (a, b) => a + b); }

  get product() { return aggregate(this, (a, b) => a * b); }

  clone() { return new Vector(this.elements.slice(0)); }

  negate() { return Vector.create(...map(this, e => -e)); }

  normalize() {
    let l = this.length;
    return ((l == 0) ? Vector.zero(this.dimensions)
                     : Vector.create(...map(this, e => e / l)));
  }

  multiply(f) { return Vector.create(...map(this, e => e * f)); }

  add(...v) {
    v = Vector.toVector(v, true);
    if (this.dimensions != v.dimensions)
      throw makeIncompatibleVectorsError(this, v, "add");
    return Vector.create(...zip(this, v, (a, b) => a + b));
  }

  subtract(...v) {
    v = Vector.toVector(v, true);
    if (this.dimensions != v.dimensions)
      throw makeIncompatibleVectorsError(this, v, "subtract");
    return Vector.create(...zip(this, v, (a, b) => a - b));
  }

  dot(...v) {
    v = Vector.toVector(v, true);
    if (this.dimensions != v.dimensions)
      throw makeIncompatibleVectorsError(this, v, "dot");
    return sum(zip(this, v, (a, b) => a * b));
  }

  cross(...v) {
    v = Vector.toVector(v, true);
    if ((this.dimensions != 3) || (v.dimensions != 3))
      throw makeIncompatibleVectorsError(this, v, "cross");
    let [ x, y, z ] = this;
    let [ a, b, c ] = v;
    return Vector.create((y * c) - (z * b),
                         (z * a) - (x * c),
                         (x * b) - (y * a));
  }

  [Symbol.iterator]() { return this.elements[Symbol.iterator](); }

  toString() { return `[Vector(${ this.dimensions }) ${ this.elements.join(", ") } ]`; }

};
<|endoftext|>


<commit_before>'use babel';

const Promise = require('bluebird');
const readdir = Promise.promisify(require('fs').readdir);
const path = require('path');
const fuzzaldrin = require('fuzzaldrin');
const escapeRegExp = require('lodash.escaperegexp');
const get = require('lodash.get');
const findBabelConfig = require('find-babel-config');
const internalModules = require('./utils/internal-modules');

const LINE_REGEXP = /require|import|export\s+(?:\*|{[a-zA-Z0-9_$,\s]+})+\s+from|}\s*from\s*['"]/;
const SELECTOR = [
  '.source.js .string.quoted',

  // for babel-language plugin
  '.source.js .punctuation.definition.string.end',
  '.source.js .punctuation.definition.string.begin',

  '.source.ts .string.quoted',
  '.source.coffee .string.quoted'
];
const SELECTOR_DISABLE = [
  '.source.js .comment',
  '.source.js .keyword',
  '.source.ts .comment',
  '.source.ts .keyword'
];

class CompletionProvider {
  constructor() {
    this.selector = SELECTOR.join(', ');
    this.disableForSelector = SELECTOR_DISABLE.join(', ');
    this.inclusionPriority = 1;
  }

  getSuggestions({editor, bufferPosition, prefix}) {
    const line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]);
    if (!LINE_REGEXP.test(line)) {
      return [];
    }

    const realPrefix = this.getRealPrefix(prefix, line);
    if (!realPrefix) {
      return [];
    }

    if (realPrefix[0] === '.') {
      return this.lookupLocal(realPrefix, path.dirname(editor.getPath()));
    }

    const vendors = atom.config.get('autocomplete-modules.vendors');

    const promises = vendors.map(
      (vendor) => this.lookupGlobal(realPrefix, vendor)
    );

    const webpack = atom.config.get('autocomplete-modules.webpack');
    if (webpack) {
      promises.push(this.lookupWebpack(realPrefix));
    }

    const babelPluginModuleResolver = atom.config.get('autocomplete-modules.babelPluginModuleResolver');
    if (babelPluginModuleResolver) {
      promises.push(this.lookupbabelPluginModuleResolver(realPrefix));
    }

    return Promise.all(promises).then(
      (suggestions) => [].concat(...suggestions)
    );
  }

  getRealPrefix(prefix, line) {
    try {
      const realPrefixRegExp = new RegExp(`['"]((?:.+?)*${escapeRegExp(prefix)})`);
      const realPrefixMathes = realPrefixRegExp.exec(line);
      if (!realPrefixMathes) {
        return false;
      }

      return realPrefixMathes[1];
    } catch (e) {
      return false;
    }
  }

  filterSuggestions(prefix, suggestions) {
    return fuzzaldrin.filter(suggestions, prefix, {
      key: 'text'
    });
  }

  lookupLocal(prefix, dirname) {
    let filterPrefix = prefix.replace(path.dirname(prefix), '').replace('/', '');
    if (prefix[prefix.length - 1] === '/') {
      filterPrefix = '';
    }

    const includeExtension = atom.config.get('autocomplete-modules.includeExtension');
    let lookupDirname = path.resolve(dirname, prefix);
    if (filterPrefix) {
      lookupDirname = lookupDirname.replace(new RegExp(`${escapeRegExp(filterPrefix)}$`), '');
    }

    return readdir(lookupDirname).catch((e) => {
      if (e.code !== 'ENOENT') {
        throw e;
      }

      return [];
    }).filter(
      (filename) => filename[0] !== '.'
    ).map((pathname) => ({
      text: includeExtension ? pathname : this.normalizeLocal(pathname),
      displayText: pathname,
      type: 'import'
    })).then(
      (suggestions) => this.filterSuggestions(filterPrefix, suggestions)
    );
  }

  normalizeLocal(filename) {
    return filename.replace(/\.(js|es6|jsx|coffee|ts|tsx)$/, '');
  }

  lookupGlobal(prefix, vendor = 'node_modules') {
    const projectPath = atom.project.getPaths()[0];
    if (!projectPath) {
      return Promise.resolve([]);
    }

    const vendorPath = path.join(projectPath, vendor);
    if (prefix.indexOf('/') !== -1) {
      return this.lookupLocal(`./${prefix}`, vendorPath);
    }

    return readdir(vendorPath).catch((e) => {
      if (e.code !== 'ENOENT') {
        throw e;
      }

      return [];
    }).then(
      (libs) => [...internalModules, ...libs]
    ).map((lib) => ({
      text: lib,
      replacementPrefix: prefix,
      type: 'import'
    })).then(
      (suggestions) => this.filterSuggestions(prefix, suggestions)
    );
  }

  lookupWebpack(prefix) {
    const projectPath = atom.project.getPaths()[0];
    if (!projectPath) {
      return Promise.resolve([]);
    }

    const vendors = atom.config.get('autocomplete-modules.vendors');
    const webpackConfig = this.fetchWebpackConfig(projectPath);

    const webpackRoot = get(webpackConfig, 'resolve.root', '');
    let moduleSearchPaths = get(webpackConfig, 'resolve.modulesDirectories', []);
    moduleSearchPaths = moduleSearchPaths.filter(
      (item) => vendors.indexOf(item) === -1
    );

    return Promise.all(moduleSearchPaths.concat(webpackRoot).map(
      (searchPath) => this.lookupLocal(prefix, path.join(projectPath, searchPath))
    )).then(
      (suggestions) => [].concat(...suggestions)
    );
  }

  fetchWebpackConfig(rootPath) {
    const webpackConfigFilename = atom.config.get('autocomplete-modules.webpackConfigFilename');
    const webpackConfigPath = path.join(rootPath, webpackConfigFilename);

    try {
      return require(webpackConfigPath); // eslint-disable-line
    } catch (error) {
      return {};
    }
  }

  lookupbabelPluginModuleResolver(prefix) {
    const projectPath = atom.project.getPaths()[0];
    if (projectPath) {
      return findBabelConfig(projectPath).then(({config}) => {
        if (config && Array.isArray(config.plugins)) {
          // Grab the v1 (module-alias) or v2 (module-resolver) plugin configuration
          const pluginConfig = config.plugins.find(p => p[0] === 'module-alias' || p[0] === 'babel-plugin-module-alias') ||
            config.plugins.find(p => p[0] === 'module-resolver' || p[0] === 'babel-plugin-module-resolver');
          if (!pluginConfig) {
            return [];
          }

          // Only v2 of the plugin supports custom root directories
          let rootPromises = [];
          if (!Array.isArray(pluginConfig[1])) {
            const rootDirs = pluginConfig[1].root || [];
            rootPromises = rootPromises.concat(rootDirs.map(r => {
              const rootDirPath = path.join(projectPath, r);
              return this.lookupLocal(`./${prefix}`, rootDirPath);
            }));
          }

          // determine the right prefix for the alias config
          // `realPrefix` is the prefix we want to use to find the right file/suggestions
          // when the prefix is a sub module (eg. module/subfile),
          // `modulePrefix` will be "module", and `realPrefix` will be "subfile"
          const prefixSplit = prefix.split('/');
          const modulePrefix = prefixSplit[0];
          const realPrefix = prefixSplit.pop();
          const moduleSearchPath = prefixSplit.join('/');

          // get the alias configs for the specific module
          const aliasConfig = Array.isArray(pluginConfig[1])
            // v1 of the plugin is an array
            ? pluginConfig[1].filter(alias => alias.expose.startsWith(modulePrefix))
            // otherwise it's v2 (an object)
            : Object.keys(pluginConfig[1].alias || {})
              .filter(expose => expose.startsWith(modulePrefix))
              .map(exp => ({
                expose: exp,
                src: pluginConfig[1].alias[exp]
              }));

          return Promise.all(rootPromises.concat(aliasConfig.map(
            (alias) => {
              // The search path is the parent directory of the source directory specified in .babelrc
              // then we append the `moduleSearchPath` to get the real search path
              const searchPath = path.join(
                path.dirname(path.resolve(projectPath, alias.src)),
                moduleSearchPath
              );

              return this.lookupLocal(realPrefix, searchPath);
            }
          ))).then(
            (suggestions) => [].concat(...suggestions)
          ).then(suggestions => {
            // make sure the suggestions are from the compatible alias
            if (prefix === realPrefix && aliasConfig.length) {
              return suggestions.filter(sugg =>
                aliasConfig.find(a => a.expose === sugg.text)
              );
            }
            return suggestions;
          });
        }

        return [];
      });
    }
  }
}

module.exports = CompletionProvider;
<commit_msg>:sparkles: Webpack v2 support<commit_after>'use babel';

const Promise = require('bluebird');
const readdir = Promise.promisify(require('fs').readdir);
const path = require('path');
const fuzzaldrin = require('fuzzaldrin');
const escapeRegExp = require('lodash.escaperegexp');
const get = require('lodash.get');
const findBabelConfig = require('find-babel-config');
const internalModules = require('./utils/internal-modules');

const LINE_REGEXP = /require|import|export\s+(?:\*|{[a-zA-Z0-9_$,\s]+})+\s+from|}\s*from\s*['"]/;
const SELECTOR = [
  '.source.js .string.quoted',

  // for babel-language plugin
  '.source.js .punctuation.definition.string.end',
  '.source.js .punctuation.definition.string.begin',

  '.source.ts .string.quoted',
  '.source.coffee .string.quoted'
];
const SELECTOR_DISABLE = [
  '.source.js .comment',
  '.source.js .keyword',
  '.source.ts .comment',
  '.source.ts .keyword'
];

class CompletionProvider {
  constructor() {
    this.selector = SELECTOR.join(', ');
    this.disableForSelector = SELECTOR_DISABLE.join(', ');
    this.inclusionPriority = 1;
  }

  getSuggestions({editor, bufferPosition, prefix}) {
    const line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]);
    if (!LINE_REGEXP.test(line)) {
      return [];
    }

    const realPrefix = this.getRealPrefix(prefix, line);
    if (!realPrefix) {
      return [];
    }

    if (realPrefix[0] === '.') {
      return this.lookupLocal(realPrefix, path.dirname(editor.getPath()));
    }

    const vendors = atom.config.get('autocomplete-modules.vendors');

    const promises = vendors.map(
      (vendor) => this.lookupGlobal(realPrefix, vendor)
    );

    const webpack = atom.config.get('autocomplete-modules.webpack');
    if (webpack) {
      promises.push(this.lookupWebpack(realPrefix));
    }

    const babelPluginModuleResolver = atom.config.get('autocomplete-modules.babelPluginModuleResolver');
    if (babelPluginModuleResolver) {
      promises.push(this.lookupbabelPluginModuleResolver(realPrefix));
    }

    return Promise.all(promises).then(
      (suggestions) => [].concat(...suggestions)
    );
  }

  getRealPrefix(prefix, line) {
    try {
      const realPrefixRegExp = new RegExp(`['"]((?:.+?)*${escapeRegExp(prefix)})`);
      const realPrefixMathes = realPrefixRegExp.exec(line);
      if (!realPrefixMathes) {
        return false;
      }

      return realPrefixMathes[1];
    } catch (e) {
      return false;
    }
  }

  filterSuggestions(prefix, suggestions) {
    return fuzzaldrin.filter(suggestions, prefix, {
      key: 'text'
    });
  }

  lookupLocal(prefix, dirname) {
    let filterPrefix = prefix.replace(path.dirname(prefix), '').replace('/', '');
    if (prefix[prefix.length - 1] === '/') {
      filterPrefix = '';
    }

    const includeExtension = atom.config.get('autocomplete-modules.includeExtension');
    let lookupDirname = path.resolve(dirname, prefix);
    if (filterPrefix) {
      lookupDirname = lookupDirname.replace(new RegExp(`${escapeRegExp(filterPrefix)}$`), '');
    }

    return readdir(lookupDirname).catch((e) => {
      if (e.code !== 'ENOENT') {
        throw e;
      }

      return [];
    }).filter(
      (filename) => filename[0] !== '.'
    ).map((pathname) => ({
      text: includeExtension ? pathname : this.normalizeLocal(pathname),
      displayText: pathname,
      type: 'import'
    })).then(
      (suggestions) => this.filterSuggestions(filterPrefix, suggestions)
    );
  }

  normalizeLocal(filename) {
    return filename.replace(/\.(js|es6|jsx|coffee|ts|tsx)$/, '');
  }

  lookupGlobal(prefix, vendor = 'node_modules') {
    const projectPath = atom.project.getPaths()[0];
    if (!projectPath) {
      return Promise.resolve([]);
    }

    const vendorPath = path.join(projectPath, vendor);
    if (prefix.indexOf('/') !== -1) {
      return this.lookupLocal(`./${prefix}`, vendorPath);
    }

    return readdir(vendorPath).catch((e) => {
      if (e.code !== 'ENOENT') {
        throw e;
      }

      return [];
    }).then(
      (libs) => [...internalModules, ...libs]
    ).map((lib) => ({
      text: lib,
      replacementPrefix: prefix,
      type: 'import'
    })).then(
      (suggestions) => this.filterSuggestions(prefix, suggestions)
    );
  }

  lookupWebpack(prefix) {
    const projectPath = atom.project.getPaths()[0];
    if (!projectPath) {
      return Promise.resolve([]);
    }

    const vendors = atom.config.get('autocomplete-modules.vendors');
    const webpackConfig = this.fetchWebpackConfig(projectPath);

    // Webpack v2
    const webpackModules = get(webpackConfig, 'resolve.modules', []);

    // Webpack v1
    const webpackRoot = get(webpackConfig, 'resolve.root', '');
    let moduleSearchPaths = get(webpackConfig, 'resolve.modulesDirectories', webpackModules);
    moduleSearchPaths = moduleSearchPaths.filter(
      (item) => vendors.indexOf(item) === -1
    );

    return Promise.all(moduleSearchPaths.concat(webpackRoot).map(
      (searchPath) => this.lookupLocal(
        prefix,
        path.isAbsolute(searchPath) ? searchPath : path.join(projectPath, searchPath)
      )
    )).then(
      (suggestions) => [].concat(...suggestions)
    );
  }

  fetchWebpackConfig(rootPath) {
    const webpackConfigFilename = atom.config.get('autocomplete-modules.webpackConfigFilename');
    const webpackConfigPath = path.join(rootPath, webpackConfigFilename);

    try {
      return require(webpackConfigPath); // eslint-disable-line
    } catch (error) {
      return {};
    }
  }

  lookupbabelPluginModuleResolver(prefix) {
    const projectPath = atom.project.getPaths()[0];
    if (projectPath) {
      return findBabelConfig(projectPath).then(({config}) => {
        if (config && Array.isArray(config.plugins)) {
          // Grab the v1 (module-alias) or v2 (module-resolver) plugin configuration
          const pluginConfig = config.plugins.find(p => p[0] === 'module-alias' || p[0] === 'babel-plugin-module-alias') ||
            config.plugins.find(p => p[0] === 'module-resolver' || p[0] === 'babel-plugin-module-resolver');
          if (!pluginConfig) {
            return [];
          }

          // Only v2 of the plugin supports custom root directories
          let rootPromises = [];
          if (!Array.isArray(pluginConfig[1])) {
            const rootDirs = pluginConfig[1].root || [];
            rootPromises = rootPromises.concat(rootDirs.map(r => {
              const rootDirPath = path.join(projectPath, r);
              return this.lookupLocal(`./${prefix}`, rootDirPath);
            }));
          }

          // determine the right prefix for the alias config
          // `realPrefix` is the prefix we want to use to find the right file/suggestions
          // when the prefix is a sub module (eg. module/subfile),
          // `modulePrefix` will be "module", and `realPrefix` will be "subfile"
          const prefixSplit = prefix.split('/');
          const modulePrefix = prefixSplit[0];
          const realPrefix = prefixSplit.pop();
          const moduleSearchPath = prefixSplit.join('/');

          // get the alias configs for the specific module
          const aliasConfig = Array.isArray(pluginConfig[1])
            // v1 of the plugin is an array
            ? pluginConfig[1].filter(alias => alias.expose.startsWith(modulePrefix))
            // otherwise it's v2 (an object)
            : Object.keys(pluginConfig[1].alias || {})
              .filter(expose => expose.startsWith(modulePrefix))
              .map(exp => ({
                expose: exp,
                src: pluginConfig[1].alias[exp]
              }));

          return Promise.all(rootPromises.concat(aliasConfig.map(
            (alias) => {
              // The search path is the parent directory of the source directory specified in .babelrc
              // then we append the `moduleSearchPath` to get the real search path
              const searchPath = path.join(
                path.dirname(path.resolve(projectPath, alias.src)),
                moduleSearchPath
              );

              return this.lookupLocal(realPrefix, searchPath);
            }
          ))).then(
            (suggestions) => [].concat(...suggestions)
          ).then(suggestions => {
            // make sure the suggestions are from the compatible alias
            if (prefix === realPrefix && aliasConfig.length) {
              return suggestions.filter(sugg =>
                aliasConfig.find(a => a.expose === sugg.text)
              );
            }
            return suggestions;
          });
        }

        return [];
      });
    }
  }
}

module.exports = CompletionProvider;
<|endoftext|>


<commit_before>
class Path {
  constructor(path) {
    this.path = path || [];
  }
  move() {
    return this;
  }
  moveTo() {
    return this;
  }
  line() {
    return this;
  }
  close() {
    return this;
  }
  toJSON() {
    return JSON.stringify(this.path);
  }
}

module.exports = Path;
<commit_msg>Add other Path methods to ART Path mock<commit_after>
class Path {
  constructor(path) {
    [
      'push',
      'reset',
      'move',
      'moveTo',
      'line',
      'lineTo',
      'curve',
      'curveTo',
      'arc',
      'arcTo',
      'counterArc',
      'counterArcTo',
      'close'
    ].forEach((methodName) => { this[methodName] = () => this });

    this.path = path || [];
  }

  toJSON() {
    return JSON.stringify(this.path);
  }
}

module.exports = Path;
<|endoftext|>


<commit_before>// dependencies
//
import React from 'react';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';
import Label from './Label';

/**
 * The Dropdown class
 */
class Dropdown extends React.Component {
    constructor(props) {
        super(props);

        // build a list of permitted values from the options values
        //
        this.permittedValues = props.options.map((opt) => opt.value);

        // generate a unique ID for this component
        //
        this.id = uniqueId('Dropdown-');

        // initialize the validation message from the custom message provided
        // (if any) or generate the default message
        //
        this.validationMessage = props.validationMessage
            || `${props.description || 'This value'} is required`;

        // validate the initial value & set the initial state
        //
        this.state = this.validate(props.value);

        // set the `hasValidated` state to its initial value
        //
        this.state.hasValidated = false;

        // bind `this` to the onEvent method
        //
        this.onEvent = this.onEvent.bind(this);
    }

    /**
     * Handle the initial mounting of the component
     *
     * This method ensures that `onValidation` is called once when the component
     * is first initialized. This allows the component to inform its parent of
     * the initial validation state.
     */
    componentWillMount() {
        // do we have an `onValidation` handler?
        //
        if (this.props.onValidation) {
            // call the `onValidation` handler
            //
            this.props.onValidation(
                this.state.hasValidated,
                this.state.isValid,
                this.state.validationMessage
            );
        }
    }

    /**
     * Handle changes to the component properties
     * @param  {Object} newProps The new properties for the object
     */
    componentWillReceiveProps(newProps) {
        // save the current value for later use
        //
        const currentValue = this.state.value;

        // build the new state by validating the new value property
        //
        const newState = this.validate(newProps.value);

        // ensure the `hasValidated` state is preserved
        //
        newState.hasValidated = this.state.hasValidated;

        // set the new state
        //
        this.setState(newState);

        // do we have an onValidation handler? has the value changed? if so,
        // call the handler with the new validation state
        //
        if (this.props.onValidation && currentValue !== newState.value) {
            this.props.onValidation(
                newState.hasValidated,
                newState.isValid,
                newState.validationMessage
            );
        }

        // do we have an onChange handler? has the value changed? if so, call
        // the handler with the new value
        //
        if (this.props.onChange && currentValue !== newState.value) {
            this.props.onChange(newState.value);
        }
    }

    /**
     * Handle events from the `select` element
     * @param  {Object} event The event object
     */
    onEvent(event) {
        // get the current value of the component
        //
        const currentValue = this.state.value;

        // get the new state of the component based on the new value from the
        // select element
        //
        const newState = this.validate(event.target.value);

        // set the new state
        //
        this.setState(() => newState);

        // do we have an `onChange` handler? do we have a new value? if so,
        // call the `onChange` handler with the new value
        //
        if (this.props.onChange && newState.value !== currentValue) {
            this.props.onChange(newState.value);
        }

        // do we have an `onValidation` handler? if so, call it with the new
        // validation state
        //
        if (this.props.onValidation) {
            this.props.onValidation(
                newState.hasValidated,
                newState.isValid,
                newState.validationMessage
            );
        }
    }

    /**
     * Validate a value for the component
     * @param  {String} option The value to validate
     * @return {Object}        The new state of the component, including the
     *                         value
     */
    validate(option) {
        // make sure the value is cast to a string
        //
        let value = `${option || ''}`;

        // determine if the value is in the list of permitted values
        //
        const inValues = this.permittedValues.find((val) => val === value);

        // if the value is not in the list of values, set it to the `null` value
        //
        if (!inValues) {
            value = '';
        }

        // determine if the value is valid, based on the `required` flag
        //
        const isValid = !this.props.required || !!value;

        // return the new state
        //
        return {
            value,
            hasValidated:      true,
            isValid,
            validationMessage: isValid ? null : this.validationMessage,
        };
    }

    /**
     * Render the component
     * @return {React.Element} The React Element describing this component
     */
    render() {

        const divClasses = classnames('form-group', {
            'has-error': this.state.hasValidated && !this.state.isValid,
        });

        return (

                {this.props.label
                    ?
                    : ''
                }
                <select
                    id={this.id}
                    className="form-control"
                    onChange={this.onEvent}
                    onBlur={this.onEvent}
                >
                    {this.props.includeNull
                        ? <option key={uniqueId('Dropdown-')} value="">
                            {this.props.nullName || 'Please select one'}
                        </option>
                        : ''
                    }
                    {this.props.options.map((opt) =>
                        <option key={uniqueId('Dropdown-')} value={opt.value}>{opt.name}</option>)
                    }
                </select>

                {this.state.hasValidated && !this.state.isValid
                    ? {this.state.validationMessage}
                    : ''
                }

        );
    }
}

// set the property types for the Dropdown component
//
Dropdown.propTypes = {
    label:             React.PropTypes.string,
    description:       React.PropTypes.string,
    includeNull:       React.PropTypes.bool,
    nullName:          React.PropTypes.string,
    required:          React.PropTypes.bool,
    validationMessage: React.PropTypes.string,
    value:             React.PropTypes.string,
    options:           React.PropTypes.array.isRequired,
    onValidation:      React.PropTypes.func,
    onChange:          React.PropTypes.func,
};

// export the component
//
export default Dropdown;
<commit_msg>added label classes to dropdown render method<commit_after>// dependencies
//
import React from 'react';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';
import Label from './Label';

/**
 * The Dropdown class
 */
class Dropdown extends React.Component {
    constructor(props) {
        super(props);

        // build a list of permitted values from the options values
        //
        this.permittedValues = props.options.map((opt) => opt.value);

        // generate a unique ID for this component
        //
        this.id = uniqueId('Dropdown-');

        // initialize the validation message from the custom message provided
        // (if any) or generate the default message
        //
        this.validationMessage = props.validationMessage
            || `${props.description || 'This value'} is required`;

        // validate the initial value & set the initial state
        //
        this.state = this.validate(props.value);

        // set the `hasValidated` state to its initial value
        //
        this.state.hasValidated = false;

        // bind `this` to the onEvent method
        //
        this.onEvent = this.onEvent.bind(this);
    }

    /**
     * Handle the initial mounting of the component
     *
     * This method ensures that `onValidation` is called once when the component
     * is first initialized. This allows the component to inform its parent of
     * the initial validation state.
     */
    componentWillMount() {
        // do we have an `onValidation` handler?
        //
        if (this.props.onValidation) {
            // call the `onValidation` handler
            //
            this.props.onValidation(
                this.state.hasValidated,
                this.state.isValid,
                this.state.validationMessage
            );
        }
    }

    /**
     * Handle changes to the component properties
     * @param  {Object} newProps The new properties for the object
     */
    componentWillReceiveProps(newProps) {
        // save the current value for later use
        //
        const currentValue = this.state.value;

        // build the new state by validating the new value property
        //
        const newState = this.validate(newProps.value);

        // ensure the `hasValidated` state is preserved
        //
        newState.hasValidated = this.state.hasValidated;

        // set the new state
        //
        this.setState(newState);

        // do we have an onValidation handler? has the value changed? if so,
        // call the handler with the new validation state
        //
        if (this.props.onValidation && currentValue !== newState.value) {
            this.props.onValidation(
                newState.hasValidated,
                newState.isValid,
                newState.validationMessage
            );
        }

        // do we have an onChange handler? has the value changed? if so, call
        // the handler with the new value
        //
        if (this.props.onChange && currentValue !== newState.value) {
            this.props.onChange(newState.value);
        }
    }

    /**
     * Handle events from the `select` element
     * @param  {Object} event The event object
     */
    onEvent(event) {
        // get the current value of the component
        //
        const currentValue = this.state.value;

        // get the new state of the component based on the new value from the
        // select element
        //
        const newState = this.validate(event.target.value);

        // set the new state
        //
        this.setState(() => newState);

        // do we have an `onChange` handler? do we have a new value? if so,
        // call the `onChange` handler with the new value
        //
        if (this.props.onChange && newState.value !== currentValue) {
            this.props.onChange(newState.value);
        }

        // do we have an `onValidation` handler? if so, call it with the new
        // validation state
        //
        if (this.props.onValidation) {
            this.props.onValidation(
                newState.hasValidated,
                newState.isValid,
                newState.validationMessage
            );
        }
    }

    /**
     * Validate a value for the component
     * @param  {String} option The value to validate
     * @return {Object}        The new state of the component, including the
     *                         value
     */
    validate(option) {
        // make sure the value is cast to a string
        //
        let value = `${option || ''}`;

        // determine if the value is in the list of permitted values
        //
        const inValues = this.permittedValues.find((val) => val === value);

        // if the value is not in the list of values, set it to the `null` value
        //
        if (!inValues) {
            value = '';
        }

        // determine if the value is valid, based on the `required` flag
        //
        const isValid = !this.props.required || !!value;

        // return the new state
        //
        return {
            value,
            hasValidated:      true,
            isValid,
            validationMessage: isValid ? null : this.validationMessage,
        };
    }

    /**
     * Render the component
     * @return {React.Element} The React Element describing this component
     */
    render() {

        const divClasses = classnames('form-group', {
            'has-error': this.state.hasValidated && !this.state.isValid,
        });

        const labelClasses = this.props.labelColumns
            ? classnames([
                this.props.labelColumns.xs ? `col-xs-${this.props.labelColumns.xs}` : null,
                this.props.labelColumns.sm ? `col-sm-${this.props.labelColumns.sm}` : null,
                this.props.labelColumns.md ? `col-md-${this.props.labelColumns.md}` : null,
                this.props.labelColumns.lg ? `col-lg-${this.props.labelColumns.lg}` : null,
            ])
            : null;

        return (

                {this.props.label
                    ?
                    : ''
                }
                <select
                    id={this.id}
                    className="form-control"
                    onChange={this.onEvent}
                    onBlur={this.onEvent}
                >
                    {this.props.includeNull
                        ? <option key={uniqueId('Dropdown-')} value="">
                            {this.props.nullName || 'Please select one'}
                        </option>
                        : ''
                    }
                    {this.props.options.map((opt) =>
                        <option key={uniqueId('Dropdown-')} value={opt.value}>{opt.name}</option>)
                    }
                </select>

                {this.state.hasValidated && !this.state.isValid
                    ? {this.state.validationMessage}
                    : ''
                }

        );
    }
}

// set the property types for the Dropdown component
//
Dropdown.propTypes = {
    label:             React.PropTypes.string,
    description:       React.PropTypes.string,
    includeNull:       React.PropTypes.bool,
    nullName:          React.PropTypes.string,
    required:          React.PropTypes.bool,
    validationMessage: React.PropTypes.string,
    value:             React.PropTypes.string,
    options:           React.PropTypes.array.isRequired,
    onValidation:      React.PropTypes.func,
    onChange:          React.PropTypes.func,
};

// export the component
//
export default Dropdown;
<|endoftext|>


<commit_before>let Preprocessor = require('./Preprocessor');
let Verify = require('../Verify');

class FastSass extends Preprocessor {
    name() {
        return ['fastSass', 'standaloneSass'];
    }

    register(src, output, pluginOptions = {}) {
        Verify.exists(src);

        return this.preprocess('fastSass', src, output, pluginOptions);
    }

    webpackPlugins() {
        let FastSassPlugin = require('../plugins/FastSassPlugin');

        return super.webpackPlugins().concat(new FastSassPlugin(this.details));
    }
}

module.exports = FastSass;
<commit_msg>Fix plugin path<commit_after>let Preprocessor = require('./Preprocessor');
let Verify = require('../Verify');

class FastSass extends Preprocessor {
    name() {
        return ['fastSass', 'standaloneSass'];
    }

    register(src, output, pluginOptions = {}) {
        Verify.exists(src);

        return this.preprocess('fastSass', src, output, pluginOptions);
    }

    webpackPlugins() {
        let FastSassPlugin = require('../webpackPlugins/FastSassPlugin');

        return super.webpackPlugins().concat(new FastSassPlugin(this.details));
    }
}

module.exports = FastSass;
<|endoftext|>


<commit_before>import React from 'react';
import '../styles/games.css';

export default class GameList extends React.Component {
    constructor(props) {
        super(props);

        this.state = {games: []};
    }
    componentDidMount() {
        let games = [];
        this.props.games.forEach(game => {
            games.push(
{game.title}
);
        });
        this.setState({games: games});
    }

    render() {
        return (
            {this.props.games.length > 0 ?
{this.state.games}
 :
No games found.
}
        );
    }
}
<commit_msg>Fixed games list.<commit_after>import React from 'react';
import '../styles/games.css';

export default class GameList extends React.Component {
    constructor(props) {
        super(props);

        this.state = {games: []};
    }

    componentWillReceiveProps(nextProps) {
        let games = [];
        nextProps.games.forEach(game => {
            games.push(
{game.title}
);
        });
        this.setState({games: games});
    }

    render() {
        if (this.props.games.length > 0) {
            return (

{this.state.games}

            );
        } else {
            return (

No games found.

            );
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

var React = require('react/addons');
var FormWidget = require('./FormWidget');
var FormGroup = require('./FormGroup');
var TYPES = require('../formWidgetTypes');
var FormBuilder = require('./FormBuilder');
// var UnipolarSlider = require('./UnipolarSlider');
// var BipolarSlider = require('./BipolarSlider');

//var Actions = require('actions/xxx')

require('styles/HomePage.less');

var forms = [{
  name: 'sex',
  question: 'What is your sex?',
  type: TYPES.CHOICE,
  choices: ['Male', 'Female']
}, {
  name: 'age',
  question: 'What is your age?',
  type: TYPES.NUMBER,
  min: 0,
  max: 120
}, {
  name: 'musical',
  question: 'Are you a trained musician?',
  type: TYPES.BOOLEAN
}, {
  name: 'color',
  question: 'Favorite color?',
  type: TYPES.SELECT,
  choices: ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
}, {
  name: 'joke',
  question: 'Whats your favorite joke?',
  type: TYPES.TEXT
}, {
  name: 'longjoke',
  question: 'Whats your favorite longjoke?',
  type: TYPES.TEXTBOX
}, {
  name: 'todo',
  question: 'Whats on your TODO list?',
  type: TYPES.LIST
}, {
  name: 'happiness',
  question: 'How happy are you feeling?',
  type: TYPES.UNIPOLAR,
  dimension: 'happy'
}, {
  name: 'valence',
  question: 'What is the general mood?',
  type: TYPES.BIPOLAR,
  dimension1: 'negative',
  dimension2: 'positive'
}];

var HomePage = React.createClass({

  onUpdate(value) {
    if (value === null) {
      this.replaceState({type: null});
    }
    else {
      this.setState(value);
    }
  },

  getInitialState() {
    return {
      type: null
    };
  },

  render() {
    return (

Content for HomePage

          <FormGroup forms={forms} />
          <FormBuilder onUpdate={(v) => console.log(v)}/>

      );
  }
});

module.exports = HomePage;

<commit_msg>create home page<commit_after>'use strict';

var _ = require('lodash');
var React = require('react/addons');
var ReactFireMixin = require('reactfire');
var Firebase = require('firebase');
var Bootstrap = require('react-bootstrap');
var ButtonGroup = Bootstrap.ButtonGroup;
var Panel = Bootstrap.Panel;
var RouterBootstrap = require('react-router-bootstrap');
var ButtonLink = RouterBootstrap.ButtonLink;

var FIREBASE_URL = 'https://popping-torch-2685.firebaseio.com/';
//var Actions = require('actions/xxx')

require('styles/HomePage.less');

var HomePage = React.createClass({
  mixins: [ReactFireMixin],

  componentWillMount: function() {
    this.bindAsObject(new Firebase(FIREBASE_URL).child('experiments'), 'experiments');
  },

  getInitialState() {
    return {
      experiments: {}
    };
  },

  render() {
    return (

          {
            _.keys(this.state.experiments).map((experiment, i) =>
              <Panel key={i} header={experiment}>
              <ButtonGroup>
                <ButtonLink to={`/experiment/${experiment}`}>View</ButtonLink>
                <ButtonLink to={`/edit/${experiment}`}>Edit</ButtonLink>
                <ButtonLink to={`/results/${experiment}`}>Results</ButtonLink>
              </ButtonGroup>
              </Panel>
            )
          }
          <ButtonLink to='new'>New Experiment</ButtonLink>

      );
  }
});

module.exports = HomePage;

<|endoftext|>


<commit_before>function runTestFile(path) {
  var response;
  var exec = require('child_process').exec;
  exec('mocha', function (error, stdout, stderr) {
    console.log("Stdout: "+stdout);
    console.log("Error: "+error);
    console.log("Stderr: "+stderr);
    response = stdout;
  });
  return response;
}

exports.runTestFile = runTestFile;
<commit_msg>Add unlink for the test file<commit_after>var fs = require('fs');
function runTestFile(path) {
  var response;
  var exec = require('child_process').exec;
  var options = {cwd: true}
  exec('mocha test.js', options, function (error, stdout, stderr) {
    console.log("Stdout: "+stdout);
    console.log("Error: "+error);
    console.log("Stderr: "+stderr);
    response = stdout;
    fs.unlink('./test.js',function(err) {
    });
  });
  return response;
}

exports.runTestFile = runTestFile;
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import SideNav from './SideNav.js'
import { Cookies } from 'react-cookie'

class HomeUser extends Component {
  constructor() {
    super()

  }

  componentWillMount() {
    let cookie = new Cookies()
    let user_id = cookie.get('id')
    fetch(`http://localhost:3000/alternatives/${user_id}`, {
      method: 'GET'
    })
    .then(res => {
      return res.text().then((alts) => {
        alts = JSON.parse(alts)
        console.log(alts)
      })
    })
    }

  render() {
    return (

        <SideNav />

Welcome

    )
  }
}

export default HomeUser
<commit_msg>fetch to alternatives made<commit_after>import React, {Component} from 'react'
import SideNav from './SideNav.js'
import { Cookies } from 'react-cookie'

class HomeUser extends Component {
  constructor() {
    super()
    this.state = {alt_ideas: ''}
  }

  componentWillMount() {
    let cookie = new Cookies()
    let user_id = cookie.get('id')

    fetch(`http://localhost:3000/v1/alternatives/${user_id}`)
    .then(res => {
      return res.json().then((alts) => {
        let alt_ideas = alts.map((alt) => {
          return (
{alt.text}
)
        })
        this.setState({alt_ideas: alt_ideas})
      })
    })
    }

  render() {
    return (

        <SideNav />

Welcome

            {this.state.alt_ideas}

    )
  }
}

export default HomeUser
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Text, Image, View, TouchableWithoutFeedback, LayoutAnimation }  from 'react-native'
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import * as actions from '../actions';

import timeDifference from './helpers';

import { CardSection, Card, Button } from './common';

/* Use ComponentWillMount LayourAnimation for transition */
/*Refactor to use Touchable opacity instead of touchable without feedback */
class ListItem extends Component {
  goToSelectedItemPage(data) {
    console.log(data,' being passed')
    Actions.selectedItem(data);
  }
  render() {
    const { titleStyle } = styles;
    const { url, id, author, thumbnail, title, ups, num_comments, domain, created_utc, downs, subreddit_name_prefixed } = this.props.item.data;
    const { data } = this.props.item;
    const {
      thumbnailStyle,
      headerContentStyle,
      thumbnailContainerStyle,
      headerTextStyle,
      imageStyle,
      articleDetails
    } = styles;
    return (
    <TouchableWithoutFeedback
      onPress={() => this.goToSelectedItemPage(data)}
    >
      <View>
      <Card>
      <CardSection>
        <Image
          source={{ uri: url }}
          style={ imageStyle }
        />
      </CardSection>
        <CardSection>
          <View style={headerContentStyle}>
            <Text
              numberOfLines={2}
              style={ headerTextStyle }>{ title }
            </Text>
            <Text style={{fontSize: 10}}>{'(' + domain + ')'}</Text>
          </View>
        </CardSection>
        <CardSection>
          <View>
            <Text style={{fontSize: 12}}> Submitted by {author} {timeDifference(created_utc)} to {subreddit_name_prefixed}</Text>
          </View>
        </CardSection>
        <CardSection>
            <Text style={ articleDetails }> Upvotes: { ups.toLocaleString() } |</Text>
            <Text style={ articleDetails }> Downvotes: { downs.toLocaleString() } |</Text>
            <Text style={ articleDetails }> Comments: {num_comments.toLocaleString()}</Text>
        </CardSection>
      </Card>
    </View>
    </TouchableWithoutFeedback>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  const selected = state.selectedItemId === ownProps.item.data.id
  // return { selectedItemId: state.selectedItemId };
  return { selected }
};

export default connect(mapStateToProps, actions)(ListItem);

const styles = {
  titleStyle: {
    fontSize: 18,
    paddingLeft: 15
  },
  headerContentStyle: {
    flexDirection: 'column',
    justifyContent: 'space-around',
    flex: 1
  },
  headerTextStyle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  thumbnailStyle: {
    height: 50,
    width: 50
  },
  thumbnailContainerStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 10,
    marginRight: 10
  },
  imageStyle: {
    height: 200,
    flex: 1,
    width: null
  },
  articleDetails: {
    fontSize: 10
  }
}
<commit_msg>[update] - add url for image<commit_after>import React, { Component } from 'react';
import { Text, Image, View, TouchableWithoutFeedback, LayoutAnimation }  from 'react-native'
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import * as actions from '../actions';

import timeDifference from './helpers';

import { CardSection, Card, Button } from './common';

/* Use ComponentWillMount LayourAnimation for transition */
/*Refactor to use Touchable opacity instead of touchable without feedback */
class ListItem extends Component {
  goToSelectedItemPage(data) {
    Actions.selectedItem(data);
  }
  render() {
    const { titleStyle } = styles;
    const { url, id, author, thumbnail, title, ups, num_comments, domain, created_utc, downs, subreddit_name_prefixed } = this.props.item.data;
    const { data } = this.props.item;
    const {
      thumbnailStyle,
      headerContentStyle,
      thumbnailContainerStyle,
      headerTextStyle,
      imageStyle,
      articleDetails
    } = styles;
    return (
    <TouchableWithoutFeedback
      onPress={() => this.goToSelectedItemPage(data)}
    >
      <View>
      <Card>
      <CardSection>
        <Image
          source={{ uri: url }}
          style={ imageStyle }
        />
      </CardSection>
        <CardSection>
          <View style={headerContentStyle}>
            <Text
              numberOfLines={2}
              style={ headerTextStyle }>{ title }
            </Text>
            <Text style={{fontSize: 10}}>{'(' + domain + ')'}</Text>
          </View>
        </CardSection>
        <CardSection>
          <View>
            <Text style={{fontSize: 12}}> Submitted by {author} {timeDifference(created_utc)} to {subreddit_name_prefixed}</Text>
          </View>
        </CardSection>
        <CardSection>
            <Text style={ articleDetails }> Upvotes: { ups.toLocaleString() } |</Text>
            <Text style={ articleDetails }> Downvotes: { downs.toLocaleString() } |</Text>
            <Text style={ articleDetails }> Comments: {num_comments.toLocaleString()}</Text>
        </CardSection>
      </Card>
    </View>
    </TouchableWithoutFeedback>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  const selected = state.selectedItemId === ownProps.item.data.id
  // return { selectedItemId: state.selectedItemId };
  return { selected }
};

export default connect(mapStateToProps, actions)(ListItem);

const styles = {
  titleStyle: {
    fontSize: 18,
    paddingLeft: 15
  },
  headerContentStyle: {
    flexDirection: 'column',
    justifyContent: 'space-around',
    flex: 1
  },
  headerTextStyle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  thumbnailStyle: {
    height: 50,
    width: 50
  },
  thumbnailContainerStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 10,
    marginRight: 10
  },
  imageStyle: {
    height: 200,
    flex: 1,
    width: null
  },
  articleDetails: {
    fontSize: 10
  }
}
<|endoftext|>


<commit_before>var sfa = sfa || {};

sfa.homePage = {
    init: function () {
        this.startButton();
        this.toggleRadios();
    },
    startButton: function () {
        var that = this;
        $('#submit-button').on('click touchstart', function (e) {
            var isYesClicked = $('#have-everything').prop('checked'),
                errorShown = $('body').data('shownError') || false;
            if (!isYesClicked && !errorShown) {
                e.preventDefault();
                that.showError();
            }
        });
    },
    showError: function() {
        $('.error-message').removeClass("js-hidden").attr("aria-hidden");
        $('#what-you-need-form').addClass("error");
        $('body').data('shownError', true);
    },
    toggleRadios: function () {
        var radios = $('input[type=radio][name=everything-you-need]');
        radios.on('change', function () {

            radios.each(function () {
                if ($(this).prop('checked')) {
                    var target = $(this).parent().data("target");
                    $("#" + target).removeClass("js-hidden").attr("aria-hidden");
                } else {
                    var target = $(this).parent().data("target");
                    $("#" + target).addClass("js-hidden").attr("aria-hidden", "true");
                }
            });

        });
    }
}

sfa.backLink = {
    init: function () {
        var backLink = $('<a>')
            .attr({ 'href': '#', 'class': 'link-back' })
            .text('Back')
            .on('click', function () {  window.history.back(); })
            .appendTo('#js-breadcrumbs');
    }
}

sfa.forms = {
    init: function () {
        this.preventDoubleSubmit();
    },
    preventDoubleSubmit: function () {
        var forms = $('form').not('.has-client-side-validation');
        forms.on('submit', function (e) {
            var button = $(this).find('.button');
            button.attr('disabled', 'disabled');
            setTimeout(function () {
                button.removeAttr('disabled');
            }, 5000);
        });
    }
}

sfa.navigation = {
    elems: {
        userNav: $('nav#user-nav > ul'),
        levyNav: $('ul#global-nav-links')
    },
    init: function () {
        this.setupMenus(this.elems.userNav);
        this.setupEvents(this.elems.userNav);
        this.linkSettings();
    },
    setupMenus: function (menu) {
        menu.find('ul').addClass("js-hidden").attr("aria-hidden", "true");
    },
    setupEvents: function (menu) {
        var that = this;
        menu.find('li.has-sub-menu > a').on('click', function (e) {
            var $that = $(this);
            that.toggleMenu($that, $that.next('ul'));
            e.stopPropagation();
            e.preventDefault();
        });
    },
    toggleMenu: function (link, subMenu) {
        var $li = link.parent();
        if ($li.hasClass("open")) {
            // Close menu
            $li.removeClass("open");
            subMenu.addClass("js-hidden").attr("aria-hidden", "true");
        } else {
            // Open menu
            this.closeAllOpenMenus();
            $li.addClass("open");
            subMenu.removeClass("js-hidden").attr("aria-hidden", "false");
        }
    },
    closeAllOpenMenus: function () {
        this.elems.userNav.find('li.has-sub-menu.open').removeClass('open').find('ul').addClass("js-hidden").attr("aria-hidden", "true");
        this.elems.levyNav.find('li.open').removeClass('open').addClass("js-hidden").attr("aria-hidden", "true");
    },
    linkSettings: function () {
        var $settingsLink = $('a#link-settings'),
            that = this;
        this.toggleUserMenu();
        $settingsLink.attr("aria-hidden", "false");
        $settingsLink.on('click touchstart', function (e) {
            var target = $(this).attr('href');
            $(this).toggleClass('open');
            that.toggleUserMenu();
            e.preventDefault();
        });
    },
    toggleUserMenu: function () {
        var $userNavParent = this.elems.userNav.parent();
        if ($userNavParent.hasClass("close")) {
            //open it
            $userNavParent.removeClass("close").attr("aria-hidden", "false");
        } else {
            // close it
            $userNavParent.addClass("close").attr("aria-hidden", "true");
        }
    }
}

if ($('#js-breadcrumbs')) {
    sfa.backLink.init();
}

sfa.navigation.init();
sfa.forms.init();

var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']");<commit_msg>Adjusted the time-out duration when disabling buttons on form submit<commit_after>var sfa = sfa || {};

sfa.homePage = {
    init: function () {
        this.startButton();
        this.toggleRadios();
    },
    startButton: function () {
        var that = this;
        $('#submit-button').on('click touchstart', function (e) {
            var isYesClicked = $('#have-everything').prop('checked'),
                errorShown = $('body').data('shownError') || false;
            if (!isYesClicked && !errorShown) {
                e.preventDefault();
                that.showError();
            }
        });
    },
    showError: function() {
        $('.error-message').removeClass("js-hidden").attr("aria-hidden");
        $('#what-you-need-form').addClass("error");
        $('body').data('shownError', true);
    },
    toggleRadios: function () {
        var radios = $('input[type=radio][name=everything-you-need]');
        radios.on('change', function () {

            radios.each(function () {
                if ($(this).prop('checked')) {
                    var target = $(this).parent().data("target");
                    $("#" + target).removeClass("js-hidden").attr("aria-hidden");
                } else {
                    var target = $(this).parent().data("target");
                    $("#" + target).addClass("js-hidden").attr("aria-hidden", "true");
                }
            });

        });
    }
}

sfa.backLink = {
    init: function () {
        var backLink = $('<a>')
            .attr({ 'href': '#', 'class': 'link-back' })
            .text('Back')
            .on('click', function () {  window.history.back(); })
            .appendTo('#js-breadcrumbs');
    }
}

sfa.forms = {
    init: function () {
        this.preventDoubleSubmit();
    },
    preventDoubleSubmit: function () {
        var forms = $('form').not('.has-client-side-validation');
        forms.on('submit', function (e) {
            var button = $(this).find('.button');
            button.attr('disabled', 'disabled');
            setTimeout(function () {
                button.removeAttr('disabled');
            }, 20000);
        });
    }
}

sfa.navigation = {
    elems: {
        userNav: $('nav#user-nav > ul'),
        levyNav: $('ul#global-nav-links')
    },
    init: function () {
        this.setupMenus(this.elems.userNav);
        this.setupEvents(this.elems.userNav);
        this.linkSettings();
    },
    setupMenus: function (menu) {
        menu.find('ul').addClass("js-hidden").attr("aria-hidden", "true");
    },
    setupEvents: function (menu) {
        var that = this;
        menu.find('li.has-sub-menu > a').on('click', function (e) {
            var $that = $(this);
            that.toggleMenu($that, $that.next('ul'));
            e.stopPropagation();
            e.preventDefault();
        });
    },
    toggleMenu: function (link, subMenu) {
        var $li = link.parent();
        if ($li.hasClass("open")) {
            // Close menu
            $li.removeClass("open");
            subMenu.addClass("js-hidden").attr("aria-hidden", "true");
        } else {
            // Open menu
            this.closeAllOpenMenus();
            $li.addClass("open");
            subMenu.removeClass("js-hidden").attr("aria-hidden", "false");
        }
    },
    closeAllOpenMenus: function () {
        this.elems.userNav.find('li.has-sub-menu.open').removeClass('open').find('ul').addClass("js-hidden").attr("aria-hidden", "true");
        this.elems.levyNav.find('li.open').removeClass('open').addClass("js-hidden").attr("aria-hidden", "true");
    },
    linkSettings: function () {
        var $settingsLink = $('a#link-settings'),
            that = this;
        this.toggleUserMenu();
        $settingsLink.attr("aria-hidden", "false");
        $settingsLink.on('click touchstart', function (e) {
            var target = $(this).attr('href');
            $(this).toggleClass('open');
            that.toggleUserMenu();
            e.preventDefault();
        });
    },
    toggleUserMenu: function () {
        var $userNavParent = this.elems.userNav.parent();
        if ($userNavParent.hasClass("close")) {
            //open it
            $userNavParent.removeClass("close").attr("aria-hidden", "false");
        } else {
            // close it
            $userNavParent.addClass("close").attr("aria-hidden", "true");
        }
    }
}

if ($('#js-breadcrumbs')) {
    sfa.backLink.init();
}

sfa.navigation.init();
sfa.forms.init();

var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']");<|endoftext|>


<commit_before>'use strict'

let DOT_WAITING_TIME = 200

let cli = require('heroku-cli-util')
let co = require('co')
let HerokuKafkaClusters = require('./clusters.js').HerokuKafkaClusters
let parseDuration = require('./shared').parseDuration
let sleep = require('co-sleep')

function * printWaitingDots () {
  yield sleep(DOT_WAITING_TIME)
  process.stdout.write('.')
  yield sleep(DOT_WAITING_TIME)
  process.stdout.write('.')
  yield sleep(DOT_WAITING_TIME)
  process.stdout.write('.')
}

function * configureTopic (context, heroku) {
  if (context.flags['no-compaction'] && context.flags['compaction']) {
    cli.error("can't pass both no-compaction and compaction")
    process.exit(1)
  } else if (context.args.CLUSTER) {
    process.stdout.write(`Configuring ${context.args.TOPIC} on ${context.args.CLUSTER}`)
  } else {
    process.stdout.write(`Configuring ${context.args.TOPIC}`)
  }

  var flags = Object.assign({}, context.flags)
  if ('retention-time' in flags) {
    let value = flags['retention-time']
    let parsed = parseDuration(value)
    if (parsed == null) {
      cli.error(`could not parse retention time '${value}'`)
      process.exit(1)
    }
    flags['retention-time'] = parsed
  }

  var creation = new HerokuKafkaClusters(heroku, process.env, context).configureTopic(context.args.CLUSTER, context.args.TOPIC, flags)
  yield printWaitingDots()

  var err = yield creation

  if (err) {
    process.stdout.write('\n')
    cli.error(err)
  } else {
    process.stdout.write(' done.\n')
    process.stdout.write(`Use \`heroku kafka:topic ${context.args.TOPIC}\` to monitor your topic`)
  }
}

module.exports = {
  topic: 'kafka',
  command: 'configure',
  description: 'configures a topic in Kafka',
  help: `
    Configures a topic in Kafka.

    Examples:

  $ heroku kafka:configure page-visits --retention-time '1 day'
  $ heroku kafka:configure HEROKU_KAFKA_BROWN_URL page-visits --retention-time '1 day' --compaction
  `,
  needsApp: true,
  needsAuth: true,
  args: [
    { name: 'TOPIC' },
    { name: 'CLUSTER', optional: true }
  ],
  flags: [
    { name: 'retention-time', description: 'length of time messages in the topic should be retained for', hasValue: true },
    { name: 'compaction', description: 'enables compaction on the topic if passed', hasValue: false },
    { name: 'no-compaction', description: 'disables compaction on the topic if passed', hasValue: false }
  ],
  run: cli.command(co.wrap(configureTopic))
}
<commit_msg>Add missing newline<commit_after>'use strict'

let DOT_WAITING_TIME = 200

let cli = require('heroku-cli-util')
let co = require('co')
let HerokuKafkaClusters = require('./clusters.js').HerokuKafkaClusters
let parseDuration = require('./shared').parseDuration
let sleep = require('co-sleep')

function * printWaitingDots () {
  yield sleep(DOT_WAITING_TIME)
  process.stdout.write('.')
  yield sleep(DOT_WAITING_TIME)
  process.stdout.write('.')
  yield sleep(DOT_WAITING_TIME)
  process.stdout.write('.')
}

function * configureTopic (context, heroku) {
  if (context.flags['no-compaction'] && context.flags['compaction']) {
    cli.error("can't pass both no-compaction and compaction")
    process.exit(1)
  } else if (context.args.CLUSTER) {
    process.stdout.write(`Configuring ${context.args.TOPIC} on ${context.args.CLUSTER}`)
  } else {
    process.stdout.write(`Configuring ${context.args.TOPIC}`)
  }

  var flags = Object.assign({}, context.flags)
  if ('retention-time' in flags) {
    let value = flags['retention-time']
    let parsed = parseDuration(value)
    if (parsed == null) {
      cli.error(`could not parse retention time '${value}'`)
      process.exit(1)
    }
    flags['retention-time'] = parsed
  }

  var creation = new HerokuKafkaClusters(heroku, process.env, context).configureTopic(context.args.CLUSTER, context.args.TOPIC, flags)
  yield printWaitingDots()

  var err = yield creation

  if (err) {
    process.stdout.write('\n')
    cli.error(err)
  } else {
    process.stdout.write(' done.\n')
    process.stdout.write(`Use \`heroku kafka:topic ${context.args.TOPIC}\` to monitor your topic.\n`)
  }
}

module.exports = {
  topic: 'kafka',
  command: 'configure',
  description: 'configures a topic in Kafka',
  help: `
    Configures a topic in Kafka.

    Examples:

  $ heroku kafka:configure page-visits --retention-time '1 day'
  $ heroku kafka:configure HEROKU_KAFKA_BROWN_URL page-visits --retention-time '1 day' --compaction
  `,
  needsApp: true,
  needsAuth: true,
  args: [
    { name: 'TOPIC' },
    { name: 'CLUSTER', optional: true }
  ],
  flags: [
    { name: 'retention-time', description: 'length of time messages in the topic should be retained for', hasValue: true },
    { name: 'compaction', description: 'enables compaction on the topic if passed', hasValue: false },
    { name: 'no-compaction', description: 'disables compaction on the topic if passed', hasValue: false }
  ],
  run: cli.command(co.wrap(configureTopic))
}
<|endoftext|>