<commit_before>/* global window, document, chrome, Blob, saveAs */
(function() {
    'use strict';

    var injected = document.createElement('script');

    /**
     * Finds, formats and allows you download routes from ViewRanger as a GPX
     * file.
     *
     * @param {Object} route - The route we've passed through from the injected script
     */
    function GPXBuilder(route) {
        this.route = route;
        this.points = route.routeJson.routes[0].points;
        this.gpxTemplate =
            '<?xml version="1.0" encoding="UTF-8"?>\n' +
            '<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">\n' +
            '  <trk>\n' +
            '    <name><![CDATA[{{name}}]]></name>\n' +
            '    <trkseg>\n' +
                   '{{waypoints}}\n' +
            '    </trkseg>\n' +
            '  </trk>\n' +
            '</gpx>\n';
        this.waypointTemplate = '      <trkpt lat="{{lat}}" lon="{{lon}}"/>';

        this.buildLink();
    }

    /**
     * Standard issue slugify
     *
     * @param {String} str - The string to slugify
     * @return {String}
     */
    GPXBuilder.prototype.slugify = function(str) {
        var from = 'àáäãâèéëêìíïîòóöôõùúüûñç·/_,:;';
        var to = 'aaaaaeeeeiiiiooooouuuunc------';
        var i = 0;
        var len = from.length;

        str = str.toLowerCase();

        for( ; i < len; i++ ){
            str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
        }

        return str.replace(/^\s+|\s+$/g, '')
            .replace(/[^-a-zA-Z0-9\s]+/ig, '')
            .replace(/\s/gi, "-");
    };

    /**
     * Create the link in the menu and bind it's click to our download
     */
    GPXBuilder.prototype.buildLink = function() {
        var menu = document.querySelector('.dropit-submenu');
        var li = document.createElement('li');
        var link = document.createElement('a');

        // Add the link to our page
        link.setAttribute('href', '#');
        link.text = 'Download GPX';
        menu.appendChild(li);
        li.appendChild(link);

        link.onclick = this.download.bind(this);
    };

    /**
     * Parse an indavidual waypoint and format it as per the template. To be
     * run on each map iteration of points.
     *
     * @param {Object} point - Lat / Lng of the point
     * @param {Number} index - Index position inside the map
     * @return {String} - The formatted template
     */
    GPXBuilder.prototype.formatWaypoint = function(point, index) {
        point.name = point.name || 'waypoint-' + index;
        return this.waypointTemplate
            .replace('{{lat}}', point.lat)
            .replace('{{lon}}', point.lon)
            .replace('{{name}}', point.name);
    };

    /**
     * Build the entire GPX on demand, then serve the blob back as a download
     *
     * @param {Event} e - The click event received from our link
     */
    GPXBuilder.prototype.download = function(e) {
        var blob;
        var filename;
        var gpx;

        e.preventDefault();

        filename = this.slugify(this.route.shortDescription) + '.gpx';
        gpx = this.gpxTemplate
            .replace('{{name}}', this.route.shortDescription)
            .replace('{{waypoints}}', this.points.map(
                this.formatWaypoint.bind(this)
            ).join('\n'));
        blob = new Blob([gpx], {type: 'text/plain;charset=utf-8'});
        saveAs(blob, filename);
    };

    // Inject script to provide our global objec
    injected.src = chrome.extension.getURL('/js/injected.js');
    document.head.appendChild(injected);

    // Listen for the message from the injected script with out route
    window.addEventListener('message', function(event) {
        if (event.data.type !== 'gpxReady' || !event.data.route) { return; }
        new GPXBuilder(event.data.route);
    });

}());
<commit_msg>Fix menu location for regular link<commit_after>/* global window, document, chrome, Blob, saveAs */
(function() {
    'use strict';

    var injected = document.createElement('script');

    /**
     * Finds, formats and allows you download routes from ViewRanger as a GPX
     * file.
     *
     * @param {Object} route - The route we've passed through from the injected script
     */
    function GPXBuilder(route) {
        this.route = route;
        this.points = route.routeJson.routes[0].points;
        this.gpxTemplate =
            '<?xml version="1.0" encoding="UTF-8"?>\n' +
            '<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">\n' +
            '  <trk>\n' +
            '    <name><![CDATA[{{name}}]]></name>\n' +
            '    <trkseg>\n' +
                   '{{waypoints}}\n' +
            '    </trkseg>\n' +
            '  </trk>\n' +
            '</gpx>\n';
        this.waypointTemplate = '      <trkpt lat="{{lat}}" lon="{{lon}}"/>';

        this.buildLink();
    }

    /**
     * Standard issue slugify
     *
     * @param {String} str - The string to slugify
     * @return {String}
     */
    GPXBuilder.prototype.slugify = function(str) {
        var from = 'àáäãâèéëêìíïîòóöôõùúüûñç·/_,:;';
        var to = 'aaaaaeeeeiiiiooooouuuunc------';
        var i = 0;
        var len = from.length;

        str = str.toLowerCase();

        for( ; i < len; i++ ){
            str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
        }

        return str.replace(/^\s+|\s+$/g, '')
            .replace(/[^-a-zA-Z0-9\s]+/ig, '')
            .replace(/\s/gi, "-");
    };

    /**
     * Create the link in the menu and bind it's click to our download
     */
    GPXBuilder.prototype.buildLink = function() {
        var menu = document.querySelector('.rdmenucenter');
        var link = document.createElement('a');

        // Add the link to our page
        link.setAttribute('href', '#');
        link.text = 'Download GPX';
        link.setAttribute('style', 'float:left;line-height:25px;color:white;margin-right:5px;')
        link.onclick = this.download.bind(this);
        menu.prepend(link);
    };

    /**
     * Parse an indavidual waypoint and format it as per the template. To be
     * run on each map iteration of points.
     *
     * @param {Object} point - Lat / Lng of the point
     * @param {Number} index - Index position inside the map
     * @return {String} - The formatted template
     */
    GPXBuilder.prototype.formatWaypoint = function(point, index) {
        point.name = point.name || 'waypoint-' + index;
        return this.waypointTemplate
            .replace('{{lat}}', point.lat)
            .replace('{{lon}}', point.lon)
            .replace('{{name}}', point.name);
    };

    /**
     * Build the entire GPX on demand, then serve the blob back as a download
     *
     * @param {Event} e - The click event received from our link
     */
    GPXBuilder.prototype.download = function(e) {
        var blob;
        var filename;
        var gpx;

        e.preventDefault();

        filename = this.slugify(this.route.shortDescription) + '.gpx';
        gpx = this.gpxTemplate
            .replace('{{name}}', this.route.shortDescription)
            .replace('{{waypoints}}', this.points.map(
                this.formatWaypoint.bind(this)
            ).join('\n'));
        blob = new Blob([gpx], {type: 'text/plain;charset=utf-8'});
        saveAs(blob, filename);
    };

    // Inject script to provide our global objec
    injected.src = chrome.extension.getURL('/js/injected.js');
    document.head.appendChild(injected);

    // Listen for the message from the injected script with out route
    window.addEventListener('message', function(event) {
        if (event.data.type !== 'gpxReady' || !event.data.route) { return; }
        new GPXBuilder(event.data.route);
    });

}());
<|endoftext|>


<commit_before>// Returns function that returns deferred or promise object.
//
// 1. If invoked without arguments then deferred object is returned
//    Deferred object consist of promise (unresolved) function and resolve
//    function through which we resolve promise
// 2. If invoked with one argument then promise is returned which resolved value
//    is given argument. Argument may be any value (even undefined),
//    if it's promise then same promise is returned
// 3. If invoked with more than one arguments then promise that resolves with
//    array of all resolved arguments is returned.

'use strict';

var isError   = require('es5-ext/lib/Error/is-error')
  , noop      = require('es5-ext/lib/Function/noop')
  , isPromise = require('./is-promise')

  , every = Array.prototype.every, push = Array.prototype.push

  , Deferred, createDeferred, count = 0, timeout, extendShim, ext
  , protoSupported = Boolean(isPromise.__proto__)
  , resolve, assimilate;

extendShim = function (promise) {
	ext._names.forEach(function (name) {
		promise[name] = function () {
			return promise.__proto__[name].apply(promise, arguments);
		};
	});
	promise.returnsPromise = true;
	promise.resolved = promise.__proto__.resolved;
};

resolve = function (value, failed) {
	var promise = function (win, fail) { return promise.then(win, fail); };
	promise.value = value;
	promise.failed = failed;
	promise.__proto__ = ext._resolved;
	if (!protoSupported) { extendShim(promise); }
	if (createDeferred._profile) createDeferred._profile(true);
	return promise;
};

Deferred = function () {
	var promise = function (win, fail) { return promise.then(win, fail); };
	if (!count) timeout = setTimeout(noop, 1e9);
	++count;
	if (createDeferred._monitor) promise.monitor = createDeferred._monitor();
	promise.__proto__ = ext._unresolved;
	if (!protoSupported) extendShim(promise);
	(createDeferred._profile && createDeferred._profile());
	this.promise = promise;
	this.resolve = this.resolve.bind(this);
	this.reject = this.reject.bind(this);
};

Deferred.prototype = {
	resolved: false,
	_settle: function (value) {
		var i, name, data;
		this.promise.value = value;
		this.promise.__proto__ = ext._resolved;
		if (!protoSupported) this.promise.resolved = true;
		if (this.promise.dependencies) {
			this.promise.dependencies.forEach(function self(dPromise) {
				dPromise.value = value;
				dPromise.failed = this.failed;
				dPromise.__proto__ = ext._resolved;
				if (!protoSupported) dPromise.resolved = true;
				delete dPromise.pending;
				if (dPromise.dependencies) {
					dPromise.dependencies.forEach(self, this);
					delete dPromise.dependencies;
				}
			}, this.promise);
			delete this.promise.dependencies;
		}
		if ((data = this.promise.pending)) {
			for (i = 0; (name = data[i]); ++i) {
				ext._onresolve[name].apply(this.promise, data[++i]);
			}
			delete this.promise.pending;
		}
		return this.promise;
	},
	resolve: function (value) {
		if (this.resolved) return this.promise;
		this.resolved = true;
		if (!--count) clearTimeout(timeout);
		if (this.promise.monitor) clearTimeout(this.promise.monitor);
		value = assimilate(value);
		if (isPromise(value)) {
			if (!value.resolved) {
				if (!value.dependencies) {
					value.dependencies = [];
				}
				value.dependencies.push(this.promise);
				if (this.promise.pending) {
					if (value.pending) {
						push.apply(value.pending, this.promise.pending);
						this.promise.pending = value.pending;
						if (this.promise.dependencies) {
							this.promise.dependencies.forEach(function self(dPromise) {
								dPromise.pending = value.pending;
								if (dPromise.dependencies) {
									dPromise.dependencies.forEach(self);
								}
							});
						}
					} else {
						value.pending = this.promise.pending;
					}
				} else if (value.pending) {
					this.promise.pending = value.pending;
				} else {
					this.promise.pending = value.pending = [];
				}
				return this.promise;
			}
			this.promise.failed = value.failed;
			value = value.value;
		}
		return this._settle(value);
	},
	reject: function (error) {
		if (this.resolved) return this.promise;
		this.resolved = true;
		if (!--count) clearTimeout(timeout);
		if (this.promise.monitor) clearTimeout(this.promise.monitor);
		this.promise.failed = true;
		return this._settle(error);
	}
};

