<commit_before>/*
* Project: Bootstrap Notify = v3.1.3
* Description: Turns standard Bootstrap alerts into "Growl-like" notifications.
* Author: Mouse0270 aka Robert McIntosh
* License: MIT License
* Website: https://github.com/mouse0270/bootstrap-growl
*/
(function (factory) {
	if (false) {
		// AMD. Register as an anonymous module.
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS
		factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {
	// Create the defaults once
	var defaults = {
			element: 'body',
			position: null,
			type: "info",
			allow_dismiss: true,
			newest_on_top: false,
			showProgressbar: false,
			placement: {
				from: "top",
				align: "right"
			},
			offset: 20,
			spacing: 10,
			z_index: 1031,
			delay: 5000,
			timer: 1000,
			url_target: '_blank',
			mouse_over: null,
			animate: {
				enter: 'animated fadeInDown',
				exit: 'animated fadeOutUp'
			},
			onShow: null,
			onShown: null,
			onClose: null,
			onClosed: null,
			icon_type: 'class',
			template: '
<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button> {1} {2}

'
		};

	String.format = function() {
		var str = arguments[0];
		for (var i = 1; i < arguments.length; i++) {
			str = str.replace(RegExp("\\{" + (i - 1) + "\\}", "gm"), arguments[i]);
		}
		return str;
	};

	function Notify ( element, content, options ) {
		// Setup Content of Notify
		var content = {
			content: {
				message: typeof content == 'object' ? content.message : content,
				title: content.title ? content.title : '',
				icon: content.icon ? content.icon : '',
				url: content.url ? content.url : '#',
				target: content.target ? content.target : '-'
			}
		};

		options = $.extend(true, {}, content, options);
		this.settings = $.extend(true, {}, defaults, options);
		this._defaults = defaults;
		if (this.settings.content.target == "-") {
			this.settings.content.target = this.settings.url_target;
		}
		this.animations = {
			start: 'webkitAnimationStart oanimationstart MSAnimationStart animationstart',
			end: 'webkitAnimationEnd oanimationend MSAnimationEnd animationend'
		}

		if (typeof this.settings.offset == 'number') {
		    this.settings.offset = {
		    	x: this.settings.offset,
		    	y: this.settings.offset
		    };
		}

		this.init();
	};

	$.extend(Notify.prototype, {
		init: function () {
			var self = this;

			this.buildNotify();
			if (this.settings.content.icon) {
				this.setIcon();
			}
			if (this.settings.content.url != "#") {
				this.styleURL();
			}
			this.placement();
			this.bind();

			this.notify = {
				$ele: this.$ele,
				update: function(command, update) {
					var commands = {};
					if (typeof command == "string") {
						commands[command] = update;
					}else{
						commands = command;
					}
					for (var command in commands) {
						switch (command) {
							case "type":
								this.$ele.removeClass('alert-' + self.settings.type);
								this.$ele.find('[data-notify="progressbar"] > .progress-bar').removeClass('progress-bar-' + self.settings.type);
								self.settings.type = commands[command];
								this.$ele.addClass('alert-' + commands[command]).find('[data-notify="progressbar"] > .progress-bar').addClass('progress-bar-' + commands[command]);
								break;
							case "icon":
								var $icon = this.$ele.find('[data-notify="icon"]');
								if (self.settings.icon_type.toLowerCase() == 'class') {
									$icon.removeClass(self.settings.content.icon).addClass(commands[command]);
								}else{
									if (!$icon.is('img')) {
										$icon.find('img');
									}
									$icon.attr('src', commands[command]);
								}
								break;
							case "progress":
								var newDelay = self.settings.delay - (self.settings.delay * (commands[command] / 100));
								this.$ele.data('notify-delay', newDelay);
								this.$ele.find('[data-notify="progressbar"] > div').attr('aria-valuenow', commands[command]).css('width', commands[command] + '%');
								break;
							case "url":
								this.$ele.find('[data-notify="url"]').attr('href', commands[command]);
								break;
							case "target":
								this.$ele.find('[data-notify="url"]').attr('target', commands[command]);
								break;
							default:
								this.$ele.find('[data-notify="' + command +'"]').html(commands[command]);
						};
					}
					var posX = this.$ele.outerHeight() + parseInt(self.settings.spacing) + parseInt(self.settings.offset.y);
					self.reposition(posX);
				},
				close: function() {
					self.close();
				}
			};
		},
		buildNotify: function () {
			var content = this.settings.content;
			this.$ele = $(String.format(this.settings.template, this.settings.type, content.title, content.message, content.url, content.target));
			this.$ele.attr('data-notify-position', this.settings.placement.from + '-' + this.settings.placement.align);
			if (!this.settings.allow_dismiss) {
				this.$ele.find('[data-notify="dismiss"]').css('display', 'none');
			}
			if ((this.settings.delay <= 0 && !this.settings.showProgressbar) || !this.settings.showProgressbar) {
				this.$ele.find('[data-notify="progressbar"]').remove();
			}
		},
		setIcon: function() {
			if (this.settings.icon_type.toLowerCase() == 'class') {
				this.$ele.find('[data-notify="icon"]').addClass(this.settings.content.icon);
			}else{
				if (this.$ele.find('[data-notify="icon"]').is('img')) {
					this.$ele.find('[data-notify="icon"]').attr('src', this.settings.content.icon);
				}else{
					this.$ele.find('[data-notify="icon"]').append('');
				}
			}
		},
		styleURL: function() {
			this.$ele.find('[data-notify="url"]').css({
				backgroundImage: 'url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)',
				height: '100%',
				left: '0px',
				position: 'absolute',
				top: '0px',
				width: '100%',
				zIndex: this.settings.z_index + 1
			});
			this.$ele.find('[data-notify="dismiss"]').css({
				position: 'absolute',
				right: '10px',
				top: '5px',
				zIndex: this.settings.z_index + 2
			});
		},
		placement: function() {
			var self = this,
				offsetAmt = this.settings.offset.y,
				css = {
					display: 'inline-block',
					margin: '0px auto',
					position: this.settings.position ?  this.settings.position : (this.settings.element === 'body' ? 'fixed' : 'absolute'),
					transition: 'all .5s ease-in-out',
					zIndex: this.settings.z_index
				},
				hasAnimation = false,
				settings = this.settings;

			$('[data-notify-position="' + this.settings.placement.from + '-' + this.settings.placement.align + '"]:not([data-closing="true"])').each(function() {
				return offsetAmt = Math.max(offsetAmt, parseInt($(this).css(settings.placement.from)) +  parseInt($(this).outerHeight()) +  parseInt(settings.spacing));
			});
			if (this.settings.newest_on_top == true) {
				offsetAmt = this.settings.offset.y;
			}
			css[this.settings.placement.from] = offsetAmt+'px';

			switch (this.settings.placement.align) {
				case "left":
				case "right":
					css[this.settings.placement.align] = this.settings.offset.x+'px';
					break;
				case "center":
					css.left = 0;
					css.right = 0;
					break;
			}
			this.$ele.css(css).addClass(this.settings.animate.enter);
			$.each(Array('webkit', 'moz', 'o', 'ms', ''), function(index, prefix) {
				self.$ele[0].style[prefix+'AnimationIterationCount'] = 1;
			});

			$(this.settings.element).append(this.$ele);

			if (this.settings.newest_on_top == true) {
				offsetAmt = (parseInt(offsetAmt)+parseInt(this.settings.spacing)) + this.$ele.outerHeight();
				this.reposition(offsetAmt);
			}

			if ($.isFunction(self.settings.onShow)) {
				self.settings.onShow.call(this.$ele);
			}

			this.$ele.one(this.animations.start, function(event) {
				hasAnimation = true;
			}).one(this.animations.end, function(event) {
				if ($.isFunction(self.settings.onShown)) {
					self.settings.onShown.call(this);
				}
			});

			setTimeout(function() {
				if (!hasAnimation) {
					if ($.isFunction(self.settings.onShown)) {
						self.settings.onShown.call(this);
					}
				}
			}, 600);
		},
		bind: function() {
			var self = this;

			this.$ele.find('[data-notify="dismiss"]').on('click', function() {
				self.close();
			})

			this.$ele.mouseover(function(e) {
				$(this).data('data-hover', "true");
			}).mouseout(function(e) {
				$(this).data('data-hover', "false");
			});
			this.$ele.data('data-hover', "false");

			if (this.settings.delay > 0) {
				self.$ele.data('notify-delay', self.settings.delay);
				var timer = setInterval(function() {
					var delay = parseInt(self.$ele.data('notify-delay')) - self.settings.timer;
					if ((self.$ele.data('data-hover') === 'false' && self.settings.mouse_over == "pause") || self.settings.mouse_over != "pause") {
						var percent = ((self.settings.delay - delay) / self.settings.delay) * 100;
						self.$ele.data('notify-delay', delay);
						self.$ele.find('[data-notify="progressbar"] > div').attr('aria-valuenow', percent).css('width', percent + '%');
					}
					if (delay <= -(self.settings.timer)) {
						clearInterval(timer);
						self.close();
					}
				}, self.settings.timer);
			}
		},
		close: function() {
			var self = this,
				$successors = null,
				posX = parseInt(this.$ele.css(this.settings.placement.from)),
				hasAnimation = false;

			this.$ele.data('closing', 'true').addClass(this.settings.animate.exit);
			self.reposition(posX);

			if ($.isFunction(self.settings.onClose)) {
				self.settings.onClose.call(this.$ele);
			}

			this.$ele.one(this.animations.start, function(event) {
				hasAnimation = true;
			}).one(this.animations.end, function(event) {
				$(this).remove();
				if ($.isFunction(self.settings.onClosed)) {
					self.settings.onClosed.call(this);
				}
			});

			setTimeout(function() {
				if (!hasAnimation) {
					self.$ele.remove();
					if (self.settings.onClosed) {
						self.settings.onClosed(self.$ele);
					}
				}
			}, 600);
		},
		reposition: function(posX) {
			var self = this,
				notifies = '[data-notify-position="' + this.settings.placement.from + '-' + this.settings.placement.align + '"]:not([data-closing="true"])',
				$elements = this.$ele.nextAll(notifies);
			if (this.settings.newest_on_top == true) {
				$elements = this.$ele.prevAll(notifies);
			}
			$elements.each(function() {
				$(this).css(self.settings.placement.from, posX);
				posX = (parseInt(posX)+parseInt(self.settings.spacing)) + $(this).outerHeight();
			});
		}
	});

	$.notify = function ( content, options ) {
		var plugin = new Notify( this, content, options );
		return plugin.notify;
	};
	$.notifyDefaults = function( options ) {
		defaults = $.extend(true, {}, defaults, options);
		return defaults;
	};
	$.notifyClose = function( command ) {
		if (typeof command === "undefined" || command == "all") {
			$('[data-notify]').find('[data-notify="dismiss"]').trigger('click');
		}else{
			$('[data-notify-position="'+command+'"]').find('[data-notify="dismiss"]').trigger('click');
		}
	};

}));<commit_msg>3 days later....fix issue where $.notify was undefined!! #61-sqlcell<commit_after><|endoftext|>


<commit_before>import Player from './Player'
import _ from 'lodash'
import CacheManager from './CacheManager'

export default class Computer extends Player{

	constructor() {
		super(...arguments)
		this.type = "computer"
		this.cache = new CacheManager({
			enabled: this.options.hasOwnProperty('cacheEnabled') ? this.options.cacheEnabled : true
		})
	}

	onMyTurn(board, turn) {
		process.nextTick(() => {
			this.findMoveInWorker(board, turn, () => {
				this.makeMove(this.choice.x, this.choice.y)
			})
		})
	}

	findMoveInWorker(board, turn, cb) {
		// TODO: Move this into a separate process/worker
		let opponent = turn === "X" ? "O" : "X"
		let w
		this.minimax(board, turn, turn, 0)
		cb()
	}

	findWinningMove(board, turn) { // Try to find two in a row
		let positions = []
		board.traverseRows((row) => {
			let same = row.filter((c) => c.piece === turn)
			if(same.length != board.size - 1)
				return false
			let empty = row.filter((c) => !c.piece)
			if(empty.length == 1)
				positions.push(empty[0])
		})
		return positions
	}

	getMMScore(board, turn, depth) {
		let winner = board.findWinner()
		if(winner === turn) {
			return 10 - (depth || 0)
		}
		else if(winner === (turn === "X" ? "O" : "X")){
			return (depth || 0) - 10
		}
		else {
			return 0
		}
	}

	scoreByRows(board, turn) {
		let score = 0
		board.traverseRows((row) => {
			let same = row.filter((c) => c.piece === turn)
			let empty = row.filter((c) => !c.piece)
			if(same.length === 3)
				score += 100
			else if(same.length === 2 && empty.length === 1)
				score += 10
			else if(same.length === 1 && empty.length === 2)
				score +=1
		})
		return score
	}

	minimax(board, currentTurn, playerTurn, depth) {
		let currentOpponent = currentTurn === "X" ? "O" : "X"
		let realOpponent = playerTurn === "X" ? "O" : "X"
		if(board.isGameOver()){
			let playerScore = this.scoreByRows(board,playerTurn)
			let opponentScore = this.scoreByRows(board,realOpponent)
			return  playerScore > opponentScore ? playerScore : -opponentScore
		}

		depth += 1
		let scores = []
		let moves = []

		board.getAvailablePositions().forEach((m) => {
			let b = board.clone()
			b.setPiece(m.x, m.y, currentTurn)
			let res, key = this.cache.generateKeyFromSHA1(b, currentOpponent, playerTurn, depth);
			if(this.cache.exist(key))
				res = this.cache.get(key)
			else
				res = this.cache.set(key, this.minimax(b, currentOpponent, playerTurn, depth))
			scores.push(res)
			moves.push(m)
		})

		// Find min and max score values
		if(currentTurn === playerTurn) {
			let maxScoreIndex = scores.indexOf(_.max(scores))
			this.choice = moves[maxScoreIndex]
			return scores[maxScoreIndex]
		} else {
			let minScoreIndex = scores.indexOf(_.min(scores))
			this.choice = moves[minScoreIndex]
			return scores[minScoreIndex]
		}
	}

	positionExistsInArray(w, x, y) {
		for (var i = 0; i < w.length; i++) {
			if(w[i].x === x && w[i].y === y)
				return true
		}
		return false
	}

	findBlockingMove(board, turn) {
		this.findWinningMove(board, turn)
	}

	getAvailableDirections() {}

}<commit_msg>Lower down minimax's search depth to have a faster response (from 3100ms to 260ms)<commit_after>import Player from './Player'
import _ from 'lodash'
import CacheManager from './CacheManager'

export default class Computer extends Player{

	constructor() {
		super(...arguments)
		this.type = "computer"
		this.cache = new CacheManager({
			enabled: this.options.hasOwnProperty('cacheEnabled') ? this.options.cacheEnabled : true
		})
	}

	onMyTurn(board, turn) {
		process.nextTick(() => {
			this.findMoveInWorker(board, turn, () => {
				this.makeMove(this.choice.x, this.choice.y)
			})
		})
	}

	findMoveInWorker(board, turn, cb) {
		// TODO: Move this into a separate process/worker
		let opponent = turn === "X" ? "O" : "X"
		let w
		this.minimax(board, turn, turn, 2)
		cb()
	}

	findWinningMove(board, turn) { // Try to find two in a row
		let positions = []
		board.traverseRows((row) => {
			let same = row.filter((c) => c.piece === turn)
			if(same.length != board.size - 1)
				return false
			let empty = row.filter((c) => !c.piece)
			if(empty.length == 1)
				positions.push(empty[0])
		})
		return positions
	}

	getMMScore(board, turn, depth) {
		let winner = board.findWinner()
		if(winner === turn) {
			return 10 - (depth || 0)
		}
		else if(winner === (turn === "X" ? "O" : "X")){
			return (depth || 0) - 10
		}
		else {
			return 0
		}
	}

	scoreByRows(board, turn) {
		let score = 0
		board.traverseRows((row) => {
			let same = row.filter((c) => c.piece === turn)
			let empty = row.filter((c) => !c.piece)
			if(same.length === 3)
				score += 100
			else if(same.length === 2 && empty.length === 1)
				score += 10
			else if(same.length === 1 && empty.length === 2)
				score +=1
		})
		return score
	}

	minimax(board, currentTurn, playerTurn, depth) {
		let currentOpponent = currentTurn === "X" ? "O" : "X"
		let realOpponent = playerTurn === "X" ? "O" : "X"
		if(board.isGameOver() || depth === 4){
			let playerScore = this.scoreByRows(board,playerTurn)
			let opponentScore = this.scoreByRows(board,realOpponent)
			return  playerScore > opponentScore ? playerScore : -opponentScore
		}

		depth += 1
		let scores = []
		let moves = []

		board.getAvailablePositions().forEach((m) => {
			let b = board.clone()
			b.setPiece(m.x, m.y, currentTurn)
			let res, key = this.cache.generateKeyFromSHA1(b, currentOpponent, playerTurn, depth);
			if(this.cache.exist(key))
				res = this.cache.get(key)
			else
				res = this.cache.set(key, this.minimax(b, currentOpponent, playerTurn, depth))
			scores.push(res)
			moves.push(m)
		})

		// Find min and max score values
		if(currentTurn === playerTurn) {
			let maxScoreIndex = scores.indexOf(_.max(scores))
			this.choice = moves[maxScoreIndex]
			return scores[maxScoreIndex]
		} else {
			let minScoreIndex = scores.indexOf(_.min(scores))
			this.choice = moves[minScoreIndex]
			return scores[minScoreIndex]
		}
	}

	positionExistsInArray(w, x, y) {
		for (var i = 0; i < w.length; i++) {
			if(w[i].x === x && w[i].y === y)
				return true
		}
		return false
	}

	findBlockingMove(board, turn) {
		this.findWinningMove(board, turn)
	}

	getAvailableDirections() {}

}<|endoftext|>


<commit_before>Template['news'].helpers({
  'stream': function() {
    return Session.get('stream');
  },
});

Template['news'].events({
});

Template['news'].onRendered(function() {
  Meteor.call('getSocialStream', function(error, stream) {
    console.log(stream)
    Session.set('stream', stream);
  });

  var body = document.body,
    timer;

  window.addEventListener('scroll', function() {
    clearTimeout(timer);
    if(!body.classList.contains('disable-hover')) {
      body.classList.add('disable-hover')
    }

    timer = setTimeout(function(){
      body.classList.remove('disable-hover')
    },500);
  }, false);
});

Template['fb_block'].helpers({
  'fbImage': function(id) {
    Meteor.call('getFB', id, function(err, data) {
      $('div[data-fb-id="'+id+'"]').attr("style", 'background-image: url("'+data.source+'");');
    });
  }
});<commit_msg>smaller scroll timeout<commit_after>Template['news'].helpers({
  'stream': function() {
    return Session.get('stream');
  },
});

Template['news'].events({
});

Template['news'].onRendered(function() {
  Meteor.call('getSocialStream', function(error, stream) {
    console.log(stream)
    Session.set('stream', stream);
  });

  var body = document.body,
    timer;

  window.addEventListener('scroll', function() {
    clearTimeout(timer);
    if(!body.classList.contains('disable-hover')) {
      body.classList.add('disable-hover')
    }

    timer = setTimeout(function(){
      body.classList.remove('disable-hover')
    },200);
  }, false);
});

Template['fb_block'].helpers({
  'fbImage': function(id) {
    Meteor.call('getFB', id, function(err, data) {
      $('div[data-fb-id="'+id+'"]').attr("style", 'background-image: url("'+data.source+'");');
    });
  }
});<|endoftext|>


<commit_before>var IEnumerable = function () {
	this.map = function (transform) {
		return new SelectEnumerable(this, transform);
	};

	this.filter = function (filter) {
		return new WhereEnumerable(this, filter);
	};

	this.takeWhile = function (filter) {
		return new TakeWhileEnumerable(this, filter);
	};

	this.skipWhile = function (filter) {
		return new SkipWhileEnumerable(this, filter);
	};

	this.forEach = function (func) {
		try {
			for (; ; ) {
				func(this.next());
			}
		}
		catch (ex) {
			if (!(ex instanceof StopIteration)) {
				throw ex;
			}
		}
	};

	this.toArray = function () {
		var result = [];
		this.forEach(result.push.bind(result));
		return result;
	};
};
var prototype = new IEnumerable();

if (!window.StopIteration) {
	window.StopIteration = function () { };
}

var ArrayEnumerable = function (array) {
	this.reset = function () {
		currentIndex = 0;
		return this;
	};

	this.setUserToken = function (userToken) {
		return this;
	};

	this.next = function () {
		while (currentIndex < array.length) {
			if (currentIndex in array) {
				return array[currentIndex++];
			}
			else {
				++currentIndex;
			}
		}
		throw new StopIteration();
	};

	var currentIndex = 0;
};
ArrayEnumerable.prototype = prototype;

var SelectEnumerable = function (previous, transform) {
	this.reset = function () {
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		return transform(previous.next(), this.userToken);
	};
};
SelectEnumerable.prototype = prototype;

var WhereEnumerable = function (previous, filter) {
	this.reset = function () {
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		var result;
		for (result = previous.next(); result && !filter(result, this.userToken); result = previous.next());
		return result;
	};
};
WhereEnumerable.prototype = prototype;

var TakeWhileEnumerable = function (previous, filter) {
	this.reset = function () {
		foundEnd = false;
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		var result;
		for (result = previous.next(); foundEnd = foundEnd || !filter(result, this.userToken); result = previous.next());
		return result;
	};

	var foundEnd = false;
};
TakeWhileEnumerable.prototype = prototype;

var SkipWhileEnumerable = function (previous, filter) {
	this.reset = function () {
		foundStart = false;
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		var result;
		for (result = previous.next(); !(foundStart = foundStart || !filter(result, this.userToken)); result = previous.next());
		return result;
	};

	var foundStart = false;
};
SkipWhileEnumerable.prototype = prototype;

Array.prototype.toEnumerable = function () {
	return new ArrayEnumerable(this);
};<commit_msg>Fixed how StopIteration is used and its mock implementation to match Mozilla's API and usage.<commit_after>var IEnumerable = function () {
	this.map = function (transform) {
		return new SelectEnumerable(this, transform);
	};

	this.filter = function (filter) {
		return new WhereEnumerable(this, filter);
	};

	this.takeWhile = function (filter) {
		return new TakeWhileEnumerable(this, filter);
	};

	this.skipWhile = function (filter) {
		return new SkipWhileEnumerable(this, filter);
	};

	this.forEach = function (func) {
		try {
			for (; ; ) {
				func(this.next());
			}
		}
		catch (ex) {
			if (!(ex instanceof StopIteration)) {
				throw ex;
			}
		}
	};

	this.toArray = function () {
		var result = [];
		this.forEach(result.push.bind(result));
		return result;
	};
};
var prototype = new IEnumerable();

