<commit_before>class animator {
  //using Web Animations API for now....will include a polyfill for unsupported browsers.
  //this provides a clean structure for all the animations....doing rotate for the demo.
  animateInterpolate(message) {
    let animationValues = message.animation;
    let keyframes = [];
    const element = document.getElementById(message.guid);
    if (animationValues.animatedProperty) {
      switch (true) {
        case /opacity/.test(animationValues.animatedProperty):

          keyframes = [
            { opacity: animationValues.value },
            { opacity: animationValues.toValue },
          ];
          break;
          case /height/.test(animationValues.animatedProperty):
          let fromValue = element.style.height;
          let toValue = animationValues.toValue !== 0 ? `${animationValues.toValue}px` : 0;
            keyframes = [
              { height: fromValue },
              { height: toValue },
            ];
            break;
        case /rotate|rotate[XYZ]/.test(animationValues.animatedProperty):
          keyframes = [
            {
              transform: `${animationValues.animatedProperty}(${
                animationValues.value
              }deg)`,
            },
            {
              transform: `${animationValues.animatedProperty}(${
                animationValues.toValue
              }deg)`,
            },
          ];
          break;
        //will need to include other cases for height,width, x, y transformations
      }
    } else {
      //default to z animations A.K.A rotate
      keyframes = [
        { transform: `rotateZ(${animationValues.value}deg)` },
        { transform: `rotateZ(${animationValues.toValue}deg)` },
      ];
    }

    let animation = element.animate(keyframes, {
      duration: animationValues.duration,
      iterations: 1,
    });
    animation.onfinish = () => {
      if(animationValues.animatedProperty == 'height' ||
         animationValues.animatedProperty == 'width'
       ) {
         element.style.height = `${animationValues.toValue}px`;
       }
      SyrEvents.emit({
        type: 'animationComplete',
        guid: message.guid,
        animation: message.animation,
      });
    };
  }

  animateComponentXY(message) {

    const animationValues = message.animation;

    const x = `${animationValues.x}px` || 0;
    const x2 = `${animationValues.x2}px` || 0;
    const y = `${animationValues.y}px` || 0;
    const y2 = `${animationValues.y2}px` || 0;

    // let destinationY = (y > y2) ? y2 - y : y2 + y;
    // let destinationX = (x > x2) ? x2 - y : x2 + x;

    const element = document.getElementById(message.guid);

    const animation = element.animate(
      [
        { transform: `translateX(${x}) translateY(${y})` },
        { transform: `translateX(${x2}) translateY(${y2})` },
      ],
      {
        duration: animationValues.duration,
        iterations: 1,
      }
    );

    animation.onfinish = () => {
      //setting the final postion of the element as the final XnY from the animation.
      element.style['top'] = y2 + 'px';
      element.style['left'] = x2 + 'px';
      SyrEvents.emit({
        type: 'animationComplete',
        guid: message.guid,
        animation: message.animation,
      });
    };
  }

  animate(message) {
    message.animation.value !== undefined
      ? this.animateInterpolate(message)
      : this.animateComponentXY(message);
  }
}

const Animator = new animator();

export { Animator };
<commit_msg>Inlcuded width animations. Ran Pretty and Cleaned up<commit_after>class animator {
  //using Web Animations API for now....will include a polyfill for unsupported browsers.
  //this provides a clean structure for all the animations....doing rotate for the demo.
  animateInterpolate(message) {
    const element = document.getElementById(message.guid);
    const animationValues = message.animation;
    const property = animationValues.animatedProperty;
    let fromValue = animationValues.value;
    let toValue = animationValues.toValue;
    let keyframes = [];
    if (property) {
      switch (true) {
        case /opacity/.test(property): {
          keyframes = [{ opacity: fromValue }, { opacity: toValue }];
          break;
        }
        case /height/.test(property): {
          fromValue = element.style.height;
          toValue = toValue !== 0 ? `${toValue}px` : 0;
          keyframes = [{ height: fromValue }, { height: toValue }];
          break;
        }
        case /width/.test(property): {
          fromValue = element.style.width;
          console.log(fromValue)
          toValue = toValue !== 0 ? `${toValue}px` : 0;
          keyframes = [{ width: fromValue }, { width: toValue }];
          break;
        }
        case /rotate|rotate[XYZ]/.test(property):
          {
            keyframes = [
              {
                transform: `${property}(${fromValue}deg)`,
              },
              {
                transform: `${property}(${toValue}deg)`,
              },
            ];
          }
          break;
        //will need to include other cases for height,width, x, y transformations
      }
    } else {
      //default to z animations A.K.A rotate
      keyframes = [
        { transform: `rotateZ(${fromValue}deg)` },
        { transform: `rotateZ(${toValue}deg)` },
      ];
    }

    let animation = element.animate(keyframes, {
      duration: animationValues.duration,
      iterations: 1,
    });
    animation.onfinish = () => {
      if (property == 'height' || property == 'width') {
        console.log(toValue)
        element.style[property] = toValue;
      }
      SyrEvents.emit({
        type: 'animationComplete',
        guid: message.guid,
        animation: message.animation,
      });
    };
  }

  animateComponentXY(message) {
    const animationValues = message.animation;

    const x = `${animationValues.x}px` || 0;
    const x2 = `${animationValues.x2}px` || 0;
    const y = `${animationValues.y}px` || 0;
    const y2 = `${animationValues.y2}px` || 0;

    // let destinationY = (y > y2) ? y2 - y : y2 + y;
    // let destinationX = (x > x2) ? x2 - y : x2 + x;

    const element = document.getElementById(message.guid);

    const animation = element.animate(
      [
        { transform: `translateX(${x}) translateY(${y})` },
        { transform: `translateX(${x2}) translateY(${y2})` },
      ],
      {
        duration: animationValues.duration,
        iterations: 1,
      }
    );

    animation.onfinish = () => {
      //setting the final postion of the element as the final XnY from the animation.
      element.style['top'] = y2 + 'px';
      element.style['left'] = x2 + 'px';
      SyrEvents.emit({
        type: 'animationComplete',
        guid: message.guid,
        animation: message.animation,
      });
    };
  }

  animate(message) {
    message.animation.value !== undefined
      ? this.animateInterpolate(message)
      : this.animateComponentXY(message);
  }
}

const Animator = new animator();

export { Animator };
<|endoftext|>


<commit_before>var request = require('request');
var config = require('./../config');

module.exports = function(device, message, callback) {

  // remove quotes around message string
  message = message.substring(1, message.length -1);
  console.log('Calling Urban Airship API...');
  request.post("https://" + config.urbanAirship.key + ":" + config.urbanAirship.secret + "@go.urbanairship.com/api/push/",
    { headers: {
        "Content-Type": "application/json",
        "Accept": "application/vnd.urbanairship+json; version=3;"
      },
      json:{"device_tokens": [device.pushID],
    "aps": {"alert": message}}
    }, function (error, response, body) {
      console.log(error, body);
      callback(body);
  });

};
<commit_msg>updated push notifications api<commit_after>var request = require('request');
var config = require('./../config');

module.exports = function(device, message, callback) {

  // remove quotes around message string
  message = message.substring(1, message.length -1);
  console.log('Calling Urban Airship API...');
  request.post("https://" + config.urbanAirship.key + ":" + config.urbanAirship.secret + "@go.urbanairship.com/api/push/",
    { headers: {
        "Content-Type": "application/json",
        "Accept": "application/vnd.urbanairship+json; version=3;"
      },
      json:{
        "audience" : {
            "device_token" : device.pushID
        },
        "notification" : {
             "alert" : message
        },
        "device_types" : "all"
      }
    }, function (error, response, body) {
      console.log(error, body);
      callback(body);
  });

};
<|endoftext|>


<commit_before>/* -*- Mode: js; js-indent-level: 2; -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Source Map.
 *
 * The Initial Developer of the Original Code is Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Nick Fitzgerald <nfitzgerald@mozilla.com> (original author)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
define(function (require, exports, module) {

  /**
   * A data structure which is a combination of an array and a set. Adding a new
   * member is O(1), testing for membership is O(1), and finding the index of an
   * element is O(1). Removing elements from the set is not supported. Only
   * strings are supported for membership.
   */
  function ArraySet () {
    this._array = [];
    this._set = {};
  }

  /**
   * Static method for creating ArraySet instances from an existing array.
   */
  ArraySet.fromArray = function ArraySet_fromArray (array) {
    var set = new ArraySet();
    for ( var i = 0, len = array.length; i < len; i++ ) {
      set.add(array[i]);
    }
    return set;
  };

  /**
   * Add the given string to this set.
   *
   * @param String str
   */
  ArraySet.prototype.add = function ArraySet_add (str) {
    var idx = this._array.length;
    this._array.push(str);
    this._set[str] = idx;
  };

  /**
   * Is the given string a member of this set?
   *
   * @param String str
   */
  ArraySet.prototype.has = function ArraySet_has (str) {
    return this._set.hasOwnProperty(str);
  };

  /**
   * What is the index of the given string in the array?
   *
   * @param String str
   */
  ArraySet.prototype.indexOf = function ArraySet_indexOf (str) {
    if ( this.has(str) ) {
      return this._set[str];
    } else {
      throw new Error('"' + str + '" is not in the set.');
    }
  };

  /**
   * What is the element at the given index?
   *
   * @param Number idx
   */
  ArraySet.prototype.at = function ArraySet_at (idx) {
    if ( idx >= 0 && idx < this._array.length ) {
      return this._array[idx];
    } else {
      throw new Error('No element indexed by ' + idx);
    }
  };

  /**
   * Returns the array representation of this set (which has the proper indices
   * indicated by indexOf).
   */
  ArraySet.prototype.toArray = function ArraySet_toArray () {
    return this._array.slice();
  };

  exports.ArraySet = ArraySet;

});
<commit_msg>Updating ArraySet comments and making add check if the string is already a member<commit_after>/* -*- Mode: js; js-indent-level: 2; -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Source Map.
 *
 * The Initial Developer of the Original Code is Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Nick Fitzgerald <nfitzgerald@mozilla.com> (original author)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
define(function (require, exports, module) {

  /**
   * A data structure which is a combination of an array and a set. Adding a new
   * member is O(1), testing for membership is O(1), and finding the index of an
   * element is O(1). Removing elements from the set is not supported. Only
   * strings are supported for membership.
   */
  function ArraySet () {
    this._array = [];
    this._set = {};
  }

  /**
   * Static method for creating ArraySet instances from an existing array.
   */
  ArraySet.fromArray = function ArraySet_fromArray (array) {
    var set = new ArraySet();
    for ( var i = 0, len = array.length; i < len; i++ ) {
      set.add(array[i]);
    }
    return set;
  };

  /**
   * Add the given string to this set.
   *
   * @param String str
   */
  ArraySet.prototype.add = function ArraySet_add (str) {
    if ( this.has(str) ) {
      // Already a member; nothing to do.
      return;
    }
    var idx = this._array.length;
    this._array.push(str);
    this._set[str] = idx;
  };

  /**
   * Is the given string a member of this set?
   *
   * @param String str
   */
  ArraySet.prototype.has = function ArraySet_has (str) {
    return this._set.hasOwnProperty(str);
  };

  /**
   * What is the index of the given string in the array?
   *
   * @param String str
   */
  ArraySet.prototype.indexOf = function ArraySet_indexOf (str) {
    if ( this.has(str) ) {
      return this._set[str];
    } else {
      throw new Error('"' + str + '" is not in the set.');
    }
  };

  /**
   * What is the element at the given index?
   *
   * @param Number idx
   */
  ArraySet.prototype.at = function ArraySet_at (idx) {
    if ( idx >= 0 && idx < this._array.length ) {
      return this._array[idx];
    } else {
      throw new Error('No element indexed by ' + idx);
    }
  };

  /**
   * Returns the array representation of this set (which has the proper indices
   * indicated by indexOf). Note that this is a copy of the internal array used
   * for storing the members so that no one can mess with internal state.
   */
  ArraySet.prototype.toArray = function ArraySet_toArray () {
    return this._array.slice();
  };

  exports.ArraySet = ArraySet;

});
<|endoftext|>


