<commit_before>function partials(file){
	return 'javascripts/app/partials/' + file
}

var App = angular.module('App', ['firebase', 'ui.bootstrap']).
	config(['$routeProvider', function($routeProvider){
				$routeProvider.
					when('/', { templateUrl: partials('home.html'), controller: HomeCtrl } ).
					when('/decks', {templateUrl: partials('decks.html'),  controller: DeckCtrl } ).
					otherwise({ redirectTo: '/' });
			}

]);

function HomeCtrl($scope) {
  $scope.myInterval = 6000;
  var slides = $scope.slides = [];
  $scope.addSlide = function() {

    var newWidth = 200 + ((slides.length + (25 * slides.length)) % 150);
    slides.push({
      image: 'http://placekitten.com/' + newWidth + '/200',
      text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
        ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
    });
  };
  for (var i=0; i<4; i++) {
    $scope.addSlide();
  }
};

// App.constant('decksUrl', 'https://greent.firebaseio.com/skateshop/products/decks');
App.constant('decksUrl', 'https://greent.firebaseio.com/mydecks');

function DeckCtrl($scope, angularFire, decksUrl){
	var promise = angularFire(decksUrl, $scope, 'deckList', []);
}

<commit_msg>removed test images from carousel<commit_after>function partials(file){
	return 'javascripts/app/partials/' + file
}

var App = angular.module('App', ['firebase', 'ui.bootstrap']).
	config(['$routeProvider', function($routeProvider){
				$routeProvider.
					when('/', { templateUrl: partials('home.html'), controller: HomeCtrl } ).
					when('/decks', {templateUrl: partials('decks.html'),  controller: DeckCtrl } ).
					otherwise({ redirectTo: '/' });
			}

]);

function HomeCtrl($scope) {
  $scope.myInterval = 6000;
  $scope.myslides = [{image: '../../skate-images/pool-crusher-deepend-wilson.jpg', text: 'Pool King Pool Crusher'},
					{image: '../../skate-images/powerstation-hyperkick.jpg', text: 'Adventures with the Pool King Crown Hyper Kick'}
];

};

// App.constant('decksUrl', 'https://greent.firebaseio.com/skateshop/products/decks');
App.constant('decksUrl', 'https://greent.firebaseio.com/mydecks');

function DeckCtrl($scope, angularFire, decksUrl){
	var promise = angularFire(decksUrl, $scope, 'deckList', []);

	$scope.imageDetail = function(deck){
		$scope.deckDetail = deck;
	}

}

<|endoftext|>


<commit_before>// Copyright 2014 Joyent, Inc.  All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

var nfs = require('nfs');
var path = require('path');

var common = require('./common');

var fs = require('fs');

///-- API

function create_lookup_dir(call, reply, next) {
    var log = call.log;

    log.debug('create_lookup_dir(%s): entered', call.where.dir);
    call.fs.fhandle(call.where.dir, function (err, name) {
        if (err) {
            log.warn(err, 'create_lookup_dir(%s): fhandle notfound',
                call.where.dir);
            reply.error(nfs.NFS3ERR_STALE);
            next(false);
        } else {
            call._dirname = name;
            call._filename = path.join(name, call.where.name);
            log.debug('create_lookup_dir(%s): done -> %s', call.where.dir,
                name);
            next();
        }
    });
}

function do_create(call, reply, next) {
    // ignore the passed in mode (call.obj_attributes.mode) since manta does
    // not support modes
    var mode = 0644;

    // We don't use the fd cache here since that only works with existing files
    // and always opens with 'r+'. We need to create the file here with 'w'.
    call.fs.open(call._filename, 'w', mode, function (open_err, fd) {
        if (open_err) {
            call.log.warn(open_err, 'create: open failed');
            reply.error(nfs.NFS3ERR_SERVERFAULT);
            next(false);
            return;
        }

        call.fs.close(fd, function (close_err) {
            // we're ignoring errors on close
            next();
        });
    });
}

function create(call, reply, next) {
    var log = call.log;

    log.debug('create(%s, %d): entered', call.object, call.how);

    if (call.how === nfs.create_how.EXCLUSIVE) {
        log.warn('create: exclusive not allowed');
        reply.error(nfs.NFS3ERR_NOTSUPP);
        next(false);
    } else if (call.how === nfs.create_how.UNCHECKED) {
        do_create(call, reply, next);
    } else {    // call.how === nfs.create_how.GUARDED
        call.fs.stat(call._filename, function (err, stats) {
            if (err && err.code === 'ENOENT') {
                // This is the "normal" code path (i.e. non-error)
                do_create(call, reply, next);
            } else {
                log.debug('create (guarded) file exists');
                reply.error(nfs.NFS3ERR_EXIST);
                next(false);
            }
        });
    }
}

function create_lookup(call, reply, next) {
    var log = call.log;

    log.debug('create_lookup(%s): entered', call._filename);
    call.fs.lookup(call._filename, function (err, fhandle) {
        if (err) {
            log.warn(err, 'create_lookup(%s): failed', call._filename);
            reply.error(nfs.NFS3ERR_NOENT);
            next(false);
            return;
        }

        log.debug('create_lookup(%s): done', fhandle);
        reply.obj = fhandle;

        next();
    });
}

function create_stat(call, reply, next) {
    var log = call.log;

    log.debug('create_stat(%s): entered', call._filename);
    call.fs.stat(call._filename, function (err, stats) {
        if (err) {
            log.warn(err, 'create_stat(%s): failed', call._filename);
            reply.error(nfs.NFS3ERR_NOENT);
            next(false);
            return;
        }

        reply.setObjAttributes(stats);
        log.debug({stats: stats}, 'create_stat(%s): done', call._filename);
        reply.send();
        next();
    });
}

///--- Exports

module.exports = function chain() {
    return ([
        create_lookup_dir,
        create,
        create_lookup,
        create_stat
    ]);
};
<commit_msg>MANTA-1844 exclusive create<commit_after>// Copyright 2014 Joyent, Inc.  All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

var nfs = require('nfs');
var path = require('path');

var common = require('./common');

var fs = require('fs');

///-- API

function create_lookup_dir(call, reply, next) {
    var log = call.log;

    log.debug('create_lookup_dir(%s): entered', call.where.dir);
    call.fs.fhandle(call.where.dir, function (err, name) {
        if (err) {
            log.warn(err, 'create_lookup_dir(%s): fhandle notfound',
                call.where.dir);
            reply.error(nfs.NFS3ERR_STALE);
            next(false);
        } else {
            call._dirname = name;
            call._filename = path.join(name, call.where.name);
            log.debug('create_lookup_dir(%s): done -> %s', call.where.dir,
                name);
            next();
        }
    });
}

function do_create(flags, call, reply, next) {
    // ignore the passed in mode (call.obj_attributes.mode) since manta does
    // not support modes
    var mode = 0644;

    // We don't use the fd cache here since that only works with existing files
    // and always opens with the 'r+' flag. We need to create the file here
    // with either the 'w' or 'wx' flags.
    call.fs.open(call._filename, flags, mode, function (open_err, fd) {
        if (open_err) {
            call.log.warn(open_err, 'create: open failed');
            reply.error(nfs.NFS3ERR_SERVERFAULT);
            next(false);
            return;
        }

        call.fs.close(fd, function (close_err) {
            // we're ignoring errors on close
            next();
        });
    });
}

function create(call, reply, next) {
    var log = call.log;

    log.debug('create(%s, %d): entered', call.object, call.how);

    if (call.how === nfs.create_how.EXCLUSIVE) {
        call.fs.stat(call._filename, function (err, stats) {
            if (err && err.code === 'ENOENT') {
                // This is the "normal" code path (i.e. non-error)
                do_create('wx', call, reply, next);
            } else {
                log.debug('create (exclusive) file exists');
                reply.error(nfs.NFS3ERR_EXIST);
                next(false);
            }
        });
    } else if (call.how === nfs.create_how.UNCHECKED) {
        do_create('w', call, reply, next);
    } else {    // call.how === nfs.create_how.GUARDED
        call.fs.stat(call._filename, function (err, stats) {
            if (err && err.code === 'ENOENT') {
                // This is the "normal" code path (i.e. non-error)
                do_create('w', call, reply, next);
            } else {
                log.debug('create (guarded) file exists');
                reply.error(nfs.NFS3ERR_EXIST);
                next(false);
            }
        });
    }
}

function create_lookup(call, reply, next) {
    var log = call.log;

    log.debug('create_lookup(%s): entered', call._filename);
    call.fs.lookup(call._filename, function (err, fhandle) {
        if (err) {
            log.warn(err, 'create_lookup(%s): failed', call._filename);
            reply.error(nfs.NFS3ERR_NOENT);
            next(false);
            return;
        }

        log.debug('create_lookup(%s): done', fhandle);
        reply.obj = fhandle;

        next();
    });
}

function create_stat(call, reply, next) {
    var log = call.log;

    log.debug('create_stat(%s): entered', call._filename);
    call.fs.stat(call._filename, function (err, stats) {
        if (err) {
            log.warn(err, 'create_stat(%s): failed', call._filename);
            reply.error(nfs.NFS3ERR_NOENT);
            next(false);
            return;
        }

        reply.setObjAttributes(stats);
        log.debug({stats: stats}, 'create_stat(%s): done', call._filename);
        reply.send();
        next();
    });
}

