<commit_before>'use strict';

/** Used to map method names to their aliases. */
var aliasMap = {
  'assign': ['extend'],
  'callback': ['iteratee'],
  'every': ['all'],
  'filter': ['select'],
  'find': ['detect'],
  'first': ['head'],
  'forEach': ['each'],
  'forEachRight': ['eachRight'],
  'includes': ['contains', 'include'],
  'map': ['collect'],
  'reduce': ['foldl', 'inject'],
  'reduceRight': ['foldr'],
  'rest': ['tail'],
  'some': ['any'],
  'uniq': ['unique'],
  'zipObject': ['object']
};

/** Used to map ary to method names. */
var aryMethodMap = {
  1: (
    'attempt,clone,create,curry,flatten,invert,max,memoize,min,mixin,sample,template,' +
    'trim,trimLeft,trimRight,uniq,words').split(','),
  2: (
    'add,after,ary,assign,at,before,bind,bindKey,chunk,countBy,curryN,debounce,defaults,' +
    'delay,difference,drop,dropRight,dropRightWhile,dropWhile,endsWith,every,' +
    'filter,find,findIndex,findKey,findLast,findLastIndex,findLastKey,findWhere,' +
    'forEach,forEachRight,forIn,forInRight,forOwn,forOwn,forOwnRight,groupBy,' +
    'has,includes,indexBy,indexOf,intersection,invoke,isEqual,isMatch,lastIndexOf,' +
    'map,mapValues,matchesProperty,maxBy,merge,minBy,omit,pad,padLeft,padRight,' +
    'parseInt,partition,pick,pluck,pull,pullAt,random,range,rearg,reject,remove,' +
    'repeat,result,runInContext,some,sortBy,sortByAll,sortedIndex,sortedLastIndex,' +
    'startsWith,take,takeRight,takeRightWhile,takeWhile,throttle,times,trunc,' +
    'union,uniqBy,uniqueId,where,without,wrap,xor,zip,zipObject').split(','),
  3:
    'slice,reduce,reduceRight,transform'.split(','),
  4:
    ['fill', 'inRange']
};

/** Used to map ary to rearg configs. */
var aryReargMap = {
  2: [1, 0],
  3: [2, 0, 1],
  4: [3, 2, 0, 1]
};

/** Used to map keys to other keys. */
var keyMap = {
  'curryN': 'curry',
  'maxBy': 'max',
  'minBy': 'min',
  'uniqBy': 'uniq'
};

/** Used to track methods that skip `_.rearg`. */
var skipReargMap = {
  'range': true,
  'random': true
};

/*----------------------------------------------------------------------------*/

/**
 * Converts `func` of `name` to an auto-curried iteratee-first version. If `name`
 * is an object the methods on it will be converted and the object returned.
 *
 * @param {string} name The name of the function to wrap.
 * @param {Function} func The function to wrap.
 * @returns {Function|Object} Returns the new converted function or object of
 *  converted functions.
 */
function convert(name, func) {
  if (!func) {
    func = name;
    name = null;
  }
  var type = typeof func,
      isLib = type == 'function' && typeof func.VERSION == 'string',
      isObj = func != null && (type == 'function' || type == 'object');

  if (name == null && !isObj) {
    throw new TypeError;
  }
  var _ = isLib ? func : {
    'ary': require('lodash-compat/function/ary'),
    'callback': require('lodash-compat/utility/callback'),
    'curry': require('lodash-compat/function/curry'),
    'rearg': require('lodash-compat/function/rearg')
  };

  var wrap = function(name, func) {
    var cap = 0,
        capLimit = 5;

    while (++cap < capLimit) {
      var names = aryMethodMap[cap],
          nameIndex = -1,
          namesLength = names.length;

      while (++nameIndex < namesLength) {
        if (names[nameIndex] === name) {
          if (cap > 1 && !skipReargMap[name]) {
            func = _.rearg(func, aryReargMap[cap]);
          }
          return _.curry(_.ary(func, cap), cap);
        }
      }
    }
    return func;
  };

  // Disable custom `_.indexOf` use by these methods.
  if (isLib) {
    _.mixin({
      'difference': require('lodash-compat/array/difference'),
      'includes': require('lodash-compat/collection/includes'),
      'intersection': require('lodash-compat/array/intersection'),
      'omit': require('lodash-compat/object/omit'),
      'pull': require('lodash-compat/array/pull'),
      'union': require('lodash-compat/array/union'),
      'uniq': require('lodash-compat/array/uniq'),
      'without': require('lodash-compat/array/without'),
      'xor': require('lodash-compat/array/xor')
    });
  }
  if (!(isLib || isObj)) {
    return wrap(name, func);
  }
  var ary = _.ary,
      callback = _.callback,
      cap = 0,
      capLimit = 5,
      pairs = [];

  pairs.push(['callback', function(func, thisArg, argCount) {
    argCount = argCount > 2 ? (argCount - 2) : 1;
    return ary(callback(func, thisArg), argCount);
  }]);

  pairs.push(['iteratee', pairs[0][1]]);

  while (++cap < capLimit) {
    // Iterate over methods for the current ary cap.
    var names = aryMethodMap[cap],
        nameIndex = -1,
        namesLength = names.length;

    while (++nameIndex < namesLength) {
      var otherName = names[nameIndex],
          fn = _[keyMap[otherName] || otherName];

      if (fn) {
        // Wrap the lodash method and its aliases.
        var wrapped = wrap(otherName, fn),
            allIndex = -1,
            allNames = [otherName].concat(aliasMap[otherName] || []),
            allLength = allNames.length;

        while (++allIndex < allLength) {
          pairs.push([allNames[allIndex], wrapped]);
        }
      }
    }
  }
  var pairsIndex = -1,
      pairsLength = pairs.length;

  // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  while (++pairsIndex < pairsLength) {
    var pair = pairs[pairsIndex];
    _[pair[0]] = pair[1];
  }
  return _;
}

module.exports = convert;
<commit_msg>Add `sortByOrder` to `aryMethodMap` and remove `runInContext` from it.<commit_after>'use strict';

/** Used to map method names to their aliases. */
var aliasMap = {
  'assign': ['extend'],
  'callback': ['iteratee'],
  'every': ['all'],
  'filter': ['select'],
  'find': ['detect'],
  'first': ['head'],
  'forEach': ['each'],
  'forEachRight': ['eachRight'],
  'includes': ['contains', 'include'],
  'map': ['collect'],
  'reduce': ['foldl', 'inject'],
  'reduceRight': ['foldr'],
  'rest': ['tail'],
  'some': ['any'],
  'uniq': ['unique'],
  'zipObject': ['object']
};

/** Used to map ary to method names. */
var aryMethodMap = {
  1: (
    'attempt,clone,create,curry,flatten,invert,max,memoize,min,mixin,sample,template,' +
    'trim,trimLeft,trimRight,uniq,words').split(','),
  2: (
    'add,after,ary,assign,at,before,bind,bindKey,chunk,countBy,curryN,debounce,defaults,' +
    'delay,difference,drop,dropRight,dropRightWhile,dropWhile,endsWith,every,' +
    'filter,find,findIndex,findKey,findLast,findLastIndex,findLastKey,findWhere,' +
    'forEach,forEachRight,forIn,forInRight,forOwn,forOwn,forOwnRight,groupBy,' +
    'has,includes,indexBy,indexOf,intersection,invoke,isEqual,isMatch,lastIndexOf,' +
    'map,mapValues,matchesProperty,maxBy,merge,minBy,omit,pad,padLeft,padRight,' +
    'parseInt,partition,pick,pluck,pull,pullAt,random,range,rearg,reject,remove,' +
    'repeat,result,some,sortBy,sortByAll,sortedIndex,sortedLastIndex,startsWith,' +
    'take,takeRight,takeRightWhile,takeWhile,throttle,times,trunc,union,uniqBy,' +
    'uniqueId,where,without,wrap,xor,zip,zipObject').split(','),
  3:
    'slice,sortByOrder,reduce,reduceRight,transform'.split(','),
  4:
    ['fill', 'inRange']
};

/** Used to map ary to rearg configs. */
var aryReargMap = {
  2: [1, 0],
  3: [2, 0, 1],
  4: [3, 2, 0, 1]
};

/** Used to map keys to other keys. */
var keyMap = {
  'curryN': 'curry',
  'maxBy': 'max',
  'minBy': 'min',
  'uniqBy': 'uniq'
};

/** Used to track methods that skip `_.rearg`. */
var skipReargMap = {
  'range': true,
  'random': true
};

/*----------------------------------------------------------------------------*/

/**
 * Converts `func` of `name` to an auto-curried iteratee-first version. If `name`
 * is an object the methods on it will be converted and the object returned.
 *
 * @param {string} name The name of the function to wrap.
 * @param {Function} func The function to wrap.
 * @returns {Function|Object} Returns the new converted function or object of
 *  converted functions.
 */