module.exports = createDeferred = function (value) {
	var l = arguments.length, d, waiting, initialized, result;
	if (!l) return new Deferred();
	if (l > 1) {
		d = new Deferred();
		waiting = 0;
		result = new Array(l);
		every.call(arguments, function (value, index) {
			value = assimilate(value);
			if (!isPromise(value)) {
				result[index] = value;
				return true;
			}
			if (value.resolved) {
				if (value.failed) {
					d.reject(value.value);
					return false;
				}
				result[index] = value.value;
				return true;
			}
			++waiting;
			value.done(function (value) {
				result[index] = value;
				if (!--waiting && initialized) d.resolve(result);
			}, d.reject);
			return true;
		});
		initialized = true;
		if (!waiting) d.resolve(result);
		return d.promise;
	}
	value = assimilate(value);
	if (isPromise(value)) return value;
	return resolve(value, isError(value));
};

createDeferred.Deferred = Deferred;
createDeferred.reject = function (value) { return resolve(value, true); };
createDeferred.resolve = function (value) { return resolve(value, false); };
ext = require('./_ext');
assimilate = require('./assimilate');
<commit_msg>Fix resolve so it assimilates promises<commit_after>// Returns function that returns deferred or promise object.
//
// 1. If invoked without arguments then deferred object is returned
//    Deferred object consist of promise (unresolved) function and resolve
//    function through which we resolve promise
// 2. If invoked with one argument then promise is returned which resolved value
//    is given argument. Argument may be any value (even undefined),
//    if it's promise then same promise is returned
// 3. If invoked with more than one arguments then promise that resolves with
//    array of all resolved arguments is returned.

'use strict';

var isError   = require('es5-ext/lib/Error/is-error')
  , noop      = require('es5-ext/lib/Function/noop')
  , isPromise = require('./is-promise')

  , every = Array.prototype.every, push = Array.prototype.push

  , Deferred, createDeferred, count = 0, timeout, extendShim, ext
  , protoSupported = Boolean(isPromise.__proto__)
  , resolve, assimilate;

extendShim = function (promise) {
	ext._names.forEach(function (name) {
		promise[name] = function () {
			return promise.__proto__[name].apply(promise, arguments);
		};
	});
	promise.returnsPromise = true;
	promise.resolved = promise.__proto__.resolved;
};

resolve = function (value, failed) {
	var promise = function (win, fail) { return promise.then(win, fail); };
	promise.value = value;
	promise.failed = failed;
	promise.__proto__ = ext._resolved;
	if (!protoSupported) { extendShim(promise); }
	if (createDeferred._profile) createDeferred._profile(true);
	return promise;
};

Deferred = function () {
	var promise = function (win, fail) { return promise.then(win, fail); };
	if (!count) timeout = setTimeout(noop, 1e9);
	++count;
	if (createDeferred._monitor) promise.monitor = createDeferred._monitor();
	promise.__proto__ = ext._unresolved;
	if (!protoSupported) extendShim(promise);
	(createDeferred._profile && createDeferred._profile());
	this.promise = promise;
	this.resolve = this.resolve.bind(this);
	this.reject = this.reject.bind(this);
};

Deferred.prototype = {
	resolved: false,
	_settle: function (value) {
		var i, name, data;
		this.promise.value = value;
		this.promise.__proto__ = ext._resolved;
		if (!protoSupported) this.promise.resolved = true;
		if (this.promise.dependencies) {
			this.promise.dependencies.forEach(function self(dPromise) {
				dPromise.value = value;
				dPromise.failed = this.failed;
				dPromise.__proto__ = ext._resolved;
				if (!protoSupported) dPromise.resolved = true;
				delete dPromise.pending;
				if (dPromise.dependencies) {
					dPromise.dependencies.forEach(self, this);
					delete dPromise.dependencies;
				}
			}, this.promise);
			delete this.promise.dependencies;
		}
		if ((data = this.promise.pending)) {
			for (i = 0; (name = data[i]); ++i) {
				ext._onresolve[name].apply(this.promise, data[++i]);
			}
			delete this.promise.pending;
		}
		return this.promise;
	},
	resolve: function (value) {
		if (this.resolved) return this.promise;
		this.resolved = true;
		if (!--count) clearTimeout(timeout);
		if (this.promise.monitor) clearTimeout(this.promise.monitor);
		value = assimilate(value);
		if (isPromise(value)) {
			if (!value.resolved) {
				if (!value.dependencies) {
					value.dependencies = [];
				}
				value.dependencies.push(this.promise);
				if (this.promise.pending) {
					if (value.pending) {
						push.apply(value.pending, this.promise.pending);
						this.promise.pending = value.pending;
						if (this.promise.dependencies) {
							this.promise.dependencies.forEach(function self(dPromise) {
								dPromise.pending = value.pending;
								if (dPromise.dependencies) {
									dPromise.dependencies.forEach(self);
								}
							});
						}
					} else {
						value.pending = this.promise.pending;
					}
				} else if (value.pending) {
					this.promise.pending = value.pending;
				} else {
					this.promise.pending = value.pending = [];
				}
				return this.promise;
			}
			this.promise.failed = value.failed;
			value = value.value;
		}
		return this._settle(value);
	},
	reject: function (error) {
		if (this.resolved) return this.promise;
		this.resolved = true;
		if (!--count) clearTimeout(timeout);
		if (this.promise.monitor) clearTimeout(this.promise.monitor);
		this.promise.failed = true;
		return this._settle(error);
	}
};

module.exports = createDeferred = function (value) {
	var l = arguments.length, d, waiting, initialized, result;
	if (!l) return new Deferred();
	if (l > 1) {
		d = new Deferred();
		waiting = 0;
		result = new Array(l);
		every.call(arguments, function (value, index) {
			value = assimilate(value);
			if (!isPromise(value)) {
				result[index] = value;
				return true;
			}
			if (value.resolved) {
				if (value.failed) {
					d.reject(value.value);
					return false;
				}
				result[index] = value.value;
				return true;
			}
			++waiting;
			value.done(function (value) {
				result[index] = value;
				if (!--waiting && initialized) d.resolve(result);
			}, d.reject);
			return true;
		});
		initialized = true;
		if (!waiting) d.resolve(result);
		return d.promise;
	}
	value = assimilate(value);
	if (isPromise(value)) return value;
	return resolve(value, isError(value));
};

createDeferred.Deferred = Deferred;
createDeferred.reject = function (value) { return resolve(value, true); };
createDeferred.resolve = function (value) {
	value = assimilate(value);
	if (isPromise(value)) return value;
	return resolve(value, false);
};
ext = require('./_ext');
assimilate = require('./assimilate');
<|endoftext|>


<commit_before>var Radium = require('radium');
var React = require('react');
var Row = require('react-bootstrap/lib/Row');
var Col = require('react-bootstrap/lib/Col');

var styles = {
    red: {
        backgroundColor: 'red'
    }
};

class Card extends React.Component {
    render() {
        return (
            <Row>
                <Col xs={4} style={styles.red}>
                    <Row>
                        <Col xs={12}>
                            7:30 AM
                        </Col>
                    </Row>
                    <Row>
                        <Col xs={12}>
                            8:30 AM
                        </Col>
                    </Row>
                </Col>
                <Col xs={8}>
                    { this.props.title }
                </Col>
            </Row>
        );
    }
}
module.exports = Radium(Card);

<commit_msg>Updated Card style<commit_after>var Radium = require('radium');
var React = require('react');
var Row = require('react-bootstrap/lib/Row');
var Col = require('react-bootstrap/lib/Col');

var style = {
    card: {
        border: '1px solid #DDD',
        borderRadius: '10px'
    }
};

class Card extends React.Component {
    render() {
        return (
            <Row style={style.card}>
                <Col xs={4}>
                    <Row>
                        <Col xs={12}>
                            7:30 AM
                        </Col>
                    </Row>
                    <Row>
                        <Col xs={12}>
                            8:30 AM
                        </Col>
                    </Row>
                </Col>
                <Col xs={8}>
                    { this.props.title }
                </Col>
            </Row>
        );
    }
}
module.exports = Radium(Card);

<|endoftext|>


<commit_before>const way = require('senseway')
const howTitle = require('./howTitle/render')

const wayel = (wa, opts) => {
  const el = document.createElement('div')
  el.classList.add('how-way-container')
  el.innerHTML = way.html(wa, opts)
  return el
}

module.exports = (model, dispatch) => {
  const root = document.createElement('div')
  root.classList.add('how-container')

  root.appendChild(howTitle(model, dispatch))

  const timeline = document.createElement('div')
  timeline.classList.add('how-timeline')

  timeline.appendChild(wayel(model.timeline, {
    reversed: true,
    heading: 'Timeline',
    caption: 'Here is the timeline - our training data set'
  }))

  const timelineMass = way.map(model.timeline, q => q === null ? 0 : 1)
  timeline.appendChild(wayel(timelineMass, {
    reversed: true,
    heading: 'Timeline Mass',
    caption: 'Mass shows which atomic events we know and which we do not know. Here are masses for each timeslot.'
  }))

  root.appendChild(timeline)

  return root
}
<commit_msg>View unknown data mass<commit_after>const way = require('senseway')
const howTitle = require('./howTitle/render')

const wayel = (wa, opts) => {
  const el = document.createElement('div')
  el.classList.add('how-way-container')
  el.innerHTML = way.html(wa, opts)
  return el
}

module.exports = (model, dispatch) => {
  const root = document.createElement('div')
  root.classList.add('how-container')

  root.appendChild(howTitle(model, dispatch))

  const timeline = document.createElement('div')
  timeline.classList.add('how-timeline')

  timeline.appendChild(wayel(model.timeline, {
    reversed: true,
    heading: 'Timeline',
    caption: 'Here is the timeline - our training data set.'
  }))

  const timelineMass = way.map(model.timeline, q => q === null ? 0 : 1)
  timeline.appendChild(wayel(timelineMass, {
    reversed: true,
    heading: 'Timeline Mass',
    caption: 'Mass shows which atomic events we know and which we '
      + 'do not know. Here are masses for each timeslot. White = 0, Black = 1.'
  }))

  const unknownEvents = way.map(timelineMass, q => 1 - q)
  timeline.appendChild(wayel(unknownEvents, {
    reversed: true,
    heading: 'Unknown Data',
    caption: 'These atomic events we do not know. Our goal is to predict '
      + 'their value from the training data.'
  }))

  root.appendChild(timeline)

  return root
}
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-14 11:23:00<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var concat = require('concat-stream')
var http = require('http')
var isSHA256 = require('is-sha-256-hex-digest')
var merkleize = require('commonform-merkleize')
var server = require('./server')
var tape = require('tape')

