<commit_before>'use strict';
const path = require('path');
const fs = require('fs');
const pify = require('pify');
const moment = require('moment');

class SharedVariablesPlugin {
	constructor(config) {
		// Create SASS vars instead of a SASS map
		this.createVariables = !!config.createVariables;
		// Pre-process incoming files
		this.files = config.files.map(file => {
			return Object.assign(file, {
				modificationDate: null,
			});
		});

		this.debug = config.debug;

		// When first make has ran
		this.firstRun = true;
		// Generate new out file when in file is older then > 1000
		this.refreshOutFileTime = 1000;
	}

	/**
	 * Apply method is called by webpack
	 * @param compiler
	 */
	apply(compiler) {
		// Listen to the make state of the compiler
		compiler.plugin('make', (compilation, callback) => {
			this.setInFilesNewModificationDate()
				.then(() => this.getInFilesToProcess())
				.then(files => this.createOutFiles(files))
				.then(() => callback());
		});
	}

	/**
	 * Stats in files and checks there modification date
	 * @param files
	 * @returns {Promise.<*>}
	 */
	setInFilesNewModificationDate() {
		const promises = new Array(this.files.length);

		for (let i = 0; i < this.files.length; i++) {
			const file = this.files[i];
			promises[i] = this.statInFile(file);
		}

		return Promise.all(promises);
	}

	/**
	 * Returns files to be processed from JS to SCSS equivalent.
	 * @returns {Promise.<Array>}
	 */
	getInFilesToProcess() {
		const filesToProcess = [];

		for (let i = 0; i < this.files.length; i++) {
			const file = this.files[i];

			if (this.firstRun) {
				filesToProcess.push(file);
			} else {
				// Refresh out file when passed time is smaller then refreshOutFileTime
				if (moment.utc().diff(moment.utc(file.modificationDate)) < this.refreshOutFileTime) {
					filesToProcess.push(file);
				}
			}
		}

		this.firstRun = false;

		return Promise.resolve(filesToProcess);
	}

	/**
	 * Stats the in file
	 * @param file
	 */
	statInFile(file) {
		return pify(fs.stat)(path.resolve(file.in))
			.then((statResult) => {
				file.modificationDate = statResult.mtime;
				return file;
			})
			.catch(error => console.error(error));
	}

	/**
	 * Parses and evaluates the content that was read
	 * @param fileData
	 * @returns {*}
	 */
	parseInFile(fileData) {
		// Remove tabs, split on newlines
		let lines = fileData.replace(/\t/, '').split(/\n/);
		// Remove first line and last line of the file
		lines.splice(0,1);
		lines.splice(-1);
		// Join remaining lines
		lines = lines.join('');

		// Check if lines end with a bracket (When user saved without empty line on EOF)
		if (lines[lines.length - 1] === '}') {
			lines = `{${lines}`;
		} else {
			lines = `{${lines}}`;
		}

		let compiledSource = null;

		try {
			// Danger danger high voltage (Compile into object)
			compiledSource = eval(`'use strict'; const compile = ${lines}; compile`);
		}
		catch(error) {
			if (this.debug) {
				console.error(error);
			}
		}

		return compiledSource;
	}

	/**
	 * Generates source code for scss file based on compiledSource
	 * @param compiledSource
	 * @returns {string}
	 */
	generateScss(compiledSource, fileInName, fileOutName) {
		if( compiledSource === null || typeof compiledSource !== 'object') {
			console.error(`[${fileInName}] Cannot generate outFile. Something seems wrong with the compiled source...`);
			return;
		}

		if(this.createVariables) {
			return Object.keys(compiledSource).map(key => `$${key}: ${compiledSource[key]};`).join("\n");
		}

		const mapName = fileOutName.split(/\./).shift();

		const prepend = `$${mapName}: (\n`;
		const content = Object.keys(compiledSource)
			.map(key => `\t${key.toUpperCase()}: '${compiledSource[key]}',`)
			.join("\n");
		const append = '\n);';

		return `${prepend}${content}${append}`;
	}

	/**
	 * Iterates through all files and processes them to create the out files
	 * @param files
	 * @returns {Promise.<*>}
	 */
	createOutFiles(files) {
		const promises = new Array(files.length);
		const getFileName = (fileName) => fileName.split(/\//).pop();

		for (let i = 0; i < files.length; i++) {
			const file = files[i];
			promises[i] = pify(fs.readFile)(path.resolve(file.in), 'utf-8')
				.then((fileData) => this.parseInFile(fileData))
				.then(compiledJs => this.generateScss(compiledJs, getFileName(file.in), getFileName(file.out)))
				.then(scssSource => this.writeOutFile(scssSource, file.out))
				.catch(error => console.error(error));
		}

		return Promise.all(promises);
	}

	/**
	 * Writes the SCSS file
	 * @param scssSource
	 * @param outFile
	 */
	writeOutFile(scssSource, outFile) {
		return pify(fs.writeFile)(path.resolve(outFile), scssSource, 'utf8');
	}
}

module.exports = SharedVariablesPlugin;
<commit_msg>Remove moment as dependency, change logic for detecting file changes<commit_after>'use strict';
const path = require('path');
const fs = require('fs');
const pify = require('pify');

class SharedVariablesPlugin {
	constructor(config) {
		// Create SASS vars instead of a SASS map
		this.createVariables = !!config.createVariables;
		// Pre-process incoming files
		this.files = config.files.map(file => {
			return Object.assign(file, {
				modificationDate: null,
			});
		});

		this.debug = config.debug;
	}

	/**
	 * Apply method is called by webpack
	 * @param compiler
	 */
	apply(compiler) {
		// Listen to the make state of the compiler
		compiler.plugin('make', (compilation, callback) => {
			this.getInFilesToProcess()
				.then(files => this.createOutFiles(files.filter(file => !!file)))
				.then(() => callback());
		});
	}

	/**
	 * Returns files to be processed from JS to SCSS equivalent.
	 * @returns {Promise.<Array>}
	 */
	getInFilesToProcess() {
		const filesToProcess = [];
		const promises = new Array(this.files.length);

		for (let i = 0; i < this.files.length; i++) {
			const file = this.files[i];

			promises[i] = this.statInFile(file).then(mtime => {
				if( file.modificationDate !== mtime) {
					file.modificationDate = mtime;
					return file;
				}
			});
		}

		return Promise.all(promises);
	}

	/**
	 * Stats the in file
	 * @param file
	 */
	statInFile(file) {
		return pify(fs.stat)(path.resolve(file.in))
			.then((statResult) => {
				return statResult.mtime.getTime();
			})
			.catch(error => console.error(error));
	}

	/**
	 * Parses and evaluates the content that was read
	 * @param fileData
	 * @returns {*}
	 */
	parseInFile(fileData) {
		// Remove tabs, split on newlines
		let lines = fileData.replace(/\t/, '').split(/\n/);
		// Remove first line and last line of the file
		lines.splice(0,1);
		lines.splice(-1);
		// Join remaining lines
		lines = lines.join('');

		// Check if lines end with a bracket (When user saved without empty line on EOF)
		if (lines[lines.length - 1] === '}') {
			lines = `{${lines}`;
		} else {
			lines = `{${lines}}`;
		}

		let compiledSource = null;

		try {
			// Danger danger high voltage (Compile into object)
			compiledSource = eval(`'use strict'; const compile = ${lines}; compile`);
		}
		catch(error) {
			if (this.debug) {
				console.error(error);
			}
		}

		return compiledSource;
	}

	/**
	 * Generates source code for scss file based on compiledSource
	 * @param compiledSource
	 * @returns {string}
	 */
	generateScss(compiledSource, fileInName, fileOutName) {
		if( compiledSource === null || typeof compiledSource !== 'object') {
			console.error(`[${fileInName}] Cannot generate outFile. Something seems wrong with the compiled source...`);
			return;
		}

		if(this.createVariables) {
			return Object.keys(compiledSource).map(key => `$${key}: ${compiledSource[key]};`).join("\n");
		}

		const mapName = fileOutName.split(/\./).shift();

		const prepend = `$${mapName}: (\n`;
		const content = Object.keys(compiledSource)
			.map(key => `\t${key.toUpperCase()}: '${compiledSource[key]}',`)
			.join("\n");
		const append = '\n);';

		return `${prepend}${content}${append}`;
	}

	/**
	 * Iterates through all files and processes them to create the out files
	 * @param files
	 * @returns {Promise.<*>}
	 */
	createOutFiles(files) {
		if( files.length === 0) {
			return Promise.resolve();
		}

		const promises = new Array(files.length);
		const getFileName = (fileName) => fileName.split(/\//).pop();

		for (let i = 0; i < files.length; i++) {
			const file = files[i];
			promises[i] = pify(fs.readFile)(path.resolve(file.in), 'utf-8')
				.then((fileData) => this.parseInFile(fileData))
				.then(compiledJs => this.generateScss(compiledJs, getFileName(file.in), getFileName(file.out)))
				.then(scssSource => this.writeOutFile(scssSource, file.out))
				.catch(error => console.error(error));
		}

		return Promise.all(promises);
	}

	/**
	 * Writes the SCSS file
	 * @param scssSource
	 * @param outFile
	 */
	writeOutFile(scssSource, outFile) {
		return pify(fs.writeFile)(path.resolve(outFile), scssSource, 'utf8');
	}
}

module.exports = SharedVariablesPlugin;
<|endoftext|>


<commit_before>/**
* @param context {WebtaskContext}
*/
module.exports = function(context, cb) {
  cb(null, { hello: context.query.name || 'Anonymous' });
};

// test<commit_msg>Updating index.js<commit_after>/**
* @param context {WebtaskContext}
*/
module.exports = function(context, cb) {
  cb(null, { hello: context.query.name || 'Anonymous' });
};

// test <|endoftext|>


<commit_before>module.exports = require('./src/nap')<commit_msg>Remove index.js<commit_after><|endoftext|>


<commit_before>var inside = require('turf-inside');

/**
 * Calculates the average value of a field for points
 * within a set of polygons.
 *
 * @module turf/average
 * @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
 * @param {FeatureCollection} points a FeatureCollection of {@link Point} features
 * @param {string} field the field in the `points` features from which to pull values to average
 * @param {string} outputField the field in the `polygons` FeatureCollection to put results of the averages
 * @return {FeatureCollection} a FeatureCollection of {@link Polygon} features with the value of `outField` set to the calculated average
 * @example
 * var poly1 = turf.polygon([[[10.666351,59.890659],[10.666351,59.936784],[10.762481,59.936784],[10.762481,59.890659],[10.666351,59.890659]]]);
 * var poly2 = turf.polygon([[[10.764541,59.889281],[10.764541,59.937128],[10.866165,59.937128],[10.866165,59.889281],[10.764541,59.889281]]]);
 * var polygons = turf.featurecollection([poly1, poly2]);
 * var pt1 = turf.point(10.724029,59.926807, {population: 200});
 * var pt2 = turf.point(10.715789,59.904778, {population: 600});
 * var pt3 = turf.point(10.746002,59.908566, {population: 100});
 * var pt4 = turf.point(10.806427,59.908910, {population: 200});
 * var pt5 = turf.point(10.79544,59.931624, {population: 300});
 * var points = turf.featurecollection([pt1, pt2, pt3, pt4, pt5]);
 *
 * var averaged = turf.average(polygons, points, 'population', 'pop_avg');
 *
 * var result = turf.featurecollection(points.features.concat(averaged.features));
 *
 * //=result
 */
module.exports = function(polyFC, ptFC, inField, outField, done){
  polyFC.features.forEach(function(poly){
    if(!poly.properties) poly.properties = {};
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) values.push(pt.properties[inField]);
    });
    poly.properties[outField] = average(values);
  });

  return polyFC;
}

