<commit_before>var canvas = document.getElementById('game');
var context = canvas.getContext('2d');

function Tower(options) {
  this.options = options || {};
  this.x = options.x;
  this.y = options.y;
  this.height = options.height;
  this.width = options.width || 80;
}

function CannonBase(options) {
  this.options = options || {};
  this.x = options.x;
  this.y = options.y;
  this.height = options.height || 40;
  this.width = options.width || 40;
}

function CannonBarrel(cannon) {
  this.x = cannon.x + 17;
  this.y = cannon.y + 17;
  this.width = 6;
  this.height = -45;
}

CannonBarrel.prototype.draw = function() {
  context.fillStyle = 'black';
  context.fillRect(this.x, this.y, this.width, this.height);
  return this;
};

CannonBarrel.prototype.moveUp = function() {
  context.save();
  context.translate(this.x, this.y);
  context.rotate(0.30);
  context.moveTo(0,0);
  context.lineTo(0, 200);
  context.stroke();
  // context.restore();
  return this;
};

CannonBarrel.prototype.moveDown = function() {

};

CannonBase.prototype.draw = function() {
  context.fillStyle = 'green';
  context.fillRect(this.x, this.y, this.width, this.height);
  return this;
  // var image = new Image();
  // image.src = 'images/rotating-cannon1.png';
  // context.drawImage(image, 35, 350);

};

Tower.prototype.draw = function() {
 context.fillStyle = 'black';
 context.fillRect(this.x,this.y,this.width,this.height);
 return this;
};

var cannonBase = new CannonBase({x: 30, y: 360});
var cannonBarrel = new CannonBarrel(cannonBase);
var tower1 = new Tower({x: 10, y: 400, height: 200});
var tower2 = new Tower({x: 95, y: 400, height: 200});
var tower3 = new Tower({x: 180, y: 400, height: 200});
var tower4 = new Tower({x: 265, y: 400, height: 200});
var tower5 = new Tower({x: 350, y: 400, height: 200});
var tower6 = new Tower({x: 435, y: 400, height: 200});
var tower7 = new Tower({x: 520, y: 400, height: 200});
var tower8 = new Tower({x: 605, y: 400, height: 200});
var tower9 = new Tower({x: 690, y: 400, height: 200, width: 100});
var towers = [tower1, tower2, tower3, tower4, tower5, tower6, tower7, tower8, tower8, tower9];

requestAnimationFrame(function gameLoop() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  towers.forEach(function(tower) {
    tower.draw();
  });
  cannonBase.draw();
  cannonBarrel.draw();
  requestAnimationFrame(gameLoop);
});

canvas.addEventListener('keydown', function(event) {
  var keyCode = event.keyCode;
  if(keyCode === 38) {
    cannonBarrel.moveUp();
  } else if(keyCode === 40) {
    cannonBarrel.moveDown();
  }
});
<commit_msg>Finishs cannon rotation<commit_after>var canvas = document.getElementById('game');
var context = canvas.getContext('2d');

function Tower(options) {
  this.options = options || {};
  this.x = options.x;
  this.y = options.y;
  this.height = options.height;
  this.width = options.width || 80;
}

function CannonBase(options) {
  this.options = options || {};
  this.x = options.x;
  this.y = options.y;
  this.height = options.height || 40;
  this.width = options.width || 40;
}

function CannonBarrel(cannon) {
  this.x = cannon.x + 17;
  this.y = cannon.y + 17;
  this.width = 6;
  this.height = 50;
  this.anglex = this.x + 50;
  this.angley = this.y;
}

CannonBarrel.prototype.draw = function(options) {
  context.fillStyle = 'white';
  context.stroke();
  context.beginPath();
  context.moveTo(this.x, this.y);
  context.lineTo(this.anglex, this.angley);
  context.strokeStyle = 'white';
  context.stroke();
  return this;
};

var theta = 0;
CannonBarrel.prototype.moveUp = function() {
  var step = Math.PI/180;
  var x = this.x + 50*Math.cos(theta+=step);
  var y = this.y - 50*Math.sin(theta+=step);
  this.anglex = x;
  this.angley = y;
  console.log(this.anglex, this.angley)
  return this;
};

CannonBarrel.prototype.moveDown = function() {
  var step = Math.PI/180;
  var x = this.x + 50*Math.cos(theta-=step);
  var y = this.y - 50*Math.sin(theta-=step);
  this.anglex = x;
  this.angley = y;
  return this;
};

CannonBase.prototype.draw = function() {
  context.fillStyle = 'green';
  context.fillRect(this.x, this.y, this.width, this.height);
  return this;
  // var image = new Image();
  // image.src = 'images/rotating-cannon1.png';
  // context.drawImage(image, 35, 350);

};

Tower.prototype.draw = function() {
 context.fillStyle = 'black';
 context.fillRect(this.x,this.y,this.width,this.height);
 return this;
};

var cannonBase = new CannonBase({x: 30, y: 360});
var cannonBarrel = new CannonBarrel(cannonBase);
var tower1 = new Tower({x: 10, y: 400, height: 200});
var tower2 = new Tower({x: 95, y: 400, height: 200});
var tower3 = new Tower({x: 180, y: 400, height: 200});
var tower4 = new Tower({x: 265, y: 400, height: 200});
var tower5 = new Tower({x: 350, y: 400, height: 200});
var tower6 = new Tower({x: 435, y: 400, height: 200});
var tower7 = new Tower({x: 520, y: 400, height: 200});
var tower8 = new Tower({x: 605, y: 400, height: 200});
var tower9 = new Tower({x: 690, y: 400, height: 200, width: 100});
var towers = [tower1, tower2, tower3, tower4, tower5, tower6, tower7, tower8, tower8, tower9];

requestAnimationFrame(function gameLoop() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  towers.forEach(function(tower) {
    tower.draw();
  });
  cannonBase.draw();
  cannonBarrel.draw();
  requestAnimationFrame(gameLoop);
});

canvas.addEventListener('keydown', function(event) {
  var keyCode = event.keyCode;
  if(keyCode === 38) {
    cannonBarrel.moveUp();
  } else if(keyCode === 40) {
    cannonBarrel.moveDown();
  }
});
<|endoftext|>


<commit_before>/* =============================================================
 * bootstrap-typeahead.js v2.0.0
 * http://twitter.github.com/bootstrap/javascript.html#collapsible
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

!function( $ ){

  "use strict"

  var Typeahead = function ( element, options ) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
    this.$menu = $(this.options.menu).appendTo('body')
    this.data = this.options.data
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

  , matcher: function (item, query) {
      // ;_; http://jsperf.com/asdfdfasdfa
      return ~item.toLowerCase().indexOf(query.toLowerCase())
    }

  , select: function () {
      var val = this.$menu.find('.active').attr('data-value')
      this.$element.val(val)
      return this.hide()
    }

  , show: function () {
      var pos = $.extend({}, this.$element.offset(), {
        height: this.$element[0].offsetHeight
      })

      this.$menu.css({
        top: pos.top + pos.height
      , left: pos.left
      })

      this.$menu.show()
      this.shown = true
      return this
    }

  , hide: function () {
      this.$menu.hide()
      this.shown = false
      return this
    }

  , lookup: function (event) {
      var query = this.$element.val()
        , that = this
        , items

      if (!query) {
        return this.shown ? this.hide() : this
      }

      items = this.data.filter(function (item) {
        if (that.matcher(item, query)) return item
      })

      if (!items.length) {
        return this.shown ? this.hide() : this
      }

      return this.render(items.slice(0, this.options.items)).show()
    }

  , render: function (items) {
      var that = this

      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)
        i.find('a').text(item)
        return i[0]
      })

      items.first().addClass('active')
      this.$menu.html(items)
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.next()

      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prev()

      if (!prev.length) {
        prev = this.$menu.find('li').last()
      }

      prev.addClass('active')
    }

  , keyup: function (e) {
      e.stopPropagation()
      e.preventDefault()

      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
          break

        case 9: // tab
        case 13: // enter
          this.select()
          break

        case 27: // escape
          this.hide()
          break

        default:
          this.lookup()
      }

  }

  , keypress: function (e) {
      e.stopPropagation()

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          if (!this.shown) return
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          if (!this.shown) return
          e.preventDefault()
          this.next()
          break
      }
    }

  , blur: function (e) {
      var that = this
      e.stopPropagation()
      e.preventDefault()
      setTimeout(function () { that.hide() }, 150)
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
    }

  , mouseenter: function (e) {
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }

  , listen: function () {
      this.$element
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

      if ($.browser.webkit || $.browser.msie) {
        this.$element.on('keydown', $.proxy(this.keypress, this))
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
    }
  }

  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  $.fn.typeahead = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
    items: 8
  , menu: '

'
  , item: '

'
  }

  $.fn.typeahead.Constructor = Typeahead

 /* TYPEAHEAD DATA-API
  * ================== */

  $(function () {
    $('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
      var $this = $(this)
      if ($this.data('typeahead')) return
      e.preventDefault()
      $this.typeahead($this.data())
    })
  })

}( window.jQuery )<commit_msg>more efficient matcher + bold matched query in item<commit_after>/* =============================================================
 * bootstrap-typeahead.js v2.0.0
 * http://twitter.github.com/bootstrap/javascript.html#collapsible
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

!function( $ ){

  "use strict"

  var Typeahead = function ( element, options ) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
    this.$menu = $(this.options.menu).appendTo('body')
    this.data = this.options.data
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

  , matcher: function (item, query) {
      // ;_; http://jsperf.com/asdfdfasdfa
      return ~item.toLowerCase().indexOf(query)
    }

  , select: function () {
      var val = this.$menu.find('.active').attr('data-value')
      this.$element.val(val)
      return this.hide()
    }

  , show: function () {
      var pos = $.extend({}, this.$element.offset(), {
        height: this.$element[0].offsetHeight
      })

      this.$menu.css({
        top: pos.top + pos.height
      , left: pos.left
      })

      this.$menu.show()
      this.shown = true
      return this
    }

  , hide: function () {
      this.$menu.hide()
      this.shown = false
      return this
    }

  , lookup: function (event) {
      var that = this
        , items
        , q

      this.query = this.$element.val()

      if (!this.query) {
        return this.shown ? this.hide() : this
      }

      q = this.query.toLowerCase()

      items = this.data.filter(function (item) {
        if (that.matcher(item, q)) return item
      })

      if (!items.length) {
        return this.shown ? this.hide() : this
      }

      return this.render(items.slice(0, this.options.items)).show()
    }

  , render: function (items) {
      var that = this
        , QUERY = new RegExp('(' + this.query + ')', 'ig')

      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)

        i.find('a').html(item.replace(QUERY, function ($1, match) {
          return '' + match + ''
        }))

        return i[0]
      })

      items.first().addClass('active')
      this.$menu.html(items)
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.next()

      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prev()

      if (!prev.length) {
        prev = this.$menu.find('li').last()
      }

      prev.addClass('active')
    }

  , listen: function () {
      this.$element
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

      if ($.browser.webkit || $.browser.msie) {
        this.$element.on('keydown', $.proxy(this.keypress, this))
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
    }

  , keyup: function (e) {
      e.stopPropagation()
      e.preventDefault()

      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
          break

        case 9: // tab
        case 13: // enter
          this.select()
          break

        case 27: // escape
          this.hide()
          break

        default:
          this.lookup()
      }

  }

  , keypress: function (e) {
      e.stopPropagation()

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          if (!this.shown) return
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          if (!this.shown) return
          e.preventDefault()
          this.next()
          break
      }
    }

  , blur: function (e) {
      var that = this
      e.stopPropagation()
      e.preventDefault()
      setTimeout(function () { that.hide() }, 150)
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
    }

  , mouseenter: function (e) {
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }

  }

  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  $.fn.typeahead = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
    items: 8
  , menu: '

'
  , item: '

'
  }

  $.fn.typeahead.Constructor = Typeahead

 /* TYPEAHEAD DATA-API
  * ================== */

  $(function () {
    $('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
      var $this = $(this)
      if ($this.data('typeahead')) return
      e.preventDefault()
      $this.typeahead($this.data())
    })
  })

}( window.jQuery )<|endoftext|>


