<commit_before>var OSNPAddressTable = require('./osnp_address_table');
var OSNPCommandQueue = require('./osnp_command_queue');

var FrameType = {
  BEACON: 0x00,
  DATA: 0x01,
  ACK: 0x02,
  MAC_CMD: 0x03
};

var AddressingMode = {
  NOT_PRESENT: 0x00,
  SHORT_ADDRESS: 0x02,
  EUI: 0x03
};

var MACCommand = {
  ASSOCIATION_REQUEST: 0x01,
  ASSOCIATION_RESPONSE: 0x02,
  DISASSOCIATED: 0x03,
  DATA_REQUEST: 0x04,
  DISCOVER: 0x07,
  KEY_UPDATE_REQUEST: 0x80,
  KEY_UPDATE_RESPONSE: 0x81,
  FRAME_COUNTER_ALIGN: 0x82
}

var SecurityLevel = {
  NONE: 0x00,
  AES_CTR: 0x01,
  AES_CCM_128: 0x02,
  AES_CCM_64: 0x03,
  AES_CCM_32: 0x04,
  AES_CBC_MAC_128: 0x05,
  AES_CBC_MAC_64: 0x06,
  AES_CBC_MAC_32: 0x07
}

var RXMode = {
  POLL_DRIVEN: 0x00,
  ALWAYS_ON: 0x01
};

exports.OSNPAddressTable = OSNPAddressTable;
exports.OSNPCommandQueue = OSNPCommandQueue;

exports.FrameType = FrameType;
exports.AddressingMode = AddressingMode;
exports.MACCommand = MACCommand;
exports.SecurityLevel = SecurityLevel;
exports.RXMode = RXMode;

function OSNPFrame() {
  this.frameControlLow = null;
  this.frameControlHigh = null;
  this.destinationPAN = null;
  this.destinationAddress = null;
  this.sourcePAN = null;
  this.sourceAddress = null;
  this.frameCounter = null;
  this.keyCounter = null;
  this.payload = null;
}

OSNPFrame.prototype.getFrameType = function() {
  return this.frameControlLow & 0x07;
}

OSNPFrame.prototype.getDestinationAddressingMode = function() {
  return (this.frameControlHigh >>> 2) & 0x03;
}

OSNPFrame.prototype.getSourceAddressingMode = function() {
  return (this.frameControlHigh >>> 6) & 0x03;
}

OSNPFrame.prototype.hasPANIDCompression = function() {
  return (this.frameControlLow & 0x40) == 0x40;
}

OSNPFrame.prototype.hasSecurityEnabled = function() {
  return (this.frameControlLow & 0x08) == 0x08;
}

OSNPFrame.prototype.hasFramePending = function() {
  return (this.frameControlLow & 0x10) == 0x10;
}

OSNPFrame.prototype.hasAckRequested = function() {
  return (this.frameControlLow & 0x20) == 0x20;
}

OSNPFrame.prototype.getKeyIdentifierMode = function() {
  return (this.securityControl >>> 3) & 0x03;
}

OSNPFrame.prototype.getEncodedLength = function() {
  var len = 3;
  if (this.destinationPAN != null) {
    len += this.destinationAddress.length + 2;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    len += 2;
  }

  if (this.sourceAddress != null) {
    len += this.sourceAddress.length;
  }

  if (this.hasSecurityEnabled()) {
    len += 5;
  }

  len += this.payload.length;

  return len;
}

OSNPFrame.prototype.encode = function(buf) {
  if (buf == undefined) {
    buf = new Buffer(this.getEncodedLength());
  }
  var index = 0;
  buf.writeUInt8(this.frameControlLow, index++);
  buf.writeUInt8(this.frameControlHigh, index++);
  buf.writeUInt8(this.sequenceNumber, index++);

  if (this.destinationPAN != null) {
    this.destinationPAN.copy(buf, index);
    index += 2;
    this.destinationAddress.copy(buf, index);
    index += this.destinationAddress.length;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    this.sourcePAN.copy(buf, index);
    index += 2;
  }

  if (this.sourceAddress != null) {
    this.sourceAddress.copy(buf, index);
    index += this.sourceAddress.length;
  }

  if (this.hasSecurityEnabled()) {
    buf.writeUInt32LE(this.frameCounter, index);
    index += 4;
    buf.writeUInt8(this.keyCounter, index++);
  }

  this.payload.copy(buf, index);

  return buf;
}

var panID;
var shortAddress;
var eui;

var sequenceNumber = 0;

exports.setPANID = function(aPANID) {
  panID = aPANID;
}

exports.getPANID = function() {
  return panID;
}

exports.setShortAddress = function(aShortAddress) {
  shortAddress = aShortAddress;
}

exports.getShortAddress = function() {
  return shortAddress;
}

exports.setEUI = function(aEUI) {
  eui = aEUI;
}

exports.getEUI = function() {
  return eui;
}

exports.createPairingCommand = function(eui, shortAddress, txKey, rxKey) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, true, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, AddressingMode.EUI);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = eui;

  frame.payload = new Buffer(35);
  frame.payload[0] = MACCommand.ASSOCIATION_REQUEST;
  txKey.copy(frame.payload, 1);
  rxKey.copy(frame.payload, 17);
  shortAddress.copy(frame.payload, 33);
  return frame;
}

exports.createUnpairingCommand = function(shortAddress) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, true, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, AddressingMode.EUI);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = exports.getPANID();
  frame.destinationAddress = shortAddress;
  frame.payload = new Buffer([MACCommand.DISASSOCIATED]);

  return frame;
}

exports.createDiscoveryRequest = function() {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, false, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, AddressingMode.SHORT_ADDRESS);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = new Buffer([0xff, 0xff]);
  frame.payload = new Buffer([MACCommand.DISCOVER]);

  return frame;
}

exports.createCommandPacket = function(data, eui, shortAddress, paired) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.DATA, paired, false, true, paired);
  var frameControlHigh;

  if (paired) {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, AddressingMode.EUI);
  } else {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, AddressingMode.SHORT_ADDRESS);
  }

  var frame = exports.createFrame(frameControlLow, frameControlHigh);

  if (paired) {
    frame.destinationPAN = exports.getPANID();
    frame.destinationAddress = shortAddress;
  } else {
    frame.destinationPAN = new Buffer([0x00, 0x00]);
    frame.destinationAddress = eui;
  }

  frame.payload = data;

  return frame;
}

exports.parseFrame = function(frame) {
  var osnpFrame = new OSNPFrame();
  var index = 0;
  osnpFrame.frameControlLow = frame.readUInt8(index++);
  osnpFrame.frameControlHigh = frame.readUInt8(index++);
  osnpFrame.sequenceNumber = frame.readUInt8(index++);

  switch (osnpFrame.getDestinationAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }

  if (osnpFrame.getSourceAddressingMode() != AddressingMode.NOT_PRESENT) {
    if(osnpFrame.hasPANIDCompression()) {
      osnpFrame.sourcePAN = osnpFrame.destinationPAN;
    } else {
      osnpFrame.sourcePAN = frame.slice(index, index + 2);
      index += 2;
    }
  }

  switch (osnpFrame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.sourceAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.sourceAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }

  if (osnpFrame.hasSecurityEnabled()) {
    osnpFrame.frameCounter = frame.readUInt32LE(index);
    index += 4;
    osnpFrame.keyCounter = frame.readUInt8(index++);
  }

  osnpFrame.payload = frame.slice(index, frame.length - 2);

  return osnpFrame;
}

exports.createFrame = function(frameControlLow, frameControlHigh) {
  var frame = new OSNPFrame();

  frame.frameControlLow = frameControlLow;
  frame.frameControlHigh = frameControlHigh;

  frame.sequenceNumber = sequenceNumber++;

  if (sequenceNumber >= 255) {
    sequenceNumber = 0;
  }

  if (frame.hasPANIDCompression() && (frame.getDestinationAddressingMode() != AddressingMode.NOT_PRESENT)) {
    frame.destinationPAN = panID;
  }

  switch (frame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    frame.sourcePAN = panID;
    frame.sourceAddress = shortAddress;
    break;
  case AddressingMode.EUI:
    frame.sourcePAN = panID;
    frame.sourceAddress = eui;
    break;
  }

  if (frame.hasSecurityEnabled()) {
    frame.frameCounter = 0;
    frame.keyCounter = 0x10;
  }

  frame.payload = new Buffer(0);

  return frame;
}

exports.makeFrameControlLow = function(frameType, securityEnabled, framePending, ackRequest, panIDCompression) {
  return frameType | (securityEnabled ? 0x08 : 0x00) | (framePending ? 0x10 : 0x00) | (ackRequest ? 0x20 : 0x00) | (panIDCompression ? 0x40 : 0x00);
}

exports.makeFrameControlHigh = function(destinationAddressingMode, sourceAddressingMode) {
  return (destinationAddressingMode << 2) | (sourceAddressingMode << 6);
}
<commit_msg>added automatic MIC removal<commit_after>var OSNPAddressTable = require('./osnp_address_table');
var OSNPCommandQueue = require('./osnp_command_queue');

var FrameType = {
  BEACON: 0x00,
  DATA: 0x01,
  ACK: 0x02,
  MAC_CMD: 0x03
};

var AddressingMode = {
  NOT_PRESENT: 0x00,
  SHORT_ADDRESS: 0x02,
  EUI: 0x03
};

var MACCommand = {
  ASSOCIATION_REQUEST: 0x01,
  ASSOCIATION_RESPONSE: 0x02,
  DISASSOCIATED: 0x03,
  DATA_REQUEST: 0x04,
  DISCOVER: 0x07,
  KEY_UPDATE_REQUEST: 0x80,
  KEY_UPDATE_RESPONSE: 0x81,
  FRAME_COUNTER_ALIGN: 0x82
}

var SecurityLevel = {
  NONE: 0x00,
  AES_CTR: 0x01,
  AES_CCM_128: 0x02,
  AES_CCM_64: 0x03,
  AES_CCM_32: 0x04,
  AES_CBC_MAC_128: 0x05,
  AES_CBC_MAC_64: 0x06,
  AES_CBC_MAC_32: 0x07
}

var RXMode = {
  POLL_DRIVEN: 0x00,
  ALWAYS_ON: 0x01
};

exports.OSNPAddressTable = OSNPAddressTable;
exports.OSNPCommandQueue = OSNPCommandQueue;

exports.FrameType = FrameType;
exports.AddressingMode = AddressingMode;
exports.MACCommand = MACCommand;
exports.SecurityLevel = SecurityLevel;
exports.RXMode = RXMode;

function OSNPFrame() {
  this.frameControlLow = null;
  this.frameControlHigh = null;
  this.destinationPAN = null;
  this.destinationAddress = null;
  this.sourcePAN = null;
  this.sourceAddress = null;
  this.frameCounter = null;
  this.keyCounter = null;
  this.payload = null;
}