function average(values) {
  var sum = 0;
  for (var i = 0; i < values.length; i++) {
    sum += values[i];
  }
  return sum / values.length;
}
<commit_msg>Fix point form<commit_after>var inside = require('turf-inside');

/**
 * Calculates the average value of a field for points
 * within a set of polygons.
 *
 * @module turf/average
 * @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
 * @param {FeatureCollection} points a FeatureCollection of {@link Point} features
 * @param {string} field the field in the `points` features from which to pull values to average
 * @param {string} outputField the field in the `polygons` FeatureCollection to put results of the averages
 * @return {FeatureCollection} a FeatureCollection of {@link Polygon} features with the value of `outField` set to the calculated average
 * @example
 * var poly1 = turf.polygon([[[10.666351,59.890659],[10.666351,59.936784],[10.762481,59.936784],[10.762481,59.890659],[10.666351,59.890659]]]);
 * var poly2 = turf.polygon([[[10.764541,59.889281],[10.764541,59.937128],[10.866165,59.937128],[10.866165,59.889281],[10.764541,59.889281]]]);
 * var polygons = turf.featurecollection([poly1, poly2]);
 * var pt1 = turf.point([10.724029,59.926807], {population: 200});
 * var pt2 = turf.point([10.715789,59.904778], {population: 600});
 * var pt3 = turf.point([10.746002,59.908566], {population: 100});
 * var pt4 = turf.point([10.806427,59.908910], {population: 200});
 * var pt5 = turf.point([10.79544,59.931624], {population: 300});
 * var points = turf.featurecollection([pt1, pt2, pt3, pt4, pt5]);
 *
 * var averaged = turf.average(polygons, points, 'population', 'pop_avg');
 *
 * var result = turf.featurecollection(points.features.concat(averaged.features));
 *
 * //=result
 */
module.exports = function(polyFC, ptFC, inField, outField, done){
  polyFC.features.forEach(function(poly){
    if(!poly.properties) poly.properties = {};
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) values.push(pt.properties[inField]);
    });
    poly.properties[outField] = average(values);
  });

  return polyFC;
}

function average(values) {
  var sum = 0;
  for (var i = 0; i < values.length; i++) {
    sum += values[i];
  }
  return sum / values.length;
}
<|endoftext|>


<commit_before>var d3 = require('d3')
var hook = require('d3-utils/lifecycle')
var ƒ = require('d3-utils/get')

var objectEqual = require('object-equal')
var origRaf = require('raf')
var raf = require('auto-abort')(origRaf, function (f) { return origRaf.cancel(f) })

var KEY_CODES = {
  UP: 38,
  DOWN: 40,
  ENTER: 13,
  ESC: 27
}

function indexOf (arr, obj) {
  for (var i = 0; i < arr.length; i++) {
    if (objectEqual(obj, arr[i])) return i
  }

  return -1
}

module.exports = function (attrs, queryCallback) {
  var emitter = d3.dispatch('change', 'error')

  var selectedIndex = 0
  var suggestionsData = []
  var hideSuggestionsTimer
  var isOpen

  var element = document.createElement('section')
  var $elm = d3.select(element)
  var input = document.createElement('input')
  var $input = d3.select(input)
  var suggestions = document.createElement('ol')
  var $suggestions = d3.select(suggestions)

  element.appendChild(input)
  element.appendChild(suggestions)

  $elm.classed({
    'autocomplete': true,
    'control': true
  })

  $input
      .classed('input', true)
      .attr({
        type: 'search',
        name: 'autocomplete',
        autocomplete: 'off',
        placeholder: attrs.placeholder || 'Search...'
      })
      .on('focus.autocomplete', completeQuery)
      .on('blur.autocomplete', onBlur)
      .on('input.autocomplete', completeQuery)
      .on('keydown.autocomplete', keyboardRouter)
      .on('keyup.autocomplete', function () { d3.event.stopPropagation() })
      .on('keypress.autocomplete', function () { d3.event.stopPropagation() })

  $suggestions
      .classed('suggestions', true)
  close()

  return {
    element: element,
    on: on,

    add: add,
    delete: del,
    clear: clear,

    close: close,
    open: open,
    toggle: toggle,

    query: query
  }

  function completeQuery () {
    if (hideSuggestionsTimer) clearTimeout(hideSuggestionsTimer)
    $elm.classed('is-loading', true)

    queryCallback($input.property('value'), function (err, results) {
      $elm.classed('is-loading', false)
      if (err) return emitter.error(err)

      open()
      selectedIndex = 0

      suggestionsData = results

      raf(render)
    })
  }

  function render () {
    $suggestions.selectAll('li')
      .data(suggestionsData, JSON.stringify)
    .call(hook(
      function (enter) {
        enter.append('li')
            .on('click.autocomplete', change)
            .on('mouseover.autocomplete', function (_, i) {
              selectedIndex = i
              raf(render)
            })
            .text(ƒ('label'))
      },
      function (update) {
        update
            .classed('search-highlight', function (d, i) {
              return i === selectedIndex
            })
      },
      function (exit) {
        exit.remove()
      }
    ))
  }

  function onBlur () {
    if (hideSuggestionsTimer) return

    hideSuggestionsTimer = setTimeout(function () {
      close()
      if (input.value.length === 0) change({label: null})
      hideSuggestionsTimer = null
    }, 100)
  }

  function keyboardRouter () {
    d3.event.stopPropagation()
    var keyCode = d3.event.keyCode
    if (keyCode === KEY_CODES.ENTER) {
      if (isOpen) {
        change(suggestionsData[selectedIndex])
        d3.event.preventDefault()
        close()
      }

      return
    }

    if (keyCode === KEY_CODES.ESC) {
      selectedIndex = 0
      close()
      return
    }

    if (keyCode === KEY_CODES.UP) {
      d3.event.preventDefault()
      selectedIndex = mod(selectedIndex - 1, suggestionsData.length)
      open()
      raf(render)
      return
    }

    if (keyCode === KEY_CODES.DOWN) {
      d3.event.preventDefault()
      selectedIndex = mod(selectedIndex + 1, suggestionsData.length)
      open()
      raf(render)
      return
    }
  }

  function on () {
    return emitter.on.apply(emitter, arguments)
  }

  function add (obj, before) {
    if (Array.isArray(obj)) suggestionsData.splice.apply(suggestionsData, [indexOf(suggestionsData, before), 0].concat(obj))
    else suggestionsData.splice(indexOf(suggestionsData, before), 0, obj)
    raf(render)
  }

  function del (obj) {
    var idx = indexOf(suggestionsData, obj)

    if (idx > -1) {
      suggestionsData.splice(idx, 1)
      raf(render)
    }
  }

  function clear () {
    suggestionsData = []
    raf(render)
  }

  function close () {
    if (isOpen === false) return
    isOpen = false
    $suggestions.style('display', 'none')
  }

  function open () {
    if (isOpen === true) return
    isOpen = true
    $suggestions.style('display', null)
  }

  function toggle () {
    if (isOpen === true) return close()

    return open()
  }

  function change (d) {
    $input.property('value', d.label)
    emitter.change(d)
  }

  function query (val) {
    if (val == null) return input.value

    $input.property('value', val)
  }
}

function mod (n, p) {
  return ((n % p) + p) % p
}
<commit_msg>Fix ordering if the data is partially changed<commit_after>var d3 = require('d3')
var hook = require('d3-utils/lifecycle')
var ƒ = require('d3-utils/get')

var objectEqual = require('object-equal')
var origRaf = require('raf')
var raf = require('auto-abort')(origRaf, function (f) { return origRaf.cancel(f) })

var KEY_CODES = {
  UP: 38,
  DOWN: 40,
  ENTER: 13,
  ESC: 27
}

function indexOf (arr, obj) {
  for (var i = 0; i < arr.length; i++) {
    if (objectEqual(obj, arr[i])) return i
  }

  return -1
}

module.exports = function (attrs, queryCallback) {
  var emitter = d3.dispatch('change', 'error')

  var selectedIndex = 0
  var suggestionsData = []
  var hideSuggestionsTimer
  var isOpen

  var element = document.createElement('section')
  var $elm = d3.select(element)
  var input = document.createElement('input')
  var $input = d3.select(input)
  var suggestions = document.createElement('ol')
  var $suggestions = d3.select(suggestions)

  element.appendChild(input)
  element.appendChild(suggestions)

  $elm.classed({
    'autocomplete': true,
    'control': true
  })

  $input
      .classed('input', true)
      .attr({
        type: 'search',
        name: 'autocomplete',
        autocomplete: 'off',
        placeholder: attrs.placeholder || 'Search...'
      })
      .on('focus.autocomplete', completeQuery)
      .on('blur.autocomplete', onBlur)
      .on('input.autocomplete', completeQuery)
      .on('keydown.autocomplete', keyboardRouter)
      .on('keyup.autocomplete', function () { d3.event.stopPropagation() })
      .on('keypress.autocomplete', function () { d3.event.stopPropagation() })

  $suggestions
      .classed('suggestions', true)
  close()

  return {
    element: element,
    on: on,

    add: add,
    delete: del,
    clear: clear,

    close: close,
    open: open,
    toggle: toggle,

    query: query
  }

  function completeQuery () {
    if (hideSuggestionsTimer) clearTimeout(hideSuggestionsTimer)
    $elm.classed('is-loading', true)

    queryCallback($input.property('value'), function (err, results) {
      $elm.classed('is-loading', false)
      if (err) return emitter.error(err)

      open()
      selectedIndex = 0

      suggestionsData = results

      raf(render)
    })
  }

  function render () {
    $suggestions.selectAll('li')
      .data(suggestionsData, JSON.stringify)
    .call(hook(
      function (enter) {
        enter.append('li')
            .on('click.autocomplete', change)
            .on('mouseover.autocomplete', function (_, i) {
              selectedIndex = i
              raf(render)
            })
            .text(ƒ('label'))
      },
      function (update) {
        update
            .order()
            .classed('search-highlight', function (d, i) {
              return i === selectedIndex
            })
      },
      function (exit) {
        exit.remove()
      }
    ))
  }

  function onBlur () {
    if (hideSuggestionsTimer) return

    hideSuggestionsTimer = setTimeout(function () {
      close()
      if (input.value.length === 0) change({label: null})
      hideSuggestionsTimer = null
    }, 100)
  }

  function keyboardRouter () {
    d3.event.stopPropagation()
    var keyCode = d3.event.keyCode
    if (keyCode === KEY_CODES.ENTER) {
      if (isOpen) {
        change(suggestionsData[selectedIndex])
        d3.event.preventDefault()
        close()
      }

      return
    }

    if (keyCode === KEY_CODES.ESC) {
      selectedIndex = 0
      close()
      return
    }

    if (keyCode === KEY_CODES.UP) {
      d3.event.preventDefault()
      selectedIndex = mod(selectedIndex - 1, suggestionsData.length)
      open()
      raf(render)
      return
    }

    if (keyCode === KEY_CODES.DOWN) {
      d3.event.preventDefault()
      selectedIndex = mod(selectedIndex + 1, suggestionsData.length)
      open()
      raf(render)
      return
    }
  }

  function on () {
    return emitter.on.apply(emitter, arguments)
  }

  function add (obj, before) {
    if (Array.isArray(obj)) suggestionsData.splice.apply(suggestionsData, [indexOf(suggestionsData, before), 0].concat(obj))
    else suggestionsData.splice(indexOf(suggestionsData, before), 0, obj)
    raf(render)
  }

  function del (obj) {
    var idx = indexOf(suggestionsData, obj)

    if (idx > -1) {
      suggestionsData.splice(idx, 1)
      raf(render)
    }
  }

  function clear () {
    suggestionsData = []
    raf(render)
  }

  function close () {
    if (isOpen === false) return
    isOpen = false
    $suggestions.style('display', 'none')
  }

  function open () {
    if (isOpen === true) return
    isOpen = true
    $suggestions.style('display', null)
  }

  function toggle () {
    if (isOpen === true) return close()

    return open()
  }

  function change (d) {
    $input.property('value', d.label)
    emitter.change(d)
  }

  function query (val) {
    if (val == null) return input.value

    $input.property('value', val)
  }
}