///--- Exports

module.exports = function chain() {
    return ([
        create_lookup_dir,
        create,
        create_lookup,
        create_stat
    ]);
};
<|endoftext|>


<commit_before>var Context;

Context = function(canvas, renderer){
	this.canvas    = canvas;
	this.elements  = [];
	this.listeners = {};
	this.renderer = $.renderers[renderer || '2d'];
	this.renderer.init(this, canvas);

	this.updateNowBounded = this.updateNow.bind(this);
};

Context.prototype = {

	// Elements
	object: function(object){
		return this.push(Object.assign(new Drawable(), object));
	},

	rect: function(){
		return this.push(new Rect(arguments, this));
	},

	circle: function(){
		return this.push(new Circle(arguments, this));
	},

	path: function(){
		return this.push(new Path(arguments, this));
	},

	image: function(){
		return this.push(new Img(arguments, this));
	},

	raster: function(){
		return this.push(new Raster(arguments, this));
	},

	text: function(){
		return this.push(new Text(arguments, this));
	},

	// Path slices
	line: function(fx, fy, tx, ty, stroke){
		return this.path([[fx, fy], [tx, ty]], null, stroke);
	},

	quadratic : function(fx, fy, tx, ty, hx, hy, stroke){
		return this.path([[fx, fy], [tx, ty, hx, hy]], null, stroke);
	},

	bezier : function(fx, fy, tx, ty, h1x, h1y, h2x, h2y, stroke){
		return this.path([[fx, fy], [tx, ty, h1x, h1y, h2x, h2y]], null, stroke);
	},

	arcTo : function(fx, fy, tx, ty, radius, clockwise, stroke){
		return this.path([[fx, fy], ['arcTo', fx, fy, tx, ty, radius, clockwise]], null, stroke);
	},

	// Fills
	gradient : function(type, colors, from, to){
		return new Gradient(type, colors, from, to, this);
	},

	pattern : function(image, repeat){
		return new Pattern(image, repeat, this);
	},

	// Methods
	push : function(element){
		element.context = this;
		this.elements.push(element);

		if(element.draw){
			element.draw(this.context);
		}

		return element;
	},

	update : function(){
		if(this._willUpdate){
			return;
		}

		this._willUpdate = true;
		requestAnimationFrame(this.updateNowBounded);
	},

	updateNow : function(){
		var ctx = this.context;
		this.renderer.preRedraw(ctx, this);
		this.elements.forEach(function(object){
			object.draw(ctx);
		});
		this.renderer.postRedraw(ctx);
		this._willUpdate = false;
	},

	getObjectInPoint : function(x, y, mouse){
		var elements = this.elements,
			i = elements.length;

		while(i--){
		// mouse=true : ignore elements with interaction = false
			if( elements[i].isPointIn && elements[i].isPointIn(x,y) &&
				(elements[i].attrs.interaction || !mouse) ){
				return elements[i];
			}
		}
		return null;
	},

	// Events
	hoverElement : null,
	focusElement : null,

	listener : function(event){
		if(this.listeners[event]){
			return this.listeners[event];
		}

		this.listeners[event] = [];

		if(this.eventsHooks.hasOwnProperty(event)){
			this.eventsHooks[event].call(this, event);
		}

		if(this.eventsInteract.indexOf(event) === -1){
			return this.listeners[event];
		}

		this.canvas.addEventListener(event, function(e){
			var element,
				propagation = true,
				coords = $.coordsOfElement(this.canvas);

			// negative contextX / contextY when canvas has a border
			e.contextX = e.clientX - coords.x;
			e.contextY = e.clientY - coords.y;

			e.cancelContextPropagation = function(){
				propagation = false;
			};

			if(event === 'mouseout'){
				element = this.hoverElement;
				this.hoverElement = null;
			} else {
				element = this.getObjectInPoint(e.contextX, e.contextY, true);
			}

			e.targetObject = element;

			if(element && element.fire){
				if(!element.fire(event, e)){
					e.stopPropagation();
					e.preventDefault();
					return;
				}
			}

			if(propagation){
				this.fire(event, e);
			}
		}.bind(this));

		return this.listeners[event];
	},

	eventsInteract: [
		// todo: check touch & pointer events
		// mouse
		'click',
		'dblclick',
		'mousedown',
		'mouseup',
		'mousemove',
		'mouseover',
		'mouseout',
		'mouseenter',
		'mouseleave',
		'mousewheel',
		'blur',
		'focus',
		// keyboard
		'keypress',
		'keydown',
		'keyup',
		// touch
		'touchstart',
		'touchmove',
		'touchend',
		'touchcancel',
		// pointer
		'pointerover',
		'pointerenter',
		'pointerdown',
		'pointermove',
		'pointerup',
		'pointercancel',
		'pointerout',
		'pointerleave',
		// check:
		'gotpointercapture',
		'lostpointercapture'
	],

	eventsHooks : {
		mouseover : function(){
			if(!this.listeners['mouseout']){
				this.listenerSpecial('mouseover', 'mouseout', 'hover', 'mousemove');
				this.listener('mouseout');
			}
		},
		mouseout: function(){
			if(!this.listeners['mouseover']){
				this.listenerSpecial('mouseover', 'mouseout', 'hover', 'mousemove');
				this.listener('mouseover');
			}
		},
		focus : function(){
			if(!this.listeners['blur']){
				this.listenerSpecial('focus', 'blur', 'focus', 'mousedown');
				this.listener('blur');
			}
		},
		blur: function(){
			if(!this.listeners['focus']){
				this.listenerSpecial('focus', 'blur', 'focus', 'mousedown');
				this.listener('focus');
			}
		}
	},

	// for mouseover/mouseout and focus/blur
	listenerSpecial : function(over, out, name, baseevent){
		// mouseover, mouseout, hover, mousemove
		// focus, blur, focus, mousedown
		name += 'Element';
		this.on(baseevent, function(e){
			var current = e.targetObject,
				last = this[name];

			if(last != current){
				if(last && last.fire){
					last.fire(out, e);
				}
				if(current && current.fire){
					current.fire(over, e);
				}
				this[name] = current;
			}

		}.bind(this));
		return this;
	},

	on : function(event, callback){
		if(event + '' !== event){
			for(var key in event) if(has(event, key)){
				this.on(key, event[key]);
			}
			return this;
		}

		(this.listeners[event] || this.listener(event)).push(callback);
		return this;
	},

	off : function(event, callback){
		if(!callback){
			this.listeners[event] = [];
		}

		var index = this.listeners[event].indexOf(callback);
		this.listeners = this.listeners[event]
								.slice(0, index)
								.concat( this.listeners[event].slice(index+1) );
		return this;
	},

	fire : function(event, data){
		if(!this.listeners[event]){
			return this;
		}

		this.listeners[event].forEach(function(callback){
			callback.call(this, data);
		}.bind(this));
		return this;
	},

	// Transforms
	matrix: null,
	transform: function(a, b, c, d, e, f, pivot){
		if(pivot){
			if(pivot + '' === pivot){
				pivot = $.corners[pivot];
				pivot = [pivot[0] * this.canvas.width, pivot[1] * this.canvas.height];
			}

			e = e - a * pivot[0] + pivot[0] - c * pivot[1];
			f = f - b * pivot[0] - d * pivot[1] + pivot[1];
		}

		this.matrix = $.transform(this.matrix || [1, 0, 0, 1, 0, 0], [a, b, c, d, e, f]);
		return this.update();
	},

	translate: function(x, y){
		return this.transform(1, 0, 0, 1, x, y);
	},

	rotate: function(angle, pivot){
		angle = angle / 180 * Math.PI;
		return this.transform(Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0, pivot);
	},

	scale: function(x, y, pivot){
		if(y === undefined || isPivot(y)){
			pivot = y;
			y = x;
		}
		return this.transform(x, 0, 0, y, 0, 0, pivot);
	},

	skew: function(x, y, pivot){
		if(y === undefined){
			y = x;
		}
		return this.transform(1, Math.tan(y * Math.PI / 180), Math.tan(x * Math.PI / 180), 1, 0, 0, pivot);
	}

};<commit_msg>Canvas transforms #26<commit_after>var Context;

Context = function(canvas, renderer){
	this.canvas    = canvas;
	this.elements  = [];
	this.listeners = {};
	this.renderer = $.renderers[renderer || '2d'];
	this.renderer.init(this, canvas);

	this.updateNowBounded = this.updateNow.bind(this);
};

