<commit_before>/**
 * Mega pixel image rendering library for iOS6 Safari
 *
 * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel),
 * which causes unexpected subsampling when drawing it in canvas.
 * By using this library, you can safely render the image with proper stretching.
 *
 * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>
 * Released under the MIT license
 */
(function() {

  /**
   * Detect subsampling in loaded image.
   * In iOS, larger images than 2M pixels may be subsampled in rendering.
   */
  function detectSubsampling(img) {
    var iw = img.naturalWidth, ih = img.naturalHeight;
    if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image
      var canvas = document.createElement('canvas');
      canvas.width = canvas.height = 1;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, -iw + 1, 0);
      // subsampled image becomes half smaller in rendering size.
      // check alpha channel value to confirm image is covering edge pixel or not.
      // if alpha value is 0 image is not covering, hence subsampled.
      return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
    } else {
      return false;
    }
  }

  /**
   * Detecting vertical squash in loaded image.
   * Fixes a bug which squash image vertically while drawing into canvas for some images.
   */
  function detectVerticalSquash(img, iw, ih) {
    var canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = ih;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
    var data = ctx.getImageData(0, 0, 1, ih).data;
    // search image edge pixel position in case it is squashed vertically.
    var sy = 0;
    var ey = ih;
    var py = ih;
    while (py > sy) {
      var alpha = data[(py - 1) * 4 + 3];
      if (alpha === 0) {
        ey = py;
      } else {
        sy = py;
      }
      py = (ey + sy) >> 1;
    }
    var ratio = (py / ih);
    return (ratio===0)?1:ratio;
  }

  /**
   * Rendering image element (with resizing) and get its data URL
   */
  function renderImageToDataURL(img, options, doSquash) {
    var canvas = document.createElement('canvas');
    renderImageToCanvas(img, canvas, options, doSquash);
    return canvas.toDataURL("image/jpeg", options.quality || 0.8);
  }

  /**
   * Rendering image element (with resizing) into the canvas element
   */
  function renderImageToCanvas(img, canvas, options, doSquash) {
    var iw = img.naturalWidth, ih = img.naturalHeight;
    var width = options.width, height = options.height;
    var ctx = canvas.getContext('2d');
    ctx.save();
    transformCoordinate(canvas, width, height, options.orientation);
    var subsampled = detectSubsampling(img);
    if (subsampled) {
      iw /= 2;
      ih /= 2;
    }
    var d = 1024; // size of tiling canvas
    var tmpCanvas = document.createElement('canvas');
    tmpCanvas.width = tmpCanvas.height = d;
    var tmpCtx = tmpCanvas.getContext('2d');
    var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1;
    var dw = Math.ceil(d * width / iw);
    var dh = Math.ceil(d * height / ih / vertSquashRatio);
    var sy = 0;
    var dy = 0;
    while (sy < ih) {
      var sx = 0;
      var dx = 0;
      while (sx < iw) {
        tmpCtx.clearRect(0, 0, d, d);
        tmpCtx.drawImage(img, -sx, -sy);
        ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
        sx += d;
        dx += dw;
      }
      sy += d;
      dy += dh;
    }
    ctx.restore();
    tmpCanvas = tmpCtx = null;
  }

  /**
   * Transform canvas coordination according to specified frame size and orientation
   * Orientation value is from EXIF tag
   */
  function transformCoordinate(canvas, width, height, orientation) {
    switch (orientation) {
      case 5:
      case 6:
      case 7:
      case 8:
        canvas.width = height;
        canvas.height = width;
        break;
      default:
        canvas.width = width;
        canvas.height = height;
    }
    var ctx = canvas.getContext('2d');
    switch (orientation) {
      case 2:
        // horizontal flip
        ctx.translate(width, 0);
        ctx.scale(-1, 1);
        break;
      case 3:
        // 180 rotate left
        ctx.translate(width, height);
        ctx.rotate(Math.PI);
        break;
      case 4:
        // vertical flip
        ctx.translate(0, height);
        ctx.scale(1, -1);
        break;
      case 5:
        // vertical flip + 90 rotate right
        ctx.rotate(0.5 * Math.PI);
        ctx.scale(1, -1);
        break;
      case 6:
        // 90 rotate right
        ctx.rotate(0.5 * Math.PI);
        ctx.translate(0, -height);
        break;
      case 7:
        // horizontal flip + 90 rotate right
        ctx.rotate(0.5 * Math.PI);
        ctx.translate(width, -height);
        ctx.scale(-1, 1);
        break;
      case 8:
        // 90 rotate left
        ctx.rotate(-0.5 * Math.PI);
        ctx.translate(-width, 0);
        break;
      default:
        break;
    }
  }

  /**
   * MegaPixImage class
   */
  function MegaPixImage(srcImage) {
    if (srcImage instanceof Blob) {
      var img = new Image();
      var URL = window.URL && window.URL.createObjectURL ? window.URL :
                window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL :
                null;
      if (!URL) { throw Error("No createObjectURL function found to create blob url"); }
      img.src = URL.createObjectURL(srcImage);
      this.blob = srcImage;
      srcImage = img;
    }
    if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
      var _this = this;
      srcImage.onload = function() {
        var listeners = _this.imageLoadListeners;
        if (listeners) {
          _this.imageLoadListeners = null;
          for (var i=0, len=listeners.length; i<len; i++) {
            listeners[i]();
          }
        }
      };
      this.imageLoadListeners = [];
    }
    this.srcImage = srcImage;
  }

  /**
   * Rendering megapix image into specified target element
   */
  MegaPixImage.prototype.render = function(target, options) {
    if (this.imageLoadListeners) {
      var _this = this;
      this.imageLoadListeners.push(function() { _this.render(target, options) });
      return;
    }
    options = options || {};
    var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight,
        width = options.width, height = options.height,
        maxWidth = options.maxWidth, maxHeight = options.maxHeight,
        doSquash = !this.blob || this.blob.type === 'image/jpeg';
    if (width && !height) {
      height = (imgHeight * width / imgWidth) << 0;
    } else if (height && !width) {
      width = (imgWidth * height / imgHeight) << 0;
    } else {
      width = imgWidth;
      height = imgHeight;
    }
    if (maxWidth && width > maxWidth) {
      width = maxWidth;
      height = (imgHeight * width / imgWidth) << 0;
    }
    if (maxHeight && height > maxHeight) {
      height = maxHeight;
      width = (imgWidth * height / imgHeight) << 0;
    }
    var opt = { width : width, height : height };
    for (var k in options) opt[k] = options[k];

    var tagName = target.tagName.toLowerCase();
    if (tagName === 'img') {
      target.src = renderImageToDataURL(this.srcImage, opt, doSquash);
    } else if (tagName === 'canvas') {
      renderImageToCanvas(this.srcImage, target, opt, doSquash);
    }
    if (typeof this.onrender === 'function') {
      this.onrender(target);
    }
  };

  /**
   * Export class to global
   */
  if (typeof define === 'function' && define.amd) {
    define([], function() { return MegaPixImage; }); // for AMD loader
  } else {
    this.MegaPixImage = MegaPixImage;
  }

})();
<commit_msg>fixed ie9 bug (Issue #20)<commit_after>/**
 * Mega pixel image rendering library for iOS6 Safari
 *
 * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel),
 * which causes unexpected subsampling when drawing it in canvas.
 * By using this library, you can safely render the image with proper stretching.
 *
 * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>
 * Released under the MIT license
 */