function mod (n, p) {
  return ((n % p) + p) % p
}
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){

  userConnectedEvent();

  socket.on('chat message', function(data){
    socket.broadcast.emit('chat message', data);
  });
});

http.listen(process.env.PORT || 5000, function(){
  console.log('listening on *:' + process.env.PORT || 5000);
});

const userConnectedEvent = () => {
  socket.emit('chat message', {
      key: (new Date()).getTime(),
      sender: "Chat",
      content: "User connected.",
      power: 0
  })
}<commit_msg>OnConnectedEvent<commit_after>var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){

  userConnectedEvent();

  socket.on('chat message', function(data){
    socket.broadcast.emit('chat message', data);
  });
});

http.listen(process.env.PORT || 5000, function(){
  console.log('listening on *:' + process.env.PORT || 5000);
});

var userConnectedEvent = function(){
  socket.emit('chat message', {
      key: (new Date()).getTime(),
      sender: "Chat",
      content: "User connected.",
      power: 0
  })
}<|endoftext|>


<commit_before>(function() {
  'use strict';

  var ripper = require('./Rip'),
    fs = require('fs'),
    encoder = require('./Encode'),
    ui = require('bull-ui/app')({
      redis: {
        host: 'localhost',
        port: '6379'
      }
    }),
    Queue = require('bull');

  var port = process.env.PORT || 2000;
  ui.listen(port, function() {
    console.log('UI started listening on port', this.address().port);
  });

  var ripQ = Queue('disc ripping');
  var encodeQ = Queue('video encoding');

  encodeQ.add({
    type: './HandBrakeCLI',
    options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o',
    destination: '/mnt/temp'
  });

  ripQ.add({
    destination: '/mnt/temp'
  });

  encodeQ.process(function(job) {
    return encoder.encode(job);
  });

  if(fs.existsSync('/dev/sr0')) {
    //if a DVD device exists, then we can process the Ripping queue
    ripQ.process(function(job) {
      return ripper.rip(job);
    });
  } else {
    console.log("No DVD device found, not processing Ripping jobs.");
  }

}());
<commit_msg>Allow custom redis connection<commit_after>(function() {
  'use strict';

  var redishost = process.env.REDIS || 'localhost';
  var redisport = process.env.REDIS_PORT || 6379;

  var ripper = require('./Rip'),
    fs = require('fs'),
    encoder = require('./Encode'),
    ui = require('bull-ui/app')({
      redis: {
        host: redishost,
        port: redisport
      }
    }),
    Queue = require('bull');

  var port = process.env.PORT || 2000;
  ui.listen(port, function() {
    console.log('UI started listening on port', this.address().port);
  });

  var ripQ = Queue('disc ripping');
  var encodeQ = Queue('video encoding');

  encodeQ.add({
    type: './HandBrakeCLI',
    options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o',
    destination: '/mnt/temp'
  });

  ripQ.add({
    destination: '/mnt/temp'
  });

  encodeQ.process(function(job) {
    return encoder.encode(job);
  });

  if(fs.existsSync('/dev/sr0')) {
    //if a DVD device exists, then we can process the Ripping queue
    ripQ.process(function(job) {
      return ripper.rip(job);
    });
  } else {
    console.log("No DVD device found, not processing Ripping jobs.");
  }

}());
<|endoftext|>


<commit_before>'use strict';
const request = require('request');
const semver = require('semver');

const manager = require('bin-manager');

const BIN_PATH = 'bin';
const LATEST_ENDPOINT = 'https://arduino-cli.github.io/arduino-latest/VERSION';
const MIRRORS = [{
  os: 'win32',
  arch: 'x64',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-windows.zip',
  bin: 'arduino-{{version}}\\arduino_debug.exe'
}, {
  os: 'darwin',
  arch: 'x64',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-macosx.zip',
  bin: 'Arduino.app/Contents/MacOS/Arduino'
}, {
  os: 'linux',
  arch: 'x32',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-linux32.tar.xz',
  bin: 'arduino-{{version}}/arduino'
}, {
  os: 'linux',
  arch: 'x64',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-linux64.tar.xz',
  bin: 'arduino-{{version}}/arduino'
}, {
  os: 'linux',
  arch: 'arm',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-linuxarm.tar.xz',
  bin: 'arduino-{{version}}/arduino'
}];

/**
 * Initialize a new `Arduino`
 *
 * @param {Object} [opts]
 * @api public
 */

function arduino(opts) {
  const version = opts.version || 'latest';
  const binPath = opts.path || BIN_PATH;
  const binSlug = opts.tag ? ('-' + opts.tag) : '';
  let inited = false;
  let bin;

  /**
   * Runs the arduino binary
   *
   * @param {Array}    [argv]
   * @param {Function} callback
   * @api public
   */
  function run(argv, callback) {
    if (callback === undefined) {
      callback = argv;
      argv = [];
    }
    if (inited) {
      bin.run(argv, callback);
      return;
    }

    getSanitizedVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.run(argv, callback);
    });
  }

  /**
   * Load/download the current version of the binary
   *
   * @param {Function} callback
   * @api public
   */
  function load(callback) {
    if (inited) {
      bin.load(err => callback(err));
      return;
    }

    getSanitizedVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.load(err => callback(err));
    });
  }

  /**
   * Removes the current version of the binary
   *
   * @param  {Function} callback
   * @api public
   */
  function unload(callback) {
    if (inited) {
      bin.unload(err => callback(err));
      return;
    }

    getSanitizedVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.unload(err => callback(err));
    });
  }

  /**
   * Gets the version and the it sanitizes it
   *
   * @param  {Function} callback
   * @api private
   */
  function getSanitizedVersion(callback) {
    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      version = semver.clean(version);
      callback(null, version);
    });
  }

  /**
   * Gets the right version number when special values are passed as version
   *
   * @param  {Function} callback
   * @api private
   */
  function getFullVersion(callback) {
    if (version !== 'latest') {
      callback(null, version);
      return;
    }
    getLatestVersion(callback);
  }

  /**
   * Retrieves latest arduino ide version available
   *
   * @param  {Function} callback
   * @api private
  */
  function getLatestVersion(callback) {
    request(LATEST_ENDPOINT, (err, res, body) => {
      if (err || res.statusCode !== 200) {
        callback(err || 'error: ' + err.statusCode);
        return;
      }
      callback(null, body);
    });
  }

  /**
   * Initializes the binary mirrors
   *
   * @param {String} version
   * @api private
   */
  function init(version) {
    if (!version) {
      throw new Error('Non semver version provided');
    }
    if (semver.lt(version, '1.5.2')) {
      throw new Error('Arduino command line options are avaiable from the version 1.5.2');
    }
    bin = manager(binPath, 'arduino-' + version + binSlug);
    MIRRORS.forEach(mirror => {
      bin.src(mirror.uri.replace('{{version}}', version), mirror.os, mirror.arch);

      if (mirror.os === process.platform) {
        bin.use(mirror.bin.replace('{{version}}', version));
      }
    });

    inited = true;
  }

  /**
   *
   * @api public
   * @returns /path/to/bin
   */
  function binary() {
    return bin.bin();
  }

  return {
    run,
    load,
    unload,
    binary
  };
}

module.exports = arduino;
<commit_msg>Remove the first leading folder from the extracted binary<commit_after>'use strict';
const request = require('request');
const semver = require('semver');

const manager = require('bin-manager');

const BIN_PATH = 'bin';
const LATEST_ENDPOINT = 'https://arduino-cli.github.io/arduino-latest/VERSION';
const MIRRORS = [{
  os: 'win32',
  arch: 'x64',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-windows.zip',
  bin: 'arduino_debug.exe'
}, {
  os: 'darwin',
  arch: 'x64',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-macosx.zip',
  bin: 'Contents/MacOS/Arduino'
}, {
  os: 'linux',
  arch: 'x32',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-linux32.tar.xz',
  bin: 'arduino'
}, {
  os: 'linux',
  arch: 'x64',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-linux64.tar.xz',
  bin: 'arduino'
}, {
  os: 'linux',
  arch: 'arm',
  uri: 'https://downloads.arduino.cc/arduino-{{version}}-linuxarm.tar.xz',
  bin: 'arduino'
}];

/**
 * Initialize a new `Arduino`
 *
 * @param {Object} [opts]
 * @api public
 */

