<commit_before>#!/usr/bin/env node

/* eslint global-require: [0] */
/* eslint no-sync: [0] */
/* eslint require-jsdoc: [0] */

// Idealy, this file belongs in ./tooling, but the first iteration is a *lot*
// simpler if we don't have to deal with adding `../` to every file operation.

// Reminder: because this script uses the package.jsons in
// packages/node_modules, it should be used *after* new versions have been
// determined by babel.

// DO NOT COPY THIS FILE INTO THE react-ciscospark REPO.
// Instead, make it a package in its own right and let the react-ciscospark
// project depend on it.

const builtins = require(`builtins`);
const denodeify = require(`denodeify`);
const detective = require(`detective`);
const fs = require(`fs`);
const {curry, uniq} = require(`lodash`);
const path = require(`path`);
const rpj = require(`read-package-json`);

const readPackage = denodeify(rpj);

function findDepsForPackage(packagePath) {
  return readPackage(packagePath)
   .then((pkg) => {
     if (pkg.main) {
       return walkDeps(path.resolve(path.dirname(packagePath), pkg.main));
     }
     else if (pkg.bin) {
       return Object.values(pkg.bin).reduce((acc, bin) => acc.concat(walkDeps(path.resolve(path.dirname(packagePath), bin))), []);
     }

     try {
       const p = path.resolve(path.dirname(packagePath), `index.js`);
       fs.statSync(p);
       return walkDeps(p);
     }
     catch (err) {
       if (err.code === `ENOENT`) {
         throw new Error(`cannot determine entrypoint for ${pkg.name}`);
       }
       throw err;
     }
   })
   .catch((err) => {
     if (err.code === `EISDIR`) {
       return findDepsForPackage(path.join(packagePath, `package.json`));
     }

     throw err;
   });
}

const depsToVersions = curry((rootPkg, deps) => deps.reduce((acc, dep) => {
  if (builtins.includes(dep)) {
    return acc;
  }
  acc[dep] = rootPkg.dependencies[dep] || rootPkg.devDependencies[dep] || rootPkg.optionalDependencies[dep];
  if (!acc[dep]) {
    try {
      acc[dep] = require(`./packages/node_modules/${dep}/package.json`).version;
    }
    catch (err) {
      // eslint-disable-next-line no-console
      console.warn(err);
      throw new Error(`Failed to determine version for ${dep}, Is it missing from package.json?`);
    }
  }
  return acc;
}, {}));

const assignDeps = curry((pkgPath, deps) => {
  if (!pkgPath.startsWith(`./`) && !pkgPath.startsWith(`/`)) {
    pkgPath = `./${pkgPath}`;
  }
  const pkg = require(pkgPath);
  pkg.dependencies = deps;
  fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
});

const visited = new Set();
function walkDeps(filePath) {
  if (visited.has(filePath)) {
    return [];
  }
  try {
    visited.add(filePath);
    const requires = detective(fs.readFileSync(filePath));
    const deps = requires.reduce((acc, dep) => {
      if (dep.startsWith(`.`)) {
        acc = acc.concat(walkDeps(path.resolve(path.dirname(filePath), dep)));
      }
      else {
        acc.push(dep);
      }
      return acc;
    }, []);
    return uniq(deps.map((d) => {
      d = d.split(`/`);
      if (d[0].startsWith(`@`)) {
        return d.slice(0, 2).join(`/`);
      }
      return d[0];
    }));
  }
  catch (err) {
    if (err.code === `EISDIR`) {
      return walkDeps(path.resolve(filePath, `index.js`));
    }
    if (err.code === `ENOENT` && !filePath.endsWith(`.js`)) {
      return walkDeps(`${filePath}.js`);
    }
    throw err;
  }
}

function updateSinglePackage(packagePath) {
  return findDepsForPackage(packagePath)
    .then(depsToVersions(require(`./package.json`)))
    .then(assignDeps(path.join(packagePath, `package.json`)));
}

function findPackages(p) {
  return fs.readdirSync(p).reduce((acc, d) => {
    const fullpath = path.resolve(p, d);
    if (fs.statSync(fullpath).isDirectory()) {
      try {
        fs.statSync(path.resolve(fullpath, `package.json`));
        acc.push(fullpath);
      }
      catch (err) {
        if (err.code === `ENOENT`) {
          return acc.concat(findPackages(fullpath));
        }
        throw err;
      }
    }
    return acc;
  }, []);
}

function updateAllPackages(rootPath) {
  const paths = findPackages(rootPath)
    // The next line can be removed once the widget code is removed from this
    // repository
    .filter((p) => !p.includes(`widget`));
  return Promise.all(paths.map(updateSinglePackage));
}

if (require.main === module) {
  if (process.argv[2] === `--help`) {
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-console
    console.log(`usage: node deps.js [packagepath]`);
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-console
    console.log(`update dependency lists for all packages in ${__dirname}/packages/node_modules`);
    // eslint-disable-next-line no-console
    console.log(`\tnode deps.js`);
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-console
    console.log(`update dependency list for single package "ciscospark"`);
    // eslint-disable-next-line no-console
    console.log(`\tnode deps.js ./packages/node_modules/ciscospark`);
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-process-exit
    process.exit(0);
  }

  let p;
  if (process.argv[2]) {
    p = updateSinglePackage(process.argv[2]);
  }
  else {
    p = updateAllPackages(path.resolve(__dirname, `./packages/node_modules`));
  }
  p.catch((err) => {
      // eslint-disable-next-line no-console
    console.error(err);
      // eslint-disable-next-line no-process-exit
    process.exit(64);
  });
}
else {
  module.exports = {
    assignDeps,
    depsToVersions,
    findDepsForPackage,
    findPackages,
    updateSinglePackage
  };
}
<commit_msg>chore(tooling): use _.values because node 6<commit_after>#!/usr/bin/env node

/* eslint global-require: [0] */
/* eslint no-sync: [0] */
/* eslint require-jsdoc: [0] */

// Idealy, this file belongs in ./tooling, but the first iteration is a *lot*
// simpler if we don't have to deal with adding `../` to every file operation.

// Reminder: because this script uses the package.jsons in
// packages/node_modules, it should be used *after* new versions have been
// determined by babel.

// DO NOT COPY THIS FILE INTO THE react-ciscospark REPO.
// Instead, make it a package in its own right and let the react-ciscospark
// project depend on it.

const builtins = require(`builtins`);
const denodeify = require(`denodeify`);
const detective = require(`detective`);
const fs = require(`fs`);
const {curry, uniq} = require(`lodash`);
const path = require(`path`);
const rpj = require(`read-package-json`);
const _ = require(`values`);

const readPackage = denodeify(rpj);

function findDepsForPackage(packagePath) {
  return readPackage(packagePath)
   .then((pkg) => {
     if (pkg.main) {
       return walkDeps(path.resolve(path.dirname(packagePath), pkg.main));
     }
     else if (pkg.bin) {
       return _.values(pkg.bin).reduce((acc, bin) => acc.concat(walkDeps(path.resolve(path.dirname(packagePath), bin))), []);
     }

     try {
       const p = path.resolve(path.dirname(packagePath), `index.js`);
       fs.statSync(p);
       return walkDeps(p);
     }
     catch (err) {
       if (err.code === `ENOENT`) {
         throw new Error(`cannot determine entrypoint for ${pkg.name}`);
       }
       throw err;
     }
   })
   .catch((err) => {
     if (err.code === `EISDIR`) {
       return findDepsForPackage(path.join(packagePath, `package.json`));
     }

     throw err;
   });
}

const depsToVersions = curry((rootPkg, deps) => deps.reduce((acc, dep) => {
  if (builtins.includes(dep)) {
    return acc;
  }
  acc[dep] = rootPkg.dependencies[dep] || rootPkg.devDependencies[dep] || rootPkg.optionalDependencies[dep];
  if (!acc[dep]) {
    try {
      acc[dep] = require(`./packages/node_modules/${dep}/package.json`).version;
    }
    catch (err) {
      // eslint-disable-next-line no-console
      console.warn(err);
      throw new Error(`Failed to determine version for ${dep}, Is it missing from package.json?`);
    }
  }
  return acc;
}, {}));

const assignDeps = curry((pkgPath, deps) => {
  if (!pkgPath.startsWith(`./`) && !pkgPath.startsWith(`/`)) {
    pkgPath = `./${pkgPath}`;
  }
  const pkg = require(pkgPath);
  pkg.dependencies = deps;
  fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
});

const visited = new Set();
function walkDeps(filePath) {
  if (visited.has(filePath)) {
    return [];
  }
  try {
    visited.add(filePath);
    const requires = detective(fs.readFileSync(filePath));
    const deps = requires.reduce((acc, dep) => {
      if (dep.startsWith(`.`)) {
        acc = acc.concat(walkDeps(path.resolve(path.dirname(filePath), dep)));
      }
      else {
        acc.push(dep);
      }
      return acc;
    }, []);
    return uniq(deps.map((d) => {
      d = d.split(`/`);
      if (d[0].startsWith(`@`)) {
        return d.slice(0, 2).join(`/`);
      }
      return d[0];
    }));
  }
  catch (err) {
    if (err.code === `EISDIR`) {
      return walkDeps(path.resolve(filePath, `index.js`));
    }
    if (err.code === `ENOENT` && !filePath.endsWith(`.js`)) {
      return walkDeps(`${filePath}.js`);
    }
    throw err;
  }
}

function updateSinglePackage(packagePath) {
  return findDepsForPackage(packagePath)
    .then(depsToVersions(require(`./package.json`)))
    .then(assignDeps(path.join(packagePath, `package.json`)));
}

function findPackages(p) {
  return fs.readdirSync(p).reduce((acc, d) => {
    const fullpath = path.resolve(p, d);
    if (fs.statSync(fullpath).isDirectory()) {
      try {
        fs.statSync(path.resolve(fullpath, `package.json`));
        acc.push(fullpath);
      }
      catch (err) {
        if (err.code === `ENOENT`) {
          return acc.concat(findPackages(fullpath));
        }
        throw err;
      }
    }
    return acc;
  }, []);
}

function updateAllPackages(rootPath) {
  const paths = findPackages(rootPath)
    // The next line can be removed once the widget code is removed from this
    // repository
    .filter((p) => !p.includes(`widget`));
  return Promise.all(paths.map(updateSinglePackage));
}

if (require.main === module) {
  if (process.argv[2] === `--help`) {
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-console
    console.log(`usage: node deps.js [packagepath]`);
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-console
    console.log(`update dependency lists for all packages in ${__dirname}/packages/node_modules`);
    // eslint-disable-next-line no-console
    console.log(`\tnode deps.js`);
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-console
    console.log(`update dependency list for single package "ciscospark"`);
    // eslint-disable-next-line no-console
    console.log(`\tnode deps.js ./packages/node_modules/ciscospark`);
    // eslint-disable-next-line no-console
    console.log();
    // eslint-disable-next-line no-process-exit
    process.exit(0);
  }

  let p;
  if (process.argv[2]) {
    p = updateSinglePackage(process.argv[2]);
  }
  else {
    p = updateAllPackages(path.resolve(__dirname, `./packages/node_modules`));
  }
  p.catch((err) => {
      // eslint-disable-next-line no-console
    console.error(err);
      // eslint-disable-next-line no-process-exit
    process.exit(64);
  });
}
else {
  module.exports = {
    assignDeps,
    depsToVersions,
    findDepsForPackage,
    findPackages,
    updateSinglePackage
  };
}
<|endoftext|>


<commit_before>/*
 * Define an interface to let you bind JS objects to DOM elements and have the
 * DOM update when the JS obj changes.
 */

