<commit_before>var preference
var ipc = require('electron').ipcRenderer
var modifiers = require('emojilib').fitzpatrick_scale_modifiers

var defaultPreference = {
  'open-window-shortcut': 'ctrl+shift+space',
  'emoji-size': '20',
  'open-at-login': false,
  'skin-tone-modifier': ''
}

var preferenceNames = {
  'open-window-shortcut': 'Mojibar shortcut',
  'emoji-size': 'Emoji font size',
  'open-at-login': 'Start Mojibar at login',
  'skin-tone-modifier': 'Skin tone modifier'
}

var applyPreferences = function (preference, initialization) {
  window.localStorage.setItem('preference', JSON.stringify(preference))

  ipc.send('update-preference', preference, initialization)
  var style = document.createElement('style')
  style.innerText = '.emoji { font-size: ' + preference['emoji-size'] + 'px; width: ' + (Number(preference['emoji-size']) + 20) + 'px; height: ' + (Number(preference['emoji-size']) + 20) + 'px; }'
  document.body.appendChild(style)
  // Update skin tone setting
  search(' ')
}

var savePreference = function (event) {
  event.preventDefault()

  Object.keys(preference).forEach(function (key) {
    var el = document.getElementById(key)
    preference[key] = el.nodeName === 'INPUT' && el.type === 'checkbox' ? el.checked : el.value
  })

  applyPreferences(preference)
}

if (window.localStorage.getItem('preference')) {
  preference = JSON.parse(window.localStorage.getItem('preference'))
  Object.keys(defaultPreference).forEach(function (key) {
    if (!preference[key]) preference[key] = defaultPreference[key]
  })
} else {
  preference = defaultPreference
}

applyPreferences(preference, true)

ipc.on('open-preference', function (event, message) {
  togglePreferencePanel()
})

ipc.on('preference-updated', function (event, result, initialization) {
  if (result) {
    if (!initialization) {
      window.alert('Saved!')
      togglePreferencePanel()
    }
  } else {
    window.alert('Something went wrong, likely related to keybindings. See http://electron.atom.io/docs/v0.36.5/api/accelerator/ for more.')
  }
})

var togglePreferencePanel = function () {
  if (document.body.classList.contains('on-preference')) {
    document.body.classList.remove('on-preference')
    document.getElementById('js-preference-panel').remove()
  } else {
    var preference = JSON.parse(window.localStorage.getItem('preference'))
    var panel = document.createElement('div')

    panel.classList.add('preference-panel')
    panel.id = 'js-preference-panel'
    var html = '<form>'
    Object.keys(preferenceNames).forEach(function (key) {
      html += '
'
      if (typeof preference[key] === 'boolean') {
        html += ''
        html += '<input type="checkbox" id="' + key + '"' + (preference[key] ? 'checked' : '') + '>'
        html += preferenceNames[key]
        html += ''
      } else if (key === 'skin-tone-modifier') {
        html += ''
        html += preferenceNames[key]
        html += ''
        html += '<select id="' + key + '">>'
        html += `<option value="">None</option>`
        modifiers.forEach(function (modifier) {
          html += `<option value="${modifier}" ${preference[key] === modifier ? 'selected' : ''}>${modifier}</option>`
        })
        html += '</select>'
        html += ''
      } else {
        html += ''
        html += preferenceNames[key]
        html += ''
        html += '<input type="text" id="' + key + '" value="' + preference[key] + '" placeholder="' + defaultPreference[key] + '">'
      }
      html += '
'
    })
    html += '<button type="submit">Save</button>'
    html += '</form>'
    panel.innerHTML += html

    panel.getElementsByTagName('form')[0].onsubmit = savePreference

    document.body.classList.add('on-preference')
    document.body.appendChild(panel)
    panel.getElementsByTagName('input')[0].focus()
  }
}
<commit_msg>window.search<commit_after>var preference
var ipc = require('electron').ipcRenderer
var modifiers = require('emojilib').fitzpatrick_scale_modifiers

var defaultPreference = {
  'open-window-shortcut': 'ctrl+shift+space',
  'emoji-size': '20',
  'open-at-login': false,
  'skin-tone-modifier': ''
}

var preferenceNames = {
  'open-window-shortcut': 'Mojibar shortcut',
  'emoji-size': 'Emoji font size',
  'open-at-login': 'Start Mojibar at login',
  'skin-tone-modifier': 'Skin tone modifier'
}

var applyPreferences = function (preference, initialization) {
  window.localStorage.setItem('preference', JSON.stringify(preference))

  ipc.send('update-preference', preference, initialization)
  var style = document.createElement('style')
  style.innerText = '.emoji { font-size: ' + preference['emoji-size'] + 'px; width: ' + (Number(preference['emoji-size']) + 20) + 'px; height: ' + (Number(preference['emoji-size']) + 20) + 'px; }'
  document.body.appendChild(style)
  // Update skin tone setting
  window.search(' ')
}

var savePreference = function (event) {
  event.preventDefault()

  Object.keys(preference).forEach(function (key) {
    var el = document.getElementById(key)
    preference[key] = el.nodeName === 'INPUT' && el.type === 'checkbox' ? el.checked : el.value
  })

  applyPreferences(preference)
}

if (window.localStorage.getItem('preference')) {
  preference = JSON.parse(window.localStorage.getItem('preference'))
  Object.keys(defaultPreference).forEach(function (key) {
    if (!preference[key]) preference[key] = defaultPreference[key]
  })
} else {
  preference = defaultPreference
}

applyPreferences(preference, true)

ipc.on('open-preference', function (event, message) {
  togglePreferencePanel()
})

ipc.on('preference-updated', function (event, result, initialization) {
  if (result) {
    if (!initialization) {
      window.alert('Saved!')
      togglePreferencePanel()
    }
  } else {
    window.alert('Something went wrong, likely related to keybindings. See http://electron.atom.io/docs/v0.36.5/api/accelerator/ for more.')
  }
})

var togglePreferencePanel = function () {
  if (document.body.classList.contains('on-preference')) {
    document.body.classList.remove('on-preference')
    document.getElementById('js-preference-panel').remove()
  } else {
    var preference = JSON.parse(window.localStorage.getItem('preference'))
    var panel = document.createElement('div')

    panel.classList.add('preference-panel')
    panel.id = 'js-preference-panel'
    var html = '<form>'
    Object.keys(preferenceNames).forEach(function (key) {
      html += '
'
      if (typeof preference[key] === 'boolean') {
        html += ''
        html += '<input type="checkbox" id="' + key + '"' + (preference[key] ? 'checked' : '') + '>'
        html += preferenceNames[key]
        html += ''
      } else if (key === 'skin-tone-modifier') {
        html += ''
        html += preferenceNames[key]
        html += ''
        html += '<select id="' + key + '">>'
        html += `<option value="">None</option>`
        modifiers.forEach(function (modifier) {
          html += `<option value="${modifier}" ${preference[key] === modifier ? 'selected' : ''}>${modifier}</option>`
        })
        html += '</select>'
        html += ''
      } else {
        html += ''
        html += preferenceNames[key]
        html += ''
        html += '<input type="text" id="' + key + '" value="' + preference[key] + '" placeholder="' + defaultPreference[key] + '">'
      }
      html += '
'
    })
    html += '<button type="submit">Save</button>'
    html += '</form>'
    panel.innerHTML += html

    panel.getElementsByTagName('form')[0].onsubmit = savePreference

    document.body.classList.add('on-preference')
    document.body.appendChild(panel)
    panel.getElementsByTagName('input')[0].focus()
  }
}
<|endoftext|>


<commit_before><commit_msg>Added redirect function.<commit_after><|endoftext|>