(function() {

  /**
   * Detect subsampling in loaded image.
   * In iOS, larger images than 2M pixels may be subsampled in rendering.
   */
  function detectSubsampling(img) {
    var iw = img.naturalWidth, ih = img.naturalHeight;
    if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image
      var canvas = document.createElement('canvas');
      canvas.width = canvas.height = 1;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, -iw + 1, 0);
      // subsampled image becomes half smaller in rendering size.
      // check alpha channel value to confirm image is covering edge pixel or not.
      // if alpha value is 0 image is not covering, hence subsampled.
      return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
    } else {
      return false;
    }
  }

  /**
   * Detecting vertical squash in loaded image.
   * Fixes a bug which squash image vertically while drawing into canvas for some images.
   */
  function detectVerticalSquash(img, iw, ih) {
    var canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = ih;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
    var data = ctx.getImageData(0, 0, 1, ih).data;
    // search image edge pixel position in case it is squashed vertically.
    var sy = 0;
    var ey = ih;
    var py = ih;
    while (py > sy) {
      var alpha = data[(py - 1) * 4 + 3];
      if (alpha === 0) {
        ey = py;
      } else {
        sy = py;
      }
      py = (ey + sy) >> 1;
    }
    var ratio = (py / ih);
    return (ratio===0)?1:ratio;
  }

  /**
   * Rendering image element (with resizing) and get its data URL
   */
  function renderImageToDataURL(img, options, doSquash) {
    var canvas = document.createElement('canvas');
    renderImageToCanvas(img, canvas, options, doSquash);
    return canvas.toDataURL("image/jpeg", options.quality || 0.8);
  }

  /**
   * Rendering image element (with resizing) into the canvas element
   */
  function renderImageToCanvas(img, canvas, options, doSquash) {
    var iw = img.naturalWidth, ih = img.naturalHeight;
    var width = options.width, height = options.height;
    var ctx = canvas.getContext('2d');
    ctx.save();
    transformCoordinate(canvas, width, height, options.orientation);
    var subsampled = detectSubsampling(img);
    if (subsampled) {
      iw /= 2;
      ih /= 2;
    }
    var d = 1024; // size of tiling canvas
    var tmpCanvas = document.createElement('canvas');
    tmpCanvas.width = tmpCanvas.height = d;
    var tmpCtx = tmpCanvas.getContext('2d');
    var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1;
    var dw = Math.ceil(d * width / iw);
    var dh = Math.ceil(d * height / ih / vertSquashRatio);
    var sy = 0;
    var dy = 0;
    while (sy < ih) {
      var sx = 0;
      var dx = 0;
      while (sx < iw) {
        tmpCtx.clearRect(0, 0, d, d);
        tmpCtx.drawImage(img, -sx, -sy);
        ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
        sx += d;
        dx += dw;
      }
      sy += d;
      dy += dh;
    }
    ctx.restore();
    tmpCanvas = tmpCtx = null;
  }

  /**
   * Transform canvas coordination according to specified frame size and orientation
   * Orientation value is from EXIF tag
   */
  function transformCoordinate(canvas, width, height, orientation) {
    switch (orientation) {
      case 5:
      case 6:
      case 7:
      case 8:
        canvas.width = height;
        canvas.height = width;
        break;
      default:
        canvas.width = width;
        canvas.height = height;
    }
    var ctx = canvas.getContext('2d');
    switch (orientation) {
      case 2:
        // horizontal flip
        ctx.translate(width, 0);
        ctx.scale(-1, 1);
        break;
      case 3:
        // 180 rotate left
        ctx.translate(width, height);
        ctx.rotate(Math.PI);
        break;
      case 4:
        // vertical flip
        ctx.translate(0, height);
        ctx.scale(1, -1);
        break;
      case 5:
        // vertical flip + 90 rotate right
        ctx.rotate(0.5 * Math.PI);
        ctx.scale(1, -1);
        break;
      case 6:
        // 90 rotate right
        ctx.rotate(0.5 * Math.PI);
        ctx.translate(0, -height);
        break;
      case 7:
        // horizontal flip + 90 rotate right
        ctx.rotate(0.5 * Math.PI);
        ctx.translate(width, -height);
        ctx.scale(-1, 1);
        break;
      case 8:
        // 90 rotate left
        ctx.rotate(-0.5 * Math.PI);
        ctx.translate(-width, 0);
        break;
      default:
        break;
    }
  }

  /**
   * MegaPixImage class
   */
  function MegaPixImage(srcImage) {
    if (window.Blob && srcImage instanceof Blob) {
      var img = new Image();
      var URL = window.URL && window.URL.createObjectURL ? window.URL :
                window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL :
                null;
      if (!URL) { throw Error("No createObjectURL function found to create blob url"); }
      img.src = URL.createObjectURL(srcImage);
      this.blob = srcImage;
      srcImage = img;
    }
    if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
      var _this = this;
      srcImage.onload = function() {
        var listeners = _this.imageLoadListeners;
        if (listeners) {
          _this.imageLoadListeners = null;
          for (var i=0, len=listeners.length; i<len; i++) {
            listeners[i]();
          }
        }
      };
      this.imageLoadListeners = [];
    }
    this.srcImage = srcImage;
  }

  /**
   * Rendering megapix image into specified target element
   */
  MegaPixImage.prototype.render = function(target, options) {
    if (this.imageLoadListeners) {
      var _this = this;
      this.imageLoadListeners.push(function() { _this.render(target, options) });
      return;
    }
    options = options || {};
    var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight,
        width = options.width, height = options.height,
        maxWidth = options.maxWidth, maxHeight = options.maxHeight,
        doSquash = !this.blob || this.blob.type === 'image/jpeg';
    if (width && !height) {
      height = (imgHeight * width / imgWidth) << 0;
    } else if (height && !width) {
      width = (imgWidth * height / imgHeight) << 0;
    } else {
      width = imgWidth;
      height = imgHeight;
    }
    if (maxWidth && width > maxWidth) {
      width = maxWidth;
      height = (imgHeight * width / imgWidth) << 0;
    }
    if (maxHeight && height > maxHeight) {
      height = maxHeight;
      width = (imgWidth * height / imgHeight) << 0;
    }
    var opt = { width : width, height : height };
    for (var k in options) opt[k] = options[k];

    var tagName = target.tagName.toLowerCase();
    if (tagName === 'img') {
      target.src = renderImageToDataURL(this.srcImage, opt, doSquash);
    } else if (tagName === 'canvas') {
      renderImageToCanvas(this.srcImage, target, opt, doSquash);
    }
    if (typeof this.onrender === 'function') {
      this.onrender(target);
    }
  };

  /**
   * Export class to global
   */
  if (typeof define === 'function' && define.amd) {
    define([], function() { return MegaPixImage; }); // for AMD loader
  } else {
    this.MegaPixImage = MegaPixImage;
  }

})();
<|endoftext|>


<commit_before>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 */

'use strict';

var openiLogger  = require('openi-logger');
var openiUtils   = require('openi-cloudlet-utils');
var zmq          = require('m2nodehandler');
var querystring  = require('querystring');
var https        = require('https');
var loglet      = require('loglet');
loglet = loglet.child({component: 'type-api'});

var allowedTypes = ['boolean', 'int', 'float', 'string', 'url', 'attachment', 'date', 'timestamp', 'hexadecimal', 'base64'];

var init = function(logger_params) {
   this.logger = openiLogger(logger_params);
};

var validateType = function(msg, callback) {

   var type     = msg.json;
   var subTypes = [];
   var errs     = [];
   var type_val;

   if ( !('@reference' in  type) || '' === type['@reference']) {
      errs.push('Required property @reference is missing.');
   }
   if ( !('@context' in  type) || !Array.isArray(type['@context']) || 0 === type['@context'].length ){
      errs.push('Required property @context is missing.');
   }

   for ( var i in type['@context']) {

      if(type['@context'].hasOwnProperty(i)) {
         var entry = type['@context'][i];
         var name  = entry['@property_name'];

         if ( !('@property_name' in  entry) || '' === entry['@property_name']) {
            errs.push('In \'' + name + '\' required parameter @property_name is missing.');
         }

         if ( !('@context_id' in  entry) || '' === entry['@context_id']) {
            errs.push('In \'' + name + '\' required parameter @context_id is missing.');
         }

         if ( !( '@openi_type' in entry) ) {
            errs.push('In \'' + name + '\' required parameter @openi_type is missing.');
         }

         if ( !( '@required' in entry) ) {
            errs.push('In \'' + name + '\' required parameter @required is missing.');
         }

         if ( !( '@multiple' in entry) ) {
            errs.push('In \'' + name + '\' required parameter @multiple is missing.');
         }

         if ( '@allowed_values' in entry ) {
            if ( Object.prototype.toString.call( entry['@allowed_values'] ) !== '[object Array]' || 0 === entry['@allowed_values'].length ){
               errs.push('In \'' + name + '\' @allowed_values array is empty');
            }
            else{
               //type = entry['@openi_type'];
               for (var allowed_entry in entry['@allowed_values']){
                  //use validator to check that allowed_entry is of apt type
               }
            }
         }

         if (undefined === entry['@openi_type'] || -1 === allowedTypes.indexOf(entry['@openi_type'].toLowerCase())) {

            type_val = entry['@openi_type'];

            if ( openiUtils.isTypeId(type_val) ){
               subTypes.push(type_val);
            }
            else{
               errs.push(entry['@openi_type'].toLowerCase() + ' is not a valid type.');
            }
         }
      }
   }

   if (errs.length > 0){
      callback( {valid:false, errors:errs});
      loglet.error(errs);
   }
   else if (0 === subTypes.length){
      callback( {valid:true});
   }
   else{
      type_val = subTypes.pop();
      validateSubType(msg, type_val, subTypes, callback);
   }
};