function convert(name, func) {
  if (!func) {
    func = name;
    name = null;
  }
  var type = typeof func,
      isLib = type == 'function' && typeof func.VERSION == 'string',
      isObj = func != null && (type == 'function' || type == 'object');

  if (name == null && !isObj) {
    throw new TypeError;
  }
  var _ = isLib ? func : {
    'ary': require('lodash-compat/function/ary'),
    'callback': require('lodash-compat/utility/callback'),
    'curry': require('lodash-compat/function/curry'),
    'rearg': require('lodash-compat/function/rearg')
  };

  var wrap = function(name, func) {
    var cap = 0,
        capLimit = 5;

    while (++cap < capLimit) {
      var names = aryMethodMap[cap],
          nameIndex = -1,
          namesLength = names.length;

      while (++nameIndex < namesLength) {
        if (names[nameIndex] === name) {
          if (cap > 1 && !skipReargMap[name]) {
            func = _.rearg(func, aryReargMap[cap]);
          }
          return _.curry(_.ary(func, cap), cap);
        }
      }
    }
    return func;
  };

  // Disable custom `_.indexOf` use by these methods.
  if (isLib) {
    _.mixin({
      'difference': require('lodash-compat/array/difference'),
      'includes': require('lodash-compat/collection/includes'),
      'intersection': require('lodash-compat/array/intersection'),
      'omit': require('lodash-compat/object/omit'),
      'pull': require('lodash-compat/array/pull'),
      'union': require('lodash-compat/array/union'),
      'uniq': require('lodash-compat/array/uniq'),
      'without': require('lodash-compat/array/without'),
      'xor': require('lodash-compat/array/xor')
    });
  }
  if (!(isLib || isObj)) {
    return wrap(name, func);
  }
  var ary = _.ary,
      callback = _.callback,
      cap = 0,
      capLimit = 5,
      pairs = [];

  pairs.push(['callback', function(func, thisArg, argCount) {
    argCount = argCount > 2 ? (argCount - 2) : 1;
    return ary(callback(func, thisArg), argCount);
  }]);

  pairs.push(['iteratee', pairs[0][1]]);

  while (++cap < capLimit) {
    // Iterate over methods for the current ary cap.
    var names = aryMethodMap[cap],
        nameIndex = -1,
        namesLength = names.length;

    while (++nameIndex < namesLength) {
      var otherName = names[nameIndex],
          fn = _[keyMap[otherName] || otherName];

      if (fn) {
        // Wrap the lodash method and its aliases.
        var wrapped = wrap(otherName, fn),
            allIndex = -1,
            allNames = [otherName].concat(aliasMap[otherName] || []),
            allLength = allNames.length;

        while (++allIndex < allLength) {
          pairs.push([allNames[allIndex], wrapped]);
        }
      }
    }
  }
  var pairsIndex = -1,
      pairsLength = pairs.length;

  // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  while (++pairsIndex < pairsLength) {
    var pair = pairs[pairsIndex];
    _[pair[0]] = pair[1];
  }
  return _;
}

module.exports = convert;
<|endoftext|>


<commit_before>SubsManager = function (options) {
  var self = this;
  self.options = options || {};
  // maxiumum number of subscriptions are cached
  self.options.cacheLimit = self.options.cacheLimit || 10;
  // maximum time, subscription stay in the cache
  self.options.expireIn = self.options.expireIn || 5;
  // alternative subscription method
  self.subscribe = self.options.subscribe || Meteor.subscribe && Meteor.subscribe.bind(Meteor)

  self._cacheMap = {};
  self._cacheList = [];
  self.ready = false;
  self.dep = new Deps.Dependency();

  self.computation = self._registerComputation();
};

SubsManager.prototype.subscribe = function() {
  var self = this;
  if(Meteor.isClient) {
    this._addSub(arguments);

    return {
      ready: function() {
        self.dep.depend();
        return self.ready;
      }
    };
  } else {
    // to support fast-render
    if(Meteor.subscribe) {
      return Meteor.subscribe.apply(Meteor, arguments);
    }
  }
};

SubsManager.prototype._addSub = function(args) {
  var self = this;
  var hash = EJSON.stringify(args);
  args = _.toArray(args);
  if(!self._cacheMap[hash]) {
    var sub = {
      args: args,
      hash: hash
    };

    this._handleError(sub);

    self._cacheMap[hash] = sub;
    self._cacheList.push(sub);

    self.ready = false;
    // no need to interfere with the current computation
    self._reRunSubs();
  }

  // add the current sub to the top of the list
  var sub = self._cacheMap[hash];
  sub.updated = (new Date).getTime();

  var index = self._cacheList.indexOf(sub);
  self._cacheList.splice(index, 1);
  self._cacheList.push(sub);
};

SubsManager.prototype._reRunSubs = function() {
  var self = this;

  if(Deps.currentComputation) {
    Deps.afterFlush(function() {
      self.computation.invalidate();
    });
  } else {
    self.computation.invalidate();
  }
};

SubsManager.prototype._applyCacheLimit = function () {
  var self = this;
  var overflow = self._cacheList.length - self.options.cacheLimit;
  if(overflow > 0) {
    var removedSubs = self._cacheList.splice(0, overflow);
    _.each(removedSubs, function(sub) {
      delete self._cacheMap[sub.hash];
    });
  }
};

SubsManager.prototype._applyExpirations = function() {
  var self = this;
  var newCacheList = [];

  var expirationTime = (new Date).getTime() - self.options.expireIn * 60 * 1000;
  _.each(self._cacheList, function(sub) {
    if(sub.updated >= expirationTime) {
      newCacheList.push(sub);
    } else {
      delete self._cacheMap[sub.hash];
    }
  });

  self._cacheList = newCacheList;
};

SubsManager.prototype._registerComputation = function() {
  var self = this;
  var computation = Deps.autorun(function() {
    self._applyExpirations();
    self._applyCacheLimit();

    var ready = true;
    _.each(self._cacheList, function(sub) {
      sub.ready = self.subscribe.apply(null, sub.args).ready();
      ready = ready && sub.ready;
    });

    if(ready) {
      self.ready = true;
      self.dep.changed();
    }
  });

  return computation;
};

SubsManager.prototype._createIdentifier = function(args) {
  var tmpArgs = _.map(args, function(value) {
    if(typeof value == "string") {
      return '"' + value + '"';
    } else {
      return value;
    }
  });

  return tmpArgs.join(', ');
};

SubsManager.prototype._handleError = function(sub) {
  var args = sub.args;
  var lastElement = _.last(args);
  sub.identifier = this._createIdentifier(args);

  if(!lastElement) {
    args.push({onError: errorHandlingLogic});
  } else if(typeof lastElement == "function") {
    args.pop();
    args.push({onReady: lastElement, onError: errorHandlingLogic});
  } else if(typeof lastElement.onError == "function") {
    var originalOnError = lastElement.onError;
    lastElement.onError = function(err) {
      errorHandlingLogic(err);
      originalOnError(err);
    };
  } else if(typeof lastElement.onReady == "function") {
    lastElement.onError = errorHandlingLogic;
  } else {
    args.push({onError: errorHandlingLogic});
  }

  function errorHandlingLogic (err) {
    console.log("Error invoking SubsManager.subscribe(%s): ", sub.identifier , err.reason);
    // expire this sub right away.
    // Then expiration machanism will take care of the sub removal
    sub.updated = new Date(1);
  }
};

SubsManager.prototype.reset = function() {
  var self = this;
  var oldComputation = self.computation;
  self.computation = self._registerComputation();

  // invalidate the new compuation and it will fire new subscriptions
  self.computation.invalidate();

  // after above invalidation completed, fire stop the old computation
  // which then send unsub messages
  // mergeBox will correct send changed data and there'll be no flicker
  Deps.afterFlush(function() {
    oldComputation.stop();
  });
};

SubsManager.prototype.clear = function() {
  this._cacheList = [];
  this._cacheMap = [];
  this._reRunSubs();
};
<commit_msg>tap-18n, connection<commit_after>SubsManager = function (options) {
  var self = this;
  self.options = options || {};
  // maxiumum number of subscriptions are cached
  self.options.cacheLimit = self.options.cacheLimit || 10;
  // maximum time, subscription stay in the cache
  self.options.expireIn = self.options.expireIn || 5;
  // alternative subscription method
  self.subscribeFunc = self.options.subscribe || Meteor.subscribe && Meteor.subscribe.bind(Meteor)

  self._cacheMap = {};
  self._cacheList = [];
  self.ready = false;
  self.dep = new Deps.Dependency();

  self.computation = self._registerComputation();
};

SubsManager.prototype.subscribe = function() {
  var self = this;
  if(Meteor.isClient) {
    this._addSub(arguments);

    return {
      ready: function() {
        self.dep.depend();
        return self.ready;
      }
    };
  } else {
    // to support fast-render
    if(Meteor.subscribe) {
      return Meteor.subscribe.apply(Meteor, arguments);
    }
  }
};

SubsManager.prototype._addSub = function(args) {
  var self = this;
  var hashArgs;
  args = _.toArray(args);
  if (args.length > 0 && _.isObject(args[0])) {
    hashArgs = args.slice(1);
  } else {
    hashArgs = args;
  }
  var hash = EJSON.stringify(hashArgs);
  if(!self._cacheMap[hash]) {
    var sub = {
      args: args,
      hash: hash
    };

    this._handleError(sub);

    self._cacheMap[hash] = sub;
    self._cacheList.push(sub);

    self.ready = false;
    // no need to interfere with the current computation
    // console.log(['cache miss, will rerun', hash]);
    self._reRunSubs();
  }

  // add the current sub to the top of the list
  var sub = self._cacheMap[hash];
  sub.updated = (new Date).getTime();

  var index = self._cacheList.indexOf(sub);
  self._cacheList.splice(index, 1);
  self._cacheList.push(sub);
};

SubsManager.prototype._reRunSubs = function() {
  var self = this;
  // console.log(['rerun', self.computation.stopped, self.computation]);

  if(Deps.currentComputation) {
    Deps.afterFlush(function() {
      self.computation.invalidate();
    });
  } else {
    self.computation.invalidate();
  }
};