<commit_before>(function () {

  var nimbleBar = $('

', {id: 'nimble-bar'});
  nimbleBar.append($('<input>', {class: 'nimble-input mousetrap'}));
  $('body').append(nimbleBar);
  window.nimbleBar = nimbleBar;

  var shown = false;

  function showNimbleBar () {

    nimbleBar.addClass('visible animated bounceInUp');
    shown = true;
    setTimeout(function (argument) {
      nimbleBar.removeClass('bounceInUp');
      $('.nimble-input').focus();
      $('.nimble-input').val('');
    }, 750);
  }

  function hideNimbleBar () {

    nimbleBar.addClass('bounceOutDown');
    shown = false;
    setTimeout(function () {
      $('.nimble-input').blur();
      $('.nimble-input').val('');
      nimbleBar.removeClass('visible animated bounceOutDown');
    }, 750);
  }

  Mousetrap.bind('n', function(e) {
    e.preventDefault();
    shown ? hideNimbleBar() : showNimbleBar();
  });

  Mousetrap.bind('esc', function(e) {
    hideNimbleBar();
  });

  Mousetrap.bind('e', function(e) {
    console.log('Nimble triggered');

    // This is a data object before it enters the current pipeline stage.
    var testObj = {
      'type': '"url"',
      'data': '"http://www.google.com"',

      'protocol': '"http"'
    };

    // Matching the object against the recipe manifest yields a list of
    // compatible recipes that may be applied.
    var matchResults = router.matchObject(testObj);
    console.log(matchResults);

    // Via some UI, the user decides on a recipe to apply.
    var selectedMatch = matchResults[0];

    // We apply the recipe to the data object.
    // In reality, the resultant object should be passed back to the pipeline,
    // until we reach the last stage, at which point, the result is discarded.
    selectedMatch.callback(testObj).then(function(result) {
      console.log(result);
    });
  });

  var plugins = [
    'Googl',
    'Facebook'
  ];

  /* Creates instances of recipe workers for each entry in a recipe manifest.
   */
  var initPlugins = function(plugins) {
    var recipes = [];
    for (var i = 0; i < plugins.length; i++) {
      var construct = plugins[i] + '()';
      var pluginRef = eval(construct);
      var supportedRecipes = pluginRef.getRecipes();
      recipes = recipes.concat(supportedRecipes);
    }
    return recipes;
  };

  var recipes = initPlugins(plugins);
  var router = Router(recipes);
  console.log('Nimble finish loading');
})();
<commit_msg>Added demo for init<commit_after>(function () {

  var nimbleBar = $('

', {id: 'nimble-bar'});
  nimbleBar.append($('<input>', {class: 'nimble-input mousetrap'}));
  $('body').append(nimbleBar);
  window.nimbleBar = nimbleBar;

  var shown = false;

  function showNimbleBar () {

    nimbleBar.addClass('visible animated bounceInUp');
    shown = true;
    setTimeout(function (argument) {
      nimbleBar.removeClass('bounceInUp');
      $('.nimble-input').focus();
      $('.nimble-input').val('');
    }, 750);
  }

  function hideNimbleBar () {

    nimbleBar.addClass('bounceOutDown');
    shown = false;
    setTimeout(function () {
      $('.nimble-input').blur();
      $('.nimble-input').val('');
      nimbleBar.removeClass('visible animated bounceOutDown');
    }, 750);
  }

  Mousetrap.bind('n', function(e) {
    e.preventDefault();
    shown ? hideNimbleBar() : showNimbleBar();
    this.nimble.getData(function(data) {console.log(data);});
  });

  Mousetrap.bind('esc', function(e) {
    hideNimbleBar();
  });

  Mousetrap.bind('e', function(e) {
    console.log('Nimble triggered');

    // This is a data object before it enters the current pipeline stage.
    var testObj = {
      'type': '"url"',
      'data': '"http://www.google.com"',

      'protocol': '"http"'
    };

    // Matching the object against the recipe manifest yields a list of
    // compatible recipes that may be applied.
    var matchResults = router.matchObject(testObj);
    console.log(matchResults);

    // Via some UI, the user decides on a recipe to apply.
    var selectedMatch = matchResults[0];

    // We apply the recipe to the data object.
    // In reality, the resultant object should be passed back to the pipeline,
    // until we reach the last stage, at which point, the result is discarded.
    selectedMatch.callback(testObj).then(function(result) {
      console.log(result);
    });
  });

  var plugins = [
    'Googl',
    'Facebook'
  ];

  /* Creates instances of recipe workers for each entry in a recipe manifest.
   */
  var initPlugins = function(plugins) {
    var recipes = [];
    for (var i = 0; i < plugins.length; i++) {
      var construct = plugins[i] + '()';
      var pluginRef = eval(construct);
      var supportedRecipes = pluginRef.getRecipes();
      recipes = recipes.concat(supportedRecipes);
    }
    return recipes;
  };

  var recipes = initPlugins(plugins);
  var router = Router(recipes);
  console.log('Nimble finish loading');
})();
<|endoftext|>


<commit_before>define([
    'app/config',
    'app/mapControls/LayerControls',
    'app/mapControls/LayerItem',
    'app/project/FeaturesGrid',
    'app/project/ProjectDetails',

    'dijit/_TemplatedMixin',
    'dijit/_WidgetBase',

    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/dom-class',
    'dojo/dom-style',
    'dojo/on',
    'dojo/on/throttle',
    'dojo/request/xhr',
    'dojo/text!app/project/templates/ProjectContainer.html',
    'dojo/topic',
    'dojo/window'
], function (
    config,
    LayerControls,
    LayerItem,
    FeaturesGrid,
    ProjectDetails,

    _TemplatedMixin,
    _WidgetBase,

    declare,
    lang,
    domClass,
    domStyle,
    on,
    throttle,
    xhr,
    template,
    topic,
    win
) {
    return declare([_WidgetBase, _TemplatedMixin], {
        // description:
        //      The container to hold and manage all the widgets for working with projects
        templateString: template,
        baseClass: 'project-container',

        // Properties to be sent into constructor

        postCreate: function () {
            // summary:
            //      Overrides method of same name in dijit._Widget.
            console.log('app.project.ProjectContainer::postCreate', arguments);

            this.childWidgets = [];

            this.setupConnections();

            var referenceLayers = new LayerControls({
                layers: [
                    new LayerItem({name: 'GNIS'}),
                    new LayerItem({name: 'HUC'})
                ]
            }, this.referenceLayerNode);

            this.childWidgets.push(referenceLayers);

            this._resetHeight();

            this.inherited(arguments);
        },
        setupConnections: function () {
            // summary:
            //      wire events, and such
            console.log('app.project.ProjectContainer::setupConnections', arguments);

            this.own(
                topic.subscribe(config.topics.projectIdsChanged,
                     lang.hitch(this, 'showDetailsForProject')),
                on(window, throttle('resize', 1000), lang.hitch(this, '_resetHeight'))
            );
        },
        showDetailsForProject: function (ids) {
            // summary:
            //      determines whether to to query for projects and show itself
            // ids: an array of project id's
            console.log('app.project.ProjectContainer::showDetailsForProject', arguments);

            if (!ids || ids.length !== 1) {
                return;
            }

            this._queryForProjectDetails(ids[0]).then(
                lang.hitch(this, '_updateDetails'),
                function handleError(response) {
                    console.warn('wri web api request failed ' + response);
                });
        },
        _queryForProjectDetails: function (id) {
            // summary:
            //      query api for project informations
            // id
            console.log('app.project.ProjectContainer::_queryForProjectDetails', arguments);

            return xhr.get(config.urls.api + '/project/' + id, {
                handleAs: 'json',
                headers: { 'Accept': 'application/json' }
            });
        },
        _updateDetails: function (response) {
            // summary:
            //      refreshes the widget data for a new project
            // response
            console.log('app.project.ProjectContainer::_updateDetails', arguments);

            if (this.projectDetails) {
                this.projectDetails.destroy();
                this.featuresGrid.destroy();

                this.projectDetails = null;
                this.featuresGrid = null;
            }

            this.projectDetails = new ProjectDetails(response.project).placeAt(this.detailsNode);
            this.featuresGrid = new FeaturesGrid({
                features: response.features
            }).placeAt(this.featureGridNode);

            domClass.remove(this.domNode, 'hidden');

            this.projectDetails.startup();
            this.featuresGrid.startup();
            this.featuresGrid.grid.startup();
        },
        _resetHeight: function () {
            // summary:
            //      resizes the div to fit the screen on window resize
            console.log('app.project.ProjectContainer::_resetHeight', arguments);

            var maxHeight = win.getBox().h - 241;
            domStyle.set(this.domNode, 'maxHeight', maxHeight + 'px');
        },
        startup: function () {
            // summary:
            //      Fires after postCreate when all of the child widgets are finished laying out.
            console.log('app.project.ProjectContainer::startup', arguments);

            var that = this;
            this.childWidgets.forEach(function (widget) {
                that.own(widget);
                widget.startup();
            });

            this.inherited(arguments);
        }
    });
});
<commit_msg>change container height a bit.<commit_after>define([
    'app/config',
    'app/mapControls/LayerControls',
    'app/mapControls/LayerItem',
    'app/project/FeaturesGrid',
    'app/project/ProjectDetails',

    'dijit/_TemplatedMixin',
    'dijit/_WidgetBase',

    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/dom-class',
    'dojo/dom-style',
    'dojo/on',
    'dojo/on/throttle',
    'dojo/request/xhr',
    'dojo/text!app/project/templates/ProjectContainer.html',
    'dojo/topic',
    'dojo/window'
], function (
    config,
    LayerControls,
    LayerItem,
    FeaturesGrid,
    ProjectDetails,

    _TemplatedMixin,
    _WidgetBase,

    declare,
    lang,
    domClass,
    domStyle,
    on,
    throttle,
    xhr,
    template,
    topic,
    win
) {
    return declare([_WidgetBase, _TemplatedMixin], {
        // description:
        //      The container to hold and manage all the widgets for working with projects
        templateString: template,
        baseClass: 'project-container',

        // Properties to be sent into constructor

        postCreate: function () {
            // summary:
            //      Overrides method of same name in dijit._Widget.
            console.log('app.project.ProjectContainer::postCreate', arguments);

            this.childWidgets = [];

            this.setupConnections();

            var referenceLayers = new LayerControls({
                layers: [
                    new LayerItem({name: 'GNIS'}),
                    new LayerItem({name: 'HUC'})
                ]
            }, this.referenceLayerNode);

            this.childWidgets.push(referenceLayers);

            this._resetHeight();

            this.inherited(arguments);
        },
        setupConnections: function () {
            // summary:
            //      wire events, and such
            console.log('app.project.ProjectContainer::setupConnections', arguments);

            this.own(
                topic.subscribe(config.topics.projectIdsChanged,
                     lang.hitch(this, 'showDetailsForProject')),
                on(window, throttle('resize', 1000), lang.hitch(this, '_resetHeight'))
            );
        },
        showDetailsForProject: function (ids) {
            // summary:
            //      determines whether to to query for projects and show itself
            // ids: an array of project id's
            console.log('app.project.ProjectContainer::showDetailsForProject', arguments);

            if (!ids || ids.length !== 1) {
                return;
            }

            this._queryForProjectDetails(ids[0]).then(
                lang.hitch(this, '_updateDetails'),
                function handleError(response) {
                    console.warn('wri web api request failed ' + response);
                });
        },
        _queryForProjectDetails: function (id) {
            // summary:
            //      query api for project informations
            // id
            console.log('app.project.ProjectContainer::_queryForProjectDetails', arguments);

            return xhr.get(config.urls.api + '/project/' + id, {
                handleAs: 'json',
                headers: { 'Accept': 'application/json' }
            });
        },
        _updateDetails: function (response) {
            // summary:
            //      refreshes the widget data for a new project
            // response
            console.log('app.project.ProjectContainer::_updateDetails', arguments);

            if (this.projectDetails) {
                this.projectDetails.destroy();
                this.featuresGrid.destroy();

                this.projectDetails = null;
                this.featuresGrid = null;
            }

            this.projectDetails = new ProjectDetails(response.project).placeAt(this.detailsNode);
            this.featuresGrid = new FeaturesGrid({
                features: response.features
            }).placeAt(this.featureGridNode);

            domClass.remove(this.domNode, 'hidden');

            this.projectDetails.startup();
            this.featuresGrid.startup();
            this.featuresGrid.grid.startup();
        },
        _resetHeight: function () {
            // summary:
            //      resizes the div to fit the screen on window resize
            console.log('app.project.ProjectContainer::_resetHeight', arguments);

            var maxHeight = win.getBox().h - 250;
            domStyle.set(this.domNode, 'maxHeight', maxHeight + 'px');
        },
        startup: function () {
            // summary:
            //      Fires after postCreate when all of the child widgets are finished laying out.
            console.log('app.project.ProjectContainer::startup', arguments);

            var that = this;
            this.childWidgets.forEach(function (widget) {
                that.own(widget);
                widget.startup();
            });

            this.inherited(arguments);
        }
    });
});
<|endoftext|>


<commit_before><commit_msg>image url send in response<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('devtoolsTodoApp')
  .factory('SocketFactory', function($rootScope) {

    var socket = io("http://" + location.host + "/browser-sync", {path: "/browser-sync/socket-io"});

    socket.on('todo', function(message) {
      $rootScope.emit('todoAction', message);
    });

    function emit(data) {
      socket.emit('todo', data);
    }

    return {
      emit: emit
    };

  });
<commit_msg>desactivation websockets<commit_after>'use strict';

angular.module('devtoolsTodoApp')
  .factory('SocketFactory', function($rootScope) {

    /*var socket = io("http://" + location.host + "/browser-sync", {path: "/browser-sync/socket-io"});

    socket.on('todo', function(message) {
      $rootScope.emit('todoAction', message);
    });
    */
    function emit(data) {
      //socket.emit('todo', data);
    }

    return {
      emit: emit
    };

  });
<|endoftext|>


<commit_before>let socket = io.connect();

// #Max To hide first div and show second
let showAndHide = function (id1, id2) {
    $(`#${id1}`).hide()
    $(`#${id2}`).show()
}

// #Max This was all Written before socket and is useless no
// //This is to validate code
// function codeComparison() {
//     let inputCode = $("#code-input").val();
//     console.log(inputCode)
//     //Compare input code to room codes available
//     // if (input code exists)
//         showAndHide("roomCode", "pregame")
//     // else
//     // Request new code
// } /#Max

function submitUsername() {
    //#Max  I don't think there needs to be validation if name is already taken but it may mess us up.  Unless each player is named player i to our programming

    //AJAX post user name to room
        //This should post it to the host to display the name on the players box

    //Shows next input if they want /#Max
    showAndHide("username", "createCards")
}

function Card(text, player) {
    this.text = text;
    this.description = "A homemade card, made with love from " + player
}

function getRandNum(){
		return (Math.floor(Math.random()*(99999-10000+1)+10000));
}

//Code comparison listener
$('#roomCode').submit(function(e) {
    e.preventDefault()
    let userData = {
        userName: $("#player-name-form").val().trim(),
        roomId: $("#code-input").val().trim(),
        role: "player",
        socketId: socket.id
    }
    console.log(userData)

    //socket.emit('set user', userData, function(){
        showAndHide("roomCode", "pregame")
        // showAndHide("pregame", "game")
    //})
});

//Name submit listener
$("#username").submit(function(e) {
    e.preventDefault();
    submitUsername()
})

//New Card submit listener
$("#createCards").submit(function(e) {
    e.preventDefault();
    submitCards()
})

//listener for host a game
$("#host").on("click", function(){
    let room = getRandNum()
    let userData = {
        userName: "Host-"+room,
        roomId: room,
        role: "host",
        socketId: socket.id
    }
    console.log(userData)
    //Bex: I moved this out here so I can see the host page while I'm working on it; it wasn't working before
    showAndHide('landing','host-page')

    socket.emit('set user', userData, function(){

    })
})

// Host Functions
function flipAllCards (){
    $(".played-card").each(function(){
        $(this).toggleClass('flipped');
    })
}
<commit_msg>frontend-host - pseudocoded some functions<commit_after>let socket = io.connect();

// #Max To hide first div and show second
let showAndHide = function (id1, id2) {
    $(`#${id1}`).hide()
    $(`#${id2}`).show()
}

// #Max This was all Written before socket and is useless no
// //This is to validate code
// function codeComparison() {
//     let inputCode = $("#code-input").val();
//     console.log(inputCode)
//     //Compare input code to room codes available
//     // if (input code exists)
//         showAndHide("roomCode", "pregame")
//     // else
//     // Request new code
// } /#Max

function submitUsername() {
    //#Max  I don't think there needs to be validation if name is already taken but it may mess us up.  Unless each player is named player i to our programming

    //AJAX post user name to room
        //This should post it to the host to display the name on the players box

    //Shows next input if they want /#Max
    showAndHide("username", "createCards")
}

function Card(text, player) {
    this.text = text;
    this.description = "A homemade card, made with love from " + player
}

function getRandNum(){
		return (Math.floor(Math.random()*(99999-10000+1)+10000));
}

//Code comparison listener
$('#roomCode').submit(function(e) {
    e.preventDefault()
    let userData = {
        userName: $("#player-name-form").val().trim(),
        roomId: $("#code-input").val().trim(),
        role: "player",
        socketId: socket.id
    }
    console.log(userData)

    //socket.emit('set user', userData, function(){
        showAndHide("roomCode", "pregame")
        // showAndHide("pregame", "game")
    //})
});

//Name submit listener
$("#username").submit(function(e) {
    e.preventDefault();
    submitUsername()
})

//New Card submit listener
$("#createCards").submit(function(e) {
    e.preventDefault();
    submitCards()
})

//listener for host a game
$("#host").on("click", function(){
    let room = getRandNum()
    let userData = {
        userName: "Host-"+room,
        roomId: room,
        role: "host",
        socketId: socket.id
    }
    console.log(userData)
    //Bex: I moved this out here so I can see the host page while I'm working on it; it wasn't working before
    showAndHide('landing','host-page')

    socket.emit('set user', userData, function(){

    })
})

// general functions for running Host
function getRandNumByInterval(min, max){
  return Math.floor(Math.random()*(max-min+1)+min);
}

//from: https://stackoverflow.com/a/2450976
function shuffleArray(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function removeItemFromArray(item, array){
    return array.splice($.inArray(item, array),1);
}

// Host Functions
function flipAllCards (){
    $(".played-card").each(function(){
        $(this).toggleClass('flipped');
    })
}

function startJudging (){
    // Bex: should run whenever all player cards are submitted
    flipAllCards();
    // Bex: switch the prompt on the host screen
    showAndHide("pre-judging-message", "mid-judging-message");
    // Bex: TODO: assign the data for the cards (and the players they belong to? might not be necessary if we keep info on player hands in the host side) on each card div
    //there's a .each function in jquery (see flipAllCards) that can be used to assign each card div the necessary data
}

function startGame(){
    //Bex: TODO: Generate random numbers to represent each card for each player
    //then run a query to obtain all of those cards and shuffle them
    //then construct an array of cards for each players hand and the remaining cards
}<|endoftext|>


<commit_before>angular.module("mopify.services.spotifylogin", [
    'spotify',
    'mopify.services.servicemanager',
    'mopify.services.versionmanager',
    'LocalStorageModule',
    'mopify.services.util'
])

.factory("SpotifyLogin", function($q, $rootScope, $timeout, $document, $http, Spotify, $interval, ServiceManager, localStorageService, VersionManager, util){
    "use strict";

    // Get body
    var body = $document.find('body').eq(0);

    // Create empty frames object
    var frame;

    // Create the iframe in the document
    function createFrame(service){
        frame = document.createElement("iframe");
        frame.setAttribute("src", "http://mopify.bitlabs.nl/auth/" + service + "/frame/#" + window.location.host);
        frame.style.width = 1 + "px";
        frame.style.height = 1 + "px";

        // Add to body and register in frames object
        body.append(frame);
    }

    // Create communication frame for Spotify
    createFrame("spotify");

    var tokenStorageKey = "spotifytokens";

    function SpotifyLogin(){
        this.frame = frame;
        this.waitingline = [];
        this.connected = false;
        this.lastPositiveLoginCheck = 0;

        // Get tokens and info from storage
        if(localStorageService.get(tokenStorageKey) !== null){
            this.refresh_token = localStorageService.get(tokenStorageKey).refresh_token;
            this.expires = localStorageService.get(tokenStorageKey).expires_in;
            this.access_token = localStorageService.get(tokenStorageKey).access_token;
            this.mopifyversion = localStorageService.get(tokenStorageKey).mopifyversion;
        }
        else{
            this.refresh_token = null;
            this.expires = null;
            this.access_token = null;
            this.mopifyversion = VersionManager.version;
        }

        // Get the login status from Spotify
        this.getLoginStatus().then(function(resp){
            $rootScope.$broadcast("mopify:spotify:" + resp.status.replace(" ", ""));
        });

        // Start token checking
        this.checkTokens();

        // Check if old token which needs refresh after installing a new version
        // This makes sure the new scopes are added to the toke
        this.checkOldToken();
    }

    /**
     * Check if the current tokens are still valid and refresh or login if needed
     */
    SpotifyLogin.prototype.checkTokens = function(){
        var that = this;
        // Check if expires equals null or expired
        if((this.expires === null || this.expires === undefined || Date.now() >= this.expires) && ServiceManager.isEnabled("spotify")){
            if(this.refresh_token !== null){
                this.refresh();
            }
            else{
                this.login();
            }
        }

        // Run this check again after 10 seconds
        $timeout(function(){
            that.checkTokens();
        }, 30000);
    };

    /**
     * Get the current login status from Spotify and return
     * if we're connected or not
     * @return {$q.defer().promise}
     */
    SpotifyLogin.prototype.getLoginStatus = function(){
        var that = this;
        var deferred = $q.defer();

        if(ServiceManager.isEnabled("spotify") !== true){
            deferred.reject();
        }
        else{
            // Check with last login check
            if(localStorageService.get(tokenStorageKey) === null){
                deferred.resolve({ status: "not connected" });
            }
            else if(Date.now() - that.lastPositiveLoginCheck > 600000){
                // Set the old token from the localstorage and check if that one still works
                var oldToken = localStorageService.get(tokenStorageKey).access_token;

                Spotify.setAuthToken(oldToken);

                // Make the call to spotify to see if we are logged in
                Spotify.getCurrentUser().then(function(data){
                    deferred.resolve({ status: "connected" });
                    that.connected = true;

                    // Set last login check
                    that.lastPositiveLoginCheck = Date.now();

                }, function(errData){
                    // If status equals 401 we have to reauthorize the user
                    if(errData.error.status == 401){
                        that.connected = false;
                        deferred.resolve({ status: "not connected" });
                    }
                });
            }
            else{
                deferred.resolve({ status: "connected" });
            }
        }

        return deferred.promise;
    };

    /**
     * Refresh the accesstoken using the refresh token
     * Using this method we can refresh the accesstoken without showing the user a new prompt
     */
    SpotifyLogin.prototype.refresh = function() {
        var deferred = $q.defer();
        var that = this;

        if(this.refresh_token === undefined){
            deferred.reject();
        }
        else{
            var postdata = {
                refresh_token: this.refresh_token,
                callback: 'JSON_CALLBACK'
            };

            $http({
                method: 'JSONP',
                url: "http://mopify.bitlabs.nl/auth/spotify/refresh/",
                params: postdata
            }).success(function(result) {

                that.access_token = result.access_token;
                that.expires = Date.now() + (result.expires_in * 1000);

                // Set token in spotify
                Spotify.setAuthToken(result.access_token);

                // Save tokens
                localStorageService.set(tokenStorageKey, {
                    access_token: that.access_token,
                    refresh_token: that.refresh_token,
                    expires_in: that.expires,
                    mopifyversion: VersionManager.version
                });

                deferred.resolve(result.response);
            });

        }

        return deferred.promise;
    };

    /**
     * Check if the current user's token passes the min software version
     * This can be used when new scopes are added and the user has to give
     * permisions for these scopes
     */
    SpotifyLogin.prototype.checkOldToken = function(){
        var minversion = '1.2.0';
        var compare = util.versionCompare(minversion, this.mopifyversion);

        // If the minversion is greater than the token's version
        // we refresh the token
        if((compare === 1 || compare === false) && ServiceManager.isEnabled("spotify")){
            this.disconnect();
            this.login();
        }
    };

    /**
     * Open the Spotify login screen and start asking for the key
     * The key will be saved on the bitlabs.nl localstorage which can be accessed
     * through the created iframe
     * @return {$q.defer().promise}
     */
    SpotifyLogin.prototype.login = function(){
        var that = this;
        var deferred = $q.defer();

        if(ServiceManager.isEnabled("spotify") !== true){
            deferred.reject();
        }

        // Ask the spotify login window
        Spotify.login();

        // Start waiting for the spotify answer
        that.requestKey().then(function(){
            if(that.access_token !== undefined){
                // Set the auth token
                Spotify.setAuthToken(that.access_token);

                // Check if the auth token works
                Spotify.getCurrentUser().then(function(data){
                    that.connected = true;

                    var tokens = {
                        access_token: that.access_token,
                        refresh_token: that.refresh_token,
                        expires: that.expires
                    };

                    // Save token and resolve
                    localStorageService.set(tokenStorageKey, tokens);
                    deferred.resolve(that.access_token);

                }, function(errData){
                    // If status equals 401 we have to reauthorize the user
                    if(errData.error.status == 401){
                        that.connected = false;
                        deferred.reject();
                    }
                });

            }
            else{
                deferred.reject();
            }
        });

        return deferred.promise;
    };

    /**
     * Disconnect from Spotify
     */
    SpotifyLogin.prototype.disconnect = function(){
        // Remove storage token
        localStorageService.remove(tokenStorageKey);

        // Clear Spotify auth token
        Spotify.setAuthToken("");

        // Remove token in iframe
        frame.contentWindow.postMessage(JSON.stringify({ method: "remove" }), "*");

        // Set connected to false
        this.connected = false;
    };

    /**
     * Request a key from spotify.
     * This is done by sending a request to the bitlabs server which will return the saved spotify key
     * @param  {$.defer} deferred
     * @return {$.defer().promise}
     */
    SpotifyLogin.prototype.requestKey = function(deferred){
        var that = this;
        deferred = deferred || $q.defer();

        var postdata = {
            method: "get"
        };

        // Ask for the key
        frame.contentWindow.postMessage(JSON.stringify(postdata), "*");

        // Check if key has landed
        if(that.access_token !== null){
            deferred.resolve();
        }
        else{
            $timeout(function(){
                that.requestKey(deferred);
            }, 1000);
        }

        return deferred.promise;
    };

    var spotifyLogin = new SpotifyLogin();

    // Handler on message
    window.addEventListener("message", function(e){

        // Check origin
        if (e.origin != "http://mopify.bitlabs.nl") {
            return;
        }

        var response = e.data;

        if(response.service == "spotify"){
            if(response.key !== null){
                // Parse json
                var tokens = JSON.parse(response.key);

                // Set tokens
                spotifyLogin.refresh_token = tokens.refresh_token;
                spotifyLogin.access_token = tokens.access_token;
                spotifyLogin.expires = Date.now() + 3600000;

                // Remove token in iframe
                frame.contentWindow.postMessage(JSON.stringify({ method: "remove" }), "*");
            }
        }
    });

    return spotifyLogin;
})

/*
 * Authentication Intercepter which checks spotify's requests results for a 401 error
 */
.factory('SpotifyAuthenticationIntercepter', function SpotifyAuthenticationIntercepter($q, $rootScope, $injector) {
    "use strict";
    var spotifyErrors = 0;
    var retrystarted = false;

    var responseInterceptor = {
        responseError: function(response) {
            if(response.status === 401 && response.config.url == "https://api.spotify.com/v1/me"){
                spotifyErrors++;

                if(spotifyErrors >= 3 && !retrystarted){
                    retrystarted = true;

                    /**
                     * Disconnect from Spotify, login, check the status and return the original response
                     * and broadcast the spotify:connected event
                     */
                    $injector.get('SpotifyLogin').disconnect();
                    $injector.get('SpotifyLogin').login().then(function(){
                        $injector.get('SpotifyLogin').getLoginStatus().then(function(resp){
                            $rootScope.$broadcast("mopify:spotify:connected");
                            return response;
                        });
                    });
                }

                return $q.reject(response);
            }

            return response;
        }
    };

    return responseInterceptor;
});

<commit_msg>removed unused var<commit_after>angular.module("mopify.services.spotifylogin", [
    'spotify',
    'mopify.services.servicemanager',
    'mopify.services.versionmanager',
    'LocalStorageModule',
    'mopify.services.util'
])

.factory("SpotifyLogin", function($q, $rootScope, $timeout, $document, $http, Spotify, $interval, ServiceManager, localStorageService, VersionManager, util){
    "use strict";

    // Get body
    var body = $document.find('body').eq(0);

    // Create empty frames object
    var frame;

    // Create the iframe in the document
    function createFrame(service){
        frame = document.createElement("iframe");
        frame.setAttribute("src", "http://mopify.bitlabs.nl/auth/" + service + "/frame/#" + window.location.host);
        frame.style.width = 1 + "px";
        frame.style.height = 1 + "px";

        // Add to body and register in frames object
        body.append(frame);
    }

    // Create communication frame for Spotify
    createFrame("spotify");

    var tokenStorageKey = "spotifytokens";

    function SpotifyLogin(){
        this.frame = frame;
        this.connected = false;
        this.lastPositiveLoginCheck = 0;

        // Get tokens and info from storage
        if(localStorageService.get(tokenStorageKey) !== null){
            this.refresh_token = localStorageService.get(tokenStorageKey).refresh_token;
            this.expires = localStorageService.get(tokenStorageKey).expires_in;
            this.access_token = localStorageService.get(tokenStorageKey).access_token;
            this.mopifyversion = localStorageService.get(tokenStorageKey).mopifyversion;
        }
        else{
            this.refresh_token = null;
            this.expires = null;
            this.access_token = null;
            this.mopifyversion = VersionManager.version;
        }

        // Get the login status from Spotify
        this.getLoginStatus().then(function(resp){
            $rootScope.$broadcast("mopify:spotify:" + resp.status.replace(" ", ""));
        });

        // Start token checking
        this.checkTokens();

        // Check if old token which needs refresh after installing a new version
        // This makes sure the new scopes are added to the toke
        this.checkOldToken();
    }

    /**
     * Check if the current tokens are still valid and refresh or login if needed
     */
    SpotifyLogin.prototype.checkTokens = function(){
        var that = this;
        // Check if expires equals null or expired
        if((this.expires === null || this.expires === undefined || Date.now() >= this.expires) && ServiceManager.isEnabled("spotify")){
            if(this.refresh_token !== null){
                this.refresh();
            }
            else{
                this.login();
            }
        }

        // Run this check again after 10 seconds
        $timeout(function(){
            that.checkTokens();
        }, 30000);
    };

    /**
     * Get the current login status from Spotify and return
     * if we're connected or not
     * @return {$q.defer().promise}
     */
    SpotifyLogin.prototype.getLoginStatus = function(){
        var that = this;
        var deferred = $q.defer();

        if(ServiceManager.isEnabled("spotify") !== true){
            deferred.reject();
        }
        else{
            // Check with last login check
            if(localStorageService.get(tokenStorageKey) === null){
                deferred.resolve({ status: "not connected" });
            }
            else if(Date.now() - that.lastPositiveLoginCheck > 600000){
                // Set the old token from the localstorage and check if that one still works
                var oldToken = localStorageService.get(tokenStorageKey).access_token;

                Spotify.setAuthToken(oldToken);

                // Make the call to spotify to see if we are logged in
                Spotify.getCurrentUser().then(function(data){
                    deferred.resolve({ status: "connected" });
                    that.connected = true;

                    // Set last login check
                    that.lastPositiveLoginCheck = Date.now();

                }, function(errData){
                    // If status equals 401 we have to reauthorize the user
                    if(errData.error.status == 401){
                        that.connected = false;
                        deferred.resolve({ status: "not connected" });
                    }
                });
            }
            else{
                deferred.resolve({ status: "connected" });
            }
        }

        return deferred.promise;
    };

    /**
     * Refresh the accesstoken using the refresh token
     * Using this method we can refresh the accesstoken without showing the user a new prompt
     */
    SpotifyLogin.prototype.refresh = function() {
        var deferred = $q.defer();
        var that = this;

        if(this.refresh_token === undefined){
            deferred.reject();
        }
        else{
            var postdata = {
                refresh_token: this.refresh_token,
                callback: 'JSON_CALLBACK'
            };

            $http({
                method: 'JSONP',
                url: "http://mopify.bitlabs.nl/auth/spotify/refresh/",
                params: postdata
            }).success(function(result) {

                that.access_token = result.access_token;
                that.expires = Date.now() + (result.expires_in * 1000);

                // Set token in spotify
                Spotify.setAuthToken(result.access_token);

                // Save tokens
                localStorageService.set(tokenStorageKey, {
                    access_token: that.access_token,
                    refresh_token: that.refresh_token,
                    expires_in: that.expires,
                    mopifyversion: VersionManager.version
                });

                deferred.resolve(result.response);
            });

        }

        return deferred.promise;
    };

    /**
     * Check if the current user's token passes the min software version
     * This can be used when new scopes are added and the user has to give
     * permisions for these scopes
     */
    SpotifyLogin.prototype.checkOldToken = function(){
        var minversion = '1.2.0';
        var compare = util.versionCompare(minversion, this.mopifyversion);

        // If the minversion is greater than the token's version
        // we refresh the token
        if((compare === 1 || compare === false) && ServiceManager.isEnabled("spotify")){
            this.disconnect();
            this.login();
        }
    };

    /**
     * Open the Spotify login screen and start asking for the key
     * The key will be saved on the bitlabs.nl localstorage which can be accessed
     * through the created iframe
     * @return {$q.defer().promise}
     */
    SpotifyLogin.prototype.login = function(){
        var that = this;
        var deferred = $q.defer();

        if(ServiceManager.isEnabled("spotify") !== true){
            deferred.reject();
        }

        // Ask the spotify login window
        Spotify.login();

        // Start waiting for the spotify answer
        that.requestKey().then(function(){
            if(that.access_token !== undefined){
                // Set the auth token
                Spotify.setAuthToken(that.access_token);

                // Check if the auth token works
                Spotify.getCurrentUser().then(function(data){
                    that.connected = true;

                    var tokens = {
                        access_token: that.access_token,
                        refresh_token: that.refresh_token,
                        expires: that.expires
                    };

                    // Save token and resolve
                    localStorageService.set(tokenStorageKey, tokens);
                    deferred.resolve(that.access_token);

                }, function(errData){
                    // If status equals 401 we have to reauthorize the user
                    if(errData.error.status == 401){
                        that.connected = false;
                        deferred.reject();
                    }
                });

            }
            else{
                deferred.reject();
            }
        });

        return deferred.promise;
    };

    /**
     * Disconnect from Spotify
     */
    SpotifyLogin.prototype.disconnect = function(){
        // Remove storage token
        localStorageService.remove(tokenStorageKey);

        // Clear Spotify auth token
        Spotify.setAuthToken("");

        // Remove token in iframe
        frame.contentWindow.postMessage(JSON.stringify({ method: "remove" }), "*");

        // Set connected to false
        this.connected = false;
    };

    /**
     * Request a key from spotify.
     * This is done by sending a request to the bitlabs server which will return the saved spotify key
     * @param  {$.defer} deferred
     * @return {$.defer().promise}
     */
    SpotifyLogin.prototype.requestKey = function(deferred){
        var that = this;
        deferred = deferred || $q.defer();

        var postdata = {
            method: "get"
        };

        // Ask for the key
        frame.contentWindow.postMessage(JSON.stringify(postdata), "*");

        // Check if key has landed
        if(that.access_token !== null){
            deferred.resolve();
        }
        else{
            $timeout(function(){
                that.requestKey(deferred);
            }, 1000);
        }

        return deferred.promise;
    };

    var spotifyLogin = new SpotifyLogin();

    // Handler on message
    window.addEventListener("message", function(e){

        // Check origin
        if (e.origin != "http://mopify.bitlabs.nl") {
            return;
        }

        var response = e.data;

        if(response.service == "spotify"){
            if(response.key !== null){
                // Parse json
                var tokens = JSON.parse(response.key);

                // Set tokens
                spotifyLogin.refresh_token = tokens.refresh_token;
                spotifyLogin.access_token = tokens.access_token;
                spotifyLogin.expires = Date.now() + 3600000;

                // Remove token in iframe
                frame.contentWindow.postMessage(JSON.stringify({ method: "remove" }), "*");
            }
        }
    });

    return spotifyLogin;
})

/*
 * Authentication Intercepter which checks spotify's requests results for a 401 error
 */
.factory('SpotifyAuthenticationIntercepter', function SpotifyAuthenticationIntercepter($q, $rootScope, $injector) {
    "use strict";
    var spotifyErrors = 0;
    var retrystarted = false;

    var responseInterceptor = {
        responseError: function(response) {
            if(response.status === 401 && response.config.url == "https://api.spotify.com/v1/me"){
                spotifyErrors++;

                if(spotifyErrors >= 3 && !retrystarted){
                    retrystarted = true;

                    /**
                     * Disconnect from Spotify, login, check the status and return the original response
                     * and broadcast the spotify:connected event
                     */
                    $injector.get('SpotifyLogin').disconnect();
                    $injector.get('SpotifyLogin').login().then(function(){
                        $injector.get('SpotifyLogin').getLoginStatus().then(function(resp){
                            $rootScope.$broadcast("mopify:spotify:connected");
                            return response;
                        });
                    });
                }

                return $q.reject(response);
            }

            return response;
        }
    };

    return responseInterceptor;
});

<|endoftext|>


<commit_before>angular.module('ng-transloadit', []).factory('Transloadit', ['$http', function($http) {
  var TRANSLOADIT_API = 'http://api2.transloadit.com/assemblies';

  function getExpiryDate() {
    var date = new Date();
    date.setHours(date.getHours() + 12);

    var year = date.getUTCFullYear();
    var month = zeroFill(date.getUTCMonth() + 1, 2);
    var day = zeroFill(date.getUTCDate(), 2);

    var hours = zeroFill(date.getUTCHours(), 2);
    var minutes = zeroFill(date.getUTCMinutes(), 2);
    var seconds = zeroFill(date.getUTCSeconds(), 2);

    return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds + '+00:00';
  }

  function zeroFill(number, width) {
    width -= number.toString().length;
    if (width > 0) {
      return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
    }

    return number + ""; // always return a string
  }

  return {
    upload: function(file, options) {
      this._validateBrowser();
      this._validateOptions(options);
      this._addExpiryDate(options);

      function check(assemblyUrl) {
        setTimeout(function() {
          $http.get(assemblyUrl).success(function(results) {
            if (results.ok === 'ASSEMBLY_COMPLETED') {
              options.uploaded(results);
            } else {
              check(results.assembly_url);
            }
          }).error(options.error);
        }, 2000);
      }

      options.signature(function(signatureValue) {
        var paramsValue = angular.toJson(options.params);

        var formData = new FormData();
        formData.append('params', paramsValue);
        formData.append('signature', signatureValue);
        formData.append(file.name, file);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', TRANSLOADIT_API, true);
        xhr.onload = function(response) {
          var results = angular.fromJson(this.response);
          options.processing();

          check(results.assembly_url);
        };

        xhr.upload.onprogress = function(e) {
          if (e.lengthComputable) {
            options.progress(e.loaded, e.total);
          }
        };

        xhr.send(formData);
      });
    },

    _validateBrowser: function() {
      var isXHR2 = new XMLHttpRequest().hasOwnProperty('upload');

      if (!isXHR2) {
        throw new Error('Transloadit will only work with XMLHttpRequest 2');
      }
    },

    _validateOptions: function(options) {
      // mandatory fields
      if (!options.signature) {
        throw new Error('must supply a signature function');
      }

      if (!options.uploaded) {
        throw new Error('must supply an uploaded callback');
      }

      if (!options.params) {
        throw new Error('must supply params');
      }

      if (!options.params.auth.key) {
        throw new Error('must supply a key');
      }

      // optional fields
      options.processing = options.processing || function() {};
      options.progress = options.progress || function() {};
      options.error = options.error || function() {};
    },

    _addExpiryDate: function(options) {
      options.params.auth.expires = getExpiryDate();
    }
  };
}]);

<commit_msg>Added cancellation support<commit_after>angular.module('ng-transloadit', []).factory('Transloadit', ['$http', function($http) {
  var TRANSLOADIT_API = 'http://api2.transloadit.com/assemblies';

  function getExpiryDate() {
    var date = new Date();
    date.setHours(date.getHours() + 12);

    var year = date.getUTCFullYear();
    var month = zeroFill(date.getUTCMonth() + 1, 2);
    var day = zeroFill(date.getUTCDate(), 2);

    var hours = zeroFill(date.getUTCHours(), 2);
    var minutes = zeroFill(date.getUTCMinutes(), 2);
    var seconds = zeroFill(date.getUTCSeconds(), 2);

    return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds + '+00:00';
  }

  function zeroFill(number, width) {
    width -= number.toString().length;
    if (width > 0) {
      return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
    }

    return number + ""; // always return a string
  }

  return {
    upload: function(file, options) {
      var cancelled = false;
      var xhr = new XMLHttpRequest();

      this._validateBrowser();
      this._validateOptions(options);
      this._addExpiryDate(options);

      function check(assemblyUrl) {
        if (cancelled) {
          return false;
        }

        setTimeout(function() {
          $http.get(assemblyUrl).success(function(results) {
            if (results.ok === 'ASSEMBLY_COMPLETED') {
              options.uploaded(results);
            } else {
              check(results.assembly_url);
            }
          }).error(options.error);
        }, 2000);
      }

      options.signature(function(signatureValue) {
        var paramsValue = angular.toJson(options.params);

        var formData = new FormData();
        formData.append('params', paramsValue);
        formData.append('signature', signatureValue);
        formData.append(file.name, file);

        xhr.open('POST', TRANSLOADIT_API, true);
        xhr.onload = function(response) {
          var results = angular.fromJson(this.response);
          options.processing();

          check(results.assembly_url);
        };

        xhr.upload.onprogress = function(e) {
          if (e.lengthComputable) {
            options.progress(e.loaded, e.total);
          }
        };

        xhr.send(formData);
      });

      return {
        cancel: function() {
          cancelled = true;
          xhr.abort();
        }
      };
    },

    _validateBrowser: function() {
      var isXHR2 = new XMLHttpRequest().hasOwnProperty('upload');

      if (!isXHR2) {
        throw new Error('Transloadit will only work with XMLHttpRequest 2');
      }
    },

    _validateOptions: function(options) {
      // mandatory fields
      if (!options.signature) {
        throw new Error('must supply a signature function');
      }

      if (!options.uploaded) {
        throw new Error('must supply an uploaded callback');
      }

      if (!options.params) {
        throw new Error('must supply params');
      }

      if (!options.params.auth.key) {
        throw new Error('must supply a key');
      }

      // optional fields
      options.processing = options.processing || function() {};
      options.progress = options.progress || function() {};
      options.error = options.error || function() {};
    },

    _addExpiryDate: function(options) {
      options.params.auth.expires = getExpiryDate();
    }
  };
}]);

<|endoftext|>


<commit_before>!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e.__locale__de=e.__locale__de||{},e.__locale__de.js=n())}(this,function(){"use strict";var e={after:function(e,n){var t=n[0];return e+" muss nach "+t+" liegen."},alpha_dash:function(e){return e+" darf alphanumerische Zeichen sowie Striche und Unterstriche enthalten."},alpha_num:function(e){return e+" darf nur alphanumerische Zeichen enthalten."},alpha:function(e){return e+" darf nur alphabetische Zeichen enthalten."},before:function(e,n){var t=n[0];return e+" muss vor "+t+" liegen."},between:function(e,n){var t=n[0],i=n[1];return e+" muss zwischen "+t+" und "+i+" liegen."},confirmed:function(e,n){var t=n[0];return e+" passt nicht zum Inhalt von "+t+"."},date_between:function(e,n){var t=n[0],i=n[1];return e+" muss zwischen "+t+" und "+i+" liegen."},date_format:function(e,n){var t=n[0];return e+" muss das Format "+t+" haben."},decimal:function(e,n){void 0===n&&(n=["*"]);var t=n[0];return e+" muss numerisch sein und darf "+("*"===t?"":t)+" Dezimalpunkte enthalten."},digits:function(e,n){var t=n[0];return e+" muss numerisch sein und exakt "+t+" Ziffern enthalten."},dimensions:function(e,n){var t=n[0],i=n[1];return e+" muss "+t+" x "+i+" Bildpunkte groß sein."},email:function(e){return e+" muss eine gültige E-Mail-Adresse sein."},ext:function(e){return e+" muss eine gültige Datei sein."},image:function(e){return e+" muss eine Grafik sein."},in:function(e){return e+" muss ein gültiger Wert sein."},ip:function(e){return e+" muss eine gültige IP-Adresse sein."},max:function(e,n){var t=n[0];return e+" darf nicht länger als "+t+" Zeichen sein."},mimes:function(e){return e+" muss einen gültigen Dateityp haben."},min:function(e,n){var t=n[0];return e+" muss mindestens "+t+" Zeichen lang sein."},not_in:function(e){return e+" muss ein gültiger Wert sein."},numeric:function(e){return e+" darf nur numerische Zeichen enthalten."},regex:function(e){return"Das Format von "+e+" ist ungültig."},required:function(e){return e+" ist ein Pflichtfeld."},size:function(e,n){var t=n[0];return e+" muss kleiner als "+t+" KB sein."},url:function(e){return e+" ist keine gültige URL."}},n={name:"de",messages:e,attributes:{}};return"undefined"!=typeof VeeValidate&&VeeValidate&&(VeeValidate.Validator,!0)&&VeeValidate.Validator.addLocale(n),n});<commit_msg>added compiled locale<commit_after>!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e.__locale__de=e.__locale__de||{},e.__locale__de.js=n())}(this,function(){"use strict";var e={_default:function(e){return e+" ist ungültig."},after:function(e,n){var t=n[0];return e+" muss nach "+t+" liegen."},alpha_dash:function(e){return e+" darf alphanumerische Zeichen sowie Striche und Unterstriche enthalten."},alpha_num:function(e){return e+" darf nur alphanumerische Zeichen enthalten."},alpha:function(e){return e+" darf nur alphabetische Zeichen enthalten."},before:function(e,n){var t=n[0];return e+" muss vor "+t+" liegen."},between:function(e,n){var t=n[0],i=n[1];return e+" muss zwischen "+t+" und "+i+" liegen."},confirmed:function(e,n){var t=n[0];return e+" passt nicht zum Inhalt von "+t+"."},date_between:function(e,n){var t=n[0],i=n[1];return e+" muss zwischen "+t+" und "+i+" liegen."},date_format:function(e,n){var t=n[0];return e+" muss das Format "+t+" haben."},decimal:function(e,n){void 0===n&&(n=["*"]);var t=n[0];return e+" muss numerisch sein und darf "+("*"===t?"":t)+" Dezimalpunkte enthalten."},digits:function(e,n){var t=n[0];return e+" muss numerisch sein und exakt "+t+" Ziffern enthalten."},dimensions:function(e,n){var t=n[0],i=n[1];return e+" muss "+t+" x "+i+" Bildpunkte groß sein."},email:function(e){return e+" muss eine gültige E-Mail-Adresse sein."},ext:function(e){return e+" muss eine gültige Datei sein."},image:function(e){return e+" muss eine Grafik sein."},in:function(e){return e+" muss ein gültiger Wert sein."},ip:function(e){return e+" muss eine gültige IP-Adresse sein."},max:function(e,n){var t=n[0];return e+" darf nicht länger als "+t+" Zeichen sein."},mimes:function(e){return e+" muss einen gültigen Dateityp haben."},min:function(e,n){var t=n[0];return e+" muss mindestens "+t+" Zeichen lang sein."},not_in:function(e){return e+" muss ein gültiger Wert sein."},numeric:function(e){return e+" darf nur numerische Zeichen enthalten."},regex:function(e){return"Das Format von "+e+" ist ungültig."},required:function(e){return e+" ist ein Pflichtfeld."},size:function(e,n){var t=n[0];return e+" muss kleiner als "+t+" KB sein."},url:function(e){return e+" ist keine gültige URL."}},n={name:"de",messages:e,attributes:{}};return"undefined"!=typeof VeeValidate&&VeeValidate&&(VeeValidate.Validator,!0)&&VeeValidate.Validator.addLocale(n),n});<|endoftext|>


