<commit_before>define(openhmis.url.backboneBase + "js/openhmis",
	[
		openhmis.url.backboneBase + 'js/lib/jquery',
		openhmis.url.backboneBase + 'js/lib/underscore',
		openhmis.url.backboneBase + 'js/lib/backbone',
		openhmis.url.backboneBase + 'js/lib/i18n',
		openhmis.url.backboneBase + 'js/lib/backbone-forms'
	],
	function($, _, Backbone, __) {

		// Use <? ?> for template tags.
		_.templateSettings = {
			evaluate:  /<\?(.+?)\?>/g,
			interpolate: /<\?=(.+?)\?>/g
		};

		var openhmis = window.openhmis || {};
		openhmis.templates = {};

		openhmis.url.getPage = function(moduleBaseName) {
			return openhmis.url.page + openhmis.url[moduleBaseName];
		}

		//TODO: Better system for identifying specific errors
		openhmis.error = function(model, resp) {
			var handleErrorResp = function(resp) {
				var o = (typeof resp === "string") ? $.parseJSON(resp).error : resp;
				if (o.detail.indexOf("ContextAuthenticationException") !== -1) {
					alert(__("Your session has timed out.  You will be redirected to the login page."));
					window.location.reload();
				}
				else if (o.detail.indexOf("AccessControlException") !== -1) {
					if (o.detail.indexOf("refund") !== -1) {
						alert(__("The total of the bill is negative and you do not have the required privileges to process a refund.\n\nPlease contact your supervisor about processing refunds."));
					}
					else if (o.detail.indexOf("adjust") !== -1) {
						alert(__("You do not have the required privileges to adjust a bill.\n\nPlease contact your supervisor about adjusting a bill."));
					}
				}
				else if (o.message.indexOf("no rounding item ID") !== -1) {
					alert(__(o.message + "\n\nPlease specify a rounding item or disable rounding."));
				}
				else {
					console.log("Message: " + o.message + "\n" + "Code: " + o.code + "\n" + "Detail: " + o.detail);
					var firstLfPos = o.detail.indexOf('\n');
					if (firstLfPos !== -1)
						o.detail = o.detail.substring(0, firstLfPos);
					alert('An error occurred during the request.\n\n' + o.message + '\n\nCode: ' + o.code + '\n\n' + o.detail);
				}
			}
			if (!(model instanceof Backbone.Model)) {
				if (model.responseText)
					handleErrorResp(model.responseText);
				else
					handleErrorResp(model);
			}
			else if (resp !== undefined) {
				handleErrorResp(resp.responseText);
				//var str = "";
				//for (var i in resp) {
				//	if (str.length > 0) str += ",\n";
				//	str += i + ": " + resp[i];
				//}
				//alert(str);
			}
		}

		openhmis.getQueryStringParameter = function(name)
		{
			name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
			var regexS = "[\\?&]" + name + "=([^&#]*)";
			var regex = new RegExp(regexS);
			var results = regex.exec(window.location.search);
			if(results == null)
				  return "";
			else
				return decodeURIComponent(results[1].replace(/\+/g, " "));
		}

		openhmis.addQueryStringParameter = function(queryString, parameter) {
			return queryString ? queryString + "&" + parameter : parameter;
		}

		openhmis.padZero = function(n) { return n < 10 ? "0" + n : n; }
		openhmis.pad2Zeros = function(n) {
			if (n < 100) n = '0' + n;
			if (n < 10) n = '0' + n;
			return n;
		}
		openhmis.dateFormat = function(date, includeTime) {
			var padZero = openhmis.padZero;
			var day = date.getDate();
			var month = date.getMonth() + 1;
			var year = date.getFullYear();
			day = padZero(day);
			month = padZero(month);
			var strDate = day + '-' + month + '-' + year;
			if (includeTime === true) {
				strDate += " " + padZero(date.getHours())
					+ ":" + padZero(date.getMinutes());
			}
			return strDate;
		}

		openhmis.dateFormatLocale = function(date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleDateString() : "";
		}
		openhmis.dateTimeFormatLocale = function(date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleString() : "";
		}
		openhmis.iso8601Date = function(d) {
			var padZero = openhmis.padZero;
			var pad2Zeros = openhmis.pad2Zeros;
			return d.getUTCFullYear() + '-' +  padZero(d.getUTCMonth() + 1) + '-' + padZero(d.getUTCDate()) + 'T' + padZero(d.getUTCHours()) + ':' +  padZero(d.getUTCMinutes()) + ':' + padZero(d.getUTCSeconds()) + '.' + pad2Zeros(d.getUTCMilliseconds()) + '+0000';
		}

		openhmis.tryParsingFuzzyDate = function(fuzzyString) {
			var numberOfSomething = /^([0-9]+)\s?(\w+)(\s+.*)?$/;
			var matches = fuzzyString.match(numberOfSomething);
			var number;
			if (matches && matches[2] && !isNaN(number = parseInt(matches[1]))) {
				matches[1] = number;
				return matches;
			}
			return null;
		}

		openhmis.toFuzzyDate = function(seconds) {
			var timeChunks = [
				[31536000, __("year")],
				[604800, __("week")],
				[86400, __("day")]
			];
			for (var i in timeChunks) {
				var chunk = timeChunks[i]
				var numberOfChunks;
				if ((numberOfChunks = Math.floor(seconds / chunk[0])) >= 1) {
					var string = numberOfChunks === 1
						? __("%d %s", numberOfChunks, chunk[1])
						: __("%d %s", numberOfChunks, openhmis.pluralize(chunk[1]));
					var remainder = seconds % chunk[0];
					if (remainder > 0)
						return string + " " + openhmis.toFuzzyDate(remainder);
					else
						return string;
				}
			}
			return null;
		}

		openhmis.fromFuzzyDate = function(fuzzyString, carry) {
			var timeChunks = [
				["year", 31536000],
				["week", 604800],
				["day", 86400]
			];
			var matches = openhmis.tryParsingFuzzyDate($.trim(fuzzyString))
			if (matches) {
				for (var i in timeChunks) {
					var chunk = timeChunks[i];
					if (matches[2] === chunk[0] || matches[2] === (chunk[0] + "s")) {
						var seconds = matches[1] * chunk[1];
						if (matches[3])
							return openhmis.fromFuzzyDate(matches[3], seconds + (carry || 0));
						else
							return seconds + (carry || 0);
					}
				}
			}
			return carry;
		}

		openhmis.validationMessage = function(parentEl, message, inputEl) {
			if ($(parentEl).length > 1) parentEl = $(parentEl)[0];
			if ($(parentEl).find('.validation').length > 0) return;
			var prevPosition = $(parentEl).css("position");
			$(parentEl).css("position", "relative");
			var el = $('

');
			el.text(message);
			$(parentEl).append(el);
			if (inputEl !== undefined) $(inputEl).focus();
			setTimeout(function() {
				$(el).remove();
				if (prevPosition !== "static")
					$(parentEl).css("position", prevPosition);
			}, 5000);
		},

		openhmis.round = function(val, nearest, mode) {
			nearest = nearest ? nearest : 1;
			if (nearest === 0) return val;
			var factor = 1 / nearest;
			switch (mode) {
				case 'FLOOR':
					return Math.floor(val * factor) / factor;
				case 'CEILING':
					return Math.ceil(val * factor) / factor;
				default:
					return Math.round(val * factor) / factor;
			}
		},

		openhmis.isNumeric = function(n) {
			return !isNaN(parseFloat(n)) && isFinite(n);
		}

		openhmis.toCamelCase = function(str, firstCapital) {
			firstCapital = firstCapital !== undefined ? firstCapital : false;
			str.replace(
				/\b(\S)(\S*)/g,
				function(match, first, rest) {
					return first.toUpperCase() + rest.toLowerCase();
				}
			);
			if (!firstCapital)
				str = str.charAt(0).toLowerCase() + str.substring(1);
			return str;
		}

		// Use uuid for id
		Backbone.Model.prototype.idAttribute = 'uuid';

		/**
		 * Template helper function
		 *
		 * Fetches a template from a remote URI unless it has been previously fetched
		 * and cached.
		 */
		Backbone.View.prototype.tmplFileRoot = openhmis.url.resources;
		Backbone.View.prototype.getTemplate = function(tmplFile, tmplSelector) {
			tmplFile = tmplFile ? tmplFile : this.tmplFile;
			tmplSelector = tmplSelector ? tmplSelector : this.tmplSelector;
			var view = this;
			if (openhmis.templates[tmplFile] === undefined) {
				var uri = view.tmplFileRoot === undefined ? tmplFile : view.tmplFileRoot + tmplFile;
				$.ajax({
					url: uri,
					async: false,
					dataType: "html",
					success: function(data, status, jq) {
						openhmis.templates[tmplFile] = $("
").html(data);
					}
				});
			}
			var template = _.template($(openhmis.templates[tmplFile]).find(tmplSelector).html());
			var augmentedTemplate = function(context) {
				if (context !== undefined) {
					context.__ = context.__ ? context.__ : __;
					context.urls = context.urls ? context.urls : openhmis.url;
					context.helpers = context.helpers ? context.helpers : Backbone.Form.helpers
					context.pluralize = openhmis.pluralize;
				}
				return template.call(this, context);
			}
			return augmentedTemplate;
		}

		return openhmis;
	}
)
<commit_msg>Shored up the formatting of the openhmis file.<commit_after>define(openhmis.url.backboneBase + "js/openhmis",
	[
		openhmis.url.backboneBase + 'js/lib/jquery',
		openhmis.url.backboneBase + 'js/lib/underscore',
		openhmis.url.backboneBase + 'js/lib/backbone',
		openhmis.url.backboneBase + 'js/lib/i18n',
		openhmis.url.backboneBase + 'js/lib/backbone-forms'
	],
	function($, _, Backbone, __) {

		// Use <? ?> for template tags.
		_.templateSettings = {
			evaluate:  /<\?(.+?)\?>/g,
			interpolate: /<\?=(.+?)\?>/g
		};

		var openhmis = window.openhmis || {};
		openhmis.templates = {};

		openhmis.url.getPage = function (moduleBaseName) {
			return openhmis.url.page + openhmis.url[moduleBaseName];
		};

		//TODO: Better system for identifying specific errors
		openhmis.error = function (model, resp) {
			var handleErrorResp = function (resp) {
				var o = (typeof resp === "string") ? $.parseJSON(resp).error : resp;
				if (o.detail.indexOf("ContextAuthenticationException") !== -1) {
					alert(__("Your session has timed out.  You will be redirected to the login page."));
					window.location.reload();
				}
				else if (o.detail.indexOf("AccessControlException") !== -1) {
					if (o.detail.indexOf("refund") !== -1) {
						alert(__("The total of the bill is negative and you do not have the required privileges to process a refund.\n\nPlease contact your supervisor about processing refunds."));
					}
					else if (o.detail.indexOf("adjust") !== -1) {
						alert(__("You do not have the required privileges to adjust a bill.\n\nPlease contact your supervisor about adjusting a bill."));
					}
				}
				else if (o.message.indexOf("no rounding item ID") !== -1) {
					alert(__(o.message + "\n\nPlease specify a rounding item or disable rounding."));
				}
				else {
					console.log("Message: " + o.message + "\n" + "Code: " + o.code + "\n" + "Detail: " + o.detail);
					var firstLfPos = o.detail.indexOf('\n');
					if (firstLfPos !== -1)
						o.detail = o.detail.substring(0, firstLfPos);
					alert('An error occurred during the request.\n\n' + o.message + '\n\nCode: ' + o.code + '\n\n' + o.detail);
				}
			};

			if (!(model instanceof Backbone.Model)) {
				if (model.responseText)
					handleErrorResp(model.responseText);
				else
					handleErrorResp(model);
			} else if (resp !== undefined) {
				handleErrorResp(resp.responseText);
				//var str = "";
				//for (var i in resp) {
				//	if (str.length > 0) str += ",\n";
				//	str += i + ": " + resp[i];
				//}
				//alert(str);
			}
		};

		openhmis.getQueryStringParameter = function (name) {
			name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
			var regexS = "[\\?&]" + name + "=([^&#]*)";
			var regex = new RegExp(regexS);
			var results = regex.exec(window.location.search);
			if (results == null)
				return "";
			else
				return decodeURIComponent(results[1].replace(/\+/g, " "));
		};

		openhmis.addQueryStringParameter = function (queryString, parameter) {
			return queryString ? queryString + "&" + parameter : parameter;
		};

		openhmis.padZero = function (n) {
			return n < 10 ? "0" + n : n;
		};

		openhmis.pad2Zeros = function (n) {
			if (n < 100) n = '0' + n;
			if (n < 10) n = '0' + n;
			return n;
		};

		openhmis.dateFormat = function (date, includeTime) {
			var padZero = openhmis.padZero;
			var day = date.getDate();
			var month = date.getMonth() + 1;
			var year = date.getFullYear();
			day = padZero(day);
			month = padZero(month);
			var strDate = day + '-' + month + '-' + year;
			if (includeTime === true) {
				strDate += " " + padZero(date.getHours())
					+ ":" + padZero(date.getMinutes());
			}
			return strDate;
		};

		openhmis.dateFormatLocale = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleDateString() : "";
		};

		openhmis.dateTimeFormatLocale = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleString() : "";
		};

		openhmis.iso8601Date = function (d) {
			var padZero = openhmis.padZero;
			var pad2Zeros = openhmis.pad2Zeros;
			return d.getUTCFullYear() + '-' + padZero(d.getUTCMonth() + 1) + '-' + padZero(d.getUTCDate()) + 'T' + padZero(d.getUTCHours()) + ':' + padZero(d.getUTCMinutes()) + ':' + padZero(d.getUTCSeconds()) + '.' + pad2Zeros(d.getUTCMilliseconds()) + '+0000';
		};

		openhmis.tryParsingFuzzyDate = function (fuzzyString) {
			var numberOfSomething = /^([0-9]+)\s?(\w+)(\s+.*)?$/;
			var matches = fuzzyString.match(numberOfSomething);
			var number;
			if (matches && matches[2] && !isNaN(number = parseInt(matches[1]))) {
				matches[1] = number;
				return matches;
			}
			return null;
		};

		openhmis.toFuzzyDate = function (seconds) {
			var timeChunks = [
				[31536000, __("year")],
				[604800, __("week")],
				[86400, __("day")]
			];
			for (var i in timeChunks) {
				var chunk = timeChunks[i]
				var numberOfChunks;
				if ((numberOfChunks = Math.floor(seconds / chunk[0])) >= 1) {
					var string = numberOfChunks === 1
						? __("%d %s", numberOfChunks, chunk[1])
						: __("%d %s", numberOfChunks, openhmis.pluralize(chunk[1]));
					var remainder = seconds % chunk[0];
					if (remainder > 0)
						return string + " " + openhmis.toFuzzyDate(remainder);
					else
						return string;
				}
			}
			return null;
		};

		openhmis.fromFuzzyDate = function (fuzzyString, carry) {
			var timeChunks = [
				["year", 31536000],
				["week", 604800],
				["day", 86400]
			];
			var matches = openhmis.tryParsingFuzzyDate($.trim(fuzzyString))
			if (matches) {
				for (var i in timeChunks) {
					var chunk = timeChunks[i];
					if (matches[2] === chunk[0] || matches[2] === (chunk[0] + "s")) {
						var seconds = matches[1] * chunk[1];
						if (matches[3])
							return openhmis.fromFuzzyDate(matches[3], seconds + (carry || 0));
						else
							return seconds + (carry || 0);
					}
				}
			}

			return carry;
		};

		openhmis.validationMessage = function (parentEl, message, inputEl) {
			if ($(parentEl).length > 1) parentEl = $(parentEl)[0];
			if ($(parentEl).find('.validation').length > 0) return;
			var prevPosition = $(parentEl).css("position");
			$(parentEl).css("position", "relative");
			var el = $('

');
			el.text(message);
			$(parentEl).append(el);
			if (inputEl !== undefined) $(inputEl).focus();
			setTimeout(function () {
				$(el).remove();
				if (prevPosition !== "static")
					$(parentEl).css("position", prevPosition);
			}, 5000);
		};

		openhmis.round = function (val, nearest, mode) {
			nearest = nearest ? nearest : 1;
			if (nearest === 0) return val;
			var factor = 1 / nearest;
			switch (mode) {
				case 'FLOOR':
					return Math.floor(val * factor) / factor;
				case 'CEILING':
					return Math.ceil(val * factor) / factor;
				default:
					return Math.round(val * factor) / factor;
			}
		};

		openhmis.isNumeric = function (n) {
			return !isNaN(parseFloat(n)) && isFinite(n);
		};

		openhmis.toCamelCase = function (str, firstCapital) {
			firstCapital = firstCapital !== undefined ? firstCapital : false;
			str.replace(
				/\b(\S)(\S*)/g,
				function (match, first, rest) {
					return first.toUpperCase() + rest.toLowerCase();
				}
			);
			if (!firstCapital)
				str = str.charAt(0).toLowerCase() + str.substring(1);
			return str;
		};

		// Use uuid for id
		Backbone.Model.prototype.idAttribute = 'uuid';

		/**
		 * Template helper function
		 *
		 * Fetches a template from a remote URI unless it has been previously fetched
		 * and cached.
		 */
		Backbone.View.prototype.tmplFileRoot = openhmis.url.resources;
		Backbone.View.prototype.getTemplate = function(tmplFile, tmplSelector) {
			tmplFile = tmplFile ? tmplFile : this.tmplFile;
			tmplSelector = tmplSelector ? tmplSelector : this.tmplSelector;
			var view = this;
			if (openhmis.templates[tmplFile] === undefined) {
				var uri = view.tmplFileRoot === undefined ? tmplFile : view.tmplFileRoot + tmplFile;
				$.ajax({
					url: uri,
					async: false,
					dataType: "html",
					success: function(data, status, jq) {
						openhmis.templates[tmplFile] = $("
").html(data);
					}
				});
			}

			var template = _.template($(openhmis.templates[tmplFile]).find(tmplSelector).html());
			var augmentedTemplate = function(context) {
				if (context !== undefined) {
					context.__ = context.__ ? context.__ : __;
					context.urls = context.urls ? context.urls : openhmis.url;
					context.helpers = context.helpers ? context.helpers : Backbone.Form.helpers
					context.pluralize = openhmis.pluralize;
				}

				return template.call(this, context);
			};

			return augmentedTemplate;
		};

		return openhmis;
	}
);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import addressFormat from 'address-format';
import PhoneList from './PhoneList';
import ContactAddress from './ContactAddress';

export default class Contact extends Component {

  render() {
    const panelClass = 'panel panel-default';
    const panelId = `collapse${this.props.index}`;
    const panelIdSelector = `#collapse${this.props.index}`;
    const contactAnchorClass = 'collapsed btn-block';

    var panelContainerClass;
    // if index is 0, this is the first contact in the list, so
    // we should give it the expanded class. If it's not the first in the list,
    // give it the visually "collapsed" class
    if (!this.props.index) {
      panelContainerClass = 'panel-collapse collapse in';
    } else {
      panelContainerClass = 'panel-collapse collapse';
    }

    const faEnvelope = 'fa fa-envelope';
    const faLegal = 'fa fa-gavel';

    const fullMailingAddress = addressFormat({
      address: this.props.mailing_address.street,
      city: this.props.mailing_address.city,
      subdivision: this.props.mailing_address.state,
      postalCode: this.props.mailing_address.zip,
      countryCode: 'US'
    }).join(' ');

    const fullResidenceAddress = addressFormat({
      address: this.props.residence_address.street,
      city: this.props.residence_address.city,
      subdivision: this.props.residence_address.state,
      postalCode: this.props.residence_address.zip,
      countryCode: 'US'
    }).join(' ');

    const hasAddress = !!fullMailingAddress || !!fullResidenceAddress;
    const hasUniqueResidenceAddress = fullMailingAddress !== fullResidenceAddress;

    let address1;
    let address2;

    if (hasAddress) {
      if (hasUniqueResidenceAddress) {
          address1 = <ContactAddress title='Mailing Address' address={fullMailingAddress} />;
          address2 = <ContactAddress title='Residence Address' address={fullResidenceAddress} />;
      } else {
        address1 = <ContactAddress title='Address' address={fullMailingAddress} />;
      }
    }

    return (

              {this.props.legal_guardian && }
              {this.props.first_name} {this.props.last_name} ({this.props.relationship})

                {address1}
                {address2}
                {this.props.employer &&

                    Employer: {this.props.employer}

                }

                {this.props.email_address &&

                     {this.props.email_address}

                }
                <PhoneList phones={this.props.phones} />

    );
  }
}

Contact.propTypes = {
  index: React.PropTypes.number,
  mailing_address: React.PropTypes.shape({
    street: React.PropTypes.string,
    city: React.PropTypes.string,
    state: React.PropTypes.string,
    zip: React.PropTypes.string,
  }),
  residence_address: React.PropTypes.shape({
    street: React.PropTypes.string,
    city: React.PropTypes.string,
    state: React.PropTypes.string,
    zip: React.PropTypes.string,
  }),
  legal_guardian: React.PropTypes.bool,
  first_name: React.PropTypes.string,
  last_name: React.PropTypes.string,
  relationship: React.PropTypes.string,
  employer: React.PropTypes.string,
  email_address: React.PropTypes.string,
  phones: React.PropTypes.arrayOf(React.PropTypes.shape({
    number: React.PropTypes.string,
    type: React.PropTypes.string,
    priority: React.PropTypes.number
  }))
};
<commit_msg>Fixed a bug where if a contact only had a "residence address", then it would still show both res. and mail. labels (instead of combining them into a single "address" field)<commit_after>import React, {Component} from 'react';
import addressFormat from 'address-format';
import PhoneList from './PhoneList';
import ContactAddress from './ContactAddress';

export default class Contact extends Component {

  render() {
    const panelClass = 'panel panel-default';
    const panelId = `collapse${this.props.index}`;
    const panelIdSelector = `#collapse${this.props.index}`;
    const contactAnchorClass = 'collapsed btn-block';

    var panelContainerClass;
    // if index is 0, this is the first contact in the list, so
    // we should give it the expanded class. If it's not the first in the list,
    // give it the "collapsed" class
    if (!this.props.index) {
      panelContainerClass = 'panel-collapse collapse in';
    } else {
      panelContainerClass = 'panel-collapse collapse';
    }

    const faEnvelope = 'fa fa-envelope';
    const faLegal = 'fa fa-gavel';

    const fullMailingAddress = addressFormat({
      address: this.props.mailing_address.street,
      city: this.props.mailing_address.city,
      subdivision: this.props.mailing_address.state,
      postalCode: this.props.mailing_address.zip,
      countryCode: 'US'
    }).join(' ');

    const fullResidenceAddress = addressFormat({
      address: this.props.residence_address.street,
      city: this.props.residence_address.city,
      subdivision: this.props.residence_address.state,
      postalCode: this.props.residence_address.zip,
      countryCode: 'US'
    }).join(' ');

    const hasAddress = !!fullMailingAddress || !!fullResidenceAddress;
    const hasTwoUniqueAddresses = !!fullMailingAddress && !!fullResidenceAddress && fullMailingAddress !== fullResidenceAddress;

    let address1;
    let address2;

    if (hasAddress) {
      if (hasTwoUniqueAddresses) {
          address1 = <ContactAddress title='Mailing Address' address={fullMailingAddress} />;
          address2 = <ContactAddress title='Residence Address' address={fullResidenceAddress} />;
      } else {
        if (fullMailingAddress) {
          address1 = <ContactAddress title='Address' address={fullMailingAddress} />;
        }
        address1 = <ContactAddress title='Address' address={fullResidenceAddress} />;
      }
    }

    return (

              {this.props.legal_guardian && }
              {this.props.first_name} {this.props.last_name} ({this.props.relationship})

                {address1}
                {address2}
                {this.props.employer &&

                    Employer: {this.props.employer}

                }

                {this.props.email_address &&

                     {this.props.email_address}

                }
                <PhoneList phones={this.props.phones} />

    );
  }
}

Contact.propTypes = {
  index: React.PropTypes.number,
  mailing_address: React.PropTypes.shape({
    street: React.PropTypes.string,
    city: React.PropTypes.string,
    state: React.PropTypes.string,
    zip: React.PropTypes.string,
  }),
  residence_address: React.PropTypes.shape({
    street: React.PropTypes.string,
    city: React.PropTypes.string,
    state: React.PropTypes.string,
    zip: React.PropTypes.string,
  }),
  legal_guardian: React.PropTypes.bool,
  first_name: React.PropTypes.string,
  last_name: React.PropTypes.string,
  relationship: React.PropTypes.string,
  employer: React.PropTypes.string,
  email_address: React.PropTypes.string,
  phones: React.PropTypes.arrayOf(React.PropTypes.shape({
    number: React.PropTypes.string,
    type: React.PropTypes.string,
    priority: React.PropTypes.number
  }))
};
<|endoftext|>


<commit_before>var esprima = require('esprima');

var moduleAnalyzer = {
	analyze: function (js) {
		var analyzedJs = esprima.parse(js, { range: true });

		//console.log(JSON.stringify(analyzedJs, null, 4));
		goThroughSyntaxTree(analyzedJs.body[0]);

		if(changes.length) {
			for (var i = changes.length - 1; i >= 0; i--) {
				js = replaceCode(js, changes[i].start, changes[i].end, changes[i].newCode);
			};
		}

		return js;
	}
};

var systemVariables = ["_event", "_sessionid", "_name", "_ioprocessors", "_x"];
var changes = [];

var treeTypes = {
	"BlockStatement": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);
	},
	"FunctionExpression": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);
	},
	"FunctionDeclaration": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);
	},
	"ExpressionStatement": function (tree) {
		tree = tree.expression;
		goThroughSyntaxTree(tree);
	},
	// "VariableDeclaration": function (tree) {

	// },
	"AssignmentExpression": function (tree) {
		//Check if assignee is a system variable
		if(systemVariables.indexOf(tree.left.name) !== -1) {

			//Raise error.execution.
			changes.push({
				newCode: "this.raise({ name:\"error.execution\", data : {}});",
				start: tree.range[0],
				end: tree.range[1]
			});

			console.log(tree.left.name + ' used illegally');
		}
	}
	// ,
	// "ReturnStatement": function (tree) {

	// },
	// "CallExpression": function (tree) {

	// },
	// "IfStatement": function (tree) {

	// }
};