tape('POST / with valid form', function(test) {
  var form = { content: [ 'Some text' ] }
  var digest = merkleize(form).digest
  server(function(port, done) {
    var request = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(request, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        response.headers.hasOwnProperty('location'),
        'sets Location header')
      test.assert(
        response.headers.location.indexOf(digest),
        'location includes digest')
      done()
      test.end() })
    .end(JSON.stringify(form)) }) })

tape('POST / with invalid form', function(test) {
  var form = { blah: 'blah' }
  server(function(port, done) {
    var request = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(request, function(response) {
      test.equal(
        response.statusCode, 400,
        'responds 400')
      done()
      test.end() })
    .end(JSON.stringify(form)) }) })

tape('POST / with non-JSON', function(test) {
  server(function(port, done) {
    var request = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(request, function(response) {
      test.equal(
        response.statusCode, 400,
        'responds 400')
      done()
      test.end() })
    .end('just plain text') }) })

tape('POST and GET a form', function(test) {
  var posted = { content: [ 'Some text' ] }
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        isSHA256(response.headers.location.slice(7)),
        'sets Location header')
      var get = {
        path: response.headers.location,
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          var served = JSON.parse(buffer)
          test.same(
            served,
            posted,
            'serves the same form back')
          done()
          test.end() })) }) })
    .end(JSON.stringify(posted)) }) })

tape('POST and GET a deep form', function(test) {
  var form = {
    content: [
      'Some text',
      { heading: 'Some Heading',
        form: { content: [ 'Even more text' ] } } ] }
  var digest = merkleize(form).digest
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        isSHA256(response.headers.location.slice(7)),
        'sets Location header')
      var get = {
        path: ( '/forms/' + digest ),
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          var served = JSON.parse(buffer)
          test.same(
            served, form,
            'serves the same form back')
          done()
          test.end() })) }) })
    .end(JSON.stringify(form)) }) })

tape('POST and GET a child form', function(test) {
  var posted = {
    content: [
      'Some text',
      { heading: 'Some Heading',
        form: { content: [ 'More text!' ] } } ] }
  var child = posted.content[1].form
  var childDigest = merkleize(child).digest
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        isSHA256(response.headers.location.slice(7)),
        'sets Location header')
      var get = {
        path: ( '/forms/' + childDigest ),
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          var served = JSON.parse(buffer)
          test.same(
            served, child,
            'serves the child form back')
          done()
          test.end() })) }) })
    .end(JSON.stringify(posted)) }) })

tape('GET /forms', function(test) {
  var posted = {
    content: [
      'Some text',
      { heading: 'Some Heading',
        form: { content: [ 'More text!' ] } } ] }
  var parentDigest = merkleize(posted).digest
  var childDigest = merkleize(posted.content[1].form).digest
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      var get = {
        path: '/forms',
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          test.same(
            buffer.toString(),
            ( [ parentDigest, childDigest ]
              .sort()
              .join('\n') + '\n' ),
            'serves list of digests')
          done()
          test.end() })) }) })
    .end(JSON.stringify(posted)) }) })
<commit_msg>Test 404 response to GET /forms/<nonexistent><commit_after>var concat = require('concat-stream')
var http = require('http')
var isSHA256 = require('is-sha-256-hex-digest')
var merkleize = require('commonform-merkleize')
var server = require('./server')
var tape = require('tape')

tape('POST / with valid form', function(test) {
  var form = { content: [ 'Some text' ] }
  var digest = merkleize(form).digest
  server(function(port, done) {
    var request = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(request, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        response.headers.hasOwnProperty('location'),
        'sets Location header')
      test.assert(
        response.headers.location.indexOf(digest),
        'location includes digest')
      done()
      test.end() })
    .end(JSON.stringify(form)) }) })

tape('POST / with invalid form', function(test) {
  var form = { blah: 'blah' }
  server(function(port, done) {
    var request = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(request, function(response) {
      test.equal(
        response.statusCode, 400,
        'responds 400')
      done()
      test.end() })
    .end(JSON.stringify(form)) }) })

tape('POST / with non-JSON', function(test) {
  server(function(port, done) {
    var request = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(request, function(response) {
      test.equal(
        response.statusCode, 400,
        'responds 400')
      done()
      test.end() })
    .end('just plain text') }) })

tape('POST and GET a form', function(test) {
  var posted = { content: [ 'Some text' ] }
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        isSHA256(response.headers.location.slice(7)),
        'sets Location header')
      var get = {
        path: response.headers.location,
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          var served = JSON.parse(buffer)
          test.same(
            served,
            posted,
            'serves the same form back')
          done()
          test.end() })) }) })
    .end(JSON.stringify(posted)) }) })

tape('POST and GET a deep form', function(test) {
  var form = {
    content: [
      'Some text',
      { heading: 'Some Heading',
        form: { content: [ 'Even more text' ] } } ] }
  var digest = merkleize(form).digest
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        isSHA256(response.headers.location.slice(7)),
        'sets Location header')
      var get = {
        path: ( '/forms/' + digest ),
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          var served = JSON.parse(buffer)
          test.same(
            served, form,
            'serves the same form back')
          done()
          test.end() })) }) })
    .end(JSON.stringify(form)) }) })

tape('POST and GET a child form', function(test) {
  var posted = {
    content: [
      'Some text',
      { heading: 'Some Heading',
        form: { content: [ 'More text!' ] } } ] }
  var child = posted.content[1].form
  var childDigest = merkleize(child).digest
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      test.assert(
        isSHA256(response.headers.location.slice(7)),
        'sets Location header')
      var get = {
        path: ( '/forms/' + childDigest ),
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          var served = JSON.parse(buffer)
          test.same(
            served, child,
            'serves the child form back')
          done()
          test.end() })) }) })
    .end(JSON.stringify(posted)) }) })

tape('GET a nonexistent form', function(test) {
  var digest = 'a'.repeat(64)
  server(function(port, done) {
    var get = {
      path: ( '/forms/' + digest ),
      port: port }
    http.get(get, function(response) {
      test.equal(
        response.statusCode, 404,
        'responds 404')
      done()
      test.end() }) }) })

tape('GET /forms', function(test) {
  var posted = {
    content: [
      'Some text',
      { heading: 'Some Heading',
        form: { content: [ 'More text!' ] } } ] }
  var parentDigest = merkleize(posted).digest
  var childDigest = merkleize(posted.content[1].form).digest
  server(function(port, done) {
    var post = {
      method: 'POST',
      path: '/forms',
      port: port }
    http.request(post, function(response) {
      test.equal(
        response.statusCode, 201,
        'responds 201')
      var get = {
        path: '/forms',
        port: port }
      http.get(get, function(response) {
        response.pipe(concat(function(buffer) {
          test.same(
            buffer.toString(),
            ( [ parentDigest, childDigest ]
              .sort()
              .join('\n') + '\n' ),
            'serves list of digests')
          done()
          test.end() })) }) })
    .end(JSON.stringify(posted)) }) })
<|endoftext|>


<commit_before>/*
 * View model for OctoPrint-Slicer
 *
 * Author: Kenneth Jiang
 * License: AGPLv3
 */
$(function() {
    function SlicerViewModel(parameters) {
        var self = this;

        // assign the injected parameters, e.g.:
        // self.loginStateViewModel = parameters[0];
        // self.settingsViewModel = parameters[1];

        // TODO: Implement your plugin's view model here.
        $(document).on("click", ".btn-mini[title='Slice']", function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            $('a[href="#tab_plugin_slicer"]').tab('show');
        });

            var container;

            var camera, cameraTarget, scene, renderer,
            CANVAS_WIDTH = 588,
            CANVAS_HEIGHT = 588;

            init();
            animate();

            function init() {
                container = document.getElementById( 'slicer-canvas' );

                camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
                camera.position.set( 3, 0.15, 3 );

                cameraTarget = new THREE.Vector3( 0, -0.25, 0 );

                scene = new THREE.Scene();
                scene.fog = new THREE.Fog( 0x72645b, 2, 15 );

                // Ground

                var plane = new THREE.Mesh(
                    new THREE.PlaneBufferGeometry( 40, 40 ),
                    new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
                );
                plane.rotation.x = -Math.PI/2;
                plane.position.y = -0.5;
                scene.add( plane );

                plane.receiveShadow = true;

                // ASCII file

                var loader = new THREE.STLLoader();
                loader.load( 'http://threejs.org/examples/models/stl/ascii/slotted_disk.stl', function ( geometry ) {

                    var material = new THREE.MeshPhongMaterial( { color: 0xff5533, specular: 0x111111, shininess: 200 } );
                    var mesh = new THREE.Mesh( geometry, material );

                    mesh.position.set( 0, - 0.25, 0.6 );
                    mesh.rotation.set( 0, - Math.PI / 2, 0 );
                    mesh.scale.set( 0.5, 0.5, 0.5 );

                    mesh.castShadow = true;
                    mesh.receiveShadow = true;

                    scene.add( mesh );

                } );

                // Lights

                scene.add( new THREE.HemisphereLight( 0x443333, 0x111122 ) );

                // renderer

                renderer = new THREE.WebGLRenderer( { antialias: true } );
                renderer.setSize( CANVAS_WIDTH, CANVAS_HEIGHT );
                renderer.setClearColor( scene.fog.color );
                renderer.setPixelRatio( window.devicePixelRatio );

                renderer.gammaInput = true;
                renderer.gammaOutput = true;

                renderer.shadowMap.enabled = true;
                renderer.shadowMap.renderReverseSided = false;

                container.appendChild( renderer.domElement );

            }

            function animate() {

                requestAnimationFrame( animate );

                render();
            }

            function render() {

                var timer = Date.now() * 0.0005;

                camera.position.x = Math.cos( timer ) * 3;
                camera.position.z = Math.sin( timer ) * 3;

                camera.lookAt( cameraTarget );

                renderer.render( scene, camera );

            }

//        self.loadSTL(BASEURL + "downloads/files/" + "local" + "/" + "fish_fossilz.stl");
    }

    // view model class, parameters for constructor, container to bind to
    OCTOPRINT_VIEWMODELS.push([
        SlicerViewModel,

        // e.g. loginStateViewModel, settingsViewModel, ...
        [ /* "loginStateViewModel", "settingsViewModel" */ ],

        // e.g. #settings_plugin_slicer, #tab_plugin_slicer, ...
        [ /* ... */ ]
    ]);
});
<commit_msg>trim three.js to the minimum I can for now<commit_after>/*
 * View model for OctoPrint-Slicer
 *
 * Author: Kenneth Jiang
 * License: AGPLv3
 */