<commit_before>import { Vfs } from '../../dar'
import { EMPTY_JATS } from '../ArticleConstants'

export default function createDemoVfs (seedXML) {
  let data = {
    'demo/manifest.xml': "<dar>\n  <documents>\n    <document id=\"manuscript\" type=\"article\" path=\"manuscript.xml\" />\n  </documents>\n  <assets>\n  </assets>\n</dar>\n", //eslint-disable-line
    'demo/manuscript.xml': EMPTY_JATS
  }
  return new Vfs(data)
}
<commit_msg>Add empty paragraph for demo article.<commit_after>import { DefaultDOMElement } from 'substance'
import { Vfs } from '../../dar'
import { EMPTY_JATS } from '../ArticleConstants'

export default function createDemoVfs () {
  let dom = DefaultDOMElement.parseXML(EMPTY_JATS)
  // add an empty paragraph into the empty body
  let $$ = dom.createElement.bind(dom)
  let bodyEl = dom.find('body')
  bodyEl.append(
    $$('p').attr('id', 'p-1').text('')
  )
  let manuscriptXML = dom.serialize()
  let data = {
    'demo/manifest.xml': "<dar>\n  <documents>\n    <document id=\"manuscript\" type=\"article\" path=\"manuscript.xml\" />\n  </documents>\n  <assets>\n  </assets>\n</dar>\n", //eslint-disable-line
    'demo/manuscript.xml': manuscriptXML
  }
  return new Vfs(data)
}
<|endoftext|>


