<commit_before>var isSale = true
letterSpacings = {}

$(document).ready(function() {
  // hide contact us form
  if (!window.location.href.match(/localhost/)) {
    var interval = setInterval(function() {
      var contactUs = $('body').find('img[src*="icf.improvely.com"]')
      if (!contactUs.length) { return; }
      contactUs.hide()
      clearInterval(interval)
    }, 200)
  }

  // fix odd safari bug where the delegated click is not being recognized, but only for the bag
  setTimeout(function() {
    $('.js-click').on('click', function() {})
  }, 1000)

  // get template html and embed it in the page
  fetch((window.baseUrl || '') + '/assets/html/custombar.html').then(function(response) {
    return response.text()
  }).then(function(html) {
    html = html.replace(/assets\/img\//g, (window.baseUrl || '') + 'assets/img/')
    $('#custombar').parent().css({ position: 'relative' })
    $('#custombar').before(html).remove()
  })
})

fetch((window.baseUrl || '') + '/assets/js/letter-spacing.json').then(function(response) {
  response.json().then(function(json) {
    letterSpacings = json
  })
})
var state = {
  bag: {
    color: 'black',
    style: 'danny',
    height: 8.5,
    width: 12
  },
  letters: '',
  letterAspectHeight: 0.376,
  materials: ['white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white'],
  positions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  activeLetter: -1,
  editing: false,
  editingBag: true,
  step: "custom-bar",
  navActive: false,
  arrowStep: 1
}

var lastState = $.extend({}, state);

//
// EVENT HANDLING
//

// tap bag to modify
$(document).on('click', '.js-bag', function(evt) {
  setState({
    editing: true,
    editingBag: true,
  })

})

// input to change both letters
$(document).on('input', '.js-bag-input', function(evt) {
  if ($(this).val().match(/[^A-z]/)) { return $(this).val(state.letters) }

  var newState = { letters: $(this).val() }
  if (state.arrowStep == 2 && newState.letters.length == 2) {
    newState.arrowStep = 3
  }
  // reset active letter pointer if letters are deleted
  if ($(this).val().length < state.letters.length) {
    const letterIndexes = $(this).val().length - 1;
    newState.activeLetter = Math.min(letterIndexes, state.activeLetter);
  }

  setState(newState)
})
$(document).on('focus', '.js-bag-input', autoselect)
$(document).on('click', '.js-bag-input', autoselect)

// select material swatch for individual letter
$(document).on('click', '.js-swatch-link', function(evt) {
  var materials = state.materials.concat([])
  var color = $(this).data('color')
  if (state.editingBag || state.activeLetter == -1) {
    materials = materials.map(function(m) { return color })
  } else {
    materials[state.activeLetter] = $(this).data('color')
  }
  var newState = { materials: materials }
  if (state.arrowStep == 4) {
    newState.arrowStep = 0
  }
  setState(newState)
})

// select bag style
$(document).on('click', '.js-bag-style-link', function(evt) {
  setState({
    bag: { color: state.bag.color, style: $(this).data('style') }
  })

})

// select bag color
$(document).on('click', '.js-bag-color-link', function(evt) {
  var newState = {
    bag: { color: $(this).data('color'), style: state.bag.style }
  }
  if (state.arrowStep == 1) {
    newState.arrowStep = 2
  }
  setState(newState)
})

// show custom bar customization step

$(document).on('click', '.js-show-custom-bar', function(evt) {
  setState({
    step: "custom-bar"
  })

})

// show style selector step
$(document).on('click', '.js-back-to-bag-styles', function(evt) {
  setState({
    step: "style"
  })
})

// edit individual letter
$(document).on('click', '.js-letter', function(evt) {
  evt.stopPropagation()
  if ($(this).data('index') > -1) {
    setState({
      editing: true,
      editingBag: false,
      activeLetter: $(this).data('index'),
    })
  }
})

// select letter tab
$(document).on('click', '.js-tab-back', function(evt) {
  var tab = $(this).children('.js-tab')
  var newState = {}
  if (tab.data('index') > -1) {
    newState = {
      editing: true,
      editingBag: false,
      activeLetter: tab.data('index'),
    }
  } else {
    newState = {
      editing: false,
      editingBag: true,
      activeLetter: tab.data('index'),
    }
  }
  if (state.arrowStep == 3) {
    newState.arrowStep = 4
  }
  setState(newState)
})

function setState(newState) {
  lastState = $.extend({}, state)
  state = $.extend({}, state, newState)
  if (window.location.href.match(/localhost/)) {
    console.log('set', newState, 'state is now', state)
  }
  render()
}

function updateCustomInfo() {
  var productDescription = state.bag.style + "-" + state.bag.color
  if (state.letters.length > 0) {
    productDescription += [' / ', state.letters[0].toUpperCase(), '-', state.materials[0]].join('')
  }
  if (state.letters.length > 1) {
    productDescription += [' / ', state.letters[1].toUpperCase(), '-', state.materials[1]].join('')
  }
  $("#custombar-custom-info").val(productDescription);
}

function setImageLoaded(sender) {
  sender.setAttribute('data-loaded', true)
  resize()
}
//resize handler
function resize() {
  $("#customBarSectionMain").height($("#customBarSectionMain").parent().height() + "px")
  $("#customBarSectionMain").width($("#customBarSectionMain").parent().width() + "px")

  $(".js-swatch").css({ maxHeight: ($(".js-swatches").width() / (($(".js-swatch").length - 1)) / 2) + "px" })
  $(".js-tab-back:not(.js-tab-back-all)").width($(".js-tab-cnr").height())
  $(".js-tab-back-all").width($(".js-tab-cnr").height() * 2)
  $(".js-tab-back-all").css({ fontSize: ($(".js-tab-back-all").height() * 0.75) + "px" })
  $(".js-letter-label").height($("js-bag-input").height())
  $(".js-letters").height(($(".js-bag-custom").height() * state.letterAspectHeight) + "px")

  $(".fa.fa-arrow-right,.fa.fa-arrow-left").css({ fontSize: $(".js-letter-label").height() + "px" })
  $(".js-bag-color-link").each(function() {
    if ($(this).attr('data-loaded')) {
      $(this).parents('.js-bag-color-thumb').width($(this).width())
    }
  })
}

function imgLoadedResize(sender) {
  console.log(sender.children())
  switch (sender) {
    case 1:
      $(".js-bag-color-thumb").width()
      break;
    default:
      break;
  }
}
$(window).on('resize', resize)
var zoom = window.devicePixelRatio
setInterval(function() {
  if (window.devicePixelRatio != zoom) {
    resize();
    zoom = window.devicePixelRatio;
  }
}, 300)

function render() {

  if (state.step == "style") {
    // show style selector step
    $("#styleViewSection").css({ display: "block" })
    $("#customBarSectionMain").css({ display: "none" })
    $(".show-custom-bar").css({ display: "flex" })
    $(".back-to-bag-styles").css({ display: "none" })
    $(".check-my-custom-out").css({ display: "none" })
  }

  if (state.step == "custom-bar") {
    // reset
    $('.js-letters').find('.js-letter').remove()
    $('.js-tab-cnr').find('.js-tab:not([data-index=-1])').parents('.js-tab-back').remove()
    $('.js-tab').html('')
    $('.js-preview').html('')
    $('.js-tab').removeClass('active')
    $('.js-tab-back').removeClass('active')
    $('.js-swatch').removeClass('active')
    $('.js-loading').hide()
    $(".fa.fa-arrow-right, .fa.fa-arrow-left").css({ display: "none" })
      // show custom-bar step
    $("#styleViewSection").css({ display: "none" })
    $("#customBarSectionMain").css({ display: "block" })
    if (state.navActive == true) {
      $(".show-custom-bar").css({ display: "none" })
      $(".back-to-bag-styles").css({ display: "flex" })
      $(".check-my-custom-out").css({ display: "flex" })
    }

    //sets step arrows
    switch (state.arrowStep) {
      case 1:
        $(".js-bag-color>.fa.fa-arrow-right, .js-bag-color>.fa.fa-arrow-left").css({ display: "flex" })
        break;
      case 2:
        $(".js-letter-label>.fa.fa-arrow-right, .js-letter-label>.fa.fa-arrow-left").css({ display: "flex" })
        break;
      case 3:
        $(".js-tab-cnr>.fa.fa-arrow-right, .js-tab-cnr>.fa.fa-arrow-left").css({ display: "flex" })
        break;
      case 4:
        $(".js-swatches>.fa.fa-arrow-right, .js-swatches>.fa.fa-arrow-left").css({ display: "flex" })
        break;

      default:
        break;
    }
    // render bag color
    $('.js-bag-custom').css({ backgroundImage: "url(" + (window.baseUrl || '') + "assets/img/bags/" + state.bag.style + "-" + state.bag.color + ".png)" })

    // render letters in bag and preview and adds tabs

    state.letters.split('').forEach(function(l, i) {
      var letter = Letter({ letter: l, material: state.materials[i], index: i })
      var tab = Tab({ letter: l, material: state.materials[i], index: i })
      $('.js-loading').show()
      $('.js-letters').append(letter)
      const tabSelector = ['.js-tab[data-index=', i - 1, ']'].join('')
      $(tabSelector).parents('.js-tab-back').after(tab)

      letter[0].onload = function() {
        letter.css({ marginLeft: letter.width() * letterSpacings[l.toUpperCase()]["left"] + "px", marginRight: letter.width() * letterSpacings[l.toUpperCase()]["right"] + "px" })
        $('.js-loading').hide()
        if (state.activeLetter === i) {
          $('.js-preview').append(letter.clone())
        }
      }
    })

    // render tabs
    $('.js-tab-all').html('ALL')

    // select input if we're showing a new input
    if (state.editing !== lastState.editing || (state.activeLetter !== lastState.activeLetter && state.activeLetter === state.letters.length)) {
      $('.js-input').select()
    }

    // render active tab
    const activeTabSelector = ['.js-tab[data-index=', state.activeLetter, ']'].join('')
    $(activeTabSelector).addClass('active').parents('.js-tab-back').addClass('active')

    // render active swatch
    if (state.activeLetter > -1) {
      const activeSwatchSelector = ['.js-swatch[data-color=', state.materials[state.activeLetter], ']'].join('')
      $(activeSwatchSelector).addClass('active')
    } else {
      const activeSwatchSelector = ['.js-swatch[data-color=', state.materials[state.activeLetter + 1], ']'].join('')
      $(activeSwatchSelector).addClass('active')
    }

    // set value of inputs
    $('.js-bag-input').val(state.letters)
    $('.js-input').val(state.letters[state.activeLetter])
  }
  // update shopify hidden input
  updateCustomInfo()
  resize()
}

function autoselect() {
  $(this).select()
}

function Letter(props) {
  var alt = [props.letter, ' in ', props.material].join('')
  var src = [window.baseUrl || '', 'assets/img/letters/', props.letter.toUpperCase(), '-', props.material, '.png'].join('')
  var html = [''].join('')
  return $(html)
}

function Tab(props) {
  var alt = [props.letter, ' in ', props.material].join('')
  var src = [window.baseUrl || '', 'assets/img/letters/', props.letter.toUpperCase(), '-', props.material, '.png'].join('')
  var html = [
    '
',
    '',
    '
',
  ].join('')

  return $(html)
}<commit_msg>changed flow of arrows<commit_after>var isSale = true
var tutorial = true
letterSpacings = {}

$(document).ready(function() {

  // shows arrows for steps
  if (tutorial) {
    $(".fa.fa-arrow-right, .fa.fa-arrow-left").css({ display: "flex" })
  }
  // hide contact us form
  if (!window.location.href.match(/localhost/)) {
    var interval = setInterval(function() {
      var contactUs = $('body').find('img[src*="icf.improvely.com"]')
      if (!contactUs.length) { return; }
      contactUs.hide()
      clearInterval(interval)
    }, 200)
  }

  // fix odd safari bug where the delegated click is not being recognized, but only for the bag
  setTimeout(function() {
    $('.js-click').on('click', function() {})
  }, 1000)

  // get template html and embed it in the page
  fetch((window.baseUrl || '') + '/assets/html/custombar.html').then(function(response) {
    return response.text()
  }).then(function(html) {
    html = html.replace(/assets\/img\//g, (window.baseUrl || '') + 'assets/img/')
    $('#custombar').parent().css({ position: 'relative' })
    $('#custombar').before(html).remove()
  })
})

fetch((window.baseUrl || '') + '/assets/js/letter-spacing.json').then(function(response) {
  response.json().then(function(json) {
    letterSpacings = json
  })
})
var state = {
  bag: {
    color: 'black',
    style: 'danny',
    height: 8.5,
    width: 12
  },
  letters: '',
  letterAspectHeight: 0.376,
  materials: ['white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white'],
  positions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  activeLetter: -1,
  editing: false,
  editingBag: true,
  step: "custom-bar",
  navActive: false,
  arrow: {
    step1: false,
    step2: false,
    step3: false,
    step4: false
  }
}

var lastState = $.extend({}, state);

//
// EVENT HANDLING
//

// tap bag to modify
$(document).on('click', '.js-bag', function(evt) {
  setState({
    editing: true,
    editingBag: true,
  })

})

// input to change both letters
$(document).on('input', '.js-bag-input', function(evt) {
  if ($(this).val().match(/[^A-z]/)) { return $(this).val(state.letters) }
  var newState = {
    letters: $(this).val(),
    arrow: { step1: state.arrow.step1, step2: state.arrow.step2, step3: state.arrow.step3, step4: state.arrow.step4 }
  }
  console.log(newState.arrow)
  if (state.arrow.step2 == false) {
    newState.arrow.step2 = true
  }
  // reset active letter pointer if letters are deleted
  if ($(this).val().length < state.letters.length) {
    const letterIndexes = $(this).val().length - 1;
    newState.activeLetter = Math.min(letterIndexes, state.activeLetter);
  }

  setState(newState)
})
$(document).on('focus', '.js-bag-input', autoselect)
$(document).on('click', '.js-bag-input', autoselect)

// select material swatch for individual letter
$(document).on('click', '.js-swatch-link', function(evt) {
  var materials = state.materials.concat([])
  var color = $(this).data('color')
  if (state.editingBag || state.activeLetter == -1) {
    materials = materials.map(function(m) { return color })
  } else {
    materials[state.activeLetter] = $(this).data('color')
  }
  var newState = {
    materials: materials,
    arrow: { step1: state.arrow.step1, step2: state.arrow.step2, step3: state.arrow.step3, step4: state.arrow.step4 }
  }
  if (state.arrow.step4 == false) {
    newState.arrow.step4 = true
  }
  setState(newState)
})

// select bag style
$(document).on('click', '.js-bag-style-link', function(evt) {
  setState({
    bag: { color: state.bag.color, style: $(this).data('style') }
  })

})

// select bag color
$(document).on('click', '.js-bag-color-link', function(evt) {
  var newState = {
    bag: { color: $(this).data('color'), style: state.bag.style },
    arrow: { step1: state.arrow.step1, step2: state.arrow.step2, step3: state.arrow.step3, step4: state.arrow.step4 }
  }
  if (state.arrow.step1 == false) {
    newState.arrow.step1 = true

  }
  setState(newState)
})

// show custom bar customization step

$(document).on('click', '.js-show-custom-bar', function(evt) {
  setState({
    step: "custom-bar"
  })

})

// show style selector step
$(document).on('click', '.js-back-to-bag-styles', function(evt) {
  setState({
    step: "style"
  })
})

// edit individual letter
$(document).on('click', '.js-letter', function(evt) {
  evt.stopPropagation()
  if ($(this).data('index') > -1) {
    setState({
      editing: true,
      editingBag: false,
      activeLetter: $(this).data('index'),
    })
  }
})

// select letter tab
$(document).on('click', '.js-tab-back', function(evt) {
  var tab = $(this).children('.js-tab')
  var newState = {}
  if (tab.data('index') > -1) {
    newState = {
      editing: true,
      editingBag: false,
      activeLetter: tab.data('index'),
      arrow: { step1: state.arrow.step1, step2: state.arrow.step2, step3: state.arrow.step3, step4: state.arrow.step4 },

    }
  } else {
    newState = {
      editing: false,
      editingBag: true,
      activeLetter: tab.data('index'),
      arrow: { step1: state.arrow.step1, step2: state.arrow.step2, step3: state.arrow.step3, step4: state.arrow.step4 },

    }
  }
  if (state.arrow.step3 == false) {
    newState.arrow.step3 = true
  }
  setState(newState)
})

function setState(newState) {
  lastState = $.extend({}, state)
  state = $.extend({}, state, newState)
  if (window.location.href.match(/localhost/)) {
    console.log('set', newState, 'state is now', state)
  }
  render()
}

function updateCustomInfo() {
  var productDescription = state.bag.style + "-" + state.bag.color
  if (state.letters.length > 0) {
    productDescription += [' / ', state.letters[0].toUpperCase(), '-', state.materials[0]].join('')
  }
  if (state.letters.length > 1) {
    productDescription += [' / ', state.letters[1].toUpperCase(), '-', state.materials[1]].join('')
  }
  $("#custombar-custom-info").val(productDescription);
}

function setImageLoaded(sender) {
  sender.setAttribute('data-loaded', true)
  resize()
}
//resize handler
function resize() {
  $("#customBarSectionMain").height($("#customBarSectionMain").parent().height() + "px")
  $("#customBarSectionMain").width($("#customBarSectionMain").parent().width() + "px")

  $(".js-swatch").css({ maxHeight: ($(".js-swatches").width() / (($(".js-swatch").length - 1)) / 2) + "px" })
  $(".js-tab-back:not(.js-tab-back-all)").width($(".js-tab-cnr").height())
  $(".js-tab-back-all").width($(".js-tab-cnr").height() * 2)
  $(".js-tab-back-all").css({ fontSize: ($(".js-tab-back-all").height() * 0.75) + "px" })
  $(".js-letter-label").height($("js-bag-input").height())
  $(".js-letters").height(($(".js-bag-custom").height() * state.letterAspectHeight) + "px")

  $(".fa.fa-arrow-right,.fa.fa-arrow-left").css({ fontSize: $(".js-letter-label").height() + "px" })
  $(".js-bag-color-link").each(function() {
    if ($(this).attr('data-loaded')) {
      $(this).parents('.js-bag-color-thumb').width($(this).width())
    }
  })
}

function imgLoadedResize(sender) {
  console.log(sender.children())
  switch (sender) {
    case 1:
      $(".js-bag-color-thumb").width()
      break;
    default:
      break;
  }
}
$(window).on('resize', resize)
var zoom = window.devicePixelRatio
setInterval(function() {
  if (window.devicePixelRatio != zoom) {
    resize();
    zoom = window.devicePixelRatio;
  }
}, 300)

function render() {

  if (state.step == "style") {
    // show style selector step
    $("#styleViewSection").css({ display: "block" })
    $("#customBarSectionMain").css({ display: "none" })
    $(".show-custom-bar").css({ display: "flex" })
    $(".back-to-bag-styles").css({ display: "none" })
    $(".check-my-custom-out").css({ display: "none" })
  }

  if (state.step == "custom-bar") {
    // reset
    $('.js-letters').find('.js-letter').remove()
    $('.js-tab-cnr').find('.js-tab:not([data-index=-1])').parents('.js-tab-back').remove()
    $('.js-tab').html('')
    $('.js-preview').html('')
    $('.js-tab').removeClass('active')
    $('.js-tab-back').removeClass('active')
    $('.js-swatch').removeClass('active')
    $('.js-loading').hide()

    // show custom-bar step
    $("#styleViewSection").css({ display: "none" })
    $("#customBarSectionMain").css({ display: "block" })
    if (state.navActive == true) {
      $(".show-custom-bar").css({ display: "none" })
      $(".back-to-bag-styles").css({ display: "flex" })
      $(".check-my-custom-out").css({ display: "flex" })
    }

    //sets step arrows
    if (state.arrow.step1) $(".js-bag-color>.fa.fa-arrow-right, .js-bag-color>.fa.fa-arrow-left").css({ display: "none" })
    if (state.arrow.step2) $(".js-letter-label>.fa.fa-arrow-right, .js-letter-label>.fa.fa-arrow-left").css({ display: "none" })
    if (state.arrow.step3) $(".js-tab-cnr>.fa.fa-arrow-right, .js-tab-cnr>.fa.fa-arrow-left").css({ display: "none" })
    if (state.arrow.step4) $(".js-swatches>.fa.fa-arrow-right, .js-swatches>.fa.fa-arrow-left").css({ display: "none" })

    // render bag color
    $('.js-bag-custom').css({ backgroundImage: "url(" + (window.baseUrl || '') + "assets/img/bags/" + state.bag.style + "-" + state.bag.color + ".png)" })

    // render letters in bag and preview and adds tabs
    state.letters.split('').forEach(function(l, i) {
      var letter = Letter({ letter: l, material: state.materials[i], index: i })
      var tab = Tab({ letter: l, material: state.materials[i], index: i })
      $('.js-loading').show()
      $('.js-letters').append(letter)
      const tabSelector = ['.js-tab[data-index=', i - 1, ']'].join('')
      $(tabSelector).parents('.js-tab-back').after(tab)

      letter[0].onload = function() {
        letter.css({ marginLeft: letter.width() * letterSpacings[l.toUpperCase()]["left"] + "px", marginRight: letter.width() * letterSpacings[l.toUpperCase()]["right"] + "px" })
        $('.js-loading').hide()
        if (state.activeLetter === i) {
          $('.js-preview').append(letter.clone())
        }
      }
    })

    // render tabs
    $('.js-tab-all').html('ALL')

    // select input if we're showing a new input
    if (state.editing !== lastState.editing || (state.activeLetter !== lastState.activeLetter && state.activeLetter === state.letters.length)) {
      $('.js-input').select()
    }

    // render active tab
    const activeTabSelector = ['.js-tab[data-index=', state.activeLetter, ']'].join('')
    $(activeTabSelector).addClass('active').parents('.js-tab-back').addClass('active')

    // render active swatch
    if (state.activeLetter > -1) {
      const activeSwatchSelector = ['.js-swatch[data-color=', state.materials[state.activeLetter], ']'].join('')
      $(activeSwatchSelector).addClass('active')
    } else {
      const activeSwatchSelector = ['.js-swatch[data-color=', state.materials[state.activeLetter + 1], ']'].join('')
      $(activeSwatchSelector).addClass('active')
    }

    // set value of inputs
    $('.js-bag-input').val(state.letters)
    $('.js-input').val(state.letters[state.activeLetter])
  }
  // update shopify hidden input
  updateCustomInfo()
  resize()
}

function autoselect() {
  $(this).select()
}

function Letter(props) {
  var alt = [props.letter, ' in ', props.material].join('')
  var src = [window.baseUrl || '', 'assets/img/letters/', props.letter.toUpperCase(), '-', props.material, '.png'].join('')
  var html = [''].join('')
  return $(html)
}

function Tab(props) {
  var alt = [props.letter, ' in ', props.material].join('')
  var src = [window.baseUrl || '', 'assets/img/letters/', props.letter.toUpperCase(), '-', props.material, '.png'].join('')
  var html = [
    '
',
    '',
    '
',
  ].join('')

  return $(html)
}<|endoftext|>


<commit_before>'use strict';

const router = require('express').Router();
const Seller = require('../models/Seller');
const bodyParser = require('body-parser');
const Promise = require('bluebird');
const _ = require('lodash');
const fs = require('fs');

router.use(bodyParser.urlencoded({extended: true}));
// router.use(bodyParser.json());

router.get('/', (req, res) => {
  fs.createReadStream('pages/map.html').pipe(res);
});

router.get('/sellers', (req, res) => {
  Seller.find().lean().exec()
    .then(data => {
      res.json(data);
    });
});

router.get('/sellers/:id', (req, res) => {
  Seller.find({_id: req.params.id}).lean().exec()
    .then(data => {
      res.json(data ? data[0] : []);
    });
});

router.delete('/sellers/:id', (req, res) => {
  Seller.findByIdAndRemove(req.params.id).exec()
    .then(data => {
      res.json({success: true});
    })
    .catch(err => res.json({success: false, error: err}));
});

router.post('/sellers', (req, res) => {
  new Seller({
    info: {
      Name: req.body.name,
    },
    coords: [req.body.latitude, req.body.longitude]
  }).save()
    .then(() => {
      return res.json({success: true});
    })
    .catch(err => {
      return res.json({success: false, error: err});
    });
});

router.post('/sellers/bulk', (req, res) => {
  Promise.all(
    _(req.body.bulk.split(/\r?\n/))
      .filter(s => s.trim().length > 0)
      .chunk(3)
      .map(c => {
        if(c.length < 3) return Promise.resolve();
        console.log('c:', c);
        return new Seller({
          info: {Name: c[0]},
          coords: [c[1], c[2]]
        }).save();
      }))
    .then(() => {
      return res.json({success: true});
    })
    .catch(err => {
      return res.json({success: false, error: err});
    });
});

router.post('/sellers/addInventory', (req, res) => {
  console.log('Finding seller with ID:', req.body.sellerId);
  Seller.findById(req.body.sellerId)
    .then(item => {
      if(!item.inventory) item.inventory = [];
      item.inventory.push({name: req.body.itemName, quantity: req.body.itemQuantity, unit: req.body.itemUnit});
      return item.save();
    }).then(() => {
      return res.json({success: true});
    });
});

module.exports = router;
<commit_msg>set homepage to hackathon.html<commit_after>'use strict';

const router = require('express').Router();
const Seller = require('../models/Seller');
const bodyParser = require('body-parser');
const Promise = require('bluebird');
const _ = require('lodash');
const fs = require('fs');

router.use(bodyParser.urlencoded({extended: true}));
// router.use(bodyParser.json());

router.get('/', (req, res) => {
  fs.createReadStream('pages/hackathon.html').pipe(res);
});

router.get('/sellers', (req, res) => {
  Seller.find().lean().exec()
    .then(data => {
      res.json(data);
    });
});

router.get('/sellers/:id', (req, res) => {
  Seller.find({_id: req.params.id}).lean().exec()
    .then(data => {
      res.json(data ? data[0] : []);
    });
});

router.delete('/sellers/:id', (req, res) => {
  Seller.findByIdAndRemove(req.params.id).exec()
    .then(data => {
      res.json({success: true});
    })
    .catch(err => res.json({success: false, error: err}));
});

router.post('/sellers', (req, res) => {
  new Seller({
    info: {
      Name: req.body.name,
    },
    coords: [req.body.latitude, req.body.longitude]
  }).save()
    .then(() => {
      return res.json({success: true});
    })
    .catch(err => {
      return res.json({success: false, error: err});
    });
});

router.post('/sellers/bulk', (req, res) => {
  Promise.all(
    _(req.body.bulk.split(/\r?\n/))
      .filter(s => s.trim().length > 0)
      .chunk(3)
      .map(c => {
        if(c.length < 3) return Promise.resolve();
        console.log('c:', c);
        return new Seller({
          info: {Name: c[0]},
          coords: [c[1], c[2]]
        }).save();
      }))
    .then(() => {
      return res.json({success: true});
    })
    .catch(err => {
      return res.json({success: false, error: err});
    });
});

router.post('/sellers/addInventory', (req, res) => {
  console.log('Finding seller with ID:', req.body.sellerId);
  Seller.findById(req.body.sellerId)
    .then(item => {
      if(!item.inventory) item.inventory = [];
      item.inventory.push({name: req.body.itemName, quantity: req.body.itemQuantity, unit: req.body.itemUnit});
      return item.save();
    }).then(() => {
      return res.json({success: true});
    });
});

module.exports = router;
<|endoftext|>


<commit_before>/* global navigator, storage, ajax */

/* jshint ignore: start */
import .storage as storage;
import util.ajax as ajax;
/* jshint ignore: end */

exports = (function () {
  'use strict';

  var err_url, uid,
    storage_id = 'game_errors',
    obj = {},
    device_info = {},
    onSend = function (err) {
      if (!err) {
        storage.del(storage_id);
      }
    },
    sendToServer = function () {
      var errors = storage.get(storage_id) || [];

      if (errors.length === 0 || !navigator.onLine) {
        return;
      }

      ajax.post({
        url: err_url,
        data: {
          user: uid,
          device: device_info,
          errors: errors
        }
      }, onSend)
    },
    onError = function (message, url, line, col) {
      storage.push(storage_id, {
        timestamp: Date.now(),
        message: message,
        url: url,
        line: line,
        col: col
      });

      sendToServer();
    };

  obj.register = function (data) {
    err_url = data.url;
    device_info = data.device_info || {};
    uid = data.uid || 'unknown';

    window.onerror = onError;
  };

  obj.setDeviceInfo = function (info) {
    device_info = info;
  };

  obj.setUID = function (usr_id) {
    uid = usr_id;
  };

  // For logging error explicitly
  obj.error = function (err) {
    var data, length;

    if (err instanceof Error) {
      data = err.stack.split('\n')[1];
      data = data.substring(data.lastIndexOf('(') + 1,
        data.lastIndexOf(')')).split(':');
      length = data.length;

      onError(err.toString(), data[length - 3],
        data[length - 2], data[length - 1]);
    }
  };

  return obj;
})();
<commit_msg>added support for ignoring specific errors and added error count prperty for error objects<commit_after>/* global navigator, storage, ajax, _ */

/* jshint ignore: start */
import .storage as storage;
import util.ajax as ajax;
import util.underscore as _;
/* jshint ignore: end */

exports = (function () {
  'use strict';

  var err_url, uid,
    storage_id = 'game_errors',
    obj = {},
    device_info = {},
    ignore_errors = [],
    onSend = function (err) {
      if (!err) {
        storage.del(storage_id);
      }
    },
    sendToServer = function () {
      var errors = storage.get(storage_id) || [];

      if (errors.length === 0 || !navigator.onLine) {
        return;
      }

      ajax.post({
        url: err_url,
        data: {
          user: uid,
          device: device_info,
          errors: errors
        }
      }, onSend)
    },
    onError = function (message, url, line, col) {
      var errors = storage.get(storage_id),
        curr_time = Date.now(),
        err;

      if (_.contains(ignore_errors, message)) {
        return;
      }

      err = _.find(errors, function (curr) {
        return curr.message === message && curr.url === url &&
          curr.line === line;
      });

      if (err) {
        ++err.count;
        err.last_occured = curr_time;
        storage.set(storage_id, errors);
      } else {
        storage.push(storage_id, {
          timestamp: curr_time,
          message: message,
          url: url,
          line: line,
          col: col,
          count: 1
        });
      }

      sendToServer();
    };

  obj.register = function (data) {
    err_url = data.url;
    device_info = data.device_info || {};
    uid = data.uid || 'unknown';
    ignore_errors = data.ignore_errors || [];

    window.onerror = onError;
  };

  obj.setDeviceInfo = function (info) {
    device_info = info;
  };

  obj.setUID = function (usr_id) {
    uid = usr_id;
  };

  // For logging error explicitly
  obj.error = function (err) {
    var data, length;

    if (err instanceof Error) {
      data = err.stack.split('\n')[1];
      data = data.substring(data.lastIndexOf('(') + 1,
        data.lastIndexOf(')')).split(':');
      length = data.length;

      onError(err.toString(), data[length - 3],
        data[length - 2], data[length - 1]);
    }
  };

  return obj;
})();
<|endoftext|>


<commit_before>/*
 * prangler
 * https://github.com/sulmanen/prangler
 *
 * Copyright (c) 2013 Samuli Ulmanen
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('prangler', 'Collect html templates and views to $templateCache.', function() {
    var str = require('string');
    var templatePaths = [], targets = [], globs = [];
    var configTemplate = "angular.module('<%= ngApp %>').run(['$templateCache', function($templateCache) {<%= loadScripts %>}]);";
    var putTemplate = "$templateCache.put('<%= key %>', '<%= template %>');\n";

    grunt.config.requires('prangler');
    grunt.config.requires('prangler.options.ngApp');
    grunt.config.requires('prangler.files');

    grunt.log.subhead('Collect templates for ngApp ' + grunt.config('prangler.options.ngApp') + '\n');

    var filesConfig = grunt.config('prangler.files');

    for (var key in filesConfig) {
      targets.push(key);
      globs.push(filesConfig[key]);
    }

    templatePaths = grunt.file.expand(globs[0]);

    var loadScripts = '';
    for (var path in templatePaths) {
        var temp = {
          key: templatePaths[path].replace(grunt.config('prangler.options.stripPathForTemplateId'),'').replace('\\', '/'),
          template: str(grunt.file.read(templatePaths[path])).collapseWhitespace().replace(/([^'\\]*(?:\\.[^'\\]*)*)'/g, "$1\\'")
        };
      grunt.log.writeln(temp.key);
      loadScripts = loadScripts + grunt.template.process(putTemplate, temp);
    }

    grunt.file.write(targets[0], grunt.template.process(configTemplate, {
      ngApp: grunt.config('prangler.options.ngApp'),
      loadScripts: loadScripts
    }));

    grunt.log.ok(targets[0] + ' has ' + templatePaths.length + ' templates.');
  });
};<commit_msg>DEVEL: upgrade to grunt 0.4<commit_after>/*
 * prangler
 * https://github.com/sulmanen/prangler
 *
 * Copyright (c) 2013 Samuli Ulmanen
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  grunt.registerTask('prangler', 'Collect html templates and views to $templateCache.', function() {
    var templatePaths = [], targets = [], globs = [];
    var configTemplate = "angular.module('<%= ngApp %>').run(['$templateCache', function($templateCache) {<%= loadScripts %>}]);";
    var putTemplate = "$templateCache.put('<%= key %>', '<%= template %>');\n";
    var str = require('string');

    grunt.config.requires('prangler');
    grunt.config.requires('prangler.options.ngApp');
    grunt.config.requires('prangler.files');

    grunt.log.subhead('Collect templates for ngApp ' + grunt.config('prangler.options.ngApp') + '\n');

    var filesConfig = grunt.config('prangler.files');

    for (var key in filesConfig) {
      targets.push(key);
      globs.push(filesConfig[key]);
    }

    templatePaths = grunt.file.expand(globs[0]);

    var loadScripts = '';
    for (var path in templatePaths) {
        var temp = {
          key: templatePaths[path].replace(grunt.config('prangler.options.stripPathForTemplateId'),'').replace('\\', '/'),
          template: str(grunt.file.read(templatePaths[path])).collapseWhitespace().replace(/([^'\\]*(?:\\.[^'\\]*)*)'/g, "$1\\'")
        };
      grunt.log.writeln(temp.key);
      loadScripts = loadScripts + grunt.template.process(putTemplate, {data: temp});
    }

    grunt.file.write(targets[0], grunt.template.process(configTemplate, {data: {
      ngApp: grunt.config('prangler.options.ngApp'),
      loadScripts: loadScripts
    }}));

    grunt.log.ok(targets[0] + ' has ' + templatePaths.length + ' templates.');
  });
};<|endoftext|>


<commit_before>$(document).ready(function() {

  var $panel = $('#panel');
  var $categories = {
    app: $('#apps'),
    service: $('#services'),
    payment: $('#payments'),
  };

  function status(data) {
    data.checks = data.checks.map(function(check) {
      check.class = check.status === 'up' ? 'operational' : 'major outage' : 'planned maintenance' ;
      check.text = check.status === 'up' ? 'operational' : 'disruptions';
      check.category = check.tags.reduce(function(cat, tag) {
        switch (tag.name) {
          case 'payment':
            return 'payment';
          case 'service':
            return 'service';
          default:
            return cat;
        }
      }, 'app');

      // check time since last outage
      if (check.status === 'up' && Date.now() - (check.lasterrortime * 1000) <= 86400000) {
        check.class = 'degraded performance';
        check.text = 'degraded performance';
      }

      return check;
    });

    var status = data.checks.reduce(function(status, check) {
      return check.status !== 'up' ? 'major outage' : status;
    }, 'operational');

    if (!$panel.data('incident')) {
      $panel.attr('class', 'panel ' + status);
      $panel.html(status === 'operational' ? 'Alle systemer er operative.' : 'Ett eller flere systemer ute av drift');
    }

    data.checks.forEach(function(item) {
      var $here = $categories[item.category];

      var name = item.name;
      var clas = item.class;
      var text = item.text;

      $here.append('
' + name + ' ' + text + '
') });
  };

  $.getJSON('https://api.github.com/repos/matfleaydaly/newstatuslive/issues?state=open').done(message);

  var $incidents = $('#incidents');

  function message(issues) {
    issues.forEach(function(issue) {
      var status_text = {
        operational: 'Operational',
        investigating: 'Investigating',
        'major outage': 'Major Outage',
        'planned maintenance': 'Planned Maintenance',
        'degraded performance': 'Degraded Performance',
      };

      var status = issue.labels.reduce(function(status, label) {
        if (/^status:/.test(label.name)) {
          return label.name.replace('status:', '');
        } else {
          return status;
        }
      }, 'operational');

      var systems = issue.labels.filter(function(label) {
        return /^system:/.test(label.name);
      }).map(function(label) {
        return label.name.replace('system:', '')
      });

      if (issue.state == 'open') {
        $panel.data('incident', 'true');
        $panel.attr('class', 'panel ' + status);
        $panel.html('' + issue.title + '');
      }

      var html = '
\n';
      html += '' + datetime(issue.created_at) + '\n';

      // status
      if (issue.state == 'closed') {
        html += 'løst';
      } else {
        html += '';
          html += status_text[status];
        html += '\n';
      }

      // systems
      for (var i = 0; i < systems.length; i++) {
        html += '' + systems[i] + '';
      }

      html += '
\n';
      html += '' + issue.title + '\n';
      html += '
' + issue.body + '
\n';

      if (issue.state == 'closed') {
        html += '
Oppdatert ' + datetime(issue.closed_at) + '
';
        html += 'Systemet er tilbake i normal drift.
';
      }

      html += '
';

      $incidents.append(html);
    });

    function datetime(string) {
      var datetime = string.split('T');

      var date = datetime[0];
      var time = datetime[1].replace('Z', '');

      return date + ' ' + time;
    };
  };
});
<commit_msg>Update script.js<commit_after>$(document).ready(function() {

  var $panel = $('#panel');
  var $categories = {
    app: $('#apps'),
    service: $('#services'),
    payment: $('#payments'),
  };

  function status(data) {
    data.checks = data.checks.map(function(check) {
      check.class = check.status === 'up' ? 'operational' : 'major outage' ;
      check.text = check.status === 'up' ? 'operational' : 'disruptions';
      check.category = check.tags.reduce(function(cat, tag) {
        switch (tag.name) {
          case 'payment':
            return 'payment';
          case 'service':
            return 'service';
          default:
            return cat;
        }
      }, 'app');

      // check time since last outage
      if (check.status === 'up' && Date.now() - (check.lasterrortime * 1000) <= 86400000) {
        check.class = 'degraded performance';
        check.text = 'degraded performance';
      }

      return check;
    });

    var status = data.checks.reduce(function(status, check) {
      return check.status !== 'up' ? 'major outage' : status;
    }, 'operational');

    if (!$panel.data('incident')) {
      $panel.attr('class', 'panel ' + status);
      $panel.html(status === 'operational' ? 'Alle systemer er operative.' : 'Ett eller flere systemer ute av drift');
    }

    data.checks.forEach(function(item) {
      var $here = $categories[item.category];

      var name = item.name;
      var clas = item.class;
      var text = item.text;

      $here.append('
' + name + ' ' + text + '
') });
  };

  $.getJSON('https://api.github.com/repos/matfleaydaly/newstatuslive/issues?state=open').done(message);

  var $incidents = $('#incidents');

  function message(issues) {
    issues.forEach(function(issue) {
      var status_text = {
        operational: 'Operational',
        investigating: 'Investigating',
        'major outage': 'Major Outage',
        'planned maintenance': 'Planned Maintenance',
        'degraded performance': 'Degraded Performance',
      };

      var status = issue.labels.reduce(function(status, label) {
        if (/^status:/.test(label.name)) {
          return label.name.replace('status:', '');
        } else {
          return status;
        }
      }, 'operational');

      var systems = issue.labels.filter(function(label) {
        return /^system:/.test(label.name);
      }).map(function(label) {
        return label.name.replace('system:', '')
      });

      if (issue.state == 'open') {
        $panel.data('incident', 'true');
        $panel.attr('class', 'panel ' + status);
        $panel.html('' + issue.title + '');
      }

      var html = '
\n';
      html += '' + datetime(issue.created_at) + '\n';

      // status
      if (issue.state == 'closed') {
        html += 'løst';
      } else {
        html += '';
          html += status_text[status];
        html += '\n';
      }

      // systems
      for (var i = 0; i < systems.length; i++) {
        html += '' + systems[i] + '';
      }

      html += '
\n';
      html += '' + issue.title + '\n';
      html += '
' + issue.body + '
\n';

      if (issue.state == 'closed') {
        html += '
Oppdatert ' + datetime(issue.closed_at) + '
';
        html += 'Systemet er tilbake i normal drift.
';
      }

      html += '
';

      $incidents.append(html);
    });

    function datetime(string) {
      var datetime = string.split('T');

      var date = datetime[0];
      var time = datetime[1].replace('Z', '');

      return date + ' ' + time;
    };
  };
});
<|endoftext|>


<commit_before>pc.extend(pc.fw, function () {
    /**
     * @name pc.fw.Entity
     * @class The Entity is the core primitive of a PlayCanvas game. Each one contains a globally unique identifier (GUID) to distinguish
     * it from other Entities, and associates it with tool-time data on the server.
     * An object in your game consists of an {@link pc.fw.Entity}, and a set of {@link pc.fw.Component}s which are
     * managed by a {@link pc.fw.ComponentSystem}.
     * The Entity uniquely identifies the object and also provides a transform for position and orientation
     * an inherits from {@pc.scene.GraphNode} so can be added into the scene graph.
     * The Component and ComponentSystem provide provide the logic to give an Entity a specific type of behaviour. e.g. the ability to
     * render a model or play a sound. Components are specific to a instance of an Entity and are attached (e.g. `this.entity.model`)
     * ComponentSystems allow access to all Entities and Components and are attached to the {@link pc.fw.ApplicationContext}
     *
     * Every object created in the PlayCanvas Designer is an Entity.
     *
     * @example
     * var entity = new pc.fw.Entity();
     * var context = ... // Get the pc.fw.ApplicationContext
     *
     * // Add a Component to the Entity
     * context.systems.camera.addComponent(entity, {
     *   fov: 45,
     *   nearClip: 1,
     *   farClip: 10000
     * });
     *
     * // Add the Entity into the scene graph
     * context.root.addChild(entity);
     *
     * @extends pc.scene.GraphNode
     */
    var Entity = function(){
        this._guid = pc.guid.create(); // Globally Unique Identifier
        this._batchHandle = null; // The handle for a RequestBatch, set this if you want to Component's to load their resources using a pre-existing RequestBatch.
        this.c = {}; // Component storage

        pc.extend(this, pc.events);
    };
    Entity = pc.inherits(Entity, pc.scene.GraphNode);

    /**
     * @function
     * @name pc.fw.Entity#getGuid
     * @description Get the GUID value for this Entity
     */
    Entity.prototype.getGuid = function () {
        return this._guid;
    };

    /**
     * @function
     * @name pc.fw.Entity#setGuid
     * @description Set the GUID value for this Entity. N.B. It is unlikely that you should need to change the GUID value of an Entity at run-time.
     * Doing so will corrupt the graph this Entity is in.
     * @param {Object} guid
     */
    Entity.prototype.setGuid = function (guid) {
        this._guid = guid;
    };

    /**
     * @function
     * @name pc.fw.Entity#setRequestBatch
     * @description Used during resource loading to ensure that child resources of Entities are tracked
     * @param {Number} handle The handle of the RequestBatch used to load this Entity
     */
    Entity.prototype.setRequestBatch = function (handle) {
        this._batchHandle = handle;
    };

    /**
     * @function
     * @name pc.fw.Entity#getRequestBatch
     * @description Get the RequestBatch handle that is being used to load this Entity
     * @returns {Number} The RequestBatch handle
     */
    Entity.prototype.getRequestBatch = function () {
        return this._batchHandle;
    };

    Entity.prototype.addChild = function (child) {
        if(child instanceof pc.fw.Entity) {
            var _debug = true
            if(_debug) {
                var root = this.getRoot();
                var dupe = root.findOne("getGuid", child.getGuid());
                if(dupe) {
                    throw new Error("GUID already exists in graph");
                }
            }
        }

        pc.scene.GraphNode.prototype.addChild.call(this, child);
    };

    /**
     * @function
     * @name pc.fw.Entity#findByGuid
     * @description Find a descendant of this Entity with the GUID
     * @returns {pc.fw.Entity}
     */
    Entity.prototype.findByGuid = function (guid) {
        if (this._guid === guid) return this;

        for (var i = 0; i < this._children.length; i++) {
            if(this._children[i].findByGuid) {
                var found = this._children[i].findByGuid(guid);
                if (found !== null) return found;
            }
        }
        return null;
    };

    /**
     * @function
     * @name pc.fw.Entity#reparent
     * @description Remove Entity from current parent and add as child to new parent
     * @param {pc.scene.GraphNode} parent New parent to attach Entity to
     */
    Entity.prototype.reparent = function(parent) {
        var current = this.getParent();
        if(current) {
            current.removeChild(this);
        }
        if(parent) {
            parent.addChild(this);
        }
    };

    /**
    * @function
    * @name pc.fw.Entity#destroy
    * @description Remove all components from the Entity and detach it from the Entity hierarchy. Then recursively destroy all ancestor Entities
    */
    Entity.prototype.destroy = function () {
        var parent = this.getParent();
        var childGuids;

        // Remove all components
        for (name in this.c) {
            this.c[name].system.removeComponent(this);
        }

        // Detach from parent
        if(parent) {
            parent.removeChild(this);
        }

        var children = this.getChildren();
        var length = children.length;
        var child;
        while(child = children.shift()) {
            if(child instanceof pc.fw.Entity) {
                child.destroy();
            }
        }
    };

    /**
    * @function
    * @name pc.fw.Entity#clone
    * @description Create a deep copy of the Entity. Duplicate the full Entity hierarchy, with all Components and all descendants.
    * Note, this Entity is not in the hierarchy and must be added manually.
    * @returns A new Entity which is a deep copy of the original.
    * @example
    *   var e = this.entity.clone(); // Clone Entity
    *   this.entity.getParent().addChild(e); // Add it as a sibling to the original
    */
    Entity.prototype.clone = function () {
        var type;
        var c = new pc.fw.Entity();
        pc.fw.Entity._super._cloneInternal.call(this, c);

        for (type in this.c) {
            var component = this.c[type];
            component.system.cloneComponent(this, c);
        }

        var i;
        for (i = 0; i < this.getChildren().length; i++) {
            var child = this.getChildren()[i];
            if (child instanceof pc.fw.Entity) {
                c.addChild(child.clone());
            }
        }

        return c;
    };

    Entity.deserialize = function (data) {
        var template = pc.json.parse(data.template);
        var parent = pc.json.parse(data.parent);
        var children = pc.json.parse(data.children);
        var transform = pc.json.parse(data.transform);
        var components = pc.json.parse(data.components);
        var labels = pc.json.parse(data.labels);

        var model = {
            _id: data._id,
            resource_id: data.resource_id,
            _rev: data._rev,
            name: data.name,
            labels: labels,
            template: template,
            parent: parent,
            children: children,
            transform: transform,
            components: components
        };

        return model;
    };

    Entity.serialize = function (model) {
        var data = {
            _id: model._id,
            resource_id: model.resource_id,
            name: model.name,
            labels: pc.json.stringify(model.labels),
            template: pc.json.stringify(model.template),
            parent: pc.json.stringify(model.parent),
            children: pc.json.stringify(model.children),
            transform: pc.json.stringify(model.transform),
            components: pc.json.stringify(model.components)
        };

        if(model._rev) {
            data._rev = model._rev
        }

        return data;
    };

    return {
        Entity: Entity
    }

}());
<commit_msg>Tidied up some Entity docs<commit_after>pc.extend(pc.fw, function () {
    /**
     * @name pc.fw.Entity
     * @class The Entity is the core primitive of a PlayCanvas game. Each one contains a globally unique identifier (GUID) to distinguish
     * it from other Entities, and associates it with tool-time data on the server.
     * An object in your game consists of an {@link pc.fw.Entity}, and a set of {@link pc.fw.Component}s which are
     * managed by their respective {@link pc.fw.ComponentSystem}s.
     * The Entity uniquely identifies the object and also provides a transform for position and orientation
     * which it inherits from {@link pc.scene.GraphNode} so can be added into the scene graph.
     * The Component and ComponentSystem provide the logic to give an Entity a specific type of behaviour. e.g. the ability to
     * render a model or play a sound. Components are specific to a instance of an Entity and are attached (e.g. `this.entity.model`)
     * ComponentSystems allow access to all Entities and Components and are attached to the {@link pc.fw.ApplicationContext}.
     *
     * Every object created in the PlayCanvas Designer is an Entity.
     *
     * @example
     * var entity = new pc.fw.Entity();
     * var context = ... // Get the pc.fw.ApplicationContext
     *
     * // Add a Component to the Entity
     * context.systems.camera.addComponent(entity, {
     *   fov: 45,
     *   nearClip: 1,
     *   farClip: 10000
     * });
     *
     * // Add the Entity into the scene graph
     * context.root.addChild(entity);
     *
     * @extends pc.scene.GraphNode
     */
    var Entity = function(){
        this._guid = pc.guid.create(); // Globally Unique Identifier
        this._batchHandle = null; // The handle for a RequestBatch, set this if you want to Component's to load their resources using a pre-existing RequestBatch.
        this.c = {}; // Component storage

        pc.extend(this, pc.events);
    };
    Entity = pc.inherits(Entity, pc.scene.GraphNode);

    /**
     * @function
     * @name pc.fw.Entity#getGuid
     * @description Get the GUID value for this Entity
     * @returns {String} The GUID of the Entity
     */
    Entity.prototype.getGuid = function () {
        return this._guid;
    };

    /**
     * @function
     * @name pc.fw.Entity#setGuid
     * @description Set the GUID value for this Entity.
     *
     * N.B. It is unlikely that you should need to change the GUID value of an Entity at run-time. Doing so will corrupt the graph this Entity is in.
     * @param {String} guid The GUID to assign to the Entity
     */
    Entity.prototype.setGuid = function (guid) {
        this._guid = guid;
    };

    /**
     * @private
     * @function
     * @name pc.fw.Entity#setRequestBatch
     * @description Used during resource loading to ensure that child resources of Entities are tracked
     * @param {Number} handle The handle of the RequestBatch used to load this Entity
     */
    Entity.prototype.setRequestBatch = function (handle) {
        this._batchHandle = handle;
    };

    /**
     * @private
     * @function
     * @name pc.fw.Entity#getRequestBatch
     * @description Get the RequestBatch handle that is being used to load this Entity
     * @returns {Number} The RequestBatch handle
     */
    Entity.prototype.getRequestBatch = function () {
        return this._batchHandle;
    };

    Entity.prototype.addChild = function (child) {
        if(child instanceof pc.fw.Entity) {
            var _debug = true
            if(_debug) {
                var root = this.getRoot();
                var dupe = root.findOne("getGuid", child.getGuid());
                if(dupe) {
                    throw new Error("GUID already exists in graph");
                }
            }
        }

        pc.scene.GraphNode.prototype.addChild.call(this, child);
    };

    /**
     * @function
     * @name pc.fw.Entity#findByGuid
     * @description Find a descendant of this Entity with the GUID
     * @returns {pc.fw.Entity} The Entity with the GUID or null
     */
    Entity.prototype.findByGuid = function (guid) {
        if (this._guid === guid) return this;

        for (var i = 0; i < this._children.length; i++) {
            if(this._children[i].findByGuid) {
                var found = this._children[i].findByGuid(guid);
                if (found !== null) return found;
            }
        }
        return null;
    };

    /**
     * @function
     * @name pc.fw.Entity#reparent
     * @description Remove Entity from current parent and add as child to new parent
     * @param {pc.scene.GraphNode} parent New parent to attach Entity to
     */
    Entity.prototype.reparent = function(parent) {
        var current = this.getParent();
        if(current) {
            current.removeChild(this);
        }
        if(parent) {
            parent.addChild(this);
        }
    };

    /**
    * @function
    * @name pc.fw.Entity#destroy
    * @description Remove all components from the Entity and detach it from the Entity hierarchy. Then recursively destroy all ancestor Entities
    */
    Entity.prototype.destroy = function () {
        var parent = this.getParent();
        var childGuids;

        // Remove all components
        for (name in this.c) {
            this.c[name].system.removeComponent(this);
        }

        // Detach from parent
        if(parent) {
            parent.removeChild(this);
        }

        var children = this.getChildren();
        var length = children.length;
        var child;
        while(child = children.shift()) {
            if(child instanceof pc.fw.Entity) {
                child.destroy();
            }
        }
    };

    /**
    * @function
    * @name pc.fw.Entity#clone
    * @description Create a deep copy of the Entity. Duplicate the full Entity hierarchy, with all Components and all descendants.
    * Note, this Entity is not in the hierarchy and must be added manually.
    * @returns {pc.fw.Entity} A new Entity which is a deep copy of the original.
    * @example
    *   var e = this.entity.clone(); // Clone Entity
    *   this.entity.getParent().addChild(e); // Add it as a sibling to the original
    */
    Entity.prototype.clone = function () {
        var type;
        var c = new pc.fw.Entity();
        pc.fw.Entity._super._cloneInternal.call(this, c);

        for (type in this.c) {
            var component = this.c[type];
            component.system.cloneComponent(this, c);
        }

        var i;
        for (i = 0; i < this.getChildren().length; i++) {
            var child = this.getChildren()[i];
            if (child instanceof pc.fw.Entity) {
                c.addChild(child.clone());
            }
        }

        return c;
    };

    Entity.deserialize = function (data) {
        var template = pc.json.parse(data.template);
        var parent = pc.json.parse(data.parent);
        var children = pc.json.parse(data.children);
        var transform = pc.json.parse(data.transform);
        var components = pc.json.parse(data.components);
        var labels = pc.json.parse(data.labels);

        var model = {
            _id: data._id,
            resource_id: data.resource_id,
            _rev: data._rev,
            name: data.name,
            labels: labels,
            template: template,
            parent: parent,
            children: children,
            transform: transform,
            components: components
        };

        return model;
    };

    Entity.serialize = function (model) {
        var data = {
            _id: model._id,
            resource_id: model.resource_id,
            name: model.name,
            labels: pc.json.stringify(model.labels),
            template: pc.json.stringify(model.template),
            parent: pc.json.stringify(model.parent),
            children: pc.json.stringify(model.children),
            transform: pc.json.stringify(model.transform),
            components: pc.json.stringify(model.components)
        };

        if(model._rev) {
            data._rev = model._rev
        }

        return data;
    };

    return {
        Entity: Entity
    }

}());
<|endoftext|>