Context.prototype = {

	// Elements
	object: function(object){
		return this.push(Object.assign(new Drawable(), object));
	},

	rect: function(){
		return this.push(new Rect(arguments, this));
	},

	circle: function(){
		return this.push(new Circle(arguments, this));
	},

	path: function(){
		return this.push(new Path(arguments, this));
	},

	image: function(){
		return this.push(new Img(arguments, this));
	},

	raster: function(){
		return this.push(new Raster(arguments, this));
	},

	text: function(){
		return this.push(new Text(arguments, this));
	},

	// Path slices
	line: function(fx, fy, tx, ty, stroke){
		return this.path([[fx, fy], [tx, ty]], null, stroke);
	},

	quadratic : function(fx, fy, tx, ty, hx, hy, stroke){
		return this.path([[fx, fy], [tx, ty, hx, hy]], null, stroke);
	},

	bezier : function(fx, fy, tx, ty, h1x, h1y, h2x, h2y, stroke){
		return this.path([[fx, fy], [tx, ty, h1x, h1y, h2x, h2y]], null, stroke);
	},

	arcTo : function(fx, fy, tx, ty, radius, clockwise, stroke){
		return this.path([[fx, fy], ['arcTo', fx, fy, tx, ty, radius, clockwise]], null, stroke);
	},

	// Fills
	gradient : function(type, colors, from, to){
		return new Gradient(type, colors, from, to, this);
	},

	pattern : function(image, repeat){
		return new Pattern(image, repeat, this);
	},

	// Methods
	push : function(element){
		element.context = this;
		this.elements.push(element);

		if(element.draw){
			element.draw(this.context);
		}

		return element;
	},

	update : function(){
		if(this._willUpdate){
			return;
		}

		this._willUpdate = true;
		requestAnimationFrame(this.updateNowBounded);
	},

	updateNow : function(){
		var ctx = this.context;
		this.renderer.preRedraw(ctx, this);
		this.elements.forEach(function(object){
			object.draw(ctx);
		});
		this.renderer.postRedraw(ctx);
		this._willUpdate = false;
	},

	getObjectInPoint : function(x, y, mouse){
		var elements = this.elements,
			i = elements.length;

		while(i--){
		// mouse=true : ignore elements with interaction = false
			if( elements[i].isPointIn && elements[i].isPointIn(x,y) &&
				(elements[i].attrs.interaction || !mouse) ){
				return elements[i];
			}
		}
		return null;
	},

	// Events
	hoverElement : null,
	focusElement : null,

	listener : function(event){
		if(this.listeners[event]){
			return this.listeners[event];
		}

		this.listeners[event] = [];

		if(this.eventsHooks.hasOwnProperty(event)){
			this.eventsHooks[event].call(this, event);
		}

		if(this.eventsInteract.indexOf(event) === -1){
			return this.listeners[event];
		}

		this.canvas.addEventListener(event, function(e){
			var element,
				propagation = true,
				coords = $.coordsOfElement(this.canvas);

			// negative contextX / contextY when canvas has a border
			e.contextX = e.clientX - coords.x;
			e.contextY = e.clientY - coords.y;

			e.cancelContextPropagation = function(){
				propagation = false;
			};

			if(event === 'mouseout'){
				element = this.hoverElement;
				this.hoverElement = null;
			} else {
				element = this.getObjectInPoint(e.contextX, e.contextY, true);
			}

			e.targetObject = element;

			if(element && element.fire){
				if(!element.fire(event, e)){
					e.stopPropagation();
					e.preventDefault();
					return;
				}
			}

			if(propagation){
				this.fire(event, e);
			}
		}.bind(this));

		return this.listeners[event];
	},

	eventsInteract: [
		// mouse
		'click',
		'dblclick',
		'mousedown',
		'mouseup',
		'mousemove',
		'mouseover',
		'mouseout',
		'mouseenter',
		'mouseleave',
		'mousewheel',
		'blur',
		'focus',
		// keyboard
		'keypress',
		'keydown',
		'keyup',
		// touch
		'touchstart',
		'touchmove',
		'touchend',
		'touchcancel',
		// pointer
		'pointerover',
		'pointerenter',
		'pointerdown',
		'pointermove',
		'pointerup',
		'pointercancel',
		'pointerout',
		'pointerleave',
		// check:
		'gotpointercapture',
		'lostpointercapture'
	],

	eventsHooks : {
		mouseover : function(){
			if(!this.listeners['mouseout']){
				this.listenerSpecial('mouseover', 'mouseout', 'hover', 'mousemove');
				this.listener('mouseout');
			}
		},
		mouseout: function(){
			if(!this.listeners['mouseover']){
				this.listenerSpecial('mouseover', 'mouseout', 'hover', 'mousemove');
				this.listener('mouseover');
			}
		},
		focus : function(){
			if(!this.listeners['blur']){
				this.listenerSpecial('focus', 'blur', 'focus', 'mousedown');
				this.listener('blur');
			}
		},
		blur: function(){
			if(!this.listeners['focus']){
				this.listenerSpecial('focus', 'blur', 'focus', 'mousedown');
				this.listener('focus');
			}
		}
	},

	// for mouseover/mouseout and focus/blur
	listenerSpecial : function(over, out, name, baseevent){
		// mouseover, mouseout, hover, mousemove
		// focus, blur, focus, mousedown
		name += 'Element';
		this.on(baseevent, function(e){
			var current = e.targetObject,
				last = this[name];

			if(last != current){
				if(last && last.fire){
					last.fire(out, e);
				}
				if(current && current.fire){
					current.fire(over, e);
				}
				this[name] = current;
			}

		}.bind(this));
		return this;
	},

	on : function(event, callback){
		if(event + '' !== event){
			for(var key in event) if(has(event, key)){
				this.on(key, event[key]);
			}
			return this;
		}

		(this.listeners[event] || this.listener(event)).push(callback);
		return this;
	},

	off : function(event, callback){
		if(!callback){
			this.listeners[event] = [];
		}

		var index = this.listeners[event].indexOf(callback);
		this.listeners = this.listeners[event]
								.slice(0, index)
								.concat( this.listeners[event].slice(index+1) );
		return this;
	},

	fire : function(event, data){
		if(!this.listeners[event]){
			return this;
		}

		this.listeners[event].forEach(function(callback){
			callback.call(this, data);
		}.bind(this));
		return this;
	},

	// Transforms
	matrix: null,
	transform: function(a, b, c, d, e, f, pivot){
		if(pivot){
			if(pivot + '' === pivot){
				pivot = $.corners[pivot];
				pivot = [pivot[0] * this.canvas.width, pivot[1] * this.canvas.height];
			}

			e = e - a * pivot[0] + pivot[0] - c * pivot[1];
			f = f - b * pivot[0] - d * pivot[1] + pivot[1];
		}

		this.matrix = $.transform(this.matrix || [1, 0, 0, 1, 0, 0], [a, b, c, d, e, f]);
		return this.update();
	},

	translate: function(x, y){
		return this.transform(1, 0, 0, 1, x, y);
	},

	rotate: function(angle, pivot){
		angle = angle / 180 * Math.PI;
		return this.transform(Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0, pivot);
	},

	scale: function(x, y, pivot){
		if(y === undefined || isPivot(y)){
			pivot = y;
			y = x;
		}
		return this.transform(x, 0, 0, y, 0, 0, pivot);
	},

	skew: function(x, y, pivot){
		if(y === undefined || isPivot(y)){
			pivot = y;
			y = x;
		}
		return this.transform(1, Math.tan(y * Math.PI / 180), Math.tan(x * Math.PI / 180), 1, 0, 0, pivot);
	}

};<|endoftext|>