<commit_before>// Source https://www.w3.org/TR/dpub-aria-1.0/
const dpubRoles = {
	'doc-abstract': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-acknowledgments': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-afterword': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-appendix': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-backlink': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true
	},
	'doc-biblioentry': {
		type: 'listitem',
		requiredContext: ['doc-bibliography'],
		allowedAttrs: [
			'aria-expanded',
			'aria-level',
			'aria-posinset',
			'aria-setsize'
		]
	},
	'doc-bibliography': {
		type: 'landmark',
		requiredOwned: ['doc-biblioentry'],
		allowedAttrs: ['aria-expanded']
	},
	'doc-biblioref': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true
	},
	'doc-chapter': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-colophon': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-conclusion': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-cover': {
		type: 'img',
		allowedAttrs: ['aria-expanded']
	},
	'doc-credit': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-credits': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-dedication': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-endnote': {
		type: 'listitem',
		requiredContext: ['doc-endnotes'],
		allowedAttrs: [
			'aria-expanded',
			'aria-level',
			'aria-posinset',
			'aria-setsize'
		]
	},
	'doc-endnotes': {
		type: 'landmark',
		requiredOwned: ['doc-endnote'],
		allowedAttrs: ['aria-expanded']
	},
	'doc-epigraph': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-epilogue': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-errata': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-example': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-footnote': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-foreword': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-glossary': {
		type: 'landmark',
		requiredOwned: ['definition', 'term'],
		allowedAttrs: ['aria-expanded']
	},
	'doc-glossref': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true
	},
	'doc-index': {
		type: 'navigation',
		allowedAttrs: ['aria-expanded']
	},
	'doc-introduction': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-noteref': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true
	},
	'doc-notice': {
		type: 'note',
		allowedAttrs: ['aria-expanded']
	},
	'doc-pagebreak': {
		type: 'separator',
		allowedAttrs: ['aria-expanded', 'aria-orientation']
	},
	'doc-pagelist': {
		type: 'navigation',
		allowedAttrs: ['aria-expanded']
	},
	'doc-part': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-preface': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-prologue': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded']
	},
	'doc-pullquote': {
		type: 'none'
	},
	'doc-qna': {
		type: 'section',
		allowedAttrs: ['aria-expanded']
	},
	'doc-subtitle': {
		type: 'sectionhead',
		allowedAttrs: ['aria-expanded']
	},
	'doc-tip': {
		type: 'note',
		allowedAttrs: ['aria-expanded']
	},
	'doc-toc': {
		type: 'navigation',
		allowedAttrs: ['aria-expanded']
	}
};

export default dpubRoles;
<commit_msg>feat(standards): add superclassRole to dpubRoles (#2606)<commit_after>// Source https://www.w3.org/TR/dpub-aria-1.0/
const dpubRoles = {
	'doc-abstract': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-acknowledgments': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-afterword': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-appendix': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-backlink': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true,
		superclassRole: ['link']
	},
	'doc-biblioentry': {
		type: 'listitem',
		requiredContext: ['doc-bibliography'],
		allowedAttrs: [
			'aria-expanded',
			'aria-level',
			'aria-posinset',
			'aria-setsize'
		],
		superclassRole: ['listitem']
	},
	'doc-bibliography': {
		type: 'landmark',
		requiredOwned: ['doc-biblioentry'],
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-biblioref': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true,
		superclassRole: ['link']
	},
	'doc-chapter': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-colophon': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-conclusion': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-cover': {
		type: 'img',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['img']
	},
	'doc-credit': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-credits': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-dedication': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-endnote': {
		type: 'listitem',
		requiredContext: ['doc-endnotes'],
		allowedAttrs: [
			'aria-expanded',
			'aria-level',
			'aria-posinset',
			'aria-setsize'
		],
		superclassRole: ['listitem']
	},
	'doc-endnotes': {
		type: 'landmark',
		requiredOwned: ['doc-endnote'],
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-epigraph': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-epilogue': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-errata': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-example': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-footnote': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-foreword': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-glossary': {
		type: 'landmark',
		requiredOwned: ['definition', 'term'],
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-glossref': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true,
		superclassRole: ['link']
	},
	'doc-index': {
		type: 'navigation',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['navigation']
	},
	'doc-introduction': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-noteref': {
		type: 'link',
		allowedAttrs: ['aria-expanded'],
		nameFromContent: true,
		superclassRole: ['link']
	},
	'doc-notice': {
		type: 'note',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['note']
	},
	'doc-pagebreak': {
		type: 'separator',
		allowedAttrs: ['aria-expanded', 'aria-orientation'],
		superclassRole: ['separator']
	},
	'doc-pagelist': {
		type: 'navigation',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['navigation']
	},
	'doc-part': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-preface': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-prologue': {
		type: 'landmark',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['landmark']
	},
	'doc-pullquote': {
		type: 'none',
		superclassRole: ['none']
	},
	'doc-qna': {
		type: 'section',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['section']
	},
	'doc-subtitle': {
		type: 'sectionhead',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['sectionhead']
	},
	'doc-tip': {
		type: 'note',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['note']
	},
	'doc-toc': {
		type: 'navigation',
		allowedAttrs: ['aria-expanded'],
		superclassRole: ['navigation']
	}
};

export default dpubRoles;
<|endoftext|>


