<commit_before>import PropTypes from 'prop-types';
import React, { Children, cloneElement } from 'react';
import { TRANSITION_DURATION_MS, TRANSITION_SCALE_ADJUSTMENT_Y } from './constants';

const DelayedItems = WrappedComponent => class extends React.PureComponent {

  static propTypes = {
    children: PropTypes.node,
    applyDelays: PropTypes.bool,
    reverse: PropTypes.bool,
  };

  constructor(props) {
    super(props);
    const { children } = this.props;
    this.state = { children };
  }

  componentWillReceiveProps({ applyDelays: nextApplyDelays }) {
    const { applyDelays, children } = this.props;
    if (applyDelays !== nextApplyDelays) {
      this.setState({
        children: nextApplyDelays ? this.applyTransitionDelays() : children,
      });
    }
  }

  applyTransitionDelays() {
    const { children, reverse } = this.props;
    const numItems = Children.count(children);
    const transitionDuration = TRANSITION_DURATION_MS / 1000;
    const start = TRANSITION_SCALE_ADJUSTMENT_Y;
    const delayedChildren = Children.map(children, (child, index) => {
      let itemDelayFraction;
      if (reverse) {
        itemDelayFraction = (numItems - index) / numItems;
      } else {
        itemDelayFraction = index / numItems;
      }
      const delay = (start + (itemDelayFraction * (1 - start))) * transitionDuration;
      return cloneElement(child, { delay });
    });
    return delayedChildren;
  }

  render() {
    const {
      applyDelays, // eslint-disable-line no-unused-vars
      children, // eslint-disable-line no-unused-vars
      reverse, // eslint-disable-line no-unused-vars
      ...otherProps
    } = this.props;
    return (
      <WrappedComponent
        {...this.state}
        {...otherProps}
      />
    );
  }
};
export default DelayedItems;
<commit_msg>Allow menu items to be dynamically added<commit_after>import PropTypes from 'prop-types';
import React, { Children, cloneElement } from 'react';
import { TRANSITION_DURATION_MS, TRANSITION_SCALE_ADJUSTMENT_Y } from './constants';

const DelayedItems = WrappedComponent => class extends React.PureComponent {

  static propTypes = {
    children: PropTypes.node,
    applyDelays: PropTypes.bool,
    reverse: PropTypes.bool,
  };

  constructor(props) {
    super(props);
    const { children } = this.props;
    this.state = { children };
  }

  componentWillReceiveProps({ applyDelays: nextApplyDelays, children: nextChildren }) {
    const { applyDelays, children } = this.props;
    const isEqualChildren = () => {
      if (children.length !== nextChildren.length) {
        return false
      }
      let i = children.length;
      if (i != nextChildren.length) return false;
      while (i--) {
        if (children[i] !== nextChildren[i]) return false;
      }
      return true;
    }
    if (applyDelays !== nextApplyDelays) {
      this.setState({
        children: nextApplyDelays ? this.applyTransitionDelays() : children,
      });
    } else if (!isEqualChildren()) {
      this.setState({children: nextChildren})
    }
  }

  applyTransitionDelays() {
    const { children, reverse } = this.props;
    const numItems = Children.count(children);
    const transitionDuration = TRANSITION_DURATION_MS / 1000;
    const start = TRANSITION_SCALE_ADJUSTMENT_Y;
    const delayedChildren = Children.map(children, (child, index) => {
      let itemDelayFraction;
      if (reverse) {
        itemDelayFraction = (numItems - index) / numItems;
      } else {
        itemDelayFraction = index / numItems;
      }
      const delay = (start + (itemDelayFraction * (1 - start))) * transitionDuration;
      return cloneElement(child, { delay });
    });
    return delayedChildren;
  }

  render() {
    const {
      applyDelays, // eslint-disable-line no-unused-vars
      children, // eslint-disable-line no-unused-vars
      reverse, // eslint-disable-line no-unused-vars
      ...otherProps
    } = this.props;
    return (
      <WrappedComponent
        {...this.state}
        {...otherProps}
      />
    );
  }
};
export default DelayedItems;
<|endoftext|>


<commit_before>jQuery(document).ready( function(){

  // $('#brand').addClass('animated zoomInDown').removeClass('hidden');

  $('#heading').addClass('animated fadeIn').removeClass('hidden');

  $('.landing>#button').addClass('animated slideInRight').removeClass('hidden');

  $('#heading a#button').addClass('animated slideInUp').removeClass('hidden');

  // $('#main-nav').addClass('animated slideInLeft').removeClass('hidden');

  $('#scroll-indicator').addClass('animated bounce').removeClass('hidden');
});

$(document).ready(function() {
  $('body').addClass('js');
  var $menu = $('.sidebar'),
    $menulink = $('.menu-toggle');

$menulink.click(function() {
  $menulink.toggleClass('active');
  $menu.toggleClass('active');
  $('#page-content-wrapper').toggleClass('active');
  return false;
});});

// CURRENT PAGE INDICATOR

$(function () {
    setNavigation();
});

function setNavigation() {
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");

    $('#main-nav>a').each(function () {
      var href = $(this).attr('href');

      if ( path.substring(0, href.length) === href ) {
        if ( href.length > 1 ) {
          $(this).addClass('active');
        }
      }
      else if ( href.length == 1 ) {
        $(this).addClass('active');
      }

    });
}

function moveClouds(e, s, d) {
    $(e).css('right', '-20%');
        var wait = window.setTimeout(function(){
            $(e).animate ({
                right: '120%'
            }, s, 'linear', function() {
            moveClouds(e, s, d);
        });
    },d);
}
// if(!Modernizr.cssanimations) {
//     var clouds = [1,2,3,4];
//
//     $.each(clouds, function() {
//         var e = $('.cloud-' + this);
//         moveClouds(e, e.data('speed'), e.data('delay'));
//     });
// }

// ICON SHADOWS

