<commit_before>;(function() {
'use strict'
/* global define */

var esprima
var exportFn
var toString = Object.prototype.toString

if (typeof module === 'object' && typeof module.exports === 'object' && typeof require === 'function') {
  // server side
  esprima = require('esprima')
  exportFn = function(redeyed) { module.exports = redeyed }
  bootstrap(esprima, exportFn)
} else if (typeof define === 'function' && define.amd) {
  // client side
  // amd
  define(['esprima'], function(esprima) {
      return bootstrap(esprima)
  })
} else if (typeof window === 'object') {
  // no amd -> attach to window if it exists
  // Note that this requires 'esprima' to be defined on the window, so that script has to be loaded first
  window.redeyed = bootstrap(window.esprima)
}

function bootstrap(esprima, exportFn) {
  function isFunction(obj) {
    return toString.call(obj) === '[object Function]'
  }

  function isString(obj) {
    return toString.call(obj) === '[object String]'
  }

  function isObject(obj) {
    return toString.call(obj) === '[object Object]'
  }

  function surroundWith(before, after) {
    return function(s) { return before + s + after }
  }

  function isNonCircular(key) {
    return key !== '_parent'
  }

  function objectizeString(value) {
    var vals = value.split(':')

    if (vals.length === 0 || vals.length > 2)      {
 throw new Error(
        'illegal string config: ' + value +
        '\nShould be of format "before:after"'
      )
}

    if (vals.length === 1 || vals[1].length === 0) {
      return vals.indexOf(':') < 0 ? { _before: vals[0] } : { _after: vals[0] }
    } else {
      return { _before: vals[0], _after: vals[1] }
    }
  }

  function objectize(node) {
    // Converts 'bef:aft' to { _before: bef, _after: aft }
    // and resolves undefined before/after from parent or root

    function resolve(value, key) {
      // resolve before/after from root or parent if it isn't present on the current node
      if (!value._parent) return undefined

      // Immediate parent
      if (value._parent._default && value._parent._default[key]) return value._parent._default[key]

      // Root
      var root = value._parent._parent
      if (!root) return undefined

      return root._default ? root._default[key] : undefined
    }

    function process(key) {
      var value = node[key]

      if (!value) return
      if (isFunction(value)) return

      // normalize all strings to objects
      if (isString(value)) {
        node[key] = value = objectizeString(value)
      }

      value._parent = node
      if (isObject(value)) {
        if (!value._before && !value._after) return objectize(value)

        // resolve missing _before or _after from parent(s)
        // in case we only have either one on this node
        value._before =  value._before || resolve(value, '_before')
        value._after  =  value._after  || resolve(value, '_after')

        return
      }

      throw new Error('nodes need to be either {String}, {Object} or {Function}.' + value + ' is neither.')
    }

    // Process _default ones first so children can resolve missing before/after from them
    if (node._default) process('_default')

    Object.keys(node)
      .filter(function(key) {
        return isNonCircular(key)
          && node.hasOwnProperty(key)
          && key !== '_before'
          && key !== '_after'
          && key !== '_default'
      })
      .forEach(process)
  }

  function functionize(node) {
    Object.keys(node)
      .filter(function(key) {
        return isNonCircular(key) && node.hasOwnProperty(key)
      })
      .forEach(function(key) {
        var value = node[key]

        if (isFunction(value)) return

        if (isObject(value)) {
          if (!value._before && !value._after) return functionize(value)

          // at this point before/after were "inherited" from the parent or root
          // (see objectize)
          var before = value._before || ''
          var after = value._after || ''

          node[key] = surroundWith(before, after)
          return node[key]
        }
      })
  }

  function normalize(root) {
    objectize(root)
    functionize(root)
  }

  function mergeTokensAndComments(tokens, comments) {
    var all = {}

    function addToAllByRangeStart(t) { all[ t.range[0] ] = t }

    tokens.forEach(addToAllByRangeStart)
    comments.forEach(addToAllByRangeStart)

    // keys are sorted automatically
    return Object.keys(all)
      .map(function(k) { return all[k] })
  }

  function redeyed(code, config, opts) {
    opts = opts || {}
    var parser = opts.parser || esprima
    var jsx = !!opts.jsx
    // tokenizer doesn't support JSX at this point (esprima@4.0.0)
    // therefore we need to generate the AST via the parser not only to
    // avoid the tokenizer from erroring but also to get JSXIdentifier tokens
    var buildAst = jsx || !!opts.buildAst

    var hashbang =  ''
    var ast
    var tokens
    var comments
    var lastSplitEnd = 0
    var splits = []
    var transformedCode
    var all
    var info

    // Replace hashbang line with empty whitespaces to preserve token locations
    if (code[0] === '#' && code[1] === '!') {
      hashbang = code.substr(0, code.indexOf('\n') + 1)
      code = Array.apply(0, Array(hashbang.length)).join(' ') + '\n' + code.substr(hashbang.length)
    }

    if (buildAst) {
      ast = parser.parse(code, { tokens: true, comment: true, range: true, loc: true, tolerant: true, jsx: true })
      tokens = ast.tokens
      comments = ast.comments
    } else {
      tokens = []
      comments = []
      parser.tokenize(code, { range: true, loc: true, comment: true }, function(token) {
        if (token.type === 'LineComment') {
          token.type = 'Line'
          comments.push(token)
        } else if (token.type === 'BlockComment') {
          token.type = 'Block'
          comments.push(token)
        } else {
          // Optimistically upgrade 'static' to a keyword
          if (token.type === 'Identifier' && token.value === 'static') token.type = 'Keyword'
          tokens.push(token)
        }
      })
    }
    const fs = require('fs')
    fs.writeFileSync('/tmp/result.json', (JSON.stringify(tokens, null, 2)), 'utf8')

    normalize(config)

    function tokenIndex(tokens, tkn, start) {
      var current
      var rangeStart = tkn.range[0]

      for (current = start; current < tokens.length; current++) {
        if (tokens[current].range[0] === rangeStart) return current
      }

      throw new Error('Token %s not found at or after index: %d', tkn, start)
    }

    function process(surround) {
      var result
      var currentIndex
      var nextIndex
      var skip = 0
      var splitEnd

      result = surround(code.slice(start, end), info)
      if (isObject(result)) {
        splits.push(result.replacement)

        currentIndex =  info.tokenIndex
        nextIndex    =  tokenIndex(info.tokens, result.skipPastToken, currentIndex)
        skip         =  nextIndex - currentIndex
        splitEnd     =  skip > 0 ? tokens[nextIndex - 1].range[1] : end
      } else {
        splits.push(result)
        splitEnd = end
      }

      return { skip: skip, splitEnd: splitEnd }
    }

    function addSplit(start, end, surround, info) {
      var result
      var skip = 0

      if (start >= end) return
      if (surround) {
        result       =  process(surround)
        skip         =  result.skip
        lastSplitEnd =  result.splitEnd
      } else {
        splits.push(code.slice(start, end))
        lastSplitEnd = end
      }

      return skip
    }

    all = mergeTokensAndComments(tokens, comments)
    for (var tokenIdx = 0; tokenIdx < all.length; tokenIdx++) {
      var token = all[tokenIdx]
      var surroundForType = config[token.type]
      var surround
      var start
      var end

      // At least the type (e.g., 'Keyword') needs to be specified for the token to be surrounded
      if (surroundForType) {
        // root defaults are only taken into account while resolving before/after otherwise
        // a root default would apply to everything, even if no type default was specified
        surround = surroundForType
          && surroundForType.hasOwnProperty(token.value)
          && surroundForType[token.value]
          && isFunction(surroundForType[token.value])
            ? surroundForType[token.value]
            : surroundForType._default

        start = token.range[0]
        end = token.range[1]

        addSplit(lastSplitEnd, start)
        info = { tokenIndex: tokenIdx, tokens: all, ast: ast, code: code }
        tokenIdx += addSplit(start, end, surround, info)
      }
    }

    if (lastSplitEnd < code.length) {
      addSplit(lastSplitEnd, code.length)
    }

  if (!opts.nojoin) {
    transformedCode = splits.join('')
    if (hashbang.length > 0) {
      transformedCode = hashbang + transformedCode.substr(hashbang.length)
    }
  }

    return {
        ast      :  ast
      , tokens   :  tokens
      , comments :  comments
      , splits   :  splits
      , code     :  transformedCode
    }
  }

  return exportFn ? exportFn(redeyed) : redeyed
}
})()
<commit_msg>fix: removing debugging code<commit_after>;(function() {
'use strict'
/* global define */

var esprima
var exportFn
var toString = Object.prototype.toString

if (typeof module === 'object' && typeof module.exports === 'object' && typeof require === 'function') {
  // server side
  esprima = require('esprima')
  exportFn = function(redeyed) { module.exports = redeyed }
  bootstrap(esprima, exportFn)
} else if (typeof define === 'function' && define.amd) {
  // client side
  // amd
  define(['esprima'], function(esprima) {
      return bootstrap(esprima)
  })
} else if (typeof window === 'object') {
  // no amd -> attach to window if it exists
  // Note that this requires 'esprima' to be defined on the window, so that script has to be loaded first
  window.redeyed = bootstrap(window.esprima)
}

function bootstrap(esprima, exportFn) {
  function isFunction(obj) {
    return toString.call(obj) === '[object Function]'
  }

  function isString(obj) {
    return toString.call(obj) === '[object String]'
  }

  function isObject(obj) {
    return toString.call(obj) === '[object Object]'
  }

  function surroundWith(before, after) {
    return function(s) { return before + s + after }
  }

  function isNonCircular(key) {
    return key !== '_parent'
  }

  function objectizeString(value) {
    var vals = value.split(':')

    if (vals.length === 0 || vals.length > 2)      {
 throw new Error(
        'illegal string config: ' + value +
        '\nShould be of format "before:after"'
      )
}

    if (vals.length === 1 || vals[1].length === 0) {
      return vals.indexOf(':') < 0 ? { _before: vals[0] } : { _after: vals[0] }
    } else {
      return { _before: vals[0], _after: vals[1] }
    }
  }

  function objectize(node) {
    // Converts 'bef:aft' to { _before: bef, _after: aft }
    // and resolves undefined before/after from parent or root

    function resolve(value, key) {
      // resolve before/after from root or parent if it isn't present on the current node
      if (!value._parent) return undefined

      // Immediate parent
      if (value._parent._default && value._parent._default[key]) return value._parent._default[key]

      // Root
      var root = value._parent._parent
      if (!root) return undefined

      return root._default ? root._default[key] : undefined
    }

    function process(key) {
      var value = node[key]

      if (!value) return
      if (isFunction(value)) return

      // normalize all strings to objects
      if (isString(value)) {
        node[key] = value = objectizeString(value)
      }

      value._parent = node
      if (isObject(value)) {
        if (!value._before && !value._after) return objectize(value)

        // resolve missing _before or _after from parent(s)
        // in case we only have either one on this node
        value._before =  value._before || resolve(value, '_before')
        value._after  =  value._after  || resolve(value, '_after')

        return
      }

      throw new Error('nodes need to be either {String}, {Object} or {Function}.' + value + ' is neither.')
    }

    // Process _default ones first so children can resolve missing before/after from them
    if (node._default) process('_default')

    Object.keys(node)
      .filter(function(key) {
        return isNonCircular(key)
          && node.hasOwnProperty(key)
          && key !== '_before'
          && key !== '_after'
          && key !== '_default'
      })
      .forEach(process)
  }

  function functionize(node) {
    Object.keys(node)
      .filter(function(key) {
        return isNonCircular(key) && node.hasOwnProperty(key)
      })
      .forEach(function(key) {
        var value = node[key]

        if (isFunction(value)) return

        if (isObject(value)) {
          if (!value._before && !value._after) return functionize(value)

          // at this point before/after were "inherited" from the parent or root
          // (see objectize)
          var before = value._before || ''
          var after = value._after || ''

          node[key] = surroundWith(before, after)
          return node[key]
        }
      })
  }

  function normalize(root) {
    objectize(root)
    functionize(root)
  }

  function mergeTokensAndComments(tokens, comments) {
    var all = {}

    function addToAllByRangeStart(t) { all[ t.range[0] ] = t }

    tokens.forEach(addToAllByRangeStart)
    comments.forEach(addToAllByRangeStart)

    // keys are sorted automatically
    return Object.keys(all)
      .map(function(k) { return all[k] })
  }

  function redeyed(code, config, opts) {
    opts = opts || {}
    var parser = opts.parser || esprima
    var jsx = !!opts.jsx
    // tokenizer doesn't support JSX at this point (esprima@4.0.0)
    // therefore we need to generate the AST via the parser not only to
    // avoid the tokenizer from erroring but also to get JSXIdentifier tokens
    var buildAst = jsx || !!opts.buildAst

    var hashbang =  ''
    var ast
    var tokens
    var comments
    var lastSplitEnd = 0
    var splits = []
    var transformedCode
    var all
    var info

    // Replace hashbang line with empty whitespaces to preserve token locations
    if (code[0] === '#' && code[1] === '!') {
      hashbang = code.substr(0, code.indexOf('\n') + 1)
      code = Array.apply(0, Array(hashbang.length)).join(' ') + '\n' + code.substr(hashbang.length)
    }

    if (buildAst) {
      ast = parser.parse(code, { tokens: true, comment: true, range: true, loc: true, tolerant: true, jsx: true })
      tokens = ast.tokens
      comments = ast.comments
    } else {
      tokens = []
      comments = []
      parser.tokenize(code, { range: true, loc: true, comment: true }, function(token) {
        if (token.type === 'LineComment') {
          token.type = 'Line'
          comments.push(token)
        } else if (token.type === 'BlockComment') {
          token.type = 'Block'
          comments.push(token)
        } else {
          // Optimistically upgrade 'static' to a keyword
          if (token.type === 'Identifier' && token.value === 'static') token.type = 'Keyword'
          tokens.push(token)
        }
      })
    }
    normalize(config)

    function tokenIndex(tokens, tkn, start) {
      var current
      var rangeStart = tkn.range[0]

      for (current = start; current < tokens.length; current++) {
        if (tokens[current].range[0] === rangeStart) return current
      }

      throw new Error('Token %s not found at or after index: %d', tkn, start)
    }

    function process(surround) {
      var result
      var currentIndex
      var nextIndex
      var skip = 0
      var splitEnd

      result = surround(code.slice(start, end), info)
      if (isObject(result)) {
        splits.push(result.replacement)

        currentIndex =  info.tokenIndex
        nextIndex    =  tokenIndex(info.tokens, result.skipPastToken, currentIndex)
        skip         =  nextIndex - currentIndex
        splitEnd     =  skip > 0 ? tokens[nextIndex - 1].range[1] : end
      } else {
        splits.push(result)
        splitEnd = end
      }

      return { skip: skip, splitEnd: splitEnd }
    }

    function addSplit(start, end, surround, info) {
      var result
      var skip = 0

      if (start >= end) return
      if (surround) {
        result       =  process(surround)
        skip         =  result.skip
        lastSplitEnd =  result.splitEnd
      } else {
        splits.push(code.slice(start, end))
        lastSplitEnd = end
      }

      return skip
    }

    all = mergeTokensAndComments(tokens, comments)
    for (var tokenIdx = 0; tokenIdx < all.length; tokenIdx++) {
      var token = all[tokenIdx]
      var surroundForType = config[token.type]
      var surround
      var start
      var end

      // At least the type (e.g., 'Keyword') needs to be specified for the token to be surrounded
      if (surroundForType) {
        // root defaults are only taken into account while resolving before/after otherwise
        // a root default would apply to everything, even if no type default was specified
        surround = surroundForType
          && surroundForType.hasOwnProperty(token.value)
          && surroundForType[token.value]
          && isFunction(surroundForType[token.value])
            ? surroundForType[token.value]
            : surroundForType._default

        start = token.range[0]
        end = token.range[1]

        addSplit(lastSplitEnd, start)
        info = { tokenIndex: tokenIdx, tokens: all, ast: ast, code: code }
        tokenIdx += addSplit(start, end, surround, info)
      }
    }

    if (lastSplitEnd < code.length) {
      addSplit(lastSplitEnd, code.length)
    }

  if (!opts.nojoin) {
    transformedCode = splits.join('')
    if (hashbang.length > 0) {
      transformedCode = hashbang + transformedCode.substr(hashbang.length)
    }
  }

    return {
        ast      :  ast
      , tokens   :  tokens
      , comments :  comments
      , splits   :  splits
      , code     :  transformedCode
    }
  }

  return exportFn ? exportFn(redeyed) : redeyed
}
})()
<|endoftext|>