<commit_before>(function(module) {
  function Brewery (opts) {
    Object.keys(opts).forEach(function(b, index, keys) {
      this[b] = opts[b];
    }, this);
  }

  Brewery.all = [];
  Brewery.ids = [];
  Brewery.names = [];

  Brewery.loadBreweryNames = function() {
    $.get('/data/breweries.json')
    .done(function(data) {
      Brewery.all = data.map(function(element){
        return element;
      });
    });
  };

  // Fill out an array of brewery ids to pick up on breweryDB URI routing
  Brewery.filterUniqueBreweryIds = function() {
    $.get('/data/breweries.json')
    .done(function(data) {
      data.forEach(function(b){
        if (Brewery.ids.indexOf(b.id) === -1) {
          Brewery.ids.push(b.id);
        }
      });
    });
  };

  Brewery.handleLocationEndpoint = function() {
    console.log('location endpoint');
    Brewery.ids.forEach(function(id) {
      $.get('/locations/' + id, function(data) {
        var breweryInstance = new Brewery(data.data[0]);
        breweryInstance.insertLocationRecord(id);
      });
    });
  };

  Brewery.handleNameEndpoint = function() {
    console.log('name endpoint');
    Brewery.ids.forEach(function(id) {
      $.get('/name/' + id, function(data) {
        var breweryInstance = new Brewery(data.data);
        breweryInstance.insertNameRecord();
      });
    });
  };

  Brewery.handleTwitterHandleEndpoint = function() {
    console.log('Twitter endpoint');
    Brewery.ids.forEach(function(id) {
      $.get('/twitter-handle/' + id, function(data) {
        for (var i in data.data) {
          if (data.data[i].socialMediaId == 2) {
            var breweryInstance = new Brewery({breweryId: id, twitterHandle: data.data[i].handle});
            breweryInstance.insertTwitterHandleRecord();
          };
        };
      });
    });
  };

  Brewery.prototype.insertLocationRecord = function(id) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryLocation (breweryId, streetAddress, postalCode, phone, latitude, longitude, openToPublic, hoursOfOperation) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
          'data': [id, this.streetAddress, this.postalCode, this.phone, this.latitude, this.longitude, this.openToPublic, this.hoursOfOperation],
        }
      ]
    );
  };

  Brewery.prototype.insertNameRecord = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryName (breweryId, name, description, website, established, isOrganic) VALUES (?, ?, ?, ?, ?, ?)',
          'data': [this.id, this.name, this.description, this.website, this.established, this.isOrganic],
        }
      ]
    );
  };

  Brewery.prototype.insertTwitterHandleRecord = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryTwitterHandle (breweryId, twitterHandle) VALUES (?, ?)',
          'data': [this.breweryId, this.twitterHandle],
        }
      ]
    );
  };

  Brewery.createLocationTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryLocation (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'streetAddress VARCHAR(255), ' +
      'postalCode, ' +
      'phone VARCHAR(255), ' +
      'latitude FLOAT, ' +
      'longitude FLOAT, ' +
      'openToPublic BOOLEAN, ' +
      'hoursOfOperation VARCHAR(255));'
    );
    callback(); // TODO: run this asynchronously
  };

  Brewery.createNameTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryName (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'name VARCHAR(255), ' +
      'description TEXT, ' +
      'website VARCHAR(255), ' +
      'established DATE, ' +
      'isOrganic BOOLEAN);'
    );
    callback(); // TODO: run this asynchronously
  };

  Brewery.createTwitterHandleTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryTwitterHandle (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'twitterHandle VARCHAR(255));'
    );
    callback(); // TODO: run this asynchronously
  };

  Brewery.findBreweryWhere = function(filterArray, sqlString, callback) {
    webDB.execute(
      [
        {
          'sql': 'SELECT * FROM breweryName LEFT JOIN breweryBeers ON (breweryName.breweryId = breweryBeers.breweryId) WHERE ' + sqlString + ' GROUP BY breweryName.name HAVING COUNT(DISTINCT breweryBeers.categoryId) = ' + filterArray.length,
        }
      ],
      callback
    );
  };

  Brewery.saveAllBreweryData = function(rows) {
    Brewery.all = rows.map(function(brew) {
      return new Brewery(brew);
    });
  };

  Brewery.grabAllBreweryData = function() {
    webDB.execute('SELECT * FROM breweryLocation ORDER BY id DESC', function(rows) {
      if (rows.length) {
        console.log('data was already there!');
        Brewery.saveAllBreweryData(rows);
      } else {
        console.log('data needed to be loaded!');
        Brewery.ids.forEach(function(id) {
          $.get('/locations/' + id, function(data) {
            var breweryInstance = new Brewery(data.data[0]);
            breweryInstance.insertLocationRecord(id);
          })
          .done(function() {
            webDB.execute('SELECT * FROM breweryLocation', function(rows) {
              console.log('stuff shouldn\'t load until the document is ready!');
              Brewery.saveAllBreweryData(rows);
            });
          });
        });
      }
    });
  };

  Brewery.searchFieldComplete = function() {
    console.log('autocomplete ready!');
    $('#brew-search-input').autocomplete(
      {
        source: Brewery.names,
        minLength: 3
      }
    );
  };
  $('#brew-search-input').on('focus', Brewery.searchFieldComplete);

  Brewery.handleTwitEndpoint = function() {

  };

  Brewery.handleYelpEndpoint = function() {

  };

  Brewery.initTables = function() {
    Brewery.filterUniqueBreweryIds();
    Brewery.createLocationTable(Brewery.handleLocationEndpoint);
    Brewery.createNameTable(Brewery.handleNameEndpoint);
    Brewery.createTwitterHandleTable(Brewery.handleTwitterHandleEndpoint);
    Brewery.grabAllBreweryData();
  };

  Brewery.initTables();
  Brewery.loadBreweryNames();

  module.Brewery = Brewery;
}(window));
<commit_msg>debug callbacks<commit_after>(function(module) {
  function Brewery (opts) {
    Object.keys(opts).forEach(function(b, index, keys) {
      this[b] = opts[b];
    }, this);
  }

  Brewery.all = [];
  Brewery.ids = [];
  Brewery.names = [];

  Brewery.loadBreweryNames = function() {
    $.get('/data/breweries.json')
    .done(function(data) {
      Brewery.all = data.map(function(element){
        return element;
      });
    });
  };

  // Fill out an array of brewery ids to pick up on breweryDB URI routing
  Brewery.filterUniqueBreweryIds = function() {
    $.get('/data/breweries.json')
    .done(function(data) {
      data.forEach(function(b){
        if (Brewery.ids.indexOf(b.id) === -1) {
          Brewery.ids.push(b.id);
        }
      });
    });
  };

  Brewery.handleLocationEndpoint = function() {
    console.log('location endpoint');
    Brewery.ids.forEach(function(id) {
      $.get('/locations/' + id, function(data) {
        var breweryInstance = new Brewery(data.data[0]);
        breweryInstance.insertLocationRecord(id);
      });
    });
  };

  Brewery.handleNameEndpoint = function() {
    console.log('name endpoint');
    Brewery.ids.forEach(function(id) {
      $.get('/name/' + id, function(data) {
        var breweryInstance = new Brewery(data.data);
        breweryInstance.insertNameRecord();
      });
    });
  };

  Brewery.handleTwitterHandleEndpoint = function() {
    console.log('Twitter endpoint');
    Brewery.ids.forEach(function(id) {
      $.get('/twitter-handle/' + id, function(data) {
        for (var i in data.data) {
          if (data.data[i].socialMediaId == 2) {
            var breweryInstance = new Brewery({breweryId: id, twitterHandle: data.data[i].handle});
            breweryInstance.insertTwitterHandleRecord();
          };
        };
      });
    });
  };

  Brewery.prototype.insertLocationRecord = function(id) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryLocation (breweryId, streetAddress, postalCode, phone, latitude, longitude, openToPublic, hoursOfOperation) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
          'data': [id, this.streetAddress, this.postalCode, this.phone, this.latitude, this.longitude, this.openToPublic, this.hoursOfOperation],
        }
      ]
    );
  };

  Brewery.prototype.insertNameRecord = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryName (breweryId, name, description, website, established, isOrganic) VALUES (?, ?, ?, ?, ?, ?)',
          'data': [this.id, this.name, this.description, this.website, this.established, this.isOrganic],
        }
      ]
    );
  };

  Brewery.prototype.insertTwitterHandleRecord = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryTwitterHandle (breweryId, twitterHandle) VALUES (?, ?)',
          'data': [this.breweryId, this.twitterHandle],
        }
      ]
    );
  };

  Brewery.createLocationTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryLocation (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'streetAddress VARCHAR(255), ' +
      'postalCode, ' +
      'phone VARCHAR(255), ' +
      'latitude FLOAT, ' +
      'longitude FLOAT, ' +
      'openToPublic BOOLEAN, ' +
      'hoursOfOperation VARCHAR(255));',
      callback
    );
    // callback(); // TODO: run this asynchronously
  };

  Brewery.createNameTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryName (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'name VARCHAR(255), ' +
      'description TEXT, ' +
      'website VARCHAR(255), ' +
      'established DATE, ' +
      'isOrganic BOOLEAN);',
      callback
    );
    // callback(); // TODO: run this asynchronously
  };

  Brewery.createTwitterHandleTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryTwitterHandle (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'twitterHandle VARCHAR(255));',
      callback
    );
    // callback(); // TODO: run this asynchronously
  };

  Brewery.findBreweryWhere = function(filterArray, sqlString, callback) {
    webDB.execute(
      [
        {
          'sql': 'SELECT * FROM breweryName LEFT JOIN breweryBeers ON (breweryName.breweryId = breweryBeers.breweryId) WHERE ' + sqlString + ' GROUP BY breweryName.name HAVING COUNT(DISTINCT breweryBeers.categoryId) = ' + filterArray.length,
        }
      ],
      callback
    );
  };

  Brewery.findBreweryWhere = function(filterArray, sqlString, callback) {
    webDB.execute(
      [
        {
          'sql': 'SELECT * FROM breweryName LEFT JOIN breweryBeers ON (breweryName.breweryId = breweryBeers.breweryId) WHERE ' + sqlString + ' GROUP BY breweryName.name HAVING COUNT(DISTINCT breweryBeers.categoryId) = ' + filterArray.length,
        }
      ],
      callback
    );
  };

  Brewery.saveAllBreweryData = function(rows) {
    Brewery.all = rows.map(function(brew) {
      return new Brewery(brew);
    });
  };

  Brewery.grabAllBreweryData = function() {
    webDB.execute('SELECT * FROM breweryLocation ORDER BY id DESC', function(rows) {
      if (rows.length) {
        console.log('data was already there!');
        Brewery.saveAllBreweryData(rows);
      } else {
        console.log('data needed to be loaded!');
        Brewery.ids.forEach(function(id) {
          $.get('/locations/' + id, function(data) {
            var breweryInstance = new Brewery(data.data[0]);
            breweryInstance.insertLocationRecord(id);
          })
          .done(function() {
            webDB.execute('SELECT * FROM breweryLocation', function(rows) {
              console.log('stuff shouldn\'t load until the document is ready!');
              Brewery.saveAllBreweryData(rows);
            });
          });
        });
      }
    });
  };

  Brewery.searchFieldComplete = function() {
    console.log('autocomplete ready!');
    $('#brew-search-input').autocomplete(
      {
        source: Brewery.names,
        minLength: 3
      }
    );
  };
  $('#brew-search-input').on('focus', Brewery.searchFieldComplete);

  Brewery.handleTwitEndpoint = function() {

  };

  Brewery.handleYelpEndpoint = function() {

  };

  Brewery.initTables = function() {
    Brewery.filterUniqueBreweryIds();
    Brewery.createLocationTable(Brewery.handleLocationEndpoint);
    Brewery.createNameTable(Brewery.handleNameEndpoint);
    Brewery.createTwitterHandleTable(Brewery.handleTwitterHandleEndpoint);
    Brewery.grabAllBreweryData();
  };

  Brewery.initTables();
  Brewery.loadBreweryNames();

  module.Brewery = Brewery;
}(window));
<|endoftext|>


<commit_before>define(['util'], function(util) {
    'use strict';

	var Parser = function () {
	}

	Parser.prototype.parse = function () {
		console.log('Error: Pure virtual parse called!');
		return {};
	}

	Parser.prototype.prepare = function (input) {
		var i;
		input = input.split('\n');

		util.forEach(input, function (line, l) {
			line = line.split(' ');
			i = 0;
			while(i < line.length) {
				if (line[i] == '') {
					line.splice(i, 1);
				} else {
					++i;
				}
			}
			input[l] = line;
		});

		i = 0;
		while (i < input.length) {
			if (input[i].length == 0) {
				input.splice(i, 1);
			} else {
				++i;
			}
		}

		console.log(input);

		return input;
	}

	return Parser;
});
<commit_msg>Forgot to remove debug output<commit_after>define(['util'], function(util) {
    'use strict';

	var Parser = function () {
	}

	Parser.prototype.parse = function () {
		console.log('Error: Pure virtual parse called!');
		return {};
	}

	Parser.prototype.prepare = function (input) {
		var i;
		input = input.split('\n');

		util.forEach(input, function (line, l) {
			line = line.split(' ');
			i = 0;
			while(i < line.length) {
				if (line[i] == '') {
					line.splice(i, 1);
				} else {
					++i;
				}
			}
			input[l] = line;
		});

		i = 0;
		while (i < input.length) {
			if (input[i].length == 0) {
				input.splice(i, 1);
			} else {
				++i;
			}
		}

		return input;
	}

	return Parser;
});
<|endoftext|>