$(function() {
    function SlicerViewModel(parameters) {
        var self = this;

        // assign the injected parameters, e.g.:
        // self.loginStateViewModel = parameters[0];
        // self.settingsViewModel = parameters[1];

        // TODO: Implement your plugin's view model here.
        $(document).on("click", ".btn-mini[title='Slice']", function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            $('a[href="#tab_plugin_slicer"]').tab('show');
        });

            var container;

            var camera, cameraTarget, scene, renderer,
            CANVAS_WIDTH = 588,
            CANVAS_HEIGHT = 588;

            init();
            animate();

            function init() {
                container = document.getElementById( 'slicer-canvas' );

                camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
                camera.position.set( 3, 0.15, 3 );

                cameraTarget = new THREE.Vector3( 0, -0.25, 0 );

                scene = new THREE.Scene();

                // ASCII file

                var loader = new THREE.STLLoader();
                loader.load( 'http://threejs.org/examples/models/stl/ascii/slotted_disk.stl', function ( geometry ) {

                    var material = new THREE.MeshPhongMaterial( { color: 0xff5533, specular: 0x111111, shininess: 200 } );
                    var mesh = new THREE.Mesh( geometry, material );

                    mesh.position.set( 0, - 0.25, 0.6 );
                    mesh.rotation.set( 0, - Math.PI / 2, 0 );
                    mesh.scale.set( 0.5, 0.5, 0.5 );

                    mesh.castShadow = true;
                    mesh.receiveShadow = true;

                    scene.add( mesh );

                } );

                // Lights

                scene.add( new THREE.HemisphereLight( 0x443333, 0x111122 ) );

                // renderer

                renderer = new THREE.WebGLRenderer( { antialias: true } );
                renderer.setSize( CANVAS_WIDTH, CANVAS_HEIGHT );
                renderer.setPixelRatio( window.devicePixelRatio );

                renderer.gammaInput = true;
                renderer.gammaOutput = true;

                container.appendChild( renderer.domElement );

            }

            function animate() {

                requestAnimationFrame( animate );

                render();
            }

            function render() {

                camera.lookAt( cameraTarget );

                renderer.render( scene, camera );

            }

//        self.loadSTL(BASEURL + "downloads/files/" + "local" + "/" + "fish_fossilz.stl");
    }

    // view model class, parameters for constructor, container to bind to
    OCTOPRINT_VIEWMODELS.push([
        SlicerViewModel,

        // e.g. loginStateViewModel, settingsViewModel, ...
        [ /* "loginStateViewModel", "settingsViewModel" */ ],

        // e.g. #settings_plugin_slicer, #tab_plugin_slicer, ...
        [ /* ... */ ]
    ]);
});
<|endoftext|>


<commit_before>exports = module.exports = {};

var fs = require("fs"),
    util = require("util"),
    esprima = require("esprima"),
    escodegen = require("escodegen"),
    estraverse = require("estraverse"),
    cp = require("child_process"),
    config = require(__dirname + "/config.js");

var DEBUG = false;
function log_debug(msg) {
    if (DEBUG)
        console.log(msg);
}

//Globals
var tmp_dir,
    // keep track of the number of attempts so far
    round = 0,
    ext,
    ast,
    smallest,
    testSucceededAtLeastOnce;

//Options
var /** only knock out entire statements */
    quick = false,

    /** Repeat until a fixpoint is found */
    findFixpoint = true,

    /** command to invoke to determine success/failure */
    cmd = null,

    /** error message indicating failure of command */
    errmsg = null,

    /** message indicating failure of command, either on stdout or stderr */
    msg = null,

    /** file to minimise */
    file = null,

    /** predicate to use for minimisation */
    predicate = {},

    /** arguments to pass to the predicate */
    predicate_args = [],

    /** file to record predicate results to */
    record = null,

    /** array to read predicate results from */
    replay = null, replay_idx = -1;

function parseOptions(options) {
    quick = options.quick;
    findFixpoint = options.findFixpoint;
    cmd = options.cmd;
    errmsg = options.errmsg;
    msg = options.msg;
    file = options.file;
    predicate = options.predicate;
    predicate_args = options.predicate_args;
    record = options.record;
    replay = options.replay;
    replay_idx = options.replay_idx;
}

exports.main = function (options) {
    parseOptions(options);
    // check that we have something to minimise
    if (!file)
        usage();

        // initialise predicate module
    if (typeof predicate.init === 'function')
        predicate.init(predicate_args);

    // if no predicate module was specified, synthesise one from the other options
    if (!predicate.test) {
        predicate.cmd = predicate.cmd || cmd;

        if (replay) {
            predicate.test = function (fn) {
                var stats = fs.statSync(fn);
                console.log("Testing candidate " + fn +
                    " (" + stats.size + " bytes)");
                var res = replay[replay_idx++] === 'true';
                if (res)
                    console.log("    aborted with relevant error (recorded)");
                else
                    console.log("    completed successfully (recorded)");
                return res;
            };
        } else {
            if (!predicate.cmd) {
                console.error("No test command specified.");
                process.exit(-1);
            }

            if (typeof predicate.checkResult !== 'function') {
                if (errmsg || msg) {
                    predicate.checkResult = function (error, stdout, stderr) {
                        if ((errmsg && stderr && stderr.indexOf(errmsg) !== -1) ||
                            (msg && ((stderr && stderr.indexOf(msg) !== -1) ||
                                (stdout && stdout.indexOf(msg) !== -1)))) {
                            console.log("    aborted with relevant error");
                            return true;
                        } else if (error) {
                            console.log("    aborted with other error");
                            return false;
                        } else {
                            console.log("    completed successfully");
                            return false;
                        }
                    };
                } else {
                    predicate.checkResult = function (error, stdout, stderr) {
                        if (error) {
                            console.log("    aborted with error");
                            return true;
                        } else {
                            console.log("    completed successfully");
                            return false;
                        }
                    };
                }
            }

            predicate.test = function (fn) {
                var stats = fs.statSync(fn);
                console.log("Testing candidate " + fn +
                    " (" + stats.size + " bytes)");
                var start = new Date();
                var stdout_file = fn + ".stdout",
                    stderr_file = fn + ".stderr";
                var error = deltalib.execSync(predicate.cmd + " '" + fn + "'" +
                    " >'" + stdout_file + "'" +
                    " 2>'" + stderr_file + "'");
                var end = new Date();
                var stdout = fs.readFileSync(stdout_file, "utf-8"),
                    stderr = fs.readFileSync(stderr_file, "utf-8");
                return predicate.checkResult(error, stdout, stderr, end - start);
            };
        }
    }

    var src = fs.readFileSync(file, 'utf-8');

    // figure out file extension; default is 'js'
    ext = (file.match(/\.(\w+)$/) || [, 'js'])[1]
    // hack to make JSON work
    if (ext === 'json')
        src = '(' + src + ')';

    // parse given file
    ast = esprima.parse(src);

    // determine a suitable temporary directory
    for (i = 0; fs.existsSync(tmp_dir = config.tmp_dir + "/tmp" + i); ++i);
    fs.mkdirSync(tmp_dir);

    // the smallest test case so far is kept here
    smallest = tmp_dir + "/delta_js_smallest." + ext;

    testSucceededAtLeastOnce = false;
    // test the current test case

    // save a copy of the original input
    var orig = getTempFileName(),
        input = fs.readFileSync(file, 'utf-8');
    fs.writeFileSync(orig, input);
    fs.writeFileSync(smallest, input);

    // get started
    var res = predicate.test(orig);
    if (record)
        fs.appendFileSync(record, !!res + "\n");
    if (res) {
        if (findFixpoint) {
            var iterations = 0;
            do {
                testSucceededAtLeastOnce = false;
                console.log("Starting fixpoint iteration #%d", ++iterations);
                minimise(ast, null, -1);
            } while (testSucceededAtLeastOnce);
        } else {
            minimise(ast, null, -1);
        }
        var stats = fs.statSync(smallest);
        if (stats.size < 2000) {
            // small enough to display
            console.log();
            console.log(fs.readFileSync(smallest, 'utf8'));
            console.log();
        }
        console.log("Minimisation finished; final version is in %s (%d bytes)", smallest, stats.size);
        process.exit(0);
    } else {
        console.error("Original file doesn't satisfy predicate.");
        process.exit(-1);
    }
}

function minimise_array(array, nonempty) {
    log_debug("minimising array " + util.inspect(array, false, 1));
    if (!nonempty && array.length === 1) {
		// special case: if there is only one element, try removing it
		var elt = array[0];
		array.length = 0;
		if (!test())
			// didn't work, need to put it back
			array[0] = elt;
    } else {
		// try removing as many chunks of size sz from array as possible
		// once we're done, switch to size sz/2; if size drops to zero,
		// recursively invoke minimise on the individual elements
		// of the array
		for (var sz = array.length >>> 1; sz > 0; sz >>>= 1) {
			log_debug("  chunk size " + sz);
			var nchunks = Math.floor(array.length / sz);
			for (var i = nchunks - 1; i >= 0; --i) {
				// try removing chunk i
				log_debug("    chunk #" + i);
				var lo = i * sz,
					hi = i === nchunks - 1 ? array.length : (i + 1) * sz;

				// avoid creating empty array if nonempty is set
				if (!nonempty || lo > 0 || hi < array.length) {
					var removed = array.splice(lo, hi - lo);
					if (!test()) {
						// didn't work, need to put it back
						Array.prototype.splice.apply(array,
							[lo, 0].concat(removed));
					}
				}
			}
		}
    }

    // now minimise each element in turn
    for (var i = 0; i < array.length; ++i)
		minimise(array[i], array, i);
}