function arduino(opts) {
  const version = opts.version || 'latest';
  const binPath = opts.path || BIN_PATH;
  const binSlug = opts.tag ? ('-' + opts.tag) : '';
  let inited = false;
  let bin;

  /**
   * Runs the arduino binary
   *
   * @param {Array}    [argv]
   * @param {Function} callback
   * @api public
   */
  function run(argv, callback) {
    if (callback === undefined) {
      callback = argv;
      argv = [];
    }
    if (inited) {
      bin.run(argv, callback);
      return;
    }

    getSanitizedVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.run(argv, callback);
    });
  }

  /**
   * Load/download the current version of the binary
   *
   * @param {Function} callback
   * @api public
   */
  function load(callback) {
    if (inited) {
      bin.load({extract: true, strip: 1}, err => callback(err));
      return;
    }

    getSanitizedVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.load({extract: true, strip: 1}, err => callback(err));
    });
  }

  /**
   * Removes the current version of the binary
   *
   * @param  {Function} callback
   * @api public
   */
  function unload(callback) {
    if (inited) {
      bin.unload(err => callback(err));
      return;
    }

    getSanitizedVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      init(version);
      bin.unload(err => callback(err));
    });
  }

  /**
   * Gets the version and the it sanitizes it
   *
   * @param  {Function} callback
   * @api private
   */
  function getSanitizedVersion(callback) {
    getFullVersion((err, version) => {
      if (err) {
        callback(err);
        return;
      }
      version = semver.clean(version);
      callback(null, version);
    });
  }

  /**
   * Gets the right version number when special values are passed as version
   *
   * @param  {Function} callback
   * @api private
   */
  function getFullVersion(callback) {
    if (version !== 'latest') {
      callback(null, version);
      return;
    }
    getLatestVersion(callback);
  }

  /**
   * Retrieves latest arduino ide version available
   *
   * @param  {Function} callback
   * @api private
  */
  function getLatestVersion(callback) {
    request(LATEST_ENDPOINT, (err, res, body) => {
      if (err || res.statusCode !== 200) {
        callback(err || 'error: ' + err.statusCode);
        return;
      }
      callback(null, body);
    });
  }

  /**
   * Initializes the binary mirrors
   *
   * @param {String} version
   * @api private
   */
  function init(version) {
    if (!version) {
      throw new Error('Non semver version provided');
    }
    if (semver.lt(version, '1.5.2')) {
      throw new Error('Arduino command line options are avaiable from the version 1.5.2');
    }
    bin = manager(binPath, 'arduino-' + version + binSlug);
    MIRRORS.forEach(mirror => {
      bin.src(mirror.uri.replace('{{version}}', version), mirror.os, mirror.arch);

      if (mirror.os === process.platform) {
        bin.use(mirror.bin.replace('{{version}}', version));
      }
    });

    inited = true;
  }

  /**
   *
   * @api public
   * @returns /path/to/bin
   */
  function binary() {
    return bin.bin();
  }

  return {
    run,
    load,
    unload,
    binary
  };
}

module.exports = arduino;
<|endoftext|>


<commit_before>var Crafty = require('craftyjs');
var dat = require('exdat');

var assets = {
	"images" : "assets/notion_logo.png"
};

function init() {

	// setup crafty
	Crafty.init();
	Crafty.background('rgb(150,200,255)');
	Crafty.webgl.init();

	// setup gui
	var gui = new dat.GUI();

	// other basic stuff
	var ctx = Crafty.webgl.context
	var dims = { width: ctx.drawingBufferWidth, height: ctx.drawingBufferHeight };

	// logo
	var logo = Crafty.e('2D, WebGL, Image, Draggable, Gravity')
		.image('assets/notion_logo.png')
		.gravity('2D');
	  // .attr({x: dims.width/2-size/2, y: dims.height/2-size/2, w: size, h: size})

	// bottom platform
	var platform = Crafty.e('2D, WebGL, Color')
									.color(0, 255, 100, 1)
									.attr({x: 0, y: dims.height-5, w: dims.width, h: 10});

}

// load & go!
Crafty.load(assets, init);
<commit_msg>WIP. Breaking into scenes<commit_after>var Crafty = require('craftyjs');
var dat = require('exdat');

var assets = {
	"images" : "assets/notion_logo.png"
};

// var gui = new dat.GUI();

// loading scene
Crafty.defineScene("loading", function() {
	Crafty.background("#000");
  Crafty.e("2D, Canvas, Text")
	  .attr({ w: 100, h: 20, x: 150, y: 120 })
	  .text("Loading")
	  .textColor("#FFFFFF");
});

Crafty.defineScene("gravity",function() {
	Crafty.background("rgb(150,200,255)");

	Crafty.webgl.init();

	// other basic stuff
	var ctx = Crafty.webgl.context
	var dims = { width: ctx.drawingBufferWidth, height: ctx.drawingBufferHeight };

	// logo
	var logo = Crafty.e('2D, WebGL, Image, Draggable, Gravity')
		.image('assets/notion_logo.png')
		.gravity('2D');
	  // .attr({x: dims.width/2-size/2, y: dims.height/2-size/2, w: size, h: size})

	// bottom platform
	var platform = Crafty.e('2D, WebGL, Color')
									.color(0, 255, 100, 1)
									.attr({x: 0, y: dims.height-5, w: dims.width, h: 10});
});

// setup crafty
Crafty.init();
Crafty.enterScene("loading");

// load & go!
Crafty.load(assets, function() {
	Crafty.enterScene("gravity");
});
<|endoftext|>