! function(e) {
    function s(e, t) {
        e = e.replace("#", "");
        r = parseInt(e.substring(0, 2), 16);
        g = parseInt(e.substring(2, 4), 16);
        b = parseInt(e.substring(4, 6), 16);
        result = "rgba(" + r + "," + g + "," + b + "," + t / 100 + ")";
        return result
    }

    function o(e, t) {
        e = String(e).replace(/[^0-9a-f]/gi, "");
        if (e.length < 6) {
            e = e[0] + e[0] + e[1] + e[1] + e[2] + e[2]
        }
        t = t || 0;
        var n = "#",
            r, i;
        for (i = 0; i < 3; i++) {
            r = parseInt(e.substr(i * 2, 2), 16);
            r = Math.round(Math.min(Math.max(0, r + r * t), 255)).toString(16);
            n += ("00" + r).substr(r.length)
        }
        return n
    }
    var t = new Array("#1ABC9C", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#f1c40f", "#e67e22", "#e74c3c");
    var n = new Array("NE", "SE", "SW", "NW");
    var i = {
        fade: false,
        color: "random",
        boxShadow: false,
        angle: "random"
    };
    e.fn.flatshadow = function(r) {
        var u = e.extend({}, i, r);
        return this.each(function() {
            el = e(this);
            if (u.fade == true) {
                width = Math.round(el.outerWidth() / 3);
                height = Math.round(el.outerHeight() / 3)
            } else {
                width = Math.round(el.outerWidth());
                height = Math.round(el.outerHeight())
            }
            if (u.boxShadow != false) {
                var r = u.boxShadow
            }
            if (u.color != "random" && !el.attr("data-color")) {
                var i = u.color
            } else {
                var i = t[Math.floor(Math.random() * t.length)];
                if (el.attr("data-color")) {
                    var i = el.attr("data-color")
                }
            }
            if (u.angle != "random" && !el.attr("data-angle")) {
                var a = u.angle
            } else {
                var a = n[Math.floor(Math.random() * n.length)];
                if (el.attr("data-angle")) {
                    var a = el.attr("data-angle")
                }
            }
            var f = o(i, -.3);
            var l = "";
            if (u.boxShadow != false) {
                var c = ""
            } else {
                var c = "none"
            }
            switch (a) {
                case "N":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NE":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "E":
                    for (var h = 1; h <= width; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + "0px 0px " + s(r, 50 - h / width * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + "0px 0px " + p;
                        if (h != width) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SE":
                    for (var h = 0.1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "S":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "W":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + "0px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + "0px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break
            }
            el.css({
                // background: i,
                "text-shadow": l
            })
        })
    }
}(window.jQuery);
$(document).ready(function() {
    RandHexVal = "#" + ("000000" + (Math.random() * 16777215 << 0).toString(16)).slice(-6);
    $("[class*='flat']").flatshadow({
      color: "#c0392b",
      angle: "SE",
      fade: false,
      boxShadow: "#222"
    });
    $(".flat-blue").flatshadow({
      color: "#34495e",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-turq").flatshadow({
      color: "#3498db",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-grey").flatshadow({
      color: "#ccc",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-pink").flatshadow({
      color: "#8e44ad",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-orange").flatshadow({
      color: "#e67e22",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-green").flatshadow({
      color: "#2ecc71",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-random").flatshadow({
      color: RandHexVal,
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    })

})
<commit_msg>added mailchimp ajax support and tided js<commit_after>// ANIMATE.CSS
//-------------------------------------
jQuery(document).ready( function(){
  $('#heading').addClass('animated fadeIn').removeClass('hidden');
  $('.landing>#button').addClass('animated slideInRight').removeClass('hidden');
  $('#heading a#button').addClass('animated slideInUp').removeClass('hidden');
  $('#scroll-indicator').addClass('animated bounce').removeClass('hidden');
});

// MENU TOGGLE ICON
//-------------------------------------
$(document).ready(function() {
  $('body').addClass('js');
  var $menu = $('.sidebar'),
    $menulink = $('.menu-toggle');

$menulink.click(function() {
  $menulink.toggleClass('active');
  $menu.toggleClass('active');
  $('#page-content-wrapper').toggleClass('active');
  return false;
});});

// CURRENT PAGE INDICATOR
//-------------------------------------
$(function() {
    setNavigation();
});

function setNavigation() {
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");

    $('#main-nav>a').each(function() {
        var href = $(this).attr('href');

        if (path.substring(0, href.length) === href) {
            if (href.length > 1) {
                $(this).addClass('active');
            }
        } else if (href.length == 1) {
            $(this).addClass('active');
        }

    });
}

// CLOUDS
//-------------------------------------
function moveClouds(e, s, d) {
    $(e).css('right', '-20%');
    var wait = window.setTimeout(function() {
        $(e).animate({
            right: '120%'
        }, s, 'linear', function() {
            moveClouds(e, s, d);
        });
    }, d);
}
// if(!Modernizr.cssanimations) {
//     var clouds = [1,2,3,4];
//
//     $.each(clouds, function() {
//         var e = $('.cloud-' + this);
//         moveClouds(e, e.data('speed'), e.data('delay'));
//     });
// }

// MAILCHIMP
//-------------------------------------
(function($) {
    'use strict';

    $.ajaxChimp = {
        responses: {
            'We have sent you a confirmation email': 0,
            'Please enter a valid email': 1,
            'An email address must contain a single @': 2,
            'The domain portion of the email address is invalid (the portion after the @: )': 3,
            'The username portion of the email address is invalid (the portion before the @: )': 4,
            'This email address looks fake or invalid. Please enter a real email address': 5
        },
        translations: {
            'en': null
        },
        init: function(selector, options) {
            $(selector).ajaxChimp(options);
        }
    };

    $.fn.ajaxChimp = function(options) {
        $(this).each(function(i, elem) {
            var form = $(elem);
            var email = form.find('input[type=email]');
            var label = form.find('.info');

            var settings = $.extend({
                'url': form.attr('action'),
                'language': 'en'
            }, options);

            var url = settings.url.replace('/post?', '/post-json?').concat('&c=?');

            form.attr('novalidate', 'true');
            email.attr('name', 'EMAIL');

            form.submit(function() {
                var msg;

                function successCallback(resp) {
                    if (resp.result === 'success') {
                        msg = 'We have sent you a confirmation email';
                        label.removeClass('error').addClass('valid');
                        email.removeClass('error').addClass('valid');
                    } else {
                        email.removeClass('valid').addClass('error');
                        label.removeClass('valid').addClass('error');
                        var index = -1;
                        try {
                            var parts = resp.msg.split(' - ', 2);
                            if (parts[1] === undefined) {
                                msg = resp.msg;
                            } else {
                                var i = parseInt(parts[0], 10);
                                if (i.toString() === parts[0]) {
                                    index = parts[0];
                                    msg = parts[1];
                                } else {
                                    index = -1;
                                    msg = resp.msg;
                                }
                            }
                        } catch (e) {
                            index = -1;
                            msg = resp.msg;
                        }
                    }

                    // Translate and display message
                    if (
                        settings.language !== 'en' && $.ajaxChimp.responses[msg] !== undefined && $.ajaxChimp.translations && $.ajaxChimp.translations[settings.language] && $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]
                    ) {
                        msg = $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]];
                    }
                    label.html(msg);

                    label.show(2000);
                    if (settings.callback) {
                        settings.callback(resp);
                    }
                }

                var data = {};
                var dataArray = form.serializeArray();
                $.each(dataArray, function(index, item) {
                    data[item.name] = item.value;
                });

                $.ajax({
                    url: url,
                    data: data,
                    success: successCallback,
                    dataType: 'jsonp',
                    error: function(resp, text) {
                        console.log('mailchimp ajax submit error: ' + text);
                    }
                });

                // Translate and display submit message
                var submitMsg = 'Submitting...';
                if (
                    settings.language !== 'en' && $.ajaxChimp.translations && $.ajaxChimp.translations[settings.language] && $.ajaxChimp.translations[settings.language]['submit']
                ) {
                    submitMsg = $.ajaxChimp.translations[settings.language]['submit'];
                }
                label.html(submitMsg).show(2000);

                return false;
            });
        });
        return this;
    };
})(jQuery);

// FLAT ICON SHADOWS
//-------------------------------------
! function(e) {
    function s(e, t) {
        e = e.replace("#", "");
        r = parseInt(e.substring(0, 2), 16);
        g = parseInt(e.substring(2, 4), 16);
        b = parseInt(e.substring(4, 6), 16);
        result = "rgba(" + r + "," + g + "," + b + "," + t / 100 + ")";
        return result
    }

    function o(e, t) {
        e = String(e).replace(/[^0-9a-f]/gi, "");
        if (e.length < 6) {
            e = e[0] + e[0] + e[1] + e[1] + e[2] + e[2]
        }
        t = t || 0;
        var n = "#",
            r, i;
        for (i = 0; i < 3; i++) {
            r = parseInt(e.substr(i * 2, 2), 16);
            r = Math.round(Math.min(Math.max(0, r + r * t), 255)).toString(16);
            n += ("00" + r).substr(r.length)
        }
        return n
    }
    var t = new Array("#1ABC9C", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#f1c40f", "#e67e22", "#e74c3c");
    var n = new Array("NE", "SE", "SW", "NW");
    var i = {
        fade: false,
        color: "random",
        boxShadow: false,
        angle: "random"
    };
    e.fn.flatshadow = function(r) {
        var u = e.extend({}, i, r);
        return this.each(function() {
            el = e(this);
            if (u.fade == true) {
                width = Math.round(el.outerWidth() / 3);
                height = Math.round(el.outerHeight() / 3)
            } else {
                width = Math.round(el.outerWidth());
                height = Math.round(el.outerHeight())
            }
            if (u.boxShadow != false) {
                var r = u.boxShadow
            }
            if (u.color != "random" && !el.attr("data-color")) {
                var i = u.color
            } else {
                var i = t[Math.floor(Math.random() * t.length)];
                if (el.attr("data-color")) {
                    var i = el.attr("data-color")
                }
            }
            if (u.angle != "random" && !el.attr("data-angle")) {
                var a = u.angle
            } else {
                var a = n[Math.floor(Math.random() * n.length)];
                if (el.attr("data-angle")) {
                    var a = el.attr("data-angle")
                }
            }
            var f = o(i, -.3);
            var l = "";
            if (u.boxShadow != false) {
                var c = ""
            } else {
                var c = "none"
            }
            switch (a) {
                case "N":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NE":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "E":
                    for (var h = 1; h <= width; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + "0px 0px " + s(r, 50 - h / width * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + "0px 0px " + p;
                        if (h != width) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SE":
                    for (var h = 0.1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "S":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "W":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + "0px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + "0px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break
            }
            el.css({
                // background: i,
                "text-shadow": l
            })
        })
    }
}(window.jQuery);
$(document).ready(function() {
    RandHexVal = "#" + ("000000" + (Math.random() * 16777215 << 0).toString(16)).slice(-6);
    $("[class*='flat']").flatshadow({
      color: "#c0392b",
      angle: "SE",
      fade: false,
      boxShadow: "#222"
    });
    $(".flat-blue").flatshadow({
      color: "#34495e",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-turq").flatshadow({
      color: "#3498db",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-grey").flatshadow({
      color: "#ccc",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-pink").flatshadow({
      color: "#8e44ad",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-orange").flatshadow({
      color: "#e67e22",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-green").flatshadow({
      color: "#2ecc71",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-random").flatshadow({
      color: RandHexVal,
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    })

})
<|endoftext|>


<commit_before>/* global describe it */

var assert = require('assert')
var blacklist = require('../')

describe('blacklist', function () {
  it('blacklists properties in a filter object', function () {
    var someInput = { a: 1, b: 2, c: 3 }
    var result = blacklist(someInput, {
      a: true,   // a will not be in the result
      b: false,  // b will be in the result
      c: 1 > 2   // false, therefore c will be in the result
    })

    assert.deepEqual(result, { b: 2, c: 3 })
  })
  it('accepts n string arguments', function () {
    var someInput = { a: 1, b: 2, c: 3 }
    var result = blacklist(someInput, 'b', 'c')

    assert.deepEqual(result, { a: 1 })
  })
})
<commit_msg>tests: remove comments, remove inline expression (fixing standard)<commit_after>/* global describe it */

var assert = require('assert')
var blacklist = require('../')

describe('blacklist', function () {
  it('blacklists properties in a filter object', function () {
    var someInput = { a: 1, b: 2, c: 3 }
    var result = blacklist(someInput, {
      a: true,
      b: false,
      c: false
    })

    assert.deepEqual(result, { b: 2, c: 3 })
  })

  it('accepts n string arguments', function () {
    var someInput = { a: 1, b: 2, c: 3 }
    var result = blacklist(someInput, 'b', 'c')

    assert.deepEqual(result, { a: 1 })
  })
})
<|endoftext|>


<commit_before>import { LineBasicMaterial, Box3Helper, Box3, Group, LineSegments } from 'three';
import { arrayToBox } from './Utils/ArrayBoxUtilities.js';

const wiremat = new LineBasicMaterial( { color: 0x00FF88, transparent: true, opacity: 0.3 } );
const boxGeom = new Box3Helper().geometry;
let boundingBox = new Box3();

class MeshBVHRootVisualizer extends Group {

	constructor( mesh, depth = 10, group = 0 ) {

		super( 'MeshBVHRootVisualizer' );

		this.depth = depth;
		this._oldDepth = - 1;
		this.mesh = mesh;
		this._boundsTree = null;
		this._group = group;

		this.update();

	}

	update() {

		this._oldDepth = this.depth;
		this._boundsTree = this.mesh.geometry.boundsTree;

		let requiredChildren = 0;
		if ( this._boundsTree ) {

			this._boundsTree.traverse( ( depth, isLeaf, boundingData, offsetOrSplit, countOrIsUnfinished ) => {

				let isTerminal = isLeaf || countOrIsUnfinished;

				// Stop traversal
				if ( depth >= this.depth ) {

					return true;

				}

				if ( depth === this.depth - 1 || isTerminal ) {

					let m = requiredChildren < this.children.length ? this.children[ requiredChildren ] : null;
					if ( ! m ) {

						m = new LineSegments( boxGeom, wiremat );
						m.raycast = () => [];
						this.add( m );

					}
					requiredChildren ++;
					arrayToBox( boundingData, boundingBox );
					boundingBox.getCenter( m.position );
					m.scale.subVectors( boundingBox.max, boundingBox.min ).multiplyScalar( 0.5 );

					if ( m.scale.x === 0 ) m.scale.x = Number.EPSILON;
					if ( m.scale.y === 0 ) m.scale.y = Number.EPSILON;
					if ( m.scale.z === 0 ) m.scale.z = Number.EPSILON;

				}

			} );

		}

		while ( this.children.length > requiredChildren ) this.remove( this.children.pop() );

	}

}

class MeshBVHVisualizer extends Group {

	constructor( mesh, depth = 10 ) {

		super( 'MeshBVHVisualizer' );

		this.depth = depth;
		this.mesh = mesh;
		this._roots = [];

		this.update();

	}

	update() {

		const bvh = this.mesh.geometry.boundsTree;
		const totalRoots = bvh ? bvh._roots.length : 0;
		while ( this._roots.length > totalRoots ) {

			this._roots.pop();

		}

		for ( let i = 0; i < totalRoots; i ++ ) {

			if ( i >= this._roots.length ) {

				const root = new MeshBVHRootVisualizer( this.mesh, this.depth, i );
				this.add( root );
				this._roots.push( root );

			} else {

				let root = this._roots[ i ];
				root.depth = this.depth;
				root.update();

			}

		}

		this.position.copy( this.mesh.position );
		this.rotation.copy( this.mesh.rotation );
		this.scale.copy( this.mesh.scale );

	}

	copy( source ) {

		this.depth = source.depth;
		this.mesh

	}

}

export default MeshBVHVisualizer;
<commit_msg>add updatematrix world<commit_after>import { LineBasicMaterial, Box3Helper, Box3, Group, LineSegments } from 'three';
import { arrayToBox } from './Utils/ArrayBoxUtilities.js';

const wiremat = new LineBasicMaterial( { color: 0x00FF88, transparent: true, opacity: 0.3 } );
const boxGeom = new Box3Helper().geometry;
let boundingBox = new Box3();

class MeshBVHRootVisualizer extends Group {

	constructor( mesh, depth = 10, group = 0 ) {

		super( 'MeshBVHRootVisualizer' );

		this.depth = depth;
		this._oldDepth = - 1;
		this.mesh = mesh;
		this._boundsTree = null;
		this._group = group;

		this.update();

	}

	update() {

		this._oldDepth = this.depth;
		this._boundsTree = this.mesh.geometry.boundsTree;

		let requiredChildren = 0;
		if ( this._boundsTree ) {

			this._boundsTree.traverse( ( depth, isLeaf, boundingData, offsetOrSplit, countOrIsUnfinished ) => {

				let isTerminal = isLeaf || countOrIsUnfinished;

				// Stop traversal
				if ( depth >= this.depth ) {

					return true;

				}

				if ( depth === this.depth - 1 || isTerminal ) {

					let m = requiredChildren < this.children.length ? this.children[ requiredChildren ] : null;
					if ( ! m ) {

						m = new LineSegments( boxGeom, wiremat );
						m.raycast = () => [];
						this.add( m );

					}
					requiredChildren ++;
					arrayToBox( boundingData, boundingBox );
					boundingBox.getCenter( m.position );
					m.scale.subVectors( boundingBox.max, boundingBox.min ).multiplyScalar( 0.5 );

					if ( m.scale.x === 0 ) m.scale.x = Number.EPSILON;
					if ( m.scale.y === 0 ) m.scale.y = Number.EPSILON;
					if ( m.scale.z === 0 ) m.scale.z = Number.EPSILON;

				}

			} );

		}

		while ( this.children.length > requiredChildren ) this.remove( this.children.pop() );

	}

}

class MeshBVHVisualizer extends Group {

	constructor( mesh, depth = 10 ) {

		super( 'MeshBVHVisualizer' );

		this.depth = depth;
		this.mesh = mesh;
		this._roots = [];

		this.update();

	}

	update() {

		const bvh = this.mesh.geometry.boundsTree;
		const totalRoots = bvh ? bvh._roots.length : 0;
		while ( this._roots.length > totalRoots ) {

			this._roots.pop();

		}

		for ( let i = 0; i < totalRoots; i ++ ) {

			if ( i >= this._roots.length ) {

				const root = new MeshBVHRootVisualizer( this.mesh, this.depth, i );
				this.add( root );
				this._roots.push( root );

			} else {

				let root = this._roots[ i ];
				root.depth = this.depth;
				root.update();

			}

		}

	}

	updateMatrixWorld( ...args ) {

		this.position.copy( this.mesh.position );
		this.rotation.copy( this.mesh.rotation );
		this.scale.copy( this.mesh.scale );

		super.updateMatrixWorld( ...args );

	}

	copy( source ) {

		this.depth = source.depth;
		this.mesh = source.mesh;

	}

	clone() {

		return new MeshBVHVisualizer( this.mesh, this.depth );

	}

}

export default MeshBVHVisualizer;
<|endoftext|>


<commit_before>/*!
 Copyright (c) 2015 Zalando SE

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

'use strict';

const assert = require('assert');
const banknote = require('../');

const ALL_KNOWN_LOCALES = Object.keys(require('../data/separators'));
const COUNTRY_CURRENCY_MAP = require('../data/country-currency');
const EXPECTED_US_OPTIONS = {
    decimalSeparator: '.',
    thousandSeparator: ',',
    currencyCode: 'USD',
    currencySymbol: '$',
    subunitsPerUnit: 100,
    showDecimalIfWhole: true
};

describe('banknote', function () {

    describe('formattingOptionsForLocale', function () {

        it('should throw for missing locale', function () {
            assert.throws(function () {
                banknote.formattingForLocale();
            });
        });

        it('should throw for unknown locale', function () {
            assert.throws(function () {
                banknote.formattingForLocale('i-klingon');
            });
        });

        it('should throw for a locale without a region', function () {
            assert.throws(function () {
                banknote.formattingForLocale('en');
            });
        });

        it('should give a full options given a valid locale with a territory', function () {
            const options = banknote.formattingForLocale('en-US');
            assert.equal(typeof options.currencyFormatter, 'function');
            delete options.currencyFormatter;
            assert.deepEqual(options, EXPECTED_US_OPTIONS);
        });

        it('should work for all known locales given an explicit currency', function () {
            ALL_KNOWN_LOCALES.forEach(function (locale) {
                assert(typeof banknote.formattingForLocale(locale, 'USD'), 'object');
            });
        });

        it('should work for all known locales where region is a valid country code', function () {
            ALL_KNOWN_LOCALES.forEach(function (locale) {
                var region = locale.split('-')[1];
                if (region && region.length === 2 && (region in COUNTRY_CURRENCY_MAP)) {
                    assert(typeof banknote.formattingForLocale(locale), 'object');
                }
            });
        });

    });

    describe('currencyForCountry', function () {
        it('should allow to find a currency code from the country code', function () {
            assert.equal(banknote.currencyForCountry('US'), 'USD');
            assert.equal(banknote.currencyForCountry('DE'), 'EUR');
        });
    });

    describe('formatSubunitAmount', function () {

        it('should work for "en-US" locale', function () {
            const options = banknote.formattingForLocale('en-US');
            assert.equal(banknote.formatSubunitAmount(123456, options), '$1,234.56');
        });

        it('should work for "de-AT" locale', function () {
            const options = banknote.formattingForLocale('de-AT');
            assert.equal(banknote.formatSubunitAmount(-123456, options), '-€ 1 234,56');
        });

        it('should work for "de-CH" locale', function () {
            const options = banknote.formattingForLocale('de-CH');
            assert.equal(banknote.formatSubunitAmount(-123456, options), 'CHF-1\'234.56');
        });

        it('should work for "en-US" locale with "EUR" currency', function () {
            const options = banknote.formattingForLocale('en-US', 'EUR');
            assert.equal(banknote.formatSubunitAmount(123456, options), '€1,234.56');
        });

        it('should work for "de" locale with "EUR" currency', function () {
            const options = banknote.formattingForLocale('de', 'EUR');
            assert.equal(banknote.formatSubunitAmount(123456, options), '1.234,56 €');
        });

        it('should correctly fill up the cents amount', function () {
            const options = banknote.formattingForLocale('de-DE');
            assert.equal(banknote.formatSubunitAmount(123406, options), '1.234,06 €');
        });

        it('should correctly hide decimal when appropriate options is specified', function () {
            const options = banknote.formattingForLocale('de-DE');
            options.showDecimalIfWhole = false;
            assert.equal(banknote.formatSubunitAmount(123400, options), '1.234 €');
        });

    });
});
<commit_msg>add test for no-NO<commit_after>/*!
 Copyright (c) 2015 Zalando SE

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

'use strict';

const assert = require('assert');
const banknote = require('../');

const ALL_KNOWN_LOCALES = Object.keys(require('../data/separators'));
const COUNTRY_CURRENCY_MAP = require('../data/country-currency');
const EXPECTED_US_OPTIONS = {
    decimalSeparator: '.',
    thousandSeparator: ',',
    currencyCode: 'USD',
    currencySymbol: '$',
    subunitsPerUnit: 100,
    showDecimalIfWhole: true
};

describe('banknote', function () {

    describe('formattingOptionsForLocale', function () {

        it('should throw for missing locale', function () {
            assert.throws(function () {
                banknote.formattingForLocale();
            });
        });

        it('should throw for unknown locale', function () {
            assert.throws(function () {
                banknote.formattingForLocale('i-klingon');
            });
        });

        it('should throw for a locale without a region', function () {
            assert.throws(function () {
                banknote.formattingForLocale('en');
            });
        });

        it('should give a full options given a valid locale with a territory', function () {
            const options = banknote.formattingForLocale('en-US');
            assert.equal(typeof options.currencyFormatter, 'function');
            delete options.currencyFormatter;
            assert.deepEqual(options, EXPECTED_US_OPTIONS);
        });

        it('should work for all known locales given an explicit currency', function () {
            ALL_KNOWN_LOCALES.forEach(function (locale) {
                assert(typeof banknote.formattingForLocale(locale, 'USD'), 'object');
            });
        });

        it('should work for all known locales where region is a valid country code', function () {
            ALL_KNOWN_LOCALES.forEach(function (locale) {
                var region = locale.split('-')[1];
                if (region && region.length === 2 && (region in COUNTRY_CURRENCY_MAP)) {
                    assert(typeof banknote.formattingForLocale(locale), 'object');
                }
            });
        });

    });

    describe('currencyForCountry', function () {
        it('should allow to find a currency code from the country code', function () {
            assert.equal(banknote.currencyForCountry('US'), 'USD');
            assert.equal(banknote.currencyForCountry('DE'), 'EUR');
        });
    });

    describe('formatSubunitAmount', function () {

        it('should work for "en-US" locale', function () {
            const options = banknote.formattingForLocale('en-US');
            assert.equal(banknote.formatSubunitAmount(123456, options), '$1,234.56');
        });

        it('should work for "de-AT" locale', function () {
            const options = banknote.formattingForLocale('de-AT');
            assert.equal(banknote.formatSubunitAmount(-123456, options), '-€ 1 234,56');
        });

        it('should work for "de-CH" locale', function () {
            const options = banknote.formattingForLocale('de-CH');
            assert.equal(banknote.formatSubunitAmount(-123456, options), 'CHF-1\'234.56');
        });

        it('should work for "en-US" locale with "EUR" currency', function () {
            const options = banknote.formattingForLocale('en-US', 'EUR');
            assert.equal(banknote.formatSubunitAmount(123456, options), '€1,234.56');
        });

        it('should work for "de" locale with "EUR" currency', function () {
            const options = banknote.formattingForLocale('de', 'EUR');
            assert.equal(banknote.formatSubunitAmount(123456, options), '1.234,56 €');
        });

        it('should work for "no" locale with "NOK" currency', function () {
            const options = banknote.formattingForLocale('no-NO', 'NOK');
            assert.equal(banknote.formatSubunitAmount(123456, options), '1 234,56 kr');
        });

        it('should correctly fill up the cents amount', function () {
            const options = banknote.formattingForLocale('de-DE');
            assert.equal(banknote.formatSubunitAmount(123406, options), '1.234,06 €');
        });

        it('should correctly hide decimal when appropriate options is specified', function () {
            const options = banknote.formattingForLocale('de-DE');
            options.showDecimalIfWhole = false;
            assert.equal(banknote.formatSubunitAmount(123400, options), '1.234 €');
        });

    });
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var assert = require('assert');
var lex = require('../');
var dir = __dirname + '/cases/';
var hasErrors = true;

fs.readdirSync(dir).forEach(function (testCase) {
  if (/\.jade$/.test(testCase)) {
    console.dir(testCase);
    var expected = fs.readFileSync(dir + testCase.replace(/\.jade$/, '.expected.json'), 'utf8')
                     .split(/\n/).map(JSON.parse);
    var result = lex(fs.readFileSync(dir + testCase, 'utf8'), dir + testCase);
    var hasErrors = false;
    fs.writeFileSync(dir + testCase.replace(/\.jade$/, '.actual.json'),
                     result.map(JSON.stringify).join('\n'));

    try {
      assert.deepEqual(expected, result);
    } catch (ex) {
      console.error(ex + '\n');
      hasErrors = true;
    }
  }
});

if (hasErrors) throw new Error('Some test cases failed');

var edir = __dirname + '/errors/';

fs.readdirSync(edir).forEach(function (testCase) {
  if (/\.jade$/.test(testCase)) {
    console.dir(testCase);
    var expected = JSON.parse(fs.readFileSync(edir + testCase.replace(/\.jade$/, '.json'), 'utf8'));
    var actual;
    try {
      lex(fs.readFileSync(edir + testCase, 'utf8'), edir + testCase);
      throw new Error('Expected ' + testCase + ' to throw an exception.');
    } catch (ex) {
      if (!ex || !ex.code || !ex.code.indexOf('JADE:') === 0) throw ex;
      actual = {
        msg: ex.msg,
        code: ex.code,
        line: ex.line
      };
    }
    assert.deepEqual(expected, actual);
  }
});
<commit_msg>> Improve test runner to continue when cases have errors<commit_after>'use strict';

var fs = require('fs');
var assert = require('assert');
var lex = require('../');
var dir = __dirname + '/cases/';
var dirCount = 0;
var hasCaseErrors = true;
var caseErrorCount = 0;

fs.readdirSync(dir).forEach(function (testCase) {
  if (/\.jade$/.test(testCase)) {
    console.dir(testCase);
    dirCount++;
    var expected = fs.readFileSync(dir + testCase.replace(/\.jade$/, '.expected.json'), 'utf8')
                     .split(/\n/).map(JSON.parse);
    var result = lex(fs.readFileSync(dir + testCase, 'utf8'), dir + testCase);
    var hasErrors = false;
    fs.writeFileSync(dir + testCase.replace(/\.jade$/, '.actual.json'),
                     result.map(JSON.stringify).join('\n'));

    try {
      assert.deepEqual(expected, result);
    } catch (ex) {
      console.error(ex + '\n');
      hasCaseErrors = true;
      caseErrorCount++;
    }
  }
});

if (hasCaseErrors) {
  throw caseErrorCount + ' of ' + dirCount + ' test cases failed';
}

var edir = __dirname + '/errors/';

fs.readdirSync(edir).forEach(function (testCase) {
  if (/\.jade$/.test(testCase)) {
    console.dir(testCase);
    var expected = JSON.parse(fs.readFileSync(edir + testCase.replace(/\.jade$/, '.json'), 'utf8'));
    var actual;
    try {
      lex(fs.readFileSync(edir + testCase, 'utf8'), edir + testCase);
      throw new Error('Expected ' + testCase + ' to throw an exception.');
    } catch (ex) {
      if (!ex || !ex.code || !ex.code.indexOf('JADE:') === 0) throw ex;
      actual = {
        msg: ex.msg,
        code: ex.code,
        line: ex.line
      };
    }
    assert.deepEqual(expected, actual);
  }
});
<|endoftext|>


<commit_before>var tape = require("tape"),
    isWhitespace = require("..");

var numbers = "0123456789".split(""),
    chars = "abcdefghijklmnopqrstuvwxyz".split(""),
    punctuation = "`~!@#$%^&*()_-+={}[]|\\:;\"'<,>.?/".split(""),
    spaces = [' ', '\n', '\t', '\u00A0', '\u2028', '\u2029', '\f', '\r', '\v'];

function testChars(assert, chars, result, name) {
    var i = -1,
        il = chars.length - 1,
        ch;

    while (i++ < il) {
        ch = chars[i];
        assert.equal(isWhitespace(ch), result, name);
    }
}

tape("isWhitespace(ch: Character) should return true if character is whitespace", function(assert) {

    testChars(assert, numbers, false, "should be false for numeric");
    testChars(assert, chars, false, "should be false for alphabetic");
    testChars(assert, punctuation, false, "should be false for punctuation");
    testChars(assert, spaces, true, "should be true for white space");

    assert.end();
});
<commit_msg>updates<commit_after>var tape = require("tape"),
    isWhitespace = require("..");

var alphabet = "abcdefghijklmnopqrstuvwxyz",
    chars = (alphabet + alphabet.toUpperCase()).split(""),
    numbers = "0123456789".split(""),
    punctuation = "`~!@#$%^&*()_-+={}[]|\\:;\"'<,>.?/".split(""),
    spaces = [' ', '\n', '\t', '\u00A0', '\u2028', '\u2029', '\f', '\r', '\v'];

function testChars(assert, chars, result, name) {
    var i = -1,
        il = chars.length - 1,
        ch;

    while (i++ < il) {
        ch = chars[i];
        assert.equal(isWhitespace(ch), result, name);
    }
}

tape("isWhitespace(ch: Character) should return true if character is whitespace", function(assert) {

    testChars(assert, numbers, false, "should be false for numeric");
    testChars(assert, chars, false, "should be false for alphabetic");
    testChars(assert, punctuation, false, "should be false for punctuation");
    testChars(assert, spaces, true, "should be true for white space");

    assert.end();
});
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var rimraf = require('rimraf');

var expect = require('chai').expect;
var Repository = require('../');

const remoteUrl = path.join(__dirname, 'fixtures', 'repo');
const cloneDir = path.join(__dirname, '..', '..', 'git-visit-test-tmp');

describe('repository', function() {
  this.timeout(5000);

  beforeEach(function() {
    rimraf.sync(cloneDir);
  });

  describe('show', function() {
    it('should show file contents of a specific revision', function(next) {

      var repo = new Repository(cloneDir, remoteUrl);
      repo.update(function(err) {
        expect(err).to.not.exist;

        repo.show('README.md', 'c43f0f08c9da96b951aabce724795a20ed8149ce', function(err, contents) {
          expect(err).to.not.exist;

          expect(contents).to.contain('Change 1');
          expect(contents).to.not.contain('Change 2');

          next();
        })
      });
    });
  });

  describe('visit', function() {
    it('should clone the repo if the repo does not exist', function(next) {
      var visitor = {
        counter : 0,
        visit : function(repo, commit, cb) {
          this.counter ++;
          cb();
        }
      };

      var repo = new Repository(cloneDir, remoteUrl);
      repo.visit(visitor, function(err) {
        expect(err).to.not.exist;
        expect(visitor.counter).to.equal(5);

        next();
      });
    });

    it('should get a parsed git diff numstat', function(next) {
      var repo = new Repository(cloneDir, remoteUrl);

      repo.update(function(err) {
        expect(err).to.not.exist;

        repo.initialCommit(function(err, hash) {
          expect(err).to.not.exist;

          repo.diff(hash, 'HEAD', function(err, diffs) {
            expect(err).to.not.exist;

            expect(diffs).to.exist;
            expect(diffs[0].path).to.equal('README.md');
            expect(diffs[0].added).to.equal(7);
            expect(diffs[0].deleted).to.equal(0);

            next();
          });
        });
      });
    });
  });
});
<commit_msg>Graceful delete and use project scoped test_tmp<commit_after>var path = require('path');
var fs = require('fs');
var rimraf = require('rimraf');

var expect = require('chai').expect;
var Repository = require('../');

var debug = require('debug')('git-visit');

const remoteUrl = path.join(__dirname, 'fixtures', 'repo');
const cloneDir = path.join(__dirname, '..', 'test_tmp');

describe('repository', function() {
  this.timeout(5000);

  beforeEach(function(next) {
    rimraf(cloneDir, (err) => {
      if (err) { debug(err); }
      next();
    });
  });

  describe('show', function() {
    it('should show file contents of a specific revision', function(next) {

      var repo = new Repository(cloneDir, remoteUrl);
      repo.update(function(err) {
        expect(err).to.not.exist;

        repo.show('README.md', 'c43f0f08c9da96b951aabce724795a20ed8149ce', function(err, contents) {
          expect(err).to.not.exist;

          expect(contents).to.contain('Change 1');
          expect(contents).to.not.contain('Change 2');

          next();
        })
      });
    });
  });

  describe('visit', function() {
    it('should clone the repo if the repo does not exist', function(next) {
      var visitor = {
        counter : 0,
        visit : function(repo, commit, cb) {
          this.counter ++;
          cb();
        }
      };

      var repo = new Repository(cloneDir, remoteUrl);
      repo.visit(visitor, function(err) {
        expect(err).to.not.exist;
        expect(visitor.counter).to.equal(5);

        next();
      });
    });

    it('should get a parsed git diff numstat', function(next) {
      var repo = new Repository(cloneDir, remoteUrl);

      repo.update(function(err) {
        expect(err).to.not.exist;

        repo.initialCommit(function(err, hash) {
          expect(err).to.not.exist;

          repo.diff(hash, 'HEAD', function(err, diffs) {
            expect(err).to.not.exist;

            expect(diffs).to.exist;
            expect(diffs[0].path).to.equal('README.md');
            expect(diffs[0].added).to.equal(7);
            expect(diffs[0].deleted).to.equal(0);

            next();
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

const Application = require('spectron').Application
const electron = require('electron')
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const path = require('path')
const fs = require('fs')

chai.should()
chai.use(chaiAsPromised)

const timeout = process.env.CI ? 30000 : 10000

describe('demo app', function () {
  this.timeout(timeout)

  let app

  const getUserDataPath = function () {
    const productName = require('../package').productName
    switch (process.platform) {
      case 'darwin':
        return path.join(process.env.HOME, 'Library', 'Application Support', productName)
      case 'win32':
        return path.join(process.env.APPDATA, productName)
      case 'freebsd':
      case 'linux':
      case 'sunos':
        return path.join(process.env.HOME, '.config', productName)
      default:
        throw new Error(`Unknown userDataPath path for platform ${process.platform}`)
    }
  }

  const removeStoredPreferences = function () {
    const userDataPath = getUserDataPath()
    try {
      fs.unlinkSync(path.join(userDataPath, 'activeDemoButtonId.json'))
    } catch (error) {
      if (error.code !== 'ENOENT') throw error
    }
    try {
      fs.unlinkSync(path.join(userDataPath, 'activeSectionButtonId.json'))
    } catch (error) {
      if (error.code !== 'ENOENT') throw error
    }
  }

  const setupApp = function (app) {
    app.client.addCommand('dismissAboutPage', function () {
      return this.isVisible('.js-nav').then(function (navVisible) {
        if (!navVisible) {
          return this.click('button[id="get-started"]').pause(500)
        }
      })
    })

    app.client.addCommand('selectSection', function (section) {
      return this.click('button[data-section="' + section + '"]').pause(100)
        .waitForVisible('#' + section + '-section')
    })

    app.client.addCommand('expandDemos', function () {
      return this.execute(function () {
        for (let demo of document.querySelectorAll('.demo-wrapper')) {
          demo.classList.add('is-open')
        }
      })
    })

    app.client.addCommand('collapseDemos', function () {
      return this.execute(function () {
        for (let demo of document.querySelectorAll('.demo-wrapper')) {
          demo.classList.remove('is-open')
        }
      })
    })

    app.client.addCommand('auditSectionAccessibility', function (section) {
      const options = {
        ignoreRules: ['AX_COLOR_01', 'AX_TITLE_01']
      }
      return this.selectSection(section)
        .expandDemos()
        .auditAccessibility(options).then(function (audit) {
          if (audit.failed) {
            throw Error(section + ' section failed accessibility audit\n' + audit.message)
          }
        })
    })

    chaiAsPromised.transferPromiseness = app.transferPromiseness
    return app.client.waitUntilWindowLoaded()
  }

  const startApp = function () {
    app = new Application({
      path: electron,
      args: [
        path.join(__dirname, '..')
      ],
      waitTimeout: timeout
    })

    return app.start().then(setupApp)
  }

  const restartApp = function () {
    return app.restart().then(setupApp)
  }

  before(function () {
    removeStoredPreferences()
    return startApp()
  })

  after(function () {
    if (app && app.isRunning()) {
      return app.stop()
    }
  })

  it('checks hardcoded path for userData is correct', function () {
    return app.client.execute(function () {
      return require('electron').remote.app.getPath('userData')
    }).then(function (result) {
      return result.value
    }).should.eventually.equal(getUserDataPath())
  })

  it('opens a window displaying the about page', function () {
    return app.client.getWindowCount().should.eventually.equal(1)
      .browserWindow.isMinimized().should.eventually.be.false
      .browserWindow.isDevToolsOpened().should.eventually.be.false
      .browserWindow.isVisible().should.eventually.be.true
      .browserWindow.isFocused().should.eventually.be.true
      .browserWindow.getBounds().should.eventually.have.property('width').and.be.above(0)
      .browserWindow.getBounds().should.eventually.have.property('height').and.be.above(0)
      .browserWindow.getTitle().should.eventually.equal('Electron API Demos')
      .waitForVisible('#about-modal').should.eventually.be.true
      .isVisible('.js-nav').should.eventually.be.false
      .click('button[id="get-started"]').pause(500)
      .isVisible('#about-modal').should.eventually.be.false
      .isVisible('.js-nav').should.eventually.be.true
  })

  describe('when clicking on a section from the nav bar', function () {
    it('it shows the selected section in the main area', function () {
      return app.client.dismissAboutPage()
        .selectSection('windows')
        .isExisting('button.is-selected[data-section="windows"]').should.eventually.be.true
        .isVisible('#pdf-section').should.eventually.be.false
        .selectSection('pdf')
        .isVisible('#windows-section').should.eventually.be.false
        .isExisting('button.is-selected[data-section="windows"]').should.eventually.be.false
        .isExisting('button.is-selected[data-section="pdf"]').should.eventually.be.true
    })
  })

  describe('when a demo title is clicked', function () {
    it('it expands the demo content', function () {
      let onlyFirstVisible = Array(28).fill(false)
      onlyFirstVisible[0] = true

      return app.client.dismissAboutPage()
        .collapseDemos()
        .selectSection('windows')
        .click('.js-container-target')
        .waitForVisible('.demo-box')
        .isVisible('.demo-box').should.eventually.deep.equal(onlyFirstVisible)
    })
  })

  describe('when the app is restarted after use', function () {
    it('it launches at last visted section & demo', function () {
      let onlyFirstVisible = Array(28).fill(false)
      onlyFirstVisible[0] = true

      return app.client.waitForVisible('#windows-section')
        .then(restartApp)
        .then(function () {
          return app.client.waitForVisible('#windows-section')
            .isVisible('#windows-section').should.eventually.be.true
            .isVisible('.demo-box').should.eventually.deep.equal(onlyFirstVisible)
        })
    })
  })

  it('does not contain any accessibility warnings or errors', function () {
    return app.client.dismissAboutPage()
      .auditSectionAccessibility('windows')
      .auditSectionAccessibility('crash-hang')
      .auditSectionAccessibility('menus')
      .auditSectionAccessibility('shortcuts')
      .auditSectionAccessibility('ex-links-file-manager')
      .auditSectionAccessibility('dialogs')
      .auditSectionAccessibility('tray')
      .auditSectionAccessibility('ipc')
      .auditSectionAccessibility('app-sys-information')
      .auditSectionAccessibility('clipboard')
      .auditSectionAccessibility('protocol')
      .auditSectionAccessibility('pdf')
      .auditSectionAccessibility('desktop-capturer')
  })
})
<commit_msg>Update tests<commit_after>'use strict'

const Application = require('spectron').Application
const electron = require('electron')
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const path = require('path')
const fs = require('fs')

chai.should()
chai.use(chaiAsPromised)

const timeout = process.env.CI ? 30000 : 10000

describe('demo app', function () {
  this.timeout(timeout)

  let app

  const getUserDataPath = function () {
    const productName = require('../package').productName
    switch (process.platform) {
      case 'darwin':
        return path.join(process.env.HOME, 'Library', 'Application Support', productName)
      case 'win32':
        return path.join(process.env.APPDATA, productName)
      case 'freebsd':
      case 'linux':
      case 'sunos':
        return path.join(process.env.HOME, '.config', productName)
      default:
        throw new Error(`Unknown userDataPath path for platform ${process.platform}`)
    }
  }

  const removeStoredPreferences = function () {
    const userDataPath = getUserDataPath()
    try {
      fs.unlinkSync(path.join(userDataPath, 'Settings'))
    } catch (error) {
      if (error.code !== 'ENOENT') throw error
    }
  }

  const setupApp = function (app) {
    app.client.addCommand('dismissAboutPage', function () {
      return this.isVisible('.js-nav').then(function (navVisible) {
        if (!navVisible) {
          return this.click('button[id="get-started"]').pause(500)
        }
      })
    })

    app.client.addCommand('selectSection', function (section) {
      return this.click('button[data-section="' + section + '"]').pause(100)
        .waitForVisible('#' + section + '-section')
    })

    app.client.addCommand('expandDemos', function () {
      return this.execute(function () {
        for (let demo of document.querySelectorAll('.demo-wrapper')) {
          demo.classList.add('is-open')
        }
      })
    })

    app.client.addCommand('collapseDemos', function () {
      return this.execute(function () {
        for (let demo of document.querySelectorAll('.demo-wrapper')) {
          demo.classList.remove('is-open')
        }
      })
    })

    app.client.addCommand('auditSectionAccessibility', function (section) {
      const options = {
        ignoreRules: ['AX_COLOR_01', 'AX_TITLE_01']
      }
      return this.selectSection(section)
        .expandDemos()
        .auditAccessibility(options).then(function (audit) {
          if (audit.failed) {
            throw Error(section + ' section failed accessibility audit\n' + audit.message)
          }
        })
    })

    chaiAsPromised.transferPromiseness = app.transferPromiseness
    return app.client.waitUntilWindowLoaded()
  }

  const startApp = function () {
    app = new Application({
      path: electron,
      args: [
        path.join(__dirname, '..')
      ],
      waitTimeout: timeout
    })

    return app.start().then(setupApp)
  }

  const restartApp = function () {
    return app.restart().then(setupApp)
  }

  before(function () {
    removeStoredPreferences()
    return startApp()
  })

  after(function () {
    if (app && app.isRunning()) {
      return app.stop()
    }
  })

  it('checks hardcoded path for userData is correct', function () {
    return app.client.execute(function () {
      return require('electron').remote.app.getPath('userData')
    }).then(function (result) {
      return result.value
    }).should.eventually.equal(getUserDataPath())
  })

  it('opens a window displaying the about page', function () {
    return app.client.getWindowCount().should.eventually.equal(1)
      .browserWindow.isMinimized().should.eventually.be.false
      .browserWindow.isDevToolsOpened().should.eventually.be.false
      .browserWindow.isVisible().should.eventually.be.true
      .browserWindow.isFocused().should.eventually.be.true
      .browserWindow.getBounds().should.eventually.have.property('width').and.be.above(0)
      .browserWindow.getBounds().should.eventually.have.property('height').and.be.above(0)
      .browserWindow.getTitle().should.eventually.equal('Electron API Demos')
      .waitForVisible('#about-modal').should.eventually.be.true
      .isVisible('.js-nav').should.eventually.be.false
      .click('button[id="get-started"]').pause(500)
      .isVisible('#about-modal').should.eventually.be.false
      .isVisible('.js-nav').should.eventually.be.true
  })

  describe('when clicking on a section from the nav bar', function () {
    it('it shows the selected section in the main area', function () {
      return app.client.dismissAboutPage()
        .selectSection('windows')
        .isExisting('button.is-selected[data-section="windows"]').should.eventually.be.true
        .isVisible('#pdf-section').should.eventually.be.false
        .selectSection('pdf')
        .isVisible('#windows-section').should.eventually.be.false
        .isExisting('button.is-selected[data-section="windows"]').should.eventually.be.false
        .isExisting('button.is-selected[data-section="pdf"]').should.eventually.be.true
    })
  })

  describe('when a demo title is clicked', function () {
    it('it expands the demo content', function () {
      let onlyFirstVisible = Array(28).fill(false)
      onlyFirstVisible[0] = true

      return app.client.dismissAboutPage()
        .collapseDemos()
        .selectSection('windows')
        .click('.js-container-target')
        .waitForVisible('.demo-box')
        .isVisible('.demo-box').should.eventually.deep.equal(onlyFirstVisible)
    })
  })

  describe('when the app is restarted after use', function () {
    it('it launches at last visted section & demo', function () {
      let onlyFirstVisible = Array(28).fill(false)
      onlyFirstVisible[0] = true

      return app.client.waitForVisible('#windows-section')
        .then(restartApp)
        .then(function () {
          return app.client.waitForVisible('#windows-section')
            .isVisible('#windows-section').should.eventually.be.true
            .isVisible('.demo-box').should.eventually.deep.equal(onlyFirstVisible)
        })
    })
  })

  it('does not contain any accessibility warnings or errors', function () {
    return app.client.dismissAboutPage()
      .auditSectionAccessibility('windows')
      .auditSectionAccessibility('crash-hang')
      .auditSectionAccessibility('menus')
      .auditSectionAccessibility('shortcuts')
      .auditSectionAccessibility('ex-links-file-manager')
      .auditSectionAccessibility('dialogs')
      .auditSectionAccessibility('tray')
      .auditSectionAccessibility('ipc')
      .auditSectionAccessibility('app-sys-information')
      .auditSectionAccessibility('clipboard')
      .auditSectionAccessibility('protocol')
      .auditSectionAccessibility('pdf')
      .auditSectionAccessibility('desktop-capturer')
  })
})
<|endoftext|>


<commit_before>/**
 * This ensures that a connection is made to the
 * test databases
 */
var mongooseConnection = require('gebo-mongoose-connection').get(true),
    basic = require('gebo-basic-action'),
    nativeMongoConnection = basic.nativeMongoConnection.get(true, function(){});

var extend = require('extend'),
    request = require('supertest'),
    utils = require('gebo-utils');

var events = require('events'),
    event = new events.EventEmitter();

var nconf = require('nconf');
nconf.file({ file: 'gebo.json' });
var TEST_DB = utils.getMongoDbName(nconf.get('testEmail'));

/**
 * Ensure the HTTP codes are as expected
 */
var _goodMessage = {
        sender: 'someguy@example.com',
        performative: 'request',
        action: 'ls',
        content: {
            resource: 'files',
            fields: ['_id', 'name', 'lastModified'],
        },
        access_token: 'LetMeIn',
    };

var geboDb, agentDb;

exports.httpCodes = {

    setUp: function(callback) {
        _gebo = require('..')(true);

        // The gebo, by default, redirects all requests to
        // HTTPS. This removes the redirecting function from
        // the middleware stack, which the tests don't like.
        var index = utils.getIndexOfObject(_gebo.server._router.stack, 'name', 'requireHttps');
        if (index > -1) {
          _gebo.server._router.stack.splice(index, 1);
        }

        // Make a friendo
        agentDb = new _gebo.schemata.agent();
        var friendo = new agentDb.friendoModel({
                name: 'Some guy',
                email: 'someguy@example.com',
                gebo: 'https://somegebo.com',
            });

        friendo.permissions.push({ resource: 'files',
                                   read: true,
                                   write: false,
                                   execute: false,
                                 });

        friendo.permissions.push({ resource: 'registerAgent',
                                   read: false,
                                   write: false,
                                   execute: true,
                                 });

        // Set up permissions and a token for a friendo
        geboDb = new _gebo.schemata.gebo();
        var token = new geboDb.tokenModel({
            friendoId: friendo._id,
            string: 'LetMeIn',
          });

        friendo.save(function(err) {
            if (err) {
              console.log(err);
            }
            token.save(function(err) {
                if (err) {
                  console.log(err);
                }
                callback();
              });
          });
    },

    tearDown: function(callback) {
        geboDb.connection.db.dropDatabase(function(err) {
            if (err) {
              console.log(err)
            }
            agentDb.connection.db.dropDatabase(function(err) {
                if (err) {
                  console.log(err)
                }
                callback();
              });
          });
    },

    'Respond with 200 when a well-formed request has been received': function(test) {
        request(_gebo.server).
            post('/perform').
            send(_goodMessage).
            expect(200, test.done);
    },

    'Respond with 401 when given an invalid token': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.access_token = 'InvalidToken';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(401, test.done);
    },

    'Respond with 400 when given invalid content type header': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.content = 'Content should be an object, not a string';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(400, test.done);
    },

    'Respond with 401 when an unknown sender presents a token': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.sender = 'somefakeguy@example.com';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(401, test.done);
    },

    'Respond with 500 if performing the action results in an error': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.action = 'registerAgent';
        badMessage.content = { newAgent: { email: 'someguy@example.com' } };

        // This creates an error because the message content doesn't contain
        // required friendoModel properties
        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(500, test.done);
    },

    'Respond with 501 if given an unknown performative': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.performative = 'FakePerformative';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(501, test.done);
    },

    'Respond with 501 if given an unknown action': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.action = 'hemTrousers';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(501, test.done);
    },

};