// the main minimisation function
function minimise(nd, parent, idx) {
    if (typeof parent === 'string') {
		idx = parent;
		parent = nd;
		nd = parent[idx];
    }

    if (!nd || typeof nd !== 'object')
		return;

    log_debug("minimising " + util.inspect(nd));
    switch (nd.type) {
		case 'Program':
			minimise_array(nd.body);
			break;
		case 'BlockStatement':
			// knock out as many statements in the block as possible
			// if we end up with a single statement, replace the block with
			// that statement
			minimise_array(nd.body);
			if (!quick && nd.body.length === 1)
				Replace(parent, idx).With(nd.body[0]);
			break;
		case 'FunctionDeclaration':
		case 'FunctionExpression':
			if (!quick) {
				if (nd.type === 'FunctionExpression')
					Replace(nd, 'name').With(null);
				minimise_array(nd.params);
			}
			minimise_array(nd.body.body);
			break;
		case 'ObjectExpression':
			minimise_array(nd.properties);
			break;
		case 'VariableDeclaration':
			minimise_array(nd.declarations, true);
			break;
		default:
			// match other node types only if we're not doing quick minimisation
			// if quick is set, !quick && ndtp will be undefined, so the
			// default branch is taken
			switch (!quick && nd.type) {
				case 'Literal':
					return;
				case 'UnaryExpression':
				case 'UpdateExpression':
					// try replacing with operand
					if (Replace(parent, idx).With(nd.argument))
						minimise(parent, idx);
					else
						minimise(nd, 'argument');
					break;
				case 'AssignmentExpression':
				case 'BinaryExpression':
				case 'LogicalExpression':
					if (Replace(parent, idx).With(nd.left))
						minimise(parent, idx);
					else if (Replace(parent, idx).With(nd.right))
						minimise(parent, idx);
					else {
						minimise(nd, 'left');
						minimise(nd, 'right');
					}
					break;
				case 'ReturnStatement':
					if (nd.argument && !Replace(nd, 'argument').With(null))
						minimise(nd, 'argument');
					break;
				case 'CallExpression':
				case 'NewExpression':
					minimise(nd, 'callee');
					minimise_array(nd['arguments']);
					break;
				case 'ArrayExpression':
					minimise_array(nd.elements);
					break;
				case 'IfStatement':
				case 'ConditionalExpression':
					if (Replace(parent, idx).With(nd.consequent))
						minimise(parent, idx);
					else if (nd.alternate && Replace(parent, idx).With(nd.alternate))
						minimise(parent, idx);
					else if (Replace(parent, idx).With(nd.test))
						minimise(parent, idx);
					else {
						minimise(nd, 'test');
						minimise(nd, 'consequent');
						minimise(nd, 'alternate');
					}
					break;
				case 'SwitchStatement':
					minimise(nd, 'discriminant');
					minimise_array(nd.cases);
					break;
				case 'WhileStatement':
					if (Replace(parent, idx).With(nd.body))
						minimise(parent, idx);
					else if (Replace(parent, idx).With(nd.test))
						minimise(parent, idx);
					else {
						minimise(nd, 'test');
						minimise(nd, 'body');
					}
					break;
				case 'ForStatement':
					Replace(nd, 'test').With(null);
					Replace(nd, 'update').With(null);
					if (Replace(parent, idx).With(nd.body))
						minimise(parent, idx);
					else if (nd.test && Replace(parent, idx).With(nd.test))
						minimise(parent, idx);
					else {
						minimise(nd, 'init');
						minimise(nd, 'test');
						minimise(nd, 'update');
						minimise(nd, 'body');
					}
					break;
				default:
					if (Array.isArray(nd)) {
						minimise_array(nd);
					} else {
						estraverse.VisitorKeys[nd.type].forEach(function (ch) {
							if (!quick || ch !== 'arguments') {
								minimise(nd, ch);
							}
						});
					}
			}
    }
}

function pp(ast) {
    // we pass the 'parse' option here to avoid converting 0.0 to 0, etc.;
    // for JSON files, we skip the top-level `Program` and `ExpressionStatement`
    // nodes to prevent escodegen from inserting spurious parentheses
    return escodegen.generate(ext === 'json' && ast.body[0] ? ast.body[0].expression : ast, {
		format: {
			json: ext === 'json'
		},
        parse: esprima.parse
    });
}

// write the current test case out to disk
function writeTempFile() {
    var fn = getTempFileName();
    fs.writeFileSync(fn, pp(ast));
    return fn;
}

function test() {
    var fn = writeTempFile();
    var res = predicate.test(fn);
    if (record)
		fs.appendFileSync(record, !!res + "\n");
    if (res) {
        testSucceededAtLeastOnce = true;
		// if the test succeeded, save it to file 'smallest'
		fs.writeFileSync(smallest, pp(ast));
		return true;
    } else {
		return false;
    }
}

function Replace(nd, idx) {
    var oldval = nd[idx];
    return {
		With: function (newval) {
			if (oldval === newval) {
				return true;
			} else {
				nd[idx] = newval;
				if (test()) {
					return true;
				} else {
					nd[idx] = oldval;
					return false;
				}
			}
		}
    };
}

execSync = function (cmd) {
    if (cp.execSync) {
        // node v0.12; use the built-in functionality
        try {
            cp.execSync(cmd);
            return false;
        } catch (e) {
            return true;
        }
    } else {
        // node v0.10; fall back on execSync package
        return require("execSync").run(cmd);
    }
}

// get name of current test case
getTempFileName = function () {
    var fn = tmp_dir + "/delta_js_" + round + "." + ext;
    ++round;
    return fn;
}
<commit_msg>Add minimal interface for jsdelta-multifile<commit_after>exports = module.exports = {};

var fs = require("fs"),
    util = require("util"),
    esprima = require("esprima"),
    escodegen = require("escodegen"),
    estraverse = require("estraverse"),
    cp = require("child_process"),
    config = require(__dirname + "/config.js");

var DEBUG = false;
function log_debug(msg) {
    if (DEBUG)
        console.log(msg);
}

//Globals
var tmp_dir,
    // keep track of the number of attempts so far
    round = 0,
    ext,
    ast,
    smallest,
    testSucceededAtLeastOnce;

//Options
var /** only knock out entire statements */
    quick = false,

    /** Repeat until a fixpoint is found */
    findFixpoint = true,

    /** command to invoke to determine success/failure */
    cmd = null,

    /** error message indicating failure of command */
    errmsg = null,

    /** message indicating failure of command, either on stdout or stderr */
    msg = null,

    /** file to minimise */
    file = null,

    /** predicate to use for minimisation */
    predicate = {},

    /** arguments to pass to the predicate */
    predicate_args = [],

    /** file to record predicate results to */
    record = null,

    /** array to read predicate results from */
    replay = null, replay_idx = -1;

function parseOptions(options) {
    quick = options.quick;
    findFixpoint = options.findFixpoint;
    cmd = options.cmd;
    errmsg = options.errmsg;
    msg = options.msg;
    file = options.file;
    predicate = options.predicate;
    predicate_args = options.predicate_args;
    record = options.record;
    replay = options.replay;
    replay_idx = options.replay_idx;
}

exports.main = function (options) {
    parseOptions(options);
    // check that we have something to minimise
    if (!file)
        usage();

        // initialise predicate module
    if (typeof predicate.init === 'function')
        predicate.init(predicate_args);

    // if no predicate module was specified, synthesise one from the other options
    if (!predicate.test) {
        predicate.cmd = predicate.cmd || cmd;

        if (replay) {
            predicate.test = function (fn) {
                var stats = fs.statSync(fn);
                console.log("Testing candidate " + fn +
                    " (" + stats.size + " bytes)");
                var res = replay[replay_idx++] === 'true';
                if (res)
                    console.log("    aborted with relevant error (recorded)");
                else
                    console.log("    completed successfully (recorded)");
                return res;
            };
        } else {
            if (!predicate.cmd) {
                console.error("No test command specified.");
                process.exit(-1);
            }

            if (typeof predicate.checkResult !== 'function') {
                if (errmsg || msg) {
                    predicate.checkResult = function (error, stdout, stderr) {
                        if ((errmsg && stderr && stderr.indexOf(errmsg) !== -1) ||
                            (msg && ((stderr && stderr.indexOf(msg) !== -1) ||
                                (stdout && stdout.indexOf(msg) !== -1)))) {
                            console.log("    aborted with relevant error");
                            return true;
                        } else if (error) {
                            console.log("    aborted with other error");
                            return false;
                        } else {
                            console.log("    completed successfully");
                            return false;
                        }
                    };
                } else {
                    predicate.checkResult = function (error, stdout, stderr) {
                        if (error) {
                            console.log("    aborted with error");
                            return true;
                        } else {
                            console.log("    completed successfully");
                            return false;
                        }
                    };
                }
            }

            predicate.test = function (fn) {
                var stats = fs.statSync(fn);
                console.log("Testing candidate " + fn +
                    " (" + stats.size + " bytes)");
                var start = new Date();
                var stdout_file = fn + ".stdout",
                    stderr_file = fn + ".stderr";
                var error = deltalib.execSync(predicate.cmd + " '" + fn + "'" +
                    " >'" + stdout_file + "'" +
                    " 2>'" + stderr_file + "'");
                var end = new Date();
                var stdout = fs.readFileSync(stdout_file, "utf-8"),
                    stderr = fs.readFileSync(stderr_file, "utf-8");
                return predicate.checkResult(error, stdout, stderr, end - start);
            };
        }
    }

    var src = fs.readFileSync(file, 'utf-8');

    // figure out file extension; default is 'js'
    ext = (file.match(/\.(\w+)$/) || [, 'js'])[1]
    // hack to make JSON work
    if (ext === 'json')
        src = '(' + src + ')';

    // parse given file
    ast = esprima.parse(src);

    // determine a suitable temporary directory
    for (i = 0; fs.existsSync(tmp_dir = config.tmp_dir + "/tmp" + i); ++i);
    fs.mkdirSync(tmp_dir);

    // the smallest test case so far is kept here
    smallest = tmp_dir + "/delta_js_smallest." + ext;

    testSucceededAtLeastOnce = false;
    // test the current test case

    // save a copy of the original input
    var orig = getTempFileName(),
        input = fs.readFileSync(file, 'utf-8');
    fs.writeFileSync(orig, input);
    fs.writeFileSync(smallest, input);

    // get started
    var res = predicate.test(orig);
    if (record)
        fs.appendFileSync(record, !!res + "\n");
    if (res) {
        if (findFixpoint) {
            var iterations = 0;
            do {
                testSucceededAtLeastOnce = false;
                console.log("Starting fixpoint iteration #%d", ++iterations);
                minimise(ast, null, -1);
            } while (testSucceededAtLeastOnce);
        } else {
            minimise(ast, null, -1);
        }
        var stats = fs.statSync(smallest);
        if (stats.size < 2000) {
            // small enough to display
            console.log();
            console.log(fs.readFileSync(smallest, 'utf8'));
            console.log();
        }
        console.log("Minimisation finished; final version is in %s (%d bytes)", smallest, stats.size);
        process.exit(0);
    } else {
        console.error("Original file doesn't satisfy predicate.");
        process.exit(-1);
    }
}