<commit_before>const test = require('tape')
const Promise = require('bluebird')
const is = require('../src/is')
const tError = require('./test-error')
const enums = require('../src/enums')
const jobAddLog = require('../src/job-add-log')
const Job = require('../src/job')
const tData = require('./test-options').tData
const lData = require('./test-options').lData
const Queue = require('../src/queue')
const tOpts = require('./test-options')

module.exports = function () {
  return new Promise((resolve, reject) => {
    test('job', (t) => {
      t.plan(93)

      const q = new Queue(tOpts.cxn(), tOpts.default())

      const newJob = new Job(q)
      newJob.data = tData
      let savedJob
      let newTimeout = 1234

      // ---------- Event Handler Setup ----------
      let testEvents = false
      function addedEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: added [${jobId}]`)
        }
      }
      function logEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: log [${jobId}]`)
        }
      }
      function progressEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: progress [${jobId}]`)
        }
      }
      function updatedEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: updated [${jobId}]`)
        }
      }
      function addEventHandlers () {
        testEvents = true
        q.on(enums.status.added, addedEventHandler)
        q.on(enums.status.log, logEventHandler)
        q.on(enums.status.progress, progressEventHandler)
        q.on(enums.status.updated, updatedEventHandler)
      }
      function removeEventHandlers () {
        testEvents = false
        q.removeListener(enums.status.added, addedEventHandler)
        q.removeListener(enums.status.log, logEventHandler)
        q.removeListener(enums.status.progress, progressEventHandler)
        q.removeListener(enums.status.updated, updatedEventHandler)
      }
      addEventHandlers()

      // ---------- New Job Tests ----------
      t.comment('job: New Job')
      t.ok(newJob instanceof Job, 'New job is a Job object')
      t.deepEqual(newJob.q, q, 'New job has a reference to the queue')
      t.ok(is.uuid(newJob.id), 'New job has valid id')
      t.equal(newJob.data, tData, 'New job data is valid')
      t.equal(newJob.priority, 'normal', 'New job priority is normal')
      t.equal(newJob.status, enums.status.created, 'New job status is created')
      t.equal(newJob.timeout, enums.options.timeout, 'New job timeout is valid')
      t.equal(newJob.retryMax, enums.options.retryMax, 'New job retryMax is valid')
      t.equal(newJob.retryDelay, enums.options.retryDelay, 'New job retryDelay is valid')
      t.equal(newJob.progress, 0, 'New job progress is 0')
      t.equal(newJob.queueId, q.id, 'New job queueId is valid')
      t.equal(newJob.retryCount, 0, 'New job retryCount is 0')
      t.equal(newJob.log.length, 0, 'New job log is an empty array')
      t.ok(is.date(newJob.dateCreated), 'New job dateCreated is a date')
      t.ok(is.date(newJob.dateEnable), 'New job dateEnable is a date')

      // ---------- Change Options Tests ----------
      t.comment('job: Change Options')
      t.throws(() => { newJob.setPriority('not valid') }, 'Job setPriority thows if invalid')
      newJob.setPriority('highest')
      t.equal(newJob.priority, 'highest', 'Job setPriority successfully changed value')
      t.throws(() => { newJob.setTimeout('not valid') }, 'Job setTimeout thows if invalid')
      newJob.setTimeout(100)
      t.equal(newJob.timeout, 100, 'Job setTimeout successfully changed value')
      t.throws(() => { newJob.setRetryMax('not valid') }, 'Job setRetryMax thows if invalid')
      newJob.setRetryMax(100)
      t.equal(newJob.retryMax, 100, 'Job setRetryMax successfully changed value')
      t.throws(() => { newJob.setRetryDelay('not valid') }, 'Job setRetryDelay thows if invalid')
      newJob.setRetryDelay(100)
      t.equal(newJob.retryDelay, 100, 'Job setRetryDelay successfully changed value')
      t.throws(() => { newJob.setDateEnable('not valid') }, 'Job setDateEnable thows if invalid')
      const testDate = new Date()
      newJob.setDateEnable(testDate)
      t.equal(newJob.dateEnable, testDate, 'Job setDateEnable successfully changed value')

      // ---------- Clean Job Tests ----------
      t.comment('job: Clean Job')
      let cleanJob = newJob.getCleanCopy()
      t.equal(Object.keys(cleanJob).length, 13, 'Clean job has valid number of properties')
      t.equal(cleanJob.id, newJob.id, 'Clean job has valid id')
      t.equal(cleanJob.data, newJob.data, 'Clean job data is valid')
      t.equal(cleanJob.priority, enums.priority[newJob.priority], 'Clean job priority is valid')
      t.equal(cleanJob.timeout, newJob.timeout, 'Clean job timeoue is valid')
      t.equal(cleanJob.retryDelay, newJob.retryDelay, 'Clean job retryDelay is valid')
      t.equal(cleanJob.retryMax, newJob.retryMax, 'Clean job retryMax is valid')
      t.equal(cleanJob.retryCount, newJob.retryCount, 'Clean job retryCount is valid')
      t.equal(cleanJob.status, newJob.status, 'Clean job status is valid')
      t.equal(cleanJob.log, newJob.log, 'Clean job log is valid')
      t.equal(cleanJob.dateCreated, newJob.dateCreated, 'Clean job dateCreated is valid')
      t.equal(cleanJob.dateEnable, newJob.dateEnable, 'Clean job dateEnable is valid')
      t.equal(cleanJob.progress, newJob.progress, 'Clean job progress is valid')
      t.equal(cleanJob.queueId, newJob.queueId, 'Clean job progress is valid')

      cleanJob = newJob.getCleanCopy(true)
      t.equal(cleanJob.priority, newJob.priority, 'Clean job priorityAsString priority is normal')

      return q.reset().then((resetResult) => {
        t.ok(is.integer(resetResult), 'Queue reset')
        return q.addJob(newJob)
      }).then((addedJobs) => {
        savedJob = addedJobs[0]
        t.equal(savedJob.id, newJob.id, 'Job saved successfully')
        let jobCopy = Object.assign({}, savedJob)
        jobCopy.priority = 40

        // ---------- New Job From Data ----------
        t.comment('job: New Job from Job Data')
        return new Job(q, jobCopy)
      }).then((newJobFromData) => {
        t.equal(newJobFromData.id, savedJob.id, 'New job from data created successfully')
        t.deepEqual(newJobFromData.q, savedJob.q, 'New job from data queue valid')
        t.equal(newJobFromData.data, savedJob.data, 'New job from data job data is valid')
        t.equal(newJobFromData.priority, 'normal', 'New job from data priority is valid')
        t.equal(newJobFromData.timeout, savedJob.timeout, 'New job from data timeout is valid')
        t.equal(newJobFromData.retryDelay, savedJob.retryDelay, 'New job from data retryDelay is valid')
        t.equal(newJobFromData.retryMax, savedJob.retryMax, 'New job from data retryMax is valid')
        t.equal(newJobFromData.retryCount, savedJob.retryCount, 'New job from data retryCount is valid')
        t.equal(newJobFromData.status, savedJob.status, 'New job from data status is valid')
        t.equal(newJobFromData.log, savedJob.log, 'Clean job log is valid')
        t.equal(newJobFromData.dateCreated, savedJob.dateCreated, 'Clean job dateCreated is valid')
        t.equal(newJobFromData.dateEnable, savedJob.dateEnable, 'Clean job dateEnable is valid')
        t.equal(newJobFromData.progress, savedJob.progress, 'New job from data progress is valid')
        t.equal(newJobFromData.queueId, q.id, 'New job from data queueId is valid')

        // ---------- New Jobs with Data and Options ----------
        t.comment('job: New Job with Data and Options')
        let custJob = new Job(q, { foo: 'bar' })
        t.equal(custJob.foo, 'bar', 'New job with object data created successfully')
        custJob = new Job(q, 'bar')
        t.equal(custJob.data, 'bar', 'New job with string data created successfully')
        custJob = new Job(q, 1234)
        t.equal(custJob.data, 1234, 'New job with number data created successfully')
        custJob = new Job(q, true)
        t.ok(is.true(custJob.data), 'New job with boolean data created successfully')
        custJob = new Job(q, [1, 2, 3])
        t.ok(is.array(custJob.data), 'New job with array data created successfully')
        custJob = new Job(q, { object: { foo: 'bar' }, priority: 'high' })
        t.equal(custJob.object.foo, 'bar', 'New job with child object data created successfully')
        t.equal(custJob.priority, 'high', 'New job with new priority created successfully')
        t.throws(() => { new Job(q, () => { }) }, 'New job with function throws error')

        // ---------- Add Job Log ----------
        t.comment('job: Add Job Log')
        return savedJob.addLog(tData, tData)
      }).then((logAddedResult) => {
        t.ok(logAddedResult, 'Job log added successfully')
        return q.getJob(savedJob.id)
      }).then((jobsFromDb) => {
        t.equal(jobsFromDb[0].id, savedJob.id, 'Job retrieved successfully')
        t.equal(jobsFromDb[0].log.length, 2, 'Job log exists')
        t.ok(is.date(jobsFromDb[0].log[1].date), 'Log date is a date')
        t.equal(jobsFromDb[0].log[1].queueId, q.id, 'Log queueId is valid')
        t.equal(jobsFromDb[0].log[1].type, enums.log.information, 'Log type is information')
        t.equal(jobsFromDb[0].log[1].status, enums.status.waiting, 'Log status is valid')
        t.ok(jobsFromDb[0].log[1].retryCount >= 0, 'Log retryCount is valid')
        t.equal(jobsFromDb[0].log[1].message, tData, 'Log message is valid')
        t.equal(jobsFromDb[0].log[1].data, tData, 'Log data is valid')

        // ---------- Set Job Progress ----------
        t.comment('job: Set Job Progress')
        savedJob.status = enums.status.active
        return savedJob.setProgress(50)
      }).then((progressResult) => {
        t.ok(progressResult, 'Job setProgress returned true')
        return q.getJob(savedJob.id)
      }).then((jobsFromDb) => {
        t.equal(jobsFromDb[0].id, savedJob.id, 'Job retrieved successfully')
        t.equal(jobsFromDb[0].progress, 50, 'Job progress valid')

        // ---------- Update Job ----------
        t.comment('job: Update Job with string message')
        savedJob.newData = tData
        savedJob.timeout = newTimeout
        return savedJob.update(tData)
      }).then((updateResult) => {
        t.ok(updateResult, 'Job update returned true')
        return q.getJob(savedJob.id)
      }).then((jobsFromDb) => {
        t.equal(jobsFromDb[0].id, savedJob.id, 'Job retrieved successfully')
        t.equal(jobsFromDb[0].newData, tData, 'Job new data valid')
        t.equal(jobsFromDb[0].timeout, newTimeout, 'Job new timeout valid')

        // ---------- Update Job Passing `data` object ----------
        t.comment('job: Update Job with Object message')
        savedJob.newData = tData
        savedJob.timeout = newTimeout
        return savedJob.update(lData)
      }).then((updateResult) => {
        t.ok(updateResult, 'Job update returned true')
        return q.getJob(savedJob.id)
      }).then((jobsFromDb) => {
        const lastLogData = jobsFromDb[0].log[jobsFromDb[0].log.length - 1]
        t.equal(jobsFromDb[0].id, savedJob.id, 'Job retrieved successfully')
        t.equal(jobsFromDb[0].timeout, newTimeout, 'Job new timeout valid')
        t.equal(lastLogData.message, enums.message.seeLogData, 'Job log message property valid')
        t.equal(lastLogData.data.one_key, lData.one_key, 'Job log message property valid')
        t.equal(lastLogData.data.some_other_key, lData.some_other_key, 'Job log data property valid')

        removeEventHandlers()
        return q.reset()
      }).then((resetResult) => {
        t.ok(resetResult >= 0, 'Queue reset')
        q.stop()
        return resolve(t.end())
      }).catch(err => tError(err, module, t))
    })
  })
}
<commit_msg>Fixed job.update tests<commit_after>const test = require('tape')
const Promise = require('bluebird')
const is = require('../src/is')
const tError = require('./test-error')
const enums = require('../src/enums')
const jobAddLog = require('../src/job-add-log')
const Job = require('../src/job')
const tData = require('./test-options').tData
const lData = require('./test-options').lData
const Queue = require('../src/queue')
const tOpts = require('./test-options')