<commit_before>/*!
 * base-task <https://github.com/node-base/base-task>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

module.exports = function(name, fn) {
  var isValid = require('is-valid-app');
  var composer = require('composer');

  if (typeof name === 'function') {
    fn = name;
    name = undefined;
  }

  return function baseTask(app) {
    if (!isValid(app, 'base-task')) return;

    // original constructor reference
    var ctor = this.constructor;
    composer.call(this, name);
    this.visit('define', composer.prototype);
    var self = this;
    var emit = this.emit;

    // fix build events
    this.on('starting', function(app, build) {
      build.status = 'starting';
      self.emit('build', build);
    });
    this.on('finished', function(app, build) {
      build.status = 'finished';
      self.emit('build', build);
    });

    // fix task events
    this.emit = function(key, val, task) {
      if (key === 'task' && typeof val === 'undefined' && task) {
        task.status = 'register';
        self.emit('task', task);
        return;
      }
      return emit.apply(self, arguments);
    };
    this.on('task:starting', function(app, task) {
      task.status = 'starting';
      self.emit('task', task);
    });
    this.on('task:finished', function(app, task) {
      task.status = 'finished';
      self.emit('task', task);
    });
    this.on('task', function() {
      console.log(arguments)
    });

    // restore original constructor
    this.constructor = ctor;
    return baseTask;
  };
};

<commit_msg>remove test code<commit_after>/*!
 * base-task <https://github.com/node-base/base-task>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

module.exports = function(name, fn) {
  var isValid = require('is-valid-app');
  var composer = require('composer');

  if (typeof name === 'function') {
    fn = name;
    name = undefined;
  }

  return function baseTask(app) {
    if (!isValid(app, 'base-task')) return;

    // original constructor reference
    var ctor = this.constructor;
    composer.call(this, name);
    this.visit('define', composer.prototype);
    var self = this;
    var emit = this.emit;

    // fix build events
    this.on('starting', function(app, build) {
      build.status = 'starting';
      self.emit('build', build);
    });
    this.on('finished', function(app, build) {
      build.status = 'finished';
      self.emit('build', build);
    });

    // fix task events
    this.emit = function(key, val, task) {
      if (key === 'task' && typeof val === 'undefined' && task) {
        task.status = 'register';
        self.emit('task', task);
        return;
      }
      return emit.apply(self, arguments);
    };
    this.on('task:starting', function(app, task) {
      task.status = 'starting';
      self.emit('task', task);
    });
    this.on('task:finished', function(app, task) {
      task.status = 'finished';
      self.emit('task', task);
    });

    // restore original constructor
    this.constructor = ctor;
    return baseTask;
  };
};

<|endoftext|>


<commit_before>'use strict';

const eachAsync = require('async-each-map');

module.exports.conf = {
  API_KEY: process.env.NTB_API_KEY,
  API_ENV: process.env.NTB_API_ENV || 'api',
  USER_AGENT: process.env.NTB_USER_AGENT || require('./package.json').version,
};

module.exports._requestDefaults = function reqestDefaults() {
  return require('request').defaults({
    baseUrl: 'http://' + module.exports.conf.API_ENV + '.nasjonalturbase.no/',
    headers: {
      'user-agent': module.exports.conf.USER_AGENT,
    },
    json: true,
    qs: {
      api_key: module.exports.conf.API_KEY,
    },
  });
};

let request = module.exports._requestDefaults();

[
  'aktiviteter',
  'bilder',
  'grupper',
  'områder',
  'steder',
  'turer',
].forEach(function typeForEach(type) {
  module.exports[type] = function typeAll(params, callback) {
    if (!callback) { return request.get({ url: encodeURIComponent(type), qs: params }); }
    request.get({ url: encodeURIComponent(type), qs: params }, callback);
  };

  module.exports[type].each = function typeEach(params, callback, done) {
    const query = params;

    query.skip = query.skip || 0;
    query.limit = query.limit || 50;
    query.sort = query.sort || '_id';

    const noSkip = !!query.__no_skip__;
    delete query.__no_skip__;

    module.exports[type](query, function typeCb(typeErr, res, body) {
      if (typeErr) { return done(typeErr); }

      eachAsync(body.documents, callback, function eachAsyncDone(eachErr) {
        if (eachErr) { return done(eachErr); }

        if (body.documents < query.limit) {
          return done(null);
        }

        if (!noSkip) {
          query.skip += query.limit;
        }

        module.exports[type].each(query, callback, done);
      });
    });
  };

  module.exports[type].post = function typePost(data, callback) {
    if (!callback) {
      return request.post({ url: encodeURIComponent(type), body: data });
    }

    request.post({ url: encodeURIComponent(type), body: data }, callback);
  };

  module.exports[type].get = function typeGet(id, callback) {
    if (!callback) {
      return request.get({ url: encodeURIComponent(type) + '/' + id });
    }

    request.get({ url: encodeURIComponent(type) + '/' + id }, callback);
  };

  module.exports[type].delete = function typeDelete(id, callback) {
    if (!callback) {
      return request.del({ url: encodeURIComponent(type) + '/' + id });
    }

    request.del({ url: encodeURIComponent(type) + '/' + id }, callback);
  };

  module.exports[type].put = function typePut(id, data, callback) {
    if (!callback) {
      return request.put({ url: encodeURIComponent(type) + '/' + id, body: data });
    }

    request.put({ url: encodeURIComponent(type) + '/' + id, body: data }, callback);
  };

  module.exports[type].patch = function typePatch(id, data, callback) {
    if (!callback) {
      return request.patch({ url: encodeURIComponent(type) + '/' + id, body: data });
    }

    request.patch({ url: encodeURIComponent(type) + '/' + id, body: data }, callback);
  };
});

module.exports.configure = function configure(obj) {
  Object.keys(obj).forEach(function objKeysForEach(key) {
    module.exports.conf[key] = obj[key];
  });

  // Generate a new request object
  request = module.exports._requestDefaults();
};

module.exports.util = {};

module.exports.util.attribution = function navngiving(type, doc, authors, license) {
  const licenses = new Map([
    ['CC BY 4.0', 'http://creativecommons.org/licenses/by/4.0/deed.no'],
    ['CC BY-SA 4.0', 'http://creativecommons.org/licenses/by-sa/4.0/deed.no'],
    ['CC BY-ND 4.0', 'http://creativecommons.org/licenses/by-nd/4.0/deed.no'],
    ['CC BY-NC 4.0', 'http://creativecommons.org/licenses/by-nc/4.0/deed.no'],
    ['CC BY-NC-SA 4.0', 'http://creativecommons.org/licenses/by-nc-sa/4.0/deed.no'],
    ['CC BY-NC-ND 4.0', 'http://creativecommons.org/licenses/by-nc-nd/4.0/deed.no'],
  ]);

  const docName = doc.navn ? doc.navn : 'Uten Navn';
  const docUrl = `http://www.ut.no/${type}/${doc._id}/`;

  let attribution = `"<a href="${docUrl}">${docName}</a>" av `;

  if (authors && authors instanceof Array) {
    attribution = attribution + authors.reduce((prev, author, i, a) => {
      let delim;

      if (prev) {
        delim = i < a.length - 1 ? ', ' : ' og ';
      } else {
        delim = '';
      }

      if (author.url) {
        return prev + delim + `<a href="${author.url}">${author.navn}</a>`;
      }

      return prev + delim + author.navn;
    }, '');
  } else if (typeof authors === 'string') {
    attribution = attribution + authors;
  } else {
    attribution = attribution + 'Ukjent';
  }

  if (licenses.has(license)) {
    return attribution + ` er lisensiert under <a href="${licenses.get(license)}">${license}</a>.`;
  }

  return attribution + ` er lisensiert under ${license}.`;
};
<commit_msg>fix(eslint): use template strings for string concatenation<commit_after>'use strict';

const eachAsync = require('async-each-map');

module.exports.conf = {
  API_KEY: process.env.NTB_API_KEY,
  API_ENV: process.env.NTB_API_ENV || 'api',
  USER_AGENT: process.env.NTB_USER_AGENT || require('./package.json').version,
};

module.exports._requestDefaults = function reqestDefaults() {
  return require('request').defaults({
    baseUrl: `http://${module.exports.conf.API_ENV}.nasjonalturbase.no/`,
    headers: {
      'user-agent': module.exports.conf.USER_AGENT,
    },
    json: true,
    qs: {
      api_key: module.exports.conf.API_KEY,
    },
  });
};

let request = module.exports._requestDefaults();

[
  'aktiviteter',
  'bilder',
  'grupper',
  'områder',
  'steder',
  'turer',
].forEach(function typeForEach(type) {
  module.exports[type] = function typeAll(params, callback) {
    if (!callback) { return request.get({ url: encodeURIComponent(type), qs: params }); }
    request.get({ url: encodeURIComponent(type), qs: params }, callback);
  };

  module.exports[type].each = function typeEach(params, callback, done) {
    const query = params;

    query.skip = query.skip || 0;
    query.limit = query.limit || 50;
    query.sort = query.sort || '_id';

    const noSkip = !!query.__no_skip__;
    delete query.__no_skip__;

    module.exports[type](query, function typeCb(typeErr, res, body) {
      if (typeErr) { return done(typeErr); }

      eachAsync(body.documents, callback, function eachAsyncDone(eachErr) {
        if (eachErr) { return done(eachErr); }

        if (body.documents < query.limit) {
          return done(null);
        }

        if (!noSkip) {
          query.skip += query.limit;
        }

        module.exports[type].each(query, callback, done);
      });
    });
  };

  module.exports[type].post = function typePost(data, callback) {
    if (!callback) {
      return request.post({ url: encodeURIComponent(type), body: data });
    }

    request.post({ url: encodeURIComponent(type), body: data }, callback);
  };

  module.exports[type].get = function typeGet(id, callback) {
    if (!callback) {
      return request.get({ url: `${encodeURIComponent(type)}/${id}` });
    }

    request.get({ url: `${encodeURIComponent(type)}/${id}` }, callback);
  };

  module.exports[type].delete = function typeDelete(id, callback) {
    if (!callback) {
      return request.del({ url: `${encodeURIComponent(type)}/${id}` });
    }

    request.del({ url: `${encodeURIComponent(type)}/${id}` }, callback);
  };

  module.exports[type].put = function typePut(id, data, callback) {
    if (!callback) {
      return request.put({ url: `${encodeURIComponent(type)}/${id}`, body: data });
    }

    request.put({ url: `${encodeURIComponent(type)}/${id}`, body: data }, callback);
  };

  module.exports[type].patch = function typePatch(id, data, callback) {
    if (!callback) {
      return request.patch({ url: `${encodeURIComponent(type)}/${id}`, body: data });
    }

    request.patch({ url: `${encodeURIComponent(type)}/${id}`, body: data }, callback);
  };
});

module.exports.configure = function configure(obj) {
  Object.keys(obj).forEach(function objKeysForEach(key) {
    module.exports.conf[key] = obj[key];
  });

  // Generate a new request object
  request = module.exports._requestDefaults();
};

module.exports.util = {};

module.exports.util.attribution = function navngiving(type, doc, authors, license) {
  const licenses = new Map([
    ['CC BY 4.0', 'http://creativecommons.org/licenses/by/4.0/deed.no'],
    ['CC BY-SA 4.0', 'http://creativecommons.org/licenses/by-sa/4.0/deed.no'],
    ['CC BY-ND 4.0', 'http://creativecommons.org/licenses/by-nd/4.0/deed.no'],
    ['CC BY-NC 4.0', 'http://creativecommons.org/licenses/by-nc/4.0/deed.no'],
    ['CC BY-NC-SA 4.0', 'http://creativecommons.org/licenses/by-nc-sa/4.0/deed.no'],
    ['CC BY-NC-ND 4.0', 'http://creativecommons.org/licenses/by-nc-nd/4.0/deed.no'],
  ]);

  const docName = doc.navn ? doc.navn : 'Uten Navn';
  const docUrl = `http://www.ut.no/${type}/${doc._id}/`;

  let attribution = `"<a href="${docUrl}">${docName}</a>" av `;

  if (authors && authors instanceof Array) {
    attribution = attribution + authors.reduce((prev, author, i, a) => {
      let delim;

      if (prev) {
        delim = i < a.length - 1 ? ', ' : ' og ';
      } else {
        delim = '';
      }

      if (author.url) {
        return `${prev}${delim}<a href="${author.url}">${author.navn}</a>`;
      }

      return prev + delim + author.navn;
    }, '');
  } else if (typeof authors === 'string') {
    attribution = attribution + authors;
  } else {
    attribution = `${attribution}Ukjent`;
  }

  if (licenses.has(license)) {
    return `${attribution} er lisensiert under <a href="${licenses.get(license)}">${license}</a>.`;
  }

  return `${attribution} er lisensiert under ${license}.`;
};
<|endoftext|>


<commit_before>'use strict';

let creds = require('./creds.js').creds;
let Promise = require('bluebird');
let Evernote = require('evernote');
var sanitizeHtml = require('sanitize-html');
let enml = require('enml-js');
let client;
let noteStore;

function tagsNotebook(notebookguid) {
  // get tags of notebook
  return noteStore.listTagsByNotebook(notebookguid);
}
function count(noteFilter) {
  // get count of notes of notebook
  return noteStore.findNoteCounts(noteFilter, false);
}
function listNote(offset, count, noteFilter, notesMetadataResultSpec) {
  // get the guids of notes
  return noteStore.findNotesMetadata(noteFilter, offset, count, notesMetadataResultSpec);
}
function listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults) {
  // get as many guids of notes as evernote will return and continue until the end
  return listNote(offset, count, noteFilter, notesMetadataResultSpec)
    .then(response => {
      // add new results to result set
      for (let index = 0; index < response.notes.length; index++) {
        noteResults.push(response.notes[index]);
      }
      if (offset < count) {
        // there are still more notes, continue
        offset += response.notes.length;
        return listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults);
      } else {
        return noteResults;
      }
    });
}
function notes(notebookguid) {
  // get note guids of notebook
  let notesMetadataResultSpec = {
    includeTitle: true,
    includeContentLength: true,
    includeCreated: true,
    includeUpdated: true,
    includeTagGuids: true
  }
  let noteFilter = {
    notebookGuid: notebookguid,
    ascending: false,
    order: 1
  }
  let noteResults = [];

  return count(noteFilter)
    .then(response => listMoreNotes(0, response.notebookCounts[notebookguid], noteFilter, notesMetadataResultSpec, noteResults));
}
function notebook(notebookguid) {
  // get tags and note guids of notebook
  return Promise.all([tagsNotebook(notebookguid), notes(notebookguid)])
}
function tagsNote(noteguid) {
  // get tags of note
  return noteStore.getNoteTagNames(noteguid);
}
function selectPic(resources) {
  // choose a usable pic resource
  let lsindex = 0;
  let lsvalue = 0;
  let usableResources = [];
  let result = '';

  if (resources) {
    // find out which resources have a non-empty sourceUrl
    for (let i = 0; i < resources.length; i++) {
      if (resources[i].attributes.sourceURL) usableResources.push(resources[i]);
    }
    if (usableResources.length > 0) {
      // select a resource using evernote's 'largest-smallest' algorithm
      for (let i = 0; i < usableResources.length; i++) {
        let temp = Math.min(usableResources[i].width, usableResources[i].height);
        if (temp === 0) { continue; }
        if (temp > lsvalue) {
          lsindex = i;
          lsvalue = temp;
        }
      }
      result = usableResources[lsindex].attributes.sourceURL;
    }
  }
  return result;
}
function noteContent(noteguid) {
  // get content of note (html, text and pic)
  let resHtml;
  return noteStore.getNoteWithResultSpec(noteguid, {'includeContent': true, 'includeResourcesData' : true})
    .then(response => {
      if (response.message) { return Promise.reject(new Error(response.message))}
      else {
        resHtml = enml.HTMLOfENML(response.content, response.resources);
        return Promise.resolve({
          html: resHtml,
          text: sanitizeHtml(resHtml, {allowedTags: [], allowedAttributes: []}),
          pic: selectPic(response.resources) // TODO find the proper property name
        });
      }
    })
}
function note(noteguid) {
  // get tags, content (raw and sanitized) and pic of note of notebook
  return Promise.all([tagsNote(noteguid), noteContent(noteguid)]);
}

exports.handler = (event, context, callback) => {
  // if no command was specified, then exit
  if ((event === undefined) || (event.cmd === undefined) || (event.cmd === '')) {
    callback(new Error('Missing cmd parameter'))
  } else {
    // init evernote api
    client = new Evernote.Client({
      token: creds.token,
      sandbox: false
    });
    noteStore = client.getNoteStore();
    // main switch
    switch (event.cmd) {
    case 'getNotebooks':
      // get all notebooks of the authenticated user
      noteStore.listNotebooks()
        .then(response => callback(null, response))
        .catch(error => callback(error));
      break;
    case 'getNotebook':
      // get info on a notebook
      // if no notebook guid was provided, then exit
      if (event.notebookguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        notebook(event.notebookguid)
          .then(response => callback(null, {tags: response[0], notes: response[1]}))
          .catch(error => callback(error));
      }
     break;
    case 'getNote':
      // get info on a note
      // if no note guid was provided, then exit
      if (event.noteguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        note(event.noteguid)
          .then(response => callback(null, {noteTags: response[0], noteHtml: response[1].html, noteText: response[1].text, notePic: response[1].pic}))
          .catch(error => callback(error));
      }
      break;
    default:
    }
  }
}

/*
  exports.handler({
    cmd: 'getNotebooks'
    // cmd: 'getNotebook',
    // cmd: 'getNote',
    // notebookguid: 'bf0ff626-e6e1-4bcb-bdfd-07f9c318cb76'
    // noteguid: '6b415a9c-2666-4cd8-8be1-0a3d615aca65'
    // noteguid: 'a969ad1e-1e1a-4ae7-8410-19069fd17c8b'
  });
*/
<commit_msg>changed command names<commit_after>'use strict';