var validateSubType = function(msg, type_id, subTypes, callback){

   var type = "https://" + msg.headers.host + "/api/v1/types/" + type_id;

   var request = https.get(type, function(res) {

      var typeStr2 = '';

      res.on('data', function (chunk) {
         typeStr2 += chunk;
      });

      res.on('end', function () {

         var type_json = {};

         try{
            type_json = JSON.parse(typeStr2);
         }
         catch(e){
            loglet.error(e);
            return callback( {valid:false, error:[ type + ' cannot be found.']});
         }

         if (type_json["@id"] === type_id ){
            if (subTypes.length > 0){
               var new_type = subTypes.pop();
               validateSubType(msg, new_type, subTypes, callback);
            }
            else{
               return callback( {valid:true});
            }
         }
         else{
            return callback( {valid:false, error:[ type + ' is not a valid type.']});
         }
      });

   }).on('error', function(e) {
         loglet.error(e);
         return  callback( {valid:false, error:[ type + ' is not a valid type.' ]});
      }).setTimeout( 5000, function( ) {
         return callback( {valid:false, error:[ type + ' could not be found.']});
      });
};

var genPostMessage = function(msg, senderToDao, senderToClient, terminal_handler) {

   if (undefined === msg.json || null === msg.json){

      senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Empty body.' });

      return;
   }

   var typeId = 't_' + openiUtils.hash(msg.json);

   var typeRestUrl = "/api/v1/types/" + typeId;

   msg.json['@id']            = typeId;
   msg.json['@location']      = typeRestUrl;
   msg.json['_date_created'] = new Date().toJSON();

   validateType(msg, function(validCheck){

      if (!validCheck.valid) {

         var errorString = (undefined === validCheck.errors)  ? "" : validCheck.errors.join(" ");

         senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Type object isn\'t properly structured : ' + errorString});

         return;
      }

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'      : 'POST',
               'database'    : typeId,
               'object_name' : 'meta',
               'object_data' : msg.json,
               'id'          : typeId,
               'bucket'      : 'types'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   });
};

var genGetMessage = function(msg, senderToDao, senderToClient, terminal_handler) {

   var query = querystring.parse(msg.headers.QUERY);

   if ( msg.path === '/api/v1/types' || msg.path === '/api/v1/types/' ) {

      var limit  = (undefined !== query.limit)  ? Number(query.limit)   : 30;
      var offset = (undefined !== query.offset) ? Number(query.offset)  :  0;
      var prev   = msg.headers.URI.replace("offset="+offset, "offset="+ (((offset - limit) < 0) ? 0 : (offset - limit)));
      var next   = msg.headers.URI.replace("offset="+offset, "offset="+ (offset + limit));

      var meta = {
         "limit"       : limit,
         "offset"      : offset,
         "total_count" : 0,
         "prev"        : (0 === offset)? null : prev,
         "next"        : next
      };

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'design_doc'   : 'type_views',
               'view_name'    : 'types_list',
               'meta'         : meta,
               'filter_show'  : query['only_show_properties'],
               'content-type' : query['content-type'],
               'resp_type'    : 'type',
               'id_only'      : ('true' === query.id_only),
               'bucket'       : 'types'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   } else if ( msg.path === '/api/v1/types/stats' ) {

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'design_doc'   : 'type_views',
               'view_name'    : 'types_usage',
               'group'        : 0,
               'resp_type'    : 'type_stats',
               'bucket'       : 'types'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   } else {

      var type =   openiUtils.extractTypeId(msg.path);

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'GET',
               'database'     : type,
               'id'           : type,
               'content-type' : query['content-type'],
               'resp_type'    : 'type',
               'bucket'       : 'types'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   }
};

var genPatchMessage = function(msg, senderToDao, senderToClient, terminal_handler) {

   return senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Feature temporarily disabled' });

   if (undefined === msg.json || null === msg.json) {

      senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Type array is empty' });

      return;
   }

   var actions = [];

   for ( var i =0; i < msg.json.length; i++) {
      var entry       = msg[i];
      var typeId      = 't_' + openiUtils.hash(entry);
      var typeRestUrl = "/api/v1/types/" + typeId;

      if (!validateType(entry)) {

         senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Type object isn\'t properly structured' });

         return;
      }

      entry['@id']            = typeId;
      entry['@location']      = typeRestUrl;
      entry['_date_created']  = new Date().toJSON();

      actions.push({
         'action'      : 'POST',
         'database'    : typeId,
         'object_name' : 'meta',
         'object_data' : entry,
         'id'          : typeId,
         'resp_type'   : 'type',
         'bucket'      : 'types'
      });
   }

   senderToDao.send({
      'dao_actions'  : actions,
      'mongrel_sink' : terminal_handler,
      'clients'      : [
         {
            'uuid' : msg.uuid,
            'connId' : msg.connId
         }
      ]
   });
};

var processMongrel2Message = function (msg, senderToDao, senderToClient, terminal_handler) {

   this.logger.logMongrel2Message(msg);

   for(var key in msg.json) {
      if(msg.json.hasOwnProperty(key)) {
         if(msg.json[key] === null) {
            delete msg.json[key];
         }
      }
   }

   switch(msg.headers['METHOD']) {
      case 'POST':
         genPostMessage(msg, senderToDao, senderToClient, terminal_handler);
         break;
      case 'GET':
         genGetMessage(msg, senderToDao, senderToClient, terminal_handler);
         break;
      case 'PATCH':
         genPatchMessage(msg, senderToDao, senderToClient, terminal_handler);
         break;
      default:
         break;
   }
};

module.exports.init                   = init;
module.exports.processMongrel2Message = processMongrel2Message;<commit_msg>fixed stats view<commit_after>/*
 * openi_data_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dmccarthy
 */

'use strict';

var openiLogger  = require('openi-logger');
var openiUtils   = require('openi-cloudlet-utils');
var zmq          = require('m2nodehandler');
var querystring  = require('querystring');
var https        = require('https');
var loglet      = require('loglet');
loglet = loglet.child({component: 'type-api'});

var allowedTypes = ['boolean', 'int', 'float', 'string', 'url', 'attachment', 'date', 'timestamp', 'hexadecimal', 'base64'];

var init = function(logger_params) {
   this.logger = openiLogger(logger_params);
};

var validateType = function(msg, callback) {

   var type     = msg.json;
   var subTypes = [];
   var errs     = [];
   var type_val;

   if ( !('@reference' in  type) || '' === type['@reference']) {
      errs.push('Required property @reference is missing.');
   }
   if ( !('@context' in  type) || !Array.isArray(type['@context']) || 0 === type['@context'].length ){
      errs.push('Required property @context is missing.');
   }

   for ( var i in type['@context']) {

      if(type['@context'].hasOwnProperty(i)) {
         var entry = type['@context'][i];
         var name  = entry['@property_name'];

         if ( !('@property_name' in  entry) || '' === entry['@property_name']) {
            errs.push('In \'' + name + '\' required parameter @property_name is missing.');
         }

         if ( !('@context_id' in  entry) || '' === entry['@context_id']) {
            errs.push('In \'' + name + '\' required parameter @context_id is missing.');
         }

         if ( !( '@openi_type' in entry) ) {
            errs.push('In \'' + name + '\' required parameter @openi_type is missing.');
         }

         if ( !( '@required' in entry) ) {
            errs.push('In \'' + name + '\' required parameter @required is missing.');
         }

         if ( !( '@multiple' in entry) ) {
            errs.push('In \'' + name + '\' required parameter @multiple is missing.');
         }

         if ( '@allowed_values' in entry ) {
            if ( Object.prototype.toString.call( entry['@allowed_values'] ) !== '[object Array]' || 0 === entry['@allowed_values'].length ){
               errs.push('In \'' + name + '\' @allowed_values array is empty');
            }
            else{
               //type = entry['@openi_type'];
               for (var allowed_entry in entry['@allowed_values']){
                  //use validator to check that allowed_entry is of apt type
               }
            }
         }

         if (undefined === entry['@openi_type'] || -1 === allowedTypes.indexOf(entry['@openi_type'].toLowerCase())) {

            type_val = entry['@openi_type'];

            if ( openiUtils.isTypeId(type_val) ){
               subTypes.push(type_val);
            }
            else{
               errs.push(entry['@openi_type'].toLowerCase() + ' is not a valid type.');
            }
         }
      }
   }

   if (errs.length > 0){
      callback( {valid:false, errors:errs});
      loglet.error(errs);
   }
   else if (0 === subTypes.length){
      callback( {valid:true});
   }
   else{
      type_val = subTypes.pop();
      validateSubType(msg, type_val, subTypes, callback);
   }
};