function goThroughSyntaxTree (tree) {
	if (Array.isArray(tree)) {
		for (var i = tree.length - 1; i >= 0; i--) {
			goThroughSyntaxTree(tree[i]);
		};
	} else if(tree.type && treeTypes[tree.type]) {
		treeTypes[tree.type](tree);
	};
}

function replaceCode (original, start, end, newCode) {
	return original.substring(0, start) + newCode + "\n" + original.substring(end, original.length);
}

module.exports = moduleAnalyzer;<commit_msg>Fixed line number bug<commit_after>var esprima = require('esprima');

var moduleAnalyzer = {
	analyze: function (js) {
		var analyzedJs = esprima.parse(js, { range: true });

		//console.log(JSON.stringify(analyzedJs, null, 4));
		goThroughSyntaxTree(analyzedJs.body[0]);

		var updatedJs = "";
		if(changes.length) {
			for (var i = changes.length - 1; i >= 0; i--) {
				updatedJs = replaceCode(js, changes[i].start, changes[i].end, changes[i].newCode);
			};
		}

		return js;
	}
};

var systemVariables = ["_event", "_sessionid", "_name", "_ioprocessors", "_x"];
var changes = [];

var treeTypes = {
	"BlockStatement": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);
	},
	"FunctionExpression": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);
	},
	"FunctionDeclaration": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);
	},
	"ExpressionStatement": function (tree) {
		tree = tree.expression;
		goThroughSyntaxTree(tree);
	},
	// "VariableDeclaration": function (tree) {

	// },
	"AssignmentExpression": function (tree) {
		//Check if assignee is a system variable
		if(systemVariables.indexOf(tree.left.name) !== -1) {

			//Raise error.execution.
			changes.push({
				newCode: "this.raise({ name:\"error.execution\", data : {}})",
				start: tree.range[0],
				end: tree.range[1]
			});

			console.log(tree.left.name + ' used illegally');
		}
	}
	// ,
	// "ReturnStatement": function (tree) {

	// },
	// "CallExpression": function (tree) {

	// },
	// "IfStatement": function (tree) {

	// }
};