<commit_before>/**
 * Backbone.GoogleMaps
 * A Backbone JS layer for the GoogleMaps API
 * Copyright (c)2012 Edan Schwartz
 * Distributed under MIT license
 * Minified by http://jscompress.com/
 * https://github.com/eschwartz/backbone.googlemaps
*/
Backbone.GoogleMaps=function(e,t,n){var r={};r.Location=e.Model.extend({constructor:function(){t.bindAll(this,"select","deselect","toggleSelect","getLatlng");this.defaults=t.extend({},this.defaults,{lat:0,lng:0,selected:false,title:""});e.Model.prototype.constructor.apply(this,arguments)},select:function(){if(!this.get("selected")){this.set("selected",true);this.trigger("selected",this)}},deselect:function(){if(this.get("selected")){this.set("selected",false);this.trigger("deselected",this)}},toggleSelect:function(){if(this.get("selected")){this.deselect()}else{this.select()}},getLatlng:function(){return new google.maps.LatLng(this.get("lat"),this.get("lng"))}});r.LocationCollection=e.Collection.extend({model:r.Location,constructor:function(){e.Collection.prototype.constructor.apply(this,arguments);this.on("selected",function(e){this.each(function(t){if(e.cid!==t.cid){t.deselect()}})},this)}});r.MapView=e.View.extend({mapEvents:{},overlayOptions:{},constructor:function(){e.View.prototype.constructor.apply(this,arguments);if(!google||!google.maps)throw new Error("Google maps API is not loaded.");if(!this.options.map&&!this.map)throw new Error("A map must be specified.");this.gOverlay=this.map=this.options.map||this.map;this.overlayOptions||(this.overlayOptions=this.options.overlayOptions)},bindMapEvents:function(e){e||(e=this.mapEvents);for(event in this.mapEvents){var t=this.mapEvents[event];google.maps.event.addListener(this.gOverlay,event,this[t])}},render:function(){if(this.beforeRender){this.beforeRender()}this.bindMapEvents();if(this.onRender){this.onRender()}},close:function(){if(this.beforeClose){this.beforeClose()}google.maps.event.clearInstanceListeners(this.gOverlay);this.gOverlay.setMap(null);this.gOverlay=null}});r.InfoWindow=r.MapView.extend({constructor:function(){r.MapView.prototype.constructor.apply(this,arguments);t.bindAll(this,"render","close");if(!this.options.marker&&!this.marker)throw new Error("A marker must be specified for InfoWindow view.");this.marker=this.options.marker||this.marker;this.template=this.template||this.options.template},render:function(){if(this.beforeRender){this.beforeRender()}r.MapView.prototype.render.apply(this,arguments);var e=this.template?n(this.template).html():"
<%=title %>
";this.$el.html(t.template(e,this.model.toJSON()));this.gOverlay=new google.maps.InfoWindow(t.extend({content:this.$el[0]},this.overlayOptions));this.gOverlay.open(this.map,this.marker);if(this.onRender){this.onRender()}return this},close:function(){if(this.beforeClose){this.beforeClose()}r.MapView.prototype.close.apply(this,arguments);if(this.onClose){this.onClose()}return this}});r.MarkerView=r.MapView.extend({infoWindow:r.InfoWindow,constructor:function(){r.MapView.prototype.constructor.apply(this,arguments);t.bindAll(this,"render","close","openDetail","closeDetail","toggleSelect");if(!this.model)throw new Error("A model must be specified for a MarkerView");this.gOverlay=new google.maps.Marker(t.extend({position:this.model.getLatlng(),map:this.map,title:this.model.title,animation:google.maps.Animation.DROP,visible:false},this.overlayOptions));t.extend(this.mapEvents,{click:"toggleSelect"});this.model.on("selected",this.openDetail,this);this.model.on("deselected",this.closeDetail,this)},toggleSelect:function(){this.model.toggleSelect()},render:function(){if(this.beforeRender){this.beforeRender()}r.MapView.prototype.render.apply(this,arguments);this.gOverlay.setVisible(true);if(this.onRender){this.onRender()}return this},close:function(){if(this.beforeClose){this.beforeClose()}this.closeDetail();r.MapView.prototype.close.apply(this,arguments);if(this.onClose){this.onClose()}return this},openDetail:function(){this.detailView=new this.infoWindow({model:this.model,map:this.options.map,marker:this.gOverlay});this.detailView.render()},closeDetail:function(){if(this.detailView){this.detailView.close();this.detailView=null}}});r.MarkerCollectionView=e.View.extend({markerView:r.MarkerView,markerViewChildren:{},constructor:function(){e.View.prototype.constructor.apply(this,arguments);t.bindAll(this,"render","closeChildren","closeChild","addChild","refresh","close");if(!this.options.map&&!this.map)throw new Error("A map must be specified on MarkerCollectionView instantiation");this.map||(this.map=this.options.map);this.collection.on("reset",this.refresh,this);this.collection.on("add",this.addChild,this);this.collection.on("remove",this.closeChild,this)},render:function(e){var e=e||this.collection;e.each(this.addChild)},closeChildren:function(){for(cid in this.markerViewChildren){this.closeChild(this.markerViewChildren[cid])}},closeChild:function(t){var n=t instanceof e.Model?this.markerViewChildren[t.cid]:t;n.close();delete this.markerViewChildren[n.model.cid]},addChild:function(e){var t=new this.markerView({model:e,map:this.map});this.markerViewChildren[e.cid]=t;t.render()},refresh:function(){this.closeChildren();this.render()},close:function(){this.closeChildren()}});return r}(Backbone,_,window.jQuery||window.Zepto||window.ender)<commit_msg>Update minified library with pull request #1 from mooreds/broken_example_code<commit_after>/**
 * Backbone.GoogleMaps
 * A Backbone JS layer for the GoogleMaps API
 * Copyright (c)2013 Edan Schwartz
 * Distributed under MIT license
 * https://github.com/eschwartz/backbone.googlemaps
*/
Backbone.GoogleMaps=function(e,t,n){var r={};r.Location=e.Model.extend({constructor:function(){t.bindAll(this,"select","deselect","toggleSelect","getLatlng");this.defaults=t.extend({},this.defaults,{lat:0,lng:0,selected:false,title:""});e.Model.prototype.constructor.apply(this,arguments)},select:function(){if(!this.get("selected")){this.set("selected",true);this.trigger("selected",this)}},deselect:function(){if(this.get("selected")){this.set("selected",false);this.trigger("deselected",this)}},toggleSelect:function(){if(this.get("selected")){this.deselect()}else{this.select()}},getLatlng:function(){return new google.maps.LatLng(this.get("lat"),this.get("lng"))}});r.LocationCollection=e.Collection.extend({model:r.Location,constructor:function(){e.Collection.prototype.constructor.apply(this,arguments);this.on("selected",function(e){this.each(function(t){if(e.cid!==t.cid){t.deselect()}})},this)}});r.MapView=e.View.extend({mapEvents:{},overlayOptions:{},constructor:function(){e.View.prototype.constructor.apply(this,arguments);if(!google||!google.maps)throw new Error("Google maps API is not loaded.");if(!this.options.map&&!this.map)throw new Error("A map must be specified.");this.gOverlay=this.map=this.options.map||this.map;this.overlayOptions||(this.overlayOptions=this.options.overlayOptions)},bindMapEvents:function(e){e||(e=this.mapEvents);for(event in this.mapEvents){var t=this.mapEvents[event];google.maps.event.addListener(this.gOverlay,event,this[t])}},render:function(){if(this.beforeRender){this.beforeRender()}this.bindMapEvents();if(this.onRender){this.onRender()}},close:function(){if(this.beforeClose){this.beforeClose()}google.maps.event.clearInstanceListeners(this.gOverlay);this.gOverlay.setMap(null);this.gOverlay=null}});r.InfoWindow=r.MapView.extend({constructor:function(){r.MapView.prototype.constructor.apply(this,arguments);t.bindAll(this,"render","close");if(!this.options.marker&&!this.marker)throw new Error("A marker must be specified for InfoWindow view.");this.marker=this.options.marker||this.marker;this.template=this.template||this.options.template},render:function(){if(this.beforeRender){this.beforeRender()}r.MapView.prototype.render.apply(this,arguments);var e=this.template?n(this.template).html():"
<%=title %>
";this.$el.html(t.template(e,this.model.toJSON()));this.gOverlay=new google.maps.InfoWindow(t.extend({content:this.$el[0]},this.overlayOptions));this.gOverlay.open(this.map,this.marker);if(this.onRender){this.onRender()}return this},close:function(){if(this.beforeClose){this.beforeClose()}r.MapView.prototype.close.apply(this,arguments);if(this.onClose){this.onClose()}return this}});r.MarkerView=r.MapView.extend({infoWindow:r.InfoWindow,constructor:function(){r.MapView.prototype.constructor.apply(this,arguments);t.bindAll(this,"render","close","openDetail","closeDetail","toggleSelect");if(!this.model)throw new Error("A model must be specified for a MarkerView");this.gOverlay=new google.maps.Marker(t.extend({position:this.model.getLatlng(),map:this.map,title:this.model.title,animation:google.maps.Animation.DROP,visible:false},this.overlayOptions));t.extend(this.mapEvents,{click:"toggleSelect"});this.model.on("selected",this.openDetail,this);this.model.on("deselected",this.closeDetail,this)},toggleSelect:function(){this.model.toggleSelect()},render:function(){if(this.beforeRender){this.beforeRender()}r.MapView.prototype.render.apply(this,arguments);this.gOverlay.setVisible(true);if(this.onRender){this.onRender()}return this},close:function(){if(this.beforeClose){this.beforeClose()}this.closeDetail();r.MapView.prototype.close.apply(this,arguments);if(this.onClose){this.onClose()}return this},openDetail:function(){this.detailView=new this.infoWindow({model:this.model,map:this.options.map,marker:this.gOverlay});this.detailView.render()},closeDetail:function(){if(this.detailView){this.detailView.close();this.detailView=null}}});r.MarkerCollectionView=e.View.extend({markerView:r.MarkerView,markerViewChildren:{},constructor:function(){e.View.prototype.constructor.apply(this,arguments);t.bindAll(this,"render","closeChildren","closeChild","addChild","refresh","close");if(!this.options.map&&!this.map)throw new Error("A map must be specified on MarkerCollectionView instantiation");this.map||(this.map=this.options.map);this.collection.on("reset",this.refresh,this);this.collection.on("add",this.addChild,this);this.collection.on("remove",this.closeChild,this)},render:function(e){var e=e||this.collection;e.each(this.addChild)},closeChildren:function(){for(cid in this.markerViewChildren){this.closeChild(this.markerViewChildren[cid])}},closeChild:function(t){var n=t instanceof e.Model?this.markerViewChildren[t.cid]:t;n.close();delete this.markerViewChildren[n.model.cid]},addChild:function(e){var t=new this.markerView({model:e,map:this.map});this.markerViewChildren[e.cid]=t;t.render()},refresh:function(){this.closeChildren();this.render()},close:function(){this.closeChildren()}});return r}(Backbone,_,window.jQuery||window.Zepto||window.ender)
<|endoftext|>


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

if (typeof require != "undefined") {
    buster = require("buster-core");
    buster.eventEmitter = require("buster-event-emitter");
    buster.promise = require("buster-promise");
}

(function (B) {
    var thenable = buster.promise.thenable;
    var sequential = buster.promise.sequential;

    function processAll(opt, method, items) {
        var i = 0, args = Array.prototype.slice.call(arguments, 3);
        var runner = this;
        items = items || [];

        return sequential({
            shift: function () {
                var item = items[i++];

                if (item) {
                    return function () {
                        return runner[method].apply(runner, [item].concat(args));
                    };
                } else {
                    return null;
                }
            }
        }, opt);
    }

    function all() {
        var args = Array.prototype.slice.call(arguments);
        return processAll.apply(this, [{ error: function () {} }].concat(args));
    }

    function noisyAll() {
        var args = Array.prototype.slice.call(arguments);
        return processAll.apply(this, [null].concat(args));
    }

    function asyncFunction(func, thisObj) {
        var promise, arg;

        if (func.length == 1) {
            promise = buster.promise.create();

            arg = function (err) {
                try {
                    if (err) {
                        promise.reject(err);
                    } else {
                        promise.resolve();
                    }
                } catch (e) {}
            };
        }

        return func.call(thisObj, arg) || promise;
    }

    function getAll(context, getter, appendMethod) {
        var funcs = [];

        while (context) {
            if (typeof context[getter] == "function") {
                funcs[appendMethod](context[getter]);
            }

            context = context.parent;
        }

        return funcs;
    }

    function getResults(runner) {
        if (!runner.results) {
            runner.results = {
                contexts: 0,
                tests: 0,
                errors: 0,
                failures: 0,
                assertions: 0,
                timeouts: 0,
                deferred: 0
            };
        }

        return runner.results;
    }

    function fireOnCreate(instance, runner) {
        var callbacks = instance.callbacks || [];

        for (var i = 0, l = callbacks.length; i < l; ++i) {
            callbacks[i](runner);
        }
    }

    var exceptionListener = {};

    if (typeof process != "undefined") {
        process.on("uncaughtException", function (err) {
            if (err.name == "AssertionError" ||
                typeof exceptionListener.listen != "function") {
                throw err;
            }

            exceptionListener.listen(err);
        });
    }

    B.testRunner = B.extend(B.create(B.eventEmitter), {
        failOnNoAssertions: true,
        timeout: 250,

        create: function (opt) {
            opt = opt || {};
            var runner = buster.create(this);

            if (typeof opt.timeout == "number") {
                runner.timeout = opt.timeout;
            }

            if (typeof opt.failOnNoAssertions == "boolean") {
                runner.failOnNoAssertions = opt.failOnNoAssertions
            }

            fireOnCreate(this, runner);

            return runner;
        },

        onCreate: function (callback) {
            this.callbacks = this.callbacks || [];

            if (typeof callback == "function") {
                this.callbacks.push(callback);
            } else {
                throw new TypeError("onCreate callback " + callback + " is not a function");
            }
        },

        runSuite: function (contexts) {
            this.emit("suite:start");
            var self = this, i = 0;
            var results = getResults(this);
            var promise = buster.promise.create();

            sequential({
                shift: function () {
                    var context = contexts[i++];

                    if (context) {
                        results.contexts += 1;
                        return B.bind(self, "run", context);
                    } else {
                        return null;
                    }
                }
            }).then(function () {
                results.ok = results.errors == 0 && results.failures == 0 &&
                    results.timeouts == 0;

                if (self.failOnNoAssertions && results.assertions == 0) {
                    results.ok = false;
                }

                self.emit("suite:end", results);
                promise.resolve();
            });

            return promise;
        },

        run: function (context) {
            this.emit("context:start", context);
            var promise = buster.promise.create();
            var self = this;
            exceptionListener.listen = buster.bind(this, "emit", "uncaughtException");

            if (!context) {
                return promise.reject();
            }

            var setUps = getAll(context, "setUp", "unshift");
            var tearDowns = getAll(context, "tearDown", "push");
            var testCase = context.testCase;

            sequential([
                B.bind(this, all, "runTest", context.tests, setUps, tearDowns, testCase),
                B.bind(this, all, "run", context.contexts)
            ]).then(function () {
                self.emit("context:end", context);
                promise.resolve();
            });

            return promise;
        },

        runTest: function (test, setUps, tearDowns, testCase) {
            if (this.isDeferred(test)) {
                return this.deferTest(test);
            }

            var self = this, results = getResults(this);
            var promise = buster.promise.create();
            testCase = B.create(testCase);

            function cleanUp(err) {
                function done(err2) {
                    var assertions = self.assertionCount();
                    var error = err || err2 || self.verifyAssertionCount(testCase);
                    delete testCase.expectedAssertions;

                    if (!error) {
                        if (!test.timeout) {
                            results.assertions += assertions;

                            self.emit("test:success", {
                                name: test.name,
                                assertions: assertions
                            });
                        }
                    } else {
                        self.error(error, test);
                    }

                    results.tests += 1;
                    promise.resolve();
                }

                self.runTearDowns(tearDowns, test, testCase).then(done, done);
            }

            sequential([
                B.bind(this, "runSetUps", setUps, test, testCase),
                B.bind(this, "emit", "test:start", { name: test.name, testCase: testCase }),
                B.bind(this, "runTestFunction", test, testCase)
            ]).then(cleanUp, cleanUp);

            return promise;
        },

        runTestFunction: function (test, testCase) {
            var result = asyncFunction(test.func, testCase);

            if (result && result.then) {
                if (!test.asyncEmitted) {
                    this.emit("test:async", { name: test.name });
                }

                this.timebox(test, result);
            }

            return thenable(result);
        },

        runSetUps: function (setUps, test, testCase) {
            this.emit("test:setUp", { name: test.name, testCase: testCase });
            return noisyAll.call(this, "runSetUp", setUps, test, testCase);
        },

        runSetUp: function (setUp, test, testCase) {
            var promise = this.timebox(test, asyncFunction(setUp, testCase));

            if (promise && !test.asyncEmitted) {
                test.asyncEmitted = true;
                this.emit("test:async", { name: test.name });
            }

            return promise;
        },

        runTearDowns: function (tearDowns, test, testCase) {
            this.emit("test:tearDown", { name: test.name, testCase: testCase });
            return noisyAll.call(this, "runTearDown", tearDowns, test, testCase);
        },

        runTearDown: function (tearDown, test, testCase) {
            var promise = this.timebox(test, asyncFunction(tearDown, testCase));

            if (promise && !test.asyncEmitted) {
                this.emit("test:async", { name: test.name });
            }

            return promise;
        },

        timebox: function (test, promise) {
            if (!promise) {
                return;
            }

            var self = this;

            var timer = setTimeout(function () {
                try {
                    promise.resolve();
                    self.emit("test:timeout", { name: test.name });
                    test.timeout = true;
                    getResults(self).timeouts += 1;
                } catch (e) {}
            }, this.timeout);

            promise.then(function () {
                clearTimeout(timer);
            });

            return promise;
        },

        isDeferred: function (test) {
            return /^\/\//.test(test.name);
        },

        deferTest: function (test) {
            test.name = test.name.replace(/^\/\/\s*/, "");
            this.emit("test:deferred", test);
            getResults(this).deferred += 1;
        },

        error: function (error, test) {
            var data = {
                name: test.name,
                error: {
                    name: error.name,
                    message: error.message,
                    stack: error.stack
                }
            };

            var results = getResults(this);

            if (error.name == "AssertionError") {
                results.failures += 1;
                this.emit("test:failure", data);
            } else {
                results.errors += 1;
                this.emit("test:error", data);
            }
        },

        assertionCount: function () {},

        verifyAssertionCount: function (testCase) {
            var message, assertions = this.assertionCount();
            var expected = testCase.expectedAssertions;

            if (this.failOnNoAssertions && assertions == 0) {
                message = "No assertions!";
            }

            if (expected && assertions != expected) {
                message = "Expected " + expected + " assertions, ran " + assertions;
            }

            if (message) {
                try {
                    var error = new Error(message);
                    error.name = "AssertionError";
                    throw error;
                } catch (e) {
                    return e;
                }
            }
        }
    });
}(buster));

if (typeof module != "undefined") {
    module.exports = buster.testRunner
}
<commit_msg>Catch uncaught exceptions conservatively. Provide option to disable feature<commit_after>var buster = buster || {};

if (typeof require != "undefined") {
    buster = require("buster-core");
    buster.eventEmitter = require("buster-event-emitter");
    buster.promise = require("buster-promise");
}

(function (B) {
    var thenable = buster.promise.thenable;
    var sequential = buster.promise.sequential;

    function processAll(opt, method, items) {
        var i = 0, args = Array.prototype.slice.call(arguments, 3);
        var runner = this;
        items = items || [];

        return sequential({
            shift: function () {
                var item = items[i++];

                if (item) {
                    return function () {
                        return runner[method].apply(runner, [item].concat(args));
                    };
                } else {
                    return null;
                }
            }
        }, opt);
    }

    function all() {
        var args = Array.prototype.slice.call(arguments);
        return processAll.apply(this, [{ error: function () {} }].concat(args));
    }

    function noisyAll() {
        var args = Array.prototype.slice.call(arguments);
        return processAll.apply(this, [null].concat(args));
    }

    function asyncFunction(func, thisObj) {
        var promise, arg;

        if (func.length == 1) {
            promise = buster.promise.create();

            arg = function (err) {
                try {
                    if (err) {
                        promise.reject(err);
                    } else {
                        promise.resolve();
                    }
                } catch (e) {}
            };
        }

        return func.call(thisObj, arg) || promise;
    }

    function getAll(context, getter, appendMethod) {
        var funcs = [];

        while (context) {
            if (typeof context[getter] == "function") {
                funcs[appendMethod](context[getter]);
            }

            context = context.parent;
        }

        return funcs;
    }

    function getResults(runner) {
        if (!runner.results) {
            runner.results = {
                contexts: 0,
                tests: 0,
                errors: 0,
                failures: 0,
                assertions: 0,
                timeouts: 0,
                deferred: 0
            };
        }

        return runner.results;
    }

    function fireOnCreate(instance, runner) {
        var callbacks = instance.callbacks || [];

        for (var i = 0, l = callbacks.length; i < l; ++i) {
            callbacks[i](runner);
        }
    }

    var exceptionListener = {};

    function uncaughtListener(err) {
        if (err.name != "AssertionError" &&
            typeof exceptionListener.listen == "function") {
            exceptionListener.listen(err);
        }
    }

    function catchUncaughtExceptions(listener) {
        if (typeof process != "undefined") {
            if (!exceptionListener.listen) {
                process.on("uncaughtException", uncaughtListener);
            }

            exceptionListener.listen = listener;
        }
    }

    function releaseUncaughtExceptions() {
        process.removeListener("uncaughtException", uncaughtListener);
        delete exceptionListener.listen;
    }

    B.testRunner = B.extend(B.create(B.eventEmitter), {
        failOnNoAssertions: true,
        timeout: 250,
        handleUncaughtExceptions: true,

        create: function (opt) {
            opt = opt || {};
            var runner = buster.create(this);

            if (typeof opt.timeout == "number") {
                runner.timeout = opt.timeout;
            }

            if (typeof opt.failOnNoAssertions == "boolean") {
                runner.failOnNoAssertions = opt.failOnNoAssertions
            }

            fireOnCreate(this, runner);

            return runner;
        },

        onCreate: function (callback) {
            this.callbacks = this.callbacks || [];

            if (typeof callback == "function") {
                this.callbacks.push(callback);
            } else {
                throw new TypeError("onCreate callback " + callback + " is not a function");
            }
        },

        runSuite: function (contexts) {
            this.emit("suite:start");
            var self = this, i = 0;
            var results = getResults(this);
            var promise = buster.promise.create();

            sequential({
                shift: function () {
                    var context = contexts[i++];

                    if (context) {
                        results.contexts += 1;
                        return B.bind(self, "run", context);
                    } else {
                        return null;
                    }
                }
            }).then(function () {
                results.ok = results.errors == 0 && results.failures == 0 &&
                    results.timeouts == 0;

                if (self.failOnNoAssertions && results.assertions == 0) {
                    results.ok = false;
                }

                self.emit("suite:end", results);
                releaseUncaughtExceptions();
                promise.resolve();
            });

            return promise;
        },

        run: function (context) {
            this.emit("context:start", context);
            var promise = buster.promise.create();
            var self = this;

            if (this.handleUncaughtExceptions) {
                catchUncaughtExceptions(buster.bind(this, "emit", "uncaughtException"));
            }

            if (!context) {
                return promise.reject();
            }

            var setUps = getAll(context, "setUp", "unshift");
            var tearDowns = getAll(context, "tearDown", "push");
            var testCase = context.testCase;

            sequential([
                B.bind(this, all, "runTest", context.tests, setUps, tearDowns, testCase),
                B.bind(this, all, "run", context.contexts)
            ]).then(function () {
                self.emit("context:end", context);
                promise.resolve();
            });

            return promise;
        },

        runTest: function (test, setUps, tearDowns, testCase) {
            if (this.isDeferred(test)) {
                return this.deferTest(test);
            }

            var self = this, results = getResults(this);
            var promise = buster.promise.create();
            testCase = B.create(testCase);

            function cleanUp(err) {
                function done(err2) {
                    var assertions = self.assertionCount();
                    var error = err || err2 || self.verifyAssertionCount(testCase);
                    delete testCase.expectedAssertions;

                    if (!error) {
                        if (!test.timeout) {
                            results.assertions += assertions;

                            self.emit("test:success", {
                                name: test.name,
                                assertions: assertions
                            });
                        }
                    } else {
                        self.error(error, test);
                    }

                    results.tests += 1;
                    promise.resolve();
                }

                self.runTearDowns(tearDowns, test, testCase).then(done, done);
            }

            sequential([
                B.bind(this, "runSetUps", setUps, test, testCase),
                B.bind(this, "emit", "test:start", { name: test.name, testCase: testCase }),
                B.bind(this, "runTestFunction", test, testCase)
            ]).then(cleanUp, cleanUp);

            return promise;
        },

        runTestFunction: function (test, testCase) {
            var result = asyncFunction(test.func, testCase);

            if (result && result.then) {
                if (!test.asyncEmitted) {
                    this.emit("test:async", { name: test.name });
                }

                this.timebox(test, result);
            }

            return thenable(result);
        },

        runSetUps: function (setUps, test, testCase) {
            this.emit("test:setUp", { name: test.name, testCase: testCase });
            return noisyAll.call(this, "runSetUp", setUps, test, testCase);
        },

        runSetUp: function (setUp, test, testCase) {
            var promise = this.timebox(test, asyncFunction(setUp, testCase));

            if (promise && !test.asyncEmitted) {
                test.asyncEmitted = true;
                this.emit("test:async", { name: test.name });
            }

            return promise;
        },

        runTearDowns: function (tearDowns, test, testCase) {
            this.emit("test:tearDown", { name: test.name, testCase: testCase });
            return noisyAll.call(this, "runTearDown", tearDowns, test, testCase);
        },

        runTearDown: function (tearDown, test, testCase) {
            var promise = this.timebox(test, asyncFunction(tearDown, testCase));

            if (promise && !test.asyncEmitted) {
                this.emit("test:async", { name: test.name });
            }

            return promise;
        },

        timebox: function (test, promise) {
            if (!promise) {
                return;
            }

            var self = this;

            var timer = setTimeout(function () {
                try {
                    promise.resolve();
                    self.emit("test:timeout", { name: test.name });
                    test.timeout = true;
                    getResults(self).timeouts += 1;
                } catch (e) {}
            }, this.timeout);

            promise.then(function () {
                clearTimeout(timer);
            });

            return promise;
        },

        isDeferred: function (test) {
            return /^\/\//.test(test.name);
        },

        deferTest: function (test) {
            test.name = test.name.replace(/^\/\/\s*/, "");
            this.emit("test:deferred", test);
            getResults(this).deferred += 1;
        },

        error: function (error, test) {
            var data = {
                name: test.name,
                error: {
                    name: error.name,
                    message: error.message,
                    stack: error.stack
                }
            };

            var results = getResults(this);

            if (error.name == "AssertionError") {
                results.failures += 1;
                this.emit("test:failure", data);
            } else {
                results.errors += 1;
                this.emit("test:error", data);
            }
        },

        assertionCount: function () {},

        verifyAssertionCount: function (testCase) {
            var message, assertions = this.assertionCount();
            var expected = testCase.expectedAssertions;

            if (this.failOnNoAssertions && assertions == 0) {
                message = "No assertions!";
            }

            if (expected && assertions != expected) {
                message = "Expected " + expected + " assertions, ran " + assertions;
            }

            if (message) {
                try {
                    var error = new Error(message);
                    error.name = "AssertionError";
                    throw error;
                } catch (e) {
                    return e;
                }
            }
        }
    });
}(buster));

if (typeof module != "undefined") {
    module.exports = buster.testRunner
}
<|endoftext|>


<commit_before>//! rhombus.js
//! authors: Spencer Phippen, Tim Grant
//! license: MIT

(function(context) {
  var r = {};
  context.rhombus = r;

  r.startPlayback = function() {

  };

  r.stopPlayback = function() {

  };

  r.getPosition = function() {

  };

  r.moveToPosition = function(tick) {

  };

  r.getLoopEnabled = function() {

  };

  r.setLoopEnabled = function(enabled) {

  };

  r.getLoopStart = function() {

  };

  r.setLoopStart = function(tick) {

  };

  r.getLoopEnd = function() {

  };

  r.setLoopEnd = function() {

  };

  r.getNoteCount = function() {

  };

  r.getNote = function(index) {

  };

  r.insertNote = function(pitch, start, length) {

  };

  function Note(pitch, start, length) {

  };

  Note.prototype = {
    getPitch: function() {

    },

    setPitch: function(pitch) {

    },

    getStart: function() {

    },

    setStart: function (start) {

    },

    getLength: function() {

    },

    setLength: function(length) {

    }
  };

})(this);
<commit_msg>Added Note delete function to interface<commit_after>//! rhombus.js
//! authors: Spencer Phippen, Tim Grant
//! license: MIT

(function(context) {
  var r = {};
  context.rhombus = r;

  r.startPlayback = function() {

  };

  r.stopPlayback = function() {

  };

  r.getPosition = function() {

  };

  r.moveToPosition = function(tick) {

  };

  r.getLoopEnabled = function() {

  };

  r.setLoopEnabled = function(enabled) {

  };

  r.getLoopStart = function() {

  };

  r.setLoopStart = function(tick) {

  };

  r.getLoopEnd = function() {

  };

  r.setLoopEnd = function() {

  };

  r.getNoteCount = function() {

  };

  r.getNote = function(index) {

  };

  r.insertNote = function(pitch, start, length) {

  };

  function Note(pitch, start, length) {

  };

  Note.prototype = {
    getPitch: function() {

    },

    setPitch: function(pitch) {

    },

    getStart: function() {

    },

    setStart: function (start) {

    },

    getLength: function() {

    },

    setLength: function(length) {

    },

    delete: function(length) {

    }
  };

})(this);
<|endoftext|>


<commit_before>import { inverse, Matrix } from 'ml-matrix';

/**
 * Difference of the matrix function over the parameters
 * @ignore
 * @param {{x:Array<number>, y:Array<number>}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param {Array<number>} evaluatedData - Array of previous evaluated function values
 * @param {Array<number>} params - Array of previous parameter values
 * @param {number} gradientDifference - Adjustment for decrease the damping parameter
 * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter
 * @return {Matrix}
 */
function gradientFunction(
  data,
  evaluatedData,
  params,
  gradientDifference,
  paramFunction,
) {
  const n = params.length;
  const m = data.x.length;

  let ans = new Array(n);

  for (let param = 0; param < n; param++) {
    ans[param] = new Array(m);
    let auxParams = params.concat();
    auxParams[param] += gradientDifference;
    let funcParam = paramFunction(auxParams);

    for (let point = 0; point < m; point++) {
      ans[param][point] = evaluatedData[point] - funcParam(data.x[point]);
    }
  }
  return new Matrix(ans);
}

/**
 * Matrix function over the samples
 * @ignore
 * @param {{x:Array<number>, y:Array<number>}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param {Array<number>} evaluatedData - Array of previous evaluated function values
 * @return {Matrix}
 */
function matrixFunction(data, evaluatedData) {
  const m = data.x.length;

  let ans = new Array(m);

  for (let point = 0; point < m; point++) {
    ans[point] = [data.y[point] - evaluatedData[point]];
  }

  return new Matrix(ans);
}

/**
 * Iteration for Levenberg-Marquardt
 * @ignore
 * @param {{x:Array<number>, y:Array<number>}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param {Array<number>} params - Array of previous parameter values
 * @param {number} damping - Levenberg-Marquardt parameter
 * @param {number} gradientDifference - Adjustment for decrease the damping parameter
 * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter
 * @return {Array<number>}
 */
export default function step(
  data,
  params,
  damping,
  gradientDifference,
  parameterizedFunction,
) {
  let value = damping * gradientDifference * gradientDifference;
  let identity = Matrix.eye(params.length, params.length, value);

  const func = parameterizedFunction(params);
  let evaluatedData = data.x.map((e) => func(e));

  let gradientFunc = gradientFunction(
    data,
    evaluatedData,
    params,
    gradientDifference,
    parameterizedFunction,
  );
  let matrixFunc = matrixFunction(data, evaluatedData);
  let inverseMatrix = inverse(
    identity.add(gradientFunc.mmul(gradientFunc.transpose())),
  );

  params = new Matrix([params]);
  params = params.sub(
    inverseMatrix
      .mmul(gradientFunc)
      .mmul(matrixFunc)
      .mul(gradientDifference)
      .transpose(),
  );

  return params.to1DArray();
}
<commit_msg>be able to use typed arrays<commit_after>import { inverse, Matrix } from 'ml-matrix';

/**
 * Difference of the matrix function over the parameters
 * @ignore
 * @param {{x:Array<number>, y:Array<number>}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param {Array<number>} evaluatedData - Array of previous evaluated function values
 * @param {Array<number>} params - Array of previous parameter values
 * @param {number} gradientDifference - Adjustment for decrease the damping parameter
 * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter
 * @return {Matrix}
 */
function gradientFunction(
  data,
  evaluatedData,
  params,
  gradientDifference,
  paramFunction,
) {
  const n = params.length;
  const m = data.x.length;

  let ans = new Array(n);

  for (let param = 0; param < n; param++) {
    ans[param] = new Array(m);
    let auxParams = params.slice();
    auxParams[param] += gradientDifference;
    let funcParam = paramFunction(auxParams);

    for (let point = 0; point < m; point++) {
      ans[param][point] = evaluatedData[point] - funcParam(data.x[point]);
    }
  }
  return new Matrix(ans);
}

/**
 * Matrix function over the samples
 * @ignore
 * @param {{x:Array<number>, y:Array<number>}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param {Array<number>} evaluatedData - Array of previous evaluated function values
 * @return {Matrix}
 */
function matrixFunction(data, evaluatedData) {
  const m = data.x.length;

  let ans = new Array(m);

  for (let point = 0; point < m; point++) {
    ans[point] = [data.y[point] - evaluatedData[point]];
  }

  return new Matrix(ans);
}

/**
 * Iteration for Levenberg-Marquardt
 * @ignore
 * @param {{x:Array<number>, y:Array<number>}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param {Array<number>} params - Array of previous parameter values
 * @param {number} damping - Levenberg-Marquardt parameter
 * @param {number} gradientDifference - Adjustment for decrease the damping parameter
 * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter
 * @return {Array<number>}
 */
export default function step(
  data,
  params,
  damping,
  gradientDifference,
  parameterizedFunction,
) {
  let value = damping * gradientDifference * gradientDifference;
  let identity = Matrix.eye(params.length, params.length, value);

  const func = parameterizedFunction(params);
  let evaluatedData = data.x.map((e) => func(e));

  let gradientFunc = gradientFunction(
    data,
    evaluatedData,
    params,
    gradientDifference,
    parameterizedFunction,
  );
  let matrixFunc = matrixFunction(data, evaluatedData);
  let inverseMatrix = inverse(
    identity.add(gradientFunc.mmul(gradientFunc.transpose())),
  );

  params = new Matrix([params]);
  params = params.sub(
    inverseMatrix
      .mmul(gradientFunc)
      .mmul(matrixFunc)
      .mul(gradientDifference)
      .transpose(),
  );

  return params.to1DArray();
}
<|endoftext|>


<commit_before>(function () {
  'use strict';

  var colors         = require('colors');
  var strip          = require('cli-color/strip');
  var fs             = require('fs');
  var prompt         = require('prompt-sync');
  var child_process  = require('child_process');
  var pkg            = require('./package.json');
  var oldVersion     = pkg.version;
  var abortCmds      = [ 'git checkout master', 'rm abort push' ];
  var pushCmds       = [ 'rm abort push'];
  var cleanupCmds    = [];
  var defaultOptions = { encoding: 'utf-8' };
  var origin         = 'https://github.com/angular/material.git';
  var lineWidth      = 65;
  var newVersion;

  if (validate()) {
    newVersion = getNewVersion();

    line();

    checkoutVersionBranch();
    updateVersion();
    createChangelog();
    commitChanges();
    tagRelease();
    cloneRepo('bower-material');
    updateBowerVersion();
    cloneRepo('code.material.angularjs.org');
    updateSite();
    updateMaster();
    writeScript('abort', abortCmds.concat(cleanupCmds));
    writeScript('push', pushCmds.concat(cleanupCmds));

    line();
    log('Your repo is ready to be pushed.');
    log('Please look over {{"CHANGELOG.md".cyan}} and make any changes.');
    log('When you are ready, please run "{{"./push".cyan}}" to finish the process.');
    log('If you would like to cancel this release, please run "./abort"');
  }

  //-- utility methods

  function validate () {
    if (exec('npm whoami') !== 'angularcore') {
      err('You must be authenticated with npm as "angularcore" to perform a release.');
    } else if (exec('git rev-parse --abbrev-ref HEAD') !== 'master') {
      err('Releases can only performed from master at this time.');
    } else if (exec('git pull -q --rebase {{origin}} master') instanceof Error) {
      err('Please make sure your local branch is synced with origin/master.');
    } else {
      return true;
    }
    function err (msg) {
      var str = 'Error: ' + msg;
      log(str.red);
    }
  }

  function checkoutVersionBranch () {
    exec('git checkout -q -b release/{{newVersion}}');
    abortCmds.push('git branch -D release/{{newVersion}}');
  }

  function updateVersion () {
    start('Updating {{"package.json".cyan}} version from {{oldVersion.cyan}} to {{newVersion.cyan}}...');
    pkg.version = newVersion;
    fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
    done();
    abortCmds.push('git checkout package.json');
    pushCmds.push('git add package.json');
  }

  function createChangelog () {
    start('Generating changelog from {{oldVersion.cyan}} to {{newVersion.cyan}}...');
    exec([
      'git fetch --tags',
      'gulp changelog --sha=$(git merge-base v{{oldVersion}} HEAD)'
    ]);
    done();
    abortCmds.push('git checkout CHANGELOG.md');
    pushCmds.push('git add CHANGELOG.md');
  }

  function clear () {
    write("\u001b[2J\u001b[0;0H");
  }

  function getNewVersion () {
    clear();
    var options = getVersionOptions(oldVersion), key, type, version;
    log('The current version is {{oldVersion.cyan}}.');
    log('');
    log('What type of release is this?');
    for (key in options) { log((+key + 1) + ') ' + options[key].cyan); }
    log('');
    write('Please select a new version: ');
    type = prompt();

    if (options[type - 1]) version = options[type - 1];
    else if (type.match(/^\d+\.\d+\.\d+(-rc\d+)?$/)) version = type;
    else throw new Error('Your entry was invalid.');

    if (version.indexOf('rc') < 0 && oldVersion.indexOf('rc') < 0) {
      log('');
      write('Is this a release candidate? {{"[yes/no]".cyan}} ');
      if (prompt() === 'yes') version += '-rc1';
    }

    log('');
    log('The new version will be ' + version.cyan + '.');
    write('Is this correct? {{"[yes/no]".cyan}} ');
    return prompt() === 'yes' ? version : getNewVersion();

    function getVersionOptions (version) {
      return version.match(/-rc\d+$/)
          ? [ increment(version, 'rc'),
              increment(version, 'minor') ]
          : [ increment(version, 'patch'),
              increment(version, 'minor'),
              increment(version, 'major') ];

      function increment (versionString, type) {
        var version = parseVersion(versionString);
        if (version.rc) {
          switch (type) {
            case 'minor': version.rc = 0; break;
            case 'rc': version.rc++; break;
          }
        } else {
          version[type]++;
          //-- reset any version numbers lower than the one changed
          switch (type) {
            case 'major': version.minor = 0;
            case 'minor': version.patch = 0;
            case 'patch': version.rc = 0;
          }
        }
        return getVersionString(version);

        function parseVersion (version) {
          var parts = version.split(/\.|\-rc/g);
          return { string: version, major: parts[0], minor: parts[1], patch: parts[2], rc: parts[3] || 0 };
        }

        function getVersionString(version) {
          var str = version.major + '.' + version.minor + '.' + version.patch;
          if (version.rc) str += '-rc' + version.rc;
          return str;
        }
      }
    }
  }

  function tagRelease () {
    pushCmds.push(
        'git tag v{{newVersion}}',
        'git push {{origin}} HEAD',
        'git push --tags'
    );
  }

  function commitChanges () {
    start('Committing changes...');
    exec('git commit -am "release: version {{newVersion}}"');
    done();
    pushCmds.push('git commit --amend --no-edit');
  }

  function cloneRepo (repo) {
    start('Cloning ' + repo.cyan + ' from Github...');
    exec('git clone https://github.com/angular/' + repo + '.git --depth=1');
    done();
    cleanupCmds.push('rm -rf ' + repo);
  }

  function fill(str) {
    return str.replace(/\{\{[^\}]+\}\}/g, function (match) {
      return eval(match.substr(2, match.length - 4));
    });
  }

  function writeScript (name, cmds) {
    fs.writeFileSync(name, '#!/usr/bin/env bash\n\n' + fill(cmds.join('\n')));
    exec('chmod +x ' + name);
  }

  function updateBowerVersion () {
    start('Updating bower version...');
    var options = { cwd: './bower-material' },
        bower = require(options.cwd + '/bower.json'),
        pkg = require(options.cwd + '/package.json');
    //-- update versions in config files
    bower.version = pkg.version = newVersion;
    fs.writeFileSync(options.cwd + '/package.json', JSON.stringify(pkg, null, 2));
    fs.writeFileSync(options.cwd + '/bower.json', JSON.stringify(bower, null, 2));
    done();
    start('Building bower files...');
    //-- build files for bower
    exec([
      'rm -rf dist',
      'gulp build',
      'gulp build-all-modules --mode=default',
      'gulp build-all-modules --mode=closure',
      'rm -rf dist/demos',
    ]);
    done();
    start('Copy files into bower repo...');
    //-- copy files over to bower repo
    exec([
      'cp -Rf ../dist/* ./',
      'git add -A',
      'git commit -m "release: version {{newVersion}}"',
      'rm -rf ../dist'
    ], options);
    done();
    //-- add steps to push script
    pushCmds.push(
        comment('push to bower (master and tag) and publish to npm'),
        'cd ' + options.cwd,
        'cp ../CHANGELOG.md .',
        'git add CHANGELOG.md',
        'git commit --amend --no-edit',
        'git tag -f v{{newVersion}}',
        'git pull --rebase',
        'git push',
        'git push --tags',
        ( newVersion.indexOf('rc') < 0 ? 'npm publish' : '# skipped npm publish due to RC version' ),
        'cd ..'
    );
  }

  function updateSite () {
    start('Adding new version of the docs site...');
    var options = { cwd: './code.material.angularjs.org' },
        config  = require(options.cwd + '/docs.json');
    config.versions.unshift(newVersion);
    //-- only set to default if not a release candidate
    if (newVersion.indexOf('rc') < 0) config.latest = newVersion;
    fs.writeFileSync(options.cwd + '/docs.json', JSON.stringify(config, null, 2));
    //-- build files for bower
    exec([
      'rm -rf dist',
      'gulp docs',
      'sed -i \'\' \'s,http:\\/\\/localhost:8080\\/angular-material,http:\\/\\/cdn.rawgit.com/angular/bower-material/v{{newVersion}}/angular-material,g\' dist/docs/docs.js'
    ]);
    //-- copy files over to site repo
    exec([
      'cp -Rf ../dist/docs {{newVersion}}',
      ( newVersion.indexOf('rc') < 0 ? 'rm -rf latest && cp -Rf ../dist/docs latest' : '# skipped latest because this is a release candidate' ),
      'git add -A',
      'git commit -m "release: version {{newVersion}}"',
      'rm -rf ../dist'
    ], options);
    done();
    //-- add steps to push script
    pushCmds.push(
        comment('push the site'),
        'cd ' + options.cwd,
        'git pull --rebase',
        'git push',
        'cd ..'
    );
  }

  function updateMaster () {
    pushCmds.push(
        comment('update package.json in master'),
        'git co master',
        'git pull --rebase {{origin}} master',
        'git checkout release/{{newVersion}} -- CHANGELOG.md',
        'node -e "' + stringifyFunction(buildCommand) + '"',
        'git add CHANGELOG.md',
        'git add package.json',
        'git commit -m "update version number in package.json to {{newVersion}}"',
        'git push'
    );
    function buildCommand () {
      require('fs').writeFileSync('package.json', JSON.stringify(getUpdatedJson(), null, 2));
      function getUpdatedJson () {
        var json = require('./package.json');
        json.version = '{{newVersion}}';
        return json;
      }
    }
    function stringifyFunction (method) {
      return method
          .toString()
          .split('\n')
          .slice(1, -1)
          .map(function (line) { return line.trim(); })
          .join(' ')
          .replace(/"/g, '\\"');
    }
  }

  function done () {
    log('done'.green);
  }

  function exec (cmd, userOptions) {
    if (cmd instanceof Array) {
      return cmd.map(function (cmd) { return exec(cmd, userOptions); });
    }
    try {
      var options = Object.create(defaultOptions);
      for (var key in userOptions) options[key] = userOptions[key];
      return child_process.execSync(fill(cmd) + ' 2> /dev/null', options).trim();
    } catch (err) {
      return err;
    }
  }

  function comment (msg) {
    return '\n# ' + msg + '\n';
  }

  function start (msg) {
    var parsedMsg = fill(msg),
        msgLength = strip(parsedMsg).length,
        diff = lineWidth - 4 - msgLength;
    write(parsedMsg + Array(diff + 1).join(' '));
  }

  function log (msg) {
    console.log(fill(msg));
  }

  function write (msg) {
    process.stdout.write(fill(msg));
  }

  function line () {
    log(Array(lineWidth + 1).join('-'));
  }
})();
<commit_msg>update(build): adds support for a dry-run to test the build process<commit_after>(function () {
  'use strict';

  var colors         = require('colors');
  var strip          = require('cli-color/strip');
  var fs             = require('fs');
  var prompt         = require('prompt-sync');
  var child_process  = require('child_process');
  var pkg            = require('./package.json');
  var oldVersion     = pkg.version;
  var abortCmds      = [ 'git checkout master', 'rm abort push' ];
  var pushCmds       = [ 'rm abort push'];
  var cleanupCmds    = [];
  var defaultOptions = { encoding: 'utf-8' };
  var origin         = 'https://github.com/angular/material.git';
  var lineWidth      = 80;
  var lastMajorVer   = JSON.parse(exec('curl https://material.angularjs.org/docs.json')).latest;
  var newVersion;
  var dryRun;

  header();
  write('Is this a dry-run? {{"[yes/no]".cyan}} ');
  dryRun = prompt();

  if (dryRun !== 'no') {
    write('What would you like the old version to be? (default: {{oldVersion.cyan}}) ');
    oldVersion = prompt() || oldVersion;
    build();
  } else if (validate()) {
    build();
  }

  function build () {
    newVersion = getNewVersion();

    line();

    checkoutVersionBranch();
    updateVersion();
    createChangelog();
    commitChanges();
    tagRelease();
    cloneRepo('bower-material');
    updateBowerVersion();
    cloneRepo('code.material.angularjs.org');
    updateSite();
    updateMaster();
    writeScript('abort', abortCmds.concat(cleanupCmds));
    if (!dryRun) writeScript('push', pushCmds.concat(cleanupCmds));

    line();
    log('Your repo is ready to be pushed.');
    log('Please look over {{"CHANGELOG.md".cyan}} and make any changes.');
    log('When you are ready, please run "{{"./push".cyan}}" to finish the process.');
    log('If you would like to cancel this release, please run "./abort"');
  }

  //-- utility methods

  function validate () {
    if (exec('npm whoami') !== 'angularcore') {
      err('You must be authenticated with npm as "angularcore" to perform a release.');
    } else if (exec('git rev-parse --abbrev-ref HEAD') !== 'master') {
      err('Releases can only performed from master at this time.');
    } else if (exec('git pull -q --rebase {{origin}} master') instanceof Error) {
      err('Please make sure your local branch is synced with origin/master.');
    } else {
      return true;
    }
    function err (msg) {
      var str = 'Error: ' + msg;
      log(str.red);
    }
  }

  function checkoutVersionBranch () {
    exec('git checkout -q -b release/{{newVersion}}');
    abortCmds.push('git branch -D release/{{newVersion}}');
  }

  function updateVersion () {
    start('Updating {{"package.json".cyan}} version from {{oldVersion.cyan}} to {{newVersion.cyan}}...');
    pkg.version = newVersion;
    fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
    done();
    abortCmds.push('git checkout package.json');
    pushCmds.push('git add package.json');
  }

  function createChangelog () {
    start('Generating changelog from {{oldVersion.cyan}} to {{newVersion.cyan}}...');
    exec([
      'git fetch --tags',
      'git checkout v{{lastMajorVer}} -- CHANGELOG.md',
      'gulp changelog --sha=$(git merge-base v{{lastMajorVer}} HEAD)'
    ]);
    done();
    abortCmds.push('git checkout CHANGELOG.md');
    pushCmds.push('git add CHANGELOG.md');
  }

  function clear () {
    write("\u001b[2J\u001b[0;0H");
  }

  function getNewVersion () {
    header();
    var options = getVersionOptions(oldVersion), key, type, version;
    log('The current version is {{oldVersion.cyan}}.');
    log('');
    log('What should the next version be?');
    for (key in options) { log((+key + 1) + ') ' + options[key].cyan); }
    log('');
    write('Please select a new version: ');
    type = prompt();

    if (options[type - 1]) version = options[type - 1];
    else if (type.match(/^\d+\.\d+\.\d+(-rc\d+)?$/)) version = type;
    else throw new Error('Your entry was invalid.');

    log('');
    log('The new version will be ' + version.cyan + '.');
    write('Is this correct? {{"[yes/no]".cyan}} ');
    return prompt() === 'yes' ? version : getNewVersion();

    function getVersionOptions (version) {
      return version.match(/-rc\d+$/)
          ? [ increment(version, 'rc'),
              increment(version, 'minor') ]
          : [ increment(version, 'patch'),
              increment(version, 'minor'),
              increment(version, 'major') ].map(addRC);

      function increment (versionString, type) {
        var version = parseVersion(versionString);
        if (version.rc) {
          switch (type) {
            case 'minor': version.rc = 0; break;
            case 'rc': version.rc++; break;
          }
        } else {
          version[type]++;
          //-- reset any version numbers lower than the one changed
          switch (type) {
            case 'major': version.minor = 0;
            case 'minor': version.patch = 0;
            case 'patch': version.rc = 0;
          }
        }
        return getVersionString(version);

        function parseVersion (version) {
          var parts = version.split(/\.|\-rc/g);
          return { string: version, major: parts[0], minor: parts[1], patch: parts[2], rc: parts[3] || 0 };
        }

        function getVersionString(version) {
          var str = version.major + '.' + version.minor + '.' + version.patch;
          if (version.rc) str += '-rc' + version.rc;
          return str;
        }
      }

      function addRC (str) {
        return str + '-rc1';
      }
    }
  }

  function tagRelease () {
    pushCmds.push(
        'git tag v{{newVersion}}',
        'git push {{origin}} HEAD',
        'git push --tags'
    );
  }

  function commitChanges () {
    start('Committing changes...');
    exec('git commit -am "release: version {{newVersion}}"');
    done();
    pushCmds.push('git commit --amend --no-edit');
  }

  function cloneRepo (repo) {
    start('Cloning ' + repo.cyan + ' from Github...');
    exec('git clone https://github.com/angular/' + repo + '.git --depth=1');
    done();
    cleanupCmds.push('rm -rf ' + repo);
  }

  function fill(str) {
    return str.replace(/\{\{[^\}]+\}\}/g, function (match) {
      return eval(match.substr(2, match.length - 4));
    });
  }

  function writeScript (name, cmds) {
    fs.writeFileSync(name, '#!/usr/bin/env bash\n\n' + fill(cmds.join('\n')));
    exec('chmod +x ' + name);
  }

  function updateBowerVersion () {
    start('Updating bower version...');
    var options = { cwd: './bower-material' },
        bower = require(options.cwd + '/bower.json'),
        pkg = require(options.cwd + '/package.json');
    //-- update versions in config files
    bower.version = pkg.version = newVersion;
    fs.writeFileSync(options.cwd + '/package.json', JSON.stringify(pkg, null, 2));
    fs.writeFileSync(options.cwd + '/bower.json', JSON.stringify(bower, null, 2));
    done();
    start('Building bower files...');
    //-- build files for bower
    exec([
      'rm -rf dist',
      'gulp build',
      'gulp build-all-modules --mode=default',
      'gulp build-all-modules --mode=closure',
      'rm -rf dist/demos',
    ]);
    done();
    start('Copy files into bower repo...');
    //-- copy files over to bower repo
    exec([
      'cp -Rf ../dist/* ./',
      'git add -A',
      'git commit -m "release: version {{newVersion}}"',
      'rm -rf ../dist'
    ], options);
    done();
    //-- add steps to push script
    pushCmds.push(
        comment('push to bower (master and tag) and publish to npm'),
        'cd ' + options.cwd,
        'cp ../CHANGELOG.md .',
        'git add CHANGELOG.md',
        'git commit --amend --no-edit',
        'git tag -f v{{newVersion}}',
        'git pull --rebase',
        'git push',
        'git push --tags',
        ( newVersion.indexOf('rc') < 0 ? 'npm publish' : '# skipped npm publish due to RC version' ),
        'cd ..'
    );
  }

  function updateSite () {
    start('Adding new version of the docs site...');
    var options = { cwd: './code.material.angularjs.org' },
        config  = require(options.cwd + '/docs.json');
    config.versions = config.versions.filter(function (version) {
      return version.indexOf('rc') < 0;
    });
    config.versions.unshift(newVersion);
    //-- only set to default if not a release candidate
    if (newVersion.indexOf('rc') < 0) config.latest = newVersion;
    fs.writeFileSync(options.cwd + '/docs.json', JSON.stringify(config, null, 2));
    //-- build files for bower
    exec([
      'rm -rf dist',
      'gulp docs',
      'sed -i \'\' \'s,http:\\/\\/localhost:8080\\/angular-material,http:\\/\\/cdn.rawgit.com/angular/bower-material/v{{newVersion}}/angular-material,g\' dist/docs/docs.js'
    ]);
    //-- copy files over to site repo
    exec([
      'rm -rf ./*-rc*',
      'cp -Rf ../dist/docs {{newVersion}}',
      ( newVersion.indexOf('rc') < 0 ? 'rm -rf latest && cp -Rf ../dist/docs latest' : '# skipped latest because this is a release candidate' ),
      'git add -A',
      'git commit -m "release: version {{newVersion}}"',
      'rm -rf ../dist'
    ], options);
    done();
    //-- add steps to push script
    pushCmds.push(
        comment('push the site'),
        'cd ' + options.cwd,
        'git pull --rebase',
        'git push',
        'cd ..'
    );
  }

  function updateMaster () {
    pushCmds.push(
        comment('update package.json in master'),
        'git co master',
        'git pull --rebase {{origin}} master',
        'git checkout release/{{newVersion}} -- CHANGELOG.md',
        'node -e "' + stringifyFunction(buildCommand) + '"',
        'git add CHANGELOG.md',
        'git add package.json',
        'git commit -m "update version number in package.json to {{newVersion}}"',
        'git push'
    );
    function buildCommand () {
      require('fs').writeFileSync('package.json', JSON.stringify(getUpdatedJson(), null, 2));
      function getUpdatedJson () {
        var json = require('./package.json');
        json.version = '{{newVersion}}';
        return json;
      }
    }
    function stringifyFunction (method) {
      return method
          .toString()
          .split('\n')
          .slice(1, -1)
          .map(function (line) { return line.trim(); })
          .join(' ')
          .replace(/"/g, '\\"');
    }
  }

  function header () {
    clear();
    line();
    log(center('Angular Material Release'));
    line();
  }

  function center (msg) {
    msg = ' ' + msg.trim() + ' ';
    var length = msg.length;
    var spaces = Math.floor((lineWidth - length) / 2);
    return Array(spaces + 1).join('-') + msg.green + Array(lineWidth - msg.length - spaces + 1).join('-');
  }

  function done () {
    log('done'.green);
  }

  function exec (cmd, userOptions) {
    if (cmd instanceof Array) {
      return cmd.map(function (cmd) { return exec(cmd, userOptions); });
    }
    try {
      var options = Object.create(defaultOptions);
      for (var key in userOptions) options[key] = userOptions[key];
      return child_process.execSync(fill(cmd) + ' 2> /dev/null', options).trim();
    } catch (err) {
      return err;
    }
  }

  function comment (msg) {
    return '\n# ' + msg + '\n';
  }

  function start (msg) {
    var parsedMsg = fill(msg),
        msgLength = strip(parsedMsg).length,
        diff = lineWidth - 4 - msgLength;
    write(parsedMsg + Array(diff + 1).join(' '));
  }

  function log (msg) {
    msg = msg || '';
    console.log(fill(msg));
  }

  function write (msg) {
    process.stdout.write(fill(msg));
  }

  function line () {
    log(Array(lineWidth + 1).join('-'));
  }
})();
<|endoftext|>


<commit_before>/* eslint-disable react/no-multi-comp */

import React, { Component, PropTypes } from 'react';
import styles from '../build/styles';

export class Tabs extends Component {
  static propTypes = {
    children: PropTypes.any,
    style: PropTypes.object,
    className: PropTypes.string,
    tabStyle: PropTypes.oneOf([
      'isBoxed',
      'isToggle',
    ]),
    isFullwidth: PropTypes.bool,
    alignment: PropTypes.oneOf([
      'isCentered',
      'isRight',
    ]),
    size: PropTypes.oneOf([
      'isSmall',
      'isMedium',
      'isLarge',
    ]),
  };

  static defaultProps = {
    style: {},
    className: '',
  };

  createClassName() {
    return [
      styles.tabs,
      styles[this.props.alignment],
      styles[this.props.size],
      styles[this.props.tabStyle],
      this.props.isFullwidth ? styles.isFullwidth : '',
      this.props.className,
    ].join(' ').trim();
  }

  render() {
    return (

        {this.props.children}

    );
  }
}

export class TabGroup extends Component {
  static propTypes = {
    children: PropTypes.any,
    className: PropTypes.string,
    alignment: PropTypes.oneOf([
      'isLeft',
      'isCenter',
      'isRight',
    ]),
  };

  static defaultProps = {
    className: '',
  };

  createClassName() {
    return [
      styles[this.props.alignment],
      this.props.className,
    ].join(' ').trim();
  }

  render() {
    return (

        {this.props.children}

    );
  }
}

export class Tab extends Component {
  static propTypes = {
    children: PropTypes.any,
    className: PropTypes.string,
    isActive: PropTypes.bool,
  };

  static defaultProps = {
    className: '',
  };

  createClassName() {
    return [
      this.props.isActive ? styles.isActive : '',
      this.props.className,
    ].join(' ').trim();
  }

  render() {
    return (

          {this.props.children}

    );
  }
}
<commit_msg>Fix tab props<commit_after>/* eslint-disable react/no-multi-comp */

import React, { Component, PropTypes } from 'react';
import { getCallbacks } from './helper/helper';
import styles from '../build/styles';

export class Tabs extends Component {
  static propTypes = {
    children: PropTypes.any,
    style: PropTypes.object,
    className: PropTypes.string,
    tabStyle: PropTypes.oneOf([
      'isBoxed',
      'isToggle',
    ]),
    isFullwidth: PropTypes.bool,
    alignment: PropTypes.oneOf([
      'isCentered',
      'isRight',
    ]),
    size: PropTypes.oneOf([
      'isSmall',
      'isMedium',
      'isLarge',
    ]),
  };

  static defaultProps = {
    style: {},
    className: '',
  };

  createClassName() {
    return [
      styles.tabs,
      styles[this.props.alignment],
      styles[this.props.size],
      styles[this.props.tabStyle],
      this.props.isFullwidth ? styles.isFullwidth : '',
      this.props.className,
    ].join(' ').trim();
  }

  render() {
    return (

        {this.props.children}

    );
  }
}

export class TabGroup extends Component {
  static propTypes = {
    children: PropTypes.any,
    className: PropTypes.string,
    alignment: PropTypes.oneOf([
      'isLeft',
      'isCenter',
      'isRight',
    ]),
  };

  static defaultProps = {
    className: '',
  };

  createClassName() {
    return [
      styles[this.props.alignment],
      this.props.className,
    ].join(' ').trim();
  }

  render() {
    return (

        {this.props.children}

    );
  }
}

export class Tab extends Component {
  static propTypes = {
    children: PropTypes.any,
    className: PropTypes.string,
    isActive: PropTypes.bool,
  };

  static defaultProps = {
    className: '',
  };

  createClassName() {
    return [
      this.props.isActive ? styles.isActive : '',
      this.props.className,
    ].join(' ').trim();
  }

  render() {
    return (

          {this.props.children}

    );
  }
}
<|endoftext|>


<commit_before>export var mytest = [
  { answer: "Ohio.", question: "Columbus?" },
  { answer: "Indiana.", question: "Indianapolis?" },
  { answer: "Michigan.", question: "Lansing?" },
  { answer: "Kentucky.", question: "Lexington?" }
];
<commit_msg>delete test fil<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

import yargs    from 'yargs'
import manifest from '../package.json'
import commit   from './commands/tick-commit'
import login    from './commands/tick-login'
import log      from './commands/tick-log'
import register from './commands/tick-register'
import rm       from './commands/tick-rm'
import upgrade  from './commands/tick-upgrade'
import sync     from './commands/tick-sync'

yargs
.usage('Usage: tick <command> [options]')
.command('commit', 'commit a tick', commit)
.command('login', 'login to your account', login)
.command('log', 'display a log of your ticks', log)
.command('register', 'create an account', register)
.command('rm', 'delete a tick', rm)
.command('upgrade', 'upgrade your tickbin', upgrade)
.command('sync', 'sync your database with remotes', sync)
.version(manifest.version, 'version', 'prints the current version of tickbin')
.demand(1)
.check(checkCommand)
.alias('h', 'help')
.help()
.argv

function checkCommand () {
  // Only executed when no other commands are matched,
  // and `demand(1)` are satisfied.
  // Therefore, when executed, an invalid command was provided
  throw new Error('An invalid command was provided')
}
<commit_msg>Version is now passed as last parameter<commit_after>#!/usr/bin/env node

import yargs    from 'yargs'
import manifest from '../package.json'
import commit   from './commands/tick-commit'
import login    from './commands/tick-login'
import log      from './commands/tick-log'
import register from './commands/tick-register'
import rm       from './commands/tick-rm'
import upgrade  from './commands/tick-upgrade'
import sync     from './commands/tick-sync'

yargs
.usage('Usage: tick <command> [options]')
.command('commit', 'commit a tick', commit)
.command('login', 'login to your account', login)
.command('log', 'display a log of your ticks', log)
.command('register', 'create an account', register)
.command('rm', 'delete a tick', rm)
.command('upgrade', 'upgrade your tickbin', upgrade)
.command('sync', 'sync your database with remotes', sync)
.version('version', 'prints the current version of tickbin', manifest.version)
.demand(1)
.check(checkCommand)
.alias('h', 'help')
.help()
.argv

function checkCommand () {
  // Only executed when no other commands are matched,
  // and `demand(1)` are satisfied.
  // Therefore, when executed, an invalid command was provided
  throw new Error('An invalid command was provided')
}
<|endoftext|>