var validateSubType = function(msg, type_id, subTypes, callback){

   var type = "https://" + msg.headers.host + "/api/v1/types/" + type_id;

   var request = https.get(type, function(res) {

      var typeStr2 = '';

      res.on('data', function (chunk) {
         typeStr2 += chunk;
      });

      res.on('end', function () {

         var type_json = {};

         try{
            type_json = JSON.parse(typeStr2);
         }
         catch(e){
            loglet.error(e);
            return callback( {valid:false, error:[ type + ' cannot be found.']});
         }

         if (type_json["@id"] === type_id ){
            if (subTypes.length > 0){
               var new_type = subTypes.pop();
               validateSubType(msg, new_type, subTypes, callback);
            }
            else{
               return callback( {valid:true});
            }
         }
         else{
            return callback( {valid:false, error:[ type + ' is not a valid type.']});
         }
      });

   }).on('error', function(e) {
         loglet.error(e);
         return  callback( {valid:false, error:[ type + ' is not a valid type.' ]});
      }).setTimeout( 5000, function( ) {
         return callback( {valid:false, error:[ type + ' could not be found.']});
      });
};

var genPostMessage = function(msg, senderToDao, senderToClient, terminal_handler) {

   if (undefined === msg.json || null === msg.json){

      senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Empty body.' });

      return;
   }

   var typeId = 't_' + openiUtils.hash(msg.json);

   var typeRestUrl = "/api/v1/types/" + typeId;

   msg.json['@id']            = typeId;
   msg.json['@location']      = typeRestUrl;
   msg.json['_date_created'] = new Date().toJSON();

   validateType(msg, function(validCheck){

      if (!validCheck.valid) {

         var errorString = (undefined === validCheck.errors)  ? "" : validCheck.errors.join(" ");

         senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Type object isn\'t properly structured : ' + errorString});

         return;
      }

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'      : 'POST',
               'database'    : typeId,
               'object_name' : 'meta',
               'object_data' : msg.json,
               'id'          : typeId,
               'bucket'      : 'types'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   });
};

var genGetMessage = function(msg, senderToDao, senderToClient, terminal_handler) {

   var query = querystring.parse(msg.headers.QUERY);

   if ( msg.path === '/api/v1/types' || msg.path === '/api/v1/types/' ) {

      var limit  = (undefined !== query.limit)  ? Number(query.limit)   : 30;
      var offset = (undefined !== query.offset) ? Number(query.offset)  :  0;
      var prev   = msg.headers.URI.replace("offset="+offset, "offset="+ (((offset - limit) < 0) ? 0 : (offset - limit)));
      var next   = msg.headers.URI.replace("offset="+offset, "offset="+ (offset + limit));

      var meta = {
         "limit"       : limit,
         "offset"      : offset,
         "total_count" : 0,
         "prev"        : (0 === offset)? null : prev,
         "next"        : next
      };

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'design_doc'   : 'type_views',
               'view_name'    : 'types_list',
               'meta'         : meta,
               'filter_show'  : query['only_show_properties'],
               'content-type' : query['content-type'],
               'resp_type'    : 'type',
               'id_only'      : ('true' === query.id_only),
               'bucket'       : 'types'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   } else if ( msg.path === '/api/v1/types/stats' ) {

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'VIEW',
               'design_doc'   : 'objects_views',
               'view_name'    : 'type_usage',
               'group_level'  : 1,
               'resp_type'    : 'type_stats',
               'reduce'       : true,
               'bucket'       : 'objects'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   } else {

      var type =   openiUtils.extractTypeId(msg.path);

      senderToDao.send({
         'dao_actions'      : [
            {
               'action'       : 'GET',
               'database'     : type,
               'id'           : type,
               'content-type' : query['content-type'],
               'resp_type'    : 'type',
               'bucket'       : 'types'
            }
         ],
         'mongrel_sink' : terminal_handler,
         'clients'      : [
            {
               'uuid' : msg.uuid,
               'connId' : msg.connId
            }
         ]
      });
   }
};

var genPatchMessage = function(msg, senderToDao, senderToClient, terminal_handler) {

   return senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Feature temporarily disabled' });

   if (undefined === msg.json || null === msg.json) {

      senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Type array is empty' });

      return;
   }

   var actions = [];

   for ( var i =0; i < msg.json.length; i++) {
      var entry       = msg[i];
      var typeId      = 't_' + openiUtils.hash(entry);
      var typeRestUrl = "/api/v1/types/" + typeId;

      if (!validateType(entry)) {

         senderToClient.send(msg.uuid, msg.connId, zmq.status.BAD_REQUEST_400, zmq.standard_headers.json, {'error' : 'Type object isn\'t properly structured' });

         return;
      }

      entry['@id']            = typeId;
      entry['@location']      = typeRestUrl;
      entry['_date_created']  = new Date().toJSON();

      actions.push({
         'action'      : 'POST',
         'database'    : typeId,
         'object_name' : 'meta',
         'object_data' : entry,
         'id'          : typeId,
         'resp_type'   : 'type',
         'bucket'      : 'types'
      });
   }

   senderToDao.send({
      'dao_actions'  : actions,
      'mongrel_sink' : terminal_handler,
      'clients'      : [
         {
            'uuid' : msg.uuid,
            'connId' : msg.connId
         }
      ]
   });
};

var processMongrel2Message = function (msg, senderToDao, senderToClient, terminal_handler) {

   this.logger.logMongrel2Message(msg);

   for(var key in msg.json) {
      if(msg.json.hasOwnProperty(key)) {
         if(msg.json[key] === null) {
            delete msg.json[key];
         }
      }
   }

   switch(msg.headers['METHOD']) {
      case 'POST':
         genPostMessage(msg, senderToDao, senderToClient, terminal_handler);
         break;
      case 'GET':
         genGetMessage(msg, senderToDao, senderToClient, terminal_handler);
         break;
      case 'PATCH':
         genPatchMessage(msg, senderToDao, senderToClient, terminal_handler);
         break;
      default:
         break;
   }
};

module.exports.init                   = init;
module.exports.processMongrel2Message = processMongrel2Message;<|endoftext|>


<commit_before>var locastyle = locastyle || {};

locastyle.progressBar = (function() {
  'use strict';

  function init() {
    structureProgressBar();
  }

  function structureProgressBar() {
    $("[data-ls-module='progressBar']").each(function (index, element){
      var percentage = $(element).attr("aria-valuenow");
      $(element).append("");
        var $bar       = $(element).find('span');
      setProgressBarValue($bar, percentage);
    });
  }

  function setProgressBarValue(target, percentage) {
    $(target).css("width", percentage+"%");
  }

  return {
    init: init
  }

}());
<commit_msg>lint progress<commit_after>var locastyle = locastyle || {};

locastyle.progressBar = (function() {
  'use strict';

  function init() {
    structureProgressBar();
  }

  function structureProgressBar() {
    $("[data-ls-module='progressBar']").each(function (index, element){
      var percentage = $(element).attr("aria-valuenow");
      $(element).append("");
        var $bar       = $(element).find('span');
      setProgressBarValue($bar, percentage);
    });
  }

  function setProgressBarValue(target, percentage) {
    $(target).css("width", percentage+"%");
  }

  return {
    init: init
  };

}());
<|endoftext|>


<commit_before>'use strict'
var vstamp = require('vigour-stamp')
var subscribe = require('./subscribe')
var hash = require('vigour-util/hash')

// function keyToNumber (key) {
//   let num = key
//   // for (let i = 0, len = key.length; i < len; i++) {
//   //   num += key.charCodeAt(i)
//   // }
//   return num
// }

module.exports = {
  properties: {
    _lstamp: true,
    _sid: true,
    _subscriptions: true,
    cachedSyncPath: true
  },
  // make it easy to create different stamps when using a hub (source ids etc)
  _lstamp: 0,
  define: {
    isState: { value: true },
    keysCheck (val, key) {
      const target = val[key]
      return target &&
        target.isState &&
        !target.keyType
    },
    subscribe (subs, update, tree, stamp, attach, id) {
      return subscribe(this, subs, update, tree, stamp, attach, id)
    },
    sid () {
      if (!('_sid' in this)) {
        if (!this.key) {
          this._sid = 1
        } else {
          this._sid = hash(this.cParent().sid() + this.key)
          console.log(this._sid)
        }
      }
      return this._sid
    }
  },
  on: {
    data: {
      lstamp: function lstamp (val, stamp) {
        var parent = this.cParent()
        this._lstamp = stamp
        if (this._subscriptions) {
          let l = this
          vstamp.on(stamp, function () {
            l.emit('subscription', val, stamp)
          })
        } else {
          while (parent && parent._lstamp !== stamp) {
            lstampInner(parent, val, stamp)
            parent = parent.cParent()
          }
        }
      }
    }
  }
}

function lstampInner (parent, val, stamp) {
  parent._lstamp = stamp
  if (parent._subscriptions) {
    let l = parent
    vstamp.on(stamp, function () {
      l.emit('subscription', val, stamp)
    })
  } else if ('base' in parent.__on._data) {
    if (parent.__on._data.base) {
      parent.__on._data.base.each(function (p) {
        lstampInner(p, val, stamp)
      })
    }
  }
}
<commit_msg>better hashing of keys<commit_after>'use strict'
var vstamp = require('vigour-stamp')
var subscribe = require('./subscribe')