function goThroughSyntaxTree (tree) {
	if (Array.isArray(tree)) {
		//Run each children of an array separately
		for (var i = tree.length - 1; i >= 0; i--) {
			goThroughSyntaxTree(tree[i]);
		};
	} else if(tree.type && treeTypes[tree.type]) {
		//If we support the type value
		treeTypes[tree.type](tree);
	};
}

function replaceCode (original, start, end, newCode) {
	return original.substring(0, start) + newCode + original.substring(end, original.length);
}

module.exports = moduleAnalyzer;<|endoftext|>


<commit_before>pontoEmbarque = "";
// Iniciando o mapa
var map = L.map('map', {
    zoomControl: false
}).setView([-21.786, -46.566], 15);

L.control.zoom({
    position: 'bottomright'
}).addTo(map);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© ' +
      'OpenStreetMap contributors'
}).addTo(map);

// Criando camada para desenhar no mapa
var markers = new L.FeatureGroup();

// Generator que desenha no mapa e html
var Generator = {};

var listaRotas = [];

/* Metodos da classe Generator */

// Draws a stop on the map, with the position and agency name.
Generator.drawAgencyStop = function(data) {

    obj = JSON.parse(data);

    L.marker([37.972117, -122.032526], {
            icon: agencyMarker
        }).addTo(map)
        .bindPopup(Generator.drawAgencyPopup(obj.agency_name, obj.agency_url, obj.agency_timezone, obj.agency_lang))
        .openPopup();

    map.setView(new L.LatLng(37.972117, -122.032526), 10);
};

/* Draws a popup on the stop, with the agency's information. */
Generator.drawAgencyPopup = function(agency_name, agency_url, agency_timezone,
                                                               agency_lang) {

    var html = "";

    html += "
" +
              "
" +
                " " +
                  agency_name +
               "
" +
              "
" +
               "" +
                "Visit Agency!" +
               "" +
              "
" +
              "
" +
                agency_timezone + " - " +
                agency_lang +
              "
" +
            "
";

    return html;

};

/* Generates the HTML code a list of routes */
Generator.drawRoutesList = function(routeListData) {

    var routeList, routeListLength, route, html, routeName;

    routeList = JSON.parse(routeListData);
    routeListLength = routeList.length;

    for (var i = 0; i < routeListLength; i++) {

        route = routeList[i];
        routeName = route.route_short_name + ": " + route.route_long_name;

        html = "<option value='" + route.route_id + "'>" +
                  routeName +
                "</option>";

        $("#routes").append(html);

        // Places the routes in a list, to be used in typeahead
        listaRotas.push(routeName);

    }
};

// Draws a line between the points of shape
Generator.drawShapes = function(data) {

    var obj = JSON.parse(data);

    // Check if shape points exists
    if (!(obj[0] === undefined || obj[0] === null)) {
        var latlngs = Array();

        for (var y = 0; y < obj[0].length; y++) {
            var marker = L.marker([obj[0][y].shape_pt_lat, obj[0][y].shape_pt_lon], {
                icon: greenIcon
            });
            //markers.addLayer(marker);
            latlngs.push(marker.getLatLng());
        }

        //map.addLayer(markers);

        // create a polyline from an arrays of LatLng points
        var polyline = L.polyline(latlngs, {
            color: '#3498db'
        }).addTo(map);
        markers.addLayer(polyline);
        map.addLayer(markers);
        // zoom the map to the polyline
        map.fitBounds(polyline.getBounds());
        map.setZoom(10);

    }
};

/* Draw a list of stops on map */
Generator.drawStops = function(stopsData) {

    var stopList, stopLength, stop, marker;

    stopList = JSON.parse(stopsData);
    stopLength = stopList.length;

    for (var i = 0; i < stopLength; i++) {

      stop = stopList[i];

      marker = L.marker([stop.stop_lat, stop.stop_lon], {
          icon: redMarker
      })
      .bindPopup(Generator.drawStopsPopup(stop.stop_id,
                                          stop.stop_name,
                                          stop.stop_desc));

      markers.addLayer(marker);

    }

    map.addLayer(markers);

};

/* Draws the pop-up stopping points on the map */
Generator.drawStopsPopup = function(stopId, stopName, stopsDesc) {

    var html = '';

    html += "
" +
        "
" + stopName + "
" +
        "
" + stopId + " - " + stopsDesc + "
" +
        "
";

    return html;

};
<commit_msg>Improving the esthetics of the generator<commit_after>pontoEmbarque = "";
// Iniciando o mapa
var map = L.map('map', {
    zoomControl: false
}).setView([-21.786, -46.566], 15);

L.control.zoom({
    position: 'bottomright'
}).addTo(map);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© ' +
      'OpenStreetMap contributors'
}).addTo(map);

// Criando camada para desenhar no mapa
var markers = new L.FeatureGroup();

// Generator que desenha no mapa e html
var Generator = {};

var listaRotas = [];

/* Metodos da classe Generator */

// Draws a stop on the map, with the position and agency name.
Generator.drawAgencyStop = function(data) {

    obj = JSON.parse(data);

    L.marker([37.972117, -122.032526], {
            icon: agencyMarker
        }).addTo(map)
        .bindPopup(Generator.drawAgencyPopup(obj.agency_name,
                                             obj.agency_url,
                                             obj.agency_timezone,
                                             obj.agency_lang))
        .openPopup();

    map.setView(new L.LatLng(37.972117, -122.032526), 10);
};

/* Draws a popup on the stop, with the agency's information. */
Generator.drawAgencyPopup = function(agency_name, agency_url, agency_timezone,
                                                               agency_lang) {

    var html = "";

    html += "
" +
              "
" +
                " " +
                  agency_name +
               "
" +
              "
" +
               "" +
                "Visit Agency!" +
               "" +
              "
" +
              "
" +
                agency_timezone + " - " +
                agency_lang +
              "
" +
            "
";

    return html;

};

/* Generates the HTML code a list of routes */
Generator.drawRoutesList = function(routeListData) {

    var routeList, routeListLength, route, html, routeName;

    routeList = JSON.parse(routeListData);
    routeListLength = routeList.length;

    for (var i = 0; i < routeListLength; i++) {

        route = routeList[i];
        routeName = route.route_short_name + ": " + route.route_long_name;

        html = "<option value='" + route.route_id + "'>" +
                  routeName +
                "</option>";

        $("#routes").append(html);

        // Places the routes in a list, to be used in typeahead
        listaRotas.push(routeName);

    }
};