<commit_before>(function() {
    'use strict';
    exports.version = '3.0.0';

    var isEqual = require('lodash.isequal');
    var filterd = require('lodash.filter');
    var clonedeep = require('lodash.clonedeep');
    var matches = require('lodash.matches');

    function RuleEngine(rules, options) {
        this.init();
        if (typeof(rules) != "undefined") {
            this.register(rules);
        }
        if (options) {
            this.ignoreFactChanges = options.ignoreFactChanges;
        }
        return this;
    }
    RuleEngine.prototype.init = function(rules) {
        this.rules = [];
        this.activeRules = [];
    };
    RuleEngine.prototype.register = function(rules) {
        if (Array.isArray(rules)) {
            this.rules = this.rules.concat(rules);
        } else if (rules !== null && typeof(rules) == "object") {
            this.rules.push(rules);
        }
        this.sync();
    };
    RuleEngine.prototype.sync = function() {
        this.activeRules = this.rules.filter(function(a) {
            if (typeof(a.on) === "undefined") {
                a.on = true;
            }
            if (a.on === true) {
                return a;
            }
        });
        this.activeRules.sort(function(a, b) {
            if (a.priority && b.priority) {
                return b.priority - a.priority;
            } else {
                return 0;
            }
        });
    };
    RuleEngine.prototype.execute = function(fact, callback) {
        //these new attributes have to be in both last session and current session to support
        // the compare function
        var complete = false;
        fact.result = true;
        var session = clonedeep(fact);
        var lastSession = clonedeep(fact);
        var _rules = this.activeRules;
        var matchPath = [];
        var ignoreFactChanges = this.ignoreFactChanges;
        (function FnRuleLoop(x) {
            var API = {
                "rule": function() { return _rules[x]; },
                "when": function(outcome) {
                    if (outcome) {
                        var _consequence = _rules[x].consequence;
                        _consequence.ruleRef = _rules[x].id || _rules[x].name || 'index_'+x;
                        process.nextTick(function() {
                            matchPath.push(_consequence.ruleRef);
                            _consequence.call(session, API, session);
                        });
                    } else {
                        process.nextTick(function() {
                            API.next();
                        });
                    }
                },
                "restart": function() {
                    return FnRuleLoop(0);
                },
                "stop": function() {
                    complete = true;
                    return FnRuleLoop(0);
                },
                "next": function() {
                    if (!ignoreFactChanges && !isEqual(lastSession, session)) {
                        lastSession = clonedeep(session);
                        process.nextTick(function() {
                            API.restart();
                        });
                    } else {
                        process.nextTick(function() {
                            return FnRuleLoop(x + 1);
                        });
                    }
                }
            };
            if (x < _rules.length && complete === false) {
                var _rule = _rules[x].condition;
                _rule.call(session, API, session);
            } else {
                process.nextTick(function() {
                    session.matchPath = matchPath;
                    return callback(session);
                });
            }
        })(0);
    };
    RuleEngine.prototype.findRules = function(filter) {
        if (typeof(filter) === "undefined") {
            return this.rules;
        } else {
            var find = matches(filter);
            return filterd(this.rules, find);
        }
    }
    RuleEngine.prototype.turn = function(state, filter) {
        var state = (state === "on" || state === "ON") ? true : false;
        var rules = this.findRules(filter);
        for (var i = 0, j = rules.length; i < j; i++) {
            rules[i].on = state;
        }
        this.sync();
    }
    RuleEngine.prototype.prioritize = function(priority, filter) {
        priority = parseInt(priority, 10);
        var rules = this.findRules(filter);
        for (var i = 0, j = rules.length; i < j; i++) {
            rules[i].priority = priority;
        }
        this.sync();
    }
    RuleEngine.prototype.toJSON = function() {
        var rules = this.rules;
        if (rules instanceof Array) {
            rules = rules.map(function(rule) {
                rule.condition = rule.condition.toString();
                rule.consequence = rule.consequence.toString();
                return rule;
            });
        } else if (typeof(rules) != "undefined") {
            rules.condition = rules.condition.toString();
            rules.consequence = rules.consequence.toString();
        }
        return rules;
    };
    RuleEngine.prototype.fromJSON = function(rules) {
        this.init();
        if (typeof(rules) == "string") {
            rules = JSON.parse(rules);
        }
        if (rules instanceof Array) {
            rules = rules.map(function(rule) {
                rule.condition = eval("(" + rule.condition + ")");
                rule.consequence = eval("(" + rule.consequence + ")");
                return rule;
            });
        } else if (rules !== null && typeof(rules) == "object") {
            rules.condition = eval("(" + rules.condition + ")");
            rules.consequence = eval("(" + rules.consequence + ")");
        }
        this.register(rules);
    };
    module.exports = RuleEngine;
}(module.exports));
<commit_msg>Fixed issue with sync not taking effect<commit_after>(function() {
    'use strict';
    exports.version = '3.0.0';

    var isEqual = require('lodash.isequal');
    var filterd = require('lodash.filter');
    var clonedeep = require('lodash.clonedeep');
    var matches = require('lodash.matches');

    function RuleEngine(rules, options) {
        this.init();
        if (typeof(rules) != "undefined") {
            this.register(rules);
        }
        if (options) {
            this.ignoreFactChanges = options.ignoreFactChanges;
        }
        return this;
    }
    RuleEngine.prototype.init = function(rules) {
        this.rules = [];
        this.activeRules = [];
    };
    RuleEngine.prototype.register = function(rules) {
        if (Array.isArray(rules)) {
            this.rules = this.rules.concat(rules);
        } else if (rules !== null && typeof(rules) == "object") {
            this.rules.push(rules);
        }
        this.sync();
    };
    RuleEngine.prototype.sync = function() {
        this.activeRules = this.rules.filter(function(a) {
            if (typeof(a.on) === "undefined") {
                a.on = true;
            }
            if (a.on === true) {
                return a;
            }
        });
        this.activeRules.sort(function(a, b) {
            if (a.priority && b.priority) {
                return b.priority - a.priority;
            } else {
                return 0;
            }
        });
    };
    RuleEngine.prototype.execute = function(fact, callback) {
        //these new attributes have to be in both last session and current session to support
        // the compare function
        var thisHolder = this;
        var complete = false;
        fact.result = true;
        var session = clonedeep(fact);
        var lastSession = clonedeep(fact);
        var _rules = this.activeRules;
        var matchPath = [];
        var ignoreFactChanges = this.ignoreFactChanges;
        (function FnRuleLoop(x) {
            var API = {
                "rule": function() { return _rules[x]; },
                "when": function(outcome) {
                    if (outcome) {
                        var _consequence = _rules[x].consequence;
                        _consequence.ruleRef = _rules[x].id || _rules[x].name || 'index_'+x;
                        process.nextTick(function() {
                            matchPath.push(_consequence.ruleRef);
                            _consequence.call(session, API, session);
                        });
                    } else {
                        process.nextTick(function() {
                            API.next();
                        });
                    }
                },
                "restart": function() {
                    return FnRuleLoop(0);
                },
                "stop": function() {
                    complete = true;
                    return FnRuleLoop(0);
                },
                "next": function() {
                    if (!ignoreFactChanges && !isEqual(lastSession, session)) {
                        lastSession = clonedeep(session);
                        process.nextTick(function() {
                            API.restart();
                        });
                    } else {
                        process.nextTick(function() {
                            return FnRuleLoop(x + 1);
                        });
                    }
                }
            };
            _rules = thisHolder.activeRules;
            if (x < _rules.length && complete === false) {
                var _rule = _rules[x].condition;
                _rule.call(session, API, session);
            } else {
                process.nextTick(function() {
                    session.matchPath = matchPath;
                    return callback(session);
                });
            }
        })(0);
    };
    RuleEngine.prototype.findRules = function(filter) {
        if (typeof(filter) === "undefined") {
            return this.rules;
        } else {
            var find = matches(filter);
            return filterd(this.rules, find);
        }
    }
    RuleEngine.prototype.turn = function(state, filter) {
        var state = (state === "on" || state === "ON") ? true : false;
        var rules = this.findRules(filter);
        for (var i = 0, j = rules.length; i < j; i++) {
            rules[i].on = state;
        }
        this.sync();
    }
    RuleEngine.prototype.prioritize = function(priority, filter) {
        priority = parseInt(priority, 10);
        var rules = this.findRules(filter);
        for (var i = 0, j = rules.length; i < j; i++) {
            rules[i].priority = priority;
        }
        this.sync();
    }
    RuleEngine.prototype.toJSON = function() {
        var rules = this.rules;
        if (rules instanceof Array) {
            rules = rules.map(function(rule) {
                rule.condition = rule.condition.toString();
                rule.consequence = rule.consequence.toString();
                return rule;
            });
        } else if (typeof(rules) != "undefined") {
            rules.condition = rules.condition.toString();
            rules.consequence = rules.consequence.toString();
        }
        return rules;
    };
    RuleEngine.prototype.fromJSON = function(rules) {
        this.init();
        if (typeof(rules) == "string") {
            rules = JSON.parse(rules);
        }
        if (rules instanceof Array) {
            rules = rules.map(function(rule) {
                rule.condition = eval("(" + rule.condition + ")");
                rule.consequence = eval("(" + rule.consequence + ")");
                return rule;
            });
        } else if (rules !== null && typeof(rules) == "object") {
            rules.condition = eval("(" + rules.condition + ")");
            rules.consequence = eval("(" + rules.consequence + ")");
        }
        this.register(rules);
    };
    module.exports = RuleEngine;
}(module.exports));
<|endoftext|>


<commit_before>// Copyright (C) 2013 Jan Krems
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
'use strict';

var execFile = require('child_process').execFile;

var Promise = require('bluebird');
var _ = require('lodash');
var attachToPort = require('bugger-agents').attachToPort;

var PageModel = require('./model');
var pageFromUrl = require('./url').pageFromUrl;

function verifyPortOpen(port) {
  return Promise.reject(new Error('Not implemented'));
}

function findOpenPort() {
  var net = require('net');
  return new Promise(function(resolve, reject) {
    var server = net.createServer();
    server.on('error', reject);
    server.listen(0, function() {
      var port = this.address().port;
      server.on('close', resolve.bind(null, port));
      server.close();
    });
  });
}

module.exports = function() {
  var store = {};
  var procByPid = {};
  var Pages = {};

  Pages.get = function(id) {
    if (!store[id]) {
      var err = new Error('Process not found');
      err.code = 404;
      throw err;
    }
    return store[id];
  };

  Pages.all = function all(skip, limit) {
    var acc = _.values(store);

    if (skip  == null || isNaN(skip)) { skip = 0; }
    if (limit == null || isNaN(limit)) { limit = acc.length; }

    return acc.slice(skip, skip + limit);
  };

  Pages.remove = function(id) {
    delete store[id];
  };

  Pages.save = function(page) {
    if (!(page instanceof PageModel)) {
      page = new PageModel(page);
    }
    page.validate();
    if (store[page.id] != null) {
      page.joinedAt = store[page.id].joinedAt;
    }
    return store[page.id] = page;
  };

  Pages.launchAndConnect = function(page) {
    // 1. get available debug port
    function getAvailablePort() {
      if (page.port !== null) {
        return verifyPortOpen(page.port);
      }
      return findOpenPort();
    }

    // 2. launch process
    function launchProcess(port) {
      page.port = port;

      var nodePath = process.execPath;
      var nodeArgs = [
        '--debug-brk=' + page.port, page.script
      ].concat(page.args);
      var childOptions = { cwd: page.cwd, env: process.env };

      var child =
        execFile(nodePath, nodeArgs, childOptions);
      if (process.env.BUGGER_PIPE_CHILD) {
        child.stdout.pipe(process.stdout);
        child.stderr.pipe(process.stderr);
      }
      var pid = child.pid;
      child.on('exit', function() {
        if (page.pid === pid) page.pid = null;
      });

      process.on('exit', function() {
        try { child.kill(); } catch (err) {}
      });

      process.on('uncaughtException', function() {
        try { child.kill(); } catch (err) {}
      });

      page.pid = child.pid;
      procByPid[page.pid] = child.pid;
      return attachToPort(page.port).then(function(agents) {
        page.agents = agents
        return page;
      });
    }

    return getAvailablePort().then(launchProcess);
  };

  Pages.createFromUrl = function(urlSpec) {
    var page = new PageModel(_.defaults({
      buggerPort: Pages.buggerPort
    }, pageFromUrl(urlSpec)));
    return Pages.launchAndConnect(page).then(Pages.save);
  };

  Pages.buggerPort = 8058;

  return Pages;
};
<commit_msg>Better responses when invalid files are launched<commit_after>// Copyright (C) 2013 Jan Krems
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
'use strict';