if (!window.StopIteration) {
	window.StopIteration = function () { };
	window.StopIteration.__proto__ = window.StopIteration;
}

var ArrayEnumerable = function (array) {
	this.reset = function () {
		currentIndex = 0;
		return this;
	};

	this.setUserToken = function (userToken) {
		return this;
	};

	this.next = function () {
		while (currentIndex < array.length) {
			if (currentIndex in array) {
				return array[currentIndex++];
			}
			else {
				++currentIndex;
			}
		}
		throw StopIteration;
	};

	var currentIndex = 0;
};
ArrayEnumerable.prototype = prototype;

var SelectEnumerable = function (previous, transform) {
	this.reset = function () {
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		return transform(previous.next(), this.userToken);
	};
};
SelectEnumerable.prototype = prototype;

var WhereEnumerable = function (previous, filter) {
	this.reset = function () {
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		var result;
		for (result = previous.next(); result && !filter(result, this.userToken); result = previous.next());
		return result;
	};
};
WhereEnumerable.prototype = prototype;

var TakeWhileEnumerable = function (previous, filter) {
	this.reset = function () {
		foundEnd = false;
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		var result;
		for (result = previous.next(); foundEnd = foundEnd || !filter(result, this.userToken); result = previous.next());
		return result;
	};

	var foundEnd = false;
};
TakeWhileEnumerable.prototype = prototype;