// Draws a line between the points of shape
Generator.drawShapes = function(data) {

    var obj = JSON.parse(data);

    // Check if shape points exists
    if (!(obj[0] === undefined || obj[0] === null)) {
        var latlngs = Array();

        for (var y = 0; y < obj[0].length; y++) {
            var marker = L.marker([obj[0][y].shape_pt_lat,
                                   obj[0][y].shape_pt_lon], {
                icon: greenIcon
            });
            //markers.addLayer(marker);
            latlngs.push(marker.getLatLng());
        }

        //map.addLayer(markers);

        // create a polyline from an arrays of LatLng points
        var polyline = L.polyline(latlngs, {
            color: '#3498db'
        }).addTo(map);
        markers.addLayer(polyline);
        map.addLayer(markers);
        // zoom the map to the polyline
        map.fitBounds(polyline.getBounds());
        map.setZoom(10);

    }
};

/* Draw a list of stops on map */
Generator.drawStops = function(stopsData) {

    var stopList, stopLength, stop, marker;

    stopList = JSON.parse(stopsData);
    stopLength = stopList.length;

    for (var i = 0; i < stopLength; i++) {

      stop = stopList[i];

      marker = L.marker([stop.stop_lat, stop.stop_lon], {
          icon: redMarker
      })
      .bindPopup(Generator.drawStopsPopup(stop.stop_id,
                                          stop.stop_name,
                                          stop.stop_desc));

      markers.addLayer(marker);

    }

    map.addLayer(markers);

};

/* Draws the pop-up stopping points on the map */
Generator.drawStopsPopup = function(stopId, stopName, stopsDesc) {

    var html = '';

    html += "
" +
        "
" + stopName + "
" +
        "
" + stopId + " - " + stopsDesc + "
" +
        "
";

    return html;

};
<|endoftext|>


<commit_before>import assert from 'assert';
import makeDebug from 'debug';
import fp from 'mostly-func';

import { getMetaSubtypes, copyDocument, moveDocument, fanoutOperations } from '../../helpers';
import defaultHooks from './document-clipboard.hooks';

const debug = makeDebug('playing:content-services:documents/clipboards');

const defaultOptions = {
  name: 'documents/clipboards',
  fanoutLimit: 10,  // number of children documents are handled in one task when doing the fanout
};

export class DocumentClipboardService {
  constructor (options) {
    this.options = fp.assignAll(defaultOptions, options);
    this.name = this.options.name;
  }

  setup (app) {
    this.app = app;
    this.hooks(defaultHooks(this.options));
  }

  /**
   * router to actions
   */
  async patch (id, data, params) {
    switch (id) {
      case 'copyDocument': return this.copy(id, data, params);
      case 'moveDocument': return this.move(id, data, params);
      default: throw new Error(`Unknown action method ${id}`);
    }
  }

  /**
   * Copy document as target document's children
   */
  async copy (id, data, params) {
    const target = params.primary;
    assert(target && target.id, 'target is not exists');
    assert(data.documents, 'documents is not provided.');
    assert(data.target, 'target is not provided.');
    debug('copyDocument target', target.id, data.documents);

    // subtypes of target
    const subtypes = getMetaSubtypes(target);

    const svcDocuments = this.app.service('documents');
    const copyDoc = async (id) => {
      const doc = await svcDocuments.get(id);
      if (fp.contains(doc.type, subtypes)) {
        return copyDocument(this.app, doc, target.id);
      } else {
        throw new Error('Target not allow doc type ' + doc.type);
      }
    };

    return Promise.all(data.documents.map(copyDoc));
  }

  /**
   * Move document to target document's children
   */
  async move (id, data, params) {
    const target = params.primary;
    assert(target && target.id, 'target is not exists');
    assert(data.documents, 'documents is not provided.');
    assert(data.target, 'target is not provided.');
    debug('moveDocument target', target.id, data.documents);

    // subtypes of target
    const subtypes = getMetaSubtypes(target);

    const svcDocuments = this.app.service('documents');
    const getDoc = async (id) => {
      const doc = await svcDocuments.get(id);
      if (fp.contains(doc.type, subtypes)) {
        return doc;
      } else {
        throw new Error('Target not allow doc type ' + doc.type);
      }
    };
    const moveDoc = async (doc) => {
      return moveDocument(this.app, doc, target.id);
    };

    const documents = await Promise.all(fp.map(getDoc, data.documents));
    const results = await Promise.all(fp.map(moveDoc, documents));

    // fanout for all children documents
    fanoutOperations(this.app, documents, 'moveDocuments', this.options.fanoutLimit);

    return results;
  }
}

export default function init (app, options, hooks) {
  return new DocumentClipboardService(options);
}

init.Service = DocumentClipboardService;
<commit_msg>add common _checkDocument<commit_after>import assert from 'assert';
import makeDebug from 'debug';
import fp from 'mostly-func';

import { getMetaSubtypes, copyDocument, moveDocument, fanoutOperations } from '../../helpers';
import defaultHooks from './document-clipboard.hooks';

const debug = makeDebug('playing:content-services:documents/clipboards');

const defaultOptions = {
  name: 'documents/clipboards',
  fanoutLimit: 10,  // number of children documents are handled in one task when doing the fanout
};

export class DocumentClipboardService {
  constructor (options) {
    this.options = fp.assignAll(defaultOptions, options);
    this.name = this.options.name;
  }

  setup (app) {
    this.app = app;
    this.hooks(defaultHooks(this.options));
  }

  /**
   * router to actions
   */
  async patch (id, data, params) {
    switch (id) {
      case 'copyDocument': return this.copy(id, data, params);
      case 'moveDocument': return this.move(id, data, params);
      default: throw new Error(`Unknown action method ${id}`);
    }
  }

  /**
   * Copy document as target document's children
   */
  async copy (id, data, params) {
    const target = params.primary;
    assert(target && target.id, 'target is not exists');
    assert(data.documents, 'documents is not provided.');
    assert(data.target, 'target is not provided.');
    debug('copyDocument target', target.id, data.documents);

    // subtypes of target
    const subtypes = getMetaSubtypes(target);

    const svcDocuments = this.app.service('documents');
    const copyDoc = async (id) => {
      const doc = await svcDocuments.get(id);
      if (fp.contains(doc.type, subtypes)) {
        return copyDocument(this.app, doc, target.id);
      } else {
        throw new Error('Target not allow doc type ' + doc.type);
      }
    };

    return Promise.all(data.documents.map(copyDoc));
  }

  /**
   * Move document to target document's children
   */
  async move (id, data, params) {
    const target = params.primary;
    assert(target && target.id, 'target is not exists');
    assert(data.documents, 'documents is not provided.');
    assert(data.target, 'target is not provided.');
    debug('moveDocument target', target.id, data.documents);

    // subtypes of target
    const subtypes = getMetaSubtypes(target);

    const documents = await Promise.all(
      fp.map(doc => this._checkDocument(doc, subtypes), data.documents)
    );
    const results = await Promise.all(
      fp.map(doc => moveDocument(this.app, doc, target.id), documents)
    );

    // fanout for all children documents
    fanoutOperations(this.app, documents, 'moveDocuments', this.options.fanoutLimit);

    return results;
  }

  async _checkDocument (id, subtypes) {
    const svcDocuments = this.app.service('documents');
    const document = await svcDocuments.get(id);
    if (fp.contains(document.type, subtypes)) {
      return document;
    } else {
      throw new Error('Target not allow doc type ' + document.type);
    }
  }
}

export default function init (app, options, hooks) {
  return new DocumentClipboardService(options);
}

init.Service = DocumentClipboardService;
<|endoftext|>


<commit_before>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var fs = require('./utils/fs');
var helper = require('./utils/config-helper');
var config, paths, pkg;

function getConfig(){
    config = helper.getConfig();
}

function ghPagesRelease(message){
    getConfig();
    var release = helper.matches(config.release, ['gh-pages']);
    if (!release) return Promise.resolve();

    var ghPages = require('gh-pages');
    message = message || 'Update';
    log.info("\n * gh-pages\n");
    return new Promise(function(resolve, reject){
        ghPages.publish(config.paths.target, {message: message }, function(err) {
            ghPages.clean();
            err && reject(err);
            !err && resolve();
        });
    });
}

function s3(version){
    getConfig();
    if (!config.release || config.release.indexOf('s3') <0){
        return Promise.resolve();
    }
    log.info("\ * s3\n");
    var Release = require('./wrappers/s3');
    var options = config.s3 || {};
    var target = options.target || '';
    if (version){
        target = target.replace(/("|\/)[0-9]+\.[0-9]+\.[0-9]\-?(?:(?:[0-9A-Za-z-]+\.?)+)?("|\/)/g, '$1' + version + '$2');
    }
    return new Release(config.paths.target + '/**/*.*', target, options).write();
}

function releaseGit(version){
    getConfig();
    if (!config.release || config.release.indexOf('git') <0){
        return Promise.resolve();
    }
    var git = require('./utils/git');
    if (!git.checkRemote()){
        return log.onError(['No valid Remote Git URL.',
            'Please update your `.git/config` file or run:',
            '$ caddy init git'].join('\n'));
    }
    version = version || config.pkg.version;
    log.info(' * Git');
    return git.release(version);
}

function releaseBower(version){
    getConfig();
    if (!config.release || config.release.indexOf('bower') <0){
        return Promise.resolve();
    }
    var git = require('./utils/git');
    var bower = require('./wrappers/bower');
    if (!git.checkRemote()){
        return log.onError(['No valid Remote Git URL.',
            'Please update your `.git/config` file or run:',
            '$ caddy init git'].join('\n'));
    }
    version = version || config.pkg.version;
    log.info(' * Bower');
    return bower.release(version).catch(log.onError);
}

function run(type){
    log.info('Releasing :');
    var bump = require('./bump').run;
    var bumpedVersion;
    return bump(type || 'current').then(function(version) {
        bumpedVersion = version;
        return releaseGit(version);
    }).then(function(){
        return ghPagesRelease('v' + bumpedVersion);
    }).then(function(){
        return s3(bumpedVersion);
    }).catch(log.onError);
}

module.exports = {
    bower: releaseBower,
    git: releaseGit,
    'gh-pages': ghPagesRelease,
    s3: s3,
    run: run,
    all: run,
    adhoc: run
};
<commit_msg>standardise release checks<commit_after>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var fs = require('./utils/fs');
var helper = require('./utils/config-helper');
var config, paths, pkg;

function getConfig(){
    config = helper.getConfig();
}

function ghPagesRelease(message){
    getConfig();
    var release = helper.matches(config.release, ['gh-pages']);
    if (!release) return Promise.resolve();

    var ghPages = require('gh-pages');
    message = message || 'Update';
    log.info("\n * gh-pages\n");
    return new Promise(function(resolve, reject){
        ghPages.publish(config.paths.target, {message: message }, function(err) {
            ghPages.clean();
            err && reject(err);
            !err && resolve();
        });
    });
}

function s3(version){
    getConfig();
    var release = helper.matches(config.release, ['s3']);
    if (!release) return Promise.resolve();

    log.info("\ * s3\n");
    var Release = require('./wrappers/s3');
    var options = config.s3 || {};
    var target = options.target || '';
    if (version){
        target = target.replace(/("|\/)[0-9]+\.[0-9]+\.[0-9]\-?(?:(?:[0-9A-Za-z-]+\.?)+)?("|\/)/g, '$1' + version + '$2');
    }
    return new Release(config.paths.target + '/**/*.*', target, options).write();
}