SubsManager.prototype._applyCacheLimit = function () {
  var self = this;
  var overflow = self._cacheList.length - self.options.cacheLimit;
  if(overflow > 0) {
    var removedSubs = self._cacheList.splice(0, overflow);
    _.each(removedSubs, function(sub) {
      delete self._cacheMap[sub.hash];
    });
  }
};

SubsManager.prototype._applyExpirations = function() {
  var self = this;
  var newCacheList = [];

  var expirationTime = (new Date).getTime() - self.options.expireIn * 60 * 1000;
  _.each(self._cacheList, function(sub) {
    if(sub.updated >= expirationTime) {
      newCacheList.push(sub);
    } else {
      delete self._cacheMap[sub.hash];
    }
  });

  self._cacheList = newCacheList;
};

SubsManager.prototype._registerComputation = function() {
  var self = this;
  var computation = Deps.autorun(function() {
    // console.log('subsman fire');
    self._applyExpirations();
    self._applyCacheLimit();

    var ready = true;
    _.each(self._cacheList, function(sub) {
      sub.ready = self.subscribeFunc.apply(null, sub.args).ready();
      ready = ready && sub.ready;
    });

    if(ready) {
      self.ready = true;
      self.dep.changed();
    }
  });

  return computation;
};

SubsManager.prototype._createIdentifier = function(args) {
  var tmpArgs = _.map(args, function(value) {
    if(typeof value == "string") {
      return '"' + value + '"';
    } else {
      return value;
    }
  });

  return tmpArgs.join(', ');
};

SubsManager.prototype._handleError = function(sub) {
  var args = sub.args;
  var lastElement = _.last(args);
  sub.identifier = this._createIdentifier(args);

  if(!lastElement) {
    args.push({onError: errorHandlingLogic});
  } else if(typeof lastElement == "function") {
    args.pop();
    args.push({onReady: lastElement, onError: errorHandlingLogic});
  } else if(typeof lastElement.onError == "function") {
    var originalOnError = lastElement.onError;
    lastElement.onError = function(err) {
      errorHandlingLogic(err);
      originalOnError(err);
    };
  } else if(typeof lastElement.onReady == "function") {
    lastElement.onError = errorHandlingLogic;
  } else {
    args.push({onError: errorHandlingLogic});
  }

  function errorHandlingLogic (err) {
    console.log("Error invoking SubsManager.subscribe(%s): ", sub.identifier , err.reason);
    // expire this sub right away.
    // Then expiration machanism will take care of the sub removal
    sub.updated = new Date(1);
  }
};

SubsManager.prototype.reset = function() {
  var self = this;
  var oldComputation = self.computation;
  self.computation = self._registerComputation();

  // invalidate the new compuation and it will fire new subscriptions
  self.computation.invalidate();

  // after above invalidation completed, fire stop the old computation
  // which then send unsub messages
  // mergeBox will correct send changed data and there'll be no flicker
  Deps.afterFlush(function() {
    oldComputation.stop();
  });
};

SubsManager.prototype.clear = function() {
  this._cacheList = [];
  this._cacheMap = [];
  this._reRunSubs();
};
<|endoftext|>


<commit_before> /*
  * Specs for the Utils class
  */

describe("Utils", function() {

  var utils = new THREEGRAPHS.Utils( );

  it("should check if it's a touch device", function( ) {
    var uagent = navigator.userAgent.toLowerCase( );
    if ( uagent.search("iphone") > -1 ){
      expect( utils.isTouchDevice ( ) ).toBeTruthy();
    }else{
      expect( utils.isTouchDevice ( ) ).toBeFalsy();
    }
  });

  it("should calculate the luminance of a colour", function( ) {
    expect( utils.colorLuminance('d17100',0.5) ).toEqual( 'ffaa00' );
  });

  it("should get the maximal value in a 2-dimensional array", function( ) {
    expect( utils.getMaxArr([[5,3,1,12],[7,2,4]]) ).toEqual( 12 );
  });

  it("should get the minumal value in a 2-dimensional array", function( ) {
    expect( utils.getMinArr([[5,3,1,12],[7,2,4]]) ).toEqual( 1 );
  });

  it("should calculate the round of a max number", function( ) {
    expect( utils.getRoundMax(98) ).toEqual( 100 );
  });

  it("should count the sum of all elements in a two dimentional array", function( ) {
    expect( utils.getTotalArr([[5,3,1,12],[7,2,4]]) ).toEqual( 34 );
  });

  it("should initiate the legend div", function( ) {
    var data = {  cols: [ { name:"2010", color:"d17100" },
                          { name:"2011", color:"d9bd00" } ],
                  rows: [ { name: "Product 1" } ]
                };
    var el = document.createElement('div');
    utils.initLegend(el, data);
    var col1 = el.getElementsByTagName("div");
    expect( col1[0].style.backgroundColor ).toEqual( 'rgb(209, 113, 0)' );
  });

  it("should generate the Three.js mouse controls", function( ) {
    var renderer = new THREE.WebGLRenderer( { antialias: true } );
    var camera = new THREE.PerspectiveCamera( 60,
                                        window.innerWidth/window.innerHeight,
                                        1,
                                        5000 );
    var controls = utils.mouseControls ( renderer, camera, 100, 1000 );
    expect( controls.minDistance ).toEqual( 100 );
  });

  it("should detect the browser", function( ){
    var agent = navigator.userAgent;
    var canSupport = 0;
    if ( agent.indexOf('Firefox') != -1 ){
      canSupport = 1;
      if ( parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Firefox') + 8)) >= 4 ){
        canSupport = 2;
      }
    }
    if ( agent.indexOf('Chrome') != -1 ){
      canSupport = 1;
      if ( parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Chrome') + 7).split(' ')[0]) >= 7 ){
        canSupport = 2;
      }
    }
    if ( agent.indexOf('Safari') != -1 ){
      canSupport = 1;
      if ( parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Version') + 8).split(' ')[0]) >= 5.1 ){
        canSupport = 2;
      }
    }
    if ( navigator.appName.indexOf("Internet Explorer")!=-1 ){
      if ( navigator.appVersion.indexOf("MSIE 9") == -1 && navigator.appVersion.indexOf("MSIE 10") == -1 ) canSupport = 1;
      if ( navigator.appVersion.indexOf("MSIE 11") == -1 ) canSupport = 2;
    }

    if ( canSupport == 0 ){
      expect( utils.detectRenderer() ).toEqual( 'none' );
    } else if ( canSupport == 1 ){
      expect( utils.detectRenderer() ).toEqual( 'canvas' );
    } else if ( canSupport == 2 ){
      expect( utils.detectRenderer() ).toEqual( 'webgl' );
    }

  });

});

 /*
  * Specs for the Bar Cubes class
  */

describe("Bar Cube", function() {

  var scene = new THREE.Scene();

  it ( 'should create a new bar object and has a standart size on the x axes', function () {
    var label = document.createElement('div');
    var nCube = new THREEGRAPHS.BarCube( "d9bd00", 0, 0, 7, "ffffff", 'full', false, { row:"row", col:"col" }, 0, 10, 10 );
    nCube.addBar ( scene );
    expect ( nCube.barobj.geometry.width ).toEqual( THREEGRAPHS.Settings.squareSize );
  });

});

 /*
  * Specs for the Bar Cubes class
  */

describe("Pie Parts", function() {

  var scene = new THREE.Scene();

  it ( 'should create a new pie object', function () {
    var label = document.createElement('div');
    var pieP = new THREEGRAPHS.PiePart( 7, 20, 500, 0, {x:0,y:0},
                                        "d9bd00", "ffffff", 'full', false,
                                        { col:"col" } );
    pieP.addPie ( scene );
    expect ( pieP.pieobj.geometry ).toBeDefined;
  });

});<commit_msg>Refactored the bar object tests. Added extra test<commit_after> /*
  * Specs for the Utils class
  */

describe("Utils", function() {

  var utils = new THREEGRAPHS.Utils( );

  it("should check if it's a touch device", function( ) {
    var uagent = navigator.userAgent.toLowerCase( );
    if ( uagent.search("iphone") > -1 ){
      expect( utils.isTouchDevice ( ) ).toBeTruthy();
    }else{
      expect( utils.isTouchDevice ( ) ).toBeFalsy();
    }
  });

  it("should calculate the luminance of a colour", function( ) {
    expect( utils.colorLuminance('d17100',0.5) ).toEqual( 'ffaa00' );
  });

  it("should get the maximal value in a 2-dimensional array", function( ) {
    expect( utils.getMaxArr([[5,3,1,12],[7,2,4]]) ).toEqual( 12 );
  });

  it("should get the minumal value in a 2-dimensional array", function( ) {
    expect( utils.getMinArr([[5,3,1,12],[7,2,4]]) ).toEqual( 1 );
  });

  it("should calculate the round of a max number", function( ) {
    expect( utils.getRoundMax(98) ).toEqual( 100 );
  });

  it("should count the sum of all elements in a two dimentional array", function( ) {
    expect( utils.getTotalArr([[5,3,1,12],[7,2,4]]) ).toEqual( 34 );
  });

  it("should initiate the legend div", function( ) {
    var data = {  cols: [ { name:"2010", color:"d17100" },
                          { name:"2011", color:"d9bd00" } ],
                  rows: [ { name: "Product 1" } ]
                };
    var el = document.createElement('div');
    utils.initLegend(el, data);
    var col1 = el.getElementsByTagName("div");
    expect( col1[0].style.backgroundColor ).toEqual( 'rgb(209, 113, 0)' );
  });

  it("should generate the Three.js mouse controls", function( ) {
    var renderer = new THREE.WebGLRenderer( { antialias: true } );
    var camera = new THREE.PerspectiveCamera( 60,
                                        window.innerWidth/window.innerHeight,
                                        1,
                                        5000 );
    var controls = utils.mouseControls ( renderer, camera, 100, 1000 );
    expect( controls.minDistance ).toEqual( 100 );
  });

  it("should detect the browser", function( ){
    var agent = navigator.userAgent;
    var canSupport = 0;
    if ( agent.indexOf('Firefox') != -1 ){
      canSupport = 1;
      if ( parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Firefox') + 8)) >= 4 ){
        canSupport = 2;
      }
    }
    if ( agent.indexOf('Chrome') != -1 ){
      canSupport = 1;
      if ( parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Chrome') + 7).split(' ')[0]) >= 7 ){
        canSupport = 2;
      }
    }
    if ( agent.indexOf('Safari') != -1 ){
      canSupport = 1;
      if ( parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Version') + 8).split(' ')[0]) >= 5.1 ){
        canSupport = 2;
      }
    }
    if ( navigator.appName.indexOf("Internet Explorer")!=-1 ){
      if ( navigator.appVersion.indexOf("MSIE 9") == -1 && navigator.appVersion.indexOf("MSIE 10") == -1 ) canSupport = 1;
      if ( navigator.appVersion.indexOf("MSIE 11") == -1 ) canSupport = 2;
    }

    if ( canSupport == 0 ){
      expect( utils.detectRenderer() ).toEqual( 'none' );
    } else if ( canSupport == 1 ){
      expect( utils.detectRenderer() ).toEqual( 'canvas' );
    } else if ( canSupport == 2 ){
      expect( utils.detectRenderer() ).toEqual( 'webgl' );
    }

  });

});

 /*
  * Specs for the Bar Cubes class
  */