module.exports = function () {
  return new Promise((resolve, reject) => {
    test('job', (t) => {
      t.plan(81)

      const q = new Queue(tOpts.cxn(), tOpts.default())

      const newJob = new Job(q)
      newJob.data = tData
      let savedJob
      let newTimeout = 1234

      // ---------- Event Handler Setup ----------
      let testEvents = false
      function addedEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: added [${jobId}]`)
        }
      }
      function logEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: log [${jobId}]`)
        }
      }
      function progressEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: progress [${jobId}]`)
        }
      }
      function updatedEventHandler (jobId) {
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: updated [${jobId}]`)
        }
      }
      function addEventHandlers () {
        testEvents = true
        q.on(enums.status.added, addedEventHandler)
        q.on(enums.status.log, logEventHandler)
        q.on(enums.status.progress, progressEventHandler)
        q.on(enums.status.updated, updatedEventHandler)
      }
      function removeEventHandlers () {
        testEvents = false
        q.removeListener(enums.status.added, addedEventHandler)
        q.removeListener(enums.status.log, logEventHandler)
        q.removeListener(enums.status.progress, progressEventHandler)
        q.removeListener(enums.status.updated, updatedEventHandler)
      }
      addEventHandlers()

      // ---------- New Job Tests ----------
      t.comment('job: New Job')
      t.ok(newJob instanceof Job, 'New job is a Job object')
      t.deepEqual(newJob.q, q, 'New job has a reference to the queue')
      t.ok(is.uuid(newJob.id), 'New job has valid id')
      t.equal(newJob.data, tData, 'New job data is valid')
      t.equal(newJob.priority, 'normal', 'New job priority is normal')
      t.equal(newJob.status, enums.status.created, 'New job status is created')
      t.equal(newJob.timeout, enums.options.timeout, 'New job timeout is valid')
      t.equal(newJob.retryMax, enums.options.retryMax, 'New job retryMax is valid')
      t.equal(newJob.retryDelay, enums.options.retryDelay, 'New job retryDelay is valid')
      t.equal(newJob.progress, 0, 'New job progress is 0')
      t.equal(newJob.queueId, q.id, 'New job queueId is valid')
      t.equal(newJob.retryCount, 0, 'New job retryCount is 0')
      t.equal(newJob.log.length, 0, 'New job log is an empty array')
      t.ok(is.date(newJob.dateCreated), 'New job dateCreated is a date')
      t.ok(is.date(newJob.dateEnable), 'New job dateEnable is a date')

      // ---------- Change Options Tests ----------
      t.comment('job: Change Options')
      t.throws(() => { newJob.setPriority('not valid') }, 'Job setPriority thows if invalid')
      newJob.setPriority('highest')
      t.equal(newJob.priority, 'highest', 'Job setPriority successfully changed value')
      t.throws(() => { newJob.setTimeout('not valid') }, 'Job setTimeout thows if invalid')
      newJob.setTimeout(100)
      t.equal(newJob.timeout, 100, 'Job setTimeout successfully changed value')
      t.throws(() => { newJob.setRetryMax('not valid') }, 'Job setRetryMax thows if invalid')
      newJob.setRetryMax(100)
      t.equal(newJob.retryMax, 100, 'Job setRetryMax successfully changed value')
      t.throws(() => { newJob.setRetryDelay('not valid') }, 'Job setRetryDelay thows if invalid')
      newJob.setRetryDelay(100)
      t.equal(newJob.retryDelay, 100, 'Job setRetryDelay successfully changed value')
      t.throws(() => { newJob.setDateEnable('not valid') }, 'Job setDateEnable thows if invalid')
      const testDate = new Date()
      newJob.setDateEnable(testDate)
      t.equal(newJob.dateEnable, testDate, 'Job setDateEnable successfully changed value')

      // ---------- Clean Job Tests ----------
      t.comment('job: Clean Job')
      let cleanJob = newJob.getCleanCopy()
      t.equal(Object.keys(cleanJob).length, 13, 'Clean job has valid number of properties')
      t.equal(cleanJob.id, newJob.id, 'Clean job has valid id')
      t.equal(cleanJob.data, newJob.data, 'Clean job data is valid')
      t.equal(cleanJob.priority, enums.priority[newJob.priority], 'Clean job priority is valid')
      t.equal(cleanJob.timeout, newJob.timeout, 'Clean job timeoue is valid')
      t.equal(cleanJob.retryDelay, newJob.retryDelay, 'Clean job retryDelay is valid')
      t.equal(cleanJob.retryMax, newJob.retryMax, 'Clean job retryMax is valid')
      t.equal(cleanJob.retryCount, newJob.retryCount, 'Clean job retryCount is valid')
      t.equal(cleanJob.status, newJob.status, 'Clean job status is valid')
      t.equal(cleanJob.log, newJob.log, 'Clean job log is valid')
      t.equal(cleanJob.dateCreated, newJob.dateCreated, 'Clean job dateCreated is valid')
      t.equal(cleanJob.dateEnable, newJob.dateEnable, 'Clean job dateEnable is valid')
      t.equal(cleanJob.progress, newJob.progress, 'Clean job progress is valid')
      t.equal(cleanJob.queueId, newJob.queueId, 'Clean job progress is valid')

      cleanJob = newJob.getCleanCopy(true)
      t.equal(cleanJob.priority, newJob.priority, 'Clean job priorityAsString priority is normal')

      return q.reset().then((resetResult) => {
        t.ok(is.integer(resetResult), 'Queue reset')
        return q.addJob(newJob)
      }).then((addedJobs) => {
        savedJob = addedJobs[0]
        t.equal(savedJob.id, newJob.id, 'Job saved successfully')
        let jobCopy = Object.assign({}, savedJob)
        jobCopy.priority = 40

        // ---------- New Job From Data ----------
        t.comment('job: New Job from Job Data')
        return new Job(q, jobCopy)
      }).then((newJobFromData) => {
        t.equal(newJobFromData.id, savedJob.id, 'New job from data created successfully')
        t.deepEqual(newJobFromData.q, savedJob.q, 'New job from data queue valid')
        t.equal(newJobFromData.data, savedJob.data, 'New job from data job data is valid')
        t.equal(newJobFromData.priority, 'normal', 'New job from data priority is valid')
        t.equal(newJobFromData.timeout, savedJob.timeout, 'New job from data timeout is valid')
        t.equal(newJobFromData.retryDelay, savedJob.retryDelay, 'New job from data retryDelay is valid')
        t.equal(newJobFromData.retryMax, savedJob.retryMax, 'New job from data retryMax is valid')
        t.equal(newJobFromData.retryCount, savedJob.retryCount, 'New job from data retryCount is valid')
        t.equal(newJobFromData.status, savedJob.status, 'New job from data status is valid')
        t.equal(newJobFromData.log, savedJob.log, 'Clean job log is valid')
        t.equal(newJobFromData.dateCreated, savedJob.dateCreated, 'Clean job dateCreated is valid')
        t.equal(newJobFromData.dateEnable, savedJob.dateEnable, 'Clean job dateEnable is valid')
        t.equal(newJobFromData.progress, savedJob.progress, 'New job from data progress is valid')
        t.equal(newJobFromData.queueId, q.id, 'New job from data queueId is valid')

        // ---------- New Jobs with Data and Options ----------
        t.comment('job: New Job with Data and Options')
        let custJob = new Job(q, { foo: 'bar' })
        t.equal(custJob.foo, 'bar', 'New job with object data created successfully')
        custJob = new Job(q, 'bar')
        t.equal(custJob.data, 'bar', 'New job with string data created successfully')
        custJob = new Job(q, 1234)
        t.equal(custJob.data, 1234, 'New job with number data created successfully')
        custJob = new Job(q, true)
        t.ok(is.true(custJob.data), 'New job with boolean data created successfully')
        custJob = new Job(q, [1, 2, 3])
        t.ok(is.array(custJob.data), 'New job with array data created successfully')
        custJob = new Job(q, { object: { foo: 'bar' }, priority: 'high' })
        t.equal(custJob.object.foo, 'bar', 'New job with child object data created successfully')
        t.equal(custJob.priority, 'high', 'New job with new priority created successfully')
        t.throws(() => { new Job(q, () => { }) }, 'New job with function throws error')

        // ---------- Add Job Log ----------
        t.comment('job: Add Job Log')
        return savedJob.addLog(tData, tData)
      }).then((logAddedResult) => {
        t.ok(logAddedResult, 'Job log added successfully')
        return q.getJob(savedJob.id)
      }).then((jobsFromDb) => {
        t.equal(jobsFromDb[0].id, savedJob.id, 'Job retrieved successfully')
        t.equal(jobsFromDb[0].log.length, 2, 'Job log exists')
        t.ok(is.date(jobsFromDb[0].log[1].date), 'Log date is a date')
        t.equal(jobsFromDb[0].log[1].queueId, q.id, 'Log queueId is valid')
        t.equal(jobsFromDb[0].log[1].type, enums.log.information, 'Log type is information')
        t.equal(jobsFromDb[0].log[1].status, enums.status.waiting, 'Log status is valid')
        t.ok(jobsFromDb[0].log[1].retryCount >= 0, 'Log retryCount is valid')
        t.equal(jobsFromDb[0].log[1].message, tData, 'Log message is valid')
        t.equal(jobsFromDb[0].log[1].data, tData, 'Log data is valid')

        // ---------- Set Job Progress ----------
        t.comment('job: Set Job Progress')
        savedJob.status = enums.status.active
        return savedJob.setProgress(50)
      }).then((progressResult) => {
        t.ok(progressResult, 'Job setProgress returned true')
        return q.getJob(savedJob.id)
      }).then((jobsFromDb) => {
        t.equal(jobsFromDb[0].id, savedJob.id, 'Job retrieved successfully')
        t.equal(jobsFromDb[0].progress, 50, 'Job progress valid')

        removeEventHandlers()
        return q.reset()
      }).then((resetResult) => {
        t.ok(resetResult >= 0, 'Queue reset')
        q.stop()
        return resolve(t.end())
      }).catch(err => tError(err, module, t))
    })
  })
}
<|endoftext|>