/**
 * Simple wrapper to selected evernote api functions
 * @param {*} event -
 * @param {*} context -
 * @param {*} callback -
 */
exports.handler = (event, context, callback) => {

  /**
   * Get tags of notebook
   * @param {*} notebookguid
   */
  function tagsNotebook(notebookguid) {
    return noteStore.listTagsByNotebook(notebookguid);
  }

  /**
   * Get count of notes of notebook
   * @param {*} noteFilter
   */
  function count(noteFilter) {
    return noteStore.findNoteCounts(noteFilter, false);
  }

  /**
   * Get the guids of notes
   * @param {*} offset
   * @param {*} count
   * @param {*} noteFilter
   * @param {*} notesMetadataResultSpec
   */
  function listNote(offset, count, noteFilter, notesMetadataResultSpec) {
    return noteStore.findNotesMetadata(noteFilter, offset, count, notesMetadataResultSpec);
  }

  /**
   * Get as many guids of notes as evernote will return and continue until the end
   * @param {*} offset
   * @param {*} count
   * @param {*} noteFilter
   * @param {*} notesMetadataResultSpec
   * @param {*} noteResults
   */
  function listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults) {
    return listNote(offset, count, noteFilter, notesMetadataResultSpec)
      .then(response => {
        // add new results to result set
        for (let index = 0; index < response.notes.length; index++) {
          noteResults.push(response.notes[index]);
        }
        if (offset < count) {
          // there are still more notes, continue
          offset += response.notes.length;
          return listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults);
        } else {
          return noteResults;
        }
      });
  }

  /**
   * Get note guids of notebook
   * @param {*} notebookguid
   */
  function notes(notebookguid) {
    let notesMetadataResultSpec = {
      includeTitle: true,
      includeContentLength: true,
      includeCreated: true,
      includeUpdated: true,
      includeTagGuids: true
    }
    let noteFilter = {
      notebookGuid: notebookguid,
      ascending: false,
      order: 1
    }
    let noteResults = [];

    return count(noteFilter)
      .then(response => listMoreNotes(0, response.notebookCounts[notebookguid], noteFilter, notesMetadataResultSpec, noteResults));
  }

  /**
   * Get tags and note guids of notebook
   * @param {*} notebookguid
   */
  function notebook(notebookguid) {
    return Promise.all([tagsNotebook(notebookguid), notes(notebookguid)])
  }

  /**
   * Get tags of note
   * @param {*} noteguid
   */
  function tagsNote(noteguid) {
    return noteStore.getNoteTagNames(noteguid);
  }

  /**
   * Select a usable pic resource
   * @param {*} resources
   */
  function selectPic(resources) {
    let lsindex = 0;
    let lsvalue = 0;
    let usableResources = [];
    let result = '';

    if (resources) {
      // find out which resources have a non-empty sourceUrl
      for (let i = 0; i < resources.length; i++) {
        if (resources[i].attributes.sourceURL) usableResources.push(resources[i]);
      }
      if (usableResources.length > 0) {
        // select a resource using evernote's 'largest-smallest' algorithm
        for (let i = 0; i < usableResources.length; i++) {
          let temp = Math.min(usableResources[i].width, usableResources[i].height);
          if (temp === 0) { continue; }
          if (temp > lsvalue) {
            lsindex = i;
            lsvalue = temp;
          }
        }
        result = usableResources[lsindex].attributes.sourceURL;
      }
    }
    return result;
  }

  /**
   * Get content of note (html, text and pic)
   * @param {*} noteguid
   */
  function noteContent(noteguid) {
    let resHtml;
    return noteStore.getNoteWithResultSpec(noteguid, {'includeContent': true, 'includeResourcesData' : true})
      .then(response => {
        if (response.message) { return Promise.reject(new Error(response.message))}
        else {
          resHtml = enml.HTMLOfENML(response.content, response.resources);
          return Promise.resolve({
            html: resHtml,
            text: sanitizeHtml(resHtml, {allowedTags: [], allowedAttributes: []}),
            pic: selectPic(response.resources) // TODO find the proper property name
          });
        }
      })
  }

  /**
   * Get tags, content (raw and sanitized) and pic of note of notebook
   * @param {*} noteguid
   */
  function note(noteguid) {
    // get tags, content (raw and sanitized) and pic of note of notebook
    return Promise.all([tagsNote(noteguid), noteContent(noteguid)]);
  }

  let creds = require('./creds.js').creds;
  let Promise = require('bluebird');
  let Evernote = require('evernote');
  var sanitizeHtml = require('sanitize-html');
  let enml = require('enml-js');
  let client;
  let noteStore;

  // If no command was provided, then exit immediately.
  if ((event === undefined) || (event.cmd === undefined) || (event.cmd === '')) {
    callback(new Error('Missing cmd parameter'))
  } else if ( (event.cmd !== 'sources') && (event.cmd !== 'list') && (event.cmd !== 'single') ) {
    callback(new Error('Unknown command'))
  } else {
    // Init evernote api.
    client = new Evernote.Client({
      token: creds.token,
      sandbox: false
    });
    noteStore = client.getNoteStore();
    // Main switch.
    switch (event.cmd) {
    /**
     * Get sources (notebooks) of authenticated user.
     */
    case 'sources':
      noteStore.listNotebooks()
        .then(response => callback(null, response))
        .catch(error => callback(error));
      break;
    /**
     * Get cards (notes) of source (notebook).
     * @param {String} notebookguid - the notebook's guid
     */
    case 'list':
      // if required params are missing, then exit immediately.
      if (event.notebookguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        notebook(event.notebookguid)
          .then(response => callback(null, {tags: response[0], notes: response[1]}))
          .catch(error => callback(error));
      }
     break;
    /**
     * Get content of card (note).
     * @param {String} noteguid - the note's guid
     */
    case 'single':
      // if required params are missing, then exit immediately.
      if (event.noteguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        note(event.noteguid)
          .then(response => callback(null, {noteTags: response[0], noteHtml: response[1].html, noteText: response[1].text, notePic: response[1].pic}))
          .catch(error => callback(error));
      }
      break;
    default:
    }
  }
}

/*
  exports.handler({
    cmd: 'getNotebooks'
    // cmd: 'getNotebook',
    // cmd: 'getNote',
    // notebookguid: 'bf0ff626-e6e1-4bcb-bdfd-07f9c318cb76'
    // noteguid: '6b415a9c-2666-4cd8-8be1-0a3d615aca65'
    // noteguid: 'a969ad1e-1e1a-4ae7-8410-19069fd17c8b'
  });
*/
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var fs = require('graceful-fs');
var _ = require('lodash');
var through = require('through2');
var convert = require('convert-source-map');
var mm = require('minimatch');

/*
 Postprocessor for wallaby.js runs module bundler compiler incrementally
 to only build changed or not yet built modules. The compiler is stopped from emitting the bundle/chunks to disk,
 because while concatenating files is beneficial for production environment, in testing environment it is different.
 Serving a large bundle/chunk every time when one of many files (that the bundle consists of) changes, is wasteful.
 So instead, each compiled module code is passed to wallaby,  wallaby caches it in memory (and when required, writes
 it on disk) and serves each requested module file separately to properly leverage browser caching.

 Apart from emitting module files, the postprocessor also emits a test loader script that executes in browser before
 any modules. The test loader sets up a global object so that each wrapped module can add itself to the loader cache.

 Each module code is wrapped in such a way that when the module file is loaded in browser, it doesn't execute
 the module code immediately. Instead, it just adds the function that executes the module code to test loader's cache.

 Modules are loaded from tests (that are entry points) when the tests are loaded. The tests are loaded from wallaby
 bootstrap function, by calling `__moduleBundler.loadTests()`.

 When wallaby runs tests first time, browser caches all modules and each subsequent test run only needs to load  a
 changed module files from the server (and not the full bundle).
 */

class Wallabify {

  constructor(opts, initializer) {
    this._patchModuleDependenciesModule();

    this._opts = opts || {};

    this._prelude = this._opts.prelude;
    this._entryPatterns = this._opts.entryPatterns;
    delete this._opts.prelude;
    delete this._opts.entryPatterns;

    if (this._entryPatterns && _.isString(this._entryPatterns)) {
      this._entryPatterns = [this._entryPatterns];
    }

    this._initializer = initializer;

    this._b = null;
    this._browserifyCache = {};
    this._affectedFilesCache = {};
    this._initRequired = false;
    this._allTrackedFiles = {};
    this._entryFiles = {};
  }