var SkipWhileEnumerable = function (previous, filter) {
	this.reset = function () {
		foundStart = false;
		previous.reset();
		return this;
	};

	this.setUserToken = function (userToken) {
		this.userToken = userToken;
		previous.setUserToken(userToken);
		return this;
	};

	this.next = function () {
		var result;
		for (result = previous.next(); !(foundStart = foundStart || !filter(result, this.userToken)); result = previous.next());
		return result;
	};

	var foundStart = false;
};
SkipWhileEnumerable.prototype = prototype;

Array.prototype.toEnumerable = function () {
	return new ArrayEnumerable(this);
};<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = function(fabricatorConfig) {

  "use strict";

  var config = {
    entry: {
      'partystreusel/scripts/p': fabricatorConfig.src.scripts.fabricator
    },
    output: {
      path: path.resolve(__dirname, fabricatorConfig.dest, 'assets'),
      filename: '[name].js'
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /(node_modules|prism\.js)/,
          loaders: ['babel'],
          presets: ['es2015', 'stage-2']
        }
      ]
    },
    plugins: [],
    cache: {}
  };

  if (!fabricatorConfig.dev) {
    config.plugins.push(
      new webpack.optimize.UglifyJsPlugin()
    );
  }

  return config;
};
<commit_msg>lint webpack config for fabricator<commit_after>import path from 'path';
import webpack from 'webpack';

module.exports = (gulpConfig) => {
  const config = {
    entry: {
      'partystreusel/scripts/p': gulpConfig.src.scripts.fabricator,
    },
    output: {
      path: path.resolve(__dirname, gulpConfig.dest, 'assets'),
      filename: '[name].js',
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /(node_modules|prism\.js)/,
          loaders: ['babel'],
          presets: ['es2015', 'stage-2'],
        },
      ],
    },
    plugins: [],
    cache: {},
  };

  if (!gulpConfig.dev) {
    config.plugins.push(
      new webpack.optimize.UglifyJsPlugin()
    );
  }

  return config;
};
<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        // include: ['index.js', 'src', 'example/assets', 'example/src'].map(
        //   name => path.resolve(__dirname, name)
        // ),
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      { test: /\.mdx?$/, use: ['babel-loader', '@mdx-js/loader'] }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: `./index.html`
    })
  ]
};
<commit_msg>remove commented out part of webpack config<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      { test: /\.mdx?$/, use: ['babel-loader', '@mdx-js/loader'] }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: `./index.html`
    })
  ]
};
<|endoftext|>


<commit_before>//webpack --display-reasons
var webpack = require('webpack');
var name = 'grapesjs';

module.exports = {
  entry: './src/main',
  output: {
      filename: './dist/' + name + '.min.js',
      library: name,
      libraryTarget: 'umd',
  },
  plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
      })
  ],
  resolve: {
    modulesDirectories: ['src', 'node_modules'],
    alias: {
      jquery: 'jquery/dist/jquery',
      underscore: 'underscore/underscore',
      backbone: 'backbone/backbone',
      backboneUndo: 'backbone-undo/Backbone.Undo',
      keymaster: 'keymaster/keymaster',
      text: 'requirejs-text/text',
      Spectrum: 'spectrum-colorpicker/spectrum',
      codemirror: 'codemirror',
      formatting: 'codemirror-formatting/formatting',
      PluginManager: 'plugin_manager',
      Abstract: 'domain_abstract',
      Editor: 'editor',
      AssetManager: 'asset_manager',
      BlockManager: 'block_manager',
      TraitManager: 'trait_manager',
      StyleManager: 'style_manager',
      DeviceManager: 'device_manager',
      StorageManager: 'storage_manager',
      PluginManager: 'plugin_manager',
      Navigator: 'navigator',
      DomComponents: 'dom_components',
      RichTextEditor: 'rich_text_editor',
      SelectorManager: 'selector_manager',
      ModalDialog: 'modal_dialog',
      CodeManager: 'code_manager',
      CssComposer: 'css_composer',
      Commands: 'commands',
      Canvas: 'canvas',
      Panels: 'panels',
      Parser: 'parser',
      Utils: 'utils',
    }
  },
  /*
  module: {
    loaders: [
      { test: /underscore/, loader: 'exports?_' },
      { test: /backbone/, loader: 'exports?Backbone!imports?underscore,jquery' },
      { test: /rte/, loader: 'exports?rte!imports?jquery' },
      { test: /backbone-undo/, loader: 'exports?backboneUndo!imports?backbone' },
      { test: /keymaster/, loader: 'exports?keymaster' },
    ]
  }*/
}