var execFile = require('child_process').execFile;

var Promise = require('bluebird');
var _ = require('lodash');
var attachToPort = require('bugger-agents').attachToPort;
var debug = require('debug')('bugger-daemon:page');

var PageModel = require('./model');
var pageFromUrl = require('./url').pageFromUrl;

function verifyPortOpen(port) {
  return Promise.reject(new Error('Not implemented'));
}

function findOpenPort() {
  var net = require('net');
  return new Promise(function(resolve, reject) {
    var server = net.createServer();
    server.on('error', reject);
    server.listen(0, function() {
      var port = this.address().port;
      server.on('close', resolve.bind(null, port));
      server.close();
    });
  });
}

module.exports = function() {
  var store = {};
  var procByPid = {};
  var Pages = {};

  Pages.get = function(id) {
    if (!store[id]) {
      var err = new Error('Process not found');
      err.code = 404;
      throw err;
    }
    return store[id];
  };

  Pages.all = function all(skip, limit) {
    var acc = _.values(store);

    if (skip  == null || isNaN(skip)) { skip = 0; }
    if (limit == null || isNaN(limit)) { limit = acc.length; }

    return acc.slice(skip, skip + limit);
  };

  Pages.remove = function(id) {
    delete store[id];
  };

  Pages.save = function(page) {
    if (!(page instanceof PageModel)) {
      page = new PageModel(page);
    }
    page.validate();
    if (store[page.id] != null) {
      page.joinedAt = store[page.id].joinedAt;
    }
    return store[page.id] = page;
  };

  Pages.launchAndConnect = function(page) {
    // 1. get available debug port
    function getAvailablePort() {
      debug('getAvailablePort', page.port);
      if (page.port !== null) {
        return verifyPortOpen(page.port);
      }
      return findOpenPort();
    }

    // 2. launch process
    function launchProcess(port) {
      debug('Found available port', port);
      page.port = port;

      var nodePath = process.execPath;
      var nodeArgs = [
        '--debug-brk=' + page.port, page.script
      ].concat(page.args);
      var childOptions = { cwd: page.cwd, env: process.env };

      return new Promise(function(resolve, reject) {
        var child =
          execFile(nodePath, nodeArgs, childOptions);
        if (process.env.BUGGER_PIPE_CHILD) {
          child.stdout.pipe(process.stdout);
          child.stderr.pipe(process.stderr);
        }
        var pid = child.pid;
        child.on('exit', function(exitCode) {
          if (page.pid === pid) page.pid = null;
          reject(new Error('Child exited with code ' + exitCode));
        });

        process.on('exit', function() {
          try { child.kill(); } catch (err) {}
        });

        process.on('uncaughtException', function() {
          try { child.kill(); } catch (err) {}
        });

        page.pid = child.pid;
        procByPid[page.pid] = child.pid;
        debug('Attaching debug client', page.port);
        attachToPort(page.port).then(function(agents) {
          debug('Attached');
          page.agents = agents
          resolve(page);
        });
      });
    }

    return getAvailablePort().then(launchProcess);
  };

  Pages.createFromUrl = function(urlSpec) {
    var page = new PageModel(_.defaults({
      buggerPort: Pages.buggerPort
    }, pageFromUrl(urlSpec)));
    return Pages.launchAndConnect(page).then(Pages.save);
  };

  Pages.buggerPort = 8058;

  return Pages;
};
<|endoftext|>


<commit_before>const {CompositeDisposable, Disposable} = require("atom")
const settings = require("./settings")
let PaneAxis = null

// Return adjacent pane of activePane within current PaneAxis.
//  * return next Pane if exists.
//  * return previous pane if next pane was not exits.
function getAdjacentPane(pane) {
  const parent = pane.getParent()
  if (!parent || !parent.getChildren) return
  const children = pane.getParent().getChildren()
  const index = children.indexOf(pane)
  const [previousPane, nextPane] = [children[index - 1], children[index + 1]]
  return nextPane || previousPane
}

function exchangePane({stay = true} = {}) {
  const activePane = atom.workspace.getActivePane()
  const adjacentPane = getAdjacentPane(activePane)

  // When adjacent was paneAxis, do nothing.
  if (!adjacentPane || adjacentPane.children) return

  const parent = activePane.getParent()
  const children = parent.getChildren()

  if (children.indexOf(activePane) < children.indexOf(adjacentPane)) {
    parent.removeChild(activePane, true)
    parent.insertChildAfter(adjacentPane, activePane)
  } else {
    parent.removeChild(activePane, true)
    parent.insertChildBefore(adjacentPane, activePane)
  }

  adjacentPane.activate()
}

function setFlexScaleToAllPaneAndPaneAxis(root, value) {
  root.setFlexScale(value)
  if (root.children) {
    for (const child of root.children) {
      setFlexScaleToAllPaneAndPaneAxis(child, value)
    }
  }
}

function equalizePanes() {
  const root = atom.workspace.getActivePane().getContainer().getRoot()
  setFlexScaleToAllPaneAndPaneAxis(root, 1)
}