function releaseGit(version){
    getConfig();
    var release = helper.matches(config.release, ['git']);
    if (!release) return Promise.resolve();

    var git = require('./utils/git');
    if (!git.checkRemote()){
        return log.onError(['No valid Remote Git URL.',
            'Please update your `.git/config` file or run:',
            '$ caddy init git'].join('\n'));
    }
    version = version || config.pkg.version;
    log.info(' * Git');
    return git.release(version);
}

function releaseBower(version){
    getConfig();
    var release = helper.matches(config.release, ['bower']);
    if (!release) return Promise.resolve();

    var git = require('./utils/git');
    var bower = require('./wrappers/bower');
    if (!git.checkRemote()){
        return log.onError(['No valid Remote Git URL.',
            'Please update your `.git/config` file or run:',
            '$ caddy init git'].join('\n'));
    }
    version = version || config.pkg.version;
    log.info(' * Bower');
    return bower.release(version).catch(log.onError);
}

function run(type){
    log.info('Releasing :');
    var bump = require('./bump').run;
    var bumpedVersion;
    return bump(type || 'current').then(function(version) {
        bumpedVersion = version;
        return releaseGit(version);
    }).then(function(){
        return ghPagesRelease('v' + bumpedVersion);
    }).then(function(){
        return s3(bumpedVersion);
    }).catch(log.onError);
}

module.exports = {
    bower: releaseBower,
    git: releaseGit,
    'gh-pages': ghPagesRelease,
    s3: s3,
    run: run,
    all: run,
    adhoc: run
};
<|endoftext|>


<commit_before>var AWS = require('../core');

/**
 * Represents credentials retrieved from STS Web Identity Federation using
 * the Amazon Cognito Identity service.
 *
 * By default this provider gets credentials using the
 * {AWS.STS.assumeRoleWithWebIdentity} service operation, after first getting
 * an Open ID token from {AWS.CognitoIdentity.getOpenIdToken}. These operations
 * require an `AccountId` (AWS account ID), `IdentityPoolId` (Amazon Cognito
 * Identity Pool ID), and `RoleArn` containing the ARN of the IAM trust policy
 * for the Amazon Cognito role that the user will log into. In addition, if
 * this credential provider is used to provide authenticated login, the
 * `Logins` map may be set to the tokens provided by the respective identity
 * providers. See {constructor} for an example on creating a credentials
 * object with proper property values.
 *
 * ## Refreshing Credentials from Identity Service
 *
 * In addition to AWS credentials expiring after a given amount of time, the
 * login token from the identity provider will also expire. Once this token
 * expires, it will not be usable to refresh AWS credentials, and another
 * token will be needed. The SDK does not manage refreshing of the token value,
 * but this can be done through a "refresh token" supported by most identity
 * providers. Consult the documentation for the identity provider for refreshing
 * tokens. Once the refreshed token is acquired, you should make sure to update
 * this new token in the credentials object's {params} property. The following
 * code will update the WebIdentityToken, assuming you have retrieved an updated
 * token from the identity provider:
 *
 * ```javascript
 * AWS.config.credentials.params.Logins['graph.facebook.com'] = updatedToken;
 * ```
 *
 * Future calls to `credentials.refresh()` will now use the new token.
 *
 * @!attribute params
 *   @return [map] the map of params passed to
 *     {AWS.CognitoIdentity.getOpenIdToken} and
 *     {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the
 *     `params.WebIdentityToken` property.
 * @!attribute data
 *   @return [map] the raw data response from the call to
 *     {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get
 *     access to other properties from the response.
 * @!attribute identityId
 *   @return [String] the Cognito ID returned by the last call to
 *     {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual
 *     final resolved identity ID from Amazon Cognito.
 */
AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, {
  /**
   * @api private
   */
  localStorageKey: {
    id: 'aws.cognito.identity-id.',
    providers: 'aws.cognito.identity-providers.'
  },

  /**
   * Creates a new credentials object.
   * @param (see AWS.STS.assumeRoleWithWebIdentity)
   * @param (see AWS.CognitoIdentity.getOpenIdToken)
   * @example Creating a new credentials object
   *   AWS.config.credentials = new AWS.CognitoIdentityCredentials({
   *     AccountId: '1234567890',
   *     IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030',
   *     RoleArn: 'arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity',
   *     Logins: { // optional tokens, used for authenticated login
   *       'graph.facebook.com': 'FBTOKEN',
   *       'www.amazon.com': 'AMAZONTOKEN',
   *       'accounts.google.com': 'GOOGLETOKEN'
   *     },
   *     RoleSessionName: 'web' // optional name, defaults to web-identity
   *   });
   * @see AWS.STS.assumeRoleWithWebIdentity
   */
  constructor: function CognitoIdentityCredentials(params) {
    AWS.Credentials.call(this);
    this.expired = true;
    this.webIdentityCredentials = new AWS.WebIdentityCredentials(params);
    this.cognito = new AWS.CognitoIdentity({params: params});
    this.sts = new AWS.STS();
    this.params = params;
    this.data = null;
    this.identityId = null;
    this.loadCachedId();
  },

  /**
   * Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity}
   *
   * @callback callback function(err)
   *   Called when the STS service responds (or fails). When
   *   this callback is called with no error, it means that the credentials
   *   information has been loaded into the object (as the `accessKeyId`,
   *   `secretAccessKey`, and `sessionToken` properties).
   *   @param err [Error] if an error occurred, this value will be filled
   * @see get
   */
  refresh: function refresh(callback) {
    var self = this;
    self.data = null;
    self.identityId = null;
    self.getId(function(err) {
      if (!err) {
        if (!self.params.RoleArn) {
          self.getCredentialsForIdentity(callback);
        } else {
          self.getCredentialsFromSTS(callback);
        }
      } else {
        self.clearCachedId();
        callback(err);
      }
    });
  },
      /*
        }*/

  /**
   * Clears the cached Cognito ID associated with the currently configured
   * identity pool ID. Use this to manually invalidate your cache if
   * the identity pool ID was deleted.
   */
  clearCachedId: function clearCache() {
    var poolId = this.params.IdentityPoolId;
    delete this.storage[this.localStorageKey.id + poolId];
    delete this.storage[this.localStorageKey.providers + poolId];
  },

  /**
   * Retrieves a Cognito ID, loading from cache if it was already retrieved
   * on this device.
   *
   * @callback callback function(err, identityId)
   *   @param err [Error, null] an error object if the call failed or null if
   *     it succeeded.
   *   @param identityId [String, null] if successful, the callback will return
   *     the Cognito ID.
   * @note If not loaded explicitly, the Cognito ID is loaded and stored in
   *   localStorage in the browser environment of a device.
   * @api private
   */
  getId: function getId(callback) {
    var self = this;
    if (typeof self.params.IdentityId === 'string') {
      return callback(null, self.params.IdentityId);
    }

    self.cognito.getId(function(err, data) {
      if (!err && data.IdentityId) {
        self.params.IdentityId = data.IdentityId;
        callback(null, data.IdentityId);
      } else {
        callback(err);
      }
    });
  },

  /**
   * @api private
   */
  loadCredentials: function loadCredentials(data, credentials) {
    if (!data || !credentials) return;
    credentials.expired = false;
    credentials.accessKeyId = data.Credentials.AccessKeyId;
    credentials.secretAccessKey = data.Credentials.SecretKey;
    credentials.sessionToken = data.Credentials.SessionToken;
    credentials.expireTime = data.Credentials.Expiration;
  },

  /**
   * @api private
   */
  getCredentialsForIdentity: function getCredentialsForIdentity(callback) {
    var self = this;
    self.cognito.getCredentialsForIdentity(function(err, data){
      if (!err){
        self.cacheId(data);
        self.data = data;
        self.loadCredentials(self.data, self);
      } else {
        self.clearCachedId();
      }
      callback(err);
    });
  },

  /**
   *
   */
  getCredentialsFromSTS: function getCredentialsFromSTS(callback) {
    var self = this;
    self.cognito.getOpenIdToken(function(err, data) {
      if (!err) {
        self.cacheId(data);
        self.params.WebIdentityToken = data.Token;
        self.webIdentityCredentials.refresh(function(webErr) {
          if (!webErr) {
            self.data = self.webIdentityCredentials.data;
            self.sts.credentialsFrom(self.data, self);
          } else {
            self.clearCachedId();
          }
          callback(webErr);
        });
      } else {
        self.clearCachedId();
        callback(err);
      }
    });
  },

  /**
   * @api private
   */
  loadCachedId: function loadCachedId() {
    var self = this;

    // in the browser we source default IdentityId from localStorage
    if (AWS.util.isBrowser() && !self.params.IdentityId) {
      var id = self.getStorage('id');
      if (id && self.params.Logins) {
        var actualProviders = Object.keys(self.params.Logins);
        var cachedProviders =
          (self.getStorage('providers') || '').split(',');

        // only load ID if at least one provider used this ID before
        var intersect = cachedProviders.filter(function(n) {
          return actualProviders.indexOf(n) !== -1;
        });
        if (intersect.length !== 0) {
          self.params.IdentityId = id;
        }
      } else if (id) {
        self.params.IdentityId = id;
      }
    }
  },

  /**
   * @api private
   */
  cacheId: function cacheId(data) {
    this.identityId = data.IdentityId;
    this.params.IdentityId = this.identityId;

    // cache this IdentityId in browser localStorage if possible
    if (AWS.util.isBrowser()) {
      this.setStorage('id', data.IdentityId);

      if (this.params.Logins) {
        this.setStorage('providers', Object.keys(this.params.Logins).join(','));
      }
    }
  },

  /**
   * @api private
   */
  getStorage: function getStorage(key) {
    return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId];
  },

  /**
   * @api private
   */
  setStorage: function setStorage(key, val) {
    this.storage[this.localStorageKey[key] + this.params.IdentityPoolId] = val;
  },

  /**
   * @api private
   */
  storage: (function() {
    try {
      return AWS.util.isBrowser() && typeof window.localStorage === 'object' ?
             window.localStorage : {};
    } catch (_) {
      return {};
    }
  })()
});
<commit_msg>Fix linting<commit_after>var AWS = require('../core');

/**
 * Represents credentials retrieved from STS Web Identity Federation using
 * the Amazon Cognito Identity service.
 *
 * By default this provider gets credentials using the
 * {AWS.STS.assumeRoleWithWebIdentity} service operation, after first getting
 * an Open ID token from {AWS.CognitoIdentity.getOpenIdToken}. These operations
 * require an `AccountId` (AWS account ID), `IdentityPoolId` (Amazon Cognito
 * Identity Pool ID), and `RoleArn` containing the ARN of the IAM trust policy
 * for the Amazon Cognito role that the user will log into. In addition, if
 * this credential provider is used to provide authenticated login, the
 * `Logins` map may be set to the tokens provided by the respective identity
 * providers. See {constructor} for an example on creating a credentials
 * object with proper property values.
 *
 * ## Refreshing Credentials from Identity Service
 *
 * In addition to AWS credentials expiring after a given amount of time, the
 * login token from the identity provider will also expire. Once this token
 * expires, it will not be usable to refresh AWS credentials, and another
 * token will be needed. The SDK does not manage refreshing of the token value,
 * but this can be done through a "refresh token" supported by most identity
 * providers. Consult the documentation for the identity provider for refreshing
 * tokens. Once the refreshed token is acquired, you should make sure to update
 * this new token in the credentials object's {params} property. The following
 * code will update the WebIdentityToken, assuming you have retrieved an updated
 * token from the identity provider:
 *
 * ```javascript
 * AWS.config.credentials.params.Logins['graph.facebook.com'] = updatedToken;
 * ```
 *
 * Future calls to `credentials.refresh()` will now use the new token.
 *
 * @!attribute params
 *   @return [map] the map of params passed to
 *     {AWS.CognitoIdentity.getOpenIdToken} and
 *     {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the
 *     `params.WebIdentityToken` property.
 * @!attribute data
 *   @return [map] the raw data response from the call to
 *     {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get
 *     access to other properties from the response.
 * @!attribute identityId
 *   @return [String] the Cognito ID returned by the last call to
 *     {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual
 *     final resolved identity ID from Amazon Cognito.
 */
AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, {
  /**
   * @api private
   */
  localStorageKey: {
    id: 'aws.cognito.identity-id.',
    providers: 'aws.cognito.identity-providers.'
  },

  /**
   * Creates a new credentials object.
   * @param (see AWS.STS.assumeRoleWithWebIdentity)
   * @param (see AWS.CognitoIdentity.getOpenIdToken)
   * @example Creating a new credentials object
   *   AWS.config.credentials = new AWS.CognitoIdentityCredentials({
   *     AccountId: '1234567890',
   *     IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030',
   *     RoleArn: 'arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity',
   *     Logins: { // optional tokens, used for authenticated login
   *       'graph.facebook.com': 'FBTOKEN',
   *       'www.amazon.com': 'AMAZONTOKEN',
   *       'accounts.google.com': 'GOOGLETOKEN'
   *     },
   *     RoleSessionName: 'web' // optional name, defaults to web-identity
   *   });
   * @see AWS.STS.assumeRoleWithWebIdentity
   */
  constructor: function CognitoIdentityCredentials(params) {
    AWS.Credentials.call(this);
    this.expired = true;
    this.webIdentityCredentials = new AWS.WebIdentityCredentials(params);
    this.cognito = new AWS.CognitoIdentity({params: params});
    this.sts = new AWS.STS();
    this.params = params;
    this.data = null;
    this.identityId = null;
    this.loadCachedId();
  },

  /**
   * Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity}
   *
   * @callback callback function(err)
   *   Called when the STS service responds (or fails). When
   *   this callback is called with no error, it means that the credentials
   *   information has been loaded into the object (as the `accessKeyId`,
   *   `secretAccessKey`, and `sessionToken` properties).
   *   @param err [Error] if an error occurred, this value will be filled
   * @see get
   */
  refresh: function refresh(callback) {
    var self = this;
    self.data = null;
    self.identityId = null;
    self.getId(function(err) {
      if (!err) {
        if (!self.params.RoleArn) {
          self.getCredentialsForIdentity(callback);
        } else {
          self.getCredentialsFromSTS(callback);
        }
      } else {
        self.clearCachedId();
        callback(err);
      }
    });
  },

  /**
   * Clears the cached Cognito ID associated with the currently configured
   * identity pool ID. Use this to manually invalidate your cache if
   * the identity pool ID was deleted.
   */
  clearCachedId: function clearCache() {
    var poolId = this.params.IdentityPoolId;
    delete this.storage[this.localStorageKey.id + poolId];
    delete this.storage[this.localStorageKey.providers + poolId];
  },

  /**
   * Retrieves a Cognito ID, loading from cache if it was already retrieved
   * on this device.
   *
   * @callback callback function(err, identityId)
   *   @param err [Error, null] an error object if the call failed or null if
   *     it succeeded.
   *   @param identityId [String, null] if successful, the callback will return
   *     the Cognito ID.
   * @note If not loaded explicitly, the Cognito ID is loaded and stored in
   *   localStorage in the browser environment of a device.
   * @api private
   */
  getId: function getId(callback) {
    var self = this;
    if (typeof self.params.IdentityId === 'string') {
      return callback(null, self.params.IdentityId);
    }

    self.cognito.getId(function(err, data) {
      if (!err && data.IdentityId) {
        self.params.IdentityId = data.IdentityId;
        callback(null, data.IdentityId);
      } else {
        callback(err);
      }
    });
  },

  /**
   * @api private
   */
  loadCredentials: function loadCredentials(data, credentials) {
    if (!data || !credentials) return;
    credentials.expired = false;
    credentials.accessKeyId = data.Credentials.AccessKeyId;
    credentials.secretAccessKey = data.Credentials.SecretKey;
    credentials.sessionToken = data.Credentials.SessionToken;
    credentials.expireTime = data.Credentials.Expiration;
  },

  /**
   * @api private
   */
  getCredentialsForIdentity: function getCredentialsForIdentity(callback) {
    var self = this;
    self.cognito.getCredentialsForIdentity(function(err, data){
      if (!err){
        self.cacheId(data);
        self.data = data;
        self.loadCredentials(self.data, self);
      } else {
        self.clearCachedId();
      }
      callback(err);
    });
  },

  /**
   *
   */
  getCredentialsFromSTS: function getCredentialsFromSTS(callback) {
    var self = this;
    self.cognito.getOpenIdToken(function(err, data) {
      if (!err) {
        self.cacheId(data);
        self.params.WebIdentityToken = data.Token;
        self.webIdentityCredentials.refresh(function(webErr) {
          if (!webErr) {
            self.data = self.webIdentityCredentials.data;
            self.sts.credentialsFrom(self.data, self);
          } else {
            self.clearCachedId();
          }
          callback(webErr);
        });
      } else {
        self.clearCachedId();
        callback(err);
      }
    });
  },

  /**
   * @api private
   */
  loadCachedId: function loadCachedId() {
    var self = this;

    // in the browser we source default IdentityId from localStorage
    if (AWS.util.isBrowser() && !self.params.IdentityId) {
      var id = self.getStorage('id');
      if (id && self.params.Logins) {
        var actualProviders = Object.keys(self.params.Logins);
        var cachedProviders =
          (self.getStorage('providers') || '').split(',');

        // only load ID if at least one provider used this ID before
        var intersect = cachedProviders.filter(function(n) {
          return actualProviders.indexOf(n) !== -1;
        });
        if (intersect.length !== 0) {
          self.params.IdentityId = id;
        }
      } else if (id) {
        self.params.IdentityId = id;
      }
    }
  },

  /**
   * @api private
   */
  cacheId: function cacheId(data) {
    this.identityId = data.IdentityId;
    this.params.IdentityId = this.identityId;

    // cache this IdentityId in browser localStorage if possible
    if (AWS.util.isBrowser()) {
      this.setStorage('id', data.IdentityId);

      if (this.params.Logins) {
        this.setStorage('providers', Object.keys(this.params.Logins).join(','));
      }
    }
  },

  /**
   * @api private
   */
  getStorage: function getStorage(key) {
    return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId];
  },

  /**
   * @api private
   */
  setStorage: function setStorage(key, val) {
    this.storage[this.localStorageKey[key] + this.params.IdentityPoolId] = val;
  },

  /**
   * @api private
   */
  storage: (function() {
    try {
      return AWS.util.isBrowser() && typeof window.localStorage === 'object' ?
             window.localStorage : {};
    } catch (_) {
      return {};
    }
  })()
});
<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: adi
 * Date: 10/17/13
 * Time: 11:37 AM
 * To change this template use File | Settings | File Templates.
 * global jQuery
 */
(function ($) {
    var $d = $(document),
        $w = $(window);

    function Slider (opts) {
        var self = this,
            state = {
                innerX: 0,
                innerY: 0,
                mouseDown: false,
                currentValue: false,
                init: false
            },
            container = opts.container,
            handle = container.find('a'),
            bounds = {};
        this.setBounds = function () {
            var offset = container.offset();
            return {
                bottom: offset.top + container.height() - handle.width(),
                left: offset.left,
                right: offset.left + container.width() - handle.width(),
                top: offset.top - handle.offset().top
            };
        };
        this.getPercentageByValue = function (value, range) {
            var percentage = 100 * (value - range.min) / (range.max - range.min);
            percentage = percentage > 100 ? 100 : percentage;
            percentage = percentage < 0 ? 0 : percentage;
            return Math.round(percentage);
        };
        this.getValueByPercentage = function (percent, range) {
            return Math.round((((range.max - range.min ) / 100) * percent) + range.min);
        };
        this.handleMove = function (position) {
            var m = {},
                percent = 0,
                value = 0;
            if(opts.direction === 'horizontal') {
                percent = self.getPercentageByValue(position.x, {min: bounds.left, max: bounds.right});
                value = self.getValueByPercentage(percent, opts.interval);
                m.left = position.x < bounds.left ? bounds.left : (position.x > bounds.right ? bounds.right : position.x);
            }
            if(opts.direction === 'vertical') {
                percent = self.getPercentageByValue(position.y, {min: bounds.top, max: bounds.bottom});
                value = self.getValueByPercentage(percent, opts.interval);
                m.top = position.y < bounds.top ? bounds.top : (position.y > bounds.bottom ? bounds.bottom : position.y);
            }
            if (value >= opts.min) {
                handle.offset(m);
                state.currentValue = value;
                if (typeof opts.slide === 'function')
                    opts.slide.apply(this, [container, value, percent, m.left]);
            }
        };
        this.bindEvents = function () {
            container.css('cursor', 'pointer').on('click', function (e) {
                self.handleMove({x: e.pageX - state.innerX, y: e.pageY - state.innerY});
            });
            handle.off().on("mousedown", function (e) {
                state.innerX = e.pageX - handle.offset().left;
                state.innerY = e.pageY - handle.offset().top;
                state.mouseDown = true;
                e.preventDefault();
            }).on("mouseup", function () {
                state.mouseDown = false;
            });
            $d.on("mousemove", function (e) {
                if (state.mouseDown) {
                    self.handleMove({x: e.pageX - state.innerX,y: e.pageY - state.innerY });
                }
                if (state.init === false) {
                    state.init = true;
                    self.handleMove({x: self.getValueByPercentage(self.getPercentageByValue(state.currentValue || opts.min, opts.interval), {min: bounds.left, max: bounds.right}), y: e.pageY - state.innerY});
                }
            }).on('mouseup', function (e) {
                state.mouseDown = false;
                e.preventDefault();
            });
            $w.on('resize', function () {
                bounds = self.setBounds();
                state.init = false;
                $d.trigger('mousemove');
            });
        };
        this.construct = function () {
            bounds = self.setBounds();
            self.bindEvents();
            $d.trigger('mousemove');
        };
    }

    $.fn.extend({
        simpleSlider: function (options) {
            return this.each(function () {
                var opts = $.extend({}, {container: $(this)}, options);
                (new Slider(opts)).construct();
            })
        }
    });
}(jQuery));
<commit_msg>Update hSlider.js<commit_after>/**
 * Created with IntelliJ IDEA.
 * User: adi
 * Date: 10/17/13
 * Time: 11:37 AM
 * To change this template use File | Settings | File Templates.
 * global jQuery
 */