<commit_before>"use strict";
var child_process = require("child_process"),
    path     = require("path"),
    fs       = require("fs"),
    pkg      = require("./package.json"),
    util     = require("./util");

util.setup();

var minimist = require("minimist"),
    chalk    = require("chalk"),
    glob     = require("glob"),
    tmp      = require("tmp");

/**
 * Runs pbts programmatically.
 * @param {string[]} args Command line arguments
 * @param {function(?Error, string=)} [callback] Optional completion callback
 * @returns {number|undefined} Exit code, if known
 */
exports.main = function(args, callback) {
    var argv = minimist(args, {
        alias: {
            name: "n",
            out : "o",
            main: "m",
            global: "g"
        },
        string: [ "name", "out", "global" ],
        boolean: [ "comments", "main" ],
        default: {
            comments: true,
            main: false
        }
    });

    var files  = argv._;

    if (!files.length) {
        if (callback)
            callback(Error("usage")); // eslint-disable-line callback-return
        else
            process.stderr.write([
                "protobuf.js v" + pkg.version + " CLI for TypeScript",
                "",
                chalk.bold.white("Generates TypeScript definitions from annotated JavaScript files."),
                "",
                "  -o, --out       Saves to a file instead of writing to stdout.",
                "",
                "  -g, --global    Name of the global object in browser environments, if any.",
                "",
                "  --no-comments   Does not output any JSDoc comments.",
                "",
                chalk.bold.gray("  Internal flags:"),
                "",
                "  -n, --name      Wraps everything in a module of the specified name.",
                "",
                "  -m, --main      Whether building the main library without any imports.",
                "",
                "usage: " + chalk.bold.green("pbts") + " [options] file1.js file2.js ..." + chalk.bold.gray("  (or)  ") + "other | " + chalk.bold.green("pbts") + " [options] -",
                ""
            ].join("\n"));
        return 1;
    }

    // Resolve glob expressions
    for (var i = 0; i < files.length;) {
        if (glob.hasMagic(files[i])) {
            var matches = glob.sync(files[i]);
            Array.prototype.splice.apply(files, [i, 1].concat(matches));
            i += matches.length;
        } else
            ++i;
    }

    var cleanup = [];

    // Read from stdin (to a temporary file)
    if (files.length === 1 && files[0] === "-") {
        var data = [];
        process.stdin.on("data", function(chunk) {
            data.push(chunk);
        });
        process.stdin.on("end", function() {
            files[0] = tmp.tmpNameSync() + ".js";
            fs.writeFileSync(files[0], Buffer.concat(data));
            cleanup.push(files[0]);
            callJsdoc();
        });

    // Load from disk
    } else {
        callJsdoc();
    }

    function callJsdoc() {

        // There is no proper API for jsdoc, so this executes the CLI and pipes the output
        var basedir = path.join(__dirname, ".");
        var moduleName = argv.name || "null";
        var nodePath = process.execPath;
        var cmd = "\"" + nodePath + "\" \"" + require.resolve("jsdoc/jsdoc.js") + "\" -c \"" + path.join(basedir, "lib", "tsd-jsdoc.json") + "\" -q \"module=" + encodeURIComponent(moduleName) + "&comments=" + Boolean(argv.comments) + "\" " + files.map(function(file) { return "\"" + file + "\""; }).join(" ");
        var child = child_process.exec(cmd, {
            cwd: process.cwd(),
            argv0: "node",
            stdio: "pipe",
            maxBuffer: 1 << 24 // 16mb
        });
        var out = [];
        var ended = false;
        var closed = false;
        child.stdout.on("data", function(data) {
            out.push(data);
        });
        child.stdout.on("end", function() {
            if (closed) finish();
            else ended = true;
        });
        child.stderr.pipe(process.stderr);
        child.on("close", function(code) {
            // clean up temporary files, no matter what
            try { cleanup.forEach(fs.unlinkSync); } catch(e) {/**/} cleanup = [];

            if (code) {
                out = out.join("").replace(/\s*JSDoc \d+\.\d+\.\d+ [^$]+/, "");
                process.stderr.write(out);
                var err = Error("code " + code);
                if (callback)
                    return callback(err);
                throw err;
            }

            if (ended) return finish();
            closed = true;
            return undefined;
        });

        function finish() {
            var output = [];
            if (argv.global)
                output.push(
                    "export as namespace " + argv.global + ";",
                    ""
                );
            if (!argv.main)
                output.push(
                    "import * as $protobuf from \"protobufjs\";",
                    ""
                );
            output = output.join("\n") + "\n" + out.join("");

            try {
                if (argv.out)
                    fs.writeFileSync(argv.out, output, { encoding: "utf8" });
                else if (!callback)
                    process.stdout.write(output, "utf8");
                return callback
                    ? callback(null, output)
                    : undefined;
            } catch (err) {
                if (callback)
                    return callback(err);
                throw err;
            }
        }
    }

    return undefined;
};
<commit_msg>CLI: Added an option to pbts to allow custom imports (#1038)<commit_after>"use strict";
var child_process = require("child_process"),
    path     = require("path"),
    fs       = require("fs"),
    pkg      = require("./package.json"),
    util     = require("./util");

util.setup();

var minimist = require("minimist"),
    chalk    = require("chalk"),
    glob     = require("glob"),
    tmp      = require("tmp");

/**
 * Runs pbts programmatically.
 * @param {string[]} args Command line arguments
 * @param {function(?Error, string=)} [callback] Optional completion callback
 * @returns {number|undefined} Exit code, if known
 */
exports.main = function(args, callback) {
    var argv = minimist(args, {
        alias: {
            name: "n",
            out : "o",
            main: "m",
            global: "g",
            import: "i"
        },
        string: [ "name", "out", "global", "import" ],
        boolean: [ "comments", "main" ],
        default: {
            comments: true,
            main: false
        }
    });

    var files  = argv._;

    if (!files.length) {
        if (callback)
            callback(Error("usage")); // eslint-disable-line callback-return
        else
            process.stderr.write([
                "protobuf.js v" + pkg.version + " CLI for TypeScript",
                "",
                chalk.bold.white("Generates TypeScript definitions from annotated JavaScript files."),
                "",
                "  -o, --out       Saves to a file instead of writing to stdout.",
                "",
                "  -g, --global    Name of the global object in browser environments, if any.",
                "",
                "  -i, --import    Comma delimited list of imports. Local names will equal camelCase of the basename.",
                "",
                "  --no-comments   Does not output any JSDoc comments.",
                "",
                chalk.bold.gray("  Internal flags:"),
                "",
                "  -n, --name      Wraps everything in a module of the specified name.",
                "",
                "  -m, --main      Whether building the main library without any imports.",
                "",
                "usage: " + chalk.bold.green("pbts") + " [options] file1.js file2.js ..." + chalk.bold.gray("  (or)  ") + "other | " + chalk.bold.green("pbts") + " [options] -",
                ""
            ].join("\n"));
        return 1;
    }

    // Resolve glob expressions
    for (var i = 0; i < files.length;) {
        if (glob.hasMagic(files[i])) {
            var matches = glob.sync(files[i]);
            Array.prototype.splice.apply(files, [i, 1].concat(matches));
            i += matches.length;
        } else
            ++i;
    }

    var cleanup = [];

    // Read from stdin (to a temporary file)
    if (files.length === 1 && files[0] === "-") {
        var data = [];
        process.stdin.on("data", function(chunk) {
            data.push(chunk);
        });
        process.stdin.on("end", function() {
            files[0] = tmp.tmpNameSync() + ".js";
            fs.writeFileSync(files[0], Buffer.concat(data));
            cleanup.push(files[0]);
            callJsdoc();
        });

    // Load from disk
    } else {
        callJsdoc();
    }

    function callJsdoc() {

        // There is no proper API for jsdoc, so this executes the CLI and pipes the output
        var basedir = path.join(__dirname, ".");
        var moduleName = argv.name || "null";
        var nodePath = process.execPath;
        var cmd = "\"" + nodePath + "\" \"" + require.resolve("jsdoc/jsdoc.js") + "\" -c \"" + path.join(basedir, "lib", "tsd-jsdoc.json") + "\" -q \"module=" + encodeURIComponent(moduleName) + "&comments=" + Boolean(argv.comments) + "\" " + files.map(function(file) { return "\"" + file + "\""; }).join(" ");
        var child = child_process.exec(cmd, {
            cwd: process.cwd(),
            argv0: "node",
            stdio: "pipe",
            maxBuffer: 1 << 24 // 16mb
        });
        var out = [];
        var ended = false;
        var closed = false;
        child.stdout.on("data", function(data) {
            out.push(data);
        });
        child.stdout.on("end", function() {
            if (closed) finish();
            else ended = true;
        });
        child.stderr.pipe(process.stderr);
        child.on("close", function(code) {
            // clean up temporary files, no matter what
            try { cleanup.forEach(fs.unlinkSync); } catch(e) {/**/} cleanup = [];

            if (code) {
                out = out.join("").replace(/\s*JSDoc \d+\.\d+\.\d+ [^$]+/, "");
                process.stderr.write(out);
                var err = Error("code " + code);
                if (callback)
                    return callback(err);
                throw err;
            }

            if (ended) return finish();
            closed = true;
            return undefined;
        });

        function getImportName(importItem) {
            var result = path.basename(importItem, ".js")
            return result.replace(/([-_~.+]\w)/g, match => {
                return match[1].toUpperCase();
            });
        }

        function finish() {
            var output = [];
            if (argv.global)
                output.push(
                    "export as namespace " + argv.global + ";",
                    ""
                );

            if (!argv.main) {
                // Ensure we have a usable array of imports
                var importArray = typeof argv.import === "string" ? argv.import.split(",") : argv.import || [];

                // Build an object of imports and paths
                var imports = {
                    $protobuf: "protobufjs"
                };
                importArray.forEach(function(importItem) {
                    imports[getImportName(importItem)] = importItem;
                });

                // Write out the imports
                Object.keys(imports).forEach(function(key) {
                    output.push("import * as " + key + " from \"" + imports[key] + "\";");
                });
            }

            output = output.join("\n") + "\n" + out.join("");

            try {
                if (argv.out)
                    fs.writeFileSync(argv.out, output, { encoding: "utf8" });
                else if (!callback)
                    process.stdout.write(output, "utf8");
                return callback
                    ? callback(null, output)
                    : undefined;
            } catch (err) {
                if (callback)
                    return callback(err);
                throw err;
            }
        }
    }

    return undefined;
};
<|endoftext|>


<commit_before><commit_msg>fixed bug in PIR sensor<commit_after><|endoftext|>


<commit_before>/*globals angular*/
(function () {
    'use strict';

    function GameService(dataService) {

        function createGame() {

           return dataService.postRequest('api/games/create');
/*
            var deferred = $q.defer();

            $http.post(domain + 'api/games/create')
                .then(function (successResponse) {
                    deferred.resolve(successResponse);
                }, function (errorResponse) {
                    deferred.reject(errorResponse);
                });

            return deferred.promise;*/
        }

        function joinGame() {

            return dataService.postRequest('api/games/join');

            /*var deferred = $q.defer();

            $http.post(domain + 'api/games/join')
                .then(function (successResponse) {
                    deferred.resolve(successResponse);
                }, function (errorResponse) {
                    deferred.reject(errorResponse);
                });

            return deferred.promise;*/
        }

        function details(id) {

            return dataService.getRequest('api/games/status?gameId=' + id);
            /*var deferred = $q.defer();

            $http.get(domain + 'api/games/status?gameId=' + id)
                .then(function (successResponse) {
                    deferred.resolve(successResponse);
                }, function (errorResponse) {
                    deferred.reject(errorResponse);
                });

            return deferred.promise;*/
        }

        function play(tileRequest) {

            return dataService.postRequest('api/games/play', tileRequest);
/*
            var deferred = $q.defer();

            $http.post(domain + 'api/games/play', tileRequest)
                .then(function (successResponse) {
                    deferred.resolve(successResponse);
                }, function (errorResponse) {

                    deferred.reject(errorResponse);
                });

            return deferred.promise;*/
        }

        function allGames() {

            return dataService.getRequest('api/games/all');
            /*var deferred = $q.defer();

            $http.get(domain + 'api/games/all')
                .then(function (successResponse) {
                    deferred.resolve(successResponse);
                }, function (errorResponse) {
                    deferred.reject(errorResponse);
                });

            return deferred.promise;*/
        }

        function getPrivateGames() {
            return dataService.getRequest('api/games/PrivateGames');
            /*
            var deferred = $q.defer();

            $http.get(domain + 'api/games/PrivateGames')
                .then(function (successResponse) {
                    deferred.resolve(successResponse);
                }, function (errorResponse) {
                    deferred.reject(errorResponse);
                });

            return deferred.promise;*/
        }

        return {
            createGame: createGame,
            joinGame: joinGame,
            gameDetails: details,
            play : play,
            allGames: allGames,
            getPrivateGames: getPrivateGames
        };
    }

    angular.module('tttGame.services')
        .factory('gameManager', ['dataService', GameService]);
}());<commit_msg>Cached games add until refresh  #4<commit_after>/*globals angular*/
(function () {
    'use strict';

    function GameService(dataService, $q) {
        var cachedGames;

        function createGame() {

            return dataService.postRequest('api/games/create');
            /*
             var deferred = $q.defer();

             $http.post(domain + 'api/games/create')
             .then(function (successResponse) {
             deferred.resolve(successResponse);
             }, function (errorResponse) {
             deferred.reject(errorResponse);
             });

             return deferred.promise;*/
        }

        function joinGame() {

            return dataService.postRequest('api/games/join');

            /*var deferred = $q.defer();

             $http.post(domain + 'api/games/join')
             .then(function (successResponse) {
             deferred.resolve(successResponse);
             }, function (errorResponse) {
             deferred.reject(errorResponse);
             });

             return deferred.promise;*/
        }

        function details(id) {

            return dataService.getRequest('api/games/status?gameId=' + id);
            /*var deferred = $q.defer();

             $http.get(domain + 'api/games/status?gameId=' + id)
             .then(function (successResponse) {
             deferred.resolve(successResponse);
             }, function (errorResponse) {
             deferred.reject(errorResponse);
             });

             return deferred.promise;*/
        }

        function play(tileRequest) {

            return dataService.postRequest('api/games/play', tileRequest);
            /*
             var deferred = $q.defer();

             $http.post(domain + 'api/games/play', tileRequest)
             .then(function (successResponse) {
             deferred.resolve(successResponse);
             }, function (errorResponse) {

             deferred.reject(errorResponse);
             });

             return deferred.promise;*/
        }

        function allGames() {
            var deferred = $q.defer();
            if (!!cachedGames) {
                deferred.resolve(cachedGames);
                return deferred.promise;
            } else {
                dataService.getRequest('api/games/all')
                    .then(function (allGames) {
                        cachedGames = allGames;
                        deferred.resolve(allGames);
                    }, function (error) {
                        deferred.reject(error);
                    });

            }

            return deferred.promise;
            /*var deferred = $q.defer();

             $http.get(domain + 'api/games/all')
             .then(function (successResponse) {
             deferred.resolve(successResponse);
             }, function (errorResponse) {
             deferred.reject(errorResponse);
             });

             return deferred.promise;*/
        }

        function getPrivateGames() {
            return dataService.getRequest('api/games/PrivateGames');
            /*
             var deferred = $q.defer();

             $http.get(domain + 'api/games/PrivateGames')
             .then(function (successResponse) {
             deferred.resolve(successResponse);
             }, function (errorResponse) {
             deferred.reject(errorResponse);
             });

             return deferred.promise;*/
        }

        return {
            createGame: createGame,
            joinGame: joinGame,
            gameDetails: details,
            play: play,
            allGames: allGames,
            getPrivateGames: getPrivateGames
        };
    }

    angular.module('tttGame.services')
        .factory('gameManager', ['dataService', '$q', GameService]);
}());<|endoftext|>


<commit_before>let assert = require('assert');
let exec = require('child_process').execSync;
let argv = require('yargs').argv;

class Verify {
    /**
     * Verify that the call the mix.js() is valid.
     *
     * @param {*} entry
     * @param {*} output
     */
    static js(entry, output) {
        assert(
            typeof entry === 'string' || Array.isArray(entry),
            'mix.js() is missing required parameter 1: entry'
        );

        assert(
            typeof output === 'string',
            'mix.js() is missing required parameter 2: output'
        );
    }

    /**
     * Verify that the calls to mix.sass() and mix.less() are valid.
     *
     * @param {string} type
     * @param {string} src
     * @param {string} output
     */
    static preprocessor(type, src, output) {
        assert(
            typeof src === 'string',
            `mix.${type}() is missing required parameter 1: src`
        );

        assert(
            typeof output === 'string',
            `mix.${type}() is missing required parameter 2: output`
        );
    }

    /**
     * Verify that calls to mix.combine() are valid.
     *
     * @param {string} src
     * @param {File}   output
     */
    static combine(src, output) {
        assert(
            output.isFile(),
            'mix.combine() requires a full output file path as the second argument.'
        );
    }

    /**
     * Assert that the given file exists.
     *
     * @param {string} file
     */
    static exists(file) {
        assert(
            File.exists(file),
            `Whoops, you are trying to compile ${file}, but that file does not exist.`
        );
    }

    // /**
    //  * Verify that the call to mix.extract() is valid.
    //  *
    //  * @param {Array} libs
    //  */
    // static extract(libs) {
    //     assert(
    //         libs && Array.isArray(libs),
    //         'mix.extract() requires an array as its first parameter.'
    //     );
    // }

    /**
     * Verify that the necessary dependencies are available.
     *
     * @param {Array}  list
     * @param {Boolean} abortOnComplete
     */
    static dependencies(list, abortOnComplete = false) {
        if (argv['$0'].includes('ava')) return;

        list
            .reject(dependency => {
                try {
                    return require.resolve(dependency.replace(/@.+$/, ''));
                } catch (e) {}
            })
            .tap(dependencies =>
                installDependencies(dependencies, abortOnComplete)
            );
    }

    /**
     * Verify that the necessary dependency is available.
     *
     * @param {string}  name
     * @param {array}   dependencies
     * @param {Boolean} abortOnComplete
     */
    static dependency(name, abortOnComplete = false) {
        if (argv['$0'].includes('ava')) return;

        try {
            require.resolve(name.replace(/@.+$/, ''));
        } catch (e) {
            installDependencies(name, abortOnComplete);
        }
    }
}

/**
 * Install the given dependencies using npm or yarn.
 *
 * @param {array} dependencies
 */
let installDependencies = (dependencies, abortOnComplete = false) => {
    console.log(
        'Additional dependencies must be installed. ' +
            'This will only take a moment.'
    );

    if (Array.isArray(dependencies)) {
        dependencies = dependencies.join(' ');
    }

    let command = `npm install ${dependencies} --save-dev`;

    if (File.exists('yarn.lock')) {
        command = `yarn add ${dependencies} --dev`;
    }

    exec(command);

    if (abortOnComplete) abort(abortOnComplete);
};

let abort = message => {
    console.log(
        typeof message === 'string'
            ? message
            : 'Finished. Please run Mix again.'
    );

    process.exit();
};

module.exports = Verify;
<commit_msg>Remove unused method<commit_after>let assert = require('assert');
let exec = require('child_process').execSync;
let argv = require('yargs').argv;

class Verify {
    /**
     * Verify that the call the mix.js() is valid.
     *
     * @param {*} entry
     * @param {*} output
     */
    static js(entry, output) {
        assert(
            typeof entry === 'string' || Array.isArray(entry),
            'mix.js() is missing required parameter 1: entry'
        );

        assert(
            typeof output === 'string',
            'mix.js() is missing required parameter 2: output'
        );
    }

    /**
     * Verify that the calls to mix.sass() and mix.less() are valid.
     *
     * @param {string} type
     * @param {string} src
     * @param {string} output
     */
    static preprocessor(type, src, output) {
        assert(
            typeof src === 'string',
            `mix.${type}() is missing required parameter 1: src`
        );

        assert(
            typeof output === 'string',
            `mix.${type}() is missing required parameter 2: output`
        );
    }

    /**
     * Verify that calls to mix.combine() are valid.
     *
     * @param {string} src
     * @param {File}   output
     */
    static combine(src, output) {
        assert(
            output.isFile(),
            'mix.combine() requires a full output file path as the second argument.'
        );
    }

    /**
     * Assert that the given file exists.
     *
     * @param {string} file
     */
    static exists(file) {
        assert(
            File.exists(file),
            `Whoops, you are trying to compile ${file}, but that file does not exist.`
        );
    }

    /**
     * Verify that the necessary dependencies are available.
     *
     * @param {Array}  list
     * @param {Boolean} abortOnComplete
     */
    static dependencies(list, abortOnComplete = false) {
        if (argv['$0'].includes('ava')) return;

        list
            .reject(dependency => {
                try {
                    return require.resolve(dependency.replace(/@.+$/, ''));
                } catch (e) {}
            })
            .tap(dependencies =>
                installDependencies(dependencies, abortOnComplete)
            );
    }

    /**
     * Verify that the necessary dependency is available.
     *
     * @param {string}  name
     * @param {array}   dependencies
     * @param {Boolean} abortOnComplete
     */
    static dependency(name, abortOnComplete = false) {
        if (argv['$0'].includes('ava')) return;

        try {
            require.resolve(name.replace(/@.+$/, ''));
        } catch (e) {
            installDependencies(name, abortOnComplete);
        }
    }
}

/**
 * Install the given dependencies using npm or yarn.
 *
 * @param {array} dependencies
 */
let installDependencies = (dependencies, abortOnComplete = false) => {
    console.log(
        'Additional dependencies must be installed. ' +
            'This will only take a moment.'
    );

    if (Array.isArray(dependencies)) {
        dependencies = dependencies.join(' ');
    }

    let command = `npm install ${dependencies} --save-dev`;

    if (File.exists('yarn.lock')) {
        command = `yarn add ${dependencies} --dev`;
    }

    exec(command);

    if (abortOnComplete) abort(abortOnComplete);
};

let abort = message => {
    console.log(
        typeof message === 'string'
            ? message
            : 'Finished. Please run Mix again.'
    );

    process.exit();
};

module.exports = Verify;
<|endoftext|>