function minimise_array(array, nonempty) {
    log_debug("minimising array " + util.inspect(array, false, 1));
    if (!nonempty && array.length === 1) {
		// special case: if there is only one element, try removing it
		var elt = array[0];
		array.length = 0;
		if (!test())
			// didn't work, need to put it back
			array[0] = elt;
    } else {
		// try removing as many chunks of size sz from array as possible
		// once we're done, switch to size sz/2; if size drops to zero,
		// recursively invoke minimise on the individual elements
		// of the array
		for (var sz = array.length >>> 1; sz > 0; sz >>>= 1) {
			log_debug("  chunk size " + sz);
			var nchunks = Math.floor(array.length / sz);
			for (var i = nchunks - 1; i >= 0; --i) {
				// try removing chunk i
				log_debug("    chunk #" + i);
				var lo = i * sz,
					hi = i === nchunks - 1 ? array.length : (i + 1) * sz;

				// avoid creating empty array if nonempty is set
				if (!nonempty || lo > 0 || hi < array.length) {
					var removed = array.splice(lo, hi - lo);
					if (!test()) {
						// didn't work, need to put it back
						Array.prototype.splice.apply(array,
							[lo, 0].concat(removed));
					}
				}
			}
		}
    }

    // now minimise each element in turn
    for (var i = 0; i < array.length; ++i)
		minimise(array[i], array, i);
}

// the main minimisation function
function minimise(nd, parent, idx) {
    if (typeof parent === 'string') {
		idx = parent;
		parent = nd;
		nd = parent[idx];
    }

    if (!nd || typeof nd !== 'object')
		return;

    log_debug("minimising " + util.inspect(nd));
    switch (nd.type) {
		case 'Program':
			minimise_array(nd.body);
			break;
		case 'BlockStatement':
			// knock out as many statements in the block as possible
			// if we end up with a single statement, replace the block with
			// that statement
			minimise_array(nd.body);
			if (!quick && nd.body.length === 1)
				Replace(parent, idx).With(nd.body[0]);
			break;
		case 'FunctionDeclaration':
		case 'FunctionExpression':
			if (!quick) {
				if (nd.type === 'FunctionExpression')
					Replace(nd, 'name').With(null);
				minimise_array(nd.params);
			}
			minimise_array(nd.body.body);
			break;
		case 'ObjectExpression':
			minimise_array(nd.properties);
			break;
		case 'VariableDeclaration':
			minimise_array(nd.declarations, true);
			break;
		default:
			// match other node types only if we're not doing quick minimisation
			// if quick is set, !quick && ndtp will be undefined, so the
			// default branch is taken
			switch (!quick && nd.type) {
				case 'Literal':
					return;
				case 'UnaryExpression':
				case 'UpdateExpression':
					// try replacing with operand
					if (Replace(parent, idx).With(nd.argument))
						minimise(parent, idx);
					else
						minimise(nd, 'argument');
					break;
				case 'AssignmentExpression':
				case 'BinaryExpression':
				case 'LogicalExpression':
					if (Replace(parent, idx).With(nd.left))
						minimise(parent, idx);
					else if (Replace(parent, idx).With(nd.right))
						minimise(parent, idx);
					else {
						minimise(nd, 'left');
						minimise(nd, 'right');
					}
					break;
				case 'ReturnStatement':
					if (nd.argument && !Replace(nd, 'argument').With(null))
						minimise(nd, 'argument');
					break;
				case 'CallExpression':
				case 'NewExpression':
					minimise(nd, 'callee');
					minimise_array(nd['arguments']);
					break;
				case 'ArrayExpression':
					minimise_array(nd.elements);
					break;
				case 'IfStatement':
				case 'ConditionalExpression':
					if (Replace(parent, idx).With(nd.consequent))
						minimise(parent, idx);
					else if (nd.alternate && Replace(parent, idx).With(nd.alternate))
						minimise(parent, idx);
					else if (Replace(parent, idx).With(nd.test))
						minimise(parent, idx);
					else {
						minimise(nd, 'test');
						minimise(nd, 'consequent');
						minimise(nd, 'alternate');
					}
					break;
				case 'SwitchStatement':
					minimise(nd, 'discriminant');
					minimise_array(nd.cases);
					break;
				case 'WhileStatement':
					if (Replace(parent, idx).With(nd.body))
						minimise(parent, idx);
					else if (Replace(parent, idx).With(nd.test))
						minimise(parent, idx);
					else {
						minimise(nd, 'test');
						minimise(nd, 'body');
					}
					break;
				case 'ForStatement':
					Replace(nd, 'test').With(null);
					Replace(nd, 'update').With(null);
					if (Replace(parent, idx).With(nd.body))
						minimise(parent, idx);
					else if (nd.test && Replace(parent, idx).With(nd.test))
						minimise(parent, idx);
					else {
						minimise(nd, 'init');
						minimise(nd, 'test');
						minimise(nd, 'update');
						minimise(nd, 'body');
					}
					break;
				default:
					if (Array.isArray(nd)) {
						minimise_array(nd);
					} else {
						estraverse.VisitorKeys[nd.type].forEach(function (ch) {
							if (!quick || ch !== 'arguments') {
								minimise(nd, ch);
							}
						});
					}
			}
    }
}

function pp(ast) {
    // we pass the 'parse' option here to avoid converting 0.0 to 0, etc.;
    // for JSON files, we skip the top-level `Program` and `ExpressionStatement`
    // nodes to prevent escodegen from inserting spurious parentheses
    return escodegen.generate(ext === 'json' && ast.body[0] ? ast.body[0].expression : ast, {
		format: {
			json: ext === 'json'
		},
        parse: esprima.parse
    });
}

// write the current test case out to disk
function writeTempFile() {
    var fn = getTempFileName();
    fs.writeFileSync(fn, pp(ast));
    return fn;
}

function test() {
    var fn = writeTempFile();
    var res = predicate.test(fn);
    if (record)
		fs.appendFileSync(record, !!res + "\n");
    if (res) {
        testSucceededAtLeastOnce = true;
		// if the test succeeded, save it to file 'smallest'
		fs.writeFileSync(smallest, pp(ast));
		return true;
    } else {
		return false;
    }
}

function Replace(nd, idx) {
    var oldval = nd[idx];
    return {
		With: function (newval) {
			if (oldval === newval) {
				return true;
			} else {
				nd[idx] = newval;
				if (test()) {
					return true;
				} else {
					nd[idx] = oldval;
					return false;
				}
			}
		}
    };
}

execSync = function (cmd) {
    if (cp.execSync) {
        // node v0.12; use the built-in functionality
        try {
            cp.execSync(cmd);
            return false;
        } catch (e) {
            return true;
        }
    } else {
        // node v0.10; fall back on execSync package
        return require("execSync").run(cmd);
    }
}

// get name of current test case
getTempFileName = function () {
    var fn = tmp_dir + "/delta_js_" + round + "." + ext;
    ++round;
    return fn;
}
<|endoftext|>


<commit_before>var sjsc = require('sockjs-client');
var noop = function() {};

var User = function(host) {
  this.socket = sjsc.create(host + "/christmas");

  this.user = {
    live: {}
  };

  this.me = {
    country: "US",
    transport: "xhr-streaming",
    browser: "test.js",
    version: "0.1",
    os: "node"
  };

  this.init();
}

User.prototype = {
  init: function() {
    var self = this;

    this.socket.on('connection', function () {
      console.log("= Connection established")
    });

    this.socket.on('data', function (msg) {
      var data = JSON.parse(msg);
      (self[data._event] || noop).apply(self, [data]);
    });

    this.socket.on('error', function (e) {
      console.log("Error: " + e);
    });
  },

  emit: function(event, data) {
    data = data || {};
    data._event = event;
    this.socket.write(JSON.stringify(data));
  },

  hello: function(data) {
    this.me.id = data._user_id;
    this.me.server = data.server;
    console.log("= Assigned ID: " + this.me.id);

    // server-overridden socket options
    for (var key in data.live)
      this.user.live[key] = data.live[key];

    // very simple heartbeat, only for server's sake
    var self = this;
    var heartbeat = setInterval(function() {
      self.emit('heartbeat', self.me)
    }, 3000);

    this.emit('arrive', this.me);
  },

  ratelimit: function(fn) {
    var last = (new Date()).getTime();
    return (function() {
      var now = (new Date()).getTime();
      if ((now - last) > this.user.live.mouse_rate) {
        last = now;
        fn.apply(null, arguments);
      }
    });
  }
}

/****** test client *****/
// test clients should send a bunch of events but not process received motion/etc
// the main purpose is to test server throughput,
// and to connect browser clients to the server while these are running,
// to observe how browsers handle many people sending events

function connect(host) {
  if (!host) host = "http://localhost:3000"
  return new User(host);
}

module.exports = {connect: connect};

/* test in repl with

var u = require("./test").connect();

*/<commit_msg>Actual useful test file<commit_after>var sjsc = require('sockjs-client');
var noop = function() {};

function start() {
  for (var n=0; n<4; n++)
    new User("http://localhost:3000", n);
}

/****** test client *****/
// test clients should send a bunch of events but not process received motion/etc
// the main purpose is to test server throughput,
// and to connect browser clients to the server while these are running,
// to observe how browsers handle many people sending events

var mouse_rate = 40;
var move_rate = 10;

var User = function(host, n) {
  if (!n) n = 0;

  this.user = {
    live: {}
  };

  this.me = {
    country: "US",
    transport: "xhr-streaming",
    browser: "test.js",
    version: "0.1",
    os: "node"
  };

  this.n = n;
  this.x = 0;
  this.y = 0;
  this.leg = 1;

  this.host = host;
  this.init();
}

User.prototype = {
  init: function() {
    var self = this;

    this.socket = sjsc.create(this.host + "/christmas");

    this.socket.on('connection', function () {
      console.log("= Connected: " + self.n)
    });

    this.socket.on('data', function (msg) {
      var data = JSON.parse(msg);
      (self.events[data._event] || noop).apply(self, [data]);
    });

    this.socket.on('error', function (e) {
      console.log("Error: " + e);
    });
  },

  emit: function(event, data) {
    data = data || {};
    data._event = event;
    this.socket.write(JSON.stringify(data));
  },

  events: {
    arrive: function(data) {
      this.emit("here", {
        to: data.id,
        id: this.me.id,
        country: this.me.country,
        transport: this.me.transport
      });
    },

    hello: function(data) {
      this.me.id = data._user_id;
      this.me.server = data.server;
      // console.log("= Assigned ID: " + this.me.id);

      // server-overridden socket options
      for (var key in data.live)
        this.user.live[key] = data.live[key];

      // very simple heartbeat, only for server's sake
      var self = this;
      var heartbeat = setInterval(function() {
        self.emit('heartbeat', self.me)
      }, 3000);

      this.emit('arrive', this.me);

      // kick off automated motion
      var motion = setInterval(function() {
        self.move.apply(self);
      }, mouse_rate);
    }
  },

  move: function() {
    this.emit('motion', {
      x: this.x + (this.n * 10),
      y: this.y + (this.n * 10),
      id: this.me.id,
      country: this.me.country
    });

    if (this.leg == 1) {
      if (this.x < 400)
        this.x += move_rate;
      else
        this.leg = 2;
    }
    if (this.leg == 2) {
      if (this.y < 400)
        this.y += move_rate;
      else
        this.leg = 3;
    }
    if (this.leg == 3) {
      if (this.x > 0)
        this.x -= move_rate;
      else
        this.leg = 4;
    }
    if (this.leg == 4) {
      if (this.y > 0)
        this.y -= move_rate;
      else
        this.leg = 1;
    }
  }

}