function keyToNumber (key) {
  var hash = 0
  if (key.length === 0) {
    return hash
  }
  for (let i = 0, len = key.length; i < len; i++) {
    hash = ((hash << 5) + hash) + key.charCodeAt(i)
    hash |= 0
  }
  console.log(hash)
  return hash
}

module.exports = {
  properties: {
    _lstamp: true,
    _sid: true,
    _subscriptions: true,
    cachedSyncPath: true
  },
  // make it easy to create different stamps when using a hub (source ids etc)
  _lstamp: 0,
  define: {
    isState: { value: true },
    keysCheck (val, key) {
      const target = val[key]
      return target &&
        target.isState &&
        !target.keyType
    },
    subscribe (subs, update, tree, stamp, attach, id) {
      return subscribe(this, subs, update, tree, stamp, attach, id)
    },
    sid () {
      if (!('_sid' in this)) {
        if (!this.key) {
          this._sid = 1
        } else {
          this._sid = this.cParent().sid() + keyToNumber(this.key)
          console.log(this._sid)
        }
      }
      return this._sid
    }
  },
  on: {
    data: {
      lstamp: function lstamp (val, stamp) {
        var parent = this.cParent()
        this._lstamp = stamp
        if (this._subscriptions) {
          let l = this
          vstamp.on(stamp, function () {
            l.emit('subscription', val, stamp)
          })
        } else {
          while (parent && parent._lstamp !== stamp) {
            lstampInner(parent, val, stamp)
            parent = parent.cParent()
          }
        }
      }
    }
  }
}