OSNPFrame.prototype.getFrameType = function() {
  return this.frameControlLow & 0x07;
}

OSNPFrame.prototype.getDestinationAddressingMode = function() {
  return (this.frameControlHigh >>> 2) & 0x03;
}

OSNPFrame.prototype.getSourceAddressingMode = function() {
  return (this.frameControlHigh >>> 6) & 0x03;
}

OSNPFrame.prototype.hasPANIDCompression = function() {
  return (this.frameControlLow & 0x40) == 0x40;
}

OSNPFrame.prototype.hasSecurityEnabled = function() {
  return (this.frameControlLow & 0x08) == 0x08;
}

OSNPFrame.prototype.hasFramePending = function() {
  return (this.frameControlLow & 0x10) == 0x10;
}

OSNPFrame.prototype.hasAckRequested = function() {
  return (this.frameControlLow & 0x20) == 0x20;
}

OSNPFrame.prototype.getKeyIdentifierMode = function() {
  return (this.securityControl >>> 3) & 0x03;
}

OSNPFrame.prototype.getEncodedLength = function() {
  var len = 3;
  if (this.destinationPAN != null) {
    len += this.destinationAddress.length + 2;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    len += 2;
  }

  if (this.sourceAddress != null) {
    len += this.sourceAddress.length;
  }

  if (this.hasSecurityEnabled()) {
    len += 5;
  }

  len += this.payload.length;

  return len;
}

OSNPFrame.prototype.encode = function(buf) {
  if (buf == undefined) {
    buf = new Buffer(this.getEncodedLength());
  }
  var index = 0;
  buf.writeUInt8(this.frameControlLow, index++);
  buf.writeUInt8(this.frameControlHigh, index++);
  buf.writeUInt8(this.sequenceNumber, index++);

  if (this.destinationPAN != null) {
    this.destinationPAN.copy(buf, index);
    index += 2;
    this.destinationAddress.copy(buf, index);
    index += this.destinationAddress.length;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    this.sourcePAN.copy(buf, index);
    index += 2;
  }

  if (this.sourceAddress != null) {
    this.sourceAddress.copy(buf, index);
    index += this.sourceAddress.length;
  }

  if (this.hasSecurityEnabled()) {
    buf.writeUInt32LE(this.frameCounter, index);
    index += 4;
    buf.writeUInt8(this.keyCounter, index++);
  }

  this.payload.copy(buf, index);

  return buf;
}

var panID;
var shortAddress;
var eui;

var sequenceNumber = 0;

exports.setPANID = function(aPANID) {
  panID = aPANID;
}

exports.getPANID = function() {
  return panID;
}

exports.setShortAddress = function(aShortAddress) {
  shortAddress = aShortAddress;
}

exports.getShortAddress = function() {
  return shortAddress;
}

exports.setEUI = function(aEUI) {
  eui = aEUI;
}

exports.getEUI = function() {
  return eui;
}

exports.createPairingCommand = function(eui, shortAddress, txKey, rxKey) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, true, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, AddressingMode.EUI);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = eui;

  frame.payload = new Buffer(35);
  frame.payload[0] = MACCommand.ASSOCIATION_REQUEST;
  txKey.copy(frame.payload, 1);
  rxKey.copy(frame.payload, 17);
  shortAddress.copy(frame.payload, 33);
  return frame;
}

exports.createUnpairingCommand = function(shortAddress) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, true, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, AddressingMode.EUI);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = exports.getPANID();
  frame.destinationAddress = shortAddress;
  frame.payload = new Buffer([MACCommand.DISASSOCIATED]);

  return frame;
}

exports.createDiscoveryRequest = function() {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, false, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, AddressingMode.SHORT_ADDRESS);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = new Buffer([0xff, 0xff]);
  frame.payload = new Buffer([MACCommand.DISCOVER]);

  return frame;
}

exports.createCommandPacket = function(data, eui, shortAddress, paired) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.DATA, paired, false, true, paired);
  var frameControlHigh;

  if (paired) {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, AddressingMode.EUI);
  } else {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, AddressingMode.SHORT_ADDRESS);
  }

  var frame = exports.createFrame(frameControlLow, frameControlHigh);

  if (paired) {
    frame.destinationPAN = exports.getPANID();
    frame.destinationAddress = shortAddress;
  } else {
    frame.destinationPAN = new Buffer([0x00, 0x00]);
    frame.destinationAddress = eui;
  }

  frame.payload = data;

  return frame;
}

exports.parseFrame = function(frame, securityLevel) {
  var osnpFrame = new OSNPFrame();
  var index = 0;
  osnpFrame.frameControlLow = frame.readUInt8(index++);
  osnpFrame.frameControlHigh = frame.readUInt8(index++);
  osnpFrame.sequenceNumber = frame.readUInt8(index++);

  switch (osnpFrame.getDestinationAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }

  if (osnpFrame.getSourceAddressingMode() != AddressingMode.NOT_PRESENT) {
    if(osnpFrame.hasPANIDCompression()) {
      osnpFrame.sourcePAN = osnpFrame.destinationPAN;
    } else {
      osnpFrame.sourcePAN = frame.slice(index, index + 2);
      index += 2;
    }
  }

  switch (osnpFrame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.sourceAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.sourceAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }

  if (osnpFrame.hasSecurityEnabled()) {
    osnpFrame.frameCounter = frame.readUInt32LE(index);
    index += 4;
    osnpFrame.keyCounter = frame.readUInt8(index++);
  }

  var micLen;

  if (osnpFrame.hasSecurityEnabled() && securityLevel) {
    switch(securityLevel) {
    case SecurityLevel.NONE:
    case SecurityLevel.AES_CTR:
      micLen = 0;
      break;
    case SecurityLevel.AES_CCM_128:
    case SecurityLevel.AES_CBC_MAC_128:
      micLen = 16;
      break;
    case SecurityLevel.AES_CCM_64:
    case SecurityLevel.AES_CBC_MAC_64:
      micLen = 8;
      break;
    case SecurityLevel.AES_CCM_32:
    case SecurityLevel.AES_CBC_MAC_32:
      micLen = 4;
      break;
    }
  } else {
    micLen = 0;
  }

  osnpFrame.payload = frame.slice(index, frame.length - micLen - 2);

  return osnpFrame;
}

exports.createFrame = function(frameControlLow, frameControlHigh) {
  var frame = new OSNPFrame();

  frame.frameControlLow = frameControlLow;
  frame.frameControlHigh = frameControlHigh;

  frame.sequenceNumber = sequenceNumber++;

  if (sequenceNumber >= 255) {
    sequenceNumber = 0;
  }

  if (frame.hasPANIDCompression() && (frame.getDestinationAddressingMode() != AddressingMode.NOT_PRESENT)) {
    frame.destinationPAN = panID;
  }

  switch (frame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    frame.sourcePAN = panID;
    frame.sourceAddress = shortAddress;
    break;
  case AddressingMode.EUI:
    frame.sourcePAN = panID;
    frame.sourceAddress = eui;
    break;
  }

  if (frame.hasSecurityEnabled()) {
    frame.frameCounter = 0;
    frame.keyCounter = 0x10;
  }

  frame.payload = new Buffer(0);

  return frame;
}

exports.makeFrameControlLow = function(frameType, securityEnabled, framePending, ackRequest, panIDCompression) {
  return frameType | (securityEnabled ? 0x08 : 0x00) | (framePending ? 0x10 : 0x00) | (ackRequest ? 0x20 : 0x00) | (panIDCompression ? 0x40 : 0x00);
}

exports.makeFrameControlHigh = function(destinationAddressingMode, sourceAddressingMode) {
  return (destinationAddressingMode << 2) | (sourceAddressingMode << 6);
}
<|endoftext|>


<commit_before>var _ = require('lodash'),
    async = require('async'),
    Contextify = require('contextify'),
    dom = require('./dom'),
    exec = require('./exec'),
      rewriteStack = exec.rewriteStack,
    fs = require('fs'),
    jQuery = require('./jquery'),
    path = require('path');

var pageCache = {},
    scriptCache = {},
    windowId = 0;

module.exports = exports = function(options) {
  var host = options.host || 'localhost',
      protocol = options.protocol || 'http:',
      callback = options.callback,
      emitCallbacks = [];

  function execUser(userMethod) {
    try {
      exec.exec(userMethod);
    } catch (err) {
      callback(err);
    }
  }

  function redirect(url) {
    callback(undefined, {redirect: url});
    callback = undefined;
  }

  var $,
      scripts,
      cacheScript,
      pending = exec.Pending.create();

  var context = Contextify.createContext({}),
      window = context.getGlobal();
  _.extend(window, {
    _id: windowId++,
    $serverSide: true,

    emit: function(after) {
      function callback() {
        if (isComplete()) {
          setImmediate(emit);
        }
      }
      function isComplete() {
        if (after === 'ajax') {
          return $.ajax.allComplete();
        } else if (after === 'events') {
          return !pending.pending();
        } else {
          return true;
        }
      }

      if (isComplete()) {
        setImmediate(emit);
      } else if (after === 'ajax') {
        $.ajax.once('complete', callback);
      } else if (after === 'events') {
        pending.on('pop', callback);
      }
    },
    onEmit: function(callback) {
      emitCallbacks.push(callback);
    },

    loadInContext: function(href, callback) {
      if (options.resolver) {
        href = options.resolver(href, window);
      } else {
        href = path.resolve(path.join(path.dirname(options.index), href));
      }

      function exec() {
        execUser(function() {
          script.runInContext(context);
        });

        if (callback) {
          setImmediate(function() {
            execUser(callback);
          });
        }
      }

      var script = scriptCache[href];
      if (!script) {
        fs.readFile(href, function(err, src) {
          if (err) {
            return callback(err);
          }

          script = Contextify.createScript(src.toString(), href);
          if (options.cacheResources) {
            scriptCache[href] = script;
          }

          exec();
        });
      } else {
        setImmediate(exec);
      }
    }
  });
  window.self = window.window = window;

  dom.async(window, pending, execUser);
  dom.console(window);
  dom.document(window);
  dom.location(window, protocol + '//' + host + options.url.path, redirect);
  dom.history(window);
  dom.navigator(window, options);
  dom.performance(window);
  dom.storage(window, 'localStorage');
  dom.storage(window, 'sessionStorage');

  function emit() {
    if (!callback) {
      // This should be considered a framework error as the pending tracker
      // should prevent this from happening.
      throw new Error('Emit outside of request: ' + window._id);
    }

    emitCallbacks.forEach(function(callback) {
      execUser(callback);
    });

    // Inline any script content that we may have received
    if (cacheScript) {
      cacheScript.remove();
    }
    cacheScript = $.$('<script>var $serverCache = ' + $.ajax.toJSON() + ';</script>');
    $.$('body').append(cacheScript);

    // Kill off anything that may be pending as well as all logs, etc
    $.ajax.reset();
    pending.reset();

    // Ensure sure that we have all of our script content and that it it at the end of the document
    // this has two benefits: the body element may be rendered to directly and this will push
    // all of the scripts after the content elements
    $.$('body').append(scripts);

    options.finalize && options.finalize(window);

    console.log('emit time: ' + (Date.now() - window.performance.timing.navigationStart));
    // And output the thing
    var _callback = callback;
    callback = undefined;
    _callback(undefined, $.root.html());
  }

  function loadPage(err, src) {
    if (err) {
      return callback(err);
    }

    if (options.cacheResources) {
      pageCache[options.index] = src;
    }

    $ = jQuery(window, src, pending);

    if (options.beforeExec) {
      options.beforeExec(window, $, execUser, loadScripts);
    } else {
      loadScripts();
    }
  }

  function loadScripts() {
    scripts = $.$('script');
    async.forEachSeries(scripts, function(script, callback) {
      var el = $.$(script),
          text = el.text(),
          external = el.attr('src');

      if (external) {
        window.loadInContext(external, callback);
      } else {
        execUser(function() {
          context.run(text, text);
        });
        callback();
      }
    },
    function(err) {
      if (err) {
        callback(err);
      } else {
        options.loaded && options.loaded(err, window, $);
      }
    });
  }

  if (pageCache[options.index]) {
    loadPage(undefined, pageCache[options.index]);
  } else {
    fs.readFile(options.index, loadPage);
  }

  return {
    id: window._id,
    window: window,
    emit: emit,

    navigate: function(path, _callback) {
      callback = _callback;
      dom.location(window, protocol + '//' + host + path, redirect);
      dom.performance(window);
      dom.storage(window, 'localStorage');
      dom.storage(window, 'sessionStorage');
    }
  };
};
<commit_msg>Use hrtime for emit time log<commit_after>var _ = require('lodash'),
    async = require('async'),
    Contextify = require('contextify'),
    dom = require('./dom'),
    exec = require('./exec'),
      rewriteStack = exec.rewriteStack,
    fs = require('fs'),
    jQuery = require('./jquery'),
    path = require('path');

