<commit_before>/**
 * @param 'createCallback' A function to be called when a new entry is created.
 *    Two arguments are supplied to this function:
 *    The select element used and the value of the option. If the function
 *    returns false addition will be cancelled. If it returns
 *    anything else it will be used as the value of the newly added option.
 * @param 'createText' The placeholder text for the create action.
 * @param 'title' The title to show if no options are selected.
 * @param 'checked' An array containing values for options that should be
 *    checked. Any options which are already selected will be added to this array.
 * @param 'labels' The corresponding labels to show for the checked items.
 * @param 'oncheck' Callback function which will be called when a
 *    checkbox/radiobutton is selected. If the function returns false the input will be unchecked.
 * @param 'onuncheck' @see 'oncheck'.
 * @param 'singleSelect' If true radiobuttons will be used instead of
 *    checkboxes.
 */
(function( $ ){
	var multiSelectId=-1;
	$.fn.multiSelect=function(options) {
		multiSelectId++;
		var settings = {
			'createCallback':false,
			'createText':false,
			'singleSelect':false,
			'selectedFirst':false,
			'sort':true,
			'title':this.attr('title'),
			'checked':[],
			'labels':[],
			'oncheck':false,
			'onuncheck':false,
			'minWidth': 'default;'
		};
		var slideDuration = 200;
		$(this).attr('data-msid', multiSelectId);
		$.extend(settings,options);
		$.each(this.children(),function(i,option) {
			// If the option is selected, but not in the checked array, add it.
			if (
				$(option).attr('selected') &&
				settings.checked.indexOf($(option).val()) === -1
			) {
				settings.checked.push($(option).val());
				settings.labels.push($(option).text().trim());
			}
			// If the option is in the checked array but not selected, select it.
			else if (
				settings.checked.indexOf($(option).val()) !== -1 &&
				!$(option).attr('selected')
			) {
				$(option).attr('selected', 'selected');
				settings.labels.push($(option).text().trim());
			}
		});
		var button=$('
'+settings.title+'▾
');
		var span=$('');
		span.append(button);
		button.data('id',multiSelectId);
		button.selectedItems=[];
		this.hide();
		this.before(span);
		if(settings.minWidth=='default') {
			settings.minWidth=button.width();
		}
		button.css('min-width',settings.minWidth);
		settings.minOuterWidth=button.outerWidth()-2;
		button.data('settings',settings);

		if(!settings.singleSelect && settings.checked.length>0) {
			button.children('span').first().text(settings.labels.join(', '));
		} else if(settings.singleSelect) {
			button.children('span').first().text(this.find(':selected').text());
		}

		var self = this;
		self.menuDirection = 'down';
		button.click(function(event){

			var button=$(this);
			if(button.parent().children('ul').length>0) {
				if(self.menuDirection === 'down') {
					button.parent().children('ul').slideUp(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active down');
					});
				} else {
					button.parent().children('ul').fadeOut(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active up');
					});
				}
				return;
			}
			var lists=$('ul.multiselectoptions');
			lists.slideUp(slideDuration,function(){
				lists.remove();
				$('div.multiselect').removeClass('active');
				button.addClass('active');
			});
			button.addClass('active');
			event.stopPropagation();
			var options=$(this).parent().next().children();
			var list=$('
').hide().appendTo($(this).parent());
			var inputType = settings.singleSelect ? 'radio' : 'checkbox';
			function createItem(element, checked){
				element=$(element);
				var item=element.val();
				var id='ms'+multiSelectId+'-option-'+item;
				var input=$('<input type="' + inputType + '"/>');
				input.attr('id',id);
				if(settings.singleSelect) {
					input.attr('name', 'ms'+multiSelectId+'-option');
				}
				var label=$('');
				label.attr('for',id);
				label.text(element.text() || item);
				if(settings.checked.indexOf(item) !== -1 || checked) {
					input.attr('checked', true);
				}
				if(checked){
					if(settings.singleSelect) {
						settings.checked = [item];
						settings.labels = [item];
					} else {
						settings.checked.push(item);
						settings.labels.push(item);
					}
				}
				input.change(function(){
					var value = $(this).attr('id').substring(String('ms'+multiSelectId+'-option').length+1);
					var label = $(this).next().text().trim();
					if($(this).is(':checked')) {
						if(settings.singleSelect) {
							settings.checked = [];
							settings.labels = [];
							$.each(self.find('option'), function() {
								$(this).removeAttr('selected');
							});
						}
						element.attr('selected','selected');
						if(typeof settings.oncheck === 'function') {
							if(settings.oncheck(value)===false) {
								$(this).attr('checked', false);
								return;
							}
						}
						settings.checked.push(value);
						settings.labels.push(label);
						$(this).parent().addClass('checked');
					} else {
						var index=settings.checked.indexOf(value);
						element.attr('selected',null);
						if(typeof settings.onuncheck === 'function') {
							if(settings.onuncheck(value)===false) {
								$(this).attr('checked',true);
								return;
							}
						}
						$(this).parent().removeClass('checked');
						settings.checked.splice(index,1);
						settings.labels.splice(index,1);
					}
					var oldWidth=button.width();
					button.children('span').first().text(settings.labels.length > 0
						? settings.labels.join(', ')
						: settings.title);
					var newOuterWidth=Math.max(
						(button.outerWidth()-2),
						settings.minOuterWidth
					)+'px';
					var newWidth=Math.max(button.width(),settings.minWidth);
					var pos=button.position();
					button.css('width',oldWidth);
					button.animate({'width':newWidth},undefined,undefined,function(){
						button.css('width','');
					});
					list.animate({'width':newOuterWidth,'left':pos.left+3});
				});
				var li=$('

');
				li.append(input).append(label);
				if(input.is(':checked')) {
					li.addClass('checked');
				}
				return li;
			}
			$.each(options,function(index,item){
				list.append(createItem(item));
			});
			button.parent().data('preventHide',false);
			if(settings.createText){
				var li=$('
+ '+settings.createText+'
');
				li.click(function(event){
					li.empty();
					var input=$('<input type="text" class="new">');
					li.append(input);
					input.focus();
					input.css('width',button.innerWidth());
					button.parent().data('preventHide',true);
					input.keypress(function(event) {
						if(event.keyCode === 13) {
							event.preventDefault();
							event.stopPropagation();
							var value = $(this).val();
							var exists = false;
							$.each(options,function(index, item) {
								if ($(item).val() == value || $(item).text() == value) {
									exists = true;
									return false;
								}
							});
							if (exists) {
								return false;
							}
							var li=$(this).parent();
							var val = $(this).val();
							var select=button.parent().next();
							if(typeof settings.createCallback === 'function') {
								var response = settings.createCallback(select, val);
								if(response === false) {
									return false;
								} else if(typeof response !== 'undefined') {
									val = response;
								}
							}
							if(settings.singleSelect) {
								$.each(select.find('option:selected'), function() {
									$(this).removeAttr('selected');
								});
							}
							$(this).remove();
							li.text('+ '+settings.createText);
							li.before(createItem(this));
							var option=$('<option selected="selected"/>');
							option.text($(this).val()).val(val).attr('selected', 'selected');
							select.append(option);
							li.prev().children('input').prop('checked', true).trigger('change');
							button.parent().data('preventHide',false);
							button.children('span').first().text(settings.labels.length > 0
								? settings.labels.join(', ')
								: settings.title);
							if(self.menuDirection === 'up') {
								var list = li.parent();
								list.css('top', list.position().top-li.outerHeight());
							}
						}
					});
					input.blur(function() {
						event.preventDefault();
						event.stopPropagation();
						$(this).remove();
						li.text('+ '+settings.createText);
						setTimeout(function(){
							button.parent().data('preventHide',false);
						},100);
					});
				});
				list.append(li);
			}

			var doSort = function(list, selector) {
				var rows = list.find('li'+selector).get();

				if(settings.sort) {
					rows.sort(function(a, b) {
						return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
					});
				}

				$.each(rows, function(index, row) {
					list.append(row);
				});
			};
			if(settings.sort && settings.selectedFirst) {
				doSort(list, '.checked');
				doSort(list, ':not(.checked)');
			} else if(settings.sort && !settings.selectedFirst) {
				doSort(list, '');
			}
			list.append(list.find('li.creator'));
			var pos=button.position();
			if(($(document).height() > (button.offset().top + button.outerHeight() + list.children().length * button.height()) &&
				$(document).height() - button.offset().top > (button.offset().top+button.outerHeight() + list.children().length * button.height())) ||
				$(document).height()/2 > button.offset().top
			) {
				list.css({
					top:pos.top+button.outerHeight()-5,
					left:pos.left+3,
					width:(button.outerWidth()-2)+'px',
					'max-height':($(document).height()-(button.offset().top+button.outerHeight()+10))+'px'
				});
				list.addClass('down');
				button.addClass('down');
				list.slideDown(slideDuration);
			} else {
				list.css('max-height', $(document).height()-($(document).height()-(pos.top)+50)+'px');
				list.css({
					top:pos.top - list.height(),
					left:pos.left+3,
					width:(button.outerWidth()-2)+'px'

				});
				list.detach().insertBefore($(this));
				list.addClass('up');
				button.addClass('up');
				list.fadeIn();
				self.menuDirection = 'up';
			}
			list.click(function(event) {
				event.stopPropagation();
			});
		});
		$(window).click(function() {
			if(!button.parent().data('preventHide')) {
				// How can I save the effect in a var?
				if(self.menuDirection === 'down') {
					button.parent().children('ul').slideUp(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active down');
					});
				} else {
					button.parent().children('ul').fadeOut(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active up');
					});
				}
			}
		});

		return span;
	};
})( jQuery );
<commit_msg>Add some more spaces for operators<commit_after>/**
 * @param 'createCallback' A function to be called when a new entry is created.
 *    Two arguments are supplied to this function:
 *    The select element used and the value of the option. If the function
 *    returns false addition will be cancelled. If it returns
 *    anything else it will be used as the value of the newly added option.
 * @param 'createText' The placeholder text for the create action.
 * @param 'title' The title to show if no options are selected.
 * @param 'checked' An array containing values for options that should be
 *    checked. Any options which are already selected will be added to this array.
 * @param 'labels' The corresponding labels to show for the checked items.
 * @param 'oncheck' Callback function which will be called when a
 *    checkbox/radiobutton is selected. If the function returns false the input will be unchecked.
 * @param 'onuncheck' @see 'oncheck'.
 * @param 'singleSelect' If true radiobuttons will be used instead of
 *    checkboxes.
 */