<commit_before>import React, {PropTypes, Component} from 'react'
import {connect} from 'react-redux'
import createImmutableSelector from '../../../../utils/ImmutableSelect'
import {fromJS} from 'immutable'
import R from 'ramda'
import * as Constants from '../../../../constants/ComponentTypes'
import {fetchAudiences, selectAudience} from '../../../../actions/Audience'
import {Drawer} from '../../../../components/Drawer'
import {List} from '../../../../components/List'
import {ListItemLink} from '../../../../components/list/ListItem';
import {Icon} from '../../../../components/Icon'
import CreateAudience from './CreateAudience'

const filterAudiences = (audiences, exerciseId) => {
  var filterByExercise = n => n.audience_exercise === exerciseId
  var filteredAudiences = R.filter(filterByExercise, audiences.toJS())
  return fromJS(filteredAudiences)
}

class AudienceNav extends Component {
  componentDidMount() {
    this.props.fetchAudiences(this.props.exerciseId);
  }

  handleChangeAudience(audienceId) {
    this.props.selectAudience(this.props.exerciseId, audienceId)
  }

  componentWillReceiveProps(nextProps) {
    let audiences = filterAudiences(nextProps.audiences, nextProps.exerciseId)
    //If current selected audience is not defined or no longer inside the filtered audiences
    if(nextProps.currentAudience === undefined || !audiences.has(nextProps.currentAudience)) {
      this.props.selectAudience(nextProps.exerciseId, audiences.count() > 0 ? audiences.keySeq().first() : undefined)
    }
  }

  render() {
    console.log("===== Render AudienceNav =====", this.props.audiences)
    return (
      <Drawer width={300} docked={true} open={true} openSecondary={true} zindex={50}>
        <CreateAudience exerciseId={this.props.exerciseId}/>
        <List>
          {this.props.audiences.toList().map(audience => {
            return (
              <ListItemLink
                key={audience.get('audience_id')}
                active={this.props.currentAudience === audience.get('audience_id')}
                onClick={this.handleChangeAudience.bind(this, audience.get('audience_id'))}
                label={audience.get('audience_name')}
                leftIcon={<Icon name={Constants.ICON_NAME_SOCIAL_GROUP}/>}
              />
            )
          })}
        </List>
      </Drawer>
    );
  }
}

AudienceNav.propTypes = {
  exerciseId: PropTypes.string,
  currentAudience: PropTypes.string,
  audiences: PropTypes.object,
  fetchAudiences: PropTypes.func,
  selectAudience: PropTypes.func
}

const filteredAudiences = createImmutableSelector(
  (state, props) => filterAudiences(state.application.getIn(['entities', 'audiences']), props.exerciseId),
  audiences => audiences)

const select = (state, props) => {
  return {
    audiences: filteredAudiences(state, props),
    currentAudience: state.application.getIn(['ui', 'states', 'current_audiences', props.exerciseId])
  }
}

export default connect(select, {fetchAudiences, selectAudience})(AudienceNav);<commit_msg>remove console log<commit_after>import React, {PropTypes, Component} from 'react'
import {connect} from 'react-redux'
import createImmutableSelector from '../../../../utils/ImmutableSelect'
import {fromJS} from 'immutable'
import R from 'ramda'
import * as Constants from '../../../../constants/ComponentTypes'
import {fetchAudiences, selectAudience} from '../../../../actions/Audience'
import {Drawer} from '../../../../components/Drawer'
import {List} from '../../../../components/List'
import {ListItemLink} from '../../../../components/list/ListItem';
import {Icon} from '../../../../components/Icon'
import CreateAudience from './CreateAudience'

const filterAudiences = (audiences, exerciseId) => {
  var filterByExercise = n => n.audience_exercise === exerciseId
  var filteredAudiences = R.filter(filterByExercise, audiences.toJS())
  return fromJS(filteredAudiences)
}

class AudienceNav extends Component {
  componentDidMount() {
    this.props.fetchAudiences(this.props.exerciseId);
  }

  handleChangeAudience(audienceId) {
    this.props.selectAudience(this.props.exerciseId, audienceId)
  }

  componentWillReceiveProps(nextProps) {
    let audiences = filterAudiences(nextProps.audiences, nextProps.exerciseId)
    //If current selected audience is not defined or no longer inside the filtered audiences
    if(nextProps.currentAudience === undefined || !audiences.has(nextProps.currentAudience)) {
      this.props.selectAudience(nextProps.exerciseId, audiences.count() > 0 ? audiences.keySeq().first() : undefined)
    }
  }

  render() {
    return (
      <Drawer width={300} docked={true} open={true} openSecondary={true} zindex={50}>
        <CreateAudience exerciseId={this.props.exerciseId}/>
        <List>
          {this.props.audiences.toList().map(audience => {
            return (
              <ListItemLink
                key={audience.get('audience_id')}
                active={this.props.currentAudience === audience.get('audience_id')}
                onClick={this.handleChangeAudience.bind(this, audience.get('audience_id'))}
                label={audience.get('audience_name')}
                leftIcon={<Icon name={Constants.ICON_NAME_SOCIAL_GROUP}/>}
              />
            )
          })}
        </List>
      </Drawer>
    );
  }
}

AudienceNav.propTypes = {
  exerciseId: PropTypes.string,
  currentAudience: PropTypes.string,
  audiences: PropTypes.object,
  fetchAudiences: PropTypes.func,
  selectAudience: PropTypes.func
}

const filteredAudiences = createImmutableSelector(
  (state, props) => filterAudiences(state.application.getIn(['entities', 'audiences']), props.exerciseId),
  audiences => audiences)

const select = (state, props) => {
  return {
    audiences: filteredAudiences(state, props),
    currentAudience: state.application.getIn(['ui', 'states', 'current_audiences', props.exerciseId])
  }
}

export default connect(select, {fetchAudiences, selectAudience})(AudienceNav);<|endoftext|>