(function(exports) {
	"use strict";

	/*
	 * update the target with obj (defaults to target.textContent)
	 * when an attribute in obj changes, update the target
	 * mappings are given by hashMap in the format:
	 *     attr
	 *     // === obj[attr] --> target
	 *     {
	 *         attr: selector
	 *     }
	 *     //  === obj[attr] --> target > selector
	 *
	 *     {
	 *         attr: { el: selector, prop: prop }
	 *     }
	 *     // === obj[attr] --> (target > selector).prop
	 *     // (el and prop are optional)
	 */
	function bind(obj, target, hashMap) {
		var attr, setter;
		target = target || document;

		if (typeof hashMap === 'string') {
			setter = setValue(target, 'text');
			setter(obj[hashMap]);
			setSetter(obj, hashMap, setter);
		} else {
			for (attr in hashMap) if (hashMap.hasOwnProperty(attr)) {
				(function() {
					var opts = (typeof hashMap[attr] === 'string') ?
							{ el: hashMap[attr] } : hashMap[attr],
						els = (opts.el) ?
							target.querySelectorAll(opts.el) : [target],
						setter = setValue(els, opts.prop);
					setter(obj[attr]);
					setSetter(obj, attr, setter);
				}());
			}
		}
	}

	/*
	 * return the correct property name given the element and intended name
	 * e.g. class --> className, text --> textContent, etc
	 */
	function getPropName(el, prop) {
		if (el[prop]) {
			return el[prop];
		} else {
			switch (prop) {
				case 'class': return 'className';
				case undefined:
				case 'text': return 'textContent';
				default: return 'setAttribute';
			}
		}
	}

	/*
	 * give all the elements in els the provided value
	 */
	function setValue(els, prop) {
		return function(value) {
			var i, l, propName, el;
			for (i = 0, l = els.length; i < l; i++) {
				el = els[i];
				propName = getPropName(el, prop);
				if (typeof el[propName] === 'function') {
					el[propName](prop, value);
				} else {
					el[propName] = value;
				}
			}
		};
	}

	/*
	 * set a listener on obj[attr] that fires fn when obj[attr] changes
	 */
	function setSetter(obj, attr, fn) {
		var descriptor, descriptorValue, _set;

		descriptor = Object.getOwnPropertyDescriptor(obj, attr);
		descriptorValue = descriptor.value;
		delete descriptor.writable;
		delete descriptor.value;
		descriptor.set = setter;
		descriptor.get = function() { return descriptorValue; }
		Object.defineProperty(obj, attr, descriptor);

		function setter(value) {
			if (value !== descriptorValue) {
				fn(value);
				descriptorValue = value;
			}
			return value;
		}
	}

	exports.domb = {
		bind: bind
	};

}(window));
<commit_msg>return property name if it exists rather than value<commit_after>/*
 * Define an interface to let you bind JS objects to DOM elements and have the
 * DOM update when the JS obj changes.
 */

(function(exports) {
	"use strict";

	/*
	 * update the target with obj (defaults to target.textContent)
	 * when an attribute in obj changes, update the target
	 * mappings are given by hashMap in the format:
	 *     attr
	 *     // === obj[attr] --> target
	 *     {
	 *         attr: selector
	 *     }
	 *     //  === obj[attr] --> target > selector
	 *
	 *     {
	 *         attr: { el: selector, prop: prop }
	 *     }
	 *     // === obj[attr] --> (target > selector).prop
	 *     // (el and prop are optional)
	 */
	function bind(obj, target, hashMap) {
		var attr, setter;
		target = target || document;

		if (typeof hashMap === 'string') {
			setter = setValue(target, 'text');
			setter(obj[hashMap]);
			setSetter(obj, hashMap, setter);
		} else {
			for (attr in hashMap) if (hashMap.hasOwnProperty(attr)) {
				(function() {
					var opts = (typeof hashMap[attr] === 'string') ?
							{ el: hashMap[attr] } : hashMap[attr],
						els = (opts.el) ?
							target.querySelectorAll(opts.el) : [target],
						setter = setValue(els, opts.prop);
					setter(obj[attr]);
					setSetter(obj, attr, setter);
				}());
			}
		}
	}

	/*
	 * return the correct property name given the element and intended name
	 * e.g. class --> className, text --> textContent, etc
	 */
	function getPropName(el, prop) {
		if (el[prop]) {
			return prop;
		} else {
			switch (prop) {
				case 'class': return 'className';
				case undefined:
				case 'text': return 'textContent';
				default: return 'setAttribute';
			}
		}
	}

	/*
	 * give all the elements in els the provided value
	 */
	function setValue(els, prop) {
		return function(value) {
			var i, l, propName, el;
			for (i = 0, l = els.length; i < l; i++) {
				el = els[i];
				propName = getPropName(el, prop);
				if (typeof el[propName] === 'function') {
					el[propName](prop, value);
				} else {
					el[propName] = value;
				}
			}
		};
	}

	/*
	 * set a listener on obj[attr] that fires fn when obj[attr] changes
	 */
	function setSetter(obj, attr, fn) {
		var descriptor, descriptorValue, _set;

		descriptor = Object.getOwnPropertyDescriptor(obj, attr);
		descriptorValue = descriptor.value;
		delete descriptor.writable;
		delete descriptor.value;
		descriptor.set = setter;
		descriptor.get = function() { return descriptorValue; }
		Object.defineProperty(obj, attr, descriptor);

		function setter(value) {
			if (value !== descriptorValue) {
				fn(value);
				descriptorValue = value;
			}
			return value;
		}
	}

	exports.domb = {
		bind: bind
	};

}(window));
<|endoftext|>


<commit_before>#!/usr/bin/env node

var abbrev = require('abbrev')
  , request = require('request')
  , optimist = require('optimist')
  , colors = require('colors');

var checkers = { github: github, harvest: harvest }
  , services = Object.keys(checkers)
  , abbr = abbrev(services);

abbr.gh = 'github';
abbr.hv = 'harvest';

var targets = optimist
  .usage('Usage: down [service]\n\nSupported Services:\n' + services.join('\n'))
  .demand(1).argv._;

targets.forEach(function start(service) {
  service = abbr[service];
  if (!service) {
    console.error("Unknown service: " + service);
    return false;
  }

  var checker = checkers[service];
  setImmediate(function checkOnce() {
    checker(function(e, result, message) {
      var tag = e ? '  ERR '.red : result ? '   UP '.green : ' DOWN '.red;

      console.log(tag + '[' + service + '] ' + message);
      setTimeout(checkOnce, 1000);
    });
  });
});

function github(callback) {
  request('https://status.github.com/api/last-message.json', function(e, resp, body) {
    if (e) return callback(e)
    if (!resp || resp.statusCode !== 200) return callback(new Error("Status not 200."));

    if (typeof body === 'string') body = JSON.parse(body);
    callback(null, body.status === 'good', body.body || '');
  });
}

function harvest(callback) {
  request('http://harveststatus.com/status.json', function(e, resp, body) {
    if (e) return callback(e);
    if (!resp || resp.statusCode !== 200) return callback(new Error("Status not 200."));

    if (typeof body === 'string') body = JSON.parse(body);
    callback(null, body.status === 'up',
      'last response time: ' + body['last_response_time']);
  });
}

<commit_msg>Minor bugfix.<commit_after>#!/usr/bin/env node

var abbrev = require('abbrev')
  , request = require('request')
  , optimist = require('optimist')
  , colors = require('colors');

var checkers = { github: github, harvest: harvest }
  , services = Object.keys(checkers)
  , abbr = abbrev(services);

abbr.gh = 'github';
abbr.hv = 'harvest';

var targets = optimist
  .usage('Usage: down [service]\n\nSupported Services:\n' + services.join('\n'))
  .demand(1).argv._;

targets.forEach(function start(service) {
  if (!(service in abbr)) {
    console.error("Unknown service: " + service);
    return false;
  }

  service = abbr[service];

  var checker = checkers[service];
  setImmediate(function checkOnce() {
    checker(function(e, result, message) {
      var tag = e ? '  ERR '.red : result ? '   UP '.green : ' DOWN '.red;

      console.log(tag + '[' + service + '] ' + message);
      setTimeout(checkOnce, 1000);
    });
  });
});

function github(callback) {
  request('https://status.github.com/api/last-message.json', function(e, resp, body) {
    if (e) return callback(e)
    if (!resp || resp.statusCode !== 200) return callback(new Error("Status not 200."));

    if (typeof body === 'string') body = JSON.parse(body);
    callback(null, body.status === 'good', body.body || '');
  });
}

function harvest(callback) {
  request('http://harveststatus.com/status.json', function(e, resp, body) {
    if (e) return callback(e);
    if (!resp || resp.statusCode !== 200) return callback(new Error("Status not 200."));

    if (typeof body === 'string') body = JSON.parse(body);
    callback(null, body.status === 'up',
      'last response time: ' + body['last_response_time']);
  });
}

<|endoftext|>


<commit_before>
var Draw = {};

// Clear the screen.

Draw.clear = function() {
	for (var x = 0; x < Pixels.width; x++) {
		for (var y = 0; y < Pixels.height / 2; y++)
			Pixels.set(x, y, [1.0, 1.0, 1.0]);
		for (var y = Pixels.height / 2; y < Pixels.width; y++)
			Pixels.set(x, y, [0.9, 0.9, 0.9]);
	}
};

// Test ray-vs-box.
//
// Parameters:
//	ray = {
//		x: 0,
//		y: 0,
//		dx: 0,
//		dy: 0
//	};
//	aabb = {
//		x: 0,
//		y: 0,
//		w: 0,
//		h: 0
//	};
//
// Returns:
//	null OR
//	{
//		x:    0, // Intersection x
//		y:    0  // Intersection y
//	};
//
Draw.testRayAABB = function(ray, aabb) {

	//
	// Given tx1, tx2, ty1, ty2, return the intercept or null.
	//
	function getIntercept(tx1, tx2, ty1, ty2) {
		// Calculate the max t
		// This will be used to "throw out" values
		// ie. if t > tMax, it's considered invalid
		var tMax  = Math.max(tx1, tx2, ty1, ty2);

		// Throw out negative values (those hits are behind us)
		if (tx1 < 0) tx1 = tMax + 1;
		if (tx2 < 0) tx2 = tMax + 1;
		if (ty1 < 0) ty1 = tMax + 1;
		if (ty2 < 0) ty2 = tMax + 1;

		// Check tx1 bounds
		if (ray.y + ray.dy * tx1 < aabb.y ||
			  ray.y + ray.dy * tx1 > aabb.y + aabb.h)
			tx1 = tMax + 1;

		// Check tx2 bounds
		if (ray.y + ray.dy * tx2 < aabb.y ||
			  ray.y + ray.dy * tx2 > aabb.y + aabb.h)
			tx2 = tMax + 1;

		// Check ty1 bounds
		if (ray.x + ray.dx * ty1 < aabb.x ||
			  ray.x + ray.dx * ty1 > aabb.x + aabb.w)
			ty1 = tMax + 1;

		// Check ty2 bounds
		if (ray.x + ray.dx * ty2 < aabb.x ||
			  ray.x + ray.dx * ty2 > aabb.x + aabb.w)
			ty2 = tMax + 1;

		// Return the closest hit (if exists)
		var tHit = Math.min(tx1, tx2, ty1, ty2);
		if (tHit > tMax)
			return null;
		return {
			x: ray.x + ray.dx * tHit,
			y: ray.y + ray.dy * tHit
		};
	}

	// Handle vertical line
	if (ray.dx === 0 && Math.abs(ray.dy) === 1) {

		// Check X bounds
		if (ray.x < aabb.x || ray.x > aabb.x + aabb.w)
			return null;

		// Calculate y intercepts
		var ty1 = (aabb.y - ray.y) / ray.dy;
		var ty2 = (aabb.y + aabb.h - ray.y) / ray.dy;

		// Find the hit
		return getIntercept(-1, -1, ty1, ty2);
	}

	// Handle horizontal line
	if (Math.abs(ray.dx) === 1 && ray.dy === 0) {

		// Check Y bounds
		if (ray.y < aabb.y || ray.y > aabb.y + aabb.h)
			return null;

		// Calculate x intercepts
		var tx1 = (aabb.x - ray.x) / ray.dx;
		var tx2 = (aabb.x + aabb.w - ray.x) / ray.dx;

		// Find the hit
		return getIntercept(tx1, tx2, -1, -1);
	}

	// Handle every other line
	// Calculate intercepts
	var tx1 = (aabb.x - ray.x) / ray.dx;
	var tx2 = (aabb.x + aabb.w - ray.x) / ray.dx;
	var ty1 = (aabb.y - ray.y) / ray.dy;
	var ty2 = (aabb.y + aabb.h - ray.y) / ray.dy;

	// Find the hit
	return getIntercept(tx1, tx2, ty1, ty2);
};

// Render the world to the screen.