(function ($) {
    var $d = $(document),
        $w = $(window);
    function Slider (opts) {
        var self = this,
            state = {
                innerX: 0,
                innerY: 0,
                mouseDown: false,
                currentValue: false,
                init: false
            },
            container = opts.container,
            handle = container.find('a'),
            bounds = {};
        this.setBounds = function () {
            var offset = container.offset();
            return {
                bottom: offset.top + container.height() - handle.height(),
                left: offset.left,
                right: offset.left + container.width() - handle.width(),
                top: offset.top
            };
        };
        this.getPercentageByValue = function (value, range) {
            var percentage = 100 * (value - range.min) / (range.max - range.min);
            percentage = percentage > 100 ? 100 : percentage;
            percentage = percentage < 0 ? 0 : percentage;
            return Math.round(percentage);
        };
        this.getValueByPercentage = function (percent, range) {
            return Math.round((((range.max - range.min ) / 100) * percent) + range.min);
        };
        this.handleMove = function (position) {
            var m = {},
                percent = 0,
                value = 0;
            if(opts.direction === 'horizontal') {
                percent = self.getPercentageByValue(position.x, {min: bounds.left, max: bounds.right});
                value = self.getValueByPercentage(percent, opts.interval);
                m.left = position.x < bounds.left ? bounds.left : (position.x > bounds.right ? bounds.right : position.x);
            }
            if(opts.direction === 'vertical') {
                percent = self.getPercentageByValue(position.y, {min: bounds.top, max: bounds.bottom});
                value = self.getValueByPercentage(percent, opts.interval);
                m.top = position.y < bounds.top ? bounds.top : (position.y > bounds.bottom ? bounds.bottom : position.y);
            }
            if (value >= opts.limits.min) {
                handle.offset(m);
                state.currentValue = value;
                if (typeof opts.slide === 'function')
                    opts.slide.apply(this, [container, value, percent, m]);
            }
        };
        this.bindEvents = function () {
            container.css('cursor', 'pointer').on('click', function (e) {
                self.handleMove({x: e.pageX - state.innerX, y: e.pageY - state.innerY});
            });
            handle.off().on("mousedown", function (e) {
                state.innerX = e.pageX - handle.offset().left;
                state.innerY = e.pageY - handle.offset().top;
                state.mouseDown = true;
                e.preventDefault();
            }).on("mouseup", function () {
                state.mouseDown = false;
            });
            $d.on("mousemove", function (e) {
                if (state.mouseDown) {
                    self.handleMove({x: e.pageX - state.innerX,y: e.pageY - state.innerY });
                }
                if (state.init === false) {
                    state.init = true;
                    self.handleMove({
                        x: self.getValueByPercentage(self.getPercentageByValue(state.currentValue || opts.limits.min, opts.interval), {min: bounds.left, max: bounds.right}),
                        y: self.getValueByPercentage(self.getPercentageByValue(state.currentValue || opts.limits.min, opts.interval), {min: bounds.top, max: bounds.bottom})
                    });
                }
            }).on('mouseup', function (e) {
                state.mouseDown = false;
                e.preventDefault();
            });
            $w.on('resize', function () {
                bounds = self.setBounds();
                state.init = false;
                $d.trigger('mousemove');
            });
        };
        this.construct = function () {
            bounds = self.setBounds();
            self.bindEvents();
            $d.trigger('mousemove');
        };
    }
    $.fn.extend({
        simpleSlider: function (options) {
            return this.each(function () {
                var opts = $.extend({}, {container: $(this)}, options);
                opts.direction = opts.container.hasClass('vertical') ? 'vertical' : 'horizontal';
                (new Slider(opts)).construct();
            });
        }
    });
}(jQuery));
<|endoftext|>


<commit_before>var zlib = require('zlib')
  , dgram = require('dgram')
  , util = require('util')
  , dns = require('dns')
  , isIp = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;

GLOBAL.LOG_EMERG=0;    // system is unusable
GLOBAL.LOG_ALERT=1;    // action must be taken immediately
GLOBAL.LOG_CRIT=2;     // critical conditions
GLOBAL.LOG_ERR=3;      // error conditions
GLOBAL.LOG_ERROR=3;    // because people WILL typo
GLOBAL.LOG_WARNING=4;  // warning conditions
GLOBAL.LOG_NOTICE=5;   // normal, but significant, condition
GLOBAL.LOG_INFO=6;     // informational message
GLOBAL.LOG_DEBUG=7;    // debug-level message

GLOBAL.graylogHost = 'localhost';
GLOBAL.graylogPort = 12201;
GLOBAL.graylogHostname = require('os').hostname();
GLOBAL.graylogToConsole = false;
GLOBAL.graylogFacility = 'Node.js';
GLOBAL.graylogSequence = 0;
GLOBAL.graylogChunkSize = 1100; // 8192 is the maximum

function generateMessageId() {
	return '' + (Date.now() + Math.floor(Math.random()*10000));
}

function _logToConsole(shortMessage, opts) {
	var consoleString = shortMessage
	  , additionalFields = [];

	if (opts.full_message) {
		consoleString+=" ("+opts.full_message+")\n";
	}

	Object.keys(opts).forEach(function(key) {
		if (key[0]=='_' && key!="_logSequence") {
			additionalFields.push(
				"  " +
				key.substr(1,1024) +
				": " +
				'\033[' + 34 + 'm' +
				opts[key] +
				'\033[' + 39 + 'm'
			);
		}
	});

	if (additionalFields.length>0) {
		consoleString+="\n"+additionalFields.join("\n");
	}

	util.log(consoleString);
}

function sendChunked(graylog2Client, compressedMessage, address) {
	var messageId = generateMessageId()
	  , sequenceSize = Math.ceil(compressedMessage.length / GLOBAL.graylogChunkSize)
	  , byteOffset = 0
	  , chunksWritten = 0;

	if (sequenceSize > 128) {
		util.debug("Graylog oops: log message is larger than 128 chunks, I print to stderr and give up: \n" + message.toString());
		return;
	}

	for(var sequence=0; sequence<sequenceSize; sequence++) {
		var chunkBytes = (byteOffset + GLOBAL.graylogChunkSize) < compressedMessage.length ? GLOBAL.graylogChunkSize : (compressedMessage.length - byteOffset)
		  , chunk = new Buffer(chunkBytes + 12);

		chunk[0] = 0x1e;
		chunk[1] = 0x0f;
		chunk.write(messageId, 2, 8, 'ascii');
		chunk[10] = sequence;
		chunk[11] = sequenceSize;
		compressedMessage.copy(chunk, 12, byteOffset, byteOffset+chunkBytes);

		byteOffset += chunkBytes;

		graylog2Client.send(chunk, 0, chunk.length, GLOBAL.graylogPort, address, function (err, byteCount) {
			chunksWritten++;
			if (chunksWritten == sequenceSize) {
				graylog2Client.close();
			}
		});
	}
}

function send(graylog2Client, compressedMessage, address) {
	graylog2Client.send(compressedMessage, 0, compressedMessage.length, GLOBAL.graylogPort, address, function (err, byteCount) {
		graylog2Client.close();
	});
}

function resolveAndSend(graylog2Client, compressedMessage, dnsName, sendFunc) {
	dns.resolve4(GLOBAL.graylogHost, function(dnsErr, addr) {
		if (dnsErr) {
			util.debug("Graylog oops: DNS Error (" + dnsErr + "), I print to stderr and give up: \n" + message.toString());
			return;
		}

		sendFunc(graylog2Client, compressedMessage, addr[0]);
	});
}

function log(shortMessage, a, b) {
	var opts = {};
	if (typeof a == 'string'){
		opts = b || {};
		opts.full_message=a;
	} else if (typeof a == 'object') {
		opts = a || {};
	}

	opts.version="1.0";
	opts.timestamp = opts.timestamp || new Date().getTime()/1000 >> 0;
	opts.host = opts.host || GLOBAL.graylogHostname;
	opts.level = opts.level !== undefined ? opts.level : GLOBAL.LOG_INFO;
	opts.facility = opts.facility || GLOBAL.graylogFacility;

	if (opts.stack) {
		retrieveFileInfo(opts);
	}

	if (GLOBAL.graylogSequence) {
		opts['_logSequence'] = GLOBAL.graylogSequence++;
	}

	opts.short_message = shortMessage;

	if (GLOBAL.graylogToConsole) {
		_logToConsole(shortMessage, opts);
	}

	var message = new Buffer(JSON.stringify(opts))
	  , sendFunc = send;

	zlib.deflate(message, function (err, compressedMessage) {
		if (err) {
			return;
		}

		var graylog2Client = dgram.createSocket("udp4");
		if (compressedMessage.length > GLOBAL.graylogChunkSize) {
			sendFunc = sendChunked;
		}

		!isIp.test(GLOBAL.graylogHost)
		?	resolveAndSend(graylog2Client, compressedMessage, GLOBAL.graylogHost, sendFunc)
		:	sendFunc(graylog2Client, compressedMessage, GLOBAL.graylogHost);
	});
}

/**
 * Retrieves the filename and line number where log() was called
 *
 * @param {Object} opts The options object that will be altered with 'file' and 'line' properties
 */
function retrieveFileInfo(opts){
	var err = new Error("test"),
		stack = (err.stack || "").toString().split(/\r?\n/),
		match;

	for(var i=0, len = stack.length; i<len; i++){
		if((match = stack[i].match(/^\s*at\s[^\(]+\(([^\):]+):(\d+):\d+\)/))){
			if(__filename.substr(-match[1].length) == match[1]){
				continue;
			}
			opts.file = match[1];
			opts.line = Number(match[2]) || 0;
			break;
		}
	}

}

GLOBAL.log = log;

<commit_msg>a bit of coding style changes<commit_after>var
	zlib = require('zlib'),
	dgram = require('dgram'),
	util = require('util'),
	dns = require('dns');

var
	isIpRegexp = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;

GLOBAL.LOG_EMERG=0;    // system is unusable
GLOBAL.LOG_ALERT=1;    // action must be taken immediately
GLOBAL.LOG_CRIT=2;     // critical conditions
GLOBAL.LOG_ERR=3;      // error conditions
GLOBAL.LOG_ERROR=3;    // because people WILL typo
GLOBAL.LOG_WARNING=4;  // warning conditions
GLOBAL.LOG_NOTICE=5;   // normal, but significant, condition
GLOBAL.LOG_INFO=6;     // informational message
GLOBAL.LOG_DEBUG=7;    // debug-level message

GLOBAL.graylogHost = 'localhost';
GLOBAL.graylogPort = 12201;
GLOBAL.graylogHostname = require('os').hostname();
GLOBAL.graylogToConsole = false;
GLOBAL.graylogFacility = 'Node.js';
GLOBAL.graylogSequence = 0;
GLOBAL.graylogChunkSize = 1100; // 8192 is the maximum

function generateMessageId() {
	return '' + (Date.now() + Math.floor(Math.random()*10000));
}

function _logToConsole(shortMessage, opts) {
	var
		consoleString = shortMessage,
		additionalFields = [];

	if (opts.full_message) {
		consoleString+=" ("+opts.full_message+")\n";
	}

	Object.keys(opts).forEach(function(key) {
		if (key[0]=='_' && key!="_logSequence") {
			additionalFields.push(
				"  " +
				key.substr(1,1024) +
				": " +
				'\033[' + 34 + 'm' +
				opts[key] +
				'\033[' + 39 + 'm'
			);
		}
	});

	if (additionalFields.length>0) {
		consoleString+="\n"+additionalFields.join("\n");
	}

	util.log(consoleString);
}

function sendChunked(graylog2Client, compressedMessage, address) {
	var
		messageId = generateMessageId(),
		sequenceSize = Math.ceil(compressedMessage.length / GLOBAL.graylogChunkSize),
		byteOffset = 0,
		chunksWritten = 0;

	if (sequenceSize > 128) {
		util.debug("Graylog oops: log message is larger than 128 chunks, I print to stderr and give up: \n" + message.toString());
		return;
	}

	for(var sequence=0; sequence<sequenceSize; sequence++) {
		var
			chunkBytes = (byteOffset + GLOBAL.graylogChunkSize) < compressedMessage.length ? GLOBAL.graylogChunkSize : (compressedMessage.length - byteOffset),
			chunk = new Buffer(chunkBytes + 12);

		chunk[0] = 0x1e;
		chunk[1] = 0x0f;
		chunk.write(messageId, 2, 8, 'ascii');
		chunk[10] = sequence;
		chunk[11] = sequenceSize;
		compressedMessage.copy(chunk, 12, byteOffset, byteOffset+chunkBytes);

		byteOffset += chunkBytes;

		graylog2Client.send(chunk, 0, chunk.length, GLOBAL.graylogPort, address, function (err, byteCount) {
			chunksWritten++;
			if (chunksWritten == sequenceSize) {
				graylog2Client.close();
			}
		});
	}
}