<commit_before>"use strict";
let colName = 'catalogs';
const driver = {

	"check": function (req, context, lib, async, BL, callback) {
		//validate if ci schema is valid
		let template = context.template;
		let schema = context.config.schema.post["/catalog/recipes/add"].catalog.validation;
		let myValidator = new req.soajs.validator.Validator();

		//check if name exists
		if (template.content && template.content.recipes && template.content.recipes.deployment && template.content.recipes.deployment.length > 0) {
			let catalogs = template.content.recipes.deployment;
			async.eachSeries(catalogs, (oneCatalog, cb) => {
				let status = myValidator.validate(oneCatalog, schema);
				if (!status.valid) {
					status.errors.forEach(function (err) {
						context.errors.push({code: 173, msg: `<b>${oneCatalog.name}</b>: ` + err.stack, group: "Catalog Deployment Recipes"})
					});
					return cb();
				}
				else {
					let opts = {
						conditions: {
							name: oneCatalog.name
						},
						collection: colName,
					};

					BL.model.countEntries(req.soajs, opts, function (error, count) {
						lib.checkReturnError(req, cb, {config: context.config, error: error, code: 600}, () => {
							if (count && count === 1) {
								context.errors.push({
									"code": 967,
									"msg": `<b>${oneCatalog.name}</b> already exists => ${oneCatalog.name}`,
									'entry':{
										'name': oneCatalog.name,
										'type': 'catalogs'
									}
								})
							}
							return cb();
						});
					});

                    async.series({
                        "checkPorts": (mCb) => {
                            if (oneCatalog.recipe.deployOptions && oneCatalog.recipe.deployOptions.ports && oneCatalog.recipe.deployOptions.ports.length > 0) {
                                var type;
                                var ports = oneCatalog.recipe.deployOptions.ports;

                                async.each(ports, function (onePort, callback) {
                                	var temp;
                                    if (onePort.isPublished || onePort.published) {
                                        temp = onePort.published ? "nodeport" : "loadbalancer";
                                        if (!type) {
                                            type = temp;
                                        }
                                        else if (type !== temp) {
                                            context.errors.push({
                                                code: 173,
                                                msg: `<b>${oneCatalog.name}</b>: Invalid port schema provided!`,
                                                group: "Catalog Deployment Recipes"
                                            });
                                        }
                                    }

                                    //object.
                                    //if isPublished is set to false and published port is set delete published port
                                    if (!onePort.isPublished && onePort.published) {
                                        delete  onePort.published;
                                    }

                                    if (!onePort.published) {
                                        return callback();
                                    }
                                    if (onePort.published && onePort.published < 0 || onePort.published > 2767) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: The port chosen for Nginx is outside the range of valid exposed ports (0 , 2767)`,
                                            group: "Catalog Deployment Recipes"
                                        });
                                    }
                                    return callback();
                                },mCb);
                            } else {
                            	return mCb();
							}
                        },
                        "checkSourceCode": (mCb) => {
                            if (oneCatalog.recipe.deployOptions.sourceCode) {
                                if (oneCatalog.recipe.deployOptions.sourceCode.configuration) {
                                    if (!oneCatalog.recipe.deployOptions.sourceCode.configuration.label) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: Label under configuration repository is missing.`,
                                            group: "Catalog Deployment Recipes"
                                        })
                                    }
                                    if (oneCatalog.recipe.deployOptions.sourceCode.configuration.repo && !oneCatalog.recipe.deployOptions.sourceCode.configuration.branch) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: Branch under configuration repository is missing.`,
                                            group: "Catalog Deployment Recipes"
                                        })
                                    }
                                }

                                if (oneCatalog.recipe.deployOptions.sourceCode.custom) {
                                    // custom repos should only be available for resources of types: server
                                    let allowedTypes = ['server'];
                                    if (allowedTypes.indexOf(oneCatalog.recipe.deployOptions.sourceCode.custom.type) === -1) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: Type under custom repository must be server.`,
                                            group: "Catalog Deployment Recipes"
                                        })
                                    }

                                    if (!oneCatalog.recipe.deployOptions.sourceCode.custom.label) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: Label under custom repository is missing.`,
                                            group: "Catalog Deployment Recipes"
                                        })
                                    }

                                    if (!oneCatalog.recipe.deployOptions.sourceCode.custom.type) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: Type under custom repository is missing.`,
                                            group: "Catalog Deployment Recipes"
                                        })
                                    }

                                    if (oneCatalog.recipe.deployOptions.sourceCode.custom.repo && !oneCatalog.recipe.deployOptions.sourceCode.custom.branch) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: Branch under custom repository is missing.`,
                                            group: "Catalog Deployment Recipes"
                                        })
                                    }
                                }
                                return mCb();
                            } else {
                                return mCb();
							}
                        },
                        "checkVolumes": (mCb) => {
                            if (oneCatalog.recipe && oneCatalog.recipe.deployOptions && oneCatalog.recipe.deployOptions.voluming && oneCatalog.recipe.deployOptions.voluming.length > 0) {
                                async.forEach(oneCatalog.recipe.deployOptions.voluming, (oneVolume, vCb) => {
                                    if (oneVolume.docker && oneVolume.docker.volume && (!oneVolume.docker.volume.Type || oneVolume.docker.volume.Type === '')) {
                                        context.errors.push({
                                            code: 173,
                                            msg: `<b>${oneCatalog.name}</b>: Specify the type for docker volume(s)`,
                                            group: "Catalog Deployment Recipes"
                                        });
                                        return vCb();
                                    }
                                    return vCb();
                                }, mCb);
                            } else {
                            	return mCb();
							}
                        }
                    },cb);
				}
			}, callback);
		} else {
			return callback();
		}
	},

	"merge": function (req, context, lib, async, BL, callback) {

		if (req.soajs.inputmaskData.correction && req.soajs.inputmaskData.correction.catalogs) {
			req.soajs.inputmaskData.correction.catalogs.forEach((oneCatalogInput) => {

				if(context.template.content.recipes && context.template.content.recipes.deployment){
					context.template.content.recipes.deployment.forEach((oneTemplateCatalog) => {
						if (oneCatalogInput.old === oneTemplateCatalog.name) {
							oneTemplateCatalog.name = oneCatalogInput.new;
						}
					});

					//check the other dependent sections
					if (context.template.content.deployments) {
						//check in repos
						if (context.template.content.deployments.repo) {
							for (let oneRepo in context.template.content.deployments.repo) {
								if (context.template.content.deployments.repo[oneRepo].deploy) {
									if (context.template.content.deployments.repo[oneRepo].deploy.recipes) {
										if (context.template.content.deployments.repo[oneRepo].deploy.recipes.default === oneCatalogInput.old) {
											context.template.content.deployments.repo[oneRepo].deploy.recipes.default = oneCatalogInput.new;
										}
										if (context.template.content.deployments.repo[oneRepo].deploy.recipes.available &&
											Array.isArray(context.template.content.deployments.repo[oneRepo].deploy.recipes.available) &&
											context.template.content.deployments.repo[oneRepo].deploy.recipes.available.length > 0) {

											for (let i = 0; i < context.template.content.deployments.repo[oneRepo].deploy.recipes.available.length; i++) {
												if (context.template.content.deployments.repo[oneRepo].deploy.recipes.available[i] === oneCatalogInput.old) {
													context.template.content.deployments.repo[oneRepo].deploy.recipes.available[i] = oneCatalogInput.new;
												}
											}
										}
									}
								}
							}
						}

						//check in resources
						if (context.template.content.deployments.resources) {
							for (let oneResource in context.template.content.deployments.resources) {
								if (context.template.content.deployments.resources[oneResource].deploy) {
									if (context.template.content.deployments.resources[oneResource].deploy.recipes) {
										if (context.template.content.deployments.resources[oneResource].deploy.recipes.default === oneCatalogInput.old) {
											context.template.content.deployments.resources[oneResource].deploy.recipes.default = oneCatalogInput.new;
										}
										if (context.template.content.deployments.resources[oneResource].deploy.recipes.available &&
											Array.isArray(context.template.content.deployments.resources[oneResource].deploy.recipes.available) &&
											context.template.content.deployments.resources[oneResource].deploy.recipes.available.length > 0) {

											for (let i = 0; i < context.template.content.deployments.resources[oneResource].deploy.recipes.available.length; i++) {
												if (context.template.content.deployments.resources[oneResource].deploy.recipes.available[i] === oneCatalogInput.old) {
													context.template.content.deployments.resources[oneResource].deploy.recipes.available[i] = oneCatalogInput.new;
												}
											}
										}
									}
								}
							}
						}
					}
				}
			});
		}

		return callback();
	},

	"save": function (req, context, lib, async, BL, callback) {
		if (context.template.content && context.template.content.recipes && context.template.content.recipes.deployment && context.template.content.recipes.deployment.length > 0) {
			lib.initBLModel('catalog', (error, catalogModule) => {
				lib.checkReturnError(req, callback, {config: context.config, error: error, code: 600}, () => {
					let catalogs = context.template.content.recipes.deployment;
					async.eachSeries(catalogs, (oneCatalog, cb) => {
						req.soajs.inputmaskData = {};
						req.soajs.inputmaskData.catalog = oneCatalog;
						catalogModule.add(context.config, req, (error) => {
							lib.checkReturnError(req, cb, {config: context.config, error: error, code: 600}, cb);
						});
					}, callback);
				});
			});
		} else {
			return callback();
		}
	},

	"export": function(req, context, lib, async, BL, callback){
		if (req.soajs.inputmaskData.deployment && req.soajs.inputmaskData.deployment.length > 0) {
			context.dbData.deployment = [];
			let deployment = req.soajs.inputmaskData.deployment;
			async.map(deployment, (oneCatalogId, cb) => {
				oneCatalogId = new BL.model.getDb(req.soajs).ObjectId(oneCatalogId);
				return cb(null, oneCatalogId);
			}, (error, ids)=> {
				//no error in this case

				BL.model.findEntries(req.soajs, {
					"collection": "catalogs",
					"conditions": {
						"_id": { "$in": ids }
					}
				}, (error, records) =>{
					let blackList = context.config.HA.blacklist;
					if (req.soajs.servicesConfig && req.soajs.servicesConfig.dashboard && req.soajs.servicesConfig.dashboard.HA && req.soajs.servicesConfig.dashboard.HA.blacklist) {
						blackList = req.soajs.servicesConfig.dashboard.HA.blacklist;
					}

					lib.checkReturnError(req, callback, {config: context.config, error: error, code: 600}, () => {
						async.map(records, (oneRecord, mCb) => {
							delete oneRecord._id;
							delete oneRecord.locked;
							delete oneRecord.v;
							delete oneRecord.ts;

							if(oneRecord.recipe && oneRecord.recipe.buildOptions && oneRecord.recipe.buildOptions.env){
								for(let env in oneRecord.recipe.buildOptions.env){
									if (blackList.indexOf(env.toLowerCase()) !== -1) {
										if(oneRecord.recipe.buildOptions.env[env].type === 'static'){
											oneRecord.recipe.buildOptions.env[env].value = "";
										}

										if(oneRecord.recipe.buildOptions.env[env].type === 'userInput'){
											oneRecord.recipe.buildOptions.env[env].default = "";
										}
									}
								}
							}

							context.dbData.deployment.push(oneRecord);
							return mCb();
						}, callback);

					});
				});
			});
		} else {
			return callback();
		}
	}
};

module.exports = driver;<commit_msg>bug fix<commit_after>"use strict";
let colName = 'catalogs';
const driver = {

	"check": function (req, context, lib, async, BL, callback) {
		//validate if ci schema is valid
		let template = context.template;
		let schema = context.config.schema.post["/catalog/recipes/add"].catalog.validation;
		let myValidator = new req.soajs.validator.Validator();

		//check if name exists
		if (template.content && template.content.recipes && template.content.recipes.deployment && template.content.recipes.deployment.length > 0) {
			let catalogs = template.content.recipes.deployment;
			async.eachSeries(catalogs, (oneCatalog, cb) => {
				let status = myValidator.validate(oneCatalog, schema);
				if (!status.valid) {
					status.errors.forEach(function (err) {
						context.errors.push({code: 173, msg: `<b>${oneCatalog.name}</b>: ` + err.stack, group: "Catalog Deployment Recipes"})
					});
					return cb();
				}
				else {
					let opts = {
						conditions: {
							name: oneCatalog.name
						},
						collection: colName,
					};
					BL.model.countEntries(req.soajs, opts, function (error, count) {
						lib.checkReturnError(req, cb, {config: context.config, error: error, code: 600}, () => {
							if (count && count === 1) {
								context.errors.push({
									"code": 967,
									"msg": `<b>${oneCatalog.name}</b> already exists => ${oneCatalog.name}`,
									'entry':{
										'name': oneCatalog.name,
										'type': 'catalogs'
									}
								})
							}
							async.series({
								"checkPorts": (mCb) => {
									if (oneCatalog.recipe.deployOptions && oneCatalog.recipe.deployOptions.ports && oneCatalog.recipe.deployOptions.ports.length > 0) {
										var type;
										var ports = oneCatalog.recipe.deployOptions.ports;

										async.each(ports, function (onePort, callback) {
											var temp;
											if (onePort.isPublished || onePort.published) {
												temp = onePort.published ? "nodeport" : "loadbalancer";
												if (!type) {
													type = temp;
												}
												else if (type !== temp) {
													context.errors.push({
														code: 173,
														msg: `<b>${oneCatalog.name}</b>: Invalid port schema provided!`,
														group: "Catalog Deployment Recipes"
													});
												}
											}

											//object.
											//if isPublished is set to false and published port is set delete published port
											if (!onePort.isPublished && onePort.published) {
												delete  onePort.published;
											}

											if (!onePort.published) {
												return callback();
											}
											if (onePort.published && onePort.published < 0 || onePort.published > 2767) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: The port chosen for Nginx is outside the range of valid exposed ports (0 , 2767)`,
													group: "Catalog Deployment Recipes"
												});
											}
											return callback();
										},mCb);
									} else {
										return mCb();
									}
								},
								"checkSourceCode": (mCb) => {
									if (oneCatalog.recipe.deployOptions.sourceCode) {
										if (oneCatalog.recipe.deployOptions.sourceCode.configuration) {
											if (!oneCatalog.recipe.deployOptions.sourceCode.configuration.label) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: Label under configuration repository is missing.`,
													group: "Catalog Deployment Recipes"
												})
											}
											if (oneCatalog.recipe.deployOptions.sourceCode.configuration.repo && !oneCatalog.recipe.deployOptions.sourceCode.configuration.branch) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: Branch under configuration repository is missing.`,
													group: "Catalog Deployment Recipes"
												})
											}
										}

										if (oneCatalog.recipe.deployOptions.sourceCode.custom) {
											// custom repos should only be available for resources of types: server
											let allowedTypes = ['server'];
											if (allowedTypes.indexOf(oneCatalog.recipe.deployOptions.sourceCode.custom.type) === -1) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: Type under custom repository must be server.`,
													group: "Catalog Deployment Recipes"
												})
											}

											if (!oneCatalog.recipe.deployOptions.sourceCode.custom.label) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: Label under custom repository is missing.`,
													group: "Catalog Deployment Recipes"
												})
											}

											if (!oneCatalog.recipe.deployOptions.sourceCode.custom.type) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: Type under custom repository is missing.`,
													group: "Catalog Deployment Recipes"
												})
											}

											if (oneCatalog.recipe.deployOptions.sourceCode.custom.repo && !oneCatalog.recipe.deployOptions.sourceCode.custom.branch) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: Branch under custom repository is missing.`,
													group: "Catalog Deployment Recipes"
												})
											}
										}
										return mCb();
									} else {
										return mCb();
									}
								},
								"checkVolumes": (mCb) => {
									if (oneCatalog.recipe && oneCatalog.recipe.deployOptions && oneCatalog.recipe.deployOptions.voluming && oneCatalog.recipe.deployOptions.voluming.length > 0) {
										async.forEach(oneCatalog.recipe.deployOptions.voluming, (oneVolume, vCb) => {
											if (oneVolume.docker && oneVolume.docker.volume && (!oneVolume.docker.volume.Type || oneVolume.docker.volume.Type === '')) {
												context.errors.push({
													code: 173,
													msg: `<b>${oneCatalog.name}</b>: Specify the type for docker volume(s)`,
													group: "Catalog Deployment Recipes"
												});
												return vCb();
											}
											return vCb();
										}, mCb);
									} else {
										return mCb();
									}
								}
							},cb);
						});
					});

				}
			}, callback);
		} else {
			return callback();
		}
	},

	"merge": function (req, context, lib, async, BL, callback) {

		if (req.soajs.inputmaskData.correction && req.soajs.inputmaskData.correction.catalogs) {
			req.soajs.inputmaskData.correction.catalogs.forEach((oneCatalogInput) => {

				if(context.template.content.recipes && context.template.content.recipes.deployment){
					context.template.content.recipes.deployment.forEach((oneTemplateCatalog) => {
						if (oneCatalogInput.old === oneTemplateCatalog.name) {
							oneTemplateCatalog.name = oneCatalogInput.new;
						}
					});

					//check the other dependent sections
					if (context.template.content.deployments) {
						//check in repos
						if (context.template.content.deployments.repo) {
							for (let oneRepo in context.template.content.deployments.repo) {
								if (context.template.content.deployments.repo[oneRepo].deploy) {
									if (context.template.content.deployments.repo[oneRepo].deploy.recipes) {
										if (context.template.content.deployments.repo[oneRepo].deploy.recipes.default === oneCatalogInput.old) {
											context.template.content.deployments.repo[oneRepo].deploy.recipes.default = oneCatalogInput.new;
										}
										if (context.template.content.deployments.repo[oneRepo].deploy.recipes.available &&
											Array.isArray(context.template.content.deployments.repo[oneRepo].deploy.recipes.available) &&
											context.template.content.deployments.repo[oneRepo].deploy.recipes.available.length > 0) {

											for (let i = 0; i < context.template.content.deployments.repo[oneRepo].deploy.recipes.available.length; i++) {
												if (context.template.content.deployments.repo[oneRepo].deploy.recipes.available[i] === oneCatalogInput.old) {
													context.template.content.deployments.repo[oneRepo].deploy.recipes.available[i] = oneCatalogInput.new;
												}
											}
										}
									}
								}
							}
						}

						//check in resources
						if (context.template.content.deployments.resources) {
							for (let oneResource in context.template.content.deployments.resources) {
								if (context.template.content.deployments.resources[oneResource].deploy) {
									if (context.template.content.deployments.resources[oneResource].deploy.recipes) {
										if (context.template.content.deployments.resources[oneResource].deploy.recipes.default === oneCatalogInput.old) {
											context.template.content.deployments.resources[oneResource].deploy.recipes.default = oneCatalogInput.new;
										}
										if (context.template.content.deployments.resources[oneResource].deploy.recipes.available &&
											Array.isArray(context.template.content.deployments.resources[oneResource].deploy.recipes.available) &&
											context.template.content.deployments.resources[oneResource].deploy.recipes.available.length > 0) {

											for (let i = 0; i < context.template.content.deployments.resources[oneResource].deploy.recipes.available.length; i++) {
												if (context.template.content.deployments.resources[oneResource].deploy.recipes.available[i] === oneCatalogInput.old) {
													context.template.content.deployments.resources[oneResource].deploy.recipes.available[i] = oneCatalogInput.new;
												}
											}
										}
									}
								}
							}
						}
					}
				}
			});
		}

		return callback();
	},

	"save": function (req, context, lib, async, BL, callback) {
		if (context.template.content && context.template.content.recipes && context.template.content.recipes.deployment && context.template.content.recipes.deployment.length > 0) {
			lib.initBLModel('catalog', (error, catalogModule) => {
				lib.checkReturnError(req, callback, {config: context.config, error: error, code: 600}, () => {
					let catalogs = context.template.content.recipes.deployment;
					async.eachSeries(catalogs, (oneCatalog, cb) => {
						req.soajs.inputmaskData = {};
						req.soajs.inputmaskData.catalog = oneCatalog;
						catalogModule.add(context.config, req, (error) => {
							lib.checkReturnError(req, cb, {config: context.config, error: error, code: 600}, cb);
						});
					}, callback);
				});
			});
		} else {
			return callback();
		}
	},

	"export": function(req, context, lib, async, BL, callback){
		if (req.soajs.inputmaskData.deployment && req.soajs.inputmaskData.deployment.length > 0) {
			context.dbData.deployment = [];
			let deployment = req.soajs.inputmaskData.deployment;
			async.map(deployment, (oneCatalogId, cb) => {
				oneCatalogId = new BL.model.getDb(req.soajs).ObjectId(oneCatalogId);
				return cb(null, oneCatalogId);
			}, (error, ids)=> {
				//no error in this case

				BL.model.findEntries(req.soajs, {
					"collection": "catalogs",
					"conditions": {
						"_id": { "$in": ids }
					}
				}, (error, records) =>{
					let blackList = context.config.HA.blacklist;
					if (req.soajs.servicesConfig && req.soajs.servicesConfig.dashboard && req.soajs.servicesConfig.dashboard.HA && req.soajs.servicesConfig.dashboard.HA.blacklist) {
						blackList = req.soajs.servicesConfig.dashboard.HA.blacklist;
					}

					lib.checkReturnError(req, callback, {config: context.config, error: error, code: 600}, () => {
						async.map(records, (oneRecord, mCb) => {
							delete oneRecord._id;
							delete oneRecord.locked;
							delete oneRecord.v;
							delete oneRecord.ts;

							if(oneRecord.recipe && oneRecord.recipe.buildOptions && oneRecord.recipe.buildOptions.env){
								for(let env in oneRecord.recipe.buildOptions.env){
									if (blackList.indexOf(env.toLowerCase()) !== -1) {
										if(oneRecord.recipe.buildOptions.env[env].type === 'static'){
											oneRecord.recipe.buildOptions.env[env].value = "";
										}

										if(oneRecord.recipe.buildOptions.env[env].type === 'userInput'){
											oneRecord.recipe.buildOptions.env[env].default = "";
										}
									}
								}
							}

							context.dbData.deployment.push(oneRecord);
							return mCb();
						}, callback);

					});
				});
			});
		} else {
			return callback();
		}
	}
};