describe("Bar Cube", function() {

  var scene = new THREE.Scene();

  var label = document.createElement('div');
  var nCube = new THREEGRAPHS.BarCube( "d9bd00", 0, 0, 7, "ffffff", 'full', false, { row:"row", col:"col" }, 0, 10, 10 );
  nCube.addBar ( scene );

  it ( 'should create a new bar object', function () {
    expect ( nCube.barobj.geometry ).toBeDefined();
  });

  it ( 'should have a width size equate to the sqare size defined', function () {
    expect ( nCube.barobj.geometry.width ).toEqual( THREEGRAPHS.Settings.squareSize );
  });

});

 /*
  * Specs for the Bar Cubes class
  */

describe("Pie Parts", function() {

  var scene = new THREE.Scene();

  it ( 'should create a new pie object', function () {
    var label = document.createElement('div');
    var pieP = new THREEGRAPHS.PiePart( 7, 20, 500, 0, {x:0,y:0},
                                        "d9bd00", "ffffff", 'full', false,
                                        { col:"col" } );
    pieP.addPie ( scene );
    expect ( pieP.pieobj.geometry ).toBeDefined();
  });

});<|endoftext|>


<commit_before>import Head from "next/head";

export default () => (

      <title>Nekostagram</title>
      <meta description="Cat Lovers Instagram Viewer" />
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />

      {/*
Oops! It seems like cats got lost.
 */}

ねこがみつかりませんでした

        ruedap/nekostagram

);
<commit_msg>Update index.js<commit_after>import Head from "next/head";

export default () => (

      <title>Nekostagram</title>
      <meta description="Cat Lovers Instagram Viewer" />
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />

Oops! It seems like cats got lost.

      {/*
ねこがみつかりませんでした
 */}

        ruedap/nekostagram

);
<|endoftext|>