var pageCache = {},
    scriptCache = {},
    windowId = 0;

module.exports = exports = function(options) {
  var host = options.host || 'localhost',
      protocol = options.protocol || 'http:',
      callback = options.callback,
      emitCallbacks = [];

  function execUser(userMethod) {
    try {
      exec.exec(userMethod);
    } catch (err) {
      callback(err);
    }
  }

  function redirect(url) {
    callback(undefined, {redirect: url});
    callback = undefined;
  }

  var start = process.hrtime();

  var $,
      scripts,
      cacheScript,
      pending = exec.Pending.create();

  var context = Contextify.createContext({}),
      window = context.getGlobal();
  _.extend(window, {
    _id: windowId++,
    $serverSide: true,

    emit: function(after) {
      function callback() {
        if (isComplete()) {
          setImmediate(emit);
        }
      }
      function isComplete() {
        if (after === 'ajax') {
          return $.ajax.allComplete();
        } else if (after === 'events') {
          return !pending.pending();
        } else {
          return true;
        }
      }

      if (isComplete()) {
        setImmediate(emit);
      } else if (after === 'ajax') {
        $.ajax.once('complete', callback);
      } else if (after === 'events') {
        pending.on('pop', callback);
      }
    },
    onEmit: function(callback) {
      emitCallbacks.push(callback);
    },

    loadInContext: function(href, callback) {
      if (options.resolver) {
        href = options.resolver(href, window);
      } else {
        href = path.resolve(path.join(path.dirname(options.index), href));
      }

      function exec() {
        execUser(function() {
          script.runInContext(context);
        });

        if (callback) {
          setImmediate(function() {
            execUser(callback);
          });
        }
      }

      var script = scriptCache[href];
      if (!script) {
        fs.readFile(href, function(err, src) {
          if (err) {
            return callback(err);
          }

          script = Contextify.createScript(src.toString(), href);
          if (options.cacheResources) {
            scriptCache[href] = script;
          }

          exec();
        });
      } else {
        setImmediate(exec);
      }
    }
  });
  window.self = window.window = window;

  dom.async(window, pending, execUser);
  dom.console(window);
  dom.document(window);
  dom.location(window, protocol + '//' + host + options.url.path, redirect);
  dom.history(window);
  dom.navigator(window, options);
  dom.performance(window);
  dom.storage(window, 'localStorage');
  dom.storage(window, 'sessionStorage');

  function emit() {
    if (!callback) {
      // This should be considered a framework error as the pending tracker
      // should prevent this from happening.
      throw new Error('Emit outside of request: ' + window._id);
    }

    emitCallbacks.forEach(function(callback) {
      execUser(callback);
    });

    // Inline any script content that we may have received
    if (cacheScript) {
      cacheScript.remove();
    }
    cacheScript = $.$('<script>var $serverCache = ' + $.ajax.toJSON() + ';</script>');
    $.$('body').append(cacheScript);

    // Kill off anything that may be pending as well as all logs, etc
    $.ajax.reset();
    pending.reset();

    // Ensure sure that we have all of our script content and that it it at the end of the document
    // this has two benefits: the body element may be rendered to directly and this will push
    // all of the scripts after the content elements
    $.$('body').append(scripts);

    options.finalize && options.finalize(window);

    console.log('emit time: ' + process.hrtime(start)[1]/1e6, 'id_' + window._id);
    // And output the thing
    var _callback = callback;
    callback = undefined;
    _callback(undefined, $.root.html());
  }

  function loadPage(err, src) {
    if (err) {
      return callback(err);
    }

    if (options.cacheResources) {
      pageCache[options.index] = src;
    }

    $ = jQuery(window, src, pending);

    if (options.beforeExec) {
      options.beforeExec(window, $, execUser, loadScripts);
    } else {
      loadScripts();
    }
  }

  function loadScripts() {
    scripts = $.$('script');
    async.forEachSeries(scripts, function(script, callback) {
      var el = $.$(script),
          text = el.text(),
          external = el.attr('src');

      if (external) {
        window.loadInContext(external, callback);
      } else {
        execUser(function() {
          context.run(text, text);
        });
        callback();
      }
    },
    function(err) {
      if (err) {
        callback(err);
      } else {
        options.loaded && options.loaded(err, window, $);
      }
    });
  }

  if (pageCache[options.index]) {
    loadPage(undefined, pageCache[options.index]);
  } else {
    fs.readFile(options.index, loadPage);
  }

  return {
    id: window._id,
    window: window,
    emit: emit,

    navigate: function(path, _callback) {
      start = process.hrtime();
      callback = _callback;
      dom.location(window, protocol + '//' + host + path, redirect);
      dom.performance(window);
      dom.storage(window, 'localStorage');
      dom.storage(window, 'sessionStorage');
    }
  };
};
<|endoftext|>


<commit_before>const wd = require('wd');
const Promise = require('bluebird');
const bl = require('bl');
const JSONStream = require('JSONStream');
const browser = require('./browser');
const normalise = require('./normalise-logs');

// augment wd with stream methods
require('./wd-streams');

const blacklist = ['UpdateLayerTree', 'Layout', 'FunctionCall', 'UpdateLayoutTree',
  'EventDispatch', 'TimerFire', 'TimerInstall', 'TimerRemove', 'ResourceSendRequest', 'ResourceReceivedData'];

function test (opts) {
  opts.driver = opts.driver || 'http://localhost:9515';
  opts.browser = wd.remote(opts.driver, 'promiseChain');
  return Promise.using(browser(opts.browser), (session) => {
    return session
      .sleep(500)
      .setWindowSize(1024, 768).catch(() => {})
      .get(opts.url)
      .then(() => {
        return Promise.resolve()
          .then(() => {
            if (opts.scroll || opts.reporter === 'fps') {
              return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);');
            }
          })
          .then(() => {
            if (typeof opts.inject === 'function') {
              return opts.inject(session);
            }
          })
          .then(() => {
            return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000)
              .catch(() => {
                console.error('Page loading timed out after 120s');
              });
          })
          .then(() => {
            return session;
          });
      })
      .sleep(opts.sleep)
      .then(() => {
        return new Promise((resolve, reject) => {
          const stream = session.logstream('performance')
            .pipe(JSONStream.parse('value.*', (item) => {
              item.message = JSON.parse(item.message);
              item.name = item.message.message.params.name;
              item.timestamp = item.message.message.params.timestamp || (item.message.message.params.ts / 1e6);

              if (item.message.message.params && item.message.message.params.cat === '__metadata') {
                return;
              }
              if (blacklist.indexOf(item.name) !== -1) {
                return;
              }
              return item;
            }))
            .pipe(JSONStream.stringify())
            .pipe(bl((err, data) => {
              err ? reject(err) : resolve(JSON.parse(data.toString()));
            }));
          stream.on('error', reject);
        });
      })
      .then((logs) => {
        opts.progress.increment();
        return normalise(logs, opts.url);
      });
  });
}

module.exports = test;
<commit_msg>Only scroll up and down by 1px<commit_after>const wd = require('wd');
const Promise = require('bluebird');
const bl = require('bl');
const JSONStream = require('JSONStream');
const browser = require('./browser');
const normalise = require('./normalise-logs');

// augment wd with stream methods
require('./wd-streams');

const blacklist = ['UpdateLayerTree', 'Layout', 'FunctionCall', 'UpdateLayoutTree',
  'EventDispatch', 'TimerFire', 'TimerInstall', 'TimerRemove', 'ResourceSendRequest', 'ResourceReceivedData'];

function test (opts) {
  opts.driver = opts.driver || 'http://localhost:9515';
  opts.browser = wd.remote(opts.driver, 'promiseChain');
  return Promise.using(browser(opts.browser), (session) => {
    return session
      .sleep(500)
      .setWindowSize(1024, 768).catch(() => {})
      .get(opts.url)
      .then(() => {
        return Promise.resolve()
          .then(() => {
            if (opts.scroll || opts.reporter === 'fps') {
              return session.execute('dir=-1;function f () { window.scrollBy(0,dir*=-1); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);');
            }
          })
          .then(() => {
            if (typeof opts.inject === 'function') {
              return opts.inject(session);
            }
          })
          .then(() => {
            return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000)
              .catch(() => {
                console.error('Page loading timed out after 120s');
              });
          })
          .then(() => {
            return session;
          });
      })
      .sleep(opts.sleep)
      .then(() => {
        return new Promise((resolve, reject) => {
          const stream = session.logstream('performance')
            .pipe(JSONStream.parse('value.*', (item) => {
              item.message = JSON.parse(item.message);
              item.name = item.message.message.params.name;
              item.timestamp = item.message.message.params.timestamp || (item.message.message.params.ts / 1e6);

              if (item.message.message.params && item.message.message.params.cat === '__metadata') {
                return;
              }
              if (blacklist.indexOf(item.name) !== -1) {
                return;
              }
              return item;
            }))
            .pipe(JSONStream.stringify())
            .pipe(bl((err, data) => {
              err ? reject(err) : resolve(JSON.parse(data.toString()));
            }));
          stream.on('error', reject);
        });
      })
      .then((logs) => {
        opts.progress.increment();
        return normalise(logs, opts.url);
      });
  });
}