Draw.render = function(camera, map) {

	// Clear the screen first
	Draw.clear();

	// Prepare rendering variables
	var e        = 0.001;
	var tanVFov  = Math.tan(camera.vFovRad / 2);
	var adjacent = (Pixels.width / 2) / Math.tan(camera.hFovRad / 2);

	// Shoot rays for every x-axis pixel
	for (var x = 0; x < Pixels.width; x++) {

		// Calculate opposite value
		var opposite = (x - Pixels.width / 2) + 0.5;

		// Calculate the ray
		var ray = {};
		ray.angleOffset = Math.atan(opposite / adjacent);
		ray.angle       = ray.angleOffset + camera.rotRad;
		ray.dx          = Math.sin(ray.angle);
		ray.dy          = Math.cos(ray.angle);
		ray.x           = camera.posX;
		ray.y           = camera.posY;

		// Shoot the ray through the map
		while (true) {

			// Try and move the ray off of any integer boundaries
			ray.x += ray.dx * e;
			ray.y += ray.dy * e;

			// Make sure we are within the map
			if (ray.x <= 0.0 && ray.dx < 0.0 ||
			    ray.y <= 0.0 && ray.dy < 0.0 ||
			    ray.x >= map.width  && ray.dx > 0.0 ||
			    ray.y >= map.height && ray.dy > 0.0)
			  break;

			// Calculate distance to next integer boundary
			var tx = -1.0, ty = -1.0;
			if (ray.dx > 0)
				tx = (Math.floor(ray.x + 1.0) - ray.x) / ray.dx;
			else
			if (ray.dx < 0)
				tx = (Math.floor(ray.x) - ray.x) / ray.dx;
			if (ray.dy > 0)
				ty = (Math.floor(ray.y + 1.0) - ray.y) / ray.dy;
			else
			if (ray.dy < 0)
				ty = (Math.floor(ray.y) - ray.y) / ray.dy;

			var tBest = null;
			if (tx >= 0.0 && ty >= 0.0) {
				tBest = (tx < ty ? tx : ty);
				//if (tx < ty) {
				//	tBest = tx;
				//} else {
				//	tBest = ty;
				//}
			} else if (tx >= 0.0) {
				tBest = tx;
			} else if (ty >= 0.0) {
				tBest = ty;
			}else
				break;

			// Move the ray
			ray.x += ray.dx * tBest;
			ray.y += ray.dy * tBest;

			// Calculate the tile we're at
			var tileX = Math.floor(ray.x + ray.dx * e);
			var tileY = Math.floor(ray.y + ray.dy * e);

			// If it's empty, we can keep moving
			if ( !map.get(tileX, tileY) )
				continue;

			// Calculate color based on face normal
			var color = [0.5, 0.5, 0.5];
			if (tx === tBest) {
				//color = [1, 0, 0];
				if (ray.dx < 0.0) color = [0, 1, 0];
				if (ray.dx > 0.0) color = [0, 0, 0];
			} else {
				//color = [0, 0, 1];
				if (ray.dy < 0.0) color = [1, 0, 0];
				if (ray.dy > 0.0) color = [0, 0, 1];
			}

			// We hit! Calculate the distance between the hit and the camera
			var diffX = (ray.x - camera.posX);
			var diffY = (ray.y - camera.posY);
			var dist  = Math.sqrt(diffX * diffX + diffY * diffY) * Math.cos(ray.angleOffset);

			// Calculate the pixel height based on the distance
			// : BlockHeight      = 2.0
			// : NormalizedHeight = (BlockHeight / 2) / (tan * distance)
			// : DrawHeight       = (PixelHeight / 2) * NormalizedHeight;
			var height = (Pixels.height / 2) / (tanVFov * dist);
			var height = Math.min(height, Pixels.height);

			// Draw the pixel line
			var y1 = Pixels.height / 2 - height / 2;
			var y2 = Pixels.height / 2 + height / 2;
			for (var y = y1; y < y2; y++)
				Pixels.set(x, Math.floor(y), color);

			if (Keyboard.isKeyDown('p'))
				console.log('Wall hit: (', tileX, ',', tileY, ')');

			// We're done here
			break;
		}

		// Reset the ray position
		ray.x = camera.posX;
		ray.y = camera.posY;

		// Shoot the ray at sprites
		/*var hit = Draw.testRayAABB( ray,
			{
				x: 0.5,
				y: 2,
				w: 1,
				h: 1
			}
		) || Draw.testRayAABB( ray,
			{
				x: -2.5,
				y: 1,
				w: 2,
				h: 1
			}
		);
		if (hit != null) {
			// Distance = dist between hit & cam * Math.cos(rayAngle)
			var diffX = (hit.x - ray.x);
			var diffY = (hit.y - ray.y);
			var dist   = Math.sqrt(diffX * diffX + diffY * diffY) * Math.cos(ray.angleOffset);

			// : BlockHeight      = 2.0
			// : NormalizedHeight = (BlockHeight / 2) / (tan * distance)
			// : DrawHeight       = (PixelHeight / 2) * NormalizedHeight;
			var height = (Pixels.height / 2) / (tanVFov * dist);

			// Draw the pixel line
			var y1 = Pixels.height / 2 - height / 2;
			var y2 = Pixels.height / 2 + height / 2;
			for (var y = y1; y < y2; y++)
				Pixels.set(x, Math.floor(y), [0, 0, 0]);
		}*/
	}

	// Update the pixels
	Pixels.draw();
};

<commit_msg>Reduced rendering glitches and implemented basic shading.<commit_after>
var Draw = {};

// Clear the screen.

Draw.clear = function() {
	for (var x = 0; x < Pixels.width; x++) {
		for (var y = 0; y < Pixels.height / 2; y++)
			Pixels.set(x, y, [1.0, 1.0, 1.0]);
		for (var y = Pixels.height / 2; y < Pixels.width; y++)
			Pixels.set(x, y, [0.9, 0.9, 0.9]);
	}
};

// Test ray-vs-box.
//
// Parameters:
//	ray = {
//		x: 0,
//		y: 0,
//		dx: 0,
//		dy: 0
//	};
//	aabb = {
//		x: 0,
//		y: 0,
//		w: 0,
//		h: 0
//	};
//
// Returns:
//	null OR
//	{
//		x:    0, // Intersection x
//		y:    0  // Intersection y
//	};
//
Draw.testRayAABB = function(ray, aabb) {

	//
	// Given tx1, tx2, ty1, ty2, return the intercept or null.
	//
	function getIntercept(tx1, tx2, ty1, ty2) {
		// Calculate the max t
		// This will be used to "throw out" values
		// ie. if t > tMax, it's considered invalid
		var tMax  = Math.max(tx1, tx2, ty1, ty2);

		// Throw out negative values (those hits are behind us)
		if (tx1 < 0) tx1 = tMax + 1;
		if (tx2 < 0) tx2 = tMax + 1;
		if (ty1 < 0) ty1 = tMax + 1;
		if (ty2 < 0) ty2 = tMax + 1;

		// Check tx1 bounds
		if (ray.y + ray.dy * tx1 < aabb.y ||
			  ray.y + ray.dy * tx1 > aabb.y + aabb.h)
			tx1 = tMax + 1;

		// Check tx2 bounds
		if (ray.y + ray.dy * tx2 < aabb.y ||
			  ray.y + ray.dy * tx2 > aabb.y + aabb.h)
			tx2 = tMax + 1;

		// Check ty1 bounds
		if (ray.x + ray.dx * ty1 < aabb.x ||
			  ray.x + ray.dx * ty1 > aabb.x + aabb.w)
			ty1 = tMax + 1;

		// Check ty2 bounds
		if (ray.x + ray.dx * ty2 < aabb.x ||
			  ray.x + ray.dx * ty2 > aabb.x + aabb.w)
			ty2 = tMax + 1;

		// Return the closest hit (if exists)
		var tHit = Math.min(tx1, tx2, ty1, ty2);
		if (tHit > tMax)
			return null;
		return {
			x: ray.x + ray.dx * tHit,
			y: ray.y + ray.dy * tHit
		};
	}

	// Handle vertical line
	if (ray.dx === 0 && Math.abs(ray.dy) === 1) {

		// Check X bounds
		if (ray.x < aabb.x || ray.x > aabb.x + aabb.w)
			return null;

		// Calculate y intercepts
		var ty1 = (aabb.y - ray.y) / ray.dy;
		var ty2 = (aabb.y + aabb.h - ray.y) / ray.dy;

		// Find the hit
		return getIntercept(-1, -1, ty1, ty2);
	}

	// Handle horizontal line
	if (Math.abs(ray.dx) === 1 && ray.dy === 0) {

		// Check Y bounds
		if (ray.y < aabb.y || ray.y > aabb.y + aabb.h)
			return null;

		// Calculate x intercepts
		var tx1 = (aabb.x - ray.x) / ray.dx;
		var tx2 = (aabb.x + aabb.w - ray.x) / ray.dx;

		// Find the hit
		return getIntercept(tx1, tx2, -1, -1);
	}

	// Handle every other line
	// Calculate intercepts
	var tx1 = (aabb.x - ray.x) / ray.dx;
	var tx2 = (aabb.x + aabb.w - ray.x) / ray.dx;
	var ty1 = (aabb.y - ray.y) / ray.dy;
	var ty2 = (aabb.y + aabb.h - ray.y) / ray.dy;

	// Find the hit
	return getIntercept(tx1, tx2, ty1, ty2);
};

// Render the world to the screen.

Draw.render = function(camera, map) {

	// Clear the screen first
	Draw.clear();

	// Prepare rendering variables
	var e        = 0.001;
	var tanVFov  = Math.tan(camera.vFovRad / 2);
	var adjacent = (Pixels.width / 2) / Math.tan(camera.hFovRad / 2);

	// Shoot rays for every x-axis pixel
	for (var x = 0; x < Pixels.width; x++) {

		// Calculate opposite value
		var opposite = (x - Pixels.width / 2) + 0.5;

		// Calculate the ray
		var ray = {};
		ray.angleOffset = Math.atan(opposite / adjacent);
		ray.angle       = ray.angleOffset + camera.rotRad;
		ray.dx          = Math.sin(ray.angle);
		ray.dy          = Math.cos(ray.angle);
		ray.x           = camera.posX;
		ray.y           = camera.posY;

		// Shoot the ray through the map
		while (true) {

			// Make sure we are within the map
			if (ray.x <= 0.0 && ray.dx < 0.0 ||
			    ray.y <= 0.0 && ray.dy < 0.0 ||
			    ray.x >= map.width  && ray.dx > 0.0 ||
			    ray.y >= map.height && ray.dy > 0.0)
			  break;

			// Calculate distance to next integer boundary
			var tx = -1.0, ty = -1.0;
			if (ray.dx > 0)
				tx = (Math.floor(ray.x + 1.0) - ray.x) / ray.dx;
			else
			if (ray.dx < 0) {
				tx = (Math.floor(ray.x) - ray.x) / ray.dx;
				if (tx === 0.0)
					tx = -1.0 / ray.dx;
			}
			if (ray.dy > 0)
				ty = (Math.floor(ray.y + 1.0) - ray.y) / ray.dy;
			else
			if (ray.dy < 0) {
				ty = (Math.floor(ray.y) - ray.y) / ray.dy;
				if (ty === 0.0)
					ty = -1.0 / ray.dy;
			}

			var tBest = null;
			if (tx >= 0.0 && ty >= 0.0) {
				tBest = (tx < ty ? tx : ty);
			} else if (tx >= 0.0) {
				tBest = tx;
			} else if (ty >= 0.0) {
				tBest = ty;
			}else
				break;

			// Move the ray
			ray.x += ray.dx * tBest;
			ray.y += ray.dy * tBest;

			// Calculate the tile we're at
			var tileX = Math.floor(ray.x + ray.dx * e);
			var tileY = Math.floor(ray.y + ray.dy * e);

			// If it's empty, we can keep moving
			if ( !map.get(tileX, tileY) )
				continue;

			// Calculate the hit normal
			var normal = {x: 0.0, y: 0.0};
			if (tx === tBest) {
				if (ray.dx < 0.0) normal.x =  1.0;
				if (ray.dx > 0.0) normal.x = -1.0;
			} else {
				if (ray.dy < 0.0) normal.y =  1.0;
				if (ray.dy > 0.0) normal.y = -1.0;
			}

			// Calculate the lighting dot product
			var lighting = (-normal.x * ray.dx) + (-normal.y * ray.dy);

			// Calculate color based on lighting dot product
			var color = [
				0.25 + lighting * 0.5,
				0.25 + lighting * 0.5,
				0.25 + lighting * 0.5
			];

			// We hit! Calculate the distance between the hit and the camera
			var diffX = (ray.x - camera.posX);
			var diffY = (ray.y - camera.posY);
			var dist  = Math.sqrt(diffX * diffX + diffY * diffY) * Math.cos(ray.angleOffset);

			// Calculate the pixel height based on the distance
			// : BlockHeight      = 2.0
			// : NormalizedHeight = (BlockHeight / 2) / (tan * distance)
			// : DrawHeight       = (PixelHeight / 2) * NormalizedHeight;
			var height = (Pixels.height / 2) / (tanVFov * dist);
			var height = Math.min(height, Pixels.height);

			// Draw the pixel line
			var y1 = Pixels.height / 2 - height / 2;
			var y2 = Pixels.height / 2 + height / 2;
			for (var y = y1; y < y2; y++)
				Pixels.set(x, Math.floor(y), color);

			if (Keyboard.isKeyDown('p'))
				console.log('Wall hit: (', tileX, ',', tileY, ')');

			// We're done here
			break;
		}

		// Reset the ray position
		ray.x = camera.posX;
		ray.y = camera.posY;

		// Shoot the ray at sprites
		/*var hit = Draw.testRayAABB( ray,
			{
				x: 0.5,
				y: 2,
				w: 1,
				h: 1
			}
		) || Draw.testRayAABB( ray,
			{
				x: -2.5,
				y: 1,
				w: 2,
				h: 1
			}
		);
		if (hit != null) {
			// Distance = dist between hit & cam * Math.cos(rayAngle)
			var diffX = (hit.x - ray.x);
			var diffY = (hit.y - ray.y);
			var dist   = Math.sqrt(diffX * diffX + diffY * diffY) * Math.cos(ray.angleOffset);

			// : BlockHeight      = 2.0
			// : NormalizedHeight = (BlockHeight / 2) / (tan * distance)
			// : DrawHeight       = (PixelHeight / 2) * NormalizedHeight;
			var height = (Pixels.height / 2) / (tanVFov * dist);

			// Draw the pixel line
			var y1 = Pixels.height / 2 - height / 2;
			var y2 = Pixels.height / 2 + height / 2;
			for (var y = y1; y < y2; y++)
				Pixels.set(x, Math.floor(y), [0, 0, 0]);
		}*/
	}

	// Update the pixels
	Pixels.draw();
};