  createPostprocessor() {
    var self = this;
    try {
      this._browserify = require('browserify');
    }
    catch (e) {
      console.error('Browserify node module is not found, missing `npm install browserify --save-dev`?');
      return;
    }

    return wallaby => {
      var logger = wallaby.logger;
      var affectedFiles = wallaby.affectedFiles;
      if (!self._b || wallaby.anyFilesAdded || wallaby.anyFilesDeleted) {

        if (!self._b) {
          logger.debug('New browserify instance created');
        }
        else {
          logger.debug('Browserify instance re-created because some tracked files were added or deleted');
        }

        self._initRequired = true;
        self._affectedFilesCache = {};
        self._allTrackedFiles = _.reduce(wallaby.allFiles, function (memo, file) {
          memo[file.fullPath] = file;
          return memo;
        }, {});
        affectedFiles = wallaby.allFiles;

        self._entryFiles = _.reduce(!self._entryPatterns
            ? wallaby.allTestFiles
            : _.filter(self._allTrackedFiles, file => _.find(self._entryPatterns, pattern => mm(file.path, pattern))),
          function (memo, file) {
            memo[file.fullPath] = file;
            return memo;
          }, {});

        self._b = self._createBrowserify({
          entries: _.map(self._entryFiles, entryFile => entryFile.fullPath),
          paths: wallaby.nodeModulesDir ? [wallaby.nodeModulesDir] : [],
          cache: {}, packageCache: {}, fullPaths: true
        });

        self._browserifyCache = self._b._options.cache;

        self._b.on('dep', function (dep) {
          if (typeof dep.id === 'string') {
            var key = dep.id;
            if (!self._browserifyCache[key]) {
              self._browserifyCache[key] = dep;
              // external files are cached by file name as well to avoid re-processing them every time
              if (dep.expose) {
                self._browserifyCache[dep.file] = dep;
              }
              // new file that has not been cached before (node module or a source file)
              self._affectedFilesCache[key] = dep;
            }
          }
        });

        // no need to pack the bundle, wallaby.js serves files one by one to leverage browser caching
        self._b.pipeline.splice('pack');
      }

      // removing changed files tracked by wallaby.js from browserify cache
      if (!self._initRequired) {
        _.each(affectedFiles, file => {
          delete self._browserifyCache[file.fullPath];
        });
      }

      return new Promise(
        function (resolve, reject) {
          try {
            // incremental bundling
            self._b.bundle()
              .on('data', () => {
              })
              .on('error', err => reject(err))
              .on('end', () => resolve());
          } catch (err) {
            reject(err);
          }
        })
        .then(function () {
          var createFilePromises = [];

          // test loader for wallaby.js
          // works exactly as browserify bundle loading, but with separate files as opposed to a single bundle file
          if (self._initRequired) {
            self._initRequired = false;

            createFilePromises.push(wallaby.createFile({
              order: -1,  // need to be the first file to load
              path: 'wallabify.js',
              content: self._getLoaderContent()
            }));

            // Executing all entry files
            if (self._entryPatterns && self._entryFiles && !_.isEmpty(self._entryFiles)) {
              createFilePromises.push(wallaby.createFile({
                order: Infinity,
                path: 'wallabify_entry.js',
                content: _.reduce(_.values(self._entryFiles),
                  (memo, file) => memo + (file.test ? '' : 'window.__moduleBundler.require(' + JSON.stringify(file.fullPath) + ');'), '')
              }));
            }
          }

          // handling changed files tracked by wallaby.js
          _.each(affectedFiles, function (file) {
            var cached = self._browserifyCache[file.fullPath];
            if (cached) {
              var code = cached.source;
              var sourceMap;
              var sourceMapConverter = convert.fromSource(code);
              if (sourceMapConverter) {
                sourceMap = sourceMapConverter.toJSON();
                code = convert.removeComments(code);
              }

              var isEntryFile = self._entryPatterns && self._entryFiles[file.fullPath];

              // cloning an original file and browserify-ing it
              createFilePromises.push(wallaby.createFile({
                // adding the suffix to store browserified file along with the original copies
                path: file.path + '.bro.js',
                original: file,
                content: Wallabify._wallabifyFile(file.fullPath, code, cached.deps),
                sourceMap: sourceMap,
                order: isEntryFile ? file.order : undefined
              }));
              delete self._affectedFilesCache[file.fullPath];
            }
          });

          // handling externally added and not tracked files (such as node modules and external files)
          try {
            _.each(self._affectedFilesCache, function (file) {
              var ext = path.extname(file.id);
              var basename = path.basename(file.id, ext);
              createFilePromises.push(wallaby.createFile({
                // file path/name doesn't matter, just has to be unique for each file
                path: path.join('__modules', basename + '.' + require('crypto').createHash('md5').update(file.id).digest('hex') + '.js'),
                content: Wallabify._wallabifyFile(file.id, file.source, file.deps)
              }));
            });
          }
          catch (e) {
            return Promise.reject(e);
          }

          // resetting till next incremental bundle run
          self._affectedFilesCache = {};

          logger.debug('Emitting %s files', createFilePromises.length);

          return Promise.all(createFilePromises);
        });
    }
  }

  _createBrowserify(mandatoryOpts) {
    var paths = mandatoryOpts.paths.concat(this._opts.paths || []);
    var mergedOpts = _.merge({}, this._opts, mandatoryOpts);
    mergedOpts.paths = paths;

    var instance = this._browserify(mergedOpts);
    if (this._initializer && _.isFunction(this._initializer)) {
      return this._initializer(instance) || instance;
    }

    return instance;
  }

  static _wallabifyFile(id, content, deps) {
    return 'window.__moduleBundler.cache[' + JSON.stringify(id) + '] = [function(require, module, exports) {'
      + content + '\n}, ' + JSON.stringify(deps) + '];';
  }

  _getLoaderContent() {
    var prelude = this._prelude ||
      '(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module \'"+o+"\'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})';

    return 'window.__moduleBundler = {};'
      + 'window.__moduleBundler.cache = {};'
      + 'window.__moduleBundler.require = function (m) {'
      + prelude
      + '(window.__moduleBundler.cache, {}, [m]);'
      + '};'
      + 'window.__moduleBundler.loadTests = function () {'
      + prelude
        // passing accumulated files and entry points (browserified tests for the current sandbox)
      + '(window.__moduleBundler.cache, {}, (function(){ var testIds = []; for(var i = 0, len = wallaby.loadedTests.length; i < len; i++) { var test = wallaby.loadedTests[i]; if (test.substr(-7) === ".bro.js") testIds.push(wallaby.baseDir + test.substr(0, test.length - 7)); } return testIds; })()); };'
  }

  _patchModuleDependenciesModule() {
    var wallabify = this;
    // patching module dependencies to use wallaby cache
    try {
      require('browserify/node_modules/module-deps').prototype.readFile = function (file, id) {
        var self = this;
        var tr = through();
        if (this.cache && this.cache[file]) {
          tr.push(this.cache[file].source);
          tr.push(null);
          return tr;
        }

        // wallaby.js may already have the file cached (if not, it will just read it from disk)
        if (wallabify._allTrackedFiles && wallabify._allTrackedFiles[file]) {
          wallabify._allTrackedFiles[file].getContent().then(function (source) {
            tr.push(source);
            tr.push(null);
          });
          return tr;
        }

        var rs = fs.createReadStream(file);
        rs.on('error', function (err) {
          self.emit('error', err)
        });
        this.emit('file', file, id);
        return rs;
      };
    }
    catch (e) {
      // not critical
      console.warn('Failed to patch `module-deps` module, wallaby.js file cache will not be used.'
        + '\nIt\'s not a critical issue, however tests will run faster when wallaby.js file cache is used.');
    }
  }
}

module.exports = function (opts, initializer) {
  return new Wallabify(opts, initializer).createPostprocessor();
};
<commit_msg>npm 3 friendly module-deps patching<commit_after>'use strict';

var path = require('path');
var fs = require('graceful-fs');
var _ = require('lodash');
var through = require('through2');
var convert = require('convert-source-map');
var mm = require('minimatch');

/*
 Postprocessor for wallaby.js runs module bundler compiler incrementally
 to only build changed or not yet built modules. The compiler is stopped from emitting the bundle/chunks to disk,
 because while concatenating files is beneficial for production environment, in testing environment it is different.
 Serving a large bundle/chunk every time when one of many files (that the bundle consists of) changes, is wasteful.
 So instead, each compiled module code is passed to wallaby,  wallaby caches it in memory (and when required, writes
 it on disk) and serves each requested module file separately to properly leverage browser caching.

 Apart from emitting module files, the postprocessor also emits a test loader script that executes in browser before
 any modules. The test loader sets up a global object so that each wrapped module can add itself to the loader cache.

 Each module code is wrapped in such a way that when the module file is loaded in browser, it doesn't execute
 the module code immediately. Instead, it just adds the function that executes the module code to test loader's cache.

 Modules are loaded from tests (that are entry points) when the tests are loaded. The tests are loaded from wallaby
 bootstrap function, by calling `__moduleBundler.loadTests()`.

 When wallaby runs tests first time, browser caches all modules and each subsequent test run only needs to load  a
 changed module files from the server (and not the full bundle).
 */

class Wallabify {

  constructor(opts, initializer) {
    this._patchModuleDependenciesModule();

    this._opts = opts || {};

    this._prelude = this._opts.prelude;
    this._entryPatterns = this._opts.entryPatterns;
    delete this._opts.prelude;
    delete this._opts.entryPatterns;

    if (this._entryPatterns && _.isString(this._entryPatterns)) {
      this._entryPatterns = [this._entryPatterns];
    }

    this._initializer = initializer;

    this._b = null;
    this._browserifyCache = {};
    this._affectedFilesCache = {};
    this._initRequired = false;
    this._allTrackedFiles = {};
    this._entryFiles = {};
  }