/*
amd: { jQuery: true }
var webpack = require('webpack');
var pkg = require('./package.json');
var name = 'grapesjs-plugin-ckeditor';
var env = process.env.WEBPACK_ENV;
var plugins = [];

plugins: [
  new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]), // saves ~100k from build
  new webpack.optimize.UglifyJsPlugin({minimize: true}),
  new webpack.BannerPlugin(pkg.name + ' - ' + pkg.version),
  new webpack.DefinePlugin({'process.env.NODE_ENV': '"production"'})
]

module.exports = {
  entry: './src/main',
  output: {
      filename: './dist/' + name + '.min.js',
      library: name,
      libraryTarget: 'umd',
  },
  module: {
    preLoaders: [
        { test: /\.json$/, loader: 'json'},
    ],
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        include: /src/,
        query: {
          presets: ['es2015']
        }
      },
    ],
  },
  plugins: plugins
};
 */
<commit_msg>Update webpack file<commit_after>//webpack --display-reasons
var webpack = require('webpack');
var pkg = require('./package.json');
var env = process.env.WEBPACK_ENV;
var name = 'grapesjs';
var plugins = [];

if(env !== 'dev'){
  plugins = [
    new webpack.optimize.UglifyJsPlugin({minimize: true}),
    new webpack.BannerPlugin(pkg.name + ' - ' + pkg.version)
  ]
}

plugins.push(new webpack.ProvidePlugin({$: 'jquery'}));
module.exports = {
  entry: './src/main',
  output: {
      filename: './dist/' + name + '.min.js',
      library: name,
      libraryTarget: 'umd',
  },
  plugins: plugins,
  resolve: {
    modulesDirectories: ['src', 'node_modules'],
    alias: {
      jquery: 'jquery/dist/jquery',
      underscore: 'underscore/underscore',
      backbone: 'backbone/backbone',
      backboneUndo: 'backbone-undo/Backbone.Undo',
      keymaster: 'keymaster/keymaster',
      text: 'requirejs-text/text',
      Spectrum: 'spectrum-colorpicker/spectrum',
      codemirror: 'codemirror',
      formatting: 'codemirror-formatting/formatting',
      PluginManager: 'plugin_manager',
      Abstract: 'domain_abstract',
      Editor: 'editor',
      AssetManager: 'asset_manager',
      BlockManager: 'block_manager',
      TraitManager: 'trait_manager',
      StyleManager: 'style_manager',
      DeviceManager: 'device_manager',
      StorageManager: 'storage_manager',
      PluginManager: 'plugin_manager',
      Navigator: 'navigator',
      DomComponents: 'dom_components',
      RichTextEditor: 'rich_text_editor',
      SelectorManager: 'selector_manager',
      ModalDialog: 'modal_dialog',
      CodeManager: 'code_manager',
      CssComposer: 'css_composer',
      Commands: 'commands',
      Canvas: 'canvas',
      Panels: 'panels',
      Parser: 'parser',
      Utils: 'utils',
    }
  },
}
<|endoftext|>


<commit_before>// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.provide('goog.async.run');

goog.require('goog.async.nextTick');
goog.require('goog.async.throwException');
goog.require('goog.testing.watchers');

/**
 * Fires the provided callback just before the current callstack unwinds, or as
 * soon as possible after the current JS execution context.
 * @param {function(this:THIS)} callback
 * @param {THIS=} opt_context Object to use as the "this value" when calling
 *     the provided function.
 * @template THIS
 */
goog.async.run = function(callback, opt_context) {
  if (!goog.async.run.schedule_) {
    goog.async.run.initializeRunner_();
  }
  if (!goog.async.run.workQueueScheduled_) {
    // Nothing is currently scheduled, schedule it now.
    goog.async.run.schedule_();
    goog.async.run.workQueueScheduled_ = true;
  }

  goog.async.run.workQueue_.push(
      new goog.async.run.WorkItem_(callback, opt_context));
};

/**
 * Initializes the function to use to process the work queue.
 * @private
 */
goog.async.run.initializeRunner_ = function() {
  goog.async.run.schedule_ = function() {
    goog.async.nextTick(goog.async.run.processWorkQueue);
  };
};

/**
 * Forces goog.async.run to use nextTick instead of Promise.
 *
 * This should only be done in unit tests. It's useful because MockClock
 * replaces nextTick, but not the browser Promise implementation, so it allows
 * Promise-based code to be tested with MockClock.
 */
goog.async.run.forceNextTick = function() {
  goog.async.run.schedule_ = function() {
    goog.async.nextTick(goog.async.run.processWorkQueue);
  };
};

/**
 * The function used to schedule work asynchronousely.
 * @private {function()}
 */
goog.async.run.schedule_;

/** @private {boolean} */
goog.async.run.workQueueScheduled_ = false;

/** @private {!Array<!goog.async.run.WorkItem_>} */
goog.async.run.workQueue_ = [];

if (goog.DEBUG) {
  /**
   * Reset the event queue.
   * @private
   */
  goog.async.run.resetQueue_ = function() {
    goog.async.run.workQueueScheduled_ = false;
    goog.async.run.workQueue_ = [];
  };

  // If there is a clock implemenation in use for testing
  // and it is reset, reset the queue.
  goog.testing.watchers.watchClockReset(goog.async.run.resetQueue_);
}

/**
 * Run any pending goog.async.run work items. This function is not intended
 * for general use, but for use by entry point handlers to run items ahead of
 * goog.async.nextTick.
 */
goog.async.run.processWorkQueue = function() {
  // NOTE: additional work queue items may be pushed while processing.
  while (goog.async.run.workQueue_.length) {
    // Don't let the work queue grow indefinitely.
    var workItems = goog.async.run.workQueue_;
    goog.async.run.workQueue_ = [];
    for (var i = 0; i < workItems.length; i++) {
      var workItem = workItems[i];
      try {
        workItem.fn.call(workItem.scope);
      } catch (e) {
        goog.async.throwException(e);
      }
    }
  }

  // There are no more work items, reset the work queue.
  goog.async.run.workQueueScheduled_ = false;
};

/**
 * @constructor
 * @final
 * @struct
 * @private
 *
 * @param {function()} fn
 * @param {Object|null|undefined} scope
 */
goog.async.run.WorkItem_ = function(fn, scope) {
  /** @const */ this.fn = fn;
  /** @const */ this.scope = scope;
};
<commit_msg>Not catch error in goog.async.run<commit_after>// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.provide('goog.async.run');

goog.require('goog.async.nextTick');
goog.require('goog.testing.watchers');

/**
 * Fires the provided callback just before the current callstack unwinds, or as
 * soon as possible after the current JS execution context.
 * @param {function(this:THIS)} callback
 * @param {THIS=} opt_context Object to use as the "this value" when calling
 *     the provided function.
 * @template THIS
 */
goog.async.run = function(callback, opt_context) {
  if (!goog.async.run.schedule_) {
    goog.async.run.initializeRunner_();
  }
  if (!goog.async.run.workQueueScheduled_) {
    // Nothing is currently scheduled, schedule it now.
    goog.async.run.schedule_();
    goog.async.run.workQueueScheduled_ = true;
  }

  goog.async.run.workQueue_.push(
      new goog.async.run.WorkItem_(callback, opt_context));
};

/**
 * Initializes the function to use to process the work queue.
 * @private
 */
goog.async.run.initializeRunner_ = function() {
  goog.async.run.schedule_ = function() {
    goog.async.nextTick(goog.async.run.processWorkQueue);
  };
};

/**
 * Forces goog.async.run to use nextTick instead of Promise.
 *
 * This should only be done in unit tests. It's useful because MockClock
 * replaces nextTick, but not the browser Promise implementation, so it allows
 * Promise-based code to be tested with MockClock.
 */
goog.async.run.forceNextTick = function() {
  goog.async.run.schedule_ = function() {
    goog.async.nextTick(goog.async.run.processWorkQueue);
  };
};

/**
 * The function used to schedule work asynchronousely.
 * @private {function()}
 */
goog.async.run.schedule_;

/** @private {boolean} */
goog.async.run.workQueueScheduled_ = false;

/** @private {!Array<!goog.async.run.WorkItem_>} */
goog.async.run.workQueue_ = [];

if (goog.DEBUG) {
  /**
   * Reset the event queue.
   * @private
   */
  goog.async.run.resetQueue_ = function() {
    goog.async.run.workQueueScheduled_ = false;
    goog.async.run.workQueue_ = [];
  };

  // If there is a clock implemenation in use for testing
  // and it is reset, reset the queue.
  goog.testing.watchers.watchClockReset(goog.async.run.resetQueue_);
}

/**
 * Run any pending goog.async.run work items. This function is not intended
 * for general use, but for use by entry point handlers to run items ahead of
 * goog.async.nextTick.
 */
goog.async.run.processWorkQueue = function() {
  // NOTE: additional work queue items may be pushed while processing.
  while (goog.async.run.workQueue_.length) {
    // Don't let the work queue grow indefinitely.
    var workItems = goog.async.run.workQueue_;
    goog.async.run.workQueue_ = [];
    for (var i = 0; i < workItems.length; i++) {
      var workItem = workItems[i];
      workItem.fn.call(workItem.scope);
    }
  }

  // There are no more work items, reset the work queue.
  goog.async.run.workQueueScheduled_ = false;
};