<|endoftext|>


<commit_before>"use strict";

var base = require("xbase"),
	tiptoe = require("tiptoe"),
	path = require("path"),
	fs = require("fs");

exports.render = render;
function render(basePath, name, data, options, cb)
{
	if(!cb)
	{
		cb = options;
		options = null;
	}

	options = options || {};

	var readDustFile = function(name, cb) { fs.readFile(path.join(basePath, name + (name.endsWith(".dust") ? "" : ".dust")), "utf8", cb); };

	var dust = require("dustjs-linkedin");

	if(options.disableCache)
		dust.config.cache = false;

	dust.helper = require("dustjs-helpers");
	dust.onLoad = readDustFile;

	tiptoe(
		function loadTemplate()
		{
			readDustFile(name, this);
		},
		function render(template)
		{
			dust.optimizers.format = function(ctx, node) { if(options.keepWhitespace) { return node; } };
			dust.renderSource(template, data, this);
		},
		function returnResult(err, result) { cb(err, result); }
	);
}
<commit_msg>Added a tolowercase filter<commit_after>"use strict";

var base = require("xbase"),
	tiptoe = require("tiptoe"),
	path = require("path"),
	fs = require("fs");

exports.render = render;
function render(basePath, name, data, options, cb)
{
	if(!cb)
	{
		cb = options;
		options = null;
	}

	options = options || {};

	var readDustFile = function(name, cb) { fs.readFile(path.join(basePath, name + (name.endsWith(".dust") ? "" : ".dust")), "utf8", cb); };

	var dust = require("dustjs-linkedin");

	if(options.disableCache)
		dust.config.cache = false;

	dust.filters.lowercase = function(value)
	{
		return typeof value==="string" ? value.toLowerCase() : value;
	};

	dust.helper = require("dustjs-helpers");
	dust.onLoad = readDustFile;

	tiptoe(
		function loadTemplate()
		{
			readDustFile(name, this);
		},
		function render(template)
		{
			dust.optimizers.format = function(ctx, node) { if(options.keepWhitespace) { return node; } };
			dust.renderSource(template, data, this);
		},
		function returnResult(err, result) { cb(err, result); }
	);
}
<|endoftext|>


<commit_before>function eForStep(arr, arrLen, i, callback) {
    if (i < arrLen) {
        let item = arr[i];
        callback(item);
        setTimeout(eForStep.bind(this, arr, arrLen, i + 1, callback));
    }
}
/**
 * For statement emulation to work with large arrays without event loop blocking.
 *
 * eFor(arr, function (item) {
 *    // do something with item
 * });
 *
 *
 * @param {Array} arr
 * @param {Function} callback
 */
function eFor(arr, callback) {
    let arrLen = arr.length;
	if (arrLen < 2) {
		callback(arr[0]);
		return;
	}
	eForStep(arr, arrLen, 0, callback);
}

export {eFor, eForStep};
<commit_msg>fixes<commit_after>function eForStep(arr, arrLen, i, callback) {
    if (i < arrLen) {
        let item = arr[i];
        callback(item);
        setTimeout(eForStep.bind(this, arr, arrLen, i + 1, callback), 0);
    }
}
/**
 * For statement emulation to work with large arrays without event loop blocking.
 *
 * eFor(arr, function (item) {
 *    // do something with item
 * });
 *
 *
 * @param {Array} arr
 * @param {Function} callback
 */
function eFor(arr, callback) {
    let arrLen = arr.length;
    if (arrLen < 2) {
        callback(arr[0]);
        return;
    }
    eForStep(arr, arrLen, 0, callback);
}

export {eFor, eForStep};
<|endoftext|>


<commit_before>// Load our modules
var fs = require('fs'),
  tabletojson = require('tabletojson'),
  json2csv = require('json2csv'),
  cheerio = require('cheerio'),
  colors = require('colors');

// Set defaults
var defaults = {
  "path" : "process",
  "dest" : "dest",
  "format" : "csv"
};

// Set theme for output
colors.setTheme({
  info: 'green',
  warn: 'yellow',
  debug: 'blue',
  error: 'red',
  data: 'grey'
});

// MARK : Main functions. Part of export
var convert = (path, dest, format, tableId) => {

  //If path is not given kick in defaults
  if(!path){
    path = __dirname+"\\"+defaults.path;
    console.log(("Warning: No path specified. Setting it to " + path).warn);
  }

  // Do the same for dest
  if(!dest){
    dest = __dirname+"\\"+defaults.dest;
    console.log(("Warning: No destination specified. Setting it to " + dest).warn);
  }

  // Set format type
  format = (!format) ? defaults.format : format;

  //Find or create path
  try {
    // Find
    fs.readdir(__dirname, function(err, files){
      if(err) { throw err };

      // Verify path
      var pathIsThere = files.filter(function(obj){
        return obj === path;
      });

      if(pathIsThere.length === 0){
        var err = "Path to process HTML files not there. Path is set to " + path;
        console.log((err).error);
        return;
      }

      // Verify dest
      var destIsThere = files.filter(function(obj){
        return obj === dest;
      });

      // If not found let us create
      if(destIsThere.length === 0){
        console.log("Creating destination folder".warn);

        try {
          fs.mkdirSync(dest);
        } catch(e) {
          var err = "Filesystem error: " + e;
          console.log((err).error);
        }
      }

      // Parse through each and find html file
      fs.readdir(path, function(err, files){

        var htmlfiles = files.filter(function(obj){
          return (obj.match(".html")  !== null);
        });

        // Process each HTML
        htmlfiles.forEach(function(file){

          var info = "Working on " + file;
          console.log((info).data);

          // Read file content
          try {
            var filePath = path + "\\"+ file;

            var p = new Promise((resolve, reject) => {
              fs.readFile(filePath,(err, html) => {

                if(err) { reject(err); }

                var tables = '',
                  tableIds = [];

                $ = cheerio.load(html);

                //Check if we should filter down based on ID.
                var filter = (typeof tableId !== 'undefined') ? "#" + tableId : 'table';

                // Try to grab each table using cheerio to get an ID for the filename. Filter HTML down to wanted tables.
                $(filter).each(function(i, element){
                  tableIds[i] = $(this).attr('id');
                  tables += $(this).parent().html();
                });

                var info = {
                  "tableIds" : tableIds,
                  "tables" : tables
                };

                resolve(info);
              });
            });

            //Convert and file to file
            p.then(function(info){

              var tablesAsJson = tabletojson.convert(info.tables);
              var status = "Found "+ tablesAsJson.length +" tables";
              console.log((status).data);

              //File to write
              tablesAsJson.forEach((table, index) => {

                if(format == 'csv'){
                  json2csv({ data: table}, function(err, csv) {
                      if(err) throw err;

                      var filePath = dest +"/"+info.tableIds[index]+".csv";

                      fs.writeFile(filePath, csv, (err) => {
                        if(err) throw err;

                        var status = "Successfully saved " + filePath;
                        console.log((status).info);
                      });
                  });
                } else {
                  filePath = dest +"/"+info.tableIds[index]+".json";

                  fs.writeFile(filePath, JSON.stringify(table), (err) => {
                    if (err) throw err;

                    var status = "Successfully saved " + filePath;
                    console.log((status).info);
                  });
                }
              });
            })
            .catch(function(e){
              //Catch for promise
              var err = "Error during converting : " + e;
              console.log((err).error);
            });

          } catch(e) {
            var err = "Error processing html file : " + e;
            console.log((err).error);
          }
        });
      });

    });
  } catch (e) {
    var err = "Error in convert: " + e;
    console.log((err).error);
  }
}

exports.convert = convert;

// MARK : Supportive functions

// MARK : Handle errors functions
function _userException(message){
  this.message = "User input error: " + message;
};

function _fsException(message){
  this.message = message;
  this.name = "Filesystem error: ";
};

function _webException(message){
  this.message = message;
  this.name = "Web connection error: ";
};
<commit_msg>Some refactoring to better organize the logic<commit_after>"use strict";

// Load our modules
var fs = require('fs'),
  tabletojson = require('tabletojson'),
  json2csv = require('json2csv'),
  cheerio = require('cheerio'),
  colors = require('colors');

// Set defaults
var defaults = {
  "path" : "process",
  "url" : "www.coolgithubprojects.com",
  "dest" : "dest",
  "format" : "csv"
};

// Set theme for output
colors.setTheme({
  info: 'green',
  warn: 'yellow',
  debug: 'blue',
  error: 'red',
  data: 'grey'
});

// MARK : Main functions. Part of export
var convert = (path, dest, format, tableId) => {

  // Validate our inputs
  var validate = new Promise((resolve, reject) => {
    let inputs = { "path" : path, "dest" : dest, "format" : format };

    _validateArguments(inputs, (options) => {
      if(options) {
        resolve(options);
      } else {
        reject("Unable to validate arguments");
      }
    });

  });

  // Validate paths
  validate.then((options) => {

    // Process
    var process = new Promise((resolve, reject) => {

      _validatePaths(options, (status) => {
        if(status){
          resolve(options);
        } else {
          reject("Unable to validate paths.");
        }
      });
    });

    // Process our data and save it
    process.then((options) => {
      _processData(options, (status) => {
        console.log("Last promise ", status);
      })
    },
    (error) => {
      let err = "Something went wrong during processing : " + error;
      console.log((err).error);
    });

  },
  (error) => {
    let err = "Something went wrong during validation : " + error;
    console.log((err).error);
  })
}

exports.convert = convert;

var convertUrl = (url, dest, tableId) {

}

exports.convertUrl = convertUrl

// MARK : Supportive functions
function _validateArguments(options, cb){
  // Validate and prepare our arguments

  //If path is not given kick in defaults
  if(!options.path){
    options.path = __dirname+"\\"+defaults.path;
    console.log(("Warning: No path specified. Setting it to " + options.path).warn);
  }

  // Do the same for dest
  if(!options.dest){
    options.dest = __dirname+"\\"+defaults.dest;
    console.log(("Warning: No destination specified. Setting it to " + options.dest).warn);
  }

  // Set format type
  options.format = (!options.format) ? defaults.format : options.format;
  cb(options);
}

function _validatePaths(options, cb){

  fs.readdir(__dirname, function(err, files){
    if(err) throw err;

    // Check if path exists if calling from convert
    if (options.path){
      // Verify path
      var pathIsThere = files.filter(function(obj){
        return obj === options.path;
      });

      if(pathIsThere.length === 0){
        var err = "Path to process HTML files not there. Path is set to " + options.path;
        console.log((err).error);
        cb(null);
      }
    }

    // Verify dest
    var destIsThere = files.filter(function(obj){
      return obj === options.dest;
    });

    // If not found let us create
    if(destIsThere.length === 0){
      console.log("Creating destination folder".warn);
      fs.mkdirSync(options.dest);
      cb("done");
    } else {
      cb("done");
    }
  });
}