module.exports = driver;<|endoftext|>


<commit_before>// Event handler for updating the current activities on the subject coordinator dashboards
SC.updateCurrentActivities = function(href) {
    new Ajax.Request(href, {
        postBody: $('current-activities-form').serialize()
    });
}

SC.registerCurrentActivitiesUpdaters = function(href) {
    Event.observe(window, 'load', function() {
        console.log("Registering")
        var handler = function() { SC.updateCurrentActivities(href) }
        $('toDate').observe('change', handler)
        $$('input.activity-type').each(function(input) {
            input.observe('change', handler)
        })
    })
}<commit_msg>ticket # 335 - Fixing "Activities for the next X date" submition for the Subject Coordinator Dashboard<commit_after>// Event handler for updating the current activities on the subject coordinator dashboards
SC.updateCurrentActivities = function(href) {
    new Ajax.Request(href, {
        postBody: $('current-activities-form').serialize()
    });
}

SC.registerCurrentActivitiesUpdaters = function(href) {
    Event.observe(window, 'load', function() {
        var handler = function() { SC.updateCurrentActivities(href) }
        $('toDate').observe('change', handler)
        $$('input.activity-type').each(function(input) {
            input.observe('change', handler)
        })

        var handler1 = function(evt) {
            Event.stop(evt)
        }
        $('current-activities-form').observe('submit', handler1)
    })
}

<|endoftext|>