module.exports = test;
<|endoftext|>


<commit_before>import { Path, Point } from './path'
import clipper from 'clipper-lib'

const DEG_TO_RAD = Math.PI / 180

// SVG tag class
class Tag {
    // Class constructor...
    constructor(element, parent) {
        // Init properties
        this.element  = element
        this.name     = element.nodeName.toLowerCase()
        this.parent   = parent || null
        this.layer    = null
        this.attrs    = {}
        this.children = []
        this.paths    = []
        this.matrix   = null
        this.path     = new Path()
        this.point    = new Point(0, 0)
        this.shapes   = []

        // Add first path
        this.paths.push(this.path)

        // Set the matrix
        this.setMatrix(this.parent && this.parent.matrix)

        // Clone parent attributes
        if (this.parent && (this.parent.name === 'g' || this.parent.name === 'svg')) {
            // Inherit layer name
            this.layer = this.parent.layer

            // Inherit parent attributes
            let excludes = ['transform', 'width', 'height']

            Object.keys(this.parent.attrs).forEach(key => {
                if (excludes.indexOf(key) === -1) {
                    this.setAttr(key, this.parent.attrs[key])
                }
            })
        }
    }

    setAttr(name, value) {
        this.attrs[name] = value
    }

    getAttr(name, defaultValue) {
        return this.attrs[name] !== undefined ? this.attrs[name]
            : (defaultValue !== undefined ? defaultValue : null)
    }

    getLayerName() {
        if (this.name === 'g') {
            return this.getAttr('inkscape:label', this.getAttr('id', null))
        }
    }

    setLayerName(name) {
        if (this.name === 'g') {
            this.layer = name || this.getLayerName()
        }
    }

    addChild(childTag) {
        this.children.push(childTag)
    }

    clearPath() {
        this.path = new Path()
    }

    newPath() {
        if (this.path.length > 0) {
            this.clearPath()
            this.paths.push(this.path)
        }
    }

    closePath() {
        return this.path.close()
    }

    addPoint(x, y, relative) {
        // Relative from the last point
        if (relative) {
            x += this.point.x
            y += this.point.y
        }

        // Add current point
        this.path.addPoint(x, y)

        // Update current point
        this.point = this.path.getPoint(-1)
    }

    addPoints(points, relative) {
        // For each couple of points
        for (let i = 0, il = points.length; i < il; i += 2) {
            this.addPoint(points[i], points[i + 1], relative)
        }
    }

    setMatrix(matrix) {
        this.matrix = matrix || [1, 0, 0, 1, 0, 0]
    }

    addMatrix(matrix) {
        this.matrix = [
            this.matrix[0] * matrix[0] + this.matrix[2] * matrix[1],
            this.matrix[1] * matrix[0] + this.matrix[3] * matrix[1],
            this.matrix[0] * matrix[2] + this.matrix[2] * matrix[3],
            this.matrix[1] * matrix[2] + this.matrix[3] * matrix[3],
            this.matrix[0] * matrix[4] + this.matrix[2] * matrix[5] + this.matrix[4],
            this.matrix[1] * matrix[4] + this.matrix[3] * matrix[5] + this.matrix[5]
        ]
    }

    translate(x, y) {
        y = y === undefined ? 0 : y
        this.addMatrix([1, 0, 0, 1, x, y])
    }

    rotate(angle, x, y) {
        angle = angle * DEG_TO_RAD

        if (arguments.length == 2) {
            this.addMatrix([1, 0, 0, 1, x, y])
        }

        this.addMatrix([Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0])

        if (arguments.length == 2) {
            this.addMatrix([1, 0, 0, 1, -x, -y])
        }
    }

    scale(x, y) {
        y = y === undefined ? x : y
        this.addMatrix([x, 0, 0, y, 0, 0])
    }

    skewX(angle) {
        this.addMatrix([1, 0, Math.tan(angle * DEG_TO_RAD), 1, 0, 0])
    }

    skewY(angle) {
        this.addMatrix([1, Math.tan(angle * DEG_TO_RAD), 0, 1, 0, 0])
    }

    applyMatrix(matrix) {
        matrix && this.addMatrix(matrix)

        this.paths.forEach(path => {
            path.transform(this.matrix)
        })

        this.shapes.forEach(shape => {
            shape.outer.transform(this.matrix)
            shape.holes.forEach(hole => {
                hole.transform(this.matrix)
            })
        })

        this.setMatrix(null)

        this.children.forEach(tag => {
            tag.applyMatrix(matrix)
        })
    }

    getPaths() {
        return this.paths
    }

    getShapes() {
        // No shapes...
        if (this.getAttr('fill', 'none') === 'none' || ! this.paths[0].length) {
            return this.shapes
        }

        // Get fill rule
        let fillRule = this.getAttr('fill-rule', 'nonzero')
            console.log(fillRule);
            fillRule = fillRule === 'nonzero' ? clipper.PolyFillType.pftNonZero : clipper.PolyFillType.pftEvenOdd

        // Create clipper path
        let clipperPaths = []
        let clipperScale = 1000000.0

        this.paths.forEach(path => {
            clipperPaths.push(path.getClipperPoints(clipperScale))
        })

        // Simplify paths (self-intersecting)
        clipperPaths = clipper.Clipper.SimplifyPolygons(clipperPaths, fillRule)

        // Clipper paths to PolyTree
        let cClipper = new clipper.Clipper()
        let polyTree = new clipper.PolyTree()

        cClipper.AddPaths(clipperPaths, clipper.PolyType.ptSubject, true)
        cClipper.Execute(clipper.ClipType.ctUnion, polyTree, fillRule, fillRule)

        // PolyTree to ExPolygons
        let exPolygons = clipper.JS.PolyTreeToExPolygons(polyTree)

        let toPath = path => new Path().fromClipperPoints(path, 1 / clipperScale)

        this.shapes = exPolygons.map(exPolygon => {
            return {
                outer: toPath(exPolygon.outer),
                holes: exPolygon.holes.map(toPath)
            }
        })

        // console.log('clipperPaths:', clipperPaths)
        // console.log('polyTree:', polyTree)
        // console.log('shapes:', this.shapes)

        return this.shapes
    }
}

// Exports
export { Tag }
export default Tag
<commit_msg>Cleanning<commit_after>import { Path, Point } from './path'
import clipper from 'clipper-lib'

const DEG_TO_RAD = Math.PI / 180

// SVG tag class
class Tag {
    // Class constructor...
    constructor(element, parent) {
        // Init properties
        this.element  = element
        this.name     = element.nodeName.toLowerCase()
        this.parent   = parent || null
        this.layer    = null
        this.attrs    = {}
        this.children = []
        this.paths    = []
        this.matrix   = null
        this.path     = new Path()
        this.point    = new Point(0, 0)
        this.shapes   = []

        // Add first path
        this.paths.push(this.path)

        // Set the matrix
        this.setMatrix(this.parent && this.parent.matrix)

        // Clone parent attributes
        if (this.parent && (this.parent.name === 'g' || this.parent.name === 'svg')) {
            // Inherit layer name
            this.layer = this.parent.layer

            // Inherit parent attributes
            let excludes = ['transform', 'width', 'height']

            Object.keys(this.parent.attrs).forEach(key => {
                if (excludes.indexOf(key) === -1) {
                    this.setAttr(key, this.parent.attrs[key])
                }
            })
        }
    }

    setAttr(name, value) {
        this.attrs[name] = value
    }

    getAttr(name, defaultValue) {
        return this.attrs[name] !== undefined ? this.attrs[name]
            : (defaultValue !== undefined ? defaultValue : null)
    }

    getLayerName() {
        if (this.name === 'g') {
            return this.getAttr('inkscape:label', this.getAttr('id', null))
        }
    }

    setLayerName(name) {
        if (this.name === 'g') {
            this.layer = name || this.getLayerName()
        }
    }

    addChild(childTag) {
        this.children.push(childTag)
    }

    clearPath() {
        this.path = new Path()
    }

    newPath() {
        if (this.path.length > 0) {
            this.clearPath()
            this.paths.push(this.path)
        }
    }

    closePath() {
        return this.path.close()
    }

    addPoint(x, y, relative) {
        // Relative from the last point
        if (relative) {
            x += this.point.x
            y += this.point.y
        }

        // Add current point
        this.path.addPoint(x, y)

        // Update current point
        this.point = this.path.getPoint(-1)
    }

    addPoints(points, relative) {
        // For each couple of points
        for (let i = 0, il = points.length; i < il; i += 2) {
            this.addPoint(points[i], points[i + 1], relative)
        }
    }

    setMatrix(matrix) {
        this.matrix = matrix || [1, 0, 0, 1, 0, 0]
    }

    addMatrix(matrix) {
        this.matrix = [
            this.matrix[0] * matrix[0] + this.matrix[2] * matrix[1],
            this.matrix[1] * matrix[0] + this.matrix[3] * matrix[1],
            this.matrix[0] * matrix[2] + this.matrix[2] * matrix[3],
            this.matrix[1] * matrix[2] + this.matrix[3] * matrix[3],
            this.matrix[0] * matrix[4] + this.matrix[2] * matrix[5] + this.matrix[4],
            this.matrix[1] * matrix[4] + this.matrix[3] * matrix[5] + this.matrix[5]
        ]
    }

    translate(x, y) {
        y = y === undefined ? 0 : y
        this.addMatrix([1, 0, 0, 1, x, y])
    }

    rotate(angle, x, y) {
        angle = angle * DEG_TO_RAD

        if (arguments.length == 2) {
            this.addMatrix([1, 0, 0, 1, x, y])
        }

        this.addMatrix([Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0])

        if (arguments.length == 2) {
            this.addMatrix([1, 0, 0, 1, -x, -y])
        }
    }

    scale(x, y) {
        y = y === undefined ? x : y
        this.addMatrix([x, 0, 0, y, 0, 0])
    }

    skewX(angle) {
        this.addMatrix([1, 0, Math.tan(angle * DEG_TO_RAD), 1, 0, 0])
    }