/**
 * Test modes
 */
//exports.testModes = {
//
//    setUp: function(callback) {
//        delete require.cache[require.resolve('../lib/native-mongo-connection')];
//        delete require.cache[require.resolve('gebo-mongoose-connection')];
//        delete require.cache[require.resolve('..')];
//        callback();
//    },
//
//    tearDown: function(callback) {
//        delete require.cache[require.resolve('../lib/native-mongo-connection')];
//        delete require.cache[require.resolve('gebo-mongoose-connection')];
//        delete require.cache[require.resolve('..')];
//        callback();
//    },
//
//    'Should go into test mode when the parameter is set to true': function(test) {
//        test.expect(2);
//        var gebo = require('../index')(true);
//
//        gebo.nativeMongoConnection.once('native-connect', function() {
//            gebo.nativeMongoConnection.get(function(nativeConn) {
//                test.equal(nativeConn.databaseName, TEST_DB);
//
//                // Test gebo-mongoose-connection
//                test.equal(gebo.mongoose.connection.name, TEST_DB);
//                gebo.mongoose.connection.db.close();
//                test.done();
//              });
//          });
//    },
//
//    'Should go into production mode when the parameter is not set': function(test) {
//        test.expect(2);
//        var gebo = require('../index')();
//        gebo.nativeMongoConnection.once('native-connect', function() {
//            gebo.nativeMongoConnection.get(function(nativeConn) {
//                test.equal(nativeConn.databaseName, utils.getMongoDbName(nconf.get('email')));
//
//                // Test gebo-mongoose-connection
//                test.equal(gebo.mongoose.connection.name, utils.getMongoDbName(nconf.get('email')));
//                gebo.mongoose.connection.db.close();
//                test.done();
//              });
//          });
//    },
//
//    'Should go into production mode when the parameter is set to false': function(test) {
//        test.expect(2);
//        var gebo = require('../index')(false);
//        gebo.nativeMongoConnection.once('native-connect', function() {
//            gebo.nativeMongoConnection.get(function(nativeConn) {
//                test.equal(nativeConn.databaseName, utils.getMongoDbName(nconf.get('email')));
//
//                // Test gebo-mongoose-connection
//                test.equal(gebo.mongoose.connection.name, utils.getMongoDbName(nconf.get('email')));
//                gebo.mongoose.connection.db.close();
//                test.done();
//              });
//          });
//    },
//
//};