<commit_before>/* eslint-disable no-var, prefer-arrow-callback, prefer-template, func-names, vars-on-top */
var env = process.env.NODE_ENV || 'development';
var stopOnErrors = ['production', 'build', 'prepublish'].indexOf(env) !== -1;
var debug = process.env.DEBUG === 1;
module.exports = function (options) {
  var fs = require('fs');
  if (!options) {
    options = {};
  }
  var gulp = options.gulp || require('gulp');
  var babel = require('gulp-babel');
  var istanbul = require('gulp-istanbul');
  var sequence = require('gulp-sequence');
  var newer = require('gulp-newer');
  var spawnMocha = require('gulp-spawn-mocha');
  var inlineMocha = require('gulp-mocha');
  var ts = require('gulp-typescript');
  var clean = require('gulp-clean');
  var sourcemaps = require('gulp-sourcemaps');
  var gulpIf = require('gulp-if');
  var plumber = require('gulp-plumber');
  var notify = require('gulp-notify');
  // var tap = require('gulp-tap');
  var add = require('gulp-add-src');
  // var inspector = require('gulp-node-inspector');
  var filter = require('gulp-filter');

  var nodemon = require('gulp-nodemon');
  var notifier = require('node-notifier');
  var merge = require('merge2');
  var remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul');

  var otherFiles = 'src/**/!(*.js|*.map|*.src|*.ts|*.d.ts)';
  var source = 'src/**/*.ts';
  var typings = 'typings/index.d.ts';
  var customTypings = 'custom_typings/**/*.d.ts';
  var dest = 'lib';
  var destGlob = dest + '/**/*.*';
  var destGlobJs = dest + '/**/*.js';
  var coveredDest = 'lib_covered';
  var testEndpoint = dest + '/test/test.js';
  var coveredTestEndpoint = coveredDest + '/test/test.js';
  var startEndpoint = options.startEndpoint || dest + '/app.js';
  // var modulesGlob = 'node_modules/**/*.*';

  var packageInfo = JSON.parse(fs.readFileSync('package.json', 'utf8'));
  var packageVersion = packageInfo.name + '@' + packageInfo.version;
  var compileErrors = 0;
  var onError = function (errorCallback) {
    return function (err) {
      if (errorCallback) {
        errorCallback();
      }
      notify.onError({
        title: 'Gulp error in ' + err.plugin,
        message: err.toString(),
      })(err);
      this.emit('end');
    };
  };

  var swallowError = function () {
    this.emit('end');
  };

  gulp.task('cleanup', ['cleanup-dest', 'cleanup-covered', 'cleanup-coverage']);
  gulp.task('cleanup-dest', function () {
    return gulp.src(dest, { read: false }).pipe(clean());
  });
  gulp.task('cleanup-coverage', function () {
    return gulp.src('coverage', { read: false }).pipe(clean());
  });
  gulp.task('cleanup-covered', function () {
    return gulp.src(coveredDest, { read: false }).pipe(clean());
  });
  gulp.task('copy-files', function () {
    return gulp.src(otherFiles)
      .pipe(newer(dest))
      // .pipe(tap(function(file) {
      //     console.log('copy', file.path);
      //  }))
      .pipe(gulp.dest(dest));
  });
  gulp.task('ts-definitions', function () {
    var tsProject = ts.createProject('tsconfig.json', { declaration: true });
    var tsResult = gulp.src(source)
      .pipe(gulpIf(!stopOnErrors, plumber({ errorHandler: swallowError })))
      .pipe(newer({ dest, ext: '.d.ts' }))
      .pipe(add.prepend(typings))
      .pipe(add.prepend(customTypings))
      .pipe(ts(tsProject));
    return tsResult.dts.pipe(gulp.dest(dest));
  });
  gulp.task('ts-compile', ['copy-files'], function () {
    compileErrors = 0;
    const noMap = filter('**/!(*.map)', { restore: false });
    const noTests = filter('**/(!test/**/*.*)', { restore: false });
    var tsProject = ts.createProject('tsconfig.json', { isolatedModules: true, declaration: false });
    var tsResult = gulp.src(source)
      .pipe(gulpIf(!stopOnErrors, plumber({ errorHandler: onError(() => {
        compileErrors++;
      }) })))
      .pipe(newer({ dest, ext: '.js' }))
      .pipe(sourcemaps.init())
      .pipe(add.prepend(typings))
      .pipe(add.prepend(customTypings))
      .pipe(ts(tsProject));
    var babelStream = tsResult.js.pipe(babel());
    return merge([
      tsResult.dts
        .pipe(gulp.dest(dest)),
      babelStream
        .pipe(sourcemaps.write('.', { sourceRoot: '/' + packageVersion + '/src' }))
        .pipe(gulp.dest(dest))
        .pipe(noMap)
        // .pipe(noTests)
        .pipe(istanbul())
        .pipe(sourcemaps.write('.', { sourceRoot: '/' + packageVersion + '/src' }))
        .pipe(gulp.dest('lib_covered')),
    ]);
  });
  gulp.task('remap-istanbul', function () {
    return gulp.src('coverage/coverage-final.json')
    .pipe(remapIstanbul({
      reports: {
        json: 'coverage/coverage.json',
        html: 'coverage/html-report',
      },
    }));
  });
  gulp.task('test', function (callback) {
    return sequence(
      // 'pre-test',
      'do-test-covered',
      'remap-istanbul'
      )(callback);
  });
  function doTest(endpoints) {
    var errorHappened = false;
    var mocha;
    if (debug) {
      mocha = spawnMocha({
        debugBrk: true,
        env: { NODE_ENV: 'test' },
      });
    } else {
      mocha = inlineMocha();
    }
    return gulp.src(endpoints, { read: false })
    .pipe(gulpIf(!stopOnErrors, plumber({ errorHandler: onError(function () {
      errorHappened = true;
    }) })))
    .pipe(mocha)
    .pipe(istanbul.writeReports({
      reporters: ['json'],
    }))
    .on('end', function () {
      if (!errorHappened && !compileErrors) {
        notifier.notify(
          { title: 'All tests passed in ' + packageInfo.name, message: 'Write some more' }
        );
      }
    });
  }
  gulp.task('do-test', function () {
    return doTest([testEndpoint]);
  });
  gulp.task('do-test-covered', function () {
    return doTest([coveredTestEndpoint]);
  });
  gulp.task('start', function () {
    nodemon({
      script: startEndpoint,
      watch: [destGlob],
    });
  });
  gulp.task('ts-watch-compile', function () {
    gulp.watch(source, ['ts-compile']);
    // gulp.watch(otherFiles, ['copy-files']);
  });
  gulp.task('ts-watch-test', function () {
    gulp.watch(source, ['ts-compile-and-test']);
    // gulp.watch(otherFiles, ['copy-files']);
  });
  gulp.task('ts-compile-and-test', function (callback) {
    sequence('ts-definitions', 'ts-compile', 'test')(callback);
  });
  gulp.task('ts-fresh-compile', function (callback) {
    sequence('cleanup', 'ts-definitions', 'ts-compile')(callback);
  });
  gulp.task('ts-run-build', function (callback) {
    sequence('ts-fresh-compile', 'ts-watch-compile')(callback);
  });
  gulp.task('ts-run-test', function (callback) {
    sequence('ts-run-build', 'ts-watch-test', 'test')(callback);
  });
  gulp.task('ts-run', function (callback) {
    sequence('ts-watch-compile', 'start')(callback);
  });
};
<commit_msg>copy not compiled files to covered dest as well<commit_after>/* eslint-disable no-var, prefer-arrow-callback, prefer-template, func-names, vars-on-top */
var env = process.env.NODE_ENV || 'development';
var stopOnErrors = ['production', 'build', 'prepublish'].indexOf(env) !== -1;
var debug = process.env.DEBUG === 1;
module.exports = function (options) {
  var fs = require('fs');
  if (!options) {
    options = {};
  }
  var gulp = options.gulp || require('gulp');
  var babel = require('gulp-babel');
  var istanbul = require('gulp-istanbul');
  var sequence = require('gulp-sequence');
  var newer = require('gulp-newer');
  var spawnMocha = require('gulp-spawn-mocha');
  var inlineMocha = require('gulp-mocha');
  var ts = require('gulp-typescript');
  var clean = require('gulp-clean');
  var sourcemaps = require('gulp-sourcemaps');
  var gulpIf = require('gulp-if');
  var plumber = require('gulp-plumber');
  var notify = require('gulp-notify');
  // var tap = require('gulp-tap');
  var add = require('gulp-add-src');
  // var inspector = require('gulp-node-inspector');
  var filter = require('gulp-filter');

  var nodemon = require('gulp-nodemon');
  var notifier = require('node-notifier');
  var merge = require('merge2');
  var remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul');

  var otherFiles = 'src/**/!(*.js|*.map|*.src|*.ts|*.d.ts)';
  var source = 'src/**/*.ts';
  var typings = 'typings/index.d.ts';
  var customTypings = 'custom_typings/**/*.d.ts';
  var dest = 'lib';
  var destGlob = dest + '/**/*.*';
  var destGlobJs = dest + '/**/*.js';
  var coveredDest = 'lib_covered';
  var testEndpoint = dest + '/test/test.js';
  var coveredTestEndpoint = coveredDest + '/test/test.js';
  var startEndpoint = options.startEndpoint || dest + '/app.js';
  // var modulesGlob = 'node_modules/**/*.*';

  var packageInfo = JSON.parse(fs.readFileSync('package.json', 'utf8'));
  var packageVersion = packageInfo.name + '@' + packageInfo.version;
  var compileErrors = 0;
  var onError = function (errorCallback) {
    return function (err) {
      if (errorCallback) {
        errorCallback();
      }
      notify.onError({
        title: 'Gulp error in ' + err.plugin,
        message: err.toString(),
      })(err);
      this.emit('end');
    };
  };

  var swallowError = function () {
    this.emit('end');
  };

  gulp.task('cleanup', ['cleanup-dest', 'cleanup-covered', 'cleanup-coverage']);
  gulp.task('cleanup-dest', function () {
    return gulp.src(dest, { read: false }).pipe(clean());
  });
  gulp.task('cleanup-coverage', function () {
    return gulp.src('coverage', { read: false }).pipe(clean());
  });
  gulp.task('cleanup-covered', function () {
    return gulp.src(coveredDest, { read: false }).pipe(clean());
  });
  gulp.task('copy-files', function () {
    return gulp.src(otherFiles)
      .pipe(newer(dest))
      // .pipe(tap(function(file) {
      //     console.log('copy', file.path);
      //  }))
      .pipe(gulp.dest(dest))
      .pipe(gulp.dest(coveredDest));
  });
  gulp.task('ts-definitions', function () {
    var tsProject = ts.createProject('tsconfig.json', { declaration: true });
    var tsResult = gulp.src(source)
      .pipe(gulpIf(!stopOnErrors, plumber({ errorHandler: swallowError })))
      .pipe(newer({ dest, ext: '.d.ts' }))
      .pipe(add.prepend(typings))
      .pipe(add.prepend(customTypings))
      .pipe(ts(tsProject));
    return tsResult.dts.pipe(gulp.dest(dest));
  });
  gulp.task('ts-compile', ['copy-files'], function () {
    compileErrors = 0;
    const noMap = filter('**/!(*.map)', { restore: false });
    const noTests = filter('**/(!test/**/*.*)', { restore: false });
    var tsProject = ts.createProject('tsconfig.json', { isolatedModules: true, declaration: false });
    var tsResult = gulp.src(source)
      .pipe(gulpIf(!stopOnErrors, plumber({ errorHandler: onError(() => {
        compileErrors++;
      }) })))
      .pipe(newer({ dest, ext: '.js' }))
      .pipe(sourcemaps.init())
      .pipe(add.prepend(typings))
      .pipe(add.prepend(customTypings))
      .pipe(ts(tsProject));
    var babelStream = tsResult.js.pipe(babel());
    return merge([
      tsResult.dts
        .pipe(gulp.dest(dest)),
      babelStream
        .pipe(sourcemaps.write('.', { sourceRoot: '/' + packageVersion + '/src' }))
        .pipe(gulp.dest(dest))
        .pipe(noMap)
        // .pipe(noTests)
        .pipe(istanbul())
        .pipe(sourcemaps.write('.', { sourceRoot: '/' + packageVersion + '/src' }))
        .pipe(gulp.dest('lib_covered')),
    ]);
  });
  gulp.task('remap-istanbul', function () {
    return gulp.src('coverage/coverage-final.json')
    .pipe(remapIstanbul({
      reports: {
        json: 'coverage/coverage.json',
        html: 'coverage/html-report',
      },
    }));
  });
  gulp.task('test', function (callback) {
    return sequence(
      // 'pre-test',
      'do-test-covered',
      'remap-istanbul'
      )(callback);
  });
  function doTest(endpoints) {
    var errorHappened = false;
    var mocha;
    if (debug) {
      mocha = spawnMocha({
        debugBrk: true,
        env: { NODE_ENV: 'test' },
      });
    } else {
      mocha = inlineMocha();
    }
    return gulp.src(endpoints, { read: false })
    .pipe(gulpIf(!stopOnErrors, plumber({ errorHandler: onError(function () {
      errorHappened = true;
    }) })))
    .pipe(mocha)
    .pipe(istanbul.writeReports({
      reporters: ['json'],
    }))
    .on('end', function () {
      if (!errorHappened && !compileErrors) {
        notifier.notify(
          { title: 'All tests passed in ' + packageInfo.name, message: 'Write some more' }
        );
      }
    });
  }
  gulp.task('do-test', function () {
    return doTest([testEndpoint]);
  });
  gulp.task('do-test-covered', function () {
    return doTest([coveredTestEndpoint]);
  });
  gulp.task('start', function () {
    nodemon({
      script: startEndpoint,
      watch: [destGlob],
    });
  });
  gulp.task('ts-watch-compile', function () {
    gulp.watch(source, ['ts-compile']);
    // gulp.watch(otherFiles, ['copy-files']);
  });
  gulp.task('ts-watch-test', function () {
    gulp.watch(source, ['ts-compile-and-test']);
    // gulp.watch(otherFiles, ['copy-files']);
  });
  gulp.task('ts-compile-and-test', function (callback) {
    sequence('ts-definitions', 'ts-compile', 'test')(callback);
  });
  gulp.task('ts-fresh-compile', function (callback) {
    sequence('cleanup', 'ts-definitions', 'ts-compile')(callback);
  });
  gulp.task('ts-run-build', function (callback) {
    sequence('ts-fresh-compile', 'ts-watch-compile')(callback);
  });
  gulp.task('ts-run-test', function (callback) {
    sequence('ts-run-build', 'ts-watch-test', 'test')(callback);
  });
  gulp.task('ts-run', function (callback) {
    sequence('ts-watch-compile', 'start')(callback);
  });
};
<|endoftext|>


<commit_before>'use strict'

import { Component } from 'react'
import 'isomorphic-fetch'
import sortArr from 'sort-arr'
import Link from 'next/link'

import Page from './../layouts/page'
import { colors, typography } from './../theme'

class Home extends Component {
  static async getInitialProps() {
    const res = await fetch(
      `https://api.github.com/users/bukinoshita/repos?per_page=100&access_token=${process
        .env.ACCESS_TOKEN}`
    )
    const json = await res.json()
    return { repos: json }
  }