<commit_before>/*
 * grunt-prettify
 * https://github.com/jonschlinkert/grunt-prettify
 *
 * Copyright (c) 2013 Jon Schlinkert
 * Licensed under the MIT license.
 */
'use strict';

// node_modules
var format = require('js-beautify').html;
var _str   = require('underscore.string');
var _      = require('lodash');
var async  = require('async');

module.exports = function(grunt) {

  grunt.task.registerMultiTask('prettify', 'Prettify HTML.', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      // Custom options
      indent: 2, // alias for indent_size
      condense: true,
      padcomments: false,
      preserveBOM: false,

      // js-beautify options
      indent_char: " ",
      indent_inner_html: true,
      indent_scripts: "keep",
      brace_style: "expand",
      preserve_newline: false,
      max_preserve_newline: 0,
      wrap_line_length: 0
    });

    options.indent_size = options.indent;

    // Extend default options with options from specified .jsbeautifyrc file
    if (options.config) {
      options = grunt.util._.extend(options, grunt.file.readJSON(options.config));
    }

    async.forEach(this.files, function(fp, cb) {

      var files = grunt.file.expand({nonull: true}, fp.src);

      // Concat specified files.
      var src = files.map(function(filepath) {
        // Warn if a source file/pattern was invalid.
        if (!grunt.file.exists(filepath)) {
          grunt.log.error('Source file "' + filepath + '" not found.');
          return '';
        }
        // Read file source.
        return grunt.file.read(filepath);
      }).join(options.separator);

      // Prettify HTML.
      var output = prettifyHTML(src, options);

      // Reduce multiple newlines to a single newline
      output = (options.condense === true) ? condense(output) : output;

      // Use at your own risk. This option will slow down the build.
      // What does "ocd" mean? Just look at the function, then lookup
      // ocd on wikipedia.
      output = (options.ocd === true) ? ocd(output) : output;

      // Add a single newline above code comments.
      if(options.padcomments === true) {
        output = padcomments(output, 1);
      }
      if(options.padcomments !== false && _.isNumber(options.padcomments)) {
        output = padcomments(output, options.padcomments);
      }

      // Preserve byte-order marks. Set to "false" by default.
      output = (options.preserveBOM === true) ? stripBOM(output) : output;

      if (output.length < 1) {
        grunt.log.warn('Destination not written because dest file was empty.');
      } else {
        // Write the destination file.
        grunt.file.write(fp.dest, output);
        // Print a success message.
        grunt.log.ok('File "' + fp.dest + '" prettified.');
      }
      cb();
    });
  });

  var stripBOM = function(content) {
    if (content.charCodeAt(0) === 0xFEFF) {
      content = content.slice(1);
    }
    return content;
  };

  // Normalize and condense all newlines
  var condense = function(str) {
    return str.replace(/(\r\n|\n\r|\n|\r){2,}/g, '\n');
  };

  // fix multiline, Bootstrap-style comments
  var padcomments = function(str, num) {
    var nl = _str.repeat('\n', (num || 1));
    return str.replace(/(\s*)(


<commit_before>/*!
 *  EspressoGraph - v1.0.0
 *  Copyright (c) 2014, Andy Barron
 *  www.andybarron.net
 *
 *  EspressoGraph is released under the MIT License.
 *  http://opensource.org/licenses/MIT
 */

(function(){
  'use strict';
  var root = this;
  var namespace = 'EspressoGraph';

  // helpers

  var arrayContains = function(a,o) {
    return a.indexOf(o) !== -1;
  };

  var exists = function(o) {
    return (o !== null) && (typeof o !== 'undefined');
  };

  var getDefault = function(a,b) {
    return exists(a) ? a : b;
  };

  var updateObject = function(oldObj, newObj) {
    for (var prop in newObj) {
      if (newObj.hasOwnProperty(prop)) {
        oldObj[prop] = newObj[prop]
      }
    }
  };

  var reconstructPath = function(cameFrom, current) {
    if (current in cameFrom) {
      var path = reconstructPath(cameFrom, cameFrom[current]); path.push(current);
      return path;
    } else {
      return [current];
    }
  };

  var zero = function() { return 0; };

  // graph class
  var Graph = function(directed) {
    this._directed = getDefault(directed, false);
    this._nodes = [];
    this._edges = [];
  };

  Graph.prototype = {

    get nodes() {
      return this._nodes.slice();
    },

    get directed() {
      return this._directed;
    },

    containsNode: function(node) {
      return arrayContains(this._nodes, node);
    },

    addNode: function(node) {
      if (!exists(node))
        throw new Error("Graph.addNode: Null/undefined nodes not allowed");
      if (!this.containsNode(node)) {
        this._nodes.push(node);
        this._edges.push({});
        return true;
      } else {
        return false;
      }
    },

    removeNode: function(node) {
      var idx = this._nodes.indexOf(node);
      if (idx === -1) return false;
      // first, remove this node from internal containers
      this._nodes.splice(idx,1);
      this._edges.splice(idx,1);
      // then, remove references to this node from edges
      for (var i in this._edges) {
        if (idx in this._edges[i]) {
          delete this._edges[i][idx];
        }
      }
      // finally, fix new indices
      for (var idxNew = idx; idxNew < this._nodes.length; idxNew++) {
        var idxOld = idxNew + 1;
        for (var k = 0; k < this._nodes.length; k++) {
          var edgeList = this._edges[k];
          if (idxOld in edgeList) {
            edgeList[idxNew] = edgeList[idxOld];
            delete edgeList[idxOld];
          }
        }
      }
      return true;
    },

    addNodeArray: function(array) {
      var ret = [];
      var graph = this;
      array.forEach(function(node, i){
        ret[i] = graph.addNode(node);
      });
      return ret;
    },

    addNodes: function() {
      var argArray = Array.prototype.slice.call(arguments);
      return this.addNodeArray(argArray);
    },

    containsEdge: function(a, b) {
      return exists(this.getEdge(a, b));
    },

    addEdge: function(a, b, data) {
      var idxA = this._nodes.indexOf(a);
      var idxB = this._nodes.indexOf(b);
      if (idxA === -1 || idxB === -1 || this.containsEdge(a, b) || idxA === idxB) {
        return false;
      }
      this._edges[idxA][idxB] = getDefault(data, {});
      return true;
    },

    getEdge: function(a, b) {
      var idxA = this._nodes.indexOf(a);
      var idxB = this._nodes.indexOf(b);
      if (idxB in this._edges[idxA]) {
        return this._edges[idxA][idxB];
      } else if (!this._directed && idxA in this._edges[idxB]) {
        return this._edges[idxB][idxA];
      } else {
        return null;
      }
    },

    getEdges: function(node) {
      var idx = this._nodes.indexOf(node);
      if (idx === -1) return null;
      var edges = [];
      var graph = this;
      this._nodes.forEach(function(neighbor, i){
        if (i in graph._edges[idx]) {
          edges.push(graph._edges[idx][i]);
        } else if (!graph._directed && idx in graph._edges[i]) {
          edges.push(graph._edges[i][idx]);
        }
      });
      return edges;
    },

    removeEdge: function(a, b) {
      var idxA = this._nodes.indexOf(a);
      var idxB = this._nodes.indexOf(b);
      if (idxA === -1 || idxB === -1) return false;
      if (idxB in this._edges[idxA]) {
        delete this._edges[idxA][idxB];
        return true;
      } else if (!this._directed && idxA in this._edges[idxB]) {
        delete this._edges[idxB][idxA];
        return true;
      } else {
        return false;
      }
    },

    _getNeighborsIndex: function(idx) {
      if (idx === -1) return null;
      var neighbors = [];
      var graph = this;
      this._nodes.forEach(function(neighbor, i){
        if ( i in graph._edges[idx] || (!graph._directed && idx in graph._edges[i]) ) {
          neighbors.push(i);
        }
      });
      return neighbors;
    },

    getNeighbors: function(node) {
      var idx = this._nodes.indexOf(node);
      if (idx === -1) return null;
      var neighbors = [];
      var graph = this;
      this._nodes.forEach(function(neighbor, i){
        if ( i in graph._edges[idx] || (!graph._directed && idx in graph._edges[i]) ) {
          neighbors.push(neighbor);
        }
      });
      return neighbors;
    },

    searchAStar: function(begin, end, heuristicFunction, costFunction) {
      // set up, abort if nodes not in graph
      var start = this._nodes.indexOf(begin);
      var goal = this._nodes.indexOf(end);
      if (start === -1 || goal === -1) return null;
      var f = getDefault(costFunction, this.getEdge).bind(this);
      var h = heuristicFunction.bind(this);
      // begin algorithm
      // adapted from Wikipedia pseudocode :-)
      var closedSet = {};
      var openSet = {}; openSet[start] = true;
      var cameFrom = {};
      var gScore = {}; gScore[start] = 0;
      var fScore = {}; fScore[start] = gScore[start] + h(start, goal);
      while (Object.keys(openSet).length != 0) {
        var current = Object.keys(openSet).sort(function(a, b) {return fScore[a] - fScore[b];})[0];
        if (current == goal) {
          var path = reconstructPath(cameFrom, current);
          // var nodePath = [];
          // var _nodes = this._nodes;
          // path.forEach(function(idx){nodePath.push(_nodes[idx])});
          // return nodePath
          var _nodes = this._nodes;
          var fullPath = [begin];
          for (var i = 1; i < path.length; i++) {
            var prevNode = _nodes[path[i-1]];
            var nextNode = _nodes[path[i]];
            fullPath.push(this.getEdge(prevNode, nextNode));
            fullPath.push(nextNode);
          }
          var nodePath = fullPath.filter(function(v, i){ return i%2 == 0; });
          var edgePath = fullPath.filter(function(v, i){ return i%2 != 0; });
          return {
            path: fullPath,
            nodes: nodePath,
            edges: edgePath,
          };
        }
        delete openSet[current];
        closedSet[current] = true;
        var neighbors = this._getNeighborsIndex(current);
        for (var i = 0; i < neighbors.length; i++) {
          var neighbor = neighbors[i];
          if (neighbor in closedSet) continue;
          var gScoreTentative = gScore[current] + f(this._nodes[current], this._nodes[neighbor]);
          if ( !(neighbor in openSet) || gScoreTentative < gScore[neighbor] ) {
            cameFrom[neighbor] = current;
            gScore[neighbor] = gScoreTentative;
            fScore[neighbor] = gScore[neighbor] + h(this._nodes[neighbor], this._nodes[goal]);
            if ( !(neighbor in openSet) ) openSet[neighbor] = true;
          }
        }
      }
      return null;
    },

    searchDijkstra: function(begin, end, costFunction) {
      return this.searchAStar(begin, end, zero, costFunction);
    },

  };

  var mod = {
    Graph: Graph,
  };

  var useCommon = (typeof require === 'function') &&
    (typeof module === 'function') &&
    (typeof exports === 'function');
  var useRequire = !useCommon && (typeof require === "function");

  if (useCommon) {
    updateObject(exports, mod);
  } else if (useRequire) {
    define(mod);
  } else {
    root[namespace] = mod;
  }
}).call(this);<commit_msg>Updates license header, fixes CommonJS compatibility<commit_after>/*!
 *  EspressoGraph - v1.0.1
 *  github.com/AndyBarron/EspressoGraph
 *  Copyright (c) 2014, Andy Barron
 *  www.andybarron.net
 *
 *  EspressoGraph is released under the MIT License.
 *  http://opensource.org/licenses/MIT
 */

(function(){
  'use strict';
  var root = this;
  var namespace = 'EspressoGraph';

  // helpers

  var arrayContains = function(a,o) {
    return a.indexOf(o) !== -1;
  };

  var exists = function(o) {
    return (o !== null) && (typeof o !== 'undefined');
  };

  var getDefault = function(a,b) {
    return exists(a) ? a : b;
  };

  var updateObject = function(oldObj, newObj) {
    for (var prop in newObj) {
      if (newObj.hasOwnProperty(prop)) {
        oldObj[prop] = newObj[prop]
      }
    }
  };

  var reconstructPath = function(cameFrom, current) {
    if (current in cameFrom) {
      var path = reconstructPath(cameFrom, cameFrom[current]); path.push(current);
      return path;
    } else {
      return [current];
    }
  };

  var zero = function() { return 0; };

  // graph class
  var Graph = function(directed) {
    this._directed = getDefault(directed, false);
    this._nodes = [];
    this._edges = [];
  };

  Graph.prototype = {

    get nodes() {
      return this._nodes.slice();
    },

    get directed() {
      return this._directed;
    },

    containsNode: function(node) {
      return arrayContains(this._nodes, node);
    },

    addNode: function(node) {
      if (!exists(node))
        throw new Error("Graph.addNode: Null/undefined nodes not allowed");
      if (!this.containsNode(node)) {
        this._nodes.push(node);
        this._edges.push({});
        return true;
      } else {
        return false;
      }
    },

    removeNode: function(node) {
      var idx = this._nodes.indexOf(node);
      if (idx === -1) return false;
      // first, remove this node from internal containers
      this._nodes.splice(idx,1);
      this._edges.splice(idx,1);
      // then, remove references to this node from edges
      for (var i in this._edges) {
        if (idx in this._edges[i]) {
          delete this._edges[i][idx];
        }
      }
      // finally, fix new indices
      for (var idxNew = idx; idxNew < this._nodes.length; idxNew++) {
        var idxOld = idxNew + 1;
        for (var k = 0; k < this._nodes.length; k++) {
          var edgeList = this._edges[k];
          if (idxOld in edgeList) {
            edgeList[idxNew] = edgeList[idxOld];
            delete edgeList[idxOld];
          }
        }
      }
      return true;
    },

    addNodeArray: function(array) {
      var ret = [];
      var graph = this;
      array.forEach(function(node, i){
        ret[i] = graph.addNode(node);
      });
      return ret;
    },

    addNodes: function() {
      var argArray = Array.prototype.slice.call(arguments);
      return this.addNodeArray(argArray);
    },

    containsEdge: function(a, b) {
      return exists(this.getEdge(a, b));
    },

    addEdge: function(a, b, data) {
      var idxA = this._nodes.indexOf(a);
      var idxB = this._nodes.indexOf(b);
      if (idxA === -1 || idxB === -1 || this.containsEdge(a, b) || idxA === idxB) {
        return false;
      }
      this._edges[idxA][idxB] = getDefault(data, {});
      return true;
    },

    getEdge: function(a, b) {
      var idxA = this._nodes.indexOf(a);
      var idxB = this._nodes.indexOf(b);
      if (idxB in this._edges[idxA]) {
        return this._edges[idxA][idxB];
      } else if (!this._directed && idxA in this._edges[idxB]) {
        return this._edges[idxB][idxA];
      } else {
        return null;
      }
    },

    getEdges: function(node) {
      var idx = this._nodes.indexOf(node);
      if (idx === -1) return null;
      var edges = [];
      var graph = this;
      this._nodes.forEach(function(neighbor, i){
        if (i in graph._edges[idx]) {
          edges.push(graph._edges[idx][i]);
        } else if (!graph._directed && idx in graph._edges[i]) {
          edges.push(graph._edges[i][idx]);
        }
      });
      return edges;
    },

    removeEdge: function(a, b) {
      var idxA = this._nodes.indexOf(a);
      var idxB = this._nodes.indexOf(b);
      if (idxA === -1 || idxB === -1) return false;
      if (idxB in this._edges[idxA]) {
        delete this._edges[idxA][idxB];
        return true;
      } else if (!this._directed && idxA in this._edges[idxB]) {
        delete this._edges[idxB][idxA];
        return true;
      } else {
        return false;
      }
    },

    _getNeighborsIndex: function(idx) {
      if (idx === -1) return null;
      var neighbors = [];
      var graph = this;
      this._nodes.forEach(function(neighbor, i){
        if ( i in graph._edges[idx] || (!graph._directed && idx in graph._edges[i]) ) {
          neighbors.push(i);
        }
      });
      return neighbors;
    },

    getNeighbors: function(node) {
      var idx = this._nodes.indexOf(node);
      if (idx === -1) return null;
      var neighbors = [];
      var graph = this;
      this._nodes.forEach(function(neighbor, i){
        if ( i in graph._edges[idx] || (!graph._directed && idx in graph._edges[i]) ) {
          neighbors.push(neighbor);
        }
      });
      return neighbors;
    },

    searchAStar: function(begin, end, heuristicFunction, costFunction) {
      // set up, abort if nodes not in graph
      var start = this._nodes.indexOf(begin);
      var goal = this._nodes.indexOf(end);
      if (start === -1 || goal === -1) return null;
      var f = getDefault(costFunction, this.getEdge).bind(this);
      var h = heuristicFunction.bind(this);
      // begin algorithm
      // adapted from Wikipedia pseudocode :-)
      var closedSet = {};
      var openSet = {}; openSet[start] = true;
      var cameFrom = {};
      var gScore = {}; gScore[start] = 0;
      var fScore = {}; fScore[start] = gScore[start] + h(start, goal);
      while (Object.keys(openSet).length != 0) {
        var current = Object.keys(openSet).sort(function(a, b) {return fScore[a] - fScore[b];})[0];
        if (current == goal) {
          var path = reconstructPath(cameFrom, current);
          // var nodePath = [];
          // var _nodes = this._nodes;
          // path.forEach(function(idx){nodePath.push(_nodes[idx])});
          // return nodePath
          var _nodes = this._nodes;
          var fullPath = [begin];
          for (var i = 1; i < path.length; i++) {
            var prevNode = _nodes[path[i-1]];
            var nextNode = _nodes[path[i]];
            fullPath.push(this.getEdge(prevNode, nextNode));
            fullPath.push(nextNode);
          }
          var nodePath = fullPath.filter(function(v, i){ return i%2 == 0; });
          var edgePath = fullPath.filter(function(v, i){ return i%2 != 0; });
          return {
            path: fullPath,
            nodes: nodePath,
            edges: edgePath,
          };
        }
        delete openSet[current];
        closedSet[current] = true;
        var neighbors = this._getNeighborsIndex(current);
        for (var i = 0; i < neighbors.length; i++) {
          var neighbor = neighbors[i];
          if (neighbor in closedSet) continue;
          var gScoreTentative = gScore[current] + f(this._nodes[current], this._nodes[neighbor]);
          if ( !(neighbor in openSet) || gScoreTentative < gScore[neighbor] ) {
            cameFrom[neighbor] = current;
            gScore[neighbor] = gScoreTentative;
            fScore[neighbor] = gScore[neighbor] + h(this._nodes[neighbor], this._nodes[goal]);
            if ( !(neighbor in openSet) ) openSet[neighbor] = true;
          }
        }
      }
      return null;
    },

    searchDijkstra: function(begin, end, costFunction) {
      return this.searchAStar(begin, end, zero, costFunction);
    },

  };

  var mod = {
    Graph: Graph,
  };

  var useCommon = (typeof require === 'function') &&
    (typeof module === 'object') &&
    (typeof exports === 'object');
  var useRequire = !useCommon &&
    (typeof require === 'function') &&
    (typeof define === 'function');

  if (useCommon) {
    updateObject(exports, mod);
  } else if (useRequire) {
    define(mod);
  } else {
    root[namespace] = mod;
  }
}).call(this);<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
var path = require('path');
var fs = require('fs');
var paramaters = [];
var parameterVersion = false;
var packageDefinitionPath = path.join(process.cwd(), 'package.json');
var buildConfigPath = path.join(process.cwd(), 'build-helper-config.json');
var userPackage = require(packageDefinitionPath);
var Helper = require('../lib');
var config = {};
try {
    fs.accessSync(buildConfigPath, fs.F_OK);
    config = require(buildConfigPath);
} catch (e) {
    // It isn't accessible
}

var options = {
  push: config.push || false,
  keep: config.keep || false,
  update: config.update || false,
  createChangelog: config.createChangelog || true,
  changelogFolder: config.changelogFolder || './changelogs',
  commitURL: config.commitURL,
  userPackage: packageDefinitionPath,
  packageSpaces: config.packageSpaces || 2,
  preConditionCommands: config.preConditionCommands || []
};

function extend(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

function showHelp() {
    console.log();
    console.log('build-helper');
    console.log();
    console.log('create a new release, update the version and build number and do the git stuff');
    console.log('build-helper 0.0.5');
    console.log('build-helper major|minor|patch');
    console.log();
    console.log('Usage: build-helper');
    console.log();
    console.log('  options');
    console.log('   -h/--help     show this help');
    console.log('   -p/--push     push new release to origin');
    console.log('   -k/--keep     keep branch after performing finish');
    // console.log('   -u/--update   ');
    console.log();
}

if (process.argv.length > 2) {
  var end = false;
  paramaters = process.argv.splice(2);
  paramaters.forEach(function(parameter) {
    switch (parameter) {
      case '-h':
      case '--help':
        showHelp();
        end = true;
        break;
      case '-p':
      case '--push':
        options.push = true;
        paramaters.shift();
        break;
      case '-k':
      case '--keep':
        options.keep = true;
        paramaters.shift();
        break;
      case '-u':
      case '--update':
        options.update = true;
        paramaters.shift();
        break;
    }
  });
  if (end) {
    process.exit(0);
  }
} else {
  showHelp();
  process.exit(1);
}

if (options.update) {
  parameterVersion = currentPackage.version;
  console.log('verison taken from package.json: ' + parameterVersion);
} else {
  parameterVersion = paramaters[0];
}

if (typeof parameterVersion === 'undefined') {
  showHelp();
  process.exit(1);
}

var helper = new Helper(extend({}, options, {
    currentVersion: userPackage.version,
    parameterVersion: parameterVersion
}));

<commit_msg>add composer support<commit_after>#!/usr/bin/env node

var path = require('path');
var fs = require('fs');
var paramaters = [];
var parameterVersion = false;
var packageDefinitionPathNpm = path.join(process.cwd(), 'package.json');
var packageDefinitionPathComposer = path.join(process.cwd(), 'composer.json');
var buildConfigPath = path.join(process.cwd(), 'build-helper-config.json');
var Helper = require('../lib');
var chalk = require('chalk');

function isFileReadable(file, callback) {
    try {
        fs.accessSync(file, fs.F_OK);
        callback(null);
    } catch(e) {
        if(!Object.getOwnPropertyNames(file).length) {
            callback('file not found');
        }
    }
}

var config = isFileReadable(buildConfigPath) ? require(buildConfigPath) : {};
var userPackage = isFileReadable(packageDefinitionPathNpm) ? require(packageDefinitionPathNpm) : {};
var packageDefinitionPath = userPackage;
if(!Object.getOwnPropertyNames(userPackage).length) {
    userPackage = isFileReadable(packageDefinitionPathComposer) ? require(packageDefinitionPathComposer) : {};
    var packageDefinitionPath = packageDefinitionPathComposer;
}

if(!Object.getOwnPropertyNames(userPackage).length) {
    console.log(chalk.red('no project file (package.json, composer.json)'))
    process.exit(1);
}

var options = {
  push: config.push || false,
  keep: config.keep || false,
  update: config.update || false,
  createChangelog: config.createChangelog || true,
  changelogFolder: config.changelogFolder || './changelogs',
  commitURL: config.commitURL,
  userPackage: packageDefinitionPath,
  packageSpaces: config.packageSpaces || 2,
  preConditionCommands: config.preConditionCommands || []
};

function extend(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

function showHelp() {
    console.log();
    console.log('build-helper');
    console.log();
    console.log('create a new release, update the version and build number and do the git stuff');
    console.log('build-helper 0.0.5');
    console.log('build-helper major|minor|patch');
    console.log();
    console.log('Usage: build-helper');
    console.log();
    console.log('  options');
    console.log('   -h/--help     show this help');
    console.log('   -p/--push     push new release to origin');
    console.log('   -k/--keep     keep branch after performing finish');
    // console.log('   -u/--update   ');
    console.log();
}

if (process.argv.length > 2) {
  var end = false;
  paramaters = process.argv.splice(2);
  paramaters.forEach(function(parameter) {
    switch (parameter) {
      case '-h':
      case '--help':
        showHelp();
        end = true;
        break;
      case '-p':
      case '--push':
        options.push = true;
        paramaters.shift();
        break;
      case '-k':
      case '--keep':
        options.keep = true;
        paramaters.shift();
        break;
      case '-u':
      case '--update':
        options.update = true;
        paramaters.shift();
        break;
    }
  });
  if (end) {
    process.exit(0);
  }
} else {
  showHelp();
  process.exit(1);
}

if (options.update) {
  parameterVersion = currentPackage.version;
  console.log('verison taken from package.json: ' + parameterVersion);
} else {
  parameterVersion = paramaters[0];
}

if (typeof parameterVersion === 'undefined') {
  showHelp();
  process.exit(1);
}

var helper = new Helper(extend({}, options, {
    currentVersion: userPackage.version,
    parameterVersion: parameterVersion
}));

<|endoftext|>


<commit_before>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

module.exports = function (configuration) {
    var router = express.Router();

	var completeError = function(err, res) {
	    if (err) {
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

    router.get('/', (req, res, next) => {
		var route = '/tertulias';
		console.log('VAMOS AQUI: 1');
		req['tertulias'] = {};
		console.log('VAMOS AQUI: 2');
		req['route'] = route;
		console.log('VAMOS AQUI: 3');
		req['resultsTag'] = 'tertulias';
		console.log('VAMOS AQUI: 4');
		reqtertulias.['query'] = queryTertulias;
		console.log('VAMOS AQUI: 5');
    	/*
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar }; // String -> sql.NVarChar; Number -> sql.Int; Boolean -> sql.Bit; Date -> sql.DateTime; Buffer -> sql.VarBinary; sql.Table -> sql.TVP
		console.log('VAMOS AQUI: 6');
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id };
		console.log('VAMOS AQUI: 7');
	    req.tertulias['links'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '" }, ' +
			'{ rel: "create", method: "POST", href: "' + route + '" }, ' +
			'{ rel: "searchPublic", method: "GET", href: "' + route + '/publicsearch" } ' +
		']';
		console.log('VAMOS AQUI: 8');
	    req.tertulias['itemLinks'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "update", method: "PUT", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "delete", method: "DELETE", href: "' + route + '/:tertulia" } ' +
		']';
		console.log('VAMOS AQUI: 9');
	    goGet(req, res, next);
		console.log('VAMOS AQUI: 10');
		*/
	});

	var goGet = function(req, res, next) {
		/*
		var query = req.tertulias.query;
		var resultsTag = req.tertulias.resultsTag;
		var route = req.tertulias.route;
	    var paramsTypes = req.tertulias.paramsTypes;
	    var paramsValues = req.tertulias.paramsValues;
	    var links = req.tertulias.links;
	    var itemLinks = req.tertulias.itemLinks;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsTypes) preparedStatement.input(key, paramsTypes[key]);
	        preparedStatement.prepare(query, function(err) {
	            if (err) { completeError(err, res); return; }
	            preparedStatement.execute(paramsValues,
	                function(err, recordset, affected) {
	                    if (err) {
	                    	completeError(err, res);
	                    	return;
	                    }
	                    res.type('application/json');
                    	if (typeof itemLinks !== typeof undefined)
		                    recordset.forEach(function(elem) {
		                    	elem['links'] = JSON.parse(itemLinks.replace(/:tertulia/g, elem.tr_id));
	                    });
	                    preparedStatement.unprepare();
	                    var results = {};
	                    results[resultsTag] = recordset;
	                    results['links'] = links;
	                    console.log(results);
	                    res.json(results);
	                    next();
	                }
	            );
	        });
	    });
	    */
	}

    return router;

}
<commit_msg>wip save<commit_after>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

module.exports = function (configuration) {
    var router = express.Router();

	var completeError = function(err, res) {
	    if (err) {
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

    router.get('/', (req, res, next) => {
		var route = '/tertulias';
		console.log('VAMOS AQUI: 1');
    	/*
		req['tertulias'] = {};
		console.log('VAMOS AQUI: 2');
		req['route'] = route;
		console.log('VAMOS AQUI: 3');
		req['resultsTag'] = 'tertulias';
		console.log('VAMOS AQUI: 4');
		reqtertulias.['query'] = queryTertulias;
		console.log('VAMOS AQUI: 5');
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar }; // String -> sql.NVarChar; Number -> sql.Int; Boolean -> sql.Bit; Date -> sql.DateTime; Buffer -> sql.VarBinary; sql.Table -> sql.TVP
		console.log('VAMOS AQUI: 6');
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id };
		console.log('VAMOS AQUI: 7');
	    req.tertulias['links'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '" }, ' +
			'{ rel: "create", method: "POST", href: "' + route + '" }, ' +
			'{ rel: "searchPublic", method: "GET", href: "' + route + '/publicsearch" } ' +
		']';
		console.log('VAMOS AQUI: 8');
	    req.tertulias['itemLinks'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "update", method: "PUT", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "delete", method: "DELETE", href: "' + route + '/:tertulia" } ' +
		']';
		console.log('VAMOS AQUI: 9');
	    goGet(req, res, next);
		console.log('VAMOS AQUI: 10');
		*/
	});

	var goGet = function(req, res, next) {
		/*
		var query = req.tertulias.query;
		var resultsTag = req.tertulias.resultsTag;
		var route = req.tertulias.route;
	    var paramsTypes = req.tertulias.paramsTypes;
	    var paramsValues = req.tertulias.paramsValues;
	    var links = req.tertulias.links;
	    var itemLinks = req.tertulias.itemLinks;

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsTypes) preparedStatement.input(key, paramsTypes[key]);
	        preparedStatement.prepare(query, function(err) {
	            if (err) { completeError(err, res); return; }
	            preparedStatement.execute(paramsValues,
	                function(err, recordset, affected) {
	                    if (err) {
	                    	completeError(err, res);
	                    	return;
	                    }
	                    res.type('application/json');
                    	if (typeof itemLinks !== typeof undefined)
		                    recordset.forEach(function(elem) {
		                    	elem['links'] = JSON.parse(itemLinks.replace(/:tertulia/g, elem.tr_id));
	                    });
	                    preparedStatement.unprepare();
	                    var results = {};
	                    results[resultsTag] = recordset;
	                    results['links'] = links;
	                    console.log(results);
	                    res.json(results);
	                    next();
	                }
	            );
	        });
	    });
	    */
	}

    return router;

}
<|endoftext|>


<commit_before>procces= function() {
  TimeSpeed=100;
  startRange=1;
  stopRange=100;
  incrementRenge=5;
  setTimeout(function run(){
        if(startRange >=stopRange) {
          console.info("stop");
        }
        else {
          console.info("rinning");
          startRange+=Math.floor(Math.random()*incrementRenge);
          $(".face back").css({"background-position":startRange+"px ,"+startRange+"px"});
          setTimeout(function() {
            run()
          },TimeSpeed)
        }
      },TimeSpeed)
}<commit_msg>Delete randomize.js<commit_after><|endoftext|>


<commit_before>/*
## Get the search term from submit named 'search'.
*/
function getQueryVariable (variable) {
  var query = window.location.search.substring(1);
  var vars = query.splits('&');

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');

    if (pair[0] === varibale) {
      return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
    }
  }
}

var searchTerm = getQueryVariable ('query');

<commit_msg>search.js + peform the search.<commit_after>/*
## Get the search term from submit named 'search'.
*/
function getQueryVariable (variable) {
  var query = window.location.search.substring(1);
  var vars = query.splits('&');

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');

    if (pair[0] === varibale) {
      return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
    }
  }
}

var searchTerm = getQueryVariable ('query');

/*
## Peform the search
*/

if (searchTerm) {
  document.getElementById('search-box').setAttribute("value", searchTerm);

  // Initalize lunr with the fields it will be searching on. I've given title
  // a bost of 10 to indeicate matches on this field are more important.

  var idex_item = lunr(function () {
    this.field('id');
    this.field('title', { boost: 10 });
    this.field('author');
    this.field('category');
    this.field('content');
  });

  for (var key in window.store) {
    idex_item.add({
      'id': key,
      'title': window.store[key].title,
      'author': window.store[key].author,
      'category': window.store[key].category,
      'content': window.store[key].content
    });

  var results = idex_item.search (searchTerm);
  displaySearchResults (results, window.store);
  }
}

<|endoftext|>