/*
 * decaffeinate suggestions:
 * DS101: Remove unnecessary use of Array.from
 * DS102: Remove unnecessary code created because of implicit returns
 * DS207: Consider shorter variations of null checks
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
function forEachPaneAxis(base, fn) {
  if (base.children) {
    fn(base)
    for (const child of base.children) {
      forEachPaneAxis(child, fn)
    }
  }
}

function maximizePane() {
  const disposables = new CompositeDisposable()

  const addClassList = (element, classList) => {
    classList = classList.map(className => `vim-mode-plus--${className}`)
    element.classList.add(...classList)
    disposables.add(new Disposable(() => element.classList.remove(...classList)))
  }

  const workspaceClassList = ["pane-maximized"]
  if (settings.get("hideTabBarOnMaximizePane")) {
    workspaceClassList.push("hide-tab-bar")
  }
  if (settings.get("hideStatusBarOnMaximizePane")) {
    workspaceClassList.push("hide-status-bar")
  }
  addClassList(atom.workspace.getElement(), workspaceClassList)

  const activePane = atom.workspace.getActivePane()
  const activePaneElement = activePane.getElement()
  addClassList(activePaneElement, ["active-pane"])

  const root = activePane.getContainer().getRoot()
  forEachPaneAxis(root, paneAxis => {
    const element = paneAxis.getElement()
    if (element.contains(activePaneElement)) {
      addClassList(element, ["active-pane-axis"])
    }
  })
  return disposables
}

function reparentNestedPaneAxis(root) {
  forEachPaneAxis(root, paneAxis => {
    const parent = paneAxis.getParent()
    if (parent instanceof PaneAxis && paneAxis.getOrientation() === parent.getOrientation()) {
      let lastChild
      for (const child of paneAxis.getChildren()) {
        if (!lastChild) {
          parent.replaceChild(paneAxis, child)
        } else {
          parent.insertChildAfter(lastChild, child)
        }
        lastChild = child
      }
      paneAxis.destroy()
    }
  })
}

// Valid direction ["top", "bottom", "left", "right"]
function movePaneToVery(direction) {
  if (atom.workspace.getCenter().getPanes().length < 2) return

  const activePane = atom.workspace.getActivePane()
  const container = activePane.getContainer()
  const parent = activePane.getParent()

  const originalRoot = container.getRoot()
  let root = originalRoot
  // If there is multiple pane in window, root is always instance of PaneAxis
  if (!PaneAxis) PaneAxis = root.constructor

  const finalOrientation = ["top", "bottom"].includes(direction) ? "vertical" : "horizontal"

  if (root.getOrientation() !== finalOrientation) {
    root = new PaneAxis({orientation: finalOrientation, children: [root]}, atom.views)
    container.setRoot(root)
  }

  // avoid automatic reparenting by pssing 2nd arg(= replacing ) to `true`.
  parent.removeChild(activePane, true)

  const indexToAdd = ["top", "left"].includes(direction) ? 0 : undefined
  root.addChild(activePane, indexToAdd)

  if (parent.children.length === 1) {
    parent.reparentLastChild()
  }
  reparentNestedPaneAxis(root)
  activePane.activate()
}

module.exports = {
  exchangePane,
  equalizePanes,
  maximizePane,
  movePaneToVery,
}
<commit_msg>:fire: decaffenate comment<commit_after>const {CompositeDisposable, Disposable} = require("atom")
const settings = require("./settings")
let PaneAxis = null

// Return adjacent pane of activePane within current PaneAxis.
//  * return next Pane if exists.
//  * return previous pane if next pane was not exits.
function getAdjacentPane(pane) {
  const parent = pane.getParent()
  if (!parent || !parent.getChildren) return
  const children = pane.getParent().getChildren()
  const index = children.indexOf(pane)
  const [previousPane, nextPane] = [children[index - 1], children[index + 1]]
  return nextPane || previousPane
}

function exchangePane({stay = true} = {}) {
  const activePane = atom.workspace.getActivePane()
  const adjacentPane = getAdjacentPane(activePane)

  // When adjacent was paneAxis, do nothing.
  if (!adjacentPane || adjacentPane.children) return

  const parent = activePane.getParent()
  const children = parent.getChildren()

  if (children.indexOf(activePane) < children.indexOf(adjacentPane)) {
    parent.removeChild(activePane, true)
    parent.insertChildAfter(adjacentPane, activePane)
  } else {
    parent.removeChild(activePane, true)
    parent.insertChildBefore(adjacentPane, activePane)
  }

  adjacentPane.activate()
}

function setFlexScaleToAllPaneAndPaneAxis(root, value) {
  root.setFlexScale(value)
  if (root.children) {
    for (const child of root.children) {
      setFlexScaleToAllPaneAndPaneAxis(child, value)
    }
  }
}

function equalizePanes() {
  const root = atom.workspace.getActivePane().getContainer().getRoot()
  setFlexScaleToAllPaneAndPaneAxis(root, 1)
}

function forEachPaneAxis(base, fn) {
  if (base.children) {
    fn(base)
    for (const child of base.children) {
      forEachPaneAxis(child, fn)
    }
  }
}

function maximizePane() {
  const disposables = new CompositeDisposable()

  const addClassList = (element, classList) => {
    classList = classList.map(className => `vim-mode-plus--${className}`)
    element.classList.add(...classList)
    disposables.add(new Disposable(() => element.classList.remove(...classList)))
  }

  const workspaceClassList = ["pane-maximized"]
  if (settings.get("hideTabBarOnMaximizePane")) {
    workspaceClassList.push("hide-tab-bar")
  }
  if (settings.get("hideStatusBarOnMaximizePane")) {
    workspaceClassList.push("hide-status-bar")
  }
  addClassList(atom.workspace.getElement(), workspaceClassList)

  const activePane = atom.workspace.getActivePane()
  const activePaneElement = activePane.getElement()
  addClassList(activePaneElement, ["active-pane"])

  const root = activePane.getContainer().getRoot()
  forEachPaneAxis(root, paneAxis => {
    const element = paneAxis.getElement()
    if (element.contains(activePaneElement)) {
      addClassList(element, ["active-pane-axis"])
    }
  })
  return disposables
}

function reparentNestedPaneAxis(root) {
  forEachPaneAxis(root, paneAxis => {
    const parent = paneAxis.getParent()
    if (parent instanceof PaneAxis && paneAxis.getOrientation() === parent.getOrientation()) {
      let lastChild
      for (const child of paneAxis.getChildren()) {
        if (!lastChild) {
          parent.replaceChild(paneAxis, child)
        } else {
          parent.insertChildAfter(lastChild, child)
        }
        lastChild = child
      }
      paneAxis.destroy()
    }
  })
}

// Valid direction ["top", "bottom", "left", "right"]
function movePaneToVery(direction) {
  if (atom.workspace.getCenter().getPanes().length < 2) return

  const activePane = atom.workspace.getActivePane()
  const container = activePane.getContainer()
  const parent = activePane.getParent()

  const originalRoot = container.getRoot()
  let root = originalRoot
  // If there is multiple pane in window, root is always instance of PaneAxis
  if (!PaneAxis) PaneAxis = root.constructor

  const finalOrientation = ["top", "bottom"].includes(direction) ? "vertical" : "horizontal"

  if (root.getOrientation() !== finalOrientation) {
    root = new PaneAxis({orientation: finalOrientation, children: [root]}, atom.views)
    container.setRoot(root)
  }

  // avoid automatic reparenting by pssing 2nd arg(= replacing ) to `true`.
  parent.removeChild(activePane, true)

  const indexToAdd = ["top", "left"].includes(direction) ? 0 : undefined
  root.addChild(activePane, indexToAdd)

  if (parent.children.length === 1) {
    parent.reparentLastChild()
  }
  reparentNestedPaneAxis(root)
  activePane.activate()
}

module.exports = {
  exchangePane,
  equalizePanes,
  maximizePane,
  movePaneToVery,
}
<|endoftext|>


<commit_before>'use strict';

var skeemas = require('skeemas'),
    objectAssign = require('object-assign');

function validateParam(spec, value) {
  var paramSchema = objectAssign({}, spec),
      paramValue = value;
  if(paramSchema.in === 'body') {
    paramSchema = paramSchema.schema; //"body" params are nest under schema
    paramValue = JSON.parse(value);
  }

  return skeemas.validate(paramValue, paramSchema);
}

module.exports = function parameters(pathSpec, options, parameters) {
  parameters = parameters || {};
  options = objectAssign({}, options);
  parameters = objectAssign({}, parameters),
  pathSpec.parameters = pathSpec.parameters || [];

  if(options.body) {
    parameters.body = options.body;
  }

  //check for extra parameters
  var pathSpecParamHash = pathSpec.parameters.reduce(function(hash, param) {
    hash[param.name] = param;
    return hash;
  }, {});
  Object.keys(parameters).forEach(function(param) {
    if(!pathSpecParamHash[param]) {
      throw new Error('Parameter not mentioned in swagger spec: "' + param + '", available params: ' +
        pathSpec.parameters.map(function(p) {
          return p.name;
        }).join(',')
      );
    }
  });

  if(pathSpec.parameters && pathSpec.parameters.length) {
    //validate provided parameters
    pathSpec.parameters.forEach(function(param) {
      //check for existance of required parameters
      if(!Object.keys(parameters).length || parameters[param.name] === undefined) {
        if(param.required) {
          throw new Error('Missing required parameter: ' + param.name + '.  Did you forget to call "params({' + param.name + ': value})"?');
        }
        return true; //not required; continue.
      }
      //validate parameter against json-schema definition
      var result = validateParam(param, parameters[param.name]);
      if(!result.valid) throw new Error('Invalid format for parameter {' + param.name + '}, received: ' + parameters[param.name] + '.  errors:' + result.errors.join(','));

      //replace parameter in url
      var regex = new RegExp('{' + param.name + '}', 'g');
      options.url = options.url.replace(regex, parameters[param.name]);
    });
  }
  return options;
}<commit_msg>minor reorg of parameters.js<commit_after>'use strict';

var skeemas = require('skeemas'),
    objectAssign = require('object-assign');

function validateParam(spec, value) {
  var paramSchema = objectAssign({}, spec),
      paramValue = value;
  if(paramSchema.in === 'body') {
    paramSchema = paramSchema.schema; //"body" params are nest under schema
    paramValue = JSON.parse(value);
  }

  return skeemas.validate(paramValue, paramSchema);
}

function checkForExtraParameters(pathSpec, parameters) {
  var pathSpecParamHash = pathSpec.parameters.reduce(function(hash, param) {
    hash[param.name] = param;
    return hash;
  }, {});
  Object.keys(parameters).forEach(function(param) {
    if(!pathSpecParamHash[param]) {
      throw new Error('Parameter not mentioned in swagger spec: "' + param + '", available params: ' +
        pathSpec.parameters.map(function(p) {
          return p.name;
        }).join(',')
      );
    }
  });
}

module.exports = function parameters(pathSpec, options, parameters) {
  parameters = parameters || {};
  options = objectAssign({}, options);
  parameters = objectAssign({}, parameters),
  pathSpec.parameters = pathSpec.parameters || [];

  if(options.body) {
    parameters.body = options.body;
  }

  checkForExtraParameters(pathSpec, parameters);

  if(pathSpec.parameters && pathSpec.parameters.length) {
    //validate provided parameters
    pathSpec.parameters.forEach(function(param) {
      //check for existance of required parameters
      if(!Object.keys(parameters).length || parameters[param.name] === undefined) {
        if(param.required) {
          throw new Error('Missing required parameter: ' + param.name + '.  Did you forget to call "params({' + param.name + ': value})"?');
        }
        return true; //not required; continue.
      }
      //validate parameter against json-schema definition
      var result = validateParam(param, parameters[param.name]);
      if(!result.valid) throw new Error('Invalid format for parameter {' + param.name + '}, received: ' + parameters[param.name] + '.  errors:' + result.errors.join(','));

      //replace parameter in url
      var regex = new RegExp('{' + param.name + '}', 'g');
      options.url = options.url.replace(regex, parameters[param.name]);
    });
  }
  return options;
}<|endoftext|>


<commit_before>const { EOL } = require('os');
const { Buffer } = require('safe-buffer');
const encoding = require('encoding');
const sharedFuncs = require('./shared');
const contentType = require('content-type');

/**
 * Exposes general compiler function. Takes a translation
 * object as a parameter and returns PO object
 *
 * @param {Object} table Translation object
 * @return {Buffer} Compiled PO object
 */