function lstampInner (parent, val, stamp) {
  parent._lstamp = stamp
  if (parent._subscriptions) {
    let l = parent
    vstamp.on(stamp, function () {
      l.emit('subscription', val, stamp)
    })
  } else if ('base' in parent.__on._data) {
    if (parent.__on._data.base) {
      parent.__on._data.base.each(function (p) {
        lstampInner(p, val, stamp)
      })
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

require
        .config({
          baseUrl: '',
          waitSeconds: 30,

          onNodeCreated: function(node, config, moduleName, url) {
            console.log('module ' + moduleName + ' is about to be loaded');

            node.addEventListener('load', function() {
              var line = document.createElement("div");
              line.className = "requireLoadingText";
              line.innerHTML = moduleName;
              document.body.appendChild(line);
              console.log('module ' + moduleName + ' has been loaded');
            });

            node.addEventListener('error', function() {
              console.log('module ' + moduleName + ' could not be loaded');
            });
          },

          paths: {
            // jquery
            'jquery': 'lib/jquery/dist/jquery.min',
            'jquery-ui': 'lib/jquery-ui/jquery-ui.min',
            'jquery-migrate': 'lib/jquery-migrate/jquery-migrate.min',

            // twitterBootstrap
            'twitterBootstrap': 'lib/bootstrap/dist/js/bootstrap.min',

            // angular
            'angular': 'lib/angular/angular.min',
            'ngRoute': 'lib/angular-route/angular-route.min',
            'ngAnimate': 'lib/angular-animate/angular-animate.min',
            'ngCookies': 'lib/angular-cookies/angular-cookies.min',
            'ngResource': 'lib/angular-resource/angular-resource.min',
            'ngSanitize': 'lib/angular-sanitize/angular-sanitize.min',
            'ngTouch': 'lib/angular-touch/angular-touch.min',

            'ui.router': 'lib/angular-ui-router/release/angular-ui-router',

            'pascalprecht.translate': 'lib/angular-translate/angular-translate.min',
            'pascalprecht.translateLoaderStaticFiles': 'lib/angular-translate-loader-static-files/angular-translate-loader-static-files.min',
            'pascalprecht.translateStorageLocal': 'lib/angular-translate-storage-local/angular-translate-storage-local.min',
            'pascalprecht.translateHandlerLog': 'lib/angular-translate-handler-log/angular-translate-handler-log.min',
            'pascalprecht.translateStorageCookie': 'lib/angular-translate-storage-cookie/angular-translate-storage-cookie.min',
            'tmh.dynamicLocale': 'lib/angular-dynamic-locale/dist/tmhDynamicLocale.min',

            'oc.lazyLoad': 'lib/oclazyload/dist/ocLazyLoad.require',
            'text': 'lib/requirejs-text/text',
            'css': 'lib/require-css/css.min',

            // module
            'fastclick': 'AdminLTE-2.3.3/plugins/fastclick/fastclick',
            'sparkline': 'AdminLTE-2.3.3/plugins/sparkline/jquery.sparkline.min',
            'jvectormap': 'AdminLTE-2.3.3/plugins/jvectormap/jquery-jvectormap-1.2.2.min',
            'jvectormapWorld': 'AdminLTE-2.3.3/plugins/jvectormap/jquery-jvectormap-world-mill-en',
            'slimScroll': 'AdminLTE-2.3.3/plugins/slimScroll/jquery.slimscroll.min',
            'chartjs': 'AdminLTE-2.3.3/plugins/chartjs/Chart.min',
            'adminLte': 'AdminLTE-2.3.3/dist/js/app',
            'demo': 'AdminLTE-2.3.3/dist/js/demo',
            'dataTables': 'AdminLTE-2.3.3/plugins/datatables/jquery.dataTables.min',
            'dataTables.bootstrap': 'AdminLTE-2.3.3/plugins/datatables/dataTables.bootstrap.min',
            'dataTables.responsive': 'AdminLTE-2.3.3/plugins/datatables/extensions/Responsive/js/dataTables.responsive.min',

            'projectWeb': 'partials/layout/routeConfig'
          },

          shim: {
            'jquery-migrate': ['jquery'],
            'jquery-ui': ['jquery-migrate'],
            'twitterBootstrap': ['jquery-ui'],

            'angular': ['twitterBootstrap'],
            'ngRoute': ['angular'],
            'ngAnimate': ['ngRoute'],
            'ngCookies': ['ngAnimate'],
            'ngResource': ['ngCookies'],
            'ngSanitize': ['ngResource'],
            'ngTouch': ['ngSanitize'],

            'ui.router': ['ngTouch'],
            'pascalprecht.translate': ['ui.router'],
            'pascalprecht.translateLoaderStaticFiles': ['pascalprecht.translate'],
            'pascalprecht.translateStorageLocal': ['pascalprecht.translateLoaderStaticFiles'],
            'pascalprecht.translateHandlerLog': ['pascalprecht.translateStorageLocal'],
            'pascalprecht.translateStorageCookie': ['pascalprecht.translateHandlerLog'],
            'tmh.dynamicLocale': ['pascalprecht.translateStorageCookie'],

            'oc.lazyLoad': ['tmh.dynamicLocale'],
            'text': ['oc.lazyLoad'],
            'css': ['text'],

            'fastclick': ['css'],
            'sparkline': ['fastclick'],
            'jvectormap': ['sparkline'],
            'jvectormapWorld': ['jvectormap'],
            'slimScroll': ['jvectormapWorld'],
            'chartjs': ['slimScroll'],

            'adminLte': ['chartjs'],
            'demo': ['adminLte'],
            'dataTables': ['demo'],
            'dataTables.bootstrap': ['dataTables'],
            'dataTables.responsive': ['dataTables.bootstrap'],
            'projectWeb': ['dataTables.responsive']
          }
        });

require(['projectWeb'], function(projectWeb) {
  $(document).ready(function() {
    angular.bootstrap(document, ['projectWeb']);
  });

  function loadCss(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
  }
  ;
}// $(document).ready
);// require
<commit_msg>SP-35: Loading Bar 기능 구현 <commit_after>'use strict';

require
        .config({
          baseUrl: '',
          waitSeconds: 30,

          onNodeCreated: function(node, config, moduleName, url) {

            node.addEventListener('load', function() {
              var line = document.createElement("div");
              line.className = "requireLoadingText";
              line.innerHTML = ">>" + moduleName
                      + " has been loaded ( 200 OK )";
              document.body.appendChild(line);
            });

            node.addEventListener('error', function() {
              var line = document.createElement("div");
              line.className = "requireLoadingText";
              line.innerHTML = ">>" + 'module ' + moduleName
                      + ' could not be loaded';
            });
          },

          paths: {
            // jquery
            'jquery': 'lib/jquery/dist/jquery.min',
            'jquery-ui': 'lib/jquery-ui/jquery-ui.min',
            'jquery-migrate': 'lib/jquery-migrate/jquery-migrate.min',

            // twitterBootstrap
            'twitterBootstrap': 'lib/bootstrap/dist/js/bootstrap.min',

            // angular
            'angular': 'lib/angular/angular.min',
            'ngRoute': 'lib/angular-route/angular-route.min',
            'ngAnimate': 'lib/angular-animate/angular-animate.min',
            'ngCookies': 'lib/angular-cookies/angular-cookies.min',
            'ngResource': 'lib/angular-resource/angular-resource.min',
            'ngSanitize': 'lib/angular-sanitize/angular-sanitize.min',
            'ngTouch': 'lib/angular-touch/angular-touch.min',

            'ui.router': 'lib/angular-ui-router/release/angular-ui-router',

            'pascalprecht.translate': 'lib/angular-translate/angular-translate.min',
            'pascalprecht.translateLoaderStaticFiles': 'lib/angular-translate-loader-static-files/angular-translate-loader-static-files.min',
            'pascalprecht.translateStorageLocal': 'lib/angular-translate-storage-local/angular-translate-storage-local.min',
            'pascalprecht.translateHandlerLog': 'lib/angular-translate-handler-log/angular-translate-handler-log.min',
            'pascalprecht.translateStorageCookie': 'lib/angular-translate-storage-cookie/angular-translate-storage-cookie.min',
            'tmh.dynamicLocale': 'lib/angular-dynamic-locale/dist/tmhDynamicLocale.min',

            'oc.lazyLoad': 'lib/oclazyload/dist/ocLazyLoad.require',
            'text': 'lib/requirejs-text/text',
            'css': 'lib/require-css/css.min',

            // module
            'fastclick': 'AdminLTE-2.3.3/plugins/fastclick/fastclick',
            'sparkline': 'AdminLTE-2.3.3/plugins/sparkline/jquery.sparkline.min',
            'jvectormap': 'AdminLTE-2.3.3/plugins/jvectormap/jquery-jvectormap-1.2.2.min',
            'jvectormapWorld': 'AdminLTE-2.3.3/plugins/jvectormap/jquery-jvectormap-world-mill-en',
            'slimScroll': 'AdminLTE-2.3.3/plugins/slimScroll/jquery.slimscroll.min',
            'chartjs': 'AdminLTE-2.3.3/plugins/chartjs/Chart.min',
            'adminLte': 'AdminLTE-2.3.3/dist/js/app',
            'demo': 'AdminLTE-2.3.3/dist/js/demo',
            'dataTables': 'AdminLTE-2.3.3/plugins/datatables/jquery.dataTables.min',
            'dataTables.bootstrap': 'AdminLTE-2.3.3/plugins/datatables/dataTables.bootstrap.min',
            'dataTables.responsive': 'AdminLTE-2.3.3/plugins/datatables/extensions/Responsive/js/dataTables.responsive.min',

            'projectWeb': 'partials/layout/routeConfig'
          },

          shim: {
            'jquery-migrate': ['jquery'],
            'jquery-ui': ['jquery-migrate'],
            'twitterBootstrap': ['jquery-ui'],

            'angular': ['twitterBootstrap'],
            'ngRoute': ['angular'],
            'ngAnimate': ['ngRoute'],
            'ngCookies': ['ngAnimate'],
            'ngResource': ['ngCookies'],
            'ngSanitize': ['ngResource'],
            'ngTouch': ['ngSanitize'],

            'ui.router': ['ngTouch'],
            'pascalprecht.translate': ['ui.router'],
            'pascalprecht.translateLoaderStaticFiles': ['pascalprecht.translate'],
            'pascalprecht.translateStorageLocal': ['pascalprecht.translateLoaderStaticFiles'],
            'pascalprecht.translateHandlerLog': ['pascalprecht.translateStorageLocal'],
            'pascalprecht.translateStorageCookie': ['pascalprecht.translateHandlerLog'],
            'tmh.dynamicLocale': ['pascalprecht.translateStorageCookie'],

            'oc.lazyLoad': ['tmh.dynamicLocale'],
            'text': ['oc.lazyLoad'],
            'css': ['text'],

            'fastclick': ['css'],
            'sparkline': ['fastclick'],
            'jvectormap': ['sparkline'],
            'jvectormapWorld': ['jvectormap'],
            'slimScroll': ['jvectormapWorld'],
            'chartjs': ['slimScroll'],

            'adminLte': ['chartjs'],
            'demo': ['adminLte'],
            'dataTables': ['demo'],
            'dataTables.bootstrap': ['dataTables'],
            'dataTables.responsive': ['dataTables.bootstrap'],
            'projectWeb': ['dataTables.responsive']
          }
        });

require(['projectWeb'], function(projectWeb) {
  $(document).ready(function() {
    angular.bootstrap(document, ['projectWeb']);
  });

  function loadCss(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
  }
  ;
}// $(document).ready
);// require
<|endoftext|>


<commit_before>/* jshint node: true */
/* global describe, it */

'use strict';

var should = require('should'),
    fs = require('fs'),
    path = require('path'),
    gutil = require('gulp-util'),
    extractCss = require('../index');

function getFile(filePath) {
    return new gutil.File({
        path: path.resolve(filePath),
        cwd: './test/',
        base: path.dirname(filePath),
        contents: new Buffer(String(fs.readFileSync(filePath)))
    });
}

function compare(fixturePath, expectedHTML, expectedCSS, options, done) {
    var file = getFile(fixturePath);

    options.url = 'file://' + file.path;

    extractCss(file.contents.toString('utf8'), options, function (err, html, css) {
        html.should.be.equal(String(fs.readFileSync(expectedHTML)));
        css.should.be.equal(String(fs.readFileSync(expectedCSS)));

        done();
    });
}

describe('extract-css', function() {
    it('Should separate css and html', function(done) {
        var options = {
            applyStyleTags: true,
            removeStyleTags: true,
            applyLinkTags: true,
            removeLinkTags: true,
            preserveMediaQueries: false
        };
        compare(path.join('test', 'fixtures', 'in.html'), path.join('test', 'expected', 'out.html'), path.join('test', 'expected', 'file.css'), options, done);
    });
});
<commit_msg>Disable eslint.<commit_after>/* eslint-disable */

'use strict';

var should = require('should'),
    fs = require('fs'),
    path = require('path'),
    gutil = require('gulp-util'),
    extractCss = require('../index');

function getFile(filePath) {
    return new gutil.File({
        path: path.resolve(filePath),
        cwd: './test/',
        base: path.dirname(filePath),
        contents: new Buffer(String(fs.readFileSync(filePath)))
    });
}

function compare(fixturePath, expectedHTML, expectedCSS, options, done) {
    var file = getFile(fixturePath);

    options.url = 'file://' + file.path;

    extractCss(file.contents.toString('utf8'), options, function (err, html, css) {
        html.should.be.equal(String(fs.readFileSync(expectedHTML)));
        css.should.be.equal(String(fs.readFileSync(expectedCSS)));

        done();
    });
}

describe('extract-css', function() {
    it('Should separate css and html', function(done) {
        var options = {
            applyStyleTags: true,
            removeStyleTags: true,
            applyLinkTags: true,
            removeLinkTags: true,
            preserveMediaQueries: false
        };
        compare(path.join('test', 'fixtures', 'in.html'), path.join('test', 'expected', 'out.html'), path.join('test', 'expected', 'file.css'), options, done);
    });
});
<|endoftext|>


<commit_before>/* jshint node:true */
/* global require, it, before, beforeEach, describe */

'use strict';
var should = require('should'),
    inquirer = require('inquirer'),
    gulp = require('gulp'),
    mockGulpDest = require('mock-gulp-dest')(gulp);

require('../slushfile');

/**
 * Mock inquirer prompt
 */

function mockPrompt(answers) {
    inquirer.prompt = function (prompts, done) {

        [].concat(prompts).forEach(function (prompt) {
            if (!(prompt.name in answers)) {
                answers[prompt.name] = prompt.default;
            }
        });

        done(answers);
    };
}

describe('slush-webapp', function() {
    before(function () {
        process.chdir(__dirname);
        process.argv.push('--skip-install');
    });

    describe('default generator', function () {
        beforeEach(function () {
            mockPrompt({
                features: [],
                moveon: true
            });
        });

        it('should put all project files in current working directory', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.cwd().should.equal(__dirname);
                mockGulpDest.basePath().should.equal(__dirname);
                done();
            });
        });

        it('should create expected files', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestContains([
                    '.bowerrc',
                    '.editorconfig',
                    '.gitattributes',
                    '.gitignore',
                    '.jshintrc',
                    'package.json',
                    'bower.json',
                    'gulpfile.js',
                    'app/404.html',
                    'app/favicon.ico',
                    'app/robots.txt',
                    'app/index.html',
                    'app/scripts/main.js'
                ]);

                done();
            });
        });
    });

    describe('default generator: sass feature', function () {
        it('should create css file', function (done) {
            mockPrompt({
                features: [],
                moveon: true
            });
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestContains('app/styles/main.css');
                mockGulpDest.assertDestNotContains('app/styles/main.scss');
                done();
            });
        });

        it('should create scss file', function (done) {
            mockPrompt({
                features: ['includeSass'],
                moveon: true
            });
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestNotContains('app/styles/main.css');
                mockGulpDest.assertDestContains('app/styles/main.scss');
                done();
            });
        });
    });
});
<commit_msg>Add tests for generators.<commit_after>/* jshint node:true */
/* global require, it, before, beforeEach, describe */