(function( $ ){
	var multiSelectId=-1;
	$.fn.multiSelect=function(options) {
		multiSelectId++;
		var settings = {
			'createCallback':false,
			'createText':false,
			'singleSelect':false,
			'selectedFirst':false,
			'sort':true,
			'title':this.attr('title'),
			'checked':[],
			'labels':[],
			'oncheck':false,
			'onuncheck':false,
			'minWidth': 'default;'
		};
		var slideDuration = 200;
		$(this).attr('data-msid', multiSelectId);
		$.extend(settings,options);
		$.each(this.children(),function(i,option) {
			// If the option is selected, but not in the checked array, add it.
			if (
				$(option).attr('selected') &&
				settings.checked.indexOf($(option).val()) === -1
			) {
				settings.checked.push($(option).val());
				settings.labels.push($(option).text().trim());
			}
			// If the option is in the checked array but not selected, select it.
			else if (
				settings.checked.indexOf($(option).val()) !== -1 &&
				!$(option).attr('selected')
			) {
				$(option).attr('selected', 'selected');
				settings.labels.push($(option).text().trim());
			}
		});
		var button=$('
'+settings.title+'▾
');
		var span=$('');
		span.append(button);
		button.data('id',multiSelectId);
		button.selectedItems=[];
		this.hide();
		this.before(span);
		if(settings.minWidth=='default') {
			settings.minWidth=button.width();
		}
		button.css('min-width',settings.minWidth);
		settings.minOuterWidth=button.outerWidth()-2;
		button.data('settings',settings);

		if(!settings.singleSelect && settings.checked.length>0) {
			button.children('span').first().text(settings.labels.join(', '));
		} else if(settings.singleSelect) {
			button.children('span').first().text(this.find(':selected').text());
		}

		var self = this;
		self.menuDirection = 'down';
		button.click(function(event){

			var button=$(this);
			if(button.parent().children('ul').length>0) {
				if(self.menuDirection === 'down') {
					button.parent().children('ul').slideUp(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active down');
					});
				} else {
					button.parent().children('ul').fadeOut(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active up');
					});
				}
				return;
			}
			var lists=$('ul.multiselectoptions');
			lists.slideUp(slideDuration,function(){
				lists.remove();
				$('div.multiselect').removeClass('active');
				button.addClass('active');
			});
			button.addClass('active');
			event.stopPropagation();
			var options=$(this).parent().next().children();
			var list=$('
').hide().appendTo($(this).parent());
			var inputType = settings.singleSelect ? 'radio' : 'checkbox';
			function createItem(element, checked){
				element=$(element);
				var item=element.val();
				var id='ms'+multiSelectId+'-option-'+item;
				var input=$('<input type="' + inputType + '"/>');
				input.attr('id',id);
				if(settings.singleSelect) {
					input.attr('name', 'ms'+multiSelectId+'-option');
				}
				var label=$('');
				label.attr('for',id);
				label.text(element.text() || item);
				if(settings.checked.indexOf(item) !== -1 || checked) {
					input.attr('checked', true);
				}
				if(checked){
					if(settings.singleSelect) {
						settings.checked = [item];
						settings.labels = [item];
					} else {
						settings.checked.push(item);
						settings.labels.push(item);
					}
				}
				input.change(function(){
					var value = $(this).attr('id').substring(String('ms'+multiSelectId+'-option').length+1);
					var label = $(this).next().text().trim();
					if($(this).is(':checked')) {
						if(settings.singleSelect) {
							settings.checked = [];
							settings.labels = [];
							$.each(self.find('option'), function() {
								$(this).removeAttr('selected');
							});
						}
						element.attr('selected','selected');
						if(typeof settings.oncheck === 'function') {
							if(settings.oncheck(value)===false) {
								$(this).attr('checked', false);
								return;
							}
						}
						settings.checked.push(value);
						settings.labels.push(label);
						$(this).parent().addClass('checked');
					} else {
						var index=settings.checked.indexOf(value);
						element.attr('selected',null);
						if(typeof settings.onuncheck === 'function') {
							if(settings.onuncheck(value)===false) {
								$(this).attr('checked',true);
								return;
							}
						}
						$(this).parent().removeClass('checked');
						settings.checked.splice(index,1);
						settings.labels.splice(index,1);
					}
					var oldWidth=button.width();
					button.children('span').first().text(settings.labels.length > 0
						? settings.labels.join(', ')
						: settings.title);
					var newOuterWidth = Math.max(
						(button.outerWidth() - 2),
						settings.minOuterWidth
					) + 'px';
					var newWidth=Math.max(button.width(),settings.minWidth);
					var pos=button.position();
					button.css('width',oldWidth);
					button.animate({'width':newWidth},undefined,undefined,function(){
						button.css('width','');
					});
					list.animate({'width':newOuterWidth,'left':pos.left+3});
				});
				var li=$('

');
				li.append(input).append(label);
				if(input.is(':checked')) {
					li.addClass('checked');
				}
				return li;
			}
			$.each(options,function(index,item){
				list.append(createItem(item));
			});
			button.parent().data('preventHide',false);
			if(settings.createText){
				var li=$('
+ '+settings.createText+'
');
				li.click(function(event){
					li.empty();
					var input=$('<input type="text" class="new">');
					li.append(input);
					input.focus();
					input.css('width',button.innerWidth());
					button.parent().data('preventHide',true);
					input.keypress(function(event) {
						if(event.keyCode === 13) {
							event.preventDefault();
							event.stopPropagation();
							var value = $(this).val();
							var exists = false;
							$.each(options,function(index, item) {
								if ($(item).val() == value || $(item).text() == value) {
									exists = true;
									return false;
								}
							});
							if (exists) {
								return false;
							}
							var li=$(this).parent();
							var val = $(this).val();
							var select=button.parent().next();
							if(typeof settings.createCallback === 'function') {
								var response = settings.createCallback(select, val);
								if(response === false) {
									return false;
								} else if(typeof response !== 'undefined') {
									val = response;
								}
							}
							if(settings.singleSelect) {
								$.each(select.find('option:selected'), function() {
									$(this).removeAttr('selected');
								});
							}
							$(this).remove();
							li.text('+ '+settings.createText);
							li.before(createItem(this));
							var option=$('<option selected="selected"/>');
							option.text($(this).val()).val(val).attr('selected', 'selected');
							select.append(option);
							li.prev().children('input').prop('checked', true).trigger('change');
							button.parent().data('preventHide',false);
							button.children('span').first().text(settings.labels.length > 0
								? settings.labels.join(', ')
								: settings.title);
							if(self.menuDirection === 'up') {
								var list = li.parent();
								list.css('top', list.position().top-li.outerHeight());
							}
						}
					});
					input.blur(function() {
						event.preventDefault();
						event.stopPropagation();
						$(this).remove();
						li.text('+ '+settings.createText);
						setTimeout(function(){
							button.parent().data('preventHide',false);
						},100);
					});
				});
				list.append(li);
			}

			var doSort = function(list, selector) {
				var rows = list.find('li'+selector).get();

				if(settings.sort) {
					rows.sort(function(a, b) {
						return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
					});
				}

				$.each(rows, function(index, row) {
					list.append(row);
				});
			};
			if(settings.sort && settings.selectedFirst) {
				doSort(list, '.checked');
				doSort(list, ':not(.checked)');
			} else if(settings.sort && !settings.selectedFirst) {
				doSort(list, '');
			}
			list.append(list.find('li.creator'));
			var pos=button.position();
			if(($(document).height() > (button.offset().top + button.outerHeight() + list.children().length * button.height()) &&
				$(document).height() - button.offset().top > (button.offset().top+button.outerHeight() + list.children().length * button.height())) ||
				$(document).height() / 2 > button.offset().top
			) {
				list.css({
					top:pos.top+button.outerHeight()-5,
					left:pos.left+3,
					width:(button.outerWidth()-2)+'px',
					'max-height':($(document).height()-(button.offset().top+button.outerHeight()+10))+'px'
				});
				list.addClass('down');
				button.addClass('down');
				list.slideDown(slideDuration);
			} else {
				list.css('max-height', $(document).height()-($(document).height()-(pos.top)+50)+'px');
				list.css({
					top:pos.top - list.height(),
					left:pos.left+3,
					width:(button.outerWidth()-2)+'px'

				});
				list.detach().insertBefore($(this));
				list.addClass('up');
				button.addClass('up');
				list.fadeIn();
				self.menuDirection = 'up';
			}
			list.click(function(event) {
				event.stopPropagation();
			});
		});
		$(window).click(function() {
			if(!button.parent().data('preventHide')) {
				// How can I save the effect in a var?
				if(self.menuDirection === 'down') {
					button.parent().children('ul').slideUp(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active down');
					});
				} else {
					button.parent().children('ul').fadeOut(slideDuration,function() {
						button.parent().children('ul').remove();
						button.removeClass('active up');
					});
				}
			}
		});

		return span;
	};
})( jQuery );
<|endoftext|>


<commit_before>/**
 * ownCloud
 *
 * @author Morris Jobke
 * @copyright 2013 Morris Jobke <morris.jobke@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*
 * Adds a background color to the element called on and adds the first charater
 * of the passed in string. This string is also the seed for the generation of
 * the background color.
 *
 * You have following HTML:
 *
 *

 *
 * And call this from Javascript:
 *
 * $('#albumart').placeholder('The Album Title');
 *
 * Which will result in:
 *
 *
T

 *
 */

(function ($) {
	$.fn.placeholder = function(seed) {
		var hash = md5(seed),
			maxRange = parseInt('ffffffffff', 16),
			red = parseInt(hash.substr(0,10), 16) / maxRange * 256,
			green = parseInt(hash.substr(10,10), 16) / maxRange * 256,
			blue = parseInt(hash.substr(20,10), 16) / maxRange * 256,
			rgb = [Math.floor(red), Math.floor(green), Math.floor(blue)];
		this.css('background-color', 'rgb(' + rgb.join(',') + ')');

		// CSS rules
		this.css('color', 'rgb(255, 255, 255)');
		this.css('font-weight', 'bold');
		this.css('text-align', 'center');

		if(seed !== null && seed.length) {
			this.html(seed[0].toUpperCase());
		}
	};
}(jQuery));
<commit_msg>calculate fontsize and line-height<commit_after>/**
 * ownCloud
 *
 * @author Morris Jobke
 * @copyright 2013 Morris Jobke <morris.jobke@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*
 * Adds a background color to the element called on and adds the first charater
 * of the passed in string. This string is also the seed for the generation of
 * the background color.
 *
 * You have following HTML:
 *
 *

 *
 * And call this from Javascript:
 *
 * $('#albumart').placeholder('The Album Title');
 *
 * Which will result in:
 *
 *
T

 *
 */

(function ($) {
	$.fn.placeholder = function(seed) {
		var hash = md5(seed),
			maxRange = parseInt('ffffffffff', 16),
			red = parseInt(hash.substr(0,10), 16) / maxRange * 256,
			green = parseInt(hash.substr(10,10), 16) / maxRange * 256,
			blue = parseInt(hash.substr(20,10), 16) / maxRange * 256,
			rgb = [Math.floor(red), Math.floor(green), Math.floor(blue)],
			height = this.height();
		this.css('background-color', 'rgb(' + rgb.join(',') + ')');

		// CSS rules
		this.css('color', 'rgb(255, 255, 255)');
		this.css('font-weight', 'bold');
		this.css('text-align', 'center');

		// calculate the height
		this.css('line-height', height + 'px');
		this.css('font-size', (height * 0.55) + 'px');

		if(seed !== null && seed.length) {
			this.html(seed[0].toUpperCase());
		}
	};
}(jQuery));
<|endoftext|>


<commit_before>/*
 * patternlab-node - v2.0.0 - 2016
 *
 * Brian Muenzenmeyer, Geoff Pursell, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

"use strict";

var diveSync = require('diveSync'),
  path = require('path');

// GTP: these two diveSync pattern processors factored out so they can be reused
// from unit tests to reduce code dupe!

function processAllPatternsIterative(pattern_assembler, patterns_dir, patternlab) {
  diveSync(
    patterns_dir,
    {
      filter: function (thisPath, dir) {
        if (dir) {
          var remainingPath = thisPath.replace(patterns_dir, '');
          var isValidPath = remainingPath.indexOf('/_') === -1;
          return isValidPath;
        }
        return true;
      }
    },
    function (err, file) {
      //log any errors
      if (err) {
        console.log(err);
        return;
      }
      pattern_assembler.process_pattern_iterative(path.relative(patterns_dir, file), patternlab);
    }
  );
}

function processAllPatternsRecursive(pattern_assembler, patterns_dir, patternlab) {
  diveSync(
    patterns_dir,
    {
      filter: function (thisPath, dir) {
        if (dir) {
          var remainingPath = thisPath.replace(patterns_dir, '');
          var isValidPath = remainingPath.indexOf('/_') === -1;
          return isValidPath;
        }
        return true;
      }
    },
    function (err, file) {
      //log any errors
      if (err) {
        console.log(err);
        return;
      }
      pattern_assembler.process_pattern_recursive(path.relative(patterns_dir, file), patternlab);
    }
  );
}

var patternlab_engine = function (config) {
  'use strict';

  var JSON5 = require('json5'),
    fs = require('fs-extra'),
    pa = require('./pattern_assembler'),
    pe = require('./pattern_exporter'),
    lh = require('./lineage_hunter'),
    buildFrontEnd = require('./ui_builder'),
    he = require('html-entities').AllHtmlEntities,
    plutils = require('./utilities'),
    sm = require('./starterkit_manager'),
    patternlab = {};

  patternlab.package = fs.readJSONSync(path.resolve(__dirname, '../../package.json'));
  patternlab.config = config || fs.readJSONSync(path.resolve(__dirname, '../../patternlab-config.json'));

  var paths = patternlab.config.paths;

  function getVersion() {
    console.log(patternlab.package.version);
  }

  function help() {
    console.log('Patternlab Node Help');
    console.log('===============================');
    console.log('Command Line Arguments');
    console.log('patternlab:only_patterns');
    console.log(' > Compiles the patterns only, outputting to config.patterns.public');
    console.log('patternlab:v');
    console.log(' > Retrieve the version of patternlab-node you have installed');
    console.log('patternlab:help');
    console.log(' > Get more information about patternlab-node, pattern lab in general, and where to report issues.');
    console.log('===============================');
    console.log('Visit http://patternlab.io/docs/index.html for general help on pattern-lab');
    console.log('Visit https://github.com/pattern-lab/patternlab-node/issues to open a bug.');
  }

  function printDebug() {
    // A replacer function to pass to stringify below; this is here to prevent
    // the debug output from blowing up into a massive fireball of circular
    // references. This happens specifically with the Handlebars engine. Remove
    // if you like 180MB log files.
    function propertyStringReplacer(key, value) {
      if (key === 'engine' && value.engineName) {
        return '{' + value.engineName + ' engine object}';
      }
      return value;
    }

    //debug file can be written by setting flag on patternlab-config.json
    if (patternlab.config.debug) {
      console.log('writing patternlab debug file to ./patternlab.json');
      fs.outputFileSync('./patternlab.json', JSON.stringify(patternlab, propertyStringReplacer, 3));
    }
  }

  function setCacheBust() {
    if (patternlab.config.cacheBust) {
      if (patternlab.config.debug) {
        console.log('setting cacheBuster value for frontend assets.');
      }
      patternlab.cacheBuster = new Date().getTime();
    } else {
      patternlab.cacheBuster = 0;
    }
  }

  function listStarterkits() {
    var starterkit_manager = new sm(patternlab);
    return starterkit_manager.list_starterkits();
  }

  function loadStarterKit(starterkitName) {
    var starterkit_manager = new sm(patternlab);
    starterkit_manager.load_starterkit(starterkitName);
  }

  function buildPatterns(deletePatternDir) {
    try {
      patternlab.data = fs.readJSONSync(path.resolve(paths.source.data, 'data.json'));
    } catch (ex) {
      console.log('missing ' + paths.source.data + '/data.json  Pattern Lab may not work without this file.');
      patternlab.data = {};
    }
    try {
      patternlab.listitems = fs.readJSONSync(path.resolve(paths.source.data, 'listitems.json'));
    } catch (ex) {
      console.log('missing ' + paths.source.data + '/listitems.json  Pattern Lab may not work without this file.');
      patternlab.listitems = {};
    }
    try {
      patternlab.header = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'general-header.mustache'), 'utf8');
      patternlab.footer = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'general-footer.mustache'), 'utf8');
      patternlab.patternSection = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'patternSection.mustache'), 'utf8');
      patternlab.patternSectionSubType = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'patternSectionSubtype.mustache'), 'utf8');
      patternlab.viewAll = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'viewall.mustache'), 'utf8');
    } catch (ex) {
      console.log(ex);
      console.log('\nERROR: missing an essential file from ' + paths.source.patternlabFiles + '. Pattern Lab won\'t work without this file.\n');
      process.exit(1);
    }
    patternlab.patterns = [];
    patternlab.partials = {};
    patternlab.data.link = {};

    setCacheBust();

    var pattern_assembler = new pa(),
      entity_encoder = new he(),
      pattern_exporter = new pe(),
      lineage_hunter = new lh(),
      patterns_dir = paths.source.patterns;

    pattern_assembler.combine_listItems(patternlab);

    // diveSync once to perform iterative populating of patternlab object
    processAllPatternsIterative(pattern_assembler, patterns_dir, patternlab);

    //diveSync again to recursively include partials, filling out the
    //extendedTemplate property of the patternlab.patterns elements
    processAllPatternsRecursive(pattern_assembler, patterns_dir, patternlab);

    //set user defined head and foot if they exist
    try {
      patternlab.userHead = fs.readFileSync(path.resolve(paths.source.root, '_meta', '_00-head.mustache'), 'utf8');
    }
    catch (ex) {
      if (patternlab.config.debug) {
        console.log(ex);
        console.log('Could not find optional user-defined header, usually found at ./source/_meta/_001-head.mustache. It was likely deleted.');
      }
    }
    try {
      patternlab.userFoot = fs.readFileSync(path.resolve(paths.source.root, '_meta', '_01-foot.mustache'), 'utf8');
    }
    catch (ex) {
      if (patternlab.config.debug) {
        console.log(ex);
        console.log('Could not find optional user-defined footer, usually found at ./source/_meta/_01-foot.mustache. It was likely deleted.');
      }
    }

    //now that all the main patterns are known, look for any links that might be within data and expand them
    //we need to do this before expanding patterns & partials into extendedTemplates, otherwise we could lose the data -> partial reference
    pattern_assembler.parse_data_links(patternlab);

    //cascade any patternStates
    lineage_hunter.cascade_pattern_states(patternlab);

    //delete the contents of config.patterns.public before writing
    if (deletePatternDir) {
      fs.emptyDirSync(paths.public.patterns);
    }

    //set pattern-specific header if necessary
    var head;
    if (patternlab.userHead) {
      head = patternlab.userHead.replace('{% pattern-lab-head %}', patternlab.header);
    } else {
      head = patternlab.header;
    }

    //set the pattern-specific header by compiling the general-header with data, and then adding it to the meta header
    patternlab.data.patternLabHead = pattern_assembler.renderPattern(patternlab.header, {
      cacheBuster: patternlab.cacheBuster
    });

    //render all patterns last, so lineageR works
    patternlab.patterns.forEach(function (pattern) {

      pattern.header = head;

      //todo move this into lineage_hunter
      pattern.patternLineages = pattern.lineage;
      pattern.patternLineageExists = pattern.lineage.length > 0;
      pattern.patternLineagesR = pattern.lineageR;
      pattern.patternLineageRExists = pattern.lineageR.length > 0;
      pattern.patternLineageEExists = pattern.patternLineageExists || pattern.patternLineageRExists;

      //render the pattern, but first consolidate any data we may have
      var allData;
      try {
        allData = JSON5.parse(JSON5.stringify(patternlab.data));
      } catch (err) {
        console.log('There was an error parsing JSON for ' + pattern.relPath);
        console.log(err);
      }
      allData = plutils.mergeData(allData, pattern.jsonFileData);

      //var headHTML = pattern_assembler.renderPattern(patternlab.userHead, allData);
      var headHTML = pattern_assembler.renderPattern(pattern.header, allData);

      //render the extendedTemplate with all data
      pattern.patternPartialCode = pattern_assembler.renderPattern(pattern, allData);

      //todo see if this is still needed
      pattern.patternPartialCodeE = entity_encoder.encode(pattern.patternPartialCode);

      // stringify this data for individual pattern rendering and use on the styleguide
      // see if patternData really needs these other duped values
      pattern.patternData = JSON.stringify({
        isPattern: true,
        cssEnabled: false,
        patternLineageExists: pattern.patternLineageExists,
        patternLineages: pattern.patternLineages,
        lineage: pattern.patternLineages,
        patternLineageRExists: pattern.patternLineageRExists,
        patternLineagesR: pattern.patternLineagesR,
        lineageR: pattern.patternLineagesR,
        patternLineageEExists: pattern.patternLineageExists || pattern.patternLineageRExists,
        patternDesc: pattern.patternDescExists ? pattern.patternDesc : '',
        patternBreadcrumb: 'TODO',
        patternExtension: pattern.fileExtension,
        patternName: pattern.patternName,
        patternPartial: pattern.patternPartial,
        patternState: pattern.patternState,
        extraOutput: {}
      });

      //set the pattern-specific footer by compiling the general-footer with data, and then adding it to the meta footer
      var footerPartial = pattern_assembler.renderPattern(patternlab.footer, {
        patternData: pattern.patternData,
        cacheBuster: patternlab.cacheBuster
      });

      var footerHTML = pattern_assembler.renderPattern(patternlab.userFoot, {
        patternLabFoot : footerPartial
      });

      //write the compiled template to the public patterns directory
      var patternPage = headHTML + pattern.patternPartialCode + footerHTML;
      fs.outputFileSync(paths.public.patterns + pattern.patternLink, patternPage);

      //write the mustache file too
      fs.outputFileSync(paths.public.patterns + pattern.patternLink.replace('.html', pattern.fileExtension), pattern.template);

      //write the encoded version too
      fs.outputFileSync(paths.public.patterns + pattern.patternLink.replace('.html', '.markup-only.html'), pattern.patternPartialCode);
    });

    //export patterns if necessary
    pattern_exporter.export_patterns(patternlab);
  }

  return {
    version: function () {
      return getVersion();
    },
    build: function (deletePatternDir) {
      buildPatterns(deletePatternDir);
      buildFrontEnd(patternlab);
      printDebug();
    },
    help: function () {
      help();
    },
    build_patterns_only: function (deletePatternDir) {
      buildPatterns(deletePatternDir);
      printDebug();
    },
    list_starterkits: function () {
      return listStarterkits();
    },
    load_starterkit: function (starterkitName) {
      loadStarterKit(starterkitName);
    }
  };
};

// export these free functions so they're available without calling the exported
// function, for use in reducing code dupe in unit tests. At least, until we
// have a better way to do this
patternlab_engine.process_all_patterns_iterative = processAllPatternsIterative;
patternlab_engine.process_all_patterns_recursive = processAllPatternsRecursive;

module.exports = patternlab_engine;
<commit_msg>move isPattern declaration to the proper data level closes https://github.com/pattern-lab/edition-node-gulp/issues/12 and https://github.com/pattern-lab/edition-node-gulp/issues/13<commit_after>/*
 * patternlab-node - v2.0.0 - 2016
 *
 * Brian Muenzenmeyer, Geoff Pursell, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

"use strict";

var diveSync = require('diveSync'),
  path = require('path');

// GTP: these two diveSync pattern processors factored out so they can be reused
// from unit tests to reduce code dupe!

function processAllPatternsIterative(pattern_assembler, patterns_dir, patternlab) {
  diveSync(
    patterns_dir,
    {
      filter: function (thisPath, dir) {
        if (dir) {
          var remainingPath = thisPath.replace(patterns_dir, '');
          var isValidPath = remainingPath.indexOf('/_') === -1;
          return isValidPath;
        }
        return true;
      }
    },
    function (err, file) {
      //log any errors
      if (err) {
        console.log(err);
        return;
      }
      pattern_assembler.process_pattern_iterative(path.relative(patterns_dir, file), patternlab);
    }
  );
}

function processAllPatternsRecursive(pattern_assembler, patterns_dir, patternlab) {
  diveSync(
    patterns_dir,
    {
      filter: function (thisPath, dir) {
        if (dir) {
          var remainingPath = thisPath.replace(patterns_dir, '');
          var isValidPath = remainingPath.indexOf('/_') === -1;
          return isValidPath;
        }
        return true;
      }
    },
    function (err, file) {
      //log any errors
      if (err) {
        console.log(err);
        return;
      }
      pattern_assembler.process_pattern_recursive(path.relative(patterns_dir, file), patternlab);
    }
  );
}

var patternlab_engine = function (config) {
  'use strict';

  var JSON5 = require('json5'),
    fs = require('fs-extra'),
    pa = require('./pattern_assembler'),
    pe = require('./pattern_exporter'),
    lh = require('./lineage_hunter'),
    buildFrontEnd = require('./ui_builder'),
    he = require('html-entities').AllHtmlEntities,
    plutils = require('./utilities'),
    sm = require('./starterkit_manager'),
    patternlab = {};

  patternlab.package = fs.readJSONSync(path.resolve(__dirname, '../../package.json'));
  patternlab.config = config || fs.readJSONSync(path.resolve(__dirname, '../../patternlab-config.json'));

  var paths = patternlab.config.paths;

  function getVersion() {
    console.log(patternlab.package.version);
  }

  function help() {
    console.log('Patternlab Node Help');
    console.log('===============================');
    console.log('Command Line Arguments');
    console.log('patternlab:only_patterns');
    console.log(' > Compiles the patterns only, outputting to config.patterns.public');
    console.log('patternlab:v');
    console.log(' > Retrieve the version of patternlab-node you have installed');
    console.log('patternlab:help');
    console.log(' > Get more information about patternlab-node, pattern lab in general, and where to report issues.');
    console.log('===============================');
    console.log('Visit http://patternlab.io/docs/index.html for general help on pattern-lab');
    console.log('Visit https://github.com/pattern-lab/patternlab-node/issues to open a bug.');
  }

  function printDebug() {
    // A replacer function to pass to stringify below; this is here to prevent
    // the debug output from blowing up into a massive fireball of circular
    // references. This happens specifically with the Handlebars engine. Remove
    // if you like 180MB log files.
    function propertyStringReplacer(key, value) {
      if (key === 'engine' && value.engineName) {
        return '{' + value.engineName + ' engine object}';
      }
      return value;
    }

    //debug file can be written by setting flag on patternlab-config.json
    if (patternlab.config.debug) {
      console.log('writing patternlab debug file to ./patternlab.json');
      fs.outputFileSync('./patternlab.json', JSON.stringify(patternlab, propertyStringReplacer, 3));
    }
  }

  function setCacheBust() {
    if (patternlab.config.cacheBust) {
      if (patternlab.config.debug) {
        console.log('setting cacheBuster value for frontend assets.');
      }
      patternlab.cacheBuster = new Date().getTime();
    } else {
      patternlab.cacheBuster = 0;
    }
  }

  function listStarterkits() {
    var starterkit_manager = new sm(patternlab);
    return starterkit_manager.list_starterkits();
  }

  function loadStarterKit(starterkitName) {
    var starterkit_manager = new sm(patternlab);
    starterkit_manager.load_starterkit(starterkitName);
  }

  function buildPatterns(deletePatternDir) {
    try {
      patternlab.data = fs.readJSONSync(path.resolve(paths.source.data, 'data.json'));
    } catch (ex) {
      console.log('missing ' + paths.source.data + '/data.json  Pattern Lab may not work without this file.');
      patternlab.data = {};
    }
    try {
      patternlab.listitems = fs.readJSONSync(path.resolve(paths.source.data, 'listitems.json'));
    } catch (ex) {
      console.log('missing ' + paths.source.data + '/listitems.json  Pattern Lab may not work without this file.');
      patternlab.listitems = {};
    }
    try {
      patternlab.header = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'general-header.mustache'), 'utf8');
      patternlab.footer = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'general-footer.mustache'), 'utf8');
      patternlab.patternSection = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'patternSection.mustache'), 'utf8');
      patternlab.patternSectionSubType = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'patternSectionSubtype.mustache'), 'utf8');
      patternlab.viewAll = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'viewall.mustache'), 'utf8');
    } catch (ex) {
      console.log(ex);
      console.log('\nERROR: missing an essential file from ' + paths.source.patternlabFiles + '. Pattern Lab won\'t work without this file.\n');
      process.exit(1);
    }
    patternlab.patterns = [];
    patternlab.partials = {};
    patternlab.data.link = {};

    setCacheBust();

    var pattern_assembler = new pa(),
      entity_encoder = new he(),
      pattern_exporter = new pe(),
      lineage_hunter = new lh(),
      patterns_dir = paths.source.patterns;

    pattern_assembler.combine_listItems(patternlab);

    // diveSync once to perform iterative populating of patternlab object
    processAllPatternsIterative(pattern_assembler, patterns_dir, patternlab);

    //diveSync again to recursively include partials, filling out the
    //extendedTemplate property of the patternlab.patterns elements
    processAllPatternsRecursive(pattern_assembler, patterns_dir, patternlab);

    //set user defined head and foot if they exist
    try {
      patternlab.userHead = fs.readFileSync(path.resolve(paths.source.root, '_meta', '_00-head.mustache'), 'utf8');
    }
    catch (ex) {
      if (patternlab.config.debug) {
        console.log(ex);
        console.log('Could not find optional user-defined header, usually found at ./source/_meta/_001-head.mustache. It was likely deleted.');
      }
    }
    try {
      patternlab.userFoot = fs.readFileSync(path.resolve(paths.source.root, '_meta', '_01-foot.mustache'), 'utf8');
    }
    catch (ex) {
      if (patternlab.config.debug) {
        console.log(ex);
        console.log('Could not find optional user-defined footer, usually found at ./source/_meta/_01-foot.mustache. It was likely deleted.');
      }
    }

    //now that all the main patterns are known, look for any links that might be within data and expand them
    //we need to do this before expanding patterns & partials into extendedTemplates, otherwise we could lose the data -> partial reference
    pattern_assembler.parse_data_links(patternlab);

    //cascade any patternStates
    lineage_hunter.cascade_pattern_states(patternlab);

    //delete the contents of config.patterns.public before writing
    if (deletePatternDir) {
      fs.emptyDirSync(paths.public.patterns);
    }

    //set pattern-specific header if necessary
    var head;
    if (patternlab.userHead) {
      head = patternlab.userHead.replace('{% pattern-lab-head %}', patternlab.header);
    } else {
      head = patternlab.header;
    }

    //set the pattern-specific header by compiling the general-header with data, and then adding it to the meta header
    patternlab.data.patternLabHead = pattern_assembler.renderPattern(patternlab.header, {
      cacheBuster: patternlab.cacheBuster
    });

    //render all patterns last, so lineageR works
    patternlab.patterns.forEach(function (pattern) {

      pattern.header = head;

      //todo move this into lineage_hunter
      pattern.patternLineages = pattern.lineage;
      pattern.patternLineageExists = pattern.lineage.length > 0;
      pattern.patternLineagesR = pattern.lineageR;
      pattern.patternLineageRExists = pattern.lineageR.length > 0;
      pattern.patternLineageEExists = pattern.patternLineageExists || pattern.patternLineageRExists;

      //render the pattern, but first consolidate any data we may have
      var allData;
      try {
        allData = JSON5.parse(JSON5.stringify(patternlab.data));
      } catch (err) {
        console.log('There was an error parsing JSON for ' + pattern.relPath);
        console.log(err);
      }
      allData = plutils.mergeData(allData, pattern.jsonFileData);

      //var headHTML = pattern_assembler.renderPattern(patternlab.userHead, allData);
      var headHTML = pattern_assembler.renderPattern(pattern.header, allData);

      //render the extendedTemplate with all data
      pattern.patternPartialCode = pattern_assembler.renderPattern(pattern, allData);

      //todo see if this is still needed
      pattern.patternPartialCodeE = entity_encoder.encode(pattern.patternPartialCode);

      // stringify this data for individual pattern rendering and use on the styleguide
      // see if patternData really needs these other duped values
      pattern.patternData = JSON.stringify({
        cssEnabled: false,
        patternLineageExists: pattern.patternLineageExists,
        patternLineages: pattern.patternLineages,
        lineage: pattern.patternLineages,
        patternLineageRExists: pattern.patternLineageRExists,
        patternLineagesR: pattern.patternLineagesR,
        lineageR: pattern.patternLineagesR,
        patternLineageEExists: pattern.patternLineageExists || pattern.patternLineageRExists,
        patternDesc: pattern.patternDescExists ? pattern.patternDesc : '',
        patternBreadcrumb: 'TODO',
        patternExtension: pattern.fileExtension,
        patternName: pattern.patternName,
        patternPartial: pattern.patternPartial,
        patternState: pattern.patternState,
        extraOutput: {}
      });

      //set the pattern-specific footer by compiling the general-footer with data, and then adding it to the meta footer
      var footerPartial = pattern_assembler.renderPattern(patternlab.footer, {
        isPattern: true,
        patternData: pattern.patternData,
        cacheBuster: patternlab.cacheBuster
      });

      var footerHTML = pattern_assembler.renderPattern(patternlab.userFoot, {
        patternLabFoot : footerPartial
      });

      //write the compiled template to the public patterns directory
      var patternPage = headHTML + pattern.patternPartialCode + footerHTML;
      fs.outputFileSync(paths.public.patterns + pattern.patternLink, patternPage);

      //write the mustache file too
      fs.outputFileSync(paths.public.patterns + pattern.patternLink.replace('.html', pattern.fileExtension), pattern.template);

      //write the encoded version too
      fs.outputFileSync(paths.public.patterns + pattern.patternLink.replace('.html', '.markup-only.html'), pattern.patternPartialCode);
    });

    //export patterns if necessary
    pattern_exporter.export_patterns(patternlab);
  }

  return {
    version: function () {
      return getVersion();
    },
    build: function (deletePatternDir) {
      buildPatterns(deletePatternDir);
      buildFrontEnd(patternlab);
      printDebug();
    },
    help: function () {
      help();
    },
    build_patterns_only: function (deletePatternDir) {
      buildPatterns(deletePatternDir);
      printDebug();
    },
    list_starterkits: function () {
      return listStarterkits();
    },
    load_starterkit: function (starterkitName) {
      loadStarterKit(starterkitName);
    }
  };
};

// export these free functions so they're available without calling the exported
// function, for use in reducing code dupe in unit tests. At least, until we
// have a better way to do this
patternlab_engine.process_all_patterns_iterative = processAllPatternsIterative;
patternlab_engine.process_all_patterns_recursive = processAllPatternsRecursive;

module.exports = patternlab_engine;
<|endoftext|>


<commit_before>module.exports = {

    /**
     * Returns the amount of friendly creeps with the given role in the given room.
     *
     * @param room The room of interest
     * @param role The name of the role the counted creeps must have,
     * or any falsy value to count all friendly creeps
     * @returns {int}
     */
    countCreeps: function (room, role) {
        return room.find(FIND_MY_CREEPS, {
            filter: creep => !role || creep.memory.role == role
        }).length;
    },

    /**
     * Returns the closest spawn, extension, storage or tower from the given
     * position that isn't already at full energy capacity.
     *
     * @param position The position to use as the source of the search
     * @returns {Structure} The closest structure, or null if no suitable
     * structure was found
     */
    findClosestEnergyDropOff: function (position) {
        return position.findClosestByPath(FIND_MY_STRUCTURES, {
            filter: structure => {
                return ((structure.structureType == STRUCTURE_EXTENSION ||
                        structure.structureType == STRUCTURE_SPAWN ||
                        structure.structureType == STRUCTURE_TOWER) &&
                        structure.energy < structure.energyCapacity) ||
                        (structure.structureType == STRUCTURE_STORAGE &&
                        _.sum(structure.store) < structure.storeCapacity);
            }
        });
    }
};<commit_msg>Added a missing require()<commit_after>var _ = require('lodash');