function _processData(options, cb){

  // Parse through each and find html file
  fs.readdir(options.path, function(err, files){

    var htmlfiles = files.filter(function(obj){
      return (obj.match(".html")  !== null);
    });

    // Process each HTML
    htmlfiles.forEach(function(file){

      var info = "Working on " + file;
      var filePath = options.path + "\\"+ file;
      console.log((info).data);

      // Read file content
      fs.readFile(filePath,(err, html) => {

        if(err) throw err;

        var tables = '',
        tableIds = [];

        var $ = cheerio.load(html);

        //Check if we should filter down based on ID.
        var filter = (typeof options.tableId !== 'undefined') ? "#" + options.tableId : 'table';

        // Try to grab each table using cheerio to get an ID for the filename. Filter HTML down to wanted tables.
        $(filter).each(function(i, element){
          tableIds[i] = $(this).attr('id');
          tables += $(this).parent().html();
        });

        var tablesAsJson = tabletojson.convert(tables);
        var status = "Found "+ tablesAsJson.length +" tables";
        console.log((status).data);

        //File to write
        tablesAsJson.forEach((table, index) => {
          var filePath = options.dest +"/" // Reset

          if(options.format == 'csv'){
            json2csv({ data: table}, function(err, csv) {
              if(err) throw err;

              filePath += tableIds[index]+".csv";

              fs.writeFile(filePath, csv, (err) => {
                if(err) throw err;

                var status = "Successfully saved " + filePath;
                console.log((status).info);
              });
            });
          }
          else {
            filePath += tableIds[index]+".json";

            fs.writeFile(filePath, JSON.stringify(table), (err) => {
              if (err) throw err;

              var status = "Successfully saved " + filePath;
              console.log((status).info);
            });
          }
        });

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


<commit_before>ServerEval = {
	version: "0.3",
	results: function() {
		return ServerEval._results.find({}, {
			sort: {
				eval_time: -1
			}
		});
	},
	metadata: function() {
		return ServerEval._metadata.find();
	},
	eval: function(expr, package) {
		Meteor.call('serverEval/eval', expr, package);
	},
	clear: function() {
		Meteor.call('serverEval/clear');
	}
};

if (Meteor.isClient) {
	ServerEval._results = new Meteor.Collection("server-eval-results");
	Meteor.subscribe("server-eval-results");

	ServerEval._metadata = new Meteor.Collection("server-eval-metadata");
	Meteor.subscribe("server-eval-metadata");
}

if (Meteor.isServer) {
	ServerEval._results = new Meteor.Collection("server-eval-results", {
		connection: null // not persistent
	});
	Meteor.publish("server-eval-results", function() {
		return ServerEval.results();
	});

	ServerEval._metadata = new Meteor.Collection("server-eval-metadata", {
		connection: null // not persistent
	});
	Meteor.publish("server-eval-metadata", function() {
		return ServerEval.metadata();
	});

	Meteor.startup(function() {
		var packages = _.keys(Package);
		var supported_packages = _.filter(packages, function(pkg) {
			return !!findEval(pkg);
		});
		ServerEval._metadata.insert({
			version: ServerEval.version,
			packages: packages,
			supported_packages: supported_packages
		});
	});

	//create json from object, filters circular dependencies
	//and adds custom ____TYPE___ property
	var prettyJSON = function(obj) {
		var cache = [];
		var path = [];

		var addToCache = function(value) {
			cache.push({
				path: path.join('.'),
				value: value
			});
		};

		var cached = function(value) {
			return _.find(cache, function(obj) {
				return obj.value === value;
			});
		};

		var formatObject = function(src_obj) {
			var dst_obj = {};

			if (src_obj instanceof Error) {
				var stacktrace = src_obj.stack && src_obj.stack.split("\n") || [];
				dst_obj = {
					____TYPE____: '[Error]',
					err: src_obj.toString(),
					stack: stacktrace.slice(1)
				};
				return dst_obj;
			}

			if (_.isFunction(src_obj)) {
				src_obj = _.extend({}, src_obj);
				src_obj.____TYPE____ = "[Function]";
			}

			_.each(src_obj, function(value, key) {
				path.push(key);

				var _cached = cached(value);
				if (_cached) {
					//remove futures!? TODO consider
					if (key !== "future") {
						// Circular reference found
						dst_obj[key] = {
							____TYPE____: '[Circular]',
							path: _cached.path
						};
					}
				} else {
					if (_.isObject(value)) {
						addToCache(value);
						dst_obj[key] = formatObject(value);
					} else {
						dst_obj[key] = value;
					}
				}

				path.pop();
			});
			return dst_obj;
		};

		return formatObject(obj);
	};

	//checks if eval function in package scope available
	var findEval = function(package) {
		if (Package[package]) {
			var supported_package = _.find(_.values(Package[package]), function(exprt) {
				return !!exprt.__serverEval;
			});
			return supported_package && supported_package.__serverEval;
		}
	};

	Meteor.methods({
		'serverEval/eval': function(expr, package) {
			if (!expr || expr.length === 0) return;

			var eval_time = Date.now();
			var scope = "global";
			var result_json;
			try {
				var result_raw;
				var _eval = eval;
				if (Package[package]) {
					var scoped_eval = findEval(package);
					if (scoped_eval) {
						_eval = scoped_eval; //use scoped eval
						scope = package;
					} else {
						scope = "global[" + package + " not supported]";
					}
				} else if (package) {
					scope = "global[no " + package + " package]";
				}
				//run eval in package scope / fallback to eval in current scope (called global)
				result_raw = _eval(expr);
				result_json = prettyJSON(result_raw);
			} catch (e) {
				result_json = prettyJSON(e);
			}

			ServerEval._results.insert({
				eval_time: eval_time,
				expr: expr,
				scope: scope,
				result: result_json // && JSON.parse(result_json)
			});
		},
		'serverEval/clear': function() {
			ServerEval._results.remove({});
		}
	});
}<commit_msg>fix array format<commit_after>ServerEval = {
	version: "0.3",
	results: function() {
		return ServerEval._results.find({}, {
			sort: {
				eval_time: -1
			}
		});
	},
	metadata: function() {
		return ServerEval._metadata.find();
	},
	eval: function(expr, package) {
		Meteor.call('serverEval/eval', expr, package);
	},
	clear: function() {
		Meteor.call('serverEval/clear');
	}
};

if (Meteor.isClient) {
	ServerEval._results = new Meteor.Collection("server-eval-results");
	Meteor.subscribe("server-eval-results");

	ServerEval._metadata = new Meteor.Collection("server-eval-metadata");
	Meteor.subscribe("server-eval-metadata");
}

if (Meteor.isServer) {
	ServerEval._results = new Meteor.Collection("server-eval-results", {
		connection: null // not persistent
	});
	Meteor.publish("server-eval-results", function() {
		return ServerEval.results();
	});

	ServerEval._metadata = new Meteor.Collection("server-eval-metadata", {
		connection: null // not persistent
	});
	Meteor.publish("server-eval-metadata", function() {
		return ServerEval.metadata();
	});

	Meteor.startup(function() {
		var packages = _.keys(Package);
		var supported_packages = _.filter(packages, function(pkg) {
			return !!findEval(pkg);
		});
		ServerEval._metadata.insert({
			version: ServerEval.version,
			packages: packages,
			supported_packages: supported_packages
		});
	});

	//create json from object, filters circular dependencies
	//and adds custom ____TYPE___ property
	var prettyResult = function(obj) {
		var cache = [];
		var path = [];

		var addToCache = function(value) {
			cache.push({
				path: path.join('.'),
				value: value
			});
		};

		var cached = function(value) {
			return _.find(cache, function(obj) {
				return obj.value === value;
			});
		};

		var formatObject = function(src_obj) {
			var dst_obj = _.isArray(src_obj) ? [] : {};

			//Errors - format stacktrace and create new error object
			if (src_obj instanceof Error) {
				var stacktrace = src_obj.stack && src_obj.stack.split("\n") || [];
				dst_obj = {
					____TYPE____: '[Error]',
					err: src_obj.toString(),
					stack: stacktrace.slice(1)
				};
				return dst_obj;
			}

			//Functions - convert in object
			if (_.isFunction(src_obj)) {
				src_obj = _.extend({}, src_obj);
				src_obj.____TYPE____ = "[Function]";
			}

			//walk the object tree recursively
			_.each(src_obj, function(value, key) {
				path.push(key);

				var _cached = cached(value);
				if (_cached) {
					//remove futures!? TODO consider
					if (key !== "future") {
						// Circular reference found
						dst_obj[key] = {
							____TYPE____: '[Circular]',
							path: _cached.path
						};
					}
				} else {
					if (_.isObject(value)) {
						addToCache(value);
						dst_obj[key] = formatObject(value);
					} else {
						dst_obj[key] = value;
					}
				}

				path.pop();
			});
			return dst_obj;
		};

		return formatObject(obj);
	};

	//checks if eval function in package scope available
	var findEval = function(package) {
		if (Package[package]) {
			var supported_package = _.find(_.values(Package[package]), function(exprt) {
				return !!exprt.__serverEval;
			});
			return supported_package && supported_package.__serverEval;
		}
	};

	Meteor.methods({
		'serverEval/eval': function(expr, package) {
			if (!expr || expr.length === 0) return;

			var eval_time = Date.now();
			var scope = "global";
			var result;
			var _eval = eval;

			if (Package[package]) {
				var scoped_eval = findEval(package);
				if (scoped_eval) {
					_eval = scoped_eval; //use scoped eval
					scope = package;
				} else {
					scope = "global[" + package + " not supported]";
				}
			} else if (package) {
				scope = "global[no " + package + " package]";
			}

			try {
				//run eval in package scope / fallback to eval in current scope (called global)
				result = _eval(expr);
			} catch (e) {
				//error in eval
				result = e;
			}

			ServerEval._results.insert({
				eval_time: eval_time,
				expr: expr,
				scope: scope,
				result: prettyResult(result)
			});
		},
		'serverEval/clear': function() {
			ServerEval._results.remove({});
		}
	});
}<|endoftext|>


<commit_before>var Discord = require("discord.js");
var fs = require("fs");
var bot = new Discord.Client();
var readyCount = 0;
const prefix = "~";
const watchlist = fs.existsSync("./watchlist.json") ? "./watchlist.json" : creatwWatchlist();
const friendList = {};

bot.on("ready", () => {
    readyCount++;
    console.log("AFlaw is ready");
    console.log(`ID: ${bot.user.id}`);
    console.log(`Username: ${bot.user.username}`);
    // console.log(bot.presences);
    // console.log(bot.user.friends);
    checkFriendsStatuses(readyCount);
    // watchForFriendPresenceUpdate(readyCount);
});

process.on('SIGINT', () => {
    console.log("AFlaw is exiting");
});

bot.on("message", msg => {
    if (msg.author.id != bot.user.id || msg.content.substring(0, 1) != prefix) return;

    let messageContent = msg.content.split(" ");
    let command = messageContent[0].slice(prefix.length);
    let fromBotChannel = msg.channel.id == process.env.BOT_TEST_ID;

    if (command === "watch") {
        // console.log("Watch command");
        // console.log(`Is someone mentioned: ${msg.mentions.users.size!=0}`);
        // console.log(messageContent[1]);
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (!fromBotChannel) msg.delete();
        watch(msg.mentions.users.size!=0 ? user.username : user);
        bot.channels.get(process.env.BOT_TEST_ID).sendMessage(`Watching ${msg.mentions.users.size!=0 ? user.username : user}`)
        .then(message => {
            // console.log(`Sent watch message: ${message.content}`);
            message.delete();
        })
        .catch(console.error);
    }

    if (command === "unwatch") {
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (msg.channel.id != process.env.BOT_TEST_ID) msg.delete();
        unwatch(msg.mentions.users.size!=0 ? user.username : user);
        bot.channels.get(process.env.BOT_TEST_ID).sendMessage(`No longer watching ${msg.mentions.users.size!=0 ? user.username : user}`)
        .then(message => {
            // console.log(`Sent unwatch message: ${message.content}`);
            message.delete();
        })
        .catch(console.error);
    }

    if (command === "testDM") {
        bot.channels.get(process.env.BOT_TEST_ID).sendMessage("This is a test DM");
        // console.log(`Sending test message`);
    }
});

bot.on("presenceUpdate", (oldUser, newUser) => {
    try {
        // if (oldUser.client.user.id in bot.user.friends.keys) return;
        fs.readFile(watchlist, 'utf8', (err, data) => {
            if (err) throw err;
            var userObject = JSON.parse(data);
            if (userObject[oldUser.user.username.replace(/\s/g, '')]) {
                if ((oldUser.presence.status != "online") && (newUser.presence.status != "offline")) {
                    console.log(`presenceUpdate: ${oldUser.client.user.username}`);
                    sendStatusMessage(`${oldUser.user.username} is ${newUser.presence.status}`);
                }
            //     userObject[[oldUser.user.username.replace(/\s/g, '')]] = newUser.presence.status;
            //     fs.writeFile(watchlist, JSON.stringify(userObject), err => {
            //        if (err) console.log(err);
            //     });
            }
        });
    } catch (error) {
        console.error(error);
    }
});

bot.login(process.env.USER_TOKEN).catch(err => console.error(err));

function watch(user) {
    try {
        fs.readFile(watchlist, 'utf8', (err, data) => {
            if (err) throw err;
            let userObject = JSON.parse(data);
            userObject[user] = user;
            fs.writeFile(watchlist, JSON.stringify(userObject));
        });
    } catch (error) {
        console.error(error);
    }
}

function unwatch(user) {
    try {
        fs.readFile(watchlist, 'utf8', (err, data) => {
            if (err) throw err;
            let userObject = JSON.parse(data);
            delete userObject[user];
            fs.writeFile(watchlist, JSON.stringify(userObject));
        });
    } catch (error) {
        console.error(error);
    }
}

function checkFriendsStatuses(count) {
    if (count > 1) return;
    let friendPresences = bot.presences;
    // console.log(friendPresences.keyArray().toString());
    friendPresences.keyArray().forEach((val, index, presences) => {
        friendList[friendPresences.keyArray()[index]] = friendPresences.get(val)["status"];
    });
    console.log(friendList);
}

// function watchForFriendPresenceUpdate(count) {
//     if (count > 1) return;
//     while(true) {
//         // let friendPresences = bot.presences;
//         // let friends = bot.user.friends;
//         // let friendPresencesKeys = friendPresences.keys;
//         // let friendKeys = friends.keys;
//         // let guilds = bot.guilds;
//         for ()
//     }
// }

function sendStatusMessage(msg) {
     bot.channels.get(process.env.BOT_TEST_ID).sendMessage(msg)
    .then(message => {
        console.log(message.content);
         message.delete();
    })
    .catch(console.error);
}

function creatwWatchlist() {
    console.log(fs.existsSync("./watchlist.json"));
    fs.writeFile("./watchlist.json", "{}", (err) => {
        if (err) console.error(err);
        return "./watchlist.json";
    });
}<commit_msg>Let's try 'wx'<commit_after>var Discord = require("discord.js");
var fs = require("fs");
var bot = new Discord.Client();
var readyCount = 0;
var watchlist = fs.existsSync("./watchlist.json") ? "./watchlist.json" : creatwWatchlist();
const prefix = "~";
const friendList = {};

bot.on("ready", () => {
    readyCount++;
    console.log("AFlaw is ready");
    console.log(`ID: ${bot.user.id}`);
    console.log(`Username: ${bot.user.username}`);
    // console.log(bot.presences);
    // console.log(bot.user.friends);
    checkFriendsStatuses(readyCount);
    // watchForFriendPresenceUpdate(readyCount);
});

process.on('SIGINT', () => {
    console.log("AFlaw is exiting");
});

bot.on("message", msg => {
    if (msg.author.id != bot.user.id || msg.content.substring(0, 1) != prefix) return;

    let messageContent = msg.content.split(" ");
    let command = messageContent[0].slice(prefix.length);
    let fromBotChannel = msg.channel.id == process.env.BOT_TEST_ID;

    if (command === "watch") {
        // console.log("Watch command");
        // console.log(`Is someone mentioned: ${msg.mentions.users.size!=0}`);
        // console.log(messageContent[1]);
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (!fromBotChannel) msg.delete();
        watch(msg.mentions.users.size!=0 ? user.username : user);
        bot.channels.get(process.env.BOT_TEST_ID).sendMessage(`Watching ${msg.mentions.users.size!=0 ? user.username : user}`)
        .then(message => {
            // console.log(`Sent watch message: ${message.content}`);
            message.delete();
        })
        .catch(console.error);
    }

    if (command === "unwatch") {
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (msg.channel.id != process.env.BOT_TEST_ID) msg.delete();
        unwatch(msg.mentions.users.size!=0 ? user.username : user);
        bot.channels.get(process.env.BOT_TEST_ID).sendMessage(`No longer watching ${msg.mentions.users.size!=0 ? user.username : user}`)
        .then(message => {
            // console.log(`Sent unwatch message: ${message.content}`);
            message.delete();
        })
        .catch(console.error);
    }

    if (command === "testDM") {
        bot.channels.get(process.env.BOT_TEST_ID).sendMessage("This is a test DM");
        // console.log(`Sending test message`);
    }
});

bot.on("presenceUpdate", (oldUser, newUser) => {
    try {
        // if (oldUser.client.user.id in bot.user.friends.keys) return;
        fs.readFile(watchlist, 'utf8', (err, data) => {
            if (err) throw err;
            var userObject = JSON.parse(data);
            if (userObject[oldUser.user.username.replace(/\s/g, '')]) {
                if ((oldUser.presence.status != "online") && (newUser.presence.status != "offline")) {
                    console.log(`presenceUpdate: ${oldUser.client.user.username}`);
                    sendStatusMessage(`${oldUser.user.username} is ${newUser.presence.status}`);
                }
            //     userObject[[oldUser.user.username.replace(/\s/g, '')]] = newUser.presence.status;
            //     fs.writeFile(watchlist, JSON.stringify(userObject), err => {
            //        if (err) console.log(err);
            //     });
            }
        });
    } catch (error) {
        console.error(error);
    }
});

bot.login(process.env.USER_TOKEN).catch(err => console.error(err));

function watch(user) {
    try {
        fs.readFile(watchlist, 'utf8', (err, data) => {
            if (err) throw err;
            let userObject = JSON.parse(data);
            userObject[user] = user;
            fs.writeFile(watchlist, JSON.stringify(userObject));
        });
    } catch (error) {
        console.error(error);
    }
}

function unwatch(user) {
    try {
        fs.readFile(watchlist, 'utf8', (err, data) => {
            if (err) throw err;
            let userObject = JSON.parse(data);
            delete userObject[user];
            fs.writeFile(watchlist, JSON.stringify(userObject));
        });
    } catch (error) {
        console.error(error);
    }
}

function checkFriendsStatuses(count) {
    if (count > 1) return;
    let friendPresences = bot.presences;
    // console.log(friendPresences.keyArray().toString());
    friendPresences.keyArray().forEach((val, index, presences) => {
        friendList[friendPresences.keyArray()[index]] = friendPresences.get(val)["status"];
    });
    console.log(friendList);
}

// function watchForFriendPresenceUpdate(count) {
//     if (count > 1) return;
//     while(true) {
//         // let friendPresences = bot.presences;
//         // let friends = bot.user.friends;
//         // let friendPresencesKeys = friendPresences.keys;
//         // let friendKeys = friends.keys;
//         // let guilds = bot.guilds;
//         for ()
//     }
// }

function sendStatusMessage(msg) {
     bot.channels.get(process.env.BOT_TEST_ID).sendMessage(msg)
    .then(message => {
        console.log(message.content);
         message.delete();
    })
    .catch(console.error);
}

function creatwWatchlist() {
    console.log(fs.existsSync("./watchlist.json"));
    fs.writeFile("./watchlist.json", "{}", {flag: 'wx'},  (err) => {
        if (err) console.error(err);
        return "./watchlist.json";
    });
}<|endoftext|>


<commit_before>const {
  FuseBox,
  WebIndexPlugin,
  QuantumPlugin,
  EnvPlugin,
  CopyPlugin,
  JSONPlugin,
} = require('fuse-box');
const { spawn } = require('child_process');

const production = process.env.NODE_ENV === 'dev' ? false : true;

const getConfig = () => {
  return {
    homeDir: 'src/',
    cache: !production,
    output: `build/$name.js`,
    tsConfig: './tsconfig.json',
    useTypescriptCompiler: true,
    plugins: [
      EnvPlugin({ NODE_ENV: production ? 'production' : 'development' }),
      production &&
        QuantumPlugin({
          bakeApiIntoBundle: true,
          treeshake: true,
          uglify: {
            es6: true,
          },
        }),
    ],
    alias: {
      '@': '~/shared/',
      '@app': '~/renderer/app/',
      '@history': '~/renderer/history/',
      '@bookmarks': '~/renderer/bookmarks/',
      '@about': '~/renderer/about/',
      '@newtab': '~/renderer/newtab/',
      '~': '~/',
    },
  };
};

const getRendererConfig = () => {
  const cfg = Object.assign({}, getConfig(), {
    sourceMaps: true,
  });

  return cfg;
};

const getWebIndexPlugin = name => {
  return WebIndexPlugin({
    template: `static/pages/${name}.html`,
    path: production ? '.' : '/',
    target: `${name}.html`,
    bundles: [name],
    defer: true,
  });
};

const getCopyPlugin = () => {
  return CopyPlugin({
    files: ['*.woff2', '*.png', '*.svg'],
    dest: 'assets',
    resolve: production ? './assets' : '/assets',
  });
};

const mainProcess = () => {
  const fuse = FuseBox.init(getConfig('server'));

  const app = fuse.bundle('main').instructions(`> [main/index.ts]`);

  if (!production) {
    app.watch();
  }

  fuse.run();
};

const renderer = () => {
  const cfg = getRendererConfig();

  cfg.plugins.push(getWebIndexPlugin('app'));
  cfg.plugins.push(JSONPlugin());
  cfg.plugins.push(getCopyPlugin());

  const fuse = FuseBox.init(cfg);

  if (!production) {
    fuse.dev({ httpServer: true });
  }

  const app = fuse
    .bundle('app')
    .target('electron')
    .instructions('> [renderer/app/index.tsx]');

  if (!production) {
    app.hmr().watch();

    return fuse.run().then(() => {
      const child = spawn('npm', ['start'], {
        shell: true,
        stdio: 'inherit',
      });
    });
  }

  fuse.run();
};

const applet = () => {
  const cfg = getRendererConfig();

  cfg.plugins.push(getWebIndexPlugin('newtab'));
  cfg.plugins.push(JSONPlugin());
  cfg.plugins.push(getCopyPlugin());

  const fuse = FuseBox.init(cfg);

  if (!production) {
    fuse.dev({
      httpServer: true,
      port: 8080,
      socketURI: 'ws://localhost:8080',
    });
  }

  const newtab = fuse
    .bundle('newtab')
    .target('browser@es6')
    .instructions('> renderer/newtab/index.tsx');

  if (!production) {
    newtab.hmr().watch();
  }

  fuse.run();
};

const preload = name => {
  const fuse = FuseBox.init(getRendererConfig());

  const bundle = fuse
    .bundle(name)
    .target('electron')
    .instructions(`> [preloads/${name}.ts]`);

  if (!production) {
    bundle.watch();
    return;
  }

  fuse.run();
};

renderer();
preload('webview-preload');
preload('background-page-preload');
mainProcess();
applet();
<commit_msg>Try to fix config<commit_after>const {
  FuseBox,
  WebIndexPlugin,
  QuantumPlugin,
  EnvPlugin,
  CopyPlugin,
  JSONPlugin,
} = require('fuse-box');
const { spawn } = require('child_process');

const production = process.env.NODE_ENV === 'dev' ? false : true;

const getConfig = (target, name) => {
  return {
    homeDir: 'src/',
    cache: !production,
    target,
    output: `build/$name.js`,
    tsConfig: './tsconfig.json',
    useTypescriptCompiler: true,
    plugins: [
      EnvPlugin({ NODE_ENV: production ? 'production' : 'development' }),
      production &&
        QuantumPlugin({
          bakeApiIntoBundle: name,
          treeshake: true,
          removeExportsInterop: false,
          uglify: {
            es6: true,
          },
        }),
    ],
    alias: {
      '@': '~/shared/',
      '@app': '~/renderer/app/',
      '@history': '~/renderer/history/',
      '@bookmarks': '~/renderer/bookmarks/',
      '@about': '~/renderer/about/',
      '@newtab': '~/renderer/newtab/',
      '~': '~/',
    },
  };
};

const getRendererConfig = (target, name) => {
  const cfg = Object.assign({}, getConfig(target, name), {
    sourceMaps: true,
  });

  return cfg;
};

const getWebIndexPlugin = name => {
  return WebIndexPlugin({
    template: `static/pages/${name}.html`,
    path: production ? '.' : '/',
    target: `${name}.html`,
    bundles: [name],
  });
};

const getCopyPlugin = () => {
  return CopyPlugin({
    files: ['*.woff2', '*.png', '*.svg'],
    dest: 'assets',
    resolve: production ? './assets' : '/assets',
  });
};

const mainProcess = () => {
  const fuse = FuseBox.init(getConfig('server', 'main'));

  const app = fuse.bundle('main').instructions(`> [main/index.ts]`);

  if (!production) {
    app.watch();
  }

  fuse.run();
};

const renderer = () => {
  const cfg = getRendererConfig('electron', 'app');

  cfg.plugins.push(getWebIndexPlugin('app'));
  cfg.plugins.push(JSONPlugin());
  cfg.plugins.push(getCopyPlugin());

  const fuse = FuseBox.init(cfg);

  if (!production) {
    fuse.dev({ httpServer: true });
  }

  const app = fuse.bundle('app').instructions('> [renderer/app/index.tsx]');

  if (!production) {
    app.hmr().watch();

    return fuse.run().then(() => {
      const child = spawn('npm', ['start'], {
        shell: true,
        stdio: 'inherit',
      });
    });
  }

  fuse.run();
};

const applet = () => {
  const cfg = getRendererConfig('browser@es6');

  cfg.plugins.push(getWebIndexPlugin('newtab'));
  cfg.plugins.push(JSONPlugin());
  cfg.plugins.push(getCopyPlugin());

  const fuse = FuseBox.init(cfg);

  if (!production) {
    fuse.dev({ httpServer: true, port: 8080 });
  }

  const newtab = fuse
    .bundle('newtab')
    .instructions('> renderer/newtab/index.tsx');

  if (!production) {
    newtab.hmr().watch();
  }

  fuse.run();
};

const preload = name => {
  const fuse = FuseBox.init(getRendererConfig('electron', name));

  const bundle = fuse.bundle(name).instructions(`> [preloads/${name}.ts]`);

  if (!production) {
    bundle.watch();
    return;
  }

  fuse.run();
};

renderer();
preload('webview-preload');
preload('background-page-preload');
mainProcess();
applet();
<|endoftext|>


<commit_before>'use strict';

var a = {letter: 'A', letterScore: 1};
var b = {letter: 'B', letterScore: 3};
var c = {letter: 'C', letterScore: 3};
var d = {letter: 'D', letterScore: 2};
var e = {letter: 'E', letterScore: 1};
var f = {letter: 'F', letterScore: 4};
var g = {letter: 'G', letterScore: 2};
var h = {letter: 'H', letterScore: 4};
var i = {letter: 'I', letterScore: 1};
var j = {letter: 'J', letterScore: 8};
var k = {letter: 'K', letterScore: 5};
var l = {letter: 'L', letterScore: 1};
var m = {letter: 'M', letterScore: 3};
var n = {letter: 'N', letterScore: 1};
var o = {letter: 'O', letterScore: 1};
var p = {letter: 'P', letterScore: 3};
var q = {letter: 'Q', letterScore: 10};
var r = {letter: 'R', letterScore: 1};
var s = {letter: 'S', letterScore: 1};
var t = {letter: 'T', letterScore: 1};
var u = {letter: 'U', letterScore: 1};
var v = {letter: 'V', letterScore: 4};
var w = {letter: 'W', letterScore: 4};
var x = {letter: 'X', letterScore: 8};
var y = {letter: 'Y', letterScore: 4};
var z = {letter: 'Z', letterScore: 10};

var vowels = [a, e, i, o, u];

var consonants = [b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z];

var numberOfLettersSelected = 0;

var letterCount = 4;

var gameCount = 61;

var score = 0;

function startLetterTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    letterCount --;
    var letterCountDisplay = document.getElementById('letterTimer');
    letterCountDisplay.innerHTML = letterCount;
    if (letterCount <= 0) {
      clearInterval(counter);
      resetLetterTimer();
      upcomingBecomesCurrent();
      generateUpcomingLetters();
    }
  }
}

function resetLetterTimer() {
  letterCount = 4;
  startLetterTimer();
}

function startGameTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    gameCount --;
    var gameCountDisplay = document.getElementById('gameTimer');
    gameCountDisplay.innerHTML = gameCount;
    if (gameCount <= 0) {
      clearInterval(counter);
      //endGame();
    }
  }
}

function addListeners () {
  for (var i = 1; i < 6; i ++) {
    var cell = document.getElementById('current ' + i);
    cell.addEventListener('click', lockIn);
  }
}

function lockIn(event) {
  var which = event.target.getAttribute('currentColumn');
  var lock = document.getElementById('lockedIn ' + which);
  var upcomingPartner = document.getElementById('upcoming ' + which);
  lock.innerHTML = event.target.innerHTML;
  event.target.removeEventListener('click', lockIn);
  upcomingPartner.setAttribute('style', 'visibility: hidden;');
  event.target.setAttribute('style', 'visibility: hidden;');
  numberOfLettersSelected ++;
  if (numberOfLettersSelected === 5) {
    // endGame();
  } else {
    upcomingBecomesCurrent();
    generateUpcomingLetters();
    letterCount = 4;
  }
}

function calculateFinalScore() {
  score += gameCount;
  for (var i = 1; i < 6; i++) {
    var ithLetter = document.getElementById('lockedIn ' + i);
    score += ith;
  }
}

function endGame() {
  //add to the if condition that the word must be legal
  if (numberOfLettersSelected === 5) {
  }
}

function upcomingBecomesCurrent() {
  for (var i = 1; i < 6; i++) {
    var upcoming = document.getElementById('upcoming ' + i).innerHTML;
    var current = document.getElementById('current ' + i);
    current.innerHTML = upcoming;
  }
}

function generateUpcomingLetters() {
  for (var i = 1; i < 6; i++) {
    var cell = document.getElementById('upcoming ' + i);
    cell.innerHTML = generateRandomLetter();
  }
}

function generateRandomLetter() {
  var vowelOrConsonant = Math.floor(Math.random() * 5);
  if (vowelOrConsonant <= 1) {
    var randomVowel = Math.floor(Math.random() * vowels.length);
    return vowels[randomVowel].letter;
  } else {
    var randomConsonant = Math.floor(Math.random() * consonants.length);
    return consonants[randomConsonant].letter;
  }
}

generateUpcomingLetters();

addListeners();

startLetterTimer();

startGameTimer();
<commit_msg>after 5 clicks or when the timer runs out, the game ends, and will only generate a score if the user has followed the rules<commit_after>'use strict';

var a = {letter: 'A', letterScore: 1};
var b = {letter: 'B', letterScore: 3};
var c = {letter: 'C', letterScore: 3};
var d = {letter: 'D', letterScore: 2};
var e = {letter: 'E', letterScore: 1};
var f = {letter: 'F', letterScore: 4};
var g = {letter: 'G', letterScore: 2};
var h = {letter: 'H', letterScore: 4};
var i = {letter: 'I', letterScore: 1};
var j = {letter: 'J', letterScore: 8};
var k = {letter: 'K', letterScore: 5};
var l = {letter: 'L', letterScore: 1};
var m = {letter: 'M', letterScore: 3};
var n = {letter: 'N', letterScore: 1};
var o = {letter: 'O', letterScore: 1};
var p = {letter: 'P', letterScore: 3};
var q = {letter: 'Q', letterScore: 10};
var r = {letter: 'R', letterScore: 1};
var s = {letter: 'S', letterScore: 1};
var t = {letter: 'T', letterScore: 1};
var u = {letter: 'U', letterScore: 1};
var v = {letter: 'V', letterScore: 4};
var w = {letter: 'W', letterScore: 4};
var x = {letter: 'X', letterScore: 8};
var y = {letter: 'Y', letterScore: 4};
var z = {letter: 'Z', letterScore: 10};

var allLetters = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z];

var vowels = [a, e, i, o, u];

var consonants = [b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z];

var numberOfLettersSelected = 0;

var letterCount = 4;

var gameCount = 61;

var score = 0;

function startLetterTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    letterCount --;
    var letterCountDisplay = document.getElementById('letterTimer');
    letterCountDisplay.innerHTML = letterCount;
    if (letterCount <= 0) {
      clearInterval(counter);
      resetLetterTimer();
      upcomingBecomesCurrent();
      generateUpcomingLetters();
    }
  }
}