    skewY(angle) {
        this.addMatrix([1, Math.tan(angle * DEG_TO_RAD), 0, 1, 0, 0])
    }

    applyMatrix(matrix) {
        matrix && this.addMatrix(matrix)

        this.paths.forEach(path => {
            path.transform(this.matrix)
        })

        this.shapes.forEach(shape => {
            shape.outer.transform(this.matrix)
            shape.holes.forEach(hole => {
                hole.transform(this.matrix)
            })
        })

        this.setMatrix(null)

        this.children.forEach(tag => {
            tag.applyMatrix(matrix)
        })
    }

    getPaths() {
        return this.paths
    }

    getShapes() {
        // No shapes...
        if (this.getAttr('fill', 'none') === 'none' || ! this.paths[0].length) {
            return this.shapes
        }

        // Get fill rule
        let fillRule = this.getAttr('fill-rule', 'nonzero')
            fillRule = fillRule === 'nonzero' ? clipper.PolyFillType.pftNonZero : clipper.PolyFillType.pftEvenOdd

        // Create clipper path
        let clipperPaths = []
        let clipperScale = 1000000.0

        this.paths.forEach(path => {
            clipperPaths.push(path.getClipperPoints(clipperScale))
        })

        // Simplify paths (self-intersecting)
        clipperPaths = clipper.Clipper.SimplifyPolygons(clipperPaths, fillRule)

        // Clipper paths to PolyTree
        let cClipper = new clipper.Clipper()
        let polyTree = new clipper.PolyTree()

        cClipper.AddPaths(clipperPaths, clipper.PolyType.ptSubject, true)
        cClipper.Execute(clipper.ClipType.ctUnion, polyTree, fillRule, fillRule)

        // PolyTree to ExPolygons
        let exPolygons = clipper.JS.PolyTreeToExPolygons(polyTree)

        let toPath = path => new Path().fromClipperPoints(path, 1 / clipperScale)

        this.shapes = exPolygons.map(exPolygon => {
            return {
                outer: toPath(exPolygon.outer),
                holes: exPolygon.holes.map(toPath)
            }
        })

        // console.log('clipperPaths:', clipperPaths)
        // console.log('polyTree:', polyTree)
        // console.log('shapes:', this.shapes)

        return this.shapes
    }
}

// Exports
export { Tag }
export default Tag
<|endoftext|>


<commit_before>export default class {
    constructor($injector, $scope) {
        'ngInject';

        this.type = null;
        this.title = null;
        this.list = null;
        this.service = null;
        this.isLoadingMore = false;
        this.isPaginationOver = false;
        this.$injector = $injector;
        this.config = $injector.get('$WPHCConfig');
        this.$stateParams = $injector.get('$stateParams');
        this.$q = $injector.get('$q');
        this.$log = $injector.get('$log');
        this.page = 1;
        this.$scope = $scope;
        this.loadMore = ionic.throttle(angular.bind(this, () => {
            this.doLoadMore().finally(() => this.$scope.$broadcast('scroll.infiniteScrollComplete'));
        }), 1000);
    }

    init() {
        this.page = 1;
        this.isPaginationOver = false;
        return this.doLoadMore();
    }

    refresh() {
        this.page = 1;
        this.isPaginationOver = false;
        this.service.clearCache();
        this.doLoadMore(true).then((response) => {
            this.$log.debug('[AbstractList] refresh', response);
        }).finally(() => this.$scope.$broadcast('scroll.refreshComplete'));
    }

    doLoadMore(refresh = false) {
        // prevent multiple call when the server takes some time to answer
        if (this.isLoadingMore || this.isPaginationOver) {
            return this.$q.when(null);
        }
        this.isLoadingMore = true;

        const query = this.getMergedQuery();
        this.$log.debug('[AbstractList] type', this.type);
        this.$log.debug('[AbstractList] query', query);

        return this.service.get(query).then((response) => {
            this.page++;
            this.list = (this.list && !refresh) ? this.list.concat(response.data) : response.data;
            this.isPaginationOver = (response.data.length === 0 || response.data.length < query.per_page);
            this.$log.debug('[AbstractList] data loded');
            this.$log.debug('[AbstractList] data loded: page', this.page);
            this.$log.debug('[AbstractList] data loded: items', response.data);
            this.$log.debug('[AbstractList] data loded: isPaginationOver', this.isPaginationOver);
            this.onDataLoaded(response);
            return response;
        }).finally(() => this.isLoadingMore = false);
    }

    getQuery() {
        return {
            page: this.page,
            per_page: 5,
            "_embed": true
        }
    }

    getMergedQuery() {
        let typeQuery = _.get(this.config, `[${this.type}].query`, {});
        if (this.type === 'customPosts' && this.$stateParams.slug) {
            typeQuery = _.get(this.config, `[${this.$stateParams.slug}].query`, {})
        } else if (this.type === 'taxonomiesPosts' && this.postType) {
            typeQuery = _.get(this.config, `[${this.postType}].query`, {})
        }
        return Object.assign(this.getQuery(), typeQuery);
    }

    setType(type = null) {
        this.type = type;
    }

    setService(service = null) {
        this.service = service;
    }

    setTitle(title = null) {
        this.title = title;
    }

    onDataLoaded(response) {

    }
}
<commit_msg>Removes ES6 code that needs a polyfill<commit_after>export default class {
    constructor($injector, $scope) {
        'ngInject';

        this.type = null;
        this.title = null;
        this.list = null;
        this.service = null;
        this.isLoadingMore = false;
        this.isPaginationOver = false;
        this.$injector = $injector;
        this.config = $injector.get('$WPHCConfig');
        this.$stateParams = $injector.get('$stateParams');
        this.$q = $injector.get('$q');
        this.$log = $injector.get('$log');
        this.page = 1;
        this.$scope = $scope;
        this.loadMore = ionic.throttle(angular.bind(this, () => {
            this.doLoadMore().finally(() => this.$scope.$broadcast('scroll.infiniteScrollComplete'));
        }), 1000);
    }

    init() {
        this.page = 1;
        this.isPaginationOver = false;
        return this.doLoadMore();
    }

    refresh() {
        this.page = 1;
        this.isPaginationOver = false;
        this.service.clearCache();
        this.doLoadMore(true).then((response) => {
            this.$log.debug('[AbstractList] refresh', response);
        }).finally(() => this.$scope.$broadcast('scroll.refreshComplete'));
    }

    doLoadMore(refresh = false) {
        // prevent multiple call when the server takes some time to answer
        if (this.isLoadingMore || this.isPaginationOver) {
            return this.$q.when(null);
        }
        this.isLoadingMore = true;

        const query = this.getMergedQuery();
        this.$log.debug('[AbstractList] type', this.type);
        this.$log.debug('[AbstractList] query', query);

        return this.service.get(query).then((response) => {
            this.page++;
            this.list = (this.list && !refresh) ? this.list.concat(response.data) : response.data;
            this.isPaginationOver = (response.data.length === 0 || response.data.length < query.per_page);
            this.$log.debug('[AbstractList] data loded');
            this.$log.debug('[AbstractList] data loded: page', this.page);
            this.$log.debug('[AbstractList] data loded: items', response.data);
            this.$log.debug('[AbstractList] data loded: isPaginationOver', this.isPaginationOver);
            this.onDataLoaded(response);
            return response;
        }).finally(() => this.isLoadingMore = false);
    }

    getQuery() {
        return {
            page: this.page,
            per_page: 5,
            "_embed": true
        }
    }

    getMergedQuery() {
        let typeQuery = _.get(this.config, `[${this.type}].query`, {});
        if (this.type === 'customPosts' && this.$stateParams.slug) {
            typeQuery = _.get(this.config, `[${this.$stateParams.slug}].query`, {})
        } else if (this.type === 'taxonomiesPosts' && this.postType) {
            typeQuery = _.get(this.config, `[${this.postType}].query`, {})
        }
        return angular.merge(this.getQuery(), typeQuery);
    }

    setType(type = null) {
        this.type = type;
    }

    setService(service = null) {
        this.service = service;
    }

    setTitle(title = null) {
        this.title = title;
    }

    onDataLoaded(response) {

    }
}
<|endoftext|>


<commit_before>import { Component } from 'react';
import getEnabled from './get-enabled';
import updateFeaturesWithQuery from './update-features-with-query';
import PropTypes from 'prop-types';

class Features extends Component {
  constructor(props, context) {
    super(props);
    this.state = {
      features: this.getEnabledFeatures(props, context)
    };
  }
  static contextTypes = {
    query: PropTypes.object
  };
  static childContextTypes = {
    hasFeature: PropTypes.func
  };
  static propTypes = {
    initialFeatures: PropTypes.array
  };
  componentWillReceiveProps(props, context) {
    this.setState(() => ({
      features: this.getEnabledFeatures(props, context)
    }));
  }
  hasFeature = featureName => {
    return this.state.features.includes(featureName);
  };
  getEnabledFeatures(props, context) {
    return getEnabled(
      updateFeaturesWithQuery(
        props.initialFeatures,
        props.query || context.query
      )
    );
  }
  getChildContext() {
    return {
      hasFeature: this.hasFeature
    };
  }
  render() {
    const { children } = this.props;
    return children({ hasFeature: this.hasFeature });
  }
}

export default Features;
<commit_msg>add query prop type<commit_after>import { Component } from 'react';
import getEnabled from './get-enabled';
import updateFeaturesWithQuery from './update-features-with-query';
import PropTypes from 'prop-types';

class Features extends Component {
  constructor(props, context) {
    super(props);
    this.state = {
      features: this.getEnabledFeatures(props, context)
    };
  }
  static contextTypes = {
    query: PropTypes.object
  };
  static childContextTypes = {
    hasFeature: PropTypes.func
  };
  static propTypes = {
    initialFeatures: PropTypes.array,
    query: PropTypes.object
  };
  componentWillReceiveProps(props, context) {
    this.setState(() => ({
      features: this.getEnabledFeatures(props, context)
    }));
  }
  hasFeature = featureName => {
    return this.state.features.includes(featureName);
  };
  getEnabledFeatures(props, context) {
    return getEnabled(
      updateFeaturesWithQuery(
        props.initialFeatures,
        props.query || context.query
      )
    );
  }
  getChildContext() {
    return {
      hasFeature: this.hasFeature
    };
  }
  render() {
    const { children } = this.props;
    return children({ hasFeature: this.hasFeature });
  }
}

export default Features;
<|endoftext|>


<commit_before>"use strict";

var schedule = require('node-schedule');
var utils = require('./utils');

module.exports = Plan;

function Plan(options, fn, hashFn) {
    if (!(this instanceof Plan)) {
        return new Plan(options, fn, hashFn);
    }

    if (typeof options === 'function') {
        hashFn = fn;
        fn = options;
        options = {};
    }
    this._options = utils.assign({
        continuous: false,
        time: '1s',
        scope: null
    }, options);
    this._fn = fn;
    this._hashFn = hashFn || function (value) { return value };

    this.jobs = {};
}