'use strict';
var should = require('should'),
    inquirer = require('inquirer'),
    gulp = require('gulp'),
    mockGulpDest = require('mock-gulp-dest')(gulp);

require('../slushfile');

/**
 * Mock inquirer prompt
 */

function mockPrompt(answers) {
    inquirer.prompt = function (prompts, done) {

        [].concat(prompts).forEach(function (prompt) {
            if (!(prompt.name in answers)) {
                answers[prompt.name] = prompt.default;
            }
        });

        done(answers);
    };
}

describe('slush-webapp', function() {
    before(function () {
        process.chdir(__dirname);
        process.argv.push('--skip-install');
    });

    describe('default generator', function () {
        beforeEach(function () {
            mockPrompt({
                features: [],
                moveon: true
            });
        });

        it('should put all project files in current working directory', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.cwd().should.equal(__dirname);
                mockGulpDest.basePath().should.equal(__dirname);
                done();
            });
        });

        it('should create expected files', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestContains([
                    '.bowerrc',
                    '.editorconfig',
                    '.gitattributes',
                    '.gitignore',
                    '.jshintrc',
                    'package.json',
                    'bower.json',
                    'gulpfile.js',
                    'app/404.html',
                    'app/favicon.ico',
                    'app/robots.txt',
                    'app/index.html',
                    'app/scripts/main.js'
                ]);

                done();
            });
        });
    });

    describe('default generator: sass feature', function () {
        it('should create css file', function (done) {
            mockPrompt({
                features: [],
                moveon: true
            });
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestContains('app/styles/main.css');
                mockGulpDest.assertDestNotContains('app/styles/main.scss');
                done();
            });
        });

        it('should create scss file', function (done) {
            mockPrompt({
                features: ['includeSass'],
                moveon: true
            });
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestNotContains('app/styles/main.css');
                mockGulpDest.assertDestContains('app/styles/main.scss');
                done();
            });
        });
    });

    describe('model generator', function () {
        it('should create backbone model', function (done) {
            mockPrompt({
                features: [],
                moveon: true
            });
            gulp.start('model').once('stop', function () {
                mockGulpDest.assertDestContains('models/application.js');
                done();
            });
        });
    });

    describe('view generator', function () {
        it('should create backbone view', function (done) {
            mockPrompt({
                features: [],
                moveon: true
            });
            gulp.start('view').once('stop', function () {
                mockGulpDest.assertDestContains('views/application.js');
                done();
            });
        });
    });

    describe('collection generator', function () {
        it('should create backbone collection', function (done) {
            mockPrompt({
                features: [],
                moveon: true
            });
            gulp.start('collection').once('stop', function () {
                mockGulpDest.assertDestContains('collections/application.js');
                done();
            });
        });
    });

    describe('router generator', function () {
        it('should create backbone router', function (done) {
            mockPrompt({
                features: [],
                moveon: true
            });
            gulp.start('router').once('stop', function () {
                mockGulpDest.assertDestContains('routes/application.js');
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

import * as phantom from 'phantom';
import test from 'ava';

const page = new Promise(resolve => {
  phantom.create()
    .then(p => p.createPage())
    .then(p => {
      resolve(p.evaluate(function() {
        return this;
      }));
    });
});
<commit_msg>:white_check_mark: Check if function is available<commit_after>'use strict';

import path from 'path';
import phantom from 'phantom';
import test from 'ava';

const script = path.normalize(__dirname + '/../dist/prlx.js');

function evaluate(cb) {
 return new Promise(resolve => {
    phantom.create()
      .then(ph => ph.createPage())
      .then(page => page.injectJs(script)
        .then(() => page)
        .then(page => resolve(page.evaluate(cb)))
      );
  });
}

test('Function should be available', t => {
  return evaluate(function() {
    return typeof window.prlx;
  }).then(r => {
    t.is(r, 'function');
  });
});
<|endoftext|>


<commit_before>/**
 * New node file
 */

var assert = require('chai').assert;
describe('Array', function() {
  describe('#indexOf()', function () {
    it('should return -1 when the value is not present', function () {
      //assert.equal(-1, [1,2,3].indexOf(5));
      //assert.equal(-1, [1,2,3].indexOf(0));
    	assert.equal(200, 200);
    });
  });
});
<commit_msg>update test case1<commit_after>/**
 * New node file
 */

var assert = require('chai').assert;
describe('Array', function() {
  describe('#indexOf()', function () {
    it('should return -1 when the value is not present', function () {
      //assert.equal(-1, [1,2,3].indexOf(5));
      //assert.equal(-1, [1,2,3].indexOf(0));
    	assert.equal(200, 400);
    });
  });
});
<|endoftext|>


<commit_before>(function(s){
"use strict";

s.initPrint = function() {
    s.addGlobalPrimProc("write", write, 1);
    s.addGlobalPrimProc("display", display, 1);
    s.addGlobalPrimProc("newline", newline, 0);
}

function write(argv) {
    s.outputToConsole(s.writeToString(argv[0], false), false, true);
    return s.voidValue;
}

function display(argv) {
    s.outputToConsole(s.displayToString(argv[0], false), false, true);
    return s.voidValue;
}

function newline(argv) {
    s.outputToConsole("\n");
    return s.voidValue;
}

s.displayToString = function(obj) {
    return s.writeToString(obj, true);
}

var syntaxColorSchemes = {
    "string": "#298026",
    "symbol": "#0000AF",
    "constant": "#298026",
    "comment": "rgb(194,158,31)",
    "parenthesis": "rgb(181,60,36)"
};
function wrapSyntaxColorHTML(type, str) {
    return "" + str + "";
}

s.writeToString = function(obj, display, writeHtml) {
    var str = null;
    if(obj.isUnspecified())
        str = null;
    else if(obj.isNumber()) {
        str = obj.val;
        if(writeHtml)
            str = wrapSyntaxColorHTML("constant", str);
    }
    else if(obj.isChar()) {
        str = "#\\" + s.charVal(obj);
        if(writeHtml)
            str = wrapSyntaxColorHTML("constant", str);
    }
    else if(obj.isString()) {
        str = s.stringVal(obj);
        if(!display)
            str = "\"" + str + "\"";
        if(writeHtml)
            str = wrapSyntaxColorHTML("string", str);
    }
    else if(obj.isSymbol()) {
        str = s.symbolVal(obj);
        if(writeHtml)
            str = wrapSyntaxColorHTML("symbol", str);
    }
    else if(obj.isBoolean()) {
        str = obj.val ? "#t" : "#f";
        if(writeHtml)
            str = wrapSyntaxColorHTML("constant", str);
    }
    else if(obj.isEmptyList()) {
        str = "()";
        if(writeHtml)
            str = wrapSyntaxColorHTML("parenthesis", str);
    }
    else if(s.isList(obj)) {
        if(s.car(obj) == s.quoteSymbol) {
            str = s.writeQuote(obj, writeHtml);
        }
        else
            str = s.writeList(obj, writeHtml);
    }
    else if(obj.isPair()) {
        str = s.writePair(obj, writeHtml);
    }
    else if(obj.isProcedure()) {
        str = '#<procedure:' + obj.val.getName() + '>';
    }
    else if(obj.isNamespace())
        str = '#<namespace:0>';
    else if(obj.isMyObject())
        str = "#object";
    else
        str = obj.val.toString();
    return str;
}

s.writeQuote = function(list, writeHtml) {
    if(s.car(list) == s.quoteSymbol)
        return "'" + s.writeQuote(s.cdr(list), writeHtml);
    else
        return s.writeToString(s.car(list), false, writeHtml);
}

s.writeList = function(list, writeHtml) {
    var strs = [];
    var obj = list;
    for(; obj.isPair(); obj = s.cdr(obj)) {
        strs.push(s.writeToString(s.car(obj), false, writeHtml));
    }
    if(writeHtml)
        return wrapSyntaxColorHTML("parenthesis", "(")
            + strs.join(' ') + wrapSyntaxColorHTML("parenthesis", ")");
    else
        return '(' + strs.join(' ') + ')';
}

s.writePair = function(pair, writeHtml) {
    var str = '(';
    if(writeHtml)
        str = wrapSyntaxColorHTML("parenthesis", "(");
    for(var i = 0; i < pair.val.length; i++) {
        var obj = pair.val[i];
        str += obj.isPair() ? s.writePair(obj, writeHtml) : s.writeToString(obj, false, writeHtml);
        if(i < pair.val.length - 1)
            str += ' . ';
    }
    if(writeHtml)
        str += wrapSyntaxColorHTML("parenthesis", ")");
    else
        str += ')';
    return str;
}

s.outputValue = function(obj) {
    if(obj.isUnspecified())
        return;
    var val = s.writeToString(obj);
    if(val != null) {
        s.outputToConsole(val);
        s.outputToConsole("\n");
    }
}

s.outputToConsole = function(str, error, write) {
    if(!s.console)
        return;
    var response = document.createElement('span');
    response.innerHTML = str;
    response.className = "scheme_response";
    if(write)
        response.className += " scheme_write_object";
    if(error)
        response.className += " scheme_error_info";
    s.console.appendChild(response);
}

})(scheme);
<commit_msg>update printer<commit_after>(function(s){
"use strict";

s.initPrint = function() {
    s.addGlobalPrimProc("write", write, 1);
    s.addGlobalPrimProc("display", display, 1);
    s.addGlobalPrimProc("newline", newline, 0);
}

function write(argv) {
    s.outputToConsole(s.writeToString(argv[0], false), false, true);
    return s.voidValue;
}

function display(argv) {
    s.outputToConsole(s.displayToString(argv[0], false), false, true);
    return s.voidValue;
}

function newline(argv) {
    s.outputToConsole("\n");
    return s.voidValue;
}

s.displayToString = function(obj) {
    return s.writeToString(obj, true);
}

var syntaxColorSchemes = {
    "string": "#298026",
    "symbol": "#0000AF",
    "constant": "#298026",
    "comment": "rgb(194,158,31)",
    "parenthesis": "rgb(181,60,36)"
};
function wrapSyntaxColorHTML(type, str) {
    return "" + str + "";
}

s.writeToString = function(obj, display, writeHtml) {
    var str = null;
    if(obj.isUnspecified())
        str = null;
    else if(obj.isNumber()) {
        str = obj.val;
        if(writeHtml)
            str = wrapSyntaxColorHTML("constant", str);
    }
    else if(obj.isChar()) {
        str = "#\\" + s.charVal(obj);
        if(writeHtml)
            str = wrapSyntaxColorHTML("constant", str);
    }
    else if(obj.isString()) {
        str = s.stringVal(obj);
        if(!display)
            str = "\"" + str + "\"";
        if(writeHtml)
            str = wrapSyntaxColorHTML("string", str);
    }
    else if(obj.isSymbol()) {
        str = s.symbolVal(obj);
        if(writeHtml)
            str = wrapSyntaxColorHTML("symbol", str);
    }
    else if(obj.isBoolean()) {
        str = obj.val ? "#t" : "#f";
        if(writeHtml)
            str = wrapSyntaxColorHTML("constant", str);
    }
    else if(obj.isEmptyList()) {
        str = "()";
        if(writeHtml)
            str = wrapSyntaxColorHTML("parenthesis", str);
    }
    else if(s.isList(obj)) {
        if(s.car(obj) == s.quoteSymbol) {
            str = s.writeQuote(obj, writeHtml);
        }
        else
            str = s.writeList(obj, writeHtml);
    }
    else if(obj.isPair()) {
        str = s.writePair(obj, writeHtml);
    }
    else if(obj.isProcedure()) {
        str = '#<procedure:' + obj.val.getName() + '>';
    }
    else if(obj.isNamespace())
        str = '#<namespace:0>';
    else if(obj.isMyObject())
        str = "#object";
    else
        str = obj.val.toString();
    return str;
}

s.writeQuote = function(list, writeHtml) {
    if(s.car(list) == s.quoteSymbol)
        return "'" + s.writeQuote(s.cdr(list), writeHtml);
    else
        return s.writeToString(s.car(list), false, writeHtml);
}

s.writeList = function(list, writeHtml) {
    var strs = [];
    var obj = list;
    for(; obj.isPair(); obj = s.cdr(obj)) {
        strs.push(s.writeToString(s.car(obj), false, writeHtml));
    }
    if(writeHtml)
        return wrapSyntaxColorHTML("parenthesis", "(")
            + strs.join(' ') + wrapSyntaxColorHTML("parenthesis", ")");
    else
        return '(' + strs.join(' ') + ')';
}

s.writePair = function(pair, writeHtml) {
    var str = '(';
    if(writeHtml)
        str = wrapSyntaxColorHTML("parenthesis", "(");
    for(var i = 0; i < pair.val.length; i++) {
        var obj = pair.val[i];
        str += obj.isPair() ? s.writePair(obj, writeHtml) : s.writeToString(obj, false, writeHtml);
        if(i < pair.val.length - 1)
            str += ' . ';
    }
    if(writeHtml)
        str += wrapSyntaxColorHTML("parenthesis", ")");
    else
        str += ')';
    return str;
}

s.outputValue = function(obj) {
    if(obj.isUnspecified())
        return;
    var val = s.writeToString(obj);
    if(val != null) {
        s.outputToConsole(val);
        s.outputToConsole("\n");
    }
}

s.outputToConsole = function(str, error, write) {
    if(!s.console)
        return;
    var response = document.createElement('span');
    response.className = "scheme_response";
    if(write)
        response.className += " scheme_write_object";
    if(error) {
        response.className += " scheme_error_info";
        response.innerText = str;
    } else {
        response.innerHTML = str;
    }
    s.console.appendChild(response);
}

})(scheme);
<|endoftext|>


<commit_before>const state = { graph: { entity: {} } }
function addEntity(id, type = 'foo') {
  state.graph.entity[id] = { id, type }
}
addEntity('a')
addEntity('b')
addEntity('c')
addEntity('d')
addEntity('a1', 'bar')
addEntity('b1', 'bar')
addEntity('c1', 'bar')
addEntity('d1', 'bar')

export const agent = {
  id: "user0",
  type: "Person","name":"Anonymous","dateCreated":"2016-08-30T17:25:25.915Z",
}
export const item = {
  approxWidth: '57"',
  category: 'textile',
  colors: [],
  contents: '100% Solution Dyed Acrylic',
  discontinued: false,
  id: '28',
  labelMessage: '5512',
  lengthUnit: 'Yards',
  name: 'Dhow',
  originCountry: 'Italy',
  patternNumber: '10001',
  price: '$90',
  colorNumber: '28',
  type: 'Item',
  isPattern: false,
}
export const trouble = {
  subject: {
    "additionalType":"Project","itemListOrder":"Ascending","title":"Favorites","type":"CollectionList","dateCreated":"2016-08-30T17:41:43.224Z","id":"i5dtxvjo"},
  predicate: "itemListElement",
  "object": {
    actionStatus:"created",
    agent,
    item,
    "position":100,"startTime":"2016-08-30T17:41:43.233Z","type":"ListItem"}}

export default state
<commit_msg>add more examples to mock<commit_after>const state = { graph: { entity: {} } }
function addEntity(id, type = 'foo') {
  state.graph.entity[id] = { id, type }
}
addEntity('a')
addEntity('b')
addEntity('c')
addEntity('d')
addEntity('a1', 'bar')
addEntity('b1', 'bar')
addEntity('c1', 'bar')
addEntity('d1', 'bar')

export const agent = {
  id: "user0",
  type: "Person",
  "name":"Anonymous",
  "dateCreated":"2016-08-30T17:25:25.915Z",
}
export const item = {
  approxWidth: '57"',
  category: 'textile',
  colors: [],
  contents: '100% Solution Dyed Acrylic',
  discontinued: false,
  id: '28',
  labelMessage: '5512',
  lengthUnit: 'Yards',
  name: 'Dhow',
  originCountry: 'Italy',
  patternNumber: '10001',
  price: '$90',
  colorNumber: '28',
  type: 'Item',
  isPattern: false,
}
export const trouble = {
  subject: {
    "additionalType":"Project","itemListOrder":"Ascending","title":"Favorites","type":"CollectionList","dateCreated":"2016-08-30T17:41:43.224Z","id":"i5dtxvjo"},
  predicate: "itemListElement",
  "object": {
    actionStatus:"created",
    agent,
    item,
    "position":100,
    "startTime":"2016-08-30T17:41:43.233Z",
    "type":"ListItem",
  }
}
export const mainEntity = { id: 'pBlf', type: 'DataFeed' }
export const creator = {
  id: 'user0',
  type: 'Person',
  name: 'Anonymous Person or User of the website',
}
export const title = 'Favorites'
export const collection = {
  creator, // User that created the thing.
  itemListOrder: 'Ascending',
  mainEntity, // List of what.
  title,
  type: 'CollectionList',
}

export default state
<|endoftext|>