function resetLetterTimer() {
  letterCount = 4;
  startLetterTimer();
}

function startGameTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    gameCount --;
    var gameCountDisplay = document.getElementById('gameTimer');
    gameCountDisplay.innerHTML = gameCount;
    if (gameCount <= 0) {
      clearInterval(counter);
      endGame();
    }
  }
}

function addListeners () {
  for (var i = 1; i < 6; i ++) {
    var cell = document.getElementById('current ' + i);
    cell.addEventListener('click', lockIn);
  }
}

function lockIn(event) {
  var which = event.target.getAttribute('currentColumn');
  var lock = document.getElementById('lockedIn ' + which);
  var upcomingPartner = document.getElementById('upcoming ' + which);
  lock.innerHTML = event.target.innerHTML;
  event.target.removeEventListener('click', lockIn);
  upcomingPartner.setAttribute('style', 'visibility: hidden;');
  event.target.setAttribute('style', 'visibility: hidden;');
  numberOfLettersSelected ++;
  if (numberOfLettersSelected === 5) {
    endGame();
  } else {
    upcomingBecomesCurrent();
    generateUpcomingLetters();
    letterCount = 4;
  }
}

function calculateFinalScore() {
  score += gameCount;
  for (var i = 1; i < 6; i++) {
    var ithLetter = document.getElementById('lockedIn ' + i).innerHTML;
    for (var j = 0; j < 26; j++) {
      if (allLetters[j].letter === ithLetter) {
        score += allLetters[j].letterScore;
      }
    }
  }
}

