<commit_before>$(function() {
  var containers = {}
  var shipments = []
  var dewars = []

  var ship = 1

  $('.error').dialog({ autoOpen: false, buttons: { 'Close': function() { $(this).dialog('close') } } });
  $('.confirm').dialog({ autoOpen: false, modal: true })

  // Setup beamline puck slots
  function load_blpos() {
    var drop = {
      accept: '.container',
      hoverClass: 'bl_puck_drag',
      drop: _container_drop
    }

    var pucks = (bl == 'i04-1' || bl == 'i24') ? 9 : 10
    for (var i = 1; i <= pucks; i++) {
      $('
'+i+'

').droppable(drop).appendTo('#assigned').data('blcid', i)
    }

    $('#unassigned').droppable({
        accept: '.bl_puck .ac div',
        hoverClass: 'unassigned_drag',
        drop: _unassigned_drop
    })
  }

  function _unassigned_drop(e,ui) {
    var t = $('.shipment[sid='+ui.draggable.attr('sid')+']').children('.dewar[did='+ui.draggable.attr('did')+']').children('.containers')
    _confirm('Unassign Container', 'Are you sure you want to unassign this container?', function() {

      if (t.length) {
        ui.draggable.appendTo(t).position({ my: 'left top', at: 'left top', of: t})
        ui.draggable.removeClass('assigned')
      } else ui.draggable.remove()

      // assign db callback
      console.log('remove container id ' + ui.draggable.attr('cid'))
      _unassign_container(ui.draggable.attr('cid'))
    })
  }

  // Container Drop
  function _container_drop(e,ui) {
    if (ui.draggable.parent().parent().attr('id') != $(this).attr('id')) {
     var p = $(this)
      _confirm('Assign Container', 'Are you sure you want to assign this container? Any other container assigned to this slot will be unassigned', function() {
      if (p.children('div').has('.container').length > 0){
        prev = p.children('div').children('.container')
        t = $('.shipment[sid='+prev.attr('sid')+']').children('.dewar[did='+prev.attr('did')+']').children('.containers')
        prev.appendTo(t).attr('loc', '').removeClass('assigned')

        // remove prev db call
        console.log('remove container id ' + prev.attr('cid'))
        _unassign_container(prev.attr('cid'))
        containers[prev.attr('cid')] = 0
      }

      p.children('div').html('')
      ui.draggable.appendTo(p.children('div')).position({ my: 'left top', at: 'left top', of: p.children('div')}).addClass('assigned').attr('loc', p.data('blcid'))

      // set dewar as active
      $('div.dewar[did='+ui.draggable.attr('did')+']').addClass('active')

      // assign db callback & refresh
      console.log('add container id ' + ui.draggable.attr('cid') + ' to ' + bl +'-'+ p.data('blcid'))
      _assign_container(ui.draggable.attr('cid'), p.data('blcid'))
    })
    }
  }

  function _assign_container(cid, pos) {
    $.ajax({
      url: '/samples/ajax/assign/visit/' + visit + '/cid/' + cid + '/pos/' + pos,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  function _unassign_container(cid) {
    $.ajax({
      url: '/samples/ajax/unassign/visit/' + visit + '/cid/' + cid,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  // Retrieve shipments for visit
  function _get_shipments(fn) {
    $.ajax({
      url: '/samples/ajax/ship/visit/'+visit+'/pp/5'+(ship ? ('/p/'+ship) : ''),
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        var pgs = []
        var pc = json[0] == 0 ? 1 : json[0]
        for (var i = 0; i < pc; i++) pgs.push('
'+(i+1)+'
')
        $('.pages').html('
'+pgs.join('')+'
')
        $('.pages li').removeClass('selected').unbind('click').click(function() {
          ship = parseInt($(this).children('a').attr('href').replace('#', ''))

          $('#unassigned').empty()
          shipments = []
          dewars = []
          containers = {}
          $('#assigned .container').each(function(i,e) { containers[$(this).attr('cid')] = 0 })

          _get_shipments()
        }).eq(ship-1).addClass('selected')

        var ship_opts = ''
        $.each(json[1], function(i,s) {
            ship_opts += '<option value="'+s['SHIPPINGID']+'">'+s['SHIPPINGNAME']+'</option>';
            if ($.inArray(s['SHIPPINGID'], shipments) == -1) {
              $('

'+s['SHIPPINGNAME']+(s['CREATED'] ? (' [Created: '+s['CREATED']+']') : '')+'

').hide().appendTo('#unassigned').slideDown()

              shipments.push(s['SHIPPINGID'])
            }
        })

        $('select[name=shipment]').html(ship_opts).combobox('value', null)
        if (fn) fn()
        _get_dewars()
      }
    })
  }

  // Retrieve dewars for visit
  function _get_dewars(fn) {
    $.ajax({
      url: '/samples/ajax/dwr/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        $.each(json, function(i,d) {
            if ($.inArray(d['DEWARID'], dewars) == -1) {
              $('

'+d['CODE']+'<button class="deact">Deactivate Dewar</button>

').hide().appendTo('div.shipment[sid='+d['SHIPPINGID']+']').addClass(d['DEWARSTATUS'] == 'processing' ? 'active' : '').slideDown()

              // if (d['DEWARSTATUS'] == 'processing' || 1) $('div[did='+d['DEWARID']+']').slideDown()

              dewars.push(d['DEWARID'])
            }
        })

        $('div.dewar button.deact').button({ icons: { primary: 'ui-icon-cross' } }).unbind('click').click(function() {
          var d = $(this).closest('div.dewar')
          $.ajax({
            url: '/samples/ajax/deact/visit/'+visit+'/did/'+d.attr('did'),
            type: 'GET',
            dataType: 'json',
            timeout: 5000,
            success: function(json){
              d.removeClass('active')
              _get_dewars()
            }
          })
          return false
        })

        if (fn) fn()
        _get_containers()
      }
    })
  }

  // Retrieve containers for visit
  function _get_containers() {
    $.ajax({
      url: '/samples/ajax/cnt/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){

        var drag = {
          containment: '#drag_container',
          stack: '#unassigned div',
          /*cursor: 'move',*/
          /*cancel: 'a',*/
          revert: true
        }

        $.each(json, function(i,c) {
            var a = c['SAMPLECHANGERLOCATION']
            //var b = c['BEAMLINELOCATION']
            var assigned = c['SAMPLECHANGERLOCATION'] && (c['BEAMLINELOCATION'] == bl) && (c['DEWARSTATUS'] == 'processing')

            if (!(c['CONTAINERID'] in containers)) {
              sc = $('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')

              if (!assigned || (assigned && !$('#blp'+a).children('div').children('div[cid='+c['CONTAINERID']+']').length)) {

                $('
View Container
'+c['CODE']+'

').appendTo(assigned ? ($('#blp'+a).children('div')) : sc).addClass(assigned ? 'assigned' : '').draggable(drag)
                containers[c['CONTAINERID']] = a
              }

            } else {
               d = $('div[cid='+c['CONTAINERID']+']')
               var state = c['SAMPLECHANGERLOCATION'] == d.attr('loc') && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing'
               if (!state) {
               if (c['SAMPLECHANGERLOCATION'] && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing') {
                   d.appendTo($('#blp'+a).children('div')).addClass('assigned')
               } else d.appendTo($('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')).removeClass('assigned')
               }

            }
        })

        map_callbacks()
      }
    })
  }

  // Generate a confirmation dialog
  function _confirm(t, q, ok_fn) {
    $('.confirm').html(q).dialog('option', 'title', t)
    $('.confirm').dialog('option', 'buttons', {
      'Ok': function() {
        ok_fn()
        $(this).dialog('close');
      },
      'Cancel': function () {
        $(this).dialog('close');
      }
    });

    $('.confirm').dialog('open');
  }

  // Map callbacks to containers
  function map_callbacks() {
    //$('.shipment > h1').unbind('click').click(function() {
    //  $(this).siblings('.dewar').slideToggle()
    //  return false
    //})

    $('.container a').button({ icons: { primary: 'ui-icon-search' }, text: false })
  }

  load_blpos()
  _get_shipments()

  // Bind links / buttons
  $('#add').button({ icons: { primary: 'ui-icon-plusthick' } }).click(function() {
    _add_container()
  })

  $('.add span a').click(function() {
    $('.add_protein').dialog('open')
    return false
  })

});
<commit_msg>Allow 23 pucks on i03<commit_after>$(function() {
  var containers = {}
  var shipments = []
  var dewars = []

  var ship = 1

  $('.error').dialog({ autoOpen: false, buttons: { 'Close': function() { $(this).dialog('close') } } });
  $('.confirm').dialog({ autoOpen: false, modal: true })

  // Setup beamline puck slots
  function load_blpos() {
    var drop = {
      accept: '.container',
      hoverClass: 'bl_puck_drag',
      drop: _container_drop
    }

    var pucks = (bl == 'i04-1' || bl == 'i24') ? 9 : (bl == 'i03' ? 23 : 10)
    for (var i = 1; i <= pucks; i++) {
      $('
'+i+'

').droppable(drop).appendTo('#assigned').data('blcid', i)
    }

    $('#unassigned').droppable({
        accept: '.bl_puck .ac div',
        hoverClass: 'unassigned_drag',
        drop: _unassigned_drop
    })
  }

  function _unassigned_drop(e,ui) {
    var t = $('.shipment[sid='+ui.draggable.attr('sid')+']').children('.dewar[did='+ui.draggable.attr('did')+']').children('.containers')
    _confirm('Unassign Container', 'Are you sure you want to unassign this container?', function() {

      if (t.length) {
        ui.draggable.appendTo(t).position({ my: 'left top', at: 'left top', of: t})
        ui.draggable.removeClass('assigned')
      } else ui.draggable.remove()

      // assign db callback
      console.log('remove container id ' + ui.draggable.attr('cid'))
      _unassign_container(ui.draggable.attr('cid'))
    })
  }

  // Container Drop
  function _container_drop(e,ui) {
    if (ui.draggable.parent().parent().attr('id') != $(this).attr('id')) {
     var p = $(this)
      _confirm('Assign Container', 'Are you sure you want to assign this container? Any other container assigned to this slot will be unassigned', function() {
      if (p.children('div').has('.container').length > 0){
        prev = p.children('div').children('.container')
        t = $('.shipment[sid='+prev.attr('sid')+']').children('.dewar[did='+prev.attr('did')+']').children('.containers')
        prev.appendTo(t).attr('loc', '').removeClass('assigned')

        // remove prev db call
        console.log('remove container id ' + prev.attr('cid'))
        _unassign_container(prev.attr('cid'))
        containers[prev.attr('cid')] = 0
      }

      p.children('div').html('')
      ui.draggable.appendTo(p.children('div')).position({ my: 'left top', at: 'left top', of: p.children('div')}).addClass('assigned').attr('loc', p.data('blcid'))

      // set dewar as active
      $('div.dewar[did='+ui.draggable.attr('did')+']').addClass('active')

      // assign db callback & refresh
      console.log('add container id ' + ui.draggable.attr('cid') + ' to ' + bl +'-'+ p.data('blcid'))
      _assign_container(ui.draggable.attr('cid'), p.data('blcid'))
    })
    }
  }

  function _assign_container(cid, pos) {
    $.ajax({
      url: '/samples/ajax/assign/visit/' + visit + '/cid/' + cid + '/pos/' + pos,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  function _unassign_container(cid) {
    $.ajax({
      url: '/samples/ajax/unassign/visit/' + visit + '/cid/' + cid,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  // Retrieve shipments for visit
  function _get_shipments(fn) {
    $.ajax({
      url: '/samples/ajax/ship/visit/'+visit+'/pp/5'+(ship ? ('/p/'+ship) : ''),
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        var pgs = []
        var pc = json[0] == 0 ? 1 : json[0]
        for (var i = 0; i < pc; i++) pgs.push('
'+(i+1)+'
')
        $('.pages').html('
'+pgs.join('')+'
')
        $('.pages li').removeClass('selected').unbind('click').click(function() {
          ship = parseInt($(this).children('a').attr('href').replace('#', ''))

          $('#unassigned').empty()
          shipments = []
          dewars = []
          containers = {}
          $('#assigned .container').each(function(i,e) { containers[$(this).attr('cid')] = 0 })

          _get_shipments()
        }).eq(ship-1).addClass('selected')

        var ship_opts = ''
        $.each(json[1], function(i,s) {
            ship_opts += '<option value="'+s['SHIPPINGID']+'">'+s['SHIPPINGNAME']+'</option>';
            if ($.inArray(s['SHIPPINGID'], shipments) == -1) {
              $('

'+s['SHIPPINGNAME']+(s['CREATED'] ? (' [Created: '+s['CREATED']+']') : '')+'

').hide().appendTo('#unassigned').slideDown()

              shipments.push(s['SHIPPINGID'])
            }
        })

        $('select[name=shipment]').html(ship_opts).combobox('value', null)
        if (fn) fn()
        _get_dewars()
      }
    })
  }

  // Retrieve dewars for visit
  function _get_dewars(fn) {
    $.ajax({
      url: '/samples/ajax/dwr/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        $.each(json, function(i,d) {
            if ($.inArray(d['DEWARID'], dewars) == -1) {
              $('

'+d['CODE']+'<button class="deact">Deactivate Dewar</button>

').hide().appendTo('div.shipment[sid='+d['SHIPPINGID']+']').addClass(d['DEWARSTATUS'] == 'processing' ? 'active' : '').slideDown()

              // if (d['DEWARSTATUS'] == 'processing' || 1) $('div[did='+d['DEWARID']+']').slideDown()

              dewars.push(d['DEWARID'])
            }
        })

        $('div.dewar button.deact').button({ icons: { primary: 'ui-icon-cross' } }).unbind('click').click(function() {
          var d = $(this).closest('div.dewar')
          $.ajax({
            url: '/samples/ajax/deact/visit/'+visit+'/did/'+d.attr('did'),
            type: 'GET',
            dataType: 'json',
            timeout: 5000,
            success: function(json){
              d.removeClass('active')
              _get_dewars()
            }
          })
          return false
        })

        if (fn) fn()
        _get_containers()
      }
    })
  }

  // Retrieve containers for visit
  function _get_containers() {
    $.ajax({
      url: '/samples/ajax/cnt/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){

        var drag = {
          containment: '#drag_container',
          stack: '#unassigned div',
          /*cursor: 'move',*/
          /*cancel: 'a',*/
          revert: true
        }

        $.each(json, function(i,c) {
            var a = c['SAMPLECHANGERLOCATION']
            //var b = c['BEAMLINELOCATION']
            var assigned = c['SAMPLECHANGERLOCATION'] && (c['BEAMLINELOCATION'] == bl) && (c['DEWARSTATUS'] == 'processing')

            if (!(c['CONTAINERID'] in containers)) {
              sc = $('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')

              if (!assigned || (assigned && !$('#blp'+a).children('div').children('div[cid='+c['CONTAINERID']+']').length)) {

                $('
View Container
'+c['CODE']+'

').appendTo(assigned ? ($('#blp'+a).children('div')) : sc).addClass(assigned ? 'assigned' : '').draggable(drag)
                containers[c['CONTAINERID']] = a
              }

            } else {
               d = $('div[cid='+c['CONTAINERID']+']')
               var state = c['SAMPLECHANGERLOCATION'] == d.attr('loc') && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing'
               if (!state) {
               if (c['SAMPLECHANGERLOCATION'] && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing') {
                   d.appendTo($('#blp'+a).children('div')).addClass('assigned')
               } else d.appendTo($('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')).removeClass('assigned')
               }

            }
        })

        map_callbacks()
      }
    })
  }

  // Generate a confirmation dialog
  function _confirm(t, q, ok_fn) {
    $('.confirm').html(q).dialog('option', 'title', t)
    $('.confirm').dialog('option', 'buttons', {
      'Ok': function() {
        ok_fn()
        $(this).dialog('close');
      },
      'Cancel': function () {
        $(this).dialog('close');
      }
    });

    $('.confirm').dialog('open');
  }

  // Map callbacks to containers
  function map_callbacks() {
    //$('.shipment > h1').unbind('click').click(function() {
    //  $(this).siblings('.dewar').slideToggle()
    //  return false
    //})

    $('.container a').button({ icons: { primary: 'ui-icon-search' }, text: false })
  }

  load_blpos()
  _get_shipments()

  // Bind links / buttons
  $('#add').button({ icons: { primary: 'ui-icon-plusthick' } }).click(function() {
    _add_container()
  })

  $('.add span a').click(function() {
    $('.add_protein').dialog('open')
    return false
  })

});
<|endoftext|>


<commit_before>//Settings
var accountAmount = 4; //The number of existing accounts
//

//Vars
var ar_ext = ['pdf', 'js', 'jpe', 'html', 'txt'];        // array with blocked extensions
var type;
var account = Math.floor(Math.random() * accountAmount + 1)
//

//Start Functions
setTimeout( function() { randomizeAccounting() }, 500)
//

function checkName(el, to, sbm) {
  var name = el.value;
  var ar_name = name.split('.');
  var ar_nm = ar_name[0].split('\\');
  for(var i=0; i<ar_nm.length; i++) var nm = ar_nm[i];
  for(var i=0; i<ar_ext.length; i++) {
    if(ar_ext[i] == ar_name[1]) {
     alert("That file can't be used... Yet");
    } else {
  document.getElementById('typeInput2').innerHTML = '<input type="hidden" name="inputformat" value="' + ar_name[1] + '"	>'
  }
 }
}

function checkAgain() {
 document.getElementById('typeInput').value = document.getElementById('dontNeed2').value
}
//document.getElementById('file').files[0].size
function randomizeAccounting() {
 if (account == 1) {
  document.getElementById('api').value = 'Ga3f-fDysMt9IjXRQmajNBb1ezL-9Wze83Emebb7E6ULVs5cIPxAG91fCjB0niLPkDzHja2BLylx_c9VabKwXA';
 } else if (account == 2) {
   document.getElementById('api').value = 'nCzR3cehoJ05hmz8E5r8Cql--m1dGABeVok5BixWns3gs8yqQ3ZfyjbVn43Afl8id22OvwAysCElup72WTAZvQ';
 } else if (account == 3) {
  document.getElementById('api').value = 'YGR9BcShFnzqEk9vSBpm7eJCxSQga1EouWfHRGsoF_0uUDSELTCz9bdWcsZSPkU2z4s545mcOhlt93iduPlOpQ'
 } else if (account == 4) {
  document.getElementById('api').value = 'H8pVuvlGgnPsm0wfGQXho6rYJ7Rc-gJLSesiccIADzUMnAmNEUNeVVX_mfJL88fsVIv_AN_-geu5WhdvkZSnUw'
 }
}

function makeUrl() {
 document.getElementById('file').type = 'url';
}

function makeFile() {
 document.getElementById('file').type = 'file';
}
<commit_msg>Update convertJava.js<commit_after>//Settings
var accountAmount = 4; //The number of existing accounts
//

//Vars
var ar_ext = ['pdf', 'js', 'jpe', 'html', 'txt'];        // array with blocked extensions
var type;
var account = Math.floor(Math.random() * accountAmount + 1)
//

//Start Functions
setTimeout( function() { randomizeAccounting() }, 500)
//

function checkName(el, to, sbm) {
  var name = el.value;
  var ar_name = name.split('.');
  var ar_nm = ar_name[0].split('\\');
  for(var i=0; i<ar_nm.length; i++) var nm = ar_nm[i];
  for(var i=0; i<ar_ext.length; i++) {
    if(ar_ext[i] == ar_name[1]) {
     alert("That file can't be used... Yet");
    } else {
  document.getElementById('typeInput2').innerHTML = '<input type="hidden" name="inputformat" value="' + ar_name[1] + '"	>'
  }
 }
}

function checkAgain() {
 document.getElementById('typeInput').value = document.getElementById('dontNeed2').value
}
//document.getElementById('file').files[0].size
function randomizeAccounting() {
 if (account == 1) {
  document.getElementById('api').value = 'Ga3f-fDysMt9IjXRQmajNBb1ezL-9Wze83Emebb7E6ULVs5cIPxAG91fCjB0niLPkDzHja2BLylx_c9VabKwXA';
 } else if (account == 2) {
   document.getElementById('api').value = 'nCzR3cehoJ05hmz8E5r8Cql--m1dGABeVok5BixWns3gs8yqQ3ZfyjbVn43Afl8id22OvwAysCElup72WTAZvQ';
 } else if (account == 3) {
  document.getElementById('api').value = 'YGR9BcShFnzqEk9vSBpm7eJCxSQga1EouWfHRGsoF_0uUDSELTCz9bdWcsZSPkU2z4s545mcOhlt93iduPlOpQ'
 } else if (account == 4) {
  document.getElementById('api').value = 'H8pVuvlGgnPsm0wfGQXho6rYJ7Rc-gJLSesiccIADzUMnAmNEUNeVVX_mfJL88fsVIv_AN_-geu5WhdvkZSnUw'
 }
}

function makeUrl() {
 document.getElementById('fFile').innerHTML = '<input type="url" id="urlT">';
 document.getElementById('dRC').innerHTML = '';
}
//<input type="file" name="file" onchange="checkName(this, 'fname', 'submit')" id="file">
function makeFile() {
 document.getElementById('fFile').innerHTML = '<input type="file" name="file" onchange="checkName(this, ''fname'', ''submit'')" id="file">';
 document.getElementById('dRC').innerHTML = '<input type="submit" value="Convert">';
}

function uUrl() {
 document.getElementById('urlA').href = document.getElementById('urlT').value;
}
<|endoftext|>


<commit_before>var _ = require('underscore'),
  log = require('../../log'),
  telldus = require('telldus');

var version = function() {
	return '1.0.0';
}

var name = function() {
	return 'Telldus';
}

var init = function(app) {

  app.all('/api/telldus/*', function(req, res, next) {
    log.verbose('[telldus]', req.originalUrl);
    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    next();
  });

	app.get('/api/telldus/devices', function(req, res) {

    var devices = telldus.getDevices();

    log.verbose('[telldus]', JSON.stringify(devices));

    res.json(devices);
	});

  app.get('/api/telldus/devices/:id', function(req, res) {

      var message;

      if (isNaN(req.params.id)) {
        message = 'Invalid id ' + req.params.id + '.';
        log.error('[telldus]', message);
        res.send(400, message);
        return;
      }

      var id = parseInt(req.params.id, 10);

      var device = _.findWhere(telldus.getDevices(), { id: id });

      if (_.isUndefined(device)) {
        message = 'No device with id ' + id + ' found.';
        log.error('[telldus]', message);
        res.send(404, message);
        return;
      }

      log.verbose('[telldus]', JSON.stringify(device));

      res.json(device);
  });
}

exports.name = name;
exports.version = version;
exports.init = init;<commit_msg>Added some working Telldus commands<commit_after>var _ = require('underscore'),
  log = require('../../log'),
  telldus = require('telldus');

var version = function() {
	return '1.0.0';
}

var name = function() {
	return 'Telldus';
}

var init = function(app) {

  app.all('/api/telldus/*', function(req, res, next) {
    log.verbose('[telldus]', req.originalUrl);
    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    next();
  });

	app.get('/api/telldus/devices', function(req, res) {

    var devices = telldus.getDevices();

    log.verbose('[telldus]', JSON.stringify(devices));

    res.json(devices);
	});

  app.put('/api/telldus/devices/:id', function(req, res) {

      var device = getDeviceById(req.params.id, res);

      if (device === null) {
        return;
      }

      var command = req.body.command;
      var level = req.body.level;

      if (command === 'off') {
        if (_.contains(device.methods, 'TURNOFF')) {
          telldus.turnOff(device.id);
        } else {
          badRequest('Unsupported command "off" for device with id "' + device.id + '".', res);
        }
      } else if (command === 'on') {
        if (_.contains(device.methods, 'TURNON')) {
          telldus.turnOn(device.id);
        } else {
          badRequest('Unsupported command "on" for device with id "' + device.id + '".', res);
        }
      } else if (command === 'dim') {
        if (_.contains(device.methods, 'DIM')) {

          if (isNaN(level)) {
            badRequest('Invalid dim level "' + level + '".', res);
          }

          level = parseInt(level, 10);

          if (level < 0 || level > 255) {
            badRequest('Invalid dim level "' + level + '".', res);
          }

          telldus.dim(device.id, level);

        } else {
          badRequest('Unsupported command "on" for device with id "' + device.id + '".', res);
        }
      } else {
        badRequest('Unknown command "' + command + '".', res);
      }

      res.send(200, 'Ok');
  });

  app.get('/api/telldus/devices/:id', function(req, res) {

      var device = getDeviceById(req.params.id, res);

      if (device === null) {
        return;
      }

      log.verbose('[telldus]', JSON.stringify(device));

      res.json(device);
  });
}

var badRequest = function(message, res) {
    log.error('[telldus]', message);
    res.send(400, message);
    return null;
}

var getDeviceById = function(id, res) {

  var message;

  if (isNaN(id)) {
    badRequest('Invalid id "' + id + '".', res);
  }

  id = parseInt(id, 10);

  var device = _.findWhere(telldus.getDevices(), { id: id });

  if (_.isUndefined(device)) {
    badRequest('No device with id "' + id + '" found.', res);
  }

  return device;
}

exports.name = name;
exports.version = version;
exports.init = init;<|endoftext|>


<commit_before>const shamIt = require("sham-it");
const createApp = require("./supertest-example");
const request = require("supertest");

describe("Example testing a webservice which depends on another webservice being mocked by sham", () => {
  let validateSham;
  let app;

  beforeAll(async () => {
    validateSham = await shamIt({
      defaultReply: {
        status: 401,
        headers: { "Content-Type": "application/json" },
        body: { valid: false }
      }
    });

    validateSham.addMatcher({
      when: ({ and, equals }) =>
        and(
          equals("method", "GET"),
          equals("pathname", "/validate"),
          equals("headers.authorization", "User-1")
        ),
      respond: { body: { valid: true } }
    });
  });

  beforeEach(() => {
    app = createApp(`${validateSham.uri}/validate`);
  });

  test("Should return valid when a request is sent with the correct authorization token", async () => {
    const res = await request(app)
      .get("/")
      .set("Authorization", "User-1")
      .expect(200);

    expect(res.text).toEqual("Valid");
  });

  test("Should return invalid when a request is sent with the incorrect autorization token", async () => {
    const res = await request(app)
      .get("/")
      .set("Authorization", "User-2")
      .expect(200);

    expect(res.text).toEqual("Invalid");
  });

  afterEach(async () => await validateSham.clear());

  afterAll(async () => await validateSham.close());
});
<commit_msg>fix(examples) Change clear() to reset()<commit_after>const shamIt = require("sham-it");
const createApp = require("./supertest-example");
const request = require("supertest");

describe("Example testing a webservice which depends on another webservice being mocked by sham", () => {
  let validateSham;
  let app;

  beforeAll(async () => {
    validateSham = await shamIt({
      defaultReply: {
        status: 401,
        headers: { "Content-Type": "application/json" },
        body: { valid: false }
      }
    });

    validateSham.addMatcher({
      when: ({ and, equals }) =>
        and(
          equals("method", "GET"),
          equals("pathname", "/validate"),
          equals("headers.authorization", "User-1")
        ),
      respond: { body: { valid: true } }
    });
  });

  beforeEach(() => {
    app = createApp(`${validateSham.uri}/validate`);
  });

  test("Should return valid when a request is sent with the correct authorization token", async () => {
    const res = await request(app)
      .get("/")
      .set("Authorization", "User-1")
      .expect(200);

    expect(res.text).toEqual("Valid");
  });

  test("Should return invalid when a request is sent with the incorrect autorization token", async () => {
    const res = await request(app)
      .get("/")
      .set("Authorization", "User-2")
      .expect(200);

    expect(res.text).toEqual("Invalid");
  });

  afterEach(async () => await validateSham.reset());

  afterAll(async () => await validateSham.close());
});
<|endoftext|>


<commit_before>module.exports = function() {
  return {
    'free-brands-svg-icons': [
      'black-tie'
    ],
    'free-solid-svg-icons': [
      'angle-double-down',
      'angle-double-left',
      'archive',
      'arrows-alt',
      'backward',
      'ban',
      'bold',
      'calendar-check',
      'calendar-minus',
      'caret-down',
      'caret-right',
      'chart-bar',
      'check',
      'circle',
      'clock',
      'cloud',
      'copy',
      'download',
      'edit',
      'ellipsis-h',
      'exclamation',
      'exclamation-circle',
      'expand',
      'external-link-square-alt',
      'eye',
      'file',
      'file-audio',
      'file-pdf',
      'file-powerpoint',
      'file-signature',
      'file-video',
      'flask',
      'forward',
      'indent',
      'info-circle',
      'italic',
      'link',
      'list',
      'list-ol',
      'list-ul',
      'minus',
      'minus-square',
      'paragraph',
      'pen-square',
      'pencil-alt',
      'plus',
      'plus-square',
      'print',
      'random',
      'rss-square',
      'search',
      'sort',
      'sort-alpha-down',
      'sort-alpha-up',
      'sort-numeric-down',
      'sort-numeric-up',
      'spinner',
      'star',
      'star-half-alt',
      'subscript',
      'superscript',
      'times',
      'trash',
      'undo',
      'unlink',
      'user',
      'user-clock',
      'user-plus',
      'user-times',
      'users'
    ],
    'pro-light-svg-icons': [
      'clipboard-list',
    ],
  };
};
<commit_msg>whitelist history icon.<commit_after>module.exports = function() {
  return {
    'free-brands-svg-icons': [
      'black-tie'
    ],
    'free-solid-svg-icons': [
      'angle-double-down',
      'angle-double-left',
      'archive',
      'arrows-alt',
      'backward',
      'ban',
      'bold',
      'calendar-check',
      'calendar-minus',
      'caret-down',
      'caret-right',
      'chart-bar',
      'check',
      'circle',
      'clock',
      'cloud',
      'copy',
      'download',
      'edit',
      'ellipsis-h',
      'exclamation',
      'exclamation-circle',
      'expand',
      'external-link-square-alt',
      'eye',
      'file',
      'file-audio',
      'file-pdf',
      'file-powerpoint',
      'file-signature',
      'file-video',
      'flask',
      'forward',
      'history',
      'indent',
      'info-circle',
      'italic',
      'link',
      'list',
      'list-ol',
      'list-ul',
      'minus',
      'minus-square',
      'paragraph',
      'pen-square',
      'pencil-alt',
      'plus',
      'plus-square',
      'print',
      'random',
      'rss-square',
      'search',
      'sort',
      'sort-alpha-down',
      'sort-alpha-up',
      'sort-numeric-down',
      'sort-numeric-up',
      'spinner',
      'star',
      'star-half-alt',
      'subscript',
      'superscript',
      'times',
      'trash',
      'undo',
      'unlink',
      'user',
      'user-clock',
      'user-plus',
      'user-times',
      'users'
    ],
    'pro-light-svg-icons': [
      'clipboard-list',
    ],
  };
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    rootPath = path.normalize(__dirname + '/..'),
    env = process.env.NODE_ENV || 'development',
    user = process.env.MONGO_USER_NAME,
    pass = process.env.MONGO_USER_PASS;

var config = {
  development : {
    env   : env,
    root  : rootPath,
    mongo : {},
    app   : {
      name : 'flickr-downloadr-webhook'
    },
    port  : 1337,
    db    : 'mongodb://localhost/flickr-downloadr-webhook-development'
  },
  test        : {
    env   : env,
    root  : rootPath,
    mongo : {},
    app   : {
      name : 'flickr-downloadr-webhook'
    },
    port  : 1337,
    db    : 'mongodb://localhost/flickr-downloadr-webhook-test'
  },
  production  : {
    env   : env,
    root  : rootPath,
    mongo : {},
    app   : {
      name : 'flickr-downloadr-webhook'
    },
    port  : process.env.PORT,
    db    : 'mongodb://' + user + ':' + pass + '@ds119748.mlab.com:19748/fd-webhook'
  }
};

module.exports = config[env];
<commit_msg>update the mongodb uri yet another time<commit_after>'use strict';

var path = require('path'),
    rootPath = path.normalize(__dirname + '/..'),
    env = process.env.NODE_ENV || 'development',
    user = process.env.MONGO_USER_NAME,
    pass = process.env.MONGO_USER_PASS,
    mongodb_uri = process.env.MONGODB_URI;

var config = {
  development : {
    env   : env,
    root  : rootPath,
    mongo : {},
    app   : {
      name : 'flickr-downloadr-webhook'
    },
    port  : 1337,
    db    : 'mongodb://localhost/flickr-downloadr-webhook-development'
  },
  test        : {
    env   : env,
    root  : rootPath,
    mongo : {},
    app   : {
      name : 'flickr-downloadr-webhook'
    },
    port  : 1337,
    db    : 'mongodb://localhost/flickr-downloadr-webhook-test'
  },
  old_production  : {
    env   : env,
    root  : rootPath,
    mongo : {},
    app   : {
      name : 'flickr-downloadr-webhook'
    },
    port  : process.env.PORT,
    db    : 'mongodb://' + user + ':' + pass + '@ds119748.mlab.com:19748/fd-webhook'
  },
  production  : {
    env   : env,
    root  : rootPath,
    mongo : {},
    app   : {
      name : 'flickr-downloadr-webhook'
    },
    port  : process.env.PORT,
    db    : mongodb_uri
  }
};

module.exports = config[env];
<|endoftext|>


<commit_before>"use strict";
define(['settings'],function(settings){
	function model(value,registry){
		var DEFAULT_PAGE = 1;
		var DEFAULT_ITEM = 5;
		var __meta = {},__data = [],__uses=[],object = {meta:__meta,data:__data};
		var registered = false;
		if(registry!=undefined){
			DEMO_REGISTRY[registry.name] = {};
			if(registry.uses){
				var models = registry.uses;
				for(var i in models){
					var endpoint =  models[i];
					require([settings.TEST_DIRECTORY+'/'+endpoint]);
				}
			}
			registered = true;
		}
		function list(){
			var config = arguments[0]||{};
			var page = config.page||DEFAULT_PAGE;
			var limit = __meta.limit||DEFAULT_ITEM;
			var keyword = config.keyword;
			var fields = config.fields;
			var index = limit=='less'?null:((page - 1) * limit);
			var data = __data;
			var __class = __meta.class;
			if(keyword&&fields){
				var _d=[];
				var regex = new RegExp(keyword, 'i');
				for(var i in data){
					var d  =  data[i];
					var t = false;
					for(var ii in fields){
						var f =  fields[ii];
						t = t || regex.test(d[f]);
					}
					if(t){
						_d.push(d);
					}
				}
				data = _d;
			}

			var regEx =  new RegExp('page|limit|keyword|fields');
			for(var field in config){
				var match = config[field];
				if(!regEx.test(field)){
					var _d=[];
					for(var i in data){
						var d  =  data[i];
						var t = d[field]==match;
						if(!d.hasOwnProperty(field))
							t = t && true;
						if(t){
							_d.push(d);
						}
					}
					data = _d;
				}
			}
			var count =  data.length;
			if(index!=null&&__class!="SystemDefault")
				data = data.slice(index,index+limit);
			var meta = __meta;
			meta.page = page;
			meta.limit = limit;
			if(__class!="SystemDefault"){
				meta.count = count;
				meta.last = limit=='less'?1:Math.ceil(meta.count/limit);
				meta.next =  page<meta.last?page+1:null;
			}
			meta.prev =  page>1?page-1:null;
			return angular.copy({meta:meta,data:data});
		};
		function error(){
			return angular.copy({meta:__meta});
		};
		function save(data){
			var saved = false;
			if(!data.hasOwnProperty('id')){
				data.id = __data.length;
			}else{
				for(var i in __data){
					var datum = __data[i];
					if(datum.id==data.id){
						for(var ii in data){
							__data[i][ii] = data[ii];
						}
						saved=true;
						break;
					}
				}
			}
			if(!saved){
				__data.push(data);
			}
			if(registered)
				DEMO_REGISTRY[registry.name]=__data;
			return angular.copy({meta:__meta,data:data});
		}
		function remove(data){
			if(data.hasOwnProperty('id')){
				for(var i in __data){
					var datum = __data[i];
					if(datum.id==data.id){
						__data.splice(i,1);
						break;
					}
				}
			}
			if(registered)
				DEMO_REGISTRY[registry.name]=__data;
			return angular.copy({meta:__meta,data:data});
		}
		function setMeta(meta){
			__meta = meta;
		}
		function setData(data){
			var __class = __meta.class;
			if(__class=="SystemDefault"){
				__data = data;
				return;
			}
			for(var i in data){
				var datum = data[i];
				if( typeof datum=='object'){
					if(!datum.hasOwnProperty('id'))
						datum.id= __data.length;
					__data.push(datum);
				}else{
					__data[i] =  datum;
				}

			}
			if(registered)
				DEMO_REGISTRY[registry.name]=__data;
		}
		object.GET = function(data){
			return {success:list(data),error:error()};
		}
		object.POST = function(data){
			return {success:save(data),error:error()};
		}
		object.DELETE = function(data){
			return {success:remove(data),error:error()};
		}
		object.PUT = function(data){
			return {success:save(data),error:error()};
		}
		object.save = save;
		object.remove = remove;
		if(value.hasOwnProperty('meta'))setMeta(value.meta);
		if(value.hasOwnProperty('data'))setData(value.data);

		return object;
	}
	return model;
});<commit_msg>add list<commit_after>"use strict";
define(['settings'],function(settings){
	function model(value,registry){
		var DEFAULT_PAGE = 1;
		var DEFAULT_ITEM = 5;
		var __meta = {},__data = [],__uses=[],object = {meta:__meta,data:__data};
		var registered = false;
		if(registry!=undefined){
			DEMO_REGISTRY[registry.name] = {};
			if(registry.uses){
				var models = registry.uses;
				for(var i in models){
					var endpoint =  models[i];
					require([settings.TEST_DIRECTORY+'/'+endpoint]);
				}
			}
			registered = true;
		}
		function list(){
			var config = arguments[0]||{};
			var page = config.page||DEFAULT_PAGE;
			var limit = __meta.limit||DEFAULT_ITEM;
			var keyword = config.keyword;
			var fields = config.fields;
			var index = limit=='less'?null:((page - 1) * limit);
			var data = __data;
			var __class = __meta.class;
			if(keyword&&fields){
				var _d=[];
				var regex = new RegExp(keyword, 'i');
				for(var i in data){
					var d  =  data[i];
					var t = false;
					for(var ii in fields){
						var f =  fields[ii];
						t = t || regex.test(d[f]);
					}
					if(t){
						_d.push(d);
					}
				}
				data = _d;
			}

			var regEx =  new RegExp('page|limit|keyword|fields');
			for(var field in config){
				var match = config[field];
				if(!regEx.test(field)){
					var _d=[];
					for(var i in data){
						var d  =  data[i];
						var t = d[field]==match;
						if(!d.hasOwnProperty(field))
							t = t && true;
						if(t){
							_d.push(d);
						}
					}
					data = _d;
				}
			}
			var count =  data.length;
			if(index!=null&&__class!="SystemDefault")
				data = data.slice(index,index+limit);
			var meta = __meta;
			meta.page = page;
			meta.limit = limit;
			if(__class!="SystemDefault"){
				meta.count = count;
				meta.last = limit=='less'?1:Math.ceil(meta.count/limit);
				meta.next =  page<meta.last?page+1:null;
			}
			meta.prev =  page>1?page-1:null;
			return angular.copy({meta:meta,data:data});
		};
		function error(){
			return angular.copy({meta:__meta});
		};
		function save(data){
			var saved = false;
			if(!data.hasOwnProperty('id')){
				data.id = __data.length;
			}else{
				for(var i in __data){
					var datum = __data[i];
					if(datum.id==data.id){
						for(var ii in data){
							__data[i][ii] = data[ii];
						}
						saved=true;
						break;
					}
				}
			}
			if(!saved){
				__data.push(data);
			}
			if(registered)
				DEMO_REGISTRY[registry.name]=__data;
			return angular.copy({meta:__meta,data:data});
		}
		function remove(data){
			if(data.hasOwnProperty('id')){
				for(var i in __data){
					var datum = __data[i];
					if(datum.id==data.id){
						__data.splice(i,1);
						break;
					}
				}
			}
			if(registered)
				DEMO_REGISTRY[registry.name]=__data;
			return angular.copy({meta:__meta,data:data});
		}
		function setMeta(meta){
			__meta = meta;
		}
		function setData(data){
			var __class = __meta.class;
			if(__class=="SystemDefault"){
				__data = data;
				return;
			}
			for(var i in data){
				var datum = data[i];
				if( typeof datum=='object'){
					if(!datum.hasOwnProperty('id'))
						datum.id= __data.length;
					__data.push(datum);
				}else{
					__data[i] =  datum;
				}

			}
			if(registered)
				DEMO_REGISTRY[registry.name]=__data;
		}
		object.GET = function(data){
			return {success:list(data),error:error()};
		}
		object.POST = function(data){
			return {success:save(data),error:error()};
		}
		object.DELETE = function(data){
			return {success:remove(data),error:error()};
		}
		object.PUT = function(data){
			return {success:save(data),error:error()};
		}
		object.list = list;
		object.save = save;
		object.remove = remove;
		if(value.hasOwnProperty('meta'))setMeta(value.meta);
		if(value.hasOwnProperty('data'))setData(value.data);

		return object;
	}
	return model;
});<|endoftext|>


<commit_before>/**
 * --------------------------------------------------------------------
 * jQuery customfileinput plugin
 * Author: Scott Jehl, scott@filamentgroup.com
 * Copyright (c) 2009 Filament Group
 * licensed under MIT (filamentgroup.com/examples/mit-license.txt)
 * --------------------------------------------------------------------
 */
$.fn.customFileInput = function(){
	//apply events and styles for file input element
	var fileInput = $(this)
		.addClass('customfile-input') //add class for CSS
		.mouseover(function(){ upload.addClass('customfile-hover'); })
		.mouseout(function(){ upload.removeClass('customfile-hover'); })
		.focus(function(){
			upload.addClass('customfile-focus');
			fileInput.data('val', fileInput.val());
		})
		.blur(function(){
			upload.removeClass('customfile-focus');
			$(this).trigger('checkChange');
		 })
		 .bind('disable',function(){
		 	fileInput.attr('disabled',true);
			upload.addClass('customfile-disabled');
		})
		.bind('enable',function(){
			fileInput.removeAttr('disabled');
			upload.removeClass('customfile-disabled');
		})
		.bind('checkChange', function(){
			if(fileInput.val() && fileInput.val() != fileInput.data('val')){
				fileInput.trigger('change');
			}
		})
		.bind('change',function(){
			//get file name
			var fileName = $(this).val().split(/\\/).pop();
			//get file extension
			var fileExt = 'customfile-ext-' + fileName.split('.').pop().toLowerCase();
			//update the feedback
			uploadFeedback
				.text(fileName) //set feedback text to filename
				.removeClass(uploadFeedback.data('fileExt') || '') //remove any existing file extension class
				.addClass(fileExt) //add file extension class
				.data('fileExt', fileExt) //store file extension for class removal on next change
				.addClass('customfile-feedback-populated'); //add class to show populated state
			//change text of button
			uploadButton.text('Change');
		})
		.click(function(){ //for IE and Opera, make sure change fires after choosing a file, using an async callback
			fileInput.data('val', fileInput.val());
			setTimeout(function(){
				fileInput.trigger('checkChange');
			},100);
		});

	//create custom control container
	var upload = $('

');
	//create custom control button
	var uploadButton = $('Browse').appendTo(upload);
	//create custom control feedback
	var uploadFeedback = $('No file selected...').appendTo(upload);

	//match disabled state
	if(fileInput.is('[disabled]')){
		fileInput.trigger('disable');
	}

	//on mousemove, keep file input under the cursor to steal click
	upload
		.mousemove(function(e){
			fileInput.css({
				'left': e.pageX - upload.offset().left - fileInput.outerWidth() + 20, //position right side 20px right of cursor X)
				'top': e.pageY - upload.offset().top - $(window).scrollTop() - 3
			});
		})
		.insertAfter(fileInput); //insert after the input

	fileInput.appendTo(upload);

	//return jQuery
	return $(this);
};<commit_msg>fixed support for multiple inputs on a page.<commit_after>/**
 * --------------------------------------------------------------------
 * jQuery customfileinput plugin
 * Author: Scott Jehl, scott@filamentgroup.com
 * Copyright (c) 2009 Filament Group
 * licensed under MIT (filamentgroup.com/examples/mit-license.txt)
 * --------------------------------------------------------------------
 */
$.fn.customFileInput = function(){
	return $(this).each(function(){
	//apply events and styles for file input element
	var fileInput = $(this)
		.addClass('customfile-input') //add class for CSS
		.mouseover(function(){ upload.addClass('customfile-hover'); })
		.mouseout(function(){ upload.removeClass('customfile-hover'); })
		.focus(function(){
			upload.addClass('customfile-focus');
			fileInput.data('val', fileInput.val());
		})
		.blur(function(){
			upload.removeClass('customfile-focus');
			$(this).trigger('checkChange');
		 })
		 .bind('disable',function(){
		 	fileInput.attr('disabled',true);
			upload.addClass('customfile-disabled');
		})
		.bind('enable',function(){
			fileInput.removeAttr('disabled');
			upload.removeClass('customfile-disabled');
		})
		.bind('checkChange', function(){
			if(fileInput.val() && fileInput.val() != fileInput.data('val')){
				fileInput.trigger('change');
			}
		})
		.bind('change',function(){
			//get file name
			var fileName = $(this).val().split(/\\/).pop();
			//get file extension
			var fileExt = 'customfile-ext-' + fileName.split('.').pop().toLowerCase();
			//update the feedback
			uploadFeedback
				.text(fileName) //set feedback text to filename
				.removeClass(uploadFeedback.data('fileExt') || '') //remove any existing file extension class
				.addClass(fileExt) //add file extension class
				.data('fileExt', fileExt) //store file extension for class removal on next change
				.addClass('customfile-feedback-populated'); //add class to show populated state
			//change text of button
			uploadButton.text('Change');
		})
		.click(function(){ //for IE and Opera, make sure change fires after choosing a file, using an async callback
			fileInput.data('val', fileInput.val());
			setTimeout(function(){
				fileInput.trigger('checkChange');
			},100);
		});

	//create custom control container
	var upload = $('

');
	//create custom control button
	var uploadButton = $('Browse').appendTo(upload);
	//create custom control feedback
	var uploadFeedback = $('No file selected...').appendTo(upload);

	//match disabled state
	if(fileInput.is('[disabled]')){
		fileInput.trigger('disable');
	}

	//on mousemove, keep file input under the cursor to steal click
	upload
		.mousemove(function(e){
			fileInput.css({
				'left': e.pageX - upload.offset().left - fileInput.outerWidth() + 20, //position right side 20px right of cursor X)
				'top': e.pageY - upload.offset().top - $(window).scrollTop() - 3
			});
		})
		.insertAfter(fileInput); //insert after the input

	fileInput.appendTo(upload);

	});
};<|endoftext|>


<commit_before>exports.default = {
  tasks: function(api){
    return {
      // Should this node run a scheduler to promote delayed tasks?
      scheduler: false,
      // what queues should the taskProcessors work?
      queues: ['*'],
      // Verbosity of task logging
      verbose: true,
      // how long to sleep between jobs / scheduler checks
      timeout: 5000,
      // at minimum, how many parallel taskProcessors should this node spawn?
      // (have number > 0 to enable, and < 1 to disable)
      minTaskProcessors: 0,
      // at maximum, how many parallel taskProcessors should this node spawn?
      maxTaskProcessors: 0,
      // how often should we check the event loop to spawn more taskProcessors?
      checkTimeout: 500,
      // how many ms would constitue an event loop delay to halt taskProcessors spawning?
      maxEventLoopDelay: 5,
      // When we kill off a taskProcessor, should we disonnect that local redis connection?
      toDisconnectProcessors: true,
      // What redis server should we connect to for tasks / delayed jobs?
      redis: api.config.redis
    }
  }
}

exports.test = {
  tasks: function(api){
    return {
      timeout: 100,
      checkTimeout: 50
    }
  }
}
<commit_msg>Fix a typo<commit_after>exports.default = {
  tasks: function(api){
    return {
      // Should this node run a scheduler to promote delayed tasks?
      scheduler: false,
      // what queues should the taskProcessors work?
      queues: ['*'],
      // Verbosity of task logging
      verbose: true,
      // how long to sleep between jobs / scheduler checks
      timeout: 5000,
      // at minimum, how many parallel taskProcessors should this node spawn?
      // (have number > 0 to enable, and < 1 to disable)
      minTaskProcessors: 0,
      // at maximum, how many parallel taskProcessors should this node spawn?
      maxTaskProcessors: 0,
      // how often should we check the event loop to spawn more taskProcessors?
      checkTimeout: 500,
      // how many ms would constitue an event loop delay to halt taskProcessors spawning?
      maxEventLoopDelay: 5,
      // When we kill off a taskProcessor, should we disconnect that local redis connection?
      toDisconnectProcessors: true,
      // What redis server should we connect to for tasks / delayed jobs?
      redis: api.config.redis
    }
  }
}

exports.test = {
  tasks: function(api){
    return {
      timeout: 100,
      checkTimeout: 50
    }
  }
}
<|endoftext|>


<commit_before>//#include config_prod.js

// multiplies health fall and tending interval lengths (i.e. 1 is "normal", more is slower)
var trant_growth_multiplier = 10;

// parameters for animal sadness; see getSadnessMax in items/include/animal_sadness.js
// the resulting maximum is halved for public streets
var population_controls = {
	'npc_piggy': {
		per_width: 2,
		min_max: 6,
		max_max: 10
	},
	'npc_butterfly': {
		per_width: 1,
		min_max: 4,
		max_max: 6
	},
	'npc_chicken': {
		per_width: 1,
		min_max: 4,
		max_max: 6
	}
};

<commit_msg>assign all alpha testers to the same live help group<commit_after>//#include config_prod.js

// multiplies health fall and tending interval lengths (i.e. 1 is "normal", more is slower)
var trant_growth_multiplier = 10;

// parameters for animal sadness; see getSadnessMax in items/include/animal_sadness.js
// the resulting maximum is halved for public streets
var population_controls = {
	'npc_piggy': {
		per_width: 2,
		min_max: 6,
		max_max: 10
	},
	'npc_butterfly': {
		per_width: 1,
		min_max: 4,
		max_max: 6
	},
	'npc_chicken': {
		per_width: 1,
		min_max: 4,
		max_max: 6
	}
};

// assign everybody to the same live help group (no distinction by level for now)
this.live_help_groups = ['RA512UITCLA22AD'];
this.newbie_live_help_groups = ['RA512UITCLA22AD'];
<|endoftext|>


<commit_before>'use strict';

describe('Router', function() {

  beforeEach(function() {
    this.hash = window.location.hash;
  });

  afterEach(function() {
    quasar.stop.router();
    window.location.hash = this.hash;
  });

  var msToWaitBeforeHashChanges = 50;
  var routeOne = {
    path: '#/route-one',
    on: function() {}
  };
  var routeTwo = {
    path: '#/route-two',
    on: function() {}
  };
  var routeThree = {
    path: '#/route-three',
    on: function() {}
  };

  it('should be able to get all routes', function() {
    expect(quasar.get.all.routes).to.be.a('function');
    var result = quasar.get.all.routes();

    expect(result).to.be.an('array');
    expect(result).to.have.length(0);
  });

  it('should be able to destroy router', function() {
    expect(quasar.stop.router).to.be.a('function');
    expect(quasar.router.is.running).to.be.a('function');
    quasar.stop.router();
    expect(quasar.router.is.running()).to.be.equal(false);
  });

  it('should be able to add a route and verify it', function() {
    expect(quasar.add.route).to.be.a('function');
    expect(quasar.has.route).to.be.a('function');

    expect(quasar.get.all.routes()).to.have.length(0);
    quasar.add.route(routeOne);
    expect(quasar.has.route(routeOne.path)).to.equal(true);
    expect(quasar.get.all.routes()).to.have.length(1);

    quasar.add.route(routeTwo);
    expect(quasar.has.route(routeTwo.path)).to.equal(true);
    expect(quasar.get.all.routes()).to.have.length(2);

    expect(function() {
      quasar.add.route();
    }).to.throw(/Missing route/);

    expect(function() {
      quasar.add.route({});
    }).to.throw(/Route has no path/);
  });

  it('should say if route is already registered', function() {
    expect(function() {
      quasar.has.route();
    }).to.throw(/Missing path/);

    expect(quasar.has.route(routeOne.path)).to.equal(false);
    quasar.add.route(routeOne);
    expect(quasar.has.route(routeOne.path)).to.equal(true);
  });

  it('should be able to remove all routes', function() {
    expect(quasar.remove.all.routes).to.be.a('function');
    quasar.add.route(routeOne);
    quasar.remove.all.routes();
    expect(quasar.has.route(routeOne.path)).to.equal(false);
    expect(quasar.get.all.routes()).to.have.length(0);
  });

  it('should be able to remove a route', function() {
    expect(quasar.remove.route).to.be.a('function');
    quasar.add.route(routeOne);
    quasar.add.route(routeTwo);
    quasar.remove.route(routeOne.path);
    expect(quasar.has.route(routeOne.path)).to.equal(false);
    expect(quasar.has.route(routeTwo.path)).to.equal(true);
    expect(quasar.get.all.routes()).to.have.length(1);

    expect(function() {
      quasar.remove.route();
    }).to.throw(/Missing path/);
  });

  it('should throw error when trying to add same route', function() {
    quasar.add.route(routeOne);
    expect(function() {
      quasar.add.route(routeOne);
    }).to.throw(/Route already registered/);
  });

  it('should be able to retrieve route by path', function() {
    expect(quasar.get.route).to.be.a('function');
    expect(function() {
      quasar.get.route();
    }).to.throw(/Missing path/);

    var result = quasar.get.route(routeOne.path);

    expect(result).to.not.be.ok;

    quasar.add.route(routeOne);

    result = quasar.get.route(routeOne.path);

    expect(result).to.be.an('object');
    expect(result.path).to.equal(routeOne.path);
  });

  it('should be able to overwrite a route', function() {
    var newRoute = _.clone(routeOne, true);

    newRoute.on = function() { console.log('new route'); };
    expect(routeOne).to.not.deep.equal(newRoute);

    quasar.add.route(routeOne);
    quasar.overwrite.route(newRoute);

    expect(quasar.get.route(routeOne.path)).to.deep.equal(newRoute);

    expect(function() {
      quasar.overwrite.route();
    }).to.throw(/Missing route/);

    expect(function() {
      quasar.overwrite.route({});
    }).to.throw(/Route has no path/);

    expect(function() {
      quasar.overwrite.route({
        path: 'bogus',
        on: function() {}
      });
    }).to.throw(/Route not registered/);
  });

  it('should be able to navigate to route', function() {
    expect(quasar.navigate.to.route).to.be.a('function');
    quasar.navigate.to.route('#/quasar');

    expect(quasar.get.current.route).to.be.a('function');
    expect(quasar.get.current.route()).to.equal('#/quasar');

    expect(function() {
      quasar.navigate.to.route();
    }).to.throw(/Path missing/);

    expect(function() {
      quasar.navigate.to.route('/quasar');
    }).to.throw(/Route should start with #/);
  });

  it('should be able to initialize and trigger a route', function(done) {
    quasar.add.route({
      path: '#/',
      on: function() { done(); }
    });
    expect(quasar.start.router).to.be.a('function');
    quasar.start.router();
    expect(quasar.get.all.routes()).to.have.length(1);
  });

  it('should be able to trigger route', function(done) {
    var times = 0;

    quasar.add.route({
      path: '#/quasar',
      on: function() {
        expect(times).to.equal(0);
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/quasar');
  });

  it('should throw error when adding route with no methods', function() {
    expect(function() {
      quasar.add.route({path: '#/quasar'});
    }).to.throw(/Missing route methods/);
  });

  it('should be able to refresh a route', function(done) {
    var times = 0;

    expect(quasar.reload.current.route).to.be.a('function');
    quasar.add.route({
      path: '#/quasar',
      on: function() {
        times++;
        if (times == 2) {
          done();
        }
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/quasar');
    quasar.reload.current.route();
  });

  it('should be able to register and trigger route with parameters', function(done) {
    quasar.add.route({
      path: '#/page/:number',
      before: function() {
        expect(this.params).to.be.an('object');
        expect(this.params.number).to.equal('10');
        this.next();
      },
      on: function() {
        expect(this.params).to.be.an('object');
        expect(this.params.number).to.equal('10');
        this.next();
      },
      after: function() {
        expect(this.params).to.be.an('object');
        expect(this.params.number).to.equal('10');
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/page/10');
  });

  it('should be able to capture query string', function(done) {
    quasar.add.route({
      path: '#/page',
      before: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        expect(this.query.tset).to.equal('false');
        expect(this.query.empty).to.equal('');
        expect(this.query.empty2).to.equal('');
        expect(this.query.complex).to.equal(' this');
        this.next();
      },
      on: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        expect(this.query.tset).to.equal('false');
        expect(this.query.empty).to.equal('');
        expect(this.query.empty2).to.equal('');
        expect(this.query.complex).to.equal(' this');
        this.next();
      },
      after: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        expect(this.query.tset).to.equal('false');
        expect(this.query.empty).to.equal('');
        expect(this.query.empty2).to.equal('');
        expect(this.query.complex).to.equal(' this');
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/page?empty=&empty2&test=true&tset=false&complex=%20this');
  });

  it('should be able to capture the query string (scenario #2)', function(done) {
    quasar.navigate.to.route('#/?test=true');
    quasar.add.route({
      path: '#/',
      on: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        done();
      }
    });
    quasar.start.router();
  });

  it('should be able to provide the correct url property for before/on/after', function(done) {
    quasar.add.route({
      path: '#/page/:number',
      before: function() {
        expect(this.url).to.equal('#/page/10?think=big');
        this.next();
      },
      on: function() {
        expect(this.url).to.equal('#/page/10?think=big');
        this.next();
      },
      after: function() {
        expect(this.url).to.equal('#/page/10?think=big');
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/page/10?think=big');
  });

  it('should trigger multiple routes', function(done) {
    quasar.add.route({
      path: '#/route1',
      on: function() { quasar.navigate.to.route('#/route2'); }
    });
    quasar.add.route({
      path: '#/route2',
      on: function() { done(); }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/route1');
  });

  it('should trigger all route methods (only once)', function(done) {
    var times = 0;

    quasar.add.route({
      path: '#/route1',
      before: function() {
        times++;
        expect(times).to.equal(1);
        expect(this.next).to.be.a('function');
        this.next('before-result');
      },
      on: function(result) {
        times++;
        expect(times).to.equal(2);
        expect(result).to.equal('before-result');
        expect(this.next).to.be.a('function');
        this.next('on-result');
      },
      after: function(result) {
        times++;
        expect(times).to.equal(3);
        expect(result).to.equal('on-result');
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/route1');
  });

  it('should trigger routes correctly on browser back/forward', function(done) {
    quasar.add.route(routeOne);
    quasar.add.route(routeTwo);
    quasar.add.route(routeThree);
    quasar.start.router();

    quasar.navigate.to.route(routeOne.path);

    setTimeout(function() {
      quasar.navigate.to.route(routeTwo.path);
      setTimeout(function() {
        quasar.navigate.to.route(routeThree.path);
        setTimeout(function() {
          expect(quasar.get.current.route()).to.equal(routeThree.path);
          window.history.go(-1);
          setTimeout(function() {
            expect(quasar.get.current.route()).to.equal(routeTwo.path);
            window.history.go(-1);
            setTimeout(function() {
              expect(quasar.get.current.route()).to.equal(routeOne.path);
              window.history.go(1);
              setTimeout(function() {
                expect(quasar.get.current.route()).to.equal(routeTwo.path);
                window.history.go(1);
                setTimeout(function() {
                  expect(quasar.get.current.route()).to.equal(routeThree.path);
                  window.history.go(-1);
                  setTimeout(function() {
                    expect(quasar.get.current.route()).to.equal(routeTwo.path);
                    done();
                  }, msToWaitBeforeHashChanges);
                }, msToWaitBeforeHashChanges);
              }, msToWaitBeforeHashChanges);
            }, msToWaitBeforeHashChanges);
          }, msToWaitBeforeHashChanges);
        }, msToWaitBeforeHashChanges);
      }, msToWaitBeforeHashChanges);
    }, msToWaitBeforeHashChanges);
  });

  it('should call onRouteChange', function(done) {
    quasar.add.route(routeOne);
    quasar.start.router({
      onRouteChange: function(route) {
        expect(route).to.be.an('object');
        expect(route.path).to.be.ok;
        done();
      }
    });
    quasar.navigate.to.route(routeOne.path);
  });

  it('should call onRouteNotFound', function(done) {
    quasar.start.router({
      onRouteNotFound: function(route) {
        expect(route).to.be.an('array');
        done();
      }
    });
    quasar.navigate.to.route(routeOne.path);
  });

  it('should log about no valid route when onRouteNotFound() is not specified', function(done) {
    sinon.spy(window.console, 'log');
    quasar.start.router();
    setTimeout(function() {
      expect(window.console.log).to.have.been.calledOnce;
      expect(window.console.log).to.have.been.calledWithMatch('No valid route');
      window.console.log.restore();
      done();
    }, msToWaitBeforeHashChanges);
  });

});
<commit_msg>test: Improve one router test.<commit_after>'use strict';

describe('Router', function() {

  beforeEach(function() {
    this.hash = window.location.hash;
  });

  afterEach(function() {
    quasar.stop.router();
    window.location.hash = this.hash;
  });

  var msToWaitBeforeHashChanges = 50;
  var routeOne = {
    path: '#/route-one',
    on: function() {}
  };
  var routeTwo = {
    path: '#/route-two',
    on: function() {}
  };
  var routeThree = {
    path: '#/route-three',
    on: function() {}
  };

  it('should be able to get all routes', function() {
    expect(quasar.get.all.routes).to.be.a('function');
    var result = quasar.get.all.routes();

    expect(result).to.be.an('array');
    expect(result).to.have.length(0);
  });

  it('should be able to destroy router', function() {
    expect(quasar.stop.router).to.be.a('function');
    expect(quasar.router.is.running).to.be.a('function');
    quasar.stop.router();
    expect(quasar.router.is.running()).to.be.equal(false);
  });

  it('should be able to add a route and verify it', function() {
    expect(quasar.add.route).to.be.a('function');
    expect(quasar.has.route).to.be.a('function');

    expect(quasar.get.all.routes()).to.have.length(0);
    quasar.add.route(routeOne);
    expect(quasar.has.route(routeOne.path)).to.equal(true);
    expect(quasar.get.all.routes()).to.have.length(1);

    quasar.add.route(routeTwo);
    expect(quasar.has.route(routeTwo.path)).to.equal(true);
    expect(quasar.get.all.routes()).to.have.length(2);

    expect(function() {
      quasar.add.route();
    }).to.throw(/Missing route/);

    expect(function() {
      quasar.add.route({});
    }).to.throw(/Route has no path/);
  });

  it('should say if route is already registered', function() {
    expect(function() {
      quasar.has.route();
    }).to.throw(/Missing path/);

    expect(quasar.has.route(routeOne.path)).to.equal(false);
    quasar.add.route(routeOne);
    expect(quasar.has.route(routeOne.path)).to.equal(true);
  });

  it('should be able to remove all routes', function() {
    expect(quasar.remove.all.routes).to.be.a('function');
    quasar.add.route(routeOne);
    quasar.remove.all.routes();
    expect(quasar.has.route(routeOne.path)).to.equal(false);
    expect(quasar.get.all.routes()).to.have.length(0);
  });

  it('should be able to remove a route', function() {
    expect(quasar.remove.route).to.be.a('function');
    quasar.add.route(routeOne);
    quasar.add.route(routeTwo);
    quasar.remove.route(routeOne.path);
    expect(quasar.has.route(routeOne.path)).to.equal(false);
    expect(quasar.has.route(routeTwo.path)).to.equal(true);
    expect(quasar.get.all.routes()).to.have.length(1);

    expect(function() {
      quasar.remove.route();
    }).to.throw(/Missing path/);
  });

  it('should throw error when trying to add same route', function() {
    quasar.add.route(routeOne);
    expect(function() {
      quasar.add.route(routeOne);
    }).to.throw(/Route already registered/);
  });

  it('should be able to retrieve route by path', function() {
    expect(quasar.get.route).to.be.a('function');
    expect(function() {
      quasar.get.route();
    }).to.throw(/Missing path/);

    var result = quasar.get.route(routeOne.path);

    expect(result).to.not.be.ok;

    quasar.add.route(routeOne);

    result = quasar.get.route(routeOne.path);

    expect(result).to.be.an('object');
    expect(result.path).to.equal(routeOne.path);
  });

  it('should be able to overwrite a route', function() {
    var newRoute = _.clone(routeOne, true);

    newRoute.on = function() { console.log('new route'); };
    expect(routeOne).to.not.deep.equal(newRoute);

    quasar.add.route(routeOne);
    quasar.overwrite.route(newRoute);

    expect(quasar.get.route(routeOne.path)).to.deep.equal(newRoute);

    expect(function() {
      quasar.overwrite.route();
    }).to.throw(/Missing route/);

    expect(function() {
      quasar.overwrite.route({});
    }).to.throw(/Route has no path/);

    expect(function() {
      quasar.overwrite.route({
        path: 'bogus',
        on: function() {}
      });
    }).to.throw(/Route not registered/);
  });

  it('should be able to navigate to route', function() {
    expect(quasar.navigate.to.route).to.be.a('function');
    quasar.navigate.to.route('#/quasar');

    expect(quasar.get.current.route).to.be.a('function');
    expect(quasar.get.current.route()).to.equal('#/quasar');

    expect(function() {
      quasar.navigate.to.route();
    }).to.throw(/Path missing/);

    expect(function() {
      quasar.navigate.to.route('/quasar');
    }).to.throw(/Route should start with #/);
  });

  it('should be able to initialize and trigger a route', function(done) {
    quasar.add.route({
      path: '#/',
      on: function() { done(); }
    });
    expect(quasar.start.router).to.be.a('function');
    quasar.start.router();
    expect(quasar.get.all.routes()).to.have.length(1);
  });

  it('should be able to trigger route', function(done) {
    var times = 0;

    quasar.add.route({
      path: '#/quasar',
      on: function() {
        expect(times).to.equal(0);
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/quasar');
  });

  it('should throw error when adding route with no methods', function() {
    expect(function() {
      quasar.add.route({path: '#/quasar'});
    }).to.throw(/Missing route methods/);
  });

  it('should be able to refresh a route', function(done) {
    var times = 0;

    expect(quasar.reload.current.route).to.be.a('function');
    quasar.add.route({
      path: '#/quasar',
      on: function() {
        times++;
        if (times == 2) {
          done();
        }
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/quasar');
    quasar.reload.current.route();
  });

  it('should be able to register and trigger route with parameters', function(done) {
    quasar.add.route({
      path: '#/page/:number',
      before: function() {
        expect(this.params).to.be.an('object');
        expect(this.params.number).to.equal('10');
        this.next();
      },
      on: function() {
        expect(this.params).to.be.an('object');
        expect(this.params.number).to.equal('10');
        this.next();
      },
      after: function() {
        expect(this.params).to.be.an('object');
        expect(this.params.number).to.equal('10');
        this.next();
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/page/10');
  });

  it('should be able to capture query string', function(done) {
    quasar.add.route({
      path: '#/page',
      before: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        expect(this.query.tset).to.equal('false');
        expect(this.query.empty).to.equal('');
        expect(this.query.empty2).to.equal('');
        expect(this.query.complex).to.equal(' this');
        this.next();
      },
      on: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        expect(this.query.tset).to.equal('false');
        expect(this.query.empty).to.equal('');
        expect(this.query.empty2).to.equal('');
        expect(this.query.complex).to.equal(' this');
        this.next();
      },
      after: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        expect(this.query.tset).to.equal('false');
        expect(this.query.empty).to.equal('');
        expect(this.query.empty2).to.equal('');
        expect(this.query.complex).to.equal(' this');
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/page?empty=&empty2&test=true&tset=false&complex=%20this');
  });

  it('should be able to capture the query string (scenario #2)', function(done) {
    quasar.navigate.to.route('#/?test=true');
    quasar.add.route({
      path: '#/',
      on: function() {
        expect(this.query).to.be.an('object');
        expect(this.query.test).to.equal('true');
        done();
      }
    });
    quasar.start.router();
  });

  it('should be able to provide the correct url property for before/on/after', function(done) {
    quasar.add.route({
      path: '#/page/:number',
      before: function() {
        expect(this.url).to.equal('#/page/10?think=big');
        this.next();
      },
      on: function() {
        expect(this.url).to.equal('#/page/10?think=big');
        this.next();
      },
      after: function() {
        expect(this.url).to.equal('#/page/10?think=big');
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/page/10?think=big');
  });

  it('should trigger multiple routes', function(done) {
    quasar.add.route({
      path: '#/route1',
      on: function() { quasar.navigate.to.route('#/route2'); }
    });
    quasar.add.route({
      path: '#/route2',
      on: function() { done(); }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/route1');
  });

  it('should trigger all route methods (only once)', function(done) {
    var times = 0;

    quasar.add.route({
      path: '#/route1',
      before: function() {
        times++;
        expect(times).to.equal(1);
        expect(this.next).to.be.a('function');
        this.next('before-result');
      },
      on: function(result) {
        times++;
        expect(times).to.equal(2);
        expect(result).to.equal('before-result');
        expect(this.next).to.be.a('function');
        this.next('on-result');
      },
      after: function(result) {
        times++;
        expect(times).to.equal(3);
        expect(result).to.equal('on-result');
        done();
      }
    });
    quasar.start.router();
    quasar.navigate.to.route('#/route1');
  });

  it('should trigger routes correctly on browser back/forward', function(done) {
    quasar.add.route(routeOne);
    quasar.add.route(routeTwo);
    quasar.add.route(routeThree);
    quasar.start.router();

    quasar.navigate.to.route(routeOne.path);

    setTimeout(function() {
      quasar.navigate.to.route(routeTwo.path);
      setTimeout(function() {
        quasar.navigate.to.route(routeThree.path);
        setTimeout(function() {
          expect(quasar.get.current.route()).to.equal(routeThree.path);
          window.history.go(-1);
          setTimeout(function() {
            expect(quasar.get.current.route()).to.equal(routeTwo.path);
            window.history.go(-1);
            setTimeout(function() {
              expect(quasar.get.current.route()).to.equal(routeOne.path);
              window.history.go(1);
              setTimeout(function() {
                expect(quasar.get.current.route()).to.equal(routeTwo.path);
                window.history.go(1);
                setTimeout(function() {
                  expect(quasar.get.current.route()).to.equal(routeThree.path);
                  window.history.go(-1);
                  setTimeout(function() {
                    expect(quasar.get.current.route()).to.equal(routeTwo.path);
                    done();
                  }, msToWaitBeforeHashChanges);
                }, msToWaitBeforeHashChanges);
              }, msToWaitBeforeHashChanges);
            }, msToWaitBeforeHashChanges);
          }, msToWaitBeforeHashChanges);
        }, msToWaitBeforeHashChanges);
      }, msToWaitBeforeHashChanges);
    }, msToWaitBeforeHashChanges);
  });

  it('should call onRouteChange', function(done) {
    quasar.add.route(routeOne);
    quasar.start.router({
      onRouteChange: function(route) {
        expect(route).to.be.an('object');
        expect(route.path).to.be.ok;
        done();
      }
    });
    quasar.navigate.to.route(routeOne.path);
  });

  it('should call onRouteNotFound', function(done) {
    quasar.start.router({
      onRouteNotFound: function(route) {
        expect(route).to.be.an('array');
        done();
      }
    });
    quasar.navigate.to.route(routeOne.path);
  });

  it('should log about no valid route when onRouteNotFound() is not specified', function(done) {
    sinon.spy(window.console, 'log');
    quasar.start.router();
    setTimeout(function() {
      expect(window.console.log).to.have.been.calledOnce;
      expect(window.console.log).to.have.been.calledWithMatch('No valid route');
      window.console.log.restore();
      done();
    }, msToWaitBeforeHashChanges);
  });

});
<|endoftext|>


<commit_before>var Login = $.import("de.linuxdozent.gittest.test.lib", "Login");
var OData = $.import("de.linuxdozent.gittest.test.lib", "OData");

var loginResult;
var header;
var discountCodeCreate = {
    "ID": "1",
    "UserName": "BSCUSTOMER",
    "DiscountValue": 10,
    "SHA256HASH": "",
    "Redeemed": "N"
};
var discountCodeService = "/de/linuxdozent/gittest/odata/service.xsodata/DiscountCode";

describe("Admin actions", function() {

    it("should login BSADMIN and get csrfToken", function() {
        loginResult = Login.getCSRFtokenAndLogin("BSADMIN", Login.newpwd);
        header = OData.prepareRequestHeader(loginResult.csrf);
    });

    it("should create discount code for BSCUSTOMER", function() {
        var response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
        if (response.status === 400) {
            expect(response).toBeNull();
        }
        expect(response.status).toBe($.net.http.CREATED);
    });

    it("should create discount code for other user", function() {
        // Read which additional customer exist
        var service = encodeURI("/de/linuxdozent/gittest/odata/service.xsodata/Customer?$filter=UserName ne '" + discountCodeCreate.UserName + "'");
        var response = jasmine.callHTTPService(service, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
		if (responseBody.d.results.length > 0) {
            discountCodeCreate.ID = "3";
            discountCodeCreate.UserName = responseBody.d.results[0].UserName;
            response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
            expect(response.status).toBe($.net.http.CREATED);
		}
    });

    it("should get a list of discounts but not the code", function() {
        var DiscountCodeURL = encodeURI( discountCodeService + "?$filter=UserName eq '" + discountCodeCreate.UserName + "'" );
        var response = jasmine.callHTTPService(DiscountCodeURL, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
        expect(responseBody.d.results[0].UserName).toBe(discountCodeCreate.UserName);
    });

    it("should logout BSADMIN", function() {
        Login.logout(loginResult.csrf, loginResult.cookies);
        Login.checkSession();
    });
});<commit_msg>Debug discount code creation<commit_after>var Login = $.import("de.linuxdozent.gittest.test.lib", "Login");
var OData = $.import("de.linuxdozent.gittest.test.lib", "OData");

var loginResult;
var header;
var discountCodeCreate = {
    "ID": "1",
    "UserName": "BSCUSTOMER",
    "DiscountValue": 10,
    "SHA256HASH": "",
    "Redeemed": "N"
};
var discountCodeService = "/de/linuxdozent/gittest/odata/service.xsodata/DiscountCode";

describe("Admin actions", function() {

    it("should login BSADMIN and get csrfToken", function() {
        loginResult = Login.getCSRFtokenAndLogin("BSADMIN", Login.newpwd);
        header = OData.prepareRequestHeader(loginResult.csrf);
    });

    it("should create discount code for BSCUSTOMER", function() {
        var response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
        if (response.status === 400) {
            expect(response.toString()).toBeNull();
        }
        expect(response.status).toBe($.net.http.CREATED);
    });

    it("should create discount code for other user", function() {
        // Read which additional customer exist
        var service = encodeURI("/de/linuxdozent/gittest/odata/service.xsodata/Customer?$filter=UserName ne '" + discountCodeCreate.UserName + "'");
        var response = jasmine.callHTTPService(service, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
		if (responseBody.d.results.length > 0) {
            discountCodeCreate.ID = "3";
            discountCodeCreate.UserName = responseBody.d.results[0].UserName;
            response = jasmine.callHTTPService(discountCodeService, $.net.http.POST, JSON.stringify(discountCodeCreate), header, loginResult.cookies);
            expect(response.status).toBe($.net.http.CREATED);
		}
    });

    it("should get a list of discounts but not the code", function() {
        var DiscountCodeURL = encodeURI( discountCodeService + "?$filter=UserName eq '" + discountCodeCreate.UserName + "'" );
        var response = jasmine.callHTTPService(DiscountCodeURL, $.net.http.GET, undefined, header, loginResult.cookies);
        expect(response.status).toBe($.net.http.OK);
		var responseBody = OData.getResponseBody(response);
        expect(responseBody.d.results[0].UserName).toBe(discountCodeCreate.UserName);
    });

    it("should logout BSADMIN", function() {
        Login.logout(loginResult.csrf, loginResult.cookies);
        Login.checkSession();
    });
});<|endoftext|>