module.exports = {

    /**
     * Returns the amount of friendly creeps with the given role in the given room.
     *
     * @param room The room of interest
     * @param role The name of the role the counted creeps must have,
     * or any falsy value to count all friendly creeps
     * @returns {int}
     */
    countCreeps: function (room, role) {
        return room.find(FIND_MY_CREEPS, {
            filter: creep => !role || creep.memory.role == role
        }).length;
    },

    /**
     * Returns the closest spawn, extension, storage or tower from the given
     * position that isn't already at full energy capacity.
     *
     * @param position The position to use as the source of the search
     * @returns {Structure} The closest structure, or null if no suitable
     * structure was found
     */
    findClosestEnergyDropOff: function (position) {
        return position.findClosestByPath(FIND_MY_STRUCTURES, {
            filter: structure => {
                return ((structure.structureType == STRUCTURE_EXTENSION ||
                        structure.structureType == STRUCTURE_SPAWN ||
                        structure.structureType == STRUCTURE_TOWER) &&
                        structure.energy < structure.energyCapacity) ||
                        (structure.structureType == STRUCTURE_STORAGE &&
                        _.sum(structure.store) < structure.storeCapacity);
            }
        });
    }
};<|endoftext|>


<commit_before>var objToString = Object.prototype.toString
  , isObject
  , isArray
  , extend
  , extendClass
  , extendFunction
  , each
  , deepCopy;