/**
 * @constructor
 * @final
 * @struct
 * @private
 *
 * @param {function()} fn
 * @param {Object|null|undefined} scope
 */
goog.async.run.WorkItem_ = function(fn, scope) {
  /** @const */ this.fn = fn;
  /** @const */ this.scope = scope;
};
<|endoftext|>


<commit_before>const autoprefixer = require('autoprefixer')

module.exports = {
  siteMetadata: {
    title: 'Scranton Hacks 2017',
    description: '',
    url: 'http://scrantonhacks.com',
    hackathonDate: 'Date: TBA',
    hackYear: '2017',
    sponsorEmail: 'sponsorship@scrantonhacks.com',
    hackathonLocation: 'University of Scranton Byron',
    //Name will translate to the 'icon' of this element.
    //Make sure to follow font-awesome documentation on what icons are what names.
    social: [
      {
        name: 'facebook',
        size: '2x',
        link: 'https://www.facebook.com/groups/397712937282963/'
      },
      {
        name: 'twitter',
        size: '2x',
        link: 'https://twitter.com/ScrantonHacks'
      },
      {
        name: 'instagram',
        size: '2x',
        link: 'https://www.instagram.com/scranton_hacks/'
      }
    ],
    landingContent: {
      about: "ScrantonHacks is a 24 Hour hackathon at the University of Scranton. We bring together students, regardless of background, to inspire and develop creative solutions to today's problems.",
      motto: {
        build: "We believe in using our technical skill to build world-class solutions to the problems facing society today.",
        connect: "Connect with the other leaders in your field - expand your perspectives, broaden your horizons, and build lasting networks.",
        learn: "We exist to the complement the knowledge and empower todays up-and-coming hackers.",
      },
      questions: [
         {
              q: "This is a question.",
              a: "This is an answer.",
         },
         {
             q: "Another question.",
             a: "Another answer.",
         },
      ],
      team: [
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Andrew Plaza',
          title: 'Benevolent Dictator for Life',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'John Prendergast',
          title: 'Designated Director of Festivities',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Regita Handijaya',
          title: 'Criminal Mastermind',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Alex Thoennes',
          title: 'Observer of all Things',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Peter Zabiegala',
          title: 'Ruthless Corporate Director',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Clarence Gallagher',
          title: 'Dark Master of All',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Sean Batzel',
          title: 'Website Defacer',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Brian Dauer',
          title: 'Supervillain Extraordinaire',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Liam O\'Hare',
          title: 'Master Evil Genius',
        },
      ],
      //logos and stuff go here
      //tier 1: largest
      //tier 2: medium
      //tier 3: small
      //order does not matter
      //examples below
      sponsors: [
        { // Facebook
          logo: "", // path of the logo
          tier: 1,
        },
        /*
        { // Google
          logo: "/sponsors/google.png",
          tier: 2,
        },
        { // Baidu
          logo: "/sponsors/baidu.png",
          tier: 3,
        },
        {
          logo: "/sponsors/Vanguard-Logo.jpg",
          tier: 1,
        },
        {
          logo: "/sponsors/android.png",
          tier: 3,
        },
        {
          logo: "/sponsors/apple.png",
          tier: 2,
        },
        {
          logo: "/sponsors/redhat.png",
          tier: 3,
        }, */
      ],
      partners: [
        {
          logo: '',
        },
        /*
        {
          logo: "/sponsors/mlh.svg",
        }
        */
      ],
    },
  },
  pathPrefix: '/',
  plugins: [
    {
      resolve: 'custom-sass-loader',
      options: {
        postCssPlugins: [
          autoprefixer({
            browsers: ['last 2 versions'],
          })
        ]
      }
    },
    `gatsby-plugin-styled-components`,
    'gatsby-plugin-react-helmet'
  ],
}
<commit_msg>small change to copy<commit_after>const autoprefixer = require('autoprefixer')

module.exports = {
  siteMetadata: {
    title: 'Scranton Hacks 2017',
    description: '',
    url: 'http://scrantonhacks.com',
    hackathonDate: 'Date: TBA',
    hackYear: '2017',
    sponsorEmail: 'sponsorship@scrantonhacks.com',
    hackathonLocation: 'University of Scranton Byron',
    //Name will translate to the 'icon' of this element.
    //Make sure to follow font-awesome documentation on what icons are what names.
    social: [
      {
        name: 'facebook',
        size: '2x',
        link: 'https://www.facebook.com/groups/397712937282963/'
      },
      {
        name: 'twitter',
        size: '2x',
        link: 'https://twitter.com/ScrantonHacks'
      },
      {
        name: 'instagram',
        size: '2x',
        link: 'https://www.instagram.com/scranton_hacks/'
      }
    ],
    landingContent: {
      about: "ScrantonHacks is a 24 Hour hackathon at the University of Scranton. We bring together students, regardless of background, to inspire and develop creative solutions to today's problems.",
      motto: {
        build: "We believe in using our technical skill to build world-class solutions to contemporary problems facing society today.",
        connect: "Connect with the other leaders in your field - expand your perspectives, broaden your horizons, and build lasting networks.",
        learn: "We exist to the the knowledge and empower todays up-and-coming hackers.",
      },
      questions: [
         {
              q: "This is a question.",
              a: "This is an answer.",
         },
         {
             q: "Another question.",
             a: "Another answer.",
         },
      ],
      team: [
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Andrew Plaza',
          title: 'Benevolent Dictator for Life',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'John Prendergast',
          title: 'Designated Director of Festivities',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Regita Handijaya',
          title: 'Criminal Mastermind',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Alex Thoennes',
          title: 'Observer of all Things',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Peter Zabiegala',
          title: 'Ruthless Corporate Director',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Clarence Gallagher',
          title: 'Dark Master of All',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Sean Batzel',
          title: 'Website Defacer',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Brian Dauer',
          title: 'Supervillain Extraordinaire',
        },
        {
          image: '/headshots/andrew_plaza.jpeg',
          name: 'Liam O\'Hare',
          title: 'Master Evil Genius',
        },
      ],
      //logos and stuff go here
      //tier 1: largest
      //tier 2: medium
      //tier 3: small
      //order does not matter
      //examples below
      sponsors: [
        { // Facebook
          logo: "", // path of the logo
          tier: 1,
        },
        /*
        { // Google
          logo: "/sponsors/google.png",
          tier: 2,
        },
        { // Baidu
          logo: "/sponsors/baidu.png",
          tier: 3,
        },
        {
          logo: "/sponsors/Vanguard-Logo.jpg",
          tier: 1,
        },
        {
          logo: "/sponsors/android.png",
          tier: 3,
        },
        {
          logo: "/sponsors/apple.png",
          tier: 2,
        },
        {
          logo: "/sponsors/redhat.png",
          tier: 3,
        }, */
      ],
      partners: [
        {
          logo: '',
        },
        /*
        {
          logo: "/sponsors/mlh.svg",
        }
        */
      ],
    },
  },
  pathPrefix: '/',
  plugins: [
    {
      resolve: 'custom-sass-loader',
      options: {
        postCssPlugins: [
          autoprefixer({
            browsers: ['last 2 versions'],
          })
        ]
      }
    },
    `gatsby-plugin-styled-components`,
    'gatsby-plugin-react-helmet'
  ],
}
<|endoftext|>


<commit_before>/* eslint-disable no-var */
var _ = require('lodash')
var overrides = {}
try { overrides = require('./truffle-overrides') } catch (e) {}

const defaults = {
  rpc: {
    gas: 4712388
  },
  networks: {
    production: {
      network_id: 1, // Ethereum public network
      host: 'localhost',
      port: 9999,
      ethercampApiSubdomain: 'state'
    },
    morden: {
      network_id: 2, // morden
      host: 'localhost',
      port: 8888,
      ethercampApiSubdomain: 'morden-state'
    },
    test: {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf',
      ethercampApiSubdomain: 'not-really'
    },
    development: {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf'
    }
  },
  mocha: {
    useColors: true
  }
}

var config = _.defaultsDeep(overrides, defaults)
module.exports = config
<commit_msg>restore lower gas limit, got "Exceeds block gas limit"<commit_after>/* eslint-disable no-var */
var _ = require('lodash')
var overrides = {}
try { overrides = require('./truffle-overrides') } catch (e) {}

const defaults = {
  rpc: {
    gas: 3141592  // default = 4712388
  },
  networks: {
    production: {
      network_id: 1, // Ethereum public network
      host: 'localhost',
      port: 9999,
      ethercampApiSubdomain: 'state'
    },
    morden: {
      network_id: 2, // morden
      host: 'localhost',
      port: 8888,
      ethercampApiSubdomain: 'morden-state'
    },
    test: {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf',
      ethercampApiSubdomain: 'not-really'
    },
    development: {
      network_id: 'default',
      host: 'localhost',
      port: 7777,
      from: '0x7e5f4552091a69125d5dfcb7b8c2659029395bdf'
    }
  },
  mocha: {
    useColors: true
  }
}

var config = _.defaultsDeep(overrides, defaults)
module.exports = config
<|endoftext|>


<commit_before>'use strict';

// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   * Should be an empty object if it's generating a test build
   * Karma will set this when it's a test build
   */
  config.entry = isTest ? void 0 : {
    app: './src/app/app.js'
  };

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   * Should be an empty object if it's generating a test build
   * Karma will handle setting it up for you when it's a test build
   */
  config.output = isTest ? {} : {
    // Absolute output directory
    path: __dirname + '/dist',

    // Output path from the view of the page
    // Uses webpack-dev-server in development
    publicPath: isProd ? '/' : 'http://localhost:8080/',

    // Filename for entry points
    // Only adds hash in build mode
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

    // Filename for non-entry points
    // Only adds hash in build mode
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else if (isProd) {
    config.devtool = 'source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */

  // Initialize module
  config.module = {
    rules: [{
      // JS LOADER
      // Reference: https://github.com/babel/babel-loader
      // Transpile .js files using babel-loader
      // Compiles ES6 and ES7 into ES5 code
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    }, {
      // CSS LOADER
      // Reference: https://github.com/webpack/css-loader
      // Allow loading css through js
      //
      // Reference: https://github.com/postcss/postcss-loader
      // Postprocess your css with PostCSS plugins
      test: /\.css$/,
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files in production builds
      //
      // Reference: https://github.com/webpack/style-loader
      // Use style-loader in development.

      loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({
        fallbackLoader: 'style-loader',
        loader: [
          {loader: 'css-loader', query: {sourceMap: true}},
          {loader: 'postcss-loader'}
        ],
      })
    }, {
      // ASSET LOADER
      // Reference: https://github.com/webpack/file-loader
      // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
      // Rename the file using the asset hash
      // Pass along the updated reference to your code
      // You can add here any file extension you want to get copied to your output
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file-loader'
    }, {
      // HTML LOADER
      // Reference: https://github.com/webpack/raw-loader
      // Allow loading html through js
      test: /\.html$/,
      loader: 'raw-loader'
    }]
  };

  // ISTANBUL LOADER
  // https://github.com/deepsweet/istanbul-instrumenter-loader
  // Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
  // Skips node_modules and files that end with .spec.js
  if (isTest) {
    config.module.rules.push({
      enforce: 'pre',
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /\.spec\.js$/
      ],
      loader: 'istanbul-instrumenter-loader',
      query: {
        esModules: true
      }
    })
  }

  /**
   * PostCSS
   * Reference: https://github.com/postcss/autoprefixer-core
   * Add vendor prefixes to your css
   */
   // NOTE: This is now handled in the `postcss.config.js`
   //       webpack2 has some issues, making the config file necessary

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
    new webpack.LoaderOptionsPlugin({
      test: /\.scss$/i,
      options: {
        postcss: {
          plugins: [autoprefixer]
        }
      }
    })
  ];

  // Skip rendering index.html in test mode
  if (!isTest) {
    // Reference: https://github.com/ampedandwired/html-webpack-plugin
    // Render index.html
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: './src/public/index.html',
        inject: 'body'
      }),

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin({filename: 'css/[name].css', disable: !isProd, allChunks: true})
    )
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin(),

      // Copy assets from the public folder
      // Reference: https://github.com/kevlened/copy-webpack-plugin
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }])
    )
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    stats: 'minimal'
  };

  return config;
}();
<commit_msg>Fixes Webpack not wanting to load or show files<commit_after>'use strict';

// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   * Should be an empty object if it's generating a test build
   * Karma will set this when it's a test build
   */
  config.entry = isTest ? void 0 : {
    app: './src/app/app.js'
  };

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   * Should be an empty object if it's generating a test build
   * Karma will handle setting it up for you when it's a test build
   */
  config.output = isTest ? {} : {
    // Absolute output directory
    path: __dirname + '/dist',

    // Output path from the view of the page
    // Uses webpack-dev-server in development
    publicPath: isProd ? '/' : 'http://0.0.0.0:8080/',

    // Filename for entry points
    // Only adds hash in build mode
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

    // Filename for non-entry points
    // Only adds hash in build mode
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else if (isProd) {
    config.devtool = 'source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */

  // Initialize module
  config.module = {
    rules: [{
      // JS LOADER
      // Reference: https://github.com/babel/babel-loader
      // Transpile .js files using babel-loader
      // Compiles ES6 and ES7 into ES5 code
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    }, {
      // CSS LOADER
      // Reference: https://github.com/webpack/css-loader
      // Allow loading css through js
      //
      // Reference: https://github.com/postcss/postcss-loader
      // Postprocess your css with PostCSS plugins
      test: /\.css$/,
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files in production builds
      //
      // Reference: https://github.com/webpack/style-loader
      // Use style-loader in development.

      loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({
        fallbackLoader: 'style-loader',
        loader: [
          {loader: 'css-loader', query: {sourceMap: true}},
          {loader: 'postcss-loader'}
        ],
      })
    }, {
      // ASSET LOADER
      // Reference: https://github.com/webpack/file-loader
      // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
      // Rename the file using the asset hash
      // Pass along the updated reference to your code
      // You can add here any file extension you want to get copied to your output
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file-loader'
    }, {
      // HTML LOADER
      // Reference: https://github.com/webpack/raw-loader
      // Allow loading html through js
      test: /\.html$/,
      loader: 'raw-loader'
    }]
  };

  // ISTANBUL LOADER
  // https://github.com/deepsweet/istanbul-instrumenter-loader
  // Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
  // Skips node_modules and files that end with .spec.js
  if (isTest) {
    config.module.rules.push({
      enforce: 'pre',
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /\.spec\.js$/
      ],
      loader: 'istanbul-instrumenter-loader',
      query: {
        esModules: true
      }
    })
  }

  /**
   * PostCSS
   * Reference: https://github.com/postcss/autoprefixer-core
   * Add vendor prefixes to your css
   */
   // NOTE: This is now handled in the `postcss.config.js`
   //       webpack2 has some issues, making the config file necessary

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
    new webpack.LoaderOptionsPlugin({
      test: /\.scss$/i,
      options: {
        postcss: {
          plugins: [autoprefixer]
        }
      }
    })
  ];

  // Skip rendering index.html in test mode
  if (!isTest) {
    // Reference: https://github.com/ampedandwired/html-webpack-plugin
    // Render index.html
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: './src/public/index.html',
        inject: 'body'
      }),

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin({filename: 'css/[name].css', disable: !isProd, allChunks: true})
    )
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin(),

      // Copy assets from the public folder
      // Reference: https://github.com/kevlened/copy-webpack-plugin
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }])
    )
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    stats: 'minimal'
  };

  return config;
}();
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Dan "Ducky" Little
 *
 * 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.
 */

/** This is used to define a *vector* layer source,
 *  it does *not* link this to a data source.
 *
 */

import { transformProperties, joinUrl, requEstimator } from '../../../util';

import GML2Format from 'ol/format/GML2';
import GeoJSONFormat from 'ol/format/GeoJSON';
import EsriJsonFormat from 'ol/format/EsriJSON';
import { tile, bbox } from 'ol/loadingstrategy';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { createXYZ } from 'ol/tilegrid';
import {getEditStyle} from './edit';
import {EDIT_LAYER_NAME} from '../../../defaults';

// WARNING! This is a monkey patch in order to
// allow rendering labels outside of a polygon's
// area. The default behaviour for this is to limit the
// label to insde the polygon.
import Text from 'ol/style/Text';
import {applyStyle as applyStyleFunction} from 'ol-mapbox-style';
import {latest as spec} from '@mapbox/mapbox-gl-style-spec';

// for JSONP support
import request from 'reqwest';

Text.prototype.getOverflow = () => {
    return true;
};

/** Create the parameters for a Vector layer.
 *
 */