Plan.prototype.signal = function (key, data) {
    var self = this;
    var opts = this._options;
    var fn = this._fn;

    var hashKey = this._hashFn(key);
    var job = this.jobs[hashKey];

    if (job && !opts.continuous) return;

    if (job) job.cancel();

    var time = opts.time;
    if (typeof time === 'string') {
        time = Date.now() + utils.parseTime(time);
    }

    this.jobs[hashKey] = schedule.scheduleJob(time, function () {
        delete self.jobs[hashKey];
        fn.call(opts.scope, key, data);
    });
};<commit_msg>Add execute<commit_after>"use strict";

var schedule = require('node-schedule');
var utils = require('./utils');

module.exports = Plan;

function Plan(options, fn, hashFn) {
    if (!(this instanceof Plan)) {
        return new Plan(options, fn, hashFn);
    }

    if (typeof options === 'function') {
        hashFn = fn;
        fn = options;
        options = {};
    }
    this._options = utils.assign({
        continuous: false,
        time: '1s',
        scope: null
    }, options);

    this._fn = fn;
    this._hashFn = hashFn || function (value) { return value };

    this.jobs = {};
}

Plan.prototype.execute = function (key, data) {
    this._fn.call(this._options.scope, key, data);
};

Plan.prototype.signal = function (key, data) {
    var self = this;
    var opts = this._options;

    var hashKey = this._hashFn(key);
    var job = this.jobs[hashKey];

    if (job && !opts.continuous) return;

    if (job) job.cancel();

    var time = opts.time;
    if (typeof time === 'string') {
        time = Date.now() + utils.parseTime(time);
    }

    this.jobs[hashKey] = schedule.scheduleJob(time, function () {
        delete self.jobs[hashKey];
        self.execute(key, data);
    });
};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Sorts servers according to the 2adic ranking using free RAM on a server
 * and the requested RAM. The returned result is in order of preference (first
 * being highest).
 */

/*
 * Sorts servers by their 2adic ranking using available RAM and requested RAM.
 *
 * Uses a schwarzian transform.
 */
function sort2Adic(servers, requestedRam) {
    var reqRamInBytes = requestedRam * 1024 * 1024;
    var serversEnoughSpace = servers.filter(function (server) {
        var availRam = server.memory_available_bytes;
        return availRam >= reqRamInBytes;
    });

    var adics = serversEnoughSpace.map(function (server) {
        var availRam = server.memory_available_bytes / 1024 / 1024;
        var hexRatio = Math.floor(availRam / requestedRam).toString(2);
        var adicFractional = hexRatio.split('').reverse().join('');
        var adic = +('0.' + adicFractional);

        return [adic, server];
    });

    var sortedAdics = adics.sort(function (i, j) {
        return j[0] - i[0];
    });

    var sortedServers = sortedAdics.map(function (adic) {
        return adic[1];
    });

    return sortedServers;
}

module.exports = {
    name: 'Sort servers by 2adic',
    run: sort2Adic
};
<commit_msg>link to the theory for why 2adic sorting here<commit_after>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Sorts servers according to the 2adic ranking using free RAM on a server
 * and the requested RAM. The returned result is in order of preference (first
 * being highest).
 *
 * Theory: https://hub.joyent.com/wiki/display/support/Selecting+the+server+for+a+new+Zone%2C+part+II
 */

/*
 * Sorts servers by their 2adic ranking using available RAM and requested RAM.
 *
 * Uses a schwarzian transform.
 */
function sort2Adic(servers, requestedRam) {
    var reqRamInBytes = requestedRam * 1024 * 1024;
    var serversEnoughSpace = servers.filter(function (server) {
        var availRam = server.memory_available_bytes;
        return availRam >= reqRamInBytes;
    });

    var adics = serversEnoughSpace.map(function (server) {
        var availRam = server.memory_available_bytes / 1024 / 1024;
        var hexRatio = Math.floor(availRam / requestedRam).toString(2);
        var adicFractional = hexRatio.split('').reverse().join('');
        var adic = +('0.' + adicFractional);

        return [adic, server];
    });

    var sortedAdics = adics.sort(function (i, j) {
        return j[0] - i[0];
    });

    var sortedServers = sortedAdics.map(function (adic) {
        return adic[1];
    });

    return sortedServers;
}

module.exports = {
    name: 'Sort servers by 2adic',
    run: sort2Adic
};
<|endoftext|>


<commit_before>// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

"use strict";

var Speech = require("ssml-builder");

var intent = {
  name: "AMAZON.HelpIntent",
  enabled: true
};

var generateResponse = function () {

  var builder = new Speech();

  builder
    .paragraph("This skill allows you to check for the status of a specific line, or for disruption in general. You can ask about any London Underground line, London Overground or the Docklands Light Railway.")
    .paragraph("Asking about disruption in general provides information about any lines that are currently experiencing issues, such as any delays or planned closures.")
    .paragraph("Asking for the status for a specific line provides a summary of the current service, such as whether there is a good service or if there are any delays.");

  return builder.ssml(true);
};

/**
 * Handles the intent for stop.
 * @param {Object} request - The Alexa skill request.
 * @param {Object} response - The Alexa skill response.
 */
intent.handler = function (request, response) {
  var text = generateResponse();
  response
    .say(text)
    .shouldEndSession(false);
};

module.exports = intent;
<commit_msg>Add help sentence for commute skill<commit_after>// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

"use strict";

var Speech = require("ssml-builder");

var intent = {
  name: "AMAZON.HelpIntent",
  enabled: true
};

var generateResponse = function () {

  var builder = new Speech();

  builder
    .paragraph("This skill allows you to check for the status of a specific line, or for disruption in general. You can ask about any London Underground line, London Overground or the Docklands Light Railway.")
    .paragraph("Asking about disruption in general provides information about any lines that are currently experiencing issues, such as any delays or planned closures.")
    .paragraph("Asking for the status for a specific line provides a summary of the current service, such as whether there is a good service or if there are any delays.");

  /* TODO Enable once ready for certification
  if (false) {
    builder.paragraph("If you link your account and setup your preferences in the London Travel website, you can ask about your commute to quickly find out the status of the lines you frequently use.");
  }
  */

  return builder.ssml(true);
};

/**
 * Handles the intent for stop.
 * @param {Object} request - The Alexa skill request.
 * @param {Object} response - The Alexa skill response.
 */
intent.handler = function (request, response) {
  var text = generateResponse();
  response
    .say(text)
    .shouldEndSession(false);
};

module.exports = intent;
<|endoftext|>


<commit_before>
/*
Tipue Search 2.1
Copyright (c) 2013 Tipue
Tipue Search is released under the MIT License
http://www.tipue.com/search
*/