start();<|endoftext|>


<commit_before>var _ = require('underscore');
var moment = require('moment');
var d3 = require('d3');

var AGGREGATION_FORMATS = {
  minute: {
    display: 'HH:mm L',
    unit: 'm'
  },
  hour: {
    display: 'HH:mm L',
    unit: 'h'
  },
  day: {
    display: 'Do MMM YYYY',
    unit: 'd'
  },
  week: {
    display: 'Do MMM YYYY',
    unit: 'w'
  },
  month: {
    display: 'MMM YYYY',
    unit: 'M'
  },
  quarter: {
    display: '[Q]Q YYYY',
    unit: 'Q'
  },
  year: {
    display: 'YYYY',
    unit: 'y'
  }
};

var format = {};

format.formatNumber = function (value, unit) {
  if (!_.isNumber(value) || value === 0) {
    return value;
  }

  var format = d3.format('.2s');
  var p = 0;
  var abs_v = Math.abs(value);

  if (value > 1000) {
    value = format(value) + (unit ? ' ' + unit : '');
    return value;
  }

  if (abs_v > 100) {
    p = 0;
  } else if (abs_v > 10) {
    p = 1;
  } else if (abs_v > 1) {
    p = 2;
  } else if (abs_v > 0) {
    p = Math.max(Math.ceil(Math.abs(Math.log(abs_v) / Math.log(10))) + 2, 3);
  }

  value = value.toFixed(p);
  var m = value.match(/(\.0+)$/);
  if (m) {
    value = value.replace(m[0], '');
  }

  return value;
};

format.formatDate = function (value) {
  return d3.time.format('%Y-%m-%d')(value);
};

format.formatTime = function (value) {
  return d3.time.format('%H:%M:%S %d/%m/%Y')(value);
};

format.timeFactory = function (format) {
  return d3.time.format(format);
};

format.formatValue = function (value) {
  if (_.isNumber(value)) {
    return format.formatNumber(value);
  }
  if (_.isDate(value)) {
    return format.formatDate(value);
  }
  return value;
};

format.timestampFactory = function (aggregation) {
  return function (timestamp) {
    if (!_.has(AGGREGATION_FORMATS, aggregation)) {
      return '-';
    }

    var format = AGGREGATION_FORMATS[aggregation];
    var date = moment.unix(timestamp).utc();
    return date.format(format.display);
  };
};

module.exports = format;
<commit_msg>Allow formatter to show seconds<commit_after>var _ = require('underscore');
var moment = require('moment');
var d3 = require('d3');

var AGGREGATION_FORMATS = {
  second: {
    display: 'HH:mm:ss',
    unit: 's'
  },
  minute: {
    display: 'HH:mm L',
    unit: 'm'
  },
  hour: {
    display: 'HH:mm L',
    unit: 'h'
  },
  day: {
    display: 'Do MMM YYYY',
    unit: 'd'
  },
  week: {
    display: 'Do MMM YYYY',
    unit: 'w'
  },
  month: {
    display: 'MMM YYYY',
    unit: 'M'
  },
  quarter: {
    display: '[Q]Q YYYY',
    unit: 'Q'
  },
  year: {
    display: 'YYYY',
    unit: 'y'
  }
};

var format = {};

format.formatNumber = function (value, unit) {
  if (!_.isNumber(value) || value === 0) {
    return value;
  }

  var format = d3.format('.2s');
  var p = 0;
  var abs_v = Math.abs(value);

  if (value > 1000) {
    value = format(value) + (unit ? ' ' + unit : '');
    return value;
  }

  if (abs_v > 100) {
    p = 0;
  } else if (abs_v > 10) {
    p = 1;
  } else if (abs_v > 1) {
    p = 2;
  } else if (abs_v > 0) {
    p = Math.max(Math.ceil(Math.abs(Math.log(abs_v) / Math.log(10))) + 2, 3);
  }

  value = value.toFixed(p);
  var m = value.match(/(\.0+)$/);
  if (m) {
    value = value.replace(m[0], '');
  }

  return value;
};

format.formatDate = function (value) {
  return d3.time.format('%Y-%m-%d')(value);
};

format.formatTime = function (value) {
  return d3.time.format('%H:%M:%S %d/%m/%Y')(value);
};

format.timeFactory = function (format) {
  return d3.time.format(format);
};

format.formatValue = function (value) {
  if (_.isNumber(value)) {
    return format.formatNumber(value);
  }
  if (_.isDate(value)) {
    return format.formatDate(value);
  }
  return value;
};

format.timestampFactory = function (aggregation) {
  return function (timestamp) {
    if (!_.has(AGGREGATION_FORMATS, aggregation)) {
      return '-';
    }

    var format = AGGREGATION_FORMATS[aggregation];
    var date = moment.unix(timestamp).utc();
    return date.format(format.display);
  };
};

module.exports = format;
<|endoftext|>


<commit_before>function convertDataFromGoogleSpreadsheetsJson(data) {
    var feedEntries = data.feed.entry;
    var features = [];

    function transformEntry(jsonEntry) {
        var currentPropertiesText = jsonEntry['content']['$t'];

        // var propsArray = currentPropertiesText.split(", ");
        var re = /(\w+): (.+?(?=(?:, \w+:|$)))/mgi;
        var propsArray = re.exec(currentPropertiesText)
        var props = {};

        while (propsArray != null) {

            var propName = propsArray[1];
            var propValue = propsArray[2];

            props[propName] = propValue;

            propsArray = re.exec(currentPropertiesText);
        }

        if (!props['longitude'] || !props['latitude']) {
            return null;
        }

        props['longitude'] = parseFloat(props['longitude'].replace(",", "."));
        props['latitude'] = parseFloat(props['latitude'].replace(",", "."));

        if (props['website'].search("http") == -1) {
		  props['website'] = "http://" + props['website'];
		}

        function fixFundingRaised() {
            var number = props['fundingraised'];
            if (!number) {
                number = "0";
            }

            if (number.indexOf('-') > 0) {
                number = number.split('-');
                number = number[0].trim()
            }

            number = number.replace(/\D/g, '');
            number = number.trim();

            number = parseInt(number);

            return number;
        }

        function fixEmployeeCount() {
            var number = props['headcount'];

            if (!number) {
                number = "0";
            }

            number = number.replace(/\D/g, '');
            number = number.trim();

            number = parseInt(number);

            return number;
        }

        function fixRevenues() {
            var number = props['revenues'];

            if (!number) {
                number = "0";
            }
            if (number.indexOf('-') > 0) {
                number = number.split('-');
                number = number[0].trim()
            }
            number = number.replace(/\D/g, '');
            number = number.trim();
            number = parseInt(number);

            return number;
        }

        props['fundingraised'] = fixFundingRaised();
        props['headcount'] = fixEmployeeCount();
        props['revenues'] = fixRevenues();

        if (!props['typetechcompanyofficeproviderfund']) {
            props['typetechcompanyofficeproviderfund'] = "";
        }

        return {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    props['longitude'],
                    props['latitude']
                ]
            },
            "properties": {
                "title": jsonEntry['title']['$t'],
                "address": props['address'],
                "contactPerson": props['contactperson'],
                "contactPhone": props['contactphone'],
                "contactEmail": props['contactemail'],
                "pictureUrl": props['logolink'],
                "websiteUrl": props['website'],
                "revenues": props['revenues'],
                "headcount": props['headcount'],
                "fundingraised": props['fundingraised'],
                "industrycategorytype": props['industrycategorytype'],
                "typetechcompanyofficeproviderfund": props['typetechcompanyofficeproviderfund'],
                "color": "blue",
                "icon": "building"
            }
        };
    }

    for (var i = 0; i < feedEntries.length; i++) {
        var geoEntry = transformEntry(feedEntries[i]);
        if (!geoEntry) {
            console.warn("Skipping ", feedEntries[i]);
            continue;
        }
        features.push(geoEntry);
    }

    return features;
}
<commit_msg>Add type filter<commit_after>function convertDataFromGoogleSpreadsheetsJson(data) {
    var feedEntries = data.feed.entry;
    var features = [];

    function transformEntry(jsonEntry) {
        var currentPropertiesText = jsonEntry['content']['$t'];

        // var propsArray = currentPropertiesText.split(", ");
        var re = /(\w+): (.+?(?=(?:, \w+:|$)))/mgi;
        var propsArray = re.exec(currentPropertiesText)
        var props = {};

        while (propsArray != null) {

            var propName = propsArray[1];
            var propValue = propsArray[2];

            props[propName] = propValue;

            propsArray = re.exec(currentPropertiesText);
        }

        if (!props['longitude'] || !props['latitude']) {
            return null;
        }

        props['longitude'] = parseFloat(props['longitude'].replace(",", "."));
        props['latitude'] = parseFloat(props['latitude'].replace(",", "."));

        if (props['website'].search("http") == -1) {
            props['website'] = "http://" + props['website'];
        }

        function fixFundingRaised() {
            var number = props['fundingraised'];
            if (!number) {
                number = "0";
            }

            if (number.indexOf('-') > 0) {
                number = number.split('-');
                number = number[0].trim()
            }

            number = number.replace(/\D/g, '');
            number = number.trim();

            number = parseInt(number);

            return number;
        }

        function fixEmployeeCount() {
            var number = props['headcount'];

            if (!number) {
                number = "0";
            }

            number = number.replace(/\D/g, '');
            number = number.trim();

            number = parseInt(number);

            return number;
        }

        function fixRevenues() {
            var number = props['revenues'];

            if (!number) {
                number = "0";
            }
            if (number.indexOf('-') > 0) {
                number = number.split('-');
                number = number[0].trim()
            }
            number = number.replace(/\D/g, '');
            number = number.trim();
            number = parseInt(number);

            return number;
        }

        props['fundingraised'] = fixFundingRaised();
        props['headcount'] = fixEmployeeCount();
        props['revenues'] = fixRevenues();

        if (!props['typetechcompanyofficeproviderfund']) {
            props['typetechcompanyofficeproviderfund'] = "";
        }

        if (!props['industrycategorytype']) {
            props['industrycategorytype'] = "";
        }

        return {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    props['longitude'],
                    props['latitude']
                ]
            },
            "properties": {
                "title": jsonEntry['title']['$t'],
                "address": props['address'],
                "contactPerson": props['contactperson'],
                "contactPhone": props['contactphone'],
                "contactEmail": props['contactemail'],
                "pictureUrl": props['logolink'],
                "websiteUrl": props['website'],
                "revenues": props['revenues'],
                "headcount": props['headcount'],
                "fundingraised": props['fundingraised'],
                "industrycategorytype": props['industrycategorytype'],
                "typetechcompanyofficeproviderfund": props['typetechcompanyofficeproviderfund'],
                "color": "blue",
                "icon": "building"
            }
        };
    }

    for (var i = 0; i < feedEntries.length; i++) {
        var geoEntry = transformEntry(feedEntries[i]);
        if (!geoEntry) {
            console.warn("Skipping ", feedEntries[i]);
            continue;
        }
        features.push(geoEntry);
    }

    return features;
}
<|endoftext|>