function defineSource(mapSource) {
    if(mapSource.type === 'wfs') {
        // add a wfs type source
        let format = GML2Format;
        let output_format = 'text/xml; subtype=gml/2.1.2';

        if(mapSource.params.outputFormat) {
            output_format = mapSource.params.outputFormat;
        }

        if(output_format.toLowerCase().indexOf('json') >= 0) {
            format = GeoJSONFormat;
        }

        return {
            format: new format({}),
            projection: 'EPSG:4326',
            url: function(extent) {
                if(typeof(mapSource.params.typename) === 'undefined') {
                    console.error('No "typename" param defined for a WFS layer. This will fail.');
                }

                const url_params = Object.assign({}, {
                    'srsname': 'EPSG:3857',
                    'outputFormat': output_format,
                    'service': 'WFS',
                    'version': '1.1.0',
                    'request': 'GetFeature',
                    'bbox': extent.concat('EPSG:3857').join(',')
                }, mapSource.params);

                return joinUrl(mapSource.urls[0], url_params);
            },
            strategy: bbox
        };
    } else if(mapSource.type === 'geojson') {
        return {
            format: new GeoJSONFormat(),
            projection: mapSource.params.crs ? mapSource.params.crs : 'EPSG:4326',
            url: mapSource.urls[0],
        };
    } else if(mapSource.type === 'ags-vector') {
        // Add an A**GIS FeatureService layer.
        // This performs a basic query based on the bounding box.
        return {
            loader: function(extent, resolution, proj) {
                const url = mapSource.urls[0] + '/query/';

                // the E**I language can get a bit complicated but
                //  this is the format for a basic BBOX query.
                const params = Object.assign({}, {
                    f: 'json',
                    returnGeometry: 'true',
                    spatialRel: 'esriSpatialRelIntersects',
                    geometry: JSON.stringify({
                        xmin: extent[0], ymin: extent[1],
                        xmax: extent[2], ymax: extent[3],
                    }),
                    spatialReference: JSON.stringify({
                        wkid: 102100
                    }),
                    geometryType: 'esriGeometryEnvelope',
                    inSR: 102100, outSR: 102100,
                    outFields: '*',
                    returnIdsOnly: true,
                }, mapSource.params);

                // use JSONP to fetch the features.
                request({
                    url: url,
                    data: params,
                    type: 'jsonp',
                    success: (response) => {
                        if(response.error) {
                            console.error('Error loading object IDs for ' + mapSource.label);
                        } else {
                            const esri_format = new EsriJsonFormat();

                            const object_ids = response.objectIds;
                            if(object_ids !== null) {
                                // E**I FeatureServer appears to have a limitation of
                                // roughly 2048 bytes past the "?" in the GET call.
                                //  this ensure that the batches are small enough to prevent
                                //  404 errors.
                                const n_objects = object_ids.length;

                                // dummy "request" that can be used to estimate the
                                //  overall length of the query.
                                const sniff_r = Object.assign({}, params, {
                                    returnIdsOnly: false
                                });

                                // the ID's need to get "batched" into groups
                                //  which will reliably be shorter than the
                                //  maximum request length.
                                const batches = [];

                                // current batch is "rotated" whenever it gets too long
                                let current_batch = [];
                                for(let i = 0; i < n_objects; i++) {
                                    // estimate the request size
                                    const requestimate = requEstimator(Object.assign(sniff_r, {
                                        objectIds: current_batch.concat([object_ids[i]]).join(',')
                                    }));
                                    // if it's too long "rotate" the batches.
                                    if(requestimate > 2000) {
                                        batches.push(current_batch.slice());
                                        current_batch = [];
                                    }
                                    current_batch.push(object_ids[i]);
                                }
                                // ensure the remainder gets pushed to a batch
                                if(current_batch.length > 0) {
                                    batches.push(current_batch);
                                }

                                // make the feature requests based on the batches.
                                for(const batch of batches) {
                                    request({
                                        url: url,
                                        data: Object.assign({}, params, {
                                            returnIdsOnly: false,
                                            objectIds: batch.join(','),
                                        }),
                                        type: 'jsonp',
                                        success: (response) => {
                                            if(response.error) {
                                                console.error('Error loading feature batch for ' + mapSource.label);
                                            } else {
                                                this.addFeatures(esri_format.readFeatures(response, {
                                                    // featureProjection: proj,
                                                }));
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    },
                    error: (response) => {
                        console.error(response)
                    }
                });
            },
            strategy: tile(createXYZ({
                tileSize: 512
            }))
        }
    }
    // empty object
    return {}
}

/** Return a style function for the layer.
 *
 */
export function applyStyle(vectorLayer, mapSource, mapTool) {
    // if this is a special-case layer, handle it.
    if (mapSource.name === EDIT_LAYER_NAME) {
        const renderPoints = (mapTool === 'Modify' || mapTool === '_Modify');
        vectorLayer.setStyle(getEditStyle(mapSource.layers[0].style, renderPoints));
        return;
    }

    const layers = [];
    for(const layer of mapSource.layers) {
        if(layer.on === true) {
            // check for the different types of mapbox-gl layers
            //  GeoMoose lets the user define all the properties at once!
            const order = ['fill', 'line', 'circle', 'symbol'];

            for (let o = 0, oo = order.length; o < oo; o++) {
                const glLayerType = order[o];
                let filterFn = n => (n.indexOf(glLayerType) === 0);
                if (glLayerType === 'symbol') {
                    filterFn = n => (
                        n.indexOf('symbol') === 0 ||
                        n.indexOf('text') === 0
                    );
                }
                const validKeys = Object.keys(layer.style)
                    .filter(filterFn);
                if (validKeys.length > 0) {
                    const layer_def = {
                        id: `${layer.name}-${glLayerType}`,
                        type: glLayerType,
                        // source is a contant that is used to dummy up
                        //  the Mapbox styles
                        source: 'dummy-source',
                        paint: {},
                        layout: {},
                    };

                    // TODO: if updates are slow then this likely needs
                    //  optimized with real for loops.
                    ['paint', 'layout'].forEach(section => {
                        Object.keys(spec[`${section}_${glLayerType}`])
                            .forEach(key => {
                                if (layer.style[key]) {
                                    layer_def[section][key] = layer.style[key];
                                }
                            });
                    });

                    // check to see if there is a filter
                    //  set on the layer.  This uses the Mapbox GL/JS
                    //  filters.
                    if(layer.filter !== undefined) {
                        layer_def.filter = layer.filter;
                    }

                    layers.push(layer_def);
                }
            }
        }
    }

    applyStyleFunction(vectorLayer, {
        'version': 8,
        'layers': layers,
        'sources': {
            'dummy-source': {
                'type': 'vector'
            }
        },
    }, 'dummy-source');
}

/** Return an OpenLayers Layer for the Vector source.
 *
 *  @param mapSource The MapSource definition from the store.
 *
 *  @returns OpenLayers Layer instance.
 */
export function createLayer(mapSource) {
    const source = new VectorSource(defineSource(mapSource));

    // get the transforms for the layer
    if(mapSource.transforms) {
        source.on('addfeature', function(evt) {
            const f = evt.feature;
            f.setProperties(transformProperties(mapSource.transforms, f.getProperties()));
        });
    }

    const opts = {
        source,
        minResolution: mapSource.minresolution,
        maxResolution: mapSource.maxresolution,
        declutter: true
    };
    const vector_layer = new VectorLayer(opts);
    applyStyle(vector_layer, mapSource);

    return vector_layer;
}

/** Ensure that the Vector parameters all match.
 */
export function updateLayer(map, layer, mapSource, mapTool) {
    if(mapSource.type === 'vector') {
        // vector layer features are defined by what
        // is stored in mapSource.features
        const layer_version = layer.get('featuresVersion');
        // check to see if there was an update to the features
        if(layer_version !== mapSource.featuresVersion) {
            // this is a bit heavy-handed strategy.
            const source = layer.getSource();
            // clear the layer without setting off events.
            source.clear(true);
            // setup the JSON parser
            const output_format = new GeoJSONFormat();
            // bring in the new features.
            const features = output_format.readFeatures({
                type: 'FeatureCollection', features: mapSource.features
            });
            source.addFeatures(features);

            // update the version number
            layer.set('featuresVersion', mapSource.featuresVersion);
        }
    } else {
        const layer_version = layer.get('featuresVersion');
        // check to see if there was an update to the features
        if(layer_version !== mapSource.featuresVersion) {
            layer.set('featuresVersion', mapSource.featuresVersion);
            // refresh is available to all vector layers,
            //  this should force a reload of the features from the server
            //  upon update.
            layer.getSource().refresh();
        }
    }

    // update the style effectively turns "layers"
    // on and off on vector layers.
    applyStyle(layer, mapSource, mapTool);
}
<commit_msg>Remove forced declutter and move it to source config.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Dan "Ducky" Little
 *
 * 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.
 */

/** This is used to define a *vector* layer source,
 *  it does *not* link this to a data source.
 *
 */

import { parseBoolean, transformProperties, joinUrl, requEstimator } from '../../../util';

import GML2Format from 'ol/format/GML2';
import GeoJSONFormat from 'ol/format/GeoJSON';
import EsriJsonFormat from 'ol/format/EsriJSON';
import { tile, bbox } from 'ol/loadingstrategy';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { createXYZ } from 'ol/tilegrid';
import {getEditStyle} from './edit';
import {EDIT_LAYER_NAME} from '../../../defaults';

// WARNING! This is a monkey patch in order to
// allow rendering labels outside of a polygon's
// area. The default behaviour for this is to limit the
// label to insde the polygon.
import Text from 'ol/style/Text';
import {applyStyle as applyStyleFunction} from 'ol-mapbox-style';
import {latest as spec} from '@mapbox/mapbox-gl-style-spec';

// for JSONP support
import request from 'reqwest';

Text.prototype.getOverflow = () => {
    return true;
};

/** Create the parameters for a Vector layer.
 *
 */
function defineSource(mapSource) {
    if(mapSource.type === 'wfs') {
        // add a wfs type source
        let format = GML2Format;
        let output_format = 'text/xml; subtype=gml/2.1.2';

        if(mapSource.params.outputFormat) {
            output_format = mapSource.params.outputFormat;
        }

        if(output_format.toLowerCase().indexOf('json') >= 0) {
            format = GeoJSONFormat;
        }

        return {
            format: new format({}),
            projection: 'EPSG:4326',
            url: function(extent) {
                if(typeof(mapSource.params.typename) === 'undefined') {
                    console.error('No "typename" param defined for a WFS layer. This will fail.');
                }

                const url_params = Object.assign({}, {
                    'srsname': 'EPSG:3857',
                    'outputFormat': output_format,
                    'service': 'WFS',
                    'version': '1.1.0',
                    'request': 'GetFeature',
                    'bbox': extent.concat('EPSG:3857').join(',')
                }, mapSource.params);

                return joinUrl(mapSource.urls[0], url_params);
            },
            strategy: bbox
        };
    } else if(mapSource.type === 'geojson') {
        return {
            format: new GeoJSONFormat(),
            projection: mapSource.params.crs ? mapSource.params.crs : 'EPSG:4326',
            url: mapSource.urls[0],
        };
    } else if(mapSource.type === 'ags-vector') {
        // Add an A**GIS FeatureService layer.
        // This performs a basic query based on the bounding box.
        return {
            loader: function(extent, resolution, proj) {
                const url = mapSource.urls[0] + '/query/';

                // the E**I language can get a bit complicated but
                //  this is the format for a basic BBOX query.
                const params = Object.assign({}, {
                    f: 'json',
                    returnGeometry: 'true',
                    spatialRel: 'esriSpatialRelIntersects',
                    geometry: JSON.stringify({
                        xmin: extent[0], ymin: extent[1],
                        xmax: extent[2], ymax: extent[3],
                    }),
                    spatialReference: JSON.stringify({
                        wkid: 102100
                    }),
                    geometryType: 'esriGeometryEnvelope',
                    inSR: 102100, outSR: 102100,
                    outFields: '*',
                    returnIdsOnly: true,
                }, mapSource.params);

                // use JSONP to fetch the features.
                request({
                    url: url,
                    data: params,
                    type: 'jsonp',
                    success: (response) => {
                        if(response.error) {
                            console.error('Error loading object IDs for ' + mapSource.label);
                        } else {
                            const esri_format = new EsriJsonFormat();

                            const object_ids = response.objectIds;
                            if(object_ids !== null) {
                                // E**I FeatureServer appears to have a limitation of
                                // roughly 2048 bytes past the "?" in the GET call.
                                //  this ensure that the batches are small enough to prevent
                                //  404 errors.
                                const n_objects = object_ids.length;

                                // dummy "request" that can be used to estimate the
                                //  overall length of the query.
                                const sniff_r = Object.assign({}, params, {
                                    returnIdsOnly: false
                                });

                                // the ID's need to get "batched" into groups
                                //  which will reliably be shorter than the
                                //  maximum request length.
                                const batches = [];

                                // current batch is "rotated" whenever it gets too long
                                let current_batch = [];
                                for(let i = 0; i < n_objects; i++) {
                                    // estimate the request size
                                    const requestimate = requEstimator(Object.assign(sniff_r, {
                                        objectIds: current_batch.concat([object_ids[i]]).join(',')
                                    }));
                                    // if it's too long "rotate" the batches.
                                    if(requestimate > 2000) {
                                        batches.push(current_batch.slice());
                                        current_batch = [];
                                    }
                                    current_batch.push(object_ids[i]);
                                }
                                // ensure the remainder gets pushed to a batch
                                if(current_batch.length > 0) {
                                    batches.push(current_batch);
                                }

                                // make the feature requests based on the batches.
                                for(const batch of batches) {
                                    request({
                                        url: url,
                                        data: Object.assign({}, params, {
                                            returnIdsOnly: false,
                                            objectIds: batch.join(','),
                                        }),
                                        type: 'jsonp',
                                        success: (response) => {
                                            if(response.error) {
                                                console.error('Error loading feature batch for ' + mapSource.label);
                                            } else {
                                                this.addFeatures(esri_format.readFeatures(response, {
                                                    // featureProjection: proj,
                                                }));
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    },
                    error: (response) => {
                        console.error(response)
                    }
                });
            },
            strategy: tile(createXYZ({
                tileSize: 512
            }))
        }
    }
    // empty object
    return {}
}

/** Return a style function for the layer.
 *
 */
export function applyStyle(vectorLayer, mapSource, mapTool) {
    // if this is a special-case layer, handle it.
    if (mapSource.name === EDIT_LAYER_NAME) {
        const renderPoints = (mapTool === 'Modify' || mapTool === '_Modify');
        vectorLayer.setStyle(getEditStyle(mapSource.layers[0].style, renderPoints));
        return;
    }

    const layers = [];
    for(const layer of mapSource.layers) {
        if(layer.on === true) {
            // check for the different types of mapbox-gl layers
            //  GeoMoose lets the user define all the properties at once!
            const order = ['fill', 'line', 'circle', 'symbol'];

            for (let o = 0, oo = order.length; o < oo; o++) {
                const glLayerType = order[o];
                let filterFn = n => (n.indexOf(glLayerType) === 0);
                if (glLayerType === 'symbol') {
                    filterFn = n => (
                        n.indexOf('symbol') === 0 ||
                        n.indexOf('text') === 0
                    );
                }
                const validKeys = Object.keys(layer.style)
                    .filter(filterFn);
                if (validKeys.length > 0) {
                    const layer_def = {
                        id: `${layer.name}-${glLayerType}`,
                        type: glLayerType,
                        // source is a contant that is used to dummy up
                        //  the Mapbox styles
                        source: 'dummy-source',
                        paint: {},
                        layout: {},
                    };

                    // TODO: if updates are slow then this likely needs
                    //  optimized with real for loops.
                    ['paint', 'layout'].forEach(section => {
                        Object.keys(spec[`${section}_${glLayerType}`])
                            .forEach(key => {
                                if (layer.style[key]) {
                                    layer_def[section][key] = layer.style[key];
                                }
                            });
                    });

                    // check to see if there is a filter
                    //  set on the layer.  This uses the Mapbox GL/JS
                    //  filters.
                    if(layer.filter !== undefined) {
                        layer_def.filter = layer.filter;
                    }

                    layers.push(layer_def);
                }
            }
        }
    }

    applyStyleFunction(vectorLayer, {
        'version': 8,
        'layers': layers,
        'sources': {
            'dummy-source': {
                'type': 'vector'
            }
        },
    }, 'dummy-source');
}

/** Return an OpenLayers Layer for the Vector source.
 *
 *  @param mapSource The MapSource definition from the store.
 *
 *  @returns OpenLayers Layer instance.
 */
export function createLayer(mapSource) {
    const source = new VectorSource(defineSource(mapSource));

    // get the transforms for the layer
    if(mapSource.transforms) {
        source.on('addfeature', function(evt) {
            const f = evt.feature;
            f.setProperties(transformProperties(mapSource.transforms, f.getProperties()));
        });
    }

    const opts = {
        source,
        minResolution: mapSource.minresolution,
        maxResolution: mapSource.maxresolution,
        declutter: parseBoolean((mapSource.config || {}).declutter),
    };
    const vector_layer = new VectorLayer(opts);
    applyStyle(vector_layer, mapSource);

    return vector_layer;
}

/** Ensure that the Vector parameters all match.
 */
export function updateLayer(map, layer, mapSource, mapTool) {
    if(mapSource.type === 'vector') {
        // vector layer features are defined by what
        // is stored in mapSource.features
        const layer_version = layer.get('featuresVersion');
        // check to see if there was an update to the features
        if(layer_version !== mapSource.featuresVersion) {
            // this is a bit heavy-handed strategy.
            const source = layer.getSource();
            // clear the layer without setting off events.
            source.clear(true);
            // setup the JSON parser
            const output_format = new GeoJSONFormat();
            // bring in the new features.
            const features = output_format.readFeatures({
                type: 'FeatureCollection', features: mapSource.features
            });
            source.addFeatures(features);

            // update the version number
            layer.set('featuresVersion', mapSource.featuresVersion);
        }
    } else {
        const layer_version = layer.get('featuresVersion');
        // check to see if there was an update to the features
        if(layer_version !== mapSource.featuresVersion) {
            layer.set('featuresVersion', mapSource.featuresVersion);
            // refresh is available to all vector layers,
            //  this should force a reload of the features from the server
            //  upon update.
            layer.getSource().refresh();
        }
    }

    // update the style effectively turns "layers"
    // on and off on vector layers.
    applyStyle(layer, mapSource, mapTool);
}
<|endoftext|>


<commit_before>//component/icon.js

var Icon = React.createClass({
  propTypes: {
    style: React.PropTypes.object,
  },
  render: function() {
    var className = 'icon ' + this.props.icon;
    return
  }
});

var Link = React.createClass({
  render: function() {
    console.log(this.props);
    var href = this.props.href ? this.props.href : 'javascript:;',
      icon = this.props.icon ? <Icon icon={this.props.icon} />  : '',
      className = (this.props.button ? 'button-block button-' + this.props.button : 'button-text') +
                  (this.props.hidden ? ' hidden' : '') + (this.props.disabled ? ' disabled' : '');
    return (

        {this.props.icon ? icon : '' }
        {this.props.label}

    );
  }
});

var creditAmountStyle = {
  color: '#216C2A',
  fontWeight: 'bold',
  fontSize: '0.8em'
}, estimateStyle = {
  marginLeft : '5px',
  color: '#aaa',
};

var CreditAmount = React.createClass({
  propTypes: {
    amount: React.PropTypes.number,
  },
  render: function() {
    var formattedAmount = lbry.formatCredits(this.props.amount);
    return (

        {formattedAmount}
        { this.props.isEstimate ? (est) : null }

    );
  }
});<commit_msg>Add title prop to Link class<commit_after>//component/icon.js

var Icon = React.createClass({
  propTypes: {
    style: React.PropTypes.object,
  },
  render: function() {
    var className = 'icon ' + this.props.icon;
    return
  }
});

var Link = React.createClass({
  render: function() {
    console.log(this.props);
    var href = this.props.href ? this.props.href : 'javascript:;',
      icon = this.props.icon ? <Icon icon={this.props.icon} />  : '',
      className = (this.props.button ? 'button-block button-' + this.props.button : 'button-text') +
                  (this.props.hidden ? ' hidden' : '') + (this.props.disabled ? ' disabled' : '');
    return (

        {this.props.icon ? icon : '' }
        {this.props.label}

    );
  }
});

var creditAmountStyle = {
  color: '#216C2A',
  fontWeight: 'bold',
  fontSize: '0.8em'
}, estimateStyle = {
  marginLeft : '5px',
  color: '#aaa',
};

var CreditAmount = React.createClass({
  propTypes: {
    amount: React.PropTypes.number,
  },
  render: function() {
    var formattedAmount = lbry.formatCredits(this.props.amount);
    return (

        {formattedAmount}
        { this.props.isEstimate ? (est) : null }

    );
  }
});<|endoftext|>