var keysFunc = Object.keys || function(obj) {
  if (typeof(obj) !== "object")
    return [];

  var keys = [];
  for (var key in obj)
    if (obj.hasOwnProperty(key))
      keys.push(key);

  return keys;
};

var resolveChain = function(defOld, defNew) {
  return function() {
    defOld.apply(this, arguments);
    defNew.apply(this, arguments);
  }
};

var createAssigner = function(resolver, executeInit) {
  return function(obj) {
    var length = arguments.length;

    if (length < 2 || obj == null)
      return obj;

    for (var index = 1; index < length; index++) {
      var source = arguments[index],
          keys = keysFunc(source),
          l = keys.length;
      for (var i = 0; i < l; i++) {
        var key = keys[i];
        if (executeInit && key === "initialize") {
          source[key].apply(obj);
        }
        else {
          if (resolver && key === "initialize" && obj[key] !== void 0)
            obj[key] = resolver(obj[key], source[key]);
          else
            obj[key] = source[key];
        }
      }
    }
    return obj;
  };
};

exports.EventEmitter = require('eventemitter3');

exports.isObject = isObject = function(obj) {
  var type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
};

exports.isFunction = function(value) {
  return typeof value === 'function';
};

exports.isArray = isArray = function(obj) {
  return isObject(obj) && objToString.call(obj) === "[object Array]";
};