function sendSingleShot(graylog2Client, compressedMessage, address) {
	graylog2Client.send(compressedMessage, 0, compressedMessage.length, GLOBAL.graylogPort, address, function (err, byteCount) {
		graylog2Client.close();
	});
}

function resolveAndSend(graylog2Client, compressedMessage, dnsName, sendFunc) {
	dns.resolve4(GLOBAL.graylogHost, function(dnsErr, addr) {
		if (dnsErr) {
			util.debug("Graylog oops: DNS Error (" + dnsErr + "), I print to stderr and give up: \n" + message.toString());
			return;
		}

		sendFunc(graylog2Client, compressedMessage, addr[0]);
	});
}

function log(shortMessage, a, b) {
	var opts = {};
	if (typeof a == 'string'){
		opts = b || {};
		opts.full_message=a;
	} else if (typeof a == 'object') {
		opts = a || {};
	}

	opts.version="1.0";
	opts.timestamp = opts.timestamp || new Date().getTime()/1000 >> 0;
	opts.host = opts.host || GLOBAL.graylogHostname;
	opts.level = opts.level !== undefined ? opts.level : GLOBAL.LOG_INFO;
	opts.facility = opts.facility || GLOBAL.graylogFacility;

	if (opts.stack) {
		retrieveFileInfo(opts);
	}

	if (GLOBAL.graylogSequence) {
		opts['_logSequence'] = GLOBAL.graylogSequence++;
	}

	opts.short_message = shortMessage;

	if (GLOBAL.graylogToConsole) {
		_logToConsole(shortMessage, opts);
	}

	var
		message = new Buffer(JSON.stringify(opts)),
		sendFunc = sendSingleShot;

	zlib.deflate(message, function (err, compressedMessage) {
		if (err) {
			return;
		}

		var graylog2Client = dgram.createSocket("udp4");
		if (compressedMessage.length > GLOBAL.graylogChunkSize) {
			sendFunc = sendChunked;
		}

		if (!isIpRegexp.test(GLOBAL.graylogHost)) {
			resolveAndSend(graylog2Client, compressedMessage, GLOBAL.graylogHost, sendFunc);
		} else {
			sendFunc(graylog2Client, compressedMessage, GLOBAL.graylogHost);
		}
	});
}

/**
 * Retrieves the filename and line number where log() was called
 *
 * @param {Object} opts The options object that will be altered with 'file' and 'line' properties
 */
function retrieveFileInfo(opts){
	var err = new Error("test"),
		stack = (err.stack || "").toString().split(/\r?\n/),
		match;

	for (var i=0, len = stack.length; i<len; i++){
		if ((match = stack[i].match(/^\s*at\s[^\(]+\(([^\):]+):(\d+):\d+\)/))){
			if (__filename.substr(-match[1].length) == match[1]){
				continue;
			}
			opts.file = match[1];
			opts.line = Number(match[2]) || 0;
			break;
		}
	}
}

GLOBAL.log = log;

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types'; // eslint-disable-line import/no-extraneous-dependencies
import './scss/widget.scss';

const NextTripWidget = ({ nextTrip, color }) => {
  let sectionClasses = 'card next';

  if (color) {
    sectionClasses += ` ${color}`;
  }

  return (

        Next trip:

        {nextTrip.destination}

        {new Date(nextTrip.dateFrom).toDateString()}
         -
        {new Date(nextTrip.dateUntil).toDateString()}

      { nextTrip.description ?
{nextTrip.description}
 : '' }

  );
};

NextTripWidget.defaultProps = {
  nextTrip: {},
  color: ''
};

NextTripWidget.propTypes = {
  nextTrip: PropTypes.shape({
    destination: PropTypes.string,
    dateFrom: PropTypes.string,
    dateUntil: PropTypes.string,
    description: PropTypes.string
  }),
  color: PropTypes.string,
};

export default NextTripWidget;
<commit_msg>Do not show NextTrip if no next trip defined<commit_after>import React from 'react';
import PropTypes from 'prop-types'; // eslint-disable-line import/no-extraneous-dependencies
import './scss/widget.scss';

const NextTripWidget = ({ nextTrip, color }) => {
  if (Object.keys(nextTrip).length === 0) {
    return '';
  }

  let sectionClasses = 'card next';
  if (color) {
    sectionClasses += ` ${color}`;
  }

  return (

        Next trip:

        {nextTrip.destination}

        {new Date(nextTrip.dateFrom).toDateString()}
         -
        {new Date(nextTrip.dateUntil).toDateString()}

      { nextTrip.description ?
{nextTrip.description}
 : '' }

  );
};

NextTripWidget.defaultProps = {
  nextTrip: {},
  color: ''
};

NextTripWidget.propTypes = {
  nextTrip: PropTypes.shape({
    destination: PropTypes.string,
    dateFrom: PropTypes.string,
    dateUntil: PropTypes.string,
    description: PropTypes.string
  }),
  color: PropTypes.string,
};

export default NextTripWidget;
<|endoftext|>


<commit_before>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var fs = require('./utils/fs');
var helper = require('./utils/config-helper');
var component, paths, pkg;

function getConfig(){
    component = helper.getConfig();
    component.release = (typeof component.release == 'string') ?
        ['git', 'gh-pages', component.release] :
        component.release;
}

function ghPagesRelease(message){
    getConfig();
    if (component.release.indexOf('s3') <0){
        log.info('Skipping gh-pages Release');
        return Promise.resolve();
    }
    var ghPages = require('gh-pages');
    message = message || 'Update';
    log.info("\nReleasing to gh-pages\n");
    return new Promise(function(resolve, reject){
        ghPages.publish(component.paths.site.root, {message: message }, function(err) {
            ghPages.clean();
            err && reject(err);
            !err && resolve();
        });
    });
}

function s3(version){
    getConfig();
    if (component.release.indexOf('s3') <0){
        log.info('Skipping S3 Release');
        return Promise.resolve();
    }
    log.info("\nReleasing s3\n");
    var Release = require('./wrappers/s3');
    var options = (component['s3']) || {};
    var target = options.target || options.directoryPrefix || '';//deprecate directoryPrefix
    if (version){
        target = target.replace(/("|\/)[0-9]+\.[0-9]+\.[0-9]\-?(?:(?:[0-9A-Za-z-]+\.?)+)?("|\/)/g, '$1' + version + '$2');
    }
    return new Release(component.paths.site.root + '/**/*.*', target, options).write();
}

function releaseGit(version){
    getConfig();
    if (component.release.indexOf('git') <0){
        log.info('Skipping Git Release');
        return Promise.resolve();
    }
    var git = require('./utils/git');
    if (!git.checkRemote()){
        log.onError(['No valid Remote Git URL.',
            'Please update your `.git/config` file or run:',
            '$ component init git'].join('\n'));
    }
    version = version || component.pkg.version;
    log.info('Releasing to Git');
    return git.release(version);
}

function run(type){
    var bump = require('./bump').run;
    var bumpedVersion;
    return bump(type).then(function(version) {
        bumpedVersion = version;
        return releaseGit(version);
    }).then(function(){
        return ghPagesRelease('v' + bumpedVersion);
    }).then(function(){
        return s3(bumpedVersion);
    }).catch(log.onError);
}

module.exports = {
    git: releaseGit,
    'gh-pages': ghPagesRelease,
    s3: s3,
    run: run,
    all: run,
    adhoc: run
};
<commit_msg>fix tests<commit_after>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var fs = require('./utils/fs');
var helper = require('./utils/config-helper');
var component, paths, pkg;

function getConfig(){
    component = helper.getConfig();
    component.release = (typeof component.release == 'string') ?
        ['git', 'gh-pages', component.release] :
        component.release;
}

function ghPagesRelease(message){
    getConfig();
    if (component.release.indexOf('s3') <0){
        log.info('Skipping gh-pages Release');
        return Promise.resolve();
    }
    var ghPages = require('gh-pages');
    message = message || 'Update';
    log.info("\nReleasing to gh-pages\n");
    return new Promise(function(resolve, reject){
        ghPages.publish(component.paths.site.root, {message: message }, function(err) {
            ghPages.clean();
            err && reject(err);
            !err && resolve();
        });
    });
}

function s3(version){
    getConfig();
    if (component.release.indexOf('s3') <0){
        log.info('Skipping S3 Release');
        return Promise.resolve();
    }
    log.info("\nReleasing s3\n");
    var Release = require('./wrappers/s3');
    var options = component.s3 || {};
    var target = options.target || options.directoryPrefix || '';//deprecate directoryPrefix
    if (version){
        target = target.replace(/("|\/)[0-9]+\.[0-9]+\.[0-9]\-?(?:(?:[0-9A-Za-z-]+\.?)+)?("|\/)/g, '$1' + version + '$2');
    }
    return new Release(component.paths.site.root + '/**/*.*', target, options).write();
}

function releaseGit(version){
    getConfig();
    if (component.release.indexOf('git') <0){
        log.info('Skipping Git Release');
        return Promise.resolve();
    }
    var git = require('./utils/git');
    if (!git.checkRemote()){
        log.onError(['No valid Remote Git URL.',
            'Please update your `.git/config` file or run:',
            '$ component init git'].join('\n'));
    }
    version = version || component.pkg.version;
    log.info('Releasing to Git');
    return git.release(version);
}

function run(type){
    var bump = require('./bump').run;
    var bumpedVersion;
    return bump(type).then(function(version) {
        bumpedVersion = version;
        return releaseGit(version);
    }).then(function(){
        return ghPagesRelease('v' + bumpedVersion);
    }).then(function(){
        return s3(bumpedVersion);
    }).catch(log.onError);
}

module.exports = {
    git: releaseGit,
    'gh-pages': ghPagesRelease,
    s3: s3,
    run: run,
    all: run,
    adhoc: run
};
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    pkg: grunt.file.readJSON('package.json'),

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      gruntfile: {
        src: 'Gruntfile.js'
      }
    },

    sass: {
      options: {
        style: 'expanded',
        require: ['./config/initializers/sass']
      },
      'tmp/styles/main.css': [
        'app/styles/main.scss'
      ]
    },

    cssmin: {
      'public/styles/main.css': 'tmp/styles/main.css'
    },

    requirejs: {
      options: {
        baseUrl: "app/scripts",
        mainConfigFile: "app/scripts/main.js",
        name: "main",
        out: "public/scripts/main.js"
      },
      scripts: {
      }
    },

    copy: {
      'public/scripts/require.js': 'components/requirejs/require.js'
    },

    clean: ['public/assets/', 'tmp/']

  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-requirejs');

  // Default task.
  grunt.registerTask('default', 'build');

  // Build task.
  grunt.registerTask('build', ['jshint', 'sass', 'cssmin', 'requirejs']);

};

<commit_msg>Rename built output file<commit_after>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    pkg: grunt.file.readJSON('package.json'),

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      gruntfile: {
        src: 'Gruntfile.js'
      }
    },

    sass: {
      options: {
        style: 'expanded',
        require: ['./config/initializers/sass']
      },
      'tmp/styles/main.css': [
        'app/styles/main.scss'
      ]
    },

    cssmin: {
      'public/styles/main.css': 'tmp/styles/main.css'
    },

    requirejs: {
      options: {
        baseUrl: "app/scripts",
        mainConfigFile: "app/scripts/application.js",
        name: "main",
        out: "public/scripts/application.js"
      },
      scripts: {
      }
    },

    copy: {
      'public/scripts/require.js': 'components/requirejs/require.js'
    },

    clean: ['public/assets/', 'tmp/']

  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-requirejs');

  // Default task.
  grunt.registerTask('default', 'build');

  // Build task.
  grunt.registerTask('build', ['jshint', 'sass', 'cssmin', 'requirejs']);

};

<|endoftext|>