(function($) {

     $.fn.tipuesearch = function(options) {

          var set = $.extend( {

               'show'                   : 7,
               'newWindow'              : false,
               'showURL'                : true,
               'minimumLength'          : 3,
               'descriptiveWords'       : 25,
               'highlightTerms'         : true,
               'highlightEveryTerm'     : false,
               'mode'                   : 'static',
               'liveDescription'        : '*',
               'liveContent'            : '*',
               'contentLocation'        : 'tipuesearch/tipuesearch_content.json'

          }, options);

          return this.each(function() {

               var tipuesearch_in = {
                    pages: []
               };
               $.ajaxSetup({
                    async: false
               });

               if (set.mode == 'live')
               {
                    for (var i = 0; i < tipuesearch_pages.length; i++)
                    {
                         $.get(tipuesearch_pages[i], '',
                              function (html)
                              {
                                   var cont = $(set.liveContent, html).text();
                                   cont = cont.replace(/\s+/g, ' ');
                                   var desc = $(set.liveDescription, html).text();
                                   desc = desc.replace(/\s+/g, ' ');

                                   var t_1 = html.toLowerCase().indexOf('<title>');
                                   var t_2 = html.toLowerCase().indexOf('</title>', t_1 + 7);
                                   if (t_1 != -1 && t_2 != -1)
                                   {
                                        var tit = html.slice(t_1 + 7, t_2);
                                   }
                                   else
                                   {
                                        var tit = 'No title';
                                   }

                                   tipuesearch_in.pages.push({
                                        "title": tit,
                                        "text": desc,
                                        "tags": cont,
                                        "loc": tipuesearch_pages[i]
                                   });
                              }
                         );
                    }
               }

               if (set.mode == 'json')
               {
                    $.getJSON(set.contentLocation,
                         function(json)
                         {
                              tipuesearch_in = $.extend({}, json);
                         }
                    );
               }

               if (set.mode == 'static' || set.mode == 'static-images')
               {
                    tipuesearch_in = $.extend({}, tipuesearch);
               }

               var tipue_search_w = '';
               if (set.newWindow)
               {
                    tipue_search_w = ' target="_blank"';
               }

               function getURLP(name)
               {
                    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20')) || null;
               }
               if (getURLP('q'))
               {
                    $('#tipue_search_input').val(getURLP('q'));
                    getTipueSearch(0, true);
               }

               $('#tipue_search_button').click(function()
               {
                    getTipueSearch(0, true);
               });
               $(this).keyup(function(event)
               {
                    if(event.keyCode == '13')
                    {
                         getTipueSearch(0, true);
                    }
               });

               function getTipueSearch(start, replace)
               {
                    $('#tipue_search_content').hide();
                    var out = '';
                    var results = '';
                    var show_replace = false;
                    var show_stop = false;

                    var d = $('#tipue_search_input').val().toLowerCase();
                    d = $.trim(d);
                    var d_w = d.split(' ');
                    d = '';
                    for (var i = 0; i < d_w.length; i++)
                    {
                         var a_w = true;
                         for (var f = 0; f < tipuesearch_stop_words.length; f++)
                         {
                              if (d_w[i] == tipuesearch_stop_words[f])
                              {
                                   a_w = false;
                                   show_stop = true;
                              }
                         }
                         if (a_w)
                         {
                              d = d + ' ' + d_w[i];
                         }
                    }
                    d = $.trim(d);
                    d_w = d.split(' ');

                    if (d.length >= set.minimumLength)
                    {
                         if (replace)
                         {
                              var d_r = d;
                              for (var i = 0; i < d_w.length; i++)
                              {
                                   for (var f = 0; f < tipuesearch_replace.words.length; f++)
                                   {
                                        if (d_w[i] == tipuesearch_replace.words[f].word)
                                        {
                                             d = d.replace(d_w[i], tipuesearch_replace.words[f].replace_with);
                                             show_replace = true;
                                        }
                                   }
                              }
                              d_w = d.split(' ');
                         }

                         var d_t = d;
                         for (var i = 0; i < d_w.length; i++)
                         {
                              for (var f = 0; f < tipuesearch_stem.words.length; f++)
                              {
                                   if (d_w[i] == tipuesearch_stem.words[f].word)
                                   {
                                        d_t = d_t + ' ' + tipuesearch_stem.words[f].stem;
                                   }
                              }
                         }
                         d_w = d_t.split(' ');

                         var c = 0;
                         found = new Array();
                         for (var i = 0; i < tipuesearch_in.pages.length; i++)
                         {
                              var score = 1000000000;
                              var s_t = tipuesearch_in.pages[i].text;
                              for (var f = 0; f < d_w.length; f++)
                              {
                                   var pat = new RegExp(d_w[f], 'i');
                                   if (tipuesearch_in.pages[i].title.search(pat) != -1)
                                   {
                                        score -= (200000 - i);
                                   }
                                   if (tipuesearch_in.pages[i].text.search(pat) != -1)
                                   {
                                        score -= (150000 - i);
                                   }

                                   if (set.highlightTerms)
                                   {
                                        if (set.highlightEveryTerm)
                                        {
                                             var patr = new RegExp('(' + d_w[f] + ')', 'gi');
                                        }
                                        else
                                        {
                                             var patr = new RegExp('(' + d_w[f] + ')', 'i');
                                        }
                                        s_t = s_t.replace(patr, "$1");
                                   }

                                   if (tipuesearch_in.pages[i].tags.search(pat) != -1)
                                   {
                                        score -= (100000 - i);
                                   }
                              }
                              if (score < 1000000000)
                              {
                                   if (set.mode == 'static-images')
                                   {
                                        found[c++] = score + '^' + tipuesearch_in.pages[i].title + '^' + s_t + '^' + tipuesearch_in.pages[i].loc + '^' + tipuesearch_in.pages[i].image;
                                   }
                                   else
                                   {
                                        found[c++] = score + '^' + tipuesearch_in.pages[i].title + '^' + s_t + '^' + tipuesearch_in.pages[i].loc;
                                   }
                              }
                         }

                         if (c != 0)
                         {
                              if (show_replace == 1)
                              {
                                   out += '
Showing results for ' + d + '
';
                                   out += '
Show results for ' + d_r + '
';
                              }
                              if (c == 1)
                              {
                                   out += '
1 result
';
                              }
                              else
                              {
                                   c_c = c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                                   out += '
' + c_c + ' results
';
                              }

                              found.sort();
                              var l_o = 0;
                              for (var i = 0; i < found.length; i++)
                              {
                                   var fo = found[i].split('^');
                                   if (l_o >= start && l_o < set.show + start)
                                   {
                                        out += '
' +  fo[1] + '
';

                                        if (set.mode == 'static-images')
                                        {
                                             if (fo[4])
                                             {
                                                  out += '

';
                                             }
                                        }

                                        var t = fo[2];
                                        var t_d = '';
                                        var t_w = t.split(' ');
                                        if (t_w.length < set.descriptiveWords)
                                        {
                                             t_d = t;
                                        }
                                        else
                                        {
                                             for (var f = 0; f < set.descriptiveWords; f++)
                                             {
                                                  t_d += t_w[f] + ' ';
                                             }
                                        }
                                        t_d = $.trim(t_d);
                                        if (t_d.charAt(t_d.length - 1) != '.')
                                        {
                                             t_d += ' ...';
                                        }
                                        out += '
' + t_d + '
';

                                        if (set.showURL)
                                        {
                                             out += '
' + fo[3] + '
';
                                        }
                                   }
                                   l_o++;
                              }

                              if (c > set.show)
                              {
                                   var pages = Math.ceil(c / set.show);
                                   var page = (start / set.show);
                                   out += '

';

                                   if (start > 0)
                                   {
                                       out += '
« Previous
';
                                   }

                                   if (page <= 4)
                                   {
                                        var p_b = pages;
                                        if (pages > 5)
                                        {
                                             p_b = 5;
                                        }
                                        for (var f = 0; f < p_b; f++)
                                        {
                                             if (f == page)
                                             {
                                                  out += '
' + (f + 1) + '
';
                                             }
                                             else
                                             {
                                                  out += '
' + (f + 1) + '
';
                                             }
                                        }
                                   }
                                   else
                                   {
                                        var p_b = pages + 4;
                                        if (p_b > pages)
                                        {
                                             p_b = pages;
                                        }
                                        for (var f = page; f < p_b; f++)
                                        {
                                             if (f == page)
                                             {
                                                  out += '
' + (f + 1) + '
';
                                             }
                                             else
                                             {
                                                  out += '
' + (f + 1) + '
';
                                             }
                                        }
                                   }

                                   if (page + 1 != pages)
                                   {
                                       out += '
Next »
';
                                   }

                                   out += '

';
                              }
                         }
                         else
                         {
                              out += '
Nothing found...would you like to try again?

                                   <form action="/search.html">
                                   <input type="text" name="q" id="tipue_search_input" placeholder="Search for JavaScript, HTML5, etc">
                                  <input type="submit" id="tipue_search_button" value="Go!">
                                  </form>

';
                         }
                    }
                    else
                    {
                         if (show_stop)
                         {
                              out += '
Nothing found

Common words are largely ignored
';
                         }
                         else
                         {
                              out += '
Search too short
';
                              if (set.minimumLength == 1)
                              {
                                   out += '
Should be one character or more
';
                              }
                              else
                              {
                                   out += '
Should be ' + set.minimumLength + ' characters or more
';
                              }
                         }
                    }

                    $('#tipue_search_content').html(out);
                    $('#tipue_search_content').slideDown(200);

                    $('#tipue_search_replaced').click(function()
                    {
                         getTipueSearch(0, false);
                    });

                    $('.tipue_search_content_image').click(function()
                    {
                         var src_i = $(this).attr('src');
                         var id_v = $(this).attr('id');
                         var id_a = id_v.split('^');

                         var l_c_i = '
' + id_a[0] + '
';
                         l_c_i += '

';
                         l_c_i += '

';

                         if ($('#tipue_lightbox').length > 0)
                         {
                              $('#tipue_lightbox_content').html(l_c_i);
                              $('#tipue_lightbox').fadeIn();
                         }
                         else
                         {
                              var tipue_lightbox = '
' + '
' + l_c_i + '

';
                              $('body').append(tipue_lightbox);
                              $('#tipue_lightbox').fadeIn();
                         }
                    });
                    $('#tipue_lightbox').live('click', function()
                    {
                         $('#tipue_lightbox').hide();
                    });

                    $('.tipue_search_foot_box').click(function()
                    {
                         var id_v = $(this).attr('id');
                         var id_a = id_v.split('_');

                         getTipueSearch(parseInt(id_a[0]), id_a[1]);
                    });
               }

          });
     };

})(jQuery);

<commit_msg>remove old "grunt/jsSrc" directory<commit_after><|endoftext|>


<commit_before>//Tip class
export default class SiimpleTip extends React.Component
{
  //Constructor
  constructor(props)
  {
    //Call super
    super(props);

    //Set the state
    this.state = { color: null, icon: null };

    //Available icons
    this._icons = [ 'exclamation', 'question', 'hearth' ];

    //Update props
    this.componentWillReceiveProps(props);
  }

  //Parse new props
  componentWillReceiveProps(props)
  {
    //Parse the color property
    if(typeof props.color !== 'undefined' && props.color !== this.state.color)
    {
      //Change the color state value
      this.state.color = props.color;
    }

    //Parse the icon property
    if(typeof props.icon !== 'undefined' && props.icon !== this.state.icon)
    {
      //Save the icon state value
      this.state.icon = props.icon;
    }
  }

  //Render the tip element
  render()
  {
    //Create element alias
    var el = React.createElement;

    //Initialize the tip class list
    var class_list = [ 'siimple-tip' ];

    //Add the tip color
    if(typeof this.state.color === 'string')
    {
      //Append the color class
      class_list.push('siimple-tip--' + this.state.color.toLowerCase().trim());
    }

    //Add the tip icon
    if(typeof this.state.icon === 'string')
    {
      //Parse the icon value
      var icon_value = this.state.icon.toLowerCase().trim();

      //Check if this icon exists
      if(this._icons.indexOf(icon_value) !== -1)
      {
        //Append the icon class
        class_list.push('siimple-tip--' + icon_value);
      }
    }

    //Return the element
    return el('div', { className: class_list.join(' ') }, this.props.children);
  }
}
<commit_msg>src/tip.js: minor changes<commit_after>//Tip class
export default class SiimpleTip extends React.Component
{
  //Constructor
  constructor(props)
  {
    //Call super
    super(props);

    //Set the state
    this.state = { color: null, icon: null };

    //Available icons
    this._icons = [ 'exclamation', 'question', 'hearth' ];

    //Update props
    this.componentWillReceiveProps(props);
  }

  //Parse new props
  componentWillReceiveProps(props)
  {
    //Parse the color property
    if(typeof props.color !== 'undefined' && props.color !== this.state.color)
    {
      //Change the color state value
      this.state.color = props.color;
    }

    //Parse the icon property
    if(typeof props.icon !== 'undefined' && props.icon !== this.state.icon)
    {
      //Save the icon state value
      this.state.icon = props.icon;
    }
  }

  //Render the tip element
  render()
  {
    //Initialize the tip class list
    var class_list = [ 'siimple-tip' ];

    //Add the tip color
    if(typeof this.state.color === 'string')
    {
      //Append the color class
      class_list.push('siimple-tip--' + this.state.color.toLowerCase().trim());
    }

    //Add the tip icon
    if(typeof this.state.icon === 'string')
    {
      //Parse the icon value
      var icon_value = this.state.icon.toLowerCase().trim();

      //Check if this icon exists
      if(this._icons.indexOf(icon_value) !== -1)
      {
        //Append the icon class
        class_list.push('siimple-tip--' + icon_value);
      }
    }

    //Return the element
    return React.createElement('div', { className: class_list.join(' ') }, this.props.children);
  }
}
<|endoftext|>


<commit_before>import { ForceNodes, Node } from "djedi-react";
import Head from "next/head";
import React from "react";

import Link from "../components/Link";

const forced = (
  <Node uri="about/forced">
    This node appears in the Djedi sidebar even when this section is collapsed.
  </Node>
);

export default class Home extends React.Component {
  state = {
    showText: false,
  };

  toggleText = () => {
    this.setState(state => ({ showText: !state.showText }));
  };