function endGame() {
  //add to the if condition that the word must be legal
  if (numberOfLettersSelected === 5) {
    calculateFinalScore();
  }
}

function upcomingBecomesCurrent() {
  for (var i = 1; i < 6; i++) {
    var upcoming = document.getElementById('upcoming ' + i).innerHTML;
    var current = document.getElementById('current ' + i);
    current.innerHTML = upcoming;
  }
}

function generateUpcomingLetters() {
  for (var i = 1; i < 6; i++) {
    var cell = document.getElementById('upcoming ' + i);
    cell.innerHTML = generateRandomLetter();
  }
}

function generateRandomLetter() {
  var vowelOrConsonant = Math.floor(Math.random() * 5);
  if (vowelOrConsonant <= 1) {
    var randomVowel = Math.floor(Math.random() * vowels.length);
    return vowels[randomVowel].letter;
  } else {
    var randomConsonant = Math.floor(Math.random() * consonants.length);
    return consonants[randomConsonant].letter;
  }
}

generateUpcomingLetters();

addListeners();

startLetterTimer();

startGameTimer();
<|endoftext|>


<commit_before>'use strict';

var a = {letter: 'A', letterScore: 1};
var b = {letter: 'B', letterScore: 3};
var c = {letter: 'C', letterScore: 3};
var d = {letter: 'D', letterScore: 2};
var e = {letter: 'E', letterScore: 1};
var f = {letter: 'F', letterScore: 4};
var g = {letter: 'G', letterScore: 2};
var h = {letter: 'H', letterScore: 4};
var i = {letter: 'I', letterScore: 1};
var j = {letter: 'J', letterScore: 8};
var k = {letter: 'K', letterScore: 5};
var l = {letter: 'L', letterScore: 1};
var m = {letter: 'M', letterScore: 3};
var n = {letter: 'N', letterScore: 1};
var o = {letter: 'O', letterScore: 1};
var p = {letter: 'P', letterScore: 3};
var q = {letter: 'Q', letterScore: 10};
var r = {letter: 'R', letterScore: 1};
var s = {letter: 'S', letterScore: 1};
var t = {letter: 'T', letterScore: 1};
var u = {letter: 'U', letterScore: 1};
var v = {letter: 'V', letterScore: 4};
var w = {letter: 'W', letterScore: 4};
var x = {letter: 'X', letterScore: 8};
var y = {letter: 'Y', letterScore: 4};
var z = {letter: 'Z', letterScore: 10};