module.exports = function (table, options) {
  const compiler = new Compiler(table, options);

  return compiler.compile();
};

/**
 * Creates a PO compiler object.
 *
 * @constructor
 * @param {Object} table Translation table to be compiled
 */
function Compiler (table = {}, options = {}) {
  this._table = table;
  this._options = options;

  this._table.translations = this._table.translations || {};

  let { headers = {} } = this._table;

  headers = Object.keys(headers).reduce((result, key) => {
    const lowerKey = key.toLowerCase();

    if (sharedFuncs.HEADERS.has(lowerKey)) {
      result[sharedFuncs.HEADERS.get(lowerKey)] = headers[key];
    } else {
      result[key] = headers[key];
    }

    return result;
  }, {});

  this._table.headers = headers;

  if (!('foldLength' in this._options)) {
    this._options.foldLength = 76;
  }

  if (!('sort' in this._options)) {
    this._options.sort = false;
  }

  if (!('eol' in this._options)) {
    this._options.eol = '\n';
  }

  this._translations = [];

  this._handleCharset();
}

/**
 * Converts a comments object to a comment string. The comment object is
 * in the form of {translator:'', reference: '', extracted: '', flag: '', previous:''}
 *
 * @param {Object} comments A comments object
 * @return {String} A comment string for the PO file
 */
Compiler.prototype._drawComments = function (comments) {
  const lines = [];
  const types = [{
    key: 'translator',
    prefix: '# '
  }, {
    key: 'reference',
    prefix: '#: '
  }, {
    key: 'extracted',
    prefix: '#. '
  }, {
    key: 'flag',
    prefix: '#, '
  }, {
    key: 'previous',
    prefix: '#| '
  }];

  types.forEach(type => {
    if (!comments[type.key]) {
      return;
    }

    comments[type.key].split(/\r?\n|\r/).forEach(line => {
      lines.push(`${type.prefix}${line}`);
    });
  });

  return lines.join(this._options.eol);
};

/**
 * Builds a PO string for a single translation object
 *
 * @param {Object} block Translation object
 * @param {Object} [override] Properties of this object will override `block` properties
 * @return {String} Translation string for a single object
 */
Compiler.prototype._drawBlock = function (block, override = {}) {
  const response = [];
  const msgctxt = override.msgctxt || block.msgctxt;
  const msgid = override.msgid || block.msgid;
  const msgidPlural = override.msgid_plural || block.msgid_plural;
  const msgstr = [].concat(override.msgstr || block.msgstr);
  let comments = override.comments || block.comments;

  // add comments
  if (comments && (comments = this._drawComments(comments))) {
    response.push(comments);
  }

  if (msgctxt) {
    response.push(this._addPOString('msgctxt', msgctxt));
  }

  response.push(this._addPOString('msgid', msgid || ''));

  if (msgidPlural) {
    response.push(this._addPOString('msgid_plural', msgidPlural));

    msgstr.forEach((msgstr, i) => {
      response.push(this._addPOString(`msgstr[${i}]`, msgstr || ''));
    });
  } else {
    response.push(this._addPOString('msgstr', msgstr[0] || ''));
  }

  return response.join(this._options.eol);
};

/**
 * Escapes and joins a key and a value for the PO string
 *
 * @param {String} key Key name
 * @param {String} value Key value
 * @return {String} Joined and escaped key-value pair
 */
Compiler.prototype._addPOString = function (key = '', value = '') {
  key = key.toString();

  // escape newlines and quotes
  value = value.toString()
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')
    .replace(/\t/g, '\\t')
    .replace(/\r/g, '\\r')
    .replace(/\n/g, '\\n');

  let lines = [value];

  const { foldLength, eol } = this._options;

  if (foldLength > 0) {
    lines = sharedFuncs.foldLine(value, foldLength);
  }

  if (lines.length < 2) {
    return `${key} "${lines.shift() || ''}"`;
  }

  return `${key} ""${eol}"${lines.join(`"${eol}"`)}"`;
};

/**
 * Handles header values, replaces or adds (if needed) a charset property
 */
Compiler.prototype._handleCharset = function () {
  const ct = contentType.parse(this._table.headers['Content-Type'] || 'text/plain');

  const charset = sharedFuncs.formatCharset(this._table.charset || ct.parameters.charset || 'utf-8');

  // clean up content-type charset independently using fallback if missing
  if (ct.parameters.charset) {
    ct.parameters.charset = sharedFuncs.formatCharset(ct.parameters.charset);
  }

  this._table.charset = charset;
  this._table.headers['Content-Type'] = contentType.format(ct);
};

/**
 * Compiles translation object into a PO object
 *
 * @return {Buffer} Compiled PO object
 */
Compiler.prototype.compile = function () {
  const headerBlock = (this._table.translations[''] && this._table.translations['']['']) || {};
  let response = [];

  Object.keys(this._table.translations).forEach(msgctxt => {
    if (typeof this._table.translations[msgctxt] !== 'object') {
      return;
    }

    Object.keys(this._table.translations[msgctxt]).forEach(msgid => {
      if (typeof this._table.translations[msgctxt][msgid] !== 'object') {
        return;
      }

      if (msgctxt === '' && msgid === '') {
        return;
      }

      response.push(this._table.translations[msgctxt][msgid]);
    });
  });

  const { sort, eol } = this._options;

  if (sort !== false) {
    if (typeof sort === 'function') {
      response = response.sort(sort);
    } else {
      response = response.sort(sharedFuncs.compareMsgid);
    }
  }

  response = response.map(r => this._drawBlock(r));

  response.unshift(this._drawBlock(headerBlock, {
    msgstr: sharedFuncs.generateHeader(this._table.headers)
  }));

  if (this._table.charset === 'utf-8' || this._table.charset === 'ascii') {
    return Buffer.from(response.join(eol + eol), 'utf-8');
  }

  return encoding.convert(response.join(eol + eol), this._table.charset);
};
<commit_msg>remove unused var<commit_after>const { Buffer } = require('safe-buffer');
const encoding = require('encoding');
const sharedFuncs = require('./shared');
const contentType = require('content-type');

/**
 * Exposes general compiler function. Takes a translation
 * object as a parameter and returns PO object
 *
 * @param {Object} table Translation object
 * @return {Buffer} Compiled PO object
 */
module.exports = function (table, options) {
  const compiler = new Compiler(table, options);

  return compiler.compile();
};

/**
 * Creates a PO compiler object.
 *
 * @constructor
 * @param {Object} table Translation table to be compiled
 */
function Compiler (table = {}, options = {}) {
  this._table = table;
  this._options = options;

  this._table.translations = this._table.translations || {};

  let { headers = {} } = this._table;

  headers = Object.keys(headers).reduce((result, key) => {
    const lowerKey = key.toLowerCase();

    if (sharedFuncs.HEADERS.has(lowerKey)) {
      result[sharedFuncs.HEADERS.get(lowerKey)] = headers[key];
    } else {
      result[key] = headers[key];
    }

    return result;
  }, {});

  this._table.headers = headers;

  if (!('foldLength' in this._options)) {
    this._options.foldLength = 76;
  }

  if (!('sort' in this._options)) {
    this._options.sort = false;
  }

  if (!('eol' in this._options)) {
    this._options.eol = '\n';
  }

  this._translations = [];

  this._handleCharset();
}

/**
 * Converts a comments object to a comment string. The comment object is
 * in the form of {translator:'', reference: '', extracted: '', flag: '', previous:''}
 *
 * @param {Object} comments A comments object
 * @return {String} A comment string for the PO file
 */
Compiler.prototype._drawComments = function (comments) {
  const lines = [];
  const types = [{
    key: 'translator',
    prefix: '# '
  }, {
    key: 'reference',
    prefix: '#: '
  }, {
    key: 'extracted',
    prefix: '#. '
  }, {
    key: 'flag',
    prefix: '#, '
  }, {
    key: 'previous',
    prefix: '#| '
  }];

  types.forEach(type => {
    if (!comments[type.key]) {
      return;
    }

    comments[type.key].split(/\r?\n|\r/).forEach(line => {
      lines.push(`${type.prefix}${line}`);
    });
  });

  return lines.join(this._options.eol);
};

/**
 * Builds a PO string for a single translation object
 *
 * @param {Object} block Translation object
 * @param {Object} [override] Properties of this object will override `block` properties
 * @return {String} Translation string for a single object
 */
Compiler.prototype._drawBlock = function (block, override = {}) {
  const response = [];
  const msgctxt = override.msgctxt || block.msgctxt;
  const msgid = override.msgid || block.msgid;
  const msgidPlural = override.msgid_plural || block.msgid_plural;
  const msgstr = [].concat(override.msgstr || block.msgstr);
  let comments = override.comments || block.comments;

  // add comments
  if (comments && (comments = this._drawComments(comments))) {
    response.push(comments);
  }

  if (msgctxt) {
    response.push(this._addPOString('msgctxt', msgctxt));
  }

  response.push(this._addPOString('msgid', msgid || ''));

  if (msgidPlural) {
    response.push(this._addPOString('msgid_plural', msgidPlural));

    msgstr.forEach((msgstr, i) => {
      response.push(this._addPOString(`msgstr[${i}]`, msgstr || ''));
    });
  } else {
    response.push(this._addPOString('msgstr', msgstr[0] || ''));
  }

  return response.join(this._options.eol);
};