  createPostprocessor() {
    var self = this;
    try {
      this._browserify = require('browserify');
    }
    catch (e) {
      console.error('Browserify node module is not found, missing `npm install browserify --save-dev`?');
      return;
    }

    return wallaby => {
      var logger = wallaby.logger;
      var affectedFiles = wallaby.affectedFiles;
      if (!self._b || wallaby.anyFilesAdded || wallaby.anyFilesDeleted) {

        if (!self._b) {
          logger.debug('New browserify instance created');
        }
        else {
          logger.debug('Browserify instance re-created because some tracked files were added or deleted');
        }

        self._initRequired = true;
        self._affectedFilesCache = {};
        self._allTrackedFiles = _.reduce(wallaby.allFiles, function (memo, file) {
          memo[file.fullPath] = file;
          return memo;
        }, {});
        affectedFiles = wallaby.allFiles;

        self._entryFiles = _.reduce(!self._entryPatterns
            ? wallaby.allTestFiles
            : _.filter(self._allTrackedFiles, file => _.find(self._entryPatterns, pattern => mm(file.path, pattern))),
          function (memo, file) {
            memo[file.fullPath] = file;
            return memo;
          }, {});

        self._b = self._createBrowserify({
          entries: _.map(self._entryFiles, entryFile => entryFile.fullPath),
          paths: wallaby.nodeModulesDir ? [wallaby.nodeModulesDir] : [],
          cache: {}, packageCache: {}, fullPaths: true
        });

        self._browserifyCache = self._b._options.cache;

        self._b.on('dep', function (dep) {
          if (typeof dep.id === 'string') {
            var key = dep.id;
            if (!self._browserifyCache[key]) {
              self._browserifyCache[key] = dep;
              // external files are cached by file name as well to avoid re-processing them every time
              if (dep.expose) {
                self._browserifyCache[dep.file] = dep;
              }
              // new file that has not been cached before (node module or a source file)
              self._affectedFilesCache[key] = dep;
            }
          }
        });

        // no need to pack the bundle, wallaby.js serves files one by one to leverage browser caching
        self._b.pipeline.splice('pack');
      }

      // removing changed files tracked by wallaby.js from browserify cache
      if (!self._initRequired) {
        _.each(affectedFiles, file => {
          delete self._browserifyCache[file.fullPath];
        });
      }

      return new Promise(
        function (resolve, reject) {
          try {
            // incremental bundling
            self._b.bundle()
              .on('data', () => {
              })
              .on('error', err => reject(err))
              .on('end', () => resolve());
          } catch (err) {
            reject(err);
          }
        })
        .then(function () {
          var createFilePromises = [];

          // test loader for wallaby.js
          // works exactly as browserify bundle loading, but with separate files as opposed to a single bundle file
          if (self._initRequired) {
            self._initRequired = false;

            createFilePromises.push(wallaby.createFile({
              order: -1,  // need to be the first file to load
              path: 'wallabify.js',
              content: self._getLoaderContent()
            }));

            // Executing all entry files
            if (self._entryPatterns && self._entryFiles && !_.isEmpty(self._entryFiles)) {
              createFilePromises.push(wallaby.createFile({
                order: Infinity,
                path: 'wallabify_entry.js',
                content: _.reduce(_.values(self._entryFiles),
                  (memo, file) => memo + (file.test ? '' : 'window.__moduleBundler.require(' + JSON.stringify(file.fullPath) + ');'), '')
              }));
            }
          }

          // handling changed files tracked by wallaby.js
          _.each(affectedFiles, function (file) {
            var cached = self._browserifyCache[file.fullPath];
            if (cached) {
              var code = cached.source;
              var sourceMap;
              var sourceMapConverter = convert.fromSource(code);
              if (sourceMapConverter) {
                sourceMap = sourceMapConverter.toJSON();
                code = convert.removeComments(code);
              }

              var isEntryFile = self._entryPatterns && self._entryFiles[file.fullPath];

              // cloning an original file and browserify-ing it
              createFilePromises.push(wallaby.createFile({
                // adding the suffix to store browserified file along with the original copies
                path: file.path + '.bro.js',
                original: file,
                content: Wallabify._wallabifyFile(file.fullPath, code, cached.deps),
                sourceMap: sourceMap,
                order: isEntryFile ? file.order : undefined
              }));
              delete self._affectedFilesCache[file.fullPath];
            }
          });

          // handling externally added and not tracked files (such as node modules and external files)
          try {
            _.each(self._affectedFilesCache, function (file) {
              var ext = path.extname(file.id);
              var basename = path.basename(file.id, ext);
              createFilePromises.push(wallaby.createFile({
                // file path/name doesn't matter, just has to be unique for each file
                path: path.join('__modules', basename + '.' + require('crypto').createHash('md5').update(file.id).digest('hex') + '.js'),
                content: Wallabify._wallabifyFile(file.id, file.source, file.deps)
              }));
            });
          }
          catch (e) {
            return Promise.reject(e);
          }

          // resetting till next incremental bundle run
          self._affectedFilesCache = {};

          logger.debug('Emitting %s files', createFilePromises.length);

          return Promise.all(createFilePromises);
        });
    }
  }

  _createBrowserify(mandatoryOpts) {
    var paths = mandatoryOpts.paths.concat(this._opts.paths || []);
    var mergedOpts = _.merge({}, this._opts, mandatoryOpts);
    mergedOpts.paths = paths;

    var instance = this._browserify(mergedOpts);
    if (this._initializer && _.isFunction(this._initializer)) {
      return this._initializer(instance) || instance;
    }

    return instance;
  }

  static _wallabifyFile(id, content, deps) {
    return 'window.__moduleBundler.cache[' + JSON.stringify(id) + '] = [function(require, module, exports) {'
      + content + '\n}, ' + JSON.stringify(deps) + '];';
  }

  _getLoaderContent() {
    var prelude = this._prelude ||
      '(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module \'"+o+"\'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})';

    return 'window.__moduleBundler = {};'
      + 'window.__moduleBundler.cache = {};'
      + 'window.__moduleBundler.require = function (m) {'
      + prelude
      + '(window.__moduleBundler.cache, {}, [m]);'
      + '};'
      + 'window.__moduleBundler.loadTests = function () {'
      + prelude
        // passing accumulated files and entry points (browserified tests for the current sandbox)
      + '(window.__moduleBundler.cache, {}, (function(){ var testIds = []; for(var i = 0, len = wallaby.loadedTests.length; i < len; i++) { var test = wallaby.loadedTests[i]; if (test.substr(-7) === ".bro.js") testIds.push(wallaby.baseDir + test.substr(0, test.length - 7)); } return testIds; })()); };'
  }

  _patchModuleDependenciesModule() {
    var wallabify = this;
    var moduleDeps;

    // patching module dependencies to use wallaby cache
    try {

      try {
        // npm 2
        moduleDeps = require('browserify/node_modules/module-deps');
      }
      catch (e) {
        // npm 3
        moduleDeps = require('module-deps');
      }

      moduleDeps.prototype.readFile = function (file, id) {
        var self = this;
        var tr = through();
        if (this.cache && this.cache[file]) {
          tr.push(this.cache[file].source);
          tr.push(null);
          return tr;
        }

        // wallaby.js may already have the file cached (if not, it will just read it from disk)
        if (wallabify._allTrackedFiles && wallabify._allTrackedFiles[file]) {
          wallabify._allTrackedFiles[file].getContent().then(function (source) {
            tr.push(source);
            tr.push(null);
          });
          return tr;
        }

        var rs = fs.createReadStream(file);
        rs.on('error', function (err) {
          self.emit('error', err)
        });
        this.emit('file', file, id);
        return rs;
      };
    }
    catch (e) {
      // not critical
      console.warn('Failed to patch `module-deps` module, wallaby.js file cache will not be used.'
        + '\nIt\'s not a critical issue, however tests will run faster when wallaby.js file cache is used.');
    }
  }
}

module.exports = function (opts, initializer) {
  return new Wallabify(opts, initializer).createPostprocessor();
};
<|endoftext|>


<commit_before>var Twitter           = require('twitter-stream-channels'),
    fs                = require('fs'),
    GoogleSpreadsheet = require("google-spreadsheet"),
    ini               = require('ini');

var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8'));

var client = new Twitter({
  "consumer_key": config.TW_CONSUMER_KEY,
  "consumer_secret": config.TW_CONSUMER_SEC,
  "access_token": config.TW_ACCESS_TOKEN_KEY,
  "access_token_secret": config.TW_ACCESS_TOKEN_SEC
});

var channels = {
  "general": config.KW_TRAVEL,
  "hawaii": config.KW_HAWAII,
  "sam": config.KW_SAM,
  "SF": config.KW_SF,
  "carlos": config.KW_CARLOS
};

var stream = client.streamChannels({track:channels});
var my_sheet = new GoogleSpreadsheet(config.GOOGLE_SPREADSHEET);
var creds = require('./google-cred.json');

function handleError(err) {
  if (err) {
    console.log(err);
    return true;
  }
  return false;
}

function logTweetToGoogle(tweet, category) {
  console.log('logging to Google');
  my_sheet.useServiceAccountAuth(creds, function(err){
    // getInfo returns info about the sheet and an array or "worksheet" objects
    my_sheet.getInfo( function( err, sheet_info ){
        console.log( sheet_info.title + ' is loaded' );
          // use worksheet object if you want to stop using the # in your calls
      });

    if(category === 'general'){
      // column names are set by google and are based
      // on the header row (first row) of your sheet
      my_sheet.addRow(1, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'hawaii'){
      my_sheet.addRow(2, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'SF'){
      my_sheet.addRow(3, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'sam'){
      my_sheet.addRow(4, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'carlos'){
      my_sheet.addRow(5, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    }
  });
}

stream.on('channels/general', function(tweet){
  logTweetToGoogle(tweet, 'general');
});

stream.on('channels/hawaii', function(tweet){
  logTweetToGoogle(tweet, 'hawaii');
});

stream.on('channels/SF', function(tweet){
  logTweetToGoogle(tweet, 'SF');
});

stream.on('channels/sam', function(tweet){
  logTweetToGoogle(tweet, 'sam');
});

stream.on('channels/carlos', function(tweet){
  logTweetToGoogle(tweet, 'carlos');
});

// setTimeout(function(){
//     stream.stop();//closes the stream connected to Twitter
//     console.log('>stream closed after 100 seconds');
// },100000);
<commit_msg>added null check<commit_after>var Twitter           = require('twitter-stream-channels'),
    fs                = require('fs'),
    GoogleSpreadsheet = require("google-spreadsheet"),
    ini               = require('ini');

var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8'));

var client = new Twitter({
  "consumer_key": config.TW_CONSUMER_KEY,
  "consumer_secret": config.TW_CONSUMER_SEC,
  "access_token": config.TW_ACCESS_TOKEN_KEY,
  "access_token_secret": config.TW_ACCESS_TOKEN_SEC
});

var channels = {
  "general": config.KW_TRAVEL,
  "hawaii": config.KW_HAWAII,
  "sam": config.KW_SAM,
  "SF": config.KW_SF,
  "carlos": config.KW_CARLOS
};

var stream = client.streamChannels({track:channels});
var my_sheet = new GoogleSpreadsheet(config.GOOGLE_SPREADSHEET);
var creds = require('./google-cred.json');

function handleError(err) {
  if (err) {
    console.log(err);
    return true;
  }
  return false;
}

function logTweetToGoogle(tweet, category) {
  console.log('logging to Google');
  my_sheet.useServiceAccountAuth(creds, function(err){
    // getInfo returns info about the sheet and an array or "worksheet" objects
    my_sheet.getInfo( function( err, sheet_info ){
        if((sheet_info !== undefined) && (sheet_info !== null)){
          console.log( sheet_info.title + ' is loaded' );
        }
      });

    if(category === 'general'){
      // column names are set by google and are based
      // on the header row (first row) of your sheet
      my_sheet.addRow(1, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'hawaii'){
      my_sheet.addRow(2, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'SF'){
      my_sheet.addRow(3, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'sam'){
      my_sheet.addRow(4, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    } else if(category === 'carlos'){
      my_sheet.addRow(5, {
        text: tweet.text, url: "https://twitter.com/" + tweet.user.screen_name + '/status/' + tweet.id_str, followers: tweet.user.followers_count, username: tweet.user.screen_name, createdAt: tweet.created_at
      }, handleError);
    }
  });
}

stream.on('channels/general', function(tweet){
  logTweetToGoogle(tweet, 'general');
});

stream.on('channels/hawaii', function(tweet){
  logTweetToGoogle(tweet, 'hawaii');
});

stream.on('channels/SF', function(tweet){
  logTweetToGoogle(tweet, 'SF');
});

stream.on('channels/sam', function(tweet){
  logTweetToGoogle(tweet, 'sam');
});

stream.on('channels/carlos', function(tweet){
  logTweetToGoogle(tweet, 'carlos');
});

// setTimeout(function(){
//     stream.stop();//closes the stream connected to Twitter
//     console.log('>stream closed after 100 seconds');
// },100000);
<|endoftext|>