exports.isPlainObject = function(obj) {
  return typeof(obj) === "object" && objToString.call(obj) === "[object Object]";
};

exports.extend = extend = createAssigner();
exports.extendClass = extendClass = createAssigner(resolveChain);
exports.extendFunction = extendFunction = createAssigner(resolveChain, true);

exports.each = each = function(obj, iteratee) {
  var i, length;
  if (typeof(obj) === "array") {
    for (i = 0, length = obj.length; i < length; i++) {
      iteratee(obj[i], i, obj);
    }
  } else {
    var keys = keysFunc(obj);
    for (i = 0, length = keys.length; i < length; i++) {
      iteratee(obj[keys[i]], keys[i], obj);
    }
  }
  return obj;
}

exports.any = function(obj, predicate) {
  var i, length;
  if (typeof(obj) === "array") {
    for (i = 0, length = obj.length; i < length; i++) {
      if (predicate(obj[i], i, obj))
        return true;
    }
  } else {
    var keys = keysFunc(obj);
    for (i = 0, length = keys.length; i < length; i++) {
      if (predicate(obj[keys[i]], keys[i], obj))
        return true;
    }
  }
  return false;
};

exports.map = function(obj, iteratee) {
  var keys = !isArray(obj) && keysFunc(obj)
    , length = (keys || obj).length
    , results = Array(length);
  for (var index = 0; index < length; index++) {
    var currentKey = keys ? keys[index] : index;
    results[index] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
};

exports.deepCopy = deepCopy = function(obj) {
  if (objToString.call(obj) === '[object Array]') {
    var out = []
      , i = 0
      , length = obj.length;
    for ( ; i < length; i++ ) {
      out[i] = deepCopy(obj[i]);
    }
    return out;
  }
  else if (typeof obj === 'object') {
    var out = {}
      , i = 0
      , keys = keysFunc(obj)
      , length = keys.length;
    for ( ; i < length; i++) {
      out[i] = deepCopy(obj[i]);
    }
    return out;
  }
  return obj;
}

exports.capitalize = function(string){
  return string.charAt(0).toUpperCase()+string.slice(1);
};

exports.nextTick = function(callback) {
  setTimeout(callback, 0);
};

exports.defineClass = function() {
  var Class = function() {
    if (this.initialize) {
      this.initialize.apply(this, arguments);
    }
  };

  each(arguments, function(definition, index) {
    extendClass(Class.prototype, definition);
  });

  return Class;
}

// TODO: Temporary
exports.log = function(zone, method, msg) {
  if (msg) {
    console.log('%c%s%c::%c%s%c - %s',
                'font-weight: bold;', zone,
                'font-weight:normal;',
                'font-weight:bold;', method,
                'font-weight:normal;', msg.toString());
  }
  else {
    console.log('%c%s%c::%c%s',
                'font-weight: bold;', zone,
                'font-weight:normal;',
                'font-weight:bold;', method);
  }
}
<commit_msg>Expose keysFor utils method<commit_after>var objToString = Object.prototype.toString
  , isObject
  , isArray
  , extend
  , extendClass
  , extendFunction
  , each
  , deepCopy
  , keysFor;

exports.keysFor = keysFor = Object.keys || function(obj) {
  if (typeof(obj) !== "object")
    return [];

  var keys = [];
  for (var key in obj)
    if (obj.hasOwnProperty(key))
      keys.push(key);

  return keys;
};

var resolveChain = function(defOld, defNew) {
  return function() {
    defOld.apply(this, arguments);
    defNew.apply(this, arguments);
  }
};

var createAssigner = function(resolver, executeInit) {
  return function(obj) {
    var length = arguments.length;

    if (length < 2 || obj == null)
      return obj;

    for (var index = 1; index < length; index++) {
      var source = arguments[index],
          keys = keysFor(source),
          l = keys.length;
      for (var i = 0; i < l; i++) {
        var key = keys[i];
        if (executeInit && key === "initialize") {
          source[key].apply(obj);
        }
        else {
          if (resolver && key === "initialize" && obj[key] !== void 0)
            obj[key] = resolver(obj[key], source[key]);
          else
            obj[key] = source[key];
        }
      }
    }
    return obj;
  };
};

exports.EventEmitter = require('eventemitter3');

exports.isObject = isObject = function(obj) {
  var type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
};

exports.isFunction = function(value) {
  return typeof value === 'function';
};

exports.isArray = isArray = function(obj) {
  return isObject(obj) && objToString.call(obj) === "[object Array]";
};

exports.isPlainObject = function(obj) {
  return typeof(obj) === "object" && objToString.call(obj) === "[object Object]";
};

exports.extend = extend = createAssigner();
exports.extendClass = extendClass = createAssigner(resolveChain);
exports.extendFunction = extendFunction = createAssigner(resolveChain, true);

exports.each = each = function(obj, iteratee) {
  var i, length;
  if (typeof(obj) === "array") {
    for (i = 0, length = obj.length; i < length; i++) {
      iteratee(obj[i], i, obj);
    }
  } else {
    var keys = keysFor(obj);
    for (i = 0, length = keys.length; i < length; i++) {
      iteratee(obj[keys[i]], keys[i], obj);
    }
  }
  return obj;
}

exports.any = function(obj, predicate) {
  var i, length;
  if (typeof(obj) === "array") {
    for (i = 0, length = obj.length; i < length; i++) {
      if (predicate(obj[i], i, obj))
        return true;
    }
  } else {
    var keys = keysFor(obj);
    for (i = 0, length = keys.length; i < length; i++) {
      if (predicate(obj[keys[i]], keys[i], obj))
        return true;
    }
  }
  return false;
};

exports.map = function(obj, iteratee) {
  var keys = !isArray(obj) && keysFor(obj)
    , length = (keys || obj).length
    , results = Array(length);
  for (var index = 0; index < length; index++) {
    var currentKey = keys ? keys[index] : index;
    results[index] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
};

exports.deepCopy = deepCopy = function(obj) {
  if (objToString.call(obj) === '[object Array]') {
    var out = []
      , i = 0
      , length = obj.length;
    for ( ; i < length; i++ ) {
      out[i] = deepCopy(obj[i]);
    }
    return out;
  }
  else if (typeof obj === 'object') {
    var out = {}
      , i = 0
      , keys = keysFor(obj)
      , length = keys.length;
    for ( ; i < length; i++) {
      out[i] = deepCopy(obj[i]);
    }
    return out;
  }
  return obj;
}

exports.capitalize = function(string){
  return string.charAt(0).toUpperCase()+string.slice(1);
};

exports.nextTick = function(callback) {
  setTimeout(callback, 0);
};

exports.defineClass = function() {
  var Class = function() {
    if (this.initialize) {
      this.initialize.apply(this, arguments);
    }
  };

  each(arguments, function(definition, index) {
    extendClass(Class.prototype, definition);
  });

  return Class;
}

// TODO: Temporary
exports.log = function(zone, method, msg) {
  if (msg) {
    console.log('%c%s%c::%c%s%c - %s',
                'font-weight: bold;', zone,
                'font-weight:normal;',
                'font-weight:bold;', method,
                'font-weight:normal;', msg.toString());
  }
  else {
    console.log('%c%s%c::%c%s',
                'font-weight: bold;', zone,
                'font-weight:normal;',
                'font-weight:bold;', method);
  }
}
<|endoftext|>


<commit_before>import humps from 'humps'
import omitBy from 'lodash/omitBy'
import isUndefined from 'lodash/isUndefined'
import overlap from 'lodash/intersection'
import attempt from 'lodash/attempt'
import isError from 'lodash/isError'
import Cookies from 'js-cookie'

export { default as get } from 'lodash/fp/get'
export { default as set } from 'lodash/fp/set'
export { default as unset } from 'lodash/fp/unset'
export { default as compose } from 'lodash/fp/compose'
export { default as union } from 'lodash/union'

export { onLoad } from '@launchpadlab/lp-utils'

// Returns true when two arrays share common items
export function hasOverlap (arr1, arr2) {
  const overlapItems = overlap(arr1, arr2)
  return (overlapItems.length > 0)
}

// A wrapper around the humps library
// Converts all keys of the given object to camelCase
// EXCEPT keys that begin with an underscore
export function camelizeKeys (obj) {
  return humps.camelizeKeys(obj, (key, convert) =>
    /^_/.test(key) ? key : convert(key)
  )
}

// A wrapper around the humps library
// Converts all keys of the given object to lower_case
export function decamelizeKeys (obj) {
  return humps.decamelizeKeys(obj)
}

// Given an object, returns a copy of that object
// with all keys with undefined values removed
export function omitUndefined (obj) {
  return omitBy(obj, isUndefined)
}

// Parses an object from a string and returns the result
// Returns undefined if there's a parsing error
export function parseObject (str) {
  const parsedObj = attempt(() => JSON.parse(str))
  if (!isError(parsedObj)) return parsedObj
}

// Get the auth cookie used by lp_token_auth
// Returns undefined if the cookie is not set
export function getLpAuthCookie () {
  return Cookies.get('lp_auth')
}
<commit_msg>add reason for not transforming underscore keys.<commit_after>import humps from 'humps'
import omitBy from 'lodash/omitBy'
import isUndefined from 'lodash/isUndefined'
import overlap from 'lodash/intersection'
import attempt from 'lodash/attempt'
import isError from 'lodash/isError'
import Cookies from 'js-cookie'

export { default as get } from 'lodash/fp/get'
export { default as set } from 'lodash/fp/set'
export { default as unset } from 'lodash/fp/unset'
export { default as compose } from 'lodash/fp/compose'
export { default as union } from 'lodash/union'

export { onLoad } from '@launchpadlab/lp-utils'

// Returns true when two arrays share common items
export function hasOverlap (arr1, arr2) {
  const overlapItems = overlap(arr1, arr2)
  return (overlapItems.length > 0)
}

// A wrapper around the humps library
// Converts all keys of the given object to camelCase
// EXCEPT keys that begin with an underscore to
// support specific keys such as the `_error`
// key used by Redux Form to communicate errors
// that are not tied to specific form fields.
export function camelizeKeys (obj) {
  return humps.camelizeKeys(obj, (key, convert) =>
    /^_/.test(key) ? key : convert(key)
  )
}

// A wrapper around the humps library
// Converts all keys of the given object to lower_case
export function decamelizeKeys (obj) {
  return humps.decamelizeKeys(obj)
}

// Given an object, returns a copy of that object
// with all keys with undefined values removed
export function omitUndefined (obj) {
  return omitBy(obj, isUndefined)
}

// Parses an object from a string and returns the result
// Returns undefined if there's a parsing error
export function parseObject (str) {
  const parsedObj = attempt(() => JSON.parse(str))
  if (!isError(parsedObj)) return parsedObj
}

// Get the auth cookie used by lp_token_auth
// Returns undefined if the cookie is not set
export function getLpAuthCookie () {
  return Cookies.get('lp_auth')
}
<|endoftext|>


<commit_before>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > 336)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*336));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});
});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var rank = Math.round(x/336 * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.splice(index,1);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			location.href = url;
		}
	}
}
function twitterIni(){
        var username =  "***REMOVED***",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}