<commit_before>var gulp = require('gulp')
var pug = require('gulp-pug')
var less = require('gulp-less')
var autoprefixer = require('gulp-autoprefixer')
var clean_css = require('gulp-clean-css')
var sourcemaps = require('gulp-sourcemaps')

gulp.task('pug:docs', function () {
  return gulp.src('docs/{index,phi,code,principles,base,obj,comp-typo,comp-ui,help,atom}.pug')
    .pipe(pug({
      basedir: './',
      locals: {
        Docs: require('./docs/_models/Docs.class.js'),
      },
    }))
    .pipe(gulp.dest('./docs/'))
})

gulp.task('lessc:docs', function () {
  return gulp.src('docs/css/src/docs.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./docs/css/'))
})

gulp.task('lessc:core', function () {
  return gulp.src(__dirname + '/css/src/still-alive.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./css/'))
    .pipe(sourcemaps.init())
    .pipe(clean_css())
    .pipe(sourcemaps.write('./')) // writes to an external .map file
    .pipe(gulp.dest('./css/'))
})

gulp.task('build', ['pug:docs', 'lessc:docs', 'lessc:core'])
<commit_msg>forgot to update gulpfile<commit_after>const gulp         = require('gulp')
const pug          = require('gulp-pug')
const less         = require('gulp-less')
const autoprefixer = require('gulp-autoprefixer')
const clean_css    = require('gulp-clean-css')
const sourcemaps   = require('gulp-sourcemaps')

gulp.task('pug:docs', function () {
  return gulp.src('docs/{index,phi,code,principles,base,obj,comp-typo,comp-ui,help,atom}.pug')
    .pipe(pug({
      basedir: './',
      locals: {
        Xmeter: require('xmeter'),
        Docs: require('./docs/_models/Docs.class.js'),
      },
    }))
    .pipe(gulp.dest('./docs/'))
})

gulp.task('lessc:docs', function () {
  return gulp.src('docs/css/src/docs.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./docs/css/'))
})

gulp.task('lessc:core', function () {
  return gulp.src(__dirname + '/css/src/still-alive.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./css/'))
    .pipe(sourcemaps.init())
    .pipe(clean_css())
    .pipe(sourcemaps.write('./')) // writes to an external .map file
    .pipe(gulp.dest('./css/'))
})

gulp.task('build', ['pug:docs', 'lessc:docs', 'lessc:core'])
<|endoftext|>


<commit_before>/* @flow */

import { isDef, isUndef, extend, toNumber } from 'shared/util'

function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
    return
  }
  let key, cur
  const elm: any = vnode.elm
  const oldProps = oldVnode.data.domProps || {}
  let props = vnode.data.domProps || {}
  // clone observed objects, as the user probably wants to mutate it
  if (isDef(props.__ob__)) {
    props = vnode.data.domProps = extend({}, props)
  }

  for (key in oldProps) {
    if (isUndef(props[key])) {
      elm[key] = ''
    }
  }
  for (key in props) {
    cur = props[key]
    // ignore children if the node has textContent or innerHTML,
    // as these will throw away existing DOM nodes and cause removal errors
    // on subsequent patches (#3360)
    if (key === 'textContent' || key === 'innerHTML') {
      if (vnode.children) vnode.children.length = 0
      if (cur === oldProps[key]) continue
      // #6601 work around Chrome version <= 55 bug where single textNode
      // replaced by innerHTML/textContent retains its parentNode property
      if (elm.childNodes.length === 1) {
        elm.removeChild(elm.childNodes[0])
      }
    }

    if (key === 'value') {
      // store value as _value as well since
      // non-string values will be stringified
      elm._value = cur
      // avoid resetting cursor position when value is the same
      const strCur = isUndef(cur) ? '' : String(cur)
      if (shouldUpdateValue(elm, vnode, strCur)) {
        elm.value = strCur
      }
    } else {
      elm[key] = cur
    }
  }
}

// check platforms/web/util/attrs.js acceptValue
type acceptValueElm = HTMLInputElement | HTMLSelectElement | HTMLOptionElement;

function shouldUpdateValue (
  elm: acceptValueElm,
  vnode: VNodeWithData,
  checkVal: string
): boolean {
  return (!elm.composing && (
    vnode.tag === 'option' ||
    isDirty(elm, checkVal) ||
    isInputChanged(elm, checkVal)
  ))
}

function isDirty (elm: acceptValueElm, checkVal: string): boolean {
  // return true when textbox (.number and .trim) loses focus and its value is
  // not equal to the updated value
  let notInFocus = true
  // #6157
  // work around IE bug when accessing document.activeElement in an iframe
  try { notInFocus = document.activeElement !== elm } catch (e) {}
  return notInFocus && elm.value !== checkVal
}

function isInputChanged (elm: any, newVal: string): boolean {
  const value = elm.value
  const modifiers = elm._vModifiers // injected by v-model runtime
  if (isDef(modifiers) && modifiers.number) {
    return toNumber(value) !== toNumber(newVal)
  }
  if (isDef(modifiers) && modifiers.trim) {
    return value.trim() !== newVal.trim()
  }
  return value !== newVal
}

export default {
  create: updateDOMProps,
  update: updateDOMProps
}
<commit_msg>refactor: remove unnecessary argument<commit_after>/* @flow */

import { isDef, isUndef, extend, toNumber } from 'shared/util'

function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
    return
  }
  let key, cur
  const elm: any = vnode.elm
  const oldProps = oldVnode.data.domProps || {}
  let props = vnode.data.domProps || {}
  // clone observed objects, as the user probably wants to mutate it
  if (isDef(props.__ob__)) {
    props = vnode.data.domProps = extend({}, props)
  }

  for (key in oldProps) {
    if (isUndef(props[key])) {
      elm[key] = ''
    }
  }
  for (key in props) {
    cur = props[key]
    // ignore children if the node has textContent or innerHTML,
    // as these will throw away existing DOM nodes and cause removal errors
    // on subsequent patches (#3360)
    if (key === 'textContent' || key === 'innerHTML') {
      if (vnode.children) vnode.children.length = 0
      if (cur === oldProps[key]) continue
      // #6601 work around Chrome version <= 55 bug where single textNode
      // replaced by innerHTML/textContent retains its parentNode property
      if (elm.childNodes.length === 1) {
        elm.removeChild(elm.childNodes[0])
      }
    }

    if (key === 'value') {
      // store value as _value as well since
      // non-string values will be stringified
      elm._value = cur
      // avoid resetting cursor position when value is the same
      const strCur = isUndef(cur) ? '' : String(cur)
      if (shouldUpdateValue(elm, strCur)) {
        elm.value = strCur
      }
    } else {
      elm[key] = cur
    }
  }
}

// check platforms/web/util/attrs.js acceptValue
type acceptValueElm = HTMLInputElement | HTMLSelectElement | HTMLOptionElement;

function shouldUpdateValue (elm: acceptValueElm, checkVal: string): boolean {
  return (!elm.composing && (
    elm.tagName === 'OPTION' ||
    isDirty(elm, checkVal) ||
    isInputChanged(elm, checkVal)
  ))
}

function isDirty (elm: acceptValueElm, checkVal: string): boolean {
  // return true when textbox (.number and .trim) loses focus and its value is
  // not equal to the updated value
  let notInFocus = true
  // #6157
  // work around IE bug when accessing document.activeElement in an iframe
  try { notInFocus = document.activeElement !== elm } catch (e) {}
  return notInFocus && elm.value !== checkVal
}

function isInputChanged (elm: any, newVal: string): boolean {
  const value = elm.value
  const modifiers = elm._vModifiers // injected by v-model runtime
  if (isDef(modifiers) && modifiers.number) {
    return toNumber(value) !== toNumber(newVal)
  }
  if (isDef(modifiers) && modifiers.trim) {
    return value.trim() !== newVal.trim()
  }
  return value !== newVal
}

export default {
  create: updateDOMProps,
  update: updateDOMProps
}
<|endoftext|>


<commit_before>// var namebtn=document.getElementById("namediv");
// var picdiv=document.getElementById('picdiv');
// namebtn.onclick=function(){
// 	alert("welcome to my webside");
// };
var namebtn=$('#namediv');
var images=$('.image');
var picdiv=$('#picdiv');

var sideimage=$('#sideimg');

urllists=new Array();
gistcontents=new Array();

// namebtn.click(function(){
// 	alert('welcome!');
// });
getUserGistLists=function(username){
	urllists=[];
	$.get('https://api.github.com/users/'+username+'/gists',function(data,status){
		var i=0;
		if(status=="success"){
			for(list in data){
				urllists[i]=data[list].url;
				i++;
			}
		}
	});
};

getAllGists=function(urllists){
	for(url in urllists){
		var i=0;
		$.get(urllists[url],function(data,status){
			if(status=='success'){
				var responsejson=data;
				gistcontents[i]=responsejson['files']['gistfile1.txt']['content'];
			}
		});
	}
};