  render() {
    const { name, html_url } = sortArr(
      this.props.repos,
      'pushed_at'
    ).reverse()[0]

    return (
      <Page color={colors.white} isInverted={false}>

bu kinoshita

front-end engineer & ux designer

            > currently working on {name}.

                <Link href="/about/work-experience" prefetch>
                  work
                </Link>/

                <Link href="/blog" prefetch>
                  blog
                </Link>/

                <Link href="/projects" prefetch>
                  projects
                </Link>/

                twitter/

                github/

                dribbble

      </Page>
    )
  }
}

export default Home
<commit_msg>fix currently working project (https://github.com/bukinoshita/bu/issues/38)<commit_after>'use strict'

import { Component } from 'react'
import 'isomorphic-fetch'
import Link from 'next/link'

import Page from './../layouts/page'
import { colors, typography } from './../theme'

class Home extends Component {
  static async getInitialProps() {
    const res = await fetch(
      `https://api.github.com/user/repos?per_page=100&sort=pushed&access_token=${process
        .env.ACCESS_TOKEN}`
    )
    const json = await res.json()
    return { repo: json[0] }
  }

  render() {
    const { name, html_url } = this.props.repo

    return (
      <Page color={colors.white} isInverted={false}>

bu kinoshita

front-end engineer & ux designer

            > currently working on {name}.

                <Link href="/about/work-experience" prefetch>
                  work
                </Link>/

                <Link href="/blog" prefetch>
                  blog
                </Link>/

                <Link href="/projects" prefetch>
                  projects
                </Link>/

                twitter/

                github/

                dribbble

      </Page>
    )
  }
}

export default Home
<|endoftext|>


<commit_before>'use strict'

import React from 'react'
import Link from 'next/link'

import Meta from '../components/meta'

export default () => (

    <Meta />

      <Link href="/login">Login</Link>
      <Link href="/signup">Sign Up</Link>

Landing Page

Ritoplz 0.0.4

)
<commit_msg>Landing Page UI Partial<commit_after>'use strict'

import React from 'react'
import Link from 'next/link'
import { style } from 'next/css'

import Meta from '../components/meta'

const styles = {
  row: {
    maxWidth: '900px',
    marginLeft: 'auto',
    marginRight: 'auto',

    '@media (max-width: 750px)': {
      paddingLeft: '20px',
      paddingRight: '20px'
    }
  },

  header: {
    height: '70px'
  },

  logo: {
    float: 'left',
    fontSize: '2rem',
    fontWeight: '700'
  },

  link: {
    color: '#333',
    textDecoration: 'none',
    lineHeight: '70px',
  },

  btnHeader: {
    color: '#fff',
    border: 'none',
    borderRadius: '5px',
    padding: '10px 25px',
    fontSize: '.9rem',
    fontWeight: '500',
    cursor: 'pointer',
    background: 'linear-gradient(to right, #52bdab 0%,#6BB6D6 100%)',
    textDeconration: 'none'
  },

  nav : {
    lineHeight: '70px',
    float: 'right'
  },

  navItem: {
    display: 'inline-block',
    marginLeft: '30px'
  },

  navLink: {
    color: '#ccc',
    fontSize: '1rem',
    fontWeight: '400',
    transition: '.25s',
    display: 'inline-block',

    ':hover': {
      color: '#333'
    }
  },

  cover: {
    textAlign: 'center',
    paddingTop: '100px',
    paddingBottom: '100px'
  },

  title: {
    color: '#333',
    fontSize: '2rem',
    textTransform: 'uppercase'
  },

  subtitle: {
    color: '#333',
    fontSize: '3.5rem',
    fontWeight: '300',
    lineHeight: '4rem',
    marginTop: '10px',
    marginBottom: '15px'
  },

  tagline: {
    color: '#999',
    fontSize: '1.5rem',
    fontWeight: '100',
    marginBottom: '75px'
  },

  btn: {
    color: '#fff',
    border: 'none',
    borderRadius: '5px',
    padding: '14px 28px',
    fontSize: '1rem',
    height: '55px',
    marginTop: '25px',
    fontWeight: '500',
    cursor: 'pointer',
    background: 'linear-gradient(to right, #52bdab 0%,#6BB6D6 100%)',
    marginLeft: '15px',
    marginRight: '15px'
  }
}

export default () => (

    <Meta />

        <Link href="/">

            Ritoplz

        </Link>

            <Link href="/login">
              <button className={style(styles.btnHeader)}>Login</button>
            </Link>

Ritoplz

Do you want to be the best?

Join the League of Legends rankings and make sure you are on top.

      <Link href="/signup">
        Join Ritoplz
      </Link>

      <Link href="/rankings">
        See Rankings
      </Link>

)
<|endoftext|>


<commit_before>/*
 * tokensearch.js: simple string token collection search
 *
 * (C) 2015 Michael Vogt
 * MIT LICENSE
 *
 */
 var Tokensearch = function(collection, options) {
  this.collection = collection;
  options = options || {};
  this.delimiter = options.delimiter || Tokensearch.defaultOptions.delimiter;
  this.maxFilterTokenEntries = options.maxFilterTokenEntries || Tokensearch.defaultOptions.maxFilterTokenEntries;
  this.defaultThreshold = options.threshold || Tokensearch.defaultOptions.threshold;
  this.collectionKeys = options.collectionKeys || Tokensearch.defaultOptions.collectionKeys;
  if (this.collectionKeys.length===0) {
    throw new Error('No collectionKeys defined!');
  }
  if (!this.collection || this.collection.length===0) {
    throw new Error('Empty collection!');
  }
  this.collectionDataTokenSize = this.collectionKeys.length;
  this._prepareSearchTokens();
};

Tokensearch.defaultOptions = {
  //split strings with the delimiter
  delimiter: ' ',

  // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
  // (of both letters and location), a threshold of '1.0' would match anything.
  threshold: 0.7,

  // How many search tokens are considered
  maxFilterTokenEntries: 5,

  // search key
  collectionKeys: []
};

Tokensearch.prototype._prepareSearchTokens = function() {
  var self = this;
  //Get all search tokens
  this.collection.forEach(function(entry) {
    var tmp = [];
    self.collectionKeys.forEach(function(key) {
      entry[key].trim().toLowerCase().split(self.delimiter).forEach(function(e) {
        tmp.push(e);
      });
    });
    entry.dataEntryTokens = tmp.filter(self._onlyUnique);
  });

};

Tokensearch.prototype._onlyUnique = function(value, index, self) {
  return self.indexOf(value) === index;
};

/**
 * returns an sorted array of { 'item': OBJECT, 'score': score }
 * -item contains the input object
 * -score defines the match with the search term, 0 means perfect match, 1 means rubbish
 */
Tokensearch.prototype.search = function(token, customThreshold) {
  var self = this;
  var searchTokens = [];
  var threshold = customThreshold || this.defaultThreshold;

  //make sure the search tokens contains no dups
  var tmp = token.trim().split(this.delimiter).filter(this._onlyUnique);
  for (var i = 0, len = Math.min(tmp.length, this.maxFilterTokenEntries); i < len; i++) {
    searchTokens.push(tmp[i].toLowerCase());
  }

  var resultTmp = [];
  var maxScore = 0;
  this.collection.forEach(function(entry) {
    var score = 0;

    entry.dataEntryTokens.forEach(function(dataEntryToken) {
      searchTokens.forEach(function(searchToken) {
        if (dataEntryToken.indexOf(searchToken) > -1) {
          score += (dataEntryToken === searchToken) ? 2 : 1;
        }
      });
    });

    if (score) {
      if (score > maxScore) {
        maxScore = score;
      }
      resultTmp.push({ 'item': entry, 'score': score });
    }
  });

  var result = [];
  var normalizedScore = 1 / maxScore;
  resultTmp.forEach(function(r) {
    r.score = 1-r.score*normalizedScore;
    if (r.score <= threshold) {
      result.push(r);
    }
  });

  return result.sort(function(a, b) {
     return a.score - b.score;
  });
};

module.exports = Tokensearch;
<commit_msg>improve search results: use regex to split tokens, use nr of found tokens in the score<commit_after>/*
 * tokensearch.js: simple string token collection search
 *
 * (C) 2015 Michael Vogt
 * MIT LICENSE
 *
 */
 var Tokensearch = function(_collection, options) {
  if (!_collection || _collection.length===0) {
    throw new Error('Empty collection!');
  }
  this.collection = _collection;
  options = options || {};
  this.delimiterRegex = options.delimiterRegex || Tokensearch.defaultOptions.delimiterRegex;
  this.maxFilterTokenEntries = options.maxFilterTokenEntries || Tokensearch.defaultOptions.maxFilterTokenEntries;
  this.defaultThreshold = options.threshold || Tokensearch.defaultOptions.threshold;
  this.collectionKeys = options.collectionKeys || Tokensearch.defaultOptions.collectionKeys;
  if (this.collectionKeys.length===0) {
    throw new Error('No collectionKeys defined!');
  }
  this.collectionDataTokenSize = this.collectionKeys.length;
  this._prepareSearchTokens();
};

Tokensearch.defaultOptions = {
  //split strings with those delimiters, default delimiters: space and dash
  delimiterRegex: /[\s-]+/,

  // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
  // (of both letters and location), a threshold of '1.0' would match anything.
  threshold: 0.7,

  // How many search tokens are considered
  maxFilterTokenEntries: 5,

  // search key
  collectionKeys: []
};

Tokensearch.prototype._prepareSearchTokens = function() {
  var self = this;
  //Get all search tokens
  this.collection.forEach(function(entry) {
    var tmp = [];
    self.collectionKeys.forEach(function(key) {
      entry[key].trim().toLowerCase().split(self.delimiterRegex).forEach(function(e) {
        tmp = tmp.concat(e);
      });
    });
    entry.dataEntryTokens = tmp.filter(self._onlyUnique);
  });

};

Tokensearch.prototype._onlyUnique = function(value, index, self) {
  return self.indexOf(value) === index;
};

/**
 * returns an sorted array of { 'item': OBJECT, 'score': score }
 * -item contains the input object
 * -score defines the match with the search term, 0 means perfect match, 1 means rubbish
 */
Tokensearch.prototype.search = function(token, customThreshold) {
  var self = this;
  var searchTokens = [];
  var threshold = customThreshold || this.defaultThreshold;

  //make sure the search tokens contains no dups
  var tmp = token.trim().split(this.delimiterRegex).filter(this._onlyUnique);
  for (var i = 0, len = Math.min(tmp.length, this.maxFilterTokenEntries); i < len; i++) {
    searchTokens.push(tmp[i].toLowerCase());
  }

  var resultTmp = [];
  var maxScore = 0;
  this.collection.forEach(function(entry) {
    var score = 0;
	var tokensFound = 0;
    entry.dataEntryTokens.forEach(function(dataEntryToken) {
      searchTokens.forEach(function(searchToken) {
        if (dataEntryToken.indexOf(searchToken) > -1) {
		  tokensFound++;
          score += (dataEntryToken === searchToken) ? 2 : 1;
        }
      });
    });

    if (score) {
	  score += tokensFound;
      if (score > maxScore) {
        maxScore = score;
      }
      resultTmp.push({ 'item': entry, 'score': score });
    }
  });

  var result = [];
  var normalizedScore = 1 / maxScore;
  resultTmp.forEach(function(r) {
    r.score = 1-r.score*normalizedScore;
    if (r.score <= threshold) {
      result.push(r);
    }
  });

  return result.sort(function(a, b) {
     return a.score - b.score;
  });
};

module.exports = Tokensearch;
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var mozl10n = {};

(function(aMozl10n) {
  var temp = {};
  Components.utils.import("resource://gre/modules/Services.jsm", temp);
  var stringBundle = temp.Services.strings.createBundle(
          "chrome://browser/locale/devtools/gclicommands.properties");

  /**
   * Lookup a string in the GCLI string bundle
   * @param name The name to lookup
   * @return The looked up name
   */
  aMozl10n.lookup = function(name) {
    try {
      return stringBundle.GetStringFromName(name);
    }
    catch (ex) {
      throw new Error("Failure in lookup('" + name + "')");
    }
  };

  /**
   * Lookup a string in the GCLI string bundle
   * @param name The name to lookup
   * @param swaps An array of swaps. See stringBundle.formatStringFromName
   * @return The looked up name
   */
  aMozl10n.lookupFormat = function(name, swaps) {
    try {
      return stringBundle.formatStringFromName(name, swaps, swaps.length);
    }
    catch (ex) {
      throw new Error("Failure in lookupFormat('" + name + "')");
    }
  };

})(mozl10n);

define(function(require, exports, module) {

  // The API for use by command authors
  exports.addCommand = require('gcli/canon').addCommand;
  exports.removeCommand = require('gcli/canon').removeCommand;
  exports.lookup = mozl10n.lookup;
  exports.lookupFormat = mozl10n.lookupFormat;

  // Internal startup process. Not exported
  require('gcli/types/basic').startup();
  require('gcli/types/javascript').startup();
  require('gcli/types/node').startup();
  require('gcli/cli').startup();
  require('gcli/commands/help').startup();

  var Requisition = require('gcli/cli').Requisition;
  var Console = require('gcli/ui/console').Console;

  var cli = require('gcli/cli');
  var jstype = require('gcli/types/javascript');
  var nodetype = require('gcli/types/node');

  /**
   * API for use by HUDService only.
   * This code is internal and subject to change without notice.
   */
  exports._internal = {
    require: require,
    define: define,
    console: console,

    /**
     * createView() for Firefox requires an options object with the following
     * members:
     * - contentDocument: From the window of the attached tab
     * - chromeDocument: GCLITerm.document
     * - environment.hudId: GCLITerm.hudId
     * - jsEnvironment.globalObject: 'window'
     * - jsEnvironment.evalFunction: 'eval' in a sandbox
     * - inputElement: GCLITerm.inputNode
     * - completeElement: GCLITerm.completeNode
     * - gcliTerm: GCLITerm
     * - hintElement: GCLITerm.hintNode
     * - inputBackgroundElement: GCLITerm.inputStack
     */
    createView: function(opts) {
      jstype.setGlobalObject(opts.jsEnvironment.globalObject);
      nodetype.setDocument(opts.contentDocument);
      cli.setEvalFunction(opts.jsEnvironment.evalFunction);

      if (opts.requisition == null) {
        opts.requisition = new Requisition(opts.environment, opts.chromeDocument);
      }

      opts.console = new Console(opts);
    },

    /**
     * Undo the effects of createView() to prevent memory leaks
     */
    removeView: function(opts) {
      opts.console.destroy();
      delete opts.console;

      opts.requisition.destroy();
      delete opts.requisition;

      cli.unsetEvalFunction();
      nodetype.unsetDocument();
      jstype.unsetGlobalObject();
    },

    commandOutputManager: require('gcli/canon').commandOutputManager
  };
});
<commit_msg>Bug 709223 (resource): Include resource type in gcli.jsm<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var mozl10n = {};

(function(aMozl10n) {
  var temp = {};
  Components.utils.import("resource://gre/modules/Services.jsm", temp);
  var stringBundle = temp.Services.strings.createBundle(
          "chrome://browser/locale/devtools/gclicommands.properties");

  /**
   * Lookup a string in the GCLI string bundle
   * @param name The name to lookup
   * @return The looked up name
   */
  aMozl10n.lookup = function(name) {
    try {
      return stringBundle.GetStringFromName(name);
    }
    catch (ex) {
      throw new Error("Failure in lookup('" + name + "')");
    }
  };

  /**
   * Lookup a string in the GCLI string bundle
   * @param name The name to lookup
   * @param swaps An array of swaps. See stringBundle.formatStringFromName
   * @return The looked up name
   */
  aMozl10n.lookupFormat = function(name, swaps) {
    try {
      return stringBundle.formatStringFromName(name, swaps, swaps.length);
    }
    catch (ex) {
      throw new Error("Failure in lookupFormat('" + name + "')");
    }
  };

})(mozl10n);

define(function(require, exports, module) {

  // The API for use by command authors
  exports.addCommand = require('gcli/canon').addCommand;
  exports.removeCommand = require('gcli/canon').removeCommand;
  exports.lookup = mozl10n.lookup;
  exports.lookupFormat = mozl10n.lookupFormat;

  // Internal startup process. Not exported
  require('gcli/types/basic').startup();
  require('gcli/types/javascript').startup();
  require('gcli/types/node').startup();
  require('gcli/types/resource').startup();
  require('gcli/cli').startup();
  require('gcli/commands/help').startup();

  var Requisition = require('gcli/cli').Requisition;
  var Console = require('gcli/ui/console').Console;

  var cli = require('gcli/cli');
  var jstype = require('gcli/types/javascript');
  var nodetype = require('gcli/types/node');

  /**
   * API for use by HUDService only.
   * This code is internal and subject to change without notice.
   */
  exports._internal = {
    require: require,
    define: define,
    console: console,

    /**
     * createView() for Firefox requires an options object with the following
     * members:
     * - contentDocument: From the window of the attached tab
     * - chromeDocument: GCLITerm.document
     * - environment.hudId: GCLITerm.hudId
     * - jsEnvironment.globalObject: 'window'
     * - jsEnvironment.evalFunction: 'eval' in a sandbox
     * - inputElement: GCLITerm.inputNode
     * - completeElement: GCLITerm.completeNode
     * - gcliTerm: GCLITerm
     * - hintElement: GCLITerm.hintNode
     * - inputBackgroundElement: GCLITerm.inputStack
     */
    createView: function(opts) {
      jstype.setGlobalObject(opts.jsEnvironment.globalObject);
      nodetype.setDocument(opts.contentDocument);
      cli.setEvalFunction(opts.jsEnvironment.evalFunction);

      if (opts.requisition == null) {
        opts.requisition = new Requisition(opts.environment, opts.chromeDocument);
      }

      opts.console = new Console(opts);
    },

    /**
     * Undo the effects of createView() to prevent memory leaks
     */
    removeView: function(opts) {
      opts.console.destroy();
      delete opts.console;

      opts.requisition.destroy();
      delete opts.requisition;

      cli.unsetEvalFunction();
      nodetype.unsetDocument();
      jstype.unsetGlobalObject();
    },

    commandOutputManager: require('gcli/canon').commandOutputManager
  };
});
<|endoftext|>


<commit_before>
function AdminError (message) {
    this.name = 'AdminError';
    this.message = message ||
        'All known errors are rendered back to the user in a friendly way.';
}
AdminError.prototype = new Error();
AdminError.prototype.constructor = AdminError;

function ValidationError (error) {
    this.name = 'ValidationError';
    this.message = error || '';
}
ValidationError.prototype = new Error();
ValidationError.prototype.constructor = ValidationError;

function DatabaseError (error) {
    this.name = 'DatabaseError';
    var column = '',
        message = '';
    switch (error.code) {
        case 'ER_DUP_ENTRY':
            // ER_DUP_ENTRY: Duplicate entry 'asd' for key 'name_UNIQUE'
            var key = error.message.match(/.*key '(.*)'.*/i)[1];
            column = error.indexes[key];
            message = error.message.split(':')[1].replace(key, column).trim();
            break;
        case 'ER_BAD_NULL_ERROR':
            // ER_BAD_NULL_ERROR: Column 'need_id' cannot be null
            column = error.message.match(/.*Column '(.*)'.*/i)[1];
            message = error.message.split(':')[1];
            break;
        default:
            // throw
            column = 'MySql Error';
            message = error.message;
            break;
    }
    this.message = {};
    this.message[error.prefix+column] = {
        type: 'Database Error!',
        message: message
    }
}
DatabaseError.prototype = new Error();
DatabaseError.prototype.constructor = DatabaseError;

exports.AdminError = AdminError;
exports.ValidationError = ValidationError;
exports.DatabaseError = DatabaseError;
<commit_msg>Removed the error module<commit_after><|endoftext|>


<commit_before>'use strict';

var join = require('path').join;
var fs = require('fs');
var readline = require('readline');

module.exports = Filer;

function Filer() {
}

Filer.prototype.getPackageJSON = function (folder) {
    if (!this.__stat(join(folder, 'package.json')))
        return 'package.json does not exist in the current directory';

    return require(join(folder, 'package.json'));
};

Filer.prototype.writeJSONFile = function (path, data, callback) {

    fs.writeFile(path, JSON.stringify(data), function (e) {

        if (e)
            return callback(e);

        callback();
    });
};

Filer.prototype.copy = function (src, dest) {
    try {
        var source = fs.readFileSync(src);

        fs.writeFileSync(dest, source);
    } catch (err) {

    }
};

Filer.prototype.__stat = function (path) {
    try {
        return fs.statSync(path);
    } catch (_) {
        return false;
    }
};

Filer.prototype.lookupDependencyHash = function (filePath, dependencyHash) {

    var lineReader = readline.createInterface({
        input: require('fs').createReadStream(filePath)
    });

    lineReader.on('line', function (line) {
        var arr = line.split(':');

        var key = arr[0];
        var value = arr[1];

        if (key == dependencyHash)
            return value;
    });

    return null;
};

Filer.prototype.addLineToFile = function (filePath, lineItem, callback) {

    fs.appendFile(filePath, lineItem, function (err) {

        if (err)
            return callback(err);

        callback();
    });
};<commit_msg>Modified filer<commit_after>'use strict';

var join = require('path').join;
var fs = require('fs');
var readline = require('readline');

module.exports = Filer;

function Filer() {
}

Filer.prototype.getPackageJSON = function (folder) {
    if (!this.__stat(join(folder, 'package.json')))
        return 'package.json does not exist in the current directory';

    return require(join(folder, 'package.json'));
};

Filer.prototype.writeJSONFile = function (path, data, callback) {

    fs.writeFile(path, JSON.stringify(data), function (e) {

        if (e)
            return callback(e);

        callback();
    });
};

Filer.prototype.copy = function (src, dest) {
    try {
        var source = fs.readFileSync(src);

        fs.writeFileSync(dest, source);
    } catch (err) {

    }
};

Filer.prototype.__stat = function (path) {
    try {
        return fs.statSync(path);
    } catch (_) {
        return false;
    }
};

Filer.prototype.lookupDependencyHash = function (filePath, dependencyHash) {

    if (!this.__stat(filePath))
        return null;

    var lineReader = readline.createInterface({
        input: require('fs').createReadStream(filePath)
    });

    lineReader.on('line', function (line) {
        var arr = line.split(':');

        var key = arr[0];
        var value = arr[1];

        if (key == dependencyHash)
            return value;
    });

    return null;
};

Filer.prototype.addLineToFile = function (filePath, lineItem, callback) {

    console.log('adding line to file...');

    fs.appendFile(filePath, lineItem, function (err) {

        if (err)
            return callback(err);

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


<commit_before>var Promise = require('es6-promise').Promise;

module.exports.extend = function () {
  Array.prototype.slice.call(arguments, 1).forEach(function (src) {
    if (src) {
      for (var prop in src) {
        obj[prop] = src[prop];
      }
    }
  });
  return obj;
};

module.exports.promisify = function (func) {
  return function () {
    var args = Array.prototype.slice.apply(arguments);

    return new Promise(function (resolve, reject) {
      func.apply({}, args.concat(function (err, value) {
        if (err) {
          reject(err);
        } else {
          resolve(value);
        }
      }));
    });
  };
};
<commit_msg>remove `lib.utils.extend`<commit_after>var Promise = require('es6-promise').Promise;

module.exports.promisify = function promisify(func) {
  return function () {
    var args = Array.prototype.slice.apply(arguments);

    return new Promise(function (resolve, reject) {
      func.apply({}, args.concat(function (err, value) {
        if (err) {
          reject(err);
        } else {
          resolve(value);
        }
      }));
    });
  };
};
<|endoftext|>


<commit_before>var structure = require('./structure')
var _ = require('underscore')

var builtInTypes = [
  'string',
  'number',
  'bool',
  'boolean',
  'array',
  'object',
  'undefined',
  'null',
  'function'
]

var tools = module.exports.tools = {
  modulename: function (longname) {
    if (longname === '_GLOBAL') {
      return 'global'
    } else if (longname.indexOf('module:') > -1) {
      return longname.split('module:')[1]
    } else {
      return longname
    }
  },
  sortByName: function (doclets) {
    return _.sortBy(doclets, function (doclet) {
      return doclet.name
    })
  },
  shortName: function (longname) {
    var parts = longname.split('~')
    if (parts && parts[1]) {
      return parts[1]
    } else {
      return longname
    }
  },
  isBuiltInType: function (typename) {
    typename = typename.toLowerCase()
    return builtInTypes.indexOf(typename) > -1
  },
  linkFromSee: function (see) {
    var parts = see.match(/^{@link\s+(http)?([^|\s]+)(\||\s)?(.*)?}/)
    if (parts) {
      var name
      if (parts[4]) {
        name = parts[4]
      } else if (parts[1]) {
        name = parts[1] + parts[2]
      } else {
        name = parts[2]
      }

      return {
        url: (parts[1] || '#') + parts[2],
        name: name
      }
    }
    parts = see.match(/^\[([^\]]+)\]{@link\s+(http)?(.*)}/)
    if (parts) {
      return {
        url: (parts[2] || '#') + parts[3],
        name: parts[1]
      }
    }
    return {}
  }

}

module.exports.getApiParams = function (data) {
  return {
    modules: structure.buildHierarchy(data),
    articles: data.articles,
    version: data.repo.branch,
    name: data.repo.name || '',
    user: data.repo.user,
    '_': _,
    tools: tools,
    versionsPath: './',
    articlesPath: data.repo.branch + '/',
    apiPath: ''
  }
}

module.exports.getArticleParams = function (data, article) {
  article = _.findWhere(data.articles, {
    id: article
  })
  var html = structure.buildArticleHtml(article, data.repo.url, data.repo.branch)
  return {
    modules: structure.buildHierarchy(data),
    articles: data.articles,
    version: data.repo.branch,
    name: data.repo.name || '',
    user: data.repo.user,
    contentHtml: html,
    '_': _,
    tools: tools,
    versionsPath: '../',
    articlesPath: '',
    apiPath: '../' + data.repo.branch
  }
}
<commit_msg>return repo object instead of single fields<commit_after>var structure = require('./structure')
var _ = require('underscore')

var builtInTypes = [
  'string',
  'number',
  'bool',
  'boolean',
  'array',
  'object',
  'undefined',
  'null',
  'function'
]

var tools = module.exports.tools = {
  modulename: function (longname) {
    if (longname === '_GLOBAL') {
      return 'global'
    } else if (longname.indexOf('module:') > -1) {
      return longname.split('module:')[1]
    } else {
      return longname
    }
  },
  sortByName: function (doclets) {
    return _.sortBy(doclets, function (doclet) {
      return doclet.name
    })
  },
  shortName: function (longname) {
    var parts = longname.split('~')
    if (parts && parts[1]) {
      return parts[1]
    } else {
      return longname
    }
  },
  isBuiltInType: function (typename) {
    typename = typename.toLowerCase()
    return builtInTypes.indexOf(typename) > -1
  },
  linkFromSee: function (see) {
    var parts = see.match(/^{@link\s+(http)?([^|\s]+)(\||\s)?(.*)?}/)
    if (parts) {
      var name
      if (parts[4]) {
        name = parts[4]
      } else if (parts[1]) {
        name = parts[1] + parts[2]
      } else {
        name = parts[2]
      }

      return {
        url: (parts[1] || '#') + parts[2],
        name: name
      }
    }
    parts = see.match(/^\[([^\]]+)\]{@link\s+(http)?(.*)}/)
    if (parts) {
      return {
        url: (parts[2] || '#') + parts[3],
        name: parts[1]
      }
    }
    return {}
  }

}

module.exports.getApiParams = function (data) {
  return {
    modules: structure.buildHierarchy(data),
    articles: data.articles,
    repo: data.repo,
    '_': _,
    tools: tools,
    versionsPath: './',
    articlesPath: data.repo.branch + '/',
    apiPath: ''
  }
}

module.exports.getArticleParams = function (data, article) {
  article = _.findWhere(data.articles, {
    id: article
  })
  var html = structure.buildArticleHtml(article, data.repo.url, data.repo.branch)
  return {
    modules: structure.buildHierarchy(data),
    articles: data.articles,
    repo: data.repo,
    contentHtml: html,
    '_': _,
    tools: tools,
    versionsPath: '../',
    articlesPath: '',
    apiPath: '../' + data.repo.branch
  }
}
<|endoftext|>