<commit_msg>twitter fixy<commit_after>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > 336)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*336));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});
});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var rank = Math.round(x/336 * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.splice(index,1);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			location.href = url;
		}
	}
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

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


<commit_before>/*
	all the proprieties
*/
var _ = require('underscore');

/// coordinates systems

var cartCS = {
	start: {
		x: 0,
		y: 0
	},
	end: {
		x: 0,
		y: 0
	}
};

var polarCS = {
	radius: {
		x: 0,
		y: 0
	},
	center: {
		x: 0,
		y: 0
	}
};

///////////
// major / minor props
/////////////

var m = {};

// that's a major
m.Grid = {
	show: false,
	color: 'LightGray',
	width: 0.5,
	length: 0,
	cart: cartCS,
	polar: polarCS
};

// that's a major
m.Tick = {
	show: true,
	where: {
		x: 0,
		y: 0
	},
	labelDir: {
		x: 0,
		y: 1
	},
	width: 1,
	length: 15,
	out: 0.25, // proportion that is outside (-dir)
	color: 'black',
	labelOffset: 0,
	labelize: null,
	label: '',
	labelFSize: 10,
	labelColor: 'black'
};

//
m.Axe = {
	ticks: {
		major: m.Tick,
		minor: _.extendOwn(_.extend({},m.Tick),{
			show: false,
			length: 7,
			out: 0,
			color: 'gray',
			labelOffset: 3.75,
		})
	},
	grid: {
		major: m.Grid,
		minor: _.extendOwn(_.extend({},m.Grid),{
			width: 0.3
		})
	},
	tickLabels: [], //{coord: where, label: ''}, coord in ds
	color:     'black',
	width:      1,
	label:      '',
	labelOffset: {
		x: 40,
		y: 40
	},
	labelFSize: 20,
	ds:         {},
	empty:      false,
	CS:         'cart',
	// in c coordinate
	origin: {
		x: 0,
		y: 0
	},
	// vector of axis
	dir: {
		x: 1,
		y: 0
	},
	// in cs !! y is top to bottom
	labelDir: {
		x: 0,
		y: 1
	},
	// for ticklabel formatting
	comFac: 1
};