// $(document).ready(function(){
// 	$.get('https://api.github.com/gists/1f4d05e72c615872dd5c',function(data,status){
// 		if(status=='success'){
// 			var responsejson=data;
// 			sideimage.html("
"+responsejson['files']['gistfile1.txt']['content']+"
");
// 		}
// 	});
// });
$(document).ready(function(){
	getUserGistLists('myworkstation');
	getAllGists(urllists);
	for(con in gistcontents){
		sideimage.html("
"+gistcontents[con]+"
");
	}
});<commit_msg>update<commit_after>
var namebtn=$('#namediv');
var images=$('.image');
var picdiv=$('#picdiv');

var sideimage=$('#sideimg');

urllists=new Array();
gistcontents=new Array();

getUserGistLists=function(username){
	urllists=[];
	$.get('https://api.github.com/users/'+username+'/gists',function(data,status){
		var i=0;
		if(status=="success"){
			for(list in data){
				urllists[i]=data[list].url;
				i++;
			}
		}
	});
};

getAllGists=function(urllists){
	for(url in urllists){
		var i=0;
		$.get(urllists[url],function(data,status){
			if(status=='success'){
				var responsejson=data;
				gistcontents[i]=responsejson['files']['gistfile1.txt']['content'];
			}
		});
	}
};

// $(document).ready(function(){
// 	$.get('https://api.github.com/gists/1f4d05e72c615872dd5c',function(data,status){
// 		if(status=='success'){
// 			var responsejson=data;
// 			sideimage.html("
"+responsejson['files']['gistfile1.txt']['content']+"
");
// 		}
// 	});
// });
// $(document).ready(function(){
// 	getUserGistLists('myworkstation');
// 	getAllGists(urllists);
// 	for(con in gistcontents){
// 		sideimage.html("
"+gistcontents[con]+"
");
// 	}
// });

$(document).ready(function(){
	$.get('https://api.github.com/users/'+'myworkstation'+'/gists',function(data,status){
		if(status=="success"){
			for(index in data){
				var gisturl=data.url;
				$.get(gisturl,function(data,status){
					if(status=="success"){
						var responsejson=data;
						sideimage.html("
"+responsejson['files']['gistfile1.txt']['content']+"
");
					}
				})
			}
		}
	})
});<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var extend = require('xtend');
var util = require('util');

var ResourcePool = require('./resource_pool');
var TestSearch = require('./test_search');
var TestIsolateSearch = require('./test_isolate_search');

/*
 * Minimal cluster object expected by this module:
 *
 *   cluster :: {
 *     client :: TChannel // top
 *     hosts :: [hostPort :: String]
 *     channels :: [chan :: TChannel]
 *     cleanup :: (assert, callback) -> void
 *   }
 *
 * cluster.client should be in cluster.channnels, it may be the only one.
 *
 * The cleanup function is called after each test to cleanup and/or assert that
 * the cluster is in an expected state.  If it does not error and if the assert
 * has no failures, then the cluster is reused for the next test.  In other
 * words, if the cleanup function can cause the cluster to not be reused in two
 * ways:
 * - call callback(err)
 * - call assert.fail() (directly or not)
 *
 * Options:
 * - setupCluster :: (cluster, callback) -> void
 *   - should setup any necessary local assets (e.g. test-specific handlers on
 *     any local channels)
 *   - should setup any test-necesasry peering on local channels
 * - setupClient :: (cluster, callback) -> void
 *   - should setup any necessary test client channels (sub channels of
 *     cluster.client); these channels should be made available as
 *     cluster.fooClient
 */

// TODO:
// - explicit Cluster prototype to share between inproc, remote, and others
// - concurrent mode
// - share channels mode (e.g. for concurrency)

function ClusterSearch(options) {
    if (!(this instanceof ClusterSearch)) {
        return new ClusterSearch(options);
    }
    var self = this;
    TestSearch.call(self, options);
    initClusterSearch(self);
}
util.inherits(ClusterSearch, TestSearch);

function ClusterIsolateSearch(options) {
    if (!(this instanceof ClusterIsolateSearch)) {
        return new ClusterIsolateSearch(options);
    }
    var self = this;
    TestIsolateSearch.call(self, options);
    initClusterSearch(self);
}
util.inherits(ClusterIsolateSearch, TestIsolateSearch);

function initClusterSearch(self) {
    self.clusterPool = new ResourcePool(setupCluster);
    if (self.options.createCluster) {
        self.createCluster = self.options.createCluster;
    } else {
        var inprocOptions = extend(self.options.inprocOptions);
        self.createCluster = inprocClusterCreator(inprocOptions);
    }

    if (!self.options.reuseChannels) self.on('done', onSearchTestDone);

    function setupCluster(callback) {
        self.setupCluster(callback);
    }

    function onSearchTestDone() {
        self.destroy();
    }
}

ClusterSearch.prototype.destroy =
ClusterIsolateSearch.prototype.destroy =
function destroy(callback) {
    var self = this;
    self.clusterPool.destroy(callback);
};

ClusterSearch.prototype.setupCluster =
ClusterIsolateSearch.prototype.setupCluster =
function setupCluster(callback) {
    var self = this;
    self.createCluster(created);

    function created(err, cluster) {
        if (err) {
            callback(err, cluster);
        } else if (self.options.setupCluster) {
            callProvidedSetup(cluster);
        } else {
            self.setupClient(cluster, callback);
        }
    }

    function callProvidedSetup(cluster) {
        self.options.setupCluster.call(self, cluster, setupDone);
        function setupDone(err) {
            if (err) {
                callback(err, cluster);
            } else {
                self.setupClient(cluster, callback);
            }
        }
    }
};

ClusterSearch.prototype.createCluster =
ClusterIsolateSearch.prototype.createCluster =
function createCluster(callback) {
    callback(new Error('not implemented'), null);
};

ClusterSearch.prototype.setupClient =
ClusterIsolateSearch.prototype.setupClient =
function setupClient(cluster, callback) {
    var self = this;

    if (cluster.hosts) {
        cluster.hosts.forEach(
            function each(host) {
            if (host !== cluster.client.hostPort) {
                cluster.client.peers.add(host);
            }
        });
    }

    if (self.options.setupClient) {
        self.options.setupClient.call(self, cluster, finish);
    } else {
        finish(null);
    }

    // TODO: could pre-connect
    // var peers = client.peers.values();
    // peers.forEach(function each(peer) {
    //     var conn = peer.connect(true);
    //     if (conn.remoteName) {
    //         ready.signal();
    //     } else {
    //         conn.on('identified', ready.signal);
    //     }
    // });
    // ready(clientReady);
    // function clientReady() {
    //     callback(null, client);
    // }

    function finish(err) {
        callback(err, cluster);
    }
};

ClusterSearch.prototype.test =
ClusterIsolateSearch.prototype.test =
function test(state, assert) {
    var self = this;
    self.clusterPool.get(gotCluster);

    function gotCluster(err, cluster) {
        if (err) {
            finish(err, cluster);
        } else {
            self.options.clusterTest.call(self, cluster, state, assert, testDone);
        }

        function testDone(err) {
            cleanup(err, cluster);
        }
    }

    function cleanup(err, cluster) {
        if (err) {
            finish(err, cluster);
        } else {
            cluster.cleanup(assert, cleanupDone);
        }
        function cleanupDone(err) {
            finish(err, cluster);
        }
    }

    function finish(err, cluster) {
        assert.ifError(err, self.describeState(state) + ': no final error');
        if (!assert._ok) {
            cluster.destroy(assert.end);
        } else {
            self.clusterPool.release(cluster);
            assert.end();
        }
    }
};

function inprocClusterCreator(options) {
    var allocCluster = require('./alloc-cluster.js');

    // TODO: create explicit client, stop re-using a "peer" for it?

    if (!options) options = {};
    if (!options.numPeers) options.numPeers = 2;
    if (!options.cleanState) {
        options.cleanState = {
            channels: [{
                peers: [{
                    connections: [
                        {direction: 'in', inReqs: 0, outReqs: 0}
                    ]
                }]
            }, {
                peers: [{
                    connections: [
                        {direction: 'out', inReqs: 0, outReqs: 0}
                    ]
                }]
            }]
        };
    }

    return createInprocCluster;

    function createInprocCluster(created) {
        var cluster = allocCluster(options);
        cluster.client = cluster.channels[1];
        cluster.cleanup = cleanupInprocCluster;
        if (options.init) {
            options.init(cluster, function initDone(err) {
                if (err) {
                    created(err, cluster);
                } else {
                    cluster.ready(inprocClusterReady);
                }
            });
        } else {
            cluster.ready(inprocClusterReady);
        }

        function cleanupInprocCluster(assert, cleanupDone) {
            if (options.cleanState) {
                cluster.assertCleanState(assert, options.cleanState);
            }
            cleanupDone(null);
        }

        function inprocClusterReady() {
            created(null, cluster);
        }
    }
}

// TODO: leftover from predecessor code, may be useful
// function closeClusterConnections(cluster, callback) {
//     var toClose = cluster.channels.length;
//     var errs = [];
//     cluster.channels.forEach(function each(channel) {
//         channel.peers.close(peersClosed);
//     });
//     function peersClosed(err) {
//         if (err) errs.push(err);
//         if (--toClose <= 0) callback(errs.length && errs[errs.length - 1]);
//     }
// }

module.exports.ClusterSearch = ClusterSearch;
module.exports.ClusterIsolateSearch = ClusterIsolateSearch;
module.exports.inprocClusterCreator = inprocClusterCreator;
<commit_msg>ClusterSearch: add remote cluster support<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var extend = require('xtend');
var util = require('util');

var ResourcePool = require('./resource_pool');
var TestSearch = require('./test_search');
var TestIsolateSearch = require('./test_isolate_search');

/*
 * Minimal cluster object expected by this module:
 *
 *   cluster :: {
 *     client :: TChannel // top
 *     hosts :: [hostPort :: String]
 *     channels :: [chan :: TChannel]
 *     cleanup :: (assert, callback) -> void
 *   }
 *
 * cluster.client should be in cluster.channnels, it may be the only one.
 *
 * The cleanup function is called after each test to cleanup and/or assert that
 * the cluster is in an expected state.  If it does not error and if the assert
 * has no failures, then the cluster is reused for the next test.  In other
 * words, if the cleanup function can cause the cluster to not be reused in two
 * ways:
 * - call callback(err)
 * - call assert.fail() (directly or not)
 *
 * Options:
 * - setupCluster :: (cluster, callback) -> void
 *   - should setup any necessary local assets (e.g. test-specific handlers on
 *     any local channels)
 *   - should setup any test-necesasry peering on local channels
 * - setupClient :: (cluster, callback) -> void
 *   - should setup any necessary test client channels (sub channels of
 *     cluster.client); these channels should be made available as
 *     cluster.fooClient
 */

// TODO:
// - explicit Cluster prototype to share between inproc, remote, and others
// - concurrent mode
// - share channels mode (e.g. for concurrency)

function ClusterSearch(options) {
    if (!(this instanceof ClusterSearch)) {
        return new ClusterSearch(options);
    }
    var self = this;
    TestSearch.call(self, options);
    initClusterSearch(self);
}
util.inherits(ClusterSearch, TestSearch);

function ClusterIsolateSearch(options) {
    if (!(this instanceof ClusterIsolateSearch)) {
        return new ClusterIsolateSearch(options);
    }
    var self = this;
    TestIsolateSearch.call(self, options);
    initClusterSearch(self);
}
util.inherits(ClusterIsolateSearch, TestIsolateSearch);

function initClusterSearch(self) {
    self.clusterPool = new ResourcePool(setupCluster);
    if (self.options.createCluster) {
        self.createCluster = self.options.createCluster;
    } else if (self.options.host) {
        var clientOptions = extend(self.options.clientOptions, {
            host: self.options.host
        });
        self.createCluster = clusterClientCreator(clientOptions);
    } else {
        var inprocOptions = extend(self.options.inprocOptions);
        self.createCluster = inprocClusterCreator(inprocOptions);
    }

    if (!self.options.reuseChannels) self.on('done', onSearchTestDone);

    function setupCluster(callback) {
        self.setupCluster(callback);
    }

    function onSearchTestDone() {
        self.destroy();
    }
}

ClusterSearch.prototype.destroy =
ClusterIsolateSearch.prototype.destroy =
function destroy(callback) {
    var self = this;
    self.clusterPool.destroy(callback);
};

ClusterSearch.prototype.setupCluster =
ClusterIsolateSearch.prototype.setupCluster =
function setupCluster(callback) {
    var self = this;
    self.createCluster(created);

    function created(err, cluster) {
        if (err) {
            callback(err, cluster);
        } else if (self.options.setupCluster) {
            callProvidedSetup(cluster);
        } else {
            self.setupClient(cluster, callback);
        }
    }

    function callProvidedSetup(cluster) {
        self.options.setupCluster.call(self, cluster, setupDone);
        function setupDone(err) {
            if (err) {
                callback(err, cluster);
            } else {
                self.setupClient(cluster, callback);
            }
        }
    }
};

ClusterSearch.prototype.createCluster =
ClusterIsolateSearch.prototype.createCluster =
function createCluster(callback) {
    callback(new Error('not implemented'), null);
};

ClusterSearch.prototype.setupClient =
ClusterIsolateSearch.prototype.setupClient =
function setupClient(cluster, callback) {
    var self = this;

    if (cluster.hosts) {
        cluster.hosts.forEach(
            function each(host) {
            if (host !== cluster.client.hostPort) {
                cluster.client.peers.add(host);
            }
        });
    }

    if (self.options.setupClient) {
        self.options.setupClient.call(self, cluster, finish);
    } else {
        finish(null);
    }

    // TODO: could pre-connect
    // var peers = client.peers.values();
    // peers.forEach(function each(peer) {
    //     var conn = peer.connect(true);
    //     if (conn.remoteName) {
    //         ready.signal();
    //     } else {
    //         conn.on('identified', ready.signal);
    //     }
    // });
    // ready(clientReady);
    // function clientReady() {
    //     callback(null, client);
    // }

    function finish(err) {
        callback(err, cluster);
    }
};

ClusterSearch.prototype.test =
ClusterIsolateSearch.prototype.test =
function test(state, assert) {
    var self = this;
    self.clusterPool.get(gotCluster);

    function gotCluster(err, cluster) {
        if (err) {
            finish(err, cluster);
        } else {
            self.options.clusterTest.call(self, cluster, state, assert, testDone);
        }

        function testDone(err) {
            cleanup(err, cluster);
        }
    }

    function cleanup(err, cluster) {
        if (err) {
            finish(err, cluster);
        } else {
            cluster.cleanup(assert, cleanupDone);
        }
        function cleanupDone(err) {
            finish(err, cluster);
        }
    }

    function finish(err, cluster) {
        assert.ifError(err, self.describeState(state) + ': no final error');
        if (!assert._ok) {
            cluster.destroy(assert.end);
        } else {
            self.clusterPool.release(cluster);
            assert.end();
        }
    }
};

function inprocClusterCreator(options) {
    var allocCluster = require('./alloc-cluster.js');

    // TODO: create explicit client, stop re-using a "peer" for it?

    if (!options) options = {};
    if (!options.numPeers) options.numPeers = 2;
    if (!options.cleanState) {
        options.cleanState = {
            channels: [{
                peers: [{
                    connections: [
                        {direction: 'in', inReqs: 0, outReqs: 0}
                    ]
                }]
            }, {
                peers: [{
                    connections: [
                        {direction: 'out', inReqs: 0, outReqs: 0}
                    ]
                }]
            }]
        };
    }

    return createInprocCluster;

    function createInprocCluster(created) {
        var cluster = allocCluster(options);
        cluster.client = cluster.channels[1];
        cluster.cleanup = cleanupInprocCluster;
        if (options.init) {
            options.init(cluster, function initDone(err) {
                if (err) {
                    created(err, cluster);
                } else {
                    cluster.ready(inprocClusterReady);
                }
            });
        } else {
            cluster.ready(inprocClusterReady);
        }

        function cleanupInprocCluster(assert, cleanupDone) {
            if (options.cleanState) {
                cluster.assertCleanState(assert, options.cleanState);
            }
            cleanupDone(null);
        }

        function inprocClusterReady() {
            created(null, cluster);
        }
    }
}

function clusterClientCreator(options) {
    var TChannel = require('../../channel');
    var format = require('util').format;

    if (!options) options = {};
    if (options.host) options.hosts = [options.host];
    if (!options.hosts) throw new Error('no host(s) specified');

    return createClusterClient;

    function createClusterClient(callback) {
        var cluster = {
            hosts: options.hosts,
            channels: [],
            destroy: destroyClusterClient,
            cleanup: cleanupClusterClient
        };
        cluster.client = TChannel(extend(options.clientOptions));
        cluster.channels.push(cluster.client);

        if (options.clientListen) {
            cluster.client.on('listening', onListening);
            cluster.client.listen(options.clientListen.port,
                                  options.clientListen.host);
        } else {
            callback(null, cluster);
        }

        // TODO: could re-use assertion logic with allocCluster, allowing user
        // to specify expected clean client state
        function cleanupClusterClient(assert, callback) {
            var peers = cluster.client.peers.values();
            peers.forEach(function eachPeer(peer, i) {
                peer.connections.forEach(function eachConn(conn, j) {
                    assert.equal(Object.keys(conn.requests.in).length, 0, format(
                        'client peer[%s] conn[%s] should have no inReqs', i, j));
                    assert.equal(Object.keys(conn.requests.out).length, 0, format(
                        'client peer[%s] conn[%s] should have no outReqs', i, j));
                });
            });
            callback(null);
        }

        function destroyClusterClient(callback) {
            cluster.client.close(callback);
        }

        function onListening() {
            callback(null, cluster);
        }
    }
}

// TODO: leftover from predecessor code, may be useful
// function closeClusterConnections(cluster, callback) {
//     var toClose = cluster.channels.length;
//     var errs = [];
//     cluster.channels.forEach(function each(channel) {
//         channel.peers.close(peersClosed);
//     });
//     function peersClosed(err) {
//         if (err) errs.push(err);
//         if (--toClose <= 0) callback(errs.length && errs[errs.length - 1]);
//     }
// }

module.exports.ClusterSearch = ClusterSearch;
module.exports.ClusterIsolateSearch = ClusterIsolateSearch;
module.exports.inprocClusterCreator = inprocClusterCreator;
module.exports.clusterClientCreator = clusterClientCreator;
<|endoftext|>


<commit_before>import Expression from '../Expression';
import Sequence from '../dataTypes/Sequence';
import Specificity from '../Specificity';

/**
 * @extends {Expression}
 */
class ContextItemExpression extends Expression {
	constructor () {
		super(
			new Specificity({}),
			[]
		);
	}

	evaluate (dynamicContext, _executionParameters) {
		if (dynamicContext.contextItem === null) {
			throw new Error('XPDY0002: context is absent, it needs to be present to use the "." operator');
		}
		return Sequence.singleton(dynamicContext.contextItem);
	}

}
export default ContextItemExpression;
<commit_msg>Make the context item expression correctly predict the result order<commit_after>import Expression from '../Expression';
import Sequence from '../dataTypes/Sequence';
import Specificity from '../Specificity';

/**
 * @extends {Expression}
 */
class ContextItemExpression extends Expression {
	constructor () {
		super(
			new Specificity({}),
			[],
			{
				resultOrder: Expression.RESULT_ORDERINGS.SORTED
			}
		);
	}

	evaluate (dynamicContext, _executionParameters) {
		if (dynamicContext.contextItem === null) {
			throw new Error('XPDY0002: context is absent, it needs to be present to use the "." operator');
		}
		return Sequence.singleton(dynamicContext.contextItem);
	}

}
export default ContextItemExpression;
<|endoftext|>


<commit_before>var jsonDateRx = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/;

/**
 * Create a deep copy of x which must be a value JSON object/array/value
 * @param {object|array|string|number|null} x object/array/value to clone
 * @returns {object|array|string|number|null} clone of x
 */
module.exports = function clone(x) {
	return x !== null && typeof x === 'object'
		? JSON.parse(JSON.stringify(x), dateReviver)
		: x;
};

/**
 * Deserialize dates from JSON
 * @param _
 * @param {*} value ISO date string
 * @returns {*|Date} returns parsed Date, or value if value is not a
 *  valid ISO date string
 */
function dateReviver(_, value) {
	var match;

	if (typeof value === 'string') {
		match = jsonDateRx.exec(value);
		if (match) {
			return new Date(Date.UTC(
					+match[1], +match[2] - 1, +match[3], +match[4], +match[5], +match[6])
			);
		}
	}

	return value;
}<commit_msg>Improve jiff.clone<commit_after>/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */

/**
 * Create a deep copy of x which must be a legal JSON object/array/value
 * @param {object|array|string|number|null} x object/array/value to clone
 * @returns {object|array|string|number|null} clone of x
 */
module.exports = clone;

function clone(x) {
	if(x == null || typeof x !== 'object') {
		return x;
	}

	if(Array.isArray(x)) {
		return cloneArray(x);
	}

	return cloneObject(x);
}

function cloneArray (x) {
	var l = x.length;
	var y = new Array(l);

	for (var i = 0; i < l; ++i) {
		y[i] = clone(x[i]);
	}

	return y;
}

function cloneObject (x) {
	var keys = Object.keys(x);
	var y = {};

	for (var k, i = 0, l = keys.length; i < l; ++i) {
		k = keys[i];
		y[k] = clone(x[k]);
	}

	return y;
}
<|endoftext|>


<commit_before>import {
  TEMP_PATH
} from '../constants'

import {
  invoke
} from '../../bridge'

import {
  warpPlusErrorCallback,
  getFileName
} from '../util'

import {
  t
} from 'uni-core/helpers/i18n'

export function chooseVideo ({
  sourceType,
  compressed,
  maxDuration,
  camera
} = {}, callbackId) {
  const errorCallback = warpPlusErrorCallback(callbackId, 'chooseVideo', 'cancel')

  function successCallback (tempFilePath = '') {
    const dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(tempFilePath)}`
    const compressVideo = compressed ? new Promise((resolve) => {
      plus.zip.compressVideo({
        src: tempFilePath,
        dst
      }, ({ tempFilePath }) => {
        resolve(tempFilePath)
      }, () => {
        resolve(tempFilePath)
      })
    }) : Promise.resolve()
    if (compressed) {
      plus.nativeUI.showWaiting()
    }
    compressVideo.then(tempFilePath => {
      if (compressed) {
        plus.nativeUI.closeWaiting()
      }
      plus.io.getVideoInfo({
        filePath: tempFilePath,
        success (videoInfo) {
          const result = {
            errMsg: 'chooseVideo:ok',
            tempFilePath: tempFilePath
          }
          result.size = videoInfo.size
          result.duration = videoInfo.duration
          result.width = videoInfo.width
          result.height = videoInfo.height
          invoke(callbackId, result)
        },
        errorCallback
      })
    })
  }

  function openAlbum () {
    plus.gallery.pick(({ files }) => successCallback(files[0]), errorCallback, {
      filter: 'video',
      system: false,
      // 不启用 multiple 时 system 无效
      multiple: true,
      maximum: 1,
      filename: TEMP_PATH + '/gallery/',
      permissionAlert: true
    })
  }

  function openCamera () {
    const plusCamera = plus.camera.getCamera()
    plusCamera.startVideoCapture(successCallback, errorCallback, {
      index: camera === 'front' ? 2 : 1,
      videoMaximumDuration: maxDuration,
      filename: TEMP_PATH + '/camera/'
    })
  }

  if (sourceType.length === 1) {
    if (sourceType.includes('album')) {
      openAlbum()
      return
    } else if (sourceType.includes('camera')) {
      openCamera()
      return
    }
  }
  plus.nativeUI.actionSheet({
    cancel: t('uni.chooseVideo.cancel'),
    buttons: [{
      title: t('uni.chooseVideo.sourceType.camera')
    }, {
      title: t('uni.chooseVideo.sourceType.album')
    }]
  }, e => {
    switch (e.index) {
      case 1:
        openCamera()
        break
      case 2:
        openAlbum()
        break
      default:
        errorCallback()
        break
    }
  })
}
<commit_msg>fix: 修复 chooseVideo 未启用压缩时无回调的问题<commit_after>import {
  TEMP_PATH
} from '../constants'

import {
  invoke
} from '../../bridge'

import {
  warpPlusErrorCallback,
  getFileName
} from '../util'

import {
  t
} from 'uni-core/helpers/i18n'

export function chooseVideo ({
  sourceType,
  compressed,
  maxDuration,
  camera
} = {}, callbackId) {
  const errorCallback = warpPlusErrorCallback(callbackId, 'chooseVideo', 'cancel')

  function successCallback (tempFilePath = '') {
    const dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(tempFilePath)}`
    const compressVideo = compressed ? new Promise((resolve) => {
      plus.zip.compressVideo({
        src: tempFilePath,
        dst
      }, ({ tempFilePath }) => {
        resolve(tempFilePath)
      }, () => {
        resolve(tempFilePath)
      })
    }) : Promise.resolve(tempFilePath)
    if (compressed) {
      plus.nativeUI.showWaiting()
    }
    compressVideo.then(tempFilePath => {
      if (compressed) {
        plus.nativeUI.closeWaiting()
      }
      plus.io.getVideoInfo({
        filePath: tempFilePath,
        success (videoInfo) {
          const result = {
            errMsg: 'chooseVideo:ok',
            tempFilePath: tempFilePath
          }
          result.size = videoInfo.size
          result.duration = videoInfo.duration
          result.width = videoInfo.width
          result.height = videoInfo.height
          invoke(callbackId, result)
        },
        fail: errorCallback
      })
    })
  }

  function openAlbum () {
    plus.gallery.pick(({ files }) => successCallback(files[0]), errorCallback, {
      filter: 'video',
      system: false,
      // 不启用 multiple 时 system 无效
      multiple: true,
      maximum: 1,
      filename: TEMP_PATH + '/gallery/',
      permissionAlert: true
    })
  }

  function openCamera () {
    const plusCamera = plus.camera.getCamera()
    plusCamera.startVideoCapture(successCallback, errorCallback, {
      index: camera === 'front' ? 2 : 1,
      videoMaximumDuration: maxDuration,
      filename: TEMP_PATH + '/camera/'
    })
  }

  if (sourceType.length === 1) {
    if (sourceType.includes('album')) {
      openAlbum()
      return
    } else if (sourceType.includes('camera')) {
      openCamera()
      return
    }
  }
  plus.nativeUI.actionSheet({
    cancel: t('uni.chooseVideo.cancel'),
    buttons: [{
      title: t('uni.chooseVideo.sourceType.camera')
    }, {
      title: t('uni.chooseVideo.sourceType.album')
    }]
  }, e => {
    switch (e.index) {
      case 1:
        openCamera()
        break
      case 2:
        openAlbum()
        break
      default:
        errorCallback()
        break
    }
  })
}
<|endoftext|>


<commit_before>'use strict';

const template = require('../../views/pages/ForecastWeather.hbs');
const Button = require('../../js/components/Button');

class ForecastWeather {

	constructor() {
		this.container = document.createElement('div');
		this.container.classList.add('forecast-weather-container');

		this.render();

	}

	render() {
		this.container.innerHTML = template();
		this.button();
	}

	button() {
		const button = new Button('Go to Current Weather');
		this.container.appendChild(button.container);

		button.container.addEventListener('click', () => {
			this.hidden();
			this.container.previousElementSibling.classList.add('show');
		});
	}

	show(data) {
		this.container.classList.add('show');

		this.printWeather(data);
	}

	hidden() {
		this.container.classList.remove('show');
	}

	//ToDo: Move this data to appropriate files.
	printWeather(data) {

		const forecastWeatherContainer = document.querySelector('.forecast-weather')
		forecastWeatherContainer.innerHTML = '';

		const forecastData = data.forecast.forecastday;
		forecastData.forEach(days => {
			forecastWeatherContainer.innerHTML += `

				${days.date}
				${data.location.name}

				${days.day.avgtemp_c + " °C"}
				${days.day.condition.text}

			`
		});

	}
}

module.exports = ForecastWeather;
<commit_msg>Delete space<commit_after>'use strict';

const template = require('../../views/pages/ForecastWeather.hbs');
const Button = require('../../js/components/Button');

class ForecastWeather {

	constructor() {
		this.container = document.createElement('div');
		this.container.classList.add('forecast-weather-container');

		this.render();

	}

	render() {
		this.container.innerHTML = template();
		this.button();
	}

	button() {
		const button = new Button('Go to Current Weather');
		this.container.appendChild(button.container);

		button.container.addEventListener('click', () => {
			this.hidden();
			this.container.previousElementSibling.classList.add('show');
		});
	}

	show(data) {
		this.container.classList.add('show');

		this.printWeather(data);
	}

	hidden() {
		this.container.classList.remove('show');
	}

	//ToDo: Move this data to appropriate files.
	printWeather(data) {
		const forecastWeatherContainer = document.querySelector('.forecast-weather')
		forecastWeatherContainer.innerHTML = '';

		const forecastData = data.forecast.forecastday;
		forecastData.forEach(days => {
			forecastWeatherContainer.innerHTML += `

				${days.date}
				${data.location.name}

				${days.day.avgtemp_c + " °C"}
				${days.day.condition.text}

			`
		});

	}
}

module.exports = ForecastWeather;
<|endoftext|>


<commit_before>var matter = require('gray-matter');
var utf8 = require('is-utf8');
var each = require('metalsmith-each');

module.exports = frontmatter;

/**
 * Assign all iterable properties in `source` to `target`.
 *
 * In ECMAScript 6, this function can be replaced with `Object.assign`.
 *
 * @param {Object} target
 * @param {Object} source
 */

function mergeProperties(target, source){
  for (var propertyName in source) {
    target[propertyName] = source[propertyName];
  }
}

/**
 * Assign metadata in `file` based on the YAML frontmatter in `file.contents`.
 *
 * @param {Object} file The Metalsmith file object to extract frontmatter from
 * @param {string} filePath The path to the file represented by `file`
 */

function extractFrontmatter(file, filePath){
  if (utf8(file.contents)) {
    try {
      parsed = matter(file.contents.toString());
    } catch (e) {
      var errMsg = 'Invalid frontmatter in file'
      if (filePath !== undefined) errMsg += ": " + filePath;
      var err = new Error(errMsg);
      err.code = 'invalid_frontmatter';
      err.cause = e;
      throw err;
    }

    mergeProperties(file, parsed.data);
    file.contents = new Buffer(parsed.content);
  }
}

/**
 * Metalsmith plugin to extract metadata from frontmatter in file contents.
 *
 * @return {Function}
 */

function frontmatter(){
  return each(extractFrontmatter);
}
<commit_msg>Remove accidental global variable<commit_after>var matter = require('gray-matter');
var utf8 = require('is-utf8');
var each = require('metalsmith-each');

module.exports = frontmatter;

/**
 * Assign all iterable properties in `source` to `target`.
 *
 * In ECMAScript 6, this function can be replaced with `Object.assign`.
 *
 * @param {Object} target
 * @param {Object} source
 */

function mergeProperties(target, source){
  for (var propertyName in source) {
    target[propertyName] = source[propertyName];
  }
}

/**
 * Assign metadata in `file` based on the YAML frontmatter in `file.contents`.
 *
 * @param {Object} file The Metalsmith file object to extract frontmatter from
 * @param {string} filePath The path to the file represented by `file`
 */

function extractFrontmatter(file, filePath){
  if (utf8(file.contents)) {
    try {
      var parsed = matter(file.contents.toString());
    } catch (e) {
      var errMsg = 'Invalid frontmatter in file'
      if (filePath !== undefined) errMsg += ": " + filePath;
      var err = new Error(errMsg);
      err.code = 'invalid_frontmatter';
      err.cause = e;
      throw err;
    }

    mergeProperties(file, parsed.data);
    file.contents = new Buffer(parsed.content);
  }
}

/**
 * Metalsmith plugin to extract metadata from frontmatter in file contents.
 *
 * @return {Function}
 */

function frontmatter(){
  return each(extractFrontmatter);
}
<|endoftext|>


<commit_before>/* ************************************************************************

   Flicky

   Copyright:
     2010-2011 Deutsche Telekom AG, Germany, http://telekom.com

************************************************************************ */

/**
 * Shows meta data of selected photo
 */
qx.Class.define("flicky.view.Meta",
{
  extend : unify.view.ServiceView,
  type : "singleton",

  properties :
  {
    // overridden
    modal :
    {
      refine : true,
      init : true
    }
  },

  members :
  {
    __content : null,
    __template : null,

    // overridden
    getTitle : function(type) {
      return "Meta Data";
    },

    // overridden
    _createView : function()
    {
      var layer = new unify.ui.Layer(this);
      var titlebar = new unify.ui.TitleBar(this);
      titlebar.add({label:"Fertig", rel:"close", target:"right"});
      layer.add(titlebar);

      var content = this.__content = new unify.ui.Content;
      layer.add(content);

      return layer;
    },

    // overridden
    _getBusinessObject : function() {
      return flicky.business.Flickr.getInstance();
    },

    // overridden
    _getServiceName : function() {
      return "info";
    },

    // overridden
    _getRenderVariant : function() {
      return flicky.view.Photo.getInstance().getParam();
    },

    // overridden
    _getServiceParams : function()
    {
      return {
        "photo" : flicky.view.Photo.getInstance().getParam()
      };
    },

    // overridden
    _renderData : function(data)
    {
      var template = this.__template;
      if (!template)
      {
        var html = "
";

        html += "
Title{title}
";
        html += "
ID{id}
";
        html += "
Description{description}
";
        html += "
Comments{comments}
";

        html += "
";

        template = this.__template = new qx.util.Template(html);
      }

      var photo = data.query.results.photo;
      this.__content.replace(template.run(photo));
    }
  }
});
<commit_msg>Minor change<commit_after>/* ************************************************************************

   Flicky

   Copyright:
     2010-2011 Deutsche Telekom AG, Germany, http://telekom.com

************************************************************************ */

/**
 * Shows meta data of selected photo
 */
qx.Class.define("flicky.view.Meta",
{
  extend : unify.view.ServiceView,
  type : "singleton",

  properties :
  {
    // overridden
    modal :
    {
      refine : true,
      init : true
    }
  },

  members :
  {
    __content : null,
    __template : null,

    // overridden
    getTitle : function(type) {
      return "Meta Data";
    },

    // overridden
    _createView : function()
    {
      var layer = new unify.ui.Layer(this);
      var titlebar = new unify.ui.TitleBar(this);
      titlebar.add({label:"Done", rel:"close", target:"right"});
      layer.add(titlebar);

      var content = this.__content = new unify.ui.Content;
      layer.add(content);

      return layer;
    },

    // overridden
    _getBusinessObject : function() {
      return flicky.business.Flickr.getInstance();
    },

    // overridden
    _getServiceName : function() {
      return "info";
    },

    // overridden
    _getRenderVariant : function() {
      return flicky.view.Photo.getInstance().getParam();
    },

    // overridden
    _getServiceParams : function()
    {
      return {
        "photo" : flicky.view.Photo.getInstance().getParam()
      };
    },

    // overridden
    _renderData : function(data)
    {
      var template = this.__template;
      if (!template)
      {
        var html = "
";

        html += "
Title{title}
";
        html += "
ID{id}
";
        html += "
Description{description}
";
        html += "
Comments{comments}
";

        html += "
";

        template = this.__template = new qx.util.Template(html);
      }

      var photo = data.query.results.photo;
      this.__content.replace(template.run(photo));
    }
  }
});
<|endoftext|>


<commit_before>/**
* used to display comment and ask pages
*/

import util from './hn_util.js';
import { HNStory } from './story.js';
import { HNComment } from './comment.js';

// HN.clearComments = function(){
// 	document.getElementById('content_main').innerHTML = '';
// };

export function displayComments(commentsType){
	var storyId = window.location.href.match(/\d+\/?$/);
	if(storyId){
		//remove possible trailing slash
		storyId = storyId[0].replace(/\/$/, '');
		var storyUrl = 'https://hacker-news.firebaseio.com/v0/item/' + storyId + '.json';
	}
	else{
		console.log("No story id found");
		return;
	}
	util.getJSON(storyUrl, function(storyInfo){
			if(!storyInfo){
				console.log('No info about the story returned');
				return;
			}
			var story = new HNStory(storyInfo);
			var title_class = 'container'
			var text = story.text();
			var title = '';
			if(text){
				text = "
" + story.author() + "

" + util.smartenQuotesHTML(story.text())  + "
";
				if(commentsType === 'ask' || story.title().match(/^(Ask|Tell) HN:/)){
					title_class += ' ask';
					title = util.getAskStoryTitle(story);
				}
			}
			else{
				title = util.getStoryTitleHTML(story)
			}
			document.title = document.title + " | " + story.title();
			document.getElementById('content_main').insertAdjacentHTML('afterbegin', "
" + title + text + "
");
			displayAllCommentChildren(story.getTopLevelCommentsIds());
		},

		function(){console.log("Error retrieving comments");}
	);

	/**
	* displays comment children of an array of comment ids
	* if no cssId is given, assumes it is top level comment and creates appropriate jquery cssId object
	*/
	function displayAllCommentChildren(commentIdArray, cssId){
		if(!commentIdArray){
			return;
		}
		var isTopLevelComment = !cssId;
		var parentList = cssId ? document.getElementById(cssId) : document.getElementById('top_list');
		var numCommentIds = commentIdArray.length;

		commentIdArray.forEach(function(commentId){
			util.getJSON(util.getItemInfoUrlFromId(commentId), function(commentInfo){
					displayComment(commentInfo, parentList, isTopLevelComment);
				},
				function(){console.log("Error retrieving info about comment: " + commentId);}
			);

		});

		//change hacker news links to hnews links
		util.redirectLinks();

	}

	/**
	* displays comment
	* parent_list is a dom object that the comment should be appended to
	* isTopLevelComment is used for styling purposes, since top level comments are styled different than child comments
	*/
	function displayComment(commentInfo, parent_list, isTopLevelComment){
		if(!commentInfo){
			return;
		}
		var comment = new HNComment(commentInfo);
		if(comment.isDead()){
			return;
		}
		if(comment.isDeleted()){
			comment = getDeletedComment(commentInfo);
		}
		var commentHTML = "
";
		if(isTopLevelComment){
			commentHTML += "
";
		}
		commentHTML += "
" + comment.author() + "

" + util.smartenQuotesHTML(comment.text()) + "
";

		if(comment.numChildren() > 0){
			commentHTML += "

";
		}
		if(isTopLevelComment){
			commentHTML += "
";
		}
		commentHTML +=  "
";

		parent_list.insertAdjacentHTML('beforeend', commentHTML);
		displayAllCommentChildren(comment.children(), commentIdToCSSId(comment.commentId()));
	}

	/**
	* Returns the correct jquery id cssId for the parent ol to append comment to
	*/
	function commentIdToCSSId(commentId){
		return 'comment' + commentId;
	}

	/**
	* Returns the text used in place of deleted comments
	*/
	function getDeletedComment(commentInfo){
		commentInfo.by = '';
		commentInfo.text = '[deleted]'
		return new HNComment(commentInfo);
	}
};

<commit_msg>Remove clearComments function since it is unused<commit_after>/**
* used to display comment and ask pages
*/

import util from './hn_util.js';
import { HNStory } from './story.js';
import { HNComment } from './comment.js';

export function displayComments(commentsType){
	var storyId = window.location.href.match(/\d+\/?$/);
	if(storyId){
		//remove possible trailing slash
		storyId = storyId[0].replace(/\/$/, '');
		var storyUrl = 'https://hacker-news.firebaseio.com/v0/item/' + storyId + '.json';
	}
	else{
		console.log("No story id found");
		return;
	}
	util.getJSON(storyUrl, function(storyInfo){
			if(!storyInfo){
				console.log('No info about the story returned');
				return;
			}
			var story = new HNStory(storyInfo);
			var title_class = 'container'
			var text = story.text();
			var title = '';
			if(text){
				text = "
" + story.author() + "

" + util.smartenQuotesHTML(story.text())  + "
";
				if(commentsType === 'ask' || story.title().match(/^(Ask|Tell) HN:/)){
					title_class += ' ask';
					title = util.getAskStoryTitle(story);
				}
			}
			else{
				title = util.getStoryTitleHTML(story)
			}
			document.title = document.title + " | " + story.title();
			document.getElementById('content_main').insertAdjacentHTML('afterbegin', "
" + title + text + "
");
			displayAllCommentChildren(story.getTopLevelCommentsIds());
		},

		function(){console.log("Error retrieving comments");}
	);

	/**
	* displays comment children of an array of comment ids
	* if no cssId is given, assumes it is top level comment and creates appropriate jquery cssId object
	*/
	function displayAllCommentChildren(commentIdArray, cssId){
		if(!commentIdArray){
			return;
		}
		var isTopLevelComment = !cssId;
		var parentList = cssId ? document.getElementById(cssId) : document.getElementById('top_list');
		var numCommentIds = commentIdArray.length;

		commentIdArray.forEach(function(commentId){
			util.getJSON(util.getItemInfoUrlFromId(commentId), function(commentInfo){
					displayComment(commentInfo, parentList, isTopLevelComment);
				},
				function(){console.log("Error retrieving info about comment: " + commentId);}
			);

		});

		//change hacker news links to hnews links
		util.redirectLinks();

	}

	/**
	* displays comment
	* parent_list is a dom object that the comment should be appended to
	* isTopLevelComment is used for styling purposes, since top level comments are styled different than child comments
	*/
	function displayComment(commentInfo, parent_list, isTopLevelComment){
		if(!commentInfo){
			return;
		}
		var comment = new HNComment(commentInfo);
		if(comment.isDead()){
			return;
		}
		if(comment.isDeleted()){
			comment = getDeletedComment(commentInfo);
		}
		var commentHTML = "
";
		if(isTopLevelComment){
			commentHTML += "
";
		}
		commentHTML += "
" + comment.author() + "

" + util.smartenQuotesHTML(comment.text()) + "
";

		if(comment.numChildren() > 0){
			commentHTML += "

";
		}
		if(isTopLevelComment){
			commentHTML += "
";
		}
		commentHTML +=  "
";

		parent_list.insertAdjacentHTML('beforeend', commentHTML);
		displayAllCommentChildren(comment.children(), commentIdToCSSId(comment.commentId()));
	}

	/**
	* Returns the correct jquery id cssId for the parent ol to append comment to
	*/
	function commentIdToCSSId(commentId){
		return 'comment' + commentId;
	}

	/**
	* Returns the text used in place of deleted comments
	*/
	function getDeletedComment(commentInfo){
		commentInfo.by = '';
		commentInfo.text = '[deleted]'
		return new HNComment(commentInfo);
	}
};

<|endoftext|>


<commit_before>var gulp = require('gulp'),
    args = require('yargs').argv,
    assemblyInfo = require('gulp-dotnet-assembly-info'),
    msbuild = require('gulp-msbuild'),
    nunit = require('gulp-nunit-runner'),
    Nuget = require('nuget-runner');

gulp.task('deploy', ['nuget-push']);

gulp.task('ci', ['nuget-package']);

gulp.task('assemblyInfo', function() {
    return gulp
        .src('**/AssemblyInfo.cs')
        .pipe(assemblyInfo({
            version: args.buildVersion,
            fileVersion: args.buildVersion,
            copyright: function(value) {
                return 'Copyright © ' + new Date().getFullYear() + ' Ultraviolet Catastrophe.';
            }
        }))
        .pipe(gulp.dest('.'));
});

gulp.task('build', ['assemblyInfo'], function() {
    return gulp
        .src('src/*.sln')
        .pipe(msbuild({
            toolsVersion: 4.0,
            targets: ['Clean', 'Build'],
            errorOnFail: true,
            stdout: true
        }));
});

gulp.task('test', ['build'], function () {
    return gulp
        .src(['**/bin/**/*Tests.dll'], { read: false })
        .pipe(nunit({
            teamcity: true
        }));
});

gulp.task('nuget-package', ['test'], function() {

    gulp.src('src/Swank/bin/Release/FubuMVC.Swank.*')
        .pipe(gulp.dest('package/lib'));

    return Nuget()
        .pack({
            spec: 'FubuMVC.Swank.nuspec',
            basePath: 'package',
            version: args.buildVersion
        });
});

gulp.task('nuget-push', ['nuget-package'], function() {
    return Nuget({ apiKey: args.nugetApiKey }).push('*.nupkg');
});<commit_msg>Bumped compiler version.<commit_after>var gulp = require('gulp'),
    args = require('yargs').argv,
    assemblyInfo = require('gulp-dotnet-assembly-info'),
    msbuild = require('gulp-msbuild'),
    nunit = require('gulp-nunit-runner'),
    Nuget = require('nuget-runner');

gulp.task('deploy', ['nuget-push']);

gulp.task('ci', ['nuget-package']);

gulp.task('assemblyInfo', function() {
    return gulp
        .src('**/AssemblyInfo.cs')
        .pipe(assemblyInfo({
            version: args.buildVersion,
            fileVersion: args.buildVersion,
            copyright: function(value) {
                return 'Copyright © ' + new Date().getFullYear() + ' Ultraviolet Catastrophe.';
            }
        }))
        .pipe(gulp.dest('.'));
});

gulp.task('build', ['assemblyInfo'], function() {
    return gulp
        .src('src/*.sln')
        .pipe(msbuild({
            toolsVersion: 14.0,
            targets: ['Clean', 'Build'],
            errorOnFail: true,
            stdout: true
        }));
});

gulp.task('test', ['build'], function () {
    return gulp
        .src(['**/bin/**/*Tests.dll'], { read: false })
        .pipe(nunit({
            teamcity: true
        }));
});

gulp.task('nuget-package', ['test'], function() {

    gulp.src('src/Swank/bin/Release/FubuMVC.Swank.*')
        .pipe(gulp.dest('package/lib'));

    return Nuget()
        .pack({
            spec: 'FubuMVC.Swank.nuspec',
            basePath: 'package',
            version: args.buildVersion
        });
});

gulp.task('nuget-push', ['nuget-package'], function() {
    return Nuget({ apiKey: args.nugetApiKey }).push('*.nupkg');
});
<|endoftext|>


<commit_before>/*jshint node: true */
'use strict';

/*
* Name :  Flow.js
* Module : UnitTest
* Location : /frontend/test/unit/Model
*
* History :
* Version       Date        Programmer                  Description
* =================================================================================================
* 0.1.1         2015-05-17  Maria Giovanna Chinellato   Fix code
*
* 0.1.0			2015-05-15	Maria Giovanna Chinellato	Add test of Model::Flow.js
*
* 0.0.1			2015-05-15	Maria Giovanna Chinellato	Initial code
* =================================================================================================
*
*/

describe('FlowFactory', function(){

	var FlowFactory;

	beforeEach(angular.mock.module('norris-nrti'));

	beforeEach(inject(function(_FlowFactory_){
		FlowFactory = _FlowFactory_;
	}));

	describe('Constructor', function(){

		var Flow;

		beforeEach(function(){
			Flow = FlowFactory.build();
		});

		afterEach(function(){
			Flow = null;
		});

		it('instance defined', function(){
			expect(Flow).toBeDefined();
		});
		it('constructor create the flow with the correct name', function(){
			expect(Flow.getName()).toEqual(null);
		});

	});

	describe('Constructor', function(){

		var json = {
			'name' : 'flusso1'
		};
		var Flow;

		beforeEach(function(){
			Flow = FlowFactory.build(json);
		});

		afterEach(function(){
			Flow = null;
		});

		it('instance defined', function(){
			expect(Flow).toBeDefined();
		});
		it('constructor create the flow with the correct name', function(){
			expect(Flow.getName()).toEqual('flusso1');
		});

	});

	describe('updateParameters', function(){
		var json = {
			'name' : 'flussoString1'
		};
		var Flow;

		beforeEach(function(){
			Flow = FlowFactory.build();
			Flow.updateParameters(json);
		});

		afterEach(function(){
			Flow = null;
		});
		it('flow updated with the correct name', function(){
			expect(Flow.getName()).toEqual('flussoString1');
		});

	});

});<commit_msg>add # to describe test<commit_after>/*jshint node: true */
'use strict';

/*
* Name :  Flow.js
* Module : UnitTest
* Location : /frontend/test/unit/Model
*
* History :
* Version       Date        Programmer                  Description
* =================================================================================================
* 0.1.1         2015-05-17  Maria Giovanna Chinellato   Fix code
*
* 0.1.0			2015-05-15	Maria Giovanna Chinellato	Add test of Model::Flow.js
*
* 0.0.1			2015-05-15	Maria Giovanna Chinellato	Initial code
* =================================================================================================
*
*/

describe('FlowFactory', function(){

	var FlowFactory;

	beforeEach(angular.mock.module('norris-nrti'));

	beforeEach(inject(function(_FlowFactory_){
		FlowFactory = _FlowFactory_;
	}));

	describe('Constructor', function(){

		var Flow;

		beforeEach(function(){
			Flow = FlowFactory.build();
		});

		afterEach(function(){
			Flow = null;
		});

		it('instance defined', function(){
			expect(Flow).toBeDefined();
		});
		it('constructor create the flow with the correct name', function(){
			expect(Flow.getName()).toEqual(null);
		});

	});

	describe('Constructor', function(){

		var json = {
			'name' : 'flusso1'
		};
		var Flow;

		beforeEach(function(){
			Flow = FlowFactory.build(json);
		});

		afterEach(function(){
			Flow = null;
		});

		it('instance defined', function(){
			expect(Flow).toBeDefined();
		});
		it('constructor create the flow with the correct name', function(){
			expect(Flow.getName()).toEqual('flusso1');
		});

	});

	describe('#updateParameters', function(){
		var json = {
			'name' : 'flussoString1'
		};
		var Flow;

		beforeEach(function(){
			Flow = FlowFactory.build();
			Flow.updateParameters(json);
		});

		afterEach(function(){
			Flow = null;
		});
		it('flow updated with the correct name', function(){
			expect(Flow.getName()).toEqual('flussoString1');
		});

	});

});<|endoftext|>


<commit_before>;(function (module) {

	'use strict';

	//+ _is :: (any, string) -> boolean
	var _is = function(entity, type) {
		return Object.prototype.toString.call(entity).slice(8, -1) === type;
	},

	//+ _truhty :: any -> object -> boolean
	_truthy = function(entity) {

		return  {
			'obj': function() {
				return (_is(entity, 'Object') && Object.keys(entity).length);
			},

			'string': function() {
				return (_is(entity, 'String') && entity.length);
			},

			'number': function() {
				return (
				entity && _is(entity, 'Number')
				&& entity !== Infinity
				&& entity !== -Infinity
				);
			},

			'fun': function() {
				return _is(entity, 'Function');
			},

			'array': function() {
				return (_is(entity, 'Array') && entity.length);
			}
		};
	},

	//+ _generate :: (object,object) -> object
	_generate = function(methods, parent) {
		// extend an object with another objects properties/state
		// returns a new object, leaving both methods & parent untouched

		// holds Builder arguments array
		var args,

		// allow us to cache arguments of the initial Builder call
		init = false,

		Builder = function() {

			// if first call, cache arguments
			if(!init) {
				args = arguments;
			}

			// builder is ready
			init = true;

			if(!(this instanceof Builder)) {
				return new Builder();
			}

			this._constructor.apply(this, args);
		};

		// attach parent members
		Builder.prototype = parent;

		// attach all method members to the Builder
		for(var method in methods) {
			if(methods.hasOwnProperty(method)) {
				Builder.prototype[method] = methods[method];
			}
		}

		// when no '_constructor' found, init an empty constructor
		if(!Builder.prototype._constructor) {
			Builder.prototype._constructor = function() { };
		}

		return Builder;
	},

	//+ _async :: function -> undefined
	_async = function(fn) {
		// force fn to be async
		setTimeout(fn, 0);
	},

	_error = {
		// convenience object for throwing helpful errors

		'subUsage': function() {
			return 'USAGE [ topic:String, object:Object, toCall:String ]';
		},

		'pubUsage': function() {
			return 'UASGE [ topic:String[, data1:Any[, data2:Any[, ..]]] ]';
		},

		'unsubUsage': function() {
			return 'USAGE [topic:String, reference:Subscriber]';
		},

		'pubError': function(topic, error) {
			return 'Failed to publish to obj on topic "' +
				topic + '" [' + error.message + ']';
		},

		'extendUsage': function() {
			return 'argument to Bugle extend must be a literal object';
		},

		'pipeUsage': function() {
			return 'USAGE [ event:String, fn:Function ]';
		},

		'unknownPipeEvent': function(evnt) {
			return 'invalid pipe event [' + evnt + '], could not add to pipeline';
		}
	},

	//+ _compose :: array(function) -> function -> any
	_compose = function() {
		var fns = Array.prototype.slice.call(arguments);

		return arr => {
			return fns.reduce((arg, fn, index) => {
				return fn.call(this, arg, index, arr);
			}, arr);
		};
	},

	//+ _flatten :: array -> array
	// e.g. [[1,2,3,4,5], [4,5,6]] -> [1,2,3,4,5,4,5,6]
	_flatten = function(arr) {
		return arr.reduce((prev, curr) => {
			var isArr = _truthy(curr).array();
			return prev.concat(isArr? _flatten(curr) : curr);
		}, []);
	},

	//+ _map :: function,array -> array
	_map = function(fn, arr) {
		return arr.reduce((prev, curr) => {
			return prev.concat([fn.call(this, curr)]);
		}, []);
	},

	//+ _filter :: function,array -> array
	_filter = function(pred, arr) {
		return arr.reduce((prev, curr) => {
			return pred.call(this, curr)? prev.concat([curr]): prev;
		}, []);
	},

	//+ _flatMap :: function,array -> array
	_flatMap = function(fn, arr) {
		// map array over accumulator function,
		// flatten each message item but no join

		var res = _compose.call(
			this,
			_map.bind(null, fn),
			_map.bind(null, _flatten)
		)(arr);

		console.log(res);

		return res;
	},

	//+ _done :: function,array -> unit
	_done = function(fn, arr) {
		fn.apply(this, [].concat(arr));
	},

	// pipe api module
	// functions are captured during pipe phase
	// apply collections over functions during digest phase
	_pipeEvents = {

		'map': function(fn) {
			return function(arr) {
				return _map.call(this, fn, arr);
			};
		},

		'filter': function(pred) {
			return function(arr) {
				return _filter.call(this, pred, arr);
			};
		},

		'flatMap': function(fn) {
			return function(arr) {
				return _flatMap.call(this, fn, arr);
			};
		},

		'done': function(fn) {
			return function(arr) {
				_done.call(this, fn, arr);
			}
		}
	},

	//+ _dispatch :: (string, any, Subscriber) -> undefined
	_dispatch = function(topic, data, subscriber) {

		// apply current sub object and pub args to sub function
		_async(() => {
			try {
				subscriber.digest(data);
			} catch(e) {
				throw _error.pubError(topic, e);
			}
		});
	},

	//+ _publish :: string [, any[, ...]] -> undefined
	_publish = function(topic) {
		// notify all subscribers of a topic with a message(s)

		var self = this;

		if(_truthy(topic).string()) {

			var args = Array.prototype.slice.call(arguments, 1),
			channelItem = _dispatch.bind(null, topic, args);

			// publish args to each subscriber on topic
			if(self.topics[topic]) {
				var subscribers = self.topics[topic];
				subscribers.forEach(channelItem);
			}
		} else {
			throw _error.pubUsage();
		}
	},

	//+ _subscribe :: (string, function, object) -> Subscriber
	_subscribe = function(topic, scope) {
		// subscribe a function to a topic
		// with a given scope (defaults to current Bugle instance)

		scope = scope? scope : this;

		if(_truthy(topic).string()) {

			if(!this.topics[topic]) {
				this.topics[topic] = [];
			}

			var subscriber = new Subscriber(++this.oId, scope);
			this.topics[topic].push(subscriber);

			return subscriber;

		} else {
			throw _error.subUsage();
		}
	},

	//+ _unsubscribe :: string, Subscriber -> undefined
 	_unsubscribe = function(topic, subscriber) {
		// removes a subscriber object from the subscriptions list

		if(subscriber
		&& _truthy(subscriber.oId).number()
		&& _truthy(topic).string()
		) {

			var subscribers = this.topics[topic],
			oId = subscriber.oId,

			// probably wont stay...
			maybeRemove = function(subscriber, index) {
				if(subscriber.oId === oId) subscribers.splice(index, 1);
			};

			if(subscribers) {
				_async(() => {
					subscribers.forEach(maybeRemove);
				});
			}

		} else {
			throw _error.unsubUsage();
		}
	},

	// extends the current bugle instance prototype with properties
	_extend = function(methods) {

		if(_truthy(methods).obj()) {
			return _generate(methods, this);
		} else {
			throw _error.extendUsage();
		}
	},

	//+ pipe :: string,function -> Subscriber
	_pipe = function(evnt, fn) {

		if(_truthy(evnt).string() && _truthy(fn).fun()) {

			var maybeEvent = _pipeEvents[evnt];

			if(maybeEvent) {
				this._pipeline_.push(maybeEvent(fn));
			} else {
				throw _error.unknownPipeEvent(evnt);
			}

		} else {
			throw _error.pipeUsage();
		}

		return this;
	},

	//+ digest :: array -> undefined
	_digest = function(data) {
		// take published data,
		// reduce over pipelined hofs
		if(_truthy(this._pipeline_).array()) {
			_compose.apply(this.obj, this._pipeline_)(data);
		}
	};

	// holds the state of each new subscription on a topic
	function Subscriber(id, obj) {
		this.oId = id;
		this.obj = obj;

		// holds all fns to reduce over published data
		this._pipeline_ = [];
	}

	Subscriber.prototype = {
		'pipe': _pipe,
		'digest': _digest
	};

	// holds all user topics & reference to next unique subscriber id
	function Bugle() {

		//removes the need for 'new' keyword
		if(!(this instanceof Bugle)) {
			return new Bugle();
		}

		// holds topic namespaces along with its subscribers
		this.topics = [];

		// tracking id generated for each new subscription
		this.oId = 0;
	}

	Bugle.prototype = {

		'pub': _publish,

		'sub': _subscribe,

		'unsub': _unsubscribe,

		'extend': _extend
	};

	module['extend'] = function(methods) {
		return Bugle().extend(methods);
	}

} )(typeof module !== 'undefined' && module.exports? module.exports : window.Bugle = {});<commit_msg>added comments, removed console.logs<commit_after>/**
 *	Bugle-js => event-driven publish-subscribe javascript api
 *
 *	TODO:
 *		1. reveal subscriber pipe api to user,
 *		2. chain calls until event is published to subscriber
 **/
;(function (module) {

	'use strict';

	//+ _is :: (any, string) -> boolean
	var _is = function(entity, type) {
		return Object.prototype.toString.call(entity).slice(8, -1) === type;
	},

	//+ _truhty :: any -> object -> boolean
	_truthy = function(entity) {

		return  {
			'obj': function() {
				return (_is(entity, 'Object') && Object.keys(entity).length);
			},

			'string': function() {
				return (_is(entity, 'String') && entity.length);
			},

			'number': function() {
				return (
				entity && _is(entity, 'Number')
				&& entity !== Infinity
				&& entity !== -Infinity
				);
			},

			'fun': function() {
				return _is(entity, 'Function');
			},

			'array': function() {
				return (_is(entity, 'Array') && entity.length);
			}
		};
	},

	//+ _generate :: (object,object) -> object
	_generate = function(methods, parent) {
		// extend an object with another objects properties/state
		// returns a new object, leaving both methods & parent untouched

		// holds Builder arguments array
		var args,

		// allow us to cache arguments of the initial Builder call
		init = false,

		Builder = function() {

			// if first call, cache arguments
			if(!init) {
				args = arguments;
			}

			// builder is ready
			init = true;

			if(!(this instanceof Builder)) {
				return new Builder();
			}

			this._constructor.apply(this, args);
		};

		// attach parent members
		Builder.prototype = parent;

		// attach all method members to the Builder
		for(var method in methods) {
			if(methods.hasOwnProperty(method)) {
				Builder.prototype[method] = methods[method];
			}
		}

		// when no '_constructor' found, init an empty constructor
		if(!Builder.prototype._constructor) {
			Builder.prototype._constructor = function() { };
		}

		return Builder;
	},

	//+ _async :: function -> undefined
	_async = function(fn) {
		// force fn to be async
		setTimeout(fn, 0);
	},

	_error = {
		// convenience object for throwing helpful errors

		'subUsage': function() {
			return 'USAGE [ topic:String, object:Object, toCall:String ]';
		},

		'pubUsage': function() {
			return 'UASGE [ topic:String[, data1:Any[, data2:Any[, ..]]] ]';
		},

		'unsubUsage': function() {
			return 'USAGE [topic:String, reference:Subscriber]';
		},

		'pubError': function(topic, error) {
			return 'Failed to publish to obj on topic "' +
				topic + '" [' + error.message + ']';
		},

		'extendUsage': function() {
			return 'argument to Bugle extend must be a literal object';
		},

		'pipeUsage': function() {
			return 'USAGE [ event:String, fn:Function ]';
		},

		'unknownPipeEvent': function(evnt) {
			return 'invalid pipe event [' + evnt + '], could not add to pipeline';
		}
	},

	//+ _compose :: array(function) -> function -> any
	_compose = function() {
		var fns = Array.prototype.slice.call(arguments);

		return arr => {
			return fns.reduce((arg, fn, index) => {
				return fn.call(this, arg, index, arr);
			}, arr);
		};
	},

	//+ _flatten :: array -> array
	// e.g. [[1,2,3,4,5], [4,5,6]] -> [1,2,3,4,5,4,5,6]
	_flatten = function(arr) {
		return arr.reduce((prev, curr) => {
			var isArr = _truthy(curr).array();
			return prev.concat(isArr? _flatten(curr) : curr);
		}, []);
	},

	//+ _map :: function,array -> array
	_map = function(fn, arr) {
		return arr.reduce((prev, curr) => {
			return prev.concat([fn.call(this, curr)]);
		}, []);
	},

	//+ _filter :: function,array -> array
	_filter = function(pred, arr) {
		return arr.reduce((prev, curr) => {
			return pred.call(this, curr)? prev.concat([curr]): prev;
		}, []);
	},

	//+ _flatMap :: function,array -> array
	_flatMap = function(fn, arr) {
		// map array over accumulator function,
		// flatten each message item but no join

		return _compose.call(
			this,
			_map.bind(null, fn),
			_map.bind(null, _flatten)
		)(arr);
	},

	//+ _done :: function,array -> unit
	_done = function(fn, arr) {
		fn.apply(this, [].concat(arr));
	},

	// pipe api module
	// functions are captured during pipe phase
	// apply collections over functions during digest phase
	_pipeEvents = {

		'map': function(fn) {
			return function(arr) {
				return _map.call(this, fn, arr);
			};
		},

		'filter': function(pred) {
			return function(arr) {
				return _filter.call(this, pred, arr);
			};
		},

		'flatMap': function(fn) {
			return function(arr) {
				return _flatMap.call(this, fn, arr);
			};
		},

		'flatten': function(arr) {
			return _flatten.call(this, arr);
		},

		'done': function(fn) {
			return function(arr) {
				_done.call(this, fn, arr);
			}
		}
	},

	//+ _dispatch :: (string, any, Subscriber) -> undefined
	_dispatch = function(topic, data, subscriber) {

		// apply current sub object and pub args to sub function
		_async(() => {
			try {
				subscriber.digest(data);
			} catch(e) {
				throw _error.pubError(topic, e);
			}
		});
	},

	//+ _publish :: string [, any[, ...]] -> undefined
	_publish = function(topic) {
		// notify all subscribers of a topic with a message(s)

		var self = this;

		if(_truthy(topic).string()) {

			var args = Array.prototype.slice.call(arguments, 1),
			channelItem = _dispatch.bind(null, topic, args);

			// publish args to each subscriber on topic
			if(self.topics[topic]) {
				var subscribers = self.topics[topic];
				subscribers.forEach(channelItem);
			}
		} else {
			throw _error.pubUsage();
		}
	},

	//+ _subscribe :: (string, function, object) -> Subscriber
	_subscribe = function(topic, scope) {
		// subscribe a function to a topic
		// with a given scope (defaults to current Bugle instance)

		scope = scope? scope : this;

		if(_truthy(topic).string()) {

			if(!this.topics[topic]) {
				this.topics[topic] = [];
			}

			var subscriber = new Subscriber(++this.oId, scope);
			this.topics[topic].push(subscriber);

			return subscriber;

		} else {
			throw _error.subUsage();
		}
	},

	//+ _unsubscribe :: string, Subscriber -> undefined
 	_unsubscribe = function(topic, subscriber) {
		// removes a subscriber object from the subscriptions list

		if(subscriber
		&& _truthy(subscriber.oId).number()
		&& _truthy(topic).string()
		) {

			var subscribers = this.topics[topic],
			oId = subscriber.oId,

			// probably wont stay...
			maybeRemove = function(subscriber, index) {
				if(subscriber.oId === oId) subscribers.splice(index, 1);
			};

			if(subscribers) {
				_async(() => {
					subscribers.forEach(maybeRemove);
				});
			}

		} else {
			throw _error.unsubUsage();
		}
	},

	// extends the current bugle instance prototype with properties
	_extend = function(methods) {

		if(_truthy(methods).obj()) {
			return _generate(methods, this);
		} else {
			throw _error.extendUsage();
		}
	},

	//+ pipe :: string,function -> Subscriber
	_pipe = function(evnt, fn) {

		if(_truthy(evnt).string() && _truthy(fn).fun()) {

			var maybeEvent = _pipeEvents[evnt];

			if(maybeEvent) {
				this._pipeline_.push(maybeEvent(fn));
			} else {
				throw _error.unknownPipeEvent(evnt);
			}

		} else {
			throw _error.pipeUsage();
		}

		return this;
	},

	//+ digest :: array -> undefined
	_digest = function(data) {
		// take published data,
		// reduce over pipelined hofs
		if(_truthy(this._pipeline_).array()) {
			_compose.apply(this.obj, this._pipeline_)(data);
		}
	};

	// holds the state of each new subscription on a topic
	function Subscriber(id, obj) {
		this.oId = id;
		this.obj = obj;

		// holds all fns to reduce over published data
		this._pipeline_ = [];
	}

	Subscriber.prototype = {
		'pipe': _pipe,
		'digest': _digest
	};

	// holds all user topics & reference to next unique subscriber id
	function Bugle() {

		//removes the need for 'new' keyword
		if(!(this instanceof Bugle)) {
			return new Bugle();
		}

		// holds topic namespaces along with its subscribers
		this.topics = [];

		// tracking id generated for each new subscription
		this.oId = 0;
	}

	Bugle.prototype = {

		'pub': _publish,

		'sub': _subscribe,

		'unsub': _unsubscribe,

		'extend': _extend
	};

	module['extend'] = function(methods) {
		return Bugle().extend(methods);
	}

} )(typeof module !== 'undefined' && module.exports? module.exports : window.Bugle = {});<|endoftext|>