<commit_before>/* global require,console,process,__dirname */

'use strict';

var fs = require('fs');
var path = require('path');
var FontSpider = require('../');// require('font-spider');

new FontSpider

// 分析 WebFont
.Spider([
        'http://font-spider.org/index.html',
        'http://font-spider.org/install.html'
    ], {

    // 忽略的文件规则。语法 @see https://github.com/kaelzhang/node-ignore
    ignore: ['*.eot', 'icons.css', 'font?name=*'],

    // 路径映射规则。映射远程路径到本地（远程字体文件必须映射到本地才能压缩）
    map: [
        ['http://font-spider.org/font', __dirname + '/../release/font'],
        ['http://font-spider.org/css', __dirname + '/../release/css']
    ],

    // CSS @import 语法导入的文件数量限制，避免爬虫陷入死循环陷阱
    maxImportCss: 16,

    // 资源加载前事件
    resourceBeforeLoad: function (file) {
        var RE_SERVER = /^https?\:\/\//i;
        var REG_DOMAIN = /^https?\:\/\/(?:\w+\.)?font-spider\.org/;

        if (RE_SERVER.test(file)) {
            if (!REG_DOMAIN.test(file)) {
                throw new Error('只允许来自 font-spider.org 网站的资源请求');
            }
        } else {
            var base = path.resolve(__dirname + '/../release');
            if (file.indexOf(base) !== 0) {
                throw new Error('禁止访问上层目录');
            }
        }
    },

    // 资源加载成功事件
    resourceLoad: function (file) {
        console.log('Load', file);
    },

    // 资源加载失败事件
    resourceError: function (file) {},

    // 爬虫爬行页面前事件
    spiderBeforeLoad: function (htmlFile) {},

    // 爬虫解析页面完成事件
    spiderLoad: function (htmlFile) {},

    // 爬虫解析错误事件
    spiderError: function (htmlFile) {}
})

// 压缩字体
.then(function (webFonts) {
    return Promise
    .all(webFonts.map(function (webFont) {
        return new FontSpider.Compress(webFont, {
            // 是否备份原始字体
            backup: true
        });
    }));
})

// 显示压缩结果
.then(function (webFonts) {
    if (webFonts.length === 0) {
        console.log('web font not found');
        return;
    }

    webFonts.forEach(function (webFont) {
        console.log('Font name:', webFont.name);
        console.log('Font id:', webFont.id);
        console.log('Original size:', webFont.originalSize / 1000, 'KB');
        console.log('Include chars:', webFont.chars);

        webFont.files.forEach(function (file) {
            if (fs.existsSync(file)) {
                console.log('File', path.relative('./', file),
                    'created:', fs.statSync(file).size / 1000, 'KB');
            } else {
                console.error('File', path.relative('./', file), 'not created');
            }
        });
    });
})
.catch(function (errors) {
    console.log('Error:', errors.stack.toString());
    process.exit(1);
});

<commit_msg>api演示<commit_after>/* global require,console,process,__dirname */

'use strict';

var fs = require('fs');
var path = require('path');
var FontSpider = require('../');// require('font-spider');

new FontSpider

// 分析 WebFont
.Spider([
        'http://font-spider.org/index.html',
        'http://font-spider.org/install.html'
    ], {

    // 忽略的文件规则。语法 @see https://github.com/kaelzhang/node-ignore
    ignore: ['*.eot', 'icons.css', 'font?name=*'],

    // 路径映射规则。映射远程路径到本地（远程字体文件必须映射到本地才能压缩）
    map: [
        ['http://font-spider.org/font', __dirname + '/../release/font'],
        ['http://font-spider.org/css', __dirname + '/../release/css']
    ],

    // CSS @import 语法导入的文件数量限制，避免爬虫陷入死循环陷阱
    maxImportCss: 16,

    // 资源加载前事件
    resourceBeforeLoad: function (file) {},

    // 资源加载成功事件
    resourceLoad: function (file) {
        console.log('Load', file);
    },

    // 资源加载失败事件
    resourceError: function (file) {},

    // 爬虫爬行页面前事件
    spiderBeforeLoad: function (htmlFile) {},

    // 爬虫解析页面完成事件
    spiderLoad: function (htmlFile) {},

    // 爬虫解析错误事件
    spiderError: function (htmlFile) {}
})

// 压缩字体
.then(function (webFonts) {
    return Promise
    .all(webFonts.map(function (webFont) {
        return new FontSpider.Compress(webFont, {
            // 是否备份原始字体
            backup: true
        });
    }));
})

// 显示压缩结果
.then(function (webFonts) {
    if (webFonts.length === 0) {
        console.log('web font not found');
        return;
    }

    webFonts.forEach(function (webFont) {
        console.log('Font name:', webFont.name);
        console.log('Font id:', webFont.id);
        console.log('Original size:', webFont.originalSize / 1000, 'KB');
        console.log('Include chars:', webFont.chars);

        webFont.files.forEach(function (file) {
            if (fs.existsSync(file)) {
                console.log('File', path.relative('./', file),
                    'created:', fs.statSync(file).size / 1000, 'KB');
            } else {
                console.error('File', path.relative('./', file), 'not created');
            }
        });
    });
})
.catch(function (errors) {
    console.log('Error:', errors.stack.toString());
    process.exit(1);
});

<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-12-4 02:53:59<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>import config from '../config'

export default class City {
  constructor (name) {
    this.name = name || 'City'
    this.demand = config.cityInitialDemand
    this.turnips = config.cityInitialTurnips
  }
  getName () {
    return this.name
  }
  getDemand () {
    return this.demand
  }
  getTurnips () {
    return this.turnips
  }
  increaseDemand (amount) {
    this.demand = this.demand + amount
  }
  resetTurnips () {
    this.turnips = config.cityInitialTurnips
  }
  receiveTurnips (amount) {
    this.turnips = this.turnips + amount
  }
  payPlayerAccordingToDemandSatisfied () {
    // if turnips equals demand player gets ? points
  }
}
<commit_msg>refaktorointia<commit_after>import config from '../config'

export default class City {
  constructor (name) {
    this.name = name || 'City'
    this.demand = config.cityInitialDemand
    this.turnips = config.cityInitialTurnips
  }

  /* Moi Miia, nämä vähän turhia javascriptis, ku city.name on oikeastaan parempi
     kun city.getName koska se on getteri ja setteri samalla.
  getName () {
    return this.name
  }
  getDemand () {
    return this.demand
  }
  getTurnips () {
    return this.turnips
  }
  */
  increaseDemand (amount) {
    this.demand = this.demand + amount
  }
  resetTurnips () {
    this.turnips = config.cityInitialTurnips
  }
  receiveTurnips (amount) {
    this.turnips = this.turnips + amount
  }
  payPlayerAccordingToDemandSatisfied () {
    // if turnips equals demand player gets ? points
  }
}
<|endoftext|>


<commit_before>var lowColor = [0, 255, 255];
var medColor = [0, 0, 255];
var highColor = [255, 128, 0];

var experience = {
	0: "Learning",
	1: "Basic",
	2: "Intermediate",
	3: "Advanced",
	4: "Expert",
};

$(window).load(function() {
      $(".experience").each(function(){
        var result = parseFloat(this.dataset.info);
        var progress = result / 5;
        var curElement = this;
        var setColor = rgbArrayToString(barColor(progress));
        var expBar = new ProgressBar.Circle(this, {
            color: '#ddd',
            trailColor: '#f7f7f7',
            duration: 1000,
            easing: 'easeOut',
            strokeWidth: 5,
            text: {
                value: '+',
                color: '#A8A8A8'
            },
            step: function(state, bar){
                 bar.path.setAttribute('stroke', state.color);
            }
        });
        expBar.animate(progress, {
                from: {color: "#606060"},
                to: {color: setColor}
        });
     });
});

// Interpolate value between two colors.
// Value is number from 0-1. 0 Means color A, 0.5 middle etc.
function interpolateColor(rgbA, rgbB, value) {
    var rDiff = rgbA[0] - rgbB[0];
    var gDiff = rgbA[1] - rgbB[1];
    var bDiff = rgbA[2] - rgbB[2];
    value = 1 - value;
    return [
        rgbB[0] + rDiff * value,
        rgbB[1] + gDiff * value,
        rgbB[2] + bDiff * value
    ];
}

function rgbArrayToString(rgb) {
    return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
}

function barColor(progress) {
	if(progress >= .5){
		return interpolateColor(medColor, highColor, progress - .5);
	}
    return interpolateColor(lowColor, medColor, progress);
}<commit_msg>Fix to interpolation such that it mixes low->medium, then that mixture against high if it reaches above half<commit_after>//var lowColor = [0, 255, 255];
var lowColor = [0, 208, 45];
var medColor = [50, 50, 255];
var highColor = [255, 128, 0];

var experience = {
	0: "Learning",
	1: "Basic",
	2: "Intermediate",
	3: "Advanced",
	4: "Expert",
};

$(window).load(function() {
      $(".experience").each(function(){
        var result = parseFloat(this.dataset.info);
        var progress = result / 5;
        var curElement = this;
        var setColor = rgbArrayToString(barColor(progress));
        var expBar = new ProgressBar.Circle(this, {
            color: '#ddd',
            trailColor: '#f7f7f7',
            duration: 1000,
            easing: 'easeOut',
            strokeWidth: 5,
            text: {
                value: '+',
                color: '#A8A8A8'
            },
            step: function(state, bar){
                 bar.path.setAttribute('stroke', state.color);
            }
        });
        expBar.animate(progress, {
                from: {color: "#f7f7f7"},
                to: {color: setColor}
        });
     });
});

// Interpolate value between two colors.
// Value is number from 0-1. 0 Means color A, 0.5 middle etc.
function interpolateColor(rgbA, rgbB, value) {
    var rDiff = rgbA[0] - rgbB[0];
    var gDiff = rgbA[1] - rgbB[1];
    var bDiff = rgbA[2] - rgbB[2];
    value = 1 - value;
    return [
        rgbB[0] + rDiff * value,
        rgbB[1] + gDiff * value,
        rgbB[2] + bDiff * value
    ];
}

function rgbArrayToString(rgb) {
    return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
}

function barColor(progress) {
    var intCol = interpolateColor(lowColor, medColor, progress*2);
    if(progress > .5){
        intCol = interpolateColor(intCol, highColor, (1-progress)*2);
    }
    return intCol;
}<|endoftext|>