  render() {
    const { showText } = this.state;

    return (

          <title>About us</title>

          <Link href={{ pathname: "/" }}>
            Home
          </Link>

          <Node uri="about/intro">
            This page exists to test that the Djedi sidebar stays up-to-date
            when switching pages or clicking buttons that show/hide nodes.
          </Node>

          <Node uri="about/duplicate">Duplicate node</Node>

          <button type="button" onClick={this.toggleText}>
            {showText ? "Collapse" : "Read more"}
          </button>

        {showText && (

              <Node uri="about/text">
                More text! Does this appear in the sidebar?
              </Node>

              <Node uri="about/duplicate">Duplicate node</Node>

{forced}

        )}

        <ForceNodes>{forced}</ForceNodes>

    );
  }
}
<commit_msg>Fix typo in example app<commit_after>import { ForceNodes, Node } from "djedi-react";
import Head from "next/head";
import React from "react";

import Link from "../components/Link";

const forced = (
  <Node uri="about/forced">
    This node appears in the Djedi sidebar even when this section is collapsed.
  </Node>
);

export default class About extends React.Component {
  state = {
    showText: false,
  };

  toggleText = () => {
    this.setState(state => ({ showText: !state.showText }));
  };

  render() {
    const { showText } = this.state;

    return (

          <title>About us</title>

          <Link href={{ pathname: "/" }}>
            Home
          </Link>

          <Node uri="about/intro">
            This page exists to test that the Djedi sidebar stays up-to-date
            when switching pages or clicking buttons that show/hide nodes.
          </Node>

          <Node uri="about/duplicate">Duplicate node</Node>

          <button type="button" onClick={this.toggleText}>
            {showText ? "Collapse" : "Read more"}
          </button>

        {showText && (

              <Node uri="about/text">
                More text! Does this appear in the sidebar?
              </Node>

              <Node uri="about/duplicate">Duplicate node</Node>

{forced}

        )}

        <ForceNodes>{forced}</ForceNodes>

    );
  }
}
<|endoftext|>


<commit_before>/**
 * @fileoverview 트리에 이벤트를 등록한다
 *
 * @author FE개발팀 이제인(jein.yi@nhnent.com)
 * @constructor
 */

ne.component.Tree.TreeEvent = ne.util.defineClass(/** @lends Event.prototype */{
    /**
     * 더블클릭을 판별하는 필드를 세팅한다.
     *
     * **/
    init: function() {

        this.doubleClickTimer = null;

    },
    /**
     * 이벤트를 추가한다, 이벤트가 더블클릭인지 아닌지에 따라 다르게 처리한다.
     *
     * @param {Object} target 이벤트가 등록되고 이벤트 핸들러의 컨텍스트가 될 객체
     * @param {String} type 이벤트 명
     * @param {Function} callback 이벤트 핸들러
     * @private
     *
     * **/
    add: function(target, type, callback) {

        if (type === 'doubleclick') {
            this._addDoubleClickEvent(target, type, callback);
        } else {
            this._addEventListener(target, type, callback);
        }

    },
    /**
     * 더블클릭이 아닌 일반적인 이벤트를 추가한다.
     *
     * @param {Object} target 이벤트가 등록되고 이벤트 핸들러의 컨텍스트가 될 객체
     * @param {String} type 이벤트 명
     * @param {Function} callback 이벤트 핸들러
     * @private
     *
     * **/
    _addEventListener: function(target, type, callback) {

        ne.component.Tree.treeUtils.addEventListener(target, type, ne.util.bind(this._onClick, this, callback, type));

    },
    /**
     * 일반 클릭에 대한 핸들러 추가
     *
     * @param {Object} e 이벤트 객체
     * @private
     */
    _onClick: function(callback, type, e) {
        e = e || window.event;
        var eventTarget = e.target || e.srcElement,
            targetTag = eventTarget.tagName.toLowerCase(),
            paths = null;

        if (this._checkRightButton(e.which || e.button)) {
            ne.component.Tree.treeUtils.stopEvent(e);
            return;
        }

        if (targetTag === 'button') {
            var parent = eventTarget.parentNode;
            var valueElement = parent;
            paths = valueElement.getAttribute('path');
        }
        else {
            paths = eventTarget.getAttribute('path');
            if (!paths) {
                paths = eventTarget.parentNode.getAttribute('path');
            }
        }

        ne.util.extend(e, {
            eventType: type,
            isButton: targetTag === 'button',
            target: eventTarget,
            paths: paths
        });
        callback(e);
    },
    /**
     * 더블클릭 이벤트를 추가한다.
     *
     * @param {Object} target 이벤트가 등록되고 이벤트 핸들러의 컨텍스트가 될 객체
     * @param {String} type 이벤트 명
     * @param {Function} callback 이벤트 핸들러
     * @private
     *
     * **/
    _addDoubleClickEvent: function(target, type, callback) {
        ne.component.Tree.treeUtils.addEventListener(target, 'click', ne.util.bind(this._onDeobleClick, this, callback, type));

    },
    /**
     * 더블클릭 핸들러
     * @param {Function} callback 이벤트 콜백
     * @param {String} type 이벤트 타입
     * @param {Event} e 이벤트객체
     * @private
     */
    _onDeobleClick: function(callback, type, e) {

        e = e || window.event;
        var eventTarget = e.target || e.srcElement,
            path = eventTarget.getAttribute('path') || eventTarget.parentNode.getAttribute('path'),
            eventTarget = eventTarget.parentNode.getAttribute('path') ? eventTarget.parentNode : eventTarget,
            text = eventTarget.innerText;

        if (this._checkRightButton(e.which || e.button)) {
            this.doubleClickTimer = null;
            ne.component.Tree.treeUtils.stopEvent(e);
            return;
        }

        if (!(path || isNaN(path))) {
            this.doubleClickTimer = null;
            return;
        }

        if (this.doubleClickTimer) {
            callback({
                eventType: type,
                target: eventTarget,
                path: path,
                text: text
            });
            this.doubleClickTimer = null;
        } else {
            this.doubleClickTimer = setTimeout(ne.util.bind(function() {
                this.doubleClickTimer = null;
            }, this), 400);
        }
    },
    /**
     * 마우스 우클릭인지 확인한다.
     *
     * @param {Number} btnNumber 마우스 버튼 값
     * @private
     *
     * **/
    _checkRightButton: function(btnNumber) {

        var isRightButton = (btnNumber == 3 || btnNumber == 2);
        return isRightButton;

    }
});
<commit_msg>js file update<commit_after>/**
 * @fileoverview 트리에 이벤트를 등록한다
 *
 * @author FE개발팀 이제인(jein.yi@nhnent.com)
 * @constructor
 */

ne.component.Tree.TreeEvent = ne.util.defineClass(/** @lends Event.prototype */{
    /**
     * 더블클릭을 판별하는 필드를 세팅한다.
     *
     * **/
    init: function() {

        this.doubleClickTimer = null;

    },
    /**
     * 이벤트를 추가한다, 이벤트가 더블클릭인지 아닌지에 따라 다르게 처리한다.
     *
     * @param {Object} target 이벤트가 등록되고 이벤트 핸들러의 컨텍스트가 될 객체
     * @param {String} type 이벤트 명
     * @param {Function} callback 이벤트 핸들러
     * @private
     *
     * **/
    add: function(target, type, callback) {

        if (type === 'doubleclick') {
            this._addDoubleClickEvent(target, type, callback);
        } else {
            this._addEventListener(target, type, callback);
        }

    },
    /**
     * 더블클릭이 아닌 일반적인 이벤트를 추가한다.
     *
     * @param {Object} target 이벤트가 등록되고 이벤트 핸들러의 컨텍스트가 될 객체
     * @param {String} type 이벤트 명
     * @param {Function} callback 이벤트 핸들러
     * @private
     *
     * **/
    _addEventListener: function(target, type, callback) {

        ne.component.Tree.treeUtils.addEventListener(target, type, ne.util.bind(this._onClick, this, callback, type));

    },
    /**
     * 일반 클릭에 대한 핸들러 추가
     *
     * @param {Object} e 이벤트 객체
     * @private
     */
    _onClick: function(callback, type, e) {
        e = e || window.event;
        var eventTarget = e.target || e.srcElement,
            targetTag = eventTarget.tagName.toLowerCase(),
            paths = null;

        if (this._checkRightButton(e.which || e.button)) {
            ne.component.Tree.treeUtils.stopEvent(e);
            return;
        }

        if (targetTag === 'button') {
            var parent = eventTarget.parentNode;
            var valueElement = parent;
            paths = valueElement.getAttribute('path');
        }
        else {
            paths = eventTarget.getAttribute('path');
            if (!paths) {
                paths = eventTarget.parentNode.getAttribute('path');
            }
        }

        ne.util.extend(e, {
            eventType: type,
            isButton: targetTag === 'button',
            target: eventTarget,
            paths: paths
        });
        callback(e);
    },
    /**
     * 더블클릭 이벤트를 추가한다.
     *
     * @param {Object} target 이벤트가 등록되고 이벤트 핸들러의 컨텍스트가 될 객체
     * @param {String} type 이벤트 명
     * @param {Function} callback 이벤트 핸들러
     * @private
     *
     * **/
    _addDoubleClickEvent: function(target, type, callback) {
        ne.component.Tree.treeUtils.addEventListener(target, 'click', ne.util.bind(this._onDeobleClick, this, callback, type));

    },
    /**
     * 더블클릭 핸들러
     * @param {Function} callback 이벤트 콜백
     * @param {String} type 이벤트 타입
     * @param {Event} e 이벤트객체
     * @private
     */
    _onDeobleClick: function(callback, type, e) {

        e = e || window.event;
        var eventTarget = e.target || e.srcElement,
            path = eventTarget.getAttribute('path') || eventTarget.parentNode.getAttribute('path'),
            eventTarget = eventTarget.parentNode.getAttribute('path') ? eventTarget.parentNode : eventTarget,
            text = eventTarget.innerText;

        if (this._checkRightButton(e.which || e.button)) {
            this.doubleClickTimer = null;
            ne.component.Tree.treeUtils.stopEvent(e);
            return;
        }

        if (!(path || isNaN(path))) {
            this.doubleClickTimer = null;
            return;
        }

        if (this.targetPath && this.targetPath !== path) {
            this.doubleClickTimer = null;
        }

        if (this.doubleClickTimer) {
            callback({
                eventType: type,
                target: eventTarget,
                path: path,
                text: text
            });
            this.doubleClickTimer = null;
        } else {
            this.doubleClickTimer = setTimeout(ne.util.bind(function() {
                this.doubleClickTimer = null;
            }, this), 500);
        }

        this.targetPath = path;
    },
    /**
     * 마우스 우클릭인지 확인한다.
     *
     * @param {Number} btnNumber 마우스 버튼 값
     * @private
     *
     * **/
    _checkRightButton: function(btnNumber) {

        var isRightButton = (btnNumber == 3 || btnNumber == 2);
        return isRightButton;

    }
});
<|endoftext|>