/**
 * Escapes and joins a key and a value for the PO string
 *
 * @param {String} key Key name
 * @param {String} value Key value
 * @return {String} Joined and escaped key-value pair
 */
Compiler.prototype._addPOString = function (key = '', value = '') {
  key = key.toString();

  // escape newlines and quotes
  value = value.toString()
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')
    .replace(/\t/g, '\\t')
    .replace(/\r/g, '\\r')
    .replace(/\n/g, '\\n');

  let lines = [value];

  const { foldLength, eol } = this._options;

  if (foldLength > 0) {
    lines = sharedFuncs.foldLine(value, foldLength);
  }

  if (lines.length < 2) {
    return `${key} "${lines.shift() || ''}"`;
  }

  return `${key} ""${eol}"${lines.join(`"${eol}"`)}"`;
};

/**
 * Handles header values, replaces or adds (if needed) a charset property
 */
Compiler.prototype._handleCharset = function () {
  const ct = contentType.parse(this._table.headers['Content-Type'] || 'text/plain');

  const charset = sharedFuncs.formatCharset(this._table.charset || ct.parameters.charset || 'utf-8');

  // clean up content-type charset independently using fallback if missing
  if (ct.parameters.charset) {
    ct.parameters.charset = sharedFuncs.formatCharset(ct.parameters.charset);
  }

  this._table.charset = charset;
  this._table.headers['Content-Type'] = contentType.format(ct);
};

/**
 * Compiles translation object into a PO object
 *
 * @return {Buffer} Compiled PO object
 */
Compiler.prototype.compile = function () {
  const headerBlock = (this._table.translations[''] && this._table.translations['']['']) || {};
  let response = [];

  Object.keys(this._table.translations).forEach(msgctxt => {
    if (typeof this._table.translations[msgctxt] !== 'object') {
      return;
    }

    Object.keys(this._table.translations[msgctxt]).forEach(msgid => {
      if (typeof this._table.translations[msgctxt][msgid] !== 'object') {
        return;
      }

      if (msgctxt === '' && msgid === '') {
        return;
      }

      response.push(this._table.translations[msgctxt][msgid]);
    });
  });

  const { sort, eol } = this._options;

  if (sort !== false) {
    if (typeof sort === 'function') {
      response = response.sort(sort);
    } else {
      response = response.sort(sharedFuncs.compareMsgid);
    }
  }

  response = response.map(r => this._drawBlock(r));

  response.unshift(this._drawBlock(headerBlock, {
    msgstr: sharedFuncs.generateHeader(this._table.headers)
  }));

  if (this._table.charset === 'utf-8' || this._table.charset === 'ascii') {
    return Buffer.from(response.join(eol + eol), 'utf-8');
  }

  return encoding.convert(response.join(eol + eol), this._table.charset);
};
<|endoftext|>


<commit_before>const path = require('path');
const commander = require('commander');
const spawn = require('cross-spawn');
const chalk = require('chalk');
const newCmd = require('./new');

const exitWithError = message => {
  console.error(chalk.red(`ERROR: ${message}`));
  process.exit(1);
};

commander.version(
  require(path.join(__dirname, 'package.json')).version,
);

commander
  .command('new')
  .description('generate a new application')
  .arguments('<appName>')
  .option('-d, --dev <path>', 'relative path to development version of gluestick')
  .option('-y, --yarn', 'use yarn instead of npm')
  .action((appName, options) => {
    newCmd(appName, options, exitWithError);
  });

commander
  .command('reinstall-dev')
  .description('reinstall gluestick dependency')
  .action(() => {
    let gsPath = null;
    try {
      gsPath = require(path.join(process.cwd(), 'package.json')).dependencies.gluestick;
    } catch (error) {
      exitWithError(error.message);
    }
    spawn(
      'npm',
      ['install', gsPath],
      { stdio: 'inherit' },
    );
  });

commander
  .command('watch')
  .description('watch and apply changes from gluestick to project')
  .action(() => {
    const packagePath = path.join(process.cwd(), 'package.json');
    let packageContent = null;
    try {
      packageContent = require(packagePath);
    } catch (error) {
      exitWithError(`Cannot find package.json in ${packagePath}`);
    }
    let srcPath = null;
    try {
      if (!/file:.*/.test(packageContent.dependencies.gluestick)) {
        exitWithError('Gluestick dependency does not contain valid path');
      }
      srcPath = path.join(
        process.cwd(),
        packageContent.dependencies.gluestick.replace('file:', ''),
      );
    } catch (error) {
      exitWithError('Invalid package.json');
    }
    const wmlBin = path.join(__dirname, './node_modules/.bin/wml');
    spawn.sync(
      wmlBin,
      ['add', srcPath, path.join(process.cwd(), 'node_modules/gluestick')],
      { stdio: 'inherit' },
    );
    spawn.sync(
      'watchman',
      ['watch', srcPath],
      { stdio: 'inherit' },
    );
    spawn.sync(
      wmlBin,
      ['start'],
      { stdio: 'inherit' },
    );
  });

commander
  .command('*', null, { noHelp: true })
  .action(() => {
    spawn(
      './node_modules/.bin/gluestick',
      commander.rawArgs.slice(2),
      { stdio: 'inherit' },
    );
  });

commander.parse(process.argv);
<commit_msg>Extend path from dependency<commit_after>const path = require('path');
const commander = require('commander');
const spawn = require('cross-spawn');
const chalk = require('chalk');
const newCmd = require('./new');

const exitWithError = message => {
  console.error(chalk.red(`ERROR: ${message}`));
  process.exit(1);
};

commander.version(
  require(path.join(__dirname, 'package.json')).version,
);

commander
  .command('new')
  .description('generate a new application')
  .arguments('<appName>')
  .option('-d, --dev <path>', 'relative path to development version of gluestick')
  .option('-y, --yarn', 'use yarn instead of npm')
  .action((appName, options) => {
    newCmd(appName, options, exitWithError);
  });

commander
  .command('reinstall-dev')
  .description('reinstall gluestick dependency')
  .action(() => {
    let gsPath = null;
    try {
      gsPath = require(path.join(process.cwd(), 'package.json')).dependencies.gluestick;
    } catch (error) {
      exitWithError(error.message);
    }
    spawn(
      'npm',
      ['install', gsPath],
      { stdio: 'inherit' },
    );
  });

commander
  .command('watch')
  .description('watch and apply changes from gluestick to project')
  .action(() => {
    const packagePath = path.join(process.cwd(), 'package.json');
    let packageContent = null;
    try {
      packageContent = require(packagePath);
    } catch (error) {
      exitWithError(`Cannot find package.json in ${packagePath}`);
    }
    let srcPath = null;
    try {
      if (!/file:.*/.test(packageContent.dependencies.gluestick)) {
        exitWithError('Gluestick dependency does not contain valid path');
      }
      const pathFromDependency = packageContent.dependencies.gluestick.replace('file://', '').replace('file:', '')
      srcPath = pathFromDependency[0] !== '/'
        ? path.join(
            process.cwd(),
            pathFromDependency
          )
        : pathFromDependency
    } catch (error) {
      exitWithError('Invalid package.json');
    }
    const wmlBin = path.join(__dirname, './node_modules/.bin/wml');
    spawn.sync(
      wmlBin,
      ['rm', 'all'],
      { stdio: 'inherit' },
    );
    spawn.sync(
      wmlBin,
      ['add', srcPath, path.join(process.cwd(), 'node_modules/gluestick')],
      { stdio: 'inherit' },
    );
    spawn.sync(
      'watchman',
      ['watch', srcPath],
      { stdio: 'inherit' },
    );
    spawn.sync(
      wmlBin,
      ['start'],
      { stdio: 'inherit' },
    );
  });

commander
  .command('*', null, { noHelp: true })
  .action(() => {
    spawn(
      './node_modules/.bin/gluestick',
      commander.rawArgs.slice(2),
      { stdio: 'inherit' },
    );
  });

commander.parse(process.argv);
<|endoftext|>


<commit_before>const PythonShell = require('python-shell');
const { join } = require('path');

const options = {};
const scriptPath = join(__dirname, 'script.py');

exports.readValues = () => {
  return new Promise((resolve, reject) => {
    console.log(scriptPath);
    PythonShell.run(scriptPath, options, function (err, results) {
      if (err) return reject(err);

      // results is an array consisting of messages collected during execution
      const result = results[0]; // should only be 1
      resolve(JSON.parse(result));
    });
  });
};
<commit_msg>change script path<commit_after>const PythonShell = require('python-shell');

const options = {};
const scriptPath = 'lib/script.py';

exports.readValues = () => {
  return new Promise((resolve, reject) => {
    console.log(scriptPath);
    PythonShell.run(scriptPath, options, function (err, results) {
      if (err) return reject(err);

      // results is an array consisting of messages collected during execution
      const result = results[0]; // should only be 1
      resolve(JSON.parse(result));
    });
  });
};
<|endoftext|>