/**
 * Add an action
 */
exports.actionAdd = {

    'Should be able to add an action': function(test) {
        test.expect(3);
        var gebo = require('../index')(true);
        test.equal(gebo.actions.testAction, undefined);

        // Create a new action
        function testAction() {
                return 'testAction, yeah yeah!';
              };

        gebo.actions.add(testAction);

        test.equal(typeof gebo.actions.testAction, 'function');
        test.equal(gebo.actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },
};

/**
 * Add a schema
 */
exports.schemaAdd = {

    'Should be able to add a schema': function(test) {
        test.expect(3);
        var gebo = require('../index')(true);
        test.equal(gebo.schemata.test, undefined);

        var testSchema = require('./schemata/mocks/test1');
        gebo.schemata.add('test', testSchema);

        test.equal(typeof gebo.schemata.test, 'function');
        var db = new gebo.schemata.test();
        test.equal(typeof db, 'object');

        test.done();
    },

    'Should be able to add a schemata object': function(test) {
        test.expect(6);

        var gebo = require('../index')(true);
        test.equal(gebo.schemata.test1, undefined);
        test.equal(gebo.schemata.test2, undefined);

        var testSchemata = require('./schemata/mocks');
        gebo.schemata.add(testSchemata);

        test.equal(typeof gebo.schemata.test1, 'function');
        var db = new gebo.schemata.test1();
        test.equal(typeof db, 'object');

        test.equal(typeof gebo.schemata.test2, 'function');
        db = new gebo.schemata.test2()
        test.equal(typeof db, 'object');

        test.done();
    },
};

/**
 * utils
 */
exports.utils = {
    'Return a mongo-friendly database name': function(test) {
        test.expect(1);
        var gebo = require('../index')(true);
        var dbName = gebo.utils.getMongoDbName('dan@example.com');
        test.equal(dbName, 'dan_at_example_dot_com');
        test.done();
    },
};

/**
 * schemata
 */
exports.schemata = {
    'Return schemata objects with which to instantiate mongoose models': function(test) {
        test.expect(5);
        var gebo = require('../index')(true);

        var dbName = new gebo.schemata.agent();
        var friendo = new dbName.friendoModel({
                name: 'Some guy',
                email: 'some@guy.com',
                gebo: 'https://somegebo.com',
            });

        test.equal(friendo.name, 'Some guy');
        test.equal(friendo.email, 'some@guy.com');
        test.equal(friendo.gebo, 'https://somegebo.com');

        dbName = new gebo.schemata.gebo();
        var registrant = new dbName.registrantModel({
                name: 'Some guy',
                email: 'some@guy.com',
            });

        test.equal(registrant.name, 'Some guy');
        test.equal(registrant.email, 'some@guy.com');

        test.done();
    },
};

/**
 * enable
 */
var _gebo;
exports.enable = {

    setUp: function(callback) {
        delete require.cache[require.resolve('../index')];
        delete require.cache[require.resolve('./mocks/full-action-module')];
        delete require.cache[require.resolve('./mocks/no-actions')];
        delete require.cache[require.resolve('./mocks/no-schema')];
        delete require.cache[require.resolve('./mocks/schema')];
        delete require.cache[require.resolve('./mocks/actions')];
        _gebo = require('..')(true);
        callback();
    },

    tearDown: function(callback) {
        // Why on earth do I have to do this? The cache deletions
        // have no impact on which schemata and actions are
        // included within the gebo. I delete these modules
        // before each test, look in the gebo after each require,
        // and there they be.
        _gebo.schemata.remove('mocks');
        _gebo.actions.remove('mocks');
        callback();
    },

    'Add schema and actions from action module': function(test) {
        test.expect(4);
        _gebo.enable('mocks', require('./mocks/full-action-module'));

        test.equal(typeof _gebo.schemata.mocks, 'function');
        var db = new _gebo.schemata.mocks();
        test.equal(typeof db.someModel, 'function');
        test.equal(typeof _gebo.actions.mocks.someAction, 'function');
        //test.equal(_gebo.actions.mocks.someAction(), 'Hi, guy!');
        _gebo.actions.mocks.someAction().
            then(function(results) {
                test.equal(results, 'Hi, guy!');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Don\'t barf if no schema is included in the action module': function(test) {
        test.expect(3);
        _gebo.enable('mocks', require('./mocks/no-schema'));
        test.equal(_gebo.schemata.mocks, undefined);
        test.equal(typeof _gebo.actions.mocks.someAction, 'function');
        //test.equal(_gebo.actions.mocks.someAction(), 'Hi, guy!');
        _gebo.actions.mocks.someAction().
            then(function(results) {
                test.equal(results, 'Hi, guy!');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Don\'t barf if no actions are included in the action module': function(test) {
        test.expect(3);
        _gebo.enable('mocks', require('./mocks/no-actions'));

        test.equal(typeof _gebo.schemata.mocks, 'function');
        var db = new _gebo.schemata.mocks();
        test.equal(typeof db.someModel, 'function');
        test.equal(_gebo.actions.mocks, undefined);
        test.done();
    },
};

<commit_msg>Uncomment test mode tests so I don't forget<commit_after>/**
 * This ensures that a connection is made to the
 * test databases
 */
var mongooseConnection = require('gebo-mongoose-connection').get(true),
    basic = require('gebo-basic-action'),
    nativeMongoConnection = basic.nativeMongoConnection.get(true, function(){});

var extend = require('extend'),
    request = require('supertest'),
    utils = require('gebo-utils');

var events = require('events'),
    event = new events.EventEmitter();

var nconf = require('nconf');
nconf.file({ file: 'gebo.json' });
var TEST_DB = utils.getMongoDbName(nconf.get('testEmail'));

/**
 * Ensure the HTTP codes are as expected
 */
var _goodMessage = {
        sender: 'someguy@example.com',
        performative: 'request',
        action: 'ls',
        content: {
            resource: 'files',
            fields: ['_id', 'name', 'lastModified'],
        },
        access_token: 'LetMeIn',
    };

var geboDb, agentDb;

exports.httpCodes = {

    setUp: function(callback) {
        _gebo = require('..')(true);

        // The gebo, by default, redirects all requests to
        // HTTPS. This removes the redirecting function from
        // the middleware stack, which the tests don't like.
        var index = utils.getIndexOfObject(_gebo.server._router.stack, 'name', 'requireHttps');
        if (index > -1) {
          _gebo.server._router.stack.splice(index, 1);
        }

        // Make a friendo
        agentDb = new _gebo.schemata.agent();
        var friendo = new agentDb.friendoModel({
                name: 'Some guy',
                email: 'someguy@example.com',
                gebo: 'https://somegebo.com',
            });

        friendo.permissions.push({ resource: 'files',
                                   read: true,
                                   write: false,
                                   execute: false,
                                 });

        friendo.permissions.push({ resource: 'registerAgent',
                                   read: false,
                                   write: false,
                                   execute: true,
                                 });

        // Set up permissions and a token for a friendo
        geboDb = new _gebo.schemata.gebo();
        var token = new geboDb.tokenModel({
            friendoId: friendo._id,
            string: 'LetMeIn',
          });

        friendo.save(function(err) {
            if (err) {
              console.log(err);
            }
            token.save(function(err) {
                if (err) {
                  console.log(err);
                }
                callback();
              });
          });
    },

    tearDown: function(callback) {
        geboDb.connection.db.dropDatabase(function(err) {
            if (err) {
              console.log(err)
            }
            agentDb.connection.db.dropDatabase(function(err) {
                if (err) {
                  console.log(err)
                }
                callback();
              });
          });
    },

    'Respond with 200 when a well-formed request has been received': function(test) {
        request(_gebo.server).
            post('/perform').
            send(_goodMessage).
            expect(200, test.done);
    },

    'Respond with 401 when given an invalid token': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.access_token = 'InvalidToken';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(401, test.done);
    },

    'Respond with 400 when given invalid content type header': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.content = 'Content should be an object, not a string';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(400, test.done);
    },

    'Respond with 401 when an unknown sender presents a token': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.sender = 'somefakeguy@example.com';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(401, test.done);
    },

    'Respond with 500 if performing the action results in an error': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.action = 'registerAgent';
        badMessage.content = { newAgent: { email: 'someguy@example.com' } };

        // This creates an error because the message content doesn't contain
        // required friendoModel properties
        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(500, test.done);
    },

    'Respond with 501 if given an unknown performative': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.performative = 'FakePerformative';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(501, test.done);
    },

    'Respond with 501 if given an unknown action': function(test) {
        var badMessage = {};
        extend(true, badMessage, _goodMessage);
        badMessage.action = 'hemTrousers';

        request(_gebo.server).
            post('/perform').
            send(badMessage).
            expect(501, test.done);
    },

};

/**
 * Test modes
 */
exports.testModes = {

    setUp: function(callback) {
        delete require.cache[require.resolve('../lib/native-mongo-connection')];
        delete require.cache[require.resolve('gebo-mongoose-connection')];
        delete require.cache[require.resolve('..')];
        callback();
    },

    tearDown: function(callback) {
        delete require.cache[require.resolve('../lib/native-mongo-connection')];
        delete require.cache[require.resolve('gebo-mongoose-connection')];
        delete require.cache[require.resolve('..')];
        callback();
    },

    'Should go into test mode when the parameter is set to true': function(test) {
        test.expect(2);
        var gebo = require('../index')(true);

        gebo.nativeMongoConnection.once('native-connect', function() {
            gebo.nativeMongoConnection.get(function(nativeConn) {
                test.equal(nativeConn.databaseName, TEST_DB);

                // Test gebo-mongoose-connection
                test.equal(gebo.mongoose.connection.name, TEST_DB);
                gebo.mongoose.connection.db.close();
                test.done();
              });
          });
    },

    'Should go into production mode when the parameter is not set': function(test) {
        test.expect(2);
        var gebo = require('../index')();
        gebo.nativeMongoConnection.once('native-connect', function() {
            gebo.nativeMongoConnection.get(function(nativeConn) {
                test.equal(nativeConn.databaseName, utils.getMongoDbName(nconf.get('email')));

                // Test gebo-mongoose-connection
                test.equal(gebo.mongoose.connection.name, utils.getMongoDbName(nconf.get('email')));
                gebo.mongoose.connection.db.close();
                test.done();
              });
          });
    },

    'Should go into production mode when the parameter is set to false': function(test) {
        test.expect(2);
        var gebo = require('../index')(false);
        gebo.nativeMongoConnection.once('native-connect', function() {
            gebo.nativeMongoConnection.get(function(nativeConn) {
                test.equal(nativeConn.databaseName, utils.getMongoDbName(nconf.get('email')));

                // Test gebo-mongoose-connection
                test.equal(gebo.mongoose.connection.name, utils.getMongoDbName(nconf.get('email')));
                gebo.mongoose.connection.db.close();
                test.done();
              });
          });
    },

};

/**
 * Add an action
 */
exports.actionAdd = {

    'Should be able to add an action': function(test) {
        test.expect(3);
        var gebo = require('../index')(true);
        test.equal(gebo.actions.testAction, undefined);

        // Create a new action
        function testAction() {
                return 'testAction, yeah yeah!';
              };

        gebo.actions.add(testAction);

        test.equal(typeof gebo.actions.testAction, 'function');
        test.equal(gebo.actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },
};

/**
 * Add a schema
 */
exports.schemaAdd = {

    'Should be able to add a schema': function(test) {
        test.expect(3);
        var gebo = require('../index')(true);
        test.equal(gebo.schemata.test, undefined);

        var testSchema = require('./schemata/mocks/test1');
        gebo.schemata.add('test', testSchema);

        test.equal(typeof gebo.schemata.test, 'function');
        var db = new gebo.schemata.test();
        test.equal(typeof db, 'object');

        test.done();
    },

    'Should be able to add a schemata object': function(test) {
        test.expect(6);

        var gebo = require('../index')(true);
        test.equal(gebo.schemata.test1, undefined);
        test.equal(gebo.schemata.test2, undefined);

        var testSchemata = require('./schemata/mocks');
        gebo.schemata.add(testSchemata);

        test.equal(typeof gebo.schemata.test1, 'function');
        var db = new gebo.schemata.test1();
        test.equal(typeof db, 'object');

        test.equal(typeof gebo.schemata.test2, 'function');
        db = new gebo.schemata.test2()
        test.equal(typeof db, 'object');

        test.done();
    },
};

/**
 * utils
 */
exports.utils = {
    'Return a mongo-friendly database name': function(test) {
        test.expect(1);
        var gebo = require('../index')(true);
        var dbName = gebo.utils.getMongoDbName('dan@example.com');
        test.equal(dbName, 'dan_at_example_dot_com');
        test.done();
    },
};

/**
 * schemata
 */
exports.schemata = {
    'Return schemata objects with which to instantiate mongoose models': function(test) {
        test.expect(5);
        var gebo = require('../index')(true);

        var dbName = new gebo.schemata.agent();
        var friendo = new dbName.friendoModel({
                name: 'Some guy',
                email: 'some@guy.com',
                gebo: 'https://somegebo.com',
            });

        test.equal(friendo.name, 'Some guy');
        test.equal(friendo.email, 'some@guy.com');
        test.equal(friendo.gebo, 'https://somegebo.com');

        dbName = new gebo.schemata.gebo();
        var registrant = new dbName.registrantModel({
                name: 'Some guy',
                email: 'some@guy.com',
            });

        test.equal(registrant.name, 'Some guy');
        test.equal(registrant.email, 'some@guy.com');

        test.done();
    },
};

/**
 * enable
 */
var _gebo;
exports.enable = {

    setUp: function(callback) {
        delete require.cache[require.resolve('../index')];
        delete require.cache[require.resolve('./mocks/full-action-module')];
        delete require.cache[require.resolve('./mocks/no-actions')];
        delete require.cache[require.resolve('./mocks/no-schema')];
        delete require.cache[require.resolve('./mocks/schema')];
        delete require.cache[require.resolve('./mocks/actions')];
        _gebo = require('..')(true);
        callback();
    },

    tearDown: function(callback) {
        // Why on earth do I have to do this? The cache deletions
        // have no impact on which schemata and actions are
        // included within the gebo. I delete these modules
        // before each test, look in the gebo after each require,
        // and there they be.
        _gebo.schemata.remove('mocks');
        _gebo.actions.remove('mocks');
        callback();
    },

    'Add schema and actions from action module': function(test) {
        test.expect(4);
        _gebo.enable('mocks', require('./mocks/full-action-module'));

        test.equal(typeof _gebo.schemata.mocks, 'function');
        var db = new _gebo.schemata.mocks();
        test.equal(typeof db.someModel, 'function');
        test.equal(typeof _gebo.actions.mocks.someAction, 'function');
        //test.equal(_gebo.actions.mocks.someAction(), 'Hi, guy!');
        _gebo.actions.mocks.someAction().
            then(function(results) {
                test.equal(results, 'Hi, guy!');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Don\'t barf if no schema is included in the action module': function(test) {
        test.expect(3);
        _gebo.enable('mocks', require('./mocks/no-schema'));
        test.equal(_gebo.schemata.mocks, undefined);
        test.equal(typeof _gebo.actions.mocks.someAction, 'function');
        //test.equal(_gebo.actions.mocks.someAction(), 'Hi, guy!');
        _gebo.actions.mocks.someAction().
            then(function(results) {
                test.equal(results, 'Hi, guy!');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Don\'t barf if no actions are included in the action module': function(test) {
        test.expect(3);
        _gebo.enable('mocks', require('./mocks/no-actions'));

        test.equal(typeof _gebo.schemata.mocks, 'function');
        var db = new _gebo.schemata.mocks();
        test.equal(typeof db.someModel, 'function');
        test.equal(_gebo.actions.mocks, undefined);
        test.done();
    },
};

<|endoftext|>