m.Axes = {
	abs: [
		_.extend({}, m.Axe,{placement: 'bottom', partner: 0})
	],
	ord: [
		_.extend({}, m.Axe,{placement: 'left', partner: 0})
	],
	CS: 'cart'
};

///
m.Graph = {
	// general
	name: 'G',
	height: 800,	// defines the universe's height
	width:	400,	// defines the universe's width
	foreground: undefined,
	background: undefined,
	title: '',
	titleFSize: 30,
	// data
	data: [{
		type: 'Plain', // Plain, Bars, yBars, Stairs
		series:[{x:0, y:0}], // x, y
		stacked: undefined, // x || y || null
		coordSys: 'cart', // cart || polar
		ord: {
			axis: 'left', // 'left' || 'right'
			type: 'number' // 'number' || 'date' || 'label'
		},
		abs: {
			axis: 'bottom', // 'bottom' || 'top'
			type: 'number' // 'number' || 'date' || 'label'
		}
	}],
	graphProps: [{
		color: 'black',
		mark: true,
		markSize: 3,
		markColor: undefined, // if undefined = color
		onlyMarks: false,
		offset: { // offset, in dataspace
			x: 0,
			y: 0
		},
		span: 0, //
		shader: null, //playing with colors
		process: null //playing with data {dir: x || y, type: 'histogram'}
	}],
	// axis
	axisProps: m.Axes,
	axis: undefined,	// b = bottom, l = left, t = top, r = right, any combination; overrides xaxis and yaxis
	// shorcuts for easyness of use, overrides
	// settings in axisProps
	// label of axis
	xLabel: '',
	yLabel: '',
	xLabelFSize: null,
	yLabelFSize: null,
	// axis
	xaxis: '',	// bottom || top
	yaxis: '',		// left || right
	// to force definition
	xmin: undefined,
	xmax: undefined,
	ymin: undefined,
	ymax: undefined,
	// margins
	axisMargin: {left: 10, bottom: 10, right: 10, top: 10}, // left, bottom, right, top
	outerMargin: {} // left, bottom, right, top
};