var allLetters = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z];

var vowels = [a, e, i, o, u];

var consonants = [b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z];

var numberOfLettersSelected = 0;

var letterCount = 4;

var gameCount = 61;

var score = 0;

var winners = [];

function startLetterTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    letterCount --;
    var letterCountDisplay = document.getElementById('letterTimer');
    letterCountDisplay.innerHTML = letterCount;
    if (letterCount <= 0) {
      clearInterval(counter);
      resetLetterTimer();
      upcomingBecomesCurrent();
      generateUpcomingLetters();
    }
  }
}

function resetLetterTimer() {
  letterCount = 4;
  startLetterTimer();
}

function startGameTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    gameCount --;
    var gameCountDisplay = document.getElementById('gameTimer');
    gameCountDisplay.innerHTML = gameCount;
    if (gameCount <= 0) {
      clearInterval(counter);
      endGame();
    }
  }
}

function addListeners () {
  for (var i = 1; i < 6; i ++) {
    var cell = document.getElementById('current ' + i);
    cell.addEventListener('click', lockIn);
  }
}

function lockIn(event) {
  var which = event.target.getAttribute('currentColumn');
  var lock = document.getElementById('lockedIn ' + which);
  var upcomingPartner = document.getElementById('upcoming ' + which);
  lock.innerHTML = event.target.innerHTML;
  event.target.removeEventListener('click', lockIn);
  upcomingPartner.setAttribute('style', 'visibility: hidden;');
  event.target.setAttribute('style', 'visibility: hidden;');
  numberOfLettersSelected ++;
  if (numberOfLettersSelected === 5) {
    endGame();
  } else {
    upcomingBecomesCurrent();
    generateUpcomingLetters();
    letterCount = 4;
  }
}

function calculateFinalScore() {
  score += gameCount;
  for (var i = 1; i < 6; i++) {
    var ithLetter = document.getElementById('lockedIn ' + i).innerHTML;
    for (var j = 0; j < 26; j++) {
      if (allLetters[j].letter === ithLetter) {
        score += allLetters[j].letterScore;
      }
    }
  }
}

function endGame() {
  var lett = document.getElementById('letterTimer');
  lett.setAttribute('style', 'visibility: hidden;');
  var game = document.getElementById('gameTimer');
  game.setAttribute('style', 'visibility: hidden;');
  letterCount = 1000;
  gameCount = 1000;
  //add to the if condition that the word must be legal
  if (numberOfLettersSelected === 5) {
    calculateFinalScore();
  }
}

function upcomingBecomesCurrent() {
  for (var i = 1; i < 6; i++) {
    var upcoming = document.getElementById('upcoming ' + i).innerHTML;
    var current = document.getElementById('current ' + i);
    current.innerHTML = upcoming;
  }
}

function generateUpcomingLetters() {
  for (var i = 1; i < 6; i++) {
    var cell = document.getElementById('upcoming ' + i);
    cell.innerHTML = generateRandomLetter();
  }
}

function generateRandomLetter() {
  var vowelOrConsonant = Math.floor(Math.random() * 5);
  if (vowelOrConsonant <= 1) {
    var randomVowel = Math.floor(Math.random() * vowels.length);
    return vowels[randomVowel].letter;
  } else {
    var randomConsonant = Math.floor(Math.random() * consonants.length);
    return consonants[randomConsonant].letter;
  }
}
function makePlayerObject(){
  var userNameList = JSON.parse(localStorage.nameArray);
  var playerName = [userNameList.length - 1];
  if (localStorage.winners){
    winners = JSON.parse(localStorage.winners);
  }

  function Newplayer(playerName, score){
    this.userName = playerName;
    this.score = score;
    winners.push(this);
  }
  localStorage.winners = JSON.stringify(winners);
}

generateUpcomingLetters();

addListeners();

startLetterTimer();

startGameTimer();
<commit_msg>created a player object and refernces the player name and score in game.js page<commit_after>'use strict';

var a = {letter: 'A', letterScore: 1};
var b = {letter: 'B', letterScore: 3};
var c = {letter: 'C', letterScore: 3};
var d = {letter: 'D', letterScore: 2};
var e = {letter: 'E', letterScore: 1};
var f = {letter: 'F', letterScore: 4};
var g = {letter: 'G', letterScore: 2};
var h = {letter: 'H', letterScore: 4};
var i = {letter: 'I', letterScore: 1};
var j = {letter: 'J', letterScore: 8};
var k = {letter: 'K', letterScore: 5};
var l = {letter: 'L', letterScore: 1};
var m = {letter: 'M', letterScore: 3};
var n = {letter: 'N', letterScore: 1};
var o = {letter: 'O', letterScore: 1};
var p = {letter: 'P', letterScore: 3};
var q = {letter: 'Q', letterScore: 10};
var r = {letter: 'R', letterScore: 1};
var s = {letter: 'S', letterScore: 1};
var t = {letter: 'T', letterScore: 1};
var u = {letter: 'U', letterScore: 1};
var v = {letter: 'V', letterScore: 4};
var w = {letter: 'W', letterScore: 4};
var x = {letter: 'X', letterScore: 8};
var y = {letter: 'Y', letterScore: 4};
var z = {letter: 'Z', letterScore: 10};

var allLetters = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z];

var vowels = [a, e, i, o, u];

var consonants = [b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z];

var numberOfLettersSelected = 0;

var letterCount = 4;

var gameCount = 61;

var score = 0;

var winners = [];

function startLetterTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    letterCount --;
    var letterCountDisplay = document.getElementById('letterTimer');
    letterCountDisplay.innerHTML = letterCount;
    if (letterCount <= 0) {
      clearInterval(counter);
      resetLetterTimer();
      upcomingBecomesCurrent();
      generateUpcomingLetters();
    }
  }
}

function resetLetterTimer() {
  letterCount = 4;
  startLetterTimer();
}

function startGameTimer() {

  var counter = setInterval(timer, 1000);

  function timer() {
    gameCount --;
    var gameCountDisplay = document.getElementById('gameTimer');
    gameCountDisplay.innerHTML = gameCount;
    if (gameCount <= 0) {
      clearInterval(counter);
      endGame();
    }
  }
}

function addListeners () {
  for (var i = 1; i < 6; i ++) {
    var cell = document.getElementById('current ' + i);
    cell.addEventListener('click', lockIn);
  }
}

function lockIn(event) {
  var which = event.target.getAttribute('currentColumn');
  var lock = document.getElementById('lockedIn ' + which);
  var upcomingPartner = document.getElementById('upcoming ' + which);
  lock.innerHTML = event.target.innerHTML;
  event.target.removeEventListener('click', lockIn);
  upcomingPartner.setAttribute('style', 'visibility: hidden;');
  event.target.setAttribute('style', 'visibility: hidden;');
  numberOfLettersSelected ++;
  if (numberOfLettersSelected === 5) {
    endGame();
  } else {
    upcomingBecomesCurrent();
    generateUpcomingLetters();
    letterCount = 4;
  }
}

function calculateFinalScore() {
  score += gameCount;
  for (var i = 1; i < 6; i++) {
    var ithLetter = document.getElementById('lockedIn ' + i).innerHTML;
    for (var j = 0; j < 26; j++) {
      if (allLetters[j].letter === ithLetter) {
        score += allLetters[j].letterScore;
      }
    }
  }
}

function endGame() {
  var lett = document.getElementById('letterTimer');
  lett.setAttribute('style', 'visibility: hidden;');
  var game = document.getElementById('gameTimer');
  game.setAttribute('style', 'visibility: hidden;');
  letterCount = 1000;
  gameCount = 1000;
  //add to the if condition that the word must be legal
  if (numberOfLettersSelected === 5) {
    calculateFinalScore();
    makePlayerObject();
  }
}

function upcomingBecomesCurrent() {
  for (var i = 1; i < 6; i++) {
    var upcoming = document.getElementById('upcoming ' + i).innerHTML;
    var current = document.getElementById('current ' + i);
    current.innerHTML = upcoming;
  }
}

function generateUpcomingLetters() {
  for (var i = 1; i < 6; i++) {
    var cell = document.getElementById('upcoming ' + i);
    cell.innerHTML = generateRandomLetter();
  }
}

function generateRandomLetter() {
  var vowelOrConsonant = Math.floor(Math.random() * 5);
  if (vowelOrConsonant <= 1) {
    var randomVowel = Math.floor(Math.random() * vowels.length);
    return vowels[randomVowel].letter;
  } else {
    var randomConsonant = Math.floor(Math.random() * consonants.length);
    return consonants[randomConsonant].letter;
  }
}
function makePlayerObject(){
  var userNameList = JSON.parse(localStorage.nameArray);
  var playerName = userNameList[userNameList.length - 1];
  if (localStorage.winners){
    winners = JSON.parse(localStorage.winners);
  }

  function Newplayer(playerName, score){
    this.userName = playerName;
    this.score = score;
    winners.push(this);
  }

  new Newplayer(playerName,score);
  localStorage.winners = JSON.stringify(winners);
}

generateUpcomingLetters();

addListeners();

startLetterTimer();

startGameTimer();
<|endoftext|>


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var replace = require('gulp-replace');
var wrap = require("gulp-wrap");
var declare = require('gulp-declare');
var watch = require('gulp-watch');
var connect = require('gulp-connect');

gulp.task('default', ['compile_template']);

var paths={
	 //不能以"./"开头否则gulp-watch会不能正常检查出文件的增加和减少
	tpl:'resources/tpl/*.html'
}
/*
 var cmd = require('run-cmd');
var sassCmd = cmd.build('compass')
  .flag('compile', 'compile') // creates a function all(), which will generate -a when called.
  .flag('watch', 'watch') // crates a function list(), which will generate -l when called.
  .default('watch');
*/

gulp.task('compile_template', function(done) {
  gulp.src(paths.tpl)
    .pipe(replace('\'','\\\''))
    .pipe(replace(/(\n|\r|(\r\n)|(\u0085)|(\u2028)|(\u2029))/g,''))
    .pipe(wrap("'<%= contents %>'"))
    .pipe(declare({
      namespace: 'MPDL.tpl',
      noRedeclare: true // 避免变量名重复
    }))
   .pipe(concat('tpl.js'))
    .pipe(gulp.dest('./resources/js'))
    .on('end', done);
});

gulp.task('watch', function() {
    watch(paths.tpl,function(){
        gulp.start('compile_template');
    });
    livereload = require('livereload');
    server = livereload.createServer();
    server.watch(__dirname +'/app');
});

gulp.task('sass', function() {
	sassCmd.compile('./resources/sass/theme.scss');
});
gulp.task('watch1', function() {
    watch(paths.tpl,function(){
        gulp.start('compile_template');
    });
});
gulp.task('server', function(next) {
    connect.server({
        root: '.'
    });
});

<commit_msg>可以分文件夹<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var replace = require('gulp-replace');
var wrap = require("gulp-wrap");
var declare = require('gulp-declare');
var watch = require('gulp-watch');
var connect = require('gulp-connect');

gulp.task('default', ['compile_template']);

var paths={
	 //不能以"./"开头否则gulp-watch会不能正常检查出文件的增加和减少
	tpl:['resources/tpl/*/*','resources/tpl/*']
}
/*
 var cmd = require('run-cmd');
var sassCmd = cmd.build('compass')
  .flag('compile', 'compile') // creates a function all(), which will generate -a when called.
  .flag('watch', 'watch') // crates a function list(), which will generate -l when called.
  .default('watch');
*/

gulp.task('compile_template', function(done) {
  gulp.src(paths.tpl)
    .pipe(replace('\'','\\\''))
    .pipe(replace(/(\n|\r|(\r\n)|(\u0085)|(\u2028)|(\u2029))/g,''))
    .pipe(wrap("'<%= contents %>'"))
    .pipe(declare({
      namespace: 'MPDL.tpl',
      noRedeclare: true // 避免变量名重复
    }))
   .pipe(concat('tpl.js'))
    .pipe(gulp.dest('./resources/js'))
    .on('end', done);
});

gulp.task('watch', function() {
    watch(paths.tpl,function(){
        gulp.start('compile_template');
    });
    livereload = require('livereload');
    server = livereload.createServer();
    server.watch(__dirname +'/app');
});

gulp.task('sass', function() {
	sassCmd.compile('./resources/sass/theme.scss');
});
gulp.task('watch1', function() {
    watch(paths.tpl,function(){
        gulp.start('compile_template');
    });
});
gulp.task('server', function(next) {
    connect.server({
        root: '.'
    });
});

<|endoftext|>