module.exports = m;
<commit_msg>Default props for graph in proprieties, a getter to fetch correct props<commit_after>/*
	all the proprieties
*/
var _ = require('underscore');

// defaults for graphs
var graph = {};
graph.common = {
	color: 'black',
	width: 1,
	fill: 'none',
	// mark props, explicit at heigh level
	// overwritten if present in markProps
	mark: true,
	markColor: undefined,
	markSize: 3,
	markType: 'dot',
	onlyMarks: false,
	// contains low-level description,
	// i.e. specific things like radius
	// for a dot, or anything.
	markProps: {},
	points: [],
	dsx: {}, // see space-mgr for details
	dsy: {},  // see space-mgr for details
	shader: null, //playing with colors
	process: null //playing with data {dir: x || y, type: 'histogram'}
};

graph.Plain = graph.common;

graph.BarChart = {
	dsx: {}, // see space-mgr for details
	dsy: {}, // see space-mgr for details
	color: 'none',
	width: 0,
	span: 0.5, // in dataSpace
	dir: {
		x: false,
		y: true
	},
	points: [],
	markColor: undefined,
	markType: 'bar',
	markProps: {
		width: 0,
		draw: false
	},
	offset: {x: 0, y: 0}
};

graph.Stairs = graph.common;

/// coordinates systems

var cartCS = {
	start: {
		x: 0,
		y: 0
	},
	end: {
		x: 0,
		y: 0
	}
};

var polarCS = {
	radius: {
		x: 0,
		y: 0
	},
	center: {
		x: 0,
		y: 0
	}
};

///////////
// major / minor props
/////////////

var m = {};

// that's a major
m.Grid = {
	show: false,
	color: 'LightGray',
	width: 0.5,
	length: 0,
	cart: cartCS,
	polar: polarCS
};

// that's a major
m.Tick = {
	show: true,
	where: {
		x: 0,
		y: 0
	},
	labelDir: {
		x: 0,
		y: 1
	},
	width: 1,
	length: 15,
	out: 0.25, // proportion that is outside (-dir)
	color: 'black',
	labelOffset: 0,
	labelize: null,
	label: '',
	labelFSize: 10,
	labelColor: 'black'
};

//
m.Axe = {
	ticks: {
		major: m.Tick,
		minor: _.extendOwn(_.extend({},m.Tick),{
			show: false,
			length: 7,
			out: 0,
			color: 'gray',
			labelOffset: 3.75,
		})
	},
	grid: {
		major: m.Grid,
		minor: _.extendOwn(_.extend({},m.Grid),{
			width: 0.3
		})
	},
	show: true,
	// to force locally definition
	min: undefined,
	max: undefined,
	tickLabels: [], //{coord: where, label: ''}, coord in ds
	color:     'black',
	width:      1,
	label:      '',
	labelOffset: {
		x: 40,
		y: 40
	},
	labelFSize: 20,
	ds:         {},
	empty:      false,
	CS:         'cart',
	// in c coordinate
	origin: {
		x: 0,
		y: 0
	},
	// vector of axis
	dir: {
		x: 1,
		y: 0
	},
	// in cs !! y is top to bottom
	labelDir: {
		x: 0,
		y: 1
	},
	// for ticklabel formatting
	comFac: 1
};

m.Axes = {
	abs: [
		_.extend({}, m.Axe,{placement: 'bottom', partner: 0})
	],
	ord: [
		_.extend({}, m.Axe,{placement: 'left', partner: 0})
	],
	CS: 'cart'
};

///
m.Graph = {
	// general
	name: 'G',
	height: 800,	// defines the universe's height
	width:	400,	// defines the universe's width
	foreground: undefined,
	background: undefined,
	title: '',
	titleFSize: 30,
	// data
	data: [{
		type: 'Plain', // Plain, Bars, yBars, Stairs
		series:[{x:0, y:0}], // x, y
		stacked: undefined, // x || y || null
		coordSys: 'cart', // cart || polar
		ord: {
			axis: 'left', // 'left' || 'right'
			type: 'number' // 'number' || 'date' || 'label'
		},
		abs: {
			axis: 'bottom', // 'bottom' || 'top'
			type: 'number' // 'number' || 'date' || 'label'
		}
	}],
	graphProps: [
		graph.common
	],
	// axis
	axisProps: m.Axes,
	axis: undefined,	// b = bottom, l = left, t = top, r = right, any combination; overrides xaxis and yaxis
	// shorcuts for easyness of use, overrides
	// settings in axisProps
	// label of axis
	xLabel: '',
	yLabel: '',
	xLabelFSize: null,
	yLabelFSize: null,
	// axis
	xaxis: '',	// bottom || top
	yaxis: '',		// left || right
	// margins
	axisMargin: {left: 10, bottom: 10, right: 10, top: 10}, // left, bottom, right, top
	outerMargin: {} // left, bottom, right, top
};

m.defaults = function(key){
	return graph[key];
};

